code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
if (typeof FormTarget === 'undefined') { FormTarget = {}; } FormTarget.arrayrun = (function($) { /* * Expected config { * isAdmin: boolean, * instruments: array * } */ return { getUserManualUrl: function() { return Urls.external.userManual('array_runs'); }, getSaveUrl: function(arrayrun) { return arrayrun.id ? Urls.rest.arrayRuns.update(arrayrun.id) : Urls.rest.arrayRuns.create; }, getSaveMethod: function(arrayrun) { return arrayrun.id ? 'PUT' : 'POST'; }, getEditUrl: function(arrayrun) { return Urls.ui.arrayRuns.edit(arrayrun.id); }, getSections: function(config, object) { return [{ title: 'Array Run Information', fields: [{ title: 'Array Run ID', data: 'id', type: 'read-only', getDisplayValue: function(arrayrun) { return arrayrun.id || 'Unsaved'; } }, { title: 'Instrument', data: 'instrumentId', type: 'dropdown', include: !object.id, required: true, nullValue: 'SELECT', source: config.instruments, getItemLabel: Utils.array.getName, getItemValue: Utils.array.getId, sortSource: Utils.sorting.standardSort('name') }, { title: 'Instrument', data: 'instrumentId', type: 'read-only', include: !!object.id, getDisplayValue: function(arrayrun) { return arrayrun.instrumentName; } }, { title: 'Alias', data: 'alias', type: 'text', required: true, maxLength: 255 }, { title: 'Description', data: 'description', type: 'text', maxLength: 255 }, { title: 'Run Path', data: 'filePath', type: 'text', maxLength: 255 }, { title: 'Array', data: 'arrayId', type: 'read-only', getDisplayValue: function(arrayrun) { return arrayrun.arrayAlias; }, getLink: function(arrayrun) { return Urls.ui.arrays.edit(arrayrun.arrayId); } }, { title: 'Change Array', type: 'special', makeControls: function(form) { return [$('<button>').addClass('ui-state-default').attr('type', 'button').text('Search').click(function() { Utils.showDialog('Array Search', 'Search', [{ label: 'Search', property: 'query', type: 'text', required: true }], function(formData) { Utils.ajaxWithDialog('Searching', 'GET', Urls.rest.arrayRuns.arraySearch + '?' + jQuery.param({ q: formData.query }), null, function(data) { if (!data || !data.length) { Utils.showOkDialog('Search Results', ['No matching arrays found']); return; } else { Utils.showWizardDialog('Search Results', data.map(function(array) { return { name: array.alias, handler: function() { form.updateField('arrayId', { value: array.id, label: array.alias, link: Urls.ui.arrays.edit(array.id) }); updateSamplesTable(array); } }; })); } }); }); }), $('<button>').addClass('ui-state-default').attr('type', 'button').text('Remove').click(function() { if (form.get('arrayId')) { Utils.showConfirmDialog("Remove Array", "Remove", ["Remove the array from this array run?"], function() { form.updateField('arrayId', { value: null, label: '', link: null }); updateSamplesTable(null); }); } else { Utils.showOkDialog('Remove Array', ['No array set']); } })]; } }, { title: 'Status', data: 'status', type: 'dropdown', required: true, source: Constants.healthTypes, getItemLabel: function(item) { return item.label; }, getItemValue: function(item) { return item.label; }, onChange: function(newValue, form) { var status = getStatus(newValue); var updates = { required: status.isDone, // Editable if run is done and either there's no value set or user is admin disabled: !status.isDone || (form.get('completionDate') && !config.isAdmin) }; if (!status.isDone) { updates.value = null; } form.updateField('completionDate', updates); }, // Only editable by admin if run is done disabled: !object.status ? false : (getStatus(object.status).isDone && !config.isAdmin) }, { title: 'Start Date', data: 'startDate', type: 'date', required: true, disabled: object.startDate && !config.isAdmin }, { title: 'Completion Date', data: 'completionDate', type: 'date' }] }]; } } function getStatus(label) { return Utils.array.findUniqueOrThrow(function(item) { return item.label === label; }, Constants.healthTypes); } function updateSamplesTable(array) { $('#listingSamplesTable').empty(); var data = []; var lengthOptions = [50, 25, 10]; if (array) { data = array.samples.map(function(sample) { return [sample.coordinates, Box.utils.hyperlinkifyBoxable(sample.name, sample.id, sample.name), Box.utils.hyperlinkifyBoxable(sample.name, sample.id, sample.alias)]; }); lengthOptions.unshift(array.columns * array.rows); } $('#listingSamplesTable') .dataTable( { "aaData": data, "aoColumns": [{ "sTitle": "Position" }, { "sTitle": "Sample Name" }, { "sTitle": "Sample Alias" }], "bJQueryUI": true, "bDestroy": true, "aLengthMenu": [lengthOptions, lengthOptions], "iDisplayLength": lengthOptions[0], "sPaginationType": "full_numbers", "sDom": '<"#toolbar.fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"lf>r<t><"fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"ip>', "aaSorting": [[0, "asc"]] }).css("width", "100%"); } })(jQuery);
TGAC/miso-lims
miso-web/src/main/webapp/scripts/form_arrayrun.js
JavaScript
gpl-3.0
7,102
import { combineReducers } from 'redux'; import { ADDED_ACCEPTOR_CAREER, DELETED_ACCEPTOR_CAREER, INIT_ACCEPTOR_CAREER_HISTORY, FETCH_FAILED, FETCHING } from '../../constants'; const error = (state = null, action) => { switch (action.type) { case FETCH_FAILED: return action.error; default: return null; } }; const data = (state = [], action) => { switch (action.type) { case INIT_ACCEPTOR_CAREER_HISTORY: return action.careerHistory; case ADDED_ACCEPTOR_CAREER: return [...state, action.career]; case DELETED_ACCEPTOR_CAREER: return state.filter(({ name, year }) => name !== action.career.name || year !== action.career.year); default: return state; } }; const toast = (state = { show: false, }, action) => { switch (action.type) { case FETCHING: return { show: true, text: '请稍候', icon: 'loading', }; case ADDED_ACCEPTOR_CAREER: case DELETED_ACCEPTOR_CAREER: return { show: true, text: '操作成功', icon: 'toast', }; default: return { show: false, }; } }; export default combineReducers({ data, error, toast, });
nagucc/jkef-wxe
src/reducers/acceptors/career.js
JavaScript
gpl-3.0
1,229
/*! * tablesorter pager plugin * updated 5/27/2013 */ /*jshint browser:true, jquery:true, unused:false */ ;(function($) { "use strict"; /*jshint supernew:true */ $.extend({ tablesorterPager: new function() { this.defaults = { // target the pager markup container: null, // use this format: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}" // where {page} is replaced by the page number, {size} is replaced by the number of records to show, // {sortList:col} adds the sortList to the url into a "col" array, and {filterList:fcol} adds // the filterList to the url into an "fcol" array. // So a sortList = [[2,0],[3,0]] becomes "&col[2]=0&col[3]=0" in the url // and a filterList = [[2,Blue],[3,13]] becomes "&fcol[2]=Blue&fcol[3]=13" in the url ajaxUrl: null, // modify the url after all processing has been applied customAjaxUrl: function(table, url) { return url; }, // modify the $.ajax object to allow complete control over your ajax requests ajaxObject: { dataType: 'json' }, // process ajax so that the following information is returned: // [ total_rows (number), rows (array of arrays), headers (array; optional) ] // example: // [ // 100, // total rows // [ // [ "row1cell1", "row1cell2", ... "row1cellN" ], // [ "row2cell1", "row2cell2", ... "row2cellN" ], // ... // [ "rowNcell1", "rowNcell2", ... "rowNcellN" ] // ], // [ "header1", "header2", ... "headerN" ] // optional // ] ajaxProcessing: function(ajax){ return [ 0, [], null ]; }, // output default: '{page}/{totalPages}' // possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows} output: '{startRow} to {endRow} of {totalRows} rows', // '{page}/{totalPages}' // apply disabled classname to the pager arrows when the rows at either extreme is visible updateArrows: true, // starting page of the pager (zero based index) page: 0, // Number of visible rows size: 10, // if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty // table row set to a height to compensate; default is false fixedHeight: false, // remove rows from the table to speed up the sort of large tables. // setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled. removeRows: false, // removing rows in larger tables speeds up the sort // css class names of pager arrows cssFirst: '.first', // go to first page arrow cssPrev: '.prev', // previous page arrow cssNext: '.next', // next page arrow cssLast: '.last', // go to last page arrow cssGoto: '.gotoPage', // go to page selector - select dropdown that sets the current page cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option cssErrorRow: 'tablesorter-errorRow', // error information row // class added to arrows when at the extremes (i.e. prev/first arrows are "disabled" when on the first page) cssDisabled: 'disabled', // Note there is no period "." in front of this class name // stuff not set by the user totalRows: 0, totalPages: 0, filteredRows: 0, filteredPages: 0 }; var $this = this, // hide arrows at extremes pagerArrows = function(c, disable) { var a = 'addClass', r = 'removeClass', d = c.cssDisabled, dis = !!disable, tp = Math.min( c.totalPages, c.filteredPages ); if ( c.updateArrows ) { c.$container.find(c.cssFirst + ',' + c.cssPrev)[ ( dis || c.page === 0 ) ? a : r ](d); c.$container.find(c.cssNext + ',' + c.cssLast)[ ( dis || c.page === tp - 1 ) ? a : r ](d); } }, updatePageDisplay = function(table, c, flag) { var i, p, s, t, out, tc = table.config, f = $(table).hasClass('hasFilters') && !c.ajaxUrl; c.totalPages = Math.ceil( c.totalRows / c.size ); // needed for "pageSize" method c.filteredRows = (f) ? tc.$tbodies.eq(0).children('tr:not(.' + (tc.widgetOptions && tc.widgetOptions.filter_filteredRow || 'filtered') + ',' + tc.selectorRemove + ')').length : c.totalRows; c.filteredPages = (f) ? Math.ceil( c.filteredRows / c.size ) || 1 : c.totalPages; if ( Math.min( c.totalPages, c.filteredPages ) >= 0 ) { t = (c.size * c.page > c.filteredRows); c.startRow = (t) ? 1 : (c.filteredRows === 0 ? 0 : c.size * c.page + 1); c.page = (t) ? 0 : c.page; c.endRow = Math.min( c.filteredRows, c.totalRows, c.size * ( c.page + 1 ) ); out = c.$container.find(c.cssPageDisplay); // form the output string s = c.output.replace(/\{(page|filteredRows|filteredPages|totalPages|startRow|endRow|totalRows)\}/gi, function(m){ return { '{page}' : c.page + 1, '{filteredRows}' : c.filteredRows, '{filteredPages}' : c.filteredPages, '{totalPages}' : c.totalPages, '{startRow}' : c.startRow, '{endRow}' : c.endRow, '{totalRows}' : c.totalRows }[m]; }); if (out.length) { out[ (out[0].tagName === 'INPUT') ? 'val' : 'html' ](s); if ( c.$goto.length ) { t = ''; p = Math.min( c.totalPages, c.filteredPages ); for ( i = 1; i <= p; i++ ) { t += '<option>' + i + '</option>'; } c.$goto.html(t).val( c.page + 1 ); } } } pagerArrows(c); if (c.initialized && flag !== false) { $(table).trigger('pagerComplete', c); } }, fixHeight = function(table, c) { var d, h, $b = table.config.$tbodies.eq(0); if (c.fixedHeight) { $b.find('tr.pagerSavedHeightSpacer').remove(); h = $.data(table, 'pagerSavedHeight'); if (h) { d = h - $b.height(); if ( d > 5 && $.data(table, 'pagerLastSize') === c.size && $b.children('tr:visible').length < c.size ) { $b.append('<tr class="pagerSavedHeightSpacer ' + table.config.selectorRemove.replace(/(tr)?\./g,'') + '" style="height:' + d + 'px;"></tr>'); } } } }, changeHeight = function(table, c) { var $b = table.config.$tbodies.eq(0); $b.find('tr.pagerSavedHeightSpacer').remove(); $.data(table, 'pagerSavedHeight', $b.height()); fixHeight(table, c); $.data(table, 'pagerLastSize', c.size); }, hideRows = function(table, c){ if (!c.ajaxUrl) { var i, tc = table.config, rows = tc.$tbodies.eq(0).children('tr:not(.' + tc.cssChildRow + ')'), l = rows.length, s = ( c.page * c.size ), e = s + c.size, f = tc.widgetOptions && tc.widgetOptions.filter_filteredRow || 'filtered', j = 0; // size counter for ( i = 0; i < l; i++ ){ if ( !rows[i].className.match(f) ) { rows[i].style.display = ( j >= s && j < e ) ? '' : 'none'; j++; } } } }, hideRowsSetup = function(table, c){ c.size = parseInt( c.$size.val(), 10 ) || c.size; $.data(table, 'pagerLastSize', c.size); pagerArrows(c); if ( !c.removeRows ) { hideRows(table, c); $(table).bind('sortEnd.pager filterEnd.pager', function(){ hideRows(table, c); }); } }, renderAjax = function(data, table, c, xhr, exception){ // process data if ( typeof(c.ajaxProcessing) === "function" ) { // ajaxProcessing result: [ total, rows, headers ] var i, j, hsh, $f, $sh, th, d, l, $err, rr_count, $t = $(table), tc = table.config, result = c.ajaxProcessing(data, table) || [ 0, [] ], hl = $t.find('thead th').length, tds = '', // allow [ total, rows, headers ] or [ rows, total, headers ] t = isNaN(result[0]) && !isNaN(result[1]); $t.find('thead tr.' + c.cssErrorRow).remove(); // Clean up any previous error. if ( exception ) { $err = $('<tr class="' + c.cssErrorRow + '"><td style="text-align:center;" colspan="' + hl + '">' + ( xhr.status === 0 ? 'Not connected, verify Network' : xhr.status === 404 ? 'Requested page not found [404]' : xhr.status === 500 ? 'Internal Server Error [500]' : exception === 'parsererror' ? 'Requested JSON parse failed' : exception === 'timeout' ? 'Time out error' : exception === 'abort' ? 'Ajax Request aborted' : 'Uncaught error: ' + xhr.statusText + ' [' + xhr.status + ']' ) + '</td></tr>') .click(function(){ $(this).remove(); }) // add error row to thead instead of tbody, or clicking on the header will result in a parser error .appendTo( $t.find('thead:first') ); tc.$tbodies.eq(0).empty(); } else { //ensure a zero returned row count doesn't fail the logical || rr_count = result[t ? 1 : 0]; c.totalRows = isNaN(rr_count) ? c.totalRows || 0 : rr_count; d = result[t ? 0 : 1] || []; // row data l = d.length; th = result[2]; // headers if (d instanceof jQuery) { // append jQuery object tc.$tbodies.eq(0).empty().append(d); } else if (d.length) { // build table from array if ( l > 0 ) { for ( i = 0; i < l; i++ ) { tds += '<tr>'; for ( j = 0; j < d[i].length; j++ ) { // build tbody cells tds += '<td>' + d[i][j] + '</td>'; } tds += '</tr>'; } } // add rows to first tbody tc.$tbodies.eq(0).html( tds ); } // only add new header text if the length matches if ( th && th.length === hl ) { hsh = $t.hasClass('hasStickyHeaders'); $sh = hsh ? tc.$sticky.children('thead:first').children().children() : ''; $f = $t.find('tfoot tr:first').children(); $t.find('th.' + tc.cssHeader).each(function(j){ var $t = $(this), icn; // add new test within the first span it finds, or just in the header if ( $t.find('.' + tc.cssIcon).length ) { icn = $t.find('.' + tc.cssIcon).clone(true); $t.find('.tablesorter-header-inner').html( th[j] ).append(icn); if ( hsh && $sh.length ) { icn = $sh.eq(j).find('.' + tc.cssIcon).clone(true); $sh.eq(j).find('.tablesorter-header-inner').html( th[j] ).append(icn); } } else { $t.find('.tablesorter-header-inner').html( th[j] ); if (hsh && $sh.length) { $sh.eq(j).find('.tablesorter-header-inner').html( th[j] ); } } $f.eq(j).html( th[j] ); }); } } if (tc.showProcessing) { $.tablesorter.isProcessing(table); // remove loading icon } $t.trigger('update'); c.totalPages = Math.ceil( c.totalRows / c.size ); updatePageDisplay(table, c); fixHeight(table, c); if (c.initialized) { $t.trigger('pagerChange', c); } } if (!c.initialized) { c.initialized = true; $(table).trigger('pagerInitialized', c); } }, getAjax = function(table, c){ var url = getAjaxUrl(table, c), $doc = $(document), tc = table.config; if ( url !== '' ) { if (tc.showProcessing) { $.tablesorter.isProcessing(table, true); // show loading icon } $doc.bind('ajaxError.pager', function(e, xhr, settings, exception) { //show the error message on the table if (url === settings.url) { renderAjax(null, table, c, xhr, exception); $doc.unbind('ajaxError.pager'); } }); c.ajaxObject.url = url; // from the ajaxUrl option and modified by customAjaxUrl c.ajaxObject.success = function(data) { renderAjax(data, table, c); $doc.unbind('ajaxError.pager'); if (typeof c.oldAjaxSuccess === 'function') { c.oldAjaxSuccess(data); } }; $.ajax(c.ajaxObject); } }, getAjaxUrl = function(table, c) { var url = (c.ajaxUrl) ? c.ajaxUrl // allow using "{page+1}" in the url string to switch to a non-zero based index .replace(/\{page([\-+]\d+)?\}/, function(s,n){ return c.page + (n ? parseInt(n, 10) : 0); }) .replace(/\{size\}/g, c.size) : '', sl = table.config.sortList, fl = c.currentFilters || [], sortCol = url.match(/\{\s*sort(?:List)?\s*:\s*(\w*)\s*\}/), filterCol = url.match(/\{\s*filter(?:List)?\s*:\s*(\w*)\s*\}/), arry = []; if (sortCol) { sortCol = sortCol[1]; $.each(sl, function(i,v){ arry.push(sortCol + '[' + v[0] + ']=' + v[1]); }); // if the arry is empty, just add the col parameter... "&{sortList:col}" becomes "&col" url = url.replace(/\{\s*sort(?:List)?\s*:\s*(\w*)\s*\}/g, arry.length ? arry.join('&') : sortCol ); arry = []; } if (filterCol) { filterCol = filterCol[1]; $.each(fl, function(i,v){ if (v) { arry.push(filterCol + '[' + i + ']=' + encodeURIComponent(v)); } }); // if the arry is empty, just add the fcol parameter... "&{filterList:fcol}" becomes "&fcol" url = url.replace(/\{\s*filter(?:List)?\s*:\s*(\w*)\s*\}/g, arry.length ? arry.join('&') : filterCol ); } if ( typeof(c.customAjaxUrl) === "function" ) { url = c.customAjaxUrl(table, url); } return url; }, renderTable = function(table, rows, c) { c.isDisabled = false; // needed because sorting will change the page and re-enable the pager var i, j, o, $tb, l = rows.length, s = ( c.page * c.size ), e = ( s + c.size ); if ( l < 1 ) { return; } // empty table, abort! if (c.initialized) { $(table).trigger('pagerChange', c); } if ( !c.removeRows ) { hideRows(table, c); } else { if ( e > rows.length ) { e = rows.length; } $.tablesorter.clearTableBody(table); $tb = $.tablesorter.processTbody(table, table.config.$tbodies.eq(0), true); for ( i = s; i < e; i++ ) { o = rows[i]; l = o.length; for ( j = 0; j < l; j++ ) { $tb.appendChild(o[j]); } } $.tablesorter.processTbody(table, $tb, false); } if ( c.page >= c.totalPages ) { moveToLastPage(table, c); } updatePageDisplay(table, c); if ( !c.isDisabled ) { fixHeight(table, c); } $(table).trigger('applyWidgets'); }, showAllRows = function(table, c){ if ( c.ajax ) { pagerArrows(c, true); } else { c.isDisabled = true; $.data(table, 'pagerLastPage', c.page); $.data(table, 'pagerLastSize', c.size); c.page = 0; c.size = c.totalRows; c.totalPages = 1; $(table).find('tr.pagerSavedHeightSpacer').remove(); renderTable(table, table.config.rowsCopy, c); } // disable size selector c.$size.add(c.$goto).each(function(){ $(this).addClass(c.cssDisabled)[0].disabled = true; }); }, moveToPage = function(table, c, flag) { if ( c.isDisabled ) { return; } var p = Math.min( c.totalPages, c.filteredPages ); if ( c.page < 0 ) { c.page = 0; } if ( c.page > ( p - 1 ) && p !== 0 ) { c.page = p - 1; } if (c.ajax) { getAjax(table, c); } else if (!c.ajax) { renderTable(table, table.config.rowsCopy, c); } $.data(table, 'pagerLastPage', c.page); $.data(table, 'pagerUpdateTriggered', true); if (c.initialized && flag !== false) { $(table).trigger('pageMoved', c); } }, setPageSize = function(table, size, c) { c.size = size; c.$size.val(size); $.data(table, 'pagerLastPage', c.page); $.data(table, 'pagerLastSize', c.size); c.totalPages = Math.ceil( c.totalRows / c.size ); moveToPage(table, c); }, moveToFirstPage = function(table, c) { c.page = 0; moveToPage(table, c); }, moveToLastPage = function(table, c) { c.page = ( Math.min( c.totalPages, c.filteredPages ) - 1 ); moveToPage(table, c); }, moveToNextPage = function(table, c) { c.page++; if ( c.page >= ( Math.min( c.totalPages, c.filteredPages ) - 1 ) ) { c.page = ( Math.min( c.totalPages, c.filteredPages ) - 1 ); } moveToPage(table, c); }, moveToPrevPage = function(table, c) { c.page--; if ( c.page <= 0 ) { c.page = 0; } moveToPage(table, c); }, destroyPager = function(table, c){ showAllRows(table, c); c.$container.hide(); // hide pager table.config.appender = null; // remove pager appender function $(table).unbind('destroy.pager sortEnd.pager filterEnd.pager enable.pager disable.pager'); }, enablePager = function(table, c, triggered){ var p = c.$size.removeClass(c.cssDisabled).removeAttr('disabled'); c.$goto.removeClass(c.cssDisabled).removeAttr('disabled'); c.isDisabled = false; c.page = $.data(table, 'pagerLastPage') || c.page || 0; c.size = $.data(table, 'pagerLastSize') || parseInt(p.find('option[selected]').val(), 10) || c.size; p.val(c.size); // set page size c.totalPages = Math.ceil( Math.min( c.totalPages, c.filteredPages ) / c.size); if ( triggered ) { $(table).trigger('update'); setPageSize(table, c.size, c); hideRowsSetup(table, c); fixHeight(table, c); } }; $this.appender = function(table, rows) { var c = table.config.pager; if ( !c.ajax ) { table.config.rowsCopy = rows; c.totalRows = rows.length; c.size = $.data(table, 'pagerLastSize') || c.size; c.totalPages = Math.ceil(c.totalRows / c.size); renderTable(table, rows, c); } }; $this.construct = function(settings) { return this.each(function() { // check if tablesorter has initialized if (!(this.config && this.hasInitialized)) { return; } var t, ctrls, fxn, config = this.config, c = config.pager = $.extend( {}, $.tablesorterPager.defaults, settings ), table = this, tc = table.config, $t = $(table), // added in case the pager is reinitialized after being destroyed. pager = c.$container = $(c.container).addClass('tablesorter-pager').show(); c.oldAjaxSuccess = c.oldAjaxSuccess || c.ajaxObject.success; config.appender = $this.appender; $t .unbind('filterStart.pager filterEnd.pager sortEnd.pager disable.pager enable.pager destroy.pager update.pager pageSize.pager') .bind('filterStart.pager', function(e, filters) { $.data(table, 'pagerUpdateTriggered', false); c.currentFilters = filters; }) // update pager after filter widget completes .bind('filterEnd.pager sortEnd.pager', function(e) { //Prevent infinite event loops from occuring by setting this in all moveToPage calls and catching it here. if ($.data(table, 'pagerUpdateTriggered')) { $.data(table, 'pagerUpdateTriggered', false); return; } //only run the server side sorting if it has been enabled if (e.type === "filterEnd" || (e.type === "sortEnd" && tc.serverSideSorting)) { moveToPage(table, c, false); } updatePageDisplay(table, c, false); fixHeight(table, c); }) .bind('disable.pager', function(e){ e.stopPropagation(); showAllRows(table, c); }) .bind('enable.pager', function(e){ e.stopPropagation(); enablePager(table, c, true); }) .bind('destroy.pager', function(e){ e.stopPropagation(); destroyPager(table, c); }) .bind('update.pager', function(e){ e.stopPropagation(); hideRows(table, c); }) .bind('pageSize.pager', function(e,v){ e.stopPropagation(); setPageSize(table, parseInt(v, 10) || 10, c); hideRows(table, c); updatePageDisplay(table, c, false); if (c.$size.length) { c.$size.val(c.size); } // twice? }) .bind('pageSet.pager', function(e,v){ e.stopPropagation(); c.page = (parseInt(v, 10) || 1) - 1; if (c.$goto.length) { c.$goto.val(c.size); } // twice? moveToPage(table, c); updatePageDisplay(table, c, false); }); // clicked controls ctrls = [ c.cssFirst, c.cssPrev, c.cssNext, c.cssLast ]; fxn = [ moveToFirstPage, moveToPrevPage, moveToNextPage, moveToLastPage ]; pager.find(ctrls.join(',')) .unbind('click.pager') .bind('click.pager', function(e){ var i, $t = $(this), l = ctrls.length; if ( !$t.hasClass(c.cssDisabled) ) { for (i = 0; i < l; i++) { if ($t.is(ctrls[i])) { fxn[i](table, c); break; } } } return false; }); // goto selector c.$goto = pager.find(c.cssGoto); if ( c.$goto.length ) { c.$goto .unbind('change') .bind('change', function(){ c.page = $(this).val() - 1; moveToPage(table, c); }); updatePageDisplay(table, c, false); } // page size selector c.$size = pager.find(c.cssPageSize); if ( c.$size.length ) { c.$size.unbind('change.pager').bind('change.pager', function() { c.$size.val( $(this).val() ); // in case there are more than one pagers if ( !$(this).hasClass(c.cssDisabled) ) { setPageSize(table, parseInt( $(this).val(), 10 ), c); changeHeight(table, c); } return false; }); } // clear initialized flag c.initialized = false; // before initialization event $t.trigger('pagerBeforeInitialized', c); enablePager(table, c, false); if ( typeof(c.ajaxUrl) === 'string' ) { // ajax pager; interact with database c.ajax = true; //When filtering with ajax, allow only custom filtering function, disable default filtering since it will be done server side. tc.widgetOptions.filter_serversideFiltering = true; tc.serverSideSorting = true; moveToPage(table, c); } else { c.ajax = false; // Regular pager; all rows stored in memory $(this).trigger("appendCache", true); hideRowsSetup(table, c); } changeHeight(table, c); // pager initialized if (!c.ajax) { c.initialized = true; $(table).trigger('pagerInitialized', c); } }); }; }() }); // extend plugin scope $.fn.extend({ tablesorterPager: $.tablesorterPager.construct }); })(jQuery);
churchill-lab/qtl-viewer
qtlviewer/static/jquery.tablesorter/addons/pager/jquery.tablesorter.pager.js
JavaScript
gpl-3.0
21,755
angular.module('senseItWeb', null, null).controller('ProfileCtrl', function ($scope, OpenIdService, $state, fileReader) { 'use strict'; var _ = $scope._ , password_min = 6; $scope.noyes = [ {value: '0', label: 'no'}, {value: '1', label: 'yes'} ]; if (!$scope.status.logged && $state.params.goBack) { OpenIdService.registerWatcher($scope, function () { if ($scope.status.logged) { $state.go($state.previous); } }); } $scope.form = new SiwFormManager(function () { if ($scope.status.profile.metadata === null) { $scope.status.profile.metadata = {}; } if ($scope.status.profile.visibility === null) { $scope.status.profile.visibility = {}; } return $scope.status.profile; }, ['username', 'email', 'notify1', 'notify2', 'notify3', 'notify4', 'notify5', 'metadata', 'visibility'], function () { $scope.status.newUser = false; $scope.openIdService.saveProfile().then(function (data) { $scope.formError = data.responses.username || null; if ($scope.formError) { $scope.form.open('username'); } }); }, function () { $scope.formError = null; } ); $scope.visibilityDisplay = function () { var options = [ ['metadata', 'Profile information'], ['projectsJoined', 'Joined projects'], ['projectsCreated', 'Projects created by me'] ].filter(function (option) { return $scope.status.profile.visibility && $scope.status.profile.visibility[option[0]]; }); if (options.length > 0) { return options.map(function (option) { return '<b>' + option[1] + '</b>'; }).join(', '); } else { return 'none'; } }; $scope.imageForm = new SiwFormManager(function () { return $scope.status.profile; }, [], function () { $scope.openIdService.saveProfileImage($scope.imageForm.files); }); $scope.filelistener = { previewFile: null, set: function (key, file) { $scope.imageForm.setFile(key, file); this.updatePreview(); }, clear: function (key) { $scope.imageForm.clearFile(key); this.updatePreview(); }, deleteFile: function (key) { $scope.imageForm.deleteFile(key); this.updatePreview(); }, updatePreview: function () { if ($scope.imageForm.files['image']) { fileReader.readAsDataUrl($scope.imageForm.files['image'], $scope).then(function (result) { $scope.filelistener.previewFile = result; }); } else { $scope.filelistener.previewFile = null; } } }; $scope.filelistener.updatePreview(); $scope.logout = function () { $scope.openIdService.logout(); }; $scope.providerLogin = function (provider, action) { OpenIdService.providerLogin(provider, action); }; $scope.deleteConnection = function (providerId) { $scope.openIdService.deleteConnection(providerId); }; $scope.formError = null; $scope.formErrorText = function () { switch ($scope.formError) { case 'username_empty': return 'Username cannot be empty'; case 'username_not_available': return 'Username not available (already taken)'; default: return ''; } }; $scope.loginMode = { mode: 'login', set: function (mode) { this.mode = mode; }, is: function (mode) { return this.mode === mode; } }; $scope.login = { editing: {username: '', password: ''}, error: { username: false, password: false }, clearPassword: function () { var p = this.editing.password; this.editing.password = ""; return p; }, submit: function () { var ok = true; this.editing.username = this.editing.username.trim(); if (this.editing.username.length === 0) { this.error.username = _('Username cannot be empty.'); ok = false; } if (this.editing.password.length === 0) { this.error.password = _('Password cannot be empty.'); ok = false; } if (ok) { var error = this.error; error.username = null; OpenIdService.login(this.editing.username, this.clearPassword(), function (data) { error.password = data === 'false' ? _('Username & password do not match.') : null; }); } } }; $scope.register = { recaptcha: {siteKey: $scope.cfg.recaptcha.siteKey}, editing: {username: '', password: '', repeatPassword: '', email: ''}, error: {username: false, password: false, repeatPassword: false, email: false, recaptcha: false}, clearPassword: function () { var p = this.editing.password; this.editing.password = this.editing.repeatPassword = ""; return p; }, reset: function () { this.editing = {username: '', password: '', repeatPassword: '', email: ''}; this.error = {username: false, password: false, repeatPassword: false, email: false, recaptcha: false}; }, submit: function () { var ok = true; this.editing.username = this.editing.username.trim(); this.editing.email = this.editing.email.trim(); this.editing.recaptcha = angular.element("#g-recaptcha-response").val(); this.error = {username: false, password: false, repeatPassword: false, email: false, recaptcha: false}; if (this.editing.username.length === 0) { this.error.username = _('Username cannot be empty.'); ok = false; } if (this.editing.email.length === 0) { this.error.email = _('Email cannot be empty.'); ok = false; } if (this.editing.password.length < password_min) { this.error.password = _('Password must have at least {{n}} characters.', { 'n': password_min }); ok = false; } if (this.editing.password !== this.editing.repeatPassword) { this.error.repeatPassword = _('Passwords do not match.'); ok = false; } if (this.editing.recaptcha === '') { this.error.recaptcha = _('Are you a human being or a robot?'); ok = false; } if (ok) { var error = this.error = {username: false, password: false, repeatPassword: false, email: false}; OpenIdService.register(this.editing.username, this.clearPassword(), this.editing.email, this.editing.recaptcha).then(function (data) { switch (data.responses.registration) { case 'username_exists': error.username = _('Username not available.'); break; case 'email_exists': error.email = _('Email already associated with a different account.'); break; case 'bad_recaptcha': error.recaptcha = _('Captcha failed. Try again.'); grecaptcha.reset(); break; } }); } } }; $scope.reminder = { recaptcha: {siteKey: $scope.cfg.recaptcha.siteKey}, editing: {email: ''}, error: {email: false}, reset: function () { this.editing = {email: ''}; this.error = {email: false}; }, submit: function () { var ok = true; this.editing.email = this.editing.email.trim(); this.editing.recaptcha = angular.element("#g-recaptcha-response").val(); if (this.editing.email.length === 0) { this.error.email = _('Email cannot be empty.'); ok = false; } if (this.editing.recaptcha === '') { this.error.recaptcha = _('Are you a human being or a robot?'); ok = false; } if (ok) { var error = this.error = {email: false}; OpenIdService.reminder(this.editing.email, this.editing.recaptcha).then(function (data) { grecaptcha.reset(); switch (data.responses.reminder) { case 'email_not_exists': error.email = _('No account found with that email or username.'); break; case 'bad_recaptcha': error.recaptcha = _('Captcha failed. Try again.'); break; case 'reminder_sent': error.email = _('A password reminder has been sent.'); break; } }); } } }; $scope.password = { set: function () { return $scope.status.profile.passwordSet; }, editing: false, error: { oldPassword: false, newPassword: false, repeatPassword: false }, edit: function () { this.editing = {oldPassword: '', newPassword: '', repeatPassword: ''}; }, close: function () { this.editing = false; }, cancel: function () { this.close(); }, save: function () { var ok = true; if (this.editing.newPassword.length < password_min) { this.error.password = _('Password must have at least {{n}} characters.', { 'n': password_min }); ok = false; } if (this.editing.newPassword !== this.editing.repeatPassword) { this.error.repeatPassword = _('Passwords do not match.'); ok = false; } if (ok) { var self = this; var error = self.error; error.repeatPassword = false; OpenIdService.setPassword(this.editing.oldPassword, this.editing.newPassword).then(function (data) { switch (data.responses.oldpassword) { case 'bad_password': error.oldPassword = 'Old password is not valid.'; break; default: error.oldPassword = false; break; } switch (data.responses.newpassword) { case 'too_short': error.newPassword = 'New password is too short.'; break; case 'same_as_username': error.newPassword = 'New password cannot be equal to your username.'; break; default: error.newPassword = false; break; } if (!error.repeatPassword && !error.newPassword && !error.oldPassword) { self.close(); } }); } } }; });
IET-OU/nquire-web-source
static/src/js/app/controllers/profile/profile-controller.js
JavaScript
gpl-3.0
10,138
/* * A JavaScript implementation of the SHA256 hash function. * * FILE: sha256.js * VERSION: 0.8 * AUTHOR: Christoph Bichlmeier <informatik@zombiearena.de> * * NOTE: This version is not tested thoroughly! * * Copyright (c) 2003, Christoph Bichlmeier * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * ====================================================================== * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* SHA256 logical functions */ function rotateRight(n,x) { return ((x >>> n) | (x << (32 - n))); } function choice(x,y,z) { return ((x & y) ^ (~x & z)); } function majority(x,y,z) { return ((x & y) ^ (x & z) ^ (y & z)); } function sha256_Sigma0(x) { return (rotateRight(2, x) ^ rotateRight(13, x) ^ rotateRight(22, x)); } function sha256_Sigma1(x) { return (rotateRight(6, x) ^ rotateRight(11, x) ^ rotateRight(25, x)); } function sha256_sigma0(x) { return (rotateRight(7, x) ^ rotateRight(18, x) ^ (x >>> 3)); } function sha256_sigma1(x) { return (rotateRight(17, x) ^ rotateRight(19, x) ^ (x >>> 10)); } function sha256_expand(W, j) { return (W[j&0x0f] += sha256_sigma1(W[(j+14)&0x0f]) + W[(j+9)&0x0f] + sha256_sigma0(W[(j+1)&0x0f])); } /* Hash constant words K: */ var K256 = new Array( 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ); /* global arrays */ var ihash, count, buffer; var sha256_hex_digits = "0123456789abcdef"; /* Add 32-bit integers with 16-bit operations (bug in some JS-interpreters: overflow) */ function safe_add(x, y) { var lsw = (x & 0xffff) + (y & 0xffff); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xffff); } /* Initialise the SHA256 computation */ function sha256_init() { ihash = new Array(8); count = new Array(2); buffer = new Array(64); count[0] = count[1] = 0; ihash[0] = 0x6a09e667; ihash[1] = 0xbb67ae85; ihash[2] = 0x3c6ef372; ihash[3] = 0xa54ff53a; ihash[4] = 0x510e527f; ihash[5] = 0x9b05688c; ihash[6] = 0x1f83d9ab; ihash[7] = 0x5be0cd19; } /* Transform a 512-bit message block */ function sha256_transform() { var a, b, c, d, e, f, g, h, T1, T2; var W = new Array(16); /* Initialize registers with the previous intermediate value */ a = ihash[0]; b = ihash[1]; c = ihash[2]; d = ihash[3]; e = ihash[4]; f = ihash[5]; g = ihash[6]; h = ihash[7]; /* make 32-bit words */ for(var i=0; i<16; i++) W[i] = ((buffer[(i<<2)+3]) | (buffer[(i<<2)+2] << 8) | (buffer[(i<<2)+1] << 16) | (buffer[i<<2] << 24)); for(var j=0; j<64; j++) { T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j]; if(j < 16) T1 += W[j]; else T1 += sha256_expand(W, j); T2 = sha256_Sigma0(a) + majority(a, b, c); h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); } /* Compute the current intermediate hash value */ ihash[0] += a; ihash[1] += b; ihash[2] += c; ihash[3] += d; ihash[4] += e; ihash[5] += f; ihash[6] += g; ihash[7] += h; } /* Read the next chunk of data and update the SHA256 computation */ function sha256_update(data, inputLen) { var i, index, curpos = 0; /* Compute number of bytes mod 64 */ index = ((count[0] >> 3) & 0x3f); var remainder = (inputLen & 0x3f); /* Update number of bits */ if ((count[0] += (inputLen << 3)) < (inputLen << 3)) count[1]++; count[1] += (inputLen >> 29); /* Transform as many times as possible */ for(i=0; i+63<inputLen; i+=64) { for(var j=index; j<64; j++) buffer[j] = data.charCodeAt(curpos++); sha256_transform(); index = 0; } /* Buffer remaining input */ for(var j=0; j<remainder; j++) buffer[j] = data.charCodeAt(curpos++); } /* Finish the computation by operations such as padding */ function sha256_final() { var index = ((count[0] >> 3) & 0x3f); buffer[index++] = 0x80; if(index <= 56) { for(var i=index; i<56; i++) buffer[i] = 0; } else { for(var i=index; i<64; i++) buffer[i] = 0; sha256_transform(); for(var i=0; i<56; i++) buffer[i] = 0; } buffer[56] = (count[1] >>> 24) & 0xff; buffer[57] = (count[1] >>> 16) & 0xff; buffer[58] = (count[1] >>> 8) & 0xff; buffer[59] = count[1] & 0xff; buffer[60] = (count[0] >>> 24) & 0xff; buffer[61] = (count[0] >>> 16) & 0xff; buffer[62] = (count[0] >>> 8) & 0xff; buffer[63] = count[0] & 0xff; sha256_transform(); } /* Split the internal hash values into an array of bytes */ function sha256_encode_bytes() { var j=0; var output = new Array(32); for(var i=0; i<8; i++) { output[j++] = ((ihash[i] >>> 24) & 0xff); output[j++] = ((ihash[i] >>> 16) & 0xff); output[j++] = ((ihash[i] >>> 8) & 0xff); output[j++] = (ihash[i] & 0xff); } return output; } /* Get the internal hash as a hex string */ function sha256_encode_hex() { var output = new String(); for(var i=0; i<8; i++) { for(var j=28; j>=0; j-=4) output += sha256_hex_digits.charAt((ihash[i] >>> j) & 0x0f); } return output; } /* Main function: returns a hex string representing the SHA256 value of the given data */ function sha256_digest(data) { sha256_init(); sha256_update(data, data.length); sha256_final(); return sha256_encode_hex(); } /* test if the JS-interpreter is working properly */ function sha256_self_test() { return sha256_digest("message digest") == "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"; }
smit-happens/WhiteboardProject
Whiteboard/WebContent/sha256.js
JavaScript
gpl-3.0
7,554
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = elementIdClick; var _ErrorHandler = require('../utils/ErrorHandler'); function elementIdClick(id) { if (typeof id !== 'string' && typeof id !== 'number') { throw new _ErrorHandler.ProtocolError('number or type of arguments don\'t agree with elementIdClick protocol command'); } return this.requestHandler.create({ path: `/session/:sessionId/element/${id}/click`, method: 'POST' }); } /** * * Click on an element. * * @param {String} ID ID of a WebElement JSON object to route the command to * * @see https://w3c.github.io/webdriver/webdriver-spec.html#dfn-element-click * @type protocol * */ module.exports = exports['default'];
Cy6erlion/wharica
node_modules/webdriverio/build/lib/protocol/elementIdClick.js
JavaScript
gpl-3.0
800
(function() { var Agent, AgentSet, Agents, Animator, Color, ColorMap, Evented, Link, Links, Model, Patch, Patches, Shapes, Util, shapes, u, util, __hasProp = {}.hasOwnProperty, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __slice = [].slice, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; Util = util = u = { error: function(s) { throw new Error(s); }, MaxINT: Math.pow(2, 53), MinINT: -Math.pow(2, 53), MaxINT32: 0 | 0x7fffffff, MinINT32: 0 | 0x80000000, isArray: Array.isArray || function(obj) { return !!(obj && obj.concat && obj.unshift && !obj.callee); }, isFunction: function(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, isString: function(obj) { return !!(obj === '' || (obj && obj.charCodeAt && obj.substr)); }, randomSeed: function(seed) { if (seed == null) { seed = 123456; } return Math.random = function() { var x; x = Math.sin(seed++) * 10000; return x - Math.floor(x); }; }, randomInt: function(max) { return Math.floor(Math.random() * max); }, randomInt2: function(min, max) { return min + Math.floor(Math.random() * (max - min)); }, randomNormal: function(mean, sigma) { var norm, u1, u2; if (mean == null) { mean = 0.0; } if (sigma == null) { sigma = 1.0; } u1 = 1.0 - Math.random(); u2 = Math.random(); norm = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2); return norm * sigma + mean; }, randomFloat: function(max) { return Math.random() * max; }, randomFloat2: function(min, max) { return min + Math.random() * (max - min); }, randomCentered: function(r) { return this.randomFloat2(-r / 2, r / 2); }, log10: function(n) { return Math.log(n) / Math.LN10; }, log2: function(n) { return this.logN(n, 2); }, logN: function(n, base) { return Math.log(n) / Math.log(base); }, mod: function(v, n) { return ((v % n) + n) % n; }, wrap: function(v, min, max) { return min + this.mod(v - min, max - min); }, clamp: function(v, min, max) { return Math.max(Math.min(v, max), min); }, sign: function(v) { if (v < 0) { return -1; } else { return 1; } }, fixed: function(n, p) { if (p == null) { p = 2; } p = Math.pow(10, p); return Math.round(n * p) / p; }, aToFixed: function(a, p) { var i, _i, _len, _results; if (p == null) { p = 2; } _results = []; for (_i = 0, _len = a.length; _i < _len; _i++) { i = a[_i]; _results.push(i.toFixed(p)); } return _results; }, tls: function(n) { return n.toLocaleString(); }, randomColor: function(c) { var i, _i; if (c == null) { c = []; } if (c.str != null) { c.str = null; } for (i = _i = 0; _i <= 2; i = ++_i) { c[i] = this.randomInt(256); } return c; }, randomGray: function(c, min, max) { var i, r, _i; if (c == null) { c = []; } if (min == null) { min = 64; } if (max == null) { max = 192; } if (arguments.length === 2) { return this.randomGray(null, c, min); } if (c.str != null) { c.str = null; } r = this.randomInt2(min, max); for (i = _i = 0; _i <= 2; i = ++_i) { c[i] = r; } return c; }, randomMapColor: function(c, set) { if (c == null) { c = []; } if (set == null) { set = [0, 63, 127, 191, 255]; } return this.setColor(c, this.oneOf(set), this.oneOf(set), this.oneOf(set)); }, randomBrightColor: function(c) { if (c == null) { c = []; } return this.randomMapColor(c, [0, 127, 255]); }, randomHSBColor: function(c) { if (c == null) { c = []; } return c = this.hsbToRgb([this.randomInt(51) * 5, 255, 255]); }, setColor: function(c, r, g, b, a) { if (c.str != null) { c.str = null; } c[0] = r; c[1] = g; c[2] = b; if (a != null) { c[3] = a; } return c; }, setGray: function(c, g, a) { return this.setColor(c, g, g, g, a); }, scaleColor: function(max, s, c) { var i, val, _i, _len; if (c == null) { c = []; } if (c.str != null) { c.str = null; } for (i = _i = 0, _len = max.length; _i < _len; i = ++_i) { val = max[i]; c[i] = this.clamp(Math.round(val * s), 0, 255); } return c; }, colorStr: function(c) { var s; if ((s = c.str) != null) { return s; } if (c.length === 4 && c[3] > 1) { this.error("alpha > 1"); } return c.str = c.length === 3 ? "rgb(" + c + ")" : "rgba(" + c + ")"; }, colorsEqual: function(c1, c2) { return c1.toString() === c2.toString(); }, rgbToGray: function(c) { return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; }, rgbToHsb: function(c) { var b, d, g, h, max, min, r, s, v; r = c[0] / 255; g = c[1] / 255; b = c[2] / 255; max = Math.max(r, g, b); min = Math.min(r, g, b); v = max; h = 0; d = max - min; s = max === 0 ? 0 : d / max; if (max !== min) { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; } } return [Math.round(255 * h / 6), Math.round(255 * s), Math.round(255 * v)]; }, hsbToRgb: function(c) { var b, f, g, h, i, p, q, r, s, t, v; h = c[0] / 255; s = c[1] / 255; v = c[2] / 255; i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; }, rgbMap: function(R, G, B) { var b, g, i, map, r, _i, _j, _k, _len, _len1, _len2; if (G == null) { G = R; } if (B == null) { B = R; } if (typeof R === "number") { R = (function() { var _i, _results; _results = []; for (i = _i = 0; 0 <= R ? _i < R : _i > R; i = 0 <= R ? ++_i : --_i) { _results.push(Math.round(i * 255 / (R - 1))); } return _results; })(); } if (typeof G === "number") { G = (function() { var _i, _results; _results = []; for (i = _i = 0; 0 <= G ? _i < G : _i > G; i = 0 <= G ? ++_i : --_i) { _results.push(Math.round(i * 255 / (G - 1))); } return _results; })(); } if (typeof B === "number") { B = (function() { var _i, _results; _results = []; for (i = _i = 0; 0 <= B ? _i < B : _i > B; i = 0 <= B ? ++_i : --_i) { _results.push(Math.round(i * 255 / (B - 1))); } return _results; })(); } map = []; for (_i = 0, _len = R.length; _i < _len; _i++) { r = R[_i]; for (_j = 0, _len1 = G.length; _j < _len1; _j++) { g = G[_j]; for (_k = 0, _len2 = B.length; _k < _len2; _k++) { b = B[_k]; map.push([r, g, b]); } } } return map; }, grayMap: function() { var i, _i, _results; _results = []; for (i = _i = 0; _i <= 255; i = ++_i) { _results.push([i, i, i]); } return _results; }, hsbMap: function(n, s, b) { var i, _i, _results; if (n == null) { n = 256; } if (s == null) { s = 255; } if (b == null) { b = 255; } _results = []; for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) { _results.push(this.hsbToRgb([i * 255 / (n - 1), s, b])); } return _results; }, gradientMap: function(nColors, stops, locs) { var ctx, grad, i, id, _i, _j, _ref, _ref1, _results; if (locs == null) { locs = (function() { var _i, _ref, _results; _results = []; for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(i / (stops.length - 1)); } return _results; })(); } ctx = this.createCtx(nColors, 1); grad = ctx.createLinearGradient(0, 0, nColors, 0); for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { grad.addColorStop(locs[i], this.colorStr(stops[i])); } ctx.fillStyle = grad; ctx.fillRect(0, 0, nColors, 1); id = this.ctxToImageData(ctx).data; _results = []; for (i = _j = 0, _ref1 = id.length; _j < _ref1; i = _j += 4) { _results.push([id[i], id[i + 1], id[i + 2]]); } return _results; }, isLittleEndian: function() { var d32; d32 = new Uint32Array([0x01020304]); return (new Uint8ClampedArray(d32.buffer))[0] === 4; }, degToRad: function(degrees) { return degrees * Math.PI / 180; }, radToDeg: function(radians) { return radians * 180 / Math.PI; }, subtractRads: function(rad1, rad2) { var PI, dr; dr = rad1 - rad2; PI = Math.PI; if (dr <= -PI) { dr += 2 * PI; } if (dr > PI) { dr -= 2 * PI; } return dr; }, ownKeys: function(obj) { var key, value, _results; _results = []; for (key in obj) { if (!__hasProp.call(obj, key)) continue; value = obj[key]; _results.push(key); } return _results; }, ownVarKeys: function(obj) { var key, value, _results; _results = []; for (key in obj) { if (!__hasProp.call(obj, key)) continue; value = obj[key]; if (!this.isFunction(value)) { _results.push(key); } } return _results; }, ownValues: function(obj) { var key, value, _results; _results = []; for (key in obj) { if (!__hasProp.call(obj, key)) continue; value = obj[key]; _results.push(value); } return _results; }, cloneObject: function(obj) { var key, newObj, value; newObj = {}; for (key in obj) { if (!__hasProp.call(obj, key)) continue; value = obj[key]; newObj[key] = obj[key]; } if (obj.__proto__ !== Object.prototype) { console.log("cloneObject, setting proto"); newObj.__proto__ = obj.__proto__; } return newObj; }, cloneClass: function(oldClass, newName) { var ctorStr; ctorStr = oldClass.toString().replace(/^/, "var ctor = "); if (newName) { ctorStr = ctorStr.replace(/function.*{/, "function " + newName + "() {"); } eval(ctorStr); ctor.prototype = this.cloneObject(oldClass.prototype); ctor.constructor = oldClass.constructor; ctor.prototype.constructor = oldClass.prototype.constructor; return ctor; }, mixin: function(destObj, srcObject) { var key, _ref, _results; for (key in srcObject) { if (!__hasProp.call(srcObject, key)) continue; destObj[key] = srcObject[key]; } _ref = srcObject.__proto__; _results = []; for (key in _ref) { if (!__hasProp.call(_ref, key)) continue; _results.push(destObj.__proto__[key] = srcObject.__proto__[key]); } return _results; }, parseToPrimitive: function(s) { var e; try { return JSON.parse(s); } catch (_error) { e = _error; return decodeURIComponent(s); } }, parseQueryString: function(query) { var res, s, t, _i, _len, _ref; if (query == null) { query = window.location.search.substring(1); } res = {}; _ref = query.split("&"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { s = _ref[_i]; if (!(query.length !== 0)) { continue; } t = s.split("="); res[t[0]] = t.length === 1 ? true : this.parseToPrimitive(t[1]); } return res; }, any: function(array) { return array.length !== 0; }, empty: function(array) { return array.length === 0; }, clone: function(array, begin, end) { var op; op = array.slice != null ? "slice" : "subarray"; if (begin != null) { return array[op](begin, end); } else { return array[op](0); } }, last: function(array) { if (this.empty(array)) { this.error("last: empty array"); } return array[array.length - 1]; }, oneOf: function(array) { if (this.empty(array)) { this.error("oneOf: empty array"); } return array[this.randomInt(array.length)]; }, nOf: function(array, n) { var o, r; n = Math.min(array.length, Math.floor(n)); r = []; while (r.length < n) { o = this.oneOf(array); if (__indexOf.call(r, o) < 0) { r.push(o); } } return r; }, contains: function(array, item, f) { return this.indexOf(array, item, f) >= 0; }, removeItem: function(array, item, f) { var i; if (!((i = this.indexOf(array, item, f)) < 0)) { return array.splice(i, 1); } else { return this.error("removeItem: item not found"); } }, removeItems: function(array, items, f) { var i, _i, _len; for (_i = 0, _len = items.length; _i < _len; _i++) { i = items[_i]; this.removeItem(array, i, f); } return array; }, insertItem: function(array, item, f) { var i; i = this.sortedIndex(array, item, f); if (array[i] === item) { error("insertItem: item already in array"); } return array.splice(i, 0, item); }, shuffle: function(array) { return array.sort(function() { return 0.5 - Math.random(); }); }, minOneOf: function(array, f, valueToo) { var a, o, r, r1, _i, _len; if (f == null) { f = this.identity; } if (valueToo == null) { valueToo = false; } if (this.empty(array)) { this.error("minOneOf: empty array"); } r = Infinity; o = null; if (this.isString(f)) { f = this.propFcn(f); } for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; if ((r1 = f(a)) < r) { r = r1; o = a; } } if (valueToo) { return [o, r]; } else { return o; } }, maxOneOf: function(array, f, valueToo) { var a, o, r, r1, _i, _len; if (f == null) { f = this.identity; } if (valueToo == null) { valueToo = false; } if (this.empty(array)) { this.error("maxOneOf: empty array"); } r = -Infinity; o = null; if (this.isString(f)) { f = this.propFcn(f); } for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; if ((r1 = f(a)) > r) { r = r1; o = a; } } if (valueToo) { return [o, r]; } else { return o; } }, firstOneOf: function(array, f) { var a, i, _i, _len; for (i = _i = 0, _len = array.length; _i < _len; i = ++_i) { a = array[i]; if (f(a)) { return i; } } return -1; }, histOf: function(array, bin, f) { var a, i, r, ri, val, _i, _j, _len, _len1; if (bin == null) { bin = 1; } if (f == null) { f = function(i) { return i; }; } r = []; if (this.isString(f)) { f = this.propFcn(f); } for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; i = Math.floor(f(a) / bin); r[i] = (ri = r[i]) != null ? ri + 1 : 1; } for (i = _j = 0, _len1 = r.length; _j < _len1; i = ++_j) { val = r[i]; if (val == null) { r[i] = 0; } } return r; }, sortBy: function(array, f) { if (this.isString(f)) { f = this.propFcn(f); } return array.sort(function(a, b) { return f(a) - f(b); }); }, sortNums: function(array, ascending) { var f; if (ascending == null) { ascending = true; } f = ascending ? function(a, b) { return a - b; } : function(a, b) { return b - a; }; if (array.sort != null) { return array.sort(f); } else { return Array.prototype.sort.call(array, f); } }, uniq: function(array) { var i, _i, _ref; if (array.length < 2) { return array; } for (i = _i = _ref = array.length - 1; _i >= 1; i = _i += -1) { if (array[i - 1] === array[i]) { array.splice(i, 1); } } return array; }, flatten: function(matrix) { return matrix.reduce(function(a, b) { return a.concat(b); }); }, aProp: function(array, propOrFn) { var a, _i, _j, _len, _len1, _results, _results1; if (typeof propOrFn === 'function') { _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; _results.push(propOrFn(a)); } return _results; } else { _results1 = []; for (_j = 0, _len1 = array.length; _j < _len1; _j++) { a = array[_j]; _results1.push(a[propOrFn]); } return _results1; } }, aToObj: function(array, names) { var i, n, _i, _len; for (i = _i = 0, _len = names.length; _i < _len; i = ++_i) { n = names[i]; array[n] = array[i]; } return array; }, aMax: function(array) { var a, v, _i, _len; v = array[0]; for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; v = Math.max(v, a); } return v; }, aMin: function(array) { var a, v, _i, _len; v = array[0]; for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; v = Math.min(v, a); } return v; }, aSum: function(array) { var a, v, _i, _len; v = 0; for (_i = 0, _len = array.length; _i < _len; _i++) { a = array[_i]; v += a; } return v; }, aAvg: function(array) { return this.aSum(array) / array.length; }, aMid: function(array) { array = array.sort != null ? this.clone(array) : this.typedToJS(array); this.sortNums(array); return array[Math.floor(array.length / 2)]; }, aStats: function(array) { var avg, max, mid, min; min = this.aMin(array); max = this.aMax(array); avg = this.aAvg(array); mid = this.aMid(array); return { min: min, max: max, avg: avg, mid: mid }; }, aNaNs: function(array) { var i, v, _i, _len, _results; _results = []; for (i = _i = 0, _len = array.length; _i < _len; i = ++_i) { v = array[i]; if (isNaN(v)) { _results.push(i); } } return _results; }, aRamp: function(start, stop, numItems, useInts) { var array, num, step; if (useInts == null) { useInts = false; } step = (stop - start) / (numItems - 1); array = (function() { var _i, _results; _results = []; for (num = _i = start; step > 0 ? _i <= stop : _i >= stop; num = _i += step) { _results.push(num); } return _results; })(); if (useInts) { array = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { num = array[_i]; _results.push(Math.round(num)); } return _results; })(); } return array; }, aRange: function(start, stop) { var _i, _results; return (function() { _results = []; for (var _i = start; start <= stop ? _i <= stop : _i >= stop; start <= stop ? _i++ : _i--){ _results.push(_i); } return _results; }).apply(this); }, aPairwise: function(a1, a2, f) { var i, v, _i, _len, _results; v = 0; _results = []; for (i = _i = 0, _len = a1.length; _i < _len; i = ++_i) { v = a1[i]; _results.push(f(v, a2[i])); } return _results; }, aPairSum: function(a1, a2) { return this.aPairwise(a1, a2, function(a, b) { return a + b; }); }, aPairDif: function(a1, a2) { return this.aPairwise(a1, a2, function(a, b) { return a - b; }); }, aPairMul: function(a1, a2) { return this.aPairwise(a1, a2, function(a, b) { return a * b; }); }, typedToJS: function(typedArray) { var i, _i, _len, _results; _results = []; for (_i = 0, _len = typedArray.length; _i < _len; _i++) { i = typedArray[_i]; _results.push(i); } return _results; }, lerp: function(lo, hi, scale) { if (lo <= hi) { return lo + (hi - lo) * scale; } else { return lo - (lo - hi) * scale; } }, lerpScale: function(number, lo, hi) { return (number - lo) / (hi - lo); }, lerp2: function(x0, y0, x1, y1, scale) { return [this.lerp(x0, x1, scale), this.lerp(y0, y1, scale)]; }, normalize: function(array, lo, hi) { var max, min, num, scale, _i, _len, _results; if (lo == null) { lo = 0; } if (hi == null) { hi = 1; } min = this.aMin(array); max = this.aMax(array); scale = 1 / (max - min); _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { num = array[_i]; _results.push(this.lerp(lo, hi, scale * (num - min))); } return _results; }, normalize8: function(array) { return new Uint8ClampedArray(this.normalize(array, -.5, 255.5)); }, normalizeInt: function(array, lo, hi) { var i, _i, _len, _ref, _results; _ref = this.normalize(array, lo, hi); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; _results.push(Math.round(i)); } return _results; }, sortedIndex: function(array, item, f) { var high, low, mid, value; if (f == null) { f = function(o) { return o; }; } if (this.isString(f)) { f = this.propFcn(f); } value = f(item); low = 0; high = array.length; while (low < high) { mid = (low + high) >>> 1; if (f(array[mid]) < value) { low = mid + 1; } else { high = mid; } } return low; }, identity: function(o) { return o; }, propFcn: function(prop) { return function(o) { return o[prop]; }; }, indexOf: function(array, item, property) { var i; if (property != null) { i = this.sortedIndex(array, item, property === "" ? null : property); if (array[i] === item) { return i; } else { return -1; } } else { return array.indexOf(item); } }, radsToward: function(x1, y1, x2, y2) { return Math.atan2(y2 - y1, x2 - x1); }, inCone: function(heading, cone, radius, x1, y1, x2, y2) { var angle12; if (radius < this.distance(x1, y1, x2, y2)) { return false; } angle12 = this.radsToward(x1, y1, x2, y2); return cone / 2 >= Math.abs(this.subtractRads(heading, angle12)); }, distance: function(x1, y1, x2, y2) { var dx, dy; dx = x1 - x2; dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); }, sqDistance: function(x1, y1, x2, y2) { var dx, dy; dx = x1 - x2; dy = y1 - y2; return dx * dx + dy * dy; }, polarToXY: function(r, theta, x, y) { if (x == null) { x = 0; } if (y == null) { y = 0; } return [x + r * Math.cos(theta), y + r * Math.sin(theta)]; }, torusDistance: function(x1, y1, x2, y2, w, h) { return Math.sqrt(this.torusSqDistance(x1, y1, x2, y2, w, h)); }, torusSqDistance: function(x1, y1, x2, y2, w, h) { var dx, dxMin, dy, dyMin; dx = Math.abs(x2 - x1); dy = Math.abs(y2 - y1); dxMin = Math.min(dx, w - dx); dyMin = Math.min(dy, h - dy); return dxMin * dxMin + dyMin * dyMin; }, torusWraps: function(x1, y1, x2, y2, w, h) { var dx, dy; dx = Math.abs(x2 - x1); dy = Math.abs(y2 - y1); return dx > w - dx || dy > h - dy; }, torus4Pts: function(x1, y1, x2, y2, w, h) { var x2r, y2r; x2r = x2 < x1 ? x2 + w : x2 - w; y2r = y2 < y1 ? y2 + h : y2 - h; return [[x2, y2], [x2r, y2], [x2, y2r], [x2r, y2r]]; }, torusPt: function(x1, y1, x2, y2, w, h) { var x, x2r, y, y2r; x2r = x2 < x1 ? x2 + w : x2 - w; y2r = y2 < y1 ? y2 + h : y2 - h; x = Math.abs(x2r - x1) < Math.abs(x2 - x1) ? x2r : x2; y = Math.abs(y2r - y1) < Math.abs(y2 - y1) ? y2r : y2; return [x, y]; }, torusRadsToward: function(x1, y1, x2, y2, w, h) { var _ref; _ref = this.torusPt(x1, y1, x2, y2, w, h), x2 = _ref[0], y2 = _ref[1]; return this.radsToward(x1, y1, x2, y2); }, inTorusCone: function(heading, cone, radius, x1, y1, x2, y2, w, h) { var p, _i, _len, _ref; _ref = this.torus4Pts(x1, y1, x2, y2, w, h); for (_i = 0, _len = _ref.length; _i < _len; _i++) { p = _ref[_i]; if (this.inCone(heading, cone, radius, x1, y1, p[0], p[1])) { return true; } } return false; }, fileIndex: {}, importImage: function(name, f) { var img; if (f == null) { f = function() {}; } if ((img = this.fileIndex[name]) != null) { f(img); } else { this.fileIndex[name] = img = new Image(); img.isDone = false; img.crossOrigin = "Anonymous"; img.onload = function() { f(img); return img.isDone = true; }; img.src = name; } return img; }, xhrLoadFile: function(name, method, type, f) { var xhr; if (method == null) { method = "GET"; } if (type == null) { type = "text"; } if (f == null) { f = function() {}; } if ((xhr = this.fileIndex[name]) != null) { f(xhr.response); } else { this.fileIndex[name] = xhr = new XMLHttpRequest(); xhr.isDone = false; xhr.open(method, name); xhr.responseType = type; xhr.onload = function() { f(xhr.response); return xhr.isDone = true; }; xhr.send(); } return xhr; }, filesLoaded: function(files) { var array, v; if (files == null) { files = this.fileIndex; } array = (function() { var _i, _len, _ref, _results; _ref = this.ownValues(files); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { v = _ref[_i]; _results.push(v.isDone); } return _results; }).call(this); return array.reduce((function(a, b) { return a && b; }), true); }, waitOnFiles: function(f, files) { if (files == null) { files = this.fileIndex; } return this.waitOn(((function(_this) { return function() { return _this.filesLoaded(files); }; })(this)), f); }, waitOn: function(done, f) { if (done()) { return f(); } else { return setTimeout(((function(_this) { return function() { return _this.waitOn(done, f); }; })(this)), 1000); } }, cloneImage: function(img) { var i; (i = new Image()).src = img.src; return i; }, imageToData: function(img, f, arrayType) { if (f == null) { f = this.pixelByte(0); } if (arrayType == null) { arrayType = Uint8ClampedArray; } return this.imageRowsToData(img, img.height, f, arrayType); }, imageRowsToData: function(img, rowsPerSlice, f, arrayType) { var ctx, data, dataStart, i, idata, rows, rowsDone, _i, _ref; if (f == null) { f = this.pixelByte(0); } if (arrayType == null) { arrayType = Uint8ClampedArray; } rowsDone = 0; data = new arrayType(img.width * img.height); while (rowsDone < img.height) { rows = Math.min(img.height - rowsDone, rowsPerSlice); ctx = this.imageSliceToCtx(img, 0, rowsDone, img.width, rows); idata = this.ctxToImageData(ctx).data; dataStart = rowsDone * img.width; for (i = _i = 0, _ref = idata.length / 4; _i < _ref; i = _i += 1) { data[dataStart + i] = f(idata, 4 * i); } rowsDone += rows; } return data; }, pixelBytesToInt: function(a) { var ImageByteFmts; ImageByteFmts = [[2], [1, 2], [0, 1, 2], [3, 0, 1, 2]]; if (typeof a === "number") { a = ImageByteFmts[a - 1]; } return function(id, i) { var j, val, _i, _len; val = 0; for (_i = 0, _len = a.length; _i < _len; _i++) { j = a[_i]; val = val * 256 + id[i + j]; } return val; }; }, pixelByte: function(n) { return function(id, i) { return id[i + n]; }; }, createCanvas: function(width, height) { var can; can = document.createElement('canvas'); can.width = width; can.height = height; return can; }, createCtx: function(width, height, ctxType) { var can, _ref; if (ctxType == null) { ctxType = "2d"; } can = this.createCanvas(width, height); if (ctxType === "2d") { return can.getContext("2d"); } else { return (_ref = can.getContext("webgl")) != null ? _ref : can.getContext("experimental-webgl"); } }, createLayer: function(div, width, height, z, ctx) { var element; if (ctx == null) { ctx = "2d"; } if (ctx === "img") { element = ctx = new Image(); ctx.width = width; ctx.height = height; } else { element = (ctx = this.createCtx(width, height, ctx)).canvas; } this.insertLayer(div, element, width, height, z); return ctx; }, insertLayer: function(div, element, w, h, z) { element.setAttribute('style', "position:absolute;top:0;left:0;width:" + w + ";height:" + h + ";z-index:" + z); return div.appendChild(element); }, setCtxSmoothing: function(ctx, smoothing) { ctx.imageSmoothingEnabled = smoothing; ctx.mozImageSmoothingEnabled = smoothing; ctx.oImageSmoothingEnabled = smoothing; return ctx.webkitImageSmoothingEnabled = smoothing; }, setIdentity: function(ctx) { ctx.save(); return ctx.setTransform(1, 0, 0, 1, 0, 0); }, clearCtx: function(ctx) { if (ctx.save != null) { this.setIdentity(ctx); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); return ctx.restore(); } else { ctx.clearColor(0, 0, 0, 0); return ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT); } }, fillCtx: function(ctx, color) { if (ctx.fillStyle != null) { this.setIdentity(ctx); ctx.fillStyle = this.colorStr(color); ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); return ctx.restore(); } else { ctx.clearColor.apply(ctx, __slice.call(color).concat([1])); return ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT); } }, ctxDrawText: function(ctx, string, x, y, color, setIdentity) { if (color == null) { color = [0, 0, 0]; } if (setIdentity == null) { setIdentity = true; } if (setIdentity) { this.setIdentity(ctx); } ctx.fillStyle = this.colorStr(color); ctx.fillText(string, x, y); if (setIdentity) { return ctx.restore(); } }, ctxTextParams: function(ctx, font, align, baseline) { if (align == null) { align = "center"; } if (baseline == null) { baseline = "middle"; } ctx.font = font; ctx.textAlign = align; return ctx.textBaseline = baseline; }, elementTextParams: function(e, font, align, baseline) { if (align == null) { align = "center"; } if (baseline == null) { baseline = "middle"; } if (e.canvas != null) { e = e.canvas; } e.style.font = font; e.style.textAlign = align; return e.style.textBaseline = baseline; }, imageToCtx: function(img, w, h) { var ctx; if ((w != null) && (h != null)) { ctx = this.createCtx(w, h); ctx.drawImage(img, 0, 0, w, h); } else { ctx = this.createCtx(img.width, img.height); ctx.drawImage(img, 0, 0); } return ctx; }, imageSliceToCtx: function(img, sx, sy, sw, sh, ctx) { if (ctx != null) { ctx.canvas.width = sw; ctx.canvas.height = sh; } else { ctx = this.createCtx(sw, sh); } ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh); return ctx; }, imageToCtxDownStepped: function(img, tw, th) { var can, ctx, ctx1, h, ihalf, step, steps, w, _i; ctx1 = this.createCtx(tw, th); w = img.width; h = img.height; ihalf = function(n) { return Math.ceil(n / 2); }; steps = Math.ceil(this.log2((w / tw) > (h / th) ? w / tw : h / th)); console.log("steps", steps); if (steps <= 1) { ctx1.drawImage(img, 0, 0, tw, th); } else { console.log("img w/h", w, h, "->", ihalf(w), ihalf(h)); ctx = this.createCtx(w = ihalf(w), h = ihalf(h)); can = ctx.canvas; ctx.drawImage(img, 0, 0, w, h); for (step = _i = steps; steps <= 2 ? _i < 2 : _i > 2; step = steps <= 2 ? ++_i : --_i) { console.log("can w/h", w, h, "->", ihalf(w), ihalf(h)); ctx.drawImage(can, 0, 0, w, h, 0, 0, w = ihalf(w), h = ihalf(h)); } console.log("target w/h", w, h, "->", tw, th); ctx1.drawImage(can, 0, 0, w, h, 0, 0, tw, th); } return ctx1; }, ctxToDataUrl: function(ctx) { return ctx.canvas.toDataURL("image/png"); }, ctxToDataUrlImage: function(ctx, f) { var img; img = new Image(); if (f != null) { img.onload = function() { return f(img); }; } img.src = ctx.canvas.toDataURL("image/png"); return img; }, ctxToImageData: function(ctx) { return ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); }, drawCenteredImage: function(ctx, img, rad, x, y, dx, dy) { ctx.translate(x, y); ctx.rotate(rad); return ctx.drawImage(img, -dx / 2, -dy / 2); }, copyCtx: function(ctx0) { var ctx; ctx = this.createCtx(ctx0.canvas.width, ctx0.canvas.height); ctx.drawImage(ctx0.canvas, 0, 0); return ctx; }, resizeCtx: function(ctx, width, height, scale) { var copy; if (scale == null) { scale = false; } copy = this.copyCtx(ctx); ctx.canvas.width = width; ctx.canvas.height = height; return ctx.drawImage(copy.canvas, 0, 0); } }; Evented = (function() { function Evented() { this.events = {}; } Evented.prototype.emit = function() { var args, cb, name, _i, _len, _ref, _results; name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (this.events[name]) { _ref = this.events[name]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { cb = _ref[_i]; _results.push(cb.apply(null, args)); } return _results; } }; Evented.prototype.on = function(name, cb) { var _base; return ((_base = this.events)[name] != null ? _base[name] : _base[name] = []).push(cb); }; Evented.prototype.off = function(name, cb) { var l; if (this.events[name]) { if (cb) { return this.events[name] = (function() { var _i, _len, _ref, _results; _ref = this.events[name]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { l = _ref[_i]; if (l !== cb) { _results.push(l); } } return _results; }).call(this); } else { return delete this.events[name]; } } }; return Evented; })(); Color = { rgbString: function(r, g, b, a) { if (a == null) { a = 1; } if (a > 1) { throw new Error("alpha > 1"); } if (a === 1) { return "rgb(" + r + "," + g + "," + b + ")"; } else { return "rgba(" + r + "," + g + "," + b + "," + a + ")"; } }, rgbIntensity: function(r, g, b) { return 0.2126 * r + 0.7152 * g + 0.0722 * b; }, rgbToHex: function(r, g, b) { return "#" + (0x1000000 | (b | g << 8 | r << 16)).toString(16).slice(-6); }, typedArrayColor: function(r, g, b, a) { var pixel, rgba; if (a == null) { a = 255; } rgba = new Uint8ClampedArray([r, g, b, a]); pixel = new Uint32Array(rgba.buffer)[0]; return { pixel: pixel, rgba: rgba }; }, ctx1x1: u.createCtx(1, 1), stringToRGB: function(string) { var a, b, g, r, _ref; this.ctx1x1.fillStyle = string; this.ctx1x1.fillRect(0, 0, 1, 1); _ref = this.ctx1x1.getImageData(0, 0, 1, 1).data, r = _ref[0], g = _ref[1], b = _ref[2], a = _ref[3]; if ((r + g + b !== 0) || (string.match(/^black$/i)) || (string === "#000" || string === "#000000") || (string.match(/rgba{0,1}\(0,0,0/i)) || (string.match(/hsla{0,1}\(0,0%,0%/i))) { return [r, g, b]; } return null; }, rgbToHsv: function(r, g, b) { var d, h, max, min, s, v; r = r / 255; g = g / 255; b = b / 255; max = Math.max(r, g, b); min = Math.min(r, g, b); v = max; h = 0; d = max - min; s = max === 0 ? 0 : d / max; if (max !== min) { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; } } return [Math.round(255 * h / 6), Math.round(255 * s), Math.round(255 * v)]; }, hsvToRgb: function(h, s, v) { var b, f, g, i, p, q, r, t; h = h / 255; s = s / 255; v = v / 255; i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; }, randomColor: function() { var i, _i, _results; _results = []; for (i = _i = 0; _i <= 2; i = ++_i) { _results.push(u.randomInt(256)); } return _results; }, rgbDistance: function(r1, g1, b1, r2, g2, b2) { var db, dg, dr, rMean, _ref; rMean = Math.round((r1 + r2) / 2); _ref = [r1 - r2, g1 - g2, b1 - b2], dr = _ref[0], dg = _ref[1], db = _ref[2]; return Math.sqrt((((512 + rMean) * dr * dr) >> 8) + (4 * dg * dg) + (((767 - rMean) * db * db) >> 8)); }, rgbLerp: function(value, min, max, rgb1, rgb0) { var i, scale, _i, _results; if (rgb0 == null) { rgb0 = [0, 0, 0]; } scale = u.lerpScale(value, min, max); _results = []; for (i = _i = 0; _i <= 2; i = ++_i) { _results.push(Math.round(u.lerp(rgb0[i], rgb1[i], scale))); } return _results; }, options: function() { return { rgb: true, hsv: true, pixel: true, rgbString: true, hexString: true, intensity: true }; }, colorObject: function(r, g, b, a, opt) { var o, pixel, rgba, _ref, _ref1, _ref2; if (a == null) { a = 1; } if (opt == null) { opt = this.options(); } o = { r: r, g: g, b: b, a: a }; if (opt.rgb) { o.rgb = [r, g, b]; } if (opt.hsv) { o.hsv = this.rgbToHsv(r, g, b); _ref = o.hsv, o.h = _ref[0], o.s = _ref[1], o.v = _ref[2]; } if (opt.pixel) { o.a255 = Math.round(a * 255); _ref1 = this.typedArrayColor(r, g, b, o.a255), pixel = _ref1.pixel, rgba = _ref1.rgba; _ref2 = [pixel, rgba], o.pixel = _ref2[0], o.rgba = _ref2[1]; } if (opt.rgbString) { o.rgbString = this.rgbString(r, g, b, a); } if (opt.hexString) { o.hexString = this.rgbToHex(r, g, b); } if (opt.intensity) { o.intensity = this.rgbIntensity(r, g, b); } return o; }, ColorMap: ColorMap = (function(_super) { __extends(ColorMap, _super); function ColorMap(rgbArray, options, dupsOK) { var i, rgb, _i, _len; this.options = options != null ? options : Color.options(); this.dupsOK = dupsOK != null ? dupsOK : false; ColorMap.__super__.constructor.call(this, 0); this.rgbIndex = {}; this.nameIndex = {}; for (i = _i = 0, _len = rgbArray.length; _i < _len; i = ++_i) { rgb = rgbArray[i]; this.addColor.apply(this, rgb); } } ColorMap.prototype.addColor = function(r, g, b, a) { var color, rgbString; if (a == null) { a = 1; } rgbString = Color.rgbString(r, g, b, a); if (!this.dupsOK) { color = this.rgbIndex[rgbString]; if (color) { console.log("dup color", color); } } if (!color) { color = Color.colorObject(r, g, b, a, this.options); color.ix = this.length; color.map = this; this.rgbIndex[rgbString] = color; this.push(color); } return color; }; ColorMap.prototype.sort = function(f) { var color, i, _i, _len; ColorMap.__super__.sort.call(this, f); for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) { color = this[i]; color.ix = i; } return this; }; ColorMap.prototype.sortBy = function(key, ascenting) { var compare; if (ascenting == null) { ascenting = true; } compare = function(a, b) { if (ascenting) { return a[key] - b[key]; } else { return b[key] - a[key]; } }; return this.sort(compare); }; ColorMap.prototype.findRGB = function(r, g, b, a) { if (a == null) { a = 1; } return this.rgbIndex[Color.rgbString(r, g, b, a)]; }; ColorMap.prototype.findKey = function(key, value) { var color, i, _i, _len; for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) { color = this[i]; if (color[key] === value) { return color; } } return void 0; }; ColorMap.prototype.randomIndex = function() { return u.randomInt(this.length); }; ColorMap.prototype.randomColor = function() { return this[this.randomIndex()]; }; ColorMap.prototype.scaleColor = function(number, min, max, minColor, maxColor) { var index, scale; if (minColor == null) { minColor = 0; } if (maxColor == null) { maxColor = this.length - 1; } scale = u.lerpScale(number, min, max); if (minColor.ix != null) { minColor = minColor.ix; } if (maxColor.ix != null) { maxColor = maxColor.ix; } index = Math.round(u.lerp(minColor, maxColor, scale)); return this[index]; }; ColorMap.prototype.findClosest = function(r, g, b) { var color, d, i, ixMin, minDist, _i, _len; if ((color = this.findRGB(r, g, b))) { return color; } minDist = Infinity; ixMin = 0; for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) { color = this[i]; d = Color.rgbDistance.apply(Color, __slice.call(color.rgb).concat([r], [g], [b])); if (d < minDist) { minDist = d; ixMin = i; } } return this[ixMin]; }; return ColorMap; })(Array), intensityArray: function(size) { var i, _i, _results; if (size == null) { size = 256; } _results = []; for (i = _i = 0; 0 <= size ? _i < size : _i > size; i = 0 <= size ? ++_i : --_i) { _results.push(Math.round(i * 255 / (size - 1))); } return _results; }, grayColorArray: function(size) { var i, _i, _len, _ref, _results; if (size == null) { size = 256; } _ref = this.intensityArray(size); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; _results.push([i, i, i]); } return _results; }, grayColorMap: function(size, options) { var i; if (size == null) { size = 256; } return new ColorMap((function() { var _i, _len, _ref, _results; _ref = this.intensityArray(size); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; _results.push([i, i, i]); } return _results; }).call(this), options); }, threeArrays: function(A1, A2, A3) { var A, _ref; if (A2 == null) { A2 = A1; } if (A3 == null) { A3 = A1; } _ref = (function() { var _i, _len, _ref, _results; _ref = [A1, A2, A3]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { A = _ref[_i]; if (A === 1) { A = [255]; } if (typeof A === "number") { _results.push(u.aRamp(0, 255, A, true)); } else { _results.push(A); } } return _results; })(), A1 = _ref[0], A2 = _ref[1], A3 = _ref[2]; return [A1, A2, A3]; }, rgbColorArray: function(R, G, B) { var array, b, g, r, _i, _j, _k, _len, _len1, _len2, _ref; if (G == null) { G = R; } if (B == null) { B = R; } _ref = this.threeArrays(R, G, B), R = _ref[0], G = _ref[1], B = _ref[2]; array = []; for (_i = 0, _len = R.length; _i < _len; _i++) { r = R[_i]; for (_j = 0, _len1 = G.length; _j < _len1; _j++) { g = G[_j]; for (_k = 0, _len2 = B.length; _k < _len2; _k++) { b = B[_k]; array.push([r, g, b]); } } } return array; }, rgbColorMap: function(R, G, B, options) { if (G == null) { G = R; } if (B == null) { B = R; } return new ColorMap(this.rgbColorArray(R, G, B), options); }, hsvColorArray: function(H, S, V) { var a, array, h, s, v, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _results; if (S == null) { S = H; } if (V == null) { V = H; } _ref = this.threeArrays(H, S, V), H = _ref[0], S = _ref[1], V = _ref[2]; array = []; for (_i = 0, _len = V.length; _i < _len; _i++) { v = V[_i]; for (_j = 0, _len1 = S.length; _j < _len1; _j++) { s = S[_j]; for (_k = 0, _len2 = H.length; _k < _len2; _k++) { h = H[_k]; array.push([h, s, v]); } } } _results = []; for (_l = 0, _len3 = array.length; _l < _len3; _l++) { a = array[_l]; _results.push(this.hsvToRgb.apply(this, a)); } return _results; }, hsvColorMap: function(H, S, V, options) { if (S == null) { S = [255]; } if (V == null) { V = H; } return new ColorMap(this.hsvColorArray(H, S, V), options); }, gradientColorArray: function(nColors, stops, locs) { var ctx, grad, i, id, _i, _j, _ref, _ref1, _results; if (locs == null) { locs = (function() { var _i, _ref, _results; _results = []; for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(i / (stops.length - 1)); } return _results; })(); } ctx = u.createCtx(nColors, 1); grad = ctx.createLinearGradient(0, 0, nColors, 0); for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { grad.addColorStop(locs[i], this.rgbString.apply(this, stops[i])); } ctx.fillStyle = grad; ctx.fillRect(0, 0, nColors, 1); id = u.ctxToImageData(ctx).data; _results = []; for (i = _j = 0, _ref1 = id.length; _j < _ref1; i = _j += 4) { _results.push([id[i], id[i + 1], id[i + 2]]); } return _results; }, gradientColorMap: function(nColors, stops, locs, options) { return new ColorMap(this.gradientColorArray(nColors, stops, locs), options); }, nameColorMap: function(colorPairs, options) { var color, i, k, map, name, names, rgbs, v, _i, _len; rgbs = (function() { var _results; _results = []; for (k in colorPairs) { v = colorPairs[k]; _results.push(v); } return _results; })(); names = (function() { var _results; _results = []; for (k in colorPairs) { v = colorPairs[k]; _results.push(k); } return _results; })(); map = new ColorMap(rgbs, options, true); for (i = _i = 0, _len = map.length; _i < _len; i = ++_i) { color = map[i]; name = names[i]; map.nameIndex[name] = color; } return map; }, randomColorArray: function(nColors) { var i, rand255, _i, _results; rand255 = function() { return u.randomInt(256); }; _results = []; for (i = _i = 0; 0 <= nColors ? _i < nColors : _i > nColors; i = 0 <= nColors ? ++_i : --_i) { _results.push([rand255(), rand255(), rand255()]); } return _results; }, randomColorMap: function(nColors, options) { return new ColorMap(this.randomColorArray(nColors), options); } }; shapes = Shapes = (function() { var ccirc, cimg, circ, csq, fillSlot, poly, spriteSheets; poly = function(c, a) { var i, p, _i, _len; for (i = _i = 0, _len = a.length; _i < _len; i = ++_i) { p = a[i]; if (i === 0) { c.moveTo(p[0], p[1]); } else { c.lineTo(p[0], p[1]); } } return null; }; circ = function(c, x, y, s) { return c.arc(x, y, s / 2, 0, 2 * Math.PI); }; ccirc = function(c, x, y, s) { return c.arc(x, y, s / 2, 0, 2 * Math.PI, true); }; cimg = function(c, x, y, s, img) { c.scale(1, -1); c.drawImage(img, x - s / 2, y - s / 2, s, s); return c.scale(1, -1); }; csq = function(c, x, y, s) { return c.fillRect(x - s / 2, y - s / 2, s, s); }; fillSlot = function(slot, img) { slot.ctx.save(); slot.ctx.scale(1, -1); slot.ctx.drawImage(img, slot.x, -(slot.y + slot.spriteSize), slot.spriteSize, slot.spriteSize); return slot.ctx.restore(); }; spriteSheets = []; return { "default": { rotate: true, draw: function(c) { return poly(c, [[.5, 0], [-.5, -.5], [-.25, 0], [-.5, .5]]); } }, triangle: { rotate: true, draw: function(c) { return poly(c, [[.5, 0], [-.5, -.4], [-.5, .4]]); } }, arrow: { rotate: true, draw: function(c) { return poly(c, [[.5, 0], [0, .5], [0, .2], [-.5, .2], [-.5, -.2], [0, -.2], [0, -.5]]); } }, bug: { rotate: true, draw: function(c) { c.strokeStyle = c.fillStyle; c.lineWidth = .05; poly(c, [[.4, .225], [.2, 0], [.4, -.225]]); c.stroke(); c.beginPath(); circ(c, .12, 0, .26); circ(c, -.05, 0, .26); return circ(c, -.27, 0, .4); } }, pyramid: { rotate: false, draw: function(c) { return poly(c, [[0, .5], [-.433, -.25], [.433, -.25]]); } }, circle: { shortcut: function(c, x, y, s) { c.beginPath(); circ(c, x, y, s); c.closePath(); return c.fill(); }, rotate: false, draw: function(c) { return circ(c, 0, 0, 1); } }, square: { shortcut: function(c, x, y, s) { return csq(c, x, y, s); }, rotate: false, draw: function(c) { return csq(c, 0, 0, 1); } }, pentagon: { rotate: false, draw: function(c) { return poly(c, [[0, .45], [-.45, .1], [-.3, -.45], [.3, -.45], [.45, .1]]); } }, ring: { rotate: false, draw: function(c) { circ(c, 0, 0, 1); c.closePath(); return ccirc(c, 0, 0, .6); } }, filledRing: { rotate: false, draw: function(c) { var tempStyle; circ(c, 0, 0, 1); tempStyle = c.fillStyle; c.fillStyle = c.strokeStyle; c.fill(); c.fillStyle = tempStyle; c.beginPath(); return circ(c, 0, 0, .8); } }, person: { rotate: false, draw: function(c) { poly(c, [[.15, .2], [.3, 0], [.125, -.1], [.125, .05], [.1, -.15], [.25, -.5], [.05, -.5], [0, -.25], [-.05, -.5], [-.25, -.5], [-.1, -.15], [-.125, .05], [-.125, -.1], [-.3, 0], [-.15, .2]]); c.closePath(); return circ(c, 0, .35, .30); } }, names: function() { var name, val, _results; _results = []; for (name in this) { if (!__hasProp.call(this, name)) continue; val = this[name]; if ((val.rotate != null) && (val.draw != null)) { _results.push(name); } } return _results; }, add: function(name, rotate, draw, shortcut) { var s; s = this[name] = u.isFunction(draw) ? { rotate: rotate, draw: draw } : { rotate: rotate, img: draw, draw: function(c) { return cimg(c, .5, .5, 1, this.img); } }; if ((s.img != null) && !s.rotate) { s.shortcut = function(c, x, y, s) { return cimg(c, x, y, s, this.img); }; } if (shortcut != null) { return s.shortcut = shortcut; } }, poly: poly, circ: circ, ccirc: ccirc, cimg: cimg, csq: csq, spriteSheets: spriteSheets, draw: function(ctx, shape, x, y, size, rad, color, strokeColor) { if (shape.shortcut != null) { if (shape.img == null) { ctx.fillStyle = u.colorStr(color); } shape.shortcut(ctx, x, y, size); } else { ctx.save(); ctx.translate(x, y); if (size !== 1) { ctx.scale(size, size); } if (rad !== 0) { ctx.rotate(rad); } if (shape.img != null) { shape.draw(ctx); } else { ctx.fillStyle = u.colorStr(color); if (strokeColor) { ctx.strokeStyle = u.colorStr(strokeColor); ctx.lineWidth = 0.05; } ctx.save(); ctx.beginPath(); shape.draw(ctx); ctx.closePath(); ctx.restore(); ctx.fill(); if (strokeColor) { ctx.stroke(); } } ctx.restore(); } return shape; }, drawSprite: function(ctx, s, x, y, size, rad) { if (rad === 0) { ctx.drawImage(s.ctx.canvas, s.x, s.y, s.spriteSize, s.spriteSize, x - size / 2, y - size / 2, size, size); } else { ctx.save(); ctx.translate(x, y); ctx.rotate(rad); ctx.drawImage(s.ctx.canvas, s.x, s.y, s.spriteSize, s.spriteSize, -size / 2, -size / 2, size, size); ctx.restore(); } return s; }, shapeToSprite: function(name, color, size, strokeColor) { var ctx, foundSlot, img, index, shape, slot, slotSize, spriteSize, strokePadding, x, y; spriteSize = Math.ceil(size); strokePadding = 4; slotSize = spriteSize + strokePadding; shape = this[name]; index = shape.img != null ? name : "" + name + "-" + (u.colorStr(color)); ctx = spriteSheets[slotSize]; if (ctx == null) { spriteSheets[slotSize] = ctx = u.createCtx(slotSize * 10, slotSize); ctx.nextX = 0; ctx.nextY = 0; ctx.index = {}; } if ((foundSlot = ctx.index[index]) != null) { return foundSlot; } if (slotSize * ctx.nextX === ctx.canvas.width) { u.resizeCtx(ctx, ctx.canvas.width, ctx.canvas.height + slotSize); ctx.nextX = 0; ctx.nextY++; } x = slotSize * ctx.nextX + strokePadding / 2; y = slotSize * ctx.nextY + strokePadding / 2; slot = { ctx: ctx, x: x, y: y, size: size, spriteSize: spriteSize, name: name, color: color, strokeColor: strokeColor, index: index }; ctx.index[index] = slot; if ((img = shape.img) != null) { if (img.height !== 0) { fillSlot(slot, img); } else { img.onload = function() { return fillSlot(slot, img); }; } } else { ctx.save(); ctx.translate((ctx.nextX + 0.5) * slotSize, (ctx.nextY + 0.5) * slotSize); ctx.scale(spriteSize, spriteSize); ctx.fillStyle = u.colorStr(color); if (strokeColor) { ctx.strokeStyle = u.colorStr(strokeColor); ctx.lineWidth = 0.05; } ctx.save(); ctx.beginPath(); shape.draw(ctx); ctx.closePath(); ctx.restore(); ctx.fill(); if (strokeColor) { ctx.stroke(); } ctx.restore(); } ctx.nextX++; return slot; } }; })(); AgentSet = (function(_super) { __extends(AgentSet, _super); AgentSet.asSet = function(a, setType) { var _ref; if (setType == null) { setType = AgentSet; } a.__proto__ = (_ref = setType.prototype) != null ? _ref : setType.constructor.prototype; if (a[0] != null) { a.model = a[0].model; } return a; }; function AgentSet(model, agentClass, name, mainSet) { this.model = model; this.agentClass = agentClass; this.name = name; this.mainSet = mainSet; AgentSet.__super__.constructor.call(this, 0); if (this.mainSet == null) { this.breeds = []; } this.agentClass.prototype.breed = this; this.agentClass.prototype.model = this.model; this.ownVariables = []; if (this.mainSet == null) { this.ID = 0; } } AgentSet.prototype.create = function() {}; AgentSet.prototype.add = function(o) { if (this.mainSet != null) { this.mainSet.add(o); } else { o.id = this.ID++; } this.push(o); return o; }; AgentSet.prototype.remove = function(o) { if (this.mainSet != null) { u.removeItem(this.mainSet, o); } u.removeItem(this, o); return this; }; AgentSet.prototype.setDefault = function(name, value) { this.agentClass.prototype[name] = value; return this; }; AgentSet.prototype.own = function(vars) { var name, _i, _len, _ref; _ref = vars.split(" "); for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; this.setDefault(name, null); this.ownVariables.push(name); } return this; }; AgentSet.prototype.setBreed = function(a) { var k, proto, v; if (a.breed.mainSet != null) { u.removeItem(a.breed, a, "id"); } if (this.mainSet != null) { u.insertItem(this, a, "id"); } proto = a.__proto__ = this.agentClass.prototype; for (k in a) { if (!__hasProp.call(a, k)) continue; v = a[k]; if (proto[k] != null) { delete a[k]; } } return a; }; AgentSet.prototype.exclude = function(breeds) { var o; breeds = breeds.split(" "); return this.asSet((function() { var _i, _len, _ref, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; if (_ref = o.breed.name, __indexOf.call(breeds, _ref) < 0) { _results.push(o); } } return _results; }).call(this)); }; AgentSet.prototype.floodFill = function(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast) { var floodFunc, _results; if (asetLast == null) { asetLast = []; } floodFunc = this.floodFillOnce(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast); _results = []; while (floodFunc) { _results.push(floodFunc = floodFunc()); } return _results; }; AgentSet.prototype.floodFillOnce = function(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast) { var asetNext, n, p, stopEarly, _i, _j, _k, _len, _len1, _len2, _ref; if (asetLast == null) { asetLast = []; } for (_i = 0, _len = aset.length; _i < _len; _i++) { p = aset[_i]; fJoin(p, asetLast); } asetNext = []; for (_j = 0, _len1 = aset.length; _j < _len1; _j++) { p = aset[_j]; _ref = fNeighbors(p); for (_k = 0, _len2 = _ref.length; _k < _len2; _k++) { n = _ref[_k]; if (fCandidate(n, aset)) { if (asetNext.indexOf(n) < 0) { asetNext.push(n); } } } } stopEarly = fCallback && fCallback(aset, asetNext); if (stopEarly || asetNext.length === 0) { return null; } else { return (function(_this) { return function() { return _this.floodFillOnce(asetNext, fCandidate, fJoin, fCallback, fNeighbors, aset); }; })(this); } }; AgentSet.prototype.uniq = function() { return u.uniq(this); }; AgentSet.prototype.asSet = function(a, setType) { if (setType == null) { setType = this; } return AgentSet.asSet(a, setType); }; AgentSet.prototype.asOrderedSet = function(a) { return this.asSet(a).sortById(); }; AgentSet.prototype.toString = function() { var a; return "[" + ((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { a = this[_i]; _results.push(a.toString()); } return _results; }).call(this)).join(", ") + "]"; }; AgentSet.prototype.getProp = function(prop) { return u.aProp(this, prop); }; AgentSet.prototype.getPropWith = function(prop, value) { var o; return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; if (o[prop] === value) { _results.push(o); } } return _results; }).call(this)); }; AgentSet.prototype.setProp = function(prop, value) { var i, o, _i, _j, _len, _len1; if (u.isArray(value)) { for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) { o = this[i]; o[prop] = value[i]; } return this; } else { for (_j = 0, _len1 = this.length; _j < _len1; _j++) { o = this[_j]; o[prop] = value; } return this; } }; AgentSet.prototype.maxProp = function(prop) { return u.aMax(this.getProp(prop)); }; AgentSet.prototype.minProp = function(prop) { return u.aMin(this.getProp(prop)); }; AgentSet.prototype.histOfProp = function(prop, bin) { if (bin == null) { bin = 1; } return u.histOf(this, bin, prop); }; AgentSet.prototype.shuffle = function() { return u.shuffle(this); }; AgentSet.prototype.sortById = function() { return u.sortBy(this, "id"); }; AgentSet.prototype.clone = function() { return this.asSet(u.clone(this)); }; AgentSet.prototype.last = function() { return u.last(this); }; AgentSet.prototype.any = function() { return u.any(this); }; AgentSet.prototype.other = function(a) { var o; return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; if (o !== a) { _results.push(o); } } return _results; }).call(this)); }; AgentSet.prototype.oneOf = function() { return u.oneOf(this); }; AgentSet.prototype.nOf = function(n) { return this.asSet(u.nOf(this, n)); }; AgentSet.prototype.minOneOf = function(f, valueToo) { if (valueToo == null) { valueToo = false; } return u.minOneOf(this, f, valueToo); }; AgentSet.prototype.maxOneOf = function(f, valueToo) { if (valueToo == null) { valueToo = false; } return u.maxOneOf(this, f, valueToo); }; AgentSet.prototype.draw = function(ctx) { var o, _i, _len; u.clearCtx(ctx); for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; if (!o.hidden) { o.draw(ctx); } } return null; }; AgentSet.prototype.show = function() { var o, _i, _len; for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; o.hidden = false; } return this.draw(this.model.contexts[this.name]); }; AgentSet.prototype.hide = function() { var o, _i, _len; for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; o.hidden = true; } return this.draw(this.model.contexts[this.name]); }; AgentSet.prototype.inRadius = function(o, d, meToo) { var a, d2, h, w, x, y; if (meToo == null) { meToo = false; } d2 = d * d; x = o.x; y = o.y; if (this.model.patches.isTorus) { w = this.model.patches.numX; h = this.model.patches.numY; return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { a = this[_i]; if (u.torusSqDistance(x, y, a.x, a.y, w, h) <= d2 && (meToo || a !== o)) { _results.push(a); } } return _results; }).call(this)); } else { return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { a = this[_i]; if (u.sqDistance(x, y, a.x, a.y) <= d2 && (meToo || a !== o)) { _results.push(a); } } return _results; }).call(this)); } }; AgentSet.prototype.inCone = function(o, heading, cone, radius, meToo) { var a, h, rSet, w, x, y; if (meToo == null) { meToo = false; } rSet = this.inRadius(o, radius, meToo); x = o.x; y = o.y; if (this.model.patches.isTorus) { w = this.model.patches.numX; h = this.model.patches.numY; return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = rSet.length; _i < _len; _i++) { a = rSet[_i]; if ((a === o && meToo) || u.inTorusCone(heading, cone, radius, x, y, a.x, a.y, w, h)) { _results.push(a); } } return _results; })()); } else { return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = rSet.length; _i < _len; _i++) { a = rSet[_i]; if ((a === o && meToo) || u.inCone(heading, cone, radius, x, y, a.x, a.y)) { _results.push(a); } } return _results; })()); } }; AgentSet.prototype.on = function(name, cb) { var agent, _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { agent = this[_i]; _results.push(agent.on(name, cb)); } return _results; }; AgentSet.prototype.off = function(name, cb) { var agent, _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { agent = this[_i]; _results.push(agent.off(name, cb)); } return _results; }; AgentSet.prototype.ask = function(f) { var o, _i, _len; if (u.isString(f)) { eval("f=function(o){return " + f + ";}"); } for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; f(o); } return this; }; AgentSet.prototype["with"] = function(f) { var o; if (u.isString(f)) { eval("f=function(o){return " + f + ";}"); } return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { o = this[_i]; if (f(o)) { _results.push(o); } } return _results; }).call(this)); }; return AgentSet; })(Array); Patch = (function() { Patch.prototype.id = null; Patch.prototype.breed = null; Patch.prototype.x = null; Patch.prototype.y = null; Patch.prototype.n = null; Patch.prototype.n4 = null; Patch.prototype.color = [0, 0, 0]; Patch.prototype.hidden = false; Patch.prototype.label = null; Patch.prototype.labelColor = [0, 0, 0]; Patch.prototype.labelOffset = [0, 0]; Patch.prototype.pRect = null; function Patch(x, y) { this.x = x; this.y = y; u.mixin(this, new Evented()); } Patch.prototype.toString = function() { return "{id:" + this.id + " xy:" + [this.x, this.y] + " c:" + this.color + "}"; }; Patch.prototype.scaleColor = function(c, s) { if (!this.hasOwnProperty("color")) { this.color = u.clone(this.color); } return u.scaleColor(c, s, this.color); }; Patch.prototype.draw = function(ctx) { var x, y, _ref; ctx.fillStyle = u.colorStr(this.color); ctx.fillRect(this.x - .5, this.y - .5, 1, 1); if (this.label != null) { _ref = this.breed.patchXYtoPixelXY(this.x, this.y), x = _ref[0], y = _ref[1]; return u.ctxDrawText(ctx, this.label, x + this.labelOffset[0], y + this.labelOffset[1], this.labelColor); } }; Patch.prototype.agentsHere = function() { var a, _ref; return (_ref = this.agents) != null ? _ref : (function() { var _i, _len, _ref1, _results; _ref1 = this.model.agents; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { a = _ref1[_i]; if (a.p === this) { _results.push(a); } } return _results; }).call(this); }; Patch.prototype.isOnEdge = function() { return this.x === this.breed.minX || this.x === this.breed.maxX || this.y === this.breed.minY || this.y === this.breed.maxY; }; Patch.prototype.sprout = function(num, breed, init) { if (num == null) { num = 1; } if (breed == null) { breed = this.model.agents; } if (init == null) { init = function() {}; } return breed.create(num, (function(_this) { return function(a) { a.setXY(_this.x, _this.y); init(a); return a; }; })(this)); }; return Patch; })(); Patches = (function(_super) { __extends(Patches, _super); function Patches() { var k, v, _ref; Patches.__super__.constructor.apply(this, arguments); this.monochrome = false; _ref = this.model.world; for (k in _ref) { if (!__hasProp.call(_ref, k)) continue; v = _ref[k]; this[k] = v; } if (this.mainSet == null) { this.populate(); } } Patches.prototype.populate = function() { var x, y, _i, _j, _ref, _ref1, _ref2, _ref3; for (y = _i = _ref = this.maxY, _ref1 = this.minY; _i >= _ref1; y = _i += -1) { for (x = _j = _ref2 = this.minX, _ref3 = this.maxX; _j <= _ref3; x = _j += 1) { this.add(new this.agentClass(x, y)); } } if (this.hasNeighbors) { this.setNeighbors(); } if (!this.isHeadless) { return this.setPixels(); } }; Patches.prototype.cacheAgentsHere = function() { var p, _i, _len; for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; p.agents = []; } return null; }; Patches.prototype.usePixels = function(drawWithPixels) { var ctx; this.drawWithPixels = drawWithPixels != null ? drawWithPixels : true; ctx = this.model.contexts.patches; return u.setCtxSmoothing(ctx, !this.drawWithPixels); }; Patches.prototype.cacheRect = function(radius, meToo) { var p, _i, _len; if (meToo == null) { meToo = false; } for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; p.pRect = this.patchRect(p, radius, radius, meToo); p.pRect.radius = radius; } return radius; }; Patches.prototype.setNeighbors = function() { var n, p, _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; p.n = this.patchRect(p, 1, 1); _results.push(p.n4 = this.asSet((function() { var _j, _len1, _ref, _results1; _ref = p.n; _results1 = []; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { n = _ref[_j]; if (n.x === p.x || n.y === p.y) { _results1.push(n); } } return _results1; })())); } return _results; }; Patches.prototype.setPixels = function() { if (this.size === 1) { this.usePixels(); this.pixelsCtx = this.model.contexts.patches; } else { this.pixelsCtx = u.createCtx(this.numX, this.numY); } this.pixelsImageData = this.pixelsCtx.getImageData(0, 0, this.numX, this.numY); this.pixelsData = this.pixelsImageData.data; if (this.pixelsData instanceof Uint8Array) { this.pixelsData32 = new Uint32Array(this.pixelsData.buffer); return this.pixelsAreLittleEndian = u.isLittleEndian(); } }; Patches.prototype.draw = function(ctx) { if (this.monochrome) { return u.fillCtx(ctx, this.agentClass.prototype.color); } else if (this.drawWithPixels) { return this.drawScaledPixels(ctx); } else { return Patches.__super__.draw.call(this, ctx); } }; Patches.prototype.patchIndex = function(x, y) { return x - this.minX + this.numX * (this.maxY - y); }; Patches.prototype.patchXY = function(x, y) { return this[this.patchIndex(x, y)]; }; Patches.prototype.clamp = function(x, y) { return [u.clamp(x, this.minXcor, this.maxXcor), u.clamp(y, this.minYcor, this.maxYcor)]; }; Patches.prototype.wrap = function(x, y) { return [u.wrap(x, this.minXcor, this.maxXcor), u.wrap(y, this.minYcor, this.maxYcor)]; }; Patches.prototype.coord = function(x, y) { if (this.isTorus) { return this.wrap(x, y); } else { return this.clamp(x, y); } }; Patches.prototype.isOnWorld = function(x, y) { return this.isTorus || ((this.minXcor <= x && x <= this.maxXcor) && (this.minYcor <= y && y <= this.maxYcor)); }; Patches.prototype.patch = function(x, y) { var _ref; _ref = this.coord(x, y), x = _ref[0], y = _ref[1]; x = u.clamp(Math.round(x), this.minX, this.maxX); y = u.clamp(Math.round(y), this.minY, this.maxY); return this.patchXY(x, y); }; Patches.prototype.randomPt = function() { return [u.randomFloat2(this.minXcor, this.maxXcor), u.randomFloat2(this.minYcor, this.maxYcor)]; }; Patches.prototype.toBits = function(p) { return p * this.size; }; Patches.prototype.fromBits = function(b) { return b / this.size; }; Patches.prototype.patchRect = function(p, dx, dy, meToo) { var pnext, rect, x, y, _i, _j, _ref, _ref1, _ref2, _ref3; if (meToo == null) { meToo = false; } if ((p.pRect != null) && p.pRect.radius === dx) { return p.pRect; } rect = []; for (y = _i = _ref = p.y - dy, _ref1 = p.y + dy; _i <= _ref1; y = _i += 1) { for (x = _j = _ref2 = p.x - dx, _ref3 = p.x + dx; _j <= _ref3; x = _j += 1) { if (this.isTorus || ((this.minX <= x && x <= this.maxX) && (this.minY <= y && y <= this.maxY))) { if (this.isTorus) { if (x < this.minX) { x += this.numX; } if (x > this.maxX) { x -= this.numX; } if (y < this.minY) { y += this.numY; } if (y > this.maxY) { y -= this.numY; } } pnext = this.patchXY(x, y); if (pnext == null) { u.error("patchRect: x,y out of bounds, see console.log"); console.log("x " + x + " y " + y + " p.x " + p.x + " p.y " + p.y + " dx " + dx + " dy " + dy); } if (meToo || p !== pnext) { rect.push(pnext); } } } } return this.asSet(rect); }; Patches.prototype.importDrawing = function(imageSrc, f) { return u.importImage(imageSrc, (function(_this) { return function(img) { _this.installDrawing(img); if (f != null) { return f(); } }; })(this)); }; Patches.prototype.installDrawing = function(img, ctx) { if (ctx == null) { ctx = this.model.contexts.drawing; } u.setIdentity(ctx); ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height); return ctx.restore(); }; Patches.prototype.pixelByteIndex = function(p) { return 4 * p.id; }; Patches.prototype.pixelWordIndex = function(p) { return p.id; }; Patches.prototype.pixelXYtoPatchXY = function(x, y) { return [this.minXcor + (x / this.size), this.maxYcor - (y / this.size)]; }; Patches.prototype.patchXYtoPixelXY = function(x, y) { return [(x - this.minXcor) * this.size, (this.maxYcor - y) * this.size]; }; Patches.prototype.importColors = function(imageSrc, f, map) { return u.importImage(imageSrc, (function(_this) { return function(img) { _this.installColors(img, map); if (f != null) { return f(); } }; })(this)); }; Patches.prototype.installColors = function(img, map) { var data, i, p, _i, _len; u.setIdentity(this.pixelsCtx); this.pixelsCtx.drawImage(img, 0, 0, this.numX, this.numY); data = this.pixelsCtx.getImageData(0, 0, this.numX, this.numY).data; for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; i = this.pixelByteIndex(p); p.color = map != null ? map[i] : [data[i++], data[i++], data[i]]; } return this.pixelsCtx.restore(); }; Patches.prototype.drawScaledPixels = function(ctx) { if (this.size !== 1) { u.setIdentity(ctx); } if (this.pixelsData32 != null) { this.drawScaledPixels32(ctx); } else { this.drawScaledPixels8(ctx); } if (this.size !== 1) { return ctx.restore(); } }; Patches.prototype.drawScaledPixels8 = function(ctx) { var a, c, data, i, j, p, _i, _j, _len; data = this.pixelsData; for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; i = this.pixelByteIndex(p); c = p.color; a = c.length === 4 ? c[3] : 255; for (j = _j = 0; _j <= 2; j = ++_j) { data[i + j] = c[j]; } data[i + 3] = a; } this.pixelsCtx.putImageData(this.pixelsImageData, 0, 0); if (this.size === 1) { return; } return ctx.drawImage(this.pixelsCtx.canvas, 0, 0, ctx.canvas.width, ctx.canvas.height); }; Patches.prototype.drawScaledPixels32 = function(ctx) { var a, c, data, i, p, _i, _len; data = this.pixelsData32; for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; i = this.pixelWordIndex(p); c = p.color; a = c.length === 4 ? c[3] : 255; if (this.pixelsAreLittleEndian) { data[i] = (a << 24) | (c[2] << 16) | (c[1] << 8) | c[0]; } else { data[i] = (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | a; } } this.pixelsCtx.putImageData(this.pixelsImageData, 0, 0); if (this.size === 1) { return; } return ctx.drawImage(this.pixelsCtx.canvas, 0, 0, ctx.canvas.width, ctx.canvas.height); }; Patches.prototype.floodFillOnce = function(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast) { if (fNeighbors == null) { fNeighbors = (function(p) { return p.n; }); } if (asetLast == null) { asetLast = []; } return Patches.__super__.floodFillOnce.call(this, aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast); }; Patches.prototype.diffuse = function(v, rate, c) { var dv, dv8, n, nn, p, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref; if (this[0]._diffuseNext == null) { for (_i = 0, _len = this.length; _i < _len; _i++) { p = this[_i]; p._diffuseNext = 0; } } for (_j = 0, _len1 = this.length; _j < _len1; _j++) { p = this[_j]; dv = p[v] * rate; dv8 = dv / 8; nn = p.n.length; p._diffuseNext += p[v] - dv + (8 - nn) * dv8; _ref = p.n; for (_k = 0, _len2 = _ref.length; _k < _len2; _k++) { n = _ref[_k]; n._diffuseNext += dv8; } } for (_l = 0, _len3 = this.length; _l < _len3; _l++) { p = this[_l]; p[v] = p._diffuseNext; p._diffuseNext = 0; if (c) { p.scaleColor(c, p[v]); } } return null; }; return Patches; })(AgentSet); Agent = (function() { Agent.prototype.id = null; Agent.prototype.breed = null; Agent.prototype.x = 0; Agent.prototype.y = 0; Agent.prototype.p = null; Agent.prototype.size = 1; Agent.prototype.color = null; Agent.prototype.strokeColor = null; Agent.prototype.shape = "default"; Agent.prototype.hidden = false; Agent.prototype.label = null; Agent.prototype.labelColor = [0, 0, 0]; Agent.prototype.labelOffset = [0, 0]; Agent.prototype.penDown = false; Agent.prototype.penSize = 1; Agent.prototype.heading = null; Agent.prototype.sprite = null; Agent.prototype.cacheLinks = false; Agent.prototype.links = null; Agent.prototype.isDragging = false; function Agent() { u.mixin(this, new Evented()); this.x = this.y = 0; this.p = this.model.patches.patch(this.x, this.y); if (this.color == null) { this.color = u.randomColor(); } if (this.heading == null) { this.heading = u.randomFloat(Math.PI * 2); } if (this.p.agents != null) { this.p.agents.push(this); } if (this.cacheLinks) { this.links = []; } } Agent.prototype.scaleColor = function(c, s) { if (!this.hasOwnProperty("color")) { this.color = u.clone(this.color); } return u.scaleColor(c, s, this.color); }; Agent.prototype.toString = function() { var h; return "{id:" + this.id + " xy:" + (u.aToFixed([this.x, this.y])) + " c:" + this.color + " h: " + (h = this.heading.toFixed(2)) + "/" + (Math.round(u.radToDeg(h))) + "}"; }; Agent.prototype.setXY = function(x, y) { var drawing, p, x0, y0, _ref, _ref1; if (this.penDown) { _ref = [this.x, this.y], x0 = _ref[0], y0 = _ref[1]; } _ref1 = this.model.patches.coord(x, y), this.x = _ref1[0], this.y = _ref1[1]; p = this.p; this.p = this.model.patches.patch(this.x, this.y); if ((p.agents != null) && p !== this.p) { u.removeItem(p.agents, this); this.p.agents.push(this); } if (this.penDown) { drawing = this.model.drawing; drawing.strokeStyle = u.colorStr(this.color); drawing.lineWidth = this.model.patches.fromBits(this.penSize); drawing.beginPath(); drawing.moveTo(x0, y0); drawing.lineTo(x, y); return drawing.stroke(); } }; Agent.prototype.moveTo = function(a) { return this.setXY(a.x, a.y); }; Agent.prototype.forward = function(d) { return this.setXY(this.x + d * Math.cos(this.heading), this.y + d * Math.sin(this.heading)); }; Agent.prototype.rotate = function(rad) { return this.heading = u.wrap(this.heading + rad, 0, Math.PI * 2); }; Agent.prototype.right = function(rad) { return this.rotate(-rad); }; Agent.prototype.left = function(rad) { return this.rotate(rad); }; Agent.prototype.draw = function(ctx) { var rad, shape, x, y, _ref; shape = Shapes[this.shape]; rad = shape.rotate ? this.heading : 0; if ((this.sprite != null) || this.breed.useSprites) { if (this.sprite == null) { this.setSprite(); } Shapes.drawSprite(ctx, this.sprite, this.x, this.y, this.size, rad); } else { Shapes.draw(ctx, shape, this.x, this.y, this.size, rad, this.color, this.strokeColor); } if (this.label != null) { _ref = this.model.patches.patchXYtoPixelXY(this.x, this.y), x = _ref[0], y = _ref[1]; return u.ctxDrawText(ctx, this.label, x + this.labelOffset[0], y + this.labelOffset[1], this.labelColor); } }; Agent.prototype.setSprite = function(sprite) { var s; if ((s = sprite) != null) { this.sprite = s; this.color = s.color; this.strokeColor = s.strokeColor; this.shape = s.shape; return this.size = s.size; } else { if (this.color == null) { this.color = u.randomColor; } return this.sprite = Shapes.shapeToSprite(this.shape, this.color, this.model.patches.toBits(this.size), this.strokeColor); } }; Agent.prototype.stamp = function() { return this.draw(this.model.drawing); }; Agent.prototype.distanceXY = function(x, y) { if (this.model.patches.isTorus) { return u.torusDistance(this.x, this.y, x, y, this.model.patches.numX, this.model.patches.numY); } else { return u.distance(this.x, this.y, x, y); } }; Agent.prototype.distance = function(o) { return this.distanceXY(o.x, o.y); }; Agent.prototype.torusPtXY = function(x, y) { return u.torusPt(this.x, this.y, x, y, this.model.patches.numX, this.model.patches.numY); }; Agent.prototype.torusPt = function(o) { return this.torusPtXY(o.x, o.y); }; Agent.prototype.face = function(o) { return this.heading = this.towards(o); }; Agent.prototype.towardsXY = function(x, y) { var ps; if ((ps = this.model.patches).isTorus) { return u.torusRadsToward(this.x, this.y, x, y, ps.numX, ps.numY); } else { return u.radsToward(this.x, this.y, x, y); } }; Agent.prototype.towards = function(o) { return this.towardsXY(o.x, o.y); }; Agent.prototype.patchAtHeadingAndDistance = function(h, d) { var dx, dy, _ref; _ref = u.polarToXY(d, h + this.heading), dx = _ref[0], dy = _ref[1]; return this.patchAt(dx, dy); }; Agent.prototype.patchLeftAndAhead = function(dh, d) { return this.patchAtHeadingAndDistance(dh, d); }; Agent.prototype.patchRightAndAhead = function(dh, d) { return this.patchAtHeadingAndDistance(-dh, d); }; Agent.prototype.patchAhead = function(d) { return this.patchAtHeadingAndDistance(0, d); }; Agent.prototype.canMove = function(d) { return this.patchAhead(d) != null; }; Agent.prototype.patchAt = function(dx, dy) { var ps, x, y; x = this.x + dx; y = this.y + dy; if ((ps = this.model.patches).isOnWorld(x, y)) { return ps.patch(x, y); } else { return null; } }; Agent.prototype.die = function() { var l, _i, _ref; this.breed.remove(this); _ref = this.myLinks(); for (_i = _ref.length - 1; _i >= 0; _i += -1) { l = _ref[_i]; l.die(); } if (this.p.agents != null) { u.removeItem(this.p.agents, this); } return null; }; Agent.prototype.hatch = function(num, breed, init) { if (num == null) { num = 1; } if (breed == null) { breed = this.model.agents; } if (init == null) { init = function() {}; } return breed.create(num, (function(_this) { return function(a) { var k, v; a.setXY(_this.x, _this.y); for (k in _this) { if (!__hasProp.call(_this, k)) continue; v = _this[k]; if (k !== "id") { a[k] = v; } } init(a); return a; }; })(this)); }; Agent.prototype.inCone = function(aset, cone, radius, meToo) { if (meToo == null) { meToo = false; } return aset.inCone(this.p, this.heading, cone, radius, meToo); }; Agent.prototype.hitTest = function(x, y) { return this.distanceXY(x, y) < this.size * this.model.patches.size; }; Agent.prototype.otherEnd = function(l) { if (l.end1 === this) { return l.end2; } else { return l.end1; } }; Agent.prototype.myLinks = function() { var l, _ref; return (_ref = this.links) != null ? _ref : (function() { var _i, _len, _ref1, _results; _ref1 = this.model.links; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { l = _ref1[_i]; if ((l.end1 === this) || (l.end2 === this)) { _results.push(l); } } return _results; }).call(this); }; Agent.prototype.linkNeighbors = function() { var l, _i, _len, _ref, _results; _ref = this.myLinks(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { l = _ref[_i]; _results.push(this.otherEnd(l)); } return _results; }; Agent.prototype.myInLinks = function() { var l, _i, _len, _ref, _results; _ref = this.myLinks(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { l = _ref[_i]; if (l.end2 === this) { _results.push(l); } } return _results; }; Agent.prototype.inLinkNeighbors = function() { var l, _i, _len, _ref, _results; _ref = this.myLinks(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { l = _ref[_i]; if (l.end2 === this) { _results.push(l.end1); } } return _results; }; Agent.prototype.myOutLinks = function() { var l, _i, _len, _ref, _results; _ref = this.myLinks(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { l = _ref[_i]; if (l.end1 === this) { _results.push(l); } } return _results; }; Agent.prototype.outLinkNeighbors = function() { var l, _i, _len, _ref, _results; _ref = this.myLinks(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { l = _ref[_i]; if (l.end1 === this) { _results.push(l.end2); } } return _results; }; Agent.prototype.setDraggable = function() { this.on('dragstart', (function(_this) { return function(mouseEvent) { return _this.dragging = true; }; })(this)); this.on('dragend', (function(_this) { return function(mouseEvent) { return _this.dragging = false; }; })(this)); return this.on('drag', (function(_this) { return function(mouseEvent) { return _this.setXY(mouseEvent.patchX, mouseEvent.patchY); }; })(this)); }; return Agent; })(); Agents = (function(_super) { __extends(Agents, _super); function Agents() { Agents.__super__.constructor.apply(this, arguments); this.useSprites = false; } Agents.prototype.cacheLinks = function() { return this.agentClass.prototype.cacheLinks = true; }; Agents.prototype.setUseSprites = function(useSprites) { this.useSprites = useSprites != null ? useSprites : true; }; Agents.prototype["in"] = function(array) { var o; return this.asSet((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { o = array[_i]; if (o.breed === this) { _results.push(o); } } return _results; }).call(this)); }; Agents.prototype.create = function(num, init) { var i, _i, _results; if (init == null) { init = function() {}; } _results = []; for (i = _i = 1; _i <= num; i = _i += 1) { _results.push((function(o) { init(o); return o; })(this.add(new this.agentClass))); } return _results; }; Agents.prototype.clear = function() { while (this.any()) { this.last().die(); } return null; }; Agents.prototype.inPatches = function(patches) { var array, p, _i, _len; array = []; for (_i = 0, _len = patches.length; _i < _len; _i++) { p = patches[_i]; array.push.apply(array, p.agentsHere()); } if (this.mainSet != null) { return this["in"](array); } else { return this.asSet(array); } }; Agents.prototype.inRect = function(a, dx, dy, meToo) { var rect; if (meToo == null) { meToo = false; } rect = this.model.patches.patchRect(a.p, dx, dy, true); rect = this.inPatches(rect); if (!meToo) { u.removeItem(rect, a); } return rect; }; Agents.prototype.inCone = function(a, heading, cone, radius, meToo) { var as; if (meToo == null) { meToo = false; } as = this.inRect(a, radius, radius, true); return Agents.__super__.inCone.call(this, a, heading, cone, radius, meToo); }; Agents.prototype.inRadius = function(a, radius, meToo) { var as; if (meToo == null) { meToo = false; } as = this.inRect(a, radius, radius, true); return Agents.__super__.inRadius.call(this, a, radius, meToo); }; Agents.prototype.setDraggable = function() { var agent, _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { agent = this[_i]; _results.push(agent.setDraggable()); } return _results; }; return Agents; })(AgentSet); Link = (function() { Link.prototype.id = null; Link.prototype.breed = null; Link.prototype.end1 = null; Link.prototype.end2 = null; Link.prototype.color = [130, 130, 130]; Link.prototype.thickness = 2; Link.prototype.hidden = false; Link.prototype.label = null; Link.prototype.labelColor = [0, 0, 0]; Link.prototype.labelOffset = [0, 0]; Link.prototype.isDragging = false; function Link(end1, end2) { this.end1 = end1; this.end2 = end2; u.mixin(this, new Evented()); if (this.end1.links != null) { this.end1.links.push(this); this.end2.links.push(this); } } Link.prototype.draw = function(ctx) { var pt, x, x0, y, y0, _ref, _ref1; ctx.save(); ctx.strokeStyle = u.colorStr(this.color); ctx.lineWidth = this.model.patches.fromBits(this.thickness); ctx.beginPath(); if (!this.model.patches.isTorus) { ctx.moveTo(this.end1.x, this.end1.y); ctx.lineTo(this.end2.x, this.end2.y); } else { pt = this.end1.torusPt(this.end2); ctx.moveTo(this.end1.x, this.end1.y); ctx.lineTo.apply(ctx, pt); if (pt[0] !== this.end2.x || pt[1] !== this.end2.y) { pt = this.end2.torusPt(this.end1); ctx.moveTo(this.end2.x, this.end2.y); ctx.lineTo.apply(ctx, pt); } } ctx.closePath(); ctx.stroke(); ctx.restore(); if (this.label != null) { _ref = u.lerp2(this.end1.x, this.end1.y, this.end2.x, this.end2.y, .5), x0 = _ref[0], y0 = _ref[1]; _ref1 = this.model.patches.patchXYtoPixelXY(x0, y0), x = _ref1[0], y = _ref1[1]; return u.ctxDrawText(ctx, this.label, x + this.labelOffset[0], y + this.labelOffset[1], this.labelColor); } }; Link.prototype.die = function() { this.breed.remove(this); if (this.end1.links != null) { u.removeItem(this.end1.links, this); } if (this.end2.links != null) { u.removeItem(this.end2.links, this); } return null; }; Link.prototype.hitTest = function(x, y) { var a, distance; distance = u.aSum((function() { var _i, _len, _ref, _results; _ref = this.bothEnds(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { a = _ref[_i]; _results.push(a.distanceXY(x, y)); } return _results; }).call(this)); return distance - this.length() < 1 / this.model.patches.size; }; Link.prototype.bothEnds = function() { return [this.end1, this.end2]; }; Link.prototype.length = function() { return this.end1.distance(this.end2); }; Link.prototype.otherEnd = function(a) { if (this.end1 === a) { return this.end2; } else { return this.end1; } }; Link.prototype.setDraggable = function() { this.on('dragstart', (function(_this) { return function(mouseEvent) { return _this.dragging = true; }; })(this)); this.on('dragend', (function(_this) { return function(mouseEvent) { return _this.dragging = false; }; })(this)); return this.on('drag', (function(_this) { return function(mouseEvent) { _this.end1.setXY(_this.end1.p.x - mouseEvent.dx, _this.end1.p.y - mouseEvent.dy); return _this.end2.setXY(_this.end2.p.x - mouseEvent.dx, _this.end2.p.y - mouseEvent.dy); }; })(this)); }; return Link; })(); Links = (function(_super) { __extends(Links, _super); function Links() { Links.__super__.constructor.apply(this, arguments); } Links.prototype.create = function(from, to, init) { var a, _i, _len, _results; if (init == null) { init = function() {}; } if (to.length == null) { to = [to]; } _results = []; for (_i = 0, _len = to.length; _i < _len; _i++) { a = to[_i]; _results.push((function(o) { init(o); return o; })(this.add(new this.agentClass(from, a)))); } return _results; }; Links.prototype.clear = function() { while (this.any()) { this.last().die(); } return null; }; Links.prototype.allEnds = function() { var l, n, _i, _len; n = this.asSet([]); for (_i = 0, _len = this.length; _i < _len; _i++) { l = this[_i]; n.push(l.end1, l.end2); } return n; }; Links.prototype.nodes = function() { return this.allEnds().sortById().uniq(); }; Links.prototype.layoutCircle = function(list, radius, startAngle, direction) { var a, dTheta, i, _i, _len; if (startAngle == null) { startAngle = Math.PI / 2; } if (direction == null) { direction = -1; } dTheta = 2 * Math.PI / list.length; for (i = _i = 0, _len = list.length; _i < _len; i = ++_i) { a = list[i]; a.setXY(0, 0); a.heading = startAngle + direction * dTheta * i; a.forward(radius); } return null; }; Links.prototype.setDraggable = function() { var link, _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { link = this[_i]; _results.push(link.setDraggable()); } return _results; }; return Links; })(AgentSet); Model = (function() { Model.prototype.contextsInit = { patches: { z: 10, ctx: "2d" }, drawing: { z: 20, ctx: "2d" }, links: { z: 30, ctx: "2d" }, agents: { z: 40, ctx: "2d" }, spotlight: { z: 50, ctx: "2d" } }; function Model(divOrOpts, size, minX, maxX, minY, maxY, isTorus, hasNeighbors, isHeadless) { var ctx, div, k, v, _ref; if (size == null) { size = 13; } if (minX == null) { minX = -16; } if (maxX == null) { maxX = 16; } if (minY == null) { minY = -16; } if (maxY == null) { maxY = 16; } if (isTorus == null) { isTorus = false; } if (hasNeighbors == null) { hasNeighbors = true; } if (isHeadless == null) { isHeadless = false; } u.mixin(this, new Evented()); if (typeof divOrOpts === 'string') { div = divOrOpts; this.setWorldDeprecated(size, minX, maxX, minY, maxY, isTorus, hasNeighbors, isHeadless); } else { div = divOrOpts.div; isHeadless = divOrOpts.isHeadless = divOrOpts.isHeadless || (div == null); this.setWorld(divOrOpts); } this.contexts = {}; if (!isHeadless) { (this.div = document.getElementById(div)).setAttribute('style', "position:relative; width:" + this.world.pxWidth + "px; height:" + this.world.pxHeight + "px"); _ref = this.contextsInit; for (k in _ref) { if (!__hasProp.call(_ref, k)) continue; v = _ref[k]; this.contexts[k] = ctx = u.createLayer(this.div, this.world.pxWidth, this.world.pxHeight, v.z, v.ctx); if (ctx.canvas != null) { this.setCtxTransform(ctx); } if (ctx.canvas != null) { ctx.canvas.style.pointerEvents = 'none'; } u.elementTextParams(ctx, "10px sans-serif", "center", "middle"); } this.drawing = this.contexts.drawing; this.drawing.clear = (function(_this) { return function() { return u.clearCtx(_this.drawing); }; })(this); this.contexts.spotlight.globalCompositeOperation = "xor"; } this.anim = new Animator(this); this.refreshLinks = this.refreshAgents = this.refreshPatches = true; this.Patches = Patches; this.Patch = u.cloneClass(Patch); this.Agents = Agents; this.Agent = u.cloneClass(Agent); this.Links = Links; this.Link = u.cloneClass(Link); this.patches = new this.Patches(this, this.Patch, "patches"); this.agents = new this.Agents(this, this.Agent, "agents"); this.links = new this.Links(this, this.Link, "links"); this.debugging = false; this.modelReady = false; this.globalNames = null; this.globalNames = u.ownKeys(this); this.globalNames.set = false; this.startup(); u.waitOnFiles((function(_this) { return function() { _this.modelReady = true; _this.setup(); if (!_this.globalNames.set) { return _this.globals(); } }; })(this)); } Model.prototype.setWorld = function(opts) { var defaults, hasNeighbors, isHeadless, isTorus, k, maxX, maxXcor, maxY, maxYcor, minX, minXcor, minY, minYcor, numX, numY, pxHeight, pxWidth, size, v, w; w = defaults = { size: 13, minX: -16, maxX: 16, minY: -16, maxY: 16, isTorus: false, hasNeighbors: true, isHeadless: false }; for (k in opts) { if (!__hasProp.call(opts, k)) continue; v = opts[k]; w[k] = v; } size = w.size, minX = w.minX, maxX = w.maxX, minY = w.minY, maxY = w.maxY, isTorus = w.isTorus, hasNeighbors = w.hasNeighbors, isHeadless = w.isHeadless; numX = maxX - minX + 1; numY = maxY - minY + 1; pxWidth = numX * size; pxHeight = numY * size; minXcor = minX - .5; maxXcor = maxX + .5; minYcor = minY - .5; maxYcor = maxY + .5; return this.world = { size: size, minX: minX, maxX: maxX, minY: minY, maxY: maxY, minXcor: minXcor, maxXcor: maxXcor, minYcor: minYcor, maxYcor: maxYcor, numX: numX, numY: numY, pxWidth: pxWidth, pxHeight: pxHeight, isTorus: isTorus, hasNeighbors: hasNeighbors, isHeadless: isHeadless }; }; Model.prototype.setWorldDeprecated = function(size, minX, maxX, minY, maxY, isTorus, hasNeighbors, isHeadless) { var maxXcor, maxYcor, minXcor, minYcor, numX, numY, pxHeight, pxWidth; numX = maxX - minX + 1; numY = maxY - minY + 1; pxWidth = numX * size; pxHeight = numY * size; minXcor = minX - .5; maxXcor = maxX + .5; minYcor = minY - .5; maxYcor = maxY + .5; return this.world = { size: size, minX: minX, maxX: maxX, minY: minY, maxY: maxY, minXcor: minXcor, maxXcor: maxXcor, minYcor: minYcor, maxYcor: maxYcor, numX: numX, numY: numY, pxWidth: pxWidth, pxHeight: pxHeight, isTorus: isTorus, hasNeighbors: hasNeighbors, isHeadless: isHeadless }; }; Model.prototype.setCtxTransform = function(ctx) { ctx.canvas.width = this.world.pxWidth; ctx.canvas.height = this.world.pxHeight; ctx.save(); ctx.scale(this.world.size, -this.world.size); return ctx.translate(-this.world.minXcor, -this.world.maxYcor); }; Model.prototype.globals = function(globalNames) { if (globalNames != null) { this.globalNames = globalNames; return this.globalNames.set = true; } else { return this.globalNames = u.removeItems(u.ownKeys(this), this.globalNames); } }; Model.prototype.setFastPatches = function() { return this.patches.usePixels(); }; Model.prototype.setMonochromePatches = function() { return this.patches.monochrome = true; }; Model.prototype.setCacheAgentsHere = function() { return this.patches.cacheAgentsHere(); }; Model.prototype.setCacheMyLinks = function() { return this.agents.cacheLinks(); }; Model.prototype.setCachePatchRect = function(radius, meToo) { if (meToo == null) { meToo = false; } return this.patches.cacheRect(radius, meToo); }; Model.prototype.startup = function() {}; Model.prototype.setup = function() {}; Model.prototype.step = function() {}; Model.prototype.start = function() { u.waitOn(((function(_this) { return function() { return _this.modelReady; }; })(this)), ((function(_this) { return function() { return _this.anim.start(); }; })(this))); return this; }; Model.prototype.stop = function() { return this.anim.stop(); }; Model.prototype.once = function() { if (!this.anim.stopped) { this.stop(); } return this.anim.once(); }; Model.prototype.reset = function(restart) { var k, v, _ref; if (restart == null) { restart = false; } console.log("reset: anim"); this.anim.reset(); console.log("reset: contexts"); _ref = this.contexts; for (k in _ref) { v = _ref[k]; if (v.canvas != null) { v.restore(); this.setCtxTransform(v); } } console.log("reset: patches"); this.patches = new this.Patches(this, this.Patch, "patches"); console.log("reset: agents"); this.agents = new this.Agents(this, this.Agent, "agents"); console.log("reset: links"); this.links = new this.Links(this, this.Link, "links"); u.s.spriteSheets.length = 0; console.log("reset: setup"); this.setup(); if (this.debugging) { this.setRootVars(); } if (restart) { return this.start(); } }; Model.prototype.draw = function(force) { if (force == null) { force = this.anim.stopped; } if (force || this.refreshPatches || this.anim.draws === 1) { this.patches.draw(this.contexts.patches); } if (force || this.refreshLinks || this.anim.draws === 1) { this.links.draw(this.contexts.links); } if (force || this.refreshAgents || this.anim.draws === 1) { this.agents.draw(this.contexts.agents); } if (this.spotlightAgent != null) { this.drawSpotlight(this.spotlightAgent, this.contexts.spotlight); } return this.emit('draw'); }; Model.prototype._step = function() { this.step(); return this.emit('step'); }; Model.prototype.setSpotlight = function(spotlightAgent) { this.spotlightAgent = spotlightAgent; if (this.spotlightAgent == null) { return u.clearCtx(this.contexts.spotlight); } }; Model.prototype.drawSpotlight = function(agent, ctx) { u.clearCtx(ctx); u.fillCtx(ctx, [0, 0, 0, 0.6]); ctx.beginPath(); ctx.arc(agent.x, agent.y, 3, 0, 2 * Math.PI, false); return ctx.fill(); }; Model.prototype.createBreeds = function(s, agentClass, breedSet) { var b, breed, breeds, c, cname, _i, _len, _ref; breeds = []; breeds.classes = {}; breeds.sets = {}; _ref = s.split(" "); for (_i = 0, _len = _ref.length; _i < _len; _i++) { b = _ref[_i]; cname = b.charAt(0).toUpperCase() + b.substr(1); c = u.cloneClass(agentClass, cname); breed = this[b] = new breedSet(this, c, b, agentClass.prototype.breed); breeds.push(breed); breeds.sets[b] = breed; breeds.classes["" + b + "Class"] = c; } return breeds; }; Model.prototype.patchBreeds = function(s) { return this.patches.breeds = this.createBreeds(s, this.Patch, this.Patches); }; Model.prototype.agentBreeds = function(s) { return this.agents.breeds = this.createBreeds(s, this.Agent, this.Agents); }; Model.prototype.linkBreeds = function(s) { return this.links.breeds = this.createBreeds(s, this.Link, this.Links); }; Model.prototype.asSet = function(a, setType) { if (setType == null) { setType = AgentSet; } return AgentSet.asSet(a, setType); }; Model.prototype.debug = function(debugging) { this.debugging = debugging != null ? debugging : true; u.waitOn(((function(_this) { return function() { return _this.modelReady; }; })(this)), ((function(_this) { return function() { return _this.setRootVars(); }; })(this))); return this; }; Model.prototype.setRootVars = function() { window.psc = this.Patches; window.pc = this.Patch; window.ps = this.patches; window.p0 = this.patches[0]; window.asc = this.Agents; window.ac = this.Agent; window.as = this.agents; window.a0 = this.agents[0]; window.lsc = this.Links; window.lc = this.Link; window.ls = this.links; window.l0 = this.links[0]; window.dr = this.drawing; window.u = Util; window.cx = this.contexts; window.an = this.anim; window.gl = this.globals(); window.dv = this.div; return window.app = this; }; return Model; })(); this.ABM = { util: util, shapes: shapes, Util: Util, Color: Color, Shapes: Shapes, AgentSet: AgentSet, Patch: Patch, Patches: Patches, Agent: Agent, Agents: Agents, Link: Link, Links: Links, Animator: Animator, Evented: Evented, Model: Model }; Animator = (function() { function Animator(model, rate, multiStep) { this.model = model; this.rate = rate != null ? rate : 30; this.multiStep = multiStep != null ? multiStep : model.world.isHeadless; this.animateDraws = __bind(this.animateDraws, this); this.animateSteps = __bind(this.animateSteps, this); this.isHeadless = model.world.isHeadless; this.reset(); } Animator.prototype.setRate = function(rate, multiStep) { this.rate = rate; this.multiStep = multiStep != null ? multiStep : this.isHeadless; return this.resetTimes(); }; Animator.prototype.start = function() { if (!this.stopped) { return; } this.resetTimes(); this.stopped = false; return this.animate(); }; Animator.prototype.stop = function() { this.stopped = true; if (this.animHandle != null) { cancelAnimationFrame(this.animHandle); } if (this.timeoutHandle != null) { clearTimeout(this.timeoutHandle); } if (this.intervalHandle != null) { clearInterval(this.intervalHandle); } return this.animHandle = this.timerHandle = this.intervalHandle = null; }; Animator.prototype.resetTimes = function() { this.startMS = this.now(); this.startTick = this.ticks; return this.startDraw = this.draws; }; Animator.prototype.reset = function() { this.stop(); return this.ticks = this.draws = 0; }; Animator.prototype.step = function() { this.ticks++; return this.model._step(); }; Animator.prototype.draw = function() { this.draws++; return this.model.draw(); }; Animator.prototype.once = function() { this.step(); return this.draw(); }; Animator.prototype.now = function() { return (typeof performance !== "undefined" && performance !== null ? performance : Date).now(); }; Animator.prototype.ms = function() { return this.now() - this.startMS; }; Animator.prototype.ticksPerSec = function() { var elapsed; if ((elapsed = this.ticks - this.startTick) === 0) { return 0; } else { return Math.round(elapsed * 1000 / this.ms()); } }; Animator.prototype.drawsPerSec = function() { var elapsed; if ((elapsed = this.draws - this.startDraw) === 0) { return 0; } else { return Math.round(elapsed * 1000 / this.ms()); } }; Animator.prototype.toString = function() { return "ticks: " + this.ticks + ", draws: " + this.draws + ", rate: " + this.rate + " tps/dps: " + (this.ticksPerSec()) + "/" + (this.drawsPerSec()); }; Animator.prototype.animateSteps = function() { this.step(); if (!this.stopped) { return this.timeoutHandle = setTimeout(this.animateSteps, 10); } }; Animator.prototype.animateDraws = function() { if (this.isHeadless) { if (this.ticksPerSec() < this.rate) { this.step(); } } else if (this.drawsPerSec() < this.rate) { if (!this.multiStep) { this.step(); } this.draw(); } if (!this.stopped) { return this.animHandle = requestAnimationFrame(this.animateDraws); } }; Animator.prototype.animate = function() { if (this.multiStep) { this.animateSteps(); } if (!(this.isHeadless && this.multiStep)) { return this.animateDraws(); } }; return Animator; })(); }).call(this);
Caroisawesome/Grill-Editor
lib/agentscript.js
JavaScript
gpl-3.0
121,427
/* * Copyright (C) 2021 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * sklintyg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*globals wcTestTools, JSON, logger*/ 'use strict'; var testdataHelper = wcTestTools.helpers.testdata; function addDays(date, days) { date.setDate(date.getDate() + days); return date; } module.exports.SendMessageToCare = function(user, person, intyg, message, testString, amneCode) { var messageID = testdataHelper.generateTestGuid(); var skickatTidpunkt = new Date(); if (!intyg.messages) { intyg.messages = []; } var svarPa = ''; var sistaDatumForSvar = '<urn1:sistaDatumForSvar>' + testdataHelper.dateFormat(addDays(skickatTidpunkt, 5)) + '</urn1:sistaDatumForSvar>'; if (amneCode) { intyg.messages.unshift({ id: messageID, typ: 'Fråga', amne: amneCode, testString: testString }); } else { // Om ämne inte skickas med till funktionen så behandlar vi det som // ett svarsmeddelande och kopierar ämne från tidigare amneCode = intyg.messages[0].amne; svarPa = '<urn1:svarPa>' + '<urn3:meddelande-id>' + intyg.messages[0].id + '</urn3:meddelande-id>' + '</urn1:svarPa>'; sistaDatumForSvar = ''; intyg.messages.unshift({ id: messageID, typ: 'Svar', amne: amneCode, testString: testString }); } logger.silly('this.intyg.messages: ' + JSON.stringify(intyg.messages)); var kompletteringar = ''; var paminnelseMeddelandeId = ''; if (intyg.messages[0].id && amneCode === 'PAMINN') { paminnelseMeddelandeId = '<urn1:paminnelseMeddelande-id>' + intyg.messages[1].id + '</urn1:paminnelseMeddelande-id>'; } else if (amneCode === 'KOMPLT') { kompletteringar = []; for (var k = 1; k <= 26; k++) { if (k === 24) { continue; // Frage-id 24 finns inte } kompletteringar.push( '<urn1:komplettering>' + '<urn1:frage-id>' + k + '</urn1:frage-id>' + '<urn1:text>Komplettering #' + k + '</urn1:text>' + '</urn1:komplettering>' ); } kompletteringar = kompletteringar.join('\n'); } return '<urn1:SendMessageToCare' + ' xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"' + ' xmlns:urn="urn:riv:itintegration:registry:1"' + ' xmlns:urn1="urn:riv:clinicalprocess:healthcond:certificate:SendMessageToCareResponder:2"' + ' xmlns:urn2="urn:riv:clinicalprocess:healthcond:certificate:types:3"' + ' xmlns:urn3="urn:riv:clinicalprocess:healthcond:certificate:3"' + '>' + ' <urn1:meddelande-id>' + messageID + '</urn1:meddelande-id>' + ' <urn1:skickatTidpunkt>' + skickatTidpunkt.toISOString().slice(0, -5) + '</urn1:skickatTidpunkt>' + ' <urn1:intygs-id>' + ' <urn2:root>' + user.enhetId + '</urn2:root>' + ' <urn2:extension>' + intyg.id + '</urn2:extension>' + ' </urn1:intygs-id>' + ' <urn1:patientPerson-id>' + ' <urn2:root>1.2.752.129.2.1.3.1</urn2:root>' + ' <urn2:extension>' + person.id.replace('-', '') + '</urn2:extension>' + ' </urn1:patientPerson-id>' + ' <urn1:logiskAdressMottagare>' + 'nmtWebcert' + process.env.environmentName + '</urn1:logiskAdressMottagare>' + ' <urn1:amne>' + ' <urn2:code>' + amneCode + '</urn2:code>' + ' <urn2:codeSystem>ffa59d8f-8d7e-46ae-ac9e-31804e8e8499</urn2:codeSystem>' + ' </urn1:amne>' + ' <urn1:meddelande>' + message + ' ' + testString + '</urn1:meddelande>' + paminnelseMeddelandeId + svarPa + ' <urn1:skickatAv>' + ' <urn1:part>' + ' <urn2:code>FKASSA</urn2:code>' + ' <urn2:codeSystem>769bb12b-bd9f-4203-a5cd-fd14f2eb3b80</urn2:codeSystem>' + ' </urn1:part>' + ' </urn1:skickatAv>' + kompletteringar + sistaDatumForSvar + '</urn1:SendMessageToCare>'; };
sklintyg/webcert
test/acceptance/features/steps/soap/SendMessageToCare.js
JavaScript
gpl-3.0
4,560
'use strict'; // Modules const _ = require('lodash'); const GitHubApi = require('github'); const Promise = require('./promise'); const semver = require('semver'); module.exports = class UpdateManager { /* * Constructor */ constructor() { this.githubApi = new GitHubApi({Promise: Promise}); }; // noinspection JSMethodCanBeStatic /** * Compares two versions and determines if an update is available or not * * @since 3.0.0 * @alias lando.updates.updateAvailable * @param {String} version1 The current version. * @param {String} version2 The potential update version * @return {Boolean} Whether an update is avaiable. * @example * // Does our current version need to be updated? * const updateAvailable = lando.updates.updateAvailable('1.0.0', '1.0.1'); */ updateAvailable(version1, version2) { return semver.lt(version1, version2); }; // noinspection JSMethodCanBeStatic /** * Determines whether we need to fetch updatest or not * * @since 3.0.0 * @alias lando.updates.fetch * @param {Object} data Cached update data * @return {Boolean} Whether we need to ping GitHub for new data or not */ fetch(data) { // Return true immediately if update is undefined if (!data) return true; // Else return based on the expiration return !(data.expires >= Math.floor(Date.now())); }; /** * Get latest version info from github * * @since 3.0.0 * @alias lando.updates.refresh * @param {String} version Lando version to use as a fallback * @param {Boolean} edge Whether to check for edge releases or not * @return {Object} Update data */ refresh(version, edge = false) { // GitHub repo config const landoRepoConfig = { owner: 'lando', repo: 'lando', page: 1, per_page: 25, }; // Helper to parse data const parseData = (latest, version) => ({ version: _.trimStart(_.get(latest, 'tag_name', version), 'v'), url: _.get(latest, 'html_url', ''), expires: Math.floor(Date.now()) + 86400000, }); // This i promise you return this.githubApi.repos.getReleases(landoRepoConfig) // Extract and return the metadata .then(data => { // Get the latest non-draft/non-prerelease version const latest = _.find(_.get(data, 'data', []), r => (r.draft === false && r.prerelease === edge)); // Return the update data return parseData(latest, version); }) // Don't let an error here kill things .catch(() => parseData(null, version)); }; };
kalabox/lando
lib/updates.js
JavaScript
gpl-3.0
2,560
Creep.prototype.report = function(){ this.say(this.test_carryPercent().toFixed(1) + '%') } Creep.prototype.test_carryPercent = function(){ return (100*(_.sum(this.carry)/this.carryCapacity)) } Creep.prototype.test_energyPercent = function(){ return (100*(this.carry.energy/this.carryCapacity)) } /** Creep moves toward <structure> * When in range, transfers <amount> of <resource> to <structure> * @param {structure} creep - structure to deliver to * @param {resource} resource - resource to deliver. Defaults to RESOURCE_ENERGY * @param {int} amount - amount to deliver. Defaults to all. */ Creep.prototype.deliver = function(structure, resource, amount){ } Creep.prototype.findNearestPath = function(){ } Creep.prototype.idle = function(){ }
dsball/Screeps
EXTEND_Creep.js
JavaScript
gpl-3.0
788
/* jslint node: true */ 'use strict'; var express = require('express'), sections = require('./sections'), http = require('http'), expressLess = require('express-less'), path = require('path'); /** * Create server */ var app = express(); /** * Configuration */ // all environments app.set('port', process.env.PORT || 4000); app.set('views', __dirname + '/sections'); app.set('view engine', 'jade'); app.use(express.compress()); app.use(express.methodOverride()); app.use(express.bodyParser()); app.use('/css', expressLess(__dirname + '/sections/_default/less')); app.use(express.static(path.join(__dirname, 'public'))); app.use('/vendor', express.static(__dirname + '/bower_components')); app.use(app.router); /** * Routes */ /* * Start Server */ var server = http.createServer( app ), io = require('socket.io')( server ), params = { server: app, io: io }; // Add the routes from the sections sections( params ); // serve index and view partials app.get('/', function (req, res) { res.render('_default/index'); }); app.get(/\/html\/([\w\/]+)\.html/, function (req, res) { var name = req.params[0]; res.render(name); }); server.listen(app.get('port'), function () { console.log('Express app listening on port ' + app.get('port')); });
RenderTeam/focus
index.js
JavaScript
gpl-3.0
1,333
/* Node-OpenDroneMap Node.js App and REST API to access OpenDroneMap. Copyright (C) 2016 Node-OpenDroneMap Contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; const config = require('../config'); const async = require('async'); const assert = require('assert'); const logger = require('./logger'); const fs = require('fs'); const glob = require("glob"); const path = require('path'); const rmdir = require('rimraf'); const odmRunner = require('./odmRunner'); const processRunner = require('./processRunner'); const archiver = require('archiver'); const Directories = require('./Directories'); const kill = require('tree-kill'); const S3 = require('./S3'); const request = require('request'); const utils = require('./utils'); const statusCodes = require('./statusCodes'); module.exports = class Task{ constructor(uuid, name, options = [], webhook = null, skipPostProcessing = false, outputs = [], done = () => {}){ assert(uuid !== undefined, "uuid must be set"); assert(done !== undefined, "ready must be set"); this.uuid = uuid; this.name = name !== "" ? name : "Task of " + (new Date()).toISOString(); this.dateCreated = new Date().getTime(); this.processingTime = -1; this.setStatus(statusCodes.QUEUED); this.options = options; this.gcpFiles = []; this.output = []; this.runningProcesses = []; this.webhook = webhook; this.skipPostProcessing = skipPostProcessing; this.outputs = utils.parseUnsafePathsList(outputs); async.series([ // Read images info cb => { fs.readdir(this.getImagesFolderPath(), (err, files) => { if (err) cb(err); else{ this.images = files; logger.debug(`Found ${this.images.length} images for ${this.uuid}`); cb(null); } }); }, // Find GCP (if any) cb => { fs.readdir(this.getGcpFolderPath(), (err, files) => { if (err) cb(err); else{ files.forEach(file => { if (/\.txt$/gi.test(file)){ this.gcpFiles.push(file); } }); logger.debug(`Found ${this.gcpFiles.length} GCP files (${this.gcpFiles.join(" ")}) for ${this.uuid}`); cb(null); } }); } ], err => { done(err, this); }); } static CreateFromSerialized(taskJson, done){ new Task(taskJson.uuid, taskJson.name, taskJson.options, taskJson.webhook, taskJson.skipPostProcessing, taskJson.outputs, (err, task) => { if (err) done(err); else{ // Override default values with those // provided in the taskJson for (let k in taskJson){ task[k] = taskJson[k]; } // Tasks that were running should be put back to QUEUED state if (task.status.code === statusCodes.RUNNING){ task.status.code = statusCodes.QUEUED; } done(null, task); } }); } // Get path where images are stored for this task // (relative to nodejs process CWD) getImagesFolderPath(){ return path.join(this.getProjectFolderPath(), "images"); } // Get path where GCP file(s) are stored // (relative to nodejs process CWD) getGcpFolderPath(){ return path.join(this.getProjectFolderPath(), "gcp"); } // Get path of project (where all images and assets folder are contained) // (relative to nodejs process CWD) getProjectFolderPath(){ return path.join(Directories.data, this.uuid); } // Get the path of the archive where all assets // outputted by this task are stored. getAssetsArchivePath(filename){ if (filename == 'all.zip'){ // OK, do nothing }else if (filename == 'orthophoto.tif'){ if (config.test){ if (config.testSkipOrthophotos) return false; else filename = path.join('..', '..', 'processing_results', 'odm_orthophoto', `odm_${filename}`); }else{ filename = path.join('odm_orthophoto', `odm_${filename}`); } }else{ return false; // Invalid } return path.join(this.getProjectFolderPath(), filename); } // Deletes files and folders related to this task cleanup(cb){ rmdir(this.getProjectFolderPath(), cb); } setStatus(code, extra){ this.status = { code: code }; for (let k in extra){ this.status[k] = extra[k]; } } updateProcessingTime(resetTime){ this.processingTime = resetTime ? -1 : new Date().getTime() - this.dateCreated; } startTrackingProcessingTime(){ this.updateProcessingTime(); if (!this._updateProcessingTimeInterval){ this._updateProcessingTimeInterval = setInterval(() => { this.updateProcessingTime(); }, 1000); } } stopTrackingProcessingTime(resetTime){ this.updateProcessingTime(resetTime); if (this._updateProcessingTimeInterval){ clearInterval(this._updateProcessingTimeInterval); this._updateProcessingTimeInterval = null; } } getStatus(){ return this.status.code; } isCanceled(){ return this.status.code === statusCodes.CANCELED; } // Cancels the current task (unless it's already canceled) cancel(cb){ if (this.status.code !== statusCodes.CANCELED){ let wasRunning = this.status.code === statusCodes.RUNNING; this.setStatus(statusCodes.CANCELED); if (wasRunning){ this.runningProcesses.forEach(proc => { // TODO: this does NOT guarantee that // the process will immediately terminate. // For eaxmple in the case of the ODM process, the process will continue running for a while // This might need to be fixed on ODM's end. // During testing, proc is undefined if (proc) kill(proc.pid); }); this.runningProcesses = []; } this.stopTrackingProcessingTime(true); cb(null); }else{ cb(new Error("Task already cancelled")); } } // Starts processing the task with OpenDroneMap // This will spawn a new process. start(done){ const finished = err => { this.stopTrackingProcessingTime(); done(err); }; const postProcess = () => { const createZipArchive = (outputFilename, files) => { return (done) => { this.output.push(`Compressing ${outputFilename}\n`); let output = fs.createWriteStream(this.getAssetsArchivePath(outputFilename)); let archive = archiver.create('zip', { zlib: { level: 1 } // Sets the compression level (1 = best speed since most assets are already compressed) }); archive.on('finish', () => { // TODO: is this being fired twice? done(); }); archive.on('error', err => { logger.error(`Could not archive .zip file: ${err.message}`); done(err); }); archive.pipe(output); let globs = []; const sourcePath = !config.test ? this.getProjectFolderPath() : path.join("tests", "processing_results"); // Process files and directories first files.forEach(file => { let filePath = path.join(sourcePath, file); // Skip non-existing items if (!fs.existsSync(filePath)) return; let isGlob = /\*/.test(file), isDirectory = !isGlob && fs.lstatSync(filePath).isDirectory(); if (isDirectory){ archive.directory(filePath, file); }else if (isGlob){ globs.push(filePath); }else{ archive.file(filePath, {name: file}); } }); // Check for globs if (globs.length !== 0){ let pending = globs.length; globs.forEach(pattern => { glob(pattern, (err, files) => { if (err) done(err); else{ files.forEach(file => { if (fs.lstatSync(file).isFile()){ archive.file(file, {name: path.basename(file)}); }else{ logger.debug(`Could not add ${file} from glob`); } }); if (--pending === 0){ archive.finalize(); } } }); }); }else{ archive.finalize(); } }; }; const runPostProcessingScript = () => { return (done) => { this.runningProcesses.push( processRunner.runPostProcessingScript({ projectFolderPath: this.getProjectFolderPath() }, (err, code, signal) => { if (err) done(err); else{ if (code === 0) done(); else done(new Error(`Process exited with code ${code}`)); } }, output => { this.output.push(output); }) ); }; }; // All paths are relative to the project directory (./data/<uuid>/) let allPaths = ['odm_orthophoto/odm_orthophoto.tif', 'odm_orthophoto/odm_orthophoto.mbtiles', 'odm_georeferencing', 'odm_texturing', 'odm_dem/dsm.tif', 'odm_dem/dtm.tif', 'dsm_tiles', 'dtm_tiles', 'orthophoto_tiles', 'potree_pointcloud', 'images.json']; // Did the user request different outputs than the default? if (this.outputs.length > 0) allPaths = this.outputs; let tasks = []; if (config.test){ if (config.testSkipOrthophotos){ logger.info("Test mode will skip orthophoto generation"); // Exclude these folders from the all.zip archive ['odm_orthophoto', 'orthophoto_tiles'].forEach(dir => { allPaths.splice(allPaths.indexOf(dir), 1); }); } if (config.testSkipDems){ logger.info("Test mode will skip DEMs generation"); // Exclude these folders from the all.zip archive ['odm_dem/dsm.tif', 'odm_dem/dtm.tif', 'dsm_tiles', 'dtm_tiles'].forEach(p => { allPaths.splice(allPaths.indexOf(p), 1); }); } if (config.testFailTasks){ logger.info("Test mode will fail the task"); tasks.push(done => done(new Error("Test fail"))); } } if (!this.skipPostProcessing) tasks.push(runPostProcessingScript()); tasks.push(createZipArchive('all.zip', allPaths)); // Upload to S3 all paths + all.zip file (if config says so) if (S3.enabled()){ tasks.push((done) => { let s3Paths; if (config.test){ s3Paths = ['all.zip']; // During testing only upload all.zip }else if (config.s3UploadEverything){ s3Paths = ['all.zip'].concat(allPaths); }else{ s3Paths = ['all.zip', 'odm_orthophoto/odm_orthophoto.tif']; } S3.uploadPaths(this.getProjectFolderPath(), config.s3Bucket, this.uuid, s3Paths, err => { if (!err) this.output.push("Done uploading to S3!"); done(err); }, output => this.output.push(output)); }); } async.series(tasks, (err) => { if (!err){ this.setStatus(statusCodes.COMPLETED); finished(); }else{ this.setStatus(statusCodes.FAILED); finished(err); } }); }; if (this.status.code === statusCodes.QUEUED){ this.startTrackingProcessingTime(); this.setStatus(statusCodes.RUNNING); let runnerOptions = this.options.reduce((result, opt) => { result[opt.name] = opt.value; return result; }, {}); runnerOptions["project-path"] = fs.realpathSync(Directories.data); if (this.gcpFiles.length > 0){ runnerOptions.gcp = fs.realpathSync(path.join(this.getGcpFolderPath(), this.gcpFiles[0])); } this.runningProcesses.push(odmRunner.run(runnerOptions, this.uuid, (err, code, signal) => { if (err){ this.setStatus(statusCodes.FAILED, {errorMessage: `Could not start process (${err.message})`}); finished(err); }else{ // Don't evaluate if we caused the process to exit via SIGINT? if (this.status.code !== statusCodes.CANCELED){ if (code === 0){ postProcess(); }else{ this.setStatus(statusCodes.FAILED, {errorMessage: `Process exited with code ${code}`}); finished(); } }else{ finished(); } } }, output => { // Replace console colors output = output.replace(/\x1b\[[0-9;]*m/g, ""); // Split lines and trim output.trim().split('\n').forEach(line => { this.output.push(line.trim()); }); }) ); return true; }else{ return false; } } // Re-executes the task (by setting it's state back to QUEUED) // Only tasks that have been canceled, completed or have failed can be restarted. restart(options, cb){ if ([statusCodes.CANCELED, statusCodes.FAILED, statusCodes.COMPLETED].indexOf(this.status.code) !== -1){ this.setStatus(statusCodes.QUEUED); this.dateCreated = new Date().getTime(); this.output = []; this.stopTrackingProcessingTime(true); if (options !== undefined) this.options = options; cb(null); }else{ cb(new Error("Task cannot be restarted")); } } // Returns the description of the task. getInfo(){ return { uuid: this.uuid, name: this.name, dateCreated: this.dateCreated, processingTime: this.processingTime, status: this.status, options: this.options, imagesCount: this.images.length }; } // Returns the output of the OpenDroneMap process // Optionally starting from a certain line number getOutput(startFromLine = 0){ return this.output.slice(startFromLine, this.output.length); } // Reads the contents of the tasks's // images.json and returns its JSON representation readImagesDatabase(callback){ const imagesDbPath = !config.test ? path.join(this.getProjectFolderPath(), 'images.json') : path.join('tests', 'processing_results', 'images.json'); fs.readFile(imagesDbPath, 'utf8', (err, data) => { if (err) callback(err); else{ try{ const json = JSON.parse(data); callback(null, json); }catch(e){ callback(e); } } }); } callWebhooks(){ // Hooks can be passed via command line // or for each individual task const hooks = [this.webhook, config.webhook]; this.readImagesDatabase((err, images) => { if (err) logger.warn(err); // Continue with callback if (!images) images = []; let json = this.getInfo(); json.images = images; hooks.forEach(hook => { if (hook && hook.length > 3){ const notifyCallback = (attempt) => { if (attempt > 5){ logger.warn(`Webhook invokation failed, will not retry: ${hook}`); return; } request.post(hook, { json }, (error, response) => { if (error || response.statusCode != 200){ logger.warn(`Webhook invokation failed, will retry in a bit: ${hook}`); setTimeout(() => { notifyCallback(attempt + 1); }, attempt * 5000); }else{ logger.debug(`Webhook invoked: ${hook}`); } }); }; notifyCallback(0); } }); }); } // Returns the data necessary to serialize this // task to restore it later. serialize(){ return { uuid: this.uuid, name: this.name, dateCreated: this.dateCreated, status: this.status, options: this.options, webhook: this.webhook, skipPostProcessing: !!this.skipPostProcessing, outputs: this.outputs || [] }; } };
pierotofy/node-OpenDroneMap
libs/Task.js
JavaScript
gpl-3.0
20,626
/** * @param {Object} options * @param {Number} options.size Max size of array to return * @param {Number} options.page Location in pagination * @param {String} options.first_name first name of user * @param {String} options.last_name last name of user * @param {Boolean} options.is_collaborator is &#x60;User&#x60;a collaborator? * @param {Boolean} options.is_creator is &#x60;User&#x60;a creator? * @param {String} options.city city location of user * @param {String} options.state state location of user * @param {Array} options.university_ids universities a &#x60;User&#x60;is associated with * @param {String} options.project_id project_id the &#x60;User&#x60;is associated with * @param {String} options.created_date date the &#x60;User&#x60;was created * @param {String} options.modified_date date the &#x60;User&#x60;was modified * @param {Array} options.keywords keyword * @param {Array} options.skills skills to search for * @param {Function} callback */ import models from '../../../../../model'; import bcrypt from 'bcrypt'; const Grant = models.grant; const Post = models.post; const Project = models.project; const Review = models.review; const Skill = models.skill; const University = models.University; const User = models.User; const UserSkill = models.userkSkill; export function getUsers (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.university_id ID of &#x27;User&#x27; to fetch * @param {Number} options.max max num of &#x27;User&#x27; to fetch * @param {Number} options.page page in pagination * @param {Function} callback */ export function getUsersByUniversityId (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.project_id ID of &#x27;Project&#x27; to fetch * @param {Number} options.max max num of &#x27;User&#x27; to fetch * @param {Number} options.page page in pagination * @param {Function} callback */ export function getUsersByProjectId (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.created_date Date that &#x60;User&#x60; object was created * @param {Function} callback */ export function getUsersByCreatedDate (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.created_date Date that &#x60;User&#x60; object was created * @param {Function} callback */ export function getUsersByCreatedDateForm (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.modified_date Date that &#x60;User&#x60; object was modified * @param {Function} callback */ export function getUsersByModifiedDate (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.modified_date Date that &#x60;User&#x60; object was modified * @param {Function} callback */ export function getUsersByModifiedDateForm (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {Array} options.keywords Keywords when searching for user * @param {Function} callback */ export function getUsersByKeywords (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {Array} options.skills Skills when searching for user * @param {Function} callback */ export function getUsersBySkills (options, callback) { // Implement you business logic here... }
ArmRay/Arm_Ray_App
server/instances/search/src/api/services/Users.js
JavaScript
gpl-3.0
3,624
// These values are updated every 5 minutes // using site_stats table from all wikis replicated in // WMF Labs databases. // Families updated include ["wikibooks", "wikipedia", "wiktionary", "wikimedia", "wikiquote", "wikisource", "wikinews", "wikiversity", "commons", "wikispecies", "wikidata", "wikivoyage"] // More questions? emijrp AT gmail DOT com var timenow = new Date().getTime(); var period = 20; // period update in miliseconds var spliter = ","; var spliter_r = new RegExp(/(^|\s)(\d+)(\d{3})/); function init() { adjustSizes(); var lang = ""; var header = ""; var donate = ""; var f11 = ""; var author = ""; if (navigator.systemLanguage) { lang = navigator.systemLanguage; }else if (navigator.userLanguage) { lang = navigator.userLanguage; }else if(navigator.language) { lang = navigator.language; }else { lang = "en"; } if (lang.length>2) { lang=lang.substring(0,2); } switch(lang){ case "example": header='<a href="http://www.wikimedia.org"></a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia"></a>'; f11=''; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "af": header='Totale wysigings in alle <a href="http://www.wikimedia.org">Wikimedia-projekte</a>:'; spliter='&nbsp;'; donate="<a href='http://wikimediafoundation.org/wiki/Skenk'>Skenk 'n donasie aan die Wikimedia-stigting</a>"; //be careful with 'n f11='Druk op F11 vir volskerm'; author='Ontwikkel deur <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (inspirasie deur <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "als": header='Gsamtaazahl Bearbeitige uff de <a href="http://www.wikimedia.org">Wikimedia-Brojäkt:</a>'; spliter='&nbsp;'; donate="<a href='http://wikimediafoundation.org/wiki/Finanzielli_Hilf'>Understütz d'Wikimedia Foundation</a>"; //be careful with d' f11='Vollbild: F11'; author='Gschribe vum <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (uff Basis vu <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "an": header='Edicions totals en <a href="http://www.wikimedia.org">prochectos Wikimedia</a>:'; spliter='.'; donate="<a href='http://wikimediafoundation.org/wiki/Support_Wikipedia'>Fer una donación t'a Fundación Wikimedia</a>"; //be careful with t' f11='Pretar F11 ta veyer en pantalla completa'; author='Desembolicau por <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirau por <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ar": header='مجموع التعديلات في <a href="http://www.wikimedia.org">مشاريع ويكيميديا</a>:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/جمع_تبرعات">تبرع لمؤسسة ويكيميديا</a>'; f11='للشاشة الكاملة اضغط F11'; author='من تطوير <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (ملهمة من <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "az": header='<a href="http://www.wikimedia.org">Wikimedia layihəsində </a> redaktələrin ümumi sayı:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Bağışlar">Wikimedia Foundation təşkilatına ianələrin göndərilməsi</a>'; f11='Ekranın tam açılması üçün F11 düyməsini basın'; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> tərəfindən (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> dəstəyi ilə) işlənmişdir'; break; case "be": header='Агулам правак у <a href="http://www.wikimedia.org">праектах Фундацыі «Вікімэдыя»</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Ахвяруйце Фундацыі Вікімэдыя</a>'; f11='Націсьніце F11 для поўнаэкраннага прагляду'; author='Распрацаваў <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (ідэя <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "bg": header='Общ брой редакции в <a href="http://www.wikimedia.org">проектите на Уикимедия</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Подкрепете с дарение Фондация Уикимедия</a>'; f11='Натиснете F11 за показване на голям екран'; author='Разработено от <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (вдъхновено от <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "bn": header='<a href="http://www.wikimedia.org">উইকিমিডিয়ার বিভিন্ন প্রকল্পে</a> সর্বমোট সম্পাদনার সংখ্যা:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">উইকিমিডিয়া ফাউন্ডেশনে দান করুন</a>'; f11='সম্পূর্ন স্ক্রিন জুড়ে দেখতে হলে F11 চাপুন'; author='এই কাউন্টারটি তৈরী করেছেন <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> এর অনুপ্রেরণায়)'; break; case "br": header='Niver hollek a gemmoù er <a href="http://www.wikimedia.org">raktresoù Wikimedia</a> :'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Donezoniñ da Ziazezadur Wikimedia</a>'; f11='Pouezit war F11 evit ar mod skramm leun'; author='Diorroet gant <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Awenet gant <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "bs": header='Ukupne izmjene u svim <a href="http://www.wikimedia.org">Wikimedia projektima</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Donirajte Wikimedia Fondaciji</a>'; f11='Pritisnite F11 za prikaz preko cijelog ekrana'; author='Razvio korisnik <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspiriran od strane <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ca": header='Edicions entre tots els <a href="http://www.wikimedia.org">projectes de Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Donatius">Dona a la Fundació Wikimedia</a>'; f11='Pantalla completa pulsant F11'; author='Desarrollat per <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirat en <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ceb": header='Mga tibuok kausaban sa <a href="http://www.wikimedia.org">mga proyekto sa Wikimedya</a>:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Idonar sa Wikimedia Foundation</a>'; f11='Tuploka ang F11 aron mapuno sa tabil'; author='Gipalambo ni <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Nadasig sa <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "cs": header='Celkový počet editací v <a href="http://www.wikimedia.org">projektech nadace Wikimedia</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Sponzorství">Podpořte Wikimedia Foundation</a>'; f11='Stisknutím klávesy F11 zobrazíte stránku na celou obrazovku'; author='Vyvinul <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (inspirováno stránkami <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "cy": header='Cyfanswm yr holl olygiadau ym <a href="http://www.wikimedia.org">mhrosiectau Wikimedia</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Cyfrannwch at Sefydliad Wikimedia</a>'; f11='Gwasgwch F11 am sgrîn lawn'; author='Datblygwyd gan <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Ysbrydolwyd gan <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "da": header='Samlet antal rettelser på tværs af alle <a href="http://www.wikimedia.org">Wikimedia-projekter</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Indsamling">Giv et bidrag til Wikimedia Foundation</a>'; f11='Tryk F11 for fuldskærmsvisning'; author='Udviklet af <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspireret af <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "de": header='Gesamtzahl der Bearbeitungen in <a href="http://www.wikimedia.org">den Wikimedia-Projekten</a>:'; spliter='&#8239;'; donate='<a href="http://wikimediafoundation.org/wiki/Spenden">Spende an die Wikimedia Foundation</a>'; f11='Drücke F11 für die Vollbild-Anzeige'; author='Entwickelt von <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspiriert durch <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "el": header='Συνολικές επεξεργασίες στα <a href="http://www.wikimedia.org">εγχειρήματα του Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Κάντε δωρεά στο Ίδρυμα Wikimedia</a>'; f11='Πατήστε F11 για πλήρη οθόνη'; author='Αναπτύχθηκε από τον <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Εμπνευσμένο από το <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "eo": header='Totala nombro de redaktoj en <a href="http://www.wikimedia.org">Vikimediaj projektoj</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Monkolektado">Donaci al Fondaĵo Vikimedio</a>'; f11='Premu F11 por plenekrana modo'; author='Kreita de <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirita de <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "es": header='Ediciones entre todos los <a href="http://www.wikimedia.org">proyectos Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Donaciones">Dona a la Fundación Wikimedia</a>'; f11='Pantalla completa pulsando F11'; author='Desarrollado por <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirado en <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "et": header='<a href="http://www.wikimedia.org">Wikimedia projektides</a> tehtud redigeerimiste koguarv:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Anneta Wikimedia sihtasutusele</a>'; f11='Täisekraani jaoks vajuta F11'; author='Kasutajalt <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> eeskujul)'; break; case "eu": header='<a href="http://www.wikimedia.org">Wikimedia proiektuetan</a> egindako eguneraketak guztira:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Dohaintzak">Wikimedia Foundazioari dohaintza egin</a>'; f11='F11 sakatu pantaila osoan erakusteko'; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a>-ek garatua (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>-ek inspiratuta)'; break; case "fa": header='مجموع ویرایش‏ها در <a href="http://www.wikimedia.org">پروژه ویکی‏مدیا</a>:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">کمک مالی به بنیاد ویکی‏مدیا</a>'; f11='را برای نمایش تمام صفحه فشار دهید F11کلید'; author='گسترش‌یافته بوسیله <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (با الهام از <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "fr": header="Nombre total d'éditions dans les <a href='http://www.wikimedia.org'>projets Wikimedia</a>:"; // be careful with d'éditions spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Faire_un_don">Donner à la Wikimedia Foundation</a>'; f11='Appuyez sur F11 pour passer en plein écran'; author='Développé par <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspiré par <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "gu": header='<a href="http://www.wikimedia.org">વિકિમીડિયા પરિયોજના </a> માં કુલ સંપાદનો'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">વિકિમીડિયા ફાઉન્ડેશનને દાન આપો</a>'; f11='ફુલ સ્ક્રીન માટે F11 દબાવો'; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp ધ્વારા વિકસિત </a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7 ધ્વરા પ્રેરિત </a>)'; break; case "hi": header='<a href="http://www.wikimedia.org">विकिमीडिया परियोजना</a> में कुल संपादन:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Donate/hi">विकिमीडिया फ़ौंडेशन को दान करें। </a>'; f11='पूर्ण स्क्रीन के लिए ऍफ़११ [F11] दबाएँ।'; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">एमिजआरपी [emijrp]</a> द्वारा विकसित (<a href="http://www.7is7.com/software/firefox/partycounter.html">७इस७ [7is7]</a> द्वारा प्रेरित।)'; break; case "hu": header='<a href="http://www.wikimedia.org">A Wikimédia projektek</a> együttes szerkesztésszáma:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia/hu">Támogasd a Wikimédia Alapítványt</a>'; f11='Teljes képernyős mód: F11'; author='Készítette: <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> ötlete alapján)'; break; case "id": header='Jumlah suntingan di <a href="http://www.wikimedia.org">proyek Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Penggalangan_dana">Menyumbang untuk Yayasan Wikimedia</a>'; f11='Tekan F11 untuk tampilan layar penuh'; author='Dikembangkan oleh <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Terinspirasi dari <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "it": header='Modifiche totali nei <a href="http://www.wikimedia.org">progetti Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Donazioni">Fai una donazione a Wikimedia Foundation</a>'; f11='Premi F11 per passare a schermo intero'; author='Sviluppato da <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (ispirato da <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ja": header='<a href="http://www.wikimedia.org">ウィキメディア・プロジェクト</a>の総編集回数'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">ウィキメディア財団に寄付</a>'; f11='F11キーでフルスクリーン表示'; author='開発:<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (原案:<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "kl": header='Tamakkiisumik amerlassutsit aaqqissuussinerni <a href="http://www.wikimedia.org">Wikimedia suliniutaani</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Wikimedia suliniutaani tunissuteqarit</a>'; f11='F11 tooruk tamaat saqqummissagukku'; author='Siuarsaasuuvoq <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Peqatigalugu <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ko": header='<a href="http://www.wikimedia.org">위키미디어 재단에서 운영하는 프로젝트</a>의 총 편집 횟수:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">위키미디어 재단에 기부하기</a>'; f11='F11 키를 누르면 전체 화면 모드로 전환합니다'; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a>이 만듬 (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>에서 영감을 얻음)'; break; case "nl": header='Totaal aantal bewerkingen in <a href="http://www.wikimedia.org">Wikimediaprojecten</a>:'; //spliter='&nbsp;'; //donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia"></a>'; //f11=''; //author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "oc": header='Edicions totalas dins <a href="http://www.wikimedia.org">los projèctes de Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Far una donacion a la fondacion Wikimedia</a>'; f11="Quichar sus F11 per un afichatge sus tot l'ecran"; author='Desvolopat per <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirat de <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "pl": header='Ogólna liczba edycji w <a href="http://www.wikimedia.org">projektach Wikimedia</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Dary_pieniężne">Wesprzyj Wikimedia Foundation</a>'; f11='Naciśnij F11, aby włączyć tryb pełnoekranowy'; author='Stworzony przez <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (zainspirowany przez <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "pt": header='Total de edições nos <a href="http://www.wikimedia.org">projetos Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Coleta_de_fundos">Doe para a Fundação Wikimedia</a>'; f11='Pressione F11 para tela cheia'; author='Desenvolvido por <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirado em <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ro": header='Numărul total de modificări în <a href="http://www.wikimedia.org">proiectele Wikimedia</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Donaţii">Donaţi pentru Wikimedia</a>'; f11='Apăsați F11 pentru afișarea pe tot ecranul'; author='Dezvoltat de <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (inspirat de la <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ru": header='Всего правок в <a href="http://www.wikimedia.org">проектах Викимедиа</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia/ru">Пожертвуйте «Фонду Викимедиа»</a>'; f11='Нажмите F11 для показа на весь экран'; author='Разработал <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Основано на <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "sv": header='Antal redigeringar i <a href="http://www.wikimedia.org">Wikimediaprojekten</a>:'; spliter='&nbsp;'; donate='<a href="http://wikimediafoundation.org/wiki/Insamling">Donera till Wikimedia Foundation</a>'; f11='Tryck F11 för helskärm'; author='Utvecklad av <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirerad av <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "te": header='<a href="http://www.wikimedia.org">వికీమీడియా ప్రాజెక్టుల</a>లో మొత్తం దిద్దుబాట్లు:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">వికీమీడియా ఫౌండేషనుకి విరాళమివ్వండి</a>'; f11='నిండుతెర కొరకు F11 నొక్కండి'; author='రూపొందించినది <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> ప్రేరణతో)'; break; case "tr": header='<a href="http://www.wikimedia.org">Wikimedia projelerindeki</a> toplam düzenleme sayısı:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Wikimedia Vakfına bağışta bulunun</a>'; f11='Tam ekran görüntülemek için F11 tuşuna basın'; author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> tarafından geliştirilmiştir (Esin kaynağı <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; case "ur": header=' جملہ ترامیم در <a href="http://www.wikimedia.org">ویکیمیڈیا منصوبہ جات</a>:'; spliter='.'; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">مؤسسہ ویکیمیڈیا کو عطیہ دیں</a>'; f11='مکمل سکرین دیکھنے کے لیے کلک رکیں F11'; author='ترقی دہندہ <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (متاثر از <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; break; default: header='Total edits in <a href="http://www.wikimedia.org">Wikimedia projects</a>:'; spliter=','; donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Donate to Wikimedia Foundation</a>'; f11='Press F11 for fullscreen'; author='Developed by <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspired by <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)'; } document.getElementById('header').innerHTML = header; document.getElementById('donate').innerHTML = donate; document.getElementById('f11').innerHTML = f11; document.getElementById('author').innerHTML = author; window.setTimeout(update, period); } function update() { timenow2 = new Date().getTime(); if (Math.round(((timenow2-timenow)/1000)+1) % 300 == 0) { window.setTimeout(window.location.reload(), 1100); } //refresh page editnow = editinit + (timenow2-timeinit) * editrate; editnowtext = ""+Math.round(editnow); for(var i=3; i<editnowtext.length; i+=3) { editnowtext = editnowtext.replace(spliter_r,'$2'+spliter+'$3'); } document.getElementById('counter').innerHTML = editnowtext; window.setTimeout(update, period); } function adjustSizes(){ var width=800; var height=600; if (self.innerWidth) { width=self.innerWidth; height=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { width=document.documentElement.clientWidth; height=document.documentElement.clientHeight; } else if (document.body) { width=document.body.clientWidth; height=document.body.clientHeight; } document.getElementById('wrapper').style.height=(height-10)+'px'; document.getElementById('header').style.fontSize=width/45+'pt'; document.getElementById('footer').style.fontSize=width/45+'pt'; document.getElementById('counter').style.fontSize=width/12+'pt'; } window.onload = init; window.onresize = adjustSizes;
emijrp/wmcounter
public_html/wmcounter.js
JavaScript
gpl-3.0
27,529
export const LOGGED_IN = 'LOGGED_IN'; export const LOGGED_OUT = 'LOGGED_OUT';
csujedihy/react-native-textgo
app/actions/types.js
JavaScript
gpl-3.0
77
import { moduleForModel, test } from 'ember-qunit' moduleForModel('team', { needs: [ 'model:user' , 'model:project' , 'model:assignment' , 'model:attendance' ] }) test('it exists', function(assert) { var model = this.subject() // var store = this.store() assert.ok(!!model) })
topaxi/timed
frontend/tests/unit/models/team-test.js
JavaScript
gpl-3.0
299
MODX Evolution 1.0.5 = dace793f0e7de11aadc0ecf54e834d93
gohdan/DFC
known_files/hashes/assets/plugins/tinymce/jscripts/tiny_mce/themes/advanced/langs/bg.js
JavaScript
gpl-3.0
56
const Log = require("../util/log.js"); const common = require("../util/common.js"); const setting_global = require("../settings.json"); const setting_color = setting_global.commands.user.guilds.color; const setting_mute = setting_global.commands.admin.mute; const setting = setting_global.events.memberAdd; module.exports = (client, member) => { Log.memberAdd(member.user); if (setting.welcomeMessage.enabled) common.getChannel(client, setting.welcomeMessage.channel) .send(setting.welcomeMessage.template[ common.getRandom(0, setting.welcomeMessage.template.length)] .replace("{user}", member.user)); if (setting.autoRole.role) setting.autoRole.role.forEach((role) => member.addRole(member.guild.roles .find("name", role))); if (setting.autoRole.random_color) member.addRole(member.guild.roles .find("name", setting_color.colors[common.getRandom(0, setting_color.colors.length)].role)); if (client.muted && setting.auto_mute) { let time = client.muted[member.id]; if (time) member.addRole(member.guild.find("name", setting_mute.role)); } };
AndreyLysenkov/LausyWalpy
events/guildMemberAdd.js
JavaScript
gpl-3.0
1,206
module.exports = { talkTo: function(player, npc){ // TODO: Dialogues this.trade(player, npc); }, trade: function(player, npc){ vendor("Obli's General Store"); } }
netherfoam/Titan
javascripts/interaction/npc/obli.js
JavaScript
gpl-3.0
203
Object.defineProperty(exports, '__esModule', { value: true }); const path = require('path'); // explicitly set the config dir, otherwise if oxygen is globally installed it will use cwd let originalNodeCfgDir = process.env.NODE_CONFIG_DIR; process.env.NODE_CONFIG_DIR = path.resolve(__dirname, '../..', 'config'); // import config and @oxygen/logger modules const config = require('config'); const loggerFactory = require('@oxygenhq/logger'); // setup logger loggerFactory.init(config.get('logger')); // revert back NODE_CONFIG_DIR value process.env.NODE_CONFIG_DIR = originalNodeCfgDir; exports.default = function logger(name) { return loggerFactory.get(name); }; const LEVEL_INFO = 'info'; const LEVEL_DEBUG = 'debug'; const LEVEL_ERROR = 'error'; const LEVEL_WARN = 'warn'; const ISSUER_SYSTEM = 'system'; const ISSUER_USER = 'user'; exports.DEFAULT_ISSUER = ISSUER_USER; exports.ISSUERS = { SYSTEM: ISSUER_SYSTEM, USER: ISSUER_USER }; exports.LEVELS = { INFO: LEVEL_INFO, DEBUG: LEVEL_DEBUG, ERROR: LEVEL_ERROR, WARN: LEVEL_WARN }; exports.DEFAULT_LOGGER_ISSUER = ISSUER_SYSTEM;
oxygenhq/oxygen
src/lib/logger.js
JavaScript
gpl-3.0
1,122
enyo.kind({ name: "Remote.Movies", kind: "VFlexBox", events: { onPlay: "", }, components: [ {kind: "PageHeader", components: [ {name: "headerText", kind: enyo.VFlexBox, content: "", flex: 1 }, {name: "backButton", kind: "Button", content: "Back", onclick: "goBack" } ]}, {name: "pane", kind: "Pane", flex: 1, components: [ {name: "movies", className: "enyo-bg", kind: "Remote.MovieList", onSelect: "selectMovie" }, ]}, ], update: function() { this.$.pane.view.update(); }, selectMovie: function(inSender, inMovie) { this.doPlay(inMovie.id); }, });
jerrykan/webos-xbmcremote
source/Movies.js
JavaScript
gpl-3.0
770
/*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! * Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=bdc334eb7ee1e998de2a85b5f46ddcac) * Config saved to config.json and https://gist.github.com/bdc334eb7ee1e998de2a85b5f46ddcac */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4') } }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.7 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.7' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector === '#' ? [] : selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.7 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.7' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d).prop(d, true) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d).prop(d, false) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target).closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) { // Prevent double click on radios, and the double selections (so cancellation) on checkboxes e.preventDefault() // The target component still receive the focus if ($btn.is('input,button')) $btn.trigger('focus') else $btn.find('input:visible,button:visible').first().trigger('focus') } }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.7 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.7' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function () { that.$element.one('mouseup.dismiss.bs.modal', function (e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (document !== e.target && this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { this.adjustDialog() } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.7 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ /* jshint latedef: false */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.7' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.7 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery);
GM-Connor/KanjiSheets
js/bootstrap.js
JavaScript
gpl-3.0
24,744
require('dotenv').config({ silent: true }); const webpack = require('webpack'); const appConfig = require('@flumens/webpack-config'); appConfig.entry = ['index.js']; const required = ['APP_SENTRY_KEY', 'APP_INDICIA_API_KEY']; const development = { APP_INDICIA_API_HOST: '', }; appConfig.plugins.unshift( new webpack.EnvironmentPlugin(required), new webpack.EnvironmentPlugin(development) ); const unusedFilesPlugin = appConfig.plugins.find(plugin => !!plugin.exclude); unusedFilesPlugin.exclude.push('*.tpl'); appConfig.module.rules.push({ test: /(\.eot)/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]', }, }); module.exports = appConfig;
NERC-CEH/npms-app
webpack.config.js
JavaScript
gpl-3.0
679
"use strict"; let templatePad = function (n, padTemplate) { let str = (n).toString(); return (padTemplate + str).substring(str.length); }; let formatByte = function (n) { return templatePad(n.toString(16).toLocaleUpperCase(), '00'); }; let instructionProperties = [ 'note', 'instrument_high','instrument_low', 'volume', 'fx0_type','fx0_high','fx0_low', ]; let getInstruction = function(overrideChannel){ let editorState = app.editorState; let projectState = app.projectState; let channelIndex = overrideChannel != null ? overrideChannel : editorState.activeChannelIndex; let activeSong = projectState.songs[editorState.activeSongIndex]; let activePatternIndex = activeSong.orders[editorState.activeOrderIndex][channelIndex]; let activePattern = activeSong.patterns[channelIndex][activePatternIndex]; while(activePattern.length < activeSong.rows) { activePattern.push(hydration.newEmptyInstruction()); } let instruction = activePattern[editorState.activeRowIndex]; return JSON.parse(JSON.stringify(instruction)); // return a copy in case our caller decides to back out of changing the instruction }; let updateInstruction = function(newInstruction, overrideChannel){ let editorState = app.editorState; let projectState = app.projectState; let channelIndex = overrideChannel != null ? overrideChannel : editorState.activeChannelIndex; let activeSong = projectState.songs[editorState.activeSongIndex]; let activePatternIndex = activeSong.orders[editorState.activeOrderIndex][channelIndex]; let activePattern = activeSong.patterns[channelIndex][activePatternIndex]; let oldInstruction = activePattern[editorState.activeRowIndex]; for(let prop in newInstruction) { // in practice, this will always update a non-null fx if(oldInstruction[prop] != newInstruction[prop]) { oldInstruction[prop] = newInstruction[prop]; } } }; let eraseValue = function () { let instruction = getInstruction(); let property = app.editorState.activeProperty.match(/^[^_]*/)[0]; if(property.startsWith('fx')){ let fxIndex = parseInt(property.substring(2), 10); instruction.fx[fxIndex] = null; instruction.fx = instruction.fx.slice(); } else { instruction[property] = null; } updateInstruction(instruction); }; let togglePlayback = function() { if(app.editorState.playbackState == 'paused') { app.vue.changePlaybackState(app.editorState.playbackStateOnLastPause || 'playSong'); } else { app.vue.changePlaybackState('paused'); } event.preventDefault(); }; let keyHandlerMap = { 'Backspace': eraseValue, 'Delete': eraseValue, ' ': togglePlayback, }; let filterHexDigitKey = function(event) { if(event.key.match(/^[0-9A-Fa-f]$/)) return parseInt(event.key, 16); else return false; }; let applyAutoInstrument = function(instruction,channel) { if(!app.editorState.autoInstrument) return; let index = app.projectState.instruments.indexOf((app.editorState.respectMIDIInstruments && channel) ? channel.instrument : app.editorState.activeInstrument); if(index >= 0) instruction.instrument = index; } let autoAdvance = function() { if(app.editorState.autoAdvance && app.editorState.playbackState == 'paused') { app.editorState.activeRowIndex = (app.editorState.activeRowIndex + 1) % app.projectState.songs[app.editorState.activeSongIndex].rows; if(app.editorState.autoAdvanceOrder && app.editorState.activeRowIndex == 0) { app.editorState.activeOrderIndex = (app.editorState.activeOrderIndex + 1) % app.projectState.songs[app.editorState.activeSongIndex].orders.length; } } } let noteLetterMap = {C:0, D:2, E:4, F:5, G:7, A:9, B:11}; let octaveDigitMap = {Z:0, 0:12, 1:24, 2:36, 3:48, 4:60, 5:72, 6:84, 7:96, 8:108}; // this is the highest note whose frequency can actually be inputted into the ET209 let maximum_voice_note = 114; let instruction_has_note_on = function(instruction) { return instruction.note !== null && instruction.note !== 'cut' && instruction.note !== 'off'; } // filters return true if they fully handled the keypress let keyFilterMap = { 'note':function(event){ if(channels[app.editorState.activeChannelIndex].isNoise) { let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction_has_note_on(instruction)) { instruction.note = ((instruction.note << 4) | digit) & 255; } else { instruction.note = digit; } applyAutoInstrument(instruction); updateInstruction(instruction); return true; } else if(event.key == ".") { let instruction = getInstruction(); applyAutoInstrument(instruction); let instrument; if(instruction.instrument != null) { instrument = app.projectState.instruments[instruction.instrument]; } else { instrument = app.editorState.activeInstrument; } if(instrument != null && instrument.autoperiod) { instruction.note = instrument.autoperiod; updateInstruction(instruction); return true; } } } else { let uppercase = event.key.toUpperCase(); if(uppercase in noteLetterMap) { let instruction = getInstruction(); if(!instruction_has_note_on(instruction)) { instruction.note = 60; } applyAutoInstrument(instruction); instruction.note = (instruction.note - instruction.note % 12) + noteLetterMap[uppercase]; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } updateInstruction(instruction); return true; } else if(uppercase in octaveDigitMap) { let instruction = getInstruction(); if(!instruction_has_note_on(instruction)) { instruction.note = 60; } applyAutoInstrument(instruction); instruction.note = octaveDigitMap[uppercase] + instruction.note % 12; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } updateInstruction(instruction); autoAdvance(); return true; } else if(event.key == "#") { let instruction = getInstruction(); if(!instruction_has_note_on(instruction)) { instruction.note = 60; } applyAutoInstrument(instruction); ++instruction.note; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } updateInstruction(instruction); return true; } } if(event.key == "x" || event.key == "X") { let instruction = getInstruction(); instruction.note = 'off'; updateInstruction(instruction); return true; } else if(event.key == "\\") { let instruction = getInstruction(); instruction.note = 'cut'; updateInstruction(instruction); return true; } }, 'instrument_high':function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.instrument === null) { instruction.instrument = digit << 4; } else { instruction.instrument = (instruction.instrument & 0xF) | (digit << 4); } updateInstruction(instruction); return true; } }, 'instrument_low':function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.instrument === null) { instruction.instrument = digit; } else { instruction.instrument = (instruction.instrument & 0xF0) | digit; } updateInstruction(instruction); return true; } }, 'volume':function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); instruction.volume = digit; updateInstruction(instruction); return true; } }, }; for(let n = 0; n < 3; ++n) { let effectIndex = n; keyFilterMap["fx"+n+"_type"] = function(event){ let uppercase = event.key.toUpperCase(); if(letter_to_effect_name[uppercase]) { let instruction = getInstruction(); if(instruction.fx == null) { instruction.fx = []; } while(instruction.fx.length < effectIndex) { instruction.fx.push(null); } if(instruction.fx[effectIndex] == undefined) { instruction.fx[effectIndex] = {value:0}; } instruction.fx[effectIndex].type = letter_to_effect_name[uppercase]; updateInstruction(instruction); return true; } }; keyFilterMap["fx"+n+"_high"] = function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.fx == null || instruction.fx[effectIndex] == undefined) { return false; } instruction.fx[effectIndex].value = (instruction.fx[effectIndex].value & 0xF) | (digit << 4) updateInstruction(instruction); return true; } }; keyFilterMap["fx"+n+"_low"] = function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.fx == null || instruction.fx[effectIndex] == undefined) { return false; } instruction.fx[effectIndex].value = (instruction.fx[effectIndex].value & 0xF0) | digit; updateInstruction(instruction); return true; } }; } let recordNoteOn = function(noteValue, velocity, channel) { let instruction = getInstruction(channel); applyAutoInstrument(instruction, channels[channel]); instruction.note = noteValue; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } if(app.editorState.respectMIDIVelocities) { instruction.volume = (velocity+7)>>3; } updateInstruction(instruction, channel); if(!app.editorState.respectMIDIClocks) { autoAdvance(); } }; let recordNoteOff = function(channel) { if(app.editorState.noteOffMode == 'ignored') return; let instruction = getInstruction(channel); instruction.instrument = null; instruction.note = app.editorState.noteOffMode; updateInstruction(instruction, channel); if(!app.editorState.respectMIDIClocks) autoAdvance(); }; let recordInstrument = function(instrument, channel) { let instruction = getInstruction(channel); instruction.instrument = instrument; updateInstruction(instruction, channel); }; let recordAdvance = function() { autoAdvance(); }; Vue.component( 'pattern-editor', { props: { channels: Array, editorState: Object, activeOrder: Array, patterns: Array, rowCount: Number }, computed: { tableRows: function () { let rows = []; let rowCount = this.rowCount; let patterns = this.patterns; let activeOrder = this.activeOrder; activeOrder.forEach(function (channelOrderIndex, channelIndex) { while(channelOrderIndex >= patterns[channelIndex].length){ patterns[channelIndex].push([]); } let patternRows = patterns[channelIndex][channelOrderIndex]; for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) { let instruction = patternRows[rowIndex]; if(instruction == undefined) { instruction = hydration.newEmptyInstruction(); patternRows.push(instruction); } if(!rows[rowIndex]){ rows[rowIndex] = []; } rows[rowIndex][channelIndex] = instruction; } }); return rows; } }, data: function(){ return { noteOffModes: { 'off': 'Note Off→Off', 'cut': 'Note Off→Cut', 'ignored': 'Note Off Ignored' }, sppModes: { 'ignored': 'Ignore SPP', 'pattern': 'Pattern SPP', 'song': 'Song SPP', }, }; }, methods: { formatByte: formatByte, toggleChannel: function (channelIndex) { let polyphonyChannels = this.editorState.polyphonyChannels; let alreadyThere = polyphonyChannels.indexOf(channelIndex) !== -1; if(alreadyThere){ arrayRemove(polyphonyChannels, channelIndex); } else { polyphonyChannels.push(channelIndex); } }, setActive: function (rowIndex, channelIndex, property) { this.editorState.activeRowIndex = rowIndex; this.editorState.activeChannelIndex = channelIndex; this.editorState.activeProperty = property; }, moveUp: function(e){this.moveCursorRelative(e, 0, -1);}, moveDown: function(e){this.moveCursorRelative(e, 0, 1);}, moveLeft: function(e){this.moveCursorRelative(e, -1, 0);}, moveRight: function(e){this.moveCursorRelative(e, 1, 0);}, moveCursorRelative: function (keydownEvent, x, y) { keydownEvent.stopPropagation(); keydownEvent.stopImmediatePropagation(); keydownEvent.preventDefault(); let currentPropertyIndex = instructionProperties.indexOf(this.editorState.activeProperty); let propertyBeforeWrap = currentPropertyIndex + x; let channelWrapDirection = propertyBeforeWrap > instructionProperties.length -1 ? 1 : propertyBeforeWrap < 0 ? -1 : 0; let channelWrapped = this.wrapRange(this.editorState.activeChannelIndex + channelWrapDirection, channels.length); let propertyIndex = this.wrapRange(propertyBeforeWrap, instructionProperties.length); let propertyName = instructionProperties[propertyIndex]; let rowWrapped = this.wrapRange(this.editorState.activeRowIndex + y, this.rowCount); this.setActive( rowWrapped, channelWrapped, propertyName ); }, input: function (keydownEvent) { let filter = keyFilterMap[app.editorState.activeProperty]; if(filter && filter(keydownEvent)) { // The filter handled the event keydownEvent.preventDefault(); return; } let handler = keyHandlerMap[keydownEvent.key]; if(handler){ keydownEvent.preventDefault(); handler(keydownEvent); } }, wrapRange: function(n, max){ return (n + max) % max; }, changeNoteOffMode: function(newMode) { app.editorState.noteOffMode = newMode; }, changeSPPMode: function(newMode) { app.editorState.sppMode = newMode; } }, template: ` <div class="pattern-editor" tabindex="0" @keydown.capture.up="moveUp" @keydown.capture.down="moveDown" @keydown.capture.left="moveLeft" @keydown.capture.right="moveRight" @keydown="input" > <editor-state-styling :editorState="editorState" /> <ul class="tab-list"> <prop-checkbox :source="editorState" prop="autoAdvance" name="Auto Advance Row" /> <prop-checkbox :source="editorState" prop="autoAdvanceOrder" name="Auto Advance Order" /> <prop-checkbox :source="editorState" prop="autoInstrument" name="Auto-Instrument" /> </ul> <ul class="tab-list"> <prop-checkbox :source="editorState" prop="recordMIDI" name="Record MIDI" /> <prop-checkbox :source="editorState" prop="respectMIDIClocks" name="MIDI Clock" /> <prop-checkbox :source="editorState" prop="respectMIDIVelocities" name="MIDI Velocity" /> <prop-checkbox :source="editorState" prop="respectMIDIInstruments" name="MIDI Instrument" /> <prop-checkbox :source="editorState" prop="respectMIDIChannels" name="MIDI Channel" /> <prop-checkbox :source="editorState" prop="enablePolyphony" name="MIDI Auto-Polyphony" /> </ul> <ul class="tab-list"> <li class="noSelect buttons"> <button v-for="(symbol, name) in noteOffModes" @click="changeNoteOffMode(name)" :title="editorState.noteOffMode" :class="{active: name === editorState.noteOffMode}" > <span v-html="symbol"></span> </button> </li> <li class="noSelect buttons"> <button v-for="(symbol, name) in sppModes" @click="changeSPPMode(name)" :title="editorState.sppMode" :class="{active: name === editorState.sppMode}" > <span v-html="symbol"></span> </button> </li> </ul> <table> <thead> <th></th> <th class="channel" v-for="(item, index) in channels" > <channel :channel="item" :index="index" :toggleChannel="toggleChannel" /> </th> </thead> <tbody> <tr v-for="(row, rowIndex) in tableRows" :class="'perow_'+rowIndex" > <th>row {{formatByte(rowIndex)}}</th> <td v-for="(instruction, channelIndex) in row" :name="'channel'+channelIndex" > <instruction-editor :isNoise="channels[channelIndex].isNoise" :instruction="instruction" :cellName="'pecell_'+rowIndex+'_'+channelIndex+'_'" :setActive="function(property){setActive(rowIndex, channelIndex, property)}" /> </td> </tr> </tbody> </table> </div> ` } ); Vue.component( 'channel', { props: { channel: Channel, index: Number, toggleChannel: Function }, template: ` <button :class="{active: !channel.isMuted}" @click="channel.isMuted = !channel.isMuted"> <span class="checkbox"></span> <span>{{channel.isNoise ? 'Noise' : ('Voice ' + (index+1))}}</span> </button> ` } ); Vue.component( 'prop-checkbox', { props: { source: Object, prop: String, name: String }, template: ` <li class="noSelect buttons"> <button @click="source[prop] = !source[prop]" :class="{active: source[prop]}" > <span class="checkbox"></span> {{name}} </button> </li> ` } ); Vue.component( 'editor-state-styling', { props: { editorState: Object }, computed: { activeStyling: function(){ let editorState = this.editorState; return ` <style> tr.perow_${editorState.activeRowIndex}{ background-color: #226; } span.pecell_${editorState.activeRowIndex}_${editorState.activeChannelIndex}_${editorState.activeProperty}{ background-color: #264; } </style> `; } }, template: ` <div class="editor-state-styling" v-html="activeStyling"></div> ` } );
AdmiralPotato/ars-tracker
js/vue-channel.js
JavaScript
gpl-3.0
17,521
function getURLVar(key) { var value = []; var query = String(document.location).split('?'); if (query[1]) { var part = query[1].split('&'); for (i = 0; i < part.length; i++) { var data = part[i].split('='); if (data[0] && data[1]) { value[data[0]] = data[1]; } } if (value[key]) { return value[key]; } else { return ''; } } } $(document).ready(function() { // Highlight any found errors $('.text-danger').each(function() { var element = $(this).parent().parent(); if (element.hasClass('form-group')) { element.addClass('has-error'); } }); // Currency $('#form-currency .currency-select').on('click', function(e) { e.preventDefault(); $('#form-currency input[name=\'code\']').attr('value', $(this).attr('name')); $('#form-currency').submit(); }); // Language $('#form-language .language-select').on('click', function(e) { e.preventDefault(); $('#form-language input[name=\'code\']').attr('value', $(this).attr('name')); $('#form-language').submit(); }) /* Search */ $('#search input[name=\'search\']').parent().find('button').on('click', function() { var url = $('base').attr('href') + 'index.php?route=product/search'; var value = $('header input[name=\'search\']').val(); if (value) { url += '&search=' + encodeURIComponent(value); } location = url; }); $('#search input[name=\'search\']').on('keydown', function(e) { if (e.keyCode == 13) { $('header input[name=\'search\']').parent().find('button').trigger('click'); } }); // Menu $('#menu .dropdown-menu').each(function() { var menu = $('#menu').offset(); var dropdown = $(this).parent().offset(); var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth()); if (i > 0) { $(this).css('margin-left', '-' + (i + 5) + 'px'); } }); // Product List $('#list-view').click(function() { $('#content .product-grid > .clearfix').remove(); $('#content .row > .product-grid').attr('class', 'product-layout product-list col-xs-12'); localStorage.setItem('display', 'list'); }); // Product Grid $('#grid-view').click(function() { // What a shame bootstrap does not take into account dynamically loaded columns var cols = $('#column-right, #column-left').length; if (cols == 2) { $('#content .product-list').attr('class', 'product-layout product-grid col-lg-6 col-md-6 col-sm-12 col-xs-12'); } else if (cols == 1) { $('#content .product-list').attr('class', 'product-layout product-grid col-lg-4 col-md-4 col-sm-6 col-xs-12'); } else { $('#content .product-list').attr('class', 'product-layout product-grid col-lg-3 col-md-3 col-sm-6 col-xs-12'); } localStorage.setItem('display', 'grid'); }); if (localStorage.getItem('display') == 'list') { $('#list-view').trigger('click'); } else { $('#grid-view').trigger('click'); } // Checkout $(document).on('keydown', '#collapse-checkout-option input[name=\'email\'], #collapse-checkout-option input[name=\'password\']', function(e) { if (e.keyCode == 13) { $('#collapse-checkout-option #button-login').trigger('click'); } }); // tooltips on hover $('[data-toggle=\'tooltip\']').tooltip({container: 'body'}); // Makes tooltips work on ajax generated content $(document).ajaxStop(function() { $('[data-toggle=\'tooltip\']').tooltip({container: 'body'}); }); }); // Cart add remove functions var cart = { 'add': function(product_id, quantity) { $.ajax({ url: 'index.php?route=checkout/cart/add', type: 'post', data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1), dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { $('.alert, .text-danger').remove(); if (json['redirect']) { location = json['redirect']; } if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); //TODO 不要捲動到最上方 //$('html, body').animate({ scrollTop: 0 }, 'slow'); $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'update': function(key, quantity) { $.ajax({ url: 'index.php?route=checkout/cart/edit', type: 'post', data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1), dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'remove': function(key) { $.ajax({ url: 'index.php?route=checkout/cart/remove', type: 'post', data: 'key=' + key, dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'addAll': function(orders, callback) { $.ajax({ url: 'index.php?route=checkout/cart/addAll', type: 'post', data: 'orders=' + orders, dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { $('.alert, .text-danger').remove(); if (json['redirect']) { location = json['redirect']; } if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); //不要捲動到最上方 //$('html, body').animate({ scrollTop: 0 }, 'slow'); $('#cart > ul').load('index.php?route=common/cart/info ul li'); callback(true); } }, error: function(xhr, ajaxOptions, thrownError) { callback(false); alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'removeAll': function(callback) { $.ajax({ url: 'index.php?route=checkout/cart/removeAll', type: 'post', data: '', dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } callback(true); }, error: function(xhr, ajaxOptions, thrownError) { callback(false); alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } } var voucher = { 'add': function() { }, 'remove': function(key) { $.ajax({ url: 'index.php?route=checkout/cart/remove', type: 'post', data: 'key=' + key, dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } } var wishlist = { 'add': function(product_id) { $.ajax({ url: 'index.php?route=account/wishlist/add', type: 'post', data: 'product_id=' + product_id, dataType: 'json', success: function(json) { $('.alert').remove(); if (json['redirect']) { location = json['redirect']; } if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); } $('#wishlist-total span').html(json['total']); $('#wishlist-total').attr('title', json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'remove': function() { } } var compare = { 'add': function(product_id) { $.ajax({ url: 'index.php?route=product/compare/add', type: 'post', data: 'product_id=' + product_id, dataType: 'json', success: function(json) { $('.alert').remove(); if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); $('#compare-total').html(json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'remove': function() { } } /* Agree to Terms */ $(document).delegate('.agree', 'click', function(e) { e.preventDefault(); $('#modal-agree').remove(); var element = this; $.ajax({ url: $(element).attr('href'), type: 'get', dataType: 'html', success: function(data) { html = '<div id="modal-agree" class="modal">'; html += ' <div class="modal-dialog">'; html += ' <div class="modal-content">'; html += ' <div class="modal-header">'; html += ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'; html += ' <h4 class="modal-title">' + $(element).text() + '</h4>'; html += ' </div>'; html += ' <div class="modal-body">' + data + '</div>'; html += ' </div'; html += ' </div>'; html += '</div>'; $('body').append(html); $('#modal-agree').modal('show'); } }); }); // Autocomplete */ (function($) { $.fn.autocomplete = function(option) { return this.each(function() { this.timer = null; this.items = new Array(); $.extend(this, option); $(this).attr('autocomplete', 'off'); // Focus $(this).on('focus', function() { this.request(); }); // Blur $(this).on('blur', function() { setTimeout(function(object) { object.hide(); }, 200, this); }); // Keydown $(this).on('keydown', function(event) { switch(event.keyCode) { case 27: // escape this.hide(); break; default: this.request(); break; } }); // Click this.click = function(event) { event.preventDefault(); value = $(event.target).parent().attr('data-value'); if (value && this.items[value]) { this.select(this.items[value]); } } // Show this.show = function() { var pos = $(this).position(); $(this).siblings('ul.dropdown-menu').css({ top: pos.top + $(this).outerHeight(), left: pos.left }); $(this).siblings('ul.dropdown-menu').show(); } // Hide this.hide = function() { $(this).siblings('ul.dropdown-menu').hide(); } // Request this.request = function() { clearTimeout(this.timer); this.timer = setTimeout(function(object) { object.source($(object).val(), $.proxy(object.response, object)); }, 200, this); } // Response this.response = function(json) { html = ''; if (json.length) { for (i = 0; i < json.length; i++) { this.items[json[i]['value']] = json[i]; } for (i = 0; i < json.length; i++) { if (!json[i]['category']) { html += '<li data-value="' + json[i]['value'] + '"><a href="#">' + json[i]['label'] + '</a></li>'; } } // Get all the ones with a categories var category = new Array(); for (i = 0; i < json.length; i++) { if (json[i]['category']) { if (!category[json[i]['category']]) { category[json[i]['category']] = new Array(); category[json[i]['category']]['name'] = json[i]['category']; category[json[i]['category']]['item'] = new Array(); } category[json[i]['category']]['item'].push(json[i]); } } for (i in category) { html += '<li class="dropdown-header">' + category[i]['name'] + '</li>'; for (j = 0; j < category[i]['item'].length; j++) { html += '<li data-value="' + category[i]['item'][j]['value'] + '"><a href="#">&nbsp;&nbsp;&nbsp;' + category[i]['item'][j]['label'] + '</a></li>'; } } } if (html) { this.show(); } else { this.hide(); } $(this).siblings('ul.dropdown-menu').html(html); } $(this).after('<ul class="dropdown-menu"></ul>'); $(this).siblings('ul.dropdown-menu').delegate('a', 'click', $.proxy(this.click, this)); }); } })(window.jQuery);
atFriendly/opencart
upload/catalog/view/javascript/common.js
JavaScript
gpl-3.0
15,343
var globals_dup = [ [ "a", "globals.html", null ], [ "b", "globals_0x62.html", null ], [ "c", "globals_0x63.html", null ], [ "d", "globals_0x64.html", null ], [ "e", "globals_0x65.html", null ], [ "f", "globals_0x66.html", null ], [ "g", "globals_0x67.html", null ], [ "h", "globals_0x68.html", null ], [ "i", "globals_0x69.html", null ], [ "k", "globals_0x6b.html", null ], [ "l", "globals_0x6c.html", null ], [ "o", "globals_0x6f.html", null ], [ "p", "globals_0x70.html", null ], [ "r", "globals_0x72.html", null ], [ "s", "globals_0x73.html", null ], [ "u", "globals_0x75.html", null ], [ "v", "globals_0x76.html", null ], [ "x", "globals_0x78.html", null ] ];
gaganjyot/LibreDWG-API
doc/html/globals_dup.js
JavaScript
gpl-3.0
736
Vue.http.options.emulateJSON = true; var profile_status = new Vue({ el: '#profile-status', data: { isSuggestShow: 0, suggest: [ {text: 'Предложение оплаты услуг, вирт за деньги, проституция, мошенничество, шантаж, спам', style: 'bg_ored'}, {text: 'Фото из интернета, парень под видои девушки, вымышленные данные, обман, фейк', style: 'bg_ored'}, {text: 'Оскорбления, хамство, троллинг, грубые сообщения, жалобы на интим фото, провокации', style: 'bg_oyel'}, {text: 'Пишет всем подряд, игнорирует анкетные данные, гей пишет натуралам, рассылки', style: 'bg_oyel'}, {text: 'Ложно, отклоненные жалобы, причина не ясна, ссора, выяснение отношений', style: 'bg_ogrn'}, ], text: 'Статус не установлен', style: '', user: '', }, created: function () { this.user = $('#profile-status__text').data('user'); var text = $('#profile-status__text').text().trim(); if (text) { this.text = text; } }, mounted: function () { this.set_style(); }, methods: { variant: function (event) { this.isSuggestShow = true; }, post: function () { if (this.user) { this.$http.post('/userinfo/setcomm/', { id: this.user, text: this.text }); } }, save: function (i) { this.text = this.suggest[i].text; this.style = this.suggest[i].style; this.isSuggestShow = false; this.post(); }, set_style: function () { if (this.text == this.suggest[0].text) { this.style = this.suggest[0].style; }; if (this.text == this.suggest[1].text) { this.style = this.suggest[0].style; }; if (this.text == this.suggest[2].text) { this.style = this.suggest[2].style; }; if (this.text == this.suggest[3].text) { this.style = this.suggest[2].style; }; if (this.text == this.suggest[4].text) { this.style = this.suggest[4].style; }; } } });
4FortyTwo2/sources
javascript/admin/src/profile-status.js
JavaScript
gpl-3.0
2,644
/* Copyright (C) 2013 Bryan Hughes <bryan@theoreticalideations.com> This file is part of Aquarium Control. Aquarium Control is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aquarium Control is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Aquarium Control. If not, see <http://www.gnu.org/licenses/>. */ var path = require('path'), exec = require('child_process').exec, STATE_OFF = 'off', STATE_DAY = 'day', STATE_NIGHT = 'night', driverPath = path.join(__dirname, '..', '..', 'driver', 'driver.py'); function log(level, message) { process.send({ destination: 'master', type: 'log', data: { level: level, message: message } }); } exec(driverPath + ' off'); log('info', 'Controller started'); process.on('message', function (message) { if (message.type === 'lights.set') { process.send({ destination: 'master', type: 'log', data: { level: 'info', message: 'State change: ' + message.data } }); switch(message.data) { case STATE_OFF: exec(driverPath + ' off'); break; case STATE_DAY: exec(driverPath + ' day'); break; case STATE_NIGHT: exec(driverPath + ' night'); break; } } });
rakesh-mohanta/aquarium-control
server/src/controller.js
JavaScript
gpl-3.0
1,615
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * André Fiedler <fiedler dot andre a t gmail dot com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { var oop = require("pilot/oop"); var lang = require("pilot/lang"); var DocCommentHighlightRules = require("ace/mode/doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules; var PhpHighlightRules = function() { var builtinFunctions = lang.arrayToMap( ('abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|' + 'aggregate_methods_by_list|aggregate_methods_by_regexp|aggregate_properties|aggregate_properties_by_list|' + 'aggregate_properties_by_regexp|aggregation_info|apache_child_terminate|apache_get_modules|' + 'apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|' + 'apache_response_headers|apache_setenv|array|array_change_key_case|array_chunk|array_combine|' + 'array_count_values|array_diff|array_diff_assoc|array_diff_uassoc|array_fill|array_filter|array_flip|' + 'array_intersect|array_intersect_assoc|array_key_exists|array_keys|array_map|array_merge|' + 'array_merge_recursive|array_multisort|array_pad|array_pop|array_push|array_rand|array_reduce|' + 'array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|array_udiff_assoc|' + 'array_udiff_uassoc|array_unique|array_unshift|array_values|array_walk|arsort|ascii2ebcdic|asin|asinh|asort|' + 'aspell_check|aspell_check_raw|aspell_new|aspell_suggest|assert|assert_options|atan|atan2|atanh|' + 'base64_decode|base64_encode|base_convert|basename|bcadd|bccomp|bcdiv|bcmod|bcmul|bcpow|bcpowmod|bcscale|' + 'bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|bindtextdomain|bzclose|bzcompress|bzdecompress|bzerrno|' + 'bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|cal_days_in_month|cal_from_jd|cal_info|cal_to_jd|' + 'call_user_func|call_user_func_array|call_user_method|call_user_method_array|ccvs_add|ccvs_auth|ccvs_command|' + 'ccvs_count|ccvs_delete|ccvs_done|ccvs_init|ccvs_lookup|ccvs_new|ccvs_report|ccvs_return|ccvs_reverse|' + 'ccvs_sale|ccvs_status|ccvs_textvalue|ccvs_void|ceil|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|' + 'chroot|chunk_split|class_exists|clearstatcache|closedir|closelog|com|com_addref|com_get|com_invoke|' + 'com_isenum|com_load|com_load_typelib|com_propget|com_propput|com_propset|com_release|com_set|compact|' + 'connection_aborted|connection_status|connection_timeout|constant|convert_cyr_string|copy|cos|cosh|count|' + 'count_chars|cpdf_add_annotation|cpdf_add_outline|cpdf_arc|cpdf_begin_text|cpdf_circle|cpdf_clip|cpdf_close|' + 'cpdf_closepath|cpdf_closepath_fill_stroke|cpdf_closepath_stroke|cpdf_continue_text|cpdf_curveto|cpdf_end_text|' + 'cpdf_fill|cpdf_fill_stroke|cpdf_finalize|cpdf_finalize_page|cpdf_global_set_document_limits|cpdf_import_jpeg|' + 'cpdf_lineto|cpdf_moveto|cpdf_newpath|cpdf_open|cpdf_output_buffer|cpdf_page_init|cpdf_place_inline_image|' + 'cpdf_rect|cpdf_restore|cpdf_rlineto|cpdf_rmoveto|cpdf_rotate|cpdf_rotate_text|cpdf_save|cpdf_save_to_file|' + 'cpdf_scale|cpdf_set_action_url|cpdf_set_char_spacing|cpdf_set_creator|cpdf_set_current_page|cpdf_set_font|' + 'cpdf_set_font_directories|cpdf_set_font_map_file|cpdf_set_horiz_scaling|cpdf_set_keywords|cpdf_set_leading|' + 'cpdf_set_page_animation|cpdf_set_subject|cpdf_set_text_matrix|cpdf_set_text_pos|cpdf_set_text_rendering|' + 'cpdf_set_text_rise|cpdf_set_title|cpdf_set_viewer_preferences|cpdf_set_word_spacing|cpdf_setdash|cpdf_setflat|' + 'cpdf_setgray|cpdf_setgray_fill|cpdf_setgray_stroke|cpdf_setlinecap|cpdf_setlinejoin|cpdf_setlinewidth|' + 'cpdf_setmiterlimit|cpdf_setrgbcolor|cpdf_setrgbcolor_fill|cpdf_setrgbcolor_stroke|cpdf_show|cpdf_show_xy|' + 'cpdf_stringwidth|cpdf_stroke|cpdf_text|cpdf_translate|crack_check|crack_closedict|crack_getlastmessage|' + 'crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|ctype_graph|' + 'ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|curl_close|curl_errno|curl_error|' + 'curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|curl_multi_getcontent|' + 'curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_version|current|' + 'cybercash_base64_decode|cybercash_base64_encode|cybercash_decr|cybercash_encr|cyrus_authenticate|cyrus_bind|' + 'cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|' + 'dba_handlers|dba_insert|dba_key_split|dba_list|dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|' + 'dbase_add_record|dbase_close|dbase_create|dbase_delete_record|dbase_get_header_info|dbase_get_record|' + 'dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|dbase_replace_record|dblist|' + 'dbmclose|dbmdelete|dbmexists|dbmfetch|dbmfirstkey|dbminsert|dbmnextkey|dbmopen|dbmreplace|dbplus_add|dbplus_aql|' + 'dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|dbplus_flush|' + 'dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|' + 'dbplus_lockrel|dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|' + 'dbplus_resolve|dbplus_restorepos|dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|' + 'dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|' + 'dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|dbplus_update|dbplus_xlockrel|' + 'dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|dbx_sort|' + 'dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debugger_off|debugger_on|decbin|dechex|' + 'decoct|define|define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|' + 'dio_seek|dio_stat|dio_tcsetattr|dio_truncate|dio_write|dir|dirname|disk_free_space|disk_total_space|diskfreespace|' + 'dl|dngettext|dns_check_record|dns_get_mx|dns_get_record|domxml_new_doc|domxml_open_file|domxml_open_mem|' + 'domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|domxml_xslt_stylesheet_file|' + 'dotnet_load|doubleval|each|easter_date|easter_days|ebcdic2ascii|echo|empty|end|ereg|ereg_replace|eregi|' + 'eregi_replace|error_log|error_reporting|escapeshellarg|escapeshellcmd|eval|exec|exif_imagetype|exif_read_data|' + 'exif_thumbnail|exit|exp|explode|expm1|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|' + 'fam_monitor_collection|fam_monitor_directory|fam_monitor_file|fam_next_event|fam_open|fam_pending|' + 'fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|fbsql_blob_size|fbsql_change_user|' + 'fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|fbsql_create_db|' + 'fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|' + 'fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|' + 'fbsql_fetch_row|fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|' + 'fbsql_field_type|fbsql_free_result|fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|' + 'fbsql_list_fields|fbsql_list_tables|fbsql_next_result|fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|' + 'fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|fbsql_select_db|fbsql_set_lob_mode|' + 'fbsql_set_password|fbsql_set_transaction|fbsql_start_db|fbsql_stop_db|fbsql_tablename|fbsql_username|fbsql_warnings|' + 'fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|' + 'fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|fdf_get_status|fdf_get_value|' + 'fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|fdf_save_string|' + 'fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_opt|fdf_set_status|' + 'fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|' + 'fgetss|file|file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|' + 'fileowner|fileperms|filepro|filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|' + 'filepro_retrieve|filepro_rowcount|filesize|filetype|floatval|flock|floor|flush|fmod|fnmatch|fopen|fpassthru|fprintf|' + 'fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|' + 'ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|ftp_mdtm|ftp_mkdir|' + 'ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|' + 'ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|' + 'func_get_args|func_num_args|function_exists|fwrite|gd_info|get_browser|get_cfg_var|get_class|get_class_methods|' + 'get_class_vars|get_current_user|get_declared_classes|get_declared_interfaces|get_defined_constants|' + 'get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|get_html_translation_table|get_include_path|' + 'get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|get_meta_tags|get_object_vars|' + 'get_parent_class|get_required_files|get_resource_type|getallheaders|getcwd|getdate|getenv|gethostbyaddr|gethostbyname|' + 'gethostbynamel|getimagesize|getlastmod|getmxrr|getmygid|getmyinode|getmypid|getmyuid|getopt|getprotobyname|' + 'getprotobynumber|getrandmax|getrusage|getservbyname|getservbyport|gettext|gettimeofday|gettype|glob|gmdate|gmmktime|' + 'gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|' + 'gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_or|' + 'gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|' + 'gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_xor|gmstrftime|gregoriantojd|gzclose|gzcompress|gzdeflate|gzencode|gzeof|' + 'gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|' + 'header|headers_list|headers_sent|hebrev|hebrevc|hexdec|highlight_file|highlight_string|html_entity_decode|htmlentities|' + 'htmlspecialchars|http_build_query|hw_api_attribute|hw_api_content|hw_api_object|hw_array2objrec|hw_changeobject|' + 'hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|' + 'hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|' + 'hw_edittext|hw_error|hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|' + 'hw_getchildcollobj|hw_getchilddoccoll|hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|' + 'hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|' + 'hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|hw_incollections|hw_info|hw_inscoll|' + 'hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|hw_new_document|' + 'hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|' + 'hwapi_hgcsp|hypot|ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|' + 'ibase_blob_create|ibase_blob_echo|ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|' + 'ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|' + 'ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|ibase_field_info|ibase_free_event_handler|' + 'ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|ibase_name_result|ibase_num_fields|' + 'ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|ibase_rollback|ibase_rollback_ret|' + 'ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|ibase_trans|' + 'ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|' + 'iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|idate|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|' + 'ifx_close|ifx_connect|ifx_copy_blob|ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|' + 'ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|' + 'ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|' + 'ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|ifxus_open_slob|ifxus_read_slob|' + 'ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|image2wbmp|image_type_to_mime_type|imagealphablending|' + 'imageantialias|imagearc|imagechar|imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|' + 'imagecolorclosestalpha|imagecolorclosesthwb|imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|' + 'imagecolorresolve|imagecolorresolvealpha|imagecolorset|imagecolorsforindex|imagecolorstotal|imagecolortransparent|imagecopy|' + 'imagecopymerge|imagecopymergegray|imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|' + 'imagecreatefromgd2part|imagecreatefromgif|imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|' + 'imagecreatefromxbm|imagecreatefromxpm|imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|' + 'imagefilledellipse|imagefilledpolygon|imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|' + 'imageftbbox|imagefttext|imagegammacorrect|imagegd|imagegd2|imagegif|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|' + 'imageline|imageloadfont|imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepscopyfont|imagepsencodefont|imagepsextendfont|' + 'imagepsfreefont|imagepsloadfont|imagepsslantfont|imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|' + 'imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|' + 'imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|' + 'imap_bodystruct|imap_check|imap_clearflag_full|imap_close|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|' + 'imap_expunge|imap_fetch_overview|imap_fetchbody|imap_fetchheader|imap_fetchstructure|imap_get_quota|imap_get_quotaroot|' + 'imap_getacl|imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|' + 'imap_listmailbox|imap_listscan|imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|' + 'imap_mailboxmsginfo|imap_mime_header_decode|imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|' + 'imap_renamemailbox|imap_reopen|imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_scanmailbox|' + 'imap_search|imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|' + 'imap_uid|imap_undelete|imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implode|import_request_variables|in_array|' + 'ingres_autocommit|ingres_close|ingres_commit|ingres_connect|ingres_fetch_array|ingres_fetch_object|ingres_fetch_row|' + 'ingres_field_length|ingres_field_name|ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|' + 'ingres_num_fields|ingres_num_rows|ingres_pconnect|ingres_query|ingres_rollback|ini_alter|ini_get|ini_get_all|ini_restore|' + 'ini_set|intval|ip2long|iptcembed|iptcparse|ircg_channel_mode|ircg_disconnect|ircg_fetch_error_msg|ircg_get_username|' + 'ircg_html_encode|ircg_ignore_add|ircg_ignore_del|ircg_invite|ircg_is_conn_alive|ircg_join|ircg_kick|ircg_list|' + 'ircg_lookup_format_messages|ircg_lusers|ircg_msg|ircg_nick|ircg_nickname_escape|ircg_nickname_unescape|ircg_notice|ircg_oper|' + 'ircg_part|ircg_pconnect|ircg_register_format_messages|ircg_set_current|ircg_set_file|ircg_set_on_die|ircg_topic|ircg_who|' + 'ircg_whois|is_a|is_array|is_bool|is_callable|is_dir|is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|' + 'is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|is_readable|is_real|is_resource|is_scalar|is_soap_fault|' + 'is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isset|java_last_exception_clear|java_last_exception_get|' + 'jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|juliantojd|key|' + 'krsort|ksort|lcg_value|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|ldap_connect|ldap_count_entries|ldap_delete|' + 'ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|ldap_first_entry|ldap_first_reference|' + 'ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|ldap_get_values_len|ldap_list|' + 'ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|ldap_next_reference|' + 'ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_search|ldap_set_option|ldap_set_rebind_proc|ldap_sort|' + 'ldap_start_tls|ldap_t61_to_8859|ldap_unbind|levenshtein|link|linkinfo|list|localeconv|localtime|log|log10|log1p|long2ip|lstat|' + 'ltrim|lzf_compress|lzf_decompress|lzf_optimized_for|mail|mailparse_determine_best_xfer_encoding|mailparse_msg_create|' + 'mailparse_msg_extract_part|mailparse_msg_extract_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|' + 'mailparse_msg_get_structure|mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|' + 'mailparse_stream_encode|mailparse_uudecode_all|main|max|mb_convert_case|mb_convert_encoding|mb_convert_kana|mb_convert_variables|' + 'mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|mb_encode_numericentity|' + 'mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|mb_ereg_search_getregs|mb_ereg_search_init|' + 'mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|mb_get_info|mb_http_input|mb_http_output|' + 'mb_internal_encoding|mb_language|mb_output_handler|mb_parse_str|mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|' + 'mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_strlen|mb_strpos|mb_strrpos|mb_strtolower|mb_strtoupper|mb_strwidth|' + 'mb_substitute_character|mb_substr|mb_substr_count|mcal_append_event|mcal_close|mcal_create_calendar|mcal_date_compare|' + 'mcal_date_valid|mcal_day_of_week|mcal_day_of_year|mcal_days_in_month|mcal_delete_calendar|mcal_delete_event|' + 'mcal_event_add_attribute|mcal_event_init|mcal_event_set_alarm|mcal_event_set_category|mcal_event_set_class|' + 'mcal_event_set_description|mcal_event_set_end|mcal_event_set_recur_daily|mcal_event_set_recur_monthly_mday|' + 'mcal_event_set_recur_monthly_wday|mcal_event_set_recur_none|mcal_event_set_recur_weekly|mcal_event_set_recur_yearly|' + 'mcal_event_set_start|mcal_event_set_title|mcal_expunge|mcal_fetch_current_stream_event|mcal_fetch_event|mcal_is_leap_year|' + 'mcal_list_alarms|mcal_list_events|mcal_next_recurrence|mcal_open|mcal_popen|mcal_rename_calendar|mcal_reopen|mcal_snooze|' + 'mcal_store_event|mcal_time_valid|mcal_week_of_year|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|' + 'mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|' + 'mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|' + 'mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|' + 'mcrypt_get_block_size|mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|' + 'mcrypt_module_close|mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|' + 'mcrypt_module_is_block_algorithm|mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|' + 'mcrypt_module_self_test|mcrypt_ofb|mcve_adduser|mcve_adduserarg|mcve_bt|mcve_checkstatus|mcve_chkpwd|mcve_chngpwd|' + 'mcve_completeauthorizations|mcve_connect|mcve_connectionerror|mcve_deleteresponse|mcve_deletetrans|mcve_deleteusersetup|' + 'mcve_deluser|mcve_destroyconn|mcve_destroyengine|mcve_disableuser|mcve_edituser|mcve_enableuser|mcve_force|mcve_getcell|' + 'mcve_getcellbynum|mcve_getcommadelimited|mcve_getheader|mcve_getuserarg|mcve_getuserparam|mcve_gft|mcve_gl|mcve_gut|mcve_initconn|' + 'mcve_initengine|mcve_initusersetup|mcve_iscommadelimited|mcve_liststats|mcve_listusers|mcve_maxconntimeout|mcve_monitor|' + 'mcve_numcolumns|mcve_numrows|mcve_override|mcve_parsecommadelimited|mcve_ping|mcve_preauth|mcve_preauthcompletion|mcve_qc|' + 'mcve_responseparam|mcve_return|mcve_returncode|mcve_returnstatus|mcve_sale|mcve_setblocking|mcve_setdropfile|mcve_setip|' + 'mcve_setssl|mcve_setssl_files|mcve_settimeout|mcve_settle|mcve_text_avs|mcve_text_code|mcve_text_cv|mcve_transactionauth|' + 'mcve_transactionavs|mcve_transactionbatch|mcve_transactioncv|mcve_transactionid|mcve_transactionitem|mcve_transactionssent|' + 'mcve_transactiontext|mcve_transinqueue|mcve_transnew|mcve_transparam|mcve_transsend|mcve_ub|mcve_uwait|mcve_verifyconnection|' + 'mcve_verifysslcert|mcve_void|md5|md5_file|mdecrypt_generic|memory_get_usage|metaphone|method_exists|mhash|mhash_count|' + 'mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_setcubicthreshold|ming_setscale|' + 'ming_useswfversion|mkdir|mktime|money_format|move_uploaded_file|msession_connect|msession_count|msession_create|msession_destroy|' + 'msession_disconnect|msession_find|msession_get|msession_get_array|msession_getdata|msession_inc|msession_list|msession_listvar|' + 'msession_lock|msession_plugin|msession_randstr|msession_set|msession_set_array|msession_setdata|msession_timeout|msession_uniq|' + 'msession_unlock|msg_get_queue|msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql|msql_affected_rows|' + 'msql_close|msql_connect|msql_create_db|msql_createdb|msql_data_seek|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|' + 'msql_fetch_field|msql_fetch_object|msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|' + 'msql_field_type|msql_fieldflags|msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|' + 'msql_list_fields|msql_list_tables|msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|' + 'msql_result|msql_select_db|msql_tablename|mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|' + 'mssql_fetch_assoc|mssql_fetch_batch|mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|' + 'mssql_field_seek|mssql_field_type|mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|' + 'mssql_min_error_severity|mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|' + 'mssql_result|mssql_rows_affected|mssql_select_db|mt_getrandmax|mt_rand|mt_srand|muscat_close|muscat_get|muscat_give|muscat_setup|' + 'muscat_setup_net|mysql_affected_rows|mysql_change_user|mysql_client_encoding|mysql_close|mysql_connect|mysql_create_db|' + 'mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|' + 'mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|' + 'mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|' + 'mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|' + 'mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|' + 'mysql_select_db|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli_affected_rows|mysqli_autocommit|' + 'mysqli_bind_param|mysqli_bind_result|mysqli_change_user|mysqli_character_set_name|mysqli_client_encoding|mysqli_close|mysqli_commit|' + 'mysqli_connect|mysqli_connect_errno|mysqli_connect_error|mysqli_data_seek|mysqli_debug|mysqli_disable_reads_from_master|' + 'mysqli_disable_rpl_parse|mysqli_dump_debug_info|mysqli_embedded_connect|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|' + 'mysqli_errno|mysqli_error|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_fetch_array|mysqli_fetch_assoc|mysqli_fetch_field|' + 'mysqli_fetch_field_direct|mysqli_fetch_fields|mysqli_fetch_lengths|mysqli_fetch_object|mysqli_fetch_row|mysqli_field_count|' + 'mysqli_field_seek|mysqli_field_tell|mysqli_free_result|mysqli_get_client_info|mysqli_get_client_version|mysqli_get_host_info|' + 'mysqli_get_metadata|mysqli_get_proto_info|mysqli_get_server_info|mysqli_get_server_version|mysqli_info|mysqli_init|mysqli_insert_id|' + 'mysqli_kill|mysqli_master_query|mysqli_more_results|mysqli_multi_query|mysqli_next_result|mysqli_num_fields|mysqli_num_rows|' + 'mysqli_options|mysqli_param_count|mysqli_ping|mysqli_prepare|mysqli_query|mysqli_real_connect|mysqli_real_escape_string|' + 'mysqli_real_query|mysqli_report|mysqli_rollback|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|mysqli_select_db|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_server_end|mysqli_server_init|mysqli_set_opt|mysqli_sqlstate|mysqli_ssl_set|mysqli_stat|' + 'mysqli_stmt_init|mysqli_stmt_affected_rows|mysqli_stmt_bind_param|mysqli_stmt_bind_result|mysqli_stmt_close|mysqli_stmt_data_seek|' + 'mysqli_stmt_errno|mysqli_stmt_error|mysqli_stmt_execute|mysqli_stmt_fetch|mysqli_stmt_free_result|mysqli_stmt_num_rows|' + 'mysqli_stmt_param_count|mysqli_stmt_prepare|mysqli_stmt_result_metadata|mysqli_stmt_send_long_data|mysqli_stmt_sqlstate|' + 'mysqli_stmt_store_result|mysqli_store_result|mysqli_thread_id|mysqli_thread_safe|mysqli_use_result|mysqli_warning_count|natcasesort|' + 'natsort|ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|' + 'ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|' + 'ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|' + 'ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|' + 'ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|' + 'ncurses_filter|ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|' + 'ncurses_has_colors|ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|' + 'ncurses_init_color|ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|' + 'ncurses_keyok|ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|' + 'ncurses_move|ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|' + 'ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|' + 'ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|' + 'ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|' + 'ncurses_putp|ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|' + 'ncurses_resetty|ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|' + 'ncurses_slk_attr|ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|' + 'ncurses_slk_noutrefresh|ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|' + 'ncurses_start_color|ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|' + 'ncurses_ungetmouse|ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|' + 'ncurses_vline|ncurses_waddch|ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|' + 'ncurses_wcolor_set|ncurses_werase|ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|' + 'ncurses_wrefresh|ncurses_wstandend|ncurses_wstandout|ncurses_wvline|next|ngettext|nl2br|nl_langinfo|notes_body|notes_copy_db|' + 'notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|' + 'notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|number_format|' + 'ob_clean|ob_end_clean|ob_end_flush|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|' + 'ob_gzhandler|ob_iconv_handler|ob_implicit_flush|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_by_name|oci_cancel|oci_close|' + 'oci_commit|oci_connect|oci_define_by_name|oci_error|oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|' + 'oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|' + 'oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_copy|oci_lob_is_equal|oci_new_collection|oci_new_connect|' + 'oci_new_cursor|oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|' + 'oci_server_version|oci_set_prefetch|oci_statement_type|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|' + 'ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|' + 'ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|' + 'ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|' + 'ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|' + 'ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|octdec|odbc_autocommit|odbc_binmode|' + 'odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|odbc_data_source|odbc_do|odbc_error|' + 'odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|odbc_fetch_row|odbc_field_len|odbc_field_name|' + 'odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|' + 'odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|' + 'odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|odbc_statistics|odbc_tableprivileges|odbc_tables|opendir|' + 'openlog|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_new|openssl_csr_sign|openssl_error_string|openssl_free_key|' + 'openssl_get_privatekey|openssl_get_publickey|openssl_open|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|' + 'openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_get_private|openssl_pkey_get_public|openssl_pkey_new|' + 'openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|openssl_seal|openssl_sign|openssl_verify|' + 'openssl_x509_check_private_key|openssl_x509_checkpurpose|openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|' + 'openssl_x509_parse|openssl_x509_read|ora_bind|ora_close|ora_columnname|ora_columnsize|ora_columntype|ora_commit|ora_commitoff|' + 'ora_commiton|ora_do|ora_error|ora_errorcode|ora_exec|ora_fetch|ora_fetch_into|ora_getcolumn|ora_logoff|ora_logon|ora_numcols|' + 'ora_numrows|ora_open|ora_parse|ora_plogon|ora_rollback|ord|output_add_rewrite_var|output_reset_rewrite_vars|overload|ovrimos_close|' + 'ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|ovrimos_field_len|' + 'ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|ovrimos_num_rows|' + 'ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parse_ini_file|parse_str|parse_url|passthru|pathinfo|pclose|' + 'pcntl_alarm|pcntl_exec|pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|' + 'pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|' + 'pdf_add_locallink|pdf_add_note|pdf_add_outline|pdf_add_pdflink|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|' + 'pdf_begin_page|pdf_begin_pattern|pdf_begin_template|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|' + 'pdf_closepath|pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_curveto|pdf_delete|pdf_end_page|' + 'pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|pdf_fill_stroke|pdf_findfont|pdf_get_buffer|pdf_get_font|pdf_get_fontname|' + 'pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|' + 'pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_initgraphics|pdf_lineto|pdf_makespotcolor|pdf_moveto|pdf_new|pdf_open|' + 'pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|' + 'pdf_open_pdi_page|pdf_open_png|pdf_open_tiff|pdf_place_image|pdf_place_pdi_page|pdf_rect|pdf_restore|pdf_rotate|pdf_save|' + 'pdf_scale|pdf_set_border_color|pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_font|' + 'pdf_set_horiz_scaling|pdf_set_info|pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|' + 'pdf_set_info_title|pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|' + 'pdf_set_value|pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|' + 'pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|' + 'pdf_setrgbcolor_stroke|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|pdf_translate|pfpro_cleanup|pfpro_init|' + 'pfpro_process|pfpro_process_raw|pfpro_version|pfsockopen|pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|' + 'pg_connection_busy|pg_connection_reset|pg_connection_status|pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|' + 'pg_escape_bytea|pg_escape_string|pg_fetch_all|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|' + 'pg_field_is_null|pg_field_name|pg_field_num|pg_field_prtlen|pg_field_size|pg_field_type|pg_free_result|pg_get_notify|pg_get_pid|' + 'pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|' + 'pg_lo_open|pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|' + 'pg_options|pg_pconnect|pg_ping|pg_port|pg_put_line|pg_query|pg_result_error|pg_result_seek|pg_result_status|pg_select|pg_send_query|' + 'pg_set_client_encoding|pg_trace|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|php_ini_scanned_files|php_logo_guid|php_sapi_name|' + 'php_uname|phpcredits|phpinfo|phpversion|pi|png2wbmp|popen|pos|posix_ctermid|posix_get_last_error|posix_getcwd|posix_getegid|' + 'posix_geteuid|posix_getgid|posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|' + 'posix_getppid|posix_getpwnam|posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_isatty|posix_kill|posix_mkfifo|' + 'posix_setegid|posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|' + 'posix_uname|pow|preg_grep|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|' + 'printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|' + 'printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|' + 'printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|' + 'printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|' + 'printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|' + 'pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|pspell_config_ignore|' + 'pspell_config_mode|pspell_config_personal|pspell_config_repl|pspell_config_runtogether|pspell_config_save_repl|pspell_new|' + 'pspell_new_config|pspell_new_personal|pspell_save_wordlist|pspell_store_replacement|pspell_suggest|putenv|qdom_error|qdom_tree|' + 'quoted_printable_decode|quotemeta|rad2deg|rand|range|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|' + 'readline_add_history|readline_clear_history|readline_completion_function|readline_info|readline_list_history|readline_read_history|' + 'readline_write_history|readlink|realpath|recode|recode_file|recode_string|register_shutdown_function|register_tick_function|rename|' + 'reset|restore_error_handler|restore_include_path|rewind|rewinddir|rmdir|round|rsort|rtrim|scandir|sem_acquire|sem_get|sem_release|' + 'sem_remove|serialize|sesam_affected_rows|sesam_commit|sesam_connect|sesam_diagnostic|sesam_disconnect|sesam_errormsg|sesam_execimm|' + 'sesam_fetch_array|sesam_fetch_result|sesam_fetch_row|sesam_field_array|sesam_field_name|sesam_free_result|sesam_num_fields|sesam_query|' + 'sesam_rollback|sesam_seek_row|sesam_settransaction|session_cache_expire|session_cache_limiter|session_commit|session_decode|' + 'session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|' + 'session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|' + 'session_unregister|session_unset|session_write_close|set_error_handler|set_file_buffer|set_include_path|set_magic_quotes_runtime|' + 'set_time_limit|setcookie|setlocale|setrawcookie|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_put_var|' + 'shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|similar_text|' + 'simplexml_import_dom|simplexml_load_file|simplexml_load_string|sin|sinh|sizeof|sleep|snmp_get_quick_print|snmp_set_quick_print|' + 'snmpget|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|' + 'socket_create|socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|' + 'socket_iovec_add|socket_iovec_alloc|socket_iovec_delete|socket_iovec_fetch|socket_iovec_free|socket_iovec_set|socket_last_error|' + 'socket_listen|socket_read|socket_readv|socket_recv|socket_recvfrom|socket_recvmsg|socket_select|socket_send|socket_sendmsg|' + 'socket_sendto|socket_set_block|socket_set_blocking|socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|' + 'socket_strerror|socket_write|socket_writev|sort|soundex|split|spliti|sprintf|sql_regcase|sqlite_array_query|sqlite_busy_timeout|' + 'sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|sqlite_create_function|sqlite_current|sqlite_error_string|' + 'sqlite_escape_string|sqlite_fetch_array|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|sqlite_has_more|sqlite_last_error|' + 'sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|' + 'sqlite_query|sqlite_rewind|sqlite_seek|sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqrt|srand|sscanf|' + 'stat|str_ireplace|str_pad|str_repeat|str_replace|str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|' + 'strcspn|stream_context_create|stream_context_get_options|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|' + 'stream_filter_append|stream_filter_prepend|stream_filter_register|stream_get_contents|stream_get_filters|stream_get_line|' + 'stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_register_wrapper|stream_select|stream_set_blocking|' + 'stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_get_name|stream_socket_recvfrom|' + 'stream_socket_sendto|stream_socket_server|stream_wrapper_register|strftime|strip_tags|stripcslashes|stripos|stripslashes|stristr|' + 'strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpos|strrchr|strrev|strripos|strrpos|strspn|strstr|strtok|strtolower|strtotime|' + 'strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|swf_actiongeturl|swf_actiongotoframe|swf_actiongotolabel|' + 'swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|swf_actiontogglequality|swf_actionwaitforframe|' + 'swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|swf_defineline|swf_definepoly|swf_definerect|' + 'swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|swf_fontslant|swf_fonttracking|swf_getbitmapinfo|' + 'swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|swf_nextid|swf_oncondition|swf_openfile|swf_ortho|' + 'swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|swf_pushmatrix|swf_removeobject|swf_rotate|' + 'swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|swf_shapefillbitmapclip|swf_shapefillbitmaptile|' + 'swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|swf_showframe|swf_startbutton|swf_startdoaction|' + 'swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|swfbitmap|swfbutton|swfbutton_keypress|' + 'swfdisplayitem|swffill|swffont|swfgradient|swfmorph|swfmovie|swfshape|swfsprite|swftext|swftextfield|sybase_affected_rows|sybase_close|' + 'sybase_connect|sybase_data_seek|sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|' + 'sybase_fetch_row|sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|' + 'sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|' + 'sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|syslog|system|tan|tanh|tcpwrap_check|tempnam|textdomain|' + 'tidy_access_count|tidy_clean_repair|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_body|tidy_get_config|tidy_get_error_buffer|' + 'tidy_get_head|tidy_get_html|tidy_get_html_ver|tidy_get_output|tidy_get_release|tidy_get_root|tidy_get_status|tidy_getopt|tidy_is_xhtml|' + 'tidy_is_xml|tidy_load_config|tidy_parse_file|tidy_parse_string|tidy_repair_file|tidy_repair_string|tidy_reset_config|tidy_save_config|' + 'tidy_set_encoding|tidy_setopt|tidy_warning_count|time|tmpfile|token_get_all|token_name|touch|trigger_error|trim|uasort|ucfirst|ucwords|' + 'udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|udm_check_stored|' + 'udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|udm_free_res|' + 'udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|uksort|umask|' + 'uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|urldecode|urlencode|user_error|usleep|usort|utf8_decode|' + 'utf8_encode|var_dump|var_export|variant|version_compare|virtual|vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|' + 'vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|vpopmail_alias_del|vpopmail_alias_del_domain|' + 'vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|vpopmail_del_domain_ex|vpopmail_del_user|' + 'vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|w32api_init_dtype|w32api_invoke_function|' + 'w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|wddx_packet_start|wddx_serialize_value|' + 'wddx_serialize_vars|wordwrap|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|xdiff_file_patch|xdiff_file_patch_binary|' + 'xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xml_error_string|' + 'xml_get_current_byte_index|xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|' + 'xml_parser_create|xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|' + 'xml_set_default_handler|xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|' + 'xml_set_notation_decl_handler|xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|' + 'xml_set_unparsed_entity_decl_handler|xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|' + 'xmlrpc_parse_method_descriptions|xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|' + 'xmlrpc_server_destroy|xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xpath_eval|' + 'xpath_eval_expression|xpath_new_context|xptr_eval|xptr_new_context|xsl_xsltprocessor_get_parameter|xsl_xsltprocessor_has_exslt_support|' + 'xsl_xsltprocessor_import_stylesheet|xsl_xsltprocessor_register_php_functions|xsl_xsltprocessor_remove_parameter|' + 'xsl_xsltprocessor_set_parameter|xsl_xsltprocessor_transform_to_doc|xsl_xsltprocessor_transform_to_uri|xsl_xsltprocessor_transform_to_xml|' + 'xslt_create|xslt_errno|xslt_error|xslt_free|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|' + 'xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|' + 'yaz_close|yaz_connect|yaz_database|yaz_element|yaz_errno|yaz_error|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|' + 'yaz_range|yaz_record|yaz_scan|yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|' + 'yp_err_string|yp_errno|yp_first|yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_version|zip_close|' + 'zip_entry_close|zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|' + 'zip_open|zip_read|zlib_get_coding_type').split('|') ); var keywords = lang.arrayToMap( ('abstract|and|array|as|break|case|catch|cfunction|class|clone|const|continue|declare|default|die|do|' + 'else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|final|for|foreach|function|' + 'include|include_once|global|goto|if|implements|interface|instanceof|namespace|new|old_function|or|' + 'private|protected|public|return|require|require_once|static|switch|throw|try|use|var|while|xor').split('|') ); var builtinConstants = lang.arrayToMap( ('true|false|null|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__CLASS__').split('|') ); var builtinVariables = lang.arrayToMap( ('$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|' + '$http_response_header|$argc|$argv').split('|') ); var futureReserved = lang.arrayToMap([]); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "support", // php open tag regex : "<\\?(?:php|\\=)" }, { token : "support", // php close tag regex : "\\?>" }, { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", regex : "#.*$" }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", // constants regex : "\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|" + "ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|" + "HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|" + "L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|" + "VERSION))|__COMPILER_HALT_OFFSET__)\\b" }, { token : "constant.language", // constants regex : "\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|" + "SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|" + "O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|" + "R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|" + "YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|" + "ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|" + "T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|" + "HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|" + "I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|" + "O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|" + "L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|" + "M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|" + "OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|" + "T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else if(value.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|self|parent)$/)) return "variable"; return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; oop.inherits(PhpHighlightRules, TextHighlightRules); exports.PhpHighlightRules = PhpHighlightRules; });
jeremyhahn/AgilePHP
studio/components/ace/mode/php_highlight_rules.js
JavaScript
gpl-3.0
62,026
function OpenReportOperations() { $("#report-operations-div").show(); $("#page-operations-div").hide(); $("#events-operations-div").hide(); $("#editandsave-operations-div").hide(); $("#report-operations-li").addClass('active'); $('#page-operations-li').removeClass('active'); $('#events-operations-li').removeClass('active'); $('#editandsave-operations-li').removeClass('active'); $("#report-operations-div .function-ul li.active").click() $("#selected-catogory-button").html("Report operations"); } function OpenPageOperations() { $("#page-operations-div").show(); $("#report-operations-div").hide(); $("#events-operations-div").hide(); $("#editandsave-operations-div").hide(); $("#page-operations-li").addClass('active'); $('#report-operations-li').removeClass('active'); $('#events-operations-li').removeClass('active'); $('#editandsave-operations-li').removeClass('active'); $("#page-operations-div .function-ul li.active").click(); $("#selected-catogory-button").html("Page operations"); } function OpenEventOperations() { $("#page-operations-div").hide(); $("#report-operations-div").hide(); $("#events-operations-div").show(); $("#editandsave-operations-div").hide(); $("#page-operations-li").removeClass('active'); $('#report-operations-li').removeClass('active'); $('#events-operations-li').addClass('active'); $('#editandsave-operations-li').removeClass('active'); $("#events-operations-div .function-ul li.active").click(); $("#selected-catogory-button").html("Events Listener"); } function OpenEditAndSaveOperations() { $("#page-operations-div").hide(); $("#report-operations-div").hide(); $("#events-operations-div").hide(); $("#editandsave-operations-div").show(); $("#page-operations-li").removeClass('active'); $('#report-operations-li').removeClass('active'); $('#events-operations-li').removeClass('active'); $('#editandsave-operations-li').addClass('active'); $("#editandsave-operations-div .function-ul li.active").click(); $("#selected-catogory-button").html("Edit and save operations"); } function SetToggleHandler(devId) { var selector = "#" + devId + " .function-ul li"; $(selector).each(function(index, li) { $(li).click(function() { $(selector).removeClass('active'); $(li).addClass('active'); }); }); }
CCAFS/MARLO
marlo-web/src/main/webapp/global/bower_components/powerbi-client/demo/code-demo/scripts/step_interact.js
JavaScript
gpl-3.0
2,466
window.jQuery = window.$ = require('jquery'); require('bootstrap'); var angular = require('angular'); var uirouter = require('angular-ui-router'); var uibootstrap = require('angular-ui-bootstrap'); var fileupload = require('ng-file-upload'); //TODO pretify these uris require('./css/main.css'); require('./css/theme.css'); require('./node_modules/bootstrap/dist/css/bootstrap.min.css'); require('./node_modules/bootstrap/dist/css/bootstrap-theme.min.css'); require('./node_modules/font-awesome/css/font-awesome.min.css'); angular.module('openstore', [uirouter, uibootstrap, fileupload]) .config(function($stateProvider, $urlRouterProvider, $locationProvider, $compileProvider) { $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); $stateProvider.state('main', { url: '/', templateUrl: '/app/partials/main.html', }) .state('docs', { url: '/docs', templateUrl: '/app/partials/docs.html', controller: 'docsCtrl' }) .state('submit', { url: '/submit', templateUrl: '/app/partials/submit.html', controller: 'submitCtrl' }) .state('apps', { url: '/apps', templateUrl: '/app/partials/apps.html', controller: 'appsCtrl' }) .state('app', { url: '/app/:name', templateUrl: '/app/partials/app.html', controller: 'appsCtrl' }) .state('manage', { url: '/manage', templateUrl: '/app/partials/manage.html', controller: 'manageCtrl' }); $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|scope|openstore):/); }) .controller('indexCtrl', require('./app/controllers/indexCtrl')) .controller('appsCtrl', require('./app/controllers/appsCtrl')) .controller('manageCtrl', require('./app/controllers/manageCtrl')) .controller('submitCtrl', require('./app/controllers/submitCtrl')) .controller('docsCtrl', require('./app/controllers/docsCtrl')) .directive('ngContent', require('./app/directives/ngContent')) .directive('types', require('./app/directives/types')) .filter('bytes', require('./app/filters/bytes')) .filter('versionFix', require('./app/filters/versionFix')) .filter('nl2br', require('./app/filters/nl2br')) .factory('api', require('./app/services/api')) .factory('info', require('./app/services/info'));
mariogrip/openappstore-web
www/app.js
JavaScript
gpl-3.0
2,324
/** @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ import"../iron-iconset-svg.js";import{html as c}from"../../polymer/lib/utils/html-tag.js";const t=c`<iron-iconset-svg name="svg-sample-icons" size="100"> <svg> <defs> <g id="codepen"> <path class="outer-ring" d="M50,0C22.385,0,0,22.385,0,50c0,27.615,22.385,50,50,50c27.614,0,50-22.385,50-50C100,22.385,77.615,0,50,0z M50,91.789 C26.958,91.789,8.212,73.042,8.212,50C8.212,26.958,26.958,8.212,50,8.212c23.042,0,41.788,18.747,41.788,41.789 C91.788,73.042,73.042,91.789,50,91.789z"></path> <path class="inner-logo" d="M80.893,40.234c-0.006-0.039-0.016-0.076-0.022-0.115c-0.013-0.075-0.027-0.15-0.046-0.223 c-0.012-0.044-0.028-0.086-0.042-0.128c-0.021-0.065-0.042-0.13-0.068-0.193c-0.018-0.044-0.039-0.088-0.059-0.13 c-0.028-0.06-0.057-0.119-0.09-0.175c-0.024-0.042-0.051-0.083-0.076-0.124c-0.036-0.055-0.073-0.109-0.112-0.161 c-0.029-0.039-0.06-0.078-0.091-0.115c-0.042-0.049-0.086-0.098-0.132-0.143c-0.035-0.036-0.069-0.072-0.106-0.104 c-0.049-0.044-0.099-0.086-0.15-0.127c-0.04-0.031-0.079-0.062-0.12-0.091c-0.016-0.01-0.029-0.023-0.044-0.033L51.474,19.531 c-0.893-0.595-2.055-0.595-2.947,0L20.267,38.371c-0.015,0.01-0.028,0.023-0.044,0.033c-0.042,0.029-0.081,0.06-0.12,0.091 c-0.052,0.041-0.102,0.083-0.15,0.127c-0.037,0.032-0.071,0.068-0.106,0.104c-0.046,0.045-0.09,0.094-0.132,0.143 c-0.031,0.038-0.062,0.077-0.092,0.115c-0.039,0.052-0.076,0.106-0.111,0.161c-0.027,0.041-0.052,0.082-0.076,0.124 c-0.033,0.057-0.062,0.115-0.09,0.175c-0.021,0.042-0.042,0.086-0.06,0.13c-0.026,0.063-0.047,0.128-0.068,0.193 c-0.014,0.042-0.029,0.084-0.042,0.128c-0.02,0.073-0.032,0.148-0.046,0.223c-0.006,0.039-0.016,0.076-0.021,0.115 c-0.016,0.114-0.024,0.229-0.024,0.346V59.42c0,0.117,0.009,0.233,0.024,0.348c0.005,0.038,0.015,0.077,0.021,0.114 c0.014,0.075,0.027,0.149,0.046,0.223c0.012,0.043,0.028,0.086,0.042,0.128c0.021,0.065,0.042,0.13,0.068,0.195 c0.018,0.044,0.039,0.086,0.06,0.129c0.028,0.06,0.058,0.118,0.09,0.177c0.024,0.041,0.049,0.082,0.076,0.122 c0.035,0.056,0.072,0.109,0.111,0.161c0.029,0.041,0.061,0.078,0.092,0.115c0.042,0.049,0.086,0.098,0.132,0.144 c0.035,0.036,0.069,0.071,0.106,0.104c0.048,0.044,0.099,0.086,0.15,0.127c0.039,0.031,0.078,0.062,0.12,0.091 c0.016,0.01,0.029,0.023,0.044,0.032l28.259,18.84c0.446,0.297,0.96,0.447,1.474,0.447c0.513,0,1.027-0.149,1.473-0.447 l28.259-18.84c0.015-0.009,0.028-0.022,0.044-0.032c0.042-0.029,0.081-0.06,0.12-0.091c0.051-0.041,0.102-0.083,0.15-0.127 c0.037-0.033,0.071-0.068,0.106-0.104c0.046-0.046,0.09-0.095,0.132-0.144c0.031-0.037,0.062-0.075,0.091-0.115 c0.04-0.052,0.076-0.105,0.112-0.161c0.025-0.041,0.051-0.081,0.076-0.122c0.033-0.059,0.062-0.117,0.09-0.177 c0.02-0.042,0.041-0.085,0.059-0.129c0.026-0.065,0.047-0.13,0.068-0.195c0.014-0.042,0.03-0.085,0.042-0.128 c0.02-0.074,0.033-0.148,0.046-0.223c0.006-0.037,0.016-0.076,0.022-0.114c0.014-0.115,0.023-0.231,0.023-0.348V40.581 C80.916,40.464,80.907,40.348,80.893,40.234z M52.657,26.707l20.817,13.877l-9.298,6.221l-11.519-7.706V26.707z M47.343,26.707 v12.393l-11.518,7.706l-9.299-6.221L47.343,26.707z M24.398,45.554L31.046,50l-6.648,4.446V45.554z M47.343,73.294L26.525,59.417 l9.299-6.219l11.518,7.704V73.294z M50,56.286L40.603,50L50,43.715L59.397,50L50,56.286z M52.657,73.294V60.902l11.519-7.704 l9.298,6.219L52.657,73.294z M75.602,54.447L68.955,50l6.647-4.446V54.447z"></path> </g> <path id="twitter" d="M100.001,17.942c-3.681,1.688-7.633,2.826-11.783,3.339 c4.236-2.624,7.49-6.779,9.021-11.73c-3.965,2.432-8.354,4.193-13.026,5.146C80.47,10.575,75.138,8,69.234,8 c-11.33,0-20.518,9.494-20.518,21.205c0,1.662,0.183,3.281,0.533,4.833c-17.052-0.884-32.168-9.326-42.288-22.155 c-1.767,3.133-2.778,6.773-2.778,10.659c0,7.357,3.622,13.849,9.127,17.65c-3.363-0.109-6.525-1.064-9.293-2.651 c-0.002,0.089-0.002,0.178-0.002,0.268c0,10.272,7.072,18.845,16.458,20.793c-1.721,0.484-3.534,0.744-5.405,0.744 c-1.322,0-2.606-0.134-3.859-0.379c2.609,8.424,10.187,14.555,19.166,14.726c-7.021,5.688-15.867,9.077-25.48,9.077 c-1.656,0-3.289-0.102-4.895-0.297C9.08,88.491,19.865,92,31.449,92c37.737,0,58.374-32.312,58.374-60.336 c0-0.92-0.02-1.834-0.059-2.743C93.771,25.929,97.251,22.195,100.001,17.942L100.001,17.942z"></path> <g id="youtube"> <path class="youtube" d="M98.77,27.492c-1.225-5.064-5.576-8.799-10.811-9.354C75.561,16.818,63.01,15.993,50.514,16 c-12.495-0.007-25.045,0.816-37.446,2.139c-5.235,0.557-9.583,4.289-10.806,9.354C0.522,34.704,0.5,42.574,0.5,50.001 c0,7.426,0,15.296,1.741,22.509c1.224,5.061,5.572,8.799,10.807,9.352c12.399,1.32,24.949,2.145,37.446,2.14 c12.494,0.005,25.047-0.817,37.443-2.14c5.234-0.555,9.586-4.291,10.81-9.352c1.741-7.213,1.753-15.083,1.753-22.509 S100.51,34.704,98.77,27.492 M67.549,52.203L43.977,64.391c-2.344,1.213-4.262,0.119-4.262-2.428V38.036 c0-2.548,1.917-3.644,4.262-2.429l23.572,12.188C69.896,49.008,69.896,50.992,67.549,52.203"></path> </g> </defs> </svg> </iron-iconset-svg>`;document.head.appendChild(t.content);
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es6/node_modules/@polymer/iron-iconset-svg/demo/svg-sample-icons.js
JavaScript
gpl-3.0
5,629
/* ************************************************************************ Copyright: License: Authors: ************************************************************************ */ qx.Theme.define("qjide.theme.Font", { extend : qx.theme.modern.Font, fonts : { } });
martin-saurer/qjide
qooxdoo/qjide/source/class/qjide/theme/Font.js
JavaScript
gpl-3.0
305
"use strict"; /* * Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com> * This file is part of "Ancilla Libary". * * "Ancilla Libary" is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * "Ancilla Libary" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with "Ancilla Libary". If not, see <http://www.gnu.org/licenses/>. */ let _ = require('lodash'); let Bluebird = require('bluebird'); let winston = require('winston'); let Chalk = require('chalk'); let Constant = require('./Constants.js'); class Logger { constructor( oLoggerOptions, oTargetToExtend ){ this.__oOptions = {}; this.config( _.extend({ sID: 'logger', sLevel: 'debug', bRemote: null, iRemotePort: 3000, bSilent: false, //sLogPath: './' + __filename + '.log', sLogPath: null, iLogMaxSize: 500000, // kB iLogMaxFiles: 1, sHeader: null, sHeaderStyleBackground: 'black', sHeaderStyleColor: 'white', bUseRandomStyle4Header: false, }, oLoggerOptions ) ); this._bRemoteEnabled = false; // Extending target with log methods if needed if( oTargetToExtend ){ this.extend( this.getID(), oTargetToExtend ); } } config( oDefaultOptions ){ // Merging curren default options with default options from argument this.__oOptions = _.extend( this.__oOptions, oDefaultOptions ); } setLevel( sLevel ){ console.error( '---->TODO Logger set Level', sLevel ); } add( sID, sHeader, oOptions ){ oOptions = this.__buildLoggerOptions( oOptions ); // Setting Header style if needed this.__setRandomStyle( oOptions ); let _Logger = this; if( !winston.loggers.loggers[ sID ] ){ // Creating Sub logger let _aTransports = [ new (winston.transports.Console)({ level: oOptions.sLevel, silent: oOptions.bSilent, colorize: true, prettyPrint: true, timestamp: true }) ]; if( oOptions.sLogPath ){ this.__oTransportLogFile = ( this.__oTransportLogFile ? this.__oTransportLogFile : new (winston.transports.File)({ level: oOptions.sLevel, filename: oOptions.sLogPath, maxsize: oOptions.iLogMaxSize, // 500 kB maxFiles: oOptions.iLogMaxFiles, prettyPrint: true, timestamp: true, json: false, tailable: true, zippedArchive: true, exitOnError: false })); _aTransports.push( this.__oTransportLogFile ); } winston.loggers.add( sID, { transports: _aTransports } ); } this.__addRemoteTransport( sID, oOptions ); winston.loggers.get( sID ).filters.push( function( sHeader ){ return function(iLevel, sMsg){ return ( sHeader ? '[ ' + sHeader + ' ] ' : '' ) + sMsg; }; }( ( oOptions.sHeader ?_Logger.__getTag( oOptions ) : null ) ) ); // if( oOptions.sLogPath ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on file: "%s"...', sID, oOptions.sLevel, oOptions.sLogPath ); } if( oOptions.sRemote ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" using remote transport "%s"...', sID, oOptions.sLevel, oOptions.sRemote ); } winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on console...', sID, oOptions.sLevel ); } __addRemoteTransport( _sLoggerID, oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ this.__oTransportLogRemote = ( this.__oTransportLogRemote ? this.__oTransportLogRemote : new (require('./Logger.Transports/' + oOptions.sRemote +'.js'))({ sLevel: oOptions.sLevel })); /* // TODO: Correct way ( but we can't create more instance of the same transport... how to deal with it ? ) let _Transport = require('./Logger.Transports/' + oOptions.sRemote +'.js'); winston.loggers.loggers[ _sLoggerID ].add( _Transport, { sLevel: oOptions.sLevel }); */ // TODO: Wrong way ( since we can't create more instance of the same transport we are following this solution ) let _sID = this.__oTransportLogRemote.getID(); winston.loggers.loggers[ _sLoggerID ].transports[ _sID ] = this.__oTransportLogRemote; winston.loggers.loggers[ _sLoggerID ]._names = winston.loggers.loggers[ _sLoggerID ]._names.concat( _sID ); return this.__oTransportLogRemote.ready(); } return Bluebird.resolve(); } enableRemoteTransport( oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _bFound = false; let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ _bFound = true; } } if( !_bFound ){ // Adding remote transport if needed _aPromises.push( this.__addRemoteTransport( _sLoggerID, oOptions ) ); } } } return Bluebird.all( _aPromises ); } else { Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN ); } } disableRemoteTransport(){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ // Killing Transport _aPromises.push( _oTransports[ _sTransportID ].destroy() ); delete _oTransports[ _sTransportID ]; } } } } return Bluebird.all( _aPromises ); } extend( sID, oTarget, oOptions ) { if( oTarget ){ // Bypassing .get because it will create an empty logger if sID is not present let _Logger = winston.loggers.loggers[ sID ];//let _Logger = winston.loggers.get( sID ); if( !_Logger ){ this.add( sID, oOptions.sHeader, oOptions ); _Logger = winston.loggers.get( sID ); } [ 'silly', 'debug', 'verbose', 'info', 'warn', 'error' ].forEach( function( sMethod ){ oTarget[ sMethod ] = function(){ return _Logger[ sMethod ].apply( _Logger, arguments ); }; }); } else { this.error( 'Unable to extend with logging functions ( ID: "%s" ), the target: ', sID, oTarget ); } return this; } get( sID ){ if( !sID ){ sID = this.getID(); } return winston.loggers.get( sID ); } __buildLoggerOptions( oOptions ){ return _.extend( this.__oOptions, oOptions ); } __getRandomItemFromArray( aArray, aFilterArray ){ if( !aFilterArray ){ aFilterArray = []; } let _aFilteredArray = aArray.filter(function( sElement ){ for( let _sElement in aFilterArray ){ if( aFilterArray.hasOwnProperty( _sElement ) ){ if( _sElement === sElement ){ return false; } } } return true; }); return _aFilteredArray[ Math.floor( Math.random() * _aFilteredArray.length ) ]; } __setRandomStyle( oOptions ){ if( oOptions.bUseRandomStyle4Header ){ /* let _aMofiers = [ 'reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough' ]; */ let _aColours = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray' ]; let _aBackground = [ 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' ]; //let _sModifier = this.__getRandomItemFromArray( _aMofiers ); oOptions.sHeaderStyleColor = this.__getRandomItemFromArray( _aColours ); oOptions.sHeaderStyleBackground = this.__getRandomItemFromArray( _aBackground ); } } __getTag( oOptions ){ return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close; } } module.exports = Logger;
KingRial/Ancilla-Server
lib/Logger.js
JavaScript
gpl-3.0
9,102
var dir_2e0ad737c5a35fd799870b9d14d04fcf = [ [ "main.cpp", "TestOpenGl_2TestOpenGl_2main_8cpp.html", "TestOpenGl_2TestOpenGl_2main_8cpp" ], [ "objloader.cpp", "objloader_8cpp.html", null ], [ "objloader.h", "objloader_8h.html", [ [ "coordinate", "structcoordinate.html", "structcoordinate" ], [ "face", "structface.html", "structface" ], [ "material", "structmaterial.html", "structmaterial" ], [ "texcoord", "structtexcoord.html", "structtexcoord" ], [ "objloader", "classobjloader.html", "classobjloader" ] ] ] ];
will421/StartAir_Safe
html/dir_2e0ad737c5a35fd799870b9d14d04fcf.js
JavaScript
gpl-3.0
561
import { Meteor } from "meteor/meteor"; import { Template } from "meteor/templating"; import { Roles } from "meteor/alanning:roles"; import { ReactiveVar } from "meteor/reactive-var"; import { Reaction } from "/client/api"; import { i18next } from "/client/api"; import * as Collections from "/lib/collections"; import { Components } from "@reactioncommerce/reaction-components"; /** * onCreated: Account Profile View */ Template.accountProfile.onCreated(() => { const template = Template.instance(); template.userHasPassword = ReactiveVar(false); Meteor.call("accounts/currentUserHasPassword", (error, result) => { template.userHasPassword.set(result); }); // hide actionView if open, doesn't relate to profile page Reaction.hideActionView(); }); /** * Helpers: Account Profile View */ Template.accountProfile.helpers({ UpdateEmail() { return { component: Components.UpdateEmail }; }, ReactionAvatar() { return { component: Components.ReactionAvatar }; }, /** * User has password * @return {Boolean} return true if the current user has a password, false otherwise */ userHasPassword() { return Template.instance().userHasPassword.get(); }, /** * User's order history * @return {Array|null} an array of available orders for the user */ userOrders() { const orderSub = Meteor.subscribe("AccountOrders", Meteor.userId()); if (orderSub.ready()) { return Collections.Orders.find({ userId: Meteor.userId() }, { sort: { createdAt: -1 }, limit: 25 }); } }, /** * User's account profile * @return {Object} account profile */ account() { return Collections.Accounts.findOne(); }, /** * User's display name * @return {String} display name */ displayName() { const userId = Meteor.userId() || {}; const user = Collections.Accounts.findOne(userId); if (user) { if (user.name) { return user.name; } else if (user.username) { return user.username; } else if (user.profile && user.profile.name) { return user.profile.name; } } if (Roles.userIsInRole(user._id || user.userId, "account/profile", Reaction.getShopId())) { return i18next.t("accountsUI.guest", { defaultValue: "Guest" }); } }, /** * Returns the address book default view * @return {String} "addressBookGrid" || "addressBookAdd" */ addressBookView: function () { const account = Collections.Accounts.findOne(); if (account.profile) { return "addressBookGrid"; } return "addressBookAdd"; }, isMarketplaceGuest: function () { return (Reaction.hasMarketplaceAccess("guest") && !Reaction.hasAdminAccess()); }, isMarketplaceSeller: function () { return (Reaction.hasMarketplaceAccess() && !Reaction.hasOwnerAccess()); } });
xxbooking/reaction
imports/plugins/core/accounts/client/templates/profile/profile.js
JavaScript
gpl-3.0
2,915
import axios from 'axios' const basePath = '/api' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' export default { Utils: { getYearsChoiceList: (app, model) => axios({ url: `${basePath}/${app}/${model}/years/`, method: 'GET' }), getModelOrderedList: (app, model, ordering = '', page = 1, query_string = '') => axios({ url: `${basePath}/${app}/${model}/?o=${ordering}&page=${page}${query_string}`, method: 'GET' }), getModelList: (app, model, page = 1, query_string = '') => axios({ url: `${basePath}/${app}/${model}/?page=${page}${query_string}`, method: 'GET' }), getModel: (app, model, id) => axios({ url: `${basePath}/${app}/${model}/${id}/`, method: 'GET' }), getModelAction: (app, model, id, action) => axios({ url: `${basePath}/${app}/${model}/${id}/${action}/`, method: 'GET' }), getModelListAction: (app, model, action, page = 1) => axios({ url: `${basePath}/${app}/${model}/${action}/?page=${page}`, method: 'GET' }), getByMetadata: (m, query_string = '') => axios({ url: `${basePath}/${m.app}/${m.model}/${m.id}${m.id !== '' ? '/' : ''}${m.action}${m.action !== '' ? '/' : ''}${query_string !== '' ? '?' : ''}${query_string}`, method: 'GET' }) } }
cmjatai/cmj
_frontend/v1/src/resources/index.js
JavaScript
gpl-3.0
1,346
/*----------------------------------------------------------------------*/ /* The name says it all */ /*----------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* Subroutines */ /*-----------------------------------------------------------------------*/ function filterTasks(occ_code) { var results = []; for (var i = 0; i < taskData.length; i++) { if (taskData[i].fedscope_occ_code == occ_code) { newObject = {}; newObject = taskData[i]; newObject.hours = freq2hours(newObject.category); results.push(newObject); } } return results; } /*-----------------------------------------------------------------------*/ /* Convert frequency categories to hours */ /*-----------------------------------------------------------------------*/ function freq2hours(category) { var hours = 0; switch(category) { case "1": hours = .5; break; case "2": hours = 1; break; case "3": hours = 12; break; case "4": hours = 52; break; case "5": hours = 260; break; case "6": hours = 520; break; case "7": hours = 1043; break; default: console.log("Unknown frequency category: " + category); break; } return hours; } /*-----------------------------------------------------------------------*/ /* refresh the pie chart when you pass in a new occ code */ /*-----------------------------------------------------------------------*/ function refreshPie(newOccCode) { filteredTaskData = []; filteredTaskData = filterTasks(newOccCode); pieChartHandle.data(filteredTaskData) .draw(); $('#pie_heading').html("Hours per task for occupation " + newOccCode); }
pviechnicki/taskExplorer
js/helper_functions.js
JavaScript
gpl-3.0
1,881
vti_encoding:SR|utf8-nl vti_timelastmodified:TW|14 Aug 2014 13:36:46 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Office-PC\\Rafael vti_modifiedby:SR|Office-PC\\Rafael vti_timecreated:TR|01 Nov 2014 09:10:51 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Aug 2014 13:36:46 -0000 vti_cacheddtm:TX|03 Nov 2015 21:10:29 -0000 vti_filesize:IR|58273 vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 13:36:46 -0000 vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:10:29 -0000
Vitronic/kaufreund.de
catalog/view/theme/theme436/js/elevate/_vti_cnf/jquery.elevatezoom.js
JavaScript
gpl-3.0
618
var helpers = require('./../../../helpers'), path = require('path'), os = require('os'), should = require('should'), sinon = require('sinon'), lib_path = helpers.lib_path(), join = require('path').join, custom_dirs = require(join(lib_path, 'agent', 'utils', 'custom-dirs')) wipe_path = join(lib_path, 'agent', 'actions', 'wipe'), wipe2 = require(join(lib_path, 'agent', 'actions', 'wipe', 'wipe')), wipe = require(wipe_path), wipe_win = require(wipe_path + '/windows'), sys_index_path = helpers.lib_path('system'), sys_index = require(sys_index_path), sys_win = require(join(sys_index_path, 'windows')) api_path = join(lib_path, 'agent', 'plugins', 'control-panel', 'api'), keys = require(join(api_path, 'keys')); var outlook_versions = { old: { '2002': '10', '2003': '11', '2007': '12', '2010': '14' }, new: { '2013': '15', '2016': '16', } }; var OUTLOOK_NEW = 15, OUTLOOK_OLD = 10; var registryPath = { outlook_version: join('HKEY_CLASSES_ROOT', 'Outlook.Application', 'CurVEr'), profileRegistry: join('HKEY_CURRENT_USER', 'Software', 'Microsoft'), firefox: join('HKEY_CLASSES_ROOT', 'FirefoxHTML', 'DefaultIcon'), thunderbird: join('HKEY_CLASSES_ROOT', 'ThunderbirdEML', 'DefaultIcon') }; var hash; describe('wipe valid types', function() { before(function() { hash = { wipe_cloud: false, wipe_directories: false, wipe_documents: false, wipe_passwords: false, wipe_cookies: false, wipe_emails: false } }); describe('when one type is selected', function() { describe('and is not directories', function() { before(function() { hash.wipe_documents = true; }); after(function() { hash.wipe_documents = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('documents'); done(); }) }); describe('and is directories', function() { describe('and is only one path', function() { describe('and the path is blank', function() { before(function() { hash.wipe_directories = ''; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should an empty array', function(done){ var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(0); done(); }) }) describe('and the path is invalid', function() { before(function() { hash.wipe_directories = 'not a path'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should an empty array', function(done){ var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(0); done(); }) }) describe('and the path is valid', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return directories', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(1); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); done(); }) }) }) describe('and there are more than one path', function() { describe('and one path is blank', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe, '; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(1); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); done(); }) }) describe('and one path is invalid', function() { describe('and one path is blank', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe, invalidpath, /Users/another/valid/path'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(2); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); wipe.directories[1].should.equal('/Users/another/valid/path'); done(); }) }) }) describe('and all paths are valid', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe,/Users/another/valid/path,/Users/lastvalid'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(3); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); wipe.directories[1].should.equal('/Users/another/valid/path'); wipe.directories[2].should.equal('/Users/lastvalid'); done(); }) }) }) }) }) describe('when more than one type is selected', function() { describe('and no includes directories', function() { before(function() { hash.wipe_documents = true; hash.wipe_passwords = true; hash.wipe_emails = true; }); after(function() { hash.wipe_documents = false; hash.wipe_passwords = false; hash.wipe_emails = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(3); out[0].should.equal('documents'); out[1].should.equal('passwords'); out[2].should.equal('emails'); done(); }) }); describe('and includes directories', function() { describe('and the path is valid', function() { before(function() { hash.wipe_directories = '/Users/valid/path'; hash.wipe_passwords = true; }); after(function() { hash.wipe_directories = false; hash.wipe_passwords = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(2); out[0].should.equal('directories'); out[1].should.equal('passwords'); wipe.directories[0].should.equal('/Users/valid/path'); done(); }) }) describe('and the path is invalid', function() { before(function() { hash.wipe_directories = 'invalidpath'; hash.wipe_passwords = true; }); after(function() { hash.wipe_directories = false; hash.wipe_passwords = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('passwords'); wipe.directories.length.should.equal(0); done(); }) }) }); }); }); describe('in Windows OS', function() { var platform_stub, outlook_version, spy_fetch_dirs; var opts = { "wipe_directories": "/Users/user/Desktop/file.txt" }; before(() => { wipe.node_bin = '/usr/local/bin/node'; sys_index.os_name = "windows"; sys_index.check_service = sys_win.check_service; sys_index.run_as_admin = sys_win.run_as_admin; platform_stub = sinon.stub(os, 'platform').callsFake(() => { return 'win32'; }); keys_get_stub = sinon.stub(keys, 'get').callsFake(() => { return { api: 'aaaaaaaaaa', device: 'bbbbbb' } }); }) after(() => { platform_stub.restore(); keys_get_stub.restore(); }) describe('on registry commands', function() { wipe_win.registryManager.query.toString().should.containEql('reg query'); wipe_win.registryManager.add.toString().should.containEql('reg add'); wipe_win.registryManager.delete.toString().should.containEql('reg delete'); wipe_win.registryManager.killtask.toString().should.containEql('taskkill'); }) describe('when running in old Outlook version', function() { iterate_versions(outlook_versions.old); }); describe('when running in new Outlook version', function() { iterate_versions(outlook_versions.new); }); describe('when service is available', () => { before(() => { spy_fetch_dirs = sinon.spy(wipe2, 'fetch_dirs'); sys_win.monitoring_service_go = true; }); after(() => { spy_fetch_dirs.restore(); }) it('should wipe through the service', (done) => { wipe.start("123",opts, (err, em) => { em.on('end', (err, out) => { spy_fetch_dirs.calledOnce.should.equal(true); done(); }) }) }) }) describe('when service is not available', () => { before(() => { sys_win.monitoring_service_go = false; }) it('should not wipe through the service', (done) => { wipe.start("1234",opts, (err, em) => { em.on('end', (id,err, out) => { should.exist(err); err.message.should.containEql("Wipe command failed.") done(); }) }) }) }) function iterate_versions(versions) { Object.keys(versions).forEach(function(k) { test_outlook_version(k, versions[k]); }); } function get_outlook_path(version) { if (parseInt(version) >= 15) { return join('HKEY_USERS', 'User1', 'Software', 'Microsoft', 'Office', `${version}.0`, 'Outlook', 'Profiles'); } else if (parseInt(version) < OUTLOOK_NEW && parseInt(version) >= OUTLOOK_OLD) { return join('HKEY_USERS', 'Software', 'Microsoft', 'User1', 'Windows NT', 'CurrentVersion', 'Windows Messaging Subsystem', 'Profiles'); } else { return join('HKEY_USERS', 'Software', 'Microsoft', `User1`, 'Windows Messaging Subsystem', 'Profiles'); } } function test_outlook_version(version_type, version) { var stub_path; var stub_registry; describe(version_type, function() { before(function() { stub_path = sinon.stub(wipe_win, 'getOutlookVersion').callsFake(cb => { cb(null, version); }) stub_registry = sinon.stub(wipe_win.registryManager, 'query').callsFake((query, cb) => { return cb(null, '\r\nUser1\r\n') }) }); after(function() { stub_registry.restore(); stub_path.restore(); }); it('returns path', function(done) { wipe_win.getProfileRegistry(function(err, out) { out[0].should.equal(get_outlook_path(version)); done(); }); }); }); }; });
prey/prey-node-client
test/lib/agent/actions/wipe.js
JavaScript
gpl-3.0
12,290
Ext.define('Onlineshopping.onlineshopping.shared.shop.model.location.TimezoneModel', { "extend": "Ext.data.Model", "fields": [{ "name": "primaryKey", "type": "string", "defaultValue": "" }, { "name": "timeZoneId", "type": "string", "defaultValue": "" }, { "name": "utcdifference", "type": "int", "defaultValue": "" }, { "name": "gmtLabel", "type": "string", "defaultValue": "" }, { "name": "timeZoneLabel", "type": "string", "defaultValue": "" }, { "name": "country", "type": "string", "defaultValue": "" }, { "name": "cities", "type": "string", "defaultValue": "" }, { "name": "versionId", "type": "int", "defaultValue": "" }, { "name": "entityAudit", "reference": "EntityAudit" }, { "name": "primaryDisplay", "type": "string", "defaultValue": "" }] });
applifireAlgo/OnlineShopEx
onlineshopping/src/main/webapp/app/onlineshopping/shared/shop/model/location/TimezoneModel.js
JavaScript
gpl-3.0
1,104
(function () { var modern = (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.ThemeManager'); var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager'); var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools'); var isBrandingEnabled = function (editor) { return editor.getParam('branding', true, 'boolean'); }; var hasMenubar = function (editor) { return getMenubar(editor) !== false; }; var getMenubar = function (editor) { return editor.getParam('menubar'); }; var hasStatusbar = function (editor) { return editor.getParam('statusbar', true, 'boolean'); }; var getToolbarSize = function (editor) { return editor.getParam('toolbar_items_size'); }; var isReadOnly = function (editor) { return editor.getParam('readonly', false, 'boolean'); }; var getFixedToolbarContainer = function (editor) { return editor.getParam('fixed_toolbar_container'); }; var getInlineToolbarPositionHandler = function (editor) { return editor.getParam('inline_toolbar_position_handler'); }; var getMenu = function (editor) { return editor.getParam('menu'); }; var getRemovedMenuItems = function (editor) { return editor.getParam('removed_menuitems', ''); }; var getMinWidth = function (editor) { return editor.getParam('min_width', 100, 'number'); }; var getMinHeight = function (editor) { return editor.getParam('min_height', 100, 'number'); }; var getMaxWidth = function (editor) { return editor.getParam('max_width', 65535, 'number'); }; var getMaxHeight = function (editor) { return editor.getParam('max_height', 65535, 'number'); }; var isSkinDisabled = function (editor) { return editor.settings.skin === false; }; var isInline = function (editor) { return editor.getParam('inline', false, 'boolean'); }; var getResize = function (editor) { var resize = editor.getParam('resize', 'vertical'); if (resize === false) { return 'none'; } else if (resize === 'both') { return 'both'; } else { return 'vertical'; } }; var getSkinUrl = function (editor) { var settings = editor.settings; var skin = settings.skin; var skinUrl = settings.skin_url; if (skin !== false) { var skinName = skin ? skin : 'lightgray'; if (skinUrl) { skinUrl = editor.documentBaseURI.toAbsolute(skinUrl); } else { skinUrl = global$1.baseURL + '/skins/' + skinName; } } return skinUrl; }; var getIndexedToolbars = function (settings, defaultToolbar) { var toolbars = []; for (var i = 1; i < 10; i++) { var toolbar_1 = settings['toolbar' + i]; if (!toolbar_1) { break; } toolbars.push(toolbar_1); } var mainToolbar = settings.toolbar ? [settings.toolbar] : [defaultToolbar]; return toolbars.length > 0 ? toolbars : mainToolbar; }; var getToolbars = function (editor) { var toolbar = editor.getParam('toolbar'); var defaultToolbar = 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image'; if (toolbar === false) { return []; } else if (global$2.isArray(toolbar)) { return global$2.grep(toolbar, function (toolbar) { return toolbar.length > 0; }); } else { return getIndexedToolbars(editor.settings, defaultToolbar); } }; var global$3 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); var global$4 = tinymce.util.Tools.resolve('tinymce.ui.Factory'); var global$5 = tinymce.util.Tools.resolve('tinymce.util.I18n'); var fireSkinLoaded = function (editor) { return editor.fire('SkinLoaded'); }; var fireResizeEditor = function (editor) { return editor.fire('ResizeEditor'); }; var fireBeforeRenderUI = function (editor) { return editor.fire('BeforeRenderUI'); }; var $_aycuj2t7jh8lz3jp = { fireSkinLoaded: fireSkinLoaded, fireResizeEditor: fireResizeEditor, fireBeforeRenderUI: fireBeforeRenderUI }; var focus = function (panel, type) { return function () { var item = panel.find(type)[0]; if (item) { item.focus(true); } }; }; var addKeys = function (editor, panel) { editor.shortcuts.add('Alt+F9', '', focus(panel, 'menubar')); editor.shortcuts.add('Alt+F10,F10', '', focus(panel, 'toolbar')); editor.shortcuts.add('Alt+F11', '', focus(panel, 'elementpath')); panel.on('cancel', function () { editor.focus(); }); }; var $_47hpztt8jh8lz3jq = { addKeys: addKeys }; var global$6 = tinymce.util.Tools.resolve('tinymce.geom.Rect'); var global$7 = tinymce.util.Tools.resolve('tinymce.util.Delay'); var noop = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } }; var noarg = function (f) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return f(); }; }; var compose = function (fa, fb) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return fa(fb.apply(null, arguments)); }; }; var constant = function (value) { return function () { return value; }; }; var identity = function (x) { return x; }; var tripleEquals = function (a, b) { return a === b; }; var curry = function (f) { var x = []; for (var _i = 1; _i < arguments.length; _i++) { x[_i - 1] = arguments[_i]; } var args = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } var newArgs = new Array(arguments.length); for (var j = 0; j < newArgs.length; j++) newArgs[j] = arguments[j]; var all = args.concat(newArgs); return f.apply(null, all); }; }; var not = function (f) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return !f.apply(null, arguments); }; }; var die = function (msg) { return function () { throw new Error(msg); }; }; var apply = function (f) { return f(); }; var call = function (f) { f(); }; var never = constant(false); var always = constant(true); var $_3pjweotejh8lz3k4 = { noop: noop, noarg: noarg, compose: compose, constant: constant, identity: identity, tripleEquals: tripleEquals, curry: curry, not: not, die: die, apply: apply, call: call, never: never, always: always }; var never$1 = $_3pjweotejh8lz3k4.never; var always$1 = $_3pjweotejh8lz3k4.always; var none = function () { return NONE; }; var NONE = function () { var eq = function (o) { return o.isNone(); }; var call = function (thunk) { return thunk(); }; var id = function (n) { return n; }; var noop = function () { }; var me = { fold: function (n, s) { return n(); }, is: never$1, isSome: never$1, isNone: always$1, getOr: id, getOrThunk: call, getOrDie: function (msg) { throw new Error(msg || 'error: getOrDie called on none.'); }, or: id, orThunk: call, map: none, ap: none, each: noop, bind: none, flatten: none, exists: never$1, forall: always$1, filter: none, equals: eq, equals_: eq, toArray: function () { return []; }, toString: $_3pjweotejh8lz3k4.constant('none()') }; if (Object.freeze) Object.freeze(me); return me; }(); var some = function (a) { var constant_a = function () { return a; }; var self = function () { return me; }; var map = function (f) { return some(f(a)); }; var bind = function (f) { return f(a); }; var me = { fold: function (n, s) { return s(a); }, is: function (v) { return a === v; }, isSome: always$1, isNone: never$1, getOr: constant_a, getOrThunk: constant_a, getOrDie: constant_a, or: self, orThunk: self, map: map, ap: function (optfab) { return optfab.fold(none, function (fab) { return some(fab(a)); }); }, each: function (f) { f(a); }, bind: bind, flatten: constant_a, exists: bind, forall: bind, filter: function (f) { return f(a) ? me : NONE; }, equals: function (o) { return o.is(a); }, equals_: function (o, elementEq) { return o.fold(never$1, function (b) { return elementEq(a, b); }); }, toArray: function () { return [a]; }, toString: function () { return 'some(' + a + ')'; } }; return me; }; var from = function (value) { return value === null || value === undefined ? NONE : some(value); }; var Option = { some: some, none: none, from: from }; var getUiContainerDelta = function (ctrl) { var uiContainer = getUiContainer(ctrl); if (uiContainer && global$3.DOM.getStyle(uiContainer, 'position', true) !== 'static') { var containerPos = global$3.DOM.getPos(uiContainer); var dx = uiContainer.scrollLeft - containerPos.x; var dy = uiContainer.scrollTop - containerPos.y; return Option.some({ x: dx, y: dy }); } else { return Option.none(); } }; var setUiContainer = function (editor, ctrl) { var uiContainer = global$3.DOM.select(editor.settings.ui_container)[0]; ctrl.getRoot().uiContainer = uiContainer; }; var getUiContainer = function (ctrl) { return ctrl ? ctrl.getRoot().uiContainer : null; }; var inheritUiContainer = function (fromCtrl, toCtrl) { return toCtrl.uiContainer = getUiContainer(fromCtrl); }; var $_1jk3jvtcjh8lz3jy = { getUiContainerDelta: getUiContainerDelta, setUiContainer: setUiContainer, getUiContainer: getUiContainer, inheritUiContainer: inheritUiContainer }; var createToolbar = function (editor, items, size) { var toolbarItems = []; var buttonGroup; if (!items) { return; } global$2.each(items.split(/[ ,]/), function (item) { var itemName; var bindSelectorChanged = function () { var selection = editor.selection; if (item.settings.stateSelector) { selection.selectorChanged(item.settings.stateSelector, function (state) { item.active(state); }, true); } if (item.settings.disabledStateSelector) { selection.selectorChanged(item.settings.disabledStateSelector, function (state) { item.disabled(state); }); } }; if (item === '|') { buttonGroup = null; } else { if (!buttonGroup) { buttonGroup = { type: 'buttongroup', items: [] }; toolbarItems.push(buttonGroup); } if (editor.buttons[item]) { itemName = item; item = editor.buttons[itemName]; if (typeof item === 'function') { item = item(); } item.type = item.type || 'button'; item.size = size; item = global$4.create(item); buttonGroup.items.push(item); if (editor.initialized) { bindSelectorChanged(); } else { editor.on('init', bindSelectorChanged); } } } }); return { type: 'toolbar', layout: 'flow', items: toolbarItems }; }; var createToolbars = function (editor, size) { var toolbars = []; var addToolbar = function (items) { if (items) { toolbars.push(createToolbar(editor, items, size)); } }; global$2.each(getToolbars(editor), function (toolbar) { addToolbar(toolbar); }); if (toolbars.length) { return { type: 'panel', layout: 'stack', classes: 'toolbar-grp', ariaRoot: true, ariaRemember: true, items: toolbars }; } }; var $_fudqhrtfjh8lz3k7 = { createToolbar: createToolbar, createToolbars: createToolbars }; var DOM = global$3.DOM; var toClientRect = function (geomRect) { return { left: geomRect.x, top: geomRect.y, width: geomRect.w, height: geomRect.h, right: geomRect.x + geomRect.w, bottom: geomRect.y + geomRect.h }; }; var hideAllFloatingPanels = function (editor) { global$2.each(editor.contextToolbars, function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var movePanelTo = function (panel, pos) { panel.moveTo(pos.left, pos.top); }; var togglePositionClass = function (panel, relPos, predicate) { relPos = relPos ? relPos.substr(0, 2) : ''; global$2.each({ t: 'down', b: 'up' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(0, 1))); }); global$2.each({ l: 'left', r: 'right' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(1, 1))); }); }; var userConstrain = function (handler, x, y, elementRect, contentAreaRect, panelRect) { panelRect = toClientRect({ x: x, y: y, w: panelRect.w, h: panelRect.h }); if (handler) { panelRect = handler({ elementRect: toClientRect(elementRect), contentAreaRect: toClientRect(contentAreaRect), panelRect: panelRect }); } return panelRect; }; var addContextualToolbars = function (editor) { var scrollContainer; var getContextToolbars = function () { return editor.contextToolbars || []; }; var getElementRect = function (elm) { var pos, targetRect, root; pos = DOM.getPos(editor.getContentAreaContainer()); targetRect = editor.dom.getRect(elm); root = editor.dom.getRoot(); if (root.nodeName === 'BODY') { targetRect.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft; targetRect.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop; } targetRect.x += pos.x; targetRect.y += pos.y; return targetRect; }; var reposition = function (match, shouldShow) { var relPos, panelRect, elementRect, contentAreaRect, panel, relRect, testPositions, smallElementWidthThreshold; var handler = getInlineToolbarPositionHandler(editor); if (editor.removed) { return; } if (!match || !match.toolbar.panel) { hideAllFloatingPanels(editor); return; } testPositions = [ 'bc-tc', 'tc-bc', 'tl-bl', 'bl-tl', 'tr-br', 'br-tr' ]; panel = match.toolbar.panel; if (shouldShow) { panel.show(); } elementRect = getElementRect(match.element); panelRect = DOM.getRect(panel.getEl()); contentAreaRect = DOM.getRect(editor.getContentAreaContainer() || editor.getBody()); var delta = $_1jk3jvtcjh8lz3jy.getUiContainerDelta(panel).getOr({ x: 0, y: 0 }); elementRect.x += delta.x; elementRect.y += delta.y; panelRect.x += delta.x; panelRect.y += delta.y; contentAreaRect.x += delta.x; contentAreaRect.y += delta.y; smallElementWidthThreshold = 25; if (DOM.getStyle(match.element, 'display', true) !== 'inline') { var clientRect = match.element.getBoundingClientRect(); elementRect.w = clientRect.width; elementRect.h = clientRect.height; } if (!editor.inline) { contentAreaRect.w = editor.getDoc().documentElement.offsetWidth; } if (editor.selection.controlSelection.isResizable(match.element) && elementRect.w < smallElementWidthThreshold) { elementRect = global$6.inflate(elementRect, 0, 8); } relPos = global$6.findBestRelativePosition(panelRect, elementRect, contentAreaRect, testPositions); elementRect = global$6.clamp(elementRect, contentAreaRect); if (relPos) { relRect = global$6.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { contentAreaRect.h += panelRect.h; elementRect = global$6.intersect(contentAreaRect, elementRect); if (elementRect) { relPos = global$6.findBestRelativePosition(panelRect, elementRect, contentAreaRect, [ 'bc-tc', 'bl-tl', 'br-tr' ]); if (relPos) { relRect = global$6.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { movePanelTo(panel, userConstrain(handler, elementRect.x, elementRect.y, elementRect, contentAreaRect, panelRect)); } } else { panel.hide(); } } togglePositionClass(panel, relPos, function (pos1, pos2) { return pos1 === pos2; }); }; var repositionHandler = function (show) { return function () { var execute = function () { if (editor.selection) { reposition(findFrontMostMatch(editor.selection.getNode()), show); } }; global$7.requestAnimationFrame(execute); }; }; var bindScrollEvent = function (panel) { if (!scrollContainer) { var reposition_1 = repositionHandler(true); var uiContainer_1 = $_1jk3jvtcjh8lz3jy.getUiContainer(panel); scrollContainer = editor.selection.getScrollContainer() || editor.getWin(); DOM.bind(scrollContainer, 'scroll', reposition_1); DOM.bind(uiContainer_1, 'scroll', reposition_1); editor.on('remove', function () { DOM.unbind(scrollContainer, 'scroll', reposition_1); DOM.unbind(uiContainer_1, 'scroll', reposition_1); }); } }; var showContextToolbar = function (match) { var panel; if (match.toolbar.panel) { match.toolbar.panel.show(); reposition(match); return; } panel = global$4.create({ type: 'floatpanel', role: 'dialog', classes: 'tinymce tinymce-inline arrow', ariaLabel: 'Inline toolbar', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: true, fixed: true, border: 1, items: $_fudqhrtfjh8lz3k7.createToolbar(editor, match.toolbar.items), oncancel: function () { editor.focus(); } }); $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel); bindScrollEvent(panel); match.toolbar.panel = panel; panel.renderTo().reflow(); reposition(match); }; var hideAllContextToolbars = function () { global$2.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var findFrontMostMatch = function (targetElm) { var i, y, parentsAndSelf; var toolbars = getContextToolbars(); parentsAndSelf = editor.$(targetElm).parents().add(targetElm); for (i = parentsAndSelf.length - 1; i >= 0; i--) { for (y = toolbars.length - 1; y >= 0; y--) { if (toolbars[y].predicate(parentsAndSelf[i])) { return { toolbar: toolbars[y], element: parentsAndSelf[i] }; } } } return null; }; editor.on('click keyup setContent ObjectResized', function (e) { if (e.type === 'setcontent' && !e.selection) { return; } global$7.setEditorTimeout(editor, function () { var match; match = findFrontMostMatch(editor.selection.getNode()); if (match) { hideAllContextToolbars(); showContextToolbar(match); } else { hideAllContextToolbars(); } }); }); editor.on('blur hide contextmenu', hideAllContextToolbars); editor.on('ObjectResizeStart', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.hide(); } }); editor.on('ResizeEditor ResizeWindow', repositionHandler(true)); editor.on('nodeChange', repositionHandler(false)); editor.on('remove', function () { global$2.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.remove(); } }); editor.contextToolbars = {}; }); editor.shortcuts.add('ctrl+shift+e > ctrl+shift+p', '', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.items()[0].focus(); } }); }; var $_5kodmdt9jh8lz3js = { addContextualToolbars: addContextualToolbars }; var typeOf = function (x) { if (x === null) return 'null'; var t = typeof x; if (t === 'object' && Array.prototype.isPrototypeOf(x)) return 'array'; if (t === 'object' && String.prototype.isPrototypeOf(x)) return 'string'; return t; }; var isType = function (type) { return function (value) { return typeOf(value) === type; }; }; var $_d8bie3tijh8lz3kn = { isString: isType('string'), isObject: isType('object'), isArray: isType('array'), isNull: isType('null'), isBoolean: isType('boolean'), isUndefined: isType('undefined'), isFunction: isType('function'), isNumber: isType('number') }; var rawIndexOf = function () { var pIndexOf = Array.prototype.indexOf; var fastIndex = function (xs, x) { return pIndexOf.call(xs, x); }; var slowIndex = function (xs, x) { return slowIndexOf(xs, x); }; return pIndexOf === undefined ? slowIndex : fastIndex; }(); var indexOf = function (xs, x) { var r = rawIndexOf(xs, x); return r === -1 ? Option.none() : Option.some(r); }; var contains = function (xs, x) { return rawIndexOf(xs, x) > -1; }; var exists = function (xs, pred) { return findIndex(xs, pred).isSome(); }; var range = function (num, f) { var r = []; for (var i = 0; i < num; i++) { r.push(f(i)); } return r; }; var chunk = function (array, size) { var r = []; for (var i = 0; i < array.length; i += size) { var s = array.slice(i, i + size); r.push(s); } return r; }; var map = function (xs, f) { var len = xs.length; var r = new Array(len); for (var i = 0; i < len; i++) { var x = xs[i]; r[i] = f(x, i, xs); } return r; }; var each = function (xs, f) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; f(x, i, xs); } }; var eachr = function (xs, f) { for (var i = xs.length - 1; i >= 0; i--) { var x = xs[i]; f(x, i, xs); } }; var partition = function (xs, pred) { var pass = []; var fail = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; var arr = pred(x, i, xs) ? pass : fail; arr.push(x); } return { pass: pass, fail: fail }; }; var filter = function (xs, pred) { var r = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { r.push(x); } } return r; }; var groupBy = function (xs, f) { if (xs.length === 0) { return []; } else { var wasType = f(xs[0]); var r = []; var group = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; var type = f(x); if (type !== wasType) { r.push(group); group = []; } wasType = type; group.push(x); } if (group.length !== 0) { r.push(group); } return r; } }; var foldr = function (xs, f, acc) { eachr(xs, function (x) { acc = f(acc, x); }); return acc; }; var foldl = function (xs, f, acc) { each(xs, function (x) { acc = f(acc, x); }); return acc; }; var find = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { return Option.some(x); } } return Option.none(); }; var findIndex = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { return Option.some(i); } } return Option.none(); }; var slowIndexOf = function (xs, x) { for (var i = 0, len = xs.length; i < len; ++i) { if (xs[i] === x) { return i; } } return -1; }; var push = Array.prototype.push; var flatten = function (xs) { var r = []; for (var i = 0, len = xs.length; i < len; ++i) { if (!Array.prototype.isPrototypeOf(xs[i])) throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); push.apply(r, xs[i]); } return r; }; var bind = function (xs, f) { var output = map(xs, f); return flatten(output); }; var forall = function (xs, pred) { for (var i = 0, len = xs.length; i < len; ++i) { var x = xs[i]; if (pred(x, i, xs) !== true) { return false; } } return true; }; var equal = function (a1, a2) { return a1.length === a2.length && forall(a1, function (x, i) { return x === a2[i]; }); }; var slice = Array.prototype.slice; var reverse = function (xs) { var r = slice.call(xs, 0); r.reverse(); return r; }; var difference = function (a1, a2) { return filter(a1, function (x) { return !contains(a2, x); }); }; var mapToObject = function (xs, f) { var r = {}; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; r[String(x)] = f(x, i); } return r; }; var pure = function (x) { return [x]; }; var sort = function (xs, comparator) { var copy = slice.call(xs, 0); copy.sort(comparator); return copy; }; var head = function (xs) { return xs.length === 0 ? Option.none() : Option.some(xs[0]); }; var last = function (xs) { return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]); }; var from$1 = $_d8bie3tijh8lz3kn.isFunction(Array.from) ? Array.from : function (x) { return slice.call(x); }; var $_f3qxhzthjh8lz3kg = { map: map, each: each, eachr: eachr, partition: partition, filter: filter, groupBy: groupBy, indexOf: indexOf, foldr: foldr, foldl: foldl, find: find, findIndex: findIndex, flatten: flatten, bind: bind, forall: forall, exists: exists, contains: contains, equal: equal, reverse: reverse, chunk: chunk, difference: difference, mapToObject: mapToObject, pure: pure, sort: sort, range: range, head: head, last: last, from: from$1 }; var defaultMenus = { file: { title: 'File', items: 'newdocument restoredraft | preview | print' }, edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall' }, view: { title: 'View', items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen' }, insert: { title: 'Insert', items: 'image link media template codesample inserttable | charmap hr | pagebreak nonbreaking anchor toc | insertdatetime' }, format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | blockformats align | removeformat' }, tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | a11ycheck code' }, table: { title: 'Table' }, help: { title: 'Help' } }; var delimiterMenuNamePair = function () { return { name: '|', item: { text: '|' } }; }; var createMenuNameItemPair = function (name, item) { var menuItem = item ? { name: name, item: item } : null; return name === '|' ? delimiterMenuNamePair() : menuItem; }; var hasItemName = function (namedMenuItems, name) { return $_f3qxhzthjh8lz3kg.findIndex(namedMenuItems, function (namedMenuItem) { return namedMenuItem.name === name; }).isSome(); }; var isSeparator = function (namedMenuItem) { return namedMenuItem && namedMenuItem.item.text === '|'; }; var cleanupMenu = function (namedMenuItems, removedMenuItems) { var menuItemsPass1 = $_f3qxhzthjh8lz3kg.filter(namedMenuItems, function (namedMenuItem) { return removedMenuItems.hasOwnProperty(namedMenuItem.name) === false; }); var menuItemsPass2 = $_f3qxhzthjh8lz3kg.filter(menuItemsPass1, function (namedMenuItem, i, namedMenuItems) { return !isSeparator(namedMenuItem) || !isSeparator(namedMenuItems[i - 1]); }); return $_f3qxhzthjh8lz3kg.filter(menuItemsPass2, function (namedMenuItem, i, namedMenuItems) { return !isSeparator(namedMenuItem) || i > 0 && i < namedMenuItems.length - 1; }); }; var createMenu = function (editorMenuItems, menus, removedMenuItems, context) { var menuButton, menu, namedMenuItems, isUserDefined; if (menus) { menu = menus[context]; isUserDefined = true; } else { menu = defaultMenus[context]; } if (menu) { menuButton = { text: menu.title }; namedMenuItems = []; global$2.each((menu.items || '').split(/[ ,]/), function (name) { var namedMenuItem = createMenuNameItemPair(name, editorMenuItems[name]); if (namedMenuItem) { namedMenuItems.push(namedMenuItem); } }); if (!isUserDefined) { global$2.each(editorMenuItems, function (item, name) { if (item.context === context && !hasItemName(namedMenuItems, name)) { if (item.separator === 'before') { namedMenuItems.push(delimiterMenuNamePair()); } if (item.prependToContext) { namedMenuItems.unshift(createMenuNameItemPair(name, item)); } else { namedMenuItems.push(createMenuNameItemPair(name, item)); } if (item.separator === 'after') { namedMenuItems.push(delimiterMenuNamePair()); } } }); } menuButton.menu = $_f3qxhzthjh8lz3kg.map(cleanupMenu(namedMenuItems, removedMenuItems), function (menuItem) { return menuItem.item; }); if (!menuButton.menu.length) { return null; } } return menuButton; }; var getDefaultMenubar = function (editor) { var name; var defaultMenuBar = []; var menu = getMenu(editor); if (menu) { for (name in menu) { defaultMenuBar.push(name); } } else { for (name in defaultMenus) { defaultMenuBar.push(name); } } return defaultMenuBar; }; var createMenuButtons = function (editor) { var menuButtons = []; var defaultMenuBar = getDefaultMenubar(editor); var removedMenuItems = global$2.makeMap(getRemovedMenuItems(editor).split(/[ ,]/)); var menubar = getMenubar(editor); var enabledMenuNames = typeof menubar === 'string' ? menubar.split(/[ ,]/) : defaultMenuBar; for (var i = 0; i < enabledMenuNames.length; i++) { var menuItems = enabledMenuNames[i]; var menu = createMenu(editor.menuItems, getMenu(editor), removedMenuItems, menuItems); if (menu) { menuButtons.push(menu); } } return menuButtons; }; var $_8i78rftgjh8lz3ka = { createMenuButtons: createMenuButtons }; var DOM$1 = global$3.DOM; var getSize = function (elm) { return { width: elm.clientWidth, height: elm.clientHeight }; }; var resizeTo = function (editor, width, height) { var containerElm, iframeElm, containerSize, iframeSize; containerElm = editor.getContainer(); iframeElm = editor.getContentAreaContainer().firstChild; containerSize = getSize(containerElm); iframeSize = getSize(iframeElm); if (width !== null) { width = Math.max(getMinWidth(editor), width); width = Math.min(getMaxWidth(editor), width); DOM$1.setStyle(containerElm, 'width', width + (containerSize.width - iframeSize.width)); DOM$1.setStyle(iframeElm, 'width', width); } height = Math.max(getMinHeight(editor), height); height = Math.min(getMaxHeight(editor), height); DOM$1.setStyle(iframeElm, 'height', height); $_aycuj2t7jh8lz3jp.fireResizeEditor(editor); }; var resizeBy = function (editor, dw, dh) { var elm = editor.getContentAreaContainer(); resizeTo(editor, elm.clientWidth + dw, elm.clientHeight + dh); }; var $_5toavetjjh8lz3ko = { resizeTo: resizeTo, resizeBy: resizeBy }; var global$8 = tinymce.util.Tools.resolve('tinymce.Env'); var api = function (elm) { return { element: function () { return elm; } }; }; var trigger = function (sidebar, panel, callbackName) { var callback = sidebar.settings[callbackName]; if (callback) { callback(api(panel.getEl('body'))); } }; var hidePanels = function (name, container, sidebars) { global$2.each(sidebars, function (sidebar) { var panel = container.items().filter('#' + sidebar.name)[0]; if (panel && panel.visible() && sidebar.name !== name) { trigger(sidebar, panel, 'onhide'); panel.visible(false); } }); }; var deactivateButtons = function (toolbar) { toolbar.items().each(function (ctrl) { ctrl.active(false); }); }; var findSidebar = function (sidebars, name) { return global$2.grep(sidebars, function (sidebar) { return sidebar.name === name; })[0]; }; var showPanel = function (editor, name, sidebars) { return function (e) { var btnCtrl = e.control; var container = btnCtrl.parents().filter('panel')[0]; var panel = container.find('#' + name)[0]; var sidebar = findSidebar(sidebars, name); hidePanels(name, container, sidebars); deactivateButtons(btnCtrl.parent()); if (panel && panel.visible()) { trigger(sidebar, panel, 'onhide'); panel.hide(); btnCtrl.active(false); } else { if (panel) { panel.show(); trigger(sidebar, panel, 'onshow'); } else { panel = global$4.create({ type: 'container', name: name, layout: 'stack', classes: 'sidebar-panel', html: '' }); container.prepend(panel); trigger(sidebar, panel, 'onrender'); trigger(sidebar, panel, 'onshow'); } btnCtrl.active(true); } $_aycuj2t7jh8lz3jp.fireResizeEditor(editor); }; }; var isModernBrowser = function () { return !global$8.ie || global$8.ie >= 11; }; var hasSidebar = function (editor) { return isModernBrowser() && editor.sidebars ? editor.sidebars.length > 0 : false; }; var createSidebar = function (editor) { var buttons = global$2.map(editor.sidebars, function (sidebar) { var settings = sidebar.settings; return { type: 'button', icon: settings.icon, image: settings.image, tooltip: settings.tooltip, onclick: showPanel(editor, sidebar.name, editor.sidebars) }; }); return { type: 'panel', name: 'sidebar', layout: 'stack', classes: 'sidebar', items: [{ type: 'toolbar', layout: 'stack', classes: 'sidebar-toolbar', items: buttons }] }; }; var $_5buua9tkjh8lz3kq = { hasSidebar: hasSidebar, createSidebar: createSidebar }; var fireSkinLoaded$1 = function (editor) { var done = function () { editor._skinLoaded = true; $_aycuj2t7jh8lz3jp.fireSkinLoaded(editor); }; return function () { if (editor.initialized) { done(); } else { editor.on('init', done); } }; }; var $_231e94tmjh8lz3ku = { fireSkinLoaded: fireSkinLoaded$1 }; var DOM$2 = global$3.DOM; var switchMode = function (panel) { return function (e) { panel.find('*').disabled(e.mode === 'readonly'); }; }; var editArea = function (border) { return { type: 'panel', name: 'iframe', layout: 'stack', classes: 'edit-area', border: border, html: '' }; }; var editAreaContainer = function (editor) { return { type: 'panel', layout: 'stack', classes: 'edit-aria-container', border: '1 0 0 0', items: [ editArea('0'), $_5buua9tkjh8lz3kq.createSidebar(editor) ] }; }; var render = function (editor, theme, args) { var panel, resizeHandleCtrl, startSize; if (isSkinDisabled(editor) === false && args.skinUiCss) { DOM$2.styleSheetLoader.load(args.skinUiCss, $_231e94tmjh8lz3ku.fireSkinLoaded(editor)); } else { $_231e94tmjh8lz3ku.fireSkinLoaded(editor)(); } panel = theme.panel = global$4.create({ type: 'panel', role: 'application', classes: 'tinymce', style: 'visibility: hidden', layout: 'stack', border: 1, items: [ { type: 'container', classes: 'top-part', items: [ hasMenubar(editor) === false ? null : { type: 'menubar', border: '0 0 1 0', items: $_8i78rftgjh8lz3ka.createMenuButtons(editor) }, $_fudqhrtfjh8lz3k7.createToolbars(editor, getToolbarSize(editor)) ] }, $_5buua9tkjh8lz3kq.hasSidebar(editor) ? editAreaContainer(editor) : editArea('1 0 0 0') ] }); $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel); if (getResize(editor) !== 'none') { resizeHandleCtrl = { type: 'resizehandle', direction: getResize(editor), onResizeStart: function () { var elm = editor.getContentAreaContainer().firstChild; startSize = { width: elm.clientWidth, height: elm.clientHeight }; }, onResize: function (e) { if (getResize(editor) === 'both') { $_5toavetjjh8lz3ko.resizeTo(editor, startSize.width + e.deltaX, startSize.height + e.deltaY); } else { $_5toavetjjh8lz3ko.resizeTo(editor, null, startSize.height + e.deltaY); } } }; } if (hasStatusbar(editor)) { var linkHtml = '<a href="https://www.tinymce.com/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce" rel="noopener" target="_blank" role="presentation" tabindex="-1">tinymce</a>'; var html = global$5.translate([ 'Powered by {0}', linkHtml ]); var brandingLabel = isBrandingEnabled(editor) ? { type: 'label', classes: 'branding', html: ' ' + html } : null; panel.add({ type: 'panel', name: 'statusbar', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', ariaRoot: true, items: [ { type: 'elementpath', editor: editor }, resizeHandleCtrl, brandingLabel ] }); } $_aycuj2t7jh8lz3jp.fireBeforeRenderUI(editor); editor.on('SwitchMode', switchMode(panel)); panel.renderBefore(args.targetNode).reflow(); if (isReadOnly(editor)) { editor.setMode('readonly'); } if (args.width) { DOM$2.setStyle(panel.getEl(), 'width', args.width); } editor.on('remove', function () { panel.remove(); panel = null; }); $_47hpztt8jh8lz3jq.addKeys(editor, panel); $_5kodmdt9jh8lz3js.addContextualToolbars(editor); return { iframeContainer: panel.find('#iframe')[0].getEl(), editorContainer: panel.getEl() }; }; var $_4cj0a3t3jh8lz3jk = { render: render }; var global$9 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery'); var count = 0; var funcs = { id: function () { return 'mceu_' + count++; }, create: function (name, attrs, children) { var elm = document.createElement(name); global$3.DOM.setAttribs(elm, attrs); if (typeof children === 'string') { elm.innerHTML = children; } else { global$2.each(children, function (child) { if (child.nodeType) { elm.appendChild(child); } }); } return elm; }, createFragment: function (html) { return global$3.DOM.createFragment(html); }, getWindowSize: function () { return global$3.DOM.getViewPort(); }, getSize: function (elm) { var width, height; if (elm.getBoundingClientRect) { var rect = elm.getBoundingClientRect(); width = Math.max(rect.width || rect.right - rect.left, elm.offsetWidth); height = Math.max(rect.height || rect.bottom - rect.bottom, elm.offsetHeight); } else { width = elm.offsetWidth; height = elm.offsetHeight; } return { width: width, height: height }; }, getPos: function (elm, root) { return global$3.DOM.getPos(elm, root || funcs.getContainer()); }, getContainer: function () { return global$8.container ? global$8.container : document.body; }, getViewPort: function (win) { return global$3.DOM.getViewPort(win); }, get: function (id) { return document.getElementById(id); }, addClass: function (elm, cls) { return global$3.DOM.addClass(elm, cls); }, removeClass: function (elm, cls) { return global$3.DOM.removeClass(elm, cls); }, hasClass: function (elm, cls) { return global$3.DOM.hasClass(elm, cls); }, toggleClass: function (elm, cls, state) { return global$3.DOM.toggleClass(elm, cls, state); }, css: function (elm, name, value) { return global$3.DOM.setStyle(elm, name, value); }, getRuntimeStyle: function (elm, name) { return global$3.DOM.getStyle(elm, name, true); }, on: function (target, name, callback, scope) { return global$3.DOM.bind(target, name, callback, scope); }, off: function (target, name, callback) { return global$3.DOM.unbind(target, name, callback); }, fire: function (target, name, args) { return global$3.DOM.fire(target, name, args); }, innerHtml: function (elm, html) { global$3.DOM.setHTML(elm, html); } }; var isStatic = function (elm) { return funcs.getRuntimeStyle(elm, 'position') === 'static'; }; var isFixed = function (ctrl) { return ctrl.state.get('fixed'); }; function calculateRelativePosition(ctrl, targetElm, rel) { var ctrlElm, pos, x, y, selfW, selfH, targetW, targetH, viewport, size; viewport = getWindowViewPort(); pos = funcs.getPos(targetElm, $_1jk3jvtcjh8lz3jy.getUiContainer(ctrl)); x = pos.x; y = pos.y; if (isFixed(ctrl) && isStatic(document.body)) { x -= viewport.x; y -= viewport.y; } ctrlElm = ctrl.getEl(); size = funcs.getSize(ctrlElm); selfW = size.width; selfH = size.height; size = funcs.getSize(targetElm); targetW = size.width; targetH = size.height; rel = (rel || '').split(''); if (rel[0] === 'b') { y += targetH; } if (rel[1] === 'r') { x += targetW; } if (rel[0] === 'c') { y += Math.round(targetH / 2); } if (rel[1] === 'c') { x += Math.round(targetW / 2); } if (rel[3] === 'b') { y -= selfH; } if (rel[4] === 'r') { x -= selfW; } if (rel[3] === 'c') { y -= Math.round(selfH / 2); } if (rel[4] === 'c') { x -= Math.round(selfW / 2); } return { x: x, y: y, w: selfW, h: selfH }; } var getUiContainerViewPort = function (customUiContainer) { return { x: 0, y: 0, w: customUiContainer.scrollWidth - 1, h: customUiContainer.scrollHeight - 1 }; }; var getWindowViewPort = function () { var win = window; var x = Math.max(win.pageXOffset, document.body.scrollLeft, document.documentElement.scrollLeft); var y = Math.max(win.pageYOffset, document.body.scrollTop, document.documentElement.scrollTop); var w = win.innerWidth || document.documentElement.clientWidth; var h = win.innerHeight || document.documentElement.clientHeight; return { x: x, y: y, w: x + w, h: y + h }; }; var getViewPortRect = function (ctrl) { var customUiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(ctrl); return customUiContainer && !isFixed(ctrl) ? getUiContainerViewPort(customUiContainer) : getWindowViewPort(); }; var $_d97gfctrjh8lz3lm = { testMoveRel: function (elm, rels) { var viewPortRect = getViewPortRect(this); for (var i = 0; i < rels.length; i++) { var pos = calculateRelativePosition(this, elm, rels[i]); if (isFixed(this)) { if (pos.x > 0 && pos.x + pos.w < viewPortRect.w && pos.y > 0 && pos.y + pos.h < viewPortRect.h) { return rels[i]; } } else { if (pos.x > viewPortRect.x && pos.x + pos.w < viewPortRect.w && pos.y > viewPortRect.y && pos.y + pos.h < viewPortRect.h) { return rels[i]; } } } return rels[0]; }, moveRel: function (elm, rel) { if (typeof rel !== 'string') { rel = this.testMoveRel(elm, rel); } var pos = calculateRelativePosition(this, elm, rel); return this.moveTo(pos.x, pos.y); }, moveBy: function (dx, dy) { var self = this, rect = self.layoutRect(); self.moveTo(rect.x + dx, rect.y + dy); return self; }, moveTo: function (x, y) { var self = this; function constrain(value, max, size) { if (value < 0) { return 0; } if (value + size > max) { value = max - size; return value < 0 ? 0 : value; } return value; } if (self.settings.constrainToViewport) { var viewPortRect = getViewPortRect(this); var layoutRect = self.layoutRect(); x = constrain(x, viewPortRect.w, layoutRect.w); y = constrain(y, viewPortRect.h, layoutRect.h); } var uiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(self); if (uiContainer && isStatic(uiContainer) && !isFixed(self)) { x -= uiContainer.scrollLeft; y -= uiContainer.scrollTop; } if (uiContainer) { x += 1; y += 1; } if (self.state.get('rendered')) { self.layoutRect({ x: x, y: y }).repaint(); } else { self.settings.x = x; self.settings.y = y; } self.fire('move', { x: x, y: y }); return self; } }; var global$10 = tinymce.util.Tools.resolve('tinymce.util.Class'); var global$11 = tinymce.util.Tools.resolve('tinymce.util.EventDispatcher'); var $_focdcktxjh8lz3mn = { parseBox: function (value) { var len; var radix = 10; if (!value) { return; } if (typeof value === 'number') { value = value || 0; return { top: value, left: value, bottom: value, right: value }; } value = value.split(' '); len = value.length; if (len === 1) { value[1] = value[2] = value[3] = value[0]; } else if (len === 2) { value[2] = value[0]; value[3] = value[1]; } else if (len === 3) { value[3] = value[1]; } return { top: parseInt(value[0], radix) || 0, right: parseInt(value[1], radix) || 0, bottom: parseInt(value[2], radix) || 0, left: parseInt(value[3], radix) || 0 }; }, measureBox: function (elm, prefix) { function getStyle(name) { var defaultView = elm.ownerDocument.defaultView; if (defaultView) { var computedStyle = defaultView.getComputedStyle(elm, null); if (computedStyle) { name = name.replace(/[A-Z]/g, function (a) { return '-' + a; }); return computedStyle.getPropertyValue(name); } else { return null; } } return elm.currentStyle[name]; } function getSide(name) { var val = parseFloat(getStyle(name)); return isNaN(val) ? 0 : val; } return { top: getSide(prefix + 'TopWidth'), right: getSide(prefix + 'RightWidth'), bottom: getSide(prefix + 'BottomWidth'), left: getSide(prefix + 'LeftWidth') }; } }; function noop$1() { } function ClassList(onchange) { this.cls = []; this.cls._map = {}; this.onchange = onchange || noop$1; this.prefix = ''; } global$2.extend(ClassList.prototype, { add: function (cls) { if (cls && !this.contains(cls)) { this.cls._map[cls] = true; this.cls.push(cls); this._change(); } return this; }, remove: function (cls) { if (this.contains(cls)) { var i = void 0; for (i = 0; i < this.cls.length; i++) { if (this.cls[i] === cls) { break; } } this.cls.splice(i, 1); delete this.cls._map[cls]; this._change(); } return this; }, toggle: function (cls, state) { var curState = this.contains(cls); if (curState !== state) { if (curState) { this.remove(cls); } else { this.add(cls); } this._change(); } return this; }, contains: function (cls) { return !!this.cls._map[cls]; }, _change: function () { delete this.clsValue; this.onchange.call(this); } }); ClassList.prototype.toString = function () { var value; if (this.clsValue) { return this.clsValue; } value = ''; for (var i = 0; i < this.cls.length; i++) { if (i > 0) { value += ' '; } value += this.prefix + this.cls[i]; } return value; }; function unique(array) { var uniqueItems = []; var i = array.length, item; while (i--) { item = array[i]; if (!item.__checked) { uniqueItems.push(item); item.__checked = 1; } } i = uniqueItems.length; while (i--) { delete uniqueItems[i].__checked; } return uniqueItems; } var expression = /^([\w\\*]+)?(?:#([\w\-\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i; var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g; var whiteSpace = /^\s*|\s*$/g; var Collection; var Selector = global$10.extend({ init: function (selector) { var match = this.match; function compileNameFilter(name) { if (name) { name = name.toLowerCase(); return function (item) { return name === '*' || item.type === name; }; } } function compileIdFilter(id) { if (id) { return function (item) { return item._name === id; }; } } function compileClassesFilter(classes) { if (classes) { classes = classes.split('.'); return function (item) { var i = classes.length; while (i--) { if (!item.classes.contains(classes[i])) { return false; } } return true; }; } } function compileAttrFilter(name, cmp, check) { if (name) { return function (item) { var value = item[name] ? item[name]() : ''; return !cmp ? !!check : cmp === '=' ? value === check : cmp === '*=' ? value.indexOf(check) >= 0 : cmp === '~=' ? (' ' + value + ' ').indexOf(' ' + check + ' ') >= 0 : cmp === '!=' ? value !== check : cmp === '^=' ? value.indexOf(check) === 0 : cmp === '$=' ? value.substr(value.length - check.length) === check : false; }; } } function compilePsuedoFilter(name) { var notSelectors; if (name) { name = /(?:not\((.+)\))|(.+)/i.exec(name); if (!name[1]) { name = name[2]; return function (item, index, length) { return name === 'first' ? index === 0 : name === 'last' ? index === length - 1 : name === 'even' ? index % 2 === 0 : name === 'odd' ? index % 2 === 1 : item[name] ? item[name]() : false; }; } notSelectors = parseChunks(name[1], []); return function (item) { return !match(item, notSelectors); }; } } function compile(selector, filters, direct) { var parts; function add(filter) { if (filter) { filters.push(filter); } } parts = expression.exec(selector.replace(whiteSpace, '')); add(compileNameFilter(parts[1])); add(compileIdFilter(parts[2])); add(compileClassesFilter(parts[3])); add(compileAttrFilter(parts[4], parts[5], parts[6])); add(compilePsuedoFilter(parts[7])); filters.pseudo = !!parts[7]; filters.direct = direct; return filters; } function parseChunks(selector, selectors) { var parts = []; var extra, matches, i; do { chunker.exec(''); matches = chunker.exec(selector); if (matches) { selector = matches[3]; parts.push(matches[1]); if (matches[2]) { extra = matches[3]; break; } } } while (matches); if (extra) { parseChunks(extra, selectors); } selector = []; for (i = 0; i < parts.length; i++) { if (parts[i] !== '>') { selector.push(compile(parts[i], [], parts[i - 1] === '>')); } } selectors.push(selector); return selectors; } this._selectors = parseChunks(selector, []); }, match: function (control, selectors) { var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item; selectors = selectors || this._selectors; for (i = 0, l = selectors.length; i < l; i++) { selector = selectors[i]; sl = selector.length; item = control; count = 0; for (si = sl - 1; si >= 0; si--) { filters = selector[si]; while (item) { if (filters.pseudo) { siblings = item.parent().items(); index = length = siblings.length; while (index--) { if (siblings[index] === item) { break; } } } for (fi = 0, fl = filters.length; fi < fl; fi++) { if (!filters[fi](item, index, length)) { fi = fl + 1; break; } } if (fi === fl) { count++; break; } else { if (si === sl - 1) { break; } } item = item.parent(); } } if (count === sl) { return true; } } return false; }, find: function (container) { var matches = [], i, l; var selectors = this._selectors; function collect(items, selector, index) { var i, l, fi, fl, item; var filters = selector[index]; for (i = 0, l = items.length; i < l; i++) { item = items[i]; for (fi = 0, fl = filters.length; fi < fl; fi++) { if (!filters[fi](item, i, l)) { fi = fl + 1; break; } } if (fi === fl) { if (index === selector.length - 1) { matches.push(item); } else { if (item.items) { collect(item.items(), selector, index + 1); } } } else if (filters.direct) { return; } if (item.items) { collect(item.items(), selector, index); } } } if (container.items) { for (i = 0, l = selectors.length; i < l; i++) { collect(container.items(), selectors[i], 0); } if (l > 1) { matches = unique(matches); } } if (!Collection) { Collection = Selector.Collection; } return new Collection(matches); } }); var Collection$1; var proto; var push$1 = Array.prototype.push; var slice$1 = Array.prototype.slice; proto = { length: 0, init: function (items) { if (items) { this.add(items); } }, add: function (items) { var self = this; if (!global$2.isArray(items)) { if (items instanceof Collection$1) { self.add(items.toArray()); } else { push$1.call(self, items); } } else { push$1.apply(self, items); } return self; }, set: function (items) { var self = this; var len = self.length; var i; self.length = 0; self.add(items); for (i = self.length; i < len; i++) { delete self[i]; } return self; }, filter: function (selector) { var self = this; var i, l; var matches = []; var item, match; if (typeof selector === 'string') { selector = new Selector(selector); match = function (item) { return selector.match(item); }; } else { match = selector; } for (i = 0, l = self.length; i < l; i++) { item = self[i]; if (match(item)) { matches.push(item); } } return new Collection$1(matches); }, slice: function () { return new Collection$1(slice$1.apply(this, arguments)); }, eq: function (index) { return index === -1 ? this.slice(index) : this.slice(index, +index + 1); }, each: function (callback) { global$2.each(this, callback); return this; }, toArray: function () { return global$2.toArray(this); }, indexOf: function (ctrl) { var self = this; var i = self.length; while (i--) { if (self[i] === ctrl) { break; } } return i; }, reverse: function () { return new Collection$1(global$2.toArray(this).reverse()); }, hasClass: function (cls) { return this[0] ? this[0].classes.contains(cls) : false; }, prop: function (name, value) { var self = this; var item; if (value !== undefined) { self.each(function (item) { if (item[name]) { item[name](value); } }); return self; } item = self[0]; if (item && item[name]) { return item[name](); } }, exec: function (name) { var self = this, args = global$2.toArray(arguments).slice(1); self.each(function (item) { if (item[name]) { item[name].apply(item, args); } }); return self; }, remove: function () { var i = this.length; while (i--) { this[i].remove(); } return this; }, addClass: function (cls) { return this.each(function (item) { item.classes.add(cls); }); }, removeClass: function (cls) { return this.each(function (item) { item.classes.remove(cls); }); } }; global$2.each('fire on off show hide append prepend before after reflow'.split(' '), function (name) { proto[name] = function () { var args = global$2.toArray(arguments); this.each(function (ctrl) { if (name in ctrl) { ctrl[name].apply(ctrl, args); } }); return this; }; }); global$2.each('text name disabled active selected checked visible parent value data'.split(' '), function (name) { proto[name] = function (value) { return this.prop(name, value); }; }); Collection$1 = global$10.extend(proto); Selector.Collection = Collection$1; var Collection$2 = Collection$1; var Binding = function (settings) { this.create = settings.create; }; Binding.create = function (model, name) { return new Binding({ create: function (otherModel, otherName) { var bindings; var fromSelfToOther = function (e) { otherModel.set(otherName, e.value); }; var fromOtherToSelf = function (e) { model.set(name, e.value); }; otherModel.on('change:' + otherName, fromOtherToSelf); model.on('change:' + name, fromSelfToOther); bindings = otherModel._bindings; if (!bindings) { bindings = otherModel._bindings = []; otherModel.on('destroy', function () { var i = bindings.length; while (i--) { bindings[i](); } }); } bindings.push(function () { model.off('change:' + name, fromSelfToOther); }); return model.get(name); } }); }; var global$12 = tinymce.util.Tools.resolve('tinymce.util.Observable'); function isNode(node) { return node.nodeType > 0; } function isEqual(a, b) { var k, checked; if (a === b) { return true; } if (a === null || b === null) { return a === b; } if (typeof a !== 'object' || typeof b !== 'object') { return a === b; } if (global$2.isArray(b)) { if (a.length !== b.length) { return false; } k = a.length; while (k--) { if (!isEqual(a[k], b[k])) { return false; } } } if (isNode(a) || isNode(b)) { return a === b; } checked = {}; for (k in b) { if (!isEqual(a[k], b[k])) { return false; } checked[k] = true; } for (k in a) { if (!checked[k] && !isEqual(a[k], b[k])) { return false; } } return true; } var ObservableObject = global$10.extend({ Mixins: [global$12], init: function (data) { var name, value; data = data || {}; for (name in data) { value = data[name]; if (value instanceof Binding) { data[name] = value.create(this, name); } } this.data = data; }, set: function (name, value) { var key, args; var oldValue = this.data[name]; if (value instanceof Binding) { value = value.create(this, name); } if (typeof name === 'object') { for (key in name) { this.set(key, name[key]); } return this; } if (!isEqual(oldValue, value)) { this.data[name] = value; args = { target: this, name: name, value: value, oldValue: oldValue }; this.fire('change:' + name, args); this.fire('change', args); } return this; }, get: function (name) { return this.data[name]; }, has: function (name) { return name in this.data; }, bind: function (name) { return Binding.create(this, name); }, destroy: function () { this.fire('destroy'); } }); var dirtyCtrls = {}; var animationFrameRequested; var $_ef12j5u4jh8lz3nl = { add: function (ctrl) { var parent = ctrl.parent(); if (parent) { if (!parent._layout || parent._layout.isNative()) { return; } if (!dirtyCtrls[parent._id]) { dirtyCtrls[parent._id] = parent; } if (!animationFrameRequested) { animationFrameRequested = true; global$7.requestAnimationFrame(function () { var id, ctrl; animationFrameRequested = false; for (id in dirtyCtrls) { ctrl = dirtyCtrls[id]; if (ctrl.state.get('rendered')) { ctrl.reflow(); } } dirtyCtrls = {}; }, document.body); } } }, remove: function (ctrl) { if (dirtyCtrls[ctrl._id]) { delete dirtyCtrls[ctrl._id]; } } }; var hasMouseWheelEventSupport = 'onmousewheel' in document; var hasWheelEventSupport = false; var classPrefix = 'mce-'; var Control; var idCounter = 0; var proto$1 = { Statics: { classPrefix: classPrefix }, isRtl: function () { return Control.rtl; }, classPrefix: classPrefix, init: function (settings) { var self = this; var classes, defaultClasses; function applyClasses(classes) { var i; classes = classes.split(' '); for (i = 0; i < classes.length; i++) { self.classes.add(classes[i]); } } self.settings = settings = global$2.extend({}, self.Defaults, settings); self._id = settings.id || 'mceu_' + idCounter++; self._aria = { role: settings.role }; self._elmCache = {}; self.$ = global$9; self.state = new ObservableObject({ visible: true, active: false, disabled: false, value: '' }); self.data = new ObservableObject(settings.data); self.classes = new ClassList(function () { if (self.state.get('rendered')) { self.getEl().className = this.toString(); } }); self.classes.prefix = self.classPrefix; classes = settings.classes; if (classes) { if (self.Defaults) { defaultClasses = self.Defaults.classes; if (defaultClasses && classes !== defaultClasses) { applyClasses(defaultClasses); } } applyClasses(classes); } global$2.each('title text name visible disabled active value'.split(' '), function (name) { if (name in settings) { self[name](settings[name]); } }); self.on('click', function () { if (self.disabled()) { return false; } }); self.settings = settings; self.borderBox = $_focdcktxjh8lz3mn.parseBox(settings.border); self.paddingBox = $_focdcktxjh8lz3mn.parseBox(settings.padding); self.marginBox = $_focdcktxjh8lz3mn.parseBox(settings.margin); if (settings.hidden) { self.hide(); } }, Properties: 'parent,name', getContainerElm: function () { var uiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(this); return uiContainer ? uiContainer : funcs.getContainer(); }, getParentCtrl: function (elm) { var ctrl; var lookup = this.getRoot().controlIdLookup; while (elm && lookup) { ctrl = lookup[elm.id]; if (ctrl) { break; } elm = elm.parentNode; } return ctrl; }, initLayoutRect: function () { var self = this; var settings = self.settings; var borderBox, layoutRect; var elm = self.getEl(); var width, height, minWidth, minHeight, autoResize; var startMinWidth, startMinHeight, initialSize; borderBox = self.borderBox = self.borderBox || $_focdcktxjh8lz3mn.measureBox(elm, 'border'); self.paddingBox = self.paddingBox || $_focdcktxjh8lz3mn.measureBox(elm, 'padding'); self.marginBox = self.marginBox || $_focdcktxjh8lz3mn.measureBox(elm, 'margin'); initialSize = funcs.getSize(elm); startMinWidth = settings.minWidth; startMinHeight = settings.minHeight; minWidth = startMinWidth || initialSize.width; minHeight = startMinHeight || initialSize.height; width = settings.width; height = settings.height; autoResize = settings.autoResize; autoResize = typeof autoResize !== 'undefined' ? autoResize : !width && !height; width = width || minWidth; height = height || minHeight; var deltaW = borderBox.left + borderBox.right; var deltaH = borderBox.top + borderBox.bottom; var maxW = settings.maxWidth || 65535; var maxH = settings.maxHeight || 65535; self._layoutRect = layoutRect = { x: settings.x || 0, y: settings.y || 0, w: width, h: height, deltaW: deltaW, deltaH: deltaH, contentW: width - deltaW, contentH: height - deltaH, innerW: width - deltaW, innerH: height - deltaH, startMinWidth: startMinWidth || 0, startMinHeight: startMinHeight || 0, minW: Math.min(minWidth, maxW), minH: Math.min(minHeight, maxH), maxW: maxW, maxH: maxH, autoResize: autoResize, scrollW: 0 }; self._lastLayoutRect = {}; return layoutRect; }, layoutRect: function (newRect) { var self = this; var curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, repaintControls; if (!curRect) { curRect = self.initLayoutRect(); } if (newRect) { deltaWidth = curRect.deltaW; deltaHeight = curRect.deltaH; if (newRect.x !== undefined) { curRect.x = newRect.x; } if (newRect.y !== undefined) { curRect.y = newRect.y; } if (newRect.minW !== undefined) { curRect.minW = newRect.minW; } if (newRect.minH !== undefined) { curRect.minH = newRect.minH; } size = newRect.w; if (size !== undefined) { size = size < curRect.minW ? curRect.minW : size; size = size > curRect.maxW ? curRect.maxW : size; curRect.w = size; curRect.innerW = size - deltaWidth; } size = newRect.h; if (size !== undefined) { size = size < curRect.minH ? curRect.minH : size; size = size > curRect.maxH ? curRect.maxH : size; curRect.h = size; curRect.innerH = size - deltaHeight; } size = newRect.innerW; if (size !== undefined) { size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size; size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size; curRect.innerW = size; curRect.w = size + deltaWidth; } size = newRect.innerH; if (size !== undefined) { size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size; size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size; curRect.innerH = size; curRect.h = size + deltaHeight; } if (newRect.contentW !== undefined) { curRect.contentW = newRect.contentW; } if (newRect.contentH !== undefined) { curRect.contentH = newRect.contentH; } lastLayoutRect = self._lastLayoutRect; if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y || lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) { repaintControls = Control.repaintControls; if (repaintControls) { if (repaintControls.map && !repaintControls.map[self._id]) { repaintControls.push(self); repaintControls.map[self._id] = true; } } lastLayoutRect.x = curRect.x; lastLayoutRect.y = curRect.y; lastLayoutRect.w = curRect.w; lastLayoutRect.h = curRect.h; } return self; } return curRect; }, repaint: function () { var self = this; var style, bodyStyle, bodyElm, rect, borderBox; var borderW, borderH, lastRepaintRect, round, value; round = !document.createRange ? Math.round : function (value) { return value; }; style = self.getEl().style; rect = self._layoutRect; lastRepaintRect = self._lastRepaintRect || {}; borderBox = self.borderBox; borderW = borderBox.left + borderBox.right; borderH = borderBox.top + borderBox.bottom; if (rect.x !== lastRepaintRect.x) { style.left = round(rect.x) + 'px'; lastRepaintRect.x = rect.x; } if (rect.y !== lastRepaintRect.y) { style.top = round(rect.y) + 'px'; lastRepaintRect.y = rect.y; } if (rect.w !== lastRepaintRect.w) { value = round(rect.w - borderW); style.width = (value >= 0 ? value : 0) + 'px'; lastRepaintRect.w = rect.w; } if (rect.h !== lastRepaintRect.h) { value = round(rect.h - borderH); style.height = (value >= 0 ? value : 0) + 'px'; lastRepaintRect.h = rect.h; } if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) { value = round(rect.innerW); bodyElm = self.getEl('body'); if (bodyElm) { bodyStyle = bodyElm.style; bodyStyle.width = (value >= 0 ? value : 0) + 'px'; } lastRepaintRect.innerW = rect.innerW; } if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) { value = round(rect.innerH); bodyElm = bodyElm || self.getEl('body'); if (bodyElm) { bodyStyle = bodyStyle || bodyElm.style; bodyStyle.height = (value >= 0 ? value : 0) + 'px'; } lastRepaintRect.innerH = rect.innerH; } self._lastRepaintRect = lastRepaintRect; self.fire('repaint', {}, false); }, updateLayoutRect: function () { var self = this; self.parent()._lastRect = null; funcs.css(self.getEl(), { width: '', height: '' }); self._layoutRect = self._lastRepaintRect = self._lastLayoutRect = null; self.initLayoutRect(); }, on: function (name, callback) { var self = this; function resolveCallbackName(name) { var callback, scope; if (typeof name !== 'string') { return name; } return function (e) { if (!callback) { self.parentsAndSelf().each(function (ctrl) { var callbacks = ctrl.settings.callbacks; if (callbacks && (callback = callbacks[name])) { scope = ctrl; return false; } }); } if (!callback) { e.action = name; this.fire('execute', e); return; } return callback.call(scope, e); }; } getEventDispatcher(self).on(name, resolveCallbackName(callback)); return self; }, off: function (name, callback) { getEventDispatcher(this).off(name, callback); return this; }, fire: function (name, args, bubble) { var self = this; args = args || {}; if (!args.control) { args.control = self; } args = getEventDispatcher(self).fire(name, args); if (bubble !== false && self.parent) { var parent_1 = self.parent(); while (parent_1 && !args.isPropagationStopped()) { parent_1.fire(name, args, false); parent_1 = parent_1.parent(); } } return args; }, hasEventListeners: function (name) { return getEventDispatcher(this).has(name); }, parents: function (selector) { var self = this; var ctrl, parents = new Collection$2(); for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) { parents.add(ctrl); } if (selector) { parents = parents.filter(selector); } return parents; }, parentsAndSelf: function (selector) { return new Collection$2(this).add(this.parents(selector)); }, next: function () { var parentControls = this.parent().items(); return parentControls[parentControls.indexOf(this) + 1]; }, prev: function () { var parentControls = this.parent().items(); return parentControls[parentControls.indexOf(this) - 1]; }, innerHtml: function (html) { this.$el.html(html); return this; }, getEl: function (suffix) { var id = suffix ? this._id + '-' + suffix : this._id; if (!this._elmCache[id]) { this._elmCache[id] = global$9('#' + id)[0]; } return this._elmCache[id]; }, show: function () { return this.visible(true); }, hide: function () { return this.visible(false); }, focus: function () { try { this.getEl().focus(); } catch (ex) { } return this; }, blur: function () { this.getEl().blur(); return this; }, aria: function (name, value) { var self = this, elm = self.getEl(self.ariaTarget); if (typeof value === 'undefined') { return self._aria[name]; } self._aria[name] = value; if (self.state.get('rendered')) { elm.setAttribute(name === 'role' ? name : 'aria-' + name, value); } return self; }, encode: function (text, translate) { if (translate !== false) { text = this.translate(text); } return (text || '').replace(/[&<>"]/g, function (match) { return '&#' + match.charCodeAt(0) + ';'; }); }, translate: function (text) { return Control.translate ? Control.translate(text) : text; }, before: function (items) { var self = this, parent = self.parent(); if (parent) { parent.insert(items, parent.items().indexOf(self), true); } return self; }, after: function (items) { var self = this, parent = self.parent(); if (parent) { parent.insert(items, parent.items().indexOf(self)); } return self; }, remove: function () { var self = this; var elm = self.getEl(); var parent = self.parent(); var newItems, i; if (self.items) { var controls = self.items().toArray(); i = controls.length; while (i--) { controls[i].remove(); } } if (parent && parent.items) { newItems = []; parent.items().each(function (item) { if (item !== self) { newItems.push(item); } }); parent.items().set(newItems); parent._lastRect = null; } if (self._eventsRoot && self._eventsRoot === self) { global$9(elm).off(); } var lookup = self.getRoot().controlIdLookup; if (lookup) { delete lookup[self._id]; } if (elm && elm.parentNode) { elm.parentNode.removeChild(elm); } self.state.set('rendered', false); self.state.destroy(); self.fire('remove'); return self; }, renderBefore: function (elm) { global$9(elm).before(this.renderHtml()); this.postRender(); return this; }, renderTo: function (elm) { global$9(elm || this.getContainerElm()).append(this.renderHtml()); this.postRender(); return this; }, preRender: function () { }, render: function () { }, renderHtml: function () { return '<div id="' + this._id + '" class="' + this.classes + '"></div>'; }, postRender: function () { var self = this; var settings = self.settings; var elm, box, parent, name, parentEventsRoot; self.$el = global$9(self.getEl()); self.state.set('rendered', true); for (name in settings) { if (name.indexOf('on') === 0) { self.on(name.substr(2), settings[name]); } } if (self._eventsRoot) { for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) { parentEventsRoot = parent._eventsRoot; } if (parentEventsRoot) { for (name in parentEventsRoot._nativeEvents) { self._nativeEvents[name] = true; } } } bindPendingEvents(self); if (settings.style) { elm = self.getEl(); if (elm) { elm.setAttribute('style', settings.style); elm.style.cssText = settings.style; } } if (self.settings.border) { box = self.borderBox; self.$el.css({ 'border-top-width': box.top, 'border-right-width': box.right, 'border-bottom-width': box.bottom, 'border-left-width': box.left }); } var root = self.getRoot(); if (!root.controlIdLookup) { root.controlIdLookup = {}; } root.controlIdLookup[self._id] = self; for (var key in self._aria) { self.aria(key, self._aria[key]); } if (self.state.get('visible') === false) { self.getEl().style.display = 'none'; } self.bindStates(); self.state.on('change:visible', function (e) { var state = e.value; var parentCtrl; if (self.state.get('rendered')) { self.getEl().style.display = state === false ? 'none' : ''; self.getEl().getBoundingClientRect(); } parentCtrl = self.parent(); if (parentCtrl) { parentCtrl._lastRect = null; } self.fire(state ? 'show' : 'hide'); $_ef12j5u4jh8lz3nl.add(self); }); self.fire('postrender', {}, false); }, bindStates: function () { }, scrollIntoView: function (align) { function getOffset(elm, rootElm) { var x, y, parent = elm; x = y = 0; while (parent && parent !== rootElm && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } return { x: x, y: y }; } var elm = this.getEl(), parentElm = elm.parentNode; var x, y, width, height, parentWidth, parentHeight; var pos = getOffset(elm, parentElm); x = pos.x; y = pos.y; width = elm.offsetWidth; height = elm.offsetHeight; parentWidth = parentElm.clientWidth; parentHeight = parentElm.clientHeight; if (align === 'end') { x -= parentWidth - width; y -= parentHeight - height; } else if (align === 'center') { x -= parentWidth / 2 - width / 2; y -= parentHeight / 2 - height / 2; } parentElm.scrollLeft = x; parentElm.scrollTop = y; return this; }, getRoot: function () { var ctrl = this, rootControl; var parents = []; while (ctrl) { if (ctrl.rootControl) { rootControl = ctrl.rootControl; break; } parents.push(ctrl); rootControl = ctrl; ctrl = ctrl.parent(); } if (!rootControl) { rootControl = this; } var i = parents.length; while (i--) { parents[i].rootControl = rootControl; } return rootControl; }, reflow: function () { $_ef12j5u4jh8lz3nl.remove(this); var parent = this.parent(); if (parent && parent._layout && !parent._layout.isNative()) { parent.reflow(); } return this; } }; global$2.each('text title visible disabled active value'.split(' '), function (name) { proto$1[name] = function (value) { if (arguments.length === 0) { return this.state.get(name); } if (typeof value !== 'undefined') { this.state.set(name, value); } return this; }; }); Control = global$10.extend(proto$1); function getEventDispatcher(obj) { if (!obj._eventDispatcher) { obj._eventDispatcher = new global$11({ scope: obj, toggleEvent: function (name, state) { if (state && global$11.isNative(name)) { if (!obj._nativeEvents) { obj._nativeEvents = {}; } obj._nativeEvents[name] = true; if (obj.state.get('rendered')) { bindPendingEvents(obj); } } } }); } return obj._eventDispatcher; } function bindPendingEvents(eventCtrl) { var i, l, parents, eventRootCtrl, nativeEvents, name; function delegate(e) { var control = eventCtrl.getParentCtrl(e.target); if (control) { control.fire(e.type, e); } } function mouseLeaveHandler() { var ctrl = eventRootCtrl._lastHoverCtrl; if (ctrl) { ctrl.fire('mouseleave', { target: ctrl.getEl() }); ctrl.parents().each(function (ctrl) { ctrl.fire('mouseleave', { target: ctrl.getEl() }); }); eventRootCtrl._lastHoverCtrl = null; } } function mouseEnterHandler(e) { var ctrl = eventCtrl.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents; if (ctrl !== lastCtrl) { eventRootCtrl._lastHoverCtrl = ctrl; parents = ctrl.parents().toArray().reverse(); parents.push(ctrl); if (lastCtrl) { lastParents = lastCtrl.parents().toArray().reverse(); lastParents.push(lastCtrl); for (idx = 0; idx < lastParents.length; idx++) { if (parents[idx] !== lastParents[idx]) { break; } } for (i = lastParents.length - 1; i >= idx; i--) { lastCtrl = lastParents[i]; lastCtrl.fire('mouseleave', { target: lastCtrl.getEl() }); } } for (i = idx; i < parents.length; i++) { ctrl = parents[i]; ctrl.fire('mouseenter', { target: ctrl.getEl() }); } } } function fixWheelEvent(e) { e.preventDefault(); if (e.type === 'mousewheel') { e.deltaY = -1 / 40 * e.wheelDelta; if (e.wheelDeltaX) { e.deltaX = -1 / 40 * e.wheelDeltaX; } } else { e.deltaX = 0; e.deltaY = e.detail; } e = eventCtrl.fire('wheel', e); } nativeEvents = eventCtrl._nativeEvents; if (nativeEvents) { parents = eventCtrl.parents().toArray(); parents.unshift(eventCtrl); for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) { eventRootCtrl = parents[i]._eventsRoot; } if (!eventRootCtrl) { eventRootCtrl = parents[parents.length - 1] || eventCtrl; } eventCtrl._eventsRoot = eventRootCtrl; for (l = i, i = 0; i < l; i++) { parents[i]._eventsRoot = eventRootCtrl; } var eventRootDelegates = eventRootCtrl._delegates; if (!eventRootDelegates) { eventRootDelegates = eventRootCtrl._delegates = {}; } for (name in nativeEvents) { if (!nativeEvents) { return false; } if (name === 'wheel' && !hasWheelEventSupport) { if (hasMouseWheelEventSupport) { global$9(eventCtrl.getEl()).on('mousewheel', fixWheelEvent); } else { global$9(eventCtrl.getEl()).on('DOMMouseScroll', fixWheelEvent); } continue; } if (name === 'mouseenter' || name === 'mouseleave') { if (!eventRootCtrl._hasMouseEnter) { global$9(eventRootCtrl.getEl()).on('mouseleave', mouseLeaveHandler).on('mouseover', mouseEnterHandler); eventRootCtrl._hasMouseEnter = 1; } } else if (!eventRootDelegates[name]) { global$9(eventRootCtrl.getEl()).on(name, delegate); eventRootDelegates[name] = true; } nativeEvents[name] = false; } } } var Control$1 = Control; var hasTabstopData = function (elm) { return elm.getAttribute('data-mce-tabstop') ? true : false; }; function KeyboardNavigation (settings) { var root = settings.root; var focusedElement, focusedControl; function isElement(node) { return node && node.nodeType === 1; } try { focusedElement = document.activeElement; } catch (ex) { focusedElement = document.body; } focusedControl = root.getParentCtrl(focusedElement); function getRole(elm) { elm = elm || focusedElement; if (isElement(elm)) { return elm.getAttribute('role'); } return null; } function getParentRole(elm) { var role, parent = elm || focusedElement; while (parent = parent.parentNode) { if (role = getRole(parent)) { return role; } } } function getAriaProp(name) { var elm = focusedElement; if (isElement(elm)) { return elm.getAttribute('aria-' + name); } } function isTextInputElement(elm) { var tagName = elm.tagName.toUpperCase(); return tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT'; } function canFocus(elm) { if (isTextInputElement(elm) && !elm.hidden) { return true; } if (hasTabstopData(elm)) { return true; } if (/^(button|menuitem|checkbox|tab|menuitemcheckbox|option|gridcell|slider)$/.test(getRole(elm))) { return true; } return false; } function getFocusElements(elm) { var elements = []; function collect(elm) { if (elm.nodeType !== 1 || elm.style.display === 'none' || elm.disabled) { return; } if (canFocus(elm)) { elements.push(elm); } for (var i = 0; i < elm.childNodes.length; i++) { collect(elm.childNodes[i]); } } collect(elm || root.getEl()); return elements; } function getNavigationRoot(targetControl) { var navigationRoot, controls; targetControl = targetControl || focusedControl; controls = targetControl.parents().toArray(); controls.unshift(targetControl); for (var i = 0; i < controls.length; i++) { navigationRoot = controls[i]; if (navigationRoot.settings.ariaRoot) { break; } } return navigationRoot; } function focusFirst(targetControl) { var navigationRoot = getNavigationRoot(targetControl); var focusElements = getFocusElements(navigationRoot.getEl()); if (navigationRoot.settings.ariaRemember && 'lastAriaIndex' in navigationRoot) { moveFocusToIndex(navigationRoot.lastAriaIndex, focusElements); } else { moveFocusToIndex(0, focusElements); } } function moveFocusToIndex(idx, elements) { if (idx < 0) { idx = elements.length - 1; } else if (idx >= elements.length) { idx = 0; } if (elements[idx]) { elements[idx].focus(); } return idx; } function moveFocus(dir, elements) { var idx = -1; var navigationRoot = getNavigationRoot(); elements = elements || getFocusElements(navigationRoot.getEl()); for (var i = 0; i < elements.length; i++) { if (elements[i] === focusedElement) { idx = i; } } idx += dir; navigationRoot.lastAriaIndex = moveFocusToIndex(idx, elements); } function left() { var parentRole = getParentRole(); if (parentRole === 'tablist') { moveFocus(-1, getFocusElements(focusedElement.parentNode)); } else if (focusedControl.parent().submenu) { cancel(); } else { moveFocus(-1); } } function right() { var role = getRole(), parentRole = getParentRole(); if (parentRole === 'tablist') { moveFocus(1, getFocusElements(focusedElement.parentNode)); } else if (role === 'menuitem' && parentRole === 'menu' && getAriaProp('haspopup')) { enter(); } else { moveFocus(1); } } function up() { moveFocus(-1); } function down() { var role = getRole(), parentRole = getParentRole(); if (role === 'menuitem' && parentRole === 'menubar') { enter(); } else if (role === 'button' && getAriaProp('haspopup')) { enter({ key: 'down' }); } else { moveFocus(1); } } function tab(e) { var parentRole = getParentRole(); if (parentRole === 'tablist') { var elm = getFocusElements(focusedControl.getEl('body'))[0]; if (elm) { elm.focus(); } } else { moveFocus(e.shiftKey ? -1 : 1); } } function cancel() { focusedControl.fire('cancel'); } function enter(aria) { aria = aria || {}; focusedControl.fire('click', { target: focusedElement, aria: aria }); } root.on('keydown', function (e) { function handleNonTabOrEscEvent(e, handler) { if (isTextInputElement(focusedElement) || hasTabstopData(focusedElement)) { return; } if (getRole(focusedElement) === 'slider') { return; } if (handler(e) !== false) { e.preventDefault(); } } if (e.isDefaultPrevented()) { return; } switch (e.keyCode) { case 37: handleNonTabOrEscEvent(e, left); break; case 39: handleNonTabOrEscEvent(e, right); break; case 38: handleNonTabOrEscEvent(e, up); break; case 40: handleNonTabOrEscEvent(e, down); break; case 27: cancel(); break; case 14: case 13: case 32: handleNonTabOrEscEvent(e, enter); break; case 9: tab(e); e.preventDefault(); break; } }); root.on('focusin', function (e) { focusedElement = e.target; focusedControl = e.control; }); return { focusFirst: focusFirst }; } var selectorCache = {}; var Container = Control$1.extend({ init: function (settings) { var self = this; self._super(settings); settings = self.settings; if (settings.fixed) { self.state.set('fixed', true); } self._items = new Collection$2(); if (self.isRtl()) { self.classes.add('rtl'); } self.bodyClasses = new ClassList(function () { if (self.state.get('rendered')) { self.getEl('body').className = this.toString(); } }); self.bodyClasses.prefix = self.classPrefix; self.classes.add('container'); self.bodyClasses.add('container-body'); if (settings.containerCls) { self.classes.add(settings.containerCls); } self._layout = global$4.create((settings.layout || '') + 'layout'); if (self.settings.items) { self.add(self.settings.items); } else { self.add(self.render()); } self._hasBody = true; }, items: function () { return this._items; }, find: function (selector) { selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector); return selector.find(this); }, add: function (items) { var self = this; self.items().add(self.create(items)).parent(self); return self; }, focus: function (keyboard) { var self = this; var focusCtrl, keyboardNav, items; if (keyboard) { keyboardNav = self.keyboardNav || self.parents().eq(-1)[0].keyboardNav; if (keyboardNav) { keyboardNav.focusFirst(self); return; } } items = self.find('*'); if (self.statusbar) { items.add(self.statusbar.items()); } items.each(function (ctrl) { if (ctrl.settings.autofocus) { focusCtrl = null; return false; } if (ctrl.canFocus) { focusCtrl = focusCtrl || ctrl; } }); if (focusCtrl) { focusCtrl.focus(); } return self; }, replace: function (oldItem, newItem) { var ctrlElm; var items = this.items(); var i = items.length; while (i--) { if (items[i] === oldItem) { items[i] = newItem; break; } } if (i >= 0) { ctrlElm = newItem.getEl(); if (ctrlElm) { ctrlElm.parentNode.removeChild(ctrlElm); } ctrlElm = oldItem.getEl(); if (ctrlElm) { ctrlElm.parentNode.removeChild(ctrlElm); } } newItem.parent(this); }, create: function (items) { var self = this; var settings; var ctrlItems = []; if (!global$2.isArray(items)) { items = [items]; } global$2.each(items, function (item) { if (item) { if (!(item instanceof Control$1)) { if (typeof item === 'string') { item = { type: item }; } settings = global$2.extend({}, self.settings.defaults, item); item.type = settings.type = settings.type || item.type || self.settings.defaultType || (settings.defaults ? settings.defaults.type : null); item = global$4.create(settings); } ctrlItems.push(item); } }); return ctrlItems; }, renderNew: function () { var self = this; self.items().each(function (ctrl, index) { var containerElm; ctrl.parent(self); if (!ctrl.state.get('rendered')) { containerElm = self.getEl('body'); if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) { global$9(containerElm.childNodes[index]).before(ctrl.renderHtml()); } else { global$9(containerElm).append(ctrl.renderHtml()); } ctrl.postRender(); $_ef12j5u4jh8lz3nl.add(ctrl); } }); self._layout.applyClasses(self.items().filter(':visible')); self._lastRect = null; return self; }, append: function (items) { return this.add(items).renderNew(); }, prepend: function (items) { var self = this; self.items().set(self.create(items).concat(self.items().toArray())); return self.renderNew(); }, insert: function (items, index, before) { var self = this; var curItems, beforeItems, afterItems; items = self.create(items); curItems = self.items(); if (!before && index < curItems.length - 1) { index += 1; } if (index >= 0 && index < curItems.length) { beforeItems = curItems.slice(0, index).toArray(); afterItems = curItems.slice(index).toArray(); curItems.set(beforeItems.concat(items, afterItems)); } return self.renderNew(); }, fromJSON: function (data) { var self = this; for (var name_1 in data) { self.find('#' + name_1).value(data[name_1]); } return self; }, toJSON: function () { var self = this, data = {}; self.find('*').each(function (ctrl) { var name = ctrl.name(), value = ctrl.value(); if (name && typeof value !== 'undefined') { data[name] = value; } }); return data; }, renderHtml: function () { var self = this, layout = self._layout, role = this.settings.role; self.preRender(); layout.preRender(self); return '<div id="' + self._id + '" class="' + self.classes + '"' + (role ? ' role="' + this.settings.role + '"' : '') + '>' + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>'; }, postRender: function () { var self = this; var box; self.items().exec('postRender'); self._super(); self._layout.postRender(self); self.state.set('rendered', true); if (self.settings.style) { self.$el.css(self.settings.style); } if (self.settings.border) { box = self.borderBox; self.$el.css({ 'border-top-width': box.top, 'border-right-width': box.right, 'border-bottom-width': box.bottom, 'border-left-width': box.left }); } if (!self.parent()) { self.keyboardNav = KeyboardNavigation({ root: self }); } return self; }, initLayoutRect: function () { var self = this, layoutRect = self._super(); self._layout.recalc(self); return layoutRect; }, recalc: function () { var self = this; var rect = self._layoutRect; var lastRect = self._lastRect; if (!lastRect || lastRect.w !== rect.w || lastRect.h !== rect.h) { self._layout.recalc(self); rect = self.layoutRect(); self._lastRect = { x: rect.x, y: rect.y, w: rect.w, h: rect.h }; return true; } }, reflow: function () { var i; $_ef12j5u4jh8lz3nl.remove(this); if (this.visible()) { Control$1.repaintControls = []; Control$1.repaintControls.map = {}; this.recalc(); i = Control$1.repaintControls.length; while (i--) { Control$1.repaintControls[i].repaint(); } if (this.settings.layout !== 'flow' && this.settings.layout !== 'stack') { this.repaint(); } Control$1.repaintControls = []; } return this; } }); function getDocumentSize(doc) { var documentElement, body, scrollWidth, clientWidth; var offsetWidth, scrollHeight, clientHeight, offsetHeight; var max = Math.max; documentElement = doc.documentElement; body = doc.body; scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); clientWidth = max(documentElement.clientWidth, body.clientWidth); offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); clientHeight = max(documentElement.clientHeight, body.clientHeight); offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); return { width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, height: scrollHeight < offsetHeight ? clientHeight : scrollHeight }; } function updateWithTouchData(e) { var keys, i; if (e.changedTouches) { keys = 'screenX screenY pageX pageY clientX clientY'.split(' '); for (i = 0; i < keys.length; i++) { e[keys[i]] = e.changedTouches[0][keys[i]]; } } } function DragHelper (id, settings) { var $eventOverlay; var doc = settings.document || document; var downButton; var start, stop, drag, startX, startY; settings = settings || {}; var handleElement = doc.getElementById(settings.handle || id); start = function (e) { var docSize = getDocumentSize(doc); var handleElm, cursor; updateWithTouchData(e); e.preventDefault(); downButton = e.button; handleElm = handleElement; startX = e.screenX; startY = e.screenY; if (window.getComputedStyle) { cursor = window.getComputedStyle(handleElm, null).getPropertyValue('cursor'); } else { cursor = handleElm.runtimeStyle.cursor; } $eventOverlay = global$9('<div></div>').css({ position: 'absolute', top: 0, left: 0, width: docSize.width, height: docSize.height, zIndex: 2147483647, opacity: 0.0001, cursor: cursor }).appendTo(doc.body); global$9(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop); settings.start(e); }; drag = function (e) { updateWithTouchData(e); if (e.button !== downButton) { return stop(e); } e.deltaX = e.screenX - startX; e.deltaY = e.screenY - startY; e.preventDefault(); settings.drag(e); }; stop = function (e) { updateWithTouchData(e); global$9(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop); $eventOverlay.remove(); if (settings.stop) { settings.stop(e); } }; this.destroy = function () { global$9(handleElement).off(); }; global$9(handleElement).on('mousedown touchstart', start); } var $_4acv48u6jh8lz3ns = { init: function () { var self = this; self.on('repaint', self.renderScroll); }, renderScroll: function () { var self = this, margin = 2; function repaintScroll() { var hasScrollH, hasScrollV, bodyElm; function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) { var containerElm, scrollBarElm, scrollThumbElm; var containerSize, scrollSize, ratio, rect; var posNameLower, sizeNameLower; scrollBarElm = self.getEl('scroll' + axisName); if (scrollBarElm) { posNameLower = posName.toLowerCase(); sizeNameLower = sizeName.toLowerCase(); global$9(self.getEl('absend')).css(posNameLower, self.layoutRect()[contentSizeName] - 1); if (!hasScroll) { global$9(scrollBarElm).css('display', 'none'); return; } global$9(scrollBarElm).css('display', 'block'); containerElm = self.getEl('body'); scrollThumbElm = self.getEl('scroll' + axisName + 't'); containerSize = containerElm['client' + sizeName] - margin * 2; containerSize -= hasScrollH && hasScrollV ? scrollBarElm['client' + ax] : 0; scrollSize = containerElm['scroll' + sizeName]; ratio = containerSize / scrollSize; rect = {}; rect[posNameLower] = containerElm['offset' + posName] + margin; rect[sizeNameLower] = containerSize; global$9(scrollBarElm).css(rect); rect = {}; rect[posNameLower] = containerElm['scroll' + posName] * ratio; rect[sizeNameLower] = containerSize * ratio; global$9(scrollThumbElm).css(rect); } } bodyElm = self.getEl('body'); hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth; hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight; repaintAxis('h', 'Left', 'Width', 'contentW', hasScrollH, 'Height'); repaintAxis('v', 'Top', 'Height', 'contentH', hasScrollV, 'Width'); } function addScroll() { function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) { var scrollStart; var axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix; global$9(self.getEl()).append('<div id="' + axisId + '" class="' + prefix + 'scrollbar ' + prefix + 'scrollbar-' + axisName + '">' + '<div id="' + axisId + 't" class="' + prefix + 'scrollbar-thumb"></div>' + '</div>'); self.draghelper = new DragHelper(axisId + 't', { start: function () { scrollStart = self.getEl('body')['scroll' + posName]; global$9('#' + axisId).addClass(prefix + 'active'); }, drag: function (e) { var ratio, hasScrollH, hasScrollV, containerSize; var layoutRect = self.layoutRect(); hasScrollH = layoutRect.contentW > layoutRect.innerW; hasScrollV = layoutRect.contentH > layoutRect.innerH; containerSize = self.getEl('body')['client' + sizeName] - margin * 2; containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)['client' + ax] : 0; ratio = containerSize / self.getEl('body')['scroll' + sizeName]; self.getEl('body')['scroll' + posName] = scrollStart + e['delta' + deltaPosName] / ratio; }, stop: function () { global$9('#' + axisId).removeClass(prefix + 'active'); } }); } self.classes.add('scroll'); addScrollAxis('v', 'Top', 'Height', 'Y', 'Width'); addScrollAxis('h', 'Left', 'Width', 'X', 'Height'); } if (self.settings.autoScroll) { if (!self._hasScroll) { self._hasScroll = true; addScroll(); self.on('wheel', function (e) { var bodyEl = self.getEl('body'); bodyEl.scrollLeft += (e.deltaX || 0) * 10; bodyEl.scrollTop += e.deltaY * 10; repaintScroll(); }); global$9(self.getEl('body')).on('scroll', repaintScroll); } repaintScroll(); } } }; var Panel = Container.extend({ Defaults: { layout: 'fit', containerCls: 'panel' }, Mixins: [$_4acv48u6jh8lz3ns], renderHtml: function () { var self = this; var layout = self._layout; var innerHtml = self.settings.html; self.preRender(); layout.preRender(self); if (typeof innerHtml === 'undefined') { innerHtml = '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + layout.renderHtml(self) + '</div>'; } else { if (typeof innerHtml === 'function') { innerHtml = innerHtml.call(self); } self._hasBody = false; } return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1" role="group">' + (self._preBodyHtml || '') + innerHtml + '</div>'; } }); var $_8a2gtru8jh8lz3ny = { resizeToContent: function () { this._layoutRect.autoResize = true; this._lastRect = null; this.reflow(); }, resizeTo: function (w, h) { if (w <= 1 || h <= 1) { var rect = funcs.getWindowSize(); w = w <= 1 ? w * rect.w : w; h = h <= 1 ? h * rect.h : h; } this._layoutRect.autoResize = false; return this.layoutRect({ minW: w, minH: h, w: w, h: h }).reflow(); }, resizeBy: function (dw, dh) { var self = this, rect = self.layoutRect(); return self.resizeTo(rect.w + dw, rect.h + dh); } }; var documentClickHandler; var documentScrollHandler; var windowResizeHandler; var visiblePanels = []; var zOrder = []; var hasModal; function isChildOf(ctrl, parent) { while (ctrl) { if (ctrl === parent) { return true; } ctrl = ctrl.parent(); } } function skipOrHidePanels(e) { var i = visiblePanels.length; while (i--) { var panel = visiblePanels[i], clickCtrl = panel.getParentCtrl(e.target); if (panel.settings.autohide) { if (clickCtrl) { if (isChildOf(clickCtrl, panel) || panel.parent() === clickCtrl) { continue; } } e = panel.fire('autohide', { target: e.target }); if (!e.isDefaultPrevented()) { panel.hide(); } } } } function bindDocumentClickHandler() { if (!documentClickHandler) { documentClickHandler = function (e) { if (e.button === 2) { return; } skipOrHidePanels(e); }; global$9(document).on('click touchstart', documentClickHandler); } } function bindDocumentScrollHandler() { if (!documentScrollHandler) { documentScrollHandler = function () { var i; i = visiblePanels.length; while (i--) { repositionPanel(visiblePanels[i]); } }; global$9(window).on('scroll', documentScrollHandler); } } function bindWindowResizeHandler() { if (!windowResizeHandler) { var docElm_1 = document.documentElement; var clientWidth_1 = docElm_1.clientWidth, clientHeight_1 = docElm_1.clientHeight; windowResizeHandler = function () { if (!document.all || clientWidth_1 !== docElm_1.clientWidth || clientHeight_1 !== docElm_1.clientHeight) { clientWidth_1 = docElm_1.clientWidth; clientHeight_1 = docElm_1.clientHeight; FloatPanel.hideAll(); } }; global$9(window).on('resize', windowResizeHandler); } } function repositionPanel(panel) { var scrollY = funcs.getViewPort().y; function toggleFixedChildPanels(fixed, deltaY) { var parent; for (var i = 0; i < visiblePanels.length; i++) { if (visiblePanels[i] !== panel) { parent = visiblePanels[i].parent(); while (parent && (parent = parent.parent())) { if (parent === panel) { visiblePanels[i].fixed(fixed).moveBy(0, deltaY).repaint(); } } } } } if (panel.settings.autofix) { if (!panel.state.get('fixed')) { panel._autoFixY = panel.layoutRect().y; if (panel._autoFixY < scrollY) { panel.fixed(true).layoutRect({ y: 0 }).repaint(); toggleFixedChildPanels(true, scrollY - panel._autoFixY); } } else { if (panel._autoFixY > scrollY) { panel.fixed(false).layoutRect({ y: panel._autoFixY }).repaint(); toggleFixedChildPanels(false, panel._autoFixY - scrollY); } } } } function addRemove(add, ctrl) { var i, zIndex = FloatPanel.zIndex || 65535, topModal; if (add) { zOrder.push(ctrl); } else { i = zOrder.length; while (i--) { if (zOrder[i] === ctrl) { zOrder.splice(i, 1); } } } if (zOrder.length) { for (i = 0; i < zOrder.length; i++) { if (zOrder[i].modal) { zIndex++; topModal = zOrder[i]; } zOrder[i].getEl().style.zIndex = zIndex; zOrder[i].zIndex = zIndex; zIndex++; } } var modalBlockEl = global$9('#' + ctrl.classPrefix + 'modal-block', ctrl.getContainerElm())[0]; if (topModal) { global$9(modalBlockEl).css('z-index', topModal.zIndex - 1); } else if (modalBlockEl) { modalBlockEl.parentNode.removeChild(modalBlockEl); hasModal = false; } FloatPanel.currentZIndex = zIndex; } var FloatPanel = Panel.extend({ Mixins: [ $_d97gfctrjh8lz3lm, $_8a2gtru8jh8lz3ny ], init: function (settings) { var self = this; self._super(settings); self._eventsRoot = self; self.classes.add('floatpanel'); if (settings.autohide) { bindDocumentClickHandler(); bindWindowResizeHandler(); visiblePanels.push(self); } if (settings.autofix) { bindDocumentScrollHandler(); self.on('move', function () { repositionPanel(this); }); } self.on('postrender show', function (e) { if (e.control === self) { var $modalBlockEl_1; var prefix_1 = self.classPrefix; if (self.modal && !hasModal) { $modalBlockEl_1 = global$9('#' + prefix_1 + 'modal-block', self.getContainerElm()); if (!$modalBlockEl_1[0]) { $modalBlockEl_1 = global$9('<div id="' + prefix_1 + 'modal-block" class="' + prefix_1 + 'reset ' + prefix_1 + 'fade"></div>').appendTo(self.getContainerElm()); } global$7.setTimeout(function () { $modalBlockEl_1.addClass(prefix_1 + 'in'); global$9(self.getEl()).addClass(prefix_1 + 'in'); }); hasModal = true; } addRemove(true, self); } }); self.on('show', function () { self.parents().each(function (ctrl) { if (ctrl.state.get('fixed')) { self.fixed(true); return false; } }); }); if (settings.popover) { self._preBodyHtml = '<div class="' + self.classPrefix + 'arrow"></div>'; self.classes.add('popover').add('bottom').add(self.isRtl() ? 'end' : 'start'); } self.aria('label', settings.ariaLabel); self.aria('labelledby', self._id); self.aria('describedby', self.describedBy || self._id + '-none'); }, fixed: function (state) { var self = this; if (self.state.get('fixed') !== state) { if (self.state.get('rendered')) { var viewport = funcs.getViewPort(); if (state) { self.layoutRect().y -= viewport.y; } else { self.layoutRect().y += viewport.y; } } self.classes.toggle('fixed', state); self.state.set('fixed', state); } return self; }, show: function () { var self = this; var i; var state = self._super(); i = visiblePanels.length; while (i--) { if (visiblePanels[i] === self) { break; } } if (i === -1) { visiblePanels.push(self); } return state; }, hide: function () { removeVisiblePanel(this); addRemove(false, this); return this._super(); }, hideAll: function () { FloatPanel.hideAll(); }, close: function () { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); addRemove(false, self); } return self; }, remove: function () { removeVisiblePanel(this); this._super(); }, postRender: function () { var self = this; if (self.settings.bodyRole) { this.getEl('body').setAttribute('role', self.settings.bodyRole); } return self._super(); } }); FloatPanel.hideAll = function () { var i = visiblePanels.length; while (i--) { var panel = visiblePanels[i]; if (panel && panel.settings.autohide) { panel.hide(); visiblePanels.splice(i, 1); } } }; function removeVisiblePanel(panel) { var i; i = visiblePanels.length; while (i--) { if (visiblePanels[i] === panel) { visiblePanels.splice(i, 1); } } i = zOrder.length; while (i--) { if (zOrder[i] === panel) { zOrder.splice(i, 1); } } } var isFixed$1 = function (inlineToolbarContainer, editor) { return !!(inlineToolbarContainer && !editor.settings.ui_container); }; var render$1 = function (editor, theme, args) { var panel, inlineToolbarContainer; var DOM = global$3.DOM; var fixedToolbarContainer = getFixedToolbarContainer(editor); if (fixedToolbarContainer) { inlineToolbarContainer = DOM.select(fixedToolbarContainer)[0]; } var reposition = function () { if (panel && panel.moveRel && panel.visible() && !panel._fixed) { var scrollContainer = editor.selection.getScrollContainer(), body = editor.getBody(); var deltaX = 0, deltaY = 0; if (scrollContainer) { var bodyPos = DOM.getPos(body), scrollContainerPos = DOM.getPos(scrollContainer); deltaX = Math.max(0, scrollContainerPos.x - bodyPos.x); deltaY = Math.max(0, scrollContainerPos.y - bodyPos.y); } panel.fixed(false).moveRel(body, editor.rtl ? [ 'tr-br', 'br-tr' ] : [ 'tl-bl', 'bl-tl', 'tr-br' ]).moveBy(deltaX, deltaY); } }; var show = function () { if (panel) { panel.show(); reposition(); DOM.addClass(editor.getBody(), 'mce-edit-focus'); } }; var hide = function () { if (panel) { panel.hide(); FloatPanel.hideAll(); DOM.removeClass(editor.getBody(), 'mce-edit-focus'); } }; var render = function () { if (panel) { if (!panel.visible()) { show(); } return; } panel = theme.panel = global$4.create({ type: inlineToolbarContainer ? 'panel' : 'floatpanel', role: 'application', classes: 'tinymce tinymce-inline', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: isFixed$1(inlineToolbarContainer, editor), fixed: isFixed$1(inlineToolbarContainer, editor), border: 1, items: [ hasMenubar(editor) === false ? null : { type: 'menubar', border: '0 0 1 0', items: $_8i78rftgjh8lz3ka.createMenuButtons(editor) }, $_fudqhrtfjh8lz3k7.createToolbars(editor, getToolbarSize(editor)) ] }); $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel); $_aycuj2t7jh8lz3jp.fireBeforeRenderUI(editor); if (inlineToolbarContainer) { panel.renderTo(inlineToolbarContainer).reflow(); } else { panel.renderTo().reflow(); } $_47hpztt8jh8lz3jq.addKeys(editor, panel); show(); $_5kodmdt9jh8lz3js.addContextualToolbars(editor); editor.on('nodeChange', reposition); editor.on('ResizeWindow', reposition); editor.on('activate', show); editor.on('deactivate', hide); editor.nodeChanged(); }; editor.settings.content_editable = true; editor.on('focus', function () { if (isSkinDisabled(editor) === false && args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, render, render); } else { render(); } }); editor.on('blur hide', hide); editor.on('remove', function () { if (panel) { panel.remove(); panel = null; } }); if (isSkinDisabled(editor) === false && args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, $_231e94tmjh8lz3ku.fireSkinLoaded(editor)); } else { $_231e94tmjh8lz3ku.fireSkinLoaded(editor)(); } return {}; }; var $_7wdylstnjh8lz3kv = { render: render$1 }; function Throbber (elm, inline) { var self = this; var state; var classPrefix = Control$1.classPrefix; var timer; self.show = function (time, callback) { function render() { if (state) { global$9(elm).append('<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>'); if (callback) { callback(); } } } self.hide(); state = true; if (time) { timer = global$7.setTimeout(render, time); } else { render(); } return self; }; self.hide = function () { var child = elm.lastChild; global$7.clearTimeout(timer); if (child && child.className.indexOf('throbber') !== -1) { child.parentNode.removeChild(child); } state = false; return self; }; } var setup = function (editor, theme) { var throbber; editor.on('ProgressState', function (e) { throbber = throbber || new Throbber(theme.panel.getEl('body')); if (e.state) { throbber.show(e.time); } else { throbber.hide(); } }); }; var $_e9w0qfu9jh8lz3nz = { setup: setup }; var renderUI = function (editor, theme, args) { var skinUrl = getSkinUrl(editor); if (skinUrl) { args.skinUiCss = skinUrl + '/skin.min.css'; editor.contentCSS.push(skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css'); } $_e9w0qfu9jh8lz3nz.setup(editor, theme); return isInline(editor) ? $_7wdylstnjh8lz3kv.render(editor, theme, args) : $_4cj0a3t3jh8lz3jk.render(editor, theme, args); }; var $_5ent4szjh8lz3ja = { renderUI: renderUI }; var Tooltip = Control$1.extend({ Mixins: [$_d97gfctrjh8lz3lm], Defaults: { classes: 'widget tooltip tooltip-n' }, renderHtml: function () { var self = this, prefix = self.classPrefix; return '<div id="' + self._id + '" class="' + self.classes + '" role="presentation">' + '<div class="' + prefix + 'tooltip-arrow"></div>' + '<div class="' + prefix + 'tooltip-inner">' + self.encode(self.state.get('text')) + '</div>' + '</div>'; }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.getEl().lastChild.innerHTML = self.encode(e.value); }); return self._super(); }, repaint: function () { var self = this; var style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; style.zIndex = 65535 + 65535; } }); var Widget = Control$1.extend({ init: function (settings) { var self = this; self._super(settings); settings = self.settings; self.canFocus = true; if (settings.tooltip && Widget.tooltips !== false) { self.on('mouseenter', function (e) { var tooltip = self.tooltip().moveTo(-65535); if (e.control === self) { var rel = tooltip.text(settings.tooltip).show().testMoveRel(self.getEl(), [ 'bc-tc', 'bc-tl', 'bc-tr' ]); tooltip.classes.toggle('tooltip-n', rel === 'bc-tc'); tooltip.classes.toggle('tooltip-nw', rel === 'bc-tl'); tooltip.classes.toggle('tooltip-ne', rel === 'bc-tr'); tooltip.moveRel(self.getEl(), rel); } else { tooltip.hide(); } }); self.on('mouseleave mousedown click', function () { self.tooltip().remove(); self._tooltip = null; }); } self.aria('label', settings.ariaLabel || settings.tooltip); }, tooltip: function () { if (!this._tooltip) { this._tooltip = new Tooltip({ type: 'tooltip' }); $_1jk3jvtcjh8lz3jy.inheritUiContainer(this, this._tooltip); this._tooltip.renderTo(); } return this._tooltip; }, postRender: function () { var self = this, settings = self.settings; self._super(); if (!self.parent() && (settings.width || settings.height)) { self.initLayoutRect(); self.repaint(); } if (settings.autofocus) { self.focus(); } }, bindStates: function () { var self = this; function disable(state) { self.aria('disabled', state); self.classes.toggle('disabled', state); } function active(state) { self.aria('pressed', state); self.classes.toggle('active', state); } self.state.on('change:disabled', function (e) { disable(e.value); }); self.state.on('change:active', function (e) { active(e.value); }); if (self.state.get('disabled')) { disable(true); } if (self.state.get('active')) { active(true); } return self._super(); }, remove: function () { this._super(); if (this._tooltip) { this._tooltip.remove(); this._tooltip = null; } } }); var Progress = Widget.extend({ Defaults: { value: 0 }, init: function (settings) { var self = this; self._super(settings); self.classes.add('progress'); if (!self.settings.filter) { self.settings.filter = function (value) { return Math.round(value); }; } }, renderHtml: function () { var self = this, id = self._id, prefix = this.classPrefix; return '<div id="' + id + '" class="' + self.classes + '">' + '<div class="' + prefix + 'bar-container">' + '<div class="' + prefix + 'bar"></div>' + '</div>' + '<div class="' + prefix + 'text">0%</div>' + '</div>'; }, postRender: function () { var self = this; self._super(); self.value(self.settings.value); return self; }, bindStates: function () { var self = this; function setValue(value) { value = self.settings.filter(value); self.getEl().lastChild.innerHTML = value + '%'; self.getEl().firstChild.firstChild.style.width = value + '%'; } self.state.on('change:value', function (e) { setValue(e.value); }); setValue(self.state.get('value')); return self._super(); } }); var updateLiveRegion = function (ctx, text) { ctx.getEl().lastChild.textContent = text + (ctx.progressBar ? ' ' + ctx.progressBar.value() + '%' : ''); }; var Notification = Control$1.extend({ Mixins: [$_d97gfctrjh8lz3lm], Defaults: { classes: 'widget notification' }, init: function (settings) { var self = this; self._super(settings); self.maxWidth = settings.maxWidth; if (settings.text) { self.text(settings.text); } if (settings.icon) { self.icon = settings.icon; } if (settings.color) { self.color = settings.color; } if (settings.type) { self.classes.add('notification-' + settings.type); } if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) { self.closeButton = false; } else { self.classes.add('has-close'); self.closeButton = true; } if (settings.progressBar) { self.progressBar = new Progress(); } self.on('click', function (e) { if (e.target.className.indexOf(self.classPrefix + 'close') !== -1) { self.close(); } }); }, renderHtml: function () { var self = this; var prefix = self.classPrefix; var icon = '', closeButton = '', progressBar = '', notificationStyle = ''; if (self.icon) { icon = '<i class="' + prefix + 'ico' + ' ' + prefix + 'i-' + self.icon + '"></i>'; } notificationStyle = ' style="max-width: ' + self.maxWidth + 'px;' + (self.color ? 'background-color: ' + self.color + ';"' : '"'); if (self.closeButton) { closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\xD7</button>'; } if (self.progressBar) { progressBar = self.progressBar.renderHtml(); } return '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '<div style="clip: rect(1px, 1px, 1px, 1px);height: 1px;overflow: hidden;position: absolute;width: 1px;"' + ' aria-live="assertive" aria-relevant="additions" aria-atomic="true"></div>' + '</div>'; }, postRender: function () { var self = this; global$7.setTimeout(function () { self.$el.addClass(self.classPrefix + 'in'); updateLiveRegion(self, self.state.get('text')); }, 100); return self._super(); }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.getEl().firstChild.innerHTML = e.value; updateLiveRegion(self, e.value); }); if (self.progressBar) { self.progressBar.bindStates(); self.progressBar.state.on('change:value', function (e) { updateLiveRegion(self, self.state.get('text')); }); } return self._super(); }, close: function () { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); } return self; }, repaint: function () { var self = this; var style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; style.zIndex = 65535 - 1; } }); function NotificationManagerImpl (editor) { var getEditorContainer = function (editor) { return editor.inline ? editor.getElement() : editor.getContentAreaContainer(); }; var getContainerWidth = function () { var container = getEditorContainer(editor); return funcs.getSize(container).width; }; var prePositionNotifications = function (notifications) { $_f3qxhzthjh8lz3kg.each(notifications, function (notification) { notification.moveTo(0, 0); }); }; var positionNotifications = function (notifications) { if (notifications.length > 0) { var firstItem = notifications.slice(0, 1)[0]; var container = getEditorContainer(editor); firstItem.moveRel(container, 'tc-tc'); $_f3qxhzthjh8lz3kg.each(notifications, function (notification, index) { if (index > 0) { notification.moveRel(notifications[index - 1].getEl(), 'bc-tc'); } }); } }; var reposition = function (notifications) { prePositionNotifications(notifications); positionNotifications(notifications); }; var open = function (args, closeCallback) { var extendedArgs = global$2.extend(args, { maxWidth: getContainerWidth() }); var notif = new Notification(extendedArgs); notif.args = extendedArgs; if (extendedArgs.timeout > 0) { notif.timer = setTimeout(function () { notif.close(); closeCallback(); }, extendedArgs.timeout); } notif.on('close', function () { closeCallback(); }); notif.renderTo(); return notif; }; var close = function (notification) { notification.close(); }; var getArgs = function (notification) { return notification.args; }; return { open: open, close: close, reposition: reposition, getArgs: getArgs }; } var windows = []; var oldMetaValue = ''; function toggleFullScreenState(state) { var noScaleMetaValue = 'width=device-width,initial-scale=1.0,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0'; var viewport = global$9('meta[name=viewport]')[0], contentValue; if (global$8.overrideViewPort === false) { return; } if (!viewport) { viewport = document.createElement('meta'); viewport.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(viewport); } contentValue = viewport.getAttribute('content'); if (contentValue && typeof oldMetaValue !== 'undefined') { oldMetaValue = contentValue; } viewport.setAttribute('content', state ? noScaleMetaValue : oldMetaValue); } function toggleBodyFullScreenClasses(classPrefix, state) { if (checkFullscreenWindows() && state === false) { global$9([ document.documentElement, document.body ]).removeClass(classPrefix + 'fullscreen'); } } function checkFullscreenWindows() { for (var i = 0; i < windows.length; i++) { if (windows[i]._fullscreen) { return true; } } return false; } function handleWindowResize() { if (!global$8.desktop) { var lastSize_1 = { w: window.innerWidth, h: window.innerHeight }; global$7.setInterval(function () { var w = window.innerWidth, h = window.innerHeight; if (lastSize_1.w !== w || lastSize_1.h !== h) { lastSize_1 = { w: w, h: h }; global$9(window).trigger('resize'); } }, 100); } function reposition() { var i; var rect = funcs.getWindowSize(); var layoutRect; for (i = 0; i < windows.length; i++) { layoutRect = windows[i].layoutRect(); windows[i].moveTo(windows[i].settings.x || Math.max(0, rect.w / 2 - layoutRect.w / 2), windows[i].settings.y || Math.max(0, rect.h / 2 - layoutRect.h / 2)); } } global$9(window).on('resize', reposition); } var Window = FloatPanel.extend({ modal: true, Defaults: { border: 1, layout: 'flex', containerCls: 'panel', role: 'dialog', callbacks: { submit: function () { this.fire('submit', { data: this.toJSON() }); }, close: function () { this.close(); } } }, init: function (settings) { var self = this; self._super(settings); if (self.isRtl()) { self.classes.add('rtl'); } self.classes.add('window'); self.bodyClasses.add('window-body'); self.state.set('fixed', true); if (settings.buttons) { self.statusbar = new Panel({ layout: 'flex', border: '1 0 0 0', spacing: 3, padding: 10, align: 'center', pack: self.isRtl() ? 'start' : 'end', defaults: { type: 'button' }, items: settings.buttons }); self.statusbar.classes.add('foot'); self.statusbar.parent(self); } self.on('click', function (e) { var closeClass = self.classPrefix + 'close'; if (funcs.hasClass(e.target, closeClass) || funcs.hasClass(e.target.parentNode, closeClass)) { self.close(); } }); self.on('cancel', function () { self.close(); }); self.on('move', function (e) { if (e.control === self) { FloatPanel.hideAll(); } }); self.aria('describedby', self.describedBy || self._id + '-none'); self.aria('label', settings.title); self._fullscreen = false; }, recalc: function () { var self = this; var statusbar = self.statusbar; var layoutRect, width, x, needsRecalc; if (self._fullscreen) { self.layoutRect(funcs.getWindowSize()); self.layoutRect().contentH = self.layoutRect().innerH; } self._super(); layoutRect = self.layoutRect(); if (self.settings.title && !self._fullscreen) { width = layoutRect.headerW; if (width > layoutRect.w) { x = layoutRect.x - Math.max(0, width / 2); self.layoutRect({ w: width, x: x }); needsRecalc = true; } } if (statusbar) { statusbar.layoutRect({ w: self.layoutRect().innerW }).recalc(); width = statusbar.layoutRect().minW + layoutRect.deltaW; if (width > layoutRect.w) { x = layoutRect.x - Math.max(0, width - layoutRect.w); self.layoutRect({ w: width, x: x }); needsRecalc = true; } } if (needsRecalc) { self.recalc(); } }, initLayoutRect: function () { var self = this; var layoutRect = self._super(); var deltaH = 0, headEl; if (self.settings.title && !self._fullscreen) { headEl = self.getEl('head'); var size = funcs.getSize(headEl); layoutRect.headerW = size.width; layoutRect.headerH = size.height; deltaH += layoutRect.headerH; } if (self.statusbar) { deltaH += self.statusbar.layoutRect().h; } layoutRect.deltaH += deltaH; layoutRect.minH += deltaH; layoutRect.h += deltaH; var rect = funcs.getWindowSize(); layoutRect.x = self.settings.x || Math.max(0, rect.w / 2 - layoutRect.w / 2); layoutRect.y = self.settings.y || Math.max(0, rect.h / 2 - layoutRect.h / 2); return layoutRect; }, renderHtml: function () { var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix; var settings = self.settings; var headerHtml = '', footerHtml = '', html = settings.html; self.preRender(); layout.preRender(self); if (settings.title) { headerHtml = '<div id="' + id + '-head" class="' + prefix + 'window-head">' + '<div id="' + id + '-title" class="' + prefix + 'title">' + self.encode(settings.title) + '</div>' + '<div id="' + id + '-dragh" class="' + prefix + 'dragh"></div>' + '<button type="button" class="' + prefix + 'close" aria-hidden="true">' + '<i class="mce-ico mce-i-remove"></i>' + '</button>' + '</div>'; } if (settings.url) { html = '<iframe src="' + settings.url + '" tabindex="-1"></iframe>'; } if (typeof html === 'undefined') { html = layout.renderHtml(self); } if (self.statusbar) { footerHtml = self.statusbar.renderHtml(); } return '<div id="' + id + '" class="' + self.classes + '" hidefocus="1">' + '<div class="' + self.classPrefix + 'reset" role="application">' + headerHtml + '<div id="' + id + '-body" class="' + self.bodyClasses + '">' + html + '</div>' + footerHtml + '</div>' + '</div>'; }, fullscreen: function (state) { var self = this; var documentElement = document.documentElement; var slowRendering; var prefix = self.classPrefix; var layoutRect; if (state !== self._fullscreen) { global$9(window).on('resize', function () { var time; if (self._fullscreen) { if (!slowRendering) { time = new Date().getTime(); var rect = funcs.getWindowSize(); self.moveTo(0, 0).resizeTo(rect.w, rect.h); if (new Date().getTime() - time > 50) { slowRendering = true; } } else { if (!self._timer) { self._timer = global$7.setTimeout(function () { var rect = funcs.getWindowSize(); self.moveTo(0, 0).resizeTo(rect.w, rect.h); self._timer = 0; }, 50); } } } }); layoutRect = self.layoutRect(); self._fullscreen = state; if (!state) { self.borderBox = $_focdcktxjh8lz3mn.parseBox(self.settings.border); self.getEl('head').style.display = ''; layoutRect.deltaH += layoutRect.headerH; global$9([ documentElement, document.body ]).removeClass(prefix + 'fullscreen'); self.classes.remove('fullscreen'); self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h); } else { self._initial = { x: layoutRect.x, y: layoutRect.y, w: layoutRect.w, h: layoutRect.h }; self.borderBox = $_focdcktxjh8lz3mn.parseBox('0'); self.getEl('head').style.display = 'none'; layoutRect.deltaH -= layoutRect.headerH + 2; global$9([ documentElement, document.body ]).addClass(prefix + 'fullscreen'); self.classes.add('fullscreen'); var rect = funcs.getWindowSize(); self.moveTo(0, 0).resizeTo(rect.w, rect.h); } } return self.reflow(); }, postRender: function () { var self = this; var startPos; setTimeout(function () { self.classes.add('in'); self.fire('open'); }, 0); self._super(); if (self.statusbar) { self.statusbar.postRender(); } self.focus(); this.dragHelper = new DragHelper(self._id + '-dragh', { start: function () { startPos = { x: self.layoutRect().x, y: self.layoutRect().y }; }, drag: function (e) { self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY); } }); self.on('submit', function (e) { if (!e.isDefaultPrevented()) { self.close(); } }); windows.push(self); toggleFullScreenState(true); }, submit: function () { return this.fire('submit', { data: this.toJSON() }); }, remove: function () { var self = this; var i; self.dragHelper.destroy(); self._super(); if (self.statusbar) { this.statusbar.remove(); } toggleBodyFullScreenClasses(self.classPrefix, false); i = windows.length; while (i--) { if (windows[i] === self) { windows.splice(i, 1); } } toggleFullScreenState(windows.length > 0); }, getContentWindow: function () { var ifr = this.getEl().getElementsByTagName('iframe')[0]; return ifr ? ifr.contentWindow : null; } }); handleWindowResize(); var MessageBox = Window.extend({ init: function (settings) { settings = { border: 1, padding: 20, layout: 'flex', pack: 'center', align: 'center', containerCls: 'panel', autoScroll: true, buttons: { type: 'button', text: 'Ok', action: 'ok' }, items: { type: 'label', multiline: true, maxWidth: 500, maxHeight: 200 } }; this._super(settings); }, Statics: { OK: 1, OK_CANCEL: 2, YES_NO: 3, YES_NO_CANCEL: 4, msgBox: function (settings) { var buttons; var callback = settings.callback || function () { }; function createButton(text, status, primary) { return { type: 'button', text: text, subtype: primary ? 'primary' : '', onClick: function (e) { e.control.parents()[1].close(); callback(status); } }; } switch (settings.buttons) { case MessageBox.OK_CANCEL: buttons = [ createButton('Ok', true, true), createButton('Cancel', false) ]; break; case MessageBox.YES_NO: case MessageBox.YES_NO_CANCEL: buttons = [ createButton('Yes', 1, true), createButton('No', 0) ]; if (settings.buttons === MessageBox.YES_NO_CANCEL) { buttons.push(createButton('Cancel', -1)); } break; default: buttons = [createButton('Ok', true, true)]; break; } return new Window({ padding: 20, x: settings.x, y: settings.y, minWidth: 300, minHeight: 100, layout: 'flex', pack: 'center', align: 'center', buttons: buttons, title: settings.title, role: 'alertdialog', items: { type: 'label', multiline: true, maxWidth: 500, maxHeight: 200, text: settings.text }, onPostRender: function () { this.aria('describedby', this.items()[0]._id); }, onClose: settings.onClose, onCancel: function () { callback(false); } }).renderTo(document.body).reflow(); }, alert: function (settings, callback) { if (typeof settings === 'string') { settings = { text: settings }; } settings.callback = callback; return MessageBox.msgBox(settings); }, confirm: function (settings, callback) { if (typeof settings === 'string') { settings = { text: settings }; } settings.callback = callback; settings.buttons = MessageBox.OK_CANCEL; return MessageBox.msgBox(settings); } } }); function WindowManagerImpl (editor) { var open = function (args, params, closeCallback) { var win; args.title = args.title || ' '; args.url = args.url || args.file; if (args.url) { args.width = parseInt(args.width || 320, 10); args.height = parseInt(args.height || 240, 10); } if (args.body) { args.items = { defaults: args.defaults, type: args.bodyType || 'form', items: args.body, data: args.data, callbacks: args.commands }; } if (!args.url && !args.buttons) { args.buttons = [ { text: 'Ok', subtype: 'primary', onclick: function () { win.find('form')[0].submit(); } }, { text: 'Cancel', onclick: function () { win.close(); } } ]; } win = new Window(args); win.on('close', function () { closeCallback(win); }); if (args.data) { win.on('postRender', function () { this.find('*').each(function (ctrl) { var name = ctrl.name(); if (name in args.data) { ctrl.value(args.data[name]); } }); }); } win.features = args || {}; win.params = params || {}; win = win.renderTo(document.body).reflow(); return win; }; var alert = function (message, choiceCallback, closeCallback) { var win; win = MessageBox.alert(message, function () { choiceCallback(); }); win.on('close', function () { closeCallback(win); }); return win; }; var confirm = function (message, choiceCallback, closeCallback) { var win; win = MessageBox.confirm(message, function (state) { choiceCallback(state); }); win.on('close', function () { closeCallback(win); }); return win; }; var close = function (window) { window.close(); }; var getParams = function (window) { return window.params; }; var setParams = function (window, params) { window.params = params; }; return { open: open, alert: alert, confirm: confirm, close: close, getParams: getParams, setParams: setParams }; } var get = function (editor) { var renderUI = function (args) { return $_5ent4szjh8lz3ja.renderUI(editor, this, args); }; var resizeTo = function (w, h) { return $_5toavetjjh8lz3ko.resizeTo(editor, w, h); }; var resizeBy = function (dw, dh) { return $_5toavetjjh8lz3ko.resizeBy(editor, dw, dh); }; var getNotificationManagerImpl = function () { return NotificationManagerImpl(editor); }; var getWindowManagerImpl = function () { return WindowManagerImpl(editor); }; return { renderUI: renderUI, resizeTo: resizeTo, resizeBy: resizeBy, getNotificationManagerImpl: getNotificationManagerImpl, getWindowManagerImpl: getWindowManagerImpl }; }; var $_1os0v5syjh8lz3j9 = { get: get }; var Layout = global$10.extend({ Defaults: { firstControlClass: 'first', lastControlClass: 'last' }, init: function (settings) { this.settings = global$2.extend({}, this.Defaults, settings); }, preRender: function (container) { container.bodyClasses.add(this.settings.containerClass); }, applyClasses: function (items) { var self = this; var settings = self.settings; var firstClass, lastClass, firstItem, lastItem; firstClass = settings.firstControlClass; lastClass = settings.lastControlClass; items.each(function (item) { item.classes.remove(firstClass).remove(lastClass).add(settings.controlClass); if (item.visible()) { if (!firstItem) { firstItem = item; } lastItem = item; } }); if (firstItem) { firstItem.classes.add(firstClass); } if (lastItem) { lastItem.classes.add(lastClass); } }, renderHtml: function (container) { var self = this; var html = ''; self.applyClasses(container.items()); container.items().each(function (item) { html += item.renderHtml(); }); return html; }, recalc: function () { }, postRender: function () { }, isNative: function () { return false; } }); var AbsoluteLayout = Layout.extend({ Defaults: { containerClass: 'abs-layout', controlClass: 'abs-layout-item' }, recalc: function (container) { container.items().filter(':visible').each(function (ctrl) { var settings = ctrl.settings; ctrl.layoutRect({ x: settings.x, y: settings.y, w: settings.w, h: settings.h }); if (ctrl.recalc) { ctrl.recalc(); } }); }, renderHtml: function (container) { return '<div id="' + container._id + '-absend" class="' + container.classPrefix + 'abs-end"></div>' + this._super(container); } }); var Button = Widget.extend({ Defaults: { classes: 'widget btn', role: 'button' }, init: function (settings) { var self = this; var size; self._super(settings); settings = self.settings; size = self.settings.size; self.on('click mousedown', function (e) { e.preventDefault(); }); self.on('touchstart', function (e) { self.fire('click', e); e.preventDefault(); }); if (settings.subtype) { self.classes.add(settings.subtype); } if (size) { self.classes.add('btn-' + size); } if (settings.icon) { self.icon(settings.icon); } }, icon: function (icon) { if (!arguments.length) { return this.state.get('icon'); } this.state.set('icon', icon); return this; }, repaint: function () { var btnElm = this.getEl().firstChild; var btnStyle; if (btnElm) { btnStyle = btnElm.style; btnStyle.width = btnStyle.height = '100%'; } this._super(); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; var icon = self.state.get('icon'), image; var text = self.state.get('text'); var textHtml = ''; var ariaPressed; var settings = self.settings; image = settings.image; if (image) { icon = 'none'; if (typeof image !== 'string') { image = window.getSelection ? image[0] : image[1]; } image = ' style="background-image: url(\'' + image + '\')"'; } else { image = ''; } if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } icon = icon ? prefix + 'ico ' + prefix + 'i-' + icon : ''; ariaPressed = typeof settings.active === 'boolean' ? ' aria-pressed="' + settings.active + '"' : ''; return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1"' + ariaPressed + '>' + '<button id="' + id + '-button" role="presentation" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + '</button>' + '</div>'; }, bindStates: function () { var self = this, $ = self.$, textCls = self.classPrefix + 'txt'; function setButtonText(text) { var $span = $('span.' + textCls, self.getEl()); if (text) { if (!$span[0]) { $('button:first', self.getEl()).append('<span class="' + textCls + '"></span>'); $span = $('span.' + textCls, self.getEl()); } $span.html(self.encode(text)); } else { $span.remove(); } self.classes.toggle('btn-has-text', !!text); } self.state.on('change:text', function (e) { setButtonText(e.value); }); self.state.on('change:icon', function (e) { var icon = e.value; var prefix = self.classPrefix; self.settings.icon = icon; icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; var btnElm = self.getEl().firstChild; var iconElm = btnElm.getElementsByTagName('i')[0]; if (icon) { if (!iconElm || iconElm !== btnElm.firstChild) { iconElm = document.createElement('i'); btnElm.insertBefore(iconElm, btnElm.firstChild); } iconElm.className = icon; } else if (iconElm) { btnElm.removeChild(iconElm); } setButtonText(self.state.get('text')); }); return self._super(); } }); var BrowseButton = Button.extend({ init: function (settings) { var self = this; settings = global$2.extend({ text: 'Browse...', multiple: false, accept: null }, settings); self._super(settings); self.classes.add('browsebutton'); if (settings.multiple) { self.classes.add('multiple'); } }, postRender: function () { var self = this; var input = funcs.create('input', { type: 'file', id: self._id + '-browse', accept: self.settings.accept }); self._super(); global$9(input).on('change', function (e) { var files = e.target.files; self.value = function () { if (!files.length) { return null; } else if (self.settings.multiple) { return files; } else { return files[0]; } }; e.preventDefault(); if (files.length) { self.fire('change', e); } }); global$9(input).on('click', function (e) { e.stopPropagation(); }); global$9(self.getEl('button')).on('click', function (e) { e.stopPropagation(); input.click(); }); self.getEl().appendChild(input); }, remove: function () { global$9(this.getEl('button')).off(); global$9(this.getEl('input')).off(); this._super(); } }); var ButtonGroup = Container.extend({ Defaults: { defaultType: 'button', role: 'group' }, renderHtml: function () { var self = this, layout = self._layout; self.classes.add('btn-group'); self.preRender(); layout.preRender(self); return '<div id="' + self._id + '" class="' + self.classes + '">' + '<div id="' + self._id + '-body">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>'; } }); var Checkbox = Widget.extend({ Defaults: { classes: 'checkbox', role: 'checkbox', checked: false }, init: function (settings) { var self = this; self._super(settings); self.on('click mousedown', function (e) { e.preventDefault(); }); self.on('click', function (e) { e.preventDefault(); if (!self.disabled()) { self.checked(!self.checked()); } }); self.checked(self.settings.checked); }, checked: function (state) { if (!arguments.length) { return this.state.get('checked'); } this.state.set('checked', state); return this; }, value: function (state) { if (!arguments.length) { return this.checked(); } return this.checked(state); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; return '<div id="' + id + '" class="' + self.classes + '" unselectable="on" aria-labelledby="' + id + '-al" tabindex="-1">' + '<i class="' + prefix + 'ico ' + prefix + 'i-checkbox"></i>' + '<span id="' + id + '-al" class="' + prefix + 'label">' + self.encode(self.state.get('text')) + '</span>' + '</div>'; }, bindStates: function () { var self = this; function checked(state) { self.classes.toggle('checked', state); self.aria('checked', state); } self.state.on('change:text', function (e) { self.getEl('al').firstChild.data = self.translate(e.value); }); self.state.on('change:checked change:value', function (e) { self.fire('change'); checked(e.value); }); self.state.on('change:icon', function (e) { var icon = e.value; var prefix = self.classPrefix; if (typeof icon === 'undefined') { return self.settings.icon; } self.settings.icon = icon; icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; var btnElm = self.getEl().firstChild; var iconElm = btnElm.getElementsByTagName('i')[0]; if (icon) { if (!iconElm || iconElm !== btnElm.firstChild) { iconElm = document.createElement('i'); btnElm.insertBefore(iconElm, btnElm.firstChild); } iconElm.className = icon; } else if (iconElm) { btnElm.removeChild(iconElm); } }); if (self.state.get('checked')) { checked(true); } return self._super(); } }); var global$13 = tinymce.util.Tools.resolve('tinymce.util.VK'); var ComboBox = Widget.extend({ init: function (settings) { var self = this; self._super(settings); settings = self.settings; self.classes.add('combobox'); self.subinput = true; self.ariaTarget = 'inp'; settings.menu = settings.menu || settings.values; if (settings.menu) { settings.icon = 'caret'; } self.on('click', function (e) { var elm = e.target; var root = self.getEl(); if (!global$9.contains(root, elm) && elm !== root) { return; } while (elm && elm !== root) { if (elm.id && elm.id.indexOf('-open') !== -1) { self.fire('action'); if (settings.menu) { self.showMenu(); if (e.aria) { self.menu.items()[0].focus(); } } } elm = elm.parentNode; } }); self.on('keydown', function (e) { var rootControl; if (e.keyCode === 13 && e.target.nodeName === 'INPUT') { e.preventDefault(); self.parents().reverse().each(function (ctrl) { if (ctrl.toJSON) { rootControl = ctrl; return false; } }); self.fire('submit', { data: rootControl.toJSON() }); } }); self.on('keyup', function (e) { if (e.target.nodeName === 'INPUT') { var oldValue = self.state.get('value'); var newValue = e.target.value; if (newValue !== oldValue) { self.state.set('value', newValue); self.fire('autocomplete', e); } } }); self.on('mouseover', function (e) { var tooltip = self.tooltip().moveTo(-65535); if (self.statusLevel() && e.target.className.indexOf(self.classPrefix + 'status') !== -1) { var statusMessage = self.statusMessage() || 'Ok'; var rel = tooltip.text(statusMessage).show().testMoveRel(e.target, [ 'bc-tc', 'bc-tl', 'bc-tr' ]); tooltip.classes.toggle('tooltip-n', rel === 'bc-tc'); tooltip.classes.toggle('tooltip-nw', rel === 'bc-tl'); tooltip.classes.toggle('tooltip-ne', rel === 'bc-tr'); tooltip.moveRel(e.target, rel); } }); }, statusLevel: function (value) { if (arguments.length > 0) { this.state.set('statusLevel', value); } return this.state.get('statusLevel'); }, statusMessage: function (value) { if (arguments.length > 0) { this.state.set('statusMessage', value); } return this.state.get('statusMessage'); }, showMenu: function () { var self = this; var settings = self.settings; var menu; if (!self.menu) { menu = settings.menu || []; if (menu.length) { menu = { type: 'menu', items: menu }; } else { menu.type = menu.type || 'menu'; } self.menu = global$4.create(menu).parent(self).renderTo(self.getContainerElm()); self.fire('createmenu'); self.menu.reflow(); self.menu.on('cancel', function (e) { if (e.control === self.menu) { self.focus(); } }); self.menu.on('show hide', function (e) { e.control.items().each(function (ctrl) { ctrl.active(ctrl.value() === self.value()); }); }).fire('show'); self.menu.on('select', function (e) { self.value(e.control.value()); }); self.on('focusin', function (e) { if (e.target.tagName.toUpperCase() === 'INPUT') { self.menu.hide(); } }); self.aria('expanded', true); } self.menu.show(); self.menu.layoutRect({ w: self.layoutRect().w }); self.menu.moveRel(self.getEl(), self.isRtl() ? [ 'br-tr', 'tr-br' ] : [ 'bl-tl', 'tl-bl' ]); }, focus: function () { this.getEl('inp').focus(); }, repaint: function () { var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect(); var width, lineHeight, innerPadding = 0; var inputElm = elm.firstChild; if (self.statusLevel() && self.statusLevel() !== 'none') { innerPadding = parseInt(funcs.getRuntimeStyle(inputElm, 'padding-right'), 10) - parseInt(funcs.getRuntimeStyle(inputElm, 'padding-left'), 10); } if (openElm) { width = rect.w - funcs.getSize(openElm).width - 10; } else { width = rect.w - 10; } var doc = document; if (doc.all && (!doc.documentMode || doc.documentMode <= 8)) { lineHeight = self.layoutRect().h - 2 + 'px'; } global$9(inputElm).css({ width: width - innerPadding, lineHeight: lineHeight }); self._super(); return self; }, postRender: function () { var self = this; global$9(this.getEl('inp')).on('change', function (e) { self.state.set('value', e.target.value); self.fire('change', e); }); return self._super(); }, renderHtml: function () { var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix; var value = self.state.get('value') || ''; var icon, text, openBtnHtml = '', extraAttrs = '', statusHtml = ''; if ('spellcheck' in settings) { extraAttrs += ' spellcheck="' + settings.spellcheck + '"'; } if (settings.maxLength) { extraAttrs += ' maxlength="' + settings.maxLength + '"'; } if (settings.size) { extraAttrs += ' size="' + settings.size + '"'; } if (settings.subtype) { extraAttrs += ' type="' + settings.subtype + '"'; } statusHtml = '<i id="' + id + '-status" class="mce-status mce-ico" style="display: none"></i>'; if (self.disabled()) { extraAttrs += ' disabled="disabled"'; } icon = settings.icon; if (icon && icon !== 'caret') { icon = prefix + 'ico ' + prefix + 'i-' + settings.icon; } text = self.state.get('text'); if (icon || text) { openBtnHtml = '<div id="' + id + '-open" class="' + prefix + 'btn ' + prefix + 'open" tabIndex="-1" role="button">' + '<button id="' + id + '-action" type="button" hidefocus="1" tabindex="-1">' + (icon !== 'caret' ? '<i class="' + icon + '"></i>' : '<i class="' + prefix + 'caret"></i>') + (text ? (icon ? ' ' : '') + text : '') + '</button>' + '</div>'; self.classes.add('has-open'); } return '<div id="' + id + '" class="' + self.classes + '">' + '<input id="' + id + '-inp" class="' + prefix + 'textbox" value="' + self.encode(value, false) + '" hidefocus="1"' + extraAttrs + ' placeholder="' + self.encode(settings.placeholder) + '" />' + statusHtml + openBtnHtml + '</div>'; }, value: function (value) { if (arguments.length) { this.state.set('value', value); return this; } if (this.state.get('rendered')) { this.state.set('value', this.getEl('inp').value); } return this.state.get('value'); }, showAutoComplete: function (items, term) { var self = this; if (items.length === 0) { self.hideMenu(); return; } var insert = function (value, title) { return function () { self.fire('selectitem', { title: title, value: value }); }; }; if (self.menu) { self.menu.items().remove(); } else { self.menu = global$4.create({ type: 'menu', classes: 'combobox-menu', layout: 'flow' }).parent(self).renderTo(); } global$2.each(items, function (item) { self.menu.add({ text: item.title, url: item.previewUrl, match: term, classes: 'menu-item-ellipsis', onclick: insert(item.value, item.title) }); }); self.menu.renderNew(); self.hideMenu(); self.menu.on('cancel', function (e) { if (e.control.parent() === self.menu) { e.stopPropagation(); self.focus(); self.hideMenu(); } }); self.menu.on('select', function () { self.focus(); }); var maxW = self.layoutRect().w; self.menu.layoutRect({ w: maxW, minW: 0, maxW: maxW }); self.menu.repaint(); self.menu.reflow(); self.menu.show(); self.menu.moveRel(self.getEl(), self.isRtl() ? [ 'br-tr', 'tr-br' ] : [ 'bl-tl', 'tl-bl' ]); }, hideMenu: function () { if (this.menu) { this.menu.hide(); } }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { if (self.getEl('inp').value !== e.value) { self.getEl('inp').value = e.value; } }); self.state.on('change:disabled', function (e) { self.getEl('inp').disabled = e.value; }); self.state.on('change:statusLevel', function (e) { var statusIconElm = self.getEl('status'); var prefix = self.classPrefix, value = e.value; funcs.css(statusIconElm, 'display', value === 'none' ? 'none' : ''); funcs.toggleClass(statusIconElm, prefix + 'i-checkmark', value === 'ok'); funcs.toggleClass(statusIconElm, prefix + 'i-warning', value === 'warn'); funcs.toggleClass(statusIconElm, prefix + 'i-error', value === 'error'); self.classes.toggle('has-status', value !== 'none'); self.repaint(); }); funcs.on(self.getEl('status'), 'mouseleave', function () { self.tooltip().hide(); }); self.on('cancel', function (e) { if (self.menu && self.menu.visible()) { e.stopPropagation(); self.hideMenu(); } }); var focusIdx = function (idx, menu) { if (menu && menu.items().length > 0) { menu.items().eq(idx)[0].focus(); } }; self.on('keydown', function (e) { var keyCode = e.keyCode; if (e.target.nodeName === 'INPUT') { if (keyCode === global$13.DOWN) { e.preventDefault(); self.fire('autocomplete'); focusIdx(0, self.menu); } else if (keyCode === global$13.UP) { e.preventDefault(); focusIdx(-1, self.menu); } } }); return self._super(); }, remove: function () { global$9(this.getEl('inp')).off(); if (this.menu) { this.menu.remove(); } this._super(); } }); var ColorBox = ComboBox.extend({ init: function (settings) { var self = this; settings.spellcheck = false; if (settings.onaction) { settings.icon = 'none'; } self._super(settings); self.classes.add('colorbox'); self.on('change keyup postrender', function () { self.repaintColor(self.value()); }); }, repaintColor: function (value) { var openElm = this.getEl('open'); var elm = openElm ? openElm.getElementsByTagName('i')[0] : null; if (elm) { try { elm.style.background = value; } catch (ex) { } } }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { if (self.state.get('rendered')) { self.repaintColor(e.value); } }); return self._super(); } }); var PanelButton = Button.extend({ showPanel: function () { var self = this, settings = self.settings; self.classes.add('opened'); if (!self.panel) { var panelSettings = settings.panel; if (panelSettings.type) { panelSettings = { layout: 'grid', items: panelSettings }; } panelSettings.role = panelSettings.role || 'dialog'; panelSettings.popover = true; panelSettings.autohide = true; panelSettings.ariaRoot = true; self.panel = new FloatPanel(panelSettings).on('hide', function () { self.classes.remove('opened'); }).on('cancel', function (e) { e.stopPropagation(); self.focus(); self.hidePanel(); }).parent(self).renderTo(self.getContainerElm()); self.panel.fire('show'); self.panel.reflow(); } else { self.panel.show(); } var rtlRels = [ 'bc-tc', 'bc-tl', 'bc-tr' ]; var ltrRels = [ 'bc-tc', 'bc-tr', 'bc-tl', 'tc-bc', 'tc-br', 'tc-bl' ]; var rel = self.panel.testMoveRel(self.getEl(), settings.popoverAlign || (self.isRtl() ? rtlRels : ltrRels)); self.panel.classes.toggle('start', rel.substr(-1) === 'l'); self.panel.classes.toggle('end', rel.substr(-1) === 'r'); var isTop = rel.substr(0, 1) === 't'; self.panel.classes.toggle('bottom', !isTop); self.panel.classes.toggle('top', isTop); self.panel.moveRel(self.getEl(), rel); }, hidePanel: function () { var self = this; if (self.panel) { self.panel.hide(); } }, postRender: function () { var self = this; self.aria('haspopup', true); self.on('click', function (e) { if (e.control === self) { if (self.panel && self.panel.visible()) { self.hidePanel(); } else { self.showPanel(); self.panel.focus(!!e.aria); } } }); return self._super(); }, remove: function () { if (this.panel) { this.panel.remove(); this.panel = null; } return this._super(); } }); var DOM$3 = global$3.DOM; var ColorButton = PanelButton.extend({ init: function (settings) { this._super(settings); this.classes.add('splitbtn'); this.classes.add('colorbutton'); }, color: function (color) { if (color) { this._color = color; this.getEl('preview').style.backgroundColor = color; return this; } return this._color; }, resetColor: function () { this._color = null; this.getEl('preview').style.backgroundColor = null; return this; }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix, text = self.state.get('text'); var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; var textHtml = ''; if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } return '<div id="' + id + '" class="' + self.classes + '" role="button" tabindex="-1" aria-haspopup="true">' + '<button role="presentation" hidefocus="1" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + '<span id="' + id + '-preview" class="' + prefix + 'preview"></span>' + textHtml + '</button>' + '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>'; }, postRender: function () { var self = this, onClickHandler = self.settings.onclick; self.on('click', function (e) { if (e.aria && e.aria.key === 'down') { return; } if (e.control === self && !DOM$3.getParent(e.target, '.' + self.classPrefix + 'open')) { e.stopImmediatePropagation(); onClickHandler.call(self, e); } }); delete self.settings.onclick; return self._super(); } }); var global$14 = tinymce.util.Tools.resolve('tinymce.util.Color'); var ColorPicker = Widget.extend({ Defaults: { classes: 'widget colorpicker' }, init: function (settings) { this._super(settings); }, postRender: function () { var self = this; var color = self.color(); var hsv, hueRootElm, huePointElm, svRootElm, svPointElm; hueRootElm = self.getEl('h'); huePointElm = self.getEl('hp'); svRootElm = self.getEl('sv'); svPointElm = self.getEl('svp'); function getPos(elm, event) { var pos = funcs.getPos(elm); var x, y; x = event.pageX - pos.x; y = event.pageY - pos.y; x = Math.max(0, Math.min(x / elm.clientWidth, 1)); y = Math.max(0, Math.min(y / elm.clientHeight, 1)); return { x: x, y: y }; } function updateColor(hsv, hueUpdate) { var hue = (360 - hsv.h) / 360; funcs.css(huePointElm, { top: hue * 100 + '%' }); if (!hueUpdate) { funcs.css(svPointElm, { left: hsv.s + '%', top: 100 - hsv.v + '%' }); } svRootElm.style.background = global$14({ s: 100, v: 100, h: hsv.h }).toHex(); self.color().parse({ s: hsv.s, v: hsv.v, h: hsv.h }); } function updateSaturationAndValue(e) { var pos; pos = getPos(svRootElm, e); hsv.s = pos.x * 100; hsv.v = (1 - pos.y) * 100; updateColor(hsv); self.fire('change'); } function updateHue(e) { var pos; pos = getPos(hueRootElm, e); hsv = color.toHsv(); hsv.h = (1 - pos.y) * 360; updateColor(hsv, true); self.fire('change'); } self._repaint = function () { hsv = color.toHsv(); updateColor(hsv); }; self._super(); self._svdraghelper = new DragHelper(self._id + '-sv', { start: updateSaturationAndValue, drag: updateSaturationAndValue }); self._hdraghelper = new DragHelper(self._id + '-h', { start: updateHue, drag: updateHue }); self._repaint(); }, rgb: function () { return this.color().toRgb(); }, value: function (value) { var self = this; if (arguments.length) { self.color().parse(value); if (self._rendered) { self._repaint(); } } else { return self.color().toHex(); } }, color: function () { if (!this._color) { this._color = global$14(); } return this._color; }, renderHtml: function () { var self = this; var id = self._id; var prefix = self.classPrefix; var hueHtml; var stops = '#ff0000,#ff0080,#ff00ff,#8000ff,#0000ff,#0080ff,#00ffff,#00ff80,#00ff00,#80ff00,#ffff00,#ff8000,#ff0000'; function getOldIeFallbackHtml() { var i, l, html = '', gradientPrefix, stopsList; gradientPrefix = 'filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='; stopsList = stops.split(','); for (i = 0, l = stopsList.length - 1; i < l; i++) { html += '<div class="' + prefix + 'colorpicker-h-chunk" style="' + 'height:' + 100 / l + '%;' + gradientPrefix + stopsList[i] + ',endColorstr=' + stopsList[i + 1] + ');' + '-ms-' + gradientPrefix + stopsList[i] + ',endColorstr=' + stopsList[i + 1] + ')' + '"></div>'; } return html; } var gradientCssText = 'background: -ms-linear-gradient(top,' + stops + ');' + 'background: linear-gradient(to bottom,' + stops + ');'; hueHtml = '<div id="' + id + '-h" class="' + prefix + 'colorpicker-h" style="' + gradientCssText + '">' + getOldIeFallbackHtml() + '<div id="' + id + '-hp" class="' + prefix + 'colorpicker-h-marker"></div>' + '</div>'; return '<div id="' + id + '" class="' + self.classes + '">' + '<div id="' + id + '-sv" class="' + prefix + 'colorpicker-sv">' + '<div class="' + prefix + 'colorpicker-overlay1">' + '<div class="' + prefix + 'colorpicker-overlay2">' + '<div id="' + id + '-svp" class="' + prefix + 'colorpicker-selector1">' + '<div class="' + prefix + 'colorpicker-selector2"></div>' + '</div>' + '</div>' + '</div>' + '</div>' + hueHtml + '</div>'; } }); var DropZone = Widget.extend({ init: function (settings) { var self = this; settings = global$2.extend({ height: 100, text: 'Drop an image here', multiple: false, accept: null }, settings); self._super(settings); self.classes.add('dropzone'); if (settings.multiple) { self.classes.add('multiple'); } }, renderHtml: function () { var self = this; var attrs, elm; var cfg = self.settings; attrs = { id: self._id, hidefocus: '1' }; elm = funcs.create('div', attrs, '<span>' + this.translate(cfg.text) + '</span>'); if (cfg.height) { funcs.css(elm, 'height', cfg.height + 'px'); } if (cfg.width) { funcs.css(elm, 'width', cfg.width + 'px'); } elm.className = self.classes; return elm.outerHTML; }, postRender: function () { var self = this; var toggleDragClass = function (e) { e.preventDefault(); self.classes.toggle('dragenter'); self.getEl().className = self.classes; }; var filter = function (files) { var accept = self.settings.accept; if (typeof accept !== 'string') { return files; } var re = new RegExp('(' + accept.split(/\s*,\s*/).join('|') + ')$', 'i'); return global$2.grep(files, function (file) { return re.test(file.name); }); }; self._super(); self.$el.on('dragover', function (e) { e.preventDefault(); }); self.$el.on('dragenter', toggleDragClass); self.$el.on('dragleave', toggleDragClass); self.$el.on('drop', function (e) { e.preventDefault(); if (self.state.get('disabled')) { return; } var files = filter(e.dataTransfer.files); self.value = function () { if (!files.length) { return null; } else if (self.settings.multiple) { return files; } else { return files[0]; } }; if (files.length) { self.fire('change', e); } }); }, remove: function () { this.$el.off(); this._super(); } }); var Path = Widget.extend({ init: function (settings) { var self = this; if (!settings.delimiter) { settings.delimiter = '\xBB'; } self._super(settings); self.classes.add('path'); self.canFocus = true; self.on('click', function (e) { var index; var target = e.target; if (index = target.getAttribute('data-index')) { self.fire('select', { value: self.row()[index], index: index }); } }); self.row(self.settings.row); }, focus: function () { var self = this; self.getEl().firstChild.focus(); return self; }, row: function (row) { if (!arguments.length) { return this.state.get('row'); } this.state.set('row', row); return this; }, renderHtml: function () { var self = this; return '<div id="' + self._id + '" class="' + self.classes + '">' + self._getDataPathHtml(self.state.get('row')) + '</div>'; }, bindStates: function () { var self = this; self.state.on('change:row', function (e) { self.innerHtml(self._getDataPathHtml(e.value)); }); return self._super(); }, _getDataPathHtml: function (data) { var self = this; var parts = data || []; var i, l, html = ''; var prefix = self.classPrefix; for (i = 0, l = parts.length; i < l; i++) { html += (i > 0 ? '<div class="' + prefix + 'divider" aria-hidden="true"> ' + self.settings.delimiter + ' </div>' : '') + '<div role="button" class="' + prefix + 'path-item' + (i === l - 1 ? ' ' + prefix + 'last' : '') + '" data-index="' + i + '" tabindex="-1" id="' + self._id + '-' + i + '" aria-level="' + (i + 1) + '">' + parts[i].name + '</div>'; } if (!html) { html = '<div class="' + prefix + 'path-item">\xA0</div>'; } return html; } }); var ElementPath = Path.extend({ postRender: function () { var self = this, editor = self.settings.editor; function isHidden(elm) { if (elm.nodeType === 1) { if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) { return true; } if (elm.getAttribute('data-mce-type') === 'bookmark') { return true; } } return false; } if (editor.settings.elementpath !== false) { self.on('select', function (e) { editor.focus(); editor.selection.select(this.row()[e.index].element); editor.nodeChanged(); }); editor.on('nodeChange', function (e) { var outParents = []; var parents = e.parents; var i = parents.length; while (i--) { if (parents[i].nodeType === 1 && !isHidden(parents[i])) { var args = editor.fire('ResolveName', { name: parents[i].nodeName.toLowerCase(), target: parents[i] }); if (!args.isDefaultPrevented()) { outParents.push({ name: args.name, element: parents[i] }); } if (args.isPropagationStopped()) { break; } } } self.row(outParents); }); } return self._super(); } }); var FormItem = Container.extend({ Defaults: { layout: 'flex', align: 'center', defaults: { flex: 1 } }, renderHtml: function () { var self = this, layout = self._layout, prefix = self.classPrefix; self.classes.add('formitem'); layout.preRender(self); return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + (self.settings.title ? '<div id="' + self._id + '-title" class="' + prefix + 'title">' + self.settings.title + '</div>' : '') + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>'; } }); var Form = Container.extend({ Defaults: { containerCls: 'form', layout: 'flex', direction: 'column', align: 'stretch', flex: 1, padding: 15, labelGap: 30, spacing: 10, callbacks: { submit: function () { this.submit(); } } }, preRender: function () { var self = this, items = self.items(); if (!self.settings.formItemDefaults) { self.settings.formItemDefaults = { layout: 'flex', autoResize: 'overflow', defaults: { flex: 1 } }; } items.each(function (ctrl) { var formItem; var label = ctrl.settings.label; if (label) { formItem = new FormItem(global$2.extend({ items: { type: 'label', id: ctrl._id + '-l', text: label, flex: 0, forId: ctrl._id, disabled: ctrl.disabled() } }, self.settings.formItemDefaults)); formItem.type = 'formitem'; ctrl.aria('labelledby', ctrl._id + '-l'); if (typeof ctrl.settings.flex === 'undefined') { ctrl.settings.flex = 1; } self.replace(ctrl, formItem); formItem.add(ctrl); } }); }, submit: function () { return this.fire('submit', { data: this.toJSON() }); }, postRender: function () { var self = this; self._super(); self.fromJSON(self.settings.data); }, bindStates: function () { var self = this; self._super(); function recalcLabels() { var maxLabelWidth = 0; var labels = []; var i, labelGap, items; if (self.settings.labelGapCalc === false) { return; } if (self.settings.labelGapCalc === 'children') { items = self.find('formitem'); } else { items = self.items(); } items.filter('formitem').each(function (item) { var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth; maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth; labels.push(labelCtrl); }); labelGap = self.settings.labelGap || 0; i = labels.length; while (i--) { labels[i].settings.minWidth = maxLabelWidth + labelGap; } } self.on('show', recalcLabels); recalcLabels(); } }); var FieldSet = Form.extend({ Defaults: { containerCls: 'fieldset', layout: 'flex', direction: 'column', align: 'stretch', flex: 1, padding: '25 15 5 15', labelGap: 30, spacing: 10, border: 1 }, renderHtml: function () { var self = this, layout = self._layout, prefix = self.classPrefix; self.preRender(); layout.preRender(self); return '<fieldset id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + (self.settings.title ? '<legend id="' + self._id + '-title" class="' + prefix + 'fieldset-title">' + self.settings.title + '</legend>' : '') + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</fieldset>'; } }); var unique$1 = 0; var generate = function (prefix) { var date = new Date(); var time = date.getTime(); var random = Math.floor(Math.random() * 1000000000); unique$1++; return prefix + '_' + random + unique$1 + String(time); }; var $_gdeezvv5jh8lz3rl = { generate: generate }; var fromHtml = function (html, scope) { var doc = scope || document; var div = doc.createElement('div'); div.innerHTML = html; if (!div.hasChildNodes() || div.childNodes.length > 1) { console.error('HTML does not have a single root node', html); throw 'HTML must have a single root node'; } return fromDom(div.childNodes[0]); }; var fromTag = function (tag, scope) { var doc = scope || document; var node = doc.createElement(tag); return fromDom(node); }; var fromText = function (text, scope) { var doc = scope || document; var node = doc.createTextNode(text); return fromDom(node); }; var fromDom = function (node) { if (node === null || node === undefined) throw new Error('Node cannot be null or undefined'); return { dom: $_3pjweotejh8lz3k4.constant(node) }; }; var fromPoint = function (doc, x, y) { return Option.from(doc.dom().elementFromPoint(x, y)).map(fromDom); }; var $_3bkrfxv6jh8lz3rm = { fromHtml: fromHtml, fromTag: fromTag, fromText: fromText, fromDom: fromDom, fromPoint: fromPoint }; var cached = function (f) { var called = false; var r; return function () { if (!called) { called = true; r = f.apply(null, arguments); } return r; }; }; var $_8me1xevajh8lz3s0 = { cached: cached }; var $_8xkvw6vcjh8lz3s2 = { ATTRIBUTE: 2, CDATA_SECTION: 4, COMMENT: 8, DOCUMENT: 9, DOCUMENT_TYPE: 10, DOCUMENT_FRAGMENT: 11, ELEMENT: 1, TEXT: 3, PROCESSING_INSTRUCTION: 7, ENTITY_REFERENCE: 5, ENTITY: 6, NOTATION: 12 }; var name = function (element) { var r = element.dom().nodeName; return r.toLowerCase(); }; var type = function (element) { return element.dom().nodeType; }; var value = function (element) { return element.dom().nodeValue; }; var isType$1 = function (t) { return function (element) { return type(element) === t; }; }; var isComment = function (element) { return type(element) === $_8xkvw6vcjh8lz3s2.COMMENT || name(element) === '#comment'; }; var isElement = isType$1($_8xkvw6vcjh8lz3s2.ELEMENT); var isText = isType$1($_8xkvw6vcjh8lz3s2.TEXT); var isDocument = isType$1($_8xkvw6vcjh8lz3s2.DOCUMENT); var $_11h2nlvbjh8lz3s1 = { name: name, type: type, value: value, isElement: isElement, isText: isText, isDocument: isDocument, isComment: isComment }; var inBody = function (element) { var dom = $_11h2nlvbjh8lz3s1.isText(element) ? element.dom().parentNode : element.dom(); return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom); }; var body = $_8me1xevajh8lz3s0.cached(function () { return getBody($_3bkrfxv6jh8lz3rm.fromDom(document)); }); var getBody = function (doc) { var body = doc.dom().body; if (body === null || body === undefined) throw 'Body is not available yet'; return $_3bkrfxv6jh8lz3rm.fromDom(body); }; var $_35bizev9jh8lz3rx = { body: body, getBody: getBody, inBody: inBody }; function Immutable () { var fields = []; for (var _i = 0; _i < arguments.length; _i++) { fields[_i] = arguments[_i]; } return function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } if (fields.length !== values.length) { throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments'); } var struct = {}; $_f3qxhzthjh8lz3kg.each(fields, function (name, i) { struct[name] = $_3pjweotejh8lz3k4.constant(values[i]); }); return struct; }; } var keys = function () { var fastKeys = Object.keys; var slowKeys = function (o) { var r = []; for (var i in o) { if (o.hasOwnProperty(i)) { r.push(i); } } return r; }; return fastKeys === undefined ? slowKeys : fastKeys; }(); var each$1 = function (obj, f) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; f(x, i, obj); } }; var objectMap = function (obj, f) { return tupleMap(obj, function (x, i, obj) { return { k: i, v: f(x, i, obj) }; }); }; var tupleMap = function (obj, f) { var r = {}; each$1(obj, function (x, i) { var tuple = f(x, i, obj); r[tuple.k] = tuple.v; }); return r; }; var bifilter = function (obj, pred) { var t = {}; var f = {}; each$1(obj, function (x, i) { var branch = pred(x, i) ? t : f; branch[i] = x; }); return { t: t, f: f }; }; var mapToArray = function (obj, f) { var r = []; each$1(obj, function (value, name) { r.push(f(value, name)); }); return r; }; var find$1 = function (obj, pred) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; if (pred(x, i, obj)) { return Option.some(x); } } return Option.none(); }; var values = function (obj) { return mapToArray(obj, function (v) { return v; }); }; var size = function (obj) { return values(obj).length; }; var $_el35e0vhjh8lz3sl = { bifilter: bifilter, each: each$1, map: objectMap, mapToArray: mapToArray, tupleMap: tupleMap, find: find$1, keys: keys, values: values, size: size }; var sort$1 = function (arr) { return arr.slice(0).sort(); }; var reqMessage = function (required, keys) { throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.'); }; var unsuppMessage = function (unsupported) { throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', ')); }; var validateStrArr = function (label, array) { if (!$_d8bie3tijh8lz3kn.isArray(array)) throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.'); $_f3qxhzthjh8lz3kg.each(array, function (a) { if (!$_d8bie3tijh8lz3kn.isString(a)) throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.'); }); }; var invalidTypeMessage = function (incorrect, type) { throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.'); }; var checkDupes = function (everything) { var sorted = sort$1(everything); var dupe = $_f3qxhzthjh8lz3kg.find(sorted, function (s, i) { return i < sorted.length - 1 && s === sorted[i + 1]; }); dupe.each(function (d) { throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].'); }); }; var $_6xoomwvijh8lz3sn = { sort: sort$1, reqMessage: reqMessage, unsuppMessage: unsuppMessage, validateStrArr: validateStrArr, invalidTypeMessage: invalidTypeMessage, checkDupes: checkDupes }; function MixedBag (required, optional) { var everything = required.concat(optional); if (everything.length === 0) throw new Error('You must specify at least one required or optional field.'); $_6xoomwvijh8lz3sn.validateStrArr('required', required); $_6xoomwvijh8lz3sn.validateStrArr('optional', optional); $_6xoomwvijh8lz3sn.checkDupes(everything); return function (obj) { var keys = $_el35e0vhjh8lz3sl.keys(obj); var allReqd = $_f3qxhzthjh8lz3kg.forall(required, function (req) { return $_f3qxhzthjh8lz3kg.contains(keys, req); }); if (!allReqd) $_6xoomwvijh8lz3sn.reqMessage(required, keys); var unsupported = $_f3qxhzthjh8lz3kg.filter(keys, function (key) { return !$_f3qxhzthjh8lz3kg.contains(everything, key); }); if (unsupported.length > 0) $_6xoomwvijh8lz3sn.unsuppMessage(unsupported); var r = {}; $_f3qxhzthjh8lz3kg.each(required, function (req) { r[req] = $_3pjweotejh8lz3k4.constant(obj[req]); }); $_f3qxhzthjh8lz3kg.each(optional, function (opt) { r[opt] = $_3pjweotejh8lz3k4.constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none()); }); return r; }; } var $_57mdu6vejh8lz3sg = { immutable: Immutable, immutableBag: MixedBag }; var toArray = function (target, f) { var r = []; var recurse = function (e) { r.push(e); return f(e); }; var cur = f(target); do { cur = cur.bind(recurse); } while (cur.isSome()); return r; }; var $_861s8bvjjh8lz3sp = { toArray: toArray }; var global$15 = typeof window !== 'undefined' ? window : Function('return this;')(); var path = function (parts, scope) { var o = scope !== undefined && scope !== null ? scope : global$15; for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i) o = o[parts[i]]; return o; }; var resolve = function (p, scope) { var parts = p.split('.'); return path(parts, scope); }; var step = function (o, part) { if (o[part] === undefined || o[part] === null) o[part] = {}; return o[part]; }; var forge = function (parts, target) { var o = target !== undefined ? target : global$15; for (var i = 0; i < parts.length; ++i) o = step(o, parts[i]); return o; }; var namespace = function (name, target) { var parts = name.split('.'); return forge(parts, target); }; var $_1cxe7nvnjh8lz3td = { path: path, resolve: resolve, forge: forge, namespace: namespace }; var unsafe = function (name, scope) { return $_1cxe7nvnjh8lz3td.resolve(name, scope); }; var getOrDie = function (name, scope) { var actual = unsafe(name, scope); if (actual === undefined || actual === null) throw name + ' not available on this browser'; return actual; }; var $_eol4qgvmjh8lz3t9 = { getOrDie: getOrDie }; var node = function () { var f = $_eol4qgvmjh8lz3t9.getOrDie('Node'); return f; }; var compareDocumentPosition = function (a, b, match) { return (a.compareDocumentPosition(b) & match) !== 0; }; var documentPositionPreceding = function (a, b) { return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING); }; var documentPositionContainedBy = function (a, b) { return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY); }; var $_7n27kvvljh8lz3t8 = { documentPositionPreceding: documentPositionPreceding, documentPositionContainedBy: documentPositionContainedBy }; var firstMatch = function (regexes, s) { for (var i = 0; i < regexes.length; i++) { var x = regexes[i]; if (x.test(s)) return x; } return undefined; }; var find$2 = function (regexes, agent) { var r = firstMatch(regexes, agent); if (!r) return { major: 0, minor: 0 }; var group = function (i) { return Number(agent.replace(r, '$' + i)); }; return nu(group(1), group(2)); }; var detect = function (versionRegexes, agent) { var cleanedAgent = String(agent).toLowerCase(); if (versionRegexes.length === 0) return unknown(); return find$2(versionRegexes, cleanedAgent); }; var unknown = function () { return nu(0, 0); }; var nu = function (major, minor) { return { major: major, minor: minor }; }; var $_afos0kvsjh8lz3tm = { nu: nu, detect: detect, unknown: unknown }; var edge = 'Edge'; var chrome = 'Chrome'; var ie = 'IE'; var opera = 'Opera'; var firefox = 'Firefox'; var safari = 'Safari'; var isBrowser = function (name, current) { return function () { return current === name; }; }; var unknown$1 = function () { return nu$1({ current: undefined, version: $_afos0kvsjh8lz3tm.unknown() }); }; var nu$1 = function (info) { var current = info.current; var version = info.version; return { current: current, version: version, isEdge: isBrowser(edge, current), isChrome: isBrowser(chrome, current), isIE: isBrowser(ie, current), isOpera: isBrowser(opera, current), isFirefox: isBrowser(firefox, current), isSafari: isBrowser(safari, current) }; }; var $_fidpetvrjh8lz3tj = { unknown: unknown$1, nu: nu$1, edge: $_3pjweotejh8lz3k4.constant(edge), chrome: $_3pjweotejh8lz3k4.constant(chrome), ie: $_3pjweotejh8lz3k4.constant(ie), opera: $_3pjweotejh8lz3k4.constant(opera), firefox: $_3pjweotejh8lz3k4.constant(firefox), safari: $_3pjweotejh8lz3k4.constant(safari) }; var windows$1 = 'Windows'; var ios = 'iOS'; var android = 'Android'; var linux = 'Linux'; var osx = 'OSX'; var solaris = 'Solaris'; var freebsd = 'FreeBSD'; var isOS = function (name, current) { return function () { return current === name; }; }; var unknown$2 = function () { return nu$2({ current: undefined, version: $_afos0kvsjh8lz3tm.unknown() }); }; var nu$2 = function (info) { var current = info.current; var version = info.version; return { current: current, version: version, isWindows: isOS(windows$1, current), isiOS: isOS(ios, current), isAndroid: isOS(android, current), isOSX: isOS(osx, current), isLinux: isOS(linux, current), isSolaris: isOS(solaris, current), isFreeBSD: isOS(freebsd, current) }; }; var $_1z8n9kvtjh8lz3to = { unknown: unknown$2, nu: nu$2, windows: $_3pjweotejh8lz3k4.constant(windows$1), ios: $_3pjweotejh8lz3k4.constant(ios), android: $_3pjweotejh8lz3k4.constant(android), linux: $_3pjweotejh8lz3k4.constant(linux), osx: $_3pjweotejh8lz3k4.constant(osx), solaris: $_3pjweotejh8lz3k4.constant(solaris), freebsd: $_3pjweotejh8lz3k4.constant(freebsd) }; function DeviceType (os, browser, userAgent) { var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; var isiPhone = os.isiOS() && !isiPad; var isAndroid3 = os.isAndroid() && os.version.major === 3; var isAndroid4 = os.isAndroid() && os.version.major === 4; var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true; var isTouch = os.isiOS() || os.isAndroid(); var isPhone = isTouch && !isTablet; var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; return { isiPad: $_3pjweotejh8lz3k4.constant(isiPad), isiPhone: $_3pjweotejh8lz3k4.constant(isiPhone), isTablet: $_3pjweotejh8lz3k4.constant(isTablet), isPhone: $_3pjweotejh8lz3k4.constant(isPhone), isTouch: $_3pjweotejh8lz3k4.constant(isTouch), isAndroid: os.isAndroid, isiOS: os.isiOS, isWebView: $_3pjweotejh8lz3k4.constant(iOSwebview) }; } var detect$1 = function (candidates, userAgent) { var agent = String(userAgent).toLowerCase(); return $_f3qxhzthjh8lz3kg.find(candidates, function (candidate) { return candidate.search(agent); }); }; var detectBrowser = function (browsers, userAgent) { return detect$1(browsers, userAgent).map(function (browser) { var version = $_afos0kvsjh8lz3tm.detect(browser.versionRegexes, userAgent); return { current: browser.name, version: version }; }); }; var detectOs = function (oses, userAgent) { return detect$1(oses, userAgent).map(function (os) { var version = $_afos0kvsjh8lz3tm.detect(os.versionRegexes, userAgent); return { current: os.name, version: version }; }); }; var $_bvrih8vvjh8lz3tv = { detectBrowser: detectBrowser, detectOs: detectOs }; var addToStart = function (str, prefix) { return prefix + str; }; var addToEnd = function (str, suffix) { return str + suffix; }; var removeFromStart = function (str, numChars) { return str.substring(numChars); }; var removeFromEnd = function (str, numChars) { return str.substring(0, str.length - numChars); }; var $_enj27ovyjh8lz3u7 = { addToStart: addToStart, addToEnd: addToEnd, removeFromStart: removeFromStart, removeFromEnd: removeFromEnd }; var first = function (str, count) { return str.substr(0, count); }; var last$1 = function (str, count) { return str.substr(str.length - count, str.length); }; var head$1 = function (str) { return str === '' ? Option.none() : Option.some(str.substr(0, 1)); }; var tail = function (str) { return str === '' ? Option.none() : Option.some(str.substring(1)); }; var $_49etxbvzjh8lz3u8 = { first: first, last: last$1, head: head$1, tail: tail }; var checkRange = function (str, substr, start) { if (substr === '') return true; if (str.length < substr.length) return false; var x = str.substr(start, start + substr.length); return x === substr; }; var supplant = function (str, obj) { var isStringOrNumber = function (a) { var t = typeof a; return t === 'string' || t === 'number'; }; return str.replace(/\${([^{}]*)}/g, function (a, b) { var value = obj[b]; return isStringOrNumber(value) ? value : a; }); }; var removeLeading = function (str, prefix) { return startsWith(str, prefix) ? $_enj27ovyjh8lz3u7.removeFromStart(str, prefix.length) : str; }; var removeTrailing = function (str, prefix) { return endsWith(str, prefix) ? $_enj27ovyjh8lz3u7.removeFromEnd(str, prefix.length) : str; }; var ensureLeading = function (str, prefix) { return startsWith(str, prefix) ? str : $_enj27ovyjh8lz3u7.addToStart(str, prefix); }; var ensureTrailing = function (str, prefix) { return endsWith(str, prefix) ? str : $_enj27ovyjh8lz3u7.addToEnd(str, prefix); }; var contains$1 = function (str, substr) { return str.indexOf(substr) !== -1; }; var capitalize = function (str) { return $_49etxbvzjh8lz3u8.head(str).bind(function (head) { return $_49etxbvzjh8lz3u8.tail(str).map(function (tail) { return head.toUpperCase() + tail; }); }).getOr(str); }; var startsWith = function (str, prefix) { return checkRange(str, prefix, 0); }; var endsWith = function (str, suffix) { return checkRange(str, suffix, str.length - suffix.length); }; var trim = function (str) { return str.replace(/^\s+|\s+$/g, ''); }; var lTrim = function (str) { return str.replace(/^\s+/g, ''); }; var rTrim = function (str) { return str.replace(/\s+$/g, ''); }; var $_2absfgvxjh8lz3u4 = { supplant: supplant, startsWith: startsWith, removeLeading: removeLeading, removeTrailing: removeTrailing, ensureLeading: ensureLeading, ensureTrailing: ensureTrailing, endsWith: endsWith, contains: contains$1, trim: trim, lTrim: lTrim, rTrim: rTrim, capitalize: capitalize }; var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; var checkContains = function (target) { return function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, target); }; }; var browsers = [ { name: 'Edge', versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], search: function (uastring) { var monstrosity = $_2absfgvxjh8lz3u4.contains(uastring, 'edge/') && $_2absfgvxjh8lz3u4.contains(uastring, 'chrome') && $_2absfgvxjh8lz3u4.contains(uastring, 'safari') && $_2absfgvxjh8lz3u4.contains(uastring, 'applewebkit'); return monstrosity; } }, { name: 'Chrome', versionRegexes: [ /.*?chrome\/([0-9]+)\.([0-9]+).*/, normalVersionRegex ], search: function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, 'chrome') && !$_2absfgvxjh8lz3u4.contains(uastring, 'chromeframe'); } }, { name: 'IE', versionRegexes: [ /.*?msie\ ?([0-9]+)\.([0-9]+).*/, /.*?rv:([0-9]+)\.([0-9]+).*/ ], search: function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, 'msie') || $_2absfgvxjh8lz3u4.contains(uastring, 'trident'); } }, { name: 'Opera', versionRegexes: [ normalVersionRegex, /.*?opera\/([0-9]+)\.([0-9]+).*/ ], search: checkContains('opera') }, { name: 'Firefox', versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/], search: checkContains('firefox') }, { name: 'Safari', versionRegexes: [ normalVersionRegex, /.*?cpu os ([0-9]+)_([0-9]+).*/ ], search: function (uastring) { return ($_2absfgvxjh8lz3u4.contains(uastring, 'safari') || $_2absfgvxjh8lz3u4.contains(uastring, 'mobile/')) && $_2absfgvxjh8lz3u4.contains(uastring, 'applewebkit'); } } ]; var oses = [ { name: 'Windows', search: checkContains('win'), versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/] }, { name: 'iOS', search: function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, 'iphone') || $_2absfgvxjh8lz3u4.contains(uastring, 'ipad'); }, versionRegexes: [ /.*?version\/\ ?([0-9]+)\.([0-9]+).*/, /.*cpu os ([0-9]+)_([0-9]+).*/, /.*cpu iphone os ([0-9]+)_([0-9]+).*/ ] }, { name: 'Android', search: checkContains('android'), versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/] }, { name: 'OSX', search: checkContains('os x'), versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/] }, { name: 'Linux', search: checkContains('linux'), versionRegexes: [] }, { name: 'Solaris', search: checkContains('sunos'), versionRegexes: [] }, { name: 'FreeBSD', search: checkContains('freebsd'), versionRegexes: [] } ]; var $_dne06dvwjh8lz3ty = { browsers: $_3pjweotejh8lz3k4.constant(browsers), oses: $_3pjweotejh8lz3k4.constant(oses) }; var detect$2 = function (userAgent) { var browsers = $_dne06dvwjh8lz3ty.browsers(); var oses = $_dne06dvwjh8lz3ty.oses(); var browser = $_bvrih8vvjh8lz3tv.detectBrowser(browsers, userAgent).fold($_fidpetvrjh8lz3tj.unknown, $_fidpetvrjh8lz3tj.nu); var os = $_bvrih8vvjh8lz3tv.detectOs(oses, userAgent).fold($_1z8n9kvtjh8lz3to.unknown, $_1z8n9kvtjh8lz3to.nu); var deviceType = DeviceType(os, browser, userAgent); return { browser: browser, os: os, deviceType: deviceType }; }; var $_8gsy8vqjh8lz3ti = { detect: detect$2 }; var detect$3 = $_8me1xevajh8lz3s0.cached(function () { var userAgent = navigator.userAgent; return $_8gsy8vqjh8lz3ti.detect(userAgent); }); var $_2rbkegvpjh8lz3tf = { detect: detect$3 }; var ELEMENT = $_8xkvw6vcjh8lz3s2.ELEMENT; var DOCUMENT = $_8xkvw6vcjh8lz3s2.DOCUMENT; var is = function (element, selector) { var elem = element.dom(); if (elem.nodeType !== ELEMENT) return false; else if (elem.matches !== undefined) return elem.matches(selector); else if (elem.msMatchesSelector !== undefined) return elem.msMatchesSelector(selector); else if (elem.webkitMatchesSelector !== undefined) return elem.webkitMatchesSelector(selector); else if (elem.mozMatchesSelector !== undefined) return elem.mozMatchesSelector(selector); else throw new Error('Browser lacks native selectors'); }; var bypassSelector = function (dom) { return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT || dom.childElementCount === 0; }; var all = function (selector, scope) { var base = scope === undefined ? document : scope.dom(); return bypassSelector(base) ? [] : $_f3qxhzthjh8lz3kg.map(base.querySelectorAll(selector), $_3bkrfxv6jh8lz3rm.fromDom); }; var one = function (selector, scope) { var base = scope === undefined ? document : scope.dom(); return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map($_3bkrfxv6jh8lz3rm.fromDom); }; var $_2nczsvw0jh8lz3ua = { all: all, is: is, one: one }; var eq = function (e1, e2) { return e1.dom() === e2.dom(); }; var isEqualNode = function (e1, e2) { return e1.dom().isEqualNode(e2.dom()); }; var member = function (element, elements) { return $_f3qxhzthjh8lz3kg.exists(elements, $_3pjweotejh8lz3k4.curry(eq, element)); }; var regularContains = function (e1, e2) { var d1 = e1.dom(), d2 = e2.dom(); return d1 === d2 ? false : d1.contains(d2); }; var ieContains = function (e1, e2) { return $_7n27kvvljh8lz3t8.documentPositionContainedBy(e1.dom(), e2.dom()); }; var browser = $_2rbkegvpjh8lz3tf.detect().browser; var contains$2 = browser.isIE() ? ieContains : regularContains; var $_9ypjy6vkjh8lz3sq = { eq: eq, isEqualNode: isEqualNode, member: member, contains: contains$2, is: $_2nczsvw0jh8lz3ua.is }; var owner = function (element) { return $_3bkrfxv6jh8lz3rm.fromDom(element.dom().ownerDocument); }; var documentElement = function (element) { var doc = owner(element); return $_3bkrfxv6jh8lz3rm.fromDom(doc.dom().documentElement); }; var defaultView = function (element) { var el = element.dom(); var defaultView = el.ownerDocument.defaultView; return $_3bkrfxv6jh8lz3rm.fromDom(defaultView); }; var parent = function (element) { var dom = element.dom(); return Option.from(dom.parentNode).map($_3bkrfxv6jh8lz3rm.fromDom); }; var findIndex$1 = function (element) { return parent(element).bind(function (p) { var kin = children(p); return $_f3qxhzthjh8lz3kg.findIndex(kin, function (elem) { return $_9ypjy6vkjh8lz3sq.eq(element, elem); }); }); }; var parents = function (element, isRoot) { var stop = $_d8bie3tijh8lz3kn.isFunction(isRoot) ? isRoot : $_3pjweotejh8lz3k4.constant(false); var dom = element.dom(); var ret = []; while (dom.parentNode !== null && dom.parentNode !== undefined) { var rawParent = dom.parentNode; var parent = $_3bkrfxv6jh8lz3rm.fromDom(rawParent); ret.push(parent); if (stop(parent) === true) break; else dom = rawParent; } return ret; }; var siblings = function (element) { var filterSelf = function (elements) { return $_f3qxhzthjh8lz3kg.filter(elements, function (x) { return !$_9ypjy6vkjh8lz3sq.eq(element, x); }); }; return parent(element).map(children).map(filterSelf).getOr([]); }; var offsetParent = function (element) { var dom = element.dom(); return Option.from(dom.offsetParent).map($_3bkrfxv6jh8lz3rm.fromDom); }; var prevSibling = function (element) { var dom = element.dom(); return Option.from(dom.previousSibling).map($_3bkrfxv6jh8lz3rm.fromDom); }; var nextSibling = function (element) { var dom = element.dom(); return Option.from(dom.nextSibling).map($_3bkrfxv6jh8lz3rm.fromDom); }; var prevSiblings = function (element) { return $_f3qxhzthjh8lz3kg.reverse($_861s8bvjjh8lz3sp.toArray(element, prevSibling)); }; var nextSiblings = function (element) { return $_861s8bvjjh8lz3sp.toArray(element, nextSibling); }; var children = function (element) { var dom = element.dom(); return $_f3qxhzthjh8lz3kg.map(dom.childNodes, $_3bkrfxv6jh8lz3rm.fromDom); }; var child = function (element, index) { var children = element.dom().childNodes; return Option.from(children[index]).map($_3bkrfxv6jh8lz3rm.fromDom); }; var firstChild = function (element) { return child(element, 0); }; var lastChild = function (element) { return child(element, element.dom().childNodes.length - 1); }; var childNodesCount = function (element) { return element.dom().childNodes.length; }; var hasChildNodes = function (element) { return element.dom().hasChildNodes(); }; var spot = $_57mdu6vejh8lz3sg.immutable('element', 'offset'); var leaf = function (element, offset) { var cs = children(element); return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset); }; var $_3jmbxmvdjh8lz3s4 = { owner: owner, defaultView: defaultView, documentElement: documentElement, parent: parent, findIndex: findIndex$1, parents: parents, siblings: siblings, prevSibling: prevSibling, offsetParent: offsetParent, prevSiblings: prevSiblings, nextSibling: nextSibling, nextSiblings: nextSiblings, children: children, child: child, firstChild: firstChild, lastChild: lastChild, childNodesCount: childNodesCount, hasChildNodes: hasChildNodes, leaf: leaf }; var all$1 = function (predicate) { return descendants($_35bizev9jh8lz3rx.body(), predicate); }; var ancestors = function (scope, predicate, isRoot) { return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.parents(scope, isRoot), predicate); }; var siblings$1 = function (scope, predicate) { return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.siblings(scope), predicate); }; var children$1 = function (scope, predicate) { return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.children(scope), predicate); }; var descendants = function (scope, predicate) { var result = []; $_f3qxhzthjh8lz3kg.each($_3jmbxmvdjh8lz3s4.children(scope), function (x) { if (predicate(x)) { result = result.concat([x]); } result = result.concat(descendants(x, predicate)); }); return result; }; var $_dz5cwuv8jh8lz3rt = { all: all$1, ancestors: ancestors, siblings: siblings$1, children: children$1, descendants: descendants }; var all$2 = function (selector) { return $_2nczsvw0jh8lz3ua.all(selector); }; var ancestors$1 = function (scope, selector, isRoot) { return $_dz5cwuv8jh8lz3rt.ancestors(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }, isRoot); }; var siblings$2 = function (scope, selector) { return $_dz5cwuv8jh8lz3rt.siblings(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var children$2 = function (scope, selector) { return $_dz5cwuv8jh8lz3rt.children(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var descendants$1 = function (scope, selector) { return $_2nczsvw0jh8lz3ua.all(selector, scope); }; var $_am3j0fv7jh8lz3rs = { all: all$2, ancestors: ancestors$1, siblings: siblings$2, children: children$2, descendants: descendants$1 }; var trim$1 = global$2.trim; var hasContentEditableState = function (value) { return function (node) { if (node && node.nodeType === 1) { if (node.contentEditable === value) { return true; } if (node.getAttribute('data-mce-contenteditable') === value) { return true; } } return false; }; }; var isContentEditableTrue = hasContentEditableState('true'); var isContentEditableFalse = hasContentEditableState('false'); var create = function (type, title, url, level, attach) { return { type: type, title: title, url: url, level: level, attach: attach }; }; var isChildOfContentEditableTrue = function (node) { while (node = node.parentNode) { var value = node.contentEditable; if (value && value !== 'inherit') { return isContentEditableTrue(node); } } return false; }; var select = function (selector, root) { return $_f3qxhzthjh8lz3kg.map($_am3j0fv7jh8lz3rs.descendants($_3bkrfxv6jh8lz3rm.fromDom(root), selector), function (element) { return element.dom(); }); }; var getElementText = function (elm) { return elm.innerText || elm.textContent; }; var getOrGenerateId = function (elm) { return elm.id ? elm.id : $_gdeezvv5jh8lz3rl.generate('h'); }; var isAnchor = function (elm) { return elm && elm.nodeName === 'A' && (elm.id || elm.name); }; var isValidAnchor = function (elm) { return isAnchor(elm) && isEditable(elm); }; var isHeader = function (elm) { return elm && /^(H[1-6])$/.test(elm.nodeName); }; var isEditable = function (elm) { return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm); }; var isValidHeader = function (elm) { return isHeader(elm) && isEditable(elm); }; var getLevel = function (elm) { return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0; }; var headerTarget = function (elm) { var headerId = getOrGenerateId(elm); var attach = function () { elm.id = headerId; }; return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach); }; var anchorTarget = function (elm) { var anchorId = elm.id || elm.name; var anchorText = getElementText(elm); return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, $_3pjweotejh8lz3k4.noop); }; var getHeaderTargets = function (elms) { return $_f3qxhzthjh8lz3kg.map($_f3qxhzthjh8lz3kg.filter(elms, isValidHeader), headerTarget); }; var getAnchorTargets = function (elms) { return $_f3qxhzthjh8lz3kg.map($_f3qxhzthjh8lz3kg.filter(elms, isValidAnchor), anchorTarget); }; var getTargetElements = function (elm) { var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm); return elms; }; var hasTitle = function (target) { return trim$1(target.title).length > 0; }; var find$3 = function (elm) { var elms = getTargetElements(elm); return $_f3qxhzthjh8lz3kg.filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle); }; var $_p3wpev4jh8lz3ra = { find: find$3 }; var getActiveEditor = function () { return window.tinymce ? window.tinymce.activeEditor : global$1.activeEditor; }; var history = {}; var HISTORY_LENGTH = 5; var clearHistory = function () { history = {}; }; var toMenuItem = function (target) { return { title: target.title, value: { title: { raw: target.title }, url: target.url, attach: target.attach } }; }; var toMenuItems = function (targets) { return global$2.map(targets, toMenuItem); }; var staticMenuItem = function (title, url) { return { title: title, value: { title: title, url: url, attach: $_3pjweotejh8lz3k4.noop } }; }; var isUniqueUrl = function (url, targets) { var foundTarget = $_f3qxhzthjh8lz3kg.exists(targets, function (target) { return target.url === url; }); return !foundTarget; }; var getSetting = function (editorSettings, name, defaultValue) { var value = name in editorSettings ? editorSettings[name] : defaultValue; return value === false ? null : value; }; var createMenuItems = function (term, targets, fileType, editorSettings) { var separator = { title: '-' }; var fromHistoryMenuItems = function (history) { var historyItems = history.hasOwnProperty(fileType) ? history[fileType] : []; var uniqueHistory = $_f3qxhzthjh8lz3kg.filter(historyItems, function (url) { return isUniqueUrl(url, targets); }); return global$2.map(uniqueHistory, function (url) { return { title: url, value: { title: url, url: url, attach: $_3pjweotejh8lz3k4.noop } }; }); }; var fromMenuItems = function (type) { var filteredTargets = $_f3qxhzthjh8lz3kg.filter(targets, function (target) { return target.type === type; }); return toMenuItems(filteredTargets); }; var anchorMenuItems = function () { var anchorMenuItems = fromMenuItems('anchor'); var topAnchor = getSetting(editorSettings, 'anchor_top', '#top'); var bottomAchor = getSetting(editorSettings, 'anchor_bottom', '#bottom'); if (topAnchor !== null) { anchorMenuItems.unshift(staticMenuItem('<top>', topAnchor)); } if (bottomAchor !== null) { anchorMenuItems.push(staticMenuItem('<bottom>', bottomAchor)); } return anchorMenuItems; }; var join = function (items) { return $_f3qxhzthjh8lz3kg.foldl(items, function (a, b) { var bothEmpty = a.length === 0 || b.length === 0; return bothEmpty ? a.concat(b) : a.concat(separator, b); }, []); }; if (editorSettings.typeahead_urls === false) { return []; } return fileType === 'file' ? join([ filterByQuery(term, fromHistoryMenuItems(history)), filterByQuery(term, fromMenuItems('header')), filterByQuery(term, anchorMenuItems()) ]) : filterByQuery(term, fromHistoryMenuItems(history)); }; var addToHistory = function (url, fileType) { var items = history[fileType]; if (!/^https?/.test(url)) { return; } if (items) { if ($_f3qxhzthjh8lz3kg.indexOf(items, url).isNone()) { history[fileType] = items.slice(0, HISTORY_LENGTH).concat(url); } } else { history[fileType] = [url]; } }; var filterByQuery = function (term, menuItems) { var lowerCaseTerm = term.toLowerCase(); var result = global$2.grep(menuItems, function (item) { return item.title.toLowerCase().indexOf(lowerCaseTerm) !== -1; }); return result.length === 1 && result[0].title === term ? [] : result; }; var getTitle = function (linkDetails) { var title = linkDetails.title; return title.raw ? title.raw : title; }; var setupAutoCompleteHandler = function (ctrl, editorSettings, bodyElm, fileType) { var autocomplete = function (term) { var linkTargets = $_p3wpev4jh8lz3ra.find(bodyElm); var menuItems = createMenuItems(term, linkTargets, fileType, editorSettings); ctrl.showAutoComplete(menuItems, term); }; ctrl.on('autocomplete', function () { autocomplete(ctrl.value()); }); ctrl.on('selectitem', function (e) { var linkDetails = e.value; ctrl.value(linkDetails.url); var title = getTitle(linkDetails); if (fileType === 'image') { ctrl.fire('change', { meta: { alt: title, attach: linkDetails.attach } }); } else { ctrl.fire('change', { meta: { text: title, attach: linkDetails.attach } }); } ctrl.focus(); }); ctrl.on('click', function (e) { if (ctrl.value().length === 0 && e.target.nodeName === 'INPUT') { autocomplete(''); } }); ctrl.on('PostRender', function () { ctrl.getRoot().on('submit', function (e) { if (!e.isDefaultPrevented()) { addToHistory(ctrl.value(), fileType); } }); }); }; var statusToUiState = function (result) { var status = result.status, message = result.message; if (status === 'valid') { return { status: 'ok', message: message }; } else if (status === 'unknown') { return { status: 'warn', message: message }; } else if (status === 'invalid') { return { status: 'warn', message: message }; } else { return { status: 'none', message: '' }; } }; var setupLinkValidatorHandler = function (ctrl, editorSettings, fileType) { var validatorHandler = editorSettings.filepicker_validator_handler; if (validatorHandler) { var validateUrl_1 = function (url) { if (url.length === 0) { ctrl.statusLevel('none'); return; } validatorHandler({ url: url, type: fileType }, function (result) { var uiState = statusToUiState(result); ctrl.statusMessage(uiState.message); ctrl.statusLevel(uiState.status); }); }; ctrl.state.on('change:value', function (e) { validateUrl_1(e.value); }); } }; var FilePicker = ComboBox.extend({ Statics: { clearHistory: clearHistory }, init: function (settings) { var self = this, editor = getActiveEditor(), editorSettings = editor.settings; var actionCallback, fileBrowserCallback, fileBrowserCallbackTypes; var fileType = settings.filetype; settings.spellcheck = false; fileBrowserCallbackTypes = editorSettings.file_picker_types || editorSettings.file_browser_callback_types; if (fileBrowserCallbackTypes) { fileBrowserCallbackTypes = global$2.makeMap(fileBrowserCallbackTypes, /[, ]/); } if (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType]) { fileBrowserCallback = editorSettings.file_picker_callback; if (fileBrowserCallback && (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType])) { actionCallback = function () { var meta = self.fire('beforecall').meta; meta = global$2.extend({ filetype: fileType }, meta); fileBrowserCallback.call(editor, function (value, meta) { self.value(value).fire('change', { meta: meta }); }, self.value(), meta); }; } else { fileBrowserCallback = editorSettings.file_browser_callback; if (fileBrowserCallback && (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType])) { actionCallback = function () { fileBrowserCallback(self.getEl('inp').id, self.value(), fileType, window); }; } } } if (actionCallback) { settings.icon = 'browse'; settings.onaction = actionCallback; } self._super(settings); self.classes.add('filepicker'); setupAutoCompleteHandler(self, editorSettings, editor.getBody(), fileType); setupLinkValidatorHandler(self, editorSettings, fileType); } }); var FitLayout = AbsoluteLayout.extend({ recalc: function (container) { var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox; container.items().filter(':visible').each(function (ctrl) { ctrl.layoutRect({ x: paddingBox.left, y: paddingBox.top, w: contLayoutRect.innerW - paddingBox.right - paddingBox.left, h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom }); if (ctrl.recalc) { ctrl.recalc(); } }); } }); var FlexLayout = AbsoluteLayout.extend({ recalc: function (container) { var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction; var ctrl, ctrlLayoutRect, ctrlSettings, flex; var maxSizeItems = []; var size, maxSize, ratio, rect, pos, maxAlignEndPos; var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, deltaSizeName, contentSizeName; var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignBeforeName, alignAfterName; var alignDeltaSizeName, alignContentSizeName; var max = Math.max, min = Math.min; items = container.items().filter(':visible'); contLayoutRect = container.layoutRect(); contPaddingBox = container.paddingBox; contSettings = container.settings; direction = container.isRtl() ? contSettings.direction || 'row-reversed' : contSettings.direction; align = contSettings.align; pack = container.isRtl() ? contSettings.pack || 'end' : contSettings.pack; spacing = contSettings.spacing || 0; if (direction === 'row-reversed' || direction === 'column-reverse') { items = items.set(items.toArray().reverse()); direction = direction.split('-')[0]; } if (direction === 'column') { posName = 'y'; sizeName = 'h'; minSizeName = 'minH'; maxSizeName = 'maxH'; innerSizeName = 'innerH'; beforeName = 'top'; deltaSizeName = 'deltaH'; contentSizeName = 'contentH'; alignBeforeName = 'left'; alignSizeName = 'w'; alignAxisName = 'x'; alignInnerSizeName = 'innerW'; alignMinSizeName = 'minW'; alignAfterName = 'right'; alignDeltaSizeName = 'deltaW'; alignContentSizeName = 'contentW'; } else { posName = 'x'; sizeName = 'w'; minSizeName = 'minW'; maxSizeName = 'maxW'; innerSizeName = 'innerW'; beforeName = 'left'; deltaSizeName = 'deltaW'; contentSizeName = 'contentW'; alignBeforeName = 'top'; alignSizeName = 'h'; alignAxisName = 'y'; alignInnerSizeName = 'innerH'; alignMinSizeName = 'minH'; alignAfterName = 'bottom'; alignDeltaSizeName = 'deltaH'; alignContentSizeName = 'contentH'; } availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName]; maxAlignEndPos = totalFlex = 0; for (i = 0, l = items.length; i < l; i++) { ctrl = items[i]; ctrlLayoutRect = ctrl.layoutRect(); ctrlSettings = ctrl.settings; flex = ctrlSettings.flex; availableSpace -= i < l - 1 ? spacing : 0; if (flex > 0) { totalFlex += flex; if (ctrlLayoutRect[maxSizeName]) { maxSizeItems.push(ctrl); } ctrlLayoutRect.flex = flex; } availableSpace -= ctrlLayoutRect[minSizeName]; size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName]; if (size > maxAlignEndPos) { maxAlignEndPos = size; } } rect = {}; if (availableSpace < 0) { rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName]; } else { rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName]; } rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName]; rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace; rect[alignContentSizeName] = maxAlignEndPos; rect.minW = min(rect.minW, contLayoutRect.maxW); rect.minH = min(rect.minH, contLayoutRect.maxH); rect.minW = max(rect.minW, contLayoutRect.startMinWidth); rect.minH = max(rect.minH, contLayoutRect.startMinHeight); if (contLayoutRect.autoResize && (rect.minW !== contLayoutRect.minW || rect.minH !== contLayoutRect.minH)) { rect.w = rect.minW; rect.h = rect.minH; container.layoutRect(rect); this.recalc(container); if (container._lastRect === null) { var parentCtrl = container.parent(); if (parentCtrl) { parentCtrl._lastRect = null; parentCtrl.recalc(); } } return; } ratio = availableSpace / totalFlex; for (i = 0, l = maxSizeItems.length; i < l; i++) { ctrl = maxSizeItems[i]; ctrlLayoutRect = ctrl.layoutRect(); maxSize = ctrlLayoutRect[maxSizeName]; size = ctrlLayoutRect[minSizeName] + ctrlLayoutRect.flex * ratio; if (size > maxSize) { availableSpace -= ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]; totalFlex -= ctrlLayoutRect.flex; ctrlLayoutRect.flex = 0; ctrlLayoutRect.maxFlexSize = maxSize; } else { ctrlLayoutRect.maxFlexSize = 0; } } ratio = availableSpace / totalFlex; pos = contPaddingBox[beforeName]; rect = {}; if (totalFlex === 0) { if (pack === 'end') { pos = availableSpace + contPaddingBox[beforeName]; } else if (pack === 'center') { pos = Math.round(contLayoutRect[innerSizeName] / 2 - (contLayoutRect[innerSizeName] - availableSpace) / 2) + contPaddingBox[beforeName]; if (pos < 0) { pos = contPaddingBox[beforeName]; } } else if (pack === 'justify') { pos = contPaddingBox[beforeName]; spacing = Math.floor(availableSpace / (items.length - 1)); } } rect[alignAxisName] = contPaddingBox[alignBeforeName]; for (i = 0, l = items.length; i < l; i++) { ctrl = items[i]; ctrlLayoutRect = ctrl.layoutRect(); size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName]; if (align === 'center') { rect[alignAxisName] = Math.round(contLayoutRect[alignInnerSizeName] / 2 - ctrlLayoutRect[alignSizeName] / 2); } else if (align === 'stretch') { rect[alignSizeName] = max(ctrlLayoutRect[alignMinSizeName] || 0, contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName]); rect[alignAxisName] = contPaddingBox[alignBeforeName]; } else if (align === 'end') { rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top; } if (ctrlLayoutRect.flex > 0) { size += ctrlLayoutRect.flex * ratio; } rect[sizeName] = size; rect[posName] = pos; ctrl.layoutRect(rect); if (ctrl.recalc) { ctrl.recalc(); } pos += size + spacing; } } }); var FlowLayout = Layout.extend({ Defaults: { containerClass: 'flow-layout', controlClass: 'flow-layout-item', endClass: 'break' }, recalc: function (container) { container.items().filter(':visible').each(function (ctrl) { if (ctrl.recalc) { ctrl.recalc(); } }); }, isNative: function () { return true; } }); function ClosestOrAncestor (is, ancestor, scope, a, isRoot) { return is(scope, a) ? Option.some(scope) : $_d8bie3tijh8lz3kn.isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot); } var first$1 = function (predicate) { return descendant($_35bizev9jh8lz3rx.body(), predicate); }; var ancestor = function (scope, predicate, isRoot) { var element = scope.dom(); var stop = $_d8bie3tijh8lz3kn.isFunction(isRoot) ? isRoot : $_3pjweotejh8lz3k4.constant(false); while (element.parentNode) { element = element.parentNode; var el = $_3bkrfxv6jh8lz3rm.fromDom(element); if (predicate(el)) return Option.some(el); else if (stop(el)) break; } return Option.none(); }; var closest = function (scope, predicate, isRoot) { var is = function (scope) { return predicate(scope); }; return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot); }; var sibling = function (scope, predicate) { var element = scope.dom(); if (!element.parentNode) return Option.none(); return child$1($_3bkrfxv6jh8lz3rm.fromDom(element.parentNode), function (x) { return !$_9ypjy6vkjh8lz3sq.eq(scope, x) && predicate(x); }); }; var child$1 = function (scope, predicate) { var result = $_f3qxhzthjh8lz3kg.find(scope.dom().childNodes, $_3pjweotejh8lz3k4.compose(predicate, $_3bkrfxv6jh8lz3rm.fromDom)); return result.map($_3bkrfxv6jh8lz3rm.fromDom); }; var descendant = function (scope, predicate) { var descend = function (element) { for (var i = 0; i < element.childNodes.length; i++) { if (predicate($_3bkrfxv6jh8lz3rm.fromDom(element.childNodes[i]))) return Option.some($_3bkrfxv6jh8lz3rm.fromDom(element.childNodes[i])); var res = descend(element.childNodes[i]); if (res.isSome()) return res; } return Option.none(); }; return descend(scope.dom()); }; var $_5a72sw6jh8lz3uv = { first: first$1, ancestor: ancestor, closest: closest, sibling: sibling, child: child$1, descendant: descendant }; var first$2 = function (selector) { return $_2nczsvw0jh8lz3ua.one(selector); }; var ancestor$1 = function (scope, selector, isRoot) { return $_5a72sw6jh8lz3uv.ancestor(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }, isRoot); }; var sibling$1 = function (scope, selector) { return $_5a72sw6jh8lz3uv.sibling(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var child$2 = function (scope, selector) { return $_5a72sw6jh8lz3uv.child(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var descendant$1 = function (scope, selector) { return $_2nczsvw0jh8lz3ua.one(selector, scope); }; var closest$1 = function (scope, selector, isRoot) { return ClosestOrAncestor($_2nczsvw0jh8lz3ua.is, ancestor$1, scope, selector, isRoot); }; var $_9rr9rgw5jh8lz3uu = { first: first$2, ancestor: ancestor$1, sibling: sibling$1, child: child$2, descendant: descendant$1, closest: closest$1 }; var toggleFormat = function (editor, fmt) { return function () { editor.execCommand('mceToggleFormat', false, fmt); }; }; var addFormatChangedListener = function (editor, name, changed) { var handler = function (state) { changed(state, name); }; if (editor.formatter) { editor.formatter.formatChanged(name, handler); } else { editor.on('init', function () { editor.formatter.formatChanged(name, handler); }); } }; var postRenderFormatToggle = function (editor, name) { return function (e) { addFormatChangedListener(editor, name, function (state) { e.control.active(state); }); }; }; var register = function (editor) { var alignFormats = [ 'alignleft', 'aligncenter', 'alignright', 'alignjustify' ]; var defaultAlign = 'alignleft'; var alignMenuItems = [ { text: 'Left', icon: 'alignleft', onclick: toggleFormat(editor, 'alignleft') }, { text: 'Center', icon: 'aligncenter', onclick: toggleFormat(editor, 'aligncenter') }, { text: 'Right', icon: 'alignright', onclick: toggleFormat(editor, 'alignright') }, { text: 'Justify', icon: 'alignjustify', onclick: toggleFormat(editor, 'alignjustify') } ]; editor.addMenuItem('align', { text: 'Align', menu: alignMenuItems }); editor.addButton('align', { type: 'menubutton', icon: defaultAlign, menu: alignMenuItems, onShowMenu: function (e) { var menu = e.control.menu; global$2.each(alignFormats, function (formatName, idx) { menu.items().eq(idx).each(function (item) { return item.active(editor.formatter.match(formatName)); }); }); }, onPostRender: function (e) { var ctrl = e.control; global$2.each(alignFormats, function (formatName, idx) { addFormatChangedListener(editor, formatName, function (state) { ctrl.icon(defaultAlign); if (state) { ctrl.icon(formatName); } }); }); } }); global$2.each({ alignleft: [ 'Align left', 'JustifyLeft' ], aligncenter: [ 'Align center', 'JustifyCenter' ], alignright: [ 'Align right', 'JustifyRight' ], alignjustify: [ 'Justify', 'JustifyFull' ], alignnone: [ 'No alignment', 'JustifyNone' ] }, function (item, name) { editor.addButton(name, { active: false, tooltip: item[0], cmd: item[1], onPostRender: postRenderFormatToggle(editor, name) }); }); }; var $_a6x5k4w8jh8lz3vh = { register: register }; var getFirstFont = function (fontFamily) { return fontFamily ? fontFamily.split(',')[0] : ''; }; var findMatchingValue = function (items, fontFamily) { var font = fontFamily ? fontFamily.toLowerCase() : ''; var value; global$2.each(items, function (item) { if (item.value.toLowerCase() === font) { value = item.value; } }); global$2.each(items, function (item) { if (!value && getFirstFont(item.value).toLowerCase() === getFirstFont(font).toLowerCase()) { value = item.value; } }); return value; }; var createFontNameListBoxChangeHandler = function (editor, items) { return function () { var self = this; editor.on('init nodeChange', function (e) { var fontFamily = editor.queryCommandValue('FontName'); var match = findMatchingValue(items, fontFamily); self.value(match ? match : null); if (!match && fontFamily) { self.text(getFirstFont(fontFamily)); } }); }; }; var createFormats = function (formats) { formats = formats.replace(/;$/, '').split(';'); var i = formats.length; while (i--) { formats[i] = formats[i].split('='); } return formats; }; var getFontItems = function (editor) { var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats'; var fonts = createFormats(editor.settings.font_formats || defaultFontsFormats); return global$2.map(fonts, function (font) { return { text: { raw: font[0] }, value: font[1], textStyle: font[1].indexOf('dings') === -1 ? 'font-family:' + font[1] : '' }; }); }; var registerButtons = function (editor) { editor.addButton('fontselect', function () { var items = getFontItems(editor); return { type: 'listbox', text: 'Font Family', tooltip: 'Font Family', values: items, fixedWidth: true, onPostRender: createFontNameListBoxChangeHandler(editor, items), onselect: function (e) { if (e.control.settings.value) { editor.execCommand('FontName', false, e.control.settings.value); } } }; }); }; var register$1 = function (editor) { registerButtons(editor); }; var $_4hdsyewajh8lz3vk = { register: register$1 }; var round = function (number, precision) { var factor = Math.pow(10, precision); return Math.round(number * factor) / factor; }; var toPt = function (fontSize, precision) { if (/[0-9.]+px$/.test(fontSize)) { return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt'; } return fontSize; }; var findMatchingValue$1 = function (items, pt, px) { var value; global$2.each(items, function (item) { if (item.value === px) { value = px; } else if (item.value === pt) { value = pt; } }); return value; }; var createFontSizeListBoxChangeHandler = function (editor, items) { return function () { var self = this; editor.on('init nodeChange', function (e) { var px, pt, precision, match; px = editor.queryCommandValue('FontSize'); if (px) { for (precision = 3; !match && precision >= 0; precision--) { pt = toPt(px, precision); match = findMatchingValue$1(items, pt, px); } } self.value(match ? match : null); if (!match) { self.text(pt); } }); }; }; var getFontSizeItems = function (editor) { var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt'; var fontsizeFormats = editor.settings.fontsize_formats || defaultFontsizeFormats; return global$2.map(fontsizeFormats.split(' '), function (item) { var text = item, value = item; var values = item.split('='); if (values.length > 1) { text = values[0]; value = values[1]; } return { text: text, value: value }; }); }; var registerButtons$1 = function (editor) { editor.addButton('fontsizeselect', function () { var items = getFontSizeItems(editor); return { type: 'listbox', text: 'Font Sizes', tooltip: 'Font Sizes', values: items, fixedWidth: true, onPostRender: createFontSizeListBoxChangeHandler(editor, items), onclick: function (e) { if (e.control.settings.value) { editor.execCommand('FontSize', false, e.control.settings.value); } } }; }); }; var register$2 = function (editor) { registerButtons$1(editor); }; var $_du9atdwbjh8lz3vn = { register: register$2 }; var hideMenuObjects = function (editor, menu) { var count = menu.length; global$2.each(menu, function (item) { if (item.menu) { item.hidden = hideMenuObjects(editor, item.menu) === 0; } var formatName = item.format; if (formatName) { item.hidden = !editor.formatter.canApply(formatName); } if (item.hidden) { count--; } }); return count; }; var hideFormatMenuItems = function (editor, menu) { var count = menu.items().length; menu.items().each(function (item) { if (item.menu) { item.visible(hideFormatMenuItems(editor, item.menu) > 0); } if (!item.menu && item.settings.menu) { item.visible(hideMenuObjects(editor, item.settings.menu) > 0); } var formatName = item.settings.format; if (formatName) { item.visible(editor.formatter.canApply(formatName)); } if (!item.visible()) { count--; } }); return count; }; var createFormatMenu = function (editor) { var count = 0; var newFormats = []; var defaultStyleFormats = [ { title: 'Headings', items: [ { title: 'Heading 1', format: 'h1' }, { title: 'Heading 2', format: 'h2' }, { title: 'Heading 3', format: 'h3' }, { title: 'Heading 4', format: 'h4' }, { title: 'Heading 5', format: 'h5' }, { title: 'Heading 6', format: 'h6' } ] }, { title: 'Inline', items: [ { title: 'Bold', icon: 'bold', format: 'bold' }, { title: 'Italic', icon: 'italic', format: 'italic' }, { title: 'Underline', icon: 'underline', format: 'underline' }, { title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough' }, { title: 'Superscript', icon: 'superscript', format: 'superscript' }, { title: 'Subscript', icon: 'subscript', format: 'subscript' }, { title: 'Code', icon: 'code', format: 'code' } ] }, { title: 'Blocks', items: [ { title: 'Paragraph', format: 'p' }, { title: 'Blockquote', format: 'blockquote' }, { title: 'Div', format: 'div' }, { title: 'Pre', format: 'pre' } ] }, { title: 'Alignment', items: [ { title: 'Left', icon: 'alignleft', format: 'alignleft' }, { title: 'Center', icon: 'aligncenter', format: 'aligncenter' }, { title: 'Right', icon: 'alignright', format: 'alignright' }, { title: 'Justify', icon: 'alignjustify', format: 'alignjustify' } ] } ]; var createMenu = function (formats) { var menu = []; if (!formats) { return; } global$2.each(formats, function (format) { var menuItem = { text: format.title, icon: format.icon }; if (format.items) { menuItem.menu = createMenu(format.items); } else { var formatName = format.format || 'custom' + count++; if (!format.format) { format.name = formatName; newFormats.push(format); } menuItem.format = formatName; menuItem.cmd = format.cmd; } menu.push(menuItem); }); return menu; }; var createStylesMenu = function () { var menu; if (editor.settings.style_formats_merge) { if (editor.settings.style_formats) { menu = createMenu(defaultStyleFormats.concat(editor.settings.style_formats)); } else { menu = createMenu(defaultStyleFormats); } } else { menu = createMenu(editor.settings.style_formats || defaultStyleFormats); } return menu; }; editor.on('init', function () { global$2.each(newFormats, function (format) { editor.formatter.register(format.name, format); }); }); return { type: 'menu', items: createStylesMenu(), onPostRender: function (e) { editor.fire('renderFormatsMenu', { control: e.control }); }, itemDefaults: { preview: true, textStyle: function () { if (this.settings.format) { return editor.formatter.getCssText(this.settings.format); } }, onPostRender: function () { var self = this; self.parent().on('show', function () { var formatName, command; formatName = self.settings.format; if (formatName) { self.disabled(!editor.formatter.canApply(formatName)); self.active(editor.formatter.match(formatName)); } command = self.settings.cmd; if (command) { self.active(editor.queryCommandState(command)); } }); }, onclick: function () { if (this.settings.format) { toggleFormat(editor, this.settings.format)(); } if (this.settings.cmd) { editor.execCommand(this.settings.cmd); } } } }; }; var registerMenuItems = function (editor, formatMenu) { editor.addMenuItem('formats', { text: 'Formats', menu: formatMenu }); }; var registerButtons$2 = function (editor, formatMenu) { editor.addButton('styleselect', { type: 'menubutton', text: 'Formats', menu: formatMenu, onShowMenu: function () { if (editor.settings.style_formats_autohide) { hideFormatMenuItems(editor, this.menu); } } }); }; var register$3 = function (editor) { var formatMenu = createFormatMenu(editor); registerMenuItems(editor, formatMenu); registerButtons$2(editor, formatMenu); }; var $_5xlhbcwcjh8lz3vr = { register: register$3 }; var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre'; var createFormats$1 = function (formats) { formats = formats.replace(/;$/, '').split(';'); var i = formats.length; while (i--) { formats[i] = formats[i].split('='); } return formats; }; var createListBoxChangeHandler = function (editor, items, formatName) { return function () { var self = this; editor.on('nodeChange', function (e) { var formatter = editor.formatter; var value = null; global$2.each(e.parents, function (node) { global$2.each(items, function (item) { if (formatName) { if (formatter.matchNode(node, formatName, { value: item.value })) { value = item.value; } } else { if (formatter.matchNode(node, item.value)) { value = item.value; } } if (value) { return false; } }); if (value) { return false; } }); self.value(value); }); }; }; var lazyFormatSelectBoxItems = function (editor, blocks) { return function () { var items = []; global$2.each(blocks, function (block) { items.push({ text: block[0], value: block[1], textStyle: function () { return editor.formatter.getCssText(block[1]); } }); }); return { type: 'listbox', text: blocks[0][0], values: items, fixedWidth: true, onselect: function (e) { if (e.control) { var fmt = e.control.value(); toggleFormat(editor, fmt)(); } }, onPostRender: createListBoxChangeHandler(editor, items) }; }; }; var buildMenuItems = function (editor, blocks) { return global$2.map(blocks, function (block) { return { text: block[0], onclick: toggleFormat(editor, block[1]), textStyle: function () { return editor.formatter.getCssText(block[1]); } }; }); }; var register$4 = function (editor) { var blocks = createFormats$1(editor.settings.block_formats || defaultBlocks); editor.addMenuItem('blockformats', { text: 'Blocks', menu: buildMenuItems(editor, blocks) }); editor.addButton('formatselect', lazyFormatSelectBoxItems(editor, blocks)); }; var $_bj8nxmwdjh8lz3vw = { register: register$4 }; var createCustomMenuItems = function (editor, names) { var items, nameList; if (typeof names === 'string') { nameList = names.split(' '); } else if (global$2.isArray(names)) { return $_f3qxhzthjh8lz3kg.flatten(global$2.map(names, function (names) { return createCustomMenuItems(editor, names); })); } items = global$2.grep(nameList, function (name) { return name === '|' || name in editor.menuItems; }); return global$2.map(items, function (name) { return name === '|' ? { text: '-' } : editor.menuItems[name]; }); }; var isSeparator$1 = function (menuItem) { return menuItem && menuItem.text === '-'; }; var trimMenuItems = function (menuItems) { var menuItems2 = $_f3qxhzthjh8lz3kg.filter(menuItems, function (menuItem, i, menuItems) { return !isSeparator$1(menuItem) || !isSeparator$1(menuItems[i - 1]); }); return $_f3qxhzthjh8lz3kg.filter(menuItems2, function (menuItem, i, menuItems) { return !isSeparator$1(menuItem) || i > 0 && i < menuItems.length - 1; }); }; var createContextMenuItems = function (editor, context) { var outputMenuItems = [{ text: '-' }]; var menuItems = global$2.grep(editor.menuItems, function (menuItem) { return menuItem.context === context; }); global$2.each(menuItems, function (menuItem) { if (menuItem.separator === 'before') { outputMenuItems.push({ text: '|' }); } if (menuItem.prependToContext) { outputMenuItems.unshift(menuItem); } else { outputMenuItems.push(menuItem); } if (menuItem.separator === 'after') { outputMenuItems.push({ text: '|' }); } }); return outputMenuItems; }; var createInsertMenu = function (editor) { var insertButtonItems = editor.settings.insert_button_items; if (insertButtonItems) { return trimMenuItems(createCustomMenuItems(editor, insertButtonItems)); } else { return trimMenuItems(createContextMenuItems(editor, 'insert')); } }; var registerButtons$3 = function (editor) { editor.addButton('insert', { type: 'menubutton', icon: 'insert', menu: [], oncreatemenu: function () { this.menu.add(createInsertMenu(editor)); this.menu.renderNew(); } }); }; var register$5 = function (editor) { registerButtons$3(editor); }; var $_drvzmkwejh8lz3vz = { register: register$5 }; var registerFormatButtons = function (editor) { global$2.each({ bold: 'Bold', italic: 'Italic', underline: 'Underline', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript' }, function (text, name) { editor.addButton(name, { active: false, tooltip: text, onPostRender: postRenderFormatToggle(editor, name), onclick: toggleFormat(editor, name) }); }); }; var registerCommandButtons = function (editor) { global$2.each({ outdent: [ 'Decrease indent', 'Outdent' ], indent: [ 'Increase indent', 'Indent' ], cut: [ 'Cut', 'Cut' ], copy: [ 'Copy', 'Copy' ], paste: [ 'Paste', 'Paste' ], help: [ 'Help', 'mceHelp' ], selectall: [ 'Select all', 'SelectAll' ], visualaid: [ 'Visual aids', 'mceToggleVisualAid' ], newdocument: [ 'New document', 'mceNewDocument' ], removeformat: [ 'Clear formatting', 'RemoveFormat' ], remove: [ 'Remove', 'Delete' ] }, function (item, name) { editor.addButton(name, { tooltip: item[0], cmd: item[1] }); }); }; var registerCommandToggleButtons = function (editor) { global$2.each({ blockquote: [ 'Blockquote', 'mceBlockQuote' ], subscript: [ 'Subscript', 'Subscript' ], superscript: [ 'Superscript', 'Superscript' ] }, function (item, name) { editor.addButton(name, { active: false, tooltip: item[0], cmd: item[1], onPostRender: postRenderFormatToggle(editor, name) }); }); }; var registerButtons$4 = function (editor) { registerFormatButtons(editor); registerCommandButtons(editor); registerCommandToggleButtons(editor); }; var registerMenuItems$1 = function (editor) { global$2.each({ bold: [ 'Bold', 'Bold', 'Meta+B' ], italic: [ 'Italic', 'Italic', 'Meta+I' ], underline: [ 'Underline', 'Underline', 'Meta+U' ], strikethrough: [ 'Strikethrough', 'Strikethrough' ], subscript: [ 'Subscript', 'Subscript' ], superscript: [ 'Superscript', 'Superscript' ], removeformat: [ 'Clear formatting', 'RemoveFormat' ], newdocument: [ 'New document', 'mceNewDocument' ], cut: [ 'Cut', 'Cut', 'Meta+X' ], copy: [ 'Copy', 'Copy', 'Meta+C' ], paste: [ 'Paste', 'Paste', 'Meta+V' ], selectall: [ 'Select all', 'SelectAll', 'Meta+A' ] }, function (item, name) { editor.addMenuItem(name, { text: item[0], icon: name, shortcut: item[2], cmd: item[1] }); }); editor.addMenuItem('codeformat', { text: 'Code', icon: 'code', onclick: toggleFormat(editor, 'code') }); }; var register$6 = function (editor) { registerButtons$4(editor); registerMenuItems$1(editor); }; var $_2d67dwfjh8lz3w2 = { register: register$6 }; var toggleUndoRedoState = function (editor, type) { return function () { var self = this; var checkState = function () { var typeFn = type === 'redo' ? 'hasRedo' : 'hasUndo'; return editor.undoManager ? editor.undoManager[typeFn]() : false; }; self.disabled(!checkState()); editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function () { self.disabled(editor.readonly || !checkState()); }); }; }; var registerMenuItems$2 = function (editor) { editor.addMenuItem('undo', { text: 'Undo', icon: 'undo', shortcut: 'Meta+Z', onPostRender: toggleUndoRedoState(editor, 'undo'), cmd: 'undo' }); editor.addMenuItem('redo', { text: 'Redo', icon: 'redo', shortcut: 'Meta+Y', onPostRender: toggleUndoRedoState(editor, 'redo'), cmd: 'redo' }); }; var registerButtons$5 = function (editor) { editor.addButton('undo', { tooltip: 'Undo', onPostRender: toggleUndoRedoState(editor, 'undo'), cmd: 'undo' }); editor.addButton('redo', { tooltip: 'Redo', onPostRender: toggleUndoRedoState(editor, 'redo'), cmd: 'redo' }); }; var register$7 = function (editor) { registerMenuItems$2(editor); registerButtons$5(editor); }; var $_cd5m9xwgjh8lz3w5 = { register: register$7 }; var toggleVisualAidState = function (editor) { return function () { var self = this; editor.on('VisualAid', function (e) { self.active(e.hasVisual); }); self.active(editor.hasVisual); }; }; var registerMenuItems$3 = function (editor) { editor.addMenuItem('visualaid', { text: 'Visual aids', selectable: true, onPostRender: toggleVisualAidState(editor), cmd: 'mceToggleVisualAid' }); }; var register$8 = function (editor) { registerMenuItems$3(editor); }; var $_1ojpofwhjh8lz3w6 = { register: register$8 }; var setupEnvironment = function () { Widget.tooltips = !global$8.iOS; Control$1.translate = function (text) { return global$1.translate(text); }; }; var setupUiContainer = function (editor) { if (editor.settings.ui_container) { global$8.container = $_9rr9rgw5jh8lz3uu.descendant($_3bkrfxv6jh8lz3rm.fromDom(document.body), editor.settings.ui_container).fold($_3pjweotejh8lz3k4.constant(null), function (elm) { return elm.dom(); }); } }; var setupRtlMode = function (editor) { if (editor.rtl) { Control$1.rtl = true; } }; var setupHideFloatPanels = function (editor) { editor.on('mousedown', function () { FloatPanel.hideAll(); }); }; var setup$1 = function (editor) { setupRtlMode(editor); setupHideFloatPanels(editor); setupUiContainer(editor); setupEnvironment(); $_bj8nxmwdjh8lz3vw.register(editor); $_a6x5k4w8jh8lz3vh.register(editor); $_2d67dwfjh8lz3w2.register(editor); $_cd5m9xwgjh8lz3w5.register(editor); $_du9atdwbjh8lz3vn.register(editor); $_4hdsyewajh8lz3vk.register(editor); $_5xlhbcwcjh8lz3vr.register(editor); $_1ojpofwhjh8lz3w6.register(editor); $_drvzmkwejh8lz3vz.register(editor); }; var $_4qdht3w4jh8lz3uo = { setup: setup$1 }; var GridLayout = AbsoluteLayout.extend({ recalc: function (container) { var settings, rows, cols, items, contLayoutRect, width, height, rect, ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY; var colWidths = []; var rowHeights = []; var ctrlMinWidth, ctrlMinHeight, availableWidth, availableHeight, reverseRows, idx; settings = container.settings; items = container.items().filter(':visible'); contLayoutRect = container.layoutRect(); cols = settings.columns || Math.ceil(Math.sqrt(items.length)); rows = Math.ceil(items.length / cols); spacingH = settings.spacingH || settings.spacing || 0; spacingV = settings.spacingV || settings.spacing || 0; alignH = settings.alignH || settings.align; alignV = settings.alignV || settings.align; contPaddingBox = container.paddingBox; reverseRows = 'reverseRows' in settings ? settings.reverseRows : container.isRtl(); if (alignH && typeof alignH === 'string') { alignH = [alignH]; } if (alignV && typeof alignV === 'string') { alignV = [alignV]; } for (x = 0; x < cols; x++) { colWidths.push(0); } for (y = 0; y < rows; y++) { rowHeights.push(0); } for (y = 0; y < rows; y++) { for (x = 0; x < cols; x++) { ctrl = items[y * cols + x]; if (!ctrl) { break; } ctrlLayoutRect = ctrl.layoutRect(); ctrlMinWidth = ctrlLayoutRect.minW; ctrlMinHeight = ctrlLayoutRect.minH; colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x]; rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y]; } } availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right; for (maxX = 0, x = 0; x < cols; x++) { maxX += colWidths[x] + (x > 0 ? spacingH : 0); availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x]; } availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom; for (maxY = 0, y = 0; y < rows; y++) { maxY += rowHeights[y] + (y > 0 ? spacingV : 0); availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y]; } maxX += contPaddingBox.left + contPaddingBox.right; maxY += contPaddingBox.top + contPaddingBox.bottom; rect = {}; rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW); rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH); rect.contentW = rect.minW - contLayoutRect.deltaW; rect.contentH = rect.minH - contLayoutRect.deltaH; rect.minW = Math.min(rect.minW, contLayoutRect.maxW); rect.minH = Math.min(rect.minH, contLayoutRect.maxH); rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth); rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight); if (contLayoutRect.autoResize && (rect.minW !== contLayoutRect.minW || rect.minH !== contLayoutRect.minH)) { rect.w = rect.minW; rect.h = rect.minH; container.layoutRect(rect); this.recalc(container); if (container._lastRect === null) { var parentCtrl = container.parent(); if (parentCtrl) { parentCtrl._lastRect = null; parentCtrl.recalc(); } } return; } if (contLayoutRect.autoResize) { rect = container.layoutRect(rect); rect.contentW = rect.minW - contLayoutRect.deltaW; rect.contentH = rect.minH - contLayoutRect.deltaH; } var flexV; if (settings.packV === 'start') { flexV = 0; } else { flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0; } var totalFlex = 0; var flexWidths = settings.flexWidths; if (flexWidths) { for (x = 0; x < flexWidths.length; x++) { totalFlex += flexWidths[x]; } } else { totalFlex = cols; } var ratio = availableWidth / totalFlex; for (x = 0; x < cols; x++) { colWidths[x] += flexWidths ? flexWidths[x] * ratio : ratio; } posY = contPaddingBox.top; for (y = 0; y < rows; y++) { posX = contPaddingBox.left; height = rowHeights[y] + flexV; for (x = 0; x < cols; x++) { if (reverseRows) { idx = y * cols + cols - 1 - x; } else { idx = y * cols + x; } ctrl = items[idx]; if (!ctrl) { break; } ctrlSettings = ctrl.settings; ctrlLayoutRect = ctrl.layoutRect(); width = Math.max(colWidths[x], ctrlLayoutRect.startMinWidth); ctrlLayoutRect.x = posX; ctrlLayoutRect.y = posY; align = ctrlSettings.alignH || (alignH ? alignH[x] || alignH[0] : null); if (align === 'center') { ctrlLayoutRect.x = posX + width / 2 - ctrlLayoutRect.w / 2; } else if (align === 'right') { ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w; } else if (align === 'stretch') { ctrlLayoutRect.w = width; } align = ctrlSettings.alignV || (alignV ? alignV[x] || alignV[0] : null); if (align === 'center') { ctrlLayoutRect.y = posY + height / 2 - ctrlLayoutRect.h / 2; } else if (align === 'bottom') { ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h; } else if (align === 'stretch') { ctrlLayoutRect.h = height; } ctrl.layoutRect(ctrlLayoutRect); posX += width + spacingH; if (ctrl.recalc) { ctrl.recalc(); } } posY += height + spacingV; } } }); var Iframe$1 = Widget.extend({ renderHtml: function () { var self = this; self.classes.add('iframe'); self.canFocus = false; return '<iframe id="' + self._id + '" class="' + self.classes + '" tabindex="-1" src="' + (self.settings.url || 'javascript:\'\'') + '" frameborder="0"></iframe>'; }, src: function (src) { this.getEl().src = src; }, html: function (html, callback) { var self = this, body = this.getEl().contentWindow.document.body; if (!body) { global$7.setTimeout(function () { self.html(html); }); } else { body.innerHTML = html; if (callback) { callback(); } } return this; } }); var InfoBox = Widget.extend({ init: function (settings) { var self = this; self._super(settings); self.classes.add('widget').add('infobox'); self.canFocus = false; }, severity: function (level) { this.classes.remove('error'); this.classes.remove('warning'); this.classes.remove('success'); this.classes.add(level); }, help: function (state) { this.state.set('help', state); }, renderHtml: function () { var self = this, prefix = self.classPrefix; return '<div id="' + self._id + '" class="' + self.classes + '">' + '<div id="' + self._id + '-body">' + self.encode(self.state.get('text')) + '<button role="button" tabindex="-1">' + '<i class="' + prefix + 'ico ' + prefix + 'i-help"></i>' + '</button>' + '</div>' + '</div>'; }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.getEl('body').firstChild.data = self.encode(e.value); if (self.state.get('rendered')) { self.updateLayoutRect(); } }); self.state.on('change:help', function (e) { self.classes.toggle('has-help', e.value); if (self.state.get('rendered')) { self.updateLayoutRect(); } }); return self._super(); } }); var Label = Widget.extend({ init: function (settings) { var self = this; self._super(settings); self.classes.add('widget').add('label'); self.canFocus = false; if (settings.multiline) { self.classes.add('autoscroll'); } if (settings.strong) { self.classes.add('strong'); } }, initLayoutRect: function () { var self = this, layoutRect = self._super(); if (self.settings.multiline) { var size = funcs.getSize(self.getEl()); if (size.width > layoutRect.maxW) { layoutRect.minW = layoutRect.maxW; self.classes.add('multiline'); } self.getEl().style.width = layoutRect.minW + 'px'; layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, funcs.getSize(self.getEl()).height); } return layoutRect; }, repaint: function () { var self = this; if (!self.settings.multiline) { self.getEl().style.lineHeight = self.layoutRect().h + 'px'; } return self._super(); }, severity: function (level) { this.classes.remove('error'); this.classes.remove('warning'); this.classes.remove('success'); this.classes.add(level); }, renderHtml: function () { var self = this; var targetCtrl, forName, forId = self.settings.forId; var text = self.settings.html ? self.settings.html : self.encode(self.state.get('text')); if (!forId && (forName = self.settings.forName)) { targetCtrl = self.getRoot().find('#' + forName)[0]; if (targetCtrl) { forId = targetCtrl._id; } } if (forId) { return '<label id="' + self._id + '" class="' + self.classes + '"' + (forId ? ' for="' + forId + '"' : '') + '>' + text + '</label>'; } return '<span id="' + self._id + '" class="' + self.classes + '">' + text + '</span>'; }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.innerHtml(self.encode(e.value)); if (self.state.get('rendered')) { self.updateLayoutRect(); } }); return self._super(); } }); var Toolbar$1 = Container.extend({ Defaults: { role: 'toolbar', layout: 'flow' }, init: function (settings) { var self = this; self._super(settings); self.classes.add('toolbar'); }, postRender: function () { var self = this; self.items().each(function (ctrl) { ctrl.classes.add('toolbar-item'); }); return self._super(); } }); var MenuBar = Toolbar$1.extend({ Defaults: { role: 'menubar', containerCls: 'menubar', ariaRoot: true, defaults: { type: 'menubutton' } } }); function isChildOf$1(node, parent) { while (node) { if (parent === node) { return true; } node = node.parentNode; } return false; } var MenuButton = Button.extend({ init: function (settings) { var self = this; self._renderOpen = true; self._super(settings); settings = self.settings; self.classes.add('menubtn'); if (settings.fixedWidth) { self.classes.add('fixed-width'); } self.aria('haspopup', true); self.state.set('menu', settings.menu || self.render()); }, showMenu: function (toggle) { var self = this; var menu; if (self.menu && self.menu.visible() && toggle !== false) { return self.hideMenu(); } if (!self.menu) { menu = self.state.get('menu') || []; self.classes.add('opened'); if (menu.length) { menu = { type: 'menu', animate: true, items: menu }; } else { menu.type = menu.type || 'menu'; menu.animate = true; } if (!menu.renderTo) { self.menu = global$4.create(menu).parent(self).renderTo(); } else { self.menu = menu.parent(self).show().renderTo(); } self.fire('createmenu'); self.menu.reflow(); self.menu.on('cancel', function (e) { if (e.control.parent() === self.menu) { e.stopPropagation(); self.focus(); self.hideMenu(); } }); self.menu.on('select', function () { self.focus(); }); self.menu.on('show hide', function (e) { if (e.control === self.menu) { self.activeMenu(e.type === 'show'); self.classes.toggle('opened', e.type === 'show'); } self.aria('expanded', e.type === 'show'); }).fire('show'); } self.menu.show(); self.menu.layoutRect({ w: self.layoutRect().w }); self.menu.repaint(); self.menu.moveRel(self.getEl(), self.isRtl() ? [ 'br-tr', 'tr-br' ] : [ 'bl-tl', 'tl-bl' ]); self.fire('showmenu'); }, hideMenu: function () { var self = this; if (self.menu) { self.menu.items().each(function (item) { if (item.hideMenu) { item.hideMenu(); } }); self.menu.hide(); } }, activeMenu: function (state) { this.classes.toggle('active', state); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; var icon = self.settings.icon, image; var text = self.state.get('text'); var textHtml = ''; image = self.settings.image; if (image) { icon = 'none'; if (typeof image !== 'string') { image = window.getSelection ? image[0] : image[1]; } image = ' style="background-image: url(\'' + image + '\')"'; } else { image = ''; } if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : ''; self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button'); return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1" aria-labelledby="' + id + '">' + '<button id="' + id + '-open" role="presentation" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>'; }, postRender: function () { var self = this; self.on('click', function (e) { if (e.control === self && isChildOf$1(e.target, self.getEl())) { self.focus(); self.showMenu(!e.aria); if (e.aria) { self.menu.items().filter(':visible')[0].focus(); } } }); self.on('mouseenter', function (e) { var overCtrl = e.control; var parent = self.parent(); var hasVisibleSiblingMenu; if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() === parent) { parent.items().filter('MenuButton').each(function (ctrl) { if (ctrl.hideMenu && ctrl !== overCtrl) { if (ctrl.menu && ctrl.menu.visible()) { hasVisibleSiblingMenu = true; } ctrl.hideMenu(); } }); if (hasVisibleSiblingMenu) { overCtrl.focus(); overCtrl.showMenu(); } } }); return self._super(); }, bindStates: function () { var self = this; self.state.on('change:menu', function () { if (self.menu) { self.menu.remove(); } self.menu = null; }); return self._super(); }, remove: function () { this._super(); if (this.menu) { this.menu.remove(); } } }); var Menu = FloatPanel.extend({ Defaults: { defaultType: 'menuitem', border: 1, layout: 'stack', role: 'application', bodyRole: 'menu', ariaRoot: true }, init: function (settings) { var self = this; settings.autohide = true; settings.constrainToViewport = true; if (typeof settings.items === 'function') { settings.itemsFactory = settings.items; settings.items = []; } if (settings.itemDefaults) { var items = settings.items; var i = items.length; while (i--) { items[i] = global$2.extend({}, settings.itemDefaults, items[i]); } } self._super(settings); self.classes.add('menu'); if (settings.animate && global$8.ie !== 11) { self.classes.add('animate'); } }, repaint: function () { this.classes.toggle('menu-align', true); this._super(); this.getEl().style.height = ''; this.getEl('body').style.height = ''; return this; }, cancel: function () { var self = this; self.hideAll(); self.fire('select'); }, load: function () { var self = this; var time, factory; function hideThrobber() { if (self.throbber) { self.throbber.hide(); self.throbber = null; } } factory = self.settings.itemsFactory; if (!factory) { return; } if (!self.throbber) { self.throbber = new Throbber(self.getEl('body'), true); if (self.items().length === 0) { self.throbber.show(); self.fire('loading'); } else { self.throbber.show(100, function () { self.items().remove(); self.fire('loading'); }); } self.on('hide close', hideThrobber); } self.requestTime = time = new Date().getTime(); self.settings.itemsFactory(function (items) { if (items.length === 0) { self.hide(); return; } if (self.requestTime !== time) { return; } self.getEl().style.width = ''; self.getEl('body').style.width = ''; hideThrobber(); self.items().remove(); self.getEl('body').innerHTML = ''; self.add(items); self.renderNew(); self.fire('loaded'); }); }, hideAll: function () { var self = this; this.find('menuitem').exec('hideMenu'); return self._super(); }, preRender: function () { var self = this; self.items().each(function (ctrl) { var settings = ctrl.settings; if (settings.icon || settings.image || settings.selectable) { self._hasIcons = true; return false; } }); if (self.settings.itemsFactory) { self.on('postrender', function () { if (self.settings.itemsFactory) { self.load(); } }); } self.on('show hide', function (e) { if (e.control === self) { if (e.type === 'show') { global$7.setTimeout(function () { self.classes.add('in'); }, 0); } else { self.classes.remove('in'); } } }); return self._super(); } }); var ListBox = MenuButton.extend({ init: function (settings) { var self = this; var values, selected, selectedText, lastItemCtrl; function setSelected(menuValues) { for (var i = 0; i < menuValues.length; i++) { selected = menuValues[i].selected || settings.value === menuValues[i].value; if (selected) { selectedText = selectedText || menuValues[i].text; self.state.set('value', menuValues[i].value); return true; } if (menuValues[i].menu) { if (setSelected(menuValues[i].menu)) { return true; } } } } self._super(settings); settings = self.settings; self._values = values = settings.values; if (values) { if (typeof settings.value !== 'undefined') { setSelected(values); } if (!selected && values.length > 0) { selectedText = values[0].text; self.state.set('value', values[0].value); } self.state.set('menu', values); } self.state.set('text', settings.text || selectedText); self.classes.add('listbox'); self.on('select', function (e) { var ctrl = e.control; if (lastItemCtrl) { e.lastControl = lastItemCtrl; } if (settings.multiple) { ctrl.active(!ctrl.active()); } else { self.value(e.control.value()); } lastItemCtrl = ctrl; }); }, value: function (value) { if (arguments.length === 0) { return this.state.get('value'); } if (typeof value === 'undefined') { return this; } if (this.settings.values) { var matchingValues = global$2.grep(this.settings.values, function (a) { return a.value === value; }); if (matchingValues.length > 0) { this.state.set('value', value); } else if (value === null) { this.state.set('value', null); } } else { this.state.set('value', value); } return this; }, bindStates: function () { var self = this; function activateMenuItemsByValue(menu, value) { if (menu instanceof Menu) { menu.items().each(function (ctrl) { if (!ctrl.hasMenus()) { ctrl.active(ctrl.value() === value); } }); } } function getSelectedItem(menuValues, value) { var selectedItem; if (!menuValues) { return; } for (var i = 0; i < menuValues.length; i++) { if (menuValues[i].value === value) { return menuValues[i]; } if (menuValues[i].menu) { selectedItem = getSelectedItem(menuValues[i].menu, value); if (selectedItem) { return selectedItem; } } } } self.on('show', function (e) { activateMenuItemsByValue(e.control, self.value()); }); self.state.on('change:value', function (e) { var selectedItem = getSelectedItem(self.state.get('menu'), e.value); if (selectedItem) { self.text(selectedItem.text); } else { self.text(self.settings.text); } }); return self._super(); } }); var toggleTextStyle = function (ctrl, state) { var textStyle = ctrl._textStyle; if (textStyle) { var textElm = ctrl.getEl('text'); textElm.setAttribute('style', textStyle); if (state) { textElm.style.color = ''; textElm.style.backgroundColor = ''; } } }; var MenuItem = Widget.extend({ Defaults: { border: 0, role: 'menuitem' }, init: function (settings) { var self = this; var text; self._super(settings); settings = self.settings; self.classes.add('menu-item'); if (settings.menu) { self.classes.add('menu-item-expand'); } if (settings.preview) { self.classes.add('menu-item-preview'); } text = self.state.get('text'); if (text === '-' || text === '|') { self.classes.add('menu-item-sep'); self.aria('role', 'separator'); self.state.set('text', '-'); } if (settings.selectable) { self.aria('role', 'menuitemcheckbox'); self.classes.add('menu-item-checkbox'); settings.icon = 'selected'; } if (!settings.preview && !settings.selectable) { self.classes.add('menu-item-normal'); } self.on('mousedown', function (e) { e.preventDefault(); }); if (settings.menu && !settings.ariaHideMenu) { self.aria('haspopup', true); } }, hasMenus: function () { return !!this.settings.menu; }, showMenu: function () { var self = this; var settings = self.settings; var menu; var parent = self.parent(); parent.items().each(function (ctrl) { if (ctrl !== self) { ctrl.hideMenu(); } }); if (settings.menu) { menu = self.menu; if (!menu) { menu = settings.menu; if (menu.length) { menu = { type: 'menu', items: menu }; } else { menu.type = menu.type || 'menu'; } if (parent.settings.itemDefaults) { menu.itemDefaults = parent.settings.itemDefaults; } menu = self.menu = global$4.create(menu).parent(self).renderTo(); menu.reflow(); menu.on('cancel', function (e) { e.stopPropagation(); self.focus(); menu.hide(); }); menu.on('show hide', function (e) { if (e.control.items) { e.control.items().each(function (ctrl) { ctrl.active(ctrl.settings.selected); }); } }).fire('show'); menu.on('hide', function (e) { if (e.control === menu) { self.classes.remove('selected'); } }); menu.submenu = true; } else { menu.show(); } menu._parentMenu = parent; menu.classes.add('menu-sub'); var rel = menu.testMoveRel(self.getEl(), self.isRtl() ? [ 'tl-tr', 'bl-br', 'tr-tl', 'br-bl' ] : [ 'tr-tl', 'br-bl', 'tl-tr', 'bl-br' ]); menu.moveRel(self.getEl(), rel); menu.rel = rel; rel = 'menu-sub-' + rel; menu.classes.remove(menu._lastRel).add(rel); menu._lastRel = rel; self.classes.add('selected'); self.aria('expanded', true); } }, hideMenu: function () { var self = this; if (self.menu) { self.menu.items().each(function (item) { if (item.hideMenu) { item.hideMenu(); } }); self.menu.hide(); self.aria('expanded', false); } return self; }, renderHtml: function () { var self = this; var id = self._id; var settings = self.settings; var prefix = self.classPrefix; var text = self.state.get('text'); var icon = self.settings.icon, image = '', shortcut = settings.shortcut; var url = self.encode(settings.url), iconHtml = ''; function convertShortcut(shortcut) { var i, value, replace = {}; if (global$8.mac) { replace = { alt: '&#x2325;', ctrl: '&#x2318;', shift: '&#x21E7;', meta: '&#x2318;' }; } else { replace = { meta: 'Ctrl' }; } shortcut = shortcut.split('+'); for (i = 0; i < shortcut.length; i++) { value = replace[shortcut[i].toLowerCase()]; if (value) { shortcut[i] = value; } } return shortcut.join('+'); } function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function markMatches(text) { var match = settings.match || ''; return match ? text.replace(new RegExp(escapeRegExp(match), 'gi'), function (match) { return '!mce~match[' + match + ']mce~match!'; }) : text; } function boldMatches(text) { return text.replace(new RegExp(escapeRegExp('!mce~match['), 'g'), '<b>').replace(new RegExp(escapeRegExp(']mce~match!'), 'g'), '</b>'); } if (icon) { self.parent().classes.add('menu-has-icons'); } if (settings.image) { image = ' style="background-image: url(\'' + settings.image + '\')"'; } if (shortcut) { shortcut = convertShortcut(shortcut); } icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none'); iconHtml = text !== '-' ? '<i class="' + icon + '"' + image + '></i>\xA0' : ''; text = boldMatches(self.encode(markMatches(text))); url = boldMatches(self.encode(markMatches(url))); return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1">' + iconHtml + (text !== '-' ? '<span id="' + id + '-text" class="' + prefix + 'text">' + text + '</span>' : '') + (shortcut ? '<div id="' + id + '-shortcut" class="' + prefix + 'menu-shortcut">' + shortcut + '</div>' : '') + (settings.menu ? '<div class="' + prefix + 'caret"></div>' : '') + (url ? '<div class="' + prefix + 'menu-item-link">' + url + '</div>' : '') + '</div>'; }, postRender: function () { var self = this, settings = self.settings; var textStyle = settings.textStyle; if (typeof textStyle === 'function') { textStyle = textStyle.call(this); } if (textStyle) { var textElm = self.getEl('text'); if (textElm) { textElm.setAttribute('style', textStyle); self._textStyle = textStyle; } } self.on('mouseenter click', function (e) { if (e.control === self) { if (!settings.menu && e.type === 'click') { self.fire('select'); global$7.requestAnimationFrame(function () { self.parent().hideAll(); }); } else { self.showMenu(); if (e.aria) { self.menu.focus(true); } } } }); self._super(); return self; }, hover: function () { var self = this; self.parent().items().each(function (ctrl) { ctrl.classes.remove('selected'); }); self.classes.toggle('selected', true); return self; }, active: function (state) { toggleTextStyle(this, state); if (typeof state !== 'undefined') { this.aria('checked', state); } return this._super(state); }, remove: function () { this._super(); if (this.menu) { this.menu.remove(); } } }); var Radio = Checkbox.extend({ Defaults: { classes: 'radio', role: 'radio' } }); var ResizeHandle = Widget.extend({ renderHtml: function () { var self = this, prefix = self.classPrefix; self.classes.add('resizehandle'); if (self.settings.direction === 'both') { self.classes.add('resizehandle-both'); } self.canFocus = false; return '<div id="' + self._id + '" class="' + self.classes + '">' + '<i class="' + prefix + 'ico ' + prefix + 'i-resize"></i>' + '</div>'; }, postRender: function () { var self = this; self._super(); self.resizeDragHelper = new DragHelper(this._id, { start: function () { self.fire('ResizeStart'); }, drag: function (e) { if (self.settings.direction !== 'both') { e.deltaX = 0; } self.fire('Resize', e); }, stop: function () { self.fire('ResizeEnd'); } }); }, remove: function () { if (this.resizeDragHelper) { this.resizeDragHelper.destroy(); } return this._super(); } }); function createOptions(options) { var strOptions = ''; if (options) { for (var i = 0; i < options.length; i++) { strOptions += '<option value="' + options[i] + '">' + options[i] + '</option>'; } } return strOptions; } var SelectBox = Widget.extend({ Defaults: { classes: 'selectbox', role: 'selectbox', options: [] }, init: function (settings) { var self = this; self._super(settings); if (self.settings.size) { self.size = self.settings.size; } if (self.settings.options) { self._options = self.settings.options; } self.on('keydown', function (e) { var rootControl; if (e.keyCode === 13) { e.preventDefault(); self.parents().reverse().each(function (ctrl) { if (ctrl.toJSON) { rootControl = ctrl; return false; } }); self.fire('submit', { data: rootControl.toJSON() }); } }); }, options: function (state) { if (!arguments.length) { return this.state.get('options'); } this.state.set('options', state); return this; }, renderHtml: function () { var self = this; var options, size = ''; options = createOptions(self._options); if (self.size) { size = ' size = "' + self.size + '"'; } return '<select id="' + self._id + '" class="' + self.classes + '"' + size + '>' + options + '</select>'; }, bindStates: function () { var self = this; self.state.on('change:options', function (e) { self.getEl().innerHTML = createOptions(e.value); }); return self._super(); } }); function constrain(value, minVal, maxVal) { if (value < minVal) { value = minVal; } if (value > maxVal) { value = maxVal; } return value; } function setAriaProp(el, name, value) { el.setAttribute('aria-' + name, value); } function updateSliderHandle(ctrl, value) { var maxHandlePos, shortSizeName, sizeName, stylePosName, styleValue, handleEl; if (ctrl.settings.orientation === 'v') { stylePosName = 'top'; sizeName = 'height'; shortSizeName = 'h'; } else { stylePosName = 'left'; sizeName = 'width'; shortSizeName = 'w'; } handleEl = ctrl.getEl('handle'); maxHandlePos = (ctrl.layoutRect()[shortSizeName] || 100) - funcs.getSize(handleEl)[sizeName]; styleValue = maxHandlePos * ((value - ctrl._minValue) / (ctrl._maxValue - ctrl._minValue)) + 'px'; handleEl.style[stylePosName] = styleValue; handleEl.style.height = ctrl.layoutRect().h + 'px'; setAriaProp(handleEl, 'valuenow', value); setAriaProp(handleEl, 'valuetext', '' + ctrl.settings.previewFilter(value)); setAriaProp(handleEl, 'valuemin', ctrl._minValue); setAriaProp(handleEl, 'valuemax', ctrl._maxValue); } var Slider = Widget.extend({ init: function (settings) { var self = this; if (!settings.previewFilter) { settings.previewFilter = function (value) { return Math.round(value * 100) / 100; }; } self._super(settings); self.classes.add('slider'); if (settings.orientation === 'v') { self.classes.add('vertical'); } self._minValue = $_d8bie3tijh8lz3kn.isNumber(settings.minValue) ? settings.minValue : 0; self._maxValue = $_d8bie3tijh8lz3kn.isNumber(settings.maxValue) ? settings.maxValue : 100; self._initValue = self.state.get('value'); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; return '<div id="' + id + '" class="' + self.classes + '">' + '<div id="' + id + '-handle" class="' + prefix + 'slider-handle" role="slider" tabindex="-1"></div>' + '</div>'; }, reset: function () { this.value(this._initValue).repaint(); }, postRender: function () { var self = this; var minValue, maxValue, screenCordName, stylePosName, sizeName, shortSizeName; function toFraction(min, max, val) { return (val + min) / (max - min); } function fromFraction(min, max, val) { return val * (max - min) - min; } function handleKeyboard(minValue, maxValue) { function alter(delta) { var value; value = self.value(); value = fromFraction(minValue, maxValue, toFraction(minValue, maxValue, value) + delta * 0.05); value = constrain(value, minValue, maxValue); self.value(value); self.fire('dragstart', { value: value }); self.fire('drag', { value: value }); self.fire('dragend', { value: value }); } self.on('keydown', function (e) { switch (e.keyCode) { case 37: case 38: alter(-1); break; case 39: case 40: alter(1); break; } }); } function handleDrag(minValue, maxValue, handleEl) { var startPos, startHandlePos, maxHandlePos, handlePos, value; self._dragHelper = new DragHelper(self._id, { handle: self._id + '-handle', start: function (e) { startPos = e[screenCordName]; startHandlePos = parseInt(self.getEl('handle').style[stylePosName], 10); maxHandlePos = (self.layoutRect()[shortSizeName] || 100) - funcs.getSize(handleEl)[sizeName]; self.fire('dragstart', { value: value }); }, drag: function (e) { var delta = e[screenCordName] - startPos; handlePos = constrain(startHandlePos + delta, 0, maxHandlePos); handleEl.style[stylePosName] = handlePos + 'px'; value = minValue + handlePos / maxHandlePos * (maxValue - minValue); self.value(value); self.tooltip().text('' + self.settings.previewFilter(value)).show().moveRel(handleEl, 'bc tc'); self.fire('drag', { value: value }); }, stop: function () { self.tooltip().hide(); self.fire('dragend', { value: value }); } }); } minValue = self._minValue; maxValue = self._maxValue; if (self.settings.orientation === 'v') { screenCordName = 'screenY'; stylePosName = 'top'; sizeName = 'height'; shortSizeName = 'h'; } else { screenCordName = 'screenX'; stylePosName = 'left'; sizeName = 'width'; shortSizeName = 'w'; } self._super(); handleKeyboard(minValue, maxValue); handleDrag(minValue, maxValue, self.getEl('handle')); }, repaint: function () { this._super(); updateSliderHandle(this, this.value()); }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { updateSliderHandle(self, e.value); }); return self._super(); } }); var Spacer = Widget.extend({ renderHtml: function () { var self = this; self.classes.add('spacer'); self.canFocus = false; return '<div id="' + self._id + '" class="' + self.classes + '"></div>'; } }); var SplitButton = MenuButton.extend({ Defaults: { classes: 'widget btn splitbtn', role: 'button' }, repaint: function () { var self = this; var elm = self.getEl(); var rect = self.layoutRect(); var mainButtonElm, menuButtonElm; self._super(); mainButtonElm = elm.firstChild; menuButtonElm = elm.lastChild; global$9(mainButtonElm).css({ width: rect.w - funcs.getSize(menuButtonElm).width, height: rect.h - 2 }); global$9(menuButtonElm).css({ height: rect.h - 2 }); return self; }, activeMenu: function (state) { var self = this; global$9(self.getEl().lastChild).toggleClass(self.classPrefix + 'active', state); }, renderHtml: function () { var self = this; var id = self._id; var prefix = self.classPrefix; var image; var icon = self.state.get('icon'); var text = self.state.get('text'); var settings = self.settings; var textHtml = '', ariaPressed; image = settings.image; if (image) { icon = 'none'; if (typeof image !== 'string') { image = window.getSelection ? image[0] : image[1]; } image = ' style="background-image: url(\'' + image + '\')"'; } else { image = ''; } icon = settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : ''; if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } ariaPressed = typeof settings.active === 'boolean' ? ' aria-pressed="' + settings.active + '"' : ''; return '<div id="' + id + '" class="' + self.classes + '" role="button"' + ariaPressed + ' tabindex="-1">' + '<button type="button" hidefocus="1" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + '</button>' + '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' + (self._menuBtnText ? (icon ? '\xA0' : '') + self._menuBtnText : '') + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>'; }, postRender: function () { var self = this, onClickHandler = self.settings.onclick; self.on('click', function (e) { var node = e.target; if (e.control === this) { while (node) { if (e.aria && e.aria.key !== 'down' || node.nodeName === 'BUTTON' && node.className.indexOf('open') === -1) { e.stopImmediatePropagation(); if (onClickHandler) { onClickHandler.call(this, e); } return; } node = node.parentNode; } } }); delete self.settings.onclick; return self._super(); } }); var StackLayout = FlowLayout.extend({ Defaults: { containerClass: 'stack-layout', controlClass: 'stack-layout-item', endClass: 'break' }, isNative: function () { return true; } }); var TabPanel = Panel.extend({ Defaults: { layout: 'absolute', defaults: { type: 'panel' } }, activateTab: function (idx) { var activeTabElm; if (this.activeTabId) { activeTabElm = this.getEl(this.activeTabId); global$9(activeTabElm).removeClass(this.classPrefix + 'active'); activeTabElm.setAttribute('aria-selected', 'false'); } this.activeTabId = 't' + idx; activeTabElm = this.getEl('t' + idx); activeTabElm.setAttribute('aria-selected', 'true'); global$9(activeTabElm).addClass(this.classPrefix + 'active'); this.items()[idx].show().fire('showtab'); this.reflow(); this.items().each(function (item, i) { if (idx !== i) { item.hide(); } }); }, renderHtml: function () { var self = this; var layout = self._layout; var tabsHtml = ''; var prefix = self.classPrefix; self.preRender(); layout.preRender(self); self.items().each(function (ctrl, i) { var id = self._id + '-t' + i; ctrl.aria('role', 'tabpanel'); ctrl.aria('labelledby', id); tabsHtml += '<div id="' + id + '" class="' + prefix + 'tab" ' + 'unselectable="on" role="tab" aria-controls="' + ctrl._id + '" aria-selected="false" tabIndex="-1">' + self.encode(ctrl.settings.title) + '</div>'; }); return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + '<div id="' + self._id + '-head" class="' + prefix + 'tabs" role="tablist">' + tabsHtml + '</div>' + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + layout.renderHtml(self) + '</div>' + '</div>'; }, postRender: function () { var self = this; self._super(); self.settings.activeTab = self.settings.activeTab || 0; self.activateTab(self.settings.activeTab); this.on('click', function (e) { var targetParent = e.target.parentNode; if (targetParent && targetParent.id === self._id + '-head') { var i = targetParent.childNodes.length; while (i--) { if (targetParent.childNodes[i] === e.target) { self.activateTab(i); } } } }); }, initLayoutRect: function () { var self = this; var rect, minW, minH; minW = funcs.getSize(self.getEl('head')).width; minW = minW < 0 ? 0 : minW; minH = 0; self.items().each(function (item) { minW = Math.max(minW, item.layoutRect().minW); minH = Math.max(minH, item.layoutRect().minH); }); self.items().each(function (ctrl) { ctrl.settings.x = 0; ctrl.settings.y = 0; ctrl.settings.w = minW; ctrl.settings.h = minH; ctrl.layoutRect({ x: 0, y: 0, w: minW, h: minH }); }); var headH = funcs.getSize(self.getEl('head')).height; self.settings.minWidth = minW; self.settings.minHeight = minH + headH; rect = self._super(); rect.deltaH += headH; rect.innerH = rect.h - rect.deltaH; return rect; } }); var TextBox = Widget.extend({ init: function (settings) { var self = this; self._super(settings); self.classes.add('textbox'); if (settings.multiline) { self.classes.add('multiline'); } else { self.on('keydown', function (e) { var rootControl; if (e.keyCode === 13) { e.preventDefault(); self.parents().reverse().each(function (ctrl) { if (ctrl.toJSON) { rootControl = ctrl; return false; } }); self.fire('submit', { data: rootControl.toJSON() }); } }); self.on('keyup', function (e) { self.state.set('value', e.target.value); }); } }, repaint: function () { var self = this; var style, rect, borderBox, borderW, borderH = 0, lastRepaintRect; style = self.getEl().style; rect = self._layoutRect; lastRepaintRect = self._lastRepaintRect || {}; var doc = document; if (!self.settings.multiline && doc.all && (!doc.documentMode || doc.documentMode <= 8)) { style.lineHeight = rect.h - borderH + 'px'; } borderBox = self.borderBox; borderW = borderBox.left + borderBox.right + 8; borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0); if (rect.x !== lastRepaintRect.x) { style.left = rect.x + 'px'; lastRepaintRect.x = rect.x; } if (rect.y !== lastRepaintRect.y) { style.top = rect.y + 'px'; lastRepaintRect.y = rect.y; } if (rect.w !== lastRepaintRect.w) { style.width = rect.w - borderW + 'px'; lastRepaintRect.w = rect.w; } if (rect.h !== lastRepaintRect.h) { style.height = rect.h - borderH + 'px'; lastRepaintRect.h = rect.h; } self._lastRepaintRect = lastRepaintRect; self.fire('repaint', {}, false); return self; }, renderHtml: function () { var self = this; var settings = self.settings; var attrs, elm; attrs = { id: self._id, hidefocus: '1' }; global$2.each([ 'rows', 'spellcheck', 'maxLength', 'size', 'readonly', 'min', 'max', 'step', 'list', 'pattern', 'placeholder', 'required', 'multiple' ], function (name) { attrs[name] = settings[name]; }); if (self.disabled()) { attrs.disabled = 'disabled'; } if (settings.subtype) { attrs.type = settings.subtype; } elm = funcs.create(settings.multiline ? 'textarea' : 'input', attrs); elm.value = self.state.get('value'); elm.className = self.classes.toString(); return elm.outerHTML; }, value: function (value) { if (arguments.length) { this.state.set('value', value); return this; } if (this.state.get('rendered')) { this.state.set('value', this.getEl().value); } return this.state.get('value'); }, postRender: function () { var self = this; self.getEl().value = self.state.get('value'); self._super(); self.$el.on('change', function (e) { self.state.set('value', e.target.value); self.fire('change', e); }); }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { if (self.getEl().value !== e.value) { self.getEl().value = e.value; } }); self.state.on('change:disabled', function (e) { self.getEl().disabled = e.value; }); return self._super(); }, remove: function () { this.$el.off(); this._super(); } }); var getApi = function () { return { Selector: Selector, Collection: Collection$2, ReflowQueue: $_ef12j5u4jh8lz3nl, Control: Control$1, Factory: global$4, KeyboardNavigation: KeyboardNavigation, Container: Container, DragHelper: DragHelper, Scrollable: $_4acv48u6jh8lz3ns, Panel: Panel, Movable: $_d97gfctrjh8lz3lm, Resizable: $_8a2gtru8jh8lz3ny, FloatPanel: FloatPanel, Window: Window, MessageBox: MessageBox, Tooltip: Tooltip, Widget: Widget, Progress: Progress, Notification: Notification, Layout: Layout, AbsoluteLayout: AbsoluteLayout, Button: Button, ButtonGroup: ButtonGroup, Checkbox: Checkbox, ComboBox: ComboBox, ColorBox: ColorBox, PanelButton: PanelButton, ColorButton: ColorButton, ColorPicker: ColorPicker, Path: Path, ElementPath: ElementPath, FormItem: FormItem, Form: Form, FieldSet: FieldSet, FilePicker: FilePicker, FitLayout: FitLayout, FlexLayout: FlexLayout, FlowLayout: FlowLayout, FormatControls: $_4qdht3w4jh8lz3uo, GridLayout: GridLayout, Iframe: Iframe$1, InfoBox: InfoBox, Label: Label, Toolbar: Toolbar$1, MenuBar: MenuBar, MenuButton: MenuButton, MenuItem: MenuItem, Throbber: Throbber, Menu: Menu, ListBox: ListBox, Radio: Radio, ResizeHandle: ResizeHandle, SelectBox: SelectBox, Slider: Slider, Spacer: Spacer, SplitButton: SplitButton, StackLayout: StackLayout, TabPanel: TabPanel, TextBox: TextBox, DropZone: DropZone, BrowseButton: BrowseButton }; }; var appendTo = function (target) { if (target.ui) { global$2.each(getApi(), function (ref, key) { target.ui[key] = ref; }); } else { target.ui = getApi(); } }; var registerToFactory = function () { global$2.each(getApi(), function (ref, key) { global$4.add(key, ref); }); }; var Api = { appendTo: appendTo, registerToFactory: registerToFactory }; Api.registerToFactory(); Api.appendTo(window.tinymce ? window.tinymce : {}); global.add('modern', function (editor) { $_4qdht3w4jh8lz3uo.setup(editor); return $_1os0v5syjh8lz3j9.get(editor); }); function Theme () { } return Theme; }()); })();
nemiah/poolPi
public_html/backend/libraries/tinymce/themes/modern/theme.js
JavaScript
gpl-3.0
323,313
(function(){ 'use strict'; Ns.views.map.Layout = Marionette.LayoutView.extend({ id: 'map-container', template: '#map-layout-template', regions: { content: '#map-js', legend: '#legend-js', panels: '#map-panels', toolbar: '#map-toolbar', add: '#map-add-node-js', details: '#map-details-js' }, /** * show regions */ onShow: function () { this.content.show(new Ns.views.map.Content({ parent: this })); }, /** * loads map data */ loadMap: function () { var options = { parent: this }; this.toolbar.show(new Ns.views.map.Toolbar(options)); this.panels.show(new Ns.views.map.Panels(options)); this.legend.show(new Ns.views.map.Legend(options)); this.content.currentView.initMapData(); }, /* * show add node view */ addNode: function () { this.reset(); // if not authenticated if (Ns.db.user.isAuthenticated() === false) { // show sign-in modal $('#signin-modal').modal('show'); // listen to loggedin event and come back here this.listenToOnce(Ns.db.user, 'loggedin', this.addNode); return; } this.add.show(new Ns.views.map.Add({ parent: this })); }, showNode: function(node) { this.details.show(new Ns.views.node.Detail({ model: node, parent: this })); }, showEditNode: function(node) { // ensure is allowed to edit if (node.get('can_edit')) { this.showNode(node); this.details.currentView.edit(); } // otherwise go back to details else { Ns.router.navigate('nodes/' + node.id, { trigger: true }); } }, /* * resets to view initial state */ reset: function () { this.content.currentView.closeLeafletPopup(); this.add.empty(); this.details.empty(); } }, { // static methods show: function (method, args) { var view; if (typeof Ns.body.currentView === 'undefined' || !(Ns.body.currentView instanceof Ns.views.map.Layout)) { view = new Ns.views.map.Layout(); Ns.body.show(view); } else { view = Ns.body.currentView; view.reset(); } // call method on Layout view is specified if (method) { view[method].apply(view, args); } }, /* * Resize page elements so that the leaflet map * takes most of the available space in the window */ resizeMap: function () { var overlayContainer = $('#map-overlay-container'), height, selector, width, setWidth = false, body = $('body'); body.css('overflow-x', 'hidden'); // map if (!overlayContainer.length) { height = $(window).height() - $('body > header').height(); selector = '#map-container, #map-toolbar'; } // node details else { height = overlayContainer.height() + parseInt(overlayContainer.css('top'), 10); selector = '#map-container'; } // set new height $(selector).height(height); width = $(window).width(); // take in consideration #map-add-node-js if visible if ($('#map-add-node-js').is(':visible')) { width = width - $('#map-add-node-js').outerWidth(); setWidth = true; } // take in consideration map toolbar if visible else if ($('#map-toolbar').is(':visible')) { width = width - $('#map-toolbar').outerWidth(); setWidth = true; } // set width only if map toolbar is showing if (setWidth){ $('#map').width(width); } else{ $('#map').attr('style', ''); } body.attr('style', ''); // TODO: this is ugly! // call leaflet invalidateSize() to download any gray spot if (Ns.body.currentView instanceof Ns.views.map.Layout && Ns.body.currentView.content && typeof Ns.body.currentView.content.currentView.map !== 'undefined'){ Ns.body.currentView.content.currentView.map.invalidateSize(); } } }); Ns.views.map.Content = Marionette.ItemView.extend({ template: false, collectionEvents: { // populate map as items are added to collection 'add': 'addGeoModelToMap', // remove items from map when models are removed 'remove': 'removeGeoModelFromMap' }, initialize: function (options) { this.parent = options.parent; this.collection = new Ns.collections.Geo(); this.popUpNodeTemplate = _.template($('#map-popup-node-template').html()); // link tweak this.popUpLinkTemplate = _.template($('#map-popup-link-template').html()); // reload data when user logs in or out this.listenTo(Ns.db.user, 'loggedin loggedout', this.reloadMapData); // bind to namespaced events $(window).on('resize.map', _.bind(this.resize, this)); $(window).on('beforeunload.map', _.bind(this.storeMapProperties, this)); // cleanup eventual alerts $.cleanupAlerts(); }, onShow: function () { this.initMap(); }, onDestroy: function () { // store current coordinates when changing view this.storeMapProperties(); // unbind the namespaced events $(window).off('beforeunload.map'); $(window).off('resize.map'); }, /* * get current map coordinates (lat, lng, zoom) */ getMapProperties: function () { var latLng = this.map.getCenter(); return { lat: latLng.lat, lng: latLng.lng, zoom: this.map.getZoom(), baseLayer: this.getCurrentBaseLayer() }; }, /* * store current map coordinates in localStorage */ storeMapProperties: function () { localStorage.setObject('map', this.getMapProperties()); }, /* * get latest stored coordinates or default ones */ rememberMapProperties: function () { return localStorage.getObject('map') || Ns.settings.map; }, /* * resize window event */ resize: function () { Ns.views.map.Layout.resizeMap(); // when narrowing the window to medium-small size and toolbar is hidden and any panel is still visible if ($(window).width() <= 767 && $('#map-toolbar').is(':hidden') && $('.side-panel:visible').length) { // close panel $('.mask').trigger('click'); } }, /* * initialize leaflet map */ initMap: function () { var self = this, memory = this.rememberMapProperties(); this.resize(); // init map this.map = $.loadDjangoLeafletMap(); // remember last coordinates this.map.setView([memory.lat, memory.lng], memory.zoom, { trackResize: true }); // store baseLayers this.baseLayers = {}; _.each(this.map.layerscontrol._layers, function (baseLayer) { self.baseLayers[baseLayer.name] = baseLayer.layer; // keep name reference self.baseLayers[baseLayer.name].name = baseLayer.name; }); // remember preferred baseLayer if (memory.baseLayer) { this.switchBaseLayer(memory.baseLayer); } // create (empty) clusters on map (will be filled by addGeoModelToMap) this.createClusters(); }, /** * changes base layer of the map, only if necessary * (calling the same action twice has no effect) */ switchBaseLayer: function(name){ // ignore if name is undefined if(typeof name === 'undefined'){ return; } // remove all base layers that are not relevant for (var key in this.baseLayers){ if (this.baseLayers[key].name !== name) { this.map.removeLayer(this.baseLayers[key]); } } // if the relevant layer is still not there add it if (!this.map.hasLayer(this.baseLayers[name])) { this.map.addLayer(this.baseLayers[name]); } }, /** * returns name of the current map base layer */ getCurrentBaseLayer: function () { for (var name in this.baseLayers){ if (Boolean(this.baseLayers[name]._map)) { return name; } } return null; }, /* * loads data from API */ initMapData: function () { Ns.changeTitle(gettext('Map')); Ns.menu.currentView.activate('map'); Ns.track(); Ns.state.onNodeClose = 'map'; // when a node-details is closed go back on map this.parent.toolbar.$el.addClass('enabled'); this.resize(); // load cached data if present if (Ns.db.geo.isEmpty() === false) { this.collection.add(Ns.db.geo.models); this.collection.trigger('ready'); } // otherwise fetch from server else { this.fetchMapData(); } // toggle legend group from map when visible attribute changes this.listenTo(Ns.db.legend, 'change:visible', this.toggleLegendGroup); // toggle layer data when visible attribute changes this.listenTo(Ns.db.layers, 'change:visible', this.toggleLayerData); }, /* * fetch map data, merging changes if necessary */ fetchMapData: function () { var self = this, // will contain fresh data geo = new Ns.collections.Geo(), // will be used to fetch data to merge in geo tmp = geo.clone(), additionalGeoJson = Ns.settings.additionalGeoJsonUrls, ready, fetch; // will be called when all sources have been fetched // we need to add 1 to account for the main geojson ready = _.after(additionalGeoJson.length + 1, function () { // reload models self.collection.remove(self.collection.models); self.collection.add(geo.models); // cache geo collection Ns.db.geo = self.collection; // trigger ready event self.collection.trigger('ready'); // unbind event self.collection.off('sync', ready); }); // fetch data and add it to collection fetch = function () { tmp.fetch().done(function () { geo.add(tmp.models); geo.trigger('sync'); }); }; geo.on('sync', ready); // fetch data from API fetch(); additionalGeoJson.forEach(function (url) { tmp._url = url; fetch(); }); // begin temporary tweak for links if (Ns.settings.links) { var links = new Ns.collections.Geo(); links._url = Ns.url('links.geojson'); links.fetch().done(function () { geo.add(links.models); geo.trigger('sync'); }); } // end tweak }, /** * reload map data in the background */ reloadMapData: function () { $.toggleLoading('hide'); // disable loading indicator while data gets refreshed Ns.state.autoToggleLoading = false; // fetch data this.fetchMapData(); // re-enable loading indicator once data is refreshed this.collection.once('ready', function(){ Ns.state.autoToggleLoading = true }); }, /** * prepare empty Leaflet.MarkerCluster objects */ createClusters: function () { var self = this, legend; // loop over each legend item Ns.db.legend.forEach(function (legendModel) { legend = legendModel.toJSON(); // group markers in clusters var cluster = new L.MarkerClusterGroup({ iconCreateFunction: function (cluster) { var count = cluster.getChildCount(), // determine size with the last number of the exponential notation // 0 for < 10, 1 for < 100, 2 for < 1000 and so on size = count.toExponential().split('+')[1]; return L.divIcon({ html: count, className: 'cluster cluster-size-' + size + ' marker-' + this.cssClass }); }, polygonOptions: { fillColor: legend.fill_color, stroke: legend.stroke_width > 0, weight: legend.stroke_width, color: legend.stroke_color, opacity: 0.4 }, cssClass: legend.slug, chunkedLoading: true, showCoverageOnHover: true, zoomToBoundsOnClick: true, removeOutsideVisibleBounds: true, disableClusteringAtZoom: Ns.settings.disableClusteringAtZoom, maxClusterRadius: Ns.settings.maxClusterRadius }); // store reference legendModel.cluster = cluster; // show cluster only if corresponding legend item is visible if(legend.visible){ self.map.addLayer(cluster); } }); }, /** * returns options for the initialization of tooltip for leaflet layers */ tooltipOptions: function(data) { return { container: '#map-js', placement: 'auto top', title: data.name, delay: { show: 600, hide: 0 } } }, /** * adds a geo model to its cluster * binds popup * called whenever a model is added to the collection */ addGeoModelToMap: function (model) { var self = this, leafletLayer = model.get('leaflet'), legend = model.get('legend'), data = model.toJSON(), layer = Ns.db.layers.get(data.layer), // link tweak template = model._type === 'node' ? this.popUpNodeTemplate : this.popUpLinkTemplate; // bind leaflet popup leafletLayer.bindPopup(template(data)); // mouse over / out events leafletLayer.on({ mouseover: function (e) { var l = e.target, type = l.feature.geometry.type; // opacity to 1 l.setStyle({ fillOpacity: 1 }); // bring to front if (!L.Browser.ie && !L.Browser.opera && type === 'Point') { l.bringToFront({ fillOpacity: 1 }); } }, mouseout: function (e) { e.target.setStyle({ fillOpacity: Ns.settings.leafletOptions.fillOpacity }); }, // when popup opens, change the URL fragment popupopen: function (e) { var fragment = Backbone.history.fragment; // do this only if in general map view if (fragment.indexOf('map') >= 0 && fragment.indexOf('nodes') < 0) { Ns.router.navigate('map/' + data.slug); } // destroy container to avoid the chance that the tooltip // might appear while showing the leaflet popup $(e.target._container).tooltip('destroy'); }, // when popup closes popupclose: function (e) { // (and no new popup opens) // URL fragment goes back to initial state var fragment = Backbone.history.fragment; setTimeout(function () { // do this only if in general map view if (self.map._popup === null && fragment.indexOf('map') >= 0 && fragment.indexOf('nodes') < 0) { Ns.router.navigate('map'); } }, 100); // rebind tooltip (it has been destroyed in popupopen event) $(e.target._container).tooltip(self.tooltipOptions(data)); }, add: function(e){ // create tootlip when leaflet layer is added to the view $(e.target._container).tooltip(self.tooltipOptions(data)); }, remove: function(e){ // ensure tooltip is removed when layer is removed from map $(e.target._container).tooltip('destroy'); } }); // show on map only if corresponding nodeshot layer is visible if (layer && layer.get('visible')) { legend.cluster.addLayer(leafletLayer); // avoid covering points if (leafletLayer._map && leafletLayer.feature.geometry.type !== 'Point') { leafletLayer.bringToBack(); } } }, /** * remove geo model from its cluster * called whenever a model is removed from the collection */ removeGeoModelFromMap: function (model) { var cluster = model.get('legend').cluster; cluster.removeLayer(model.get('leaflet')); }, /* * show / hide from map items of a legend group */ toggleLegendGroup: function (legend, visible) { var method = (visible) ? 'addLayer' : 'removeLayer'; this.map[method](legend.cluster); }, /* * show / hide from map items of a legend group */ toggleLayerData: function (layer, visible) { var geo = this.collection, method = (visible) ? 'addLayers' : 'removeLayers', l; Ns.db.legend.forEach(function(legend){ l = geo.whereCollection({ legend: legend, layer: layer.id }).pluck('leaflet'); legend.cluster[method](l); }); // needed to recalculate stats on legend this.trigger('layer-toggled'); }, /* * Open leaflet popup of the specified element */ openLeafletPopup: function (id) { var collection = this.collection, self = this, leafletLayer; // open leaflet pop up if ready if (collection.length && typeof collection !== 'undefined') { try { leafletLayer = this.collection.get(id).get('leaflet'); } catch (e) { $.createModal({ message: id + ' ' + gettext('not found'), onClose: function () { Ns.router.navigate('map'); } }); return; } try { leafletLayer.openPopup(); } // clustering plugin hides leafletLayers when clustered or outside viewport // so we have to zoom in and center the map catch (e){ this.map.fitBounds(leafletLayer.getBounds()); leafletLayer.openPopup(); } } // if not ready wait for map.collectionReady and call again else { this.collection.once('ready', function () { self.openLeafletPopup(id); }); } return; }, /* * Close leaflet popup if open */ closeLeafletPopup: function () { var popup = $('#map-js .leaflet-popup-close-button'); if (popup.length) { popup.get(0).click(); } }, /* * Go to specified latitude and longitude */ goToLatLng: function (latlng, zoom) { latlng = latlng.split(',') latlng = L.latLng(latlng[0], latlng[1]); var self = this, marker = L.marker(latlng); // used in search address feature if (!zoom) { marker.addTo(this.map); zoom = 18; } // go to marker and zoom in this.map.setView(latlng, zoom); // fade out marker if (typeof(marker) !== 'undefined' && this.map.hasLayer(marker)) { $([marker._icon, marker._shadow]).fadeOut(4000, function () { self.map.removeLayer(marker); }); } } }); Ns.views.map.Legend = Marionette.ItemView.extend({ id: 'map-legend', className: 'overlay inverse', template: '#map-legend-template', ui: { 'close': 'a.icon-close' }, events: { 'click @ui.close': 'toggleLegend', 'click li a': 'toggleGroup' }, collectionEvents: { // automatically render when toggling group or recounting 'change:visible counted': 'render' }, initialize: function (options) { this.parent = options.parent; this.collection = Ns.db.legend; this.legendButton = this.parent.toolbar.currentView.ui.legendButton; // display count in legend this.listenTo(this.parent.content.currentView.collection, 'ready', this.count); this.listenTo(this.parent.content.currentView, 'layer-toggled', this.count); }, onRender: function () { // default is true if (localStorage.getObject('legendOpen') === false) { this.$el.hide(); } else { this.legendButton.addClass('disabled'); } }, /* * calculate counts */ count: function () { this.collection.forEach(function (legend) { legend.set('count', legend.cluster.getLayers().length); }); // trigger once all legend items have been counted this.collection.trigger('counted'); }, /* * open or close legend */ toggleLegend: function (e) { e.preventDefault(); var legend = this.$el, button = this.legendButton, open; if (legend.is(':visible')) { legend.fadeOut(255); button.removeClass('disabled'); button.tooltip('enable'); open = false; } else { legend.fadeIn(255); button.addClass('disabled'); button.tooltip('disable').tooltip('hide'); open = true; } localStorage.setItem('legendOpen', open); }, /* * enable or disable something on the map * by clicking on its related legend control */ toggleGroup: function (e) { e.preventDefault(); var status = $(e.currentTarget).attr('data-status'), item = this.collection.get(status); item.set('visible', !item.get('visible')); } }); Ns.views.map.Toolbar = Marionette.ItemView.extend({ template: '#map-toolbar-template', ui: { 'buttons': 'a', 'switchMapMode': '#btn-map-mode', 'legendButton': '#btn-legend', 'toolsButton': 'a.icon-tools', 'prefButton': 'a.icon-config', 'layersControl': 'a.icon-layer-2' }, events: { 'click .icon-pin-add': 'addNode', 'click @ui.buttons': 'togglePanel', 'click @ui.switchMapMode': 'switchMapMode', // siblings events 'click @ui.legendButton': 'toggleLegend' }, initialize: function (options) { this.parent = options.parent; }, onRender: function () { var self = this; // init tooltip this.ui.buttons.tooltip(); // correction for map tools this.ui.toolsButton.click(function (e) { var button = $(this), prefButton = self.ui.prefButton; if (button.hasClass('active')) { prefButton.tooltip('disable'); } else { prefButton.tooltip('enable'); } }); // correction for map-filter this.ui.layersControl.click(function (e) { var button = $(this), otherButtons = self.$el.find('a.icon-config, a.icon-3d, a.icon-tools'); if (button.hasClass('active')) { otherButtons.tooltip('disable'); } else { otherButtons.tooltip('enable'); } }); }, /* * show / hide map toolbar on narrow screens */ toggleToolbar: function (e) { e.preventDefault(); // shortcut var toolbar = this.parent.toolbar.$el, target = $(e.currentTarget); // show toolbar if (toolbar.is(':hidden')) { // just add display:block // which overrides css media-query toolbar.show(); // overimpose on toolbar target.css('right', '-60px'); } // hide toolbar else { // instead of using jQuery.hide() which would hide the toolbar also // if the user enlarged the screen, we clear the style attribute // which will cause the toolbar to be hidden only on narrow screens toolbar.attr('style', ''); // close any open panel if ($('.side-panel:visible').length) { $('.mask').trigger('click'); } // eliminate negative margin correction target.css('right', '0'); } Ns.views.map.Layout.resizeMap(); }, /* * proxy to call add node */ addNode: function (e) { e.preventDefault(); this.parent.addNode(); }, /* * redirects to Ns.views.map.Panels */ toggleLegend: function (e) { this.parent.legend.currentView.toggleLegend(e); }, /* * redirects to Ns.views.map.Panels */ togglePanel: function (e) { this.parent.panels.currentView.togglePanel(e); }, /* * toggle 3D or 2D map */ switchMapMode: function (e) { e.preventDefault(); $.createModal({message: gettext('not implemented yet')}); } }); Ns.views.map.Panels = Marionette.ItemView.extend({ template: '#map-panels-template', ui: { 'switches': 'input.switch', 'scrollers': '.scroller', 'selects': '.selectpicker', 'tools': '.tool', 'distance': '#fn-map-tools .icon-ruler', 'area': '#fn-map-tools .icon-select-area', 'elevation': '#fn-map-tools .icon-elevation-profile' }, events: { 'click #fn-map-tools .notImplemented': 'toggleToolNotImplemented', 'click @ui.distance': 'toggleDistance', 'click @ui.area': 'toggleArea', 'click @ui.elevation': 'toggleElevation', 'click #toggle-toolbar': 'toggleToolbar', 'change .js-base-layers input': 'switchBaseLayer', 'switch-change #fn-map-layers .toggle-layer-data': 'toggleLayer', 'switch-change #fn-map-layers .toggle-legend-data': 'toggleLegend' }, initialize: function (options) { this.parent = options.parent; this.mapView = this.parent.content.currentView; this.toolbarView = this.parent.toolbar.currentView; this.toolbarButtons = this.toolbarView.ui.buttons; // listen to legend change event this.listenTo(Ns.db.legend, 'change:visible', this.syncLegendSwitch); this.populateBaseLayers(); // init tools if (Ns.settings.mapTools) { this.tools = { 'distance': new L.Polyline.Measure(this.mapView.map), 'area': new L.Polygon.Measure(this.mapView.map), 'elevation': new L.Polyline.Elevation(this.mapView.map) }; } }, // populate this.baseLayers populateBaseLayers: function () { var self = this, layer; this.baseLayers = []; // get ordering of baselayers django-leaflet options this.mapView.map.options.djoptions.layers.forEach(function (layerConfig) { layer = self.mapView.baseLayers[layerConfig[0]]; self.baseLayers.push({ checked: Boolean(layer._map), // if _map is not null it means this is the active layer name: layer.name }); }); }, serializeData: function(){ return { 'layers': Ns.db.layers.toJSON(), 'legend': Ns.db.legend.toJSON(), 'baseLayers': this.baseLayers } }, onRender: function () { this.ui.tools.tooltip(); // activate switch this.ui.switches.bootstrapSwitch().bootstrapSwitch('setSizeClass', 'switch-small'); // activate scroller this.ui.scrollers.scroller({ trackMargin: 6 }); // fancy selects this.ui.selects.selectpicker({ style: 'btn-special' }); }, /* * show / hide toolbar panels */ togglePanel: function (e) { e.preventDefault(); var button = $(e.currentTarget), panelId = button.attr('data-panel'), panel = $('#' + panelId), self = this, // determine distance from top distanceFromTop = button.offset().top - $('body > header').eq(0).outerHeight(), preferencesHeight; // if no panel return here if (!panel.length) { return; } // hide any open tooltip $('#map-toolbar .tooltip').hide(); panel.css('top', distanceFromTop); // adjust height of panel if marked as 'adjust-height' if (panel.hasClass('adjust-height')) { preferencesHeight = $('#map-toolbar').height() - distanceFromTop - 18; panel.height(preferencesHeight); } panel.fadeIn(25, function () { panel.find('.scroller').scroller('reset'); button.addClass('active'); button.tooltip('hide').tooltip('disable'); // create a mask for easy closing $.mask(panel, function (e) { // close function if (panel.is(':visible')) { panel.hide(); self.toolbarButtons.removeClass('active'); button.tooltip('enable'); // if clicking again on the same button avoid reopening the panel if ($(e.target).attr('data-panel') === panelId) { e.stopPropagation(); e.preventDefault(); } } }); }); }, toggleToolNotImplemented: function (e) { e.preventDefault(); $.createModal({ message: gettext('not implemented yet') }); return false; }, /* * toggle map tool */ toggleToolButton: function (e) { var button = $(e.currentTarget), active_buttons = $('#fn-map-tools .tool.active'); // if activating a tool if (!button.hasClass('active')) { // deactivate any other active_buttons.trigger('click'); button.addClass('active') .tooltip('hide') .tooltip('disable'); return true; // deactivate } else { button.removeClass('active') .tooltip('enable') .trigger('blur'); return false; } }, toggleDrawTool: function (toolName, e) { var result = this.toggleToolButton(e), tool = this.tools[toolName]; if (result) { tool.enable(); // if tool is disabled with ESC or other ways // sync the nodeshot UI tool.once('disabled', function () { this.toggleToolButton(e); }, this); } else { tool.off('disabled'); tool.disable(); } }, toggleDistance: function (e) { this.toggleDrawTool('distance', e); }, toggleArea: function (e) { this.toggleDrawTool('area', e); }, toggleElevation: function (e) { this.toggleDrawTool('elevation', e); }, drawElevation: function (geojson) { // local vars var points = [], self = this; // the elevation API expects latitude, longitude, so we have to reverse our coords geojson.geometry.coordinates.forEach(function(point){ points.push(point.reverse()); }); // query the elevation API $.getJSON(Ns.url('elevation/'), { // output is '<lat>,<lng>|<lat>,<lng>|<lat>,<lng' path: points.join('|') }).done(function(geojson){ // close tools panel $('.mask').trigger('click'); // create control var el = L.control.elevation({ position: 'bottomright', width: 1020, height: 299, margins: { top: 25, right: 40, bottom: 40, left: 70 }, }); el.addTo(self.mapView.map); var geojsonLayer = L.geoJson(geojson, { onEachFeature: el.addData.bind(el), style: function () { return { color: '#e6a1b3', opacity: 0.7 } } }).addTo(self.mapView.map); var close = $('<a href="#" class="icon-close"></a>'); $('#map-js .elevation.leaflet-control').append('<a href="#" class="icon-close"></a>'); $('#map-js .elevation.leaflet-control .icon-close').one('click', function (e) { e.preventDefault(); self.mapView.map.removeControl(el); self.mapView.map.removeLayer(geojsonLayer); }) }); }, /* * proxy to Ns.views.map.Toolbar.toggleToolbar */ toggleToolbar: function (e) { this.toolbarView.toggleToolbar(e); }, /** * changes base layer of the map * proxy to Ns.views.map.Content.switchBaseLayer */ switchBaseLayer: function (event) { this.mapView.switchBaseLayer($(event.target).attr('data-name')); }, /** * hide / show layer data on map */ toggleLayer: function (event, data) { var layer = Ns.db.layers.get(data.el.attr('data-slug')); layer.set('visible', data.value); }, /** * hide / show legend data on map */ toggleLegend: function(event, data){ this.parent.legend.currentView.$('a[data-status=' + data.el.attr('data-slug') + ']').trigger('click'); }, /** * sync legend state with switches in panel */ syncLegendSwitch: function(legend, state){ var input = this.$('#map-control-legend-' + legend.get('slug')); if(input.bootstrapSwitch('state') !== state){ // second parameter indicates wheter to skip triggering switch event input.bootstrapSwitch('toggleState', true); } } }); Ns.views.map.Add = Marionette.ItemView.extend({ template: '#map-add-node-template', tagName: 'article', ui: { 'formContainer': '#add-node-form-container' }, events: { 'click #add-node-form-container .btn-default': 'destroy', 'submit #add-node-form-container form': 'submitAddNode' }, initialize: function (options) { this.parent = options.parent; // references to objects of other views this.ext = { legend: this.parent.legend.$el, toolbar: this.parent.toolbar.$el, map: this.parent.content.$el, leafletMap: this.parent.content.currentView.map, geo: this.parent.content.currentView.collection, step1: $('#add-node-step1'), step2: $('#add-node-step2') }; // elements that must be hidden this.hidden = $().add(this.ext.legend) .add(this.ext.toolbar) .add(this.ext.map.find('.leaflet-control-attribution')); // needed for toggleLeafletLayers this.dimmed = false; }, serializeData: function(){ return { 'layers': Ns.db.layers.toJSON() }; }, onShow: function () { Ns.router.navigate('map/add'); Ns.changeTitle(gettext('Add node')); Ns.track(); // go to step1 when collection is ready if (this.ext.geo.length){ this.step1(); } else { this.listenToOnce(this.ext.geo, 'ready', this.step1); } // dynamic form this.form = new Backbone.Form({ model: new Ns.models.Node(), submitButton: gettext('Add node') }).render(); this.ui.formContainer.html(this.form.$el); this.$('input[type=checkbox]').bootstrapSwitch().bootstrapSwitch('setSizeClass', 'switch-small'); this.$('select').selectpicker({style: 'btn-special' }); }, /* * when the view is destroyed the map is taken backto its original state */ onBeforeDestroy: function () { this.closeAddNode(); // change url fragment but only if we are still on the map if (Backbone.history.fragment.substr(0, 3) == 'map'){ Ns.router.navigate('map'); } }, /* * proxy to Ns.views.map.Layout.resizeMap */ resizeMap: function() { Ns.views.map.Layout.resizeMap(); }, /* * hide elements that are not needed when adding a new node * show them back when finished */ toggleHidden: function(){ this.hidden.toggle(); this.resizeMap(); this.toggleLeafletLayers(); }, /* * dim out leaflet layers from map when adding a new node * reset default options when finished * clusters are toggled (hidden and shown back) through an additional style tag in <head> * because clusters are re-rendered whenever the map is moved or resized so inline changes * do not persist when resizing or moving */ toggleLeafletLayers: function () { var leafletOptions = Ns.settings.leafletOptions, tmpOpacity = leafletOptions.temporaryOpacity, clusterCss = $('#add-node-cluster-css'), dimOut = !this.dimmed, leaflet; // dim out or reset all leaflet layers this.ext.geo.forEach(function(model){ leaflet = model.get('leaflet'); if (dimOut) { leaflet.options.opacity = tmpOpacity; leaflet.options.fillOpacity = tmpOpacity; leaflet.setStyle(leaflet.options); } else { leaflet.options.opacity = leafletOptions.opacity; leaflet.options.fillOpacity = leafletOptions.fillOpacity; leaflet.setStyle(leaflet.options); } }); if (clusterCss.length === 0) { $('head').append('<style id="add-node-cluster-css">.cluster{ display: none }</style>'); } else{ clusterCss.remove(); } // change dimmed state this.dimmed = dimOut; }, /* * step1 of adding a new node */ step1: function (e) { var self = this, dialog = this.ext.step1, dialog_dimensions = dialog.getHiddenDimensions(); // hide toolbar and enlarge map this.toggleHidden(); // show step1 dialog.css({ width: dialog_dimensions.width+2, right: 0 }); dialog.fadeIn(255); // cancel this.ext.step1.find('button').one('click', function () { self.destroy() }); // on map click (only once) this.ext.leafletMap.once('click', function (e) { dialog.fadeOut(255); self.step2(e); }); }, step2: function (e) { var self = this, dialog = this.ext.step2, dialog_dimensions = dialog.getHiddenDimensions(), map = this.ext.leafletMap, callback, latlng, // draggable marker marker = L.marker([e.latlng.lat, e.latlng.lng], {draggable: true}).addTo(map); // keep a global reference this.newNodeMarker = marker; // set address on form this.setAddressFromLatLng(e.latlng); this.form.setValue('geometry', JSON.stringify(marker.toGeoJSON())); this.setGeometryFromMarker(marker); // update address when moving the marker marker.on('dragend', function (event) { latlng = event.target.getLatLng(); self.setAddressFromLatLng(latlng); self.setGeometryFromMarker(event.target); map.panTo(latlng); }); // zoom in to marker map.setView(marker.getLatLng(), 18, { animate: true }); // show step2 dialog = self.ext.step2, dialog_dimensions = dialog.getHiddenDimensions(); dialog.css({ width: dialog_dimensions.width+2, right: 0 }); dialog.fadeIn(255); // bind cancel button once this.ext.step2.find('.btn-default').one('click', function () { self.destroy() }); // bind confirm button once this.ext.step2.find('.btn-success').one('click', function () { callback = function () { self.resizeMap(); map.panTo(marker._latlng); }; dialog.fadeOut(255); // show form with a nice animation self.parent.add.$el.show().animate({ width: '+70%'}, { duration: 400, progress: callback, complete: callback }); }); }, /* * submit new node */ submitAddNode: function (e) { e.preventDefault(); var self = this, form = this.form, geojson = JSON.stringify(this.newNodeMarker.toGeoJSON().geometry), errorList = this.$('.error-list'), node = form.model, errors = form.commit(), geo; if (errors) { return false; } this.$('.help-block').text('').hide(); this.$('.error').removeClass('error'); this.$('.has-error').removeClass('has-error'); errorList.html('').hide(); node.save().done(function () { // convert to Geo model node = new Ns.models.Geo(node.toJSON()); // add to geo collection self.ext.geo.add(node); // destroy this view self.destroy(); // open new node popup node.get('leaflet').openPopup(); }).error(function (http) { // TODO: make this reusable var json = http.responseJSON, key, input, errorContainer; for (key in json) { input = self.$('input[name=' + key + ']'); if (input.length) { input.addClass('error'); errorContainer = input.parents('.form-group').find('.help-block'); errorContainer.text(json[key]) .removeClass('hidden') .addClass('has-error') .fadeIn(255); } else { errorList.show(); errorList.append('<li>' + json[key] + '</li>'); } } }); }, /* * cancel addNode operation * resets normal map functions */ closeAddNode: function () { var marker = this.newNodeMarker, container = this.parent.add.$el, map = this.ext.leafletMap, self = this, resetToOriginalState = function () { container.hide(); // show hidden elements again self.toggleHidden(); }; // unbind click events map.off('click'); this.ext.step1.find('button').off('click'); this.ext.step2.find('.btn-default').off('click'); this.ext.step2.find('.btn-success').off('click'); // remove marker if necessary if (marker) { map.removeLayer(marker); } // hide step1 if necessary if (this.ext.step1.is(':visible')) { this.ext.step1.fadeOut(255); } // hide step2 if necessary if (this.ext.step2.is(':visible')) { this.ext.step2.fadeOut(255); } // if container is visible if (container.is(':visible')) { // hide it with a nice animation container.animate({ width: '0' }, { duration: 400, progress: function () { self.resizeMap(); if (marker) { map.panTo(marker._latlng); } }, complete: resetToOriginalState }); } // reset original state else{ resetToOriginalState(); } }, /* * retrieve address from latlng through OSM Nominatim service * and set it on the add node form */ setAddressFromLatLng: function (latlng) { var self = this; $.geocode({ lat: latlng.lat, lon: latlng.lng, callback: function(result){ self.form.setValue('address', result.display_name); } }); }, /** * set geometry on model from marker geojson */ setGeometryFromMarker: function (marker) { this.form.setValue('geometry', JSON.stringify(marker.toGeoJSON().geometry)); } }); })();
ninuxorg/nodeshot
nodeshot/ui/default/static/ui/nodeshot/js/views/map.js
JavaScript
gpl-3.0
50,921
YUI(M.yui.loader, {lang: M.local_mail_lang}).use('io-base', 'node', 'json-parse', 'panel', 'datatable-base', 'dd-plugin', 'moodle-form-dateselector', 'datatype-date', 'calendar-base', function(Y) { var mail_message_view = false; var mail_checkbox_labels_default = {}; var mail_view_type = ''; var mail_edit_label_panel; var mail_new_label_panel; var mail_undo_function = ''; var mail_undo_ids = ''; var mail_search_selected = ''; var mail_searchfrom_selected = ''; var mail_searchto_selected = ''; var mail_unread_selected = false; var mail_attach_selected = false; var mail_date_selected = ''; var mail_doing_search = false; var mail_after_message_search = false; var mail_before_message_search = false; var mail_perpageid = 0; var init = function(){ mail_view_type = Y.one('input[name="type"]').get('value'); if (Y.one('input[name="m"]')) { mail_message_view = true; Y.one('.mail_checkbox_all').remove(); } mail_enable_all_buttons(mail_message_view); if (!mail_message_view) { mail_select_none(); } if (mail_view_type == 'trash') { mail_remove_action('.mail_menu_action_markasstarred'); mail_remove_action('.mail_menu_action_markasunstarred'); } mail_update_menu_actions(); mail_create_edit_label_panel(); mail_create_new_label_panel(); mail_define_label_handlers(); }; var mail_define_label_handlers = function () { if (Y.one('#local_mail_form_new_label')) { //Click on new label color div Y.one('#local_mail_form_new_label').delegate('click', function(e) { e.stopPropagation(); mail_label_set_selected(this, 'new'); }, '.mail_label_color'); } if (Y.one('#local_mail_form_edit_label')) { //Click on edit label color div Y.one('#local_mail_form_edit_label').delegate('click', function(e) { e.stopPropagation(); mail_label_set_selected(this, 'edit'); }, '.mail_label_color'); } }; var mail_create_edit_label_panel = function () { var title = M.util.get_string('editlabel', 'local_mail'); var obj = (Y.one('.mail_list')?Y.one('.mail_list'):Y.one('.mail_view')); var position = obj.getXY(); var width = 400; var posx = position[0]+(Y.one('body').get('offsetWidth')/2)-width; mail_edit_label_panel = new Y.Panel({ srcNode : '#local_mail_form_edit_label', headerContent: title, width : width, zIndex : 5, centered : false, modal : true, visible : false, render : true, xy : [posx,position[1]], plugins : [Y.Plugin.Drag] }); mail_edit_label_panel.addButton({ value : M.util.get_string('submit', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_edit_label_panel.hide(); mail_doaction('setlabel'); } }); mail_edit_label_panel.addButton({ value : M.util.get_string('cancel', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_edit_label_panel.hide(); } }); }; var mail_create_new_label_panel = function () { var title = M.util.get_string('newlabel', 'local_mail'); var obj = (Y.one('.mail_list')?Y.one('.mail_list'):Y.one('.mail_view')); var position = obj.getXY(); var width = 400; var posx = position[0]+(Y.one('body').get('offsetWidth')/2)-width; mail_new_label_panel = new Y.Panel({ srcNode : '#local_mail_form_new_label', headerContent: title, width : width, zIndex : 5, centered : true, modal : true, visible : false, render : true, xy : [posx,position[1]], plugins : [Y.Plugin.Drag] }); mail_new_label_panel.addButton({ value : M.util.get_string('submit', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_new_label_panel.hide(); mail_doaction('newlabel'); } }); mail_new_label_panel.addButton({ value : M.util.get_string('cancel', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_new_label_panel.hide(); } }); }; var mail_hide_actions = function() { Y.all('.mail_menu_actions li').each(function(node){ node.hide(); }); mail_show_label_actions(false); }; var mail_show_label_actions = function(separator) { if (mail_view_type == 'label' && !mail_message_view) { if (separator) { Y.one('.mail_menu_action_separator').ancestor('li').show(); } Y.one('.mail_menu_action_editlabel').ancestor('li').show(); Y.one('.mail_menu_action_removelabel').ancestor('li').show(); } }; var mail_update_menu_actions = function() { var separator = false; mail_hide_actions(); if (mail_message_view) { if (mail_view_type == 'trash') { Y.one('.mail_menu_action_markasunread').ancestor('li').show(); } else { Y.one('.mail_menu_action_markasunread').ancestor('li').show(); if (Y.one('.mail_flags span').hasClass('mail_starred')) { Y.one('.mail_menu_action_markasunstarred').ancestor('li').show(); } else { Y.one('.mail_menu_action_markasstarred').ancestor('li').show(); } } } else { if (Y.all('.mail_selected.mail_unread').size()) { Y.one('.mail_menu_action_markasread').ancestor('li').show(); separator = true; } if (Y.all('.mail_selected.mail_unread').size() < Y.all('.mail_selected').size()) { Y.one('.mail_menu_action_markasunread').ancestor('li').show(); separator = true; } if (Y.all('.mail_selected span.mail_starred').size()) { Y.one('.mail_menu_action_markasunstarred').ancestor('li').show(); separator = true; } if (Y.all('.mail_selected span.mail_unstarred').size()) { Y.one('.mail_menu_action_markasstarred').ancestor('li').show(); separator = true; } } mail_show_label_actions(separator); }; var mail_toggle_menu = function() { var button = Y.one('.mail_checkbox_all'); var menu = Y.one('.mail_optselect'); var position = button.getXY(); if (!button.hasClass('mail_button_disabled')) { position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); } }; var mail_hide_menu_options = function() { Y.one('.mail_optselect').addClass('mail_hidden'); }; var mail_hide_menu_actions = function() { Y.one('.mail_actselect').addClass('mail_hidden'); }; var mail_hide_menu_labels = function() { if (mail_view_type != 'trash') { Y.one('.mail_labelselect').addClass('mail_hidden'); } }; var mail_hide_menu_search = function() { var menu = Y.one('#mail_menu_search'); if (menu) { menu.addClass('mail_hidden'); } if (M.form.dateselector.panel) { M.form.dateselector.panel.hide(); } }; var mail_toggle_menu_actions = function() { var button = Y.one('.mail_more_actions'); var menu = Y.one('.mail_actselect'); var position = button.getXY(); if (!button.hasClass('mail_button_disabled')) { position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); } }; var mail_toggle_menu_labels = function() { var button = Y.one('.mail_assignlbl'); var menu = Y.one('.mail_labelselect'); var position = button.getXY(); if (!button.hasClass('mail_button_disabled')) { position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); } }; var mail_toggle_menu_search = function() { var button = Y.one('#mail_search'); var menu = Y.one('#mail_menu_search'); var advsearch = Y.one('#mail_adv_search'); var position = button.getXY(); var date; position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); if (!menu.hasClass('mail_hidden')) { Y.one('#textsearch').focus(); if (!advsearch.hasClass('mail_hidden')) { mail_position_datepicker(); } if (mail_doing_search) { Y.one('#buttoncancelsearch').removeClass('mail_hidden'); } else { Y.one('#buttoncancelsearch').addClass('mail_hidden'); } } else { M.form.dateselector.panel.hide(); } }; var mail_toggle_adv_search = function() { var menu = Y.one('#mail_adv_search'); var status = Y.one('#mail_adv_status'); menu.toggleClass('mail_hidden'); if (menu.hasClass('mail_hidden')) { M.form.dateselector.panel.hide(); status.set('src', M.util.image_url('t/collapsed', 'moodle')); status.set('alt', 'collapsed'); } else { mail_position_datepicker(); status.set('src', M.util.image_url('t/expanded', 'moodle')); status.set('alt' ,'expanded'); } }; var mail_do_search = function() { mail_doing_search = true; mail_perpageid = 0; mail_search_selected = Y.one('#textsearch').get('value'); mail_searchfrom_selected = Y.one('#textsearchfrom').get('value'); mail_searchto_selected = Y.one('#textsearchto').get('value'); mail_unread_selected = Y.one('#searchunread').get('checked'); mail_attach_selected = Y.one('#searchattach').get('checked'); mail_select_none(); mail_check_selected(); Y.all('.mail_paging input').set('disabled', 'disabled'); mail_show_loading_image(); mail_doaction('search'); mail_hide_menu_search(); }; var mail_show_loading_image = function() { Y.one('.mail_list').addClass('mail_hidden'); Y.one('.mail_search_loading').removeClass('mail_hidden'); }; var mail_update_form_search = function() { Y.one('#textsearch').set('value', mail_search_selected); Y.one('#textsearchfrom').set('value', mail_searchfrom_selected); Y.one('#textsearchto').set('value', mail_searchto_selected); if (mail_unread_selected) { Y.one('#searchunread').set('checked', 'checked'); } if (mail_attach_selected) { Y.one('#searchattach').set('checked', 'checked'); } }; var mail_remove_action = function(action) { Y.one(action).ancestor('li').remove(); }; var mail_customize_menu_actions = function(checkbox) { var menu = Y.one('.mail_menu_actions'); var mailitem = checkbox.ancestor('.mail_item'); var separator = false; var nodes; if (mail_is_checkbox_checked(checkbox)) { //Read or unread if (mailitem.hasClass('mail_unread')) { menu.one('a.mail_menu_action_markasread').ancestor('li').show(); separator = true; } else { menu.one('a.mail_menu_action_markasunread').ancestor('li').show(); separator = true; } //Starred or unstarred if (mail_view_type != 'trash' && mailitem.one('.mail_flags span').hasClass('mail_starred')) { menu.one('a.mail_menu_action_markasunstarred').ancestor('li').show(); separator = true; } else { if (mail_view_type != 'trash') { menu.one('a.mail_menu_action_markasstarred').ancestor('li').show(); separator = true; } } } else { if (!Y.all('.mail_list .mail_selected').size()) { mail_hide_actions(); } else { //Read or unread if (mailitem.hasClass('mail_unread')) { if (!mailitem.siblings('.mail_selected.mail_unread').size()) { menu.one('a.mail_menu_action_markasread').ancestor('li').hide(); } } else { if (mailitem.siblings('.mail_selected.mail_unread').size() == mailitem.siblings('.mail_selected').size()) { menu.one('a.mail_menu_action_markasunread').ancestor('li').hide(); } } //Starred or unstarred if (mail_view_type != 'trash' && mailitem.one('.mail_flags a span').hasClass('mail_starred')) { nodes = mailitem.siblings(function(obj) { return obj.hasClass('mail_selected') && obj.one('.mail_flags a span.mail_starred'); }); if (!nodes.size()) { menu.one('a.mail_menu_action_markasunstarred').ancestor('li').hide(); } } else { nodes = mailitem.siblings(function(obj) { return obj.hasClass('mail_selected') && obj.one('.mail_flags a span.mail_unstarred'); }); if (mail_view_type != 'trash' && !nodes.size()) { menu.one('a.mail_menu_action_markasstarred').ancestor('li').hide(); } } } } mail_show_label_actions(separator); }; var mail_label_default_values = function () { var grouplabels; if (Y.one('.mail_labelselect').hasClass('mail_hidden')) { Y.each(M.local_mail.mail_labels, function (label, index) { mail_checkbox_labels_default[index] = 0; }); if (mail_message_view) { grouplabels = Y.all('.mail_group_labels span'); if (grouplabels) { mail_set_label_default_values(grouplabels); } } else { var nodes = mail_get_checkboxs_checked(); Y.each(nodes, function (node, index) { grouplabels = node.ancestor('.mail_item').all('.mail_group_labels span'); if (grouplabels) { mail_set_label_default_values(grouplabels); } }); } mail_label_set_values(); } }; var mail_set_label_default_values = function (grouplabels) { var classnames = []; var num; Y.each(grouplabels, function (grouplabel, index) { classnames = grouplabel.getAttribute('class').split(' '); Y.each(classnames, function(classname){ num = /mail_label_(\d+)/.exec(classname); if (num) { mail_checkbox_labels_default[num[1]] += 1; } }); }); if (mail_view_type == 'label') { num = parseInt(Y.one('input[name="itemid"]').get('value'), 10); mail_checkbox_labels_default[num] += 1; } }; var mail_menu_label_selection = function (node) { var checkbox = node.one('.mail_adv_checkbox'); if (checkbox) { mail_toggle_checkbox(checkbox); } }; var mail_customize_menu_label = function() { if (Y.all('.mail_menu_labels li').size() > 1) { if(mail_label_check_default_values()) { Y.one('.mail_menu_labels .mail_menu_label_newlabel').removeClass('mail_hidden'); Y.one('.mail_menu_labels .mail_menu_label_apply').addClass('mail_hidden'); } else { Y.one('.mail_menu_labels .mail_menu_label_newlabel').addClass('mail_hidden'); Y.one('.mail_menu_labels .mail_menu_label_apply').removeClass('mail_hidden'); } } }; var mail_label_check_default_values = function () { var isdefault = true; var classname; var labelid; var num; var labels = Y.all('.mail_menu_labels .mail_adv_checkbox'); if (!mail_message_view) { var total = mail_get_checkboxs_checked().size(); Y.each(labels, function(label, index) { classname = label.getAttribute('class'); num = /mail_label_value_(\d+)/.exec(classname); if (num) { labelid = num[1]; if (mail_checkbox_labels_default[labelid] == total) { isdefault = isdefault && label.hasClass('mail_checkbox1'); } else if(mail_checkbox_labels_default[labelid] > 0) { isdefault = isdefault && label.hasClass('mail_checkbox2'); } else { isdefault = isdefault && label.hasClass('mail_checkbox0'); } } }); } else { Y.each(labels, function(label, index) { classname = label.getAttribute('class'); num = /mail_label_value_(\d+)/.exec(classname); if (num) { labelid = num[1]; if (mail_checkbox_labels_default[labelid] == 1) { isdefault = isdefault && label.hasClass('mail_checkbox1'); } else { isdefault = isdefault && label.hasClass('mail_checkbox0'); } } }); } return isdefault; }; var mail_label_set_values = function () { var total = (mail_message_view?1:mail_get_checkboxs_checked().size()); var state; Y.each(mail_checkbox_labels_default, function(value, index){ if (value == total) { state = 1; } else if(value > 0) { state = 2; } else { state = 0; } mail_set_checkbox(Y.one('.mail_menu_labels .mail_label_value_'+index), state); }); }; var mail_get_label_value = function(checkbox){ var value; classnames = checkbox.getAttribute('class').split(' '); Y.each(classnames, function(classname){ num = /mail_label_value_(\d+)/.exec(classname); if (num) { value = num[1]; } }); return value; }; var mail_get_labels_checked = function(){ return Y.all('.mail_menu_labels .mail_checkbox1'); }; var mail_get_labels_thirdstate = function(){ return Y.all('.mail_menu_labels .mail_checkbox2'); }; var mail_get_labels_values = function(thirdstate){ var nodes = (thirdstate?mail_get_labels_thirdstate():mail_get_labels_checked()); var values = []; Y.each(nodes, function (node, index) { values.push(mail_get_label_value(node)); }); return values.join(); }; var mail_assign_labels = function (node) { node = (typeof node !== 'undefined' ? node : false); var grouplabels; var elem; var labelid = 0; if (mail_message_view) { grouplabels = Y.one('.mail_group_labels'); } else { grouplabels = node.ancestor('.mail_item').one('.mail_group_labels'); } if (mail_view_type == 'label') { labelid = parseInt(Y.one('input[name="itemid"]').get('value'), 10); } var lblstoadd = mail_get_labels_values(false).split(','); var lblstoremain = mail_get_labels_values(true).split(','); Y.each(M.local_mail.mail_labels, function (value, index) { if (Y.Array.indexOf(lblstoadd, index) != -1) { if (index != labelid) { elem = grouplabels.one('.mail_label_'+index); if (!elem) { elem = Y.Node.create('<span class="mail_label mail_label_'+M.local_mail.mail_labels[index].color+' mail_label_'+index+'">'+M.local_mail.mail_labels[index].name+'</span>'); grouplabels.append(elem); } } } else if (Y.Array.indexOf(lblstoremain, index) == -1) { if (!mail_message_view && index == labelid) { grouplabels.ancestor('.mail_item').remove(); } else { elem = grouplabels.one('.mail_label_'+index); if (elem) { elem.remove(); } } } }); }; var mail_check_selected = function() { mail_enable_all_buttons(Y.all('.mail_selected').size()); }; var mail_enable_button = function(button, bool) { bool = (typeof bool !== 'undefined' ? bool : false); if (bool) { button.removeClass('mail_button_disabled'); } else if(!button.hasClass('mail_checkbox_all')){ button.addClass('mail_button_disabled'); } }; var mail_enable_all_buttons = function(bool) { var mail_buttons = Y.all('.mail_toolbar .mail_buttons .mail_button'); Y.each(mail_buttons, (function(button) { button.removeClass('mail_hidden'); mail_enable_button(button, bool); })); if (Y.one('#mail_search')) { mail_enable_button(Y.one('#mail_search'), true); } if (Y.one('#buttonsearch')) { mail_enable_button(Y.one('#buttonsearch'), true); } if (Y.one('#buttoncancelsearch')) { mail_enable_button(Y.one('#buttoncancelsearch'), true); } if (mail_view_type == 'label') { mail_enable_button(Y.one('.mail_toolbar .mail_more_actions'), true); } }; var mail_get_checkboxs_checked = function(){ return Y.all('.mail_list .mail_checkbox1'); }; var mail_get_checkbox_value = function(checkbox){ var value; classnames = checkbox.getAttribute('class').split(' '); Y.each(classnames, function(classname){ num = /mail_checkbox_value_(\d+)/.exec(classname); if (num) { value = num[1]; } }); return value; }; var mail_get_checkboxs_values = function(){ var nodes = mail_get_checkboxs_checked(); var values = []; Y.each(nodes, function (node, index) { values.push(mail_get_checkbox_value(node)); }); return values.join(); }; var mail_set_checkbox = function(node, value){ if (value == 1) { node.removeClass('mail_checkbox0').removeClass('mail_checkbox2').addClass('mail_checkbox1'); } else if (value == 2) { node.removeClass('mail_checkbox0').removeClass('mail_checkbox1').addClass('mail_checkbox2'); } else { node.removeClass('mail_checkbox1').removeClass('mail_checkbox2').addClass('mail_checkbox0'); } }; var mail_toggle_checkbox = function(node){ if (node.hasClass('mail_checkbox0')) { mail_set_checkbox(node, 1); } else { mail_set_checkbox(node, 0); } }; var mail_is_checkbox_checked = function(node){ return node.hasClass('mail_checkbox1'); }; var mail_main_checkbox = function(){ if(!Y.all('.mail_selected').size()) { mail_set_checkbox(Y.one('.mail_checkbox_all > .mail_adv_checkbox'), 0); } else if(Y.all('.mail_selected').size() == Y.all('.mail_item').size()) { mail_set_checkbox(Y.one('.mail_checkbox_all > .mail_adv_checkbox'), 1); } else { mail_set_checkbox(Y.one('.mail_checkbox_all > .mail_adv_checkbox'), 2); } mail_check_selected(); }; var mail_select_all = function(){ var checkbox = Y.one('.mail_checkbox_all > .mail_adv_checkbox'); mail_set_checkbox(checkbox, 1); var nodes = Y.all('.mail_list .mail_adv_checkbox'); nodes.each(function(node) { mail_set_checkbox(node, 1); node.ancestor('.mail_item').addClass('mail_selected'); }); }; var mail_select_none = function(){ var checkbox = Y.one('.mail_checkbox_all > .mail_adv_checkbox'); mail_set_checkbox(checkbox, 0); var nodes = Y.all('.mail_list .mail_adv_checkbox'); nodes.each(function(node) { mail_set_checkbox(node, 0); node.ancestor('.mail_item').removeClass('mail_selected'); }); }; var mail_select_read = function(){ var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (!ancestor.hasClass('mail_unread')){ mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; var mail_select_unread = function() { var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (ancestor.hasClass('mail_unread')){ mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; var mail_select_starred = function() { var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (ancestor.one('.mail_starred')) { mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; var mail_select_unstarred = function() { var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (ancestor.one('.mail_unstarred')) { mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; //Success call var handleSuccess = function (transactionid, response, args) { var obj = Y.JSON.parse(response.responseText); var img; var node; if (obj.msgerror) { alert(obj.msgerror); } else { if (obj.html) { Y.one('#local_mail_main_form').setContent(obj.html); init(); mail_update_url(); } if (obj.search) { mail_perpageid = obj.search.perpageid; mail_doing_search = true; Y.one('#mail_search').addClass('mail_button_searching'); Y.one('.mail_paging input[name="prevpage"]').set('disabled', 'disabled'); Y.one('.mail_paging input[name="nextpage"]').set('disabled', 'disabled'); Y.one('.mail_paging > span').addClass('mail_hidden'); mail_search_selected = obj.search.query; mail_searchfrom_selected = obj.search.searchfrom; mail_searchto_selected = obj.search.searchto; mail_unread_selected = obj.search.unread; mail_attach_selected = obj.search.attach; mail_date_selected = obj.search.date; mail_update_form_search(); if (obj.search.prev) { Y.one('.mail_paging input[name="prevpage"]').set('disabled', ''); } if (obj.search.next) { Y.one('.mail_paging input[name="nextpage"]').set('disabled', ''); } if (!mail_message_view) { mail_before_message_search = obj.search.idbefore; mail_after_message_search = obj.search.idafter; } } if (obj.info) { if (obj.info.root) { node = Y.one('.mail_root span'); if (node) { node.setContent(obj.info.root); } node = Y.one('.mail_root'); if (node) { if(obj.info.root.match(/\(\d+\)/)) { node.addClass('local_mail_new_messages'); } else { node.removeClass('local_mail_new_messages'); } } } if (obj.info.inbox) { node = Y.one('.mail_inbox a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_inbox a'); if (node) { node.setContent(img+obj.info.inbox); } } } if (obj.info.drafts) { node = Y.one('.mail_drafts a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_drafts a'); if (node) { node.setContent(img+obj.info.drafts); } } } if (obj.info.courses) { Y.each(obj.info.courses, (function(value, index) { node = Y.one('.mail_course_'+index+' a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_course_'+index+' a'); if (node) { Y.one('.mail_course_'+index+' a').setContent(img+value); } } })); } if (obj.info.labels) { Y.each(obj.info.labels, (function(value, index) { node = Y.one('.mail_label_'+index+' a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_label_'+index+' a'); if (node) { node.setContent(img+value); } } })); } } //Undo last action if (obj.undo && mail_undo_function != 'undo') { var msg = M.util.get_string('undo'+mail_undo_function, 'local_mail', obj.undo.split(',').length); if (mail_undo_function == 'delete') { mail_undo_function = 'restore'; } else if (mail_undo_function == 'restore') { mail_undo_function = 'delete'; } mail_notification_message(msg); mail_undo_ids = obj.undo; } else { mail_undo_function = ''; } if(obj.redirect) { document.location.href = obj.redirect; } } }; //Failure call var handleFailure = function (transactionid, response, args) { console.log(response); }; //Update screen data and async call var mail_doaction = function(action, node) { node = (typeof node !== 'undefined' ? node : null); var nodes = mail_get_checkboxs_checked(); var obj; var child; var ancestor; var ids; var request; var mail_view; if(mail_message_view) { if(action == 'togglestarred') { obj = node.one('span'); if (obj.hasClass('mail_starred')) { action = 'unstarred'; obj.replaceClass('mail_starred', 'mail_unstarred'); node.set('title', M.util.get_string('unstarred','local_mail')); } else { action = 'starred'; obj.replaceClass('mail_unstarred', 'mail_starred'); node.set('title', M.util.get_string('starred','local_mail')); } } else if (action == 'delete' || action == 'restore') { mail_undo_function = action; mail_message_view = false; } else if (action == 'starred') { node = Y.one('.mail_flags span'); node.replaceClass('mail_unstarred', 'mail_starred'); node.ancestor('a').set('title', M.util.get_string('starred','local_mail')); } else if (action == 'unstarred') { node = Y.one('.mail_flags span'); node.replaceClass('mail_starred', 'mail_unstarred'); node.ancestor('a').set('title', M.util.get_string('unstarred','local_mail')); } else if(action == 'markasunread') { mail_message_view = false; } else if(action == 'goback') { mail_message_view = false; } else if(action == 'assignlabels') { mail_assign_labels(); } mail_view = true; ids = Y.one('input[name="m"]').get('value'); } else {//List messages view if(action == 'viewmail') { nodes.empty(); var url = node.get('href'); if (url.match(/compose\.php/)){ document.location.href = url; return 0; } else { ids = /m=(\d+)/.exec(node.get('href'))[1]; } } else if (action == 'delete') { mail_undo_function = action; ids = mail_get_checkboxs_values(); } else if (action == 'restore') { mail_undo_function = action; ids = mail_get_checkboxs_values(); } else if (action == 'discard') { ids = mail_get_checkboxs_values(); } else if (action == 'undo') { nodes.empty(); action = mail_undo_function; mail_undo_function = 'undo'; ids = mail_undo_ids; } else if (action == 'togglestarred') { obj = node.ancestor('.mail_item').one('.mail_adv_checkbox'); nodes = Y.all(obj); if (node.one('span').hasClass('mail_starred')) { action = 'unstarred'; } else { action = 'starred'; } ids = mail_get_checkbox_value(obj); } else if(action == 'perpage' || action == 'search'){ nodes.empty(); } else { ids = mail_get_checkboxs_values(); } if (nodes.size()) { nodes.each(function (node) { ancestor = node.ancestor('.mail_item'); if (action == 'starred') { child = ancestor.one('.mail_unstarred'); if(child) { child.replaceClass('mail_unstarred', 'mail_starred'); child.ancestor('a').set('title', M.util.get_string('starred','local_mail')); } } else if(action == 'unstarred') { if (mail_view_type == 'starred') { ancestor.remove(); } else { child = ancestor.one('.mail_starred'); if(child) { child.replaceClass('mail_starred', 'mail_unstarred'); child.ancestor('a').set('title', M.util.get_string('unstarred','local_mail')); } } } else if(action == 'markasread') { ancestor.removeClass('mail_unread'); } else if(action == 'markasunread') { ancestor.addClass('mail_unread'); } else if(action == 'delete' || action == 'restore' || action == 'discard') { ancestor.remove(); } else if(action == 'assignlabels') { mail_assign_labels(node); } }); } mail_view = false; } //Ajax call var cfg = { method: 'POST', data: { msgs: ids, sesskey: Y.one('input[name="sesskey"]').get('value'), type: mail_view_type, offset: Y.one('input[name="offset"]').get('value'), action: action, mailview: mail_view }, on: { success:handleSuccess, failure:handleFailure } }; if (Y.one('input[name="m"]')) { cfg.data.m = Y.one('input[name="m"]').get('value'); } if(Y.one('input[name="itemid"]')) { cfg.data.itemid = Y.one('input[name="itemid"]').get('value'); } if (action == 'perpage') { cfg.data.perpage = (node.get('innerText')?node.get('innerText'):node.get('textContent')); } if (action == 'assignlabels') { cfg.data.labelids = mail_get_labels_values(false); cfg.data.labeltsids = mail_get_labels_values(true); } if (action == 'setlabel') { obj = Y.one('#local_mail_edit_label_color'); cfg.data.labelname = Y.one('#local_mail_edit_label_name').get('value'); if (!cfg.data.labelname) { alert(M.util.get_string('erroremptylabelname', 'local_mail')); mail_label_edit(); return false; } else if (cfg.data.labelname.length > 100) { alert(M.util.get_string('maximumchars', 'moodle', 100)); mail_label_edit(); return false; } cfg.data.labelcolor = obj.get('value'); } if (action == 'newlabel') { obj = Y.one('#local_mail_new_label_color'); cfg.data.labelname = Y.one('#local_mail_new_label_name').get('value'); if (!cfg.data.labelname) { alert(M.util.get_string('erroremptylabelname', 'local_mail')); mail_label_new(); return false; } else if (cfg.data.labelname.length > 100) { alert(M.util.get_string('maximumchars', 'moodle', 100)); mail_label_new(); return false; } cfg.data.labelcolor = obj.get('value'); } if (action == 'nextpage' || action == 'prevpage' ) { obj = Y.one('#mail_loading_small'); var btn = Y.one('.mail_paging input[name="'+action+'"]'); var position = btn.getXY(); obj.removeClass('mail_hidden'); position[0] += (btn.get('offsetWidth')/2) - (obj.one('img').get('offsetWidth')/2); position[1] = btn.getXY()[1] + (obj.one('img').get('offsetHeight')/2); obj.setXY(position); } if (mail_doing_search) { //Go back when searching keeps current page if (action == 'goback') { if (mail_before_message_search) { cfg.data.before = mail_before_message_search; } else if (mail_after_message_search) { cfg.data.after = mail_after_message_search; } } cfg.data.search = mail_search_selected; cfg.data.searchfrom = mail_searchfrom_selected; cfg.data.searchto = mail_searchto_selected; cfg.data.unread = (mail_unread_selected?'1':''); cfg.data.attach = (mail_attach_selected?'1':''); cfg.data.time = mail_date_selected; cfg.data.perpageid = mail_perpageid; if (action == 'prevpage') { obj = Y.one('.mail_list .mail_item .mail_adv_checkbox'); if (obj) { cfg.data.after = mail_get_checkbox_value(obj); } cfg.data.action = 'search'; } else if (action == 'nextpage') { obj = Y.all('.mail_item:last-child .mail_adv_checkbox'); if (obj) { cfg.data.before = mail_get_checkbox_value(obj.shift()); cfg.data.perpageid = cfg.data.before; } cfg.data.action = 'search'; } cfg.data.searching = true; } if (mail_undo_function == 'undo') { cfg.data.undo = true; } request = Y.io(M.cfg.wwwroot + '/local/mail/ajax.php', cfg); }; var mail_label_confirm_delete = function(e) { var labelid; var message; var labelname = ''; labelid = Y.one('input[name="itemid"]').get('value'); labelname = M.local_mail.mail_labels[labelid].name; if (labelname.length > 25) { labelname = labelname.substring(0, 25) + '...'; } message = M.util.get_string('labeldeleteconfirm', 'local_mail', labelname); M.util.show_confirm_dialog(e, { 'callback' : mail_label_remove, 'message' : message, 'continuelabel': M.util.get_string('delete', 'local_mail') } ); }; var mail_label_remove = function() { var params = []; params.push('offset='+Y.one('input[name="offset"]').get('value')); params.push('sesskey='+Y.one('input[name="sesskey"]').get('value')); params.push('removelbl=1'); params.push('confirmlbl=1'); var url = Y.one('#local_mail_main_form').get('action'); document.location.href = url+'&'+params.join('&'); }; var mail_label_new = function() { mail_new_label_panel.show(); Y.one('#local_mail_form_new_label').removeClass('mail_hidden'); Y.one('#local_mail_new_label_name').focus(); }; var mail_label_edit = function() { var labelid = Y.one('input[name="itemid"]').get('value'); var labelname = M.local_mail.mail_labels[labelid].name; var labelcolor = M.local_mail.mail_labels[labelid].color; Y.one('#local_mail_edit_label_name').set('value', labelname); Y.all('.mail_label_color').removeClass('mail_label_color_selected'); if (!labelcolor) { Y.one('.mail_label_color.mail_label_nocolor').addClass('mail_label_color_selected'); labelcolor = ''; } else { Y.one('.mail_label_color.mail_label_' + labelcolor).addClass('mail_label_color_selected'); } Y.one('#local_mail_edit_label_color').set('value', labelcolor); mail_edit_label_panel.show(); Y.one('#local_mail_form_edit_label').removeClass('mail_hidden'); Y.one('#local_mail_edit_label_name').focus(); }; var mail_label_set_selected = function(obj, action) { Y.all('.mail_label_color').removeClass('mail_label_color_selected'); obj.addClass('mail_label_color_selected'); Y.one('#local_mail_' + action + '_label_color').set('value', obj.getAttribute('data-color')); }; var mail_update_url = function() { var params = []; var offset; var m; var type; if (history.pushState) { params.push('t='+mail_view_type); if (mail_message_view) { params.push('m='+Y.one('input[name="m"]').get('value')); } if (mail_view_type == 'course') { params.push('c='+Y.one('input[name="itemid"]').get('value')); } else { if (mail_view_type == 'label') { params.push('l='+Y.one('input[name="itemid"]').get('value')); } } offset = Y.one('input[name="offset"]').get('value'); if (parseInt(offset, 10) > 0) { params.push('offset='+offset); } history.pushState({}, document.title, M.cfg.wwwroot + '/local/mail/view.php?' + params.join('&')); } }; var mail_position_datepicker = function() { var menu = Y.one('#mail_menu_search'); var datepicker = Y.one('#dateselector-calendar-panel'); var search = Y.one('.mail_search_datepicker'); var position = menu.getXY(); position[0] += (menu.get('offsetWidth')/2) - (datepicker.get('offsetWidth')/2); position[1] = search.getXY()[1] - datepicker.get('offsetHeight'); datepicker.setXY(position); }; var mail_get_selected_date = function(cell, date) { mail_date_selected = cell.date.getFullYear() + ',' + cell.date.getMonth() + ',' + cell.date.getDate(); mail_set_selected_date(mail_date_selected); M.form.dateselector.panel.hide(); }; var mail_set_selected_date = function(date) { if (date) { var elems = date.split(','); date = Y.Date.format(new Date(elems[0], elems[1], elems[2]), {format:"%x"}) } else { date = Y.Date.format(new Date(), {format:"%x"}) } Y.one('#searchdate').set('text', date); }; var mail_notification_message = function(message) { if (message) { Y.one('#mail_notification').addClass('mail_enabled').removeClass('mail_novisible'); Y.one('#mail_notification_message').setContent(message); Y.one('#mail_notification_undo').removeClass('mail_novisible'); } else { Y.one('#mail_notification').removeClass('mail_enabled').addClass('mail_novisible'); Y.one('#mail_notification_message').setContent(''); Y.one('#mail_notification_undo').addClass('mail_novisible'); } }; var mail_reset_date_selected = function() { date = new Date(); mail_date_selected = date.getFullYear() + ',' + date.getMonth() + ',' + date.getDate(); M.form.dateselector.calendar.deselectDates(date); }; /*** Event listeners***/ //Background selection Y.one("#region-main").delegate('click', function(e) { var ancestor = this.ancestor('.mail_item'); mail_toggle_checkbox(this); ancestor.toggleClass('mail_selected'); mail_main_checkbox(); mail_customize_menu_actions(this); }, '.mail_list .mail_adv_checkbox'); //Select all/none Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_checkbox(this); mail_hide_menu_options(); mail_hide_menu_labels(); if (mail_is_checkbox_checked(this)) { mail_select_all(); } else { mail_select_none(); } mail_check_selected(); mail_update_menu_actions(); }, '.mail_checkbox_all > .mail_adv_checkbox'); //Toggle menu select all/none Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_menu(); mail_hide_menu_actions(); mail_hide_menu_labels(); mail_hide_menu_search(); }, '.mail_checkbox_all'); //Checkbox hides other menus Y.one("#region-main").delegate('click', function(e) { mail_hide_menu_options(); mail_hide_menu_labels(); }, '.mail_checkbox_all > .mail_adv_checkbox'); //Toggle menu actions Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_menu_actions(); mail_hide_menu_options(); mail_hide_menu_labels(); mail_hide_menu_search(); }, '.mail_more_actions'); //Toggle menu actions Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_label_default_values(); mail_customize_menu_label(); mail_toggle_menu_labels(); mail_hide_menu_options(); mail_hide_menu_actions(); mail_hide_menu_search(); }, '.mail_assignlbl'); //Menu select all Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_all(); mail_update_menu_actions(); }, '.mail_menu_option_all'); //Menu select none Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_none(); }, '.mail_menu_option_none'); //Menu select read Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_read(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_read'); //Menu select unread Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_unread(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_unread'); //Menu select starred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_starred(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_starred'); //Menu select unstarred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_unstarred(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_unstarred'); Y.one("#region-main").delegate('click', function(e) { mail_check_selected(); }, '.mail_optselect'); Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); }, '.mail_labelselect'); //Menu action starred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('starred'); mail_update_menu_actions(); }, '.mail_menu_action_markasstarred'); //Menu action unstarred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('unstarred'); mail_update_menu_actions(); }, '.mail_menu_action_markasunstarred'); //Menu action markasread Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('markasread'); mail_update_menu_actions(); }, '.mail_menu_action_markasread'); //Menu action markasunread Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('markasunread'); mail_update_menu_actions(); }, '.mail_menu_action_markasunread'); //Menu action editlabel Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_label_edit(); }, '.mail_menu_action_editlabel'); //Menu action removelabel Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_label_confirm_delete(e); }, '.mail_menu_action_removelabel'); //Starred and unstarred Y.one('#region-main').delegate('click', function(e) { e.preventDefault(); mail_doaction('togglestarred', this); mail_update_menu_actions(); }, '.mail_flags a'); //Delete button Y.one("#region-main").delegate('click', function(e) { if (!this.hasClass('mail_button_disabled')) { mail_doaction('delete'); } }, '#mail_delete'); //Discard button Y.one("#region-main").delegate('click', function(e) { if (!this.hasClass('mail_button_disabled')) { mail_doaction('discard'); } }, '#mail_discard'); //Restore button Y.one("#region-main").delegate('click', function(e) { if (!this.hasClass('mail_button_disabled')) { mail_doaction('restore'); } }, '#mail_restore'); //Prev page button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('prevpage'); }, 'input[name="prevpage"]'); //Prev page button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('nextpage'); }, 'input[name="nextpage"]'); //Go back button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('goback'); }, '.mail_goback'); //Mail per page Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('perpage', this); }, 'div.mail_perpage a'); //Hide all menus Y.on('click', function(e) { mail_hide_menu_options(); mail_hide_menu_actions(); mail_hide_menu_labels(); mail_hide_menu_search(); }, 'body'); //Show message Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('viewmail', this); }, 'a.mail_link'); //Click apply changes on labels Y.one("#region-main").delegate('click', function(e) { mail_hide_menu_labels(); mail_doaction('assignlabels'); }, '.mail_menu_label_apply'); //Click new label Y.one("#region-main").delegate('click', function(e) { mail_hide_menu_labels(); mail_label_new(); }, '.mail_menu_label_newlabel'); //Click label on menu labels Y.one("#region-main").delegate('click', function(e) { mail_menu_label_selection(this); mail_customize_menu_label(); }, '.mail_menu_labels li'); //Click notification bar undo Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); var ancestor = Y.one('#mail_notification'); if (ancestor.hasClass('mail_enabled')) { ancestor.removeClass('mail_enabled').addClass('mail_novisible'); mail_doaction('undo'); } }, '#mail_notification_undo'); //Click cancel search button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doing_search = false; mail_hide_menu_search(); mail_doaction('goback'); mail_before_message_search = false; mail_after_message_search = false; mail_reset_date_selected(); }, '#buttoncancelsearch'); //Click search button Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); var date; mail_hide_menu_options(); mail_hide_menu_actions(); mail_hide_menu_labels(); mail_toggle_menu_search(); if (!mail_date_selected) { mail_reset_date_selected(); } mail_set_selected_date(mail_date_selected); }, '#mail_search'); //Click menu search Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); M.form.dateselector.panel.hide(); }, '#mail_menu_search'); //Click adv search Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_adv_search(); }, '#mail_toggle_adv_search'); //Click date search Y.one("#local_mail_main_form").delegate('click', function(e) { e.stopPropagation(); if(Y.one('#dateselector-calendar-panel').hasClass('yui3-overlay-hidden')) { M.form.dateselector.panel.show(); } else { M.form.dateselector.panel.hide(); } }, '.mail_search_date'); Y.on('contentready', function() { if (M.form.dateselector.calendar) { M.form.dateselector.calendar.on('dateClick', mail_get_selected_date); M.form.dateselector.calendar.set('maximumDate', new Date()); M.form.dateselector.panel.set('zIndex', 1); Y.one('#dateselector-calendar-panel').setStyle('border', 0); M.form.dateselector.calendar.render(); } }, '#dateselector-calendar-panel'); //Click on button search Y.one("#region-main").delegate('keydown', function(e) { e.stopPropagation(); if (e.keyCode == 13) { this.focus(); mail_do_search(); } }, '#textsearch, #textsearchfrom, #textsearchto'); //Click on button search Y.one("#region-main").delegate('click', function(e) { mail_do_search(); }, '#buttonsearch'); //Initialize init(); mail_update_url(); });
nitro2010/moodle
local/mail/mail.js
JavaScript
gpl-3.0
58,550
import { combineReducers } from 'redux'; import listAcceptors from './listAcceptors'; import me from './wxe-auth'; import acceptors from './acceptors'; import { doneForm, toastState } from './ceeRegistration/ceeRegistration'; import { reducer as formReducer } from 'redux-form'; import stat from './stat'; import cee from './cee'; import { FETCH_FAILED } from '../constants'; const error = (state = null, action) => { switch (action.type) { case FETCH_FAILED: return action.error; default: return null; } }; export default combineReducers({ doneForm, toastState, listAcceptors, me, acceptors, cee, form: formReducer, stat, error, });
nagucc/jkef-wxe
src/reducers/index.js
JavaScript
gpl-3.0
678
window.onload = function() { document.getElementById('smile').innerHTML = ":)"; };
nishant-jain-94/express-app
public/javascripts/main.js
JavaScript
gpl-3.0
85
import fs from 'fs' import path from 'path' const Jimp = require('jimp') const hjson = require('hjson') const electronImageResize = require('./electronImageResize') const {getPath1,getPath2} = require('./chromeExtensionUtil') const contentScriptName = '___contentScriptModify_.js' const backgroundScriptName = '___backgroundScriptModify_.js' const polyfillName = 'browser-polyfill.min.js' const webExtModifyBg = 'webextensionModifyBg.js' const webExtModifyCs = 'webextensionModifyCs.js' const webExtStyleName = 'webextension.css' const backgroundHtmlName = '___backgroundModify_.html' let backgroundHtmlStr = `<!DOCTYPE html> <head><meta charset="UTF-8"></head> <body> <script src="${backgroundScriptName}"></script> __REPLACE__ </body></html>` function findJsTags(obj,callback){ if(obj.js){ obj.js = callback(obj.js) } if(Array.isArray(obj)) { for(let ele of obj){ findJsTags(ele,callback) } } else if(obj instanceof Object){ for(let [key,ele] of Object.entries(obj)){ if(key != 'js') findJsTags(ele,callback) } } } function copyModifyFile(to,flagContent,flagBackground,isWebExt){ if(flagContent){ const cont = fs.readFileSync(path.join(__dirname,'../src/extension/contentScriptModify.js')).toString() const contPath = path.join(to,contentScriptName) if(fs.existsSync(contPath)) fs.unlinkSync(contPath) fs.writeFileSync(contPath,cont) } if(flagBackground){ const bg = fs.readFileSync(path.join(__dirname,'../src/extension/backgroundScriptModify.js')).toString() const bgPath = path.join(to,backgroundScriptName) if(fs.existsSync(bgPath)) fs.unlinkSync(bgPath) fs.writeFileSync(bgPath,bg) } if(isWebExt){ for(let file of [polyfillName,webExtModifyBg,webExtModifyCs,webExtStyleName]){ const poli = fs.readFileSync(path.join(__dirname,`../resource/${file}`)).toString() const poliPath = path.join(to,file) if(fs.existsSync(poliPath)) fs.unlinkSync(poliPath) fs.writeFileSync(poliPath,poli) } } } let cache = new Set() function htmlModify(verPath,fname,isWebExt){ const dirName = path.dirname(fname) const backStr = dirName == '.' ? dirName : dirName.split(/[\/\\]/).map(x=>'..').join('/') console.log(verPath,fname,dirName,backStr) const fullPath = path.join(verPath,dirName,path.basename(fname).split("?")[0]) if(cache.has(fullPath) || !fs.existsSync(fullPath)) return cache.add(fullPath) const str = fs.readFileSync(fullPath).toString() if(str.includes(backgroundScriptName)) return fs.unlinkSync(fullPath) let writeStr = str.replace(/< *(head)([^>]*)>/i,`<$1$2>\n ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n` : ''}<script src="${backStr}/${backgroundScriptName}"></script>`) if(!writeStr.includes(backgroundScriptName)){ writeStr = str.replace(/< *(body)([^>]*)>/i,`<$1$2>\n ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n` : ''}<script src="${backStr}/${backgroundScriptName}"></script>`) } if(!writeStr.includes(backgroundScriptName)){ writeStr = str.replace(/html>/i,`html>\n ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n<link rel="stylesheet" href="${backStr}/${webExtStyleName}">\n` : ''}\n<script src="${backStr}/${backgroundScriptName}"></script>`) } if(!writeStr.includes(backgroundScriptName)){ writeStr = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Background</title> ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n` : ''} <script src="${backStr}/${backgroundScriptName}"></script> ${writeStr} </head> <body> </body> </html>` } fs.writeFileSync(fullPath,writeStr) } function removeBom(x){ return x.charCodeAt(0) === 0xFEFF ? x.slice(1) : x } export default async function modify(extensionId,verPath){ const isWebExt = !extensionId.match(/(^[a-z]+$)|(_chrome_$)/) cache = new Set() if(!verPath){ verPath = getPath2(extensionId) || getPath1(extensionId) //getPath1(extensionId) } const manifestPath = path.join(verPath, 'manifest.json') const exists = fs.existsSync(manifestPath) if (exists) { const manifestStr = removeBom(fs.readFileSync(manifestPath).toString()).replace('\\u003Call_urls>','<all_urls>') const infos = hjson.parse(manifestStr) if(!infos.key || infos.key.match(/[\-\.]/)){ infos.key = new Buffer(extensionId).toString('base64') } if(infos.permissions && infos.permissions.includes('activeTab') && (!infos.permissions.includes('http://*/*') || !infos.permissions.includes('https://*/*'))){ infos.permissions = [...new Set([...infos.permissions,'http://*/*','https://*/*'])] } if(infos.optional_permissions){ infos.permissions = [...new Set([...(infos.permissions || []),...infos.optional_permissions])] } if(!infos.content_security_policy){ infos.content_security_policy = "script-src 'self' 'unsafe-eval'; object-src 'self'" } if(isWebExt && infos.permissions){ infos.permissions = infos.permissions.filter(x=>x!=='clipboardWrite' && x!=='clipboardRead') const ind = infos.permissions.findIndex(x=>x=='menus') if(ind != -1) infos.permissions[ind] = 'contextMenus' } let flagContent,flagBackground if(infos.content_scripts){ findJsTags(infos.content_scripts,js=>{ if(!Array.isArray(js)) js = [js] if(isWebExt && !js.includes(polyfillName)){ js.unshift(webExtModifyCs) js.unshift(polyfillName) } if(!js.includes(contentScriptName)) js.unshift(contentScriptName) return js }) flagContent = true } let open const imageResize = new electronImageResize() try{ if(infos.background){ if(infos.background.persistent === false && !['jpkfjicglakibpenojifdiepckckakgk','occjjkgifpmdgodlplnacmkejpdionan'].includes(extensionId)){ infos.background.persistent = true } if(infos.background.page){ htmlModify(verPath,infos.background.page,isWebExt) } else if(infos.background.scripts){ if(!Array.isArray(infos.background.scripts)) infos.background.scripts = [infos.background.scripts] if(isWebExt) backgroundHtmlStr = backgroundHtmlStr.replace('<body>',`<body>\n<script src="${polyfillName}"></script>\n<script src="${webExtModifyBg}"></script>`) const content = backgroundHtmlStr.replace('__REPLACE__',infos.background.scripts.map(src=>`<script src="${src}"></script>`).join("\n ")) fs.writeFileSync(path.join(verPath,backgroundHtmlName),content) infos.background.page = backgroundHtmlName delete infos.background.scripts } flagBackground = true } if(infos.options_page){ htmlModify(verPath,infos.options_page,isWebExt) flagBackground = true } if(infos.options_ui && infos.options_ui.page){ if(!infos.options_page) infos.options_page = infos.options_ui.page htmlModify(verPath,infos.options_ui.page,isWebExt) flagBackground = true } if(infos.page_action && infos.page_action.default_popup){ htmlModify(verPath,infos.page_action.default_popup,isWebExt) flagBackground = true } if(infos.browser_action && infos.browser_action.default_popup){ htmlModify(verPath,infos.browser_action.default_popup,isWebExt) flagBackground = true } if(infos.web_accessible_resources){ for(let file of infos.web_accessible_resources){ if(file.match(/\.html?$/)){ htmlModify(verPath,file,isWebExt) flagBackground = true } } } if(infos.chrome_url_overrides){ for(let file of Object.values(infos.chrome_url_overrides)){ htmlModify(verPath,file,isWebExt) flagBackground = true } } if(infos.page_action){ if(!infos.browser_action){ infos.browser_action = infos.page_action if(infos.browser_action.show){ infos.browser_action.enable = infos.browser_action.show delete infos.browser_action.show } if(infos.browser_action.hide){ infos.browser_action.disable = infos.browser_action.hide delete infos.browser_action.hide } } delete infos.page_action } for(let file of require("glob").sync(`${verPath}/**/*.html`)){ console.log(222444,verPath,file.replace(`${verPath}/`,''),isWebExt) htmlModify(verPath,file.replace(`${verPath.replace(/\\/g,'/')}/`,''),isWebExt) } for(let file of require("glob").sync(`${verPath}/**/*.js`)){ let datas = fs.readFileSync(file).toString(),needWrite = false if (isWebExt && datas.includes('moz-extension')) { // console.log(file) datas = datas.replace(/moz\-extension/ig,'chrome-extension') needWrite = true } if(extensionId == 'mlomiejdfkolichcflejclcbmpeaniij' && datas.includes('about:blank')){ datas = datas.replace(/about:blank/ig,'chrome-extension://dckpbojndfoinamcdamhkjhnjnmjkfjd/blank.html') needWrite = true } if(needWrite){ fs.writeFileSync(file, datas) } } if(infos.commands){ for(let [k,v] of Object.entries(infos.commands)) { if(v.suggested_key){ for(let [k2,v2] of Object.entries(v.suggested_key)){ if(v2.match(/^F\d+$/)){ delete infos.commands[k] break } } } if (k == '_execute_browser_action' || k == '_execute_page_action') continue if (!v.description) v.description = "description" } } copyModifyFile(verPath,flagContent,flagBackground,isWebExt) fs.unlinkSync(manifestPath) fs.writeFileSync(manifestPath,JSON.stringify(infos, null, ' ')) console.log(33332001) for(let svg of require("glob").sync(`${verPath}/**/*.svg`)){ const out = svg.replace(/\.svg$/,".png") if(!fs.existsSync(out)){ if(!open){ imageResize.open({width: 16, height: 16}) open = true } console.log(`file://${svg}`) const url = path.join(path.parse(svg).dir,'svg.html') fs.writeFileSync(url,`<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style type="text/css"> img,svg{ width: 100%; height: 100%; } </style> </head> <body> <img src="${svg}"/> </body> </html>`) const img = await imageResize.capture({url: `file://${url}`, width: 16, height: 16}) Jimp.read(img.toPNG(), function (err, image) { if(image.bitmap.width > image.bitmap.height){ image = image.resize(16,Jimp.AUTO,Jimp.RESIZE_BICUBIC) } else{ image = image.resize(Jimp.AUTO,16,Jimp.RESIZE_BICUBIC) } image.write(out) }) } } if(open) imageResize.close() }catch(e){ if(open) imageResize.close() console.log(33332002,e) } // if(isWebExt){ // for(let js of require("glob").sync(`${verPath}/**/*.js`)){ // const datas = fs.readFileSync(js).toString() // if(datas.match(/document.execCommand\( *(["'])copy\1 *\)/)){ // const result = datas.replace(/document.execCommand\( *(["'])copy\1 *\)/,`chrome.ipcRenderer.send('execCommand-copy')`) // fs.writeFileSync(js, result) // } // } // } } }
kura52/sushi-browser
src/chromeManifestModify.js
JavaScript
gpl-3.0
11,818
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colorbutton', 'hr', { auto: 'Automatski', bgColorTitle: 'Boja pozadine', colors: { '000': 'Crna', '800000': 'Kesten', '8B4513': 'Smeđa', '2F4F4F': 'Tamno siva', '008080': 'Teal', '000080': 'Mornarska', '4B0082': 'Indigo', '696969': 'Tamno siva', B22222: 'Vatrena cigla', A52A2A: 'Smeđa', DAA520: 'Zlatna', '006400': 'Tamno zelena', '40E0D0': 'Tirkizna', '0000CD': 'Srednje plava', '800080': 'Ljubičasta', '808080': 'Siva', F00: 'Crvena', FF8C00: 'Tamno naranđasta', FFD700: 'Zlatna', '008000': 'Zelena', '0FF': 'Cijan', '00F': 'Plava', EE82EE: 'Ljubičasta', A9A9A9: 'Mutno siva', FFA07A: 'Svijetli losos', FFA500: 'Naranđasto', FFFF00: 'Žuto', '00FF00': 'Limun', AFEEEE: 'Blijedo tirkizna', ADD8E6: 'Svijetlo plava', DDA0DD: 'Šljiva', D3D3D3: 'Svijetlo siva', FFF0F5: 'Lavanda rumeno', FAEBD7: 'Antikno bijela', FFFFE0: 'Svijetlo žuta', F0FFF0: 'Med', F0FFFF: 'Azurna', F0F8FF: 'Alice plava', E6E6FA: 'Lavanda', FFF: 'Bijela', '1ABC9C': 'Jaka cijan', '2ECC71': 'Emerald', '3498DB': 'Svijetlo plava', '9B59B6': 'Ametist', '4E5F70': 'Sivkasto plava', 'F1C40F': 'Žarka žuta', '16A085': 'Tamna cijan', '27AE60': 'Tamna emerald', '2980B9': 'Jaka plava', '8E44AD': 'Tamno ljubičasta', '2C3E50': 'Desatuirarana plava', 'F39C12': 'Narančasta', 'E67E22': 'Mrkva', 'E74C3C': 'Blijedo crvena', 'ECF0F1': 'Sjana srebrna', '95A5A6': 'Svijetlo sivkasta cijan', 'DDD': 'Svijetlo siva', 'D35400': 'Tikva', 'C0392B': 'Jaka crvena', 'BDC3C7': 'Srebrna', '7F8C8D': 'Sivkasto cijan', '999': 'Tamno siva' }, more: 'Više boja...', panelTitle: 'Boje', textColorTitle: 'Boja teksta' } );
sgsinclair/Voyant
src/main/webapp/resources/ckeditor/ckeditor4.15.0/plugins/colorbutton/lang/hr.js
JavaScript
gpl-3.0
1,902
//============================================================================== // // File drop zone view // //============================================================================== (function(app, config, $) { app.FileDropZoneView = Marionette.ItemView.extend({ events : { 'drop' : 'handleDrop' }, initialize : function() { _.bindAll(this, 'enableEffect', 'disableEffect'); }, delegateEvents : function() { // Check browser compatibility if(!(window.File && window.FileList && window.FileReader)) { return; } Marionette.ItemView.prototype.delegateEvents.apply(this, arguments); this.el.addEventListener('dragover', this.enableEffect, false); this.el.addEventListener('dragleave', this.disableEffect, false); }, undelegateEvents : function() { // Check browser compatibility if(!(window.File && window.FileList && window.FileReader)) { return; } this.el.removeEventListener('dragover', this.enableEffect, false); this.el.removeEventListener('dragleave', this.disableEffect, false); Marionette.ItemView.prototype.undelegateEvents.apply(this, arguments); }, enableEffect : function(e) { e.preventDefault(); e.stopPropagation(); if(!this._isFileTransfer(e)) return; if(this.disableTimer) clearTimeout(this.disableTimer); this.$el.addClass('active'); }, disableEffect : function(e) { if(this.disableTimer) clearTimeout(this.disableTimer); var _this = this; this.disableTimer = setTimeout(function() { _this.$el.removeClass('active'); }, 100); }, handleDrop : function(e) { e.preventDefault(); e.stopPropagation(); this.disableEffect(); var files = e.originalEvent.dataTransfer.files || e.originalEvent.target.files; if(files && files.length > 0) { this.trigger('drop', files); } }, _isFileTransfer : function(e) { if(e.dataTransfer.types) { for(var i = 0; i < e.dataTransfer.types.length; i++) { if(e.dataTransfer.types[i] === 'Files') return true; } return false; } return true; } }); })(window.Application, window.chatConfig, jQuery);
johnnyswp/promin
chat/js/app/view/FileDropZoneView.js
JavaScript
gpl-3.0
2,758
"use strict"; const logger = require('../logwrapper'); const eventManager = require("../events/EventManager"); const NodeCache = require("node-cache"); const cache = new NodeCache({ stdTTL: 0, checkperiod: 5 }); exports._cache = cache; cache.on("expired", function(key, value) { eventManager.triggerEvent("firebot", "custom-variable-expired", { username: "Firebot", expiredCustomVariableName: key, expiredCustomVariableData: value }); }); cache.on("set", function(key, value) { eventManager.triggerEvent("firebot", "custom-variable-set", { username: "Firebot", createdCustomVariableName: key, createdCustomVariableData: value }); }); function getVariableCacheDb() { const profileManager = require("../common/profile-manager"); return profileManager .getJsonDbInProfile("custom-variable-cache"); } exports.persistVariablesToFile = () => { const db = getVariableCacheDb(); db.push("/", cache.data); }; exports.loadVariablesFromFile = () => { const db = getVariableCacheDb(); const data = db.getData("/"); if (data) { for (const [key, {t, v}] of Object.entries(data)) { const now = Date.now(); if (t && t > 0 && t < now) { // this var has expired continue; } const ttl = t === 0 ? 0 : (t - now) / 1000; cache.set(key, v, ttl); } } }; exports.addCustomVariable = (name, data, ttl = 0, propertyPath = null) => { //attempt to parse data as json try { data = JSON.parse(data); } catch (error) { //silently fail } let dataRaw = data != null ? data.toString().toLowerCase() : "null"; let dataIsNull = dataRaw === "null" || dataRaw === "undefined"; let currentData = cache.get(name); if (propertyPath == null || propertyPath.length < 1) { let dataToSet = dataIsNull ? undefined : data; if (currentData && Array.isArray(currentData) && !Array.isArray(data) && !dataIsNull) { currentData.push(data); dataToSet = currentData; } cache.set(name, dataToSet, ttl === "" ? 0 : ttl); } else { let currentData = cache.get(name); if (!currentData) return; try { let cursor = currentData; let pathNodes = propertyPath.split("."); for (let i = 0; i < pathNodes.length; i++) { let node = pathNodes[i]; // parse to int for array access if (!isNaN(node)) { node = parseInt(node); } let isLastItem = i === pathNodes.length - 1; if (isLastItem) { // if data recognized as null and cursor is an array, remove index instead of setting value if (dataIsNull && Array.isArray(cursor) && !isNaN(node)) { cursor.splice(node, 1); } else { //if next node is an array and we detect we are not setting a new array or removing array, then push data to array if (Array.isArray(cursor[node]) && !Array.isArray(data) && !dataIsNull) { cursor[node].push(data); } else { cursor[node] = dataIsNull ? undefined : data; } } } else { cursor = cursor[node]; } } cache.set(name, currentData, ttl === "" ? 0 : ttl); } catch (error) { logger.debug(`error setting data to custom variable ${name} using property path ${propertyPath}`); } } }; exports.getCustomVariable = (name, propertyPath, defaultData = null) => { let data = cache.get(name); if (data == null) { return defaultData; } if (propertyPath == null) { return data; } try { let pathNodes = propertyPath.split("."); for (let i = 0; i < pathNodes.length; i++) { if (data == null) break; let node = pathNodes[i]; // parse to int for array access if (!isNaN(node)) { node = parseInt(node); } data = data[node]; } return data != null ? data : defaultData; } catch (error) { logger.debug(`error getting data from custom variable ${name} using property path ${propertyPath}`); return defaultData; } };
Firebottle/Firebot
backend/common/custom-variable-manager.js
JavaScript
gpl-3.0
4,564
"use strict"; var uuid = require('node-uuid'); var crypto = require('crypto'); var NodeGeocoder = require('node-geocoder'); var secret = "I@Love@NNNode.JS"; var options = { provider: 'google', httpAdapter: 'https', apiKey: 'AIzaSyBF9xb6TLxfTEji1O4UqL7rwZc16fQRctA', formatter: null }; var Util = function () { return { GenerateAuthToken: function () { return uuid.v4(); }, Encrypt: function (strToEncrypt) { return crypto.createHmac('sha256', secret) .update(strToEncrypt) .digest('hex'); }, getLatLon: function (address, callback) { var geocoder = NodeGeocoder(options); geocoder.geocode(address, function(err, res) { if (err) { callback(err.message, null) } else { callback(null, {"lat": res[0].latitude, "lon": res[0].longitude}); } }); } }; }(); module.exports = Util;
oczane/geochat
util.js
JavaScript
gpl-3.0
1,071
var searchData= [ ['haier_443',['haier',['../classIRac.html#ae0a29a4cb8c7a4707a7725c576822a58',1,'IRac']]], ['haier_5fac_444',['HAIER_AC',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada1f232bcdf330ec2e353196941b9f1628',1,'IRremoteESP8266.h']]], ['haier_5fac_5fyrw02_445',['HAIER_AC_YRW02',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fadaacda5821835865551f6df46c76282fa4',1,'IRremoteESP8266.h']]], ['haierprotocol_446',['HaierProtocol',['../unionHaierProtocol.html',1,'']]], ['haieryrw02protocol_447',['HaierYRW02Protocol',['../unionHaierYRW02Protocol.html',1,'']]], ['haieryrwo2_448',['haierYrwo2',['../classIRac.html#a7bc779a162dd9a1b4c925febec443353',1,'IRac']]], ['handlespecialstate_449',['handleSpecialState',['../classIRCoolixAC.html#af78090c6d8b45b4202a80f1223640390',1,'IRCoolixAC::handleSpecialState()'],['../classIRTranscoldAc.html#a01a3e3f8f92b8fb3b6d023e595f3ce17',1,'IRTranscoldAc::handleSpecialState()']]], ['handletoggles_450',['handleToggles',['../classIRac.html#a36833999dce4ad608a5a0f084988cfd1',1,'IRac']]], ['hasacstate_451',['hasACState',['../IRutils_8cpp.html#a6efd4986db60709d3501606ec7ab5382',1,'hasACState(const decode_type_t protocol):&#160;IRutils.cpp'],['../IRutils_8h.html#a6efd4986db60709d3501606ec7ab5382',1,'hasACState(const decode_type_t protocol):&#160;IRutils.cpp']]], ['hasinvertedstates_452',['hasInvertedStates',['../classIRHitachiAc3.html#ac06b36245c85480d97c1a9f49cfaa005',1,'IRHitachiAc3']]], ['hasstatechanged_453',['hasStateChanged',['../classIRac.html#a35258c35a2d2b19886292b22b2aa053a',1,'IRac']]], ['header0_454',['Header0',['../structCoronaSection.html#a3b3c0a1a42da65bb4b481e59b42f26a6',1,'CoronaSection']]], ['header1_455',['Header1',['../structCoronaSection.html#a3d6d6c1e31f82a76cd88f81bcdb83a3a',1,'CoronaSection']]], ['health_456',['Health',['../unionHaierProtocol.html#a4cf70c633e33066e3fc0f98bb2ad3820',1,'HaierProtocol::Health()'],['../unionHaierYRW02Protocol.html#a7fa39803fd72a788736bb8f00acfa76f',1,'HaierYRW02Protocol::Health()']]], ['heat_5fmode_457',['heat_mode',['../classIRArgoAC.html#a255762f71502b9ffeb0686759991ec53',1,'IRArgoAC']]], ['hitachi_458',['hitachi',['../classIRac.html#acd0f2fcf03aabf947a19a195000add3c',1,'IRac']]], ['hitachi1_459',['hitachi1',['../classIRac.html#ac8807d62f6ae87af72d44b50bed3f17b',1,'IRac']]], ['hitachi344_460',['hitachi344',['../classIRac.html#a0bc34635a1a349816344916a82585460',1,'IRac']]], ['hitachi424_461',['hitachi424',['../classIRac.html#aec6de0752ddd3a3e7c6824cb1b692508',1,'IRac']]], ['hitachi_5fac_462',['HITACHI_AC',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada9020fb54ac69d8aec0185f7e80c962ca',1,'IRremoteESP8266.h']]], ['hitachi_5fac1_463',['HITACHI_AC1',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada7d9a74161d95e62bece3c0e48900cb35',1,'IRremoteESP8266.h']]], ['hitachi_5fac1_5fremote_5fmodel_5ft_464',['hitachi_ac1_remote_model_t',['../IRsend_8h.html#acd0c6107b5a6cab2080b18a8de14ea49',1,'IRsend.h']]], ['hitachi_5fac2_465',['HITACHI_AC2',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fadab5a44068d519506efa8a3113aa44c9c0',1,'IRremoteESP8266.h']]], ['hitachi_5fac3_466',['HITACHI_AC3',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fadac3487c47b14da6af922f5b27992b30f3',1,'IRremoteESP8266.h']]], ['hitachi_5fac344_467',['HITACHI_AC344',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada1e147eb39adc40e4181940cc2357f070',1,'IRremoteESP8266.h']]], ['hitachi_5fac424_468',['HITACHI_AC424',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada85af068f8964d4359512265d8cc27a31',1,'IRremoteESP8266.h']]], ['htmlescape_469',['htmlEscape',['../namespaceirutils.html#a6e55c6fdcc82e1ef8bd5f73df83609a7',1,'irutils']]] ];
don-willingham/Sonoff-Tasmota
lib/IRremoteESP8266-2.7.11/docs/doxygen/html/search/all_8.js
JavaScript
gpl-3.0
3,792
var util = require( '../../utils/util.js' ) Page( { data: { projects: [ { name: 'FinalScheduler(终极排班系统)', git: "https://github.com/giscafer/FinalScheduler" }, { name: 'MoveSite(电影狙击手)', git: "https://github.com/giscafer/moviesite" }, { name: 'Ponitor(价格监控)', git: "https://github.com/giscafer/Ponitor" }, { name: 'hexo-theme-cafe(Hexo博客主题)', git: "https://github.com/giscafer/hexo-theme-cafe" }, { name: 'ife-course-demo(百度前端学院)', git: "https://github.com/giscafer/ife-course-demo" } ] }, onReady: function() { this.clickName(); }, clickName: function( e ) { var pros = this.data.projects; console.log( "#########################################################################################################" ) console.log( "## 其他项目 ##" ) console.log( "##-----------------------------------------------------------------------------------------------------##" ) pros.forEach( function( item, index ) { console.log( "## ", item.name + ":" + item.git ) }) console.log( "## ##" ) console.log( "#########################################################################################################" ) } })
gouyuwang/private
wxapp/map/pages/logs/logs.js
JavaScript
gpl-3.0
1,470
/*! fabrik */ var FbListArticle=new Class({Extends:FbListPlugin});
robho/fabrik
plugins/fabrik_list/article/article-min.js
JavaScript
gpl-3.0
66
/* * This file is part of ARSnova Mobile. * Copyright (C) 2011-2012 Christian Thomas Weber * Copyright (C) 2012-2015 The ARSnova Team * * ARSnova Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ARSnova Mobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ARSnova Mobile. If not, see <http://www.gnu.org/licenses/>. */ Ext.define('ARSnova.view.speaker.NewQuestionPanel', { extend: 'Ext.Panel', requires: [ 'ARSnova.view.speaker.form.AbstentionForm', 'ARSnova.view.speaker.form.ExpandingAnswerForm', 'ARSnova.view.speaker.form.IndexedExpandingAnswerForm', 'ARSnova.view.speaker.form.FlashcardQuestion', 'ARSnova.view.speaker.form.SchoolQuestion', 'ARSnova.view.speaker.form.VoteQuestion', 'ARSnova.view.speaker.form.YesNoQuestion', 'ARSnova.view.speaker.form.NullQuestion', 'ARSnova.view.speaker.form.GridQuestion', 'ARSnova.view.speaker.form.FreeTextQuestion', 'ARSnova.view.speaker.form.ImageUploadPanel', 'ARSnova.view.MarkDownEditorPanel' ], config: { title: 'NewQuestionPanel', fullscreen: true, scrollable: true, scroll: 'vertical', variant: 'lecture', releasedFor: 'all' }, /* toolbar items */ toolbar: null, backButton: null, saveButton: null, /* items */ text: null, subject: null, duration: null, image: null, /* for estudy */ userCourses: [], initialize: function () { this.callParent(arguments); var screenWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width; this.backButton = Ext.create('Ext.Button', { text: Messages.QUESTIONS, ui: 'back', handler: function () { var sTP = ARSnova.app.mainTabPanel.tabPanel.speakerTabPanel; sTP.animateActiveItem(sTP.audienceQuestionPanel, { type: 'slide', direction: 'right', duration: 700 }); } }); this.saveButtonToolbar = Ext.create('Ext.Button', { text: Messages.SAVE, ui: 'confirm', cls: 'saveQuestionButton', style: 'width: 89px', handler: function (button) { this.saveHandler(button).then(function (response) { ARSnova.app.getController('Questions').details({ question: Ext.decode(response.responseText) }); }); }, scope: this }); this.subject = Ext.create('Ext.field.Text', { name: 'subject', placeHolder: Messages.CATEGORY_PLACEHOLDER }); this.textarea = Ext.create('Ext.plugins.ResizableTextArea', { name: 'text', placeHolder: Messages.FORMAT_PLACEHOLDER }); this.markdownEditPanel = Ext.create('ARSnova.view.MarkDownEditorPanel', { processElement: this.textarea }); // Preview button this.previewButton = Ext.create('Ext.Button', { text: Ext.os.is.Desktop ? Messages.QUESTION_PREVIEW_BUTTON_TITLE_DESKTOP : Messages.QUESTION_PREVIEW_BUTTON_TITLE, ui: 'action', cls: Ext.os.is.Desktop ? 'previewButtonLong' : 'previewButton', scope: this, handler: function () { this.defaultPreviewHandler(); } }); // Preview panel with integrated button this.previewPart = Ext.create('Ext.form.FormPanel', { cls: 'newQuestion', scrollable: null, hidden: true, items: [{ xtype: 'fieldset', items: [this.previewButton] }] }); this.mainPart = Ext.create('Ext.form.FormPanel', { cls: 'newQuestion', scrollable: null, items: [{ xtype: 'fieldset', items: [this.subject] }, { xtype: 'fieldset', items: [this.markdownEditPanel, this.textarea] }] }); this.abstentionPart = Ext.create('ARSnova.view.speaker.form.AbstentionForm', { id: 'abstentionPart' }); this.uploadView = Ext.create('ARSnova.view.speaker.form.ImageUploadPanel', { handlerScope: this, addRemoveButton: true, activateTemplates: false, urlUploadHandler: this.setImage, fsUploadHandler: this.setImage }); this.grid = Ext.create('ARSnova.view.components.GridImageContainer', { editable: false, gridIsHidden: true, hidden: true, style: "padding-top: 10px; margin-top: 30px" }); this.releasePart = Ext.create('Ext.Panel', { items: [ { cls: 'gravure', html: '<span class="coursemembersonlyicon"></span><span class="coursemembersonlymessage">' + Messages.MEMBERS_ONLY + '</span>' } ], hidden: true }); this.yesNoQuestion = Ext.create('ARSnova.view.speaker.form.YesNoQuestion', { hidden: true }); this.multipleChoiceQuestion = Ext.create('ARSnova.view.speaker.form.ExpandingAnswerForm', { hidden: true }); this.voteQuestion = Ext.create('ARSnova.view.speaker.form.VoteQuestion', { hidden: true }); this.schoolQuestion = Ext.create('ARSnova.view.speaker.form.SchoolQuestion', { hidden: true }); this.abcdQuestion = Ext.create('ARSnova.view.speaker.form.IndexedExpandingAnswerForm', { hidden: true }); this.freetextQuestion = Ext.create('ARSnova.view.speaker.form.FreeTextQuestion', { hidden: true }); var messageAppendix = screenWidth >= 650 ? "_LONG" : ""; var formatItems = [ {text: Messages["MC" + messageAppendix], itemId: Messages.MC}, {text: Messages["ABCD" + messageAppendix], itemId: Messages.ABCD}, {text: Messages["YESNO" + messageAppendix], itemId: Messages.YESNO}, {text: Messages["FREETEXT" + messageAppendix], itemId: Messages.FREETEXT}, {text: Messages["EVALUATION" + messageAppendix], itemId: Messages.EVALUATION}, {text: Messages["SCHOOL" + messageAppendix], itemId: Messages.SCHOOL} ]; var me = this; var config = ARSnova.app.globalConfig; if (config.features.flashcard) { formatItems.push({ itemId: Messages.FLASHCARD, text: messageAppendix.length ? Messages.FLASHCARD : Messages.FLASHCARD_SHORT }); me.flashcardQuestion = Ext.create('ARSnova.view.speaker.form.FlashcardQuestion', { editPanel: false, hidden: true }); } if (config.features.gridSquare) { formatItems.push({ itemId: Messages.GRID, text: Messages["GRID" + messageAppendix] }); me.gridQuestion = Ext.create('ARSnova.view.speaker.form.GridQuestion', { id: 'grid', hidden: true }); } me.questionOptions = Ext.create('Ext.SegmentedButton', { allowDepress: false, items: formatItems, defaults: { ui: 'action' }, listeners: { scope: me, toggle: function (container, button, pressed) { var label = Ext.bind(function (longv, shortv) { var screenWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width; return (screenWidth >= 490 || me.backButton.isHidden()) ? longv : shortv; }, me); var title = ''; me.previewPart.hide(); me.previewButton.setHandler(this.defaultPreviewHandler); switch (button.getText()) { case Messages.GRID: case Messages.GRID_LONG: if (pressed) { me.gridQuestion.show(); me.previewButton.setHandler(me.gridQuestion.previewHandler); title = label(Messages.QUESTION_GRID, Messages.QUESTION_GRID_SHORT); this.previewPart.show(); this.uploadView.hide(); this.grid.hide(); } else { me.gridQuestion.hide(); this.uploadView.show(); if (this.grid.getImageFile()) { this.grid.show(); } } break; case Messages.EVALUATION: case Messages.EVALUATION_LONG: if (pressed) { me.voteQuestion.show(); title = label(Messages.QUESTION_RATING, Messages.QUESTION_RATING_SHORT); } else { me.voteQuestion.hide(); } break; case Messages.SCHOOL: case Messages.SCHOOL_LONG: if (pressed) { me.schoolQuestion.show(); title = label(Messages.QUESTION_GRADE, Messages.QUESTION_GRADE_SHORT); } else { me.schoolQuestion.hide(); } break; case Messages.MC: case Messages.MC_LONG: if (pressed) { me.multipleChoiceQuestion.show(); title = label(Messages.QUESTION_MC, Messages.QUESTION_MC_SHORT); } else { me.multipleChoiceQuestion.hide(); } break; case Messages.YESNO: case Messages.YESNO_LONG: if (pressed) { me.previewPart.show(); me.yesNoQuestion.show(); me.previewButton.setHandler(me.yesNoQuestion.previewHandler); title = label(Messages.QUESTION_YESNO, Messages.QUESTION_YESNO_SHORT); } else { me.yesNoQuestion.hide(); } break; case Messages.ABCD: case Messages.ABCD_LONG: if (pressed) { me.abcdQuestion.show(); title = label(Messages.QUESTION_SINGLE_CHOICE, Messages.QUESTION_SINGLE_CHOICE_SHORT); } else { me.abcdQuestion.hide(); } break; case Messages.FREETEXT: case Messages.FREETEXT_LONG: if (pressed) { me.previewPart.show(); me.freetextQuestion.show(); title = label(Messages.QUESTION_FREETEXT, Messages.QUESTION_FREETEXT_SHORT); } else { me.freetextQuestion.hide(); } break; case Messages.FLASHCARD: case Messages.FLASHCARD_SHORT: if (pressed) { me.textarea.setPlaceHolder(Messages.FLASHCARD_FRONT_PAGE); me.flashcardQuestion.show(); me.abstentionPart.hide(); title = Messages.FLASHCARD; me.uploadView.setUploadPanelConfig( Messages.PICTURE_SOURCE + " - " + Messages.FLASHCARD_BACK_PAGE, me.setFcImage, me.setFcImage ); } else { me.textarea.setPlaceHolder(Messages.FORMAT_PLACEHOLDER); me.flashcardQuestion.hide(); me.abstentionPart.show(); me.uploadView.setUploadPanelConfig( Messages.PICTURE_SOURCE, me.setImage, me.setImage ); } break; default: title = Messages.NEW_QUESTION_TITLE; break; } me.toolbar.setTitle(title); } } }); me.toolbar = Ext.create('Ext.Toolbar', { title: Messages.NEW_QUESTION_TITLE, cls: 'speakerTitleText', docked: 'top', ui: 'light', items: [ me.backButton, {xtype: 'spacer'}, me.saveButtonToolbar ] }); me.saveAndContinueButton = Ext.create('Ext.Button', { ui: 'confirm', cls: 'saveQuestionButton', text: Messages.SAVE_AND_CONTINUE, style: 'margin-top: 70px', handler: function (button) { me.saveHandler(button).then(function () { var theNotificationBox = {}; theNotificationBox = Ext.create('Ext.Panel', { cls: 'notificationBox', name: 'notificationBox', showAnimation: 'pop', modal: true, centered: true, width: 300, styleHtmlContent: true, styleHtmlCls: 'notificationBoxText', html: Messages.QUESTION_SAVED }); Ext.Viewport.add(theNotificationBox); theNotificationBox.show(); /* Workaround for Chrome 34+ */ Ext.defer(function () { theNotificationBox.destroy(); }, 3000); }).then(Ext.bind(function (response) { me.getScrollable().getScroller().scrollTo(0, 0, true); }, me)); }, scope: me }); me.add([me.toolbar, Ext.create('Ext.Toolbar', { cls: 'noBackground noBorder', docked: 'top', scrollable: { direction: 'horizontal', directionLock: true }, items: [{ xtype: 'spacer' }, me.questionOptions, { xtype: 'spacer' } ] }), me.mainPart, me.previewPart, /* only one of the question types will be shown at the same time */ me.voteQuestion, me.multipleChoiceQuestion, me.yesNoQuestion, me.schoolQuestion, me.abcdQuestion, me.freetextQuestion ]); if (me.flashcardQuestion) { me.add(me.flashcardQuestion); } me.add([ me.abstentionPart, me.uploadView, me.grid ]); if (me.gridQuestion) { me.add(me.gridQuestion); } me.add([ me.releasePart, me.saveAndContinueButton ]); me.on('activate', me.onActivate); }, onActivate: function () { this.questionOptions.setPressedButtons([0]); this.releasePart.setHidden(localStorage.getItem('courseId') === null || localStorage.getItem('courseId').length === 0); }, defaultPreviewHandler: function () { var questionPreview = Ext.create('ARSnova.view.QuestionPreviewBox'); questionPreview.showPreview(this.subject.getValue(), this.textarea.getValue()); }, saveHandler: function (button) { /* disable save button in order to avoid multiple question creation */ button.disable(); var panel = ARSnova.app.mainTabPanel.tabPanel.speakerTabPanel.newQuestionPanel; var values = {}; /* get text, subject of question from mainPart */ var mainPartValues = panel.mainPart.getValues(); values.text = mainPartValues.text; values.subject = mainPartValues.subject; values.abstention = !panel.abstentionPart.isHidden() && panel.abstentionPart.getAbstention(); values.questionVariant = panel.getVariant(); values.image = this.image; values.flashcardImage = null; values.imageQuestion = false; if (localStorage.getItem('courseId') != null && localStorage.getItem('courseId').length > 0) { values.releasedFor = 'courses'; } else { values.releasedFor = panel.getReleasedFor(); } /* fetch the values */ switch (panel.questionOptions.getPressedButtons()[0]._text) { case Messages.GRID: case Messages.GRID_LONG: values.questionType = "grid"; Ext.apply(values, panel.gridQuestion.getQuestionValues()); break; case Messages.EVALUATION: case Messages.EVALUATION_LONG: values.questionType = "vote"; Ext.apply(values, panel.voteQuestion.getQuestionValues()); break; case Messages.SCHOOL: case Messages.SCHOOL_LONG: values.questionType = "school"; Ext.apply(values, panel.schoolQuestion.getQuestionValues()); break; case Messages.MC: case Messages.MC_LONG: values.questionType = "mc"; Ext.apply(values, panel.multipleChoiceQuestion.getQuestionValues()); break; case Messages.YESNO: case Messages.YESNO_LONG: values.questionType = "yesno"; Ext.apply(values, panel.yesNoQuestion.getQuestionValues()); break; case Messages.ABCD: case Messages.ABCD_LONG: values.questionType = "abcd"; Ext.apply(values, panel.abcdQuestion.getQuestionValues()); break; case Messages.FREETEXT: case Messages.FREETEXT_LONG: values.questionType = "freetext"; values.possibleAnswers = []; Ext.apply(values, panel.freetextQuestion.getQuestionValues()); break; case Messages.FLASHCARD: case Messages.FLASHCARD_SHORT: values.questionType = "flashcard"; values.flashcardImage = this.fcImage; Ext.apply(values, panel.flashcardQuestion.getQuestionValues()); break; default: break; } var promise = panel.dispatch(values, button); promise.then(function () { panel.subject.reset(); panel.textarea.reset(); if (panel.flashcardQuestion) { panel.flashcardQuestion.answer.reset(); panel.flashcardQuestion.uploadView.resetButtons(); panel.setFcImage(null); } panel.multipleChoiceQuestion.resetFields(); panel.abcdQuestion.resetFields(); switch (panel.questionOptions.getPressedButtons()[0]._text) { case Messages.GRID: case Messages.GRID_LONG: panel.gridQuestion.resetView(); /* fall through */ default: panel.setImage(null); panel.uploadView.resetButtons(); panel.uploadView.setUploadPanelConfig( Messages.PICTURE_SOURCE, panel.setImage, panel.setImage ); break; } // animated scrolling to top panel.getScrollable().getScroller().scrollTo(0, 0, true); }); return promise; }, dispatch: function (values, button) { var promise = new RSVP.Promise(); ARSnova.app.getController('Questions').add({ sessionKeyword: sessionStorage.getItem('keyword'), text: values.text, subject: values.subject, type: "skill_question", questionType: values.questionType, questionVariant: values.questionVariant, duration: values.duration, number: 0, // unused active: 1, possibleAnswers: values.possibleAnswers, releasedFor: values.releasedFor, noCorrect: values.noCorrect, abstention: values.abstention, showStatistic: 1, gridSize: values.gridSize, offsetX: values.offsetX, offsetY: values.offsetY, zoomLvl: values.zoomLvl, image: values.image, fcImage: values.flashcardImage, gridOffsetX: values.gridOffsetX, gridOffsetY: values.gridOffsetY, gridZoomLvl: values.gridZoomLvl, gridSizeX: values.gridSizeX, gridSizeY: values.gridSizeY, gridIsHidden: values.gridIsHidden, imgRotation: values.imgRotation, toggleFieldsLeft: values.toggleFieldsLeft, numClickableFields: values.numClickableFields, thresholdCorrectAnswers: values.thresholdCorrectAnswers, cvIsColored: values.cvIsColored, gridLineColor: values.gridLineColor, numberOfDots: values.numberOfDots, gridType: values.gridType, scaleFactor: values.scaleFactor, gridScaleFactor: values.gridScaleFactor, imageQuestion: values.imageQuestion, textAnswerEnabled: values.textAnswerEnabled, saveButton: button, successFunc: function (response, opts) { promise.resolve(response); button.enable(); }, failureFunc: function (response, opts) { Ext.Msg.alert(Messages.NOTICE, Messages.QUESTION_CREATION_ERROR); promise.reject(response); button.enable(); } }); return promise; }, setGridConfiguration: function (grid) { grid.setEditable(false); grid.setGridIsHidden(true); }, setImage: function (image, test) { var title = this.toolbar.getTitle().getTitle(), isFlashcard = title === Messages.FLASHCARD, grid = isFlashcard ? this.flashcardQuestion.grid : this.grid; this.image = image; grid.setImage(image); if (image) { grid.show(); } else { grid.hide(); grid.clearImage(); this.setGridConfiguration(grid); } }, setFcImage: function (image) { this.fcImage = image; this.grid.setImage(image); if (image) { this.grid.show(); } else { this.grid.hide(); this.grid.clearImage(); this.setGridConfiguration(this.grid); } }, /** * Selects a button of the segmentation component with the given name. * * @param text The text of the button to be selected. */ activateButtonWithText: function (text) { var me = this; this.questionOptions.innerItems.forEach(function (item, index) { if (item.getItemId() === text) { me.questionOptions.setPressedButtons([index]); } }); } });
commana/arsnova-mobile
src/main/webapp/app/view/speaker/NewQuestionPanel.js
JavaScript
gpl-3.0
18,815
/** * Created by Akkadius on 2/10/2015. */ $(document).ready(function() { var CalcDataTableHeight = function () { return $(window).height() * 60 / 100; }; var table = $("#npc_head_table").DataTable( { scrollY: CalcDataTableHeight(), scrollX: true, scrollCollapse: true, paging: false, "searching": false, "ordering": true, "columnDefs": [ { "targets": 0, "orderable": false } ], "oLanguage": { "sProcessing": "DataTables is currently busy" } } ); // $(window).resize(function () { // var table = $("#npc_head_table").DataTable(); // var oSettings = table.fnSettings().oScroll.sY = CalcDataTableHeight(); // table.fnDraw(); // }); new $.fn.dataTable.FixedColumns( table, { leftColumns: 3 } ); var timer = setInterval(function () { var table = $("#npc_head_table").DataTable(); table.draw(); window.clearInterval(timer); }, 500); $( "#npc_head_table td, .DTFC_Cloned td" ).unbind("mouseenter"); $( "#npc_head_table td, .DTFC_Cloned td" ).bind("mouseenter", function() { // console.log("Hovering in"); if($(this).attr("is_field_translated") == 1){ return; } npc_id = $(this).attr("npc_id"); field_name = $(this).attr("npc_db_field"); width = $(this).css("width"); height = $(this).css("height"); data = $(this).html(); // console.log(npc_id + " " + field_name); /* Dont replace the button */ if(data.match(/button/i)){ return; } $(this).html('<input type="text" class="form-control" value="' + data + '" onchange="update_npc_field(npc_id, field_name, this.value)">'); $(this).children("input").css('width', (parseInt(width) * 1)); $(this).children("input").css('height', (parseInt(height))); $(this).children("input").css("font-size", "12px"); // $('textarea').autosize(); data = ""; }); $( "#npc_head_table td, .DTFC_Cloned td" ).unbind("mouseleave"); $( "#npc_head_table td, .DTFC_Cloned td" ).bind("mouseleave", function() { data = ""; if($(this).has("select").length){ data = $(this).children("select").val(); } else if($(this).has("input").length){ data = $(this).children("input").val(); } if($(this).has("button").length){ return; } /* If no data present and */ if(!data && (!$(this).has("select").length && !$(this).has("input").length)){ $(this).attr("is_field_translated", 0); return; } // console.log('data catch ' + data); $(this).html(data); data = ""; $(this).attr("is_field_translated", 0); }); } ); /* NPC TABLE :: Click */ $( "#npc_head_table td" ).click(function() { npc_id = $(this).attr("npc_id"); db_field = $(this).attr("npc_db_field"); width = $(this).css("width"); height = $(this).css("height"); data = $(this).html(); if(data.match(/button/i)){ return; } // console.log(npc_id); /* Highlight row */ if($('#top_right_pane').attr('npc_loaded') == npc_id){ console.log('npc already loaded, returning...'); return; } /* Highlight Row when selected */ $("td[background='yellow']").css("background", "").attr("background", ""); $("td[npc_id='" + npc_id + "']").css("background", "yellow").attr("background", "yellow"); $.ajax({ url: "ajax.php?M=NPC&load_npc_top_pane_dash=" + npc_id, context: document.body }).done(function(e) { /* Update Data Table as well */ $('#top_right_pane').html(e).fadeIn(); $('#top_right_pane').attr('npc_loaded', npc_id); }); }); /* NPC TABLE :: Double Click */ $( "#npc_head_table td" ).dblclick(function() { npc_id = $(this).attr("npc_id"); db_field = $(this).attr("npc_db_field"); width = $(this).css("width"); height = $(this).css("height"); data = $(this).html(); input_data = $(this).find("input").val(); cell = $(this); if(data.match(/button/i)){ return; } if(db_field == "special_abilities"){ DoModal("ajax.php?M=NPC&special_abilities_editor&val=" + input_data + "&npc_id=" + npc_id + "&db_field=" + db_field); return; } $.ajax({ url: "ajax.php?M=NPC&get_field_translator&npc_id=" + npc_id + "&field_name=" + db_field + "&value=" + input_data, context: document.body }).done(function(e) { // console.log(e); /* Return if tool result is empty */ if(e == ""){ return; } /* Update Table Cell with Field Translator Tool */ cell.html(e).fadeIn(); cell.attr("is_field_translated", 1); }); });
Akkadius/EQEmuEOC
modules/NPC/ajax/npc_table.js
JavaScript
gpl-3.0
4,786
var mongoose = require('mongoose'); var characterSchema = new mongoose.Schema({ name: String, userID: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, inventarID: { type: mongoose.Schema.Types.ObjectId, ref: 'Inventar' }, gender: String, skincolor: String, hair: Number, haircolor: String, gear: { head: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }, body: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }, legs: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' } }, costume: { head: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }, body: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }, legs: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' } }, hp: Number, weapon: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }, deaths: Number, kills: Number, rounds: Number, created: { type: Date, default: Date.now } }); // Updates a character from the database. characterSchema.methods.update = function(_id, data, callback){ this.findById(_id, function(err, character){ if(err) return callback(err); if(character){ updateCharacter(character, data, err); if(err) return callback(err); else return callback(null); } }); } // Deletes a character from the database. characterSchema.methods.delete = function(name, callback){ this.findById(name, function(err, character){ if(err) return callback(err); if(character) character.remove(function(err){ return callback(err); }); else return callback("Could not be removed"); }); } // Helper function to update every single field in the database if it's in the data-object. function updateCharacter(character, data, callback){ if("name" in data) character.name = data.name; if("userID" in data) character.userID = data.userID; if("inventarID" in data) character.inventarID = data.inventarID; if("gender" in data) character.gender = data.gender; if("skincolor" in data) character.skincolor = data.skincolor; if("hair" in data) character.hair = data.hair; if("haircolor" in data) character.haircolor = data.haircolor; if("hp" in data) character.hp = data.hp; if("weapon" in data) character.weapon = data.weapon; if("deaths" in data) character.deaths = data.deaths; if("kills" in data) character.kills = data.kills; if("rounds" in data) character.rounds = data.rounds; if("gear" in data){ if("head" in data.gear) character.gear.head = data.gear.head; if("body" in data.gear) character.gear.body = data.gear.body; if("legs" in data.gear) character.gear.legs = data.gear.legs; } if("costume" in data){ if("head" in data.costume) character.costume.head = data.costume.head; if("body" in data.costume) character.costume.body = data.costume.body; if("legs" in data.costume) character.costume.legs = data.costume.legs; } character.save(function(err){ if(err) return callback(err) else return callback(null); }); } module.exports = mongoose.model("Character", characterSchema);
FA15bZombieSurvival/Zurival
models/character.js
JavaScript
gpl-3.0
3,251
/* * @Author: LIU CHENG * @Date: 2017-02-22 18:39:38 * @Last Modified by: LIU CHENG * @Last Modified time: 2017-03-05 11:39:18 */ import React, { PropTypes } from 'react'; import { Text, View, Image, TouchableHighlight, ActivityIndicator, StyleSheet } from 'react-native'; /** * Dashboard * props: * avatar_url: String uri of avatar * buttonsController: Array [{onPress:func, backgroundColor: Color, buttonText: String}] * loading: Boolean, if data is prepared */ function Dashboard(props) { const { avatar_url, buttonsController, loading } = props; return ( <View style={styles.container}> {loading ? ( <ActivityIndicator animating={loading} color="#111" size="large" style={styles.image} /> ) : ( <Image source={{uri: avatar_url}} style={styles.image} /> )} {buttonsController.map((item, index) => ( <TouchableHighlight key={index} onPress={item.onPress} style={[styles.button, {backgroundColor: item.backgroundColor}]} underlayColor="#8BD4F5" > <Text style={styles.buttonText}>{item.buttonText}</Text> </TouchableHighlight> ) )} </View> ) } Dashboard.propTypes = { avatar_url: PropTypes.string.isRequired, buttonsController: PropTypes.array.isRequired, loading: PropTypes.bool.isRequired, } const styles = StyleSheet.create({ container: { marginTop: 65, flex: 1 }, image: { height: 350 }, buttonText: { fontSize: 24, color: 'white', alignSelf: 'center' }, button: { flexDirection: 'row', alignSelf: 'stretch', justifyContent: 'center', flex: 1 } }); export default Dashboard;
kimochg/react-native-githubnote-app
src/components/Dashboard.js
JavaScript
gpl-3.0
1,787
import { commitMutation, graphql } from 'react-relay' import { ConnectionHandler } from 'relay-runtime' const mutation = graphql` mutation CreateSpeciesMutation($input: CreateSpeciesInput!) { createSpecies(input: $input) { clientMutationId speciesEdge { node { authorId id nodeId air temp water soil } } query { ...SpeciesList_query } } } ` let nextClientMutationId = 0 const commit = (environment, { species, viewer }) => new Promise((resolve, reject) => { const clientMutationId = nextClientMutationId++ const variables = { input: { clientMutationId, species: { ...species, authorId: viewer.id, }, }, } return commitMutation(environment, { mutation, variables, onError: (error: Error) => { reject(error) }, onCompleted: (response: Object) => { resolve(response) }, // See https://github.com/facebook/relay/issues/1701#issuecomment-301012344 // and also https://github.com/facebook/relay/issues/1701#issuecomment-300995425 // and also https://github.com/facebook/relay/issues/1701 updater: store => { const payload = store.getRootField('createSpecies') const newEdge = payload.getLinkedRecord('speciesEdge') const storeRoot = store.getRoot() const connection = ConnectionHandler.getConnection( storeRoot, 'SpeciesList_species', { first: 2147483647, orderBy: 'GENUS_ASC' } ) if (connection) { ConnectionHandler.insertEdgeBefore(connection, newEdge) } else { console.error('No connection found') } }, }) }) export default { commit }
doeg/plantly-graphql
web/src/mutations/CreateSpeciesMutation.js
JavaScript
gpl-3.0
1,851
var fs = require('fs') // Script directories var settings = require('./settings.json'); // The settings file var scriptDir = settings.scriptDir + '/'; // The directory where dota scripts are placed var scriptDirOut = settings.scriptDirOut; // The directory where our files are outputted var resourcePath = settings.dotaDir + 'game/dota/resource/'; // The directory to read resource files from var customDir = settings.customDir; // The directory where our mods are read from, to be merged in var customAbilitiesLocation = '../src/scripts/npc/npc_abilities_custom.txt' var langDir = '../src/localization/'; // Code needed to do multipliers var spellMult = require('./spellMult.json'); // Create the output folder if(!fs.existsSync(scriptDirOut)) fs.mkdirSync(scriptDirOut); // Create the output folder //if(!fs.existsSync(scriptDirOut)) fs.mkdirSync(scriptDirOut); // Store for our custom stuff var customAbilities = {}; var customUnits = {}; //var customItems = {}; //var items = {}; var abilities = {}; /* Prepare language files */ var langs = ['english', 'schinese']; var langIn = {}; var langOut = {}; var specialChar; // Special character needed for doto encoding // theString is the string we search for and use as a key to store in // if theString can't be find, search using altString // search in actual language, if that fails, search in english, if that fails, commit suicide function generateLanguage(theString, altString, appendOnEnd) { // Grab a reference to english var english = langIn.english; if(appendOnEnd == null) appendOnEnd = ''; for(var i=0; i<langs.length; ++i) { // Grab a language var lang = langs[i]; var langFile = langIn[lang]; var storeTo = langOut[lang]; if(langFile[theString]) { storeTo[theString] = langFile[theString] + appendOnEnd; } else if(langFile[altString]) { storeTo[theString] = langFile[altString] + appendOnEnd; } else if(english[theString]) { storeTo[theString] = english[theString] + appendOnEnd; } else if(english[altString]) { storeTo[theString] = english[altString] + appendOnEnd; } else if(storeTo[altString]) { storeTo[theString] = storeTo[altString] + appendOnEnd; } else { console.log('Failed to find ' + theString); } if(!langFile[theString]) langFile[theString] = storeTo[theString]; } } var generateAfter = []; function generateLanguageAfter(theString, altString, appendOnEnd) { generateAfter.push([theString, altString, appendOnEnd]); } function clearGenerateAfter() { generateAfter = []; } // Read in our language files function prepareLanguageFiles(next) { var ourData = ''+fs.readFileSync(langDir + 'addon_english.txt'); var english = parseKV(ourData).addon; specialChar = fs.readFileSync(resourcePath + 'dota_english.txt', 'utf16le').substring(0, 1); for(var i=0; i<langs.length; ++i) { // Grab a language var lang = langs[i]; var data = fs.readFileSync(resourcePath + 'dota_' + lang + '.txt', 'utf16le').substring(1); // Load her up langIn[lang] = parseKV(data).lang.Tokens; langOut[lang] = {}; var toUse; if(fs.existsSync(langDir + 'addon_' + lang + '.txt')) { var ourData if(lang == 'english') { ourData = ''+fs.readFileSync(langDir + 'addon_' + lang + '.txt'); } else { ourData = ''+fs.readFileSync(langDir + 'addon_' + lang + '.txt', 'utf16le').substring(1); } toUse = parseKV(ourData).addon; } else { toUse = english; } for(var key in english) { if(toUse[key]) { langOut[lang][key] = toUse[key]; } else { langOut[lang][key] = english[key]; } } for(var key in toUse) { if(!langIn[lang][key]) { langIn[lang][key] = toUse[key]; } } } console.log('Done loading languages!'); // Run the next step if there is one if(next) next(); } /* Precache generator */ function generatePrecacheData(next) { // Precache generator fs.readFile(scriptDir+'npc_heroes.txt', function(err, rawHeroes) { console.log('Loading heroes...'); var rootHeroes = parseKV(''+rawHeroes); var newKV = {}; // List of heroes to ignore differs based on s1 and s2 // In s2, no bots are supported, so we can just strip every hero var ignoreHeroes = { npc_dota_hero_techies: true, npc_dota_hero_gyrocopter: true, npc_dota_hero_riki: true }; var heroes = rootHeroes.DOTAHeroes; for(var name in heroes) { if(name == 'Version') continue; if(name == 'npc_dota_hero_base') continue; var data = heroes[name]; if(!ignoreHeroes[name]) { newKV[name+'_lod'] = { override_hero: name, AbilityLayout: 6 } if(data.BotImplemented != 1) { //newKV[name+'_lod'].Ability1 = 'attribute_bonus'; for(var i=1;i<=32;++i) { var txt = heroes[name]['Ability' + i]; if(txt) { if(txt[0].indexOf('special_bonus_') != -1) { //newKV[name+'_lod']['Ability' + i] = txt; } else { newKV[name+'_lod']['Ability' + i] = ''; } } } } } // Check if they are melee if(data.AttackCapabilities == 'DOTA_UNIT_CAP_MELEE_ATTACK') { if(!newKV[name+'_lod']) { newKV[name+'_lod'] = { override_hero: name } } // Give them projectile speed + model newKV[name+'_lod'].ProjectileSpeed = 1000 newKV[name+'_lod'].ProjectileModel = 'luna_base_attack' } // Add ability layout = 6 if(!newKV[name+'_lod']) { newKV[name+'_lod'] = { override_hero: name } } newKV[name+'_lod'].AbilityLayout = 6; // Source2 precache customUnits['npc_precache_'+name] = { BaseClass: 'npc_dota_creep', precache: { particle_folder: data.particle_folder, soundfile: data.GameSoundsFile } } // Extra precache stuff if(data.precache) { for(var key in data.precache) { customUnits['npc_precache_'+name].precache[key] = data.precache[key]; } } } // Techies override prcaching customUnits.npc_precache_npc_dota_hero_techies.precache.model = 'models/heroes/techies/fx_techiesfx_mine.vmdl'; // Store the hero data fs.writeFile(scriptDirOut+'npc_heroes_custom.txt', toKV(newKV, 'DOTAHeroes'), function(err) { if (err) throw err; console.log('Done saving custom heroes!'); // Continue, if there is something else to run if(next) next(); }); }); } /* Custom file mergers */ /*function loadItems(next) { // Simply read in the file, and store into our varible fs.readFile(scriptDir+'items.txt', function(err, rawItems) { console.log('Loading items...'); items = parseKV(''+rawItems).DOTAAbilities; // Continue, if there is something else to run if(next) next(); }); }*/ function loadAbilities(next) { // Simply read in the file, and store into our varible fs.readFile(scriptDir+'npc_abilities.txt', function(err, rawAbs) { console.log('Loading abilities...'); abilities = parseKV(''+rawAbs).DOTAAbilities; // Continue, if there is something else to run if(next) next(); }); } function loadCustomUnits(next) { // Simply read in the file, and store into our varible fs.readFile(customDir+'npc_units_custom.txt', function(err, rawCustomUnits) { console.log('Loading custom units...'); customUnits = parseKV(''+rawCustomUnits).DOTAUnits; // Continue, if there is something else to run if(next) next(); }); } function loadCustomAbilities(next) { // Simply read in the file, and store into our varible fs.readFile(customAbilitiesLocation, function(err, rawCustomAbilities) { console.log('Loading custom abilities...'); customAbilities = parseKV(''+rawCustomAbilities).DOTAAbilities; // Continue, if there is something else to run if(next) next(); }); } /* Process Skill Warnings */ function generateSkillWarnings(next) { // Grab a reference to english var english = langIn.english; for(var word in english) { if(word.indexOf('warning_') == 0) { var value = english[word]; var abilityName = word.replace('warning_', ''); for(var i=0; i<langs.length; ++i) { // Grab a language var lang = langs[i]; var langFile = langIn[lang]; var storeTo = langOut[lang]; var storeValue = value; // Does this language have a different translation of the word? if(langFile[word]) { storeValue = langFile[word]; } // Do we have anything to change? var searchKey = 'DOTA_Tooltip_ability_' + abilityName+ '_Description'; if(langFile[searchKey]) { storeValue = langFile[searchKey] + '<br><br>' + storeValue + '<br>'; } // Store it storeTo[searchKey] = storeValue; } } } // Continue next(); } /* Helper functions */ // Round to places decimal places function r(value, places) { for(var i=0; i<places; i++) { value *= 10; } value = Math.round(value); for(var i=0; i<places; i++) { value /= 10; } return value; } function clone(x) { if (x === null || x === undefined) return x; if (x.clone) return x.clone(); if (x.constructor == Array) { var r = []; for (var i=0,n=x.length; i<n; i++) r.push(clone(x[i])); return r; } if(typeof(x) == 'object') { var y = {}; for(var key in x) { y[key] = clone(x[key]); } return y; } return x; } /* Parses most of a KV file Mostly copied from here: https://github.com/Matheus28/KeyValue/blob/master/m28/keyvalue/KeyValue.hx */ var TYPE_BLOCK = 0; function parseKV(data) { // Make sure we have some data to work with if(!data) return null; var tree = [{}]; var treeType = [TYPE_BLOCK]; var keys = [null]; var i = 0; var line = 1; while(i < data.length) { var chr = data.charAt(i); if(chr == ' ' || chr == '\t') { // Ignore white space } else if(chr == '\n') { // We moved onto the next line line++; if(data.charAt(i+1) == '\r') i++; } else if(chr == '\r') { // We moved onto the next line line++; if(data.charAt(i+1) == '\n') i++; } else if(chr == '/') { if(data.charAt(i+1) == '/') { // We found a comment, ignore rest of the line while(++i < data.length) { chr = data.charAt(i); // Check for new line if(chr == '\n') { if(data.charAt(i+1) == '\r') ++i; break; } if(chr == '\r') { if(data.charAt(i+1) == '\n') ++i; break; } } // We are on a new line line++; } } else if(chr == '"') { var resultString = ''; i++; while(i < data.length) { chr = data.charAt(i); if(chr == '"') break; if(chr == '\n') { // We moved onto the next line line++; if(data.charAt(i+1) == '\r') i++; } else if(chr == '\r') { // We moved onto the next line line++; if(data.charAt(i+1) == '\n') i++; } else if(chr == '\\') { i++; // Gran the mext cjaracter chr = data.charAt(i); // Check for escaped characters switch(chr) { case '\\':chr = '\\'; break; case '"': chr = '"'; break; case '\'': chr = '\''; break; case 'n': chr = '\n'; break; case 'r': chr = '\r'; break; default: chr = '\\'; i--; break; } } resultString += chr; i++; } if (i == data.length || chr == '\n' || chr == '\r') throw new Error("Unterminated string at line " + line); if(treeType[treeType.length - 1] == TYPE_BLOCK){ if (keys[keys.length - 1] == null) { keys[keys.length - 1] = resultString; }else { if(tree[tree.length - 1][keys[keys.length - 1]] == null) { tree[tree.length - 1][keys[keys.length - 1]] = []; } tree[tree.length - 1][keys[keys.length - 1]].push(resultString); keys[keys.length - 1] = null; } } // Check if we need to reparse the character that ended this string if(chr != '"') --i; } else if(chr == '{') { if(treeType[treeType.length - 1] == TYPE_BLOCK){ if (keys[keys.length - 1] == null) { throw new Error("A block needs a key at line " + line + " (offset " + i + ")"); } } tree.push({}); treeType.push(TYPE_BLOCK); keys.push(null); } else if (chr == '}') { if (tree.length == 1) { throw new Error("Mismatching bracket at line " + line + " (offset " + i + ")"); } if (treeType.pop() != TYPE_BLOCK) { throw new Error("Mismatching brackets at line " + line + " (offset " + i + ")"); } keys.pop(); var obj = tree.pop(); if(treeType[treeType.length - 1] == TYPE_BLOCK){ tree[tree.length - 1][keys[keys.length - 1]] = obj; keys[keys.length - 1] = null; }else { tree[tree.length - 1].push(obj); } } else { console.log("Unexpected character \"" + chr + "\" at line " + line + " (offset " + i + ")"); // Skip to next line while(++i < data.length) { chr = data.charAt(i); // Check for new line if(chr == '\n') { if(data.charAt(i+1) == '\r') ++i; break; } if(chr == '\r') { if(data.charAt(i+1) == '\n') ++i; break; } } // We are on a new line line++; // Move onto the next char i++; } i++; } if (tree.length != 1) { throw new Error("Missing brackets"); } return tree[0]; } function escapeString(str) { return str.replace(/\\/gm, '\\\\').replace(/\"/gm, '\\"').replace(/(\r\n|\n|\r|\n\r)/gm, '\\n'); } function toKV(obj, key) { var myStr = ''; if(obj == null) { // Nothing to return return ''; } else if (typeof obj == 'number') { return '"' + escapeString(key) + '""' + obj + '"'; } else if (typeof obj == 'boolean') { return '"' + escapeString(key) + '""' + obj + '"'; } else if (typeof obj == 'string') { return '"' + escapeString(key) + '""' + escapeString(obj) + '"'; } else if(obj instanceof Array) { // An array of strings for(var i=0; i<obj.length; i++) { myStr = myStr + '"' + escapeString(key) + '"\n"' + escapeString(obj[i]) + '"'; } return myStr; } else { // An object for(var entry in obj) { myStr += toKV(obj[entry], entry) } if(key != null) { return '"' + escapeString(key) + '"{\n' + myStr + '}'; } else { return myStr; } } } /* Run everything */ // Prepare hte languge files prepareLanguageFiles(function() { // Load our custom units loadCustomUnits(function() { // Load abilities loadAbilities(function() { // Load items //loadItems(function() { // Load our custom items //loadCustomItems(function() { // Load our custom abilities loadCustomAbilities(function() { // Generate the custom item abilities //generateAbilityItems(function() { // Generate our precache data generatePrecacheData(function() { //doCSP(function() { //doLvl1Ults(function() { generateSkillWarnings(function() { // Output language files for(var i=0; i<langs.length; ++i) { (function(lang) { fs.writeFile(scriptDirOut+'addon_' + lang + '_token.txt', specialChar + toKV({Tokens: langOut[lang]}, 'lang'), 'utf16le', function(err) { if (err) throw err; console.log('Finished saving ' + lang + '!'); }); fs.writeFile(scriptDirOut+'addon_' + lang + '.txt', specialChar + toKV(langOut[lang], 'addon'), 'utf16le', function(err) { if (err) throw err; console.log('Finished saving ' + lang + '!'); }); })(langs[i]); } // Output custom files fs.writeFile(scriptDirOut+'npc_units_custom.txt', toKV(customUnits, 'DOTAUnits'), function(err) { if (err) throw err; console.log('Done saving custom units file!'); }); }); //}); //}); }); //}); }); //}); //}); }); }); });
LegendsOfDota/LegendsOfDota
script_generator/app.js
JavaScript
gpl-3.0
20,039
/* * jQuery File Upload User Interface Plugin * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* jshint nomen:false */ /* global define, require, window */ ;(function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'tmpl', './jquery.fileupload-image', './jquery.fileupload-audio', './jquery.fileupload-video', './jquery.fileupload-validate' ], factory); } else if (typeof exports === 'object') { // Node/CommonJS: factory( require('jquery'), require('tmpl') ); } else { // Browser globals: factory( window.jQuery, window.tmpl ); } }(function ($, tmpl) { 'use strict'; jQuery.blueimp.fileupload.prototype._specialOptions.push( 'filesContainer', 'uploadTemplateId', 'downloadTemplateId' ); // The UI version extends the file upload widget // and adds complete user interface interaction: jQuery.widget('blueimp.fileupload', jQuery.blueimp.fileupload, { options: { // By default, files added to the widget are uploaded as soon // as the user clicks on the start buttons. To enable automatic // uploads, set the following option to true: autoUpload: false, // The ID of the upload template: uploadTemplateId: 'template-upload', // The ID of the download template: downloadTemplateId: 'template-download', // The container for the list of files. If undefined, it is set to // an element with class "files" inside of the widget element: filesContainer: undefined, // By default, files are appended to the files container. // Set the following option to true, to prepend files instead: prependFiles: false, // The expected data type of the upload response, sets the dataType // option of the jQuery.ajax upload requests: dataType: 'json', // Error and info messages: messages: { unknownError: 'Unknown error' }, // Function returning the current number of files, // used by the maxNumberOfFiles validation: getNumberOfFiles: function () { return this.filesContainer.children() .not('.processing').length; }, // Callback to retrieve the list of files from the server response: getFilesFromResponse: function (data) { if (data.result && jQuery.isArray(data.result.files)) { return data.result.files; } return []; }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop or add API call). // See the basic file upload widget for more information: add: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = jQuery(this), that = $this.data('blueimp-fileupload') || $this.data('fileupload'), options = that.options; data.context = that._renderUpload(data.files) .data('data', data) .addClass('processing'); options.filesContainer[ options.prependFiles ? 'prepend' : 'append' ](data.context); that._forceReflow(data.context); that._transition(data.context); data.process(function () { return $this.fileupload('process', data); }).always(function () { data.context.each(function (index) { jQuery(this).find('.size').text( that._formatFileSize(data.files[index].size) ); }).removeClass('processing'); that._renderPreviews(data); }).done(function () { data.context.find('.start').prop('disabled', false); if ((that._trigger('added', e, data) !== false) && (options.autoUpload || data.autoUpload) && data.autoUpload !== false) { data.submit(); } }).fail(function () { if (data.files.error) { data.context.each(function (index) { var error = data.files[index].error; if (error) { jQuery(this).find('.error').text(error); } }); } }); }, // Callback for the start of each file upload request: send: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = jQuery(this).data('blueimp-fileupload') || jQuery(this).data('fileupload'); if (data.context && data.dataType && data.dataType.substr(0, 6) === 'iframe') { // Iframe Transport does not support progress events. // In lack of an indeterminate progress bar, we set // the progress to 100%, showing the full animated bar: data.context .find('.progress').addClass( !jQuery.support.transition && 'progress-animated' ) .attr('aria-valuenow', 100) .children().first().css( 'width', '100%' ); } return that._trigger('sent', e, data); }, // Callback for successful uploads: done: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = jQuery(this).data('blueimp-fileupload') || jQuery(this).data('fileupload'), getFilesFromResponse = data.getFilesFromResponse || that.options.getFilesFromResponse, files = getFilesFromResponse(data), template, deferred; if (data.context) { data.context.each(function (index) { var file = files[index] || {error: 'Empty file upload result'}; deferred = that._addFinishedDeferreds(); that._transition(jQuery(this)).done( function () { var node = jQuery(this); template = that._renderDownload([file]) .replaceAll(node); that._forceReflow(template); that._transition(template).done( function () { data.context = jQuery(this); that._trigger('completed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } ); }); } else { template = that._renderDownload(files)[ that.options.prependFiles ? 'prependTo' : 'appendTo' ](that.options.filesContainer); that._forceReflow(template); deferred = that._addFinishedDeferreds(); that._transition(template).done( function () { data.context = jQuery(this); that._trigger('completed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } }, // Callback for failed (abort or error) uploads: fail: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = jQuery(this).data('blueimp-fileupload') || jQuery(this).data('fileupload'), template, deferred; if (data.context) { data.context.each(function (index) { if (data.errorThrown !== 'abort') { var file = data.files[index]; file.error = file.error || data.errorThrown || data.i18n('unknownError'); deferred = that._addFinishedDeferreds(); that._transition(jQuery(this)).done( function () { var node = jQuery(this); template = that._renderDownload([file]) .replaceAll(node); that._forceReflow(template); that._transition(template).done( function () { data.context = jQuery(this); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } ); } else { deferred = that._addFinishedDeferreds(); that._transition(jQuery(this)).done( function () { jQuery(this).remove(); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } }); } else if (data.errorThrown !== 'abort') { data.context = that._renderUpload(data.files)[ that.options.prependFiles ? 'prependTo' : 'appendTo' ](that.options.filesContainer) .data('data', data); that._forceReflow(data.context); deferred = that._addFinishedDeferreds(); that._transition(data.context).done( function () { data.context = jQuery(this); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } else { that._trigger('failed', e, data); that._trigger('finished', e, data); that._addFinishedDeferreds().resolve(); } }, // Callback for upload progress events: progress: function (e, data) { if (e.isDefaultPrevented()) { return false; } var progress = Math.floor(data.loaded / data.total * 100); if (data.context) { data.context.each(function () { jQuery(this).find('.progress') .attr('aria-valuenow', progress) .children().first().css( 'width', progress + '%' ); }); } }, // Callback for global upload progress events: progressall: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = jQuery(this), progress = Math.floor(data.loaded / data.total * 100), globalProgressNode = $this.find('.fileupload-progress'), extendedProgressNode = globalProgressNode .find('.progress-extended'); if (extendedProgressNode.length) { extendedProgressNode.html( ($this.data('blueimp-fileupload') || $this.data('fileupload')) ._renderExtendedProgress(data) ); } globalProgressNode .find('.progress') .attr('aria-valuenow', progress) .children().first().css( 'width', progress + '%' ); }, // Callback for uploads start, equivalent to the global ajaxStart event: start: function (e) { if (e.isDefaultPrevented()) { return false; } var that = jQuery(this).data('blueimp-fileupload') || jQuery(this).data('fileupload'); that._resetFinishedDeferreds(); that._transition(jQuery(this).find('.fileupload-progress')).done( function () { that._trigger('started', e); } ); }, // Callback for uploads stop, equivalent to the global ajaxStop event: stop: function (e) { if (e.isDefaultPrevented()) { return false; } var that = jQuery(this).data('blueimp-fileupload') || jQuery(this).data('fileupload'), deferred = that._addFinishedDeferreds(); jQuery.when.apply($, that._getFinishedDeferreds()) .done(function () { that._trigger('stopped', e); }); that._transition(jQuery(this).find('.fileupload-progress')).done( function () { jQuery(this).find('.progress') .attr('aria-valuenow', '0') .children().first().css('width', '0%'); jQuery(this).find('.progress-extended').html('&nbsp;'); deferred.resolve(); } ); }, processstart: function (e) { if (e.isDefaultPrevented()) { return false; } jQuery(this).addClass('fileupload-processing'); }, processstop: function (e) { if (e.isDefaultPrevented()) { return false; } jQuery(this).removeClass('fileupload-processing'); }, // Callback for file deletion: destroy: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = jQuery(this).data('blueimp-fileupload') || jQuery(this).data('fileupload'), removeNode = function () { that._transition(data.context).done( function () { jQuery(this).remove(); that._trigger('destroyed', e, data); } ); }; if (data.url) { data.dataType = data.dataType || that.options.dataType; jQuery.ajax(data).done(removeNode).fail(function () { that._trigger('destroyfailed', e, data); }); } else { removeNode(); } } }, _resetFinishedDeferreds: function () { this._finishedUploads = []; }, _addFinishedDeferreds: function (deferred) { if (!deferred) { deferred = jQuery.Deferred(); } this._finishedUploads.push(deferred); return deferred; }, _getFinishedDeferreds: function () { return this._finishedUploads; }, // Link handler, that allows to download files // by drag & drop of the links to the desktop: _enableDragToDesktop: function () { var link = jQuery(this), url = link.prop('href'), name = link.prop('download'), type = 'application/octet-stream'; link.bind('dragstart', function (e) { try { e.originalEvent.dataTransfer.setData( 'DownloadURL', [type, name, url].join(':') ); } catch (ignore) {} }); }, _formatFileSize: function (bytes) { if (typeof bytes !== 'number') { return ''; } if (bytes >= 1000000000) { return (bytes / 1000000000).toFixed(2) + ' GB'; } if (bytes >= 1000000) { return (bytes / 1000000).toFixed(2) + ' MB'; } return (bytes / 1000).toFixed(2) + ' KB'; }, _formatBitrate: function (bits) { if (typeof bits !== 'number') { return ''; } if (bits >= 1000000000) { return (bits / 1000000000).toFixed(2) + ' Gbit/s'; } if (bits >= 1000000) { return (bits / 1000000).toFixed(2) + ' Mbit/s'; } if (bits >= 1000) { return (bits / 1000).toFixed(2) + ' kbit/s'; } return bits.toFixed(2) + ' bit/s'; }, _formatTime: function (seconds) { var date = new Date(seconds * 1000), days = Math.floor(seconds / 86400); days = days ? days + 'd ' : ''; return days + ('0' + date.getUTCHours()).slice(-2) + ':' + ('0' + date.getUTCMinutes()).slice(-2) + ':' + ('0' + date.getUTCSeconds()).slice(-2); }, _formatPercentage: function (floatValue) { return (floatValue * 100).toFixed(2) + ' %'; }, _renderExtendedProgress: function (data) { return this._formatBitrate(data.bitrate) + ' | ' + this._formatTime( (data.total - data.loaded) * 8 / data.bitrate ) + ' | ' + this._formatPercentage( data.loaded / data.total ) + ' | ' + this._formatFileSize(data.loaded) + ' / ' + this._formatFileSize(data.total); }, _renderTemplate: function (func, files) { if (!func) { return jQuery(); } var result = func({ files: files, formatFileSize: this._formatFileSize, options: this.options }); if (result instanceof $) { return result; } return jQuery(this.options.templatesContainer).html(result).children(); }, _renderPreviews: function (data) { data.context.find('.preview').each(function (index, elm) { jQuery(elm).append(data.files[index].preview); }); }, _renderUpload: function (files) { return this._renderTemplate( this.options.uploadTemplate, files ); }, _renderDownload: function (files) { return this._renderTemplate( this.options.downloadTemplate, files ).find('a[download]').each(this._enableDragToDesktop).end(); }, _startHandler: function (e) { e.preventDefault(); var button = jQuery(e.currentTarget), template = button.closest('.template-upload'), data = template.data('data'); button.prop('disabled', true); if (data && data.submit) { data.submit(); } }, _cancelHandler: function (e) { e.preventDefault(); var template = jQuery(e.currentTarget) .closest('.template-upload,.template-download'), data = template.data('data') || {}; data.context = data.context || template; if (data.abort) { data.abort(); } else { data.errorThrown = 'abort'; this._trigger('fail', e, data); } }, _deleteHandler: function (e) { e.preventDefault(); var button = jQuery(e.currentTarget); this._trigger('destroy', e, jQuery.extend({ context: button.closest('.template-download'), type: 'DELETE' }, button.data())); }, _forceReflow: function (node) { return jQuery.support.transition && node.length && node[0].offsetWidth; }, _transition: function (node) { var dfd = jQuery.Deferred(); if (jQuery.support.transition && node.hasClass('fade') && node.is(':visible')) { node.bind( jQuery.support.transition.end, function (e) { // Make sure we don't respond to other transitions events // in the container element, e.g. from button elements: if (e.target === node[0]) { node.unbind(jQuery.support.transition.end); dfd.resolveWith(node); } } ).toggleClass('in'); } else { node.toggleClass('in'); dfd.resolveWith(node); } return dfd; }, _initButtonBarEventHandlers: function () { var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'), filesList = this.options.filesContainer; this._on(fileUploadButtonBar.find('.start'), { click: function (e) { e.preventDefault(); filesList.find('.start').click(); } }); this._on(fileUploadButtonBar.find('.cancel'), { click: function (e) { e.preventDefault(); filesList.find('.cancel').click(); } }); this._on(fileUploadButtonBar.find('.delete'), { click: function (e) { e.preventDefault(); filesList.find('.toggle:checked') .closest('.template-download') .find('.delete').click(); fileUploadButtonBar.find('.toggle') .prop('checked', false); } }); this._on(fileUploadButtonBar.find('.toggle'), { change: function (e) { filesList.find('.toggle').prop( 'checked', jQuery(e.currentTarget).is(':checked') ); } }); }, _destroyButtonBarEventHandlers: function () { this._off( this.element.find('.fileupload-buttonbar') .find('.start, .cancel, .delete'), 'click' ); this._off( this.element.find('.fileupload-buttonbar .toggle'), 'change.' ); }, _initEventHandlers: function () { this._super(); this._on(this.options.filesContainer, { 'click .start': this._startHandler, 'click .cancel': this._cancelHandler, 'click .delete': this._deleteHandler }); this._initButtonBarEventHandlers(); }, _destroyEventHandlers: function () { this._destroyButtonBarEventHandlers(); this._off(this.options.filesContainer, 'click'); this._super(); }, _enableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', false) .parent().removeClass('disabled'); }, _disableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', true) .parent().addClass('disabled'); }, _initTemplates: function () { var options = this.options; options.templatesContainer = this.document[0].createElement( options.filesContainer.prop('nodeName') ); if (tmpl) { if (options.uploadTemplateId) { options.uploadTemplate = tmpl(options.uploadTemplateId); } if (options.downloadTemplateId) { options.downloadTemplate = tmpl(options.downloadTemplateId); } } }, _initFilesContainer: function () { var options = this.options; if (options.filesContainer === undefined) { options.filesContainer = this.element.find('.files'); } else if (!(options.filesContainer instanceof $)) { options.filesContainer = jQuery(options.filesContainer); } }, _initSpecialOptions: function () { this._super(); this._initFilesContainer(); this._initTemplates(); }, _create: function () { this._super(); this._resetFinishedDeferreds(); if (!jQuery.support.fileInput) { this._disableFileInputButton(); } }, enable: function () { var wasDisabled = false; if (this.options.disabled) { wasDisabled = true; } this._super(); if (wasDisabled) { this.element.find('input, button').prop('disabled', false); this._enableFileInputButton(); } }, disable: function () { if (!this.options.disabled) { this.element.find('input, button').prop('disabled', true); this._disableFileInputButton(); } this._super(); } }); }));
sea75300/fanpresscm3
inc/lib/jqupload/js/jquery.fileupload-ui.js
JavaScript
gpl-3.0
28,144
tinyMCE.addI18n('en.tinycimmimage_dlg',{ title : 'Image Manager', upload:'Upload' });
wuts/xiaodoudian
application/assets/js/tiny_mce/plugins/tinycimm/langs/en_dlg.js
JavaScript
gpl-3.0
95
function divReplaceWith(selector, url) { $.get(url, function(response) { $(selector).html(response); }) }
smcs/online-language-lab
examples/dynamic-replacement/js/main.js
JavaScript
gpl-3.0
109
(function (root) { "use strict"; var Tone; //constructs the main Tone object function Main(func){ Tone = func(); } //invokes each of the modules with the main Tone object as the argument function Module(func){ func(Tone); } /** * Tone.js * @author Yotam Mann * @license http://opensource.org/licenses/MIT MIT License * @copyright 2014-2015 Yotam Mann */ Main(function () { ////////////////////////////////////////////////////////////////////////// // WEB AUDIO CONTEXT /////////////////////////////////////////////////////////////////////////// //borrowed from underscore.js function isUndef(val) { return val === void 0; } //borrowed from underscore.js function isFunction(val) { return typeof val === 'function'; } var audioContext; //polyfill for AudioContext and OfflineAudioContext if (isUndef(window.AudioContext)) { window.AudioContext = window.webkitAudioContext; } if (isUndef(window.OfflineAudioContext)) { window.OfflineAudioContext = window.webkitOfflineAudioContext; } if (!isUndef(AudioContext)) { audioContext = new AudioContext(); } else { throw new Error('Web Audio is not supported in this browser'); } //SHIMS//////////////////////////////////////////////////////////////////// if (!isFunction(AudioContext.prototype.createGain)) { AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; } if (!isFunction(AudioContext.prototype.createDelay)) { AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; } if (!isFunction(AudioContext.prototype.createPeriodicWave)) { AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; } if (!isFunction(AudioBufferSourceNode.prototype.start)) { AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; } if (!isFunction(AudioBufferSourceNode.prototype.stop)) { AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; } if (!isFunction(OscillatorNode.prototype.start)) { OscillatorNode.prototype.start = OscillatorNode.prototype.noteOn; } if (!isFunction(OscillatorNode.prototype.stop)) { OscillatorNode.prototype.stop = OscillatorNode.prototype.noteOff; } if (!isFunction(OscillatorNode.prototype.setPeriodicWave)) { OscillatorNode.prototype.setPeriodicWave = OscillatorNode.prototype.setWaveTable; } //extend the connect function to include Tones AudioNode.prototype._nativeConnect = AudioNode.prototype.connect; AudioNode.prototype.connect = function (B, outNum, inNum) { if (B.input) { if (Array.isArray(B.input)) { if (isUndef(inNum)) { inNum = 0; } this.connect(B.input[inNum]); } else { this.connect(B.input, outNum, inNum); } } else { try { if (B instanceof AudioNode) { this._nativeConnect(B, outNum, inNum); } else { this._nativeConnect(B, outNum); } } catch (e) { throw new Error('error connecting to node: ' + B); } } }; /////////////////////////////////////////////////////////////////////////// // TONE /////////////////////////////////////////////////////////////////////////// /** * @class Tone is the base class of all other classes. It provides * a lot of methods and functionality to all classes that extend * it. * * @constructor * @alias Tone * @param {number} [inputs=1] the number of input nodes * @param {number} [outputs=1] the number of output nodes */ var Tone = function (inputs, outputs) { /** * the input node(s) * @type {GainNode|Array} */ if (isUndef(inputs) || inputs === 1) { this.input = this.context.createGain(); } else if (inputs > 1) { this.input = new Array(inputs); } /** * the output node(s) * @type {GainNode|Array} */ if (isUndef(outputs) || outputs === 1) { this.output = this.context.createGain(); } else if (outputs > 1) { this.output = new Array(inputs); } }; /** * Set the parameters at once. Either pass in an * object mapping parameters to values, or to set a * single parameter, by passing in a string and value. * The last argument is an optional ramp time which * will ramp any signal values to their destination value * over the duration of the rampTime. * @param {Object|string} params * @param {number=} value * @param {Time=} rampTime * @returns {Tone} this * @example * //set values using an object * filter.set({ * "frequency" : 300, * "type" : highpass * }); * @example * filter.set("type", "highpass"); * @example * //ramp to the value 220 over 3 seconds. * oscillator.set({ * "frequency" : 220 * }, 3); */ Tone.prototype.set = function (params, value, rampTime) { if (this.isObject(params)) { rampTime = value; } else if (this.isString(params)) { var tmpObj = {}; tmpObj[params] = value; params = tmpObj; } for (var attr in params) { value = params[attr]; var parent = this; if (attr.indexOf('.') !== -1) { var attrSplit = attr.split('.'); for (var i = 0; i < attrSplit.length - 1; i++) { parent = parent[attrSplit[i]]; } attr = attrSplit[attrSplit.length - 1]; } var param = parent[attr]; if (isUndef(param)) { continue; } if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) { if (param.value !== value) { if (isUndef(rampTime)) { param.value = value; } else { param.rampTo(value, rampTime); } } } else if (param instanceof AudioParam) { if (param.value !== value) { param.value = value; } } else if (param instanceof Tone) { param.set(value); } else if (param !== value) { parent[attr] = value; } } return this; }; /** * Get the object's attributes. Given no arguments get * will return all available object properties and their corresponding * values. Pass in a single attribute to retrieve or an array * of attributes. The attribute strings can also include a "." * to access deeper properties. * @example * osc.get(); * //returns {"type" : "sine", "frequency" : 440, ...etc} * @example * osc.get("type"); * //returns { "type" : "sine"} * @example * //use dot notation to access deep properties * synth.get(["envelope.attack", "envelope.release"]); * //returns {"envelope" : {"attack" : 0.2, "release" : 0.4}} * @param {Array=|string|undefined} params the parameters to get, otherwise will return * all available. * @returns {Object} */ Tone.prototype.get = function (params) { if (isUndef(params)) { params = this._collectDefaults(this.constructor); } else if (this.isString(params)) { params = [params]; } var ret = {}; for (var i = 0; i < params.length; i++) { var attr = params[i]; var parent = this; var subRet = ret; if (attr.indexOf('.') !== -1) { var attrSplit = attr.split('.'); for (var j = 0; j < attrSplit.length - 1; j++) { var subAttr = attrSplit[j]; subRet[subAttr] = subRet[subAttr] || {}; subRet = subRet[subAttr]; parent = parent[subAttr]; } attr = attrSplit[attrSplit.length - 1]; } var param = parent[attr]; if (this.isObject(params[attr])) { subRet[attr] = param.get(); } else if (Tone.Signal && param instanceof Tone.Signal) { subRet[attr] = param.value; } else if (Tone.Param && param instanceof Tone.Param) { subRet[attr] = param.value; } else if (param instanceof AudioParam) { subRet[attr] = param.value; } else if (param instanceof Tone) { subRet[attr] = param.get(); } else if (!isFunction(param) && !isUndef(param)) { subRet[attr] = param; } } return ret; }; /** * collect all of the default attributes in one * @private * @param {function} constr the constructor to find the defaults from * @return {Array} all of the attributes which belong to the class */ Tone.prototype._collectDefaults = function (constr) { var ret = []; if (!isUndef(constr.defaults)) { ret = Object.keys(constr.defaults); } if (!isUndef(constr._super)) { var superDefs = this._collectDefaults(constr._super); //filter out repeats for (var i = 0; i < superDefs.length; i++) { if (ret.indexOf(superDefs[i]) === -1) { ret.push(superDefs[i]); } } } return ret; }; /** * @returns {string} returns the name of the class as a string */ Tone.prototype.toString = function () { for (var className in Tone) { var isLetter = className[0].match(/^[A-Z]$/); var sameConstructor = Tone[className] === this.constructor; if (isFunction(Tone[className]) && isLetter && sameConstructor) { return className; } } return 'Tone'; }; /////////////////////////////////////////////////////////////////////////// // CLASS VARS /////////////////////////////////////////////////////////////////////////// /** * A static pointer to the audio context accessible as Tone.context. * @type {AudioContext} */ Tone.context = audioContext; /** * The audio context. * @type {AudioContext} */ Tone.prototype.context = Tone.context; /** * the default buffer size * @type {number} * @static * @const */ Tone.prototype.bufferSize = 2048; /** * The delay time of a single frame (128 samples according to the spec). * @type {number} * @static * @const */ Tone.prototype.blockTime = 128 / Tone.context.sampleRate; /////////////////////////////////////////////////////////////////////////// // CONNECTIONS /////////////////////////////////////////////////////////////////////////// /** * disconnect and dispose * @returns {Tone} this */ Tone.prototype.dispose = function () { if (!this.isUndef(this.input)) { if (this.input instanceof AudioNode) { this.input.disconnect(); } this.input = null; } if (!this.isUndef(this.output)) { if (this.output instanceof AudioNode) { this.output.disconnect(); } this.output = null; } return this; }; /** * a silent connection to the DesinationNode * which will ensure that anything connected to it * will not be garbage collected * * @private */ var _silentNode = null; /** * makes a connection to ensure that the node will not be garbage collected * until 'dispose' is explicitly called * * use carefully. circumvents JS and WebAudio's normal Garbage Collection behavior * @returns {Tone} this */ Tone.prototype.noGC = function () { this.output.connect(_silentNode); return this; }; AudioNode.prototype.noGC = function () { this.connect(_silentNode); return this; }; /** * connect the output of a ToneNode to an AudioParam, AudioNode, or ToneNode * @param {Tone | AudioParam | AudioNode} unit * @param {number} [outputNum=0] optionally which output to connect from * @param {number} [inputNum=0] optionally which input to connect to * @returns {Tone} this */ Tone.prototype.connect = function (unit, outputNum, inputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].connect(unit, 0, inputNum); } else { this.output.connect(unit, outputNum, inputNum); } return this; }; /** * disconnect the output * @returns {Tone} this */ Tone.prototype.disconnect = function (outputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].disconnect(); } else { this.output.disconnect(); } return this; }; /** * connect together all of the arguments in series * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.connectSeries = function () { if (arguments.length > 1) { var currentUnit = arguments[0]; for (var i = 1; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } return this; }; /** * fan out the connection from the first argument to the rest of the arguments * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.connectParallel = function () { var connectFrom = arguments[0]; if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { var connectTo = arguments[i]; connectFrom.connect(connectTo); } } return this; }; /** * Connect the output of this node to the rest of the nodes in series. * @example * //connect a node to an effect, panVol and then to the master output * node.chain(effect, panVol, Tone.Master); * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.chain = function () { if (arguments.length > 0) { var currentUnit = this; for (var i = 0; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } return this; }; /** * connect the output of this node to the rest of the nodes in parallel. * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.fan = function () { if (arguments.length > 0) { for (var i = 0; i < arguments.length; i++) { this.connect(arguments[i]); } } return this; }; //give native nodes chain and fan methods AudioNode.prototype.chain = Tone.prototype.chain; AudioNode.prototype.fan = Tone.prototype.fan; /////////////////////////////////////////////////////////////////////////// // UTILITIES / HELPERS / MATHS /////////////////////////////////////////////////////////////////////////// /** * If the `given` parameter is undefined, use the `fallback`. * If both `given` and `fallback` are object literals, it will * return a deep copy which includes all of the parameters from both * objects. If a parameter is undefined in given, it will return * the fallback property. * <br><br> * WARNING: if object is self referential, it will go into an an * infinite recursive loop. * * @param {*} given * @param {*} fallback * @return {*} */ Tone.prototype.defaultArg = function (given, fallback) { if (this.isObject(given) && this.isObject(fallback)) { var ret = {}; //make a deep copy of the given object for (var givenProp in given) { ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]); } for (var fallbackProp in fallback) { ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]); } return ret; } else { return isUndef(given) ? fallback : given; } }; /** * returns the args as an options object with given arguments * mapped to the names provided. * * if the args given is an array containing only one object, it is assumed * that that's already the options object and will just return it. * * @param {Array} values the 'arguments' object of the function * @param {Array} keys the names of the arguments as they * should appear in the options object * @param {Object=} defaults optional defaults to mixin to the returned * options object * @return {Object} the options object with the names mapped to the arguments */ Tone.prototype.optionsObject = function (values, keys, defaults) { var options = {}; if (values.length === 1 && this.isObject(values[0])) { options = values[0]; } else { for (var i = 0; i < keys.length; i++) { options[keys[i]] = values[i]; } } if (!this.isUndef(defaults)) { return this.defaultArg(options, defaults); } else { return options; } }; /////////////////////////////////////////////////////////////////////////// // TYPE CHECKING /////////////////////////////////////////////////////////////////////////// /** * test if the arg is undefined * @param {*} arg the argument to test * @returns {boolean} true if the arg is undefined * @function */ Tone.prototype.isUndef = isUndef; /** * test if the arg is a function * @param {*} arg the argument to test * @returns {boolean} true if the arg is a function * @function */ Tone.prototype.isFunction = isFunction; /** * Test if the argument is a number. * @param {*} arg the argument to test * @returns {boolean} true if the arg is a number */ Tone.prototype.isNumber = function (arg) { return typeof arg === 'number'; }; /** * Test if the given argument is an object literal (i.e. `{}`); * @param {*} arg the argument to test * @returns {boolean} true if the arg is an object literal. */ Tone.prototype.isObject = function (arg) { return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object; }; /** * Test if the argument is a boolean. * @param {*} arg the argument to test * @returns {boolean} true if the arg is a boolean */ Tone.prototype.isBoolean = function (arg) { return typeof arg === 'boolean'; }; /** * Test if the argument is an Array * @param {*} arg the argument to test * @returns {boolean} true if the arg is an array */ Tone.prototype.isArray = function (arg) { return Array.isArray(arg); }; /** * Test if the argument is a string. * @param {*} arg the argument to test * @returns {boolean} true if the arg is a string */ Tone.prototype.isString = function (arg) { return typeof arg === 'string'; }; /** * An empty function. * @static */ Tone.noOp = function () { }; /** * Make the property not writable. Internal use only. * @private * @param {string} property the property to make not writable */ Tone.prototype._readOnly = function (property) { if (Array.isArray(property)) { for (var i = 0; i < property.length; i++) { this._readOnly(property[i]); } } else { Object.defineProperty(this, property, { writable: false, enumerable: true }); } }; /** * Make an attribute writeable. Interal use only. * @private * @param {string} property the property to make writable */ Tone.prototype._writable = function (property) { if (Array.isArray(property)) { for (var i = 0; i < property.length; i++) { this._writable(property[i]); } } else { Object.defineProperty(this, property, { writable: true }); } }; /** * Possible play states. * @enum {string} */ Tone.State = { Started: 'started', Stopped: 'stopped', Paused: 'paused' }; /////////////////////////////////////////////////////////////////////////// // GAIN CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Equal power gain scale. Good for cross-fading. * @param {NormalRange} percent (0-1) * @return {Number} output gain (0-1) */ Tone.prototype.equalPowerScale = function (percent) { var piFactor = 0.5 * Math.PI; return Math.sin(percent * piFactor); }; /** * Convert decibels into gain. * @param {Decibels} db * @return {Number} */ Tone.prototype.dbToGain = function (db) { return Math.pow(2, db / 6); }; /** * Convert gain to decibels. * @param {Number} gain (0-1) * @return {Decibels} */ Tone.prototype.gainToDb = function (gain) { return 20 * (Math.log(gain) / Math.LN10); }; /////////////////////////////////////////////////////////////////////////// // TIMING /////////////////////////////////////////////////////////////////////////// /** * Return the current time of the clock + a single buffer frame. * If this value is used to schedule a value to change, the earliest * it could be scheduled is the following frame. * @return {number} the currentTime from the AudioContext */ Tone.prototype.now = function () { return this.context.currentTime; }; /////////////////////////////////////////////////////////////////////////// // INHERITANCE /////////////////////////////////////////////////////////////////////////// /** * have a child inherit all of Tone's (or a parent's) prototype * to inherit the parent's properties, make sure to call * Parent.call(this) in the child's constructor * * based on closure library's inherit function * * @static * @param {function} child * @param {function=} parent (optional) parent to inherit from * if no parent is supplied, the child * will inherit from Tone */ Tone.extend = function (child, parent) { if (isUndef(parent)) { parent = Tone; } function TempConstructor() { } TempConstructor.prototype = parent.prototype; child.prototype = new TempConstructor(); /** @override */ child.prototype.constructor = child; child._super = parent; }; /////////////////////////////////////////////////////////////////////////// // CONTEXT /////////////////////////////////////////////////////////////////////////// /** * array of callbacks to be invoked when a new context is added * @private * @private */ var newContextCallbacks = []; /** * invoke this callback when a new context is added * will be invoked initially with the first context * @private * @static * @param {function(AudioContext)} callback the callback to be invoked * with the audio context */ Tone._initAudioContext = function (callback) { //invoke the callback with the existing AudioContext callback(Tone.context); //add it to the array newContextCallbacks.push(callback); }; /** * Tone automatically creates a context on init, but if you are working * with other libraries which also create an AudioContext, it can be * useful to set your own. If you are going to set your own context, * be sure to do it at the start of your code, before creating any objects. * @static * @param {AudioContext} ctx The new audio context to set */ Tone.setContext = function (ctx) { //set the prototypes Tone.prototype.context = ctx; Tone.context = ctx; //invoke all the callbacks for (var i = 0; i < newContextCallbacks.length; i++) { newContextCallbacks[i](ctx); } }; /** * Bind this to a touchstart event to start the audio on mobile devices. * <br> * http://stackoverflow.com/questions/12517000/no-sound-on-ios-6-web-audio-api/12569290#12569290 * @static */ Tone.startMobile = function () { var osc = Tone.context.createOscillator(); var silent = Tone.context.createGain(); silent.gain.value = 0; osc.connect(silent); silent.connect(Tone.context.destination); var now = Tone.context.currentTime; osc.start(now); osc.stop(now + 1); }; //setup the context Tone._initAudioContext(function (audioContext) { //set the blockTime Tone.prototype.blockTime = 128 / audioContext.sampleRate; _silentNode = audioContext.createGain(); _silentNode.gain.value = 0; _silentNode.connect(audioContext.destination); }); Tone.version = 'r6'; console.log('%c * Tone.js ' + Tone.version + ' * ', 'background: #000; color: #fff'); return Tone; }); Module(function (Tone) { /** * @class Base class for all Signals. Used Internally. * * @constructor * @extends {Tone} */ Tone.SignalBase = function () { }; Tone.extend(Tone.SignalBase); /** * When signals connect to other signals or AudioParams, * they take over the output value of that signal or AudioParam. * For all other nodes, the behavior is the same as a default <code>connect</code>. * * @override * @param {AudioParam|AudioNode|Tone.Signal|Tone} node * @param {number} [outputNumber=0] The output number to connect from. * @param {number} [inputNumber=0] The input number to connect to. * @returns {Tone.SignalBase} this */ Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { //zero it out so that the signal can have full control if (Tone.Signal && Tone.Signal === node.constructor || Tone.Param && Tone.Param === node.constructor || Tone.TimelineSignal && Tone.TimelineSignal === node.constructor) { //cancel changes node._param.cancelScheduledValues(0); //reset the value node._param.value = 0; //mark the value as overridden node.overridden = true; } else if (node instanceof AudioParam) { node.cancelScheduledValues(0); node.value = 0; } Tone.prototype.connect.call(this, node, outputNumber, inputNumber); return this; }; return Tone.SignalBase; }); Module(function (Tone) { /** * @class Wraps the native Web Audio API * [WaveShaperNode](http://webaudio.github.io/web-audio-api/#the-waveshapernode-interface). * * @extends {Tone.SignalBase} * @constructor * @param {function|Array|Number} mapping The function used to define the values. * The mapping function should take two arguments: * the first is the value at the current position * and the second is the array position. * If the argument is an array, that array will be * set as the wave shaping function. The input * signal is an AudioRange [-1, 1] value and the output * signal can take on any numerical values. * * @param {Number} [bufferLen=1024] The length of the WaveShaperNode buffer. * @example * var timesTwo = new Tone.WaveShaper(function(val){ * return val * 2; * }, 2048); * @example * //a waveshaper can also be constructed with an array of values * var invert = new Tone.WaveShaper([1, -1]); */ Tone.WaveShaper = function (mapping, bufferLen) { /** * the waveshaper * @type {WaveShaperNode} * @private */ this._shaper = this.input = this.output = this.context.createWaveShaper(); /** * the waveshapers curve * @type {Float32Array} * @private */ this._curve = null; if (Array.isArray(mapping)) { this.curve = mapping; } else if (isFinite(mapping) || this.isUndef(mapping)) { this._curve = new Float32Array(this.defaultArg(mapping, 1024)); } else if (this.isFunction(mapping)) { this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); this.setMap(mapping); } }; Tone.extend(Tone.WaveShaper, Tone.SignalBase); /** * Uses a mapping function to set the value of the curve. * @param {function} mapping The function used to define the values. * The mapping function take two arguments: * the first is the value at the current position * which goes from -1 to 1 over the number of elements * in the curve array. The second argument is the array position. * @returns {Tone.WaveShaper} this * @example * //map the input signal from [-1, 1] to [0, 10] * shaper.setMap(function(val, index){ * return (val + 1) * 5; * }) */ Tone.WaveShaper.prototype.setMap = function (mapping) { for (var i = 0, len = this._curve.length; i < len; i++) { var normalized = i / len * 2 - 1; this._curve[i] = mapping(normalized, i); } this._shaper.curve = this._curve; return this; }; /** * The array to set as the waveshaper curve. For linear curves * array length does not make much difference, but for complex curves * longer arrays will provide smoother interpolation. * @memberOf Tone.WaveShaper# * @type {Array} * @name curve */ Object.defineProperty(Tone.WaveShaper.prototype, 'curve', { get: function () { return this._shaper.curve; }, set: function (mapping) { this._curve = new Float32Array(mapping); this._shaper.curve = this._curve; } }); /** * Specifies what type of oversampling (if any) should be used when * applying the shaping curve. Can either be "none", "2x" or "4x". * @memberOf Tone.WaveShaper# * @type {string} * @name oversample */ Object.defineProperty(Tone.WaveShaper.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { if ([ 'none', '2x', '4x' ].indexOf(oversampling) !== -1) { this._shaper.oversample = oversampling; } else { throw new Error('invalid oversampling: ' + oversampling); } } }); /** * Clean up. * @returns {Tone.WaveShaper} this */ Tone.WaveShaper.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._shaper.disconnect(); this._shaper = null; this._curve = null; return this; }; return Tone.WaveShaper; }); Module(function (Tone) { /////////////////////////////////////////////////////////////////////////// // TYPES /////////////////////////////////////////////////////////////////////////// /** * Units which a value can take on. * @enum {String} */ Tone.Type = { /** * The default value is a number which can take on any value between [-Infinity, Infinity] */ Default: 'number', /** * Time can be described in a number of ways. Read more [Time](https://github.com/Tonejs/Tone.js/wiki/Time). * * <ul> * <li>Numbers, which will be taken literally as the time (in seconds).</li> * <li>Notation, ("4n", "8t") describes time in BPM and time signature relative values.</li> * <li>TransportTime, ("4:3:2") will also provide tempo and time signature relative times * in the form BARS:QUARTERS:SIXTEENTHS.</li> * <li>Frequency, ("8hz") is converted to the length of the cycle in seconds.</li> * <li>Now-Relative, ("+1") prefix any of the above with "+" and it will be interpreted as * "the current time plus whatever expression follows".</li> * <li>Expressions, ("3:0 + 2 - (1m / 7)") any of the above can also be combined * into a mathematical expression which will be evaluated to compute the desired time.</li> * <li>No Argument, for methods which accept time, no argument will be interpreted as * "now" (i.e. the currentTime).</li> * </ul> * * @typedef {Time} */ Time: 'time', /** * Frequency can be described similar to time, except ultimately the * values are converted to frequency instead of seconds. A number * is taken literally as the value in hertz. Additionally any of the * Time encodings can be used. Note names in the form * of NOTE OCTAVE (i.e. C4) are also accepted and converted to their * frequency value. * @typedef {Frequency} */ Frequency: 'frequency', /** * Normal values are within the range [0, 1]. * @typedef {NormalRange} */ NormalRange: 'normalRange', /** * AudioRange values are between [-1, 1]. * @typedef {AudioRange} */ AudioRange: 'audioRange', /** * Decibels are a logarithmic unit of measurement which is useful for volume * because of the logarithmic way that we perceive loudness. 0 decibels * means no change in volume. -10db is approximately half as loud and 10db * is twice is loud. * @typedef {Decibels} */ Decibels: 'db', /** * Half-step note increments, i.e. 12 is an octave above the root. and 1 is a half-step up. * @typedef {Interval} */ Interval: 'interval', /** * Beats per minute. * @typedef {BPM} */ BPM: 'bpm', /** * The value must be greater than or equal to 0. * @typedef {Positive} */ Positive: 'positive', /** * A cent is a hundredth of a semitone. * @typedef {Cents} */ Cents: 'cents', /** * Angle between 0 and 360. * @typedef {Degrees} */ Degrees: 'degrees', /** * A number representing a midi note. * @typedef {MIDI} */ MIDI: 'midi', /** * A colon-separated representation of time in the form of * BARS:QUARTERS:SIXTEENTHS. * @typedef {TransportTime} */ TransportTime: 'transportTime', /** * Ticks are the basic subunit of the Transport. They are * the smallest unit of time that the Transport supports. * @typedef {Ticks} */ Ticks: 'tick', /** * A frequency represented by a letter name, * accidental and octave. This system is known as * [Scientific Pitch Notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation). * @typedef {Note} */ Note: 'note', /** * One millisecond is a thousandth of a second. * @typedef {Milliseconds} */ Milliseconds: 'milliseconds', /** * A string representing a duration relative to a measure. * <ul> * <li>"4n" = quarter note</li> * <li>"2m" = two measures</li> * <li>"8t" = eighth-note triplet</li> * </ul> * @typedef {Notation} */ Notation: 'notation' }; /////////////////////////////////////////////////////////////////////////// // MATCHING TESTS /////////////////////////////////////////////////////////////////////////// /** * Test if a function is "now-relative", i.e. starts with "+". * * @param {String} str The string to test * @return {boolean} * @method isNowRelative * @lends Tone.prototype.isNowRelative */ Tone.prototype.isNowRelative = function () { var nowRelative = new RegExp(/^\s*\+(.)+/i); return function (note) { return nowRelative.test(note); }; }(); /** * Tests if a string is in Ticks notation. * * @param {String} str The string to test * @return {boolean} * @method isTicks * @lends Tone.prototype.isTicks */ Tone.prototype.isTicks = function () { var tickFormat = new RegExp(/^\d+i$/i); return function (note) { return tickFormat.test(note); }; }(); /** * Tests if a string is musical notation. * i.e.: * <ul> * <li>4n = quarter note</li> * <li>2m = two measures</li> * <li>8t = eighth-note triplet</li> * </ul> * * @param {String} str The string to test * @return {boolean} * @method isNotation * @lends Tone.prototype.isNotation */ Tone.prototype.isNotation = function () { var notationFormat = new RegExp(/^[0-9]+[mnt]$/i); return function (note) { return notationFormat.test(note); }; }(); /** * Test if a string is in the transportTime format. * "Bars:Beats:Sixteenths" * @param {String} transportTime * @return {boolean} * @method isTransportTime * @lends Tone.prototype.isTransportTime */ Tone.prototype.isTransportTime = function () { var transportTimeFormat = new RegExp(/^(\d+(\.\d+)?\:){1,2}(\d+(\.\d+)?)?$/i); return function (transportTime) { return transportTimeFormat.test(transportTime); }; }(); /** * Test if a string is in Scientific Pitch Notation: i.e. "C4". * @param {String} note The note to test * @return {boolean} true if it's in the form of a note * @method isNote * @lends Tone.prototype.isNote * @function */ Tone.prototype.isNote = function () { var noteFormat = new RegExp(/^[a-g]{1}(b|#|x|bb)?-?[0-9]+$/i); return function (note) { return noteFormat.test(note); }; }(); /** * Test if the input is in the format of number + hz * i.e.: 10hz * * @param {String} freq * @return {boolean} * @function */ Tone.prototype.isFrequency = function () { var freqFormat = new RegExp(/^\d*\.?\d+hz$/i); return function (freq) { return freqFormat.test(freq); }; }(); /////////////////////////////////////////////////////////////////////////// // TO SECOND CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * @private * @return {Object} The Transport's BPM if the Transport exists, * otherwise returns reasonable defaults. */ function getTransportBpm() { if (Tone.Transport && Tone.Transport.bpm) { return Tone.Transport.bpm.value; } else { return 120; } } /** * @private * @return {Object} The Transport's Time Signature if the Transport exists, * otherwise returns reasonable defaults. */ function getTransportTimeSignature() { if (Tone.Transport && Tone.Transport.timeSignature) { return Tone.Transport.timeSignature; } else { return 4; } } /** * * convert notation format strings to seconds * * @param {String} notation * @param {BPM=} bpm * @param {number=} timeSignature * @return {number} * */ Tone.prototype.notationToSeconds = function (notation, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var beatTime = 60 / bpm; //special case: 1n = 1m if (notation === '1n') { notation = '1m'; } var subdivision = parseInt(notation, 10); var beats = 0; if (subdivision === 0) { beats = 0; } var lastLetter = notation.slice(-1); if (lastLetter === 't') { beats = 4 / subdivision * 2 / 3; } else if (lastLetter === 'n') { beats = 4 / subdivision; } else if (lastLetter === 'm') { beats = subdivision * timeSignature; } else { beats = 0; } return beatTime * beats; }; /** * convert transportTime into seconds. * * ie: 4:2:3 == 4 measures + 2 quarters + 3 sixteenths * * @param {TransportTime} transportTime * @param {BPM=} bpm * @param {number=} timeSignature * @return {number} seconds */ Tone.prototype.transportTimeToSeconds = function (transportTime, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var measures = 0; var quarters = 0; var sixteenths = 0; var split = transportTime.split(':'); if (split.length === 2) { measures = parseFloat(split[0]); quarters = parseFloat(split[1]); } else if (split.length === 1) { quarters = parseFloat(split[0]); } else if (split.length === 3) { measures = parseFloat(split[0]); quarters = parseFloat(split[1]); sixteenths = parseFloat(split[2]); } var beats = measures * timeSignature + quarters + sixteenths / 4; return beats * (60 / bpm); }; /** * Convert ticks into seconds * @param {Ticks} ticks * @param {BPM=} bpm * @return {number} seconds */ Tone.prototype.ticksToSeconds = function (ticks, bpm) { if (this.isUndef(Tone.Transport)) { return 0; } ticks = parseFloat(ticks); bpm = this.defaultArg(bpm, getTransportBpm()); var tickTime = 60 / bpm / Tone.Transport.PPQ; return tickTime * ticks; }; /** * Convert a frequency into seconds. * Accepts numbers and strings: i.e. "10hz" or * 10 both return 0.1. * * @param {Frequency} freq * @return {number} */ Tone.prototype.frequencyToSeconds = function (freq) { return 1 / parseFloat(freq); }; /** * Convert a sample count to seconds. * @param {number} samples * @return {number} */ Tone.prototype.samplesToSeconds = function (samples) { return samples / this.context.sampleRate; }; /** * Convert from seconds to samples. * @param {number} seconds * @return {number} The number of samples */ Tone.prototype.secondsToSamples = function (seconds) { return seconds * this.context.sampleRate; }; /////////////////////////////////////////////////////////////////////////// // FROM SECOND CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Convert seconds to transportTime in the form * "measures:quarters:sixteenths" * * @param {Number} seconds * @param {BPM=} bpm * @param {Number=} timeSignature * @return {TransportTime} */ Tone.prototype.secondsToTransportTime = function (seconds, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var quarterTime = 60 / bpm; var quarters = seconds / quarterTime; var measures = Math.floor(quarters / timeSignature); var sixteenths = quarters % 1 * 4; quarters = Math.floor(quarters) % timeSignature; var progress = [ measures, quarters, sixteenths ]; return progress.join(':'); }; /** * Convert a number in seconds to a frequency. * @param {number} seconds * @return {number} */ Tone.prototype.secondsToFrequency = function (seconds) { return 1 / seconds; }; /////////////////////////////////////////////////////////////////////////// // GENERALIZED CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Convert seconds to the closest transportTime in the form * measures:quarters:sixteenths * * @method toTransportTime * * @param {Time} time * @param {BPM=} bpm * @param {number=} timeSignature * @return {TransportTime} * * @lends Tone.prototype.toTransportTime */ Tone.prototype.toTransportTime = function (time, bpm, timeSignature) { var seconds = this.toSeconds(time); return this.secondsToTransportTime(seconds, bpm, timeSignature); }; /** * Convert a frequency representation into a number. * * @param {Frequency} freq * @param {number=} now if passed in, this number will be * used for all 'now' relative timings * @return {number} the frequency in hertz */ Tone.prototype.toFrequency = function (freq, now) { if (this.isFrequency(freq)) { return parseFloat(freq); } else if (this.isNotation(freq) || this.isTransportTime(freq)) { return this.secondsToFrequency(this.toSeconds(freq, now)); } else if (this.isNote(freq)) { return this.noteToFrequency(freq); } else { return freq; } }; /** * Convert the time representation into ticks. * Now-Relative timing will be relative to the current * Tone.Transport.ticks. * @param {Time} time * @return {Ticks} */ Tone.prototype.toTicks = function (time) { if (this.isUndef(Tone.Transport)) { return 0; } var bpm = Tone.Transport.bpm.value; //get the seconds var plusNow = 0; if (this.isNowRelative(time)) { time = time.replace('+', ''); plusNow = Tone.Transport.ticks; } else if (this.isUndef(time)) { return Tone.Transport.ticks; } var seconds = this.toSeconds(time); var quarter = 60 / bpm; var quarters = seconds / quarter; var tickNum = quarters * Tone.Transport.PPQ; //align the tick value return Math.round(tickNum + plusNow); }; /** * convert a time into samples * * @param {Time} time * @return {number} */ Tone.prototype.toSamples = function (time) { var seconds = this.toSeconds(time); return Math.round(seconds * this.context.sampleRate); }; /** * Convert Time into seconds. * * Unlike the method which it overrides, this takes into account * transporttime and musical notation. * * Time : 1.40 * Notation: 4n|1m|2t * TransportTime: 2:4:1 (measure:quarters:sixteens) * Now Relative: +3n * Math: 3n+16n or even complicated expressions ((3n*2)/6 + 1) * * @override * @param {Time} time * @param {number=} now if passed in, this number will be * used for all 'now' relative timings * @return {number} */ Tone.prototype.toSeconds = function (time, now) { now = this.defaultArg(now, this.now()); if (this.isNumber(time)) { return time; //assuming that it's seconds } else if (this.isString(time)) { var plusTime = 0; if (this.isNowRelative(time)) { time = time.replace('+', ''); plusTime = now; } var betweenParens = time.match(/\(([^)(]+)\)/g); if (betweenParens) { //evaluate the expressions between the parenthesis for (var j = 0; j < betweenParens.length; j++) { //remove the parens var symbol = betweenParens[j].replace(/[\(\)]/g, ''); var symbolVal = this.toSeconds(symbol); time = time.replace(betweenParens[j], symbolVal); } } //test if it is quantized if (time.indexOf('@') !== -1) { var quantizationSplit = time.split('@'); if (!this.isUndef(Tone.Transport)) { var toQuantize = quantizationSplit[0].trim(); //if there's no argument it should be evaluated as the current time if (toQuantize === '') { toQuantize = undefined; } //if it's now-relative, it should be evaluated by `quantize` if (plusTime > 0) { toQuantize = '+' + toQuantize; plusTime = 0; } var subdivision = quantizationSplit[1].trim(); time = Tone.Transport.quantize(toQuantize, subdivision); } else { throw new Error('quantization requires Tone.Transport'); } } else { var components = time.split(/[\(\)\-\+\/\*]/); if (components.length > 1) { var originalTime = time; for (var i = 0; i < components.length; i++) { var symb = components[i].trim(); if (symb !== '') { var val = this.toSeconds(symb); time = time.replace(symb, val); } } try { //eval is evil time = eval(time); // jshint ignore:line } catch (e) { throw new EvalError('cannot evaluate Time: ' + originalTime); } } else if (this.isNotation(time)) { time = this.notationToSeconds(time); } else if (this.isTransportTime(time)) { time = this.transportTimeToSeconds(time); } else if (this.isFrequency(time)) { time = this.frequencyToSeconds(time); } else if (this.isTicks(time)) { time = this.ticksToSeconds(time); } else { time = parseFloat(time); } } return time + plusTime; } else { return now; } }; /** * Convert a Time to Notation. Values will be thresholded to the nearest 128th note. * @param {Time} time * @param {BPM=} bpm * @param {number=} timeSignature * @return {Notation} */ Tone.prototype.toNotation = function (time, bpm, timeSignature) { var testNotations = [ '1m', '2n', '4n', '8n', '16n', '32n', '64n', '128n' ]; var retNotation = toNotationHelper.call(this, time, bpm, timeSignature, testNotations); //try the same thing but with tripelets var testTripletNotations = [ '1m', '2n', '2t', '4n', '4t', '8n', '8t', '16n', '16t', '32n', '32t', '64n', '64t', '128n' ]; var retTripletNotation = toNotationHelper.call(this, time, bpm, timeSignature, testTripletNotations); //choose the simpler expression of the two if (retTripletNotation.split('+').length < retNotation.split('+').length) { return retTripletNotation; } else { return retNotation; } }; /** * Helper method for Tone.toNotation * @private */ function toNotationHelper(time, bpm, timeSignature, testNotations) { var seconds = this.toSeconds(time); var threshold = this.notationToSeconds(testNotations[testNotations.length - 1], bpm, timeSignature); var retNotation = ''; for (var i = 0; i < testNotations.length; i++) { var notationTime = this.notationToSeconds(testNotations[i], bpm, timeSignature); //account for floating point errors (i.e. round up if the value is 0.999999) var multiple = seconds / notationTime; var floatingPointError = 0.000001; if (1 - multiple % 1 < floatingPointError) { multiple += floatingPointError; } multiple = Math.floor(multiple); if (multiple > 0) { if (multiple === 1) { retNotation += testNotations[i]; } else { retNotation += multiple.toString() + '*' + testNotations[i]; } seconds -= multiple * notationTime; if (seconds < threshold) { break; } else { retNotation += ' + '; } } } if (retNotation === '') { retNotation = '0'; } return retNotation; } /** * Convert the given value from the type specified by units * into a number. * @param {*} val the value to convert * @return {Number} the number which the value should be set to */ Tone.prototype.fromUnits = function (val, units) { if (this.convert || this.isUndef(this.convert)) { switch (units) { case Tone.Type.Time: return this.toSeconds(val); case Tone.Type.Frequency: return this.toFrequency(val); case Tone.Type.Decibels: return this.dbToGain(val); case Tone.Type.NormalRange: return Math.min(Math.max(val, 0), 1); case Tone.Type.AudioRange: return Math.min(Math.max(val, -1), 1); case Tone.Type.Positive: return Math.max(val, 0); default: return val; } } else { return val; } }; /** * Convert a number to the specified units. * @param {number} val the value to convert * @return {number} */ Tone.prototype.toUnits = function (val, units) { if (this.convert || this.isUndef(this.convert)) { switch (units) { case Tone.Type.Decibels: return this.gainToDb(val); default: return val; } } else { return val; } }; /////////////////////////////////////////////////////////////////////////// // FREQUENCY CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Note to scale index * @type {Object} */ var noteToScaleIndex = { 'cbb': -2, 'cb': -1, 'c': 0, 'c#': 1, 'cx': 2, 'dbb': 0, 'db': 1, 'd': 2, 'd#': 3, 'dx': 4, 'ebb': 2, 'eb': 3, 'e': 4, 'e#': 5, 'ex': 6, 'fbb': 3, 'fb': 4, 'f': 5, 'f#': 6, 'fx': 7, 'gbb': 5, 'gb': 6, 'g': 7, 'g#': 8, 'gx': 9, 'abb': 7, 'ab': 8, 'a': 9, 'a#': 10, 'ax': 11, 'bbb': 9, 'bb': 10, 'b': 11, 'b#': 12, 'bx': 13 }; /** * scale index to note (sharps) * @type {Array} */ var scaleIndexToNote = [ 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B' ]; /** * The [concert pitch](https://en.wikipedia.org/wiki/Concert_pitch, * A4's values in Hertz. * @type {Frequency} * @static */ Tone.A4 = 440; /** * Convert a note name to frequency. * @param {String} note * @return {number} * @example * var freq = tone.noteToFrequency("A4"); //returns 440 */ Tone.prototype.noteToFrequency = function (note) { //break apart the note by frequency and octave var parts = note.split(/(-?\d+)/); if (parts.length === 3) { var index = noteToScaleIndex[parts[0].toLowerCase()]; var octave = parts[1]; var noteNumber = index + (parseInt(octave, 10) + 1) * 12; return this.midiToFrequency(noteNumber); } else { return 0; } }; /** * Convert a frequency to a note name (i.e. A4, C#5). * @param {number} freq * @return {String} */ Tone.prototype.frequencyToNote = function (freq) { var log = Math.log(freq / Tone.A4) / Math.LN2; var noteNumber = Math.round(12 * log) + 57; var octave = Math.floor(noteNumber / 12); if (octave < 0) { noteNumber += -12 * octave; } var noteName = scaleIndexToNote[noteNumber % 12]; return noteName + octave.toString(); }; /** * Convert an interval (in semitones) to a frequency ratio. * * @param {Interval} interval the number of semitones above the base note * @return {number} the frequency ratio * @example * tone.intervalToFrequencyRatio(0); // returns 1 * tone.intervalToFrequencyRatio(12); // returns 2 */ Tone.prototype.intervalToFrequencyRatio = function (interval) { return Math.pow(2, interval / 12); }; /** * Convert a midi note number into a note name. * * @param {MIDI} midiNumber the midi note number * @return {String} the note's name and octave * @example * tone.midiToNote(60); // returns "C3" */ Tone.prototype.midiToNote = function (midiNumber) { var octave = Math.floor(midiNumber / 12) - 1; var note = midiNumber % 12; return scaleIndexToNote[note] + octave; }; /** * Convert a note to it's midi value. * * @param {String} note the note name (i.e. "C3") * @return {MIDI} the midi value of that note * @example * tone.noteToMidi("C3"); // returns 60 */ Tone.prototype.noteToMidi = function (note) { //break apart the note by frequency and octave var parts = note.split(/(\d+)/); if (parts.length === 3) { var index = noteToScaleIndex[parts[0].toLowerCase()]; var octave = parts[1]; return index + (parseInt(octave, 10) + 1) * 12; } else { return 0; } }; /** * Convert a MIDI note to frequency value. * * @param {MIDI} midi The midi number to convert. * @return {Frequency} the corresponding frequency value * @example * tone.midiToFrequency(57); // returns 440 */ Tone.prototype.midiToFrequency = function (midi) { return Tone.A4 * Math.pow(2, (midi - 69) / 12); }; return Tone; }); Module(function (Tone) { /** * @class Tone.Param wraps the native Web Audio's AudioParam to provide * additional unit conversion functionality. It also * serves as a base-class for classes which have a single, * automatable parameter. * @extends {Tone} * @param {AudioParam} param The parameter to wrap. * @param {Tone.Type} units The units of the audio param. * @param {Boolean} convert If the param should be converted. */ Tone.Param = function () { var options = this.optionsObject(arguments, [ 'param', 'units', 'convert' ], Tone.Param.defaults); /** * The native parameter to control * @type {AudioParam} * @private */ this._param = this.input = options.param; /** * The units of the parameter * @type {Tone.Type} */ this.units = options.units; /** * If the value should be converted or not * @type {Boolean} */ this.convert = options.convert; /** * True if the signal value is being overridden by * a connected signal. * @readOnly * @type {boolean} * @private */ this.overridden = false; if (!this.isUndef(options.value)) { this.value = options.value; } }; Tone.extend(Tone.Param); /** * Defaults * @type {Object} * @const */ Tone.Param.defaults = { 'units': Tone.Type.Default, 'convert': true, 'param': undefined }; /** * The current value of the parameter. * @memberOf Tone.Param# * @type {Number} * @name value */ Object.defineProperty(Tone.Param.prototype, 'value', { get: function () { return this._toUnits(this._param.value); }, set: function (value) { var convertedVal = this._fromUnits(value); this._param.value = convertedVal; } }); /** * Convert the given value from the type specified by Tone.Param.units * into the destination value (such as Gain or Frequency). * @private * @param {*} val the value to convert * @return {number} the number which the value should be set to */ Tone.Param.prototype._fromUnits = function (val) { if (this.convert || this.isUndef(this.convert)) { switch (this.units) { case Tone.Type.Time: return this.toSeconds(val); case Tone.Type.Frequency: return this.toFrequency(val); case Tone.Type.Decibels: return this.dbToGain(val); case Tone.Type.NormalRange: return Math.min(Math.max(val, 0), 1); case Tone.Type.AudioRange: return Math.min(Math.max(val, -1), 1); case Tone.Type.Positive: return Math.max(val, 0); default: return val; } } else { return val; } }; /** * Convert the parameters value into the units specified by Tone.Param.units. * @private * @param {number} val the value to convert * @return {number} */ Tone.Param.prototype._toUnits = function (val) { if (this.convert || this.isUndef(this.convert)) { switch (this.units) { case Tone.Type.Decibels: return this.gainToDb(val); default: return val; } } else { return val; } }; /** * the minimum output value * @type {Number} * @private */ Tone.Param.prototype._minOutput = 0.00001; /** * Schedules a parameter value change at the given time. * @param {*} value The value to set the signal. * @param {Time} time The time when the change should occur. * @returns {Tone.Param} this * @example * //set the frequency to "G4" in exactly 1 second from now. * freq.setValueAtTime("G4", "+1"); */ Tone.Param.prototype.setValueAtTime = function (value, time) { value = this._fromUnits(value); this._param.setValueAtTime(value, this.toSeconds(time)); return this; }; /** * Creates a schedule point with the current value at the current time. * This is useful for creating an automation anchor point in order to * schedule changes from the current value. * * @param {number=} now (Optionally) pass the now value in. * @returns {Tone.Param} this */ Tone.Param.prototype.setRampPoint = function (now) { now = this.defaultArg(now, this.now()); var currentVal = this._param.value; this._param.setValueAtTime(currentVal, now); return this; }; /** * Schedules a linear continuous change in parameter value from the * previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.Param} this */ Tone.Param.prototype.linearRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); this._param.linearRampToValueAtTime(value, this.toSeconds(endTime)); return this; }; /** * Schedules an exponential continuous change in parameter value from * the previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.Param} this */ Tone.Param.prototype.exponentialRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); this._param.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); return this; }; /** * Schedules an exponential continuous change in parameter value from * the current time and current value to the given value over the * duration of the rampTime. * * @param {number} value The value to ramp to. * @param {Time} rampTime the time that it takes the * value to ramp from it's current value * @returns {Tone.Param} this * @example * //exponentially ramp to the value 2 over 4 seconds. * signal.exponentialRampToValue(2, 4); */ Tone.Param.prototype.exponentialRampToValue = function (value, rampTime) { var now = this.now(); // exponentialRampToValueAt cannot ever ramp from 0, apparently. // More info: https://bugzilla.mozilla.org/show_bug.cgi?id=1125600#c2 var currentVal = this.value; this.setValueAtTime(Math.max(currentVal, this._minOutput), now); this.exponentialRampToValueAtTime(value, now + this.toSeconds(rampTime)); return this; }; /** * Schedules an linear continuous change in parameter value from * the current time and current value to the given value over the * duration of the rampTime. * * @param {number} value The value to ramp to. * @param {Time} rampTime the time that it takes the * value to ramp from it's current value * @returns {Tone.Param} this * @example * //linearly ramp to the value 4 over 3 seconds. * signal.linearRampToValue(4, 3); */ Tone.Param.prototype.linearRampToValue = function (value, rampTime) { var now = this.now(); this.setRampPoint(now); this.linearRampToValueAtTime(value, now + this.toSeconds(rampTime)); return this; }; /** * Start exponentially approaching the target value at the given time with * a rate having the given time constant. * @param {number} value * @param {Time} startTime * @param {number} timeConstant * @returns {Tone.Param} this */ Tone.Param.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value = this._fromUnits(value); // The value will never be able to approach without timeConstant > 0. // http://www.w3.org/TR/webaudio/#dfn-setTargetAtTime, where the equation // is described. 0 results in a division by 0. value = Math.max(this._minOutput, value); timeConstant = Math.max(this._minOutput, timeConstant); this._param.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); return this; }; /** * Sets an array of arbitrary parameter values starting at the given time * for the given duration. * * @param {Array} values * @param {Time} startTime * @param {Time} duration * @returns {Tone.Param} this */ Tone.Param.prototype.setValueCurveAtTime = function (values, startTime, duration) { for (var i = 0; i < values.length; i++) { values[i] = this._fromUnits(values[i]); } this._param.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); return this; }; /** * Cancels all scheduled parameter changes with times greater than or * equal to startTime. * * @param {Time} startTime * @returns {Tone.Param} this */ Tone.Param.prototype.cancelScheduledValues = function (startTime) { this._param.cancelScheduledValues(this.toSeconds(startTime)); return this; }; /** * Ramps to the given value over the duration of the rampTime. * Automatically selects the best ramp type (exponential or linear) * depending on the `units` of the signal * * @param {number} value * @param {Time} rampTime the time that it takes the * value to ramp from it's current value * @returns {Tone.Param} this * @example * //ramp to the value either linearly or exponentially * //depending on the "units" value of the signal * signal.rampTo(0, 10); */ Tone.Param.prototype.rampTo = function (value, rampTime) { rampTime = this.defaultArg(rampTime, 0); if (this.units === Tone.Type.Frequency || this.units === Tone.Type.BPM) { this.exponentialRampToValue(value, rampTime); } else { this.linearRampToValue(value, rampTime); } return this; }; /** * Clean up * @returns {Tone.Param} this */ Tone.Param.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param = null; return this; }; return Tone.Param; }); Module(function (Tone) { /** * @class A thin wrapper around the Native Web Audio GainNode. * The GainNode is a basic building block of the Web Audio * API and is useful for routing audio and adjusting gains. * @extends {Tone} * @param {Number=} gain The initial gain of the GainNode * @param {Tone.Type=} units The units of the gain parameter. */ Tone.Gain = function () { var options = this.optionsObject(arguments, [ 'gain', 'units' ], Tone.Gain.defaults); /** * The GainNode * @type {GainNode} * @private */ this.input = this.output = this._gainNode = this.context.createGain(); /** * The gain parameter of the gain node. * @type {AudioParam} * @signal */ this.gain = new Tone.Param({ 'param': this._gainNode.gain, 'units': options.units, 'value': options.gain, 'convert': options.convert }); this._readOnly('gain'); }; Tone.extend(Tone.Gain); /** * The defaults * @const * @type {Object} */ Tone.Gain.defaults = { 'gain': 1, 'convert': true }; /** * Clean up. * @return {Tone.Gain} this */ Tone.Gain.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._gainNode.disconnect(); this._gainNode = null; this._writable('gain'); this.gain.dispose(); this.gain = null; }; return Tone.Gain; }); Module(function (Tone) { /** * @class A signal is an audio-rate value. Tone.Signal is a core component of the library. * Unlike a number, Signals can be scheduled with sample-level accuracy. Tone.Signal * has all of the methods available to native Web Audio * [AudioParam](http://webaudio.github.io/web-audio-api/#the-audioparam-interface) * as well as additional conveniences. Read more about working with signals * [here](https://github.com/Tonejs/Tone.js/wiki/Signals). * * @constructor * @extends {Tone.Param} * @param {Number|AudioParam} [value] Initial value of the signal. If an AudioParam * is passed in, that parameter will be wrapped * and controlled by the Signal. * @param {string} [units=Number] unit The units the signal is in. * @example * var signal = new Tone.Signal(10); */ Tone.Signal = function () { var options = this.optionsObject(arguments, [ 'value', 'units' ], Tone.Signal.defaults); /** * The node where the constant signal value is scaled. * @type {GainNode} * @private */ this.output = this._gain = this.context.createGain(); options.param = this._gain.gain; Tone.Param.call(this, options); /** * The node where the value is set. * @type {Tone.Param} * @private */ this.input = this._param = this._gain.gain; //connect the const output to the node output Tone.Signal._constant.chain(this._gain); }; Tone.extend(Tone.Signal, Tone.Param); /** * The default values * @type {Object} * @static * @const */ Tone.Signal.defaults = { 'value': 0, 'units': Tone.Type.Default, 'convert': true }; /** * When signals connect to other signals or AudioParams, * they take over the output value of that signal or AudioParam. * For all other nodes, the behavior is the same as a default <code>connect</code>. * * @override * @param {AudioParam|AudioNode|Tone.Signal|Tone} node * @param {number} [outputNumber=0] The output number to connect from. * @param {number} [inputNumber=0] The input number to connect to. * @returns {Tone.SignalBase} this * @method */ Tone.Signal.prototype.connect = Tone.SignalBase.prototype.connect; /** * dispose and disconnect * @returns {Tone.Signal} this */ Tone.Signal.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._param = null; this._gain.disconnect(); this._gain = null; return this; }; /////////////////////////////////////////////////////////////////////////// // STATIC /////////////////////////////////////////////////////////////////////////// /** * Generates a constant output of 1. * @static * @private * @const * @type {AudioBufferSourceNode} */ Tone.Signal._constant = null; /** * initializer function */ Tone._initAudioContext(function (audioContext) { var buffer = audioContext.createBuffer(1, 128, audioContext.sampleRate); var arr = buffer.getChannelData(0); for (var i = 0; i < arr.length; i++) { arr[i] = 1; } Tone.Signal._constant = audioContext.createBufferSource(); Tone.Signal._constant.channelCount = 1; Tone.Signal._constant.channelCountMode = 'explicit'; Tone.Signal._constant.buffer = buffer; Tone.Signal._constant.loop = true; Tone.Signal._constant.start(0); Tone.Signal._constant.noGC(); }); return Tone.Signal; }); Module(function (Tone) { /** * @class A Timeline class for scheduling and maintaining state * along a timeline. All events must have a "time" property. * Internally, events are stored in time order for fast * retrieval. * @extends {Tone} * @param {Positive} [memory=Infinity] The number of previous events that are retained. */ Tone.Timeline = function () { var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults); /** * The array of scheduled timeline events * @type {Array} * @private */ this._timeline = []; /** * An array of items to remove from the list. * @type {Array} * @private */ this._toRemove = []; /** * Flag if the tieline is mid iteration * @private * @type {Boolean} */ this._iterating = false; /** * The memory of the timeline, i.e. * how many events in the past it will retain * @type {Positive} */ this.memory = options.memory; }; Tone.extend(Tone.Timeline); /** * the default parameters * @static * @const */ Tone.Timeline.defaults = { 'memory': Infinity }; /** * The number of items in the timeline. * @type {Number} * @memberOf Tone.Timeline# * @name length * @readOnly */ Object.defineProperty(Tone.Timeline.prototype, 'length', { get: function () { return this._timeline.length; } }); /** * Insert an event object onto the timeline. Events must have a "time" attribute. * @param {Object} event The event object to insert into the * timeline. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.addEvent = function (event) { //the event needs to have a time attribute if (this.isUndef(event.time)) { throw new Error('events must have a time attribute'); } event.time = this.toSeconds(event.time); if (this._timeline.length) { var index = this._search(event.time); this._timeline.splice(index + 1, 0, event); } else { this._timeline.push(event); } //if the length is more than the memory, remove the previous ones if (this.length > this.memory) { var diff = this.length - this.memory; this._timeline.splice(0, diff); } return this; }; /** * Remove an event from the timeline. * @param {Object} event The event object to remove from the list. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.removeEvent = function (event) { if (this._iterating) { this._toRemove.push(event); } else { var index = this._timeline.indexOf(event); if (index !== -1) { this._timeline.splice(index, 1); } } return this; }; /** * Get the event whose time is less than or equal to the given time. * @param {Number} time The time to query. * @returns {Object} The event object set after that time. */ Tone.Timeline.prototype.getEvent = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index !== -1) { return this._timeline[index]; } else { return null; } }; /** * Get the event which is scheduled after the given time. * @param {Number} time The time to query. * @returns {Object} The event object after the given time */ Tone.Timeline.prototype.getEventAfter = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index + 1 < this._timeline.length) { return this._timeline[index + 1]; } else { return null; } }; /** * Get the event before the event at the given time. * @param {Number} time The time to query. * @returns {Object} The event object before the given time */ Tone.Timeline.prototype.getEventBefore = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index - 1 >= 0) { return this._timeline[index - 1]; } else { return null; } }; /** * Cancel events after the given time * @param {Time} time The time to query. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.cancel = function (after) { if (this._timeline.length > 1) { after = this.toSeconds(after); var index = this._search(after); if (index >= 0) { this._timeline = this._timeline.slice(0, index); } else { this._timeline = []; } } else if (this._timeline.length === 1) { //the first item's time if (this._timeline[0].time >= after) { this._timeline = []; } } return this; }; /** * Cancel events before or equal to the given time. * @param {Time} time The time to cancel before. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.cancelBefore = function (time) { if (this._timeline.length) { time = this.toSeconds(time); var index = this._search(time); if (index >= 0) { this._timeline = this._timeline.slice(index + 1); } } return this; }; /** * Does a binary serach on the timeline array and returns the * event which is after or equal to the time. * @param {Number} time * @return {Number} the index in the timeline array * @private */ Tone.Timeline.prototype._search = function (time) { var beginning = 0; var len = this._timeline.length; var end = len; // continue searching while [imin,imax] is not empty while (beginning <= end && beginning < len) { // calculate the midpoint for roughly equal partition var midPoint = Math.floor(beginning + (end - beginning) / 2); var event = this._timeline[midPoint]; if (event.time === time) { //choose the last one that has the same time for (var i = midPoint; i < this._timeline.length; i++) { var testEvent = this._timeline[i]; if (testEvent.time === time) { midPoint = i; } } return midPoint; } else if (event.time > time) { //search lower end = midPoint - 1; } else if (event.time < time) { //search upper beginning = midPoint + 1; } } return beginning - 1; }; /** * Internal iterator. Applies extra safety checks for * removing items from the array. * @param {Function} callback * @param {Number=} lowerBound * @param {Number=} upperBound * @private */ Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) { this._iterating = true; lowerBound = this.defaultArg(lowerBound, 0); upperBound = this.defaultArg(upperBound, this._timeline.length - 1); for (var i = lowerBound; i <= upperBound; i++) { callback(this._timeline[i]); } this._iterating = false; if (this._toRemove.length > 0) { for (var j = 0; j < this._toRemove.length; j++) { var index = this._timeline.indexOf(this._toRemove[j]); if (index !== -1) { this._timeline.splice(index, 1); } } this._toRemove = []; } }; /** * Iterate over everything in the array * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEach = function (callback) { this._iterate(callback); return this; }; /** * Iterate over everything in the array at or before the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachBefore = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var upperBound = this._search(time); if (upperBound !== -1) { this._iterate(callback, 0, upperBound); } return this; }; /** * Iterate over everything in the array after the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachAfter = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var lowerBound = this._search(time); this._iterate(callback, lowerBound + 1); return this; }; /** * Iterate over everything in the array at or after the given time. Similar to * forEachAfter, but includes the item(s) at the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachFrom = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var lowerBound = this._search(time); //work backwards until the event time is less than time while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) { lowerBound--; } this._iterate(callback, lowerBound + 1); return this; }; /** * Iterate over everything in the array at the given time * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachAtTime = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var upperBound = this._search(time); if (upperBound !== -1) { this._iterate(function (event) { if (event.time === time) { callback(event); } }, 0, upperBound); } return this; }; /** * Clean up. * @return {Tone.Timeline} this */ Tone.Timeline.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._timeline = null; this._toRemove = null; }; return Tone.Timeline; }); Module(function (Tone) { /** * @class A signal which adds the method getValueAtTime. * Code and inspiration from https://github.com/jsantell/web-audio-automation-timeline * @extends {Tone.Param} * @param {Number=} value The initial value of the signal * @param {String=} units The conversion units of the signal. */ Tone.TimelineSignal = function () { var options = this.optionsObject(arguments, [ 'value', 'units' ], Tone.Signal.defaults); //constructors Tone.Signal.apply(this, options); options.param = this._param; Tone.Param.call(this, options); /** * The scheduled events * @type {Tone.Timeline} * @private */ this._events = new Tone.Timeline(10); /** * The initial scheduled value * @type {Number} * @private */ this._initial = this._fromUnits(this._param.value); }; Tone.extend(Tone.TimelineSignal, Tone.Param); /** * The event types of a schedulable signal. * @enum {String} */ Tone.TimelineSignal.Type = { Linear: 'linear', Exponential: 'exponential', Target: 'target', Set: 'set' }; /** * The current value of the signal. * @memberOf Tone.TimelineSignal# * @type {Number} * @name value */ Object.defineProperty(Tone.TimelineSignal.prototype, 'value', { get: function () { return this._toUnits(this._param.value); }, set: function (value) { var convertedVal = this._fromUnits(value); this._initial = convertedVal; this._param.value = convertedVal; } }); /////////////////////////////////////////////////////////////////////////// // SCHEDULING /////////////////////////////////////////////////////////////////////////// /** * Schedules a parameter value change at the given time. * @param {*} value The value to set the signal. * @param {Time} time The time when the change should occur. * @returns {Tone.TimelineSignal} this * @example * //set the frequency to "G4" in exactly 1 second from now. * freq.setValueAtTime("G4", "+1"); */ Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) { value = this._fromUnits(value); startTime = this.toSeconds(startTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Set, 'value': value, 'time': startTime }); //invoke the original event this._param.setValueAtTime(value, startTime); return this; }; /** * Schedules a linear continuous change in parameter value from the * previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); endTime = this.toSeconds(endTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Linear, 'value': value, 'time': endTime }); this._param.linearRampToValueAtTime(value, endTime); return this; }; /** * Schedules an exponential continuous change in parameter value from * the previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); endTime = this.toSeconds(endTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Exponential, 'value': value, 'time': endTime }); this._param.exponentialRampToValueAtTime(value, endTime); return this; }; /** * Start exponentially approaching the target value at the given time with * a rate having the given time constant. * @param {number} value * @param {Time} startTime * @param {number} timeConstant * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); timeConstant = Math.max(this._minOutput, timeConstant); startTime = this.toSeconds(startTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Target, 'value': value, 'time': startTime, 'constant': timeConstant }); this._param.setTargetAtTime(value, startTime, timeConstant); return this; }; /** * Cancels all scheduled parameter changes with times greater than or * equal to startTime. * * @param {Time} startTime * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) { this._events.cancel(after); this._param.cancelScheduledValues(this.toSeconds(after)); return this; }; /** * Sets the computed value at the given time. This provides * a point from which a linear or exponential curve * can be scheduled after. Will cancel events after * the given time and shorten the currently scheduled * linear or exponential ramp so that it ends at `time` . * This is to avoid discontinuities and clicks in envelopes. * @param {Time} time When to set the ramp point * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.setRampPoint = function (time) { time = this.toSeconds(time); //get the value at the given time var val = this.getValueAtTime(time); //reschedule the next event to end at the given time var after = this._searchAfter(time); if (after) { //cancel the next event(s) this.cancelScheduledValues(time); if (after.type === Tone.TimelineSignal.Type.Linear) { this.linearRampToValueAtTime(val, time); } else if (after.type === Tone.TimelineSignal.Type.Exponential) { this.exponentialRampToValueAtTime(val, time); } } this.setValueAtTime(val, time); return this; }; /** * Do a linear ramp to the given value between the start and finish times. * @param {Number} value The value to ramp to. * @param {Time} start The beginning anchor point to do the linear ramp * @param {Time} finish The ending anchor point by which the value of * the signal will equal the given value. * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) { this.setRampPoint(start); this.linearRampToValueAtTime(value, finish); return this; }; /** * Do a exponential ramp to the given value between the start and finish times. * @param {Number} value The value to ramp to. * @param {Time} start The beginning anchor point to do the exponential ramp * @param {Time} finish The ending anchor point by which the value of * the signal will equal the given value. * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) { this.setRampPoint(start); this.exponentialRampToValueAtTime(value, finish); return this; }; /////////////////////////////////////////////////////////////////////////// // GETTING SCHEDULED VALUES /////////////////////////////////////////////////////////////////////////// /** * Returns the value before or equal to the given time * @param {Number} time The time to query * @return {Object} The event at or before the given time. * @private */ Tone.TimelineSignal.prototype._searchBefore = function (time) { return this._events.getEvent(time); }; /** * The event after the given time * @param {Number} time The time to query. * @return {Object} The next event after the given time * @private */ Tone.TimelineSignal.prototype._searchAfter = function (time) { return this._events.getEventAfter(time); }; /** * Get the scheduled value at the given time. This will * return the unconverted (raw) value. * @param {Number} time The time in seconds. * @return {Number} The scheduled value at the given time. */ Tone.TimelineSignal.prototype.getValueAtTime = function (time) { var after = this._searchAfter(time); var before = this._searchBefore(time); var value = this._initial; //if it was set by if (before === null) { value = this._initial; } else if (before.type === Tone.TimelineSignal.Type.Target) { var previous = this._events.getEventBefore(before.time); var previouVal; if (previous === null) { previouVal = this._initial; } else { previouVal = previous.value; } value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time); } else if (after === null) { value = before.value; } else if (after.type === Tone.TimelineSignal.Type.Linear) { value = this._linearInterpolate(before.time, before.value, after.time, after.value, time); } else if (after.type === Tone.TimelineSignal.Type.Exponential) { value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time); } else { value = before.value; } return value; }; /** * When signals connect to other signals or AudioParams, * they take over the output value of that signal or AudioParam. * For all other nodes, the behavior is the same as a default <code>connect</code>. * * @override * @param {AudioParam|AudioNode|Tone.Signal|Tone} node * @param {number} [outputNumber=0] The output number to connect from. * @param {number} [inputNumber=0] The input number to connect to. * @returns {Tone.TimelineSignal} this * @method */ Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect; /////////////////////////////////////////////////////////////////////////// // AUTOMATION CURVE CALCULATIONS // MIT License, copyright (c) 2014 Jordan Santell /////////////////////////////////////////////////////////////////////////// /** * Calculates the the value along the curve produced by setTargetAtTime * @private */ Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) { return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant); }; /** * Calculates the the value along the curve produced by linearRampToValueAtTime * @private */ Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) { return v0 + (v1 - v0) * ((t - t0) / (t1 - t0)); }; /** * Calculates the the value along the curve produced by exponentialRampToValueAtTime * @private */ Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) { v0 = Math.max(this._minOutput, v0); return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0)); }; /** * Clean up. * @return {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.dispose = function () { Tone.Signal.prototype.dispose.call(this); Tone.Param.prototype.dispose.call(this); this._events.dispose(); this._events = null; }; return Tone.TimelineSignal; }); Module(function (Tone) { /** * @class Pow applies an exponent to the incoming signal. The incoming signal * must be AudioRange. * * @extends {Tone.SignalBase} * @constructor * @param {Positive} exp The exponent to apply to the incoming signal, must be at least 2. * @example * var pow = new Tone.Pow(2); * var sig = new Tone.Signal(0.5).connect(pow); * //output of pow is 0.25. */ Tone.Pow = function (exp) { /** * the exponent * @private * @type {number} */ this._exp = this.defaultArg(exp, 1); /** * @type {WaveShaperNode} * @private */ this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192); }; Tone.extend(Tone.Pow, Tone.SignalBase); /** * The value of the exponent. * @memberOf Tone.Pow# * @type {number} * @name value */ Object.defineProperty(Tone.Pow.prototype, 'value', { get: function () { return this._exp; }, set: function (exp) { this._exp = exp; this._expScaler.setMap(this._expFunc(this._exp)); } }); /** * the function which maps the waveshaper * @param {number} exp * @return {function} * @private */ Tone.Pow.prototype._expFunc = function (exp) { return function (val) { return Math.pow(Math.abs(val), exp); }; }; /** * Clean up. * @returns {Tone.Pow} this */ Tone.Pow.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._expScaler.dispose(); this._expScaler = null; return this; }; return Tone.Pow; }); Module(function (Tone) { /** * @class Tone.Envelope is an [ADSR](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope) * envelope generator. Tone.Envelope outputs a signal which * can be connected to an AudioParam or Tone.Signal. * <img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/ADSR_parameter.svg"> * * @constructor * @extends {Tone} * @param {Time} [attack] The amount of time it takes for the envelope to go from * 0 to it's maximum value. * @param {Time} [decay] The period of time after the attack that it takes for the envelope * to fall to the sustain value. * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until * the release is triggered. * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. * @example * //an amplitude envelope * var gainNode = Tone.context.createGain(); * var env = new Tone.Envelope({ * "attack" : 0.1, * "decay" : 0.2, * "sustain" : 1, * "release" : 0.8, * }); * env.connect(gainNode.gain); */ Tone.Envelope = function () { //get all of the defaults var options = this.optionsObject(arguments, [ 'attack', 'decay', 'sustain', 'release' ], Tone.Envelope.defaults); /** * When triggerAttack is called, the attack time is the amount of * time it takes for the envelope to reach it's maximum value. * @type {Time} */ this.attack = options.attack; /** * After the attack portion of the envelope, the value will fall * over the duration of the decay time to it's sustain value. * @type {Time} */ this.decay = options.decay; /** * The sustain value is the value * which the envelope rests at after triggerAttack is * called, but before triggerRelease is invoked. * @type {NormalRange} */ this.sustain = options.sustain; /** * After triggerRelease is called, the envelope's * value will fall to it's miminum value over the * duration of the release time. * @type {Time} */ this.release = options.release; /** * the next time the envelope is at standby * @type {number} * @private */ this._attackCurve = Tone.Envelope.Type.Linear; /** * the next time the envelope is at standby * @type {number} * @private */ this._releaseCurve = Tone.Envelope.Type.Exponential; /** * the minimum output value * @type {number} * @private */ this._minOutput = 0.00001; /** * the signal * @type {Tone.TimelineSignal} * @private */ this._sig = this.output = new Tone.TimelineSignal(); this._sig.setValueAtTime(this._minOutput, 0); //set the attackCurve initially this.attackCurve = options.attackCurve; this.releaseCurve = options.releaseCurve; }; Tone.extend(Tone.Envelope); /** * the default parameters * @static * @const */ Tone.Envelope.defaults = { 'attack': 0.01, 'decay': 0.1, 'sustain': 0.5, 'release': 1, 'attackCurve': 'linear', 'releaseCurve': 'exponential' }; /** * the envelope time multipler * @type {number} * @private */ Tone.Envelope.prototype._timeMult = 0.25; /** * Read the current value of the envelope. Useful for * syncronizing visual output to the envelope. * @memberOf Tone.Envelope# * @type {Number} * @name value * @readOnly */ Object.defineProperty(Tone.Envelope.prototype, 'value', { get: function () { return this._sig.value; } }); /** * The slope of the attack. Either "linear" or "exponential". * @memberOf Tone.Envelope# * @type {string} * @name attackCurve * @example * env.attackCurve = "linear"; */ Object.defineProperty(Tone.Envelope.prototype, 'attackCurve', { get: function () { return this._attackCurve; }, set: function (type) { if (type === Tone.Envelope.Type.Linear || type === Tone.Envelope.Type.Exponential) { this._attackCurve = type; } else { throw Error('attackCurve must be either "linear" or "exponential". Invalid type: ', type); } } }); /** * The slope of the Release. Either "linear" or "exponential". * @memberOf Tone.Envelope# * @type {string} * @name releaseCurve * @example * env.releaseCurve = "linear"; */ Object.defineProperty(Tone.Envelope.prototype, 'releaseCurve', { get: function () { return this._releaseCurve; }, set: function (type) { if (type === Tone.Envelope.Type.Linear || type === Tone.Envelope.Type.Exponential) { this._releaseCurve = type; } else { throw Error('releaseCurve must be either "linear" or "exponential". Invalid type: ', type); } } }); /** * Trigger the attack/decay portion of the ADSR envelope. * @param {Time} [time=now] When the attack should start. * @param {NormalRange} [velocity=1] The velocity of the envelope scales the vales. * number between 0-1 * @returns {Tone.Envelope} this * @example * //trigger the attack 0.5 seconds from now with a velocity of 0.2 * env.triggerAttack("+0.5", 0.2); */ Tone.Envelope.prototype.triggerAttack = function (time, velocity) { //to seconds var now = this.now() + this.blockTime; time = this.toSeconds(time, now); var attack = this.toSeconds(this.attack) + time; var decay = this.toSeconds(this.decay); velocity = this.defaultArg(velocity, 1); //attack if (this._attackCurve === Tone.Envelope.Type.Linear) { this._sig.linearRampToValueBetween(velocity, time, attack); } else { this._sig.exponentialRampToValueBetween(velocity, time, attack); } //decay this._sig.setValueAtTime(velocity, attack); this._sig.exponentialRampToValueAtTime(this.sustain * velocity, attack + decay); return this; }; /** * Triggers the release of the envelope. * @param {Time} [time=now] When the release portion of the envelope should start. * @returns {Tone.Envelope} this * @example * //trigger release immediately * env.triggerRelease(); */ Tone.Envelope.prototype.triggerRelease = function (time) { var now = this.now() + this.blockTime; time = this.toSeconds(time, now); var release = this.toSeconds(this.release); if (this._releaseCurve === Tone.Envelope.Type.Linear) { this._sig.linearRampToValueBetween(this._minOutput, time, time + release); } else { this._sig.exponentialRampToValueBetween(this._minOutput, time, release + time); } return this; }; /** * triggerAttackRelease is shorthand for triggerAttack, then waiting * some duration, then triggerRelease. * @param {Time} duration The duration of the sustain. * @param {Time} [time=now] When the attack should be triggered. * @param {number} [velocity=1] The velocity of the envelope. * @returns {Tone.Envelope} this * @example * //trigger the attack and then the release after 0.6 seconds. * env.triggerAttackRelease(0.6); */ Tone.Envelope.prototype.triggerAttackRelease = function (duration, time, velocity) { time = this.toSeconds(time); this.triggerAttack(time, velocity); this.triggerRelease(time + this.toSeconds(duration)); return this; }; /** * Borrows the connect method from Tone.Signal. * @function * @private */ Tone.Envelope.prototype.connect = Tone.Signal.prototype.connect; /** * Disconnect and dispose. * @returns {Tone.Envelope} this */ Tone.Envelope.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sig.dispose(); this._sig = null; return this; }; /** * The phase of the envelope. * @enum {string} */ Tone.Envelope.Phase = { Attack: 'attack', Decay: 'decay', Sustain: 'sustain', Release: 'release', Standby: 'standby' }; /** * The phase of the envelope. * @enum {string} */ Tone.Envelope.Type = { Linear: 'linear', Exponential: 'exponential' }; return Tone.Envelope; }); Module(function (Tone) { /** * @class Tone.AmplitudeEnvelope is a Tone.Envelope connected to a gain node. * Unlike Tone.Envelope, which outputs the envelope's value, Tone.AmplitudeEnvelope accepts * an audio signal as the input and will apply the envelope to the amplitude * of the signal. Read more about ADSR Envelopes on [Wikipedia](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope). * * @constructor * @extends {Tone.Envelope} * @param {Time|Object} [attack] The amount of time it takes for the envelope to go from * 0 to it's maximum value. * @param {Time} [decay] The period of time after the attack that it takes for the envelope * to fall to the sustain value. * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until * the release is triggered. * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. * @example * var ampEnv = new Tone.AmplitudeEnvelope({ * "attack": 0.1, * "decay": 0.2, * "sustain": 1.0, * "release": 0.8 * }).toMaster(); * //create an oscillator and connect it * var osc = new Tone.Oscillator().connect(ampEnv).start(); * //trigger the envelopes attack and release "8t" apart * ampEnv.triggerAttackRelease("8t"); */ Tone.AmplitudeEnvelope = function () { Tone.Envelope.apply(this, arguments); /** * the input node * @type {GainNode} * @private */ this.input = this.output = new Tone.Gain(); this._sig.connect(this.output.gain); }; Tone.extend(Tone.AmplitudeEnvelope, Tone.Envelope); /** * Clean up * @return {Tone.AmplitudeEnvelope} this */ Tone.AmplitudeEnvelope.prototype.dispose = function () { this.input.dispose(); this.input = null; Tone.Envelope.prototype.dispose.call(this); return this; }; return Tone.AmplitudeEnvelope; }); Module(function (Tone) { /** * @class Wrapper around the native Web Audio's * [AnalyserNode](http://webaudio.github.io/web-audio-api/#idl-def-AnalyserNode). * Extracts FFT or Waveform data from the incoming signal. * @extends {Tone} * @param {Number=} size The size of the FFT. Value must be a power of * two in the range 32 to 32768. * @param {String=} type The return type of the analysis, either "fft", or "waveform". */ Tone.Analyser = function () { var options = this.optionsObject(arguments, [ 'size', 'type' ], Tone.Analyser.defaults); /** * The analyser node. * @private * @type {AnalyserNode} */ this._analyser = this.input = this.context.createAnalyser(); /** * The analysis type * @type {String} * @private */ this._type = options.type; /** * The return type of the analysis * @type {String} * @private */ this._returnType = options.returnType; /** * The buffer that the FFT data is written to * @type {TypedArray} * @private */ this._buffer = null; //set the values initially this.size = options.size; this.type = options.type; this.returnType = options.returnType; this.minDecibels = options.minDecibels; this.maxDecibels = options.maxDecibels; }; Tone.extend(Tone.Analyser); /** * The default values. * @type {Object} * @const */ Tone.Analyser.defaults = { 'size': 2048, 'returnType': 'byte', 'type': 'fft', 'smoothing': 0.8, 'maxDecibels': -30, 'minDecibels': -100 }; /** * Possible return types of Tone.Analyser.value * @enum {String} */ Tone.Analyser.Type = { Waveform: 'waveform', FFT: 'fft' }; /** * Possible return types of Tone.Analyser.value * @enum {String} */ Tone.Analyser.ReturnType = { Byte: 'byte', Float: 'float' }; /** * Run the analysis given the current settings and return the * result as a TypedArray. * @returns {TypedArray} */ Tone.Analyser.prototype.analyse = function () { if (this._type === Tone.Analyser.Type.FFT) { if (this._returnType === Tone.Analyser.ReturnType.Byte) { this._analyser.getByteFrequencyData(this._buffer); } else { this._analyser.getFloatFrequencyData(this._buffer); } } else if (this._type === Tone.Analyser.Type.Waveform) { if (this._returnType === Tone.Analyser.ReturnType.Byte) { this._analyser.getByteTimeDomainData(this._buffer); } else { this._analyser.getFloatTimeDomainData(this._buffer); } } return this._buffer; }; /** * The size of analysis. This must be a power of two in the range 32 to 32768. * @memberOf Tone.Analyser# * @type {Number} * @name size */ Object.defineProperty(Tone.Analyser.prototype, 'size', { get: function () { return this._analyser.frequencyBinCount; }, set: function (size) { this._analyser.fftSize = size * 2; this.type = this._type; } }); /** * The return type of Tone.Analyser.value, either "byte" or "float". * When the type is set to "byte" the range of values returned in the array * are between 0-255, when set to "float" the values are between 0-1. * @memberOf Tone.Analyser# * @type {String} * @name type */ Object.defineProperty(Tone.Analyser.prototype, 'returnType', { get: function () { return this._returnType; }, set: function (type) { if (type === Tone.Analyser.ReturnType.Byte) { this._buffer = new Uint8Array(this._analyser.frequencyBinCount); } else if (type === Tone.Analyser.ReturnType.Float) { this._buffer = new Float32Array(this._analyser.frequencyBinCount); } else { throw new Error('Invalid Return Type: ' + type); } this._returnType = type; } }); /** * The analysis function returned by Tone.Analyser.value, either "fft" or "waveform". * @memberOf Tone.Analyser# * @type {String} * @name type */ Object.defineProperty(Tone.Analyser.prototype, 'type', { get: function () { return this._type; }, set: function (type) { if (type !== Tone.Analyser.Type.Waveform && type !== Tone.Analyser.Type.FFT) { throw new Error('Invalid Type: ' + type); } this._type = type; } }); /** * 0 represents no time averaging with the last analysis frame. * @memberOf Tone.Analyser# * @type {NormalRange} * @name smoothing */ Object.defineProperty(Tone.Analyser.prototype, 'smoothing', { get: function () { return this._analyser.smoothingTimeConstant; }, set: function (val) { this._analyser.smoothingTimeConstant = val; } }); /** * The smallest decibel value which is analysed by the FFT. * @memberOf Tone.Analyser# * @type {Decibels} * @name minDecibels */ Object.defineProperty(Tone.Analyser.prototype, 'minDecibels', { get: function () { return this._analyser.minDecibels; }, set: function (val) { this._analyser.minDecibels = val; } }); /** * The largest decibel value which is analysed by the FFT. * @memberOf Tone.Analyser# * @type {Decibels} * @name maxDecibels */ Object.defineProperty(Tone.Analyser.prototype, 'maxDecibels', { get: function () { return this._analyser.maxDecibels; }, set: function (val) { this._analyser.maxDecibels = val; } }); /** * Clean up. * @return {Tone.Analyser} this */ Tone.Analyser.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._analyser.disconnect(); this._analyser = null; this._buffer = null; }; return Tone.Analyser; }); Module(function (Tone) { /** * @class Tone.Compressor is a thin wrapper around the Web Audio * [DynamicsCompressorNode](http://webaudio.github.io/web-audio-api/#the-dynamicscompressornode-interface). * Compression reduces the volume of loud sounds or amplifies quiet sounds * by narrowing or "compressing" an audio signal's dynamic range. * Read more on [Wikipedia](https://en.wikipedia.org/wiki/Dynamic_range_compression). * * @extends {Tone} * @constructor * @param {Decibels|Object} [threshold] The value above which the compression starts to be applied. * @param {Positive} [ratio] The gain reduction ratio. * @example * var comp = new Tone.Compressor(-30, 3); */ Tone.Compressor = function () { var options = this.optionsObject(arguments, [ 'threshold', 'ratio' ], Tone.Compressor.defaults); /** * the compressor node * @type {DynamicsCompressorNode} * @private */ this._compressor = this.input = this.output = this.context.createDynamicsCompressor(); /** * the threshold vaue * @type {Decibels} * @signal */ this.threshold = this._compressor.threshold; /** * The attack parameter * @type {Time} * @signal */ this.attack = new Tone.Param(this._compressor.attack, Tone.Type.Time); /** * The release parameter * @type {Time} * @signal */ this.release = new Tone.Param(this._compressor.release, Tone.Type.Time); /** * The knee parameter * @type {Decibels} * @signal */ this.knee = this._compressor.knee; /** * The ratio value * @type {Number} * @signal */ this.ratio = this._compressor.ratio; //set the defaults this._readOnly([ 'knee', 'release', 'attack', 'ratio', 'threshold' ]); this.set(options); }; Tone.extend(Tone.Compressor); /** * @static * @const * @type {Object} */ Tone.Compressor.defaults = { 'ratio': 12, 'threshold': -24, 'release': 0.25, 'attack': 0.003, 'knee': 30 }; /** * clean up * @returns {Tone.Compressor} this */ Tone.Compressor.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'knee', 'release', 'attack', 'ratio', 'threshold' ]); this._compressor.disconnect(); this._compressor = null; this.attack.dispose(); this.attack = null; this.release.dispose(); this.release = null; this.threshold = null; this.ratio = null; this.knee = null; return this; }; return Tone.Compressor; }); Module(function (Tone) { /** * @class Add a signal and a number or two signals. When no value is * passed into the constructor, Tone.Add will sum <code>input[0]</code> * and <code>input[1]</code>. If a value is passed into the constructor, * the it will be added to the input. * * @constructor * @extends {Tone.Signal} * @param {number=} value If no value is provided, Tone.Add will sum the first * and second inputs. * @example * var signal = new Tone.Signal(2); * var add = new Tone.Add(2); * signal.connect(add); * //the output of add equals 4 * @example * //if constructed with no arguments * //it will add the first and second inputs * var add = new Tone.Add(); * var sig0 = new Tone.Signal(3).connect(add, 0, 0); * var sig1 = new Tone.Signal(4).connect(add, 0, 1); * //the output of add equals 7. */ Tone.Add = function (value) { Tone.call(this, 2, 0); /** * the summing node * @type {GainNode} * @private */ this._sum = this.input[0] = this.input[1] = this.output = this.context.createGain(); /** * @private * @type {Tone.Signal} */ this._param = this.input[1] = new Tone.Signal(value); this._param.connect(this._sum); }; Tone.extend(Tone.Add, Tone.Signal); /** * Clean up. * @returns {Tone.Add} this */ Tone.Add.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sum.disconnect(); this._sum = null; this._param.dispose(); this._param = null; return this; }; return Tone.Add; }); Module(function (Tone) { /** * @class Multiply two incoming signals. Or, if a number is given in the constructor, * multiplies the incoming signal by that value. * * @constructor * @extends {Tone.Signal} * @param {number=} value Constant value to multiple. If no value is provided, * it will return the product of the first and second inputs * @example * var mult = new Tone.Multiply(); * var sigA = new Tone.Signal(3); * var sigB = new Tone.Signal(4); * sigA.connect(mult, 0, 0); * sigB.connect(mult, 0, 1); * //output of mult is 12. * @example * var mult = new Tone.Multiply(10); * var sig = new Tone.Signal(2).connect(mult); * //the output of mult is 20. */ Tone.Multiply = function (value) { Tone.call(this, 2, 0); /** * the input node is the same as the output node * it is also the GainNode which handles the scaling of incoming signal * * @type {GainNode} * @private */ this._mult = this.input[0] = this.output = this.context.createGain(); /** * the scaling parameter * @type {AudioParam} * @private */ this._param = this.input[1] = this.output.gain; this._param.value = this.defaultArg(value, 0); }; Tone.extend(Tone.Multiply, Tone.Signal); /** * clean up * @returns {Tone.Multiply} this */ Tone.Multiply.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._mult.disconnect(); this._mult = null; this._param = null; return this; }; return Tone.Multiply; }); Module(function (Tone) { /** * @class Negate the incoming signal. i.e. an input signal of 10 will output -10 * * @constructor * @extends {Tone.SignalBase} * @example * var neg = new Tone.Negate(); * var sig = new Tone.Signal(-2).connect(neg); * //output of neg is positive 2. */ Tone.Negate = function () { /** * negation is done by multiplying by -1 * @type {Tone.Multiply} * @private */ this._multiply = this.input = this.output = new Tone.Multiply(-1); }; Tone.extend(Tone.Negate, Tone.SignalBase); /** * clean up * @returns {Tone.Negate} this */ Tone.Negate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._multiply.dispose(); this._multiply = null; return this; }; return Tone.Negate; }); Module(function (Tone) { /** * @class Subtract the signal connected to <code>input[1]</code> from the signal connected * to <code>input[0]</code>. If an argument is provided in the constructor, the * signals <code>.value</code> will be subtracted from the incoming signal. * * @extends {Tone.Signal} * @constructor * @param {number=} value The value to subtract from the incoming signal. If the value * is omitted, it will subtract the second signal from the first. * @example * var sub = new Tone.Subtract(1); * var sig = new Tone.Signal(4).connect(sub); * //the output of sub is 3. * @example * var sub = new Tone.Subtract(); * var sigA = new Tone.Signal(10); * var sigB = new Tone.Signal(2.5); * sigA.connect(sub, 0, 0); * sigB.connect(sub, 0, 1); * //output of sub is 7.5 */ Tone.Subtract = function (value) { Tone.call(this, 2, 0); /** * the summing node * @type {GainNode} * @private */ this._sum = this.input[0] = this.output = this.context.createGain(); /** * negate the input of the second input before connecting it * to the summing node. * @type {Tone.Negate} * @private */ this._neg = new Tone.Negate(); /** * the node where the value is set * @private * @type {Tone.Signal} */ this._param = this.input[1] = new Tone.Signal(value); this._param.chain(this._neg, this._sum); }; Tone.extend(Tone.Subtract, Tone.Signal); /** * Clean up. * @returns {Tone.SignalBase} this */ Tone.Subtract.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._neg.dispose(); this._neg = null; this._sum.disconnect(); this._sum = null; this._param.dispose(); this._param = null; return this; }; return Tone.Subtract; }); Module(function (Tone) { /** * @class GreaterThanZero outputs 1 when the input is strictly greater than zero * * @constructor * @extends {Tone.SignalBase} * @example * var gt0 = new Tone.GreaterThanZero(); * var sig = new Tone.Signal(0.01).connect(gt0); * //the output of gt0 is 1. * sig.value = 0; * //the output of gt0 is 0. */ Tone.GreaterThanZero = function () { /** * @type {Tone.WaveShaper} * @private */ this._thresh = this.output = new Tone.WaveShaper(function (val) { if (val <= 0) { return 0; } else { return 1; } }); /** * scale the first thresholded signal by a large value. * this will help with values which are very close to 0 * @type {Tone.Multiply} * @private */ this._scale = this.input = new Tone.Multiply(10000); //connections this._scale.connect(this._thresh); }; Tone.extend(Tone.GreaterThanZero, Tone.SignalBase); /** * dispose method * @returns {Tone.GreaterThanZero} this */ Tone.GreaterThanZero.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._scale.dispose(); this._scale = null; this._thresh.dispose(); this._thresh = null; return this; }; return Tone.GreaterThanZero; }); Module(function (Tone) { /** * @class EqualZero outputs 1 when the input is equal to * 0 and outputs 0 otherwise. * * @constructor * @extends {Tone.SignalBase} * @example * var eq0 = new Tone.EqualZero(); * var sig = new Tone.Signal(0).connect(eq0); * //the output of eq0 is 1. */ Tone.EqualZero = function () { /** * scale the incoming signal by a large factor * @private * @type {Tone.Multiply} */ this._scale = this.input = new Tone.Multiply(10000); /** * @type {Tone.WaveShaper} * @private */ this._thresh = new Tone.WaveShaper(function (val) { if (val === 0) { return 1; } else { return 0; } }, 128); /** * threshold the output so that it's 0 or 1 * @type {Tone.GreaterThanZero} * @private */ this._gtz = this.output = new Tone.GreaterThanZero(); //connections this._scale.chain(this._thresh, this._gtz); }; Tone.extend(Tone.EqualZero, Tone.SignalBase); /** * Clean up. * @returns {Tone.EqualZero} this */ Tone.EqualZero.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._gtz.dispose(); this._gtz = null; this._scale.dispose(); this._scale = null; this._thresh.dispose(); this._thresh = null; return this; }; return Tone.EqualZero; }); Module(function (Tone) { /** * @class Output 1 if the signal is equal to the value, otherwise outputs 0. * Can accept two signals if connected to inputs 0 and 1. * * @constructor * @extends {Tone.SignalBase} * @param {number=} value The number to compare the incoming signal to * @example * var eq = new Tone.Equal(3); * var sig = new Tone.Signal(3).connect(eq); * //the output of eq is 1. */ Tone.Equal = function (value) { Tone.call(this, 2, 0); /** * subtract the value from the incoming signal * * @type {Tone.Add} * @private */ this._sub = this.input[0] = new Tone.Subtract(value); /** * @type {Tone.EqualZero} * @private */ this._equals = this.output = new Tone.EqualZero(); this._sub.connect(this._equals); this.input[1] = this._sub.input[1]; }; Tone.extend(Tone.Equal, Tone.SignalBase); /** * The value to compare to the incoming signal. * @memberOf Tone.Equal# * @type {number} * @name value */ Object.defineProperty(Tone.Equal.prototype, 'value', { get: function () { return this._sub.value; }, set: function (value) { this._sub.value = value; } }); /** * Clean up. * @returns {Tone.Equal} this */ Tone.Equal.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._equals.dispose(); this._equals = null; this._sub.dispose(); this._sub = null; return this; }; return Tone.Equal; }); Module(function (Tone) { /** * @class Select between any number of inputs, sending the one * selected by the gate signal to the output * * @constructor * @extends {Tone.SignalBase} * @param {number} [sourceCount=2] the number of inputs the switch accepts * @example * var sel = new Tone.Select(2); * var sigA = new Tone.Signal(10).connect(sel, 0, 0); * var sigB = new Tone.Signal(20).connect(sel, 0, 1); * sel.gate.value = 0; * //sel outputs 10 (the value of sigA); * sel.gate.value = 1; * //sel outputs 20 (the value of sigB); */ Tone.Select = function (sourceCount) { sourceCount = this.defaultArg(sourceCount, 2); Tone.call(this, sourceCount, 1); /** * the control signal * @type {Number} * @signal */ this.gate = new Tone.Signal(0); this._readOnly('gate'); //make all the inputs and connect them for (var i = 0; i < sourceCount; i++) { var switchGate = new SelectGate(i); this.input[i] = switchGate; this.gate.connect(switchGate.selecter); switchGate.connect(this.output); } }; Tone.extend(Tone.Select, Tone.SignalBase); /** * Open a specific input and close the others. * @param {number} which The gate to open. * @param {Time} [time=now] The time when the switch will open * @returns {Tone.Select} this * @example * //open input 1 in a half second from now * sel.select(1, "+0.5"); */ Tone.Select.prototype.select = function (which, time) { //make sure it's an integer which = Math.floor(which); this.gate.setValueAtTime(which, this.toSeconds(time)); return this; }; /** * Clean up. * @returns {Tone.Select} this */ Tone.Select.prototype.dispose = function () { this._writable('gate'); this.gate.dispose(); this.gate = null; for (var i = 0; i < this.input.length; i++) { this.input[i].dispose(); this.input[i] = null; } Tone.prototype.dispose.call(this); return this; }; ////////////START HELPER//////////// /** * helper class for Tone.Select representing a single gate * @constructor * @extends {Tone} * @private */ var SelectGate = function (num) { /** * the selector * @type {Tone.Equal} */ this.selecter = new Tone.Equal(num); /** * the gate * @type {GainNode} */ this.gate = this.input = this.output = this.context.createGain(); //connect the selecter to the gate gain this.selecter.connect(this.gate.gain); }; Tone.extend(SelectGate); /** * clean up * @private */ SelectGate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.selecter.dispose(); this.gate.disconnect(); this.selecter = null; this.gate = null; }; ////////////END HELPER//////////// //return Tone.Select return Tone.Select; }); Module(function (Tone) { /** * @class IfThenElse has three inputs. When the first input (if) is true (i.e. === 1), * then it will pass the second input (then) through to the output, otherwise, * if it's not true (i.e. === 0) then it will pass the third input (else) * through to the output. * * @extends {Tone.SignalBase} * @constructor * @example * var ifThenElse = new Tone.IfThenElse(); * var ifSignal = new Tone.Signal(1).connect(ifThenElse.if); * var pwmOsc = new Tone.PWMOscillator().connect(ifThenElse.then); * var pulseOsc = new Tone.PulseOscillator().connect(ifThenElse.else); * //ifThenElse outputs pwmOsc * signal.value = 0; * //now ifThenElse outputs pulseOsc */ Tone.IfThenElse = function () { Tone.call(this, 3, 0); /** * the selector node which is responsible for the routing * @type {Tone.Select} * @private */ this._selector = this.output = new Tone.Select(2); //the input mapping this.if = this.input[0] = this._selector.gate; this.then = this.input[1] = this._selector.input[1]; this.else = this.input[2] = this._selector.input[0]; }; Tone.extend(Tone.IfThenElse, Tone.SignalBase); /** * clean up * @returns {Tone.IfThenElse} this */ Tone.IfThenElse.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._selector.dispose(); this._selector = null; this.if = null; this.then = null; this.else = null; return this; }; return Tone.IfThenElse; }); Module(function (Tone) { /** * @class [OR](https://en.wikipedia.org/wiki/OR_gate) * the inputs together. True if at least one of the inputs is true. * * @extends {Tone.SignalBase} * @constructor * @param {number} [inputCount=2] the input count * @example * var or = new Tone.OR(2); * var sigA = new Tone.Signal(0)connect(or, 0, 0); * var sigB = new Tone.Signal(1)connect(or, 0, 1); * //output of or is 1 because at least * //one of the inputs is equal to 1. */ Tone.OR = function (inputCount) { inputCount = this.defaultArg(inputCount, 2); Tone.call(this, inputCount, 0); /** * a private summing node * @type {GainNode} * @private */ this._sum = this.context.createGain(); /** * @type {Tone.Equal} * @private */ this._gtz = this.output = new Tone.GreaterThanZero(); //make each of the inputs an alias for (var i = 0; i < inputCount; i++) { this.input[i] = this._sum; } this._sum.connect(this._gtz); }; Tone.extend(Tone.OR, Tone.SignalBase); /** * clean up * @returns {Tone.OR} this */ Tone.OR.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._gtz.dispose(); this._gtz = null; this._sum.disconnect(); this._sum = null; return this; }; return Tone.OR; }); Module(function (Tone) { /** * @class [AND](https://en.wikipedia.org/wiki/Logical_conjunction) * returns 1 when all the inputs are equal to 1 and returns 0 otherwise. * * @extends {Tone.SignalBase} * @constructor * @param {number} [inputCount=2] the number of inputs. NOTE: all inputs are * connected to the single AND input node * @example * var and = new Tone.AND(2); * var sigA = new Tone.Signal(0).connect(and, 0, 0); * var sigB = new Tone.Signal(1).connect(and, 0, 1); * //the output of and is 0. */ Tone.AND = function (inputCount) { inputCount = this.defaultArg(inputCount, 2); Tone.call(this, inputCount, 0); /** * @type {Tone.Equal} * @private */ this._equals = this.output = new Tone.Equal(inputCount); //make each of the inputs an alias for (var i = 0; i < inputCount; i++) { this.input[i] = this._equals; } }; Tone.extend(Tone.AND, Tone.SignalBase); /** * clean up * @returns {Tone.AND} this */ Tone.AND.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._equals.dispose(); this._equals = null; return this; }; return Tone.AND; }); Module(function (Tone) { /** * @class Just an alias for Tone.EqualZero, but has the same effect as a NOT operator. * Outputs 1 when input equals 0. * * @constructor * @extends {Tone.SignalBase} * @example * var not = new Tone.NOT(); * var sig = new Tone.Signal(1).connect(not); * //output of not equals 0. * sig.value = 0; * //output of not equals 1. */ Tone.NOT = Tone.EqualZero; return Tone.NOT; }); Module(function (Tone) { /** * @class Output 1 if the signal is greater than the value, otherwise outputs 0. * can compare two signals or a signal and a number. * * @constructor * @extends {Tone.Signal} * @param {number} [value=0] the value to compare to the incoming signal * @example * var gt = new Tone.GreaterThan(2); * var sig = new Tone.Signal(4).connect(gt); * //output of gt is equal 1. */ Tone.GreaterThan = function (value) { Tone.call(this, 2, 0); /** * subtract the amount from the incoming signal * @type {Tone.Subtract} * @private */ this._param = this.input[0] = new Tone.Subtract(value); this.input[1] = this._param.input[1]; /** * compare that amount to zero * @type {Tone.GreaterThanZero} * @private */ this._gtz = this.output = new Tone.GreaterThanZero(); //connect this._param.connect(this._gtz); }; Tone.extend(Tone.GreaterThan, Tone.Signal); /** * dispose method * @returns {Tone.GreaterThan} this */ Tone.GreaterThan.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param.dispose(); this._param = null; this._gtz.dispose(); this._gtz = null; return this; }; return Tone.GreaterThan; }); Module(function (Tone) { /** * @class Output 1 if the signal is less than the value, otherwise outputs 0. * Can compare two signals or a signal and a number. * * @constructor * @extends {Tone.Signal} * @param {number=} value The value to compare to the incoming signal. * If no value is provided, it will compare * <code>input[0]</code> and <code>input[1]</code> * @example * var lt = new Tone.LessThan(2); * var sig = new Tone.Signal(-1).connect(lt); * //if (sig < 2) lt outputs 1 */ Tone.LessThan = function (value) { Tone.call(this, 2, 0); /** * negate the incoming signal * @type {Tone.Negate} * @private */ this._neg = this.input[0] = new Tone.Negate(); /** * input < value === -input > -value * @type {Tone.GreaterThan} * @private */ this._gt = this.output = new Tone.GreaterThan(); /** * negate the signal coming from the second input * @private * @type {Tone.Negate} */ this._rhNeg = new Tone.Negate(); /** * the node where the value is set * @private * @type {Tone.Signal} */ this._param = this.input[1] = new Tone.Signal(value); //connect this._neg.connect(this._gt); this._param.connect(this._rhNeg); this._rhNeg.connect(this._gt, 0, 1); }; Tone.extend(Tone.LessThan, Tone.Signal); /** * Clean up. * @returns {Tone.LessThan} this */ Tone.LessThan.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._neg.dispose(); this._neg = null; this._gt.dispose(); this._gt = null; this._rhNeg.dispose(); this._rhNeg = null; this._param.dispose(); this._param = null; return this; }; return Tone.LessThan; }); Module(function (Tone) { /** * @class Return the absolute value of an incoming signal. * * @constructor * @extends {Tone.SignalBase} * @example * var signal = new Tone.Signal(-1); * var abs = new Tone.Abs(); * signal.connect(abs); * //the output of abs is 1. */ Tone.Abs = function () { Tone.call(this, 1, 0); /** * @type {Tone.LessThan} * @private */ this._ltz = new Tone.LessThan(0); /** * @type {Tone.Select} * @private */ this._switch = this.output = new Tone.Select(2); /** * @type {Tone.Negate} * @private */ this._negate = new Tone.Negate(); //two signal paths, positive and negative this.input.connect(this._switch, 0, 0); this.input.connect(this._negate); this._negate.connect(this._switch, 0, 1); //the control signal this.input.chain(this._ltz, this._switch.gate); }; Tone.extend(Tone.Abs, Tone.SignalBase); /** * dispose method * @returns {Tone.Abs} this */ Tone.Abs.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._switch.dispose(); this._switch = null; this._ltz.dispose(); this._ltz = null; this._negate.dispose(); this._negate = null; return this; }; return Tone.Abs; }); Module(function (Tone) { /** * @class Outputs the greater of two signals. If a number is provided in the constructor * it will use that instead of the signal. * * @constructor * @extends {Tone.Signal} * @param {number=} max Max value if provided. if not provided, it will use the * signal value from input 1. * @example * var max = new Tone.Max(2); * var sig = new Tone.Signal(3).connect(max); * //max outputs 3 * sig.value = 1; * //max outputs 2 * @example * var max = new Tone.Max(); * var sigA = new Tone.Signal(3); * var sigB = new Tone.Signal(4); * sigA.connect(max, 0, 0); * sigB.connect(max, 0, 1); * //output of max is 4. */ Tone.Max = function (max) { Tone.call(this, 2, 0); this.input[0] = this.context.createGain(); /** * the max signal * @type {Tone.Signal} * @private */ this._param = this.input[1] = new Tone.Signal(max); /** * @type {Tone.Select} * @private */ this._ifThenElse = this.output = new Tone.IfThenElse(); /** * @type {Tone.Select} * @private */ this._gt = new Tone.GreaterThan(); //connections this.input[0].chain(this._gt, this._ifThenElse.if); this.input[0].connect(this._ifThenElse.then); this._param.connect(this._ifThenElse.else); this._param.connect(this._gt, 0, 1); }; Tone.extend(Tone.Max, Tone.Signal); /** * Clean up. * @returns {Tone.Max} this */ Tone.Max.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param.dispose(); this._ifThenElse.dispose(); this._gt.dispose(); this._param = null; this._ifThenElse = null; this._gt = null; return this; }; return Tone.Max; }); Module(function (Tone) { /** * @class Outputs the lesser of two signals. If a number is given * in the constructor, it will use a signal and a number. * * @constructor * @extends {Tone.Signal} * @param {number} min The minimum to compare to the incoming signal * @example * var min = new Tone.Min(2); * var sig = new Tone.Signal(3).connect(min); * //min outputs 2 * sig.value = 1; * //min outputs 1 * @example * var min = new Tone.Min(); * var sigA = new Tone.Signal(3); * var sigB = new Tone.Signal(4); * sigA.connect(min, 0, 0); * sigB.connect(min, 0, 1); * //output of min is 3. */ Tone.Min = function (min) { Tone.call(this, 2, 0); this.input[0] = this.context.createGain(); /** * @type {Tone.Select} * @private */ this._ifThenElse = this.output = new Tone.IfThenElse(); /** * @type {Tone.Select} * @private */ this._lt = new Tone.LessThan(); /** * the min signal * @type {Tone.Signal} * @private */ this._param = this.input[1] = new Tone.Signal(min); //connections this.input[0].chain(this._lt, this._ifThenElse.if); this.input[0].connect(this._ifThenElse.then); this._param.connect(this._ifThenElse.else); this._param.connect(this._lt, 0, 1); }; Tone.extend(Tone.Min, Tone.Signal); /** * clean up * @returns {Tone.Min} this */ Tone.Min.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param.dispose(); this._ifThenElse.dispose(); this._lt.dispose(); this._param = null; this._ifThenElse = null; this._lt = null; return this; }; return Tone.Min; }); Module(function (Tone) { /** * @class Signal-rate modulo operator. Only works in AudioRange [-1, 1] and for modulus * values in the NormalRange. * * @constructor * @extends {Tone.SignalBase} * @param {NormalRange} modulus The modulus to apply. * @example * var mod = new Tone.Modulo(0.2) * var sig = new Tone.Signal(0.5).connect(mod); * //mod outputs 0.1 */ Tone.Modulo = function (modulus) { Tone.call(this, 1, 1); /** * A waveshaper gets the integer multiple of * the input signal and the modulus. * @private * @type {Tone.WaveShaper} */ this._shaper = new Tone.WaveShaper(Math.pow(2, 16)); /** * the integer multiple is multiplied by the modulus * @type {Tone.Multiply} * @private */ this._multiply = new Tone.Multiply(); /** * and subtracted from the input signal * @type {Tone.Subtract} * @private */ this._subtract = this.output = new Tone.Subtract(); /** * the modulus signal * @type {Tone.Signal} * @private */ this._modSignal = new Tone.Signal(modulus); //connections this.input.fan(this._shaper, this._subtract); this._modSignal.connect(this._multiply, 0, 0); this._shaper.connect(this._multiply, 0, 1); this._multiply.connect(this._subtract, 0, 1); this._setWaveShaper(modulus); }; Tone.extend(Tone.Modulo, Tone.SignalBase); /** * @param {number} mod the modulus to apply * @private */ Tone.Modulo.prototype._setWaveShaper = function (mod) { this._shaper.setMap(function (val) { var multiple = Math.floor((val + 0.0001) / mod); return multiple; }); }; /** * The modulus value. * @memberOf Tone.Modulo# * @type {NormalRange} * @name value */ Object.defineProperty(Tone.Modulo.prototype, 'value', { get: function () { return this._modSignal.value; }, set: function (mod) { this._modSignal.value = mod; this._setWaveShaper(mod); } }); /** * clean up * @returns {Tone.Modulo} this */ Tone.Modulo.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._shaper.dispose(); this._shaper = null; this._multiply.dispose(); this._multiply = null; this._subtract.dispose(); this._subtract = null; this._modSignal.dispose(); this._modSignal = null; return this; }; return Tone.Modulo; }); Module(function (Tone) { /** * @class AudioToGain converts an input in AudioRange [-1,1] to NormalRange [0,1]. * See Tone.GainToAudio. * * @extends {Tone.SignalBase} * @constructor * @example * var a2g = new Tone.AudioToGain(); */ Tone.AudioToGain = function () { /** * @type {WaveShaperNode} * @private */ this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { return (x + 1) / 2; }); }; Tone.extend(Tone.AudioToGain, Tone.SignalBase); /** * clean up * @returns {Tone.AudioToGain} this */ Tone.AudioToGain.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._norm.dispose(); this._norm = null; return this; }; return Tone.AudioToGain; }); Module(function (Tone) { /** * @class Evaluate an expression at audio rate. <br><br> * Parsing code modified from https://code.google.com/p/tapdigit/ * Copyright 2011 2012 Ariya Hidayat, New BSD License * * @extends {Tone.SignalBase} * @constructor * @param {string} expr the expression to generate * @example * //adds the signals from input[0] and input[1]. * var expr = new Tone.Expr("$0 + $1"); */ Tone.Expr = function () { var expr = this._replacements(Array.prototype.slice.call(arguments)); var inputCount = this._parseInputs(expr); /** * hold onto all of the nodes for disposal * @type {Array} * @private */ this._nodes = []; /** * The inputs. The length is determined by the expression. * @type {Array} */ this.input = new Array(inputCount); //create a gain for each input for (var i = 0; i < inputCount; i++) { this.input[i] = this.context.createGain(); } //parse the syntax tree var tree = this._parseTree(expr); //evaluate the results var result; try { result = this._eval(tree); } catch (e) { this._disposeNodes(); throw new Error('Could evaluate expression: ' + expr); } /** * The output node is the result of the expression * @type {Tone} */ this.output = result; }; Tone.extend(Tone.Expr, Tone.SignalBase); //some helpers to cut down the amount of code function applyBinary(Constructor, args, self) { var op = new Constructor(); self._eval(args[0]).connect(op, 0, 0); self._eval(args[1]).connect(op, 0, 1); return op; } function applyUnary(Constructor, args, self) { var op = new Constructor(); self._eval(args[0]).connect(op, 0, 0); return op; } function getNumber(arg) { return arg ? parseFloat(arg) : undefined; } function literalNumber(arg) { return arg && arg.args ? parseFloat(arg.args) : undefined; } /* * the Expressions that Tone.Expr can parse. * * each expression belongs to a group and contains a regexp * for selecting the operator as well as that operators method * * @type {Object} * @private */ Tone.Expr._Expressions = { //values 'value': { 'signal': { regexp: /^\d+\.\d+|^\d+/, method: function (arg) { var sig = new Tone.Signal(getNumber(arg)); return sig; } }, 'input': { regexp: /^\$\d/, method: function (arg, self) { return self.input[getNumber(arg.substr(1))]; } } }, //syntactic glue 'glue': { '(': { regexp: /^\(/ }, ')': { regexp: /^\)/ }, ',': { regexp: /^,/ } }, //functions 'func': { 'abs': { regexp: /^abs/, method: applyUnary.bind(this, Tone.Abs) }, 'min': { regexp: /^min/, method: applyBinary.bind(this, Tone.Min) }, 'max': { regexp: /^max/, method: applyBinary.bind(this, Tone.Max) }, 'if': { regexp: /^if/, method: function (args, self) { var op = new Tone.IfThenElse(); self._eval(args[0]).connect(op.if); self._eval(args[1]).connect(op.then); self._eval(args[2]).connect(op.else); return op; } }, 'gt0': { regexp: /^gt0/, method: applyUnary.bind(this, Tone.GreaterThanZero) }, 'eq0': { regexp: /^eq0/, method: applyUnary.bind(this, Tone.EqualZero) }, 'mod': { regexp: /^mod/, method: function (args, self) { var modulus = literalNumber(args[1]); var op = new Tone.Modulo(modulus); self._eval(args[0]).connect(op); return op; } }, 'pow': { regexp: /^pow/, method: function (args, self) { var exp = literalNumber(args[1]); var op = new Tone.Pow(exp); self._eval(args[0]).connect(op); return op; } }, 'a2g': { regexp: /^a2g/, method: function (args, self) { var op = new Tone.AudioToGain(); self._eval(args[0]).connect(op); return op; } } }, //binary expressions 'binary': { '+': { regexp: /^\+/, precedence: 1, method: applyBinary.bind(this, Tone.Add) }, '-': { regexp: /^\-/, precedence: 1, method: function (args, self) { //both unary and binary op if (args.length === 1) { return applyUnary(Tone.Negate, args, self); } else { return applyBinary(Tone.Subtract, args, self); } } }, '*': { regexp: /^\*/, precedence: 0, method: applyBinary.bind(this, Tone.Multiply) }, '>': { regexp: /^\>/, precedence: 2, method: applyBinary.bind(this, Tone.GreaterThan) }, '<': { regexp: /^</, precedence: 2, method: applyBinary.bind(this, Tone.LessThan) }, '==': { regexp: /^==/, precedence: 3, method: applyBinary.bind(this, Tone.Equal) }, '&&': { regexp: /^&&/, precedence: 4, method: applyBinary.bind(this, Tone.AND) }, '||': { regexp: /^\|\|/, precedence: 5, method: applyBinary.bind(this, Tone.OR) } }, //unary expressions 'unary': { '-': { regexp: /^\-/, method: applyUnary.bind(this, Tone.Negate) }, '!': { regexp: /^\!/, method: applyUnary.bind(this, Tone.NOT) } } }; /** * @param {string} expr the expression string * @return {number} the input count * @private */ Tone.Expr.prototype._parseInputs = function (expr) { var inputArray = expr.match(/\$\d/g); var inputMax = 0; if (inputArray !== null) { for (var i = 0; i < inputArray.length; i++) { var inputNum = parseInt(inputArray[i].substr(1)) + 1; inputMax = Math.max(inputMax, inputNum); } } return inputMax; }; /** * @param {Array} args an array of arguments * @return {string} the results of the replacements being replaced * @private */ Tone.Expr.prototype._replacements = function (args) { var expr = args.shift(); for (var i = 0; i < args.length; i++) { expr = expr.replace(/\%/i, args[i]); } return expr; }; /** * tokenize the expression based on the Expressions object * @param {string} expr * @return {Object} returns two methods on the tokenized list, next and peek * @private */ Tone.Expr.prototype._tokenize = function (expr) { var position = -1; var tokens = []; while (expr.length > 0) { expr = expr.trim(); var token = getNextToken(expr); tokens.push(token); expr = expr.substr(token.value.length); } function getNextToken(expr) { for (var type in Tone.Expr._Expressions) { var group = Tone.Expr._Expressions[type]; for (var opName in group) { var op = group[opName]; var reg = op.regexp; var match = expr.match(reg); if (match !== null) { return { type: type, value: match[0], method: op.method }; } } } throw new SyntaxError('Unexpected token ' + expr); } return { next: function () { return tokens[++position]; }, peek: function () { return tokens[position + 1]; } }; }; /** * recursively parse the string expression into a syntax tree * * @param {string} expr * @return {Object} * @private */ Tone.Expr.prototype._parseTree = function (expr) { var lexer = this._tokenize(expr); var isUndef = this.isUndef.bind(this); function matchSyntax(token, syn) { return !isUndef(token) && token.type === 'glue' && token.value === syn; } function matchGroup(token, groupName, prec) { var ret = false; var group = Tone.Expr._Expressions[groupName]; if (!isUndef(token)) { for (var opName in group) { var op = group[opName]; if (op.regexp.test(token.value)) { if (!isUndef(prec)) { if (op.precedence === prec) { return true; } } else { return true; } } } } return ret; } function parseExpression(precedence) { if (isUndef(precedence)) { precedence = 5; } var expr; if (precedence < 0) { expr = parseUnary(); } else { expr = parseExpression(precedence - 1); } var token = lexer.peek(); while (matchGroup(token, 'binary', precedence)) { token = lexer.next(); expr = { operator: token.value, method: token.method, args: [ expr, parseExpression(precedence) ] }; token = lexer.peek(); } return expr; } function parseUnary() { var token, expr; token = lexer.peek(); if (matchGroup(token, 'unary')) { token = lexer.next(); expr = parseUnary(); return { operator: token.value, method: token.method, args: [expr] }; } return parsePrimary(); } function parsePrimary() { var token, expr; token = lexer.peek(); if (isUndef(token)) { throw new SyntaxError('Unexpected termination of expression'); } if (token.type === 'func') { token = lexer.next(); return parseFunctionCall(token); } if (token.type === 'value') { token = lexer.next(); return { method: token.method, args: token.value }; } if (matchSyntax(token, '(')) { lexer.next(); expr = parseExpression(); token = lexer.next(); if (!matchSyntax(token, ')')) { throw new SyntaxError('Expected )'); } return expr; } throw new SyntaxError('Parse error, cannot process token ' + token.value); } function parseFunctionCall(func) { var token, args = []; token = lexer.next(); if (!matchSyntax(token, '(')) { throw new SyntaxError('Expected ( in a function call "' + func.value + '"'); } token = lexer.peek(); if (!matchSyntax(token, ')')) { args = parseArgumentList(); } token = lexer.next(); if (!matchSyntax(token, ')')) { throw new SyntaxError('Expected ) in a function call "' + func.value + '"'); } return { method: func.method, args: args, name: name }; } function parseArgumentList() { var token, expr, args = []; while (true) { expr = parseExpression(); if (isUndef(expr)) { // TODO maybe throw exception? break; } args.push(expr); token = lexer.peek(); if (!matchSyntax(token, ',')) { break; } lexer.next(); } return args; } return parseExpression(); }; /** * recursively evaluate the expression tree * @param {Object} tree * @return {AudioNode} the resulting audio node from the expression * @private */ Tone.Expr.prototype._eval = function (tree) { if (!this.isUndef(tree)) { var node = tree.method(tree.args, this); this._nodes.push(node); return node; } }; /** * dispose all the nodes * @private */ Tone.Expr.prototype._disposeNodes = function () { for (var i = 0; i < this._nodes.length; i++) { var node = this._nodes[i]; if (this.isFunction(node.dispose)) { node.dispose(); } else if (this.isFunction(node.disconnect)) { node.disconnect(); } node = null; this._nodes[i] = null; } this._nodes = null; }; /** * clean up */ Tone.Expr.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._disposeNodes(); }; return Tone.Expr; }); Module(function (Tone) { /** * @class Convert an incoming signal between 0, 1 to an equal power gain scale. * * @extends {Tone.SignalBase} * @constructor * @example * var eqPowGain = new Tone.EqualPowerGain(); */ Tone.EqualPowerGain = function () { /** * @type {Tone.WaveShaper} * @private */ this._eqPower = this.input = this.output = new Tone.WaveShaper(function (val) { if (Math.abs(val) < 0.001) { //should output 0 when input is 0 return 0; } else { return this.equalPowerScale(val); } }.bind(this), 4096); }; Tone.extend(Tone.EqualPowerGain, Tone.SignalBase); /** * clean up * @returns {Tone.EqualPowerGain} this */ Tone.EqualPowerGain.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._eqPower.dispose(); this._eqPower = null; return this; }; return Tone.EqualPowerGain; }); Module(function (Tone) { /** * @class Tone.Crossfade provides equal power fading between two inputs. * More on crossfading technique [here](https://en.wikipedia.org/wiki/Fade_(audio_engineering)#Crossfading). * * @constructor * @extends {Tone} * @param {NormalRange} [initialFade=0.5] * @example * var crossFade = new Tone.CrossFade(0.5); * //connect effect A to crossfade from * //effect output 0 to crossfade input 0 * effectA.connect(crossFade, 0, 0); * //connect effect B to crossfade from * //effect output 0 to crossfade input 1 * effectB.connect(crossFade, 0, 1); * crossFade.fade.value = 0; * // ^ only effectA is output * crossFade.fade.value = 1; * // ^ only effectB is output * crossFade.fade.value = 0.5; * // ^ the two signals are mixed equally. */ Tone.CrossFade = function (initialFade) { Tone.call(this, 2, 1); /** * Alias for <code>input[0]</code>. * @type {GainNode} */ this.a = this.input[0] = this.context.createGain(); /** * Alias for <code>input[1]</code>. * @type {GainNode} */ this.b = this.input[1] = this.context.createGain(); /** * The mix between the two inputs. A fade value of 0 * will output 100% <code>input[0]</code> and * a value of 1 will output 100% <code>input[1]</code>. * @type {NormalRange} * @signal */ this.fade = new Tone.Signal(this.defaultArg(initialFade, 0.5), Tone.Type.NormalRange); /** * equal power gain cross fade * @private * @type {Tone.EqualPowerGain} */ this._equalPowerA = new Tone.EqualPowerGain(); /** * equal power gain cross fade * @private * @type {Tone.EqualPowerGain} */ this._equalPowerB = new Tone.EqualPowerGain(); /** * invert the incoming signal * @private * @type {Tone} */ this._invert = new Tone.Expr('1 - $0'); //connections this.a.connect(this.output); this.b.connect(this.output); this.fade.chain(this._equalPowerB, this.b.gain); this.fade.chain(this._invert, this._equalPowerA, this.a.gain); this._readOnly('fade'); }; Tone.extend(Tone.CrossFade); /** * clean up * @returns {Tone.CrossFade} this */ Tone.CrossFade.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('fade'); this._equalPowerA.dispose(); this._equalPowerA = null; this._equalPowerB.dispose(); this._equalPowerB = null; this.fade.dispose(); this.fade = null; this._invert.dispose(); this._invert = null; this.a.disconnect(); this.a = null; this.b.disconnect(); this.b = null; return this; }; return Tone.CrossFade; }); Module(function (Tone) { /** * @class Tone.Filter is a filter which allows for all of the same native methods * as the [BiquadFilterNode](http://webaudio.github.io/web-audio-api/#the-biquadfilternode-interface). * Tone.Filter has the added ability to set the filter rolloff at -12 * (default), -24 and -48. * * @constructor * @extends {Tone} * @param {Frequency|Object} [frequency] The cutoff frequency of the filter. * @param {string=} type The type of filter. * @param {number=} rolloff The drop in decibels per octave after the cutoff frequency. * 3 choices: -12, -24, and -48 * @example * var filter = new Tone.Filter(200, "highpass"); */ Tone.Filter = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'frequency', 'type', 'rolloff' ], Tone.Filter.defaults); /** * the filter(s) * @type {Array} * @private */ this._filters = []; /** * The cutoff frequency of the filter. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The detune parameter * @type {Cents} * @signal */ this.detune = new Tone.Signal(0, Tone.Type.Cents); /** * The gain of the filter, only used in certain filter types * @type {Number} * @signal */ this.gain = new Tone.Signal({ 'value': options.gain, 'convert': false }); /** * The Q or Quality of the filter * @type {Positive} * @signal */ this.Q = new Tone.Signal(options.Q); /** * the type of the filter * @type {string} * @private */ this._type = options.type; /** * the rolloff value of the filter * @type {number} * @private */ this._rolloff = options.rolloff; //set the rolloff; this.rolloff = options.rolloff; this._readOnly([ 'detune', 'frequency', 'gain', 'Q' ]); }; Tone.extend(Tone.Filter); /** * the default parameters * * @static * @type {Object} */ Tone.Filter.defaults = { 'type': 'lowpass', 'frequency': 350, 'rolloff': -12, 'Q': 1, 'gain': 0 }; /** * The type of the filter. Types: "lowpass", "highpass", * "bandpass", "lowshelf", "highshelf", "notch", "allpass", or "peaking". * @memberOf Tone.Filter# * @type {string} * @name type */ Object.defineProperty(Tone.Filter.prototype, 'type', { get: function () { return this._type; }, set: function (type) { var types = [ 'lowpass', 'highpass', 'bandpass', 'lowshelf', 'highshelf', 'notch', 'allpass', 'peaking' ]; if (types.indexOf(type) === -1) { throw new Error('Tone.Filter does not have filter type ' + type); } this._type = type; for (var i = 0; i < this._filters.length; i++) { this._filters[i].type = type; } } }); /** * The rolloff of the filter which is the drop in db * per octave. Implemented internally by cascading filters. * Only accepts the values -12, -24, -48 and -96. * @memberOf Tone.Filter# * @type {number} * @name rolloff */ Object.defineProperty(Tone.Filter.prototype, 'rolloff', { get: function () { return this._rolloff; }, set: function (rolloff) { rolloff = parseInt(rolloff, 10); var possibilities = [ -12, -24, -48, -96 ]; var cascadingCount = possibilities.indexOf(rolloff); //check the rolloff is valid if (cascadingCount === -1) { throw new Error('Filter rolloff can only be -12, -24, -48 or -96'); } cascadingCount += 1; this._rolloff = rolloff; //first disconnect the filters and throw them away this.input.disconnect(); for (var i = 0; i < this._filters.length; i++) { this._filters[i].disconnect(); this._filters[i] = null; } this._filters = new Array(cascadingCount); for (var count = 0; count < cascadingCount; count++) { var filter = this.context.createBiquadFilter(); filter.type = this._type; this.frequency.connect(filter.frequency); this.detune.connect(filter.detune); this.Q.connect(filter.Q); this.gain.connect(filter.gain); this._filters[count] = filter; } //connect them up var connectionChain = [this.input].concat(this._filters).concat([this.output]); this.connectSeries.apply(this, connectionChain); } }); /** * Clean up. * @return {Tone.Filter} this */ Tone.Filter.prototype.dispose = function () { Tone.prototype.dispose.call(this); for (var i = 0; i < this._filters.length; i++) { this._filters[i].disconnect(); this._filters[i] = null; } this._filters = null; this._writable([ 'detune', 'frequency', 'gain', 'Q' ]); this.frequency.dispose(); this.Q.dispose(); this.frequency = null; this.Q = null; this.detune.dispose(); this.detune = null; this.gain.dispose(); this.gain = null; return this; }; return Tone.Filter; }); Module(function (Tone) { /** * @class Split the incoming signal into three bands (low, mid, high) * with two crossover frequency controls. * * @extends {Tone} * @constructor * @param {Frequency|Object} [lowFrequency] the low/mid crossover frequency * @param {Frequency} [highFrequency] the mid/high crossover frequency */ Tone.MultibandSplit = function () { var options = this.optionsObject(arguments, [ 'lowFrequency', 'highFrequency' ], Tone.MultibandSplit.defaults); /** * the input * @type {GainNode} * @private */ this.input = this.context.createGain(); /** * the outputs * @type {Array} * @private */ this.output = new Array(3); /** * The low band. Alias for <code>output[0]</code> * @type {Tone.Filter} */ this.low = this.output[0] = new Tone.Filter(0, 'lowpass'); /** * the lower filter of the mid band * @type {Tone.Filter} * @private */ this._lowMidFilter = new Tone.Filter(0, 'highpass'); /** * The mid band output. Alias for <code>output[1]</code> * @type {Tone.Filter} */ this.mid = this.output[1] = new Tone.Filter(0, 'lowpass'); /** * The high band output. Alias for <code>output[2]</code> * @type {Tone.Filter} */ this.high = this.output[2] = new Tone.Filter(0, 'highpass'); /** * The low/mid crossover frequency. * @type {Frequency} * @signal */ this.lowFrequency = new Tone.Signal(options.lowFrequency, Tone.Type.Frequency); /** * The mid/high crossover frequency. * @type {Frequency} * @signal */ this.highFrequency = new Tone.Signal(options.highFrequency, Tone.Type.Frequency); /** * The quality of all the filters * @type {Number} * @signal */ this.Q = new Tone.Signal(options.Q); this.input.fan(this.low, this.high); this.input.chain(this._lowMidFilter, this.mid); //the frequency control signal this.lowFrequency.connect(this.low.frequency); this.lowFrequency.connect(this._lowMidFilter.frequency); this.highFrequency.connect(this.mid.frequency); this.highFrequency.connect(this.high.frequency); //the Q value this.Q.connect(this.low.Q); this.Q.connect(this._lowMidFilter.Q); this.Q.connect(this.mid.Q); this.Q.connect(this.high.Q); this._readOnly([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); }; Tone.extend(Tone.MultibandSplit); /** * @private * @static * @type {Object} */ Tone.MultibandSplit.defaults = { 'lowFrequency': 400, 'highFrequency': 2500, 'Q': 1 }; /** * Clean up. * @returns {Tone.MultibandSplit} this */ Tone.MultibandSplit.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); this.low.dispose(); this.low = null; this._lowMidFilter.dispose(); this._lowMidFilter = null; this.mid.dispose(); this.mid = null; this.high.dispose(); this.high = null; this.lowFrequency.dispose(); this.lowFrequency = null; this.highFrequency.dispose(); this.highFrequency = null; this.Q.dispose(); this.Q = null; return this; }; return Tone.MultibandSplit; }); Module(function (Tone) { /** * @class Tone.EQ3 is a three band EQ with control over low, mid, and high gain as * well as the low and high crossover frequencies. * * @constructor * @extends {Tone} * * @param {Decibels|Object} [lowLevel] The gain applied to the lows. * @param {Decibels} [midLevel] The gain applied to the mid. * @param {Decibels} [highLevel] The gain applied to the high. * @example * var eq = new Tone.EQ3(-10, 3, -20); */ Tone.EQ3 = function () { var options = this.optionsObject(arguments, [ 'low', 'mid', 'high' ], Tone.EQ3.defaults); /** * the output node * @type {GainNode} * @private */ this.output = this.context.createGain(); /** * the multiband split * @type {Tone.MultibandSplit} * @private */ this._multibandSplit = this.input = new Tone.MultibandSplit({ 'lowFrequency': options.lowFrequency, 'highFrequency': options.highFrequency }); /** * The gain for the lower signals * @type {Tone.Gain} * @private */ this._lowGain = new Tone.Gain(options.low, Tone.Type.Decibels); /** * The gain for the mid signals * @type {Tone.Gain} * @private */ this._midGain = new Tone.Gain(options.mid, Tone.Type.Decibels); /** * The gain in decibels of the high part * @type {Tone.Gain} * @private */ this._highGain = new Tone.Gain(options.high, Tone.Type.Decibels); /** * The gain in decibels of the low part * @type {Decibels} * @signal */ this.low = this._lowGain.gain; /** * The gain in decibels of the mid part * @type {Decibels} * @signal */ this.mid = this._midGain.gain; /** * The gain in decibels of the high part * @type {Decibels} * @signal */ this.high = this._highGain.gain; /** * The Q value for all of the filters. * @type {Positive} * @signal */ this.Q = this._multibandSplit.Q; /** * The low/mid crossover frequency. * @type {Frequency} * @signal */ this.lowFrequency = this._multibandSplit.lowFrequency; /** * The mid/high crossover frequency. * @type {Frequency} * @signal */ this.highFrequency = this._multibandSplit.highFrequency; //the frequency bands this._multibandSplit.low.chain(this._lowGain, this.output); this._multibandSplit.mid.chain(this._midGain, this.output); this._multibandSplit.high.chain(this._highGain, this.output); this._readOnly([ 'low', 'mid', 'high', 'lowFrequency', 'highFrequency' ]); }; Tone.extend(Tone.EQ3); /** * the default values */ Tone.EQ3.defaults = { 'low': 0, 'mid': 0, 'high': 0, 'lowFrequency': 400, 'highFrequency': 2500 }; /** * clean up * @returns {Tone.EQ3} this */ Tone.EQ3.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'low', 'mid', 'high', 'lowFrequency', 'highFrequency' ]); this._multibandSplit.dispose(); this._multibandSplit = null; this.lowFrequency = null; this.highFrequency = null; this._lowGain.dispose(); this._lowGain = null; this._midGain.dispose(); this._midGain = null; this._highGain.dispose(); this._highGain = null; this.low = null; this.mid = null; this.high = null; this.Q = null; return this; }; return Tone.EQ3; }); Module(function (Tone) { /** * @class Performs a linear scaling on an input signal. * Scales a NormalRange input to between * outputMin and outputMax. * * @constructor * @extends {Tone.SignalBase} * @param {number} [outputMin=0] The output value when the input is 0. * @param {number} [outputMax=1] The output value when the input is 1. * @example * var scale = new Tone.Scale(50, 100); * var signal = new Tone.Signal(0.5).connect(scale); * //the output of scale equals 75 */ Tone.Scale = function (outputMin, outputMax) { /** * @private * @type {number} */ this._outputMin = this.defaultArg(outputMin, 0); /** * @private * @type {number} */ this._outputMax = this.defaultArg(outputMax, 1); /** * @private * @type {Tone.Multiply} * @private */ this._scale = this.input = new Tone.Multiply(1); /** * @private * @type {Tone.Add} * @private */ this._add = this.output = new Tone.Add(0); this._scale.connect(this._add); this._setRange(); }; Tone.extend(Tone.Scale, Tone.SignalBase); /** * The minimum output value. This number is output when * the value input value is 0. * @memberOf Tone.Scale# * @type {number} * @name min */ Object.defineProperty(Tone.Scale.prototype, 'min', { get: function () { return this._outputMin; }, set: function (min) { this._outputMin = min; this._setRange(); } }); /** * The maximum output value. This number is output when * the value input value is 1. * @memberOf Tone.Scale# * @type {number} * @name max */ Object.defineProperty(Tone.Scale.prototype, 'max', { get: function () { return this._outputMax; }, set: function (max) { this._outputMax = max; this._setRange(); } }); /** * set the values * @private */ Tone.Scale.prototype._setRange = function () { this._add.value = this._outputMin; this._scale.value = this._outputMax - this._outputMin; }; /** * Clean up. * @returns {Tone.Scale} this */ Tone.Scale.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._add.dispose(); this._add = null; this._scale.dispose(); this._scale = null; return this; }; return Tone.Scale; }); Module(function (Tone) { /** * @class Performs an exponential scaling on an input signal. * Scales a NormalRange value [0,1] exponentially * to the output range of outputMin to outputMax. * * @constructor * @extends {Tone.SignalBase} * @param {number} [outputMin=0] The output value when the input is 0. * @param {number} [outputMax=1] The output value when the input is 1. * @param {number} [exponent=2] The exponent which scales the incoming signal. * @example * var scaleExp = new Tone.ScaleExp(0, 100, 2); * var signal = new Tone.Signal(0.5).connect(scaleExp); */ Tone.ScaleExp = function (outputMin, outputMax, exponent) { /** * scale the input to the output range * @type {Tone.Scale} * @private */ this._scale = this.output = new Tone.Scale(outputMin, outputMax); /** * @private * @type {Tone.Pow} * @private */ this._exp = this.input = new Tone.Pow(this.defaultArg(exponent, 2)); this._exp.connect(this._scale); }; Tone.extend(Tone.ScaleExp, Tone.SignalBase); /** * Instead of interpolating linearly between the <code>min</code> and * <code>max</code> values, setting the exponent will interpolate between * the two values with an exponential curve. * @memberOf Tone.ScaleExp# * @type {number} * @name exponent */ Object.defineProperty(Tone.ScaleExp.prototype, 'exponent', { get: function () { return this._exp.value; }, set: function (exp) { this._exp.value = exp; } }); /** * The minimum output value. This number is output when * the value input value is 0. * @memberOf Tone.ScaleExp# * @type {number} * @name min */ Object.defineProperty(Tone.ScaleExp.prototype, 'min', { get: function () { return this._scale.min; }, set: function (min) { this._scale.min = min; } }); /** * The maximum output value. This number is output when * the value input value is 1. * @memberOf Tone.ScaleExp# * @type {number} * @name max */ Object.defineProperty(Tone.ScaleExp.prototype, 'max', { get: function () { return this._scale.max; }, set: function (max) { this._scale.max = max; } }); /** * Clean up. * @returns {Tone.ScaleExp} this */ Tone.ScaleExp.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._scale.dispose(); this._scale = null; this._exp.dispose(); this._exp = null; return this; }; return Tone.ScaleExp; }); Module(function (Tone) { /** * @class Comb filters are basic building blocks for physical modeling. Read more * about comb filters on [CCRMA's website](https://ccrma.stanford.edu/~jos/pasp/Feedback_Comb_Filters.html). * * @extends {Tone} * @constructor * @param {Time|Object} [delayTime] The delay time of the filter. * @param {NormalRange=} resonance The amount of feedback the filter has. */ Tone.FeedbackCombFilter = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'delayTime', 'resonance' ], Tone.FeedbackCombFilter.defaults); /** * the delay node * @type {DelayNode} * @private */ this._delay = this.input = this.output = this.context.createDelay(1); /** * The amount of delay of the comb filter. * @type {Time} * @signal */ this.delayTime = new Tone.Param({ 'param': this._delay.delayTime, 'value': options.delayTime, 'units': Tone.Type.Time }); /** * the feedback node * @type {GainNode} * @private */ this._feedback = this.context.createGain(); /** * The amount of feedback of the delayed signal. * @type {NormalRange} * @signal */ this.resonance = new Tone.Param({ 'param': this._feedback.gain, 'value': options.resonance, 'units': Tone.Type.NormalRange }); this._delay.chain(this._feedback, this._delay); this._readOnly([ 'resonance', 'delayTime' ]); }; Tone.extend(Tone.FeedbackCombFilter); /** * the default parameters * @static * @const * @type {Object} */ Tone.FeedbackCombFilter.defaults = { 'delayTime': 0.1, 'resonance': 0.5 }; /** * clean up * @returns {Tone.FeedbackCombFilter} this */ Tone.FeedbackCombFilter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'resonance', 'delayTime' ]); this._delay.disconnect(); this._delay = null; this.delayTime.dispose(); this.delayTime = null; this.resonance.dispose(); this.resonance = null; this._feedback.disconnect(); this._feedback = null; return this; }; return Tone.FeedbackCombFilter; }); Module(function (Tone) { /** * @class Tone.Follower is a crude envelope follower which will follow * the amplitude of an incoming signal. * Take care with small (< 0.02) attack or decay values * as follower has some ripple which is exaggerated * at these values. Read more about envelope followers (also known * as envelope detectors) on [Wikipedia](https://en.wikipedia.org/wiki/Envelope_detector). * * @constructor * @extends {Tone} * @param {Time|Object} [attack] The rate at which the follower rises. * @param {Time=} release The rate at which the folower falls. * @example * var follower = new Tone.Follower(0.2, 0.4); */ Tone.Follower = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'attack', 'release' ], Tone.Follower.defaults); /** * @type {Tone.Abs} * @private */ this._abs = new Tone.Abs(); /** * the lowpass filter which smooths the input * @type {BiquadFilterNode} * @private */ this._filter = this.context.createBiquadFilter(); this._filter.type = 'lowpass'; this._filter.frequency.value = 0; this._filter.Q.value = -100; /** * @type {WaveShaperNode} * @private */ this._frequencyValues = new Tone.WaveShaper(); /** * @type {Tone.Subtract} * @private */ this._sub = new Tone.Subtract(); /** * @type {DelayNode} * @private */ this._delay = this.context.createDelay(); this._delay.delayTime.value = this.blockTime; /** * this keeps it far from 0, even for very small differences * @type {Tone.Multiply} * @private */ this._mult = new Tone.Multiply(10000); /** * @private * @type {number} */ this._attack = options.attack; /** * @private * @type {number} */ this._release = options.release; //the smoothed signal to get the values this.input.chain(this._abs, this._filter, this.output); //the difference path this._abs.connect(this._sub, 0, 1); this._filter.chain(this._delay, this._sub); //threshold the difference and use the thresh to set the frequency this._sub.chain(this._mult, this._frequencyValues, this._filter.frequency); //set the attack and release values in the table this._setAttackRelease(this._attack, this._release); }; Tone.extend(Tone.Follower); /** * @static * @type {Object} */ Tone.Follower.defaults = { 'attack': 0.05, 'release': 0.5 }; /** * sets the attack and release times in the wave shaper * @param {Time} attack * @param {Time} release * @private */ Tone.Follower.prototype._setAttackRelease = function (attack, release) { var minTime = this.blockTime; attack = this.secondsToFrequency(this.toSeconds(attack)); release = this.secondsToFrequency(this.toSeconds(release)); attack = Math.max(attack, minTime); release = Math.max(release, minTime); this._frequencyValues.setMap(function (val) { if (val <= 0) { return attack; } else { return release; } }); }; /** * The attack time. * @memberOf Tone.Follower# * @type {Time} * @name attack */ Object.defineProperty(Tone.Follower.prototype, 'attack', { get: function () { return this._attack; }, set: function (attack) { this._attack = attack; this._setAttackRelease(this._attack, this._release); } }); /** * The release time. * @memberOf Tone.Follower# * @type {Time} * @name release */ Object.defineProperty(Tone.Follower.prototype, 'release', { get: function () { return this._release; }, set: function (release) { this._release = release; this._setAttackRelease(this._attack, this._release); } }); /** * Borrows the connect method from Signal so that the output can be used * as a Tone.Signal control signal. * @function */ Tone.Follower.prototype.connect = Tone.Signal.prototype.connect; /** * dispose * @returns {Tone.Follower} this */ Tone.Follower.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._filter.disconnect(); this._filter = null; this._frequencyValues.disconnect(); this._frequencyValues = null; this._delay.disconnect(); this._delay = null; this._sub.disconnect(); this._sub = null; this._abs.dispose(); this._abs = null; this._mult.dispose(); this._mult = null; this._curve = null; return this; }; return Tone.Follower; }); Module(function (Tone) { /** * @class Tone.ScaledEnvelop is an envelope which can be scaled * to any range. It's useful for applying an envelope * to a frequency or any other non-NormalRange signal * parameter. * * @extends {Tone.Envelope} * @constructor * @param {Time|Object} [attack] the attack time in seconds * @param {Time} [decay] the decay time in seconds * @param {number} [sustain] a percentage (0-1) of the full amplitude * @param {Time} [release] the release time in seconds * @example * var scaledEnv = new Tone.ScaledEnvelope({ * "attack" : 0.2, * "min" : 200, * "max" : 2000 * }); * scaledEnv.connect(oscillator.frequency); */ Tone.ScaledEnvelope = function () { //get all of the defaults var options = this.optionsObject(arguments, [ 'attack', 'decay', 'sustain', 'release' ], Tone.Envelope.defaults); Tone.Envelope.call(this, options); options = this.defaultArg(options, Tone.ScaledEnvelope.defaults); /** * scale the incoming signal by an exponent * @type {Tone.Pow} * @private */ this._exp = this.output = new Tone.Pow(options.exponent); /** * scale the signal to the desired range * @type {Tone.Multiply} * @private */ this._scale = this.output = new Tone.Scale(options.min, options.max); this._sig.chain(this._exp, this._scale); }; Tone.extend(Tone.ScaledEnvelope, Tone.Envelope); /** * the default parameters * @static */ Tone.ScaledEnvelope.defaults = { 'min': 0, 'max': 1, 'exponent': 1 }; /** * The envelope's min output value. This is the value which it * starts at. * @memberOf Tone.ScaledEnvelope# * @type {number} * @name min */ Object.defineProperty(Tone.ScaledEnvelope.prototype, 'min', { get: function () { return this._scale.min; }, set: function (min) { this._scale.min = min; } }); /** * The envelope's max output value. In other words, the value * at the peak of the attack portion of the envelope. * @memberOf Tone.ScaledEnvelope# * @type {number} * @name max */ Object.defineProperty(Tone.ScaledEnvelope.prototype, 'max', { get: function () { return this._scale.max; }, set: function (max) { this._scale.max = max; } }); /** * The envelope's exponent value. * @memberOf Tone.ScaledEnvelope# * @type {number} * @name exponent */ Object.defineProperty(Tone.ScaledEnvelope.prototype, 'exponent', { get: function () { return this._exp.value; }, set: function (exp) { this._exp.value = exp; } }); /** * clean up * @returns {Tone.ScaledEnvelope} this */ Tone.ScaledEnvelope.prototype.dispose = function () { Tone.Envelope.prototype.dispose.call(this); this._scale.dispose(); this._scale = null; this._exp.dispose(); this._exp = null; return this; }; return Tone.ScaledEnvelope; }); Module(function (Tone) { /** * @class Tone.FrequencyEnvelope is a Tone.ScaledEnvelope, but instead of `min` and `max` * it's got a `baseFrequency` and `octaves` parameter. * * @extends {Tone.Envelope} * @constructor * @param {Time|Object} [attack] the attack time in seconds * @param {Time} [decay] the decay time in seconds * @param {number} [sustain] a percentage (0-1) of the full amplitude * @param {Time} [release] the release time in seconds * @example * var env = new Tone.FrequencyEnvelope({ * "attack" : 0.2, * "baseFrequency" : "C2", * "octaves" : 4 * }); * scaledEnv.connect(oscillator.frequency); */ Tone.FrequencyEnvelope = function () { var options = this.optionsObject(arguments, [ 'attack', 'decay', 'sustain', 'release' ], Tone.Envelope.defaults); Tone.ScaledEnvelope.call(this, options); options = this.defaultArg(options, Tone.FrequencyEnvelope.defaults); /** * Stores the octave value * @type {Positive} * @private */ this._octaves = options.octaves; //setup this.baseFrequency = options.baseFrequency; this.octaves = options.octaves; }; Tone.extend(Tone.FrequencyEnvelope, Tone.Envelope); /** * the default parameters * @static */ Tone.FrequencyEnvelope.defaults = { 'baseFrequency': 200, 'octaves': 4, 'exponent': 2 }; /** * The envelope's mininum output value. This is the value which it * starts at. * @memberOf Tone.FrequencyEnvelope# * @type {Frequency} * @name baseFrequency */ Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'baseFrequency', { get: function () { return this._scale.min; }, set: function (min) { this._scale.min = this.toFrequency(min); } }); /** * The number of octaves above the baseFrequency that the * envelope will scale to. * @memberOf Tone.FrequencyEnvelope# * @type {Positive} * @name octaves */ Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (octaves) { this._octaves = octaves; this._scale.max = this.baseFrequency * Math.pow(2, octaves); } }); /** * The envelope's exponent value. * @memberOf Tone.FrequencyEnvelope# * @type {number} * @name exponent */ Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'exponent', { get: function () { return this._exp.value; }, set: function (exp) { this._exp.value = exp; } }); /** * clean up * @returns {Tone.FrequencyEnvelope} this */ Tone.FrequencyEnvelope.prototype.dispose = function () { Tone.ScaledEnvelope.prototype.dispose.call(this); return this; }; return Tone.FrequencyEnvelope; }); Module(function (Tone) { /** * @class Tone.Gate only passes a signal through when the incoming * signal exceeds a specified threshold. To do this, Gate uses * a Tone.Follower to follow the amplitude of the incoming signal. * A common implementation of this class is a [Noise Gate](https://en.wikipedia.org/wiki/Noise_gate). * * @constructor * @extends {Tone} * @param {Decibels|Object} [threshold] The threshold above which the gate will open. * @param {Time=} attack The follower's attack time * @param {Time=} release The follower's release time * @example * var gate = new Tone.Gate(-30, 0.2, 0.3).toMaster(); * var mic = new Tone.Microphone().connect(gate); * //the gate will only pass through the incoming * //signal when it's louder than -30db */ Tone.Gate = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'threshold', 'attack', 'release' ], Tone.Gate.defaults); /** * @type {Tone.Follower} * @private */ this._follower = new Tone.Follower(options.attack, options.release); /** * @type {Tone.GreaterThan} * @private */ this._gt = new Tone.GreaterThan(this.dbToGain(options.threshold)); //the connections this.input.connect(this.output); //the control signal this.input.chain(this._gt, this._follower, this.output.gain); }; Tone.extend(Tone.Gate); /** * @const * @static * @type {Object} */ Tone.Gate.defaults = { 'attack': 0.1, 'release': 0.1, 'threshold': -40 }; /** * The threshold of the gate in decibels * @memberOf Tone.Gate# * @type {Decibels} * @name threshold */ Object.defineProperty(Tone.Gate.prototype, 'threshold', { get: function () { return this.gainToDb(this._gt.value); }, set: function (thresh) { this._gt.value = this.dbToGain(thresh); } }); /** * The attack speed of the gate * @memberOf Tone.Gate# * @type {Time} * @name attack */ Object.defineProperty(Tone.Gate.prototype, 'attack', { get: function () { return this._follower.attack; }, set: function (attackTime) { this._follower.attack = attackTime; } }); /** * The release speed of the gate * @memberOf Tone.Gate# * @type {Time} * @name release */ Object.defineProperty(Tone.Gate.prototype, 'release', { get: function () { return this._follower.release; }, set: function (releaseTime) { this._follower.release = releaseTime; } }); /** * Clean up. * @returns {Tone.Gate} this */ Tone.Gate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._follower.dispose(); this._gt.dispose(); this._follower = null; this._gt = null; return this; }; return Tone.Gate; }); Module(function (Tone) { /** * @class A Timeline State. Provides the methods: <code>setStateAtTime("state", time)</code> * and <code>getStateAtTime(time)</code>. * * @extends {Tone.Timeline} * @param {String} initial The initial state of the TimelineState. * Defaults to <code>undefined</code> */ Tone.TimelineState = function (initial) { Tone.Timeline.call(this); /** * The initial state * @private * @type {String} */ this._initial = initial; }; Tone.extend(Tone.TimelineState, Tone.Timeline); /** * Returns the scheduled state scheduled before or at * the given time. * @param {Time} time The time to query. * @return {String} The name of the state input in setStateAtTime. */ Tone.TimelineState.prototype.getStateAtTime = function (time) { var event = this.getEvent(time); if (event !== null) { return event.state; } else { return this._initial; } }; /** * Returns the scheduled state scheduled before or at * the given time. * @param {String} state The name of the state to set. * @param {Time} time The time to query. */ Tone.TimelineState.prototype.setStateAtTime = function (state, time) { this.addEvent({ 'state': state, 'time': this.toSeconds(time) }); }; return Tone.TimelineState; }); Module(function (Tone) { /** * @class A sample accurate clock which provides a callback at the given rate. * While the callback is not sample-accurate (it is still susceptible to * loose JS timing), the time passed in as the argument to the callback * is precise. For most applications, it is better to use Tone.Transport * instead of the Clock by itself since you can synchronize multiple callbacks. * * @constructor * @extends {Tone} * @param {function} callback The callback to be invoked with the time of the audio event * @param {Frequency} frequency The rate of the callback * @example * //the callback will be invoked approximately once a second * //and will print the time exactly once a second apart. * var clock = new Tone.Clock(function(time){ * console.log(time); * }, 1); */ Tone.Clock = function () { var options = this.optionsObject(arguments, [ 'callback', 'frequency' ], Tone.Clock.defaults); /** * The callback function to invoke at the scheduled tick. * @type {Function} */ this.callback = options.callback; /** * The time which the clock will schedule events in advance * of the current time. Scheduling notes in advance improves * performance and decreases the chance for clicks caused * by scheduling events in the past. If set to "auto", * this value will be automatically computed based on the * rate of requestAnimationFrame (0.016 seconds). Larger values * will yeild better performance, but at the cost of latency. * Values less than 0.016 are not recommended. * @type {Number|String} */ this._lookAhead = 'auto'; /** * The lookahead value which was automatically * computed using a time-based averaging. * @type {Number} * @private */ this._computedLookAhead = 1 / 60; /** * The value afterwhich events are thrown out * @type {Number} * @private */ this._threshold = 0.5; /** * The next time the callback is scheduled. * @type {Number} * @private */ this._nextTick = -1; /** * The last time the callback was invoked * @type {Number} * @private */ this._lastUpdate = 0; /** * The id of the requestAnimationFrame * @type {Number} * @private */ this._loopID = -1; /** * The rate the callback function should be invoked. * @type {BPM} * @signal */ this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency); /** * The number of times the callback was invoked. Starts counting at 0 * and increments after the callback was invoked. * @type {Ticks} * @readOnly */ this.ticks = 0; /** * The state timeline * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * A pre-binded loop function to save a tiny bit of overhead * of rebinding the function on every frame. * @type {Function} * @private */ this._boundLoop = this._loop.bind(this); this._readOnly('frequency'); //start the loop this._loop(); }; Tone.extend(Tone.Clock); /** * The defaults * @const * @type {Object} */ Tone.Clock.defaults = { 'callback': Tone.noOp, 'frequency': 1, 'lookAhead': 'auto' }; /** * Returns the playback state of the source, either "started", "stopped" or "paused". * @type {Tone.State} * @readOnly * @memberOf Tone.Clock# * @name state */ Object.defineProperty(Tone.Clock.prototype, 'state', { get: function () { return this._state.getStateAtTime(this.now()); } }); /** * The time which the clock will schedule events in advance * of the current time. Scheduling notes in advance improves * performance and decreases the chance for clicks caused * by scheduling events in the past. If set to "auto", * this value will be automatically computed based on the * rate of requestAnimationFrame (0.016 seconds). Larger values * will yeild better performance, but at the cost of latency. * Values less than 0.016 are not recommended. * @type {Number|String} * @memberOf Tone.Clock# * @name lookAhead */ Object.defineProperty(Tone.Clock.prototype, 'lookAhead', { get: function () { return this._lookAhead; }, set: function (val) { if (val === 'auto') { this._lookAhead = 'auto'; } else { this._lookAhead = this.toSeconds(val); } } }); /** * Start the clock at the given time. Optionally pass in an offset * of where to start the tick counter from. * @param {Time} time The time the clock should start * @param {Ticks=} offset Where the tick counter starts counting from. * @return {Tone.Clock} this */ Tone.Clock.prototype.start = function (time, offset) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Started) { this._state.addEvent({ 'state': Tone.State.Started, 'time': time, 'offset': offset }); } return this; }; /** * Stop the clock. Stopping the clock resets the tick counter to 0. * @param {Time} [time=now] The time when the clock should stop. * @returns {Tone.Clock} this * @example * clock.stop(); */ Tone.Clock.prototype.stop = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Stopped) { this._state.setStateAtTime(Tone.State.Stopped, time); } return this; }; /** * Pause the clock. Pausing does not reset the tick counter. * @param {Time} [time=now] The time when the clock should stop. * @returns {Tone.Clock} this */ Tone.Clock.prototype.pause = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Paused, time); } return this; }; /** * The scheduling loop. * @param {Number} time The current page time starting from 0 * when the page was loaded. * @private */ Tone.Clock.prototype._loop = function (time) { this._loopID = requestAnimationFrame(this._boundLoop); //compute the look ahead if (this._lookAhead === 'auto') { if (!this.isUndef(time)) { var diff = (time - this._lastUpdate) / 1000; this._lastUpdate = time; //throw away large differences if (diff < this._threshold) { //averaging this._computedLookAhead = (9 * this._computedLookAhead + diff) / 10; } } } else { this._computedLookAhead = this._lookAhead; } //get the frequency value to compute the value of the next loop var now = this.now(); //if it's started var lookAhead = this._computedLookAhead * 2; var event = this._state.getEvent(now + lookAhead); var state = Tone.State.Stopped; if (event) { state = event.state; //if it was stopped and now started if (this._nextTick === -1 && state === Tone.State.Started) { this._nextTick = event.time; if (!this.isUndef(event.offset)) { this.ticks = event.offset; } } } if (state === Tone.State.Started) { while (now + lookAhead > this._nextTick) { //catch up if (now > this._nextTick + this._threshold) { this._nextTick = now; } var tickTime = this._nextTick; this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick); this.callback(tickTime); this.ticks++; } } else if (state === Tone.State.Stopped) { this._nextTick = -1; this.ticks = 0; } }; /** * Returns the scheduled state at the given time. * @param {Time} time The time to query. * @return {String} The name of the state input in setStateAtTime. * @example * clock.start("+0.1"); * clock.getStateAtTime("+0.1"); //returns "started" */ Tone.Clock.prototype.getStateAtTime = function (time) { return this._state.getStateAtTime(time); }; /** * Clean up * @returns {Tone.Clock} this */ Tone.Clock.prototype.dispose = function () { cancelAnimationFrame(this._loopID); Tone.TimelineState.prototype.dispose.call(this); this._writable('frequency'); this.frequency.dispose(); this.frequency = null; this._boundLoop = Tone.noOp; this._nextTick = Infinity; this.callback = null; this._state.dispose(); this._state = null; }; return Tone.Clock; }); Module(function (Tone) { /** * @class Tone.Emitter gives classes which extend it * the ability to listen for and trigger events. * Inspiration and reference from Jerome Etienne's [MicroEvent](https://github.com/jeromeetienne/microevent.js). * MIT (c) 2011 Jerome Etienne. * * @extends {Tone} */ Tone.Emitter = function () { /** * Contains all of the events. * @private * @type {Object} */ this._events = {}; }; Tone.extend(Tone.Emitter); /** * Bind a callback to a specific event. * @param {String} event The name of the event to listen for. * @param {Function} callback The callback to invoke when the * event is triggered * @return {Tone.Emitter} this */ Tone.Emitter.prototype.on = function (event, callback) { //split the event var events = event.split(/\W+/); for (var i = 0; i < events.length; i++) { var eventName = events[i]; if (!this._events.hasOwnProperty(eventName)) { this._events[eventName] = []; } this._events[eventName].push(callback); } return this; }; /** * Remove the event listener. * @param {String} event The event to stop listening to. * @param {Function=} callback The callback which was bound to * the event with Tone.Emitter.on. * If no callback is given, all callbacks * events are removed. * @return {Tone.Emitter} this */ Tone.Emitter.prototype.off = function (event, callback) { var events = event.split(/\W+/); for (var ev = 0; ev < events.length; ev++) { event = events[ev]; if (this._events.hasOwnProperty(event)) { if (Tone.prototype.isUndef(callback)) { this._events[event] = []; } else { var eventList = this._events[event]; for (var i = 0; i < eventList.length; i++) { if (eventList[i] === callback) { eventList.splice(i, 1); } } } } } return this; }; /** * Invoke all of the callbacks bound to the event * with any arguments passed in. * @param {String} event The name of the event. * @param {*...} args The arguments to pass to the functions listening. * @return {Tone.Emitter} this */ Tone.Emitter.prototype.trigger = function (event) { if (this._events) { var args = Array.prototype.slice.call(arguments, 1); if (this._events.hasOwnProperty(event)) { var eventList = this._events[event]; for (var i = 0, len = eventList.length; i < len; i++) { eventList[i].apply(this, args); } } } return this; }; /** * Add Emitter functions (on/off/trigger) to the object * @param {Object|Function} object The object or class to extend. */ Tone.Emitter.mixin = function (object) { var functions = [ 'on', 'off', 'trigger' ]; object._events = {}; for (var i = 0; i < functions.length; i++) { var func = functions[i]; var emitterFunc = Tone.Emitter.prototype[func]; object[func] = emitterFunc; } }; /** * Clean up * @return {Tone.Emitter} this */ Tone.Emitter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._events = null; return this; }; return Tone.Emitter; }); Module(function (Tone) { /** * @class Similar to Tone.Timeline, but all events represent * intervals with both "time" and "duration" times. The * events are placed in a tree structure optimized * for querying an intersection point with the timeline * events. Internally uses an [Interval Tree](https://en.wikipedia.org/wiki/Interval_tree) * to represent the data. * @extends {Tone} */ Tone.IntervalTimeline = function () { /** * The root node of the inteval tree * @type {IntervalNode} * @private */ this._root = null; /** * Keep track of the length of the timeline. * @type {Number} * @private */ this._length = 0; }; Tone.extend(Tone.IntervalTimeline); /** * The event to add to the timeline. All events must * have a time and duration value * @param {Object} event The event to add to the timeline * @return {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.addEvent = function (event) { if (this.isUndef(event.time) || this.isUndef(event.duration)) { throw new Error('events must have time and duration parameters'); } var node = new IntervalNode(event.time, event.time + event.duration, event); if (this._root === null) { this._root = node; } else { this._root.insert(node); } this._length++; // Restructure tree to be balanced while (node !== null) { node.updateHeight(); node.updateMax(); this._rebalance(node); node = node.parent; } return this; }; /** * Remove an event from the timeline. * @param {Object} event The event to remove from the timeline * @return {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.removeEvent = function (event) { if (this._root !== null) { var results = []; this._root.search(event.time, results); for (var i = 0; i < results.length; i++) { var node = results[i]; if (node.event === event) { this._removeNode(node); this._length--; break; } } } return this; }; /** * The number of items in the timeline. * @type {Number} * @memberOf Tone.IntervalTimeline# * @name length * @readOnly */ Object.defineProperty(Tone.IntervalTimeline.prototype, 'length', { get: function () { return this._length; } }); /** * Remove events whose time time is after the given time * @param {Time} time The time to query. * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.cancel = function (after) { after = this.toSeconds(after); this.forEachAfter(after, function (event) { this.removeEvent(event); }.bind(this)); return this; }; /** * Set the root node as the given node * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._setRoot = function (node) { this._root = node; if (this._root !== null) { this._root.parent = null; } }; /** * Replace the references to the node in the node's parent * with the replacement node. * @param {IntervalNode} node * @param {IntervalNode} replacement * @private */ Tone.IntervalTimeline.prototype._replaceNodeInParent = function (node, replacement) { if (node.parent !== null) { if (node.isLeftChild()) { node.parent.left = replacement; } else { node.parent.right = replacement; } this._rebalance(node.parent); } else { this._setRoot(replacement); } }; /** * Remove the node from the tree and replace it with * a successor which follows the schema. * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._removeNode = function (node) { if (node.left === null && node.right === null) { this._replaceNodeInParent(node, null); } else if (node.right === null) { this._replaceNodeInParent(node, node.left); } else if (node.left === null) { this._replaceNodeInParent(node, node.right); } else { var balance = node.getBalance(); var replacement, temp; if (balance > 0) { if (node.left.right === null) { replacement = node.left; replacement.right = node.right; temp = replacement; } else { replacement = node.left.right; while (replacement.right !== null) { replacement = replacement.right; } replacement.parent.right = replacement.left; temp = replacement.parent; replacement.left = node.left; replacement.right = node.right; } } else { if (node.right.left === null) { replacement = node.right; replacement.left = node.left; temp = replacement; } else { replacement = node.right.left; while (replacement.left !== null) { replacement = replacement.left; } replacement.parent = replacement.parent; replacement.parent.left = replacement.right; temp = replacement.parent; replacement.left = node.left; replacement.right = node.right; } } if (node.parent !== null) { if (node.isLeftChild()) { node.parent.left = replacement; } else { node.parent.right = replacement; } } else { this._setRoot(replacement); } // this._replaceNodeInParent(node, replacement); this._rebalance(temp); } node.dispose(); }; /** * Rotate the tree to the left * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._rotateLeft = function (node) { var parent = node.parent; var isLeftChild = node.isLeftChild(); // Make node.right the new root of this sub tree (instead of node) var pivotNode = node.right; node.right = pivotNode.left; pivotNode.left = node; if (parent !== null) { if (isLeftChild) { parent.left = pivotNode; } else { parent.right = pivotNode; } } else { this._setRoot(pivotNode); } }; /** * Rotate the tree to the right * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._rotateRight = function (node) { var parent = node.parent; var isLeftChild = node.isLeftChild(); // Make node.left the new root of this sub tree (instead of node) var pivotNode = node.left; node.left = pivotNode.right; pivotNode.right = node; if (parent !== null) { if (isLeftChild) { parent.left = pivotNode; } else { parent.right = pivotNode; } } else { this._setRoot(pivotNode); } }; /** * Balance the BST * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._rebalance = function (node) { var balance = node.getBalance(); if (balance > 1) { if (node.left.getBalance() < 0) { this._rotateLeft(node.left); } else { this._rotateRight(node); } } else if (balance < -1) { if (node.right.getBalance() > 0) { this._rotateRight(node.right); } else { this._rotateLeft(node); } } }; /** * Get an event whose time and duration span the give time. Will * return the match whose "time" value is closest to the given time. * @param {Object} event The event to add to the timeline * @return {Object} The event which spans the desired time */ Tone.IntervalTimeline.prototype.getEvent = function (time) { if (this._root !== null) { var results = []; this._root.search(time, results); if (results.length > 0) { var max = results[0]; for (var i = 1; i < results.length; i++) { if (results[i].low > max.low) { max = results[i]; } } return max.event; } } return null; }; /** * Iterate over everything in the timeline. * @param {Function} callback The callback to invoke with every item * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.forEach = function (callback) { if (this._root !== null) { var allNodes = []; if (this._root !== null) { this._root.traverse(function (node) { allNodes.push(node); }); } for (var i = 0; i < allNodes.length; i++) { var ev = allNodes[i].event; if (ev) { callback(ev); } } } return this; }; /** * Iterate over everything in the array in which the given time * overlaps with the time and duration time of the event. * @param {Time} time The time to check if items are overlapping * @param {Function} callback The callback to invoke with every item * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.forEachOverlap = function (time, callback) { time = this.toSeconds(time); if (this._root !== null) { var results = []; this._root.search(time, results); for (var i = results.length - 1; i >= 0; i--) { var ev = results[i].event; if (ev) { callback(ev); } } } return this; }; /** * Iterate over everything in the array in which the time is greater * than the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.forEachAfter = function (time, callback) { time = this.toSeconds(time); if (this._root !== null) { var results = []; this._root.searchAfter(time, results); for (var i = results.length - 1; i >= 0; i--) { var ev = results[i].event; if (ev) { callback(ev); } } } return this; }; /** * Clean up * @return {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.dispose = function () { var allNodes = []; if (this._root !== null) { this._root.traverse(function (node) { allNodes.push(node); }); } for (var i = 0; i < allNodes.length; i++) { allNodes[i].dispose(); } allNodes = null; this._root = null; return this; }; /////////////////////////////////////////////////////////////////////////// // INTERVAL NODE HELPER /////////////////////////////////////////////////////////////////////////// /** * Represents a node in the binary search tree, with the addition * of a "high" value which keeps track of the highest value of * its children. * References: * https://brooknovak.wordpress.com/2013/12/07/augmented-interval-tree-in-c/ * http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf * @param {Number} low * @param {Number} high * @private */ var IntervalNode = function (low, high, event) { //the event container this.event = event; //the low value this.low = low; //the high value this.high = high; //the high value for this and all child nodes this.max = this.high; //the nodes to the left this._left = null; //the nodes to the right this._right = null; //the parent node this.parent = null; //the number of child nodes this.height = 0; }; /** * Insert a node into the correct spot in the tree * @param {IntervalNode} node */ IntervalNode.prototype.insert = function (node) { if (node.low <= this.low) { if (this.left === null) { this.left = node; } else { this.left.insert(node); } } else { if (this.right === null) { this.right = node; } else { this.right.insert(node); } } }; /** * Search the tree for nodes which overlap * with the given point * @param {Number} point The point to query * @param {Array} results The array to put the results */ IntervalNode.prototype.search = function (point, results) { // If p is to the right of the rightmost point of any interval // in this node and all children, there won't be any matches. if (point > this.max) { return; } // Search left children if (this.left !== null) { this.left.search(point, results); } // Check this node if (this.low <= point && this.high >= point) { results.push(this); } // If p is to the left of the time of this interval, // then it can't be in any child to the right. if (this.low > point) { return; } // Search right children if (this.right !== null) { this.right.search(point, results); } }; /** * Search the tree for nodes which are less * than the given point * @param {Number} point The point to query * @param {Array} results The array to put the results */ IntervalNode.prototype.searchAfter = function (point, results) { // Check this node if (this.low >= point) { results.push(this); if (this.left !== null) { this.left.searchAfter(point, results); } } // search the right side if (this.right !== null) { this.right.searchAfter(point, results); } }; /** * Invoke the callback on this element and both it's branches * @param {Function} callback */ IntervalNode.prototype.traverse = function (callback) { callback(this); if (this.left !== null) { this.left.traverse(callback); } if (this.right !== null) { this.right.traverse(callback); } }; /** * Update the height of the node */ IntervalNode.prototype.updateHeight = function () { if (this.left !== null && this.right !== null) { this.height = Math.max(this.left.height, this.right.height) + 1; } else if (this.right !== null) { this.height = this.right.height + 1; } else if (this.left !== null) { this.height = this.left.height + 1; } else { this.height = 0; } }; /** * Update the height of the node */ IntervalNode.prototype.updateMax = function () { this.max = this.high; if (this.left !== null) { this.max = Math.max(this.max, this.left.max); } if (this.right !== null) { this.max = Math.max(this.max, this.right.max); } }; /** * The balance is how the leafs are distributed on the node * @return {Number} Negative numbers are balanced to the right */ IntervalNode.prototype.getBalance = function () { var balance = 0; if (this.left !== null && this.right !== null) { balance = this.left.height - this.right.height; } else if (this.left !== null) { balance = this.left.height + 1; } else if (this.right !== null) { balance = -(this.right.height + 1); } return balance; }; /** * @returns {Boolean} true if this node is the left child * of its parent */ IntervalNode.prototype.isLeftChild = function () { return this.parent !== null && this.parent.left === this; }; /** * get/set the left node * @type {IntervalNode} */ Object.defineProperty(IntervalNode.prototype, 'left', { get: function () { return this._left; }, set: function (node) { this._left = node; if (node !== null) { node.parent = this; } this.updateHeight(); this.updateMax(); } }); /** * get/set the right node * @type {IntervalNode} */ Object.defineProperty(IntervalNode.prototype, 'right', { get: function () { return this._right; }, set: function (node) { this._right = node; if (node !== null) { node.parent = this; } this.updateHeight(); this.updateMax(); } }); /** * null out references. */ IntervalNode.prototype.dispose = function () { this.parent = null; this._left = null; this._right = null; this.event = null; }; /////////////////////////////////////////////////////////////////////////// // END INTERVAL NODE HELPER /////////////////////////////////////////////////////////////////////////// return Tone.IntervalTimeline; }); Module(function (Tone) { /** * @class Transport for timing musical events. * Supports tempo curves and time changes. Unlike browser-based timing (setInterval, requestAnimationFrame) * Tone.Transport timing events pass in the exact time of the scheduled event * in the argument of the callback function. Pass that time value to the object * you're scheduling. <br><br> * A single transport is created for you when the library is initialized. * <br><br> * The transport emits the events: "start", "stop", "pause", and "loop" which are * called with the time of that event as the argument. * * @extends {Tone.Emitter} * @singleton * @example * //repeated event every 8th note * Tone.Transport.setInterval(function(time){ * //do something with the time * }, "8n"); * @example * //one time event 1 second in the future * Tone.Transport.setTimeout(function(time){ * //do something with the time * }, 1); * @example * //event fixed to the Transports timeline. * Tone.Transport.setTimeline(function(time){ * //do something with the time * }, "16:0:0"); */ Tone.Transport = function () { Tone.Emitter.call(this); /////////////////////////////////////////////////////////////////////// // LOOPING ////////////////////////////////////////////////////////////////////// /** * If the transport loops or not. * @type {boolean} */ this.loop = false; /** * The loop start position in ticks * @type {Ticks} * @private */ this._loopStart = 0; /** * The loop end position in ticks * @type {Ticks} * @private */ this._loopEnd = 0; /////////////////////////////////////////////////////////////////////// // CLOCK/TEMPO ////////////////////////////////////////////////////////////////////// /** * Pulses per quarter is the number of ticks per quarter note. * @private * @type {Number} */ this._ppq = TransportConstructor.defaults.PPQ; /** * watches the main oscillator for timing ticks * initially starts at 120bpm * @private * @type {Tone.Clock} */ this._clock = new Tone.Clock({ 'callback': this._processTick.bind(this), 'frequency': 0 }); /** * The Beats Per Minute of the Transport. * @type {BPM} * @signal * @example * Tone.Transport.bpm.value = 80; * //ramp the bpm to 120 over 10 seconds * Tone.Transport.bpm.rampTo(120, 10); */ this.bpm = this._clock.frequency; this.bpm._toUnits = this._toUnits.bind(this); this.bpm._fromUnits = this._fromUnits.bind(this); this.bpm.units = Tone.Type.BPM; this.bpm.value = TransportConstructor.defaults.bpm; this._readOnly('bpm'); /** * The time signature, or more accurately the numerator * of the time signature over a denominator of 4. * @type {Number} * @private */ this._timeSignature = TransportConstructor.defaults.timeSignature; /////////////////////////////////////////////////////////////////////// // TIMELINE EVENTS ////////////////////////////////////////////////////////////////////// /** * All the events in an object to keep track by ID * @type {Object} * @private */ this._scheduledEvents = {}; /** * The event ID counter * @type {Number} * @private */ this._eventID = 0; /** * The scheduled events. * @type {Tone.Timeline} * @private */ this._timeline = new Tone.Timeline(); /** * Repeated events * @type {Array} * @private */ this._repeatedEvents = new Tone.IntervalTimeline(); /** * Events that occur once * @type {Array} * @private */ this._onceEvents = new Tone.Timeline(); /** * All of the synced Signals * @private * @type {Array} */ this._syncedSignals = []; /////////////////////////////////////////////////////////////////////// // SWING ////////////////////////////////////////////////////////////////////// var swingSeconds = this.notationToSeconds(TransportConstructor.defaults.swingSubdivision, TransportConstructor.defaults.bpm, TransportConstructor.defaults.timeSignature); /** * The subdivision of the swing * @type {Ticks} * @private */ this._swingTicks = swingSeconds / (60 / TransportConstructor.defaults.bpm) * this._ppq; /** * The swing amount * @type {NormalRange} * @private */ this._swingAmount = 0; }; Tone.extend(Tone.Transport, Tone.Emitter); /** * the defaults * @type {Object} * @const * @static */ Tone.Transport.defaults = { 'bpm': 120, 'swing': 0, 'swingSubdivision': '16n', 'timeSignature': 4, 'loopStart': 0, 'loopEnd': '4m', 'PPQ': 48 }; /////////////////////////////////////////////////////////////////////////////// // TICKS /////////////////////////////////////////////////////////////////////////////// /** * called on every tick * @param {number} tickTime clock relative tick time * @private */ Tone.Transport.prototype._processTick = function (tickTime) { //handle swing if (this._swingAmount > 0 && this._clock.ticks % this._ppq !== 0 && //not on a downbeat this._clock.ticks % this._swingTicks === 0) { //add some swing tickTime += this.ticksToSeconds(this._swingTicks) * this._swingAmount; } //do the loop test if (this.loop) { if (this._clock.ticks === this._loopEnd) { this.ticks = this._loopStart; this.trigger('loop', tickTime); } } var ticks = this._clock.ticks; //fire the next tick events if their time has come this._timeline.forEachAtTime(ticks, function (event) { event.callback(tickTime); }); //process the repeated events this._repeatedEvents.forEachOverlap(ticks, function (event) { if ((ticks - event.time) % event.interval === 0) { event.callback(tickTime); } }); //process the single occurrence events this._onceEvents.forEachBefore(ticks, function (event) { event.callback(tickTime); }); //and clear the single occurrence timeline this._onceEvents.cancelBefore(ticks); }; /////////////////////////////////////////////////////////////////////////////// // SCHEDULABLE EVENTS /////////////////////////////////////////////////////////////////////////////// /** * Schedule an event along the timeline. * @param {Function} callback The callback to be invoked at the time. * @param {Time} time The time to invoke the callback at. * @return {Number} The id of the event which can be used for canceling the event. * @example * //trigger the callback when the Transport reaches the desired time * Tone.Transport.schedule(function(time){ * envelope.triggerAttack(time); * }, "128i"); */ Tone.Transport.prototype.schedule = function (callback, time) { var event = { 'time': this.toTicks(time), 'callback': callback }; var id = this._eventID++; this._scheduledEvents[id.toString()] = { 'event': event, 'timeline': this._timeline }; this._timeline.addEvent(event); return id; }; /** * Schedule a repeated event along the timeline. The event will fire * at the `interval` starting at the `startTime` and for the specified * `duration`. * @param {Function} callback The callback to invoke. * @param {Time} interval The duration between successive * callbacks. * @param {Time=} startTime When along the timeline the events should * start being invoked. * @param {Time} [duration=Infinity] How long the event should repeat. * @return {Number} The ID of the scheduled event. Use this to cancel * the event. * @example * //a callback invoked every eighth note after the first measure * Tone.Transport.scheduleRepeat(callback, "8n", "1m"); */ Tone.Transport.prototype.scheduleRepeat = function (callback, interval, startTime, duration) { if (interval <= 0) { throw new Error('repeat events must have an interval larger than 0'); } var event = { 'time': this.toTicks(startTime), 'duration': this.toTicks(this.defaultArg(duration, Infinity)), 'interval': this.toTicks(interval), 'callback': callback }; var id = this._eventID++; this._scheduledEvents[id.toString()] = { 'event': event, 'timeline': this._repeatedEvents }; this._repeatedEvents.addEvent(event); return id; }; /** * Schedule an event that will be removed after it is invoked. * Note that if the given time is less than the current transport time, * the event will be invoked immediately. * @param {Function} callback The callback to invoke once. * @param {Time} time The time the callback should be invoked. * @returns {Number} The ID of the scheduled event. */ Tone.Transport.prototype.scheduleOnce = function (callback, time) { var event = { 'time': this.toTicks(time), 'callback': callback }; var id = this._eventID++; this._scheduledEvents[id.toString()] = { 'event': event, 'timeline': this._onceEvents }; this._onceEvents.addEvent(event); return id; }; /** * Clear the passed in event id from the timeline * @param {Number} eventId The id of the event. * @returns {Tone.Transport} this */ Tone.Transport.prototype.clear = function (eventId) { if (this._scheduledEvents.hasOwnProperty(eventId)) { var item = this._scheduledEvents[eventId.toString()]; item.timeline.removeEvent(item.event); delete this._scheduledEvents[eventId.toString()]; } return this; }; /** * Remove scheduled events from the timeline after * the given time. Repeated events will be removed * if their startTime is after the given time * @param {Time} [after=0] Clear all events after * this time. * @returns {Tone.Transport} this */ Tone.Transport.prototype.cancel = function (after) { after = this.defaultArg(after, 0); after = this.toTicks(after); this._timeline.cancel(after); this._onceEvents.cancel(after); this._repeatedEvents.cancel(after); return this; }; /////////////////////////////////////////////////////////////////////////////// // QUANTIZATION /////////////////////////////////////////////////////////////////////////////// /** * Returns the time closest time (equal to or after the given time) that aligns * to the subidivision. * @param {Time} time The time value to quantize to the given subdivision * @param {String} [subdivision="4n"] The subdivision to quantize to. * @return {Number} the time in seconds until the next subdivision. * @example * Tone.Transport.bpm.value = 120; * Tone.Transport.quantize("3 * 4n", "1m"); //return 0.5 * //if the clock is started, it will return a value less than 0.5 */ Tone.Transport.prototype.quantize = function (time, subdivision) { subdivision = this.defaultArg(subdivision, '4n'); var tickTime = this.toTicks(time); subdivision = this.toTicks(subdivision); var remainingTicks = subdivision - tickTime % subdivision; if (remainingTicks === subdivision) { remainingTicks = 0; } var now = this.now(); if (this.state === Tone.State.Started) { now = this._clock._nextTick; } return this.toSeconds(time, now) + this.ticksToSeconds(remainingTicks); }; /////////////////////////////////////////////////////////////////////////////// // START/STOP/PAUSE /////////////////////////////////////////////////////////////////////////////// /** * Returns the playback state of the source, either "started", "stopped", or "paused" * @type {Tone.State} * @readOnly * @memberOf Tone.Transport# * @name state */ Object.defineProperty(Tone.Transport.prototype, 'state', { get: function () { return this._clock.getStateAtTime(this.now()); } }); /** * Start the transport and all sources synced to the transport. * @param {Time} [time=now] The time when the transport should start. * @param {Time=} offset The timeline offset to start the transport. * @returns {Tone.Transport} this * @example * //start the transport in one second starting at beginning of the 5th measure. * Tone.Transport.start("+1", "4:0:0"); */ Tone.Transport.prototype.start = function (time, offset) { time = this.toSeconds(time); if (!this.isUndef(offset)) { offset = this.toTicks(offset); } else { offset = this.defaultArg(offset, this._clock.ticks); } //start the clock this._clock.start(time, offset); this.trigger('start', time, this.ticksToSeconds(offset)); return this; }; /** * Stop the transport and all sources synced to the transport. * @param {Time} [time=now] The time when the transport should stop. * @returns {Tone.Transport} this * @example * Tone.Transport.stop(); */ Tone.Transport.prototype.stop = function (time) { time = this.toSeconds(time); this._clock.stop(time); this.trigger('stop', time); return this; }; /** * Pause the transport and all sources synced to the transport. * @param {Time} [time=now] * @returns {Tone.Transport} this */ Tone.Transport.prototype.pause = function (time) { time = this.toSeconds(time); this._clock.pause(time); this.trigger('pause', time); return this; }; /////////////////////////////////////////////////////////////////////////////// // SETTERS/GETTERS /////////////////////////////////////////////////////////////////////////////// /** * The time signature as just the numerator over 4. * For example 4/4 would be just 4 and 6/8 would be 3. * @memberOf Tone.Transport# * @type {Number|Array} * @name timeSignature * @example * //common time * Tone.Transport.timeSignature = 4; * // 7/8 * Tone.Transport.timeSignature = [7, 8]; * //this will be reduced to a single number * Tone.Transport.timeSignature; //returns 3.5 */ Object.defineProperty(Tone.Transport.prototype, 'timeSignature', { get: function () { return this._timeSignature; }, set: function (timeSig) { if (this.isArray(timeSig)) { timeSig = timeSig[0] / timeSig[1] * 4; } this._timeSignature = timeSig; } }); /** * When the Tone.Transport.loop = true, this is the starting position of the loop. * @memberOf Tone.Transport# * @type {Time} * @name loopStart */ Object.defineProperty(Tone.Transport.prototype, 'loopStart', { get: function () { return this.ticksToSeconds(this._loopStart); }, set: function (startPosition) { this._loopStart = this.toTicks(startPosition); } }); /** * When the Tone.Transport.loop = true, this is the ending position of the loop. * @memberOf Tone.Transport# * @type {Time} * @name loopEnd */ Object.defineProperty(Tone.Transport.prototype, 'loopEnd', { get: function () { return this.ticksToSeconds(this._loopEnd); }, set: function (endPosition) { this._loopEnd = this.toTicks(endPosition); } }); /** * Set the loop start and stop at the same time. * @param {Time} startPosition * @param {Time} endPosition * @returns {Tone.Transport} this * @example * //loop over the first measure * Tone.Transport.setLoopPoints(0, "1m"); * Tone.Transport.loop = true; */ Tone.Transport.prototype.setLoopPoints = function (startPosition, endPosition) { this.loopStart = startPosition; this.loopEnd = endPosition; return this; }; /** * The swing value. Between 0-1 where 1 equal to * the note + half the subdivision. * @memberOf Tone.Transport# * @type {NormalRange} * @name swing */ Object.defineProperty(Tone.Transport.prototype, 'swing', { get: function () { return this._swingAmount * 2; }, set: function (amount) { //scale the values to a normal range this._swingAmount = amount * 0.5; } }); /** * Set the subdivision which the swing will be applied to. * The default values is a 16th note. Value must be less * than a quarter note. * * @memberOf Tone.Transport# * @type {Time} * @name swingSubdivision */ Object.defineProperty(Tone.Transport.prototype, 'swingSubdivision', { get: function () { return this.toNotation(this._swingTicks + 'i'); }, set: function (subdivision) { this._swingTicks = this.toTicks(subdivision); } }); /** * The Transport's position in MEASURES:BEATS:SIXTEENTHS. * Setting the value will jump to that position right away. * * @memberOf Tone.Transport# * @type {TransportTime} * @name position */ Object.defineProperty(Tone.Transport.prototype, 'position', { get: function () { var quarters = this.ticks / this._ppq; var measures = Math.floor(quarters / this._timeSignature); var sixteenths = quarters % 1 * 4; //if the sixteenths aren't a whole number, fix their length if (sixteenths % 1 > 0) { sixteenths = sixteenths.toFixed(3); } quarters = Math.floor(quarters) % this._timeSignature; var progress = [ measures, quarters, sixteenths ]; return progress.join(':'); }, set: function (progress) { var ticks = this.toTicks(progress); this.ticks = ticks; } }); /** * The Transport's loop position as a normalized value. Always * returns 0 if the transport if loop is not true. * @memberOf Tone.Transport# * @name progress * @type {NormalRange} */ Object.defineProperty(Tone.Transport.prototype, 'progress', { get: function () { if (this.loop) { return (this.ticks - this._loopStart) / (this._loopEnd - this._loopStart); } else { return 0; } } }); /** * The transports current tick position. * * @memberOf Tone.Transport# * @type {Ticks} * @name ticks */ Object.defineProperty(Tone.Transport.prototype, 'ticks', { get: function () { return this._clock.ticks; }, set: function (t) { this._clock.ticks = t; } }); /** * Pulses Per Quarter note. This is the smallest resolution * the Transport timing supports. This should be set once * on initialization and not set again. Changing this value * after other objects have been created can cause problems. * * @memberOf Tone.Transport# * @type {Number} * @name PPQ */ Object.defineProperty(Tone.Transport.prototype, 'PPQ', { get: function () { return this._ppq; }, set: function (ppq) { this._ppq = ppq; this.bpm.value = this.bpm.value; } }); /** * Convert from BPM to frequency (factoring in PPQ) * @param {BPM} bpm The BPM value to convert to frequency * @return {Frequency} The BPM as a frequency with PPQ factored in. * @private */ Tone.Transport.prototype._fromUnits = function (bpm) { return 1 / (60 / bpm / this.PPQ); }; /** * Convert from frequency (with PPQ) into BPM * @param {Frequency} freq The clocks frequency to convert to BPM * @return {BPM} The frequency value as BPM. * @private */ Tone.Transport.prototype._toUnits = function (freq) { return freq / this.PPQ * 60; }; /////////////////////////////////////////////////////////////////////////////// // SYNCING /////////////////////////////////////////////////////////////////////////////// /** * Attaches the signal to the tempo control signal so that * any changes in the tempo will change the signal in the same * ratio. * * @param {Tone.Signal} signal * @param {number=} ratio Optionally pass in the ratio between * the two signals. Otherwise it will be computed * based on their current values. * @returns {Tone.Transport} this */ Tone.Transport.prototype.syncSignal = function (signal, ratio) { if (!ratio) { //get the sync ratio if (signal._param.value !== 0) { ratio = signal._param.value / this.bpm._param.value; } else { ratio = 0; } } var ratioSignal = new Tone.Gain(ratio); this.bpm.chain(ratioSignal, signal._param); this._syncedSignals.push({ 'ratio': ratioSignal, 'signal': signal, 'initial': signal._param.value }); signal._param.value = 0; return this; }; /** * Unsyncs a previously synced signal from the transport's control. * See Tone.Transport.syncSignal. * @param {Tone.Signal} signal * @returns {Tone.Transport} this */ Tone.Transport.prototype.unsyncSignal = function (signal) { for (var i = this._syncedSignals.length - 1; i >= 0; i--) { var syncedSignal = this._syncedSignals[i]; if (syncedSignal.signal === signal) { syncedSignal.ratio.dispose(); syncedSignal.signal._param.value = syncedSignal.initial; this._syncedSignals.splice(i, 1); } } return this; }; /** * Clean up. * @returns {Tone.Transport} this * @private */ Tone.Transport.prototype.dispose = function () { Tone.Emitter.prototype.dispose.call(this); this._clock.dispose(); this._clock = null; this._writable('bpm'); this.bpm = null; this._timeline.dispose(); this._timeline = null; this._onceEvents.dispose(); this._onceEvents = null; this._repeatedEvents.dispose(); this._repeatedEvents = null; return this; }; /////////////////////////////////////////////////////////////////////////////// // DEPRECATED FUNCTIONS // (will be removed in r7) /////////////////////////////////////////////////////////////////////////////// /** * @deprecated Use Tone.scheduleRepeat instead. * Set a callback for a recurring event. * @param {function} callback * @param {Time} interval * @return {number} the id of the interval * @example * //triggers a callback every 8th note with the exact time of the event * Tone.Transport.setInterval(function(time){ * envelope.triggerAttack(time); * }, "8n"); * @private */ Tone.Transport.prototype.setInterval = function (callback, interval) { console.warn('This method is deprecated. Use Tone.Transport.scheduleRepeat instead.'); return Tone.Transport.scheduleRepeat(callback, interval); }; /** * @deprecated Use Tone.cancel instead. * Stop and ongoing interval. * @param {number} intervalID The ID of interval to remove. The interval * ID is given as the return value in Tone.Transport.setInterval. * @return {boolean} true if the event was removed * @private */ Tone.Transport.prototype.clearInterval = function (id) { console.warn('This method is deprecated. Use Tone.Transport.clear instead.'); return Tone.Transport.clear(id); }; /** * @deprecated Use Tone.Note instead. * Set a timeout to occur after time from now. NB: the transport must be * running for this to be triggered. All timeout events are cleared when the * transport is stopped. * * @param {function} callback * @param {Time} time The time (from now) that the callback will be invoked. * @return {number} The id of the timeout. * @example * //trigger an event to happen 1 second from now * Tone.Transport.setTimeout(function(time){ * player.start(time); * }, 1) * @private */ Tone.Transport.prototype.setTimeout = function (callback, timeout) { console.warn('This method is deprecated. Use Tone.Transport.scheduleOnce instead.'); return Tone.Transport.scheduleOnce(callback, timeout); }; /** * @deprecated Use Tone.Note instead. * Clear a timeout using it's ID. * @param {number} intervalID The ID of timeout to remove. The timeout * ID is given as the return value in Tone.Transport.setTimeout. * @return {boolean} true if the timeout was removed * @private */ Tone.Transport.prototype.clearTimeout = function (id) { console.warn('This method is deprecated. Use Tone.Transport.clear instead.'); return Tone.Transport.clear(id); }; /** * @deprecated Use Tone.Note instead. * Timeline events are synced to the timeline of the Tone.Transport. * Unlike Timeout, Timeline events will restart after the * Tone.Transport has been stopped and restarted. * * @param {function} callback * @param {Time} time * @return {number} the id for clearing the transportTimeline event * @example * //trigger the start of a part on the 16th measure * Tone.Transport.setTimeline(function(time){ * part.start(time); * }, "16m"); * @private */ Tone.Transport.prototype.setTimeline = function (callback, time) { console.warn('This method is deprecated. Use Tone.Transport.schedule instead.'); return Tone.Transport.schedule(callback, time); }; /** * @deprecated Use Tone.Note instead. * Clear the timeline event. * @param {number} id * @return {boolean} true if it was removed * @private */ Tone.Transport.prototype.clearTimeline = function (id) { console.warn('This method is deprecated. Use Tone.Transport.clear instead.'); return Tone.Transport.clear(id); }; /////////////////////////////////////////////////////////////////////////////// // INITIALIZATION /////////////////////////////////////////////////////////////////////////////// var TransportConstructor = Tone.Transport; Tone._initAudioContext(function () { if (typeof Tone.Transport === 'function') { //a single transport object Tone.Transport = new Tone.Transport(); } else { //stop the clock Tone.Transport.stop(); //get the previous values var prevSettings = Tone.Transport.get(); //destory the old transport Tone.Transport.dispose(); //make new Transport insides TransportConstructor.call(Tone.Transport); //set the previous config Tone.Transport.set(prevSettings); } }); return Tone.Transport; }); Module(function (Tone) { /** * @class Tone.Volume is a simple volume node, useful for creating a volume fader. * * @extends {Tone} * @constructor * @param {Decibels} [volume=0] the initial volume * @example * var vol = new Tone.Volume(-12); * instrument.chain(vol, Tone.Master); */ Tone.Volume = function () { var options = this.optionsObject(arguments, ['volume'], Tone.Volume.defaults); /** * the output node * @type {GainNode} * @private */ this.output = this.input = new Tone.Gain(options.volume, Tone.Type.Decibels); /** * The volume control in decibels. * @type {Decibels} * @signal */ this.volume = this.output.gain; this._readOnly('volume'); }; Tone.extend(Tone.Volume); /** * Defaults * @type {Object} * @const * @static */ Tone.Volume.defaults = { 'volume': 0 }; /** * clean up * @returns {Tone.Volume} this */ Tone.Volume.prototype.dispose = function () { this.input.dispose(); Tone.prototype.dispose.call(this); this._writable('volume'); this.volume.dispose(); this.volume = null; return this; }; return Tone.Volume; }); Module(function (Tone) { /** * @class Base class for sources. Sources have start/stop methods * and the ability to be synced to the * start/stop of Tone.Transport. * * @constructor * @extends {Tone} * @example * //Multiple state change events can be chained together, * //but must be set in the correct order and with ascending times * * // OK * state.start().stop("+0.2"); * // AND * state.start().stop("+0.2").start("+0.4").stop("+0.7") * * // BAD * state.stop("+0.2").start(); * // OR * state.start("+0.3").stop("+0.2"); * */ Tone.Source = function (options) { //Sources only have an output and no input Tone.call(this); options = this.defaultArg(options, Tone.Source.defaults); /** * The output volume node * @type {Tone.Volume} * @private */ this._volume = this.output = new Tone.Volume(options.volume); /** * The volume of the output in decibels. * @type {Decibels} * @signal * @example * source.volume.value = -6; */ this.volume = this._volume.volume; this._readOnly('volume'); /** * Keep track of the scheduled state. * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * The synced `start` callback function from the transport * @type {Function} * @private */ this._syncStart = function (time, offset) { time = this.toSeconds(time); time += this.toSeconds(this._startDelay); this.start(time, offset); }.bind(this); /** * The synced `stop` callback function from the transport * @type {Function} * @private */ this._syncStop = this.stop.bind(this); /** * The offset from the start of the Transport `start` * @type {Time} * @private */ this._startDelay = 0; //make the output explicitly stereo this._volume.output.output.channelCount = 2; this._volume.output.output.channelCountMode = 'explicit'; }; Tone.extend(Tone.Source); /** * The default parameters * @static * @const * @type {Object} */ Tone.Source.defaults = { 'volume': 0 }; /** * Returns the playback state of the source, either "started" or "stopped". * @type {Tone.State} * @readOnly * @memberOf Tone.Source# * @name state */ Object.defineProperty(Tone.Source.prototype, 'state', { get: function () { return this._state.getStateAtTime(this.now()); } }); /** * Start the source at the specified time. If no time is given, * start the source now. * @param {Time} [time=now] When the source should be started. * @returns {Tone.Source} this * @example * source.start("+0.5"); //starts the source 0.5 seconds from now */ Tone.Source.prototype.start = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Started || this.retrigger) { this._state.setStateAtTime(Tone.State.Started, time); if (this._start) { this._start.apply(this, arguments); } } return this; }; /** * Stop the source at the specified time. If no time is given, * stop the source now. * @param {Time} [time=now] When the source should be stopped. * @returns {Tone.Source} this * @example * source.stop(); // stops the source immediately */ Tone.Source.prototype.stop = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Stopped, time); if (this._stop) { this._stop.apply(this, arguments); } } return this; }; /** * Sync the source to the Transport so that when the transport * is started, this source is started and when the transport is stopped * or paused, so is the source. * * @param {Time} [delay=0] Delay time before starting the source after the * Transport has started. * @returns {Tone.Source} this * @example * //sync the source to start 1 measure after the transport starts * source.sync("1m"); * //start the transport. the source will start 1 measure later. * Tone.Transport.start(); */ Tone.Source.prototype.sync = function (delay) { this._startDelay = this.defaultArg(delay, 0); Tone.Transport.on('start', this._syncStart); Tone.Transport.on('stop pause', this._syncStop); return this; }; /** * Unsync the source to the Transport. See Tone.Source.sync * @returns {Tone.Source} this */ Tone.Source.prototype.unsync = function () { this._startDelay = 0; Tone.Transport.off('start', this._syncStart); Tone.Transport.off('stop pause', this._syncStop); return this; }; /** * Clean up. * @return {Tone.Source} this */ Tone.Source.prototype.dispose = function () { this.stop(); Tone.prototype.dispose.call(this); this.unsync(); this._writable('volume'); this._volume.dispose(); this._volume = null; this.volume = null; this._state.dispose(); this._state = null; this._syncStart = null; this._syncStart = null; }; return Tone.Source; }); Module(function (Tone) { /** * @class Tone.Oscillator supports a number of features including * phase rotation, multiple oscillator types (see Tone.Oscillator.type), * and Transport syncing (see Tone.Oscillator.syncFrequency). * * @constructor * @extends {Tone.Source} * @param {Frequency} [frequency] Starting frequency * @param {string} [type] The oscillator type. Read more about type below. * @example * //make and start a 440hz sine tone * var osc = new Tone.Oscillator(440, "sine").toMaster().start(); */ Tone.Oscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'type' ], Tone.Oscillator.defaults); Tone.Source.call(this, options); /** * the main oscillator * @type {OscillatorNode} * @private */ this._oscillator = null; /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The detune control signal. * @type {Cents} * @signal */ this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); /** * the periodic wave * @type {PeriodicWave} * @private */ this._wave = null; /** * The partials of the oscillator * @type {Array} * @private */ this._partials = this.defaultArg(options.partials, [1]); /** * the phase of the oscillator * between 0 - 360 * @type {number} * @private */ this._phase = options.phase; /** * the type of the oscillator * @type {string} * @private */ this._type = null; //setup this.type = options.type; this.phase = this._phase; this._readOnly([ 'frequency', 'detune' ]); }; Tone.extend(Tone.Oscillator, Tone.Source); /** * the default parameters * @type {Object} */ Tone.Oscillator.defaults = { 'type': 'sine', 'frequency': 440, 'detune': 0, 'phase': 0, 'partials': [] }; /** * The Oscillator types * @enum {String} */ Tone.Oscillator.Type = { Sine: 'sine', Triangle: 'triangle', Sawtooth: 'sawtooth', Square: 'square', Custom: 'custom' }; /** * start the oscillator * @param {Time} [time=now] * @private */ Tone.Oscillator.prototype._start = function (time) { //new oscillator with previous values this._oscillator = this.context.createOscillator(); this._oscillator.setPeriodicWave(this._wave); //connect the control signal to the oscillator frequency & detune this._oscillator.connect(this.output); this.frequency.connect(this._oscillator.frequency); this.detune.connect(this._oscillator.detune); //start the oscillator this._oscillator.start(this.toSeconds(time)); }; /** * stop the oscillator * @private * @param {Time} [time=now] (optional) timing parameter * @returns {Tone.Oscillator} this */ Tone.Oscillator.prototype._stop = function (time) { if (this._oscillator) { this._oscillator.stop(this.toSeconds(time)); this._oscillator = null; } return this; }; /** * Sync the signal to the Transport's bpm. Any changes to the transports bpm, * will also affect the oscillators frequency. * @returns {Tone.Oscillator} this * @example * Tone.Transport.bpm.value = 120; * osc.frequency.value = 440; * //the ration between the bpm and the frequency will be maintained * osc.syncFrequency(); * Tone.Transport.bpm.value = 240; * // the frequency of the oscillator is doubled to 880 */ Tone.Oscillator.prototype.syncFrequency = function () { Tone.Transport.syncSignal(this.frequency); return this; }; /** * Unsync the oscillator's frequency from the Transport. * See Tone.Oscillator.syncFrequency * @returns {Tone.Oscillator} this */ Tone.Oscillator.prototype.unsyncFrequency = function () { Tone.Transport.unsyncSignal(this.frequency); return this; }; /** * The type of the oscillator: either sine, square, triangle, or sawtooth. Also capable of * setting the first x number of partials of the oscillator. For example: "sine4" would * set be the first 4 partials of the sine wave and "triangle8" would set the first * 8 partials of the triangle wave. * <br><br> * Uses PeriodicWave internally even for native types so that it can set the phase. * PeriodicWave equations are from the * [Webkit Web Audio implementation](https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp&sq=package:chromium). * * @memberOf Tone.Oscillator# * @type {string} * @name type * @example * //set it to a square wave * osc.type = "square"; * @example * //set the first 6 partials of a sawtooth wave * osc.type = "sawtooth6"; */ Object.defineProperty(Tone.Oscillator.prototype, 'type', { get: function () { return this._type; }, set: function (type) { var coefs = this._getRealImaginary(type, this._phase); var periodicWave = this.context.createPeriodicWave(coefs[0], coefs[1]); this._wave = periodicWave; if (this._oscillator !== null) { this._oscillator.setPeriodicWave(this._wave); } this._type = type; } }); /** * Returns the real and imaginary components based * on the oscillator type. * @returns {Array} [real, imaginary] * @private */ Tone.Oscillator.prototype._getRealImaginary = function (type, phase) { var fftSize = 4096; var periodicWaveSize = fftSize / 2; var real = new Float32Array(periodicWaveSize); var imag = new Float32Array(periodicWaveSize); var partialCount = 1; if (type === Tone.Oscillator.Type.Custom) { partialCount = this._partials.length + 1; periodicWaveSize = partialCount; } else { var partial = /^(sine|triangle|square|sawtooth)(\d+)$/.exec(type); if (partial) { partialCount = parseInt(partial[2]) + 1; type = partial[1]; partialCount = Math.max(partialCount, 2); periodicWaveSize = partialCount; } } for (var n = 1; n < periodicWaveSize; ++n) { var piFactor = 2 / (n * Math.PI); var b; switch (type) { case Tone.Oscillator.Type.Sine: b = n <= partialCount ? 1 : 0; break; case Tone.Oscillator.Type.Square: b = n & 1 ? 2 * piFactor : 0; break; case Tone.Oscillator.Type.Sawtooth: b = piFactor * (n & 1 ? 1 : -1); break; case Tone.Oscillator.Type.Triangle: if (n & 1) { b = 2 * (piFactor * piFactor) * (n - 1 >> 1 & 1 ? -1 : 1); } else { b = 0; } break; case Tone.Oscillator.Type.Custom: b = this._partials[n - 1]; break; default: throw new Error('invalid oscillator type: ' + type); } if (b !== 0) { real[n] = -b * Math.sin(phase * n); imag[n] = b * Math.cos(phase * n); } else { real[n] = 0; imag[n] = 0; } } return [ real, imag ]; }; /** * Compute the inverse FFT for a given phase. * @param {Float32Array} real * @param {Float32Array} imag * @param {NormalRange} phase * @return {AudioRange} * @private */ Tone.Oscillator.prototype._inverseFFT = function (real, imag, phase) { var sum = 0; var len = real.length; for (var i = 0; i < len; i++) { sum += real[i] * Math.cos(i * phase) + imag[i] * Math.sin(i * phase); } return sum; }; /** * Returns the initial value of the oscillator. * @return {AudioRange} * @private */ Tone.Oscillator.prototype._getInitialValue = function () { var coefs = this._getRealImaginary(this._type, 0); var real = coefs[0]; var imag = coefs[1]; var maxValue = 0; var twoPi = Math.PI * 2; //check for peaks in 8 places for (var i = 0; i < 8; i++) { maxValue = Math.max(this._inverseFFT(real, imag, i / 8 * twoPi), maxValue); } return -this._inverseFFT(real, imag, this._phase) / maxValue; }; /** * The partials of the waveform. A partial represents * the amplitude at a harmonic. The first harmonic is the * fundamental frequency, the second is the octave and so on * following the harmonic series. * Setting this value will automatically set the type to "custom". * The value is an empty array when the type is not "custom". * @memberOf Tone.Oscillator# * @type {Array} * @name partials * @example * osc.partials = [1, 0.2, 0.01]; */ Object.defineProperty(Tone.Oscillator.prototype, 'partials', { get: function () { if (this._type !== Tone.Oscillator.Type.Custom) { return []; } else { return this._partials; } }, set: function (partials) { this._partials = partials; this.type = Tone.Oscillator.Type.Custom; } }); /** * The phase of the oscillator in degrees. * @memberOf Tone.Oscillator# * @type {Degrees} * @name phase * @example * osc.phase = 180; //flips the phase of the oscillator */ Object.defineProperty(Tone.Oscillator.prototype, 'phase', { get: function () { return this._phase * (180 / Math.PI); }, set: function (phase) { this._phase = phase * Math.PI / 180; //reset the type this.type = this._type; } }); /** * Dispose and disconnect. * @return {Tone.Oscillator} this */ Tone.Oscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); if (this._oscillator !== null) { this._oscillator.disconnect(); this._oscillator = null; } this._wave = null; this._writable([ 'frequency', 'detune' ]); this.frequency.dispose(); this.frequency = null; this.detune.dispose(); this.detune = null; this._partials = null; return this; }; return Tone.Oscillator; }); Module(function (Tone) { /** * @class LFO stands for low frequency oscillator. Tone.LFO produces an output signal * which can be attached to an AudioParam or Tone.Signal * in order to modulate that parameter with an oscillator. The LFO can * also be synced to the transport to start/stop and change when the tempo changes. * * @constructor * @extends {Tone.Oscillator} * @param {Frequency|Object} [frequency] The frequency of the oscillation. Typically, LFOs will be * in the frequency range of 0.1 to 10 hertz. * @param {number=} min The minimum output value of the LFO. * @param {number=} max The maximum value of the LFO. * @example * var lfo = new Tone.LFO("4n", 400, 4000); * lfo.connect(filter.frequency); */ Tone.LFO = function () { var options = this.optionsObject(arguments, [ 'frequency', 'min', 'max' ], Tone.LFO.defaults); /** * The oscillator. * @type {Tone.Oscillator} * @private */ this._oscillator = new Tone.Oscillator({ 'frequency': options.frequency, 'type': options.type }); /** * the lfo's frequency * @type {Frequency} * @signal */ this.frequency = this._oscillator.frequency; /** * The amplitude of the LFO, which controls the output range between * the min and max output. For example if the min is -10 and the max * is 10, setting the amplitude to 0.5 would make the LFO modulate * between -5 and 5. * @type {Number} * @signal */ this.amplitude = this._oscillator.volume; this.amplitude.units = Tone.Type.NormalRange; this.amplitude.value = options.amplitude; /** * The signal which is output when the LFO is stopped * @type {Tone.Signal} * @private */ this._stoppedSignal = new Tone.Signal(0, Tone.Type.AudioRange); /** * The value that the LFO outputs when it's stopped * @type {AudioRange} * @private */ this._stoppedValue = 0; /** * @type {Tone.AudioToGain} * @private */ this._a2g = new Tone.AudioToGain(); /** * @type {Tone.Scale} * @private */ this._scaler = this.output = new Tone.Scale(options.min, options.max); /** * the units of the LFO (used for converting) * @type {Tone.Type} * @private */ this._units = Tone.Type.Default; this.units = options.units; //connect it up this._oscillator.chain(this._a2g, this._scaler); this._stoppedSignal.connect(this._a2g); this._readOnly([ 'amplitude', 'frequency' ]); this.phase = options.phase; }; Tone.extend(Tone.LFO, Tone.Oscillator); /** * the default parameters * * @static * @const * @type {Object} */ Tone.LFO.defaults = { 'type': 'sine', 'min': 0, 'max': 1, 'phase': 0, 'frequency': '4n', 'amplitude': 1, 'units': Tone.Type.Default }; /** * Start the LFO. * @param {Time} [time=now] the time the LFO will start * @returns {Tone.LFO} this */ Tone.LFO.prototype.start = function (time) { time = this.toSeconds(time); this._stoppedSignal.setValueAtTime(0, time); this._oscillator.start(time); return this; }; /** * Stop the LFO. * @param {Time} [time=now] the time the LFO will stop * @returns {Tone.LFO} this */ Tone.LFO.prototype.stop = function (time) { time = this.toSeconds(time); this._stoppedSignal.setValueAtTime(this._stoppedValue, time); this._oscillator.stop(time); return this; }; /** * Sync the start/stop/pause to the transport * and the frequency to the bpm of the transport * * @param {Time} [delay=0] the time to delay the start of the * LFO from the start of the transport * @returns {Tone.LFO} this * @example * lfo.frequency.value = "8n"; * lfo.sync(); * //the rate of the LFO will always be an eighth note, * //even as the tempo changes */ Tone.LFO.prototype.sync = function (delay) { this._oscillator.sync(delay); this._oscillator.syncFrequency(); return this; }; /** * unsync the LFO from transport control * @returns {Tone.LFO} this */ Tone.LFO.prototype.unsync = function () { this._oscillator.unsync(); this._oscillator.unsyncFrequency(); return this; }; /** * The miniumum output of the LFO. * @memberOf Tone.LFO# * @type {number} * @name min */ Object.defineProperty(Tone.LFO.prototype, 'min', { get: function () { return this._toUnits(this._scaler.min); }, set: function (min) { min = this._fromUnits(min); this._scaler.min = min; } }); /** * The maximum output of the LFO. * @memberOf Tone.LFO# * @type {number} * @name max */ Object.defineProperty(Tone.LFO.prototype, 'max', { get: function () { return this._toUnits(this._scaler.max); }, set: function (max) { max = this._fromUnits(max); this._scaler.max = max; } }); /** * The type of the oscillator: sine, square, sawtooth, triangle. * @memberOf Tone.LFO# * @type {string} * @name type */ Object.defineProperty(Tone.LFO.prototype, 'type', { get: function () { return this._oscillator.type; }, set: function (type) { this._oscillator.type = type; this._stoppedValue = this._oscillator._getInitialValue(); this._stoppedSignal.value = this._stoppedValue; } }); /** * The phase of the LFO. * @memberOf Tone.LFO# * @type {number} * @name phase */ Object.defineProperty(Tone.LFO.prototype, 'phase', { get: function () { return this._oscillator.phase; }, set: function (phase) { this._oscillator.phase = phase; this._stoppedValue = this._oscillator._getInitialValue(); this._stoppedSignal.value = this._stoppedValue; } }); /** * The output units of the LFO. * @memberOf Tone.LFO# * @type {Tone.Type} * @name units */ Object.defineProperty(Tone.LFO.prototype, 'units', { get: function () { return this._units; }, set: function (val) { var currentMin = this.min; var currentMax = this.max; //convert the min and the max this._units = val; this.min = currentMin; this.max = currentMax; } }); /** * Returns the playback state of the source, either "started" or "stopped". * @type {Tone.State} * @readOnly * @memberOf Tone.LFO# * @name state */ Object.defineProperty(Tone.LFO.prototype, 'state', { get: function () { return this._oscillator.state; } }); /** * Connect the output of the LFO to an AudioParam, AudioNode, or Tone Node. * Tone.LFO will automatically convert to the destination units of the * will get the units from the connected node. * @param {Tone | AudioParam | AudioNode} node * @param {number} [outputNum=0] optionally which output to connect from * @param {number} [inputNum=0] optionally which input to connect to * @returns {Tone.LFO} this * @private */ Tone.LFO.prototype.connect = function (node) { if (node.constructor === Tone.Signal || node.constructor === Tone.Param || node.constructor === Tone.TimelineSignal) { this.convert = node.convert; this.units = node.units; } Tone.Signal.prototype.connect.apply(this, arguments); return this; }; /** * private method borrowed from Param converts * units from their destination value * @function * @private */ Tone.LFO.prototype._fromUnits = Tone.Param.prototype._fromUnits; /** * private method borrowed from Param converts * units to their destination value * @function * @private */ Tone.LFO.prototype._toUnits = Tone.Param.prototype._toUnits; /** * disconnect and dispose * @returns {Tone.LFO} this */ Tone.LFO.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'amplitude', 'frequency' ]); this._oscillator.dispose(); this._oscillator = null; this._stoppedSignal.dispose(); this._stoppedSignal = null; this._scaler.dispose(); this._scaler = null; this._a2g.dispose(); this._a2g = null; this.frequency = null; this.amplitude = null; return this; }; return Tone.LFO; }); Module(function (Tone) { /** * @class Tone.Limiter will limit the loudness of an incoming signal. * It is composed of a Tone.Compressor with a fast attack * and release. Limiters are commonly used to safeguard against * signal clipping. Unlike a compressor, limiters do not provide * smooth gain reduction and almost completely prevent * additional gain above the threshold. * * @extends {Tone} * @constructor * @param {number} threshold The theshold above which the limiting is applied. * @example * var limiter = new Tone.Limiter(-6); */ Tone.Limiter = function () { var options = this.optionsObject(arguments, ['threshold'], Tone.Limiter.defaults); /** * the compressor * @private * @type {Tone.Compressor} */ this._compressor = this.input = this.output = new Tone.Compressor({ 'attack': 0.001, 'decay': 0.001, 'threshold': options.threshold }); /** * The threshold of of the limiter * @type {Decibel} * @signal */ this.threshold = this._compressor.threshold; this._readOnly('threshold'); }; Tone.extend(Tone.Limiter); /** * The default value * @type {Object} * @const * @static */ Tone.Limiter.defaults = { 'threshold': -12 }; /** * Clean up. * @returns {Tone.Limiter} this */ Tone.Limiter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._compressor.dispose(); this._compressor = null; this._writable('threshold'); this.threshold = null; return this; }; return Tone.Limiter; }); Module(function (Tone) { /** * @class Tone.Lowpass is a lowpass feedback comb filter. It is similar to * Tone.FeedbackCombFilter, but includes a lowpass filter. * * @extends {Tone} * @constructor * @param {Time|Object} [delayTime] The delay time of the comb filter * @param {NormalRange=} resonance The resonance (feedback) of the comb filter * @param {Frequency=} dampening The cutoff of the lowpass filter dampens the * signal as it is fedback. */ Tone.LowpassCombFilter = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'delayTime', 'resonance', 'dampening' ], Tone.LowpassCombFilter.defaults); /** * the delay node * @type {DelayNode} * @private */ this._delay = this.input = this.context.createDelay(1); /** * The delayTime of the comb filter. * @type {Time} * @signal */ this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); /** * the lowpass filter * @type {BiquadFilterNode} * @private */ this._lowpass = this.output = this.context.createBiquadFilter(); this._lowpass.Q.value = 0; this._lowpass.type = 'lowpass'; /** * The dampening control of the feedback * @type {Frequency} * @signal */ this.dampening = new Tone.Param({ 'param': this._lowpass.frequency, 'units': Tone.Type.Frequency, 'value': options.dampening }); /** * the feedback gain * @type {GainNode} * @private */ this._feedback = this.context.createGain(); /** * The amount of feedback of the delayed signal. * @type {NormalRange} * @signal */ this.resonance = new Tone.Param({ 'param': this._feedback.gain, 'units': Tone.Type.NormalRange, 'value': options.resonance }); //connections this._delay.chain(this._lowpass, this._feedback, this._delay); this.delayTime.connect(this._delay.delayTime); this._readOnly([ 'dampening', 'resonance', 'delayTime' ]); }; Tone.extend(Tone.LowpassCombFilter); /** * the default parameters * @static * @const * @type {Object} */ Tone.LowpassCombFilter.defaults = { 'delayTime': 0.1, 'resonance': 0.5, 'dampening': 3000 }; /** * Clean up. * @returns {Tone.LowpassCombFilter} this */ Tone.LowpassCombFilter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'dampening', 'resonance', 'delayTime' ]); this.dampening.dispose(); this.dampening = null; this.resonance.dispose(); this.resonance = null; this._delay.disconnect(); this._delay = null; this._lowpass.disconnect(); this._lowpass = null; this._feedback.disconnect(); this._feedback = null; this.delayTime.dispose(); this.delayTime = null; return this; }; return Tone.LowpassCombFilter; }); Module(function (Tone) { /** * @class Tone.Merge brings two signals into the left and right * channels of a single stereo channel. * * @constructor * @extends {Tone} * @example * var merge = new Tone.Merge().toMaster(); * //routing a sine tone in the left channel * //and noise in the right channel * var osc = new Tone.Oscillator().connect(merge.left); * var noise = new Tone.Noise().connect(merge.right); * //starting our oscillators * noise.start(); * osc.start(); */ Tone.Merge = function () { Tone.call(this, 2, 0); /** * The left input channel. * Alias for <code>input[0]</code> * @type {GainNode} */ this.left = this.input[0] = this.context.createGain(); /** * The right input channel. * Alias for <code>input[1]</code>. * @type {GainNode} */ this.right = this.input[1] = this.context.createGain(); /** * the merger node for the two channels * @type {ChannelMergerNode} * @private */ this._merger = this.output = this.context.createChannelMerger(2); //connections this.left.connect(this._merger, 0, 0); this.right.connect(this._merger, 0, 1); this.left.channelCount = 1; this.right.channelCount = 1; this.left.channelCountMode = 'explicit'; this.right.channelCountMode = 'explicit'; }; Tone.extend(Tone.Merge); /** * Clean up. * @returns {Tone.Merge} this */ Tone.Merge.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.left.disconnect(); this.left = null; this.right.disconnect(); this.right = null; this._merger.disconnect(); this._merger = null; return this; }; return Tone.Merge; }); Module(function (Tone) { /** * @class Tone.Meter gets the [RMS](https://en.wikipedia.org/wiki/Root_mean_square) * of an input signal with some averaging applied. * It can also get the raw value of the signal or the value in dB. For signal * processing, it's better to use Tone.Follower which will produce an audio-rate * envelope follower instead of needing to poll the Meter to get the output. * <br><br> * Meter was inspired by [Chris Wilsons Volume Meter](https://github.com/cwilso/volume-meter/blob/master/volume-meter.js). * * @constructor * @extends {Tone} * @param {number} [channels=1] number of channels being metered * @param {number} [smoothing=0.8] amount of smoothing applied to the volume * @param {number} [clipMemory=0.5] number in seconds that a "clip" should be remembered * @example * var meter = new Tone.Meter(); * var mic = new Tone.Microphone().start(); * //connect mic to the meter * mic.connect(meter); * //use getLevel or getDb * //to access meter level * meter.getLevel(); */ Tone.Meter = function () { var options = this.optionsObject(arguments, [ 'channels', 'smoothing' ], Tone.Meter.defaults); //extends Unit Tone.call(this); /** * The channel count * @type {number} * @private */ this._channels = options.channels; /** * The amount which the decays of the meter are smoothed. Small values * will follow the contours of the incoming envelope more closely than large values. * @type {NormalRange} */ this.smoothing = options.smoothing; /** * The amount of time a clip is remember for. * @type {Time} */ this.clipMemory = options.clipMemory; /** * The value above which the signal is considered clipped. * @type {Number} */ this.clipLevel = options.clipLevel; /** * the rms for each of the channels * @private * @type {Array} */ this._volume = new Array(this._channels); /** * the raw values for each of the channels * @private * @type {Array} */ this._values = new Array(this._channels); //zero out the volume array for (var i = 0; i < this._channels; i++) { this._volume[i] = 0; this._values[i] = 0; } /** * last time the values clipped * @private * @type {Array} */ this._lastClip = new Array(this._channels); //zero out the clip array for (var j = 0; j < this._lastClip.length; j++) { this._lastClip[j] = 0; } /** * @private * @type {ScriptProcessorNode} */ this._jsNode = this.context.createScriptProcessor(options.bufferSize, this._channels, 1); this._jsNode.onaudioprocess = this._onprocess.bind(this); //so it doesn't get garbage collected this._jsNode.noGC(); //signal just passes this.input.connect(this.output); this.input.connect(this._jsNode); }; Tone.extend(Tone.Meter); /** * The defaults * @type {Object} * @static * @const */ Tone.Meter.defaults = { 'smoothing': 0.8, 'bufferSize': 1024, 'clipMemory': 0.5, 'clipLevel': 0.9, 'channels': 1 }; /** * called on each processing frame * @private * @param {AudioProcessingEvent} event */ Tone.Meter.prototype._onprocess = function (event) { var bufferSize = this._jsNode.bufferSize; var smoothing = this.smoothing; for (var channel = 0; channel < this._channels; channel++) { var input = event.inputBuffer.getChannelData(channel); var sum = 0; var total = 0; var x; for (var i = 0; i < bufferSize; i++) { x = input[i]; total += x; sum += x * x; } var average = total / bufferSize; var rms = Math.sqrt(sum / bufferSize); if (rms > 0.9) { this._lastClip[channel] = Date.now(); } this._volume[channel] = Math.max(rms, this._volume[channel] * smoothing); this._values[channel] = average; } }; /** * Get the rms of the signal. * @param {number} [channel=0] which channel * @return {number} the value */ Tone.Meter.prototype.getLevel = function (channel) { channel = this.defaultArg(channel, 0); var vol = this._volume[channel]; if (vol < 0.00001) { return 0; } else { return vol; } }; /** * Get the raw value of the signal. * @param {number=} channel * @return {number} */ Tone.Meter.prototype.getValue = function (channel) { channel = this.defaultArg(channel, 0); return this._values[channel]; }; /** * Get the volume of the signal in dB * @param {number=} channel * @return {Decibels} */ Tone.Meter.prototype.getDb = function (channel) { return this.gainToDb(this.getLevel(channel)); }; /** * @returns {boolean} if the audio has clipped. The value resets * based on the clipMemory defined. */ Tone.Meter.prototype.isClipped = function (channel) { channel = this.defaultArg(channel, 0); return Date.now() - this._lastClip[channel] < this._clipMemory * 1000; }; /** * Clean up. * @returns {Tone.Meter} this */ Tone.Meter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._jsNode.disconnect(); this._jsNode.onaudioprocess = null; this._jsNode = null; this._volume = null; this._values = null; this._lastClip = null; return this; }; return Tone.Meter; }); Module(function (Tone) { /** * @class Tone.Split splits an incoming signal into left and right channels. * * @constructor * @extends {Tone} * @example * var split = new Tone.Split(); * stereoSignal.connect(split); */ Tone.Split = function () { Tone.call(this, 0, 2); /** * @type {ChannelSplitterNode} * @private */ this._splitter = this.input = this.context.createChannelSplitter(2); /** * Left channel output. * Alias for <code>output[0]</code> * @type {GainNode} */ this.left = this.output[0] = this.context.createGain(); /** * Right channel output. * Alias for <code>output[1]</code> * @type {GainNode} */ this.right = this.output[1] = this.context.createGain(); //connections this._splitter.connect(this.left, 0, 0); this._splitter.connect(this.right, 1, 0); }; Tone.extend(Tone.Split); /** * Clean up. * @returns {Tone.Split} this */ Tone.Split.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._splitter.disconnect(); this.left.disconnect(); this.right.disconnect(); this.left = null; this.right = null; this._splitter = null; return this; }; return Tone.Split; }); Module(function (Tone) { /** * @class Mid/Side processing separates the the 'mid' signal * (which comes out of both the left and the right channel) * and the 'side' (which only comes out of the the side channels). <br><br> * <code> * Mid = (Left+Right)/sqrt(2); // obtain mid-signal from left and right<br> * Side = (Left-Right)/sqrt(2); // obtain side-signal from left and righ<br> * </code> * * @extends {Tone} * @constructor */ Tone.MidSideSplit = function () { Tone.call(this, 0, 2); /** * split the incoming signal into left and right channels * @type {Tone.Split} * @private */ this._split = this.input = new Tone.Split(); /** * The mid send. Connect to mid processing. Alias for * <code>output[0]</code> * @type {Tone.Expr} */ this.mid = this.output[0] = new Tone.Expr('($0 + $1) * $2'); /** * The side output. Connect to side processing. Alias for * <code>output[1]</code> * @type {Tone.Expr} */ this.side = this.output[1] = new Tone.Expr('($0 - $1) * $2'); this._split.connect(this.mid, 0, 0); this._split.connect(this.mid, 1, 1); this._split.connect(this.side, 0, 0); this._split.connect(this.side, 1, 1); sqrtTwo.connect(this.mid, 0, 2); sqrtTwo.connect(this.side, 0, 2); }; Tone.extend(Tone.MidSideSplit); /** * a constant signal equal to 1 / sqrt(2) * @type {Number} * @signal * @private * @static */ var sqrtTwo = null; Tone._initAudioContext(function () { sqrtTwo = new Tone.Signal(1 / Math.sqrt(2)); }); /** * clean up * @returns {Tone.MidSideSplit} this */ Tone.MidSideSplit.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.mid.dispose(); this.mid = null; this.side.dispose(); this.side = null; this._split.dispose(); this._split = null; return this; }; return Tone.MidSideSplit; }); Module(function (Tone) { /** * @class Mid/Side processing separates the the 'mid' signal * (which comes out of both the left and the right channel) * and the 'side' (which only comes out of the the side channels). * MidSideMerge merges the mid and side signal after they've been seperated * by Tone.MidSideSplit.<br><br> * <code> * Left = (Mid+Side)/sqrt(2); // obtain left signal from mid and side<br> * Right = (Mid-Side)/sqrt(2); // obtain right signal from mid and side<br> * </code> * * @extends {Tone.StereoEffect} * @constructor */ Tone.MidSideMerge = function () { Tone.call(this, 2, 0); /** * The mid signal input. Alias for * <code>input[0]</code> * @type {GainNode} */ this.mid = this.input[0] = this.context.createGain(); /** * recombine the mid/side into Left * @type {Tone.Expr} * @private */ this._left = new Tone.Expr('($0 + $1) * $2'); /** * The side signal input. Alias for * <code>input[1]</code> * @type {GainNode} */ this.side = this.input[1] = this.context.createGain(); /** * recombine the mid/side into Right * @type {Tone.Expr} * @private */ this._right = new Tone.Expr('($0 - $1) * $2'); /** * Merge the left/right signal back into a stereo signal. * @type {Tone.Merge} * @private */ this._merge = this.output = new Tone.Merge(); this.mid.connect(this._left, 0, 0); this.side.connect(this._left, 0, 1); this.mid.connect(this._right, 0, 0); this.side.connect(this._right, 0, 1); this._left.connect(this._merge, 0, 0); this._right.connect(this._merge, 0, 1); sqrtTwo.connect(this._left, 0, 2); sqrtTwo.connect(this._right, 0, 2); }; Tone.extend(Tone.MidSideMerge); /** * A constant signal equal to 1 / sqrt(2). * @type {Number} * @signal * @private * @static */ var sqrtTwo = null; Tone._initAudioContext(function () { sqrtTwo = new Tone.Signal(1 / Math.sqrt(2)); }); /** * clean up * @returns {Tone.MidSideMerge} this */ Tone.MidSideMerge.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.mid.disconnect(); this.mid = null; this.side.disconnect(); this.side = null; this._left.dispose(); this._left = null; this._right.dispose(); this._right = null; this._merge.dispose(); this._merge = null; return this; }; return Tone.MidSideMerge; }); Module(function (Tone) { /** * @class Tone.MidSideCompressor applies two different compressors to the mid * and side signal components. See Tone.MidSideSplit. * * @extends {Tone} * @param {Object} options The options that are passed to the mid and side * compressors. * @constructor */ Tone.MidSideCompressor = function (options) { options = this.defaultArg(options, Tone.MidSideCompressor.defaults); /** * the mid/side split * @type {Tone.MidSideSplit} * @private */ this._midSideSplit = this.input = new Tone.MidSideSplit(); /** * the mid/side recombination * @type {Tone.MidSideMerge} * @private */ this._midSideMerge = this.output = new Tone.MidSideMerge(); /** * The compressor applied to the mid signal * @type {Tone.Compressor} */ this.mid = new Tone.Compressor(options.mid); /** * The compressor applied to the side signal * @type {Tone.Compressor} */ this.side = new Tone.Compressor(options.side); this._midSideSplit.mid.chain(this.mid, this._midSideMerge.mid); this._midSideSplit.side.chain(this.side, this._midSideMerge.side); this._readOnly([ 'mid', 'side' ]); }; Tone.extend(Tone.MidSideCompressor); /** * @const * @static * @type {Object} */ Tone.MidSideCompressor.defaults = { 'mid': { 'ratio': 3, 'threshold': -24, 'release': 0.03, 'attack': 0.02, 'knee': 16 }, 'side': { 'ratio': 6, 'threshold': -30, 'release': 0.25, 'attack': 0.03, 'knee': 10 } }; /** * Clean up. * @returns {Tone.MidSideCompressor} this */ Tone.MidSideCompressor.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'mid', 'side' ]); this.mid.dispose(); this.mid = null; this.side.dispose(); this.side = null; this._midSideSplit.dispose(); this._midSideSplit = null; this._midSideMerge.dispose(); this._midSideMerge = null; return this; }; return Tone.MidSideCompressor; }); Module(function (Tone) { /** * @class Tone.Mono coerces the incoming mono or stereo signal into a mono signal * where both left and right channels have the same value. This can be useful * for [stereo imaging](https://en.wikipedia.org/wiki/Stereo_imaging). * * @extends {Tone} * @constructor */ Tone.Mono = function () { Tone.call(this, 1, 0); /** * merge the signal * @type {Tone.Merge} * @private */ this._merge = this.output = new Tone.Merge(); this.input.connect(this._merge, 0, 0); this.input.connect(this._merge, 0, 1); this.input.gain.value = this.dbToGain(-10); }; Tone.extend(Tone.Mono); /** * clean up * @returns {Tone.Mono} this */ Tone.Mono.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._merge.dispose(); this._merge = null; return this; }; return Tone.Mono; }); Module(function (Tone) { /** * @class A compressor with seperate controls over low/mid/high dynamics * * @extends {Tone} * @constructor * @param {Object} options The low/mid/high compressor settings. * @example * var multiband = new Tone.MultibandCompressor({ * "lowFrequency" : 200, * "highFrequency" : 1300 * "low" : { * "threshold" : -12 * } * }) */ Tone.MultibandCompressor = function (options) { options = this.defaultArg(arguments, Tone.MultibandCompressor.defaults); /** * split the incoming signal into high/mid/low * @type {Tone.MultibandSplit} * @private */ this._splitter = this.input = new Tone.MultibandSplit({ 'lowFrequency': options.lowFrequency, 'highFrequency': options.highFrequency }); /** * low/mid crossover frequency. * @type {Frequency} * @signal */ this.lowFrequency = this._splitter.lowFrequency; /** * mid/high crossover frequency. * @type {Frequency} * @signal */ this.highFrequency = this._splitter.highFrequency; /** * the output * @type {GainNode} * @private */ this.output = this.context.createGain(); /** * The compressor applied to the low frequencies. * @type {Tone.Compressor} */ this.low = new Tone.Compressor(options.low); /** * The compressor applied to the mid frequencies. * @type {Tone.Compressor} */ this.mid = new Tone.Compressor(options.mid); /** * The compressor applied to the high frequencies. * @type {Tone.Compressor} */ this.high = new Tone.Compressor(options.high); //connect the compressor this._splitter.low.chain(this.low, this.output); this._splitter.mid.chain(this.mid, this.output); this._splitter.high.chain(this.high, this.output); this._readOnly([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); }; Tone.extend(Tone.MultibandCompressor); /** * @const * @static * @type {Object} */ Tone.MultibandCompressor.defaults = { 'low': Tone.Compressor.defaults, 'mid': Tone.Compressor.defaults, 'high': Tone.Compressor.defaults, 'lowFrequency': 250, 'highFrequency': 2000 }; /** * clean up * @returns {Tone.MultibandCompressor} this */ Tone.MultibandCompressor.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._splitter.dispose(); this._writable([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); this.low.dispose(); this.mid.dispose(); this.high.dispose(); this._splitter = null; this.low = null; this.mid = null; this.high = null; this.lowFrequency = null; this.highFrequency = null; return this; }; return Tone.MultibandCompressor; }); Module(function (Tone) { /** * @class Maps a NormalRange [0, 1] to an AudioRange [-1, 1]. * See also Tone.AudioToGain. * * @extends {Tone.SignalBase} * @constructor * @example * var g2a = new Tone.GainToAudio(); */ Tone.GainToAudio = function () { /** * @type {WaveShaperNode} * @private */ this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { return Math.abs(x) * 2 - 1; }); }; Tone.extend(Tone.GainToAudio, Tone.SignalBase); /** * clean up * @returns {Tone.GainToAudio} this */ Tone.GainToAudio.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._norm.dispose(); this._norm = null; return this; }; return Tone.GainToAudio; }); Module(function (Tone) { /** * @class Tone.Panner is an equal power Left/Right Panner and does not * support 3D. Panner uses the StereoPannerNode when available. * * @constructor * @extends {Tone} * @param {NormalRange} [initialPan=0.5] The initail panner value (defaults to 0.5 = center) * @example * //pan the input signal hard right. * var panner = new Tone.Panner(1); */ Tone.Panner = function (initialPan) { Tone.call(this); /** * indicates if the panner is using the new StereoPannerNode internally * @type {boolean} * @private */ this._hasStereoPanner = this.isFunction(this.context.createStereoPanner); if (this._hasStereoPanner) { /** * the panner node * @type {StereoPannerNode} * @private */ this._panner = this.input = this.output = this.context.createStereoPanner(); /** * The pan control. 0 = hard left, 1 = hard right. * @type {NormalRange} * @signal */ this.pan = new Tone.Signal(0, Tone.Type.NormalRange); /** * scale the pan signal to between -1 and 1 * @type {Tone.WaveShaper} * @private */ this._scalePan = new Tone.GainToAudio(); //connections this.pan.chain(this._scalePan, this._panner.pan); } else { /** * the dry/wet knob * @type {Tone.CrossFade} * @private */ this._crossFade = new Tone.CrossFade(); /** * @type {Tone.Merge} * @private */ this._merger = this.output = new Tone.Merge(); /** * @type {Tone.Split} * @private */ this._splitter = this.input = new Tone.Split(); /** * The pan control. 0 = hard left, 1 = hard right. * @type {NormalRange} * @signal */ this.pan = this._crossFade.fade; //CONNECTIONS: //left channel is a, right channel is b this._splitter.connect(this._crossFade, 0, 0); this._splitter.connect(this._crossFade, 1, 1); //merge it back together this._crossFade.a.connect(this._merger, 0, 0); this._crossFade.b.connect(this._merger, 0, 1); } //initial value this.pan.value = this.defaultArg(initialPan, 0.5); this._readOnly('pan'); }; Tone.extend(Tone.Panner); /** * Clean up. * @returns {Tone.Panner} this */ Tone.Panner.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('pan'); if (this._hasStereoPanner) { this._panner.disconnect(); this._panner = null; this.pan.dispose(); this.pan = null; this._scalePan.dispose(); this._scalePan = null; } else { this._crossFade.dispose(); this._crossFade = null; this._splitter.dispose(); this._splitter = null; this._merger.dispose(); this._merger = null; this.pan = null; } return this; }; return Tone.Panner; }); Module(function (Tone) { /** * @class Tone.PanVol is a Tone.Panner and Tone.Volume in one. * * @extends {Tone} * @constructor * @param {NormalRange} pan the initial pan * @param {number} volume The output volume. * @example * //pan the incoming signal left and drop the volume * var panVol = new Tone.PanVol(0.25, -12); */ Tone.PanVol = function () { var options = this.optionsObject(arguments, [ 'pan', 'volume' ], Tone.PanVol.defaults); /** * The panning node * @type {Tone.Panner} * @private */ this._panner = this.input = new Tone.Panner(options.pan); /** * The L/R panning control. * @type {NormalRange} * @signal */ this.pan = this._panner.pan; /** * The volume node * @type {Tone.Volume} */ this._volume = this.output = new Tone.Volume(options.volume); /** * The volume control in decibels. * @type {Decibels} * @signal */ this.volume = this._volume.volume; //connections this._panner.connect(this._volume); this._readOnly([ 'pan', 'volume' ]); }; Tone.extend(Tone.PanVol); /** * The defaults * @type {Object} * @const * @static */ Tone.PanVol.defaults = { 'pan': 0.5, 'volume': 0 }; /** * clean up * @returns {Tone.PanVol} this */ Tone.PanVol.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'pan', 'volume' ]); this._panner.dispose(); this._panner = null; this.pan = null; this._volume.dispose(); this._volume = null; this.volume = null; return this; }; return Tone.PanVol; }); Module(function (Tone) { /** * @class Tone.CtrlInterpolate will interpolate between given values based * on the "index" property. Passing in an array or object literal * will interpolate each of the parameters. Note (i.e. "C3") * and Time (i.e. "4n + 2") can be interpolated. All other values are * assumed to be numbers. * @example * var interp = new Tone.CtrlInterpolate([0, 2, 9, 4]); * interp.index = 0.75; * interp.value; //returns 1.5 * * @example * var interp = new Tone.CtrlInterpolate([ * ["C3", "G4", "E5"], * ["D4", "F#4", "E5"], * ]); * @param {Array} values The array of values to interpolate over * @param {Positive} index The initial interpolation index. * @extends {Tone} */ Tone.CtrlInterpolate = function () { var options = this.optionsObject(arguments, [ 'values', 'index' ], Tone.CtrlInterpolate.defaults); /** * The values to interpolate between * @type {Array} */ this.values = options.values; /** * The interpolated index between values. For example: a value of 1.5 * would interpolate equally between the value at index 1 * and the value at index 2. * @example * interp.index = 0; * interp.value; //returns the value at 0 * interp.index = 0.5; * interp.value; //returns the value between indices 0 and 1. * @type {Positive} */ this.index = options.index; }; Tone.extend(Tone.CtrlInterpolate); /** * The defaults * @const * @type {Object} */ Tone.CtrlInterpolate.defaults = { 'index': 0, 'values': [] }; /** * The current interpolated value based on the index * @readOnly * @memberOf Tone.CtrlInterpolate# * @type {*} * @name value */ Object.defineProperty(Tone.CtrlInterpolate.prototype, 'value', { get: function () { var index = this.index; index = Math.min(index, this.values.length - 1); var lowerPosition = Math.floor(index); var lower = this.values[lowerPosition]; var upper = this.values[Math.ceil(index)]; return this._interpolate(index - lowerPosition, lower, upper); } }); /** * Internal interpolation routine * @param {NormalRange} index The index between the lower and upper * @param {*} lower * @param {*} upper * @return {*} The interpolated value * @private */ Tone.CtrlInterpolate.prototype._interpolate = function (index, lower, upper) { if (this.isArray(lower)) { var retArray = []; for (var i = 0; i < lower.length; i++) { retArray[i] = this._interpolate(index, lower[i], upper[i]); } return retArray; } else if (this.isObject(lower)) { var retObj = {}; for (var attr in lower) { retObj[attr] = this._interpolate(index, lower[attr], upper[attr]); } return retObj; } else { lower = this._toNumber(lower); upper = this._toNumber(upper); return (1 - index) * lower + index * upper; } }; /** * Convert from the given type into a number * @param {Number|String} value * @return {Number} * @private */ Tone.CtrlInterpolate.prototype._toNumber = function (val) { if (this.isNumber(val)) { return val; } else if (this.isNote(val)) { return this.toFrequency(val); } else { //otherwise assume that it's Time... return this.toSeconds(val); } }; /** * Clean up * @return {Tone.CtrlInterpolate} this */ Tone.CtrlInterpolate.prototype.dispose = function () { this.values = null; }; return Tone.CtrlInterpolate; }); Module(function (Tone) { /** * @class Tone.CtrlMarkov represents a Markov Chain where each call * to Tone.CtrlMarkov.next will move to the next state. If the next * state choice is an array, the next state is chosen randomly with * even probability for all of the choices. For a weighted probability * of the next choices, pass in an object with "state" and "probability" attributes. * The probabilities will be normalized and then chosen. If no next options * are given for the current state, the state will stay there. * @extends {Tone} * @example * var chain = new Tone.CtrlMarkov({ * "beginning" : ["end", "middle"], * "middle" : "end" * }); * chain.value = "beginning"; * chain.next(); //returns "end" or "middle" with 50% probability * * @example * var chain = new Tone.CtrlMarkov({ * "beginning" : [{"value" : "end", "probability" : 0.8}, * {"value" : "middle", "probability" : 0.2}], * "middle" : "end" * }); * chain.value = "beginning"; * chain.next(); //returns "end" with 80% probability or "middle" with 20%. * @param {Object} values An object with the state names as the keys * and the next state(s) as the values. */ Tone.CtrlMarkov = function (values, initial) { /** * The Markov values with states as the keys * and next state(s) as the values. * @type {Object} */ this.values = this.defaultArg(values, {}); /** * The current state of the Markov values. The next * state will be evaluated and returned when Tone.CtrlMarkov.next * is invoked. * @type {String} */ this.value = this.defaultArg(initial, Object.keys(this.values)[0]); }; Tone.extend(Tone.CtrlMarkov); /** * Returns the next state of the Markov values. * @return {String} */ Tone.CtrlMarkov.prototype.next = function () { if (this.values.hasOwnProperty(this.value)) { var next = this.values[this.value]; if (this.isArray(next)) { var distribution = this._getProbDistribution(next); var rand = Math.random(); var total = 0; for (var i = 0; i < distribution.length; i++) { var dist = distribution[i]; if (rand > total && rand < total + dist) { var chosen = next[i]; if (this.isObject(chosen)) { this.value = chosen.value; } else { this.value = chosen; } } total += dist; } } else { this.value = next; } } return this.value; }; /** * Choose randomly from an array weighted options in the form * {"state" : string, "probability" : number} or an array of values * @param {Array} options * @return {Array} The randomly selected choice * @private */ Tone.CtrlMarkov.prototype._getProbDistribution = function (options) { var distribution = []; var total = 0; var needsNormalizing = false; for (var i = 0; i < options.length; i++) { var option = options[i]; if (this.isObject(option)) { needsNormalizing = true; distribution[i] = option.probability; } else { distribution[i] = 1 / options.length; } total += distribution[i]; } if (needsNormalizing) { //normalize the values for (var j = 0; j < distribution.length; j++) { distribution[j] = distribution[j] / total; } } return distribution; }; /** * Clean up * @return {Tone.CtrlMarkov} this */ Tone.CtrlMarkov.prototype.dispose = function () { this.values = null; }; return Tone.CtrlMarkov; }); Module(function (Tone) { /** * @class Generate patterns from an array of values. * Has a number of arpeggiation and randomized * selection patterns. * <ul> * <li>"up" - cycles upward</li> * <li>"down" - cycles downward</li> * <li>"upDown" - up then and down</li> * <li>"downUp" - cycles down then and up</li> * <li>"alternateUp" - jump up two and down one</li> * <li>"alternateDown" - jump down two and up one</li> * <li>"random" - randomly select an index</li> * <li>"randomWalk" - randomly moves one index away from the current position</li> * <li>"randomOnce" - randomly select an index without repeating until all values have been chosen.</li> * </ul> * @param {Array} values An array of options to choose from. * @param {Tone.CtrlPattern.Type=} type The name of the pattern. * @extends {Tone} */ Tone.CtrlPattern = function () { var options = this.optionsObject(arguments, [ 'values', 'type' ], Tone.CtrlPattern.defaults); /** * The array of values to arpeggiate over * @type {Array} */ this.values = options.values; /** * The current position in the values array * @type {Number} */ this.index = 0; /** * The type placeholder * @type {Tone.CtrlPattern.Type} * @private */ this._type = null; /** * Shuffled values for the RandomOnce type * @type {Array} * @private */ this._shuffled = null; /** * The direction of the movement * @type {String} * @private */ this._direction = null; this.type = options.type; }; Tone.extend(Tone.CtrlPattern); /** * The Control Patterns * @type {Object} * @static */ Tone.CtrlPattern.Type = { Up: 'up', Down: 'down', UpDown: 'upDown', DownUp: 'downUp', AlternateUp: 'alternateUp', AlternateDown: 'alternateDown', Random: 'random', RandomWalk: 'randomWalk', RandomOnce: 'randomOnce' }; /** * The default values. * @type {Object} */ Tone.CtrlPattern.defaults = { 'type': Tone.CtrlPattern.Type.Up, 'values': [] }; /** * The value at the current index of the pattern. * @readOnly * @memberOf Tone.CtrlPattern# * @type {*} * @name value */ Object.defineProperty(Tone.CtrlPattern.prototype, 'value', { get: function () { //some safeguards if (this.values.length === 0) { return; } else if (this.values.length === 1) { return this.values[0]; } this.index = Math.min(this.index, this.values.length - 1); var val = this.values[this.index]; if (this.type === Tone.CtrlPattern.Type.RandomOnce) { if (this.values.length !== this._shuffled.length) { this._shuffleValues(); } val = this.values[this._shuffled[this.index]]; } return val; } }); /** * The pattern used to select the next * item from the values array * @memberOf Tone.CtrlPattern# * @type {Tone.CtrlPattern.Type} * @name type */ Object.defineProperty(Tone.CtrlPattern.prototype, 'type', { get: function () { return this._type; }, set: function (type) { this._type = type; this._shuffled = null; //the first index if (this._type === Tone.CtrlPattern.Type.Up || this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.RandomOnce || this._type === Tone.CtrlPattern.Type.AlternateUp) { this.index = 0; } else if (this._type === Tone.CtrlPattern.Type.Down || this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { this.index = this.values.length - 1; } //the direction if (this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.AlternateUp) { this._direction = Tone.CtrlPattern.Type.Up; } else if (this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { this._direction = Tone.CtrlPattern.Type.Down; } //randoms if (this._type === Tone.CtrlPattern.Type.RandomOnce) { this._shuffleValues(); } else if (this._type === Tone.CtrlPattern.Random) { this.index = Math.floor(Math.random() * this.values.length); } } }); /** * Return the next value given the current position * and pattern. * @return {*} The next value */ Tone.CtrlPattern.prototype.next = function () { var type = this.type; //choose the next index if (type === Tone.CtrlPattern.Type.Up) { this.index++; if (this.index >= this.values.length) { this.index = 0; } } else if (type === Tone.CtrlPattern.Type.Down) { this.index--; if (this.index < 0) { this.index = this.values.length - 1; } } else if (type === Tone.CtrlPattern.Type.UpDown || type === Tone.CtrlPattern.Type.DownUp) { if (this._direction === Tone.CtrlPattern.Type.Up) { this.index++; } else { this.index--; } if (this.index < 0) { this.index = 1; this._direction = Tone.CtrlPattern.Type.Up; } else if (this.index >= this.values.length) { this.index = this.values.length - 2; this._direction = Tone.CtrlPattern.Type.Down; } } else if (type === Tone.CtrlPattern.Type.Random) { this.index = Math.floor(Math.random() * this.values.length); } else if (type === Tone.CtrlPattern.Type.RandomWalk) { if (Math.random() < 0.5) { this.index--; this.index = Math.max(this.index, 0); } else { this.index++; this.index = Math.min(this.index, this.values.length - 1); } } else if (type === Tone.CtrlPattern.Type.RandomOnce) { this.index++; if (this.index >= this.values.length) { this.index = 0; //reshuffle the values for next time this._shuffleValues(); } } else if (type === Tone.CtrlPattern.Type.AlternateUp) { if (this._direction === Tone.CtrlPattern.Type.Up) { this.index += 2; this._direction = Tone.CtrlPattern.Type.Down; } else { this.index -= 1; this._direction = Tone.CtrlPattern.Type.Up; } if (this.index >= this.values.length) { this.index = 0; this._direction = Tone.CtrlPattern.Type.Up; } } else if (type === Tone.CtrlPattern.Type.AlternateDown) { if (this._direction === Tone.CtrlPattern.Type.Up) { this.index += 1; this._direction = Tone.CtrlPattern.Type.Down; } else { this.index -= 2; this._direction = Tone.CtrlPattern.Type.Up; } if (this.index < 0) { this.index = this.values.length - 1; this._direction = Tone.CtrlPattern.Type.Down; } } return this.value; }; /** * Shuffles the values and places the results into the _shuffled * @private */ Tone.CtrlPattern.prototype._shuffleValues = function () { var copy = []; this._shuffled = []; for (var i = 0; i < this.values.length; i++) { copy[i] = i; } while (copy.length > 0) { var randVal = copy.splice(Math.floor(copy.length * Math.random()), 1); this._shuffled.push(randVal[0]); } }; /** * Clean up * @returns {Tone.CtrlPattern} this */ Tone.CtrlPattern.prototype.dispose = function () { this._shuffled = null; this.values = null; }; return Tone.CtrlPattern; }); Module(function (Tone) { /** * @class Choose a random value. * @extends {Tone} * @example * var randomWalk = new Tone.CtrlRandom({ * "min" : 0, * "max" : 10, * "integer" : true * }); * randomWalk.eval(); * * @param {Number|Time=} min The minimum return value. * @param {Number|Time=} max The maximum return value. */ Tone.CtrlRandom = function () { var options = this.optionsObject(arguments, [ 'min', 'max' ], Tone.CtrlRandom.defaults); /** * The minimum return value * @type {Number|Time} */ this.min = options.min; /** * The maximum return value * @type {Number|Time} */ this.max = options.max; /** * If the return value should be an integer * @type {Boolean} */ this.integer = options.integer; }; Tone.extend(Tone.CtrlRandom); /** * The defaults * @const * @type {Object} */ Tone.CtrlRandom.defaults = { 'min': 0, 'max': 1, 'integer': false }; /** * Return a random value between min and max. * @readOnly * @memberOf Tone.CtrlRandom# * @type {*} * @name value */ Object.defineProperty(Tone.CtrlRandom.prototype, 'value', { get: function () { var min = this.toSeconds(this.min); var max = this.toSeconds(this.max); var rand = Math.random(); var val = rand * min + (1 - rand) * max; if (this.integer) { val = Math.floor(val); } return val; } }); return Tone.CtrlRandom; }); Module(function (Tone) { /** * @class Buffer loading and storage. Tone.Buffer is used internally by all * classes that make requests for audio files such as Tone.Player, * Tone.Sampler and Tone.Convolver. * <br><br> * Aside from load callbacks from individual buffers, Tone.Buffer * provides static methods which keep track of the loading progress * of all of the buffers. These methods are Tone.Buffer.onload, Tone.Buffer.onprogress, * and Tone.Buffer.onerror. * * @constructor * @extends {Tone} * @param {AudioBuffer|string} url The url to load, or the audio buffer to set. * @param {function=} onload A callback which is invoked after the buffer is loaded. * It's recommended to use Tone.Buffer.onload instead * since it will give you a callback when ALL buffers are loaded. * @example * var buffer = new Tone.Buffer("path/to/sound.mp3", function(){ * //the buffer is now available. * var buff = buffer.get(); * }); */ Tone.Buffer = function () { var options = this.optionsObject(arguments, [ 'url', 'onload' ], Tone.Buffer.defaults); /** * stores the loaded AudioBuffer * @type {AudioBuffer} * @private */ this._buffer = null; /** * indicates if the buffer should be reversed or not * @type {boolean} * @private */ this._reversed = options.reverse; /** * The url of the buffer. <code>undefined</code> if it was * constructed with a buffer * @type {string} * @readOnly */ this.url = undefined; /** * Indicates if the buffer is loaded or not. * @type {boolean} * @readOnly */ this.loaded = false; /** * The callback to invoke when everything is loaded. * @type {function} */ this.onload = options.onload.bind(this, this); if (options.url instanceof AudioBuffer || options.url instanceof Tone.Buffer) { this.set(options.url); this.onload(this); } else if (this.isString(options.url)) { this.url = options.url; Tone.Buffer._addToQueue(options.url, this); } }; Tone.extend(Tone.Buffer); /** * the default parameters * @type {Object} */ Tone.Buffer.defaults = { 'url': undefined, 'onload': Tone.noOp, 'reverse': false }; /** * Pass in an AudioBuffer or Tone.Buffer to set the value * of this buffer. * @param {AudioBuffer|Tone.Buffer} buffer the buffer * @returns {Tone.Buffer} this */ Tone.Buffer.prototype.set = function (buffer) { if (buffer instanceof Tone.Buffer) { this._buffer = buffer.get(); } else { this._buffer = buffer; } this.loaded = true; return this; }; /** * @return {AudioBuffer} The audio buffer stored in the object. */ Tone.Buffer.prototype.get = function () { return this._buffer; }; /** * Load url into the buffer. * @param {String} url The url to load * @param {Function=} callback The callback to invoke on load. * don't need to set if `onload` is * already set. * @returns {Tone.Buffer} this */ Tone.Buffer.prototype.load = function (url, callback) { this.url = url; this.onload = this.defaultArg(callback, this.onload); Tone.Buffer._addToQueue(url, this); return this; }; /** * dispose and disconnect * @returns {Tone.Buffer} this */ Tone.Buffer.prototype.dispose = function () { Tone.prototype.dispose.call(this); Tone.Buffer._removeFromQueue(this); this._buffer = null; this.onload = Tone.Buffer.defaults.onload; return this; }; /** * The duration of the buffer. * @memberOf Tone.Buffer# * @type {number} * @name duration * @readOnly */ Object.defineProperty(Tone.Buffer.prototype, 'duration', { get: function () { if (this._buffer) { return this._buffer.duration; } else { return 0; } } }); /** * Reverse the buffer. * @private * @return {Tone.Buffer} this */ Tone.Buffer.prototype._reverse = function () { if (this.loaded) { for (var i = 0; i < this._buffer.numberOfChannels; i++) { Array.prototype.reverse.call(this._buffer.getChannelData(i)); } } return this; }; /** * Reverse the buffer. * @memberOf Tone.Buffer# * @type {boolean} * @name reverse */ Object.defineProperty(Tone.Buffer.prototype, 'reverse', { get: function () { return this._reversed; }, set: function (rev) { if (this._reversed !== rev) { this._reversed = rev; this._reverse(); } } }); /////////////////////////////////////////////////////////////////////////// // STATIC METHODS /////////////////////////////////////////////////////////////////////////// //statically inherits Emitter methods Tone.Emitter.mixin(Tone.Buffer); /** * the static queue for all of the xhr requests * @type {Array} * @private */ Tone.Buffer._queue = []; /** * the array of current downloads * @type {Array} * @private */ Tone.Buffer._currentDownloads = []; /** * the total number of downloads * @type {number} * @private */ Tone.Buffer._totalDownloads = 0; /** * the maximum number of simultaneous downloads * @static * @type {number} */ Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS = 6; /** * Adds a file to be loaded to the loading queue * @param {string} url the url to load * @param {function} callback the callback to invoke once it's loaded * @private */ Tone.Buffer._addToQueue = function (url, buffer) { Tone.Buffer._queue.push({ url: url, Buffer: buffer, progress: 0, xhr: null }); this._totalDownloads++; Tone.Buffer._next(); }; /** * Remove an object from the queue's (if it's still there) * Abort the XHR if it's in progress * @param {Tone.Buffer} buffer the buffer to remove * @private */ Tone.Buffer._removeFromQueue = function (buffer) { var i; for (i = 0; i < Tone.Buffer._queue.length; i++) { var q = Tone.Buffer._queue[i]; if (q.Buffer === buffer) { Tone.Buffer._queue.splice(i, 1); } } for (i = 0; i < Tone.Buffer._currentDownloads.length; i++) { var dl = Tone.Buffer._currentDownloads[i]; if (dl.Buffer === buffer) { Tone.Buffer._currentDownloads.splice(i, 1); dl.xhr.abort(); dl.xhr.onprogress = null; dl.xhr.onload = null; dl.xhr.onerror = null; } } }; /** * load the next buffer in the queue * @private */ Tone.Buffer._next = function () { if (Tone.Buffer._queue.length > 0) { if (Tone.Buffer._currentDownloads.length < Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS) { var next = Tone.Buffer._queue.shift(); Tone.Buffer._currentDownloads.push(next); next.xhr = Tone.Buffer.load(next.url, function (buffer) { //remove this one from the queue var index = Tone.Buffer._currentDownloads.indexOf(next); Tone.Buffer._currentDownloads.splice(index, 1); next.Buffer.set(buffer); if (next.Buffer._reversed) { next.Buffer._reverse(); } next.Buffer.onload(next.Buffer); Tone.Buffer._onprogress(); Tone.Buffer._next(); }); next.xhr.onprogress = function (event) { next.progress = event.loaded / event.total; Tone.Buffer._onprogress(); }; next.xhr.onerror = function (e) { Tone.Buffer.trigger('error', e); }; } } else if (Tone.Buffer._currentDownloads.length === 0) { Tone.Buffer.trigger('load'); //reset the downloads Tone.Buffer._totalDownloads = 0; } }; /** * internal progress event handler * @private */ Tone.Buffer._onprogress = function () { var curretDownloadsProgress = 0; var currentDLLen = Tone.Buffer._currentDownloads.length; var inprogress = 0; if (currentDLLen > 0) { for (var i = 0; i < currentDLLen; i++) { var dl = Tone.Buffer._currentDownloads[i]; curretDownloadsProgress += dl.progress; } inprogress = curretDownloadsProgress; } var currentDownloadProgress = currentDLLen - inprogress; var completed = Tone.Buffer._totalDownloads - Tone.Buffer._queue.length - currentDownloadProgress; Tone.Buffer.trigger('progress', completed / Tone.Buffer._totalDownloads); }; /** * Makes an xhr reqest for the selected url then decodes * the file as an audio buffer. Invokes * the callback once the audio buffer loads. * @param {string} url The url of the buffer to load. * filetype support depends on the * browser. * @param {function} callback The function to invoke when the url is loaded. * @returns {XMLHttpRequest} returns the XHR */ Tone.Buffer.load = function (url, callback) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; // decode asynchronously request.onload = function () { Tone.context.decodeAudioData(request.response, function (buff) { if (!buff) { throw new Error('could not decode audio data:' + url); } callback(buff); }); }; //send the request request.send(); return request; }; /** * @deprecated us on([event]) instead */ Object.defineProperty(Tone.Buffer, 'onload', { set: function (cb) { console.warn('Tone.Buffer.onload is deprecated, use Tone.Buffer.on(\'load\', callback)'); Tone.Buffer.on('load', cb); } }); Object.defineProperty(Tone.Buffer, 'onprogress', { set: function (cb) { console.warn('Tone.Buffer.onprogress is deprecated, use Tone.Buffer.on(\'progress\', callback)'); Tone.Buffer.on('progress', cb); } }); Object.defineProperty(Tone.Buffer, 'onerror', { set: function (cb) { console.warn('Tone.Buffer.onerror is deprecated, use Tone.Buffer.on(\'error\', callback)'); Tone.Buffer.on('error', cb); } }); return Tone.Buffer; }); Module(function (Tone) { /** * buses are another way of routing audio * * augments Tone.prototype to include send and recieve */ /** * All of the routes * * @type {Object} * @static * @private */ var Buses = {}; /** * Send this signal to the channel name. * @param {string} channelName A named channel to send the signal to. * @param {Decibels} amount The amount of the source to send to the bus. * @return {GainNode} The gain node which connects this node to the desired channel. * Can be used to adjust the levels of the send. * @example * source.send("reverb", -12); */ Tone.prototype.send = function (channelName, amount) { if (!Buses.hasOwnProperty(channelName)) { Buses[channelName] = this.context.createGain(); } var sendKnob = this.context.createGain(); sendKnob.gain.value = this.dbToGain(this.defaultArg(amount, 1)); this.output.chain(sendKnob, Buses[channelName]); return sendKnob; }; /** * Recieve the input from the desired channelName to the input * * @param {string} channelName A named channel to send the signal to. * @param {AudioNode} [input] If no input is selected, the * input of the current node is * chosen. * @returns {Tone} this * @example * reverbEffect.receive("reverb"); */ Tone.prototype.receive = function (channelName, input) { if (!Buses.hasOwnProperty(channelName)) { Buses[channelName] = this.context.createGain(); } if (this.isUndef(input)) { input = this.input; } Buses[channelName].connect(input); return this; }; return Tone; }); Module(function (Tone) { /** * @class Wrapper around Web Audio's native [DelayNode](http://webaudio.github.io/web-audio-api/#the-delaynode-interface). * @extends {Tone} * @param {Time=} delayTime The delay applied to the incoming signal. * @param {Time=} maxDelay The maximum delay time. */ Tone.Delay = function () { var options = this.optionsObject(arguments, [ 'delayTime', 'maxDelay' ], Tone.Delay.defaults); /** * The native delay node * @type {DelayNode} * @private */ this._delayNode = this.input = this.output = this.context.createDelay(this.toSeconds(options.maxDelay)); /** * The amount of time the incoming signal is * delayed. * @type {Tone.Param} * @signal */ this.delayTime = new Tone.Param({ 'param': this._delayNode.delayTime, 'units': Tone.Type.Time, 'value': options.delayTime }); this._readOnly('delayTime'); }; Tone.extend(Tone.Delay); /** * The defaults * @const * @type {Object} */ Tone.Delay.defaults = { 'maxDelay': 1, 'delayTime': 0 }; /** * Clean up. * @return {Tone.Delay} this */ Tone.Delay.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._delayNode.disconnect(); this._delayNode = null; this._writable('delayTime'); this.delayTime = null; return this; }; return Tone.Delay; }); Module(function (Tone) { /** * @class A single master output which is connected to the * AudioDestinationNode (aka your speakers). * It provides useful conveniences such as the ability * to set the volume and mute the entire application. * It also gives you the ability to apply master effects to your application. * <br><br> * Like Tone.Transport, A single Tone.Master is created * on initialization and you do not need to explicitly construct one. * * @constructor * @extends {Tone} * @singleton * @example * //the audio will go from the oscillator to the speakers * oscillator.connect(Tone.Master); * //a convenience for connecting to the master output is also provided: * oscillator.toMaster(); * //the above two examples are equivalent. */ Tone.Master = function () { Tone.call(this); /** * the unmuted volume * @type {number} * @private */ this._unmutedVolume = 1; /** * if the master is muted * @type {boolean} * @private */ this._muted = false; /** * The private volume node * @type {Tone.Volume} * @private */ this._volume = this.output = new Tone.Volume(); /** * The volume of the master output. * @type {Decibels} * @signal */ this.volume = this._volume.volume; this._readOnly('volume'); //connections this.input.chain(this.output, this.context.destination); }; Tone.extend(Tone.Master); /** * @type {Object} * @const */ Tone.Master.defaults = { 'volume': 0, 'mute': false }; /** * Mute the output. * @memberOf Tone.Master# * @type {boolean} * @name mute * @example * //mute the output * Tone.Master.mute = true; */ Object.defineProperty(Tone.Master.prototype, 'mute', { get: function () { return this._muted; }, set: function (mute) { if (!this._muted && mute) { this._unmutedVolume = this.volume.value; //maybe it should ramp here? this.volume.value = -Infinity; } else if (this._muted && !mute) { this.volume.value = this._unmutedVolume; } this._muted = mute; } }); /** * Add a master effects chain. NOTE: this will disconnect any nodes which were previously * chained in the master effects chain. * @param {AudioNode|Tone...} args All arguments will be connected in a row * and the Master will be routed through it. * @return {Tone.Master} this * @example * //some overall compression to keep the levels in check * var masterCompressor = new Tone.Compressor({ * "threshold" : -6, * "ratio" : 3, * "attack" : 0.5, * "release" : 0.1 * }); * //give a little boost to the lows * var lowBump = new Tone.Filter(200, "lowshelf"); * //route everything through the filter * //and compressor before going to the speakers * Tone.Master.chain(lowBump, masterCompressor); */ Tone.Master.prototype.chain = function () { this.input.disconnect(); this.input.chain.apply(this.input, arguments); arguments[arguments.length - 1].connect(this.output); }; /** * Clean up * @return {Tone.Master} this */ Tone.Master.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('volume'); this._volume.dispose(); this._volume = null; this.volume = null; }; /////////////////////////////////////////////////////////////////////////// // AUGMENT TONE's PROTOTYPE /////////////////////////////////////////////////////////////////////////// /** * Connect 'this' to the master output. Shorthand for this.connect(Tone.Master) * @returns {Tone} this * @example * //connect an oscillator to the master output * var osc = new Tone.Oscillator().toMaster(); */ Tone.prototype.toMaster = function () { this.connect(Tone.Master); return this; }; /** * Also augment AudioNode's prototype to include toMaster * as a convenience * @returns {AudioNode} this */ AudioNode.prototype.toMaster = function () { this.connect(Tone.Master); return this; }; var MasterConstructor = Tone.Master; /** * initialize the module and listen for new audio contexts */ Tone._initAudioContext(function () { //a single master output if (!Tone.prototype.isUndef(Tone.Master)) { Tone.Master = new MasterConstructor(); } else { MasterConstructor.prototype.dispose.call(Tone.Master); MasterConstructor.call(Tone.Master); } }); return Tone.Master; }); Module(function (Tone) { /** * @class A timed note. Creating a note will register a callback * which will be invoked on the channel at the time with * whatever value was specified. * * @constructor * @param {number|string} channel the channel name of the note * @param {Time} time the time when the note will occur * @param {string|number|Object|Array} value the value of the note */ Tone.Note = function (channel, time, value) { /** * the value of the note. This value is returned * when the channel callback is invoked. * * @type {string|number|Object} */ this.value = value; /** * the channel name or number * * @type {string|number} * @private */ this._channel = channel; /** * an internal reference to the id of the timeline * callback which is set. * * @type {number} * @private */ this._timelineID = Tone.Transport.setTimeline(this._trigger.bind(this), time); }; /** * invoked by the timeline * @private * @param {number} time the time at which the note should play */ Tone.Note.prototype._trigger = function (time) { //invoke the callback channelCallbacks(this._channel, time, this.value); }; /** * clean up * @returns {Tone.Note} this */ Tone.Note.prototype.dispose = function () { Tone.Transport.clearTimeline(this._timelineID); this.value = null; return this; }; /** * @private * @static * @type {Object} */ var NoteChannels = {}; /** * invoke all of the callbacks on a specific channel * @private */ function channelCallbacks(channel, time, value) { if (NoteChannels.hasOwnProperty(channel)) { var callbacks = NoteChannels[channel]; for (var i = 0, len = callbacks.length; i < len; i++) { var callback = callbacks[i]; if (Array.isArray(value)) { callback.apply(window, [time].concat(value)); } else { callback(time, value); } } } } /** * listen to a specific channel, get all of the note callbacks * @static * @param {string|number} channel the channel to route note events from * @param {function(*)} callback callback to be invoked when a note will occur * on the specified channel */ Tone.Note.route = function (channel, callback) { if (NoteChannels.hasOwnProperty(channel)) { NoteChannels[channel].push(callback); } else { NoteChannels[channel] = [callback]; } }; /** * Remove a previously routed callback from a channel. * @static * @param {string|number} channel The channel to unroute note events from * @param {function(*)} callback Callback which was registered to the channel. */ Tone.Note.unroute = function (channel, callback) { if (NoteChannels.hasOwnProperty(channel)) { var channelCallback = NoteChannels[channel]; var index = channelCallback.indexOf(callback); if (index !== -1) { NoteChannels[channel].splice(index, 1); } } }; /** * Parses a score and registers all of the notes along the timeline. * <br><br> * Scores are a JSON object with instruments at the top level * and an array of time and values. The value of a note can be 0 or more * parameters. * <br><br> * The only requirement for the score format is that the time is the first (or only) * value in the array. All other values are optional and will be passed into the callback * function registered using `Note.route(channelName, callback)`. * <br><br> * To convert MIDI files to score notation, take a look at utils/MidiToScore.js * * @example * //an example JSON score which sets up events on channels * var score = { * "synth" : [["0", "C3"], ["0:1", "D3"], ["0:2", "E3"], ... ], * "bass" : [["0", "C2"], ["1:0", "A2"], ["2:0", "C2"], ["3:0", "A2"], ... ], * "kick" : ["0", "0:2", "1:0", "1:2", "2:0", ... ], * //... * }; * //parse the score into Notes * Tone.Note.parseScore(score); * //route all notes on the "synth" channel * Tone.Note.route("synth", function(time, note){ * //trigger synth * }); * @static * @param {Object} score * @return {Array} an array of all of the notes that were created */ Tone.Note.parseScore = function (score) { var notes = []; for (var inst in score) { var part = score[inst]; if (inst === 'tempo') { Tone.Transport.bpm.value = part; } else if (inst === 'timeSignature') { Tone.Transport.timeSignature = part[0] / (part[1] / 4); } else if (Array.isArray(part)) { for (var i = 0; i < part.length; i++) { var noteDescription = part[i]; var note; if (Array.isArray(noteDescription)) { var time = noteDescription[0]; var value = noteDescription.slice(1); note = new Tone.Note(inst, time, value); } else if (typeof noteDescription === 'object') { note = new Tone.Note(inst, noteDescription.time, noteDescription); } else { note = new Tone.Note(inst, noteDescription); } notes.push(note); } } else { throw new TypeError('score parts must be Arrays'); } } return notes; }; return Tone.Note; }); Module(function (Tone) { /** * @class Tone.Effect is the base class for effects. Connect the effect between * the effectSend and effectReturn GainNodes, then control the amount of * effect which goes to the output using the wet control. * * @constructor * @extends {Tone} * @param {NormalRange|Object} [wet] The starting wet value. */ Tone.Effect = function () { Tone.call(this); //get all of the defaults var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); /** * the drywet knob to control the amount of effect * @type {Tone.CrossFade} * @private */ this._dryWet = new Tone.CrossFade(options.wet); /** * The wet control is how much of the effected * will pass through to the output. 1 = 100% effected * signal, 0 = 100% dry signal. * @type {NormalRange} * @signal */ this.wet = this._dryWet.fade; /** * connect the effectSend to the input of hte effect * @type {GainNode} * @private */ this.effectSend = this.context.createGain(); /** * connect the output of the effect to the effectReturn * @type {GainNode} * @private */ this.effectReturn = this.context.createGain(); //connections this.input.connect(this._dryWet.a); this.input.connect(this.effectSend); this.effectReturn.connect(this._dryWet.b); this._dryWet.connect(this.output); this._readOnly(['wet']); }; Tone.extend(Tone.Effect); /** * @static * @type {Object} */ Tone.Effect.defaults = { 'wet': 1 }; /** * chains the effect in between the effectSend and effectReturn * @param {Tone} effect * @private * @returns {Tone.Effect} this */ Tone.Effect.prototype.connectEffect = function (effect) { this.effectSend.chain(effect, this.effectReturn); return this; }; /** * Clean up. * @returns {Tone.Effect} this */ Tone.Effect.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._dryWet.dispose(); this._dryWet = null; this.effectSend.disconnect(); this.effectSend = null; this.effectReturn.disconnect(); this.effectReturn = null; this._writable(['wet']); this.wet = null; return this; }; return Tone.Effect; }); Module(function (Tone) { /** * @class Tone.AutoFilter is a Tone.Filter with a Tone.LFO connected to the filter cutoff frequency. * Setting the LFO rate and depth allows for control over the filter modulation rate * and depth. * * @constructor * @extends {Tone.Effect} * @param {Time|Object} [frequency] The rate of the LFO. * @param {Frequency=} baseFrequency The lower value of the LFOs oscillation * @param {Frequency=} octaves The number of octaves above the baseFrequency * @example * //create an autofilter and start it's LFO * var autoFilter = new Tone.AutoFilter("4n").toMaster().start(); * //route an oscillator through the filter and start it * var oscillator = new Tone.Oscillator().connect(autoFilter).start(); */ Tone.AutoFilter = function () { var options = this.optionsObject(arguments, [ 'frequency', 'baseFrequency', 'octaves' ], Tone.AutoFilter.defaults); Tone.Effect.call(this, options); /** * the lfo which drives the filter cutoff * @type {Tone.LFO} * @private */ this._lfo = new Tone.LFO({ 'frequency': options.frequency, 'amplitude': options.depth }); /** * The range of the filter modulating between the min and max frequency. * 0 = no modulation. 1 = full modulation. * @type {NormalRange} * @signal */ this.depth = this._lfo.amplitude; /** * How fast the filter modulates between min and max. * @type {Frequency} * @signal */ this.frequency = this._lfo.frequency; /** * The filter node * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); /** * The octaves placeholder * @type {Positive} * @private */ this._octaves = 0; //connections this.connectEffect(this.filter); this._lfo.connect(this.filter.frequency); this.type = options.type; this._readOnly([ 'frequency', 'depth' ]); this.octaves = options.octaves; this.baseFrequency = options.baseFrequency; }; //extend Effect Tone.extend(Tone.AutoFilter, Tone.Effect); /** * defaults * @static * @type {Object} */ Tone.AutoFilter.defaults = { 'frequency': 1, 'type': 'sine', 'depth': 1, 'baseFrequency': 200, 'octaves': 2.6, 'filter': { 'type': 'lowpass', 'rolloff': -12, 'Q': 1 } }; /** * Start the effect. * @param {Time} [time=now] When the LFO will start. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.start = function (time) { this._lfo.start(time); return this; }; /** * Stop the effect. * @param {Time} [time=now] When the LFO will stop. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.stop = function (time) { this._lfo.stop(time); return this; }; /** * Sync the filter to the transport. * @param {Time} [delay=0] Delay time before starting the effect after the * Transport has started. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.sync = function (delay) { this._lfo.sync(delay); return this; }; /** * Unsync the filter from the transport. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.unsync = function () { this._lfo.unsync(); return this; }; /** * Type of oscillator attached to the AutoFilter. * Possible values: "sine", "square", "triangle", "sawtooth". * @memberOf Tone.AutoFilter# * @type {string} * @name type */ Object.defineProperty(Tone.AutoFilter.prototype, 'type', { get: function () { return this._lfo.type; }, set: function (type) { this._lfo.type = type; } }); /** * The minimum value of the filter's cutoff frequency. * @memberOf Tone.AutoFilter# * @type {Frequency} * @name min */ Object.defineProperty(Tone.AutoFilter.prototype, 'baseFrequency', { get: function () { return this._lfo.min; }, set: function (freq) { this._lfo.min = this.toFrequency(freq); } }); /** * The maximum value of the filter's cutoff frequency. * @memberOf Tone.AutoFilter# * @type {Positive} * @name octaves */ Object.defineProperty(Tone.AutoFilter.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (oct) { this._octaves = oct; this._lfo.max = this.baseFrequency * Math.pow(2, oct); } }); /** * Clean up. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._lfo.dispose(); this._lfo = null; this.filter.dispose(); this.filter = null; this._writable([ 'frequency', 'depth' ]); this.frequency = null; this.depth = null; return this; }; return Tone.AutoFilter; }); Module(function (Tone) { /** * @class Tone.AutoPanner is a Tone.Panner with an LFO connected to the pan amount. * More on using autopanners [here](https://www.ableton.com/en/blog/autopan-chopper-effect-and-more-liveschool/). * * @constructor * @extends {Tone.Effect} * @param {Frequency|Object} [frequency] Rate of left-right oscillation. * @example * //create an autopanner and start it's LFO * var autoPanner = new Tone.AutoPanner("4n").toMaster().start(); * //route an oscillator through the panner and start it * var oscillator = new Tone.Oscillator().connect(autoPanner).start(); */ Tone.AutoPanner = function () { var options = this.optionsObject(arguments, ['frequency'], Tone.AutoPanner.defaults); Tone.Effect.call(this, options); /** * the lfo which drives the panning * @type {Tone.LFO} * @private */ this._lfo = new Tone.LFO({ 'frequency': options.frequency, 'amplitude': options.depth, 'min': 0, 'max': 1 }); /** * The amount of panning between left and right. * 0 = always center. 1 = full range between left and right. * @type {NormalRange} * @signal */ this.depth = this._lfo.amplitude; /** * the panner node which does the panning * @type {Tone.Panner} * @private */ this._panner = new Tone.Panner(); /** * How fast the panner modulates between left and right. * @type {Frequency} * @signal */ this.frequency = this._lfo.frequency; //connections this.connectEffect(this._panner); this._lfo.connect(this._panner.pan); this.type = options.type; this._readOnly([ 'depth', 'frequency' ]); }; //extend Effect Tone.extend(Tone.AutoPanner, Tone.Effect); /** * defaults * @static * @type {Object} */ Tone.AutoPanner.defaults = { 'frequency': 1, 'type': 'sine', 'depth': 1 }; /** * Start the effect. * @param {Time} [time=now] When the LFO will start. * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.start = function (time) { this._lfo.start(time); return this; }; /** * Stop the effect. * @param {Time} [time=now] When the LFO will stop. * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.stop = function (time) { this._lfo.stop(time); return this; }; /** * Sync the panner to the transport. * @param {Time} [delay=0] Delay time before starting the effect after the * Transport has started. * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.sync = function (delay) { this._lfo.sync(delay); return this; }; /** * Unsync the panner from the transport * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.unsync = function () { this._lfo.unsync(); return this; }; /** * Type of oscillator attached to the AutoFilter. * Possible values: "sine", "square", "triangle", "sawtooth". * @memberOf Tone.AutoFilter# * @type {string} * @name type */ Object.defineProperty(Tone.AutoPanner.prototype, 'type', { get: function () { return this._lfo.type; }, set: function (type) { this._lfo.type = type; } }); /** * clean up * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._lfo.dispose(); this._lfo = null; this._panner.dispose(); this._panner = null; this._writable([ 'depth', 'frequency' ]); this.frequency = null; this.depth = null; return this; }; return Tone.AutoPanner; }); Module(function (Tone) { /** * @class Tone.AutoWah connects a Tone.Follower to a bandpass filter (Tone.Filter). * The frequency of the filter is adjusted proportionally to the * incoming signal's amplitude. Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna). * * @constructor * @extends {Tone.Effect} * @param {Frequency|Object} [baseFrequency] The frequency the filter is set * to at the low point of the wah * @param {Positive} [octaves] The number of octaves above the baseFrequency * the filter will sweep to when fully open * @param {Decibels} [sensitivity] The decibel threshold sensitivity for * the incoming signal. Normal range of -40 to 0. * @example * var autoWah = new Tone.AutoWah(50, 6, -30).toMaster(); * //initialize the synth and connect to autowah * var synth = new SimpleSynth.connect(autoWah); * //Q value influences the effect of the wah - default is 2 * autoWah.Q.value = 6; * //more audible on higher notes * synth.triggerAttackRelease("C4", "8n") */ Tone.AutoWah = function () { var options = this.optionsObject(arguments, [ 'baseFrequency', 'octaves', 'sensitivity' ], Tone.AutoWah.defaults); Tone.Effect.call(this, options); /** * The envelope follower. Set the attack/release * timing to adjust how the envelope is followed. * @type {Tone.Follower} * @private */ this.follower = new Tone.Follower(options.follower); /** * scales the follower value to the frequency domain * @type {Tone} * @private */ this._sweepRange = new Tone.ScaleExp(0, 1, 0.5); /** * @type {number} * @private */ this._baseFrequency = options.baseFrequency; /** * @type {number} * @private */ this._octaves = options.octaves; /** * the input gain to adjust the sensitivity * @type {GainNode} * @private */ this._inputBoost = this.context.createGain(); /** * @type {BiquadFilterNode} * @private */ this._bandpass = new Tone.Filter({ 'rolloff': -48, 'frequency': 0, 'Q': options.Q }); /** * @type {Tone.Filter} * @private */ this._peaking = new Tone.Filter(0, 'peaking'); this._peaking.gain.value = options.gain; /** * The gain of the filter. * @type {Number} * @signal */ this.gain = this._peaking.gain; /** * The quality of the filter. * @type {Positive} * @signal */ this.Q = this._bandpass.Q; //the control signal path this.effectSend.chain(this._inputBoost, this.follower, this._sweepRange); this._sweepRange.connect(this._bandpass.frequency); this._sweepRange.connect(this._peaking.frequency); //the filtered path this.effectSend.chain(this._bandpass, this._peaking, this.effectReturn); //set the initial value this._setSweepRange(); this.sensitivity = options.sensitivity; this._readOnly([ 'gain', 'Q' ]); }; Tone.extend(Tone.AutoWah, Tone.Effect); /** * @static * @type {Object} */ Tone.AutoWah.defaults = { 'baseFrequency': 100, 'octaves': 6, 'sensitivity': 0, 'Q': 2, 'gain': 2, 'follower': { 'attack': 0.3, 'release': 0.5 } }; /** * The number of octaves that the filter will sweep above the * baseFrequency. * @memberOf Tone.AutoWah# * @type {Number} * @name octaves */ Object.defineProperty(Tone.AutoWah.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (octaves) { this._octaves = octaves; this._setSweepRange(); } }); /** * The base frequency from which the sweep will start from. * @memberOf Tone.AutoWah# * @type {Frequency} * @name baseFrequency */ Object.defineProperty(Tone.AutoWah.prototype, 'baseFrequency', { get: function () { return this._baseFrequency; }, set: function (baseFreq) { this._baseFrequency = baseFreq; this._setSweepRange(); } }); /** * The sensitivity to control how responsive to the input signal the filter is. * @memberOf Tone.AutoWah# * @type {Decibels} * @name sensitivity */ Object.defineProperty(Tone.AutoWah.prototype, 'sensitivity', { get: function () { return this.gainToDb(1 / this._inputBoost.gain.value); }, set: function (sensitivy) { this._inputBoost.gain.value = 1 / this.dbToGain(sensitivy); } }); /** * sets the sweep range of the scaler * @private */ Tone.AutoWah.prototype._setSweepRange = function () { this._sweepRange.min = this._baseFrequency; this._sweepRange.max = Math.min(this._baseFrequency * Math.pow(2, this._octaves), this.context.sampleRate / 2); }; /** * Clean up. * @returns {Tone.AutoWah} this */ Tone.AutoWah.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this.follower.dispose(); this.follower = null; this._sweepRange.dispose(); this._sweepRange = null; this._bandpass.dispose(); this._bandpass = null; this._peaking.dispose(); this._peaking = null; this._inputBoost.disconnect(); this._inputBoost = null; this._writable([ 'gain', 'Q' ]); this.gain = null; this.Q = null; return this; }; return Tone.AutoWah; }); Module(function (Tone) { /** * @class Tone.Bitcrusher downsamples the incoming signal to a different bitdepth. * Lowering the bitdepth of the signal creates distortion. Read more about Bitcrushing * on [Wikipedia](https://en.wikipedia.org/wiki/Bitcrusher). * * @constructor * @extends {Tone.Effect} * @param {Number} bits The number of bits to downsample the signal. Nominal range * of 1 to 8. * @example * //initialize crusher and route a synth through it * var crusher = new Tone.BitCrusher(4).toMaster(); * var synth = new Tone.MonoSynth().connect(crusher); */ Tone.BitCrusher = function () { var options = this.optionsObject(arguments, ['bits'], Tone.BitCrusher.defaults); Tone.Effect.call(this, options); var invStepSize = 1 / Math.pow(2, options.bits - 1); /** * Subtract the input signal and the modulus of the input signal * @type {Tone.Subtract} * @private */ this._subtract = new Tone.Subtract(); /** * The mod function * @type {Tone.Modulo} * @private */ this._modulo = new Tone.Modulo(invStepSize); /** * keeps track of the bits * @type {number} * @private */ this._bits = options.bits; //connect it up this.effectSend.fan(this._subtract, this._modulo); this._modulo.connect(this._subtract, 0, 1); this._subtract.connect(this.effectReturn); }; Tone.extend(Tone.BitCrusher, Tone.Effect); /** * the default values * @static * @type {Object} */ Tone.BitCrusher.defaults = { 'bits': 4 }; /** * The bit depth of the effect. Nominal range of 1-8. * @memberOf Tone.BitCrusher# * @type {number} * @name bits */ Object.defineProperty(Tone.BitCrusher.prototype, 'bits', { get: function () { return this._bits; }, set: function (bits) { this._bits = bits; var invStepSize = 1 / Math.pow(2, bits - 1); this._modulo.value = invStepSize; } }); /** * Clean up. * @returns {Tone.BitCrusher} this */ Tone.BitCrusher.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._subtract.dispose(); this._subtract = null; this._modulo.dispose(); this._modulo = null; return this; }; return Tone.BitCrusher; }); Module(function (Tone) { /** * @class Tone.ChebyShev is a Chebyshev waveshaper, an effect which is good * for making different types of distortion sounds. * Note that odd orders sound very different from even ones, * and order = 1 is no change. * Read more at [music.columbia.edu](http://music.columbia.edu/cmc/musicandcomputers/chapter4/04_06.php). * * @extends {Tone.Effect} * @constructor * @param {Positive|Object} [order] The order of the chebyshev polynomial. Normal range between 1-100. * @example * //create a new cheby * var cheby = new Tone.Chebyshev(50); * //create a monosynth connected to our cheby * synth = new Tone.MonoSynth().connect(cheby); */ Tone.Chebyshev = function () { var options = this.optionsObject(arguments, ['order'], Tone.Chebyshev.defaults); Tone.Effect.call(this, options); /** * @type {WaveShaperNode} * @private */ this._shaper = new Tone.WaveShaper(4096); /** * holds onto the order of the filter * @type {number} * @private */ this._order = options.order; this.connectEffect(this._shaper); this.order = options.order; this.oversample = options.oversample; }; Tone.extend(Tone.Chebyshev, Tone.Effect); /** * @static * @const * @type {Object} */ Tone.Chebyshev.defaults = { 'order': 1, 'oversample': 'none' }; /** * get the coefficient for that degree * @param {number} x the x value * @param {number} degree * @param {Object} memo memoize the computed value. * this speeds up computation greatly. * @return {number} the coefficient * @private */ Tone.Chebyshev.prototype._getCoefficient = function (x, degree, memo) { if (memo.hasOwnProperty(degree)) { return memo[degree]; } else if (degree === 0) { memo[degree] = 0; } else if (degree === 1) { memo[degree] = x; } else { memo[degree] = 2 * x * this._getCoefficient(x, degree - 1, memo) - this._getCoefficient(x, degree - 2, memo); } return memo[degree]; }; /** * The order of the Chebyshev polynomial which creates * the equation which is applied to the incoming * signal through a Tone.WaveShaper. The equations * are in the form:<br> * order 2: 2x^2 + 1<br> * order 3: 4x^3 + 3x <br> * @memberOf Tone.Chebyshev# * @type {Positive} * @name order */ Object.defineProperty(Tone.Chebyshev.prototype, 'order', { get: function () { return this._order; }, set: function (order) { this._order = order; var curve = new Array(4096); var len = curve.length; for (var i = 0; i < len; ++i) { var x = i * 2 / len - 1; if (x === 0) { //should output 0 when input is 0 curve[i] = 0; } else { curve[i] = this._getCoefficient(x, order, {}); } } this._shaper.curve = curve; } }); /** * The oversampling of the effect. Can either be "none", "2x" or "4x". * @memberOf Tone.Chebyshev# * @type {string} * @name oversample */ Object.defineProperty(Tone.Chebyshev.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { this._shaper.oversample = oversampling; } }); /** * Clean up. * @returns {Tone.Chebyshev} this */ Tone.Chebyshev.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._shaper.dispose(); this._shaper = null; return this; }; return Tone.Chebyshev; }); Module(function (Tone) { /** * @class Base class for Stereo effects. Provides effectSendL/R and effectReturnL/R. * * @constructor * @extends {Tone.Effect} */ Tone.StereoEffect = function () { Tone.call(this); //get the defaults var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); /** * the drywet knob to control the amount of effect * @type {Tone.CrossFade} * @private */ this._dryWet = new Tone.CrossFade(options.wet); /** * The wet control, i.e. how much of the effected * will pass through to the output. * @type {NormalRange} * @signal */ this.wet = this._dryWet.fade; /** * then split it * @type {Tone.Split} * @private */ this._split = new Tone.Split(); /** * the effects send LEFT * @type {GainNode} * @private */ this.effectSendL = this._split.left; /** * the effects send RIGHT * @type {GainNode} * @private */ this.effectSendR = this._split.right; /** * the stereo effect merger * @type {Tone.Merge} * @private */ this._merge = new Tone.Merge(); /** * the effect return LEFT * @type {GainNode} * @private */ this.effectReturnL = this._merge.left; /** * the effect return RIGHT * @type {GainNode} * @private */ this.effectReturnR = this._merge.right; //connections this.input.connect(this._split); //dry wet connections this.input.connect(this._dryWet, 0, 0); this._merge.connect(this._dryWet, 0, 1); this._dryWet.connect(this.output); this._readOnly(['wet']); }; Tone.extend(Tone.StereoEffect, Tone.Effect); /** * Clean up. * @returns {Tone.StereoEffect} this */ Tone.StereoEffect.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._dryWet.dispose(); this._dryWet = null; this._split.dispose(); this._split = null; this._merge.dispose(); this._merge = null; this.effectSendL = null; this.effectSendR = null; this.effectReturnL = null; this.effectReturnR = null; this._writable(['wet']); this.wet = null; return this; }; return Tone.StereoEffect; }); Module(function (Tone) { /** * @class Tone.FeedbackEffect provides a loop between an * audio source and its own output. This is a base-class * for feedback effects. * * @constructor * @extends {Tone.Effect} * @param {NormalRange|Object} [feedback] The initial feedback value. */ Tone.FeedbackEffect = function () { var options = this.optionsObject(arguments, ['feedback']); options = this.defaultArg(options, Tone.FeedbackEffect.defaults); Tone.Effect.call(this, options); /** * The amount of signal which is fed back into the effect input. * @type {NormalRange} * @signal */ this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); /** * the gain which controls the feedback * @type {GainNode} * @private */ this._feedbackGain = this.context.createGain(); //the feedback loop this.effectReturn.chain(this._feedbackGain, this.effectSend); this.feedback.connect(this._feedbackGain.gain); this._readOnly(['feedback']); }; Tone.extend(Tone.FeedbackEffect, Tone.Effect); /** * @static * @type {Object} */ Tone.FeedbackEffect.defaults = { 'feedback': 0.125 }; /** * Clean up. * @returns {Tone.FeedbackEffect} this */ Tone.FeedbackEffect.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._writable(['feedback']); this.feedback.dispose(); this.feedback = null; this._feedbackGain.disconnect(); this._feedbackGain = null; return this; }; return Tone.FeedbackEffect; }); Module(function (Tone) { /** * @class Just like a stereo feedback effect, but the feedback is routed from left to right * and right to left instead of on the same channel. * * @constructor * @extends {Tone.FeedbackEffect} */ Tone.StereoXFeedbackEffect = function () { var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); Tone.StereoEffect.call(this, options); /** * The amount of feedback from the output * back into the input of the effect (routed * across left and right channels). * @type {NormalRange} * @signal */ this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); /** * the left side feeback * @type {GainNode} * @private */ this._feedbackLR = this.context.createGain(); /** * the right side feeback * @type {GainNode} * @private */ this._feedbackRL = this.context.createGain(); //connect it up this.effectReturnL.chain(this._feedbackLR, this.effectSendR); this.effectReturnR.chain(this._feedbackRL, this.effectSendL); this.feedback.fan(this._feedbackLR.gain, this._feedbackRL.gain); this._readOnly(['feedback']); }; Tone.extend(Tone.StereoXFeedbackEffect, Tone.FeedbackEffect); /** * clean up * @returns {Tone.StereoXFeedbackEffect} this */ Tone.StereoXFeedbackEffect.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable(['feedback']); this.feedback.dispose(); this.feedback = null; this._feedbackLR.disconnect(); this._feedbackLR = null; this._feedbackRL.disconnect(); this._feedbackRL = null; return this; }; return Tone.StereoXFeedbackEffect; }); Module(function (Tone) { /** * @class Tone.Chorus is a stereo chorus effect with feedback composed of * a left and right delay with a Tone.LFO applied to the delayTime of each channel. * Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna/blob/master/tuna.js). * Read more on the chorus effect on [SoundOnSound](http://www.soundonsound.com/sos/jun04/articles/synthsecrets.htm). * * @constructor * @extends {Tone.StereoXFeedbackEffect} * @param {Frequency|Object} [frequency] The frequency of the LFO. * @param {Milliseconds} [delayTime] The delay of the chorus effect in ms. * @param {NormalRange} [depth] The depth of the chorus. * @example * var chorus = new Tone.Chorus(4, 2.5, 0.5); * var synth = new Tone.PolySynth(4, Tone.MonoSynth).connect(chorus); * synth.triggerAttackRelease(["C3","E3","G3"], "8n"); */ Tone.Chorus = function () { var options = this.optionsObject(arguments, [ 'frequency', 'delayTime', 'depth' ], Tone.Chorus.defaults); Tone.StereoXFeedbackEffect.call(this, options); /** * the depth of the chorus * @type {number} * @private */ this._depth = options.depth; /** * the delayTime * @type {number} * @private */ this._delayTime = options.delayTime / 1000; /** * the lfo which controls the delayTime * @type {Tone.LFO} * @private */ this._lfoL = new Tone.LFO({ 'frequency': options.frequency, 'min': 0, 'max': 1 }); /** * another LFO for the right side with a 180 degree phase diff * @type {Tone.LFO} * @private */ this._lfoR = new Tone.LFO({ 'frequency': options.frequency, 'min': 0, 'max': 1, 'phase': 180 }); /** * delay for left * @type {DelayNode} * @private */ this._delayNodeL = this.context.createDelay(); /** * delay for right * @type {DelayNode} * @private */ this._delayNodeR = this.context.createDelay(); /** * The frequency of the LFO which modulates the delayTime. * @type {Frequency} * @signal */ this.frequency = this._lfoL.frequency; //connections this.effectSendL.chain(this._delayNodeL, this.effectReturnL); this.effectSendR.chain(this._delayNodeR, this.effectReturnR); //and pass through to make the detune apparent this.effectSendL.connect(this.effectReturnL); this.effectSendR.connect(this.effectReturnR); //lfo setup this._lfoL.connect(this._delayNodeL.delayTime); this._lfoR.connect(this._delayNodeR.delayTime); //start the lfo this._lfoL.start(); this._lfoR.start(); //have one LFO frequency control the other this._lfoL.frequency.connect(this._lfoR.frequency); //set the initial values this.depth = this._depth; this.frequency.value = options.frequency; this.type = options.type; this._readOnly(['frequency']); this.spread = options.spread; }; Tone.extend(Tone.Chorus, Tone.StereoXFeedbackEffect); /** * @static * @type {Object} */ Tone.Chorus.defaults = { 'frequency': 1.5, 'delayTime': 3.5, 'depth': 0.7, 'feedback': 0.1, 'type': 'sine', 'spread': 180 }; /** * The depth of the effect. A depth of 1 makes the delayTime * modulate between 0 and 2*delayTime (centered around the delayTime). * @memberOf Tone.Chorus# * @type {NormalRange} * @name depth */ Object.defineProperty(Tone.Chorus.prototype, 'depth', { get: function () { return this._depth; }, set: function (depth) { this._depth = depth; var deviation = this._delayTime * depth; this._lfoL.min = Math.max(this._delayTime - deviation, 0); this._lfoL.max = this._delayTime + deviation; this._lfoR.min = Math.max(this._delayTime - deviation, 0); this._lfoR.max = this._delayTime + deviation; } }); /** * The delayTime in milliseconds of the chorus. A larger delayTime * will give a more pronounced effect. Nominal range a delayTime * is between 2 and 20ms. * @memberOf Tone.Chorus# * @type {Milliseconds} * @name delayTime */ Object.defineProperty(Tone.Chorus.prototype, 'delayTime', { get: function () { return this._delayTime * 1000; }, set: function (delayTime) { this._delayTime = delayTime / 1000; this.depth = this._depth; } }); /** * The oscillator type of the LFO. * @memberOf Tone.Chorus# * @type {string} * @name type */ Object.defineProperty(Tone.Chorus.prototype, 'type', { get: function () { return this._lfoL.type; }, set: function (type) { this._lfoL.type = type; this._lfoR.type = type; } }); /** * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. * When set to 180, LFO's will be panned hard left and right respectively. * @memberOf Tone.Chorus# * @type {Degrees} * @name spread */ Object.defineProperty(Tone.Chorus.prototype, 'spread', { get: function () { return this._lfoR.phase - this._lfoL.phase; //180 }, set: function (spread) { this._lfoL.phase = 90 - spread / 2; this._lfoR.phase = spread / 2 + 90; } }); /** * Clean up. * @returns {Tone.Chorus} this */ Tone.Chorus.prototype.dispose = function () { Tone.StereoXFeedbackEffect.prototype.dispose.call(this); this._lfoL.dispose(); this._lfoL = null; this._lfoR.dispose(); this._lfoR = null; this._delayNodeL.disconnect(); this._delayNodeL = null; this._delayNodeR.disconnect(); this._delayNodeR = null; this._writable('frequency'); this.frequency = null; return this; }; return Tone.Chorus; }); Module(function (Tone) { /** * @class Tone.Convolver is a wrapper around the Native Web Audio * [ConvolverNode](http://webaudio.github.io/web-audio-api/#the-convolvernode-interface). * Convolution is useful for reverb and filter emulation. Read more about convolution reverb on * [Wikipedia](https://en.wikipedia.org/wiki/Convolution_reverb). * * @constructor * @extends {Tone.Effect} * @param {string|Tone.Buffer|Object} [url] The URL of the impulse response or the Tone.Buffer * contianing the impulse response. * @example * //initializing the convolver with an impulse response * var convolver = new Tone.Convolver("./path/to/ir.wav"); * convolver.toMaster(); * //after the buffer has loaded * Tone.Buffer.onload = function(){ * //testing out convolution with a noise burst * var burst = new Tone.NoiseSynth().connect(convolver); * burst.triggerAttackRelease("16n"); * }; */ Tone.Convolver = function () { var options = this.optionsObject(arguments, ['url'], Tone.Convolver.defaults); Tone.Effect.call(this, options); /** * convolver node * @type {ConvolverNode} * @private */ this._convolver = this.context.createConvolver(); /** * the convolution buffer * @type {Tone.Buffer} * @private */ this._buffer = new Tone.Buffer(options.url, function (buffer) { this.buffer = buffer; options.onload(); }.bind(this)); this.connectEffect(this._convolver); }; Tone.extend(Tone.Convolver, Tone.Effect); /** * @static * @const * @type {Object} */ Tone.Convolver.defaults = { 'url': '', 'onload': Tone.noOp }; /** * The convolver's buffer * @memberOf Tone.Convolver# * @type {AudioBuffer} * @name buffer */ Object.defineProperty(Tone.Convolver.prototype, 'buffer', { get: function () { return this._buffer.get(); }, set: function (buffer) { this._buffer.set(buffer); this._convolver.buffer = this._buffer.get(); } }); /** * Load an impulse response url as an audio buffer. * Decodes the audio asynchronously and invokes * the callback once the audio buffer loads. * @param {string} url The url of the buffer to load. * filetype support depends on the * browser. * @param {function=} callback * @returns {Tone.Convolver} this */ Tone.Convolver.prototype.load = function (url, callback) { this._buffer.load(url, function (buff) { this.buffer = buff; if (callback) { callback(); } }.bind(this)); return this; }; /** * Clean up. * @returns {Tone.Convolver} this */ Tone.Convolver.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._convolver.disconnect(); this._convolver = null; this._buffer.dispose(); this._buffer = null; return this; }; return Tone.Convolver; }); Module(function (Tone) { /** * @class Tone.Distortion is a simple distortion effect using Tone.WaveShaper. * Algorithm from [a stackoverflow answer](http://stackoverflow.com/a/22313408). * * @extends {Tone.Effect} * @constructor * @param {Number|Object} [distortion] The amount of distortion (nominal range of 0-1) * @example * var dist = new Tone.Distortion(0.8).toMaster(); * var fm = new Tone.SimpleFM().connect(dist); * //this sounds good on bass notes * fm.triggerAttackRelease("A1", "8n"); */ Tone.Distortion = function () { var options = this.optionsObject(arguments, ['distortion'], Tone.Distortion.defaults); Tone.Effect.call(this, options); /** * @type {Tone.WaveShaper} * @private */ this._shaper = new Tone.WaveShaper(4096); /** * holds the distortion amount * @type {number} * @private */ this._distortion = options.distortion; this.connectEffect(this._shaper); this.distortion = options.distortion; this.oversample = options.oversample; }; Tone.extend(Tone.Distortion, Tone.Effect); /** * @static * @const * @type {Object} */ Tone.Distortion.defaults = { 'distortion': 0.4, 'oversample': 'none' }; /** * The amount of distortion. * @memberOf Tone.Distortion# * @type {NormalRange} * @name distortion */ Object.defineProperty(Tone.Distortion.prototype, 'distortion', { get: function () { return this._distortion; }, set: function (amount) { this._distortion = amount; var k = amount * 100; var deg = Math.PI / 180; this._shaper.setMap(function (x) { if (Math.abs(x) < 0.001) { //should output 0 when input is 0 return 0; } else { return (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x)); } }); } }); /** * The oversampling of the effect. Can either be "none", "2x" or "4x". * @memberOf Tone.Distortion# * @type {string} * @name oversample */ Object.defineProperty(Tone.Distortion.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { this._shaper.oversample = oversampling; } }); /** * Clean up. * @returns {Tone.Distortion} this */ Tone.Distortion.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._shaper.dispose(); this._shaper = null; return this; }; return Tone.Distortion; }); Module(function (Tone) { /** * @class Tone.FeedbackDelay is a DelayNode in which part of output * signal is fed back into the delay. * * @constructor * @extends {Tone.FeedbackEffect} * @param {Time|Object} [delayTime] The delay applied to the incoming signal. * @param {NormalRange=} feedback The amount of the effected signal which * is fed back through the delay. * @example * var feedbackDelay = new Tone.FeedbackDelay("8n", 0.5).toMaster(); * var tom = new Tone.DrumSynth({ * "octaves" : 4, * "pitchDecay" : 0.1 * }).connect(feedbackDelay); * tom.triggerAttackRelease("A2","32n"); */ Tone.FeedbackDelay = function () { var options = this.optionsObject(arguments, [ 'delayTime', 'feedback' ], Tone.FeedbackDelay.defaults); Tone.FeedbackEffect.call(this, options); /** * The delayTime of the DelayNode. * @type {Time} * @signal */ this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); /** * the delay node * @type {DelayNode} * @private */ this._delayNode = this.context.createDelay(4); // connect it up this.connectEffect(this._delayNode); this.delayTime.connect(this._delayNode.delayTime); this._readOnly(['delayTime']); }; Tone.extend(Tone.FeedbackDelay, Tone.FeedbackEffect); /** * The default values. * @const * @static * @type {Object} */ Tone.FeedbackDelay.defaults = { 'delayTime': 0.25 }; /** * clean up * @returns {Tone.FeedbackDelay} this */ Tone.FeedbackDelay.prototype.dispose = function () { Tone.FeedbackEffect.prototype.dispose.call(this); this.delayTime.dispose(); this._delayNode.disconnect(); this._delayNode = null; this._writable(['delayTime']); this.delayTime = null; return this; }; return Tone.FeedbackDelay; }); Module(function (Tone) { /** * an array of comb filter delay values from Freeverb implementation * @static * @private * @type {Array} */ var combFilterTunings = [ 1557 / 44100, 1617 / 44100, 1491 / 44100, 1422 / 44100, 1277 / 44100, 1356 / 44100, 1188 / 44100, 1116 / 44100 ]; /** * an array of allpass filter frequency values from Freeverb implementation * @private * @static * @type {Array} */ var allpassFilterFrequencies = [ 225, 556, 441, 341 ]; /** * @class Tone.Freeverb is a reverb based on [Freeverb](https://ccrma.stanford.edu/~jos/pasp/Freeverb.html). * Read more on reverb on [SoundOnSound](http://www.soundonsound.com/sos/may00/articles/reverb.htm). * * @extends {Tone.Effect} * @constructor * @param {NormalRange|Object} [roomSize] Correlated to the decay time. * @param {Frequency} [dampening] The cutoff frequency of a lowpass filter as part * of the reverb. * @example * var freeverb = new Tone.Freeverb().toMaster(); * freeverb.dampening.value = 1000; * //routing synth through the reverb * var synth = new Tone.AMSynth().connect(freeverb); */ Tone.Freeverb = function () { var options = this.optionsObject(arguments, [ 'roomSize', 'dampening' ], Tone.Freeverb.defaults); Tone.StereoEffect.call(this, options); /** * The roomSize value between. A larger roomSize * will result in a longer decay. * @type {NormalRange} * @signal */ this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); /** * The amount of dampening of the reverberant signal. * @type {Frequency} * @signal */ this.dampening = new Tone.Signal(options.dampening, Tone.Type.Frequency); /** * the comb filters * @type {Array} * @private */ this._combFilters = []; /** * the allpass filters on the left * @type {Array} * @private */ this._allpassFiltersL = []; /** * the allpass filters on the right * @type {Array} * @private */ this._allpassFiltersR = []; //make the allpass filters on teh right for (var l = 0; l < allpassFilterFrequencies.length; l++) { var allpassL = this.context.createBiquadFilter(); allpassL.type = 'allpass'; allpassL.frequency.value = allpassFilterFrequencies[l]; this._allpassFiltersL.push(allpassL); } //make the allpass filters on the left for (var r = 0; r < allpassFilterFrequencies.length; r++) { var allpassR = this.context.createBiquadFilter(); allpassR.type = 'allpass'; allpassR.frequency.value = allpassFilterFrequencies[r]; this._allpassFiltersR.push(allpassR); } //make the comb filters for (var c = 0; c < combFilterTunings.length; c++) { var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]); if (c < combFilterTunings.length / 2) { this.effectSendL.chain(lfpf, this._allpassFiltersL[0]); } else { this.effectSendR.chain(lfpf, this._allpassFiltersR[0]); } this.roomSize.connect(lfpf.resonance); this.dampening.connect(lfpf.dampening); this._combFilters.push(lfpf); } //chain the allpass filters togetehr this.connectSeries.apply(this, this._allpassFiltersL); this.connectSeries.apply(this, this._allpassFiltersR); this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL); this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR); this._readOnly([ 'roomSize', 'dampening' ]); }; Tone.extend(Tone.Freeverb, Tone.StereoEffect); /** * @static * @type {Object} */ Tone.Freeverb.defaults = { 'roomSize': 0.7, 'dampening': 3000 }; /** * Clean up. * @returns {Tone.Freeverb} this */ Tone.Freeverb.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); for (var al = 0; al < this._allpassFiltersL.length; al++) { this._allpassFiltersL[al].disconnect(); this._allpassFiltersL[al] = null; } this._allpassFiltersL = null; for (var ar = 0; ar < this._allpassFiltersR.length; ar++) { this._allpassFiltersR[ar].disconnect(); this._allpassFiltersR[ar] = null; } this._allpassFiltersR = null; for (var cf = 0; cf < this._combFilters.length; cf++) { this._combFilters[cf].dispose(); this._combFilters[cf] = null; } this._combFilters = null; this._writable([ 'roomSize', 'dampening' ]); this.roomSize.dispose(); this.roomSize = null; this.dampening.dispose(); this.dampening = null; return this; }; return Tone.Freeverb; }); Module(function (Tone) { /** * an array of the comb filter delay time values * @private * @static * @type {Array} */ var combFilterDelayTimes = [ 1687 / 25000, 1601 / 25000, 2053 / 25000, 2251 / 25000 ]; /** * the resonances of each of the comb filters * @private * @static * @type {Array} */ var combFilterResonances = [ 0.773, 0.802, 0.753, 0.733 ]; /** * the allpass filter frequencies * @private * @static * @type {Array} */ var allpassFilterFreqs = [ 347, 113, 37 ]; /** * @class Tone.JCReverb is a simple [Schroeder Reverberator](https://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberators.html) * tuned by John Chowning in 1970. * It is made up of three allpass filters and four Tone.FeedbackCombFilter. * * * @extends {Tone.Effect} * @constructor * @param {NormalRange|Object} [roomSize] Coorelates to the decay time. * @example * var reverb = new Tone.JCReverb(0.4).connect(Tone.Master); * var delay = new Tone.FeedbackDelay(0.5); * //connecting the synth to reverb through delay * var synth = new Tone.DuoSynth().chain(delay, reverb); * synth.triggerAttackRelease("A4","8n"); */ Tone.JCReverb = function () { var options = this.optionsObject(arguments, ['roomSize'], Tone.JCReverb.defaults); Tone.StereoEffect.call(this, options); /** * room size control values between [0,1] * @type {NormalRange} * @signal */ this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); /** * scale the room size * @type {Tone.Scale} * @private */ this._scaleRoomSize = new Tone.Scale(-0.733, 0.197); /** * a series of allpass filters * @type {Array} * @private */ this._allpassFilters = []; /** * parallel feedback comb filters * @type {Array} * @private */ this._feedbackCombFilters = []; //make the allpass filters for (var af = 0; af < allpassFilterFreqs.length; af++) { var allpass = this.context.createBiquadFilter(); allpass.type = 'allpass'; allpass.frequency.value = allpassFilterFreqs[af]; this._allpassFilters.push(allpass); } //and the comb filters for (var cf = 0; cf < combFilterDelayTimes.length; cf++) { var fbcf = new Tone.FeedbackCombFilter(combFilterDelayTimes[cf], 0.1); this._scaleRoomSize.connect(fbcf.resonance); fbcf.resonance.value = combFilterResonances[cf]; this._allpassFilters[this._allpassFilters.length - 1].connect(fbcf); if (cf < combFilterDelayTimes.length / 2) { fbcf.connect(this.effectReturnL); } else { fbcf.connect(this.effectReturnR); } this._feedbackCombFilters.push(fbcf); } //chain the allpass filters together this.roomSize.connect(this._scaleRoomSize); this.connectSeries.apply(this, this._allpassFilters); this.effectSendL.connect(this._allpassFilters[0]); this.effectSendR.connect(this._allpassFilters[0]); this._readOnly(['roomSize']); }; Tone.extend(Tone.JCReverb, Tone.StereoEffect); /** * the default values * @static * @const * @type {Object} */ Tone.JCReverb.defaults = { 'roomSize': 0.5 }; /** * Clean up. * @returns {Tone.JCReverb} this */ Tone.JCReverb.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); for (var apf = 0; apf < this._allpassFilters.length; apf++) { this._allpassFilters[apf].disconnect(); this._allpassFilters[apf] = null; } this._allpassFilters = null; for (var fbcf = 0; fbcf < this._feedbackCombFilters.length; fbcf++) { this._feedbackCombFilters[fbcf].dispose(); this._feedbackCombFilters[fbcf] = null; } this._feedbackCombFilters = null; this._writable(['roomSize']); this.roomSize.dispose(); this.roomSize = null; this._scaleRoomSize.dispose(); this._scaleRoomSize = null; return this; }; return Tone.JCReverb; }); Module(function (Tone) { /** * @class Mid/Side processing separates the the 'mid' signal * (which comes out of both the left and the right channel) * and the 'side' (which only comes out of the the side channels) * and effects them separately before being recombined. * Applies a Mid/Side seperation and recombination. * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). * <br><br> * This is a base-class for Mid/Side Effects. * * @extends {Tone.Effect} * @constructor */ Tone.MidSideEffect = function () { Tone.Effect.apply(this, arguments); /** * The mid/side split * @type {Tone.MidSideSplit} * @private */ this._midSideSplit = new Tone.MidSideSplit(); /** * The mid/side merge * @type {Tone.MidSideMerge} * @private */ this._midSideMerge = new Tone.MidSideMerge(); /** * The mid send. Connect to mid processing * @type {Tone.Expr} * @private */ this.midSend = this._midSideSplit.mid; /** * The side send. Connect to side processing * @type {Tone.Expr} * @private */ this.sideSend = this._midSideSplit.side; /** * The mid return connection * @type {GainNode} * @private */ this.midReturn = this._midSideMerge.mid; /** * The side return connection * @type {GainNode} * @private */ this.sideReturn = this._midSideMerge.side; //the connections this.effectSend.connect(this._midSideSplit); this._midSideMerge.connect(this.effectReturn); }; Tone.extend(Tone.MidSideEffect, Tone.Effect); /** * Clean up. * @returns {Tone.MidSideEffect} this */ Tone.MidSideEffect.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._midSideSplit.dispose(); this._midSideSplit = null; this._midSideMerge.dispose(); this._midSideMerge = null; this.midSend = null; this.sideSend = null; this.midReturn = null; this.sideReturn = null; return this; }; return Tone.MidSideEffect; }); Module(function (Tone) { /** * @class Tone.Phaser is a phaser effect. Phasers work by changing the phase * of different frequency components of an incoming signal. Read more on * [Wikipedia](https://en.wikipedia.org/wiki/Phaser_(effect)). * Inspiration for this phaser comes from [Tuna.js](https://github.com/Dinahmoe/tuna/). * * @extends {Tone.StereoEffect} * @constructor * @param {Frequency|Object} [frequency] The speed of the phasing. * @param {number} [octaves] The octaves of the effect. * @param {Frequency} [baseFrequency] The base frequency of the filters. * @example * var phaser = new Tone.Phaser({ * "frequency" : 15, * "octaves" : 5, * "baseFrequency" : 1000 * }).toMaster(); * var synth = new Tone.FMSynth().connect(phaser); * synth.triggerAttackRelease("E3", "2n"); */ Tone.Phaser = function () { //set the defaults var options = this.optionsObject(arguments, [ 'frequency', 'octaves', 'baseFrequency' ], Tone.Phaser.defaults); Tone.StereoEffect.call(this, options); /** * the lfo which controls the frequency on the left side * @type {Tone.LFO} * @private */ this._lfoL = new Tone.LFO(options.frequency, 0, 1); /** * the lfo which controls the frequency on the right side * @type {Tone.LFO} * @private */ this._lfoR = new Tone.LFO(options.frequency, 0, 1); this._lfoR.phase = 180; /** * the base modulation frequency * @type {number} * @private */ this._baseFrequency = options.baseFrequency; /** * the octaves of the phasing * @type {number} * @private */ this._octaves = options.octaves; /** * The quality factor of the filters * @type {Positive} * @signal */ this.Q = new Tone.Signal(options.Q, Tone.Type.Positive); /** * the array of filters for the left side * @type {Array} * @private */ this._filtersL = this._makeFilters(options.stages, this._lfoL, this.Q); /** * the array of filters for the left side * @type {Array} * @private */ this._filtersR = this._makeFilters(options.stages, this._lfoR, this.Q); /** * the frequency of the effect * @type {Tone.Signal} */ this.frequency = this._lfoL.frequency; this.frequency.value = options.frequency; //connect them up this.effectSendL.connect(this._filtersL[0]); this.effectSendR.connect(this._filtersR[0]); this._filtersL[options.stages - 1].connect(this.effectReturnL); this._filtersR[options.stages - 1].connect(this.effectReturnR); //control the frequency with one LFO this._lfoL.frequency.connect(this._lfoR.frequency); //set the options this.baseFrequency = options.baseFrequency; this.octaves = options.octaves; //start the lfo this._lfoL.start(); this._lfoR.start(); this._readOnly([ 'frequency', 'Q' ]); }; Tone.extend(Tone.Phaser, Tone.StereoEffect); /** * defaults * @static * @type {object} */ Tone.Phaser.defaults = { 'frequency': 0.5, 'octaves': 3, 'stages': 10, 'Q': 10, 'baseFrequency': 350 }; /** * @param {number} stages * @returns {Array} the number of filters all connected together * @private */ Tone.Phaser.prototype._makeFilters = function (stages, connectToFreq, Q) { var filters = new Array(stages); //make all the filters for (var i = 0; i < stages; i++) { var filter = this.context.createBiquadFilter(); filter.type = 'allpass'; Q.connect(filter.Q); connectToFreq.connect(filter.frequency); filters[i] = filter; } this.connectSeries.apply(this, filters); return filters; }; /** * The number of octaves the phase goes above * the baseFrequency * @memberOf Tone.Phaser# * @type {Positive} * @name octaves */ Object.defineProperty(Tone.Phaser.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (octaves) { this._octaves = octaves; var max = this._baseFrequency * Math.pow(2, octaves); this._lfoL.max = max; this._lfoR.max = max; } }); /** * The the base frequency of the filters. * @memberOf Tone.Phaser# * @type {number} * @name baseFrequency */ Object.defineProperty(Tone.Phaser.prototype, 'baseFrequency', { get: function () { return this._baseFrequency; }, set: function (freq) { this._baseFrequency = freq; this._lfoL.min = freq; this._lfoR.min = freq; this.octaves = this._octaves; } }); /** * clean up * @returns {Tone.Phaser} this */ Tone.Phaser.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable([ 'frequency', 'Q' ]); this.Q.dispose(); this.Q = null; this._lfoL.dispose(); this._lfoL = null; this._lfoR.dispose(); this._lfoR = null; for (var i = 0; i < this._filtersL.length; i++) { this._filtersL[i].disconnect(); this._filtersL[i] = null; } this._filtersL = null; for (var j = 0; j < this._filtersR.length; j++) { this._filtersR[j].disconnect(); this._filtersR[j] = null; } this._filtersR = null; this.frequency = null; return this; }; return Tone.Phaser; }); Module(function (Tone) { /** * @class Tone.PingPongDelay is a feedback delay effect where the echo is heard * first in one channel and next in the opposite channel. In a stereo * system these are the right and left channels. * PingPongDelay in more simplified terms is two Tone.FeedbackDelays * with independent delay values. Each delay is routed to one channel * (left or right), and the channel triggered second will always * trigger at the same interval after the first. * * @constructor * @extends {Tone.StereoXFeedbackEffect} * @param {Time|Object} [delayTime] The delayTime between consecutive echos. * @param {NormalRange=} feedback The amount of the effected signal which * is fed back through the delay. * @example * var pingPong = new Tone.PingPongDelay("4n", 0.2).toMaster(); * var drum = new Tone.DrumSynth().connect(pingPong); * drum.triggerAttackRelease("C4", "32n"); */ Tone.PingPongDelay = function () { var options = this.optionsObject(arguments, [ 'delayTime', 'feedback' ], Tone.PingPongDelay.defaults); Tone.StereoXFeedbackEffect.call(this, options); /** * the delay node on the left side * @type {DelayNode} * @private */ this._leftDelay = this.context.createDelay(options.maxDelayTime); /** * the delay node on the right side * @type {DelayNode} * @private */ this._rightDelay = this.context.createDelay(options.maxDelayTime); /** * the predelay on the right side * @type {DelayNode} * @private */ this._rightPreDelay = this.context.createDelay(options.maxDelayTime); /** * the delay time signal * @type {Time} * @signal */ this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); //connect it up this.effectSendL.chain(this._leftDelay, this.effectReturnL); this.effectSendR.chain(this._rightPreDelay, this._rightDelay, this.effectReturnR); this.delayTime.fan(this._leftDelay.delayTime, this._rightDelay.delayTime, this._rightPreDelay.delayTime); //rearranged the feedback to be after the rightPreDelay this._feedbackLR.disconnect(); this._feedbackLR.connect(this._rightDelay); this._readOnly(['delayTime']); }; Tone.extend(Tone.PingPongDelay, Tone.StereoXFeedbackEffect); /** * @static * @type {Object} */ Tone.PingPongDelay.defaults = { 'delayTime': 0.25, 'maxDelayTime': 1 }; /** * Clean up. * @returns {Tone.PingPongDelay} this */ Tone.PingPongDelay.prototype.dispose = function () { Tone.StereoXFeedbackEffect.prototype.dispose.call(this); this._leftDelay.disconnect(); this._leftDelay = null; this._rightDelay.disconnect(); this._rightDelay = null; this._rightPreDelay.disconnect(); this._rightPreDelay = null; this._writable(['delayTime']); this.delayTime.dispose(); this.delayTime = null; return this; }; return Tone.PingPongDelay; }); Module(function (Tone) { /** * @class Tone.PitchShift does near-realtime pitch shifting to the incoming signal. * The effect is achieved by speeding up or slowing down the delayTime * of a DelayNode using a sawtooth wave. * Algorithm found in [this pdf](http://dsp-book.narod.ru/soundproc.pdf). * Additional reference by [Miller Pucket](http://msp.ucsd.edu/techniques/v0.11/book-html/node115.html). * * @extends {Tone.FeedbackEffect} * @param {Interval=} pitch The interval to transpose the incoming signal by. */ Tone.PitchShift = function () { var options = this.optionsObject(arguments, ['pitch'], Tone.PitchShift.defaults); Tone.FeedbackEffect.call(this, options); /** * The pitch signal * @type {Tone.Signal} * @private */ this._frequency = new Tone.Signal(0); /** * Uses two DelayNodes to cover up the jump in * the sawtooth wave. * @type {DelayNode} * @private */ this._delayA = new Tone.Delay(0, 1); /** * The first LFO. * @type {Tone.LFO} * @private */ this._lfoA = new Tone.LFO({ 'min': 0, 'max': 0.1, 'type': 'sawtooth' }).connect(this._delayA.delayTime); /** * The second DelayNode * @type {DelayNode} * @private */ this._delayB = new Tone.Delay(0, 1); /** * The first LFO. * @type {Tone.LFO} * @private */ this._lfoB = new Tone.LFO({ 'min': 0, 'max': 0.1, 'type': 'sawtooth', 'phase': 180 }).connect(this._delayB.delayTime); /** * Crossfade quickly between the two delay lines * to cover up the jump in the sawtooth wave * @type {Tone.CrossFade} * @private */ this._crossFade = new Tone.CrossFade(); /** * LFO which alternates between the two * delay lines to cover up the disparity in the * sawtooth wave. * @type {Tone.LFO} * @private */ this._crossFadeLFO = new Tone.LFO({ 'min': 0, 'max': 1, 'type': 'triangle', 'phase': 90 }).connect(this._crossFade.fade); /** * The delay node * @type {Tone.Delay} * @private */ this._feedbackDelay = new Tone.Delay(options.delayTime); /** * The amount of delay on the input signal * @type {Time} * @signal */ this.delayTime = this._feedbackDelay.delayTime; this._readOnly('delayTime'); /** * Hold the current pitch * @type {Number} * @private */ this._pitch = options.pitch; /** * Hold the current windowSize * @type {Number} * @private */ this._windowSize = options.windowSize; //connect the two delay lines up this._delayA.connect(this._crossFade.a); this._delayB.connect(this._crossFade.b); //connect the frequency this._frequency.fan(this._lfoA.frequency, this._lfoB.frequency, this._crossFadeLFO.frequency); //route the input this.effectSend.fan(this._delayA, this._delayB); this._crossFade.chain(this._feedbackDelay, this.effectReturn); //start the LFOs at the same time var now = this.now(); this._lfoA.start(now); this._lfoB.start(now); this._crossFadeLFO.start(now); //set the initial value this.windowSize = this._windowSize; }; Tone.extend(Tone.PitchShift, Tone.FeedbackEffect); /** * default values * @static * @type {Object} * @const */ Tone.PitchShift.defaults = { 'pitch': 0, 'windowSize': 0.1, 'delayTime': 0, 'feedback': 0 }; /** * Repitch the incoming signal by some interval (measured * in semi-tones). * @memberOf Tone.PitchShift# * @type {Interval} * @name pitch * @example * pitchShift.pitch = -12; //down one octave * pitchShift.pitch = 7; //up a fifth */ Object.defineProperty(Tone.PitchShift.prototype, 'pitch', { get: function () { return this._pitch; }, set: function (interval) { this._pitch = interval; var factor = 0; if (interval < 0) { this._lfoA.min = 0; this._lfoA.max = this._windowSize; this._lfoB.min = 0; this._lfoB.max = this._windowSize; factor = this.intervalToFrequencyRatio(interval - 1) + 1; } else { this._lfoA.min = this._windowSize; this._lfoA.max = 0; this._lfoB.min = this._windowSize; this._lfoB.max = 0; factor = this.intervalToFrequencyRatio(interval) - 1; } this._frequency.value = factor * (1.2 / this._windowSize); } }); /** * The window size corresponds roughly to the sample length in a looping sampler. * Smaller values are desirable for a less noticeable delay time of the pitch shifted * signal, but larger values will result in smoother pitch shifting for larger intervals. * A nominal range of 0.03 to 0.1 is recommended. * @memberOf Tone.PitchShift# * @type {Time} * @name windowSize * @example * pitchShift.windowSize = 0.1; */ Object.defineProperty(Tone.PitchShift.prototype, 'windowSize', { get: function () { return this._windowSize; }, set: function (size) { this._windowSize = this.toSeconds(size); this.pitch = this._pitch; } }); /** * Clean up. * @return {Tone.PitchShift} this */ Tone.PitchShift.prototype.dispose = function () { Tone.FeedbackEffect.prototype.dispose.call(this); this._frequency.dispose(); this._frequency = null; this._delayA.disconnect(); this._delayA = null; this._delayB.disconnect(); this._delayB = null; this._lfoA.dispose(); this._lfoA = null; this._lfoB.dispose(); this._lfoB = null; this._crossFade.dispose(); this._crossFade = null; this._crossFadeLFO.dispose(); this._crossFadeLFO = null; this._writable('delayTime'); this._feedbackDelay.dispose(); this._feedbackDelay = null; this.delayTime = null; return this; }; return Tone.PitchShift; }); Module(function (Tone) { /** * @class Base class for stereo feedback effects where the effectReturn * is fed back into the same channel. * * @constructor * @extends {Tone.FeedbackEffect} */ Tone.StereoFeedbackEffect = function () { var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); Tone.StereoEffect.call(this, options); /** * controls the amount of feedback * @type {NormalRange} * @signal */ this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); /** * the left side feeback * @type {GainNode} * @private */ this._feedbackL = this.context.createGain(); /** * the right side feeback * @type {GainNode} * @private */ this._feedbackR = this.context.createGain(); //connect it up this.effectReturnL.chain(this._feedbackL, this.effectSendL); this.effectReturnR.chain(this._feedbackR, this.effectSendR); this.feedback.fan(this._feedbackL.gain, this._feedbackR.gain); this._readOnly(['feedback']); }; Tone.extend(Tone.StereoFeedbackEffect, Tone.FeedbackEffect); /** * clean up * @returns {Tone.StereoFeedbackEffect} this */ Tone.StereoFeedbackEffect.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable(['feedback']); this.feedback.dispose(); this.feedback = null; this._feedbackL.disconnect(); this._feedbackL = null; this._feedbackR.disconnect(); this._feedbackR = null; return this; }; return Tone.StereoFeedbackEffect; }); Module(function (Tone) { /** * @class Applies a width factor to the mid/side seperation. * 0 is all mid and 1 is all side. * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). * <br><br> * <code> * Mid *= 2*(1-width)<br> * Side *= 2*width * </code> * * @extends {Tone.MidSideEffect} * @constructor * @param {NormalRange|Object} [width] The stereo width. A width of 0 is mono and 1 is stereo. 0.5 is no change. */ Tone.StereoWidener = function () { var options = this.optionsObject(arguments, ['width'], Tone.StereoWidener.defaults); Tone.MidSideEffect.call(this, options); /** * The width control. 0 = 100% mid. 1 = 100% side. 0.5 = no change. * @type {NormalRange} * @signal */ this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); /** * Mid multiplier * @type {Tone.Expr} * @private */ this._midMult = new Tone.Expr('$0 * ($1 * (1 - $2))'); /** * Side multiplier * @type {Tone.Expr} * @private */ this._sideMult = new Tone.Expr('$0 * ($1 * $2)'); /** * constant output of 2 * @type {Tone} * @private */ this._two = new Tone.Signal(2); //the mid chain this._two.connect(this._midMult, 0, 1); this.width.connect(this._midMult, 0, 2); //the side chain this._two.connect(this._sideMult, 0, 1); this.width.connect(this._sideMult, 0, 2); //connect it to the effect send/return this.midSend.chain(this._midMult, this.midReturn); this.sideSend.chain(this._sideMult, this.sideReturn); this._readOnly(['width']); }; Tone.extend(Tone.StereoWidener, Tone.MidSideEffect); /** * the default values * @static * @type {Object} */ Tone.StereoWidener.defaults = { 'width': 0.5 }; /** * Clean up. * @returns {Tone.StereoWidener} this */ Tone.StereoWidener.prototype.dispose = function () { Tone.MidSideEffect.prototype.dispose.call(this); this._writable(['width']); this.width.dispose(); this.width = null; this._midMult.dispose(); this._midMult = null; this._sideMult.dispose(); this._sideMult = null; this._two.dispose(); this._two = null; return this; }; return Tone.StereoWidener; }); Module(function (Tone) { /** * @class Tone.Tremolo modulates the amplitude of an incoming signal using a Tone.LFO. * The type, frequency, and depth of the LFO is controllable. * * @extends {Tone.StereoEffect} * @constructor * @param {Frequency} [frequency] The rate of the effect. * @param {NormalRange} [depth] The depth of the effect. * @example * //create a tremolo and start it's LFO * var tremolo = new Tone.Tremolo(9, 0.75).toMaster().start(); * //route an oscillator through the tremolo and start it * var oscillator = new Tone.Oscillator().connect(tremolo).start(); */ Tone.Tremolo = function () { var options = this.optionsObject(arguments, [ 'frequency', 'depth' ], Tone.Tremolo.defaults); Tone.StereoEffect.call(this, options); /** * The tremelo LFO in the left channel * @type {Tone.LFO} * @private */ this._lfoL = new Tone.LFO({ 'phase': options.spread, 'min': 1, 'max': 0 }); /** * The tremelo LFO in the left channel * @type {Tone.LFO} * @private */ this._lfoR = new Tone.LFO({ 'phase': options.spread, 'min': 1, 'max': 0 }); /** * Where the gain is multiplied * @type {Tone.Gain} * @private */ this._amplitudeL = new Tone.Gain(); /** * Where the gain is multiplied * @type {Tone.Gain} * @private */ this._amplitudeR = new Tone.Gain(); /** * The frequency of the tremolo. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The depth of the effect. A depth of 0, has no effect * on the amplitude, and a depth of 1 makes the amplitude * modulate fully between 0 and 1. * @type {NormalRange} * @signal */ this.depth = new Tone.Signal(options.depth, Tone.Type.NormalRange); this._readOnly([ 'frequency', 'depth' ]); this.effectSendL.chain(this._amplitudeL, this.effectReturnL); this.effectSendR.chain(this._amplitudeR, this.effectReturnR); this._lfoL.connect(this._amplitudeL.gain); this._lfoR.connect(this._amplitudeR.gain); this.frequency.fan(this._lfoL.frequency, this._lfoR.frequency); this.depth.fan(this._lfoR.amplitude, this._lfoL.amplitude); this.type = options.type; this.spread = options.spread; }; Tone.extend(Tone.Tremolo, Tone.StereoEffect); /** * @static * @const * @type {Object} */ Tone.Tremolo.defaults = { 'frequency': 10, 'type': 'sine', 'depth': 0.5, 'spread': 180 }; /** * Start the tremolo. * @param {Time} [time=now] When the tremolo begins. * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.start = function (time) { this._lfoL.start(time); this._lfoR.start(time); return this; }; /** * Stop the tremolo. * @param {Time} [time=now] When the tremolo stops. * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.stop = function (time) { this._lfoL.stop(time); this._lfoR.stop(time); return this; }; /** * Sync the effect to the transport. * @param {Time} [delay=0] Delay time before starting the effect after the * Transport has started. * @returns {Tone.AutoFilter} this */ Tone.Tremolo.prototype.sync = function (delay) { this._lfoL.sync(delay); this._lfoR.sync(delay); return this; }; /** * Unsync the filter from the transport * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.unsync = function () { this._lfoL.unsync(); this._lfoR.unsync(); return this; }; /** * The Tremolo's oscillator type. * @memberOf Tone.Tremolo# * @type {string} * @name type */ Object.defineProperty(Tone.Tremolo.prototype, 'type', { get: function () { return this._lfoL.type; }, set: function (type) { this._lfoL.type = type; this._lfoR.type = type; } }); /** * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. * When set to 180, LFO's will be panned hard left and right respectively. * @memberOf Tone.Tremolo# * @type {Degrees} * @name spread */ Object.defineProperty(Tone.Tremolo.prototype, 'spread', { get: function () { return this._lfoR.phase - this._lfoL.phase; //180 }, set: function (spread) { this._lfoL.phase = 90 - spread / 2; this._lfoR.phase = spread / 2 + 90; } }); /** * clean up * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable([ 'frequency', 'depth' ]); this._lfoL.dispose(); this._lfoL = null; this._lfoR.dispose(); this._lfoR = null; this._amplitudeL.dispose(); this._amplitudeL = null; this._amplitudeR.dispose(); this._amplitudeR = null; this.frequency = null; this.depth = null; return this; }; return Tone.Tremolo; }); Module(function (Tone) { /** * @class A Vibrato effect composed of a Tone.Delay and a Tone.LFO. The LFO * modulates the delayTime of the delay, causing the pitch to rise * and fall. * @extends {Tone.Effect} * @param {Frequency} frequency The frequency of the vibrato. * @param {NormalRange} depth The amount the pitch is modulated. */ Tone.Vibrato = function () { var options = this.optionsObject(arguments, [ 'frequency', 'depth' ], Tone.Vibrato.defaults); Tone.Effect.call(this, options); /** * The delay node used for the vibrato effect * @type {Tone.Delay} * @private */ this._delayNode = new Tone.Delay(0, options.maxDelay); /** * The LFO used to control the vibrato * @type {Tone.LFO} * @private */ this._lfo = new Tone.LFO({ 'type': options.type, 'min': 0, 'max': options.maxDelay, 'frequency': options.frequency, 'phase': -90 //offse the phase so the resting position is in the center }).start().connect(this._delayNode.delayTime); /** * The frequency of the vibrato * @type {Frequency} * @signal */ this.frequency = this._lfo.frequency; /** * The depth of the vibrato. * @type {NormalRange} * @signal */ this.depth = this._lfo.amplitude; this.depth.value = options.depth; this._readOnly([ 'frequency', 'depth' ]); this.effectSend.chain(this._delayNode, this.effectReturn); }; Tone.extend(Tone.Vibrato, Tone.Effect); /** * The defaults * @type {Object} * @const */ Tone.Vibrato.defaults = { 'maxDelay': 0.005, 'frequency': 5, 'depth': 0.1, 'type': 'sine' }; /** * Type of oscillator attached to the Vibrato. * @memberOf Tone.Vibrato# * @type {string} * @name type */ Object.defineProperty(Tone.Vibrato.prototype, 'type', { get: function () { return this._lfo.type; }, set: function (type) { this._lfo.type = type; } }); /** * Clean up. * @returns {Tone.Vibrato} this */ Tone.Vibrato.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._delayNode.dispose(); this._delayNode = null; this._lfo.dispose(); this._lfo = null; this._writable([ 'frequency', 'depth' ]); this.frequency = null; this.depth = null; }; return Tone.Vibrato; }); Module(function (Tone) { /** * @class Tone.Event abstracts away Tone.Transport.schedule and provides a schedulable * callback for a single or repeatable events along the timeline. * * @extends {Tone} * @param {function} callback The callback to invoke at the time. * @param {*} value The value or values which should be passed to * the callback function on invocation. * @example * var chord = new Tone.Event(function(time, chord){ * //the chord as well as the exact time of the event * //are passed in as arguments to the callback function * }, ["D4", "E4", "F4"]); * //start the chord at the beginning of the transport timeline * chord.start(); * //loop it every measure for 8 measures * chord.loop = 8; * chord.loopEnd = "1m"; */ Tone.Event = function () { var options = this.optionsObject(arguments, [ 'callback', 'value' ], Tone.Event.defaults); /** * Loop value * @type {Boolean|Positive} * @private */ this._loop = options.loop; /** * The callback to invoke. * @type {Function} */ this.callback = options.callback; /** * The value which is passed to the * callback function. * @type {*} * @private */ this.value = options.value; /** * When the note is scheduled to start. * @type {Number} * @private */ this._loopStart = this.toTicks(options.loopStart); /** * When the note is scheduled to start. * @type {Number} * @private */ this._loopEnd = this.toTicks(options.loopEnd); /** * Tracks the scheduled events * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * The playback speed of the note. A speed of 1 * is no change. * @private * @type {Positive} */ this._playbackRate = 1; /** * A delay time from when the event is scheduled to start * @type {Ticks} * @private */ this._startOffset = 0; /** * The probability that the callback will be invoked * at the scheduled time. * @type {NormalRange} * @example * //the callback will be invoked 50% of the time * event.probability = 0.5; */ this.probability = options.probability; /** * If set to true, will apply small (+/-0.02 seconds) random variation * to the callback time. If the value is given as a time, it will randomize * by that amount. * @example * event.humanize = true; * @type {Boolean|Time} */ this.humanize = options.humanize; /** * If mute is true, the callback won't be * invoked. * @type {Boolean} */ this.mute = options.mute; //set the initial values this.playbackRate = options.playbackRate; }; Tone.extend(Tone.Event); /** * The default values * @type {Object} * @const */ Tone.Event.defaults = { 'callback': Tone.noOp, 'loop': false, 'loopEnd': '1m', 'loopStart': 0, 'playbackRate': 1, 'value': null, 'probability': 1, 'mute': false, 'humanize': false }; /** * Reschedule all of the events along the timeline * with the updated values. * @param {Time} after Only reschedules events after the given time. * @return {Tone.Event} this * @private */ Tone.Event.prototype._rescheduleEvents = function (after) { //if no argument is given, schedules all of the events after = this.defaultArg(after, -1); this._state.forEachFrom(after, function (event) { var duration; if (event.state === Tone.State.Started) { if (!this.isUndef(event.id)) { Tone.Transport.clear(event.id); } var startTick = event.time + Math.round(this.startOffset / this._playbackRate); if (this._loop) { duration = Infinity; if (this.isNumber(this._loop)) { duration = (this._loop - 1) * this._getLoopDuration(); } var nextEvent = this._state.getEventAfter(startTick); if (nextEvent !== null) { duration = Math.min(duration, nextEvent.time - startTick); } if (duration !== Infinity) { //schedule a stop since it's finite duration this._state.setStateAtTime(Tone.State.Stopped, startTick + duration + 1); duration += 'i'; } event.id = Tone.Transport.scheduleRepeat(this._tick.bind(this), this._getLoopDuration().toString() + 'i', startTick + 'i', duration); } else { event.id = Tone.Transport.schedule(this._tick.bind(this), startTick + 'i'); } } }.bind(this)); return this; }; /** * Returns the playback state of the note, either "started" or "stopped". * @type {String} * @readOnly * @memberOf Tone.Event# * @name state */ Object.defineProperty(Tone.Event.prototype, 'state', { get: function () { return this._state.getStateAtTime(Tone.Transport.ticks); } }); /** * The start from the scheduled start time * @type {Ticks} * @memberOf Tone.Event# * @name startOffset * @private */ Object.defineProperty(Tone.Event.prototype, 'startOffset', { get: function () { return this._startOffset; }, set: function (offset) { this._startOffset = offset; } }); /** * Start the note at the given time. * @param {Time} time When the note should start. * @return {Tone.Event} this */ Tone.Event.prototype.start = function (time) { time = this.toTicks(time); if (this._state.getStateAtTime(time) === Tone.State.Stopped) { this._state.addEvent({ 'state': Tone.State.Started, 'time': time, 'id': undefined }); this._rescheduleEvents(time); } return this; }; /** * Stop the Event at the given time. * @param {Time} time When the note should stop. * @return {Tone.Event} this */ Tone.Event.prototype.stop = function (time) { this.cancel(time); time = this.toTicks(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Stopped, time); var previousEvent = this._state.getEventBefore(time); var reschedulTime = time; if (previousEvent !== null) { reschedulTime = previousEvent.time; } this._rescheduleEvents(reschedulTime); } return this; }; /** * Cancel all scheduled events greater than or equal to the given time * @param {Time} [time=0] The time after which events will be cancel. * @return {Tone.Event} this */ Tone.Event.prototype.cancel = function (time) { time = this.defaultArg(time, -Infinity); time = this.toTicks(time); this._state.forEachFrom(time, function (event) { Tone.Transport.clear(event.id); }); this._state.cancel(time); return this; }; /** * The callback function invoker. Also * checks if the Event is done playing * @param {Number} time The time of the event in seconds * @private */ Tone.Event.prototype._tick = function (time) { if (!this.mute && this._state.getStateAtTime(Tone.Transport.ticks) === Tone.State.Started) { if (this.probability < 1 && Math.random() > this.probability) { return; } if (this.humanize) { var variation = 0.02; if (!this.isBoolean(this.humanize)) { variation = this.toSeconds(this.humanize); } time += (Math.random() * 2 - 1) * variation; } this.callback(time, this.value); } }; /** * Get the duration of the loop. * @return {Ticks} * @private */ Tone.Event.prototype._getLoopDuration = function () { return Math.round((this._loopEnd - this._loopStart) / this._playbackRate); }; /** * If the note should loop or not * between Tone.Event.loopStart and * Tone.Event.loopEnd. An integer * value corresponds to the number of * loops the Event does after it starts. * @memberOf Tone.Event# * @type {Boolean|Positive} * @name loop */ Object.defineProperty(Tone.Event.prototype, 'loop', { get: function () { return this._loop; }, set: function (loop) { this._loop = loop; this._rescheduleEvents(); } }); /** * The playback rate of the note. Defaults to 1. * @memberOf Tone.Event# * @type {Positive} * @name playbackRate * @example * note.loop = true; * //repeat the note twice as fast * note.playbackRate = 2; */ Object.defineProperty(Tone.Event.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; this._rescheduleEvents(); } }); /** * The loopEnd point is the time the event will loop. * Note: only loops if Tone.Event.loop is true. * @memberOf Tone.Event# * @type {Boolean|Positive} * @name loopEnd */ Object.defineProperty(Tone.Event.prototype, 'loopEnd', { get: function () { return this.toNotation(this._loopEnd + 'i'); }, set: function (loopEnd) { this._loopEnd = this.toTicks(loopEnd); if (this._loop) { this._rescheduleEvents(); } } }); /** * The time when the loop should start. * @memberOf Tone.Event# * @type {Boolean|Positive} * @name loopStart */ Object.defineProperty(Tone.Event.prototype, 'loopStart', { get: function () { return this.toNotation(this._loopStart + 'i'); }, set: function (loopStart) { this._loopStart = this.toTicks(loopStart); if (this._loop) { this._rescheduleEvents(); } } }); /** * The current progress of the loop interval. * Returns 0 if the event is not started yet or * it is not set to loop. * @memberOf Tone.Event# * @type {NormalRange} * @name progress * @readOnly */ Object.defineProperty(Tone.Event.prototype, 'progress', { get: function () { if (this._loop) { var ticks = Tone.Transport.ticks; var lastEvent = this._state.getEvent(ticks); if (lastEvent !== null && lastEvent.state === Tone.State.Started) { var loopDuration = this._getLoopDuration(); var progress = (ticks - lastEvent.time) % loopDuration; return progress / loopDuration; } else { return 0; } } else { return 0; } } }); /** * Clean up * @return {Tone.Event} this */ Tone.Event.prototype.dispose = function () { this.cancel(); this._state.dispose(); this._state = null; this.callback = null; this.value = null; }; return Tone.Event; }); Module(function (Tone) { /** * @class Tone.Loop creates a looped callback at the * specified interval. The callback can be * started, stopped and scheduled along * the Transport's timeline. * @example * var loop = new Tone.Loop(function(time){ * //triggered every eighth note. * console.log(time); * }, "8n").start(0); * Tone.Transport.start(); * @extends {Tone} * @param {Function} callback The callback to invoke with the * event. * @param {Array} events The events to arpeggiate over. */ Tone.Loop = function () { var options = this.optionsObject(arguments, [ 'callback', 'interval' ], Tone.Loop.defaults); /** * The event which produces the callbacks */ this._event = new Tone.Event({ 'callback': this._tick.bind(this), 'loop': true, 'loopEnd': options.interval, 'playbackRate': options.playbackRate, 'probability': options.probability }); /** * The callback to invoke with the next event in the pattern * @type {Function} */ this.callback = options.callback; //set the iterations this.iterations = options.iterations; }; Tone.extend(Tone.Loop); /** * The defaults * @const * @type {Object} */ Tone.Loop.defaults = { 'interval': '4n', 'callback': Tone.noOp, 'playbackRate': 1, 'iterations': Infinity, 'probability': true, 'mute': false }; /** * Start the loop at the specified time along the Transport's * timeline. * @param {Time=} time When to start the Loop. * @return {Tone.Loop} this */ Tone.Loop.prototype.start = function (time) { this._event.start(time); return this; }; /** * Stop the loop at the given time. * @param {Time=} time When to stop the Arpeggio * @return {Tone.Loop} this */ Tone.Loop.prototype.stop = function (time) { this._event.stop(time); return this; }; /** * Cancel all scheduled events greater than or equal to the given time * @param {Time} [time=0] The time after which events will be cancel. * @return {Tone.Loop} this */ Tone.Loop.prototype.cancel = function (time) { this._event.cancel(time); return this; }; /** * Internal function called when the notes should be called * @param {Number} time The time the event occurs * @private */ Tone.Loop.prototype._tick = function (time) { this.callback(time); }; /** * The state of the Loop, either started or stopped. * @memberOf Tone.Loop# * @type {String} * @name state * @readOnly */ Object.defineProperty(Tone.Loop.prototype, 'state', { get: function () { return this._event.state; } }); /** * The progress of the loop as a value between 0-1. 0, when * the loop is stopped or done iterating. * @memberOf Tone.Loop# * @type {NormalRange} * @name progress * @readOnly */ Object.defineProperty(Tone.Loop.prototype, 'progress', { get: function () { return this._event.progress; } }); /** * The time between successive callbacks. * @example * loop.interval = "8n"; //loop every 8n * @memberOf Tone.Loop# * @type {Time} * @name interval */ Object.defineProperty(Tone.Loop.prototype, 'interval', { get: function () { return this._event.loopEnd; }, set: function (interval) { this._event.loopEnd = interval; } }); /** * The playback rate of the loop. The normal playback rate is 1 (no change). * A `playbackRate` of 2 would be twice as fast. * @memberOf Tone.Loop# * @type {Time} * @name playbackRate */ Object.defineProperty(Tone.Loop.prototype, 'playbackRate', { get: function () { return this._event.playbackRate; }, set: function (rate) { this._event.playbackRate = rate; } }); /** * Random variation +/-0.01s to the scheduled time. * Or give it a time value which it will randomize by. * @type {Boolean|Time} * @memberOf Tone.Loop# * @name humanize */ Object.defineProperty(Tone.Loop.prototype, 'humanize', { get: function () { return this._event.humanize; }, set: function (variation) { this._event.humanize = variation; } }); /** * The probably of the callback being invoked. * @memberOf Tone.Loop# * @type {NormalRange} * @name probability */ Object.defineProperty(Tone.Loop.prototype, 'probability', { get: function () { return this._event.probability; }, set: function (prob) { this._event.probability = prob; } }); /** * Muting the Loop means that no callbacks are invoked. * @memberOf Tone.Loop# * @type {Boolean} * @name mute */ Object.defineProperty(Tone.Loop.prototype, 'mute', { get: function () { return this._event.mute; }, set: function (mute) { this._event.mute = mute; } }); /** * The number of iterations of the loop. The default * value is Infinity (loop forever). * @memberOf Tone.Loop# * @type {Positive} * @name iterations */ Object.defineProperty(Tone.Loop.prototype, 'iterations', { get: function () { if (this._event.loop === true) { return Infinity; } else { return this._event.loop; } return this._pattern.index; }, set: function (iters) { if (iters === Infinity) { this._event.loop = true; } else { this._event.loop = iters; } } }); /** * Clean up * @return {Tone.Loop} this */ Tone.Loop.prototype.dispose = function () { this._event.dispose(); this._event = null; this.callback = null; }; return Tone.Loop; }); Module(function (Tone) { /** * @class Tone.Part is a collection Tone.Events which can be * started/stoped and looped as a single unit. * * @extends {Tone.Event} * @param {Function} callback The callback to invoke on each event * @param {Array} events the array of events * @example * var part = new Tone.Part(function(time, note){ * //the notes given as the second element in the array * //will be passed in as the second argument * synth.triggerAttackRelease(note, "8n", time); * }, [[0, "C2"], ["0:2", "C3"], ["0:3:2", "G2"]]); * @example * //use an array of objects as long as the object has a "time" attribute * var part = new Tone.Part(function(time, value){ * //the value is an object which contains both the note and the velocity * synth.triggerAttackRelease(value.note, "8n", time, value.velocity); * }, [{"time" : 0, "note" : "C3", "velocity": 0.9}, * {"time" : "0:2", "note" : "C4", "velocity": 0.5} * ]).start(0); */ Tone.Part = function () { var options = this.optionsObject(arguments, [ 'callback', 'events' ], Tone.Part.defaults); /** * If the part is looping or not * @type {Boolean|Positive} * @private */ this._loop = options.loop; /** * When the note is scheduled to start. * @type {Ticks} * @private */ this._loopStart = this.toTicks(options.loopStart); /** * When the note is scheduled to start. * @type {Ticks} * @private */ this._loopEnd = this.toTicks(options.loopEnd); /** * The playback rate of the part * @type {Positive} * @private */ this._playbackRate = options.playbackRate; /** * private holder of probability value * @type {NormalRange} * @private */ this._probability = options.probability; /** * the amount of variation from the * given time. * @type {Boolean|Time} * @private */ this._humanize = options.humanize; /** * The start offset * @type {Ticks} * @private */ this._startOffset = 0; /** * Keeps track of the current state * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * An array of Objects. * @type {Array} * @private */ this._events = []; /** * The callback to invoke at all the scheduled events. * @type {Function} */ this.callback = options.callback; /** * If mute is true, the callback won't be * invoked. * @type {Boolean} */ this.mute = options.mute; //add the events var events = this.defaultArg(options.events, []); if (!this.isUndef(options.events)) { for (var i = 0; i < events.length; i++) { if (Array.isArray(events[i])) { this.add(events[i][0], events[i][1]); } else { this.add(events[i]); } } } }; Tone.extend(Tone.Part, Tone.Event); /** * The default values * @type {Object} * @const */ Tone.Part.defaults = { 'callback': Tone.noOp, 'loop': false, 'loopEnd': '1m', 'loopStart': 0, 'playbackRate': 1, 'probability': 1, 'humanize': false, 'mute': false }; /** * Start the part at the given time. * @param {Time} time When to start the part. * @param {Time=} offset The offset from the start of the part * to begin playing at. * @return {Tone.Part} this */ Tone.Part.prototype.start = function (time, offset) { var ticks = this.toTicks(time); if (this._state.getStateAtTime(ticks) !== Tone.State.Started) { offset = this.defaultArg(offset, 0); offset = this.toTicks(offset); this._state.addEvent({ 'state': Tone.State.Started, 'time': ticks, 'offset': offset }); this._forEach(function (event) { this._startNote(event, ticks, offset); }); } return this; }; /** * Start the event in the given event at the correct time given * the ticks and offset and looping. * @param {Tone.Event} event * @param {Ticks} ticks * @param {Ticks} offset * @private */ Tone.Part.prototype._startNote = function (event, ticks, offset) { ticks -= offset; if (this._loop) { if (event.startOffset >= this._loopStart && event.startOffset < this._loopEnd) { if (event.startOffset < offset) { //start it on the next loop ticks += this._getLoopDuration(); } event.start(ticks + 'i'); } } else { if (event.startOffset >= offset) { event.start(ticks + 'i'); } } }; /** * The start from the scheduled start time * @type {Ticks} * @memberOf Tone.Part# * @name startOffset * @private */ Object.defineProperty(Tone.Part.prototype, 'startOffset', { get: function () { return this._startOffset; }, set: function (offset) { this._startOffset = offset; this._forEach(function (event) { event.startOffset += this._startOffset; }); } }); /** * Stop the part at the given time. * @param {Time} time When to stop the part. * @return {Tone.Part} this */ Tone.Part.prototype.stop = function (time) { var ticks = this.toTicks(time); if (this._state.getStateAtTime(ticks) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Stopped, ticks); this._forEach(function (event) { event.stop(time); }); } return this; }; /** * Get/Set an Event's value at the given time. * If a value is passed in and no event exists at * the given time, one will be created with that value. * If two events are at the same time, the first one will * be returned. * @example * part.at("1m"); //returns the part at the first measure * * part.at("2m", "C2"); //set the value at "2m" to C2. * //if an event didn't exist at that time, it will be created. * @param {Time} time the time of the event to get or set * @param {*=} value If a value is passed in, the value of the * event at the given time will be set to it. * @return {Tone.Event} the event at the time */ Tone.Part.prototype.at = function (time, value) { time = this.toTicks(time); var tickTime = this.ticksToSeconds(1); for (var i = 0; i < this._events.length; i++) { var event = this._events[i]; if (Math.abs(time - event.startOffset) < tickTime) { if (!this.isUndef(value)) { event.value = value; } return event; } } //if there was no event at that time, create one if (!this.isUndef(value)) { this.add(time + 'i', value); //return the new event return this._events[this._events.length - 1]; } else { return null; } }; /** * Add a an event to the part. * @param {Time} time The time the note should start. * If an object is passed in, it should * have a 'time' attribute and the rest * of the object will be used as the 'value'. * @param {Tone.Event|*} value * @returns {Tone.Part} this * @example * part.add("1m", "C#+11"); */ Tone.Part.prototype.add = function (time, value) { //extract the parameters if (this.isObject(time) && time.hasOwnProperty('time')) { value = time; time = value.time; delete value.time; } time = this.toTicks(time); var event; if (value instanceof Tone.Event) { event = value; event.callback = this._tick.bind(this); } else { event = new Tone.Event({ 'callback': this._tick.bind(this), 'value': value }); } //the start offset event.startOffset = time; //initialize the values event.set({ 'loopEnd': this.loopEnd, 'loopStart': this.loopStart, 'loop': this.loop, 'humanize': this.humanize, 'playbackRate': this.playbackRate, 'probability': this.probability }); this._events.push(event); //start the note if it should be played right now this._restartEvent(event); return this; }; /** * Restart the given event * @param {Tone.Event} event * @private */ Tone.Part.prototype._restartEvent = function (event) { var stateEvent = this._state.getEvent(this.now()); if (stateEvent && stateEvent.state === Tone.State.Started) { this._startNote(event, stateEvent.time, stateEvent.offset); } }; /** * Remove an event from the part. Will recursively iterate * into nested parts to find the event. * @param {Time} time The time of the event * @param {*} value Optionally select only a specific event value */ Tone.Part.prototype.remove = function (time, value) { //extract the parameters if (this.isObject(time) && time.hasOwnProperty('time')) { value = time; time = value.time; } time = this.toTicks(time); for (var i = this._events.length - 1; i >= 0; i--) { var event = this._events[i]; if (event instanceof Tone.Part) { event.remove(time, value); } else { if (event.startOffset === time) { if (this.isUndef(value) || !this.isUndef(value) && event.value === value) { this._events.splice(i, 1); event.dispose(); } } } } return this; }; /** * Remove all of the notes from the group. * @return {Tone.Part} this */ Tone.Part.prototype.removeAll = function () { this._forEach(function (event) { event.dispose(); }); this._events = []; return this; }; /** * Cancel scheduled state change events: i.e. "start" and "stop". * @param {Time} after The time after which to cancel the scheduled events. * @return {Tone.Part} this */ Tone.Part.prototype.cancel = function (after) { this._forEach(function (event) { event.cancel(after); }); this._state.cancel(after); return this; }; /** * Iterate over all of the events * @param {Function} callback * @param {Object} ctx The context * @private */ Tone.Part.prototype._forEach = function (callback, ctx) { ctx = this.defaultArg(ctx, this); for (var i = this._events.length - 1; i >= 0; i--) { var e = this._events[i]; if (e instanceof Tone.Part) { e._forEach(callback, ctx); } else { callback.call(ctx, e); } } return this; }; /** * Set the attribute of all of the events * @param {String} attr the attribute to set * @param {*} value The value to set it to * @private */ Tone.Part.prototype._setAll = function (attr, value) { this._forEach(function (event) { event[attr] = value; }); }; /** * Internal tick method * @param {Number} time The time of the event in seconds * @private */ Tone.Part.prototype._tick = function (time, value) { if (!this.mute) { this.callback(time, value); } }; /** * Determine if the event should be currently looping * given the loop boundries of this Part. * @param {Tone.Event} event The event to test * @private */ Tone.Part.prototype._testLoopBoundries = function (event) { if (event.startOffset < this._loopStart || event.startOffset >= this._loopEnd) { event.cancel(); } else { //reschedule it if it's stopped if (event.state === Tone.State.Stopped) { this._restartEvent(event); } } }; /** * The probability of the notes being triggered. * @memberOf Tone.Part# * @type {NormalRange} * @name probability */ Object.defineProperty(Tone.Part.prototype, 'probability', { get: function () { return this._probability; }, set: function (prob) { this._probability = prob; this._setAll('probability', prob); } }); /** * If set to true, will apply small random variation * to the callback time. If the value is given as a time, it will randomize * by that amount. * @example * event.humanize = true; * @type {Boolean|Time} * @name humanize */ Object.defineProperty(Tone.Part.prototype, 'humanize', { get: function () { return this._humanize; }, set: function (variation) { this._humanize = variation; this._setAll('humanize', variation); } }); /** * If the part should loop or not * between Tone.Part.loopStart and * Tone.Part.loopEnd. An integer * value corresponds to the number of * loops the Part does after it starts. * @memberOf Tone.Part# * @type {Boolean|Positive} * @name loop * @example * //loop the part 8 times * part.loop = 8; */ Object.defineProperty(Tone.Part.prototype, 'loop', { get: function () { return this._loop; }, set: function (loop) { this._loop = loop; this._forEach(function (event) { event._loopStart = this._loopStart; event._loopEnd = this._loopEnd; event.loop = loop; this._testLoopBoundries(event); }); } }); /** * The loopEnd point determines when it will * loop if Tone.Part.loop is true. * @memberOf Tone.Part# * @type {Boolean|Positive} * @name loopEnd */ Object.defineProperty(Tone.Part.prototype, 'loopEnd', { get: function () { return this.toNotation(this._loopEnd + 'i'); }, set: function (loopEnd) { this._loopEnd = this.toTicks(loopEnd); if (this._loop) { this._forEach(function (event) { event.loopEnd = this.loopEnd; this._testLoopBoundries(event); }); } } }); /** * The loopStart point determines when it will * loop if Tone.Part.loop is true. * @memberOf Tone.Part# * @type {Boolean|Positive} * @name loopStart */ Object.defineProperty(Tone.Part.prototype, 'loopStart', { get: function () { return this.toNotation(this._loopStart + 'i'); }, set: function (loopStart) { this._loopStart = this.toTicks(loopStart); if (this._loop) { this._forEach(function (event) { event.loopStart = this.loopStart; this._testLoopBoundries(event); }); } } }); /** * The playback rate of the part * @memberOf Tone.Part# * @type {Positive} * @name playbackRate */ Object.defineProperty(Tone.Part.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; this._setAll('playbackRate', rate); } }); /** * The number of scheduled notes in the part. * @memberOf Tone.Part# * @type {Positive} * @name length * @readOnly */ Object.defineProperty(Tone.Part.prototype, 'length', { get: function () { return this._events.length; } }); /** * Clean up * @return {Tone.Part} this */ Tone.Part.prototype.dispose = function () { this.removeAll(); this._state.dispose(); this._state = null; this.callback = null; this._events = null; return this; }; return Tone.Part; }); Module(function (Tone) { /** * @class Tone.Pattern arpeggiates between the given notes * in a number of patterns. See Tone.CtrlPattern for * a full list of patterns. * @example * var pattern = new Tone.Pattern(function(time, note){ * //the order of the notes passed in depends on the pattern * }, ["C2", "D4", "E5", "A6"], "upDown"); * @extends {Tone.Loop} * @param {Function} callback The callback to invoke with the * event. * @param {Array} events The events to arpeggiate over. */ Tone.Pattern = function () { var options = this.optionsObject(arguments, [ 'callback', 'events', 'pattern' ], Tone.Pattern.defaults); Tone.Loop.call(this, options); /** * The pattern manager * @type {Tone.CtrlPattern} * @private */ this._pattern = new Tone.CtrlPattern({ 'values': options.events, 'type': options.pattern, 'index': options.index }); }; Tone.extend(Tone.Pattern, Tone.Loop); /** * The defaults * @const * @type {Object} */ Tone.Pattern.defaults = { 'pattern': Tone.CtrlPattern.Type.Up, 'events': [] }; /** * Internal function called when the notes should be called * @param {Number} time The time the event occurs * @private */ Tone.Pattern.prototype._tick = function (time) { this.callback(time, this._pattern.value); this._pattern.next(); }; /** * The current index in the events array. * @memberOf Tone.Pattern# * @type {Positive} * @name index */ Object.defineProperty(Tone.Pattern.prototype, 'index', { get: function () { return this._pattern.index; }, set: function (i) { this._pattern.index = i; } }); /** * The array of events. * @memberOf Tone.Pattern# * @type {Array} * @name events */ Object.defineProperty(Tone.Pattern.prototype, 'events', { get: function () { return this._pattern.values; }, set: function (vals) { this._pattern.values = vals; } }); /** * The current value of the pattern. * @memberOf Tone.Pattern# * @type {*} * @name value * @readOnly */ Object.defineProperty(Tone.Pattern.prototype, 'value', { get: function () { return this._pattern.value; } }); /** * The pattern type. See Tone.CtrlPattern for the full list of patterns. * @memberOf Tone.Pattern# * @type {String} * @name pattern */ Object.defineProperty(Tone.Pattern.prototype, 'pattern', { get: function () { return this._pattern.type; }, set: function (pattern) { this._pattern.type = pattern; } }); /** * Clean up * @return {Tone.Pattern} this */ Tone.Pattern.prototype.dispose = function () { Tone.Loop.prototype.dispose.call(this); this._pattern.dispose(); this._pattern = null; }; return Tone.Pattern; }); Module(function (Tone) { /** * @class A sequence is an alternate notation of a part. Instead * of passing in an array of [time, event] pairs, pass * in an array of events which will be spaced at the * given subdivision. Sub-arrays will subdivide that beat * by the number of items are in the array. * Sequence notation inspiration from [Tidal](http://yaxu.org/tidal/) * @param {Function} callback The callback to invoke with every note * @param {Array} events The sequence * @param {Time} subdivision The subdivision between which events are placed. * @extends {Tone.Part} * @example * var seq = new Tone.Sequence(function(time, note){ * console.log(note); * //straight quater notes * }, ["C4", "E4", "G4", "A4"], "4n"); * @example * var seq = new Tone.Sequence(function(time, note){ * console.log(note); * //subdivisions are given as subarrays * }, ["C4", ["E4", "D4", "E4"], "G4", ["A4", "G4"]]); */ Tone.Sequence = function () { var options = this.optionsObject(arguments, [ 'callback', 'events', 'subdivision' ], Tone.Sequence.defaults); //remove the events var events = options.events; delete options.events; Tone.Part.call(this, options); /** * The subdivison of each note * @type {Ticks} * @private */ this._subdivision = this.toTicks(options.subdivision); //if no time was passed in, the loop end is the end of the cycle if (this.isUndef(options.loopEnd) && !this.isUndef(events)) { this._loopEnd = events.length * this._subdivision; } //defaults to looping this._loop = true; //add all of the events if (!this.isUndef(events)) { for (var i = 0; i < events.length; i++) { this.add(i, events[i]); } } }; Tone.extend(Tone.Sequence, Tone.Part); /** * The default values. * @type {Object} */ Tone.Sequence.defaults = { 'subdivision': '4n' }; /** * The subdivision of the sequence. This can only be * set in the constructor. The subdivision is the * interval between successive steps. * @type {Time} * @memberOf Tone.Sequence# * @name subdivision * @readOnly */ Object.defineProperty(Tone.Sequence.prototype, 'subdivision', { get: function () { return this.toNotation(this._subdivision + 'i'); } }); /** * Get/Set an index of the sequence. If the index contains a subarray, * a Tone.Sequence representing that sub-array will be returned. * @example * var sequence = new Tone.Sequence(playNote, ["E4", "C4", "F#4", ["A4", "Bb3"]]) * sequence.at(0)// => returns "E4" * //set a value * sequence.at(0, "G3"); * //get a nested sequence * sequence.at(3).at(1)// => returns "Bb3" * @param {Positive} index The index to get or set * @param {*} value Optionally pass in the value to set at the given index. */ Tone.Sequence.prototype.at = function (index, value) { //if the value is an array, if (this.isArray(value)) { //remove the current event at that index this.remove(index); } //call the parent's method return Tone.Part.prototype.at.call(this, this._indexTime(index), value); }; /** * Add an event at an index, if there's already something * at that index, overwrite it. If `value` is an array, * it will be parsed as a subsequence. * @param {Number} index The index to add the event to * @param {*} value The value to add at that index * @returns {Tone.Sequence} this */ Tone.Sequence.prototype.add = function (index, value) { if (value === null) { return this; } if (this.isArray(value)) { //make a subsequence and add that to the sequence var subSubdivision = Math.round(this._subdivision / value.length) + 'i'; value = new Tone.Sequence(this._tick.bind(this), value, subSubdivision); } Tone.Part.prototype.add.call(this, this._indexTime(index), value); return this; }; /** * Remove a value from the sequence by index * @param {Number} index The index of the event to remove * @returns {Tone.Sequence} this */ Tone.Sequence.prototype.remove = function (index, value) { Tone.Part.prototype.remove.call(this, this._indexTime(index), value); return this; }; /** * Get the time of the index given the Sequence's subdivision * @param {Number} index * @return {Time} The time of that index * @private */ Tone.Sequence.prototype._indexTime = function (index) { if (this.isTicks(index)) { return index; } else { return index * this._subdivision + this.startOffset + 'i'; } }; /** * Clean up. * @return {Tone.Sequence} this */ Tone.Sequence.prototype.dispose = function () { Tone.Part.prototype.dispose.call(this); return this; }; return Tone.Sequence; }); Module(function (Tone) { /** * @class Tone.PulseOscillator is a pulse oscillator with control over pulse width, * also known as the duty cycle. At 50% duty cycle (width = 0.5) the wave is * a square and only odd-numbered harmonics are present. At all other widths * even-numbered harmonics are present. Read more * [here](https://wigglewave.wordpress.com/2014/08/16/pulse-waveforms-and-harmonics/). * * @constructor * @extends {Tone.Oscillator} * @param {Frequency} [frequency] The frequency of the oscillator * @param {NormalRange} [width] The width of the pulse * @example * var pulse = new Tone.PulseOscillator("E5", 0.4).toMaster().start(); */ Tone.PulseOscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'width' ], Tone.Oscillator.defaults); Tone.Source.call(this, options); /** * The width of the pulse. * @type {NormalRange} * @signal */ this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); /** * gate the width amount * @type {GainNode} * @private */ this._widthGate = this.context.createGain(); /** * the sawtooth oscillator * @type {Tone.Oscillator} * @private */ this._sawtooth = new Tone.Oscillator({ frequency: options.frequency, detune: options.detune, type: 'sawtooth', phase: options.phase }); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this._sawtooth.frequency; /** * The detune in cents. * @type {Cents} * @signal */ this.detune = this._sawtooth.detune; /** * Threshold the signal to turn it into a square * @type {Tone.WaveShaper} * @private */ this._thresh = new Tone.WaveShaper(function (val) { if (val < 0) { return -1; } else { return 1; } }); //connections this._sawtooth.chain(this._thresh, this.output); this.width.chain(this._widthGate, this._thresh); this._readOnly([ 'width', 'frequency', 'detune' ]); }; Tone.extend(Tone.PulseOscillator, Tone.Oscillator); /** * The default parameters. * @static * @const * @type {Object} */ Tone.PulseOscillator.defaults = { 'frequency': 440, 'detune': 0, 'phase': 0, 'width': 0.2 }; /** * start the oscillator * @param {Time} time * @private */ Tone.PulseOscillator.prototype._start = function (time) { time = this.toSeconds(time); this._sawtooth.start(time); this._widthGate.gain.setValueAtTime(1, time); }; /** * stop the oscillator * @param {Time} time * @private */ Tone.PulseOscillator.prototype._stop = function (time) { time = this.toSeconds(time); this._sawtooth.stop(time); //the width is still connected to the output. //that needs to be stopped also this._widthGate.gain.setValueAtTime(0, time); }; /** * The phase of the oscillator in degrees. * @memberOf Tone.PulseOscillator# * @type {Degrees} * @name phase */ Object.defineProperty(Tone.PulseOscillator.prototype, 'phase', { get: function () { return this._sawtooth.phase; }, set: function (phase) { this._sawtooth.phase = phase; } }); /** * The type of the oscillator. Always returns "pulse". * @readOnly * @memberOf Tone.PulseOscillator# * @type {string} * @name type */ Object.defineProperty(Tone.PulseOscillator.prototype, 'type', { get: function () { return 'pulse'; } }); /** * The partials of the waveform. Cannot set partials for this waveform type * @memberOf Tone.PulseOscillator# * @type {Array} * @name partials * @private */ Object.defineProperty(Tone.PulseOscillator.prototype, 'partials', { get: function () { return []; } }); /** * Clean up method. * @return {Tone.PulseOscillator} this */ Tone.PulseOscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this._sawtooth.dispose(); this._sawtooth = null; this._writable([ 'width', 'frequency', 'detune' ]); this.width.dispose(); this.width = null; this._widthGate.disconnect(); this._widthGate = null; this._widthGate = null; this._thresh.disconnect(); this._thresh = null; this.frequency = null; this.detune = null; return this; }; return Tone.PulseOscillator; }); Module(function (Tone) { /** * @class Tone.PWMOscillator modulates the width of a Tone.PulseOscillator * at the modulationFrequency. This has the effect of continuously * changing the timbre of the oscillator by altering the harmonics * generated. * * @extends {Tone.Oscillator} * @constructor * @param {Frequency} frequency The starting frequency of the oscillator. * @param {Frequency} modulationFrequency The modulation frequency of the width of the pulse. * @example * var pwm = new Tone.PWMOscillator("Ab3", 0.3).toMaster().start(); */ Tone.PWMOscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'modulationFrequency' ], Tone.PWMOscillator.defaults); Tone.Source.call(this, options); /** * the pulse oscillator * @type {Tone.PulseOscillator} * @private */ this._pulse = new Tone.PulseOscillator(options.modulationFrequency); //change the pulse oscillator type this._pulse._sawtooth.type = 'sine'; /** * the modulator * @type {Tone.Oscillator} * @private */ this._modulator = new Tone.Oscillator({ 'frequency': options.frequency, 'detune': options.detune, 'phase': options.phase }); /** * Scale the oscillator so it doesn't go silent * at the extreme values. * @type {Tone.Multiply} * @private */ this._scale = new Tone.Multiply(1.01); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this._modulator.frequency; /** * The detune of the oscillator. * @type {Cents} * @signal */ this.detune = this._modulator.detune; /** * The modulation rate of the oscillator. * @type {Frequency} * @signal */ this.modulationFrequency = this._pulse.frequency; //connections this._modulator.chain(this._scale, this._pulse.width); this._pulse.connect(this.output); this._readOnly([ 'modulationFrequency', 'frequency', 'detune' ]); }; Tone.extend(Tone.PWMOscillator, Tone.Oscillator); /** * default values * @static * @type {Object} * @const */ Tone.PWMOscillator.defaults = { 'frequency': 440, 'detune': 0, 'phase': 0, 'modulationFrequency': 0.4 }; /** * start the oscillator * @param {Time} [time=now] * @private */ Tone.PWMOscillator.prototype._start = function (time) { time = this.toSeconds(time); this._modulator.start(time); this._pulse.start(time); }; /** * stop the oscillator * @param {Time} time (optional) timing parameter * @private */ Tone.PWMOscillator.prototype._stop = function (time) { time = this.toSeconds(time); this._modulator.stop(time); this._pulse.stop(time); }; /** * The type of the oscillator. Always returns "pwm". * @readOnly * @memberOf Tone.PWMOscillator# * @type {string} * @name type */ Object.defineProperty(Tone.PWMOscillator.prototype, 'type', { get: function () { return 'pwm'; } }); /** * The partials of the waveform. Cannot set partials for this waveform type * @memberOf Tone.PWMOscillator# * @type {Array} * @name partials * @private */ Object.defineProperty(Tone.PWMOscillator.prototype, 'partials', { get: function () { return []; } }); /** * The phase of the oscillator in degrees. * @memberOf Tone.PWMOscillator# * @type {number} * @name phase */ Object.defineProperty(Tone.PWMOscillator.prototype, 'phase', { get: function () { return this._modulator.phase; }, set: function (phase) { this._modulator.phase = phase; } }); /** * Clean up. * @return {Tone.PWMOscillator} this */ Tone.PWMOscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this._pulse.dispose(); this._pulse = null; this._scale.dispose(); this._scale = null; this._modulator.dispose(); this._modulator = null; this._writable([ 'modulationFrequency', 'frequency', 'detune' ]); this.frequency = null; this.detune = null; this.modulationFrequency = null; return this; }; return Tone.PWMOscillator; }); Module(function (Tone) { /** * @class Tone.OmniOscillator aggregates Tone.Oscillator, Tone.PulseOscillator, * and Tone.PWMOscillator into one class, allowing it to have the * types: sine, square, triangle, sawtooth, pulse or pwm. Additionally, * OmniOscillator is capable of setting the first x number of partials * of the oscillator. For example: "sine4" would set be the first 4 * partials of the sine wave and "triangle8" would set the first * 8 partials of the triangle wave. * * @extends {Tone.Oscillator} * @constructor * @param {Frequency} frequency The initial frequency of the oscillator. * @param {string} type The type of the oscillator. * @example * var omniOsc = new Tone.OmniOscillator("C#4", "pwm"); */ Tone.OmniOscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'type' ], Tone.OmniOscillator.defaults); Tone.Source.call(this, options); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The detune control * @type {Cents} * @signal */ this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); /** * the type of the oscillator source * @type {string} * @private */ this._sourceType = undefined; /** * the oscillator * @type {Tone.Oscillator|Tone.PWMOscillator|Tone.PulseOscillator} * @private */ this._oscillator = null; //set the oscillator this.type = options.type; this.phase = options.phase; this._readOnly([ 'frequency', 'detune' ]); if (this.isArray(options.partials)) { this.partials = options.partials; } }; Tone.extend(Tone.OmniOscillator, Tone.Oscillator); /** * default values * @static * @type {Object} * @const */ Tone.OmniOscillator.defaults = { 'frequency': 440, 'detune': 0, 'type': 'sine', 'phase': 0, 'width': 0.4, //only applies if the oscillator is set to "pulse", 'modulationFrequency': 0.4 }; /** * @enum {string} * @private */ var OmniOscType = { PulseOscillator: 'PulseOscillator', PWMOscillator: 'PWMOscillator', Oscillator: 'Oscillator' }; /** * start the oscillator * @param {Time} [time=now] the time to start the oscillator * @private */ Tone.OmniOscillator.prototype._start = function (time) { this._oscillator.start(time); }; /** * start the oscillator * @param {Time} [time=now] the time to start the oscillator * @private */ Tone.OmniOscillator.prototype._stop = function (time) { this._oscillator.stop(time); }; /** * The type of the oscillator. sine, square, triangle, sawtooth, pwm, or pulse. * @memberOf Tone.OmniOscillator# * @type {string} * @name type */ Object.defineProperty(Tone.OmniOscillator.prototype, 'type', { get: function () { return this._oscillator.type; }, set: function (type) { if (type.indexOf('sine') === 0 || type.indexOf('square') === 0 || type.indexOf('triangle') === 0 || type.indexOf('sawtooth') === 0 || type === Tone.Oscillator.Type.Custom) { if (this._sourceType !== OmniOscType.Oscillator) { this._sourceType = OmniOscType.Oscillator; this._createNewOscillator(Tone.Oscillator); } this._oscillator.type = type; } else if (type === 'pwm') { if (this._sourceType !== OmniOscType.PWMOscillator) { this._sourceType = OmniOscType.PWMOscillator; this._createNewOscillator(Tone.PWMOscillator); } } else if (type === 'pulse') { if (this._sourceType !== OmniOscType.PulseOscillator) { this._sourceType = OmniOscType.PulseOscillator; this._createNewOscillator(Tone.PulseOscillator); } } else { throw new Error('Tone.OmniOscillator does not support type ' + type); } } }); /** * The partials of the waveform. A partial represents * the amplitude at a harmonic. The first harmonic is the * fundamental frequency, the second is the octave and so on * following the harmonic series. * Setting this value will automatically set the type to "custom". * The value is an empty array when the type is not "custom". * @memberOf Tone.OmniOscillator# * @type {Array} * @name partials * @example * osc.partials = [1, 0.2, 0.01]; */ Object.defineProperty(Tone.OmniOscillator.prototype, 'partials', { get: function () { return this._oscillator.partials; }, set: function (partials) { if (this._sourceType !== OmniOscType.Oscillator) { this.type = Tone.Oscillator.Type.Custom; } this._oscillator.partials = partials; } }); /** * connect the oscillator to the frequency and detune signals * @private */ Tone.OmniOscillator.prototype._createNewOscillator = function (OscillatorConstructor) { //short delay to avoid clicks on the change var now = this.now() + this.blockTime; if (this._oscillator !== null) { var oldOsc = this._oscillator; oldOsc.stop(now); //dispose the old one setTimeout(function () { oldOsc.dispose(); oldOsc = null; }, this.blockTime * 1000); } this._oscillator = new OscillatorConstructor(); this.frequency.connect(this._oscillator.frequency); this.detune.connect(this._oscillator.detune); this._oscillator.connect(this.output); if (this.state === Tone.State.Started) { this._oscillator.start(now); } }; /** * The phase of the oscillator in degrees. * @memberOf Tone.OmniOscillator# * @type {Degrees} * @name phase */ Object.defineProperty(Tone.OmniOscillator.prototype, 'phase', { get: function () { return this._oscillator.phase; }, set: function (phase) { this._oscillator.phase = phase; } }); /** * The width of the oscillator (only if the oscillator is set to pulse) * @memberOf Tone.OmniOscillator# * @type {NormalRange} * @signal * @name width * @example * var omniOsc = new Tone.OmniOscillator(440, "pulse"); * //can access the width attribute only if type === "pulse" * omniOsc.width.value = 0.2; */ Object.defineProperty(Tone.OmniOscillator.prototype, 'width', { get: function () { if (this._sourceType === OmniOscType.PulseOscillator) { return this._oscillator.width; } } }); /** * The modulationFrequency Signal of the oscillator * (only if the oscillator type is set to pwm). * @memberOf Tone.OmniOscillator# * @type {Frequency} * @signal * @name modulationFrequency * @example * var omniOsc = new Tone.OmniOscillator(440, "pwm"); * //can access the modulationFrequency attribute only if type === "pwm" * omniOsc.modulationFrequency.value = 0.2; */ Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationFrequency', { get: function () { if (this._sourceType === OmniOscType.PWMOscillator) { return this._oscillator.modulationFrequency; } } }); /** * Clean up. * @return {Tone.OmniOscillator} this */ Tone.OmniOscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this._writable([ 'frequency', 'detune' ]); this.detune.dispose(); this.detune = null; this.frequency.dispose(); this.frequency = null; this._oscillator.dispose(); this._oscillator = null; this._sourceType = null; return this; }; return Tone.OmniOscillator; }); Module(function (Tone) { /** * @class Base-class for all instruments * * @constructor * @extends {Tone} */ Tone.Instrument = function (options) { //get the defaults options = this.defaultArg(options, Tone.Instrument.defaults); /** * The output and volume triming node * @type {Tone.Volume} * @private */ this._volume = this.output = new Tone.Volume(options.volume); /** * The volume of the output in decibels. * @type {Decibels} * @signal * @example * source.volume.value = -6; */ this.volume = this._volume.volume; this._readOnly('volume'); }; Tone.extend(Tone.Instrument); /** * the default attributes * @type {object} */ Tone.Instrument.defaults = { /** the volume of the output in decibels */ 'volume': 0 }; /** * @abstract * @param {string|number} note the note to trigger * @param {Time} [time=now] the time to trigger the ntoe * @param {number} [velocity=1] the velocity to trigger the note */ Tone.Instrument.prototype.triggerAttack = Tone.noOp; /** * @abstract * @param {Time} [time=now] when to trigger the release */ Tone.Instrument.prototype.triggerRelease = Tone.noOp; /** * Trigger the attack and then the release after the duration. * @param {Frequency} note The note to trigger. * @param {Time} duration How long the note should be held for before * triggering the release. * @param {Time} [time=now] When the note should be triggered. * @param {NormalRange} [velocity=1] The velocity the note should be triggered at. * @returns {Tone.Instrument} this * @example * //trigger "C4" for the duration of an 8th note * synth.triggerAttackRelease("C4", "8n"); */ Tone.Instrument.prototype.triggerAttackRelease = function (note, duration, time, velocity) { time = this.toSeconds(time); duration = this.toSeconds(duration); this.triggerAttack(note, time, velocity); this.triggerRelease(time + duration); return this; }; /** * clean up * @returns {Tone.Instrument} this */ Tone.Instrument.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._volume.dispose(); this._volume = null; this._writable(['volume']); this.volume = null; return this; }; return Tone.Instrument; }); Module(function (Tone) { /** * @class This is an abstract base class for other monophonic instruments to * extend. IMPORTANT: It does not make any sound on its own and * shouldn't be directly instantiated. * * @constructor * @abstract * @extends {Tone.Instrument} */ Tone.Monophonic = function (options) { //get the defaults options = this.defaultArg(options, Tone.Monophonic.defaults); Tone.Instrument.call(this, options); /** * The glide time between notes. * @type {Time} */ this.portamento = options.portamento; }; Tone.extend(Tone.Monophonic, Tone.Instrument); /** * @static * @const * @type {Object} */ Tone.Monophonic.defaults = { 'portamento': 0 }; /** * Trigger the attack of the note optionally with a given velocity. * * * @param {Frequency} note The note to trigger. * @param {Time} [time=now] When the note should start. * @param {number} [velocity=1] velocity The velocity scaler * determines how "loud" the note * will be triggered. * @returns {Tone.Monophonic} this * @example * synth.triggerAttack("C4"); * @example * //trigger the note a half second from now at half velocity * synth.triggerAttack("C4", "+0.5", 0.5); */ Tone.Monophonic.prototype.triggerAttack = function (note, time, velocity) { time = this.toSeconds(time); this._triggerEnvelopeAttack(time, velocity); this.setNote(note, time); return this; }; /** * Trigger the release portion of the envelope * @param {Time} [time=now] If no time is given, the release happens immediatly * @returns {Tone.Monophonic} this * @example * synth.triggerRelease(); */ Tone.Monophonic.prototype.triggerRelease = function (time) { this._triggerEnvelopeRelease(time); return this; }; /** * override this method with the actual method * @abstract * @private */ Tone.Monophonic.prototype._triggerEnvelopeAttack = function () { }; /** * override this method with the actual method * @abstract * @private */ Tone.Monophonic.prototype._triggerEnvelopeRelease = function () { }; /** * Set the note at the given time. If no time is given, the note * will set immediately. * @param {Frequency} note The note to change to. * @param {Time} [time=now] The time when the note should be set. * @returns {Tone.Monophonic} this * @example * //change to F#6 in one quarter note from now. * synth.setNote("F#6", "+4n"); * @example * //change to Bb4 right now * synth.setNote("Bb4"); */ Tone.Monophonic.prototype.setNote = function (note, time) { time = this.toSeconds(time); if (this.portamento > 0) { var currentNote = this.frequency.value; this.frequency.setValueAtTime(currentNote, time); var portTime = this.toSeconds(this.portamento); this.frequency.exponentialRampToValueAtTime(note, time + portTime); } else { this.frequency.setValueAtTime(note, time); } return this; }; return Tone.Monophonic; }); Module(function (Tone) { /** * @class Tone.MonoSynth is composed of one oscillator, one filter, and two envelopes. * The amplitude of the Tone.Oscillator and the cutoff frequency of the * Tone.Filter are controlled by Tone.Envelopes. * <img src="https://docs.google.com/drawings/d/1gaY1DF9_Hzkodqf8JI1Cg2VZfwSElpFQfI94IQwad38/pub?w=924&h=240"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.MonoSynth({ * "oscillator" : { * "type" : "square" * }, * "envelope" : { * "attack" : 0.1 * } * }).toMaster(); * synth.triggerAttackRelease("C4", "8n"); */ Tone.MonoSynth = function (options) { //get the defaults options = this.defaultArg(options, Tone.MonoSynth.defaults); Tone.Monophonic.call(this, options); /** * The oscillator. * @type {Tone.OmniOscillator} */ this.oscillator = new Tone.OmniOscillator(options.oscillator); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this.oscillator.frequency; /** * The detune control. * @type {Cents} * @signal */ this.detune = this.oscillator.detune; /** * The filter. * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); /** * The filter envelope. * @type {Tone.FrequencyEnvelope} */ this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); //connect the oscillators to the output this.oscillator.chain(this.filter, this.envelope, this.output); //start the oscillators this.oscillator.start(); //connect the filter envelope this.filterEnvelope.connect(this.filter.frequency); this._readOnly([ 'oscillator', 'frequency', 'detune', 'filter', 'filterEnvelope', 'envelope' ]); }; Tone.extend(Tone.MonoSynth, Tone.Monophonic); /** * @const * @static * @type {Object} */ Tone.MonoSynth.defaults = { 'frequency': 'C4', 'detune': 0, 'oscillator': { 'type': 'square' }, 'filter': { 'Q': 6, 'type': 'lowpass', 'rolloff': -24 }, 'envelope': { 'attack': 0.005, 'decay': 0.1, 'sustain': 0.9, 'release': 1 }, 'filterEnvelope': { 'attack': 0.06, 'decay': 0.2, 'sustain': 0.5, 'release': 2, 'baseFrequency': 200, 'octaves': 7, 'exponent': 2 } }; /** * start the attack portion of the envelope * @param {Time} [time=now] the time the attack should start * @param {NormalRange} [velocity=1] the velocity of the note (0-1) * @returns {Tone.MonoSynth} this * @private */ Tone.MonoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the envelopes this.envelope.triggerAttack(time, velocity); this.filterEnvelope.triggerAttack(time); return this; }; /** * start the release portion of the envelope * @param {Time} [time=now] the time the release should start * @returns {Tone.MonoSynth} this * @private */ Tone.MonoSynth.prototype._triggerEnvelopeRelease = function (time) { this.envelope.triggerRelease(time); this.filterEnvelope.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.MonoSynth} this */ Tone.MonoSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'oscillator', 'frequency', 'detune', 'filter', 'filterEnvelope', 'envelope' ]); this.oscillator.dispose(); this.oscillator = null; this.envelope.dispose(); this.envelope = null; this.filterEnvelope.dispose(); this.filterEnvelope = null; this.filter.dispose(); this.filter = null; this.frequency = null; this.detune = null; return this; }; return Tone.MonoSynth; }); Module(function (Tone) { /** * @class AMSynth uses the output of one Tone.MonoSynth to modulate the * amplitude of another Tone.MonoSynth. The harmonicity (the ratio between * the two signals) affects the timbre of the output signal the most. * Read more about Amplitude Modulation Synthesis on * [SoundOnSound](http://www.soundonsound.com/sos/mar00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1TQu8Ed4iFr1YTLKpB3U1_hur-UwBrh5gdBXc8BxfGKw/pub?w=1009&h=457"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.AMSynth().toMaster(); * synth.triggerAttackRelease("C4", "4n"); */ Tone.AMSynth = function (options) { options = this.defaultArg(options, Tone.AMSynth.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.MonoSynth} */ this.carrier = new Tone.MonoSynth(options.carrier); this.carrier.volume.value = -10; /** * The modulator voice. * @type {Tone.MonoSynth} */ this.modulator = new Tone.MonoSynth(options.modulator); this.modulator.volume.value = -10; /** * The frequency. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * synth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * convert the -1,1 output to 0,1 * @type {Tone.AudioToGain} * @private */ this._modulationScale = new Tone.AudioToGain(); /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.modulator.chain(this._modulationScale, this._modulationNode.gain); this.carrier.chain(this._modulationNode, this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); }; Tone.extend(Tone.AMSynth, Tone.Monophonic); /** * @static * @type {Object} */ Tone.AMSynth.defaults = { 'harmonicity': 3, 'carrier': { 'volume': -10, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0.01, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5, 'baseFrequency': 20000, 'octaves': 0 }, 'filter': { 'Q': 6, 'type': 'lowpass', 'rolloff': -24 } }, 'modulator': { 'volume': -10, 'oscillator': { 'type': 'square' }, 'envelope': { 'attack': 2, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 4, 'decay': 0.2, 'sustain': 0.5, 'release': 0.5, 'baseFrequency': 20, 'octaves': 6 }, 'filter': { 'Q': 6, 'type': 'lowpass', 'rolloff': -24 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {NormalRange} [velocity=1] the velocity of the note * @private * @returns {Tone.AMSynth} this */ Tone.AMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); this.carrier.filterEnvelope.triggerAttack(time); this.modulator.filterEnvelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @private * @returns {Tone.AMSynth} this */ Tone.AMSynth.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.AMSynth} this */ Tone.AMSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationScale.dispose(); this._modulationScale = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.AMSynth; }); Module(function (Tone) { /** * @class Tone.DrumSynth makes kick and tom sounds using a single oscillator * with an amplitude envelope and frequency ramp. A Tone.Oscillator * is routed through a Tone.AmplitudeEnvelope to the output. The drum * quality of the sound comes from the frequency envelope applied * during during Tone.DrumSynth.triggerAttack(note). The frequency * envelope starts at <code>note * .octaves</code> and ramps to * <code>note</code> over the duration of <code>.pitchDecay</code>. * * @constructor * @extends {Tone.Instrument} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.DrumSynth().toMaster(); * synth.triggerAttackRelease("C2", "8n"); */ Tone.DrumSynth = function (options) { options = this.defaultArg(options, Tone.DrumSynth.defaults); Tone.Instrument.call(this, options); /** * The oscillator. * @type {Tone.Oscillator} */ this.oscillator = new Tone.Oscillator(options.oscillator).start(); /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); /** * The number of octaves the pitch envelope ramps. * @type {Positive} */ this.octaves = options.octaves; /** * The amount of time the frequency envelope takes. * @type {Time} */ this.pitchDecay = options.pitchDecay; this.oscillator.chain(this.envelope, this.output); this._readOnly([ 'oscillator', 'envelope' ]); }; Tone.extend(Tone.DrumSynth, Tone.Instrument); /** * @static * @type {Object} */ Tone.DrumSynth.defaults = { 'pitchDecay': 0.05, 'octaves': 10, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.001, 'decay': 0.4, 'sustain': 0.01, 'release': 1.4, 'attackCurve': 'exponential' } }; /** * Trigger the note at the given time with the given velocity. * * @param {Frequency} note the note * @param {Time} [time=now] the time, if not given is now * @param {number} [velocity=1] velocity defaults to 1 * @returns {Tone.DrumSynth} this * @example * kick.triggerAttack(60); */ Tone.DrumSynth.prototype.triggerAttack = function (note, time, velocity) { time = this.toSeconds(time); note = this.toFrequency(note); var maxNote = note * this.octaves; this.oscillator.frequency.setValueAtTime(maxNote, time); this.oscillator.frequency.exponentialRampToValueAtTime(note, time + this.toSeconds(this.pitchDecay)); this.envelope.triggerAttack(time, velocity); return this; }; /** * Trigger the release portion of the note. * * @param {Time} [time=now] the time the note will release * @returns {Tone.DrumSynth} this */ Tone.DrumSynth.prototype.triggerRelease = function (time) { this.envelope.triggerRelease(time); return this; }; /** * Clean up. * @returns {Tone.DrumSynth} this */ Tone.DrumSynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._writable([ 'oscillator', 'envelope' ]); this.oscillator.dispose(); this.oscillator = null; this.envelope.dispose(); this.envelope = null; return this; }; return Tone.DrumSynth; }); Module(function (Tone) { /** * @class Tone.DuoSynth is a monophonic synth composed of two * MonoSynths run in parallel with control over the * frequency ratio between the two voices and vibrato effect. * <img src="https://docs.google.com/drawings/d/1bL4GXvfRMMlqS7XyBm9CjL9KJPSUKbcdBNpqOlkFLxk/pub?w=1012&h=448"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var duoSynth = new Tone.DuoSynth().toMaster(); * duoSynth.triggerAttackRelease("C4", "2n"); */ Tone.DuoSynth = function (options) { options = this.defaultArg(options, Tone.DuoSynth.defaults); Tone.Monophonic.call(this, options); /** * the first voice * @type {Tone.MonoSynth} */ this.voice0 = new Tone.MonoSynth(options.voice0); this.voice0.volume.value = -10; /** * the second voice * @type {Tone.MonoSynth} */ this.voice1 = new Tone.MonoSynth(options.voice1); this.voice1.volume.value = -10; /** * The vibrato LFO. * @type {Tone.LFO} * @private */ this._vibrato = new Tone.LFO(options.vibratoRate, -50, 50); this._vibrato.start(); /** * the vibrato frequency * @type {Frequency} * @signal */ this.vibratoRate = this._vibrato.frequency; /** * the vibrato gain * @type {GainNode} * @private */ this._vibratoGain = this.context.createGain(); /** * The amount of vibrato * @type {Positive} * @signal */ this.vibratoAmount = new Tone.Param({ 'param': this._vibratoGain.gain, 'units': Tone.Type.Positive, 'value': options.vibratoAmount }); /** * the delay before the vibrato starts * @type {number} * @private */ this._vibratoDelay = this.toSeconds(options.vibratoDelay); /** * the frequency control * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * duoSynth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; //control the two voices frequency this.frequency.connect(this.voice0.frequency); this.frequency.chain(this.harmonicity, this.voice1.frequency); this._vibrato.connect(this._vibratoGain); this._vibratoGain.fan(this.voice0.detune, this.voice1.detune); this.voice0.connect(this.output); this.voice1.connect(this.output); this._readOnly([ 'voice0', 'voice1', 'frequency', 'vibratoAmount', 'vibratoRate' ]); }; Tone.extend(Tone.DuoSynth, Tone.Monophonic); /** * @static * @type {Object} */ Tone.DuoSynth.defaults = { 'vibratoAmount': 0.5, 'vibratoRate': 5, 'vibratoDelay': 1, 'harmonicity': 1.5, 'voice0': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } }, 'voice1': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } } }; /** * start the attack portion of the envelopes * * @param {Time} [time=now] the time the attack should start * @param {NormalRange} [velocity=1] the velocity of the note (0-1) * @returns {Tone.DuoSynth} this * @private */ Tone.DuoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { time = this.toSeconds(time); this.voice0.envelope.triggerAttack(time, velocity); this.voice1.envelope.triggerAttack(time, velocity); this.voice0.filterEnvelope.triggerAttack(time); this.voice1.filterEnvelope.triggerAttack(time); return this; }; /** * start the release portion of the envelopes * * @param {Time} [time=now] the time the release should start * @returns {Tone.DuoSynth} this * @private */ Tone.DuoSynth.prototype._triggerEnvelopeRelease = function (time) { this.voice0.triggerRelease(time); this.voice1.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.DuoSynth} this */ Tone.DuoSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'voice0', 'voice1', 'frequency', 'vibratoAmount', 'vibratoRate' ]); this.voice0.dispose(); this.voice0 = null; this.voice1.dispose(); this.voice1 = null; this.frequency.dispose(); this.frequency = null; this._vibrato.dispose(); this._vibrato = null; this._vibratoGain.disconnect(); this._vibratoGain = null; this.harmonicity.dispose(); this.harmonicity = null; this.vibratoAmount.dispose(); this.vibratoAmount = null; this.vibratoRate = null; return this; }; return Tone.DuoSynth; }); Module(function (Tone) { /** * @class FMSynth is composed of two Tone.MonoSynths where one Tone.MonoSynth modulates * the frequency of a second Tone.MonoSynth. A lot of spectral content * can be explored using the modulationIndex parameter. Read more about * frequency modulation synthesis on [SoundOnSound](http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1h0PUDZXPgi4Ikx6bVT6oncrYPLluFKy7lj53puxj-DM/pub?w=902&h=462"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var fmSynth = new Tone.FMSynth().toMaster(); * fmSynth.triggerAttackRelease("C5", "4n"); */ Tone.FMSynth = function (options) { options = this.defaultArg(options, Tone.FMSynth.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.MonoSynth} */ this.carrier = new Tone.MonoSynth(options.carrier); this.carrier.volume.value = -10; /** * The modulator voice. * @type {Tone.MonoSynth} */ this.modulator = new Tone.MonoSynth(options.modulator); this.modulator.volume.value = -10; /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * synth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * The modulation index which essentially the depth or amount of the modulation. It is the * ratio of the frequency of the modulating signal (mf) to the amplitude of the * modulating signal (ma) -- as in ma/mf. * @type {Positive} * @signal */ this.modulationIndex = new Tone.Multiply(options.modulationIndex); this.modulationIndex.units = Tone.Type.Positive; /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.frequency.chain(this.modulationIndex, this._modulationNode); this.modulator.connect(this._modulationNode.gain); this._modulationNode.gain.value = 0; this._modulationNode.connect(this.carrier.frequency); this.carrier.connect(this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); }; Tone.extend(Tone.FMSynth, Tone.Monophonic); /** * @static * @type {Object} */ Tone.FMSynth.defaults = { 'harmonicity': 3, 'modulationIndex': 10, 'carrier': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5, 'baseFrequency': 200, 'octaves': 8 } }, 'modulator': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'triangle' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5, 'baseFrequency': 600, 'octaves': 5 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {number} [velocity=1] the velocity of the note * @returns {Tone.FMSynth} this * @private */ Tone.FMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); this.carrier.filterEnvelope.triggerAttack(time); this.modulator.filterEnvelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @returns {Tone.FMSynth} this * @private */ Tone.FMSynth.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.FMSynth} this */ Tone.FMSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.modulationIndex.dispose(); this.modulationIndex = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.FMSynth; }); Module(function (Tone) { /** * @class Tone.Noise is a noise generator. It uses looped noise buffers to save on performance. * Tone.Noise supports the noise types: "pink", "white", and "brown". Read more about * colors of noise on [Wikipedia](https://en.wikipedia.org/wiki/Colors_of_noise). * * @constructor * @extends {Tone.Source} * @param {string} type the noise type (white|pink|brown) * @example * //initialize the noise and start * var noise = new Tone.Noise("pink").start(); * * //make an autofilter to shape the noise * var autoFilter = new Tone.AutoFilter({ * "frequency" : "8m", * "min" : 800, * "max" : 15000 * }).connect(Tone.Master); * * //connect the noise * noise.connect(autoFilter); * //start the autofilter LFO * autoFilter.start() */ Tone.Noise = function () { var options = this.optionsObject(arguments, ['type'], Tone.Noise.defaults); Tone.Source.call(this, options); /** * @private * @type {AudioBufferSourceNode} */ this._source = null; /** * the buffer * @private * @type {AudioBuffer} */ this._buffer = null; /** * The playback rate of the noise. Affects * the "frequency" of the noise. * @type {Positive} * @signal */ this._playbackRate = options.playbackRate; this.type = options.type; }; Tone.extend(Tone.Noise, Tone.Source); /** * the default parameters * * @static * @const * @type {Object} */ Tone.Noise.defaults = { 'type': 'white', 'playbackRate': 1 }; /** * The type of the noise. Can be "white", "brown", or "pink". * @memberOf Tone.Noise# * @type {string} * @name type * @example * noise.type = "white"; */ Object.defineProperty(Tone.Noise.prototype, 'type', { get: function () { if (this._buffer === _whiteNoise) { return 'white'; } else if (this._buffer === _brownNoise) { return 'brown'; } else if (this._buffer === _pinkNoise) { return 'pink'; } }, set: function (type) { if (this.type !== type) { switch (type) { case 'white': this._buffer = _whiteNoise; break; case 'pink': this._buffer = _pinkNoise; break; case 'brown': this._buffer = _brownNoise; break; default: throw new Error('invalid noise type: ' + type); } //if it's playing, stop and restart it if (this.state === Tone.State.Started) { var now = this.now() + this.blockTime; //remove the listener this._stop(now); this._start(now); } } } }); /** * The playback rate of the noise. Affects * the "frequency" of the noise. * @type {Positive} * @signal */ Object.defineProperty(Tone.Noise.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; if (this._source) { this._source.playbackRate.value = rate; } } }); /** * internal start method * * @param {Time} time * @private */ Tone.Noise.prototype._start = function (time) { this._source = this.context.createBufferSource(); this._source.buffer = this._buffer; this._source.loop = true; this._source.playbackRate.value = this._playbackRate; this._source.connect(this.output); this._source.start(this.toSeconds(time)); }; /** * internal stop method * * @param {Time} time * @private */ Tone.Noise.prototype._stop = function (time) { if (this._source) { this._source.stop(this.toSeconds(time)); } }; /** * Clean up. * @returns {Tone.Noise} this */ Tone.Noise.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); if (this._source !== null) { this._source.disconnect(); this._source = null; } this._buffer = null; return this; }; /////////////////////////////////////////////////////////////////////////// // THE BUFFERS // borrowed heavily from http://noisehack.com/generate-noise-web-audio-api/ /////////////////////////////////////////////////////////////////////////// /** * static noise buffers * * @static * @private * @type {AudioBuffer} */ var _pinkNoise = null, _brownNoise = null, _whiteNoise = null; Tone._initAudioContext(function (audioContext) { var sampleRate = audioContext.sampleRate; //four seconds per buffer var bufferLength = sampleRate * 4; //fill the buffers _pinkNoise = function () { var buffer = audioContext.createBuffer(2, bufferLength, sampleRate); for (var channelNum = 0; channelNum < buffer.numberOfChannels; channelNum++) { var channel = buffer.getChannelData(channelNum); var b0, b1, b2, b3, b4, b5, b6; b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; for (var i = 0; i < bufferLength; i++) { var white = Math.random() * 2 - 1; b0 = 0.99886 * b0 + white * 0.0555179; b1 = 0.99332 * b1 + white * 0.0750759; b2 = 0.969 * b2 + white * 0.153852; b3 = 0.8665 * b3 + white * 0.3104856; b4 = 0.55 * b4 + white * 0.5329522; b5 = -0.7616 * b5 - white * 0.016898; channel[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; channel[i] *= 0.11; // (roughly) compensate for gain b6 = white * 0.115926; } } return buffer; }(); _brownNoise = function () { var buffer = audioContext.createBuffer(2, bufferLength, sampleRate); for (var channelNum = 0; channelNum < buffer.numberOfChannels; channelNum++) { var channel = buffer.getChannelData(channelNum); var lastOut = 0; for (var i = 0; i < bufferLength; i++) { var white = Math.random() * 2 - 1; channel[i] = (lastOut + 0.02 * white) / 1.02; lastOut = channel[i]; channel[i] *= 3.5; // (roughly) compensate for gain } } return buffer; }(); _whiteNoise = function () { var buffer = audioContext.createBuffer(2, bufferLength, sampleRate); for (var channelNum = 0; channelNum < buffer.numberOfChannels; channelNum++) { var channel = buffer.getChannelData(channelNum); for (var i = 0; i < bufferLength; i++) { channel[i] = Math.random() * 2 - 1; } } return buffer; }(); }); return Tone.Noise; }); Module(function (Tone) { /** * @class Tone.NoiseSynth is composed of a noise generator (Tone.Noise), one filter (Tone.Filter), * and two envelopes (Tone.Envelop). One envelope controls the amplitude * of the noise and the other is controls the cutoff frequency of the filter. * <img src="https://docs.google.com/drawings/d/1rqzuX9rBlhT50MRvD2TKml9bnZhcZmzXF1rf_o7vdnE/pub?w=918&h=242"> * * @constructor * @extends {Tone.Instrument} * @param {Object} [options] the options available for the synth * see defaults below * @example * var noiseSynth = new Tone.NoiseSynth().toMaster(); * noiseSynth.triggerAttackRelease("8n"); */ Tone.NoiseSynth = function (options) { //get the defaults options = this.defaultArg(options, Tone.NoiseSynth.defaults); Tone.Instrument.call(this, options); /** * The noise source. * @type {Tone.Noise} * @example * noiseSynth.set("noise.type", "brown"); */ this.noise = new Tone.Noise(); /** * The filter. * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); /** * The filter envelope. * @type {Tone.FrequencyEnvelope} */ this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); //connect the noise to the output this.noise.chain(this.filter, this.envelope, this.output); //start the noise this.noise.start(); //connect the filter envelope this.filterEnvelope.connect(this.filter.frequency); this._readOnly([ 'noise', 'filter', 'filterEnvelope', 'envelope' ]); }; Tone.extend(Tone.NoiseSynth, Tone.Instrument); /** * @const * @static * @type {Object} */ Tone.NoiseSynth.defaults = { 'noise': { 'type': 'white' }, 'filter': { 'Q': 6, 'type': 'highpass', 'rolloff': -24 }, 'envelope': { 'attack': 0.005, 'decay': 0.1, 'sustain': 0 }, 'filterEnvelope': { 'attack': 0.06, 'decay': 0.2, 'sustain': 0, 'release': 2, 'baseFrequency': 20, 'octaves': 5 } }; /** * Start the attack portion of the envelopes. Unlike other * instruments, Tone.NoiseSynth doesn't have a note. * @param {Time} [time=now] the time the attack should start * @param {number} [velocity=1] the velocity of the note (0-1) * @returns {Tone.NoiseSynth} this * @example * noiseSynth.triggerAttack(); */ Tone.NoiseSynth.prototype.triggerAttack = function (time, velocity) { //the envelopes this.envelope.triggerAttack(time, velocity); this.filterEnvelope.triggerAttack(time); return this; }; /** * Start the release portion of the envelopes. * @param {Time} [time=now] the time the release should start * @returns {Tone.NoiseSynth} this */ Tone.NoiseSynth.prototype.triggerRelease = function (time) { this.envelope.triggerRelease(time); this.filterEnvelope.triggerRelease(time); return this; }; /** * Trigger the attack and then the release. * @param {Time} duration the duration of the note * @param {Time} [time=now] the time of the attack * @param {number} [velocity=1] the velocity * @returns {Tone.NoiseSynth} this */ Tone.NoiseSynth.prototype.triggerAttackRelease = function (duration, time, velocity) { time = this.toSeconds(time); duration = this.toSeconds(duration); this.triggerAttack(time, velocity); this.triggerRelease(time + duration); return this; }; /** * Clean up. * @returns {Tone.NoiseSynth} this */ Tone.NoiseSynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._writable([ 'noise', 'filter', 'filterEnvelope', 'envelope' ]); this.noise.dispose(); this.noise = null; this.envelope.dispose(); this.envelope = null; this.filterEnvelope.dispose(); this.filterEnvelope = null; this.filter.dispose(); this.filter = null; return this; }; return Tone.NoiseSynth; }); Module(function (Tone) { /** * @class Karplus-String string synthesis. Often out of tune. * Will change when the AudioWorkerNode is available across * browsers. * * @constructor * @extends {Tone.Instrument} * @param {Object} [options] see the defaults * @example * var plucky = new Tone.PluckSynth().toMaster(); * plucky.triggerAttack("C4"); */ Tone.PluckSynth = function (options) { options = this.defaultArg(options, Tone.PluckSynth.defaults); Tone.Instrument.call(this, options); /** * @type {Tone.Noise} * @private */ this._noise = new Tone.Noise('pink'); /** * The amount of noise at the attack. * Nominal range of [0.1, 20] * @type {number} */ this.attackNoise = 1; /** * the LFCF * @type {Tone.LowpassCombFilter} * @private */ this._lfcf = new Tone.LowpassCombFilter({ 'resonance': options.resonance, 'dampening': options.dampening }); /** * The resonance control. * @type {NormalRange} * @signal */ this.resonance = this._lfcf.resonance; /** * The dampening control. i.e. the lowpass filter frequency of the comb filter * @type {Frequency} * @signal */ this.dampening = this._lfcf.dampening; //connections this._noise.connect(this._lfcf); this._lfcf.connect(this.output); this._readOnly([ 'resonance', 'dampening' ]); }; Tone.extend(Tone.PluckSynth, Tone.Instrument); /** * @static * @const * @type {Object} */ Tone.PluckSynth.defaults = { 'attackNoise': 1, 'dampening': 4000, 'resonance': 0.9 }; /** * Trigger the note. * @param {Frequency} note The note to trigger. * @param {Time} [time=now] When the note should be triggered. * @returns {Tone.PluckSynth} this */ Tone.PluckSynth.prototype.triggerAttack = function (note, time) { note = this.toFrequency(note); time = this.toSeconds(time); var delayAmount = 1 / note; this._lfcf.delayTime.setValueAtTime(delayAmount, time); this._noise.start(time); this._noise.stop(time + delayAmount * this.attackNoise); return this; }; /** * Clean up. * @returns {Tone.PluckSynth} this */ Tone.PluckSynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._noise.dispose(); this._lfcf.dispose(); this._noise = null; this._lfcf = null; this._writable([ 'resonance', 'dampening' ]); this.dampening = null; this.resonance = null; return this; }; return Tone.PluckSynth; }); Module(function (Tone) { /** * @class Tone.PolySynth handles voice creation and allocation for any * instruments passed in as the second paramter. PolySynth is * not a synthesizer by itself, it merely manages voices of * one of the other types of synths, allowing any of the * monophonic synthesizers to be polyphonic. * * @constructor * @extends {Tone.Instrument} * @param {number|Object} [polyphony=4] The number of voices to create * @param {function} [voice=Tone.MonoSynth] The constructor of the voices * uses Tone.MonoSynth by default. * @example * //a polysynth composed of 6 Voices of MonoSynth * var synth = new Tone.PolySynth(6, Tone.MonoSynth).toMaster(); * //set the attributes using the set interface * synth.set("detune", -1200); * //play a chord * synth.triggerAttackRelease(["C4", "E4", "A4"], "4n"); */ Tone.PolySynth = function () { Tone.Instrument.call(this); var options = this.optionsObject(arguments, [ 'polyphony', 'voice' ], Tone.PolySynth.defaults); /** * the array of voices * @type {Array} */ this.voices = new Array(options.polyphony); /** * If there are no more voices available, * should an active voice be stolen to play the new note? * @type {Boolean} */ this.stealVoices = true; /** * the queue of free voices * @private * @type {Array} */ this._freeVoices = []; /** * keeps track of which notes are down * @private * @type {Object} */ this._activeVoices = {}; //create the voices for (var i = 0; i < options.polyphony; i++) { var v = new options.voice(arguments[2], arguments[3]); this.voices[i] = v; v.connect(this.output); } //make a copy of the voices this._freeVoices = this.voices.slice(0); //get the prototypes and properties }; Tone.extend(Tone.PolySynth, Tone.Instrument); /** * the defaults * @const * @static * @type {Object} */ Tone.PolySynth.defaults = { 'polyphony': 4, 'voice': Tone.MonoSynth }; /** * Trigger the attack portion of the note * @param {Frequency|Array} notes The notes to play. Accepts a single * Frequency or an array of frequencies. * @param {Time} [time=now] The start time of the note. * @param {number} [velocity=1] The velocity of the note. * @returns {Tone.PolySynth} this * @example * //trigger a chord immediately with a velocity of 0.2 * poly.triggerAttack(["Ab3", "C4", "F5"], undefined, 0.2); */ Tone.PolySynth.prototype.triggerAttack = function (notes, time, velocity) { if (!Array.isArray(notes)) { notes = [notes]; } for (var i = 0; i < notes.length; i++) { var val = notes[i]; var stringified = JSON.stringify(val); //retrigger the same note if possible if (this._activeVoices.hasOwnProperty(stringified)) { this._activeVoices[stringified].triggerAttack(val, time, velocity); } else if (this._freeVoices.length > 0) { var voice = this._freeVoices.shift(); voice.triggerAttack(val, time, velocity); this._activeVoices[stringified] = voice; } else if (this.stealVoices) { //steal a voice //take the first voice for (var voiceName in this._activeVoices) { this._activeVoices[voiceName].triggerAttack(val, time, velocity); break; } } } return this; }; /** * Trigger the attack and release after the specified duration * * @param {Frequency|Array} notes The notes to play. Accepts a single * Frequency or an array of frequencies. * @param {Time} duration the duration of the note * @param {Time} [time=now] if no time is given, defaults to now * @param {number} [velocity=1] the velocity of the attack (0-1) * @returns {Tone.PolySynth} this * @example * //trigger a chord for a duration of a half note * poly.triggerAttackRelease(["Eb3", "G4", "C5"], "2n"); */ Tone.PolySynth.prototype.triggerAttackRelease = function (notes, duration, time, velocity) { time = this.toSeconds(time); this.triggerAttack(notes, time, velocity); this.triggerRelease(notes, time + this.toSeconds(duration)); return this; }; /** * Trigger the release of the note. Unlike monophonic instruments, * a note (or array of notes) needs to be passed in as the first argument. * @param {Frequency|Array} notes The notes to play. Accepts a single * Frequency or an array of frequencies. * @param {Time} [time=now] When the release will be triggered. * @returns {Tone.PolySynth} this * @example * poly.triggerRelease(["Ab3", "C4", "F5"], "+2n"); */ Tone.PolySynth.prototype.triggerRelease = function (notes, time) { if (!Array.isArray(notes)) { notes = [notes]; } for (var i = 0; i < notes.length; i++) { //get the voice var stringified = JSON.stringify(notes[i]); var voice = this._activeVoices[stringified]; if (voice) { voice.triggerRelease(time); this._freeVoices.push(voice); delete this._activeVoices[stringified]; voice = null; } } return this; }; /** * Set a member/attribute of the voices. * @param {Object|string} params * @param {number=} value * @param {Time=} rampTime * @returns {Tone.PolySynth} this * @example * poly.set({ * "filter" : { * "type" : "highpass" * }, * "envelope" : { * "attack" : 0.25 * } * }); */ Tone.PolySynth.prototype.set = function (params, value, rampTime) { for (var i = 0; i < this.voices.length; i++) { this.voices[i].set(params, value, rampTime); } return this; }; /** * Get the synth's attributes. Given no arguments get * will return all available object properties and their corresponding * values. Pass in a single attribute to retrieve or an array * of attributes. The attribute strings can also include a "." * to access deeper properties. * @param {Array=} params the parameters to get, otherwise will return * all available. */ Tone.PolySynth.prototype.get = function (params) { return this.voices[0].get(params); }; /** * Trigger the release portion of all the currently active voices. * @param {Time} [time=now] When the notes should be released. * @return {Tone.PolySynth} this */ Tone.PolySynth.prototype.releaseAll = function (time) { for (var i = 0; i < this.voices.length; i++) { this.voices[i].triggerRelease(time); } return this; }; /** * Clean up. * @returns {Tone.PolySynth} this */ Tone.PolySynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); for (var i = 0; i < this.voices.length; i++) { this.voices[i].dispose(); this.voices[i] = null; } this.voices = null; this._activeVoices = null; this._freeVoices = null; return this; }; return Tone.PolySynth; }); Module(function (Tone) { /** * @class Tone.Player is an audio file player with start, loop, and stop functions. * * @constructor * @extends {Tone.Source} * @param {string|AudioBuffer} url Either the AudioBuffer or the url from * which to load the AudioBuffer * @param {function=} onload The function to invoke when the buffer is loaded. * Recommended to use Tone.Buffer.onload instead. * @example * var player = new Tone.Player("./path/to/sample.mp3").toMaster(); * Tone.Buffer.onload = function(){ * player.start(); * } */ Tone.Player = function (url) { var options; if (url instanceof Tone.Buffer) { url = url.get(); options = Tone.Player.defaults; } else { options = this.optionsObject(arguments, [ 'url', 'onload' ], Tone.Player.defaults); } Tone.Source.call(this, options); /** * @private * @type {AudioBufferSourceNode} */ this._source = null; /** * If the file should play as soon * as the buffer is loaded. * @type {boolean} * @example * //will play as soon as it's loaded * var player = new Tone.Player({ * "url" : "./path/to/sample.mp3", * "autostart" : true, * }).toMaster(); */ this.autostart = options.autostart; /** * the buffer * @private * @type {Tone.Buffer} */ this._buffer = new Tone.Buffer({ 'url': options.url, 'onload': this._onload.bind(this, options.onload), 'reverse': options.reverse }); if (url instanceof AudioBuffer) { this._buffer.set(url); } /** * if the buffer should loop once it's over * @type {boolean} * @private */ this._loop = options.loop; /** * if 'loop' is true, the loop will start at this position * @type {Time} * @private */ this._loopStart = options.loopStart; /** * if 'loop' is true, the loop will end at this position * @type {Time} * @private */ this._loopEnd = options.loopEnd; /** * the playback rate * @private * @type {number} */ this._playbackRate = options.playbackRate; /** * Enabling retrigger will allow a player to be restarted * before the the previous 'start' is done playing. Otherwise, * successive calls to Tone.Player.start will only start * the sample if it had played all the way through. * @type {boolean} */ this.retrigger = options.retrigger; }; Tone.extend(Tone.Player, Tone.Source); /** * the default parameters * @static * @const * @type {Object} */ Tone.Player.defaults = { 'onload': Tone.noOp, 'playbackRate': 1, 'loop': false, 'autostart': false, 'loopStart': 0, 'loopEnd': 0, 'retrigger': false, 'reverse': false }; /** * Load the audio file as an audio buffer. * Decodes the audio asynchronously and invokes * the callback once the audio buffer loads. * Note: this does not need to be called if a url * was passed in to the constructor. Only use this * if you want to manually load a new url. * @param {string} url The url of the buffer to load. * Filetype support depends on the * browser. * @param {function=} callback The function to invoke once * the sample is loaded. * @returns {Tone.Player} this */ Tone.Player.prototype.load = function (url, callback) { this._buffer.load(url, this._onload.bind(this, callback)); return this; }; /** * Internal callback when the buffer is loaded. * @private */ Tone.Player.prototype._onload = function (callback) { callback(this); if (this.autostart) { this.start(); } }; /** * play the buffer between the desired positions * * @private * @param {Time} [startTime=now] when the player should start. * @param {Time} [offset=0] the offset from the beginning of the sample * to start at. * @param {Time=} duration how long the sample should play. If no duration * is given, it will default to the full length * of the sample (minus any offset) * @returns {Tone.Player} this */ Tone.Player.prototype._start = function (startTime, offset, duration) { if (this._buffer.loaded) { //if it's a loop the default offset is the loopstart point if (this._loop) { offset = this.defaultArg(offset, this._loopStart); } else { //otherwise the default offset is 0 offset = this.defaultArg(offset, 0); } offset = this.toSeconds(offset); duration = this.defaultArg(duration, this._buffer.duration - offset); //the values in seconds startTime = this.toSeconds(startTime); duration = this.toSeconds(duration); //make the source this._source = this.context.createBufferSource(); this._source.buffer = this._buffer.get(); //set the looping properties if (this._loop) { this._source.loop = this._loop; this._source.loopStart = this.toSeconds(this._loopStart); this._source.loopEnd = this.toSeconds(this._loopEnd); } else { //if it's not looping, set the state change at the end of the sample this._state.setStateAtTime(Tone.State.Stopped, startTime + duration); } //and other properties this._source.playbackRate.value = this._playbackRate; this._source.connect(this.output); //start it if (this._loop) { this._source.start(startTime, offset); } else { this._source.start(startTime, offset, duration); } } else { throw Error('tried to start Player before the buffer was loaded'); } return this; }; /** * Stop playback. * @private * @param {Time} [time=now] * @returns {Tone.Player} this */ Tone.Player.prototype._stop = function (time) { if (this._source) { this._source.stop(this.toSeconds(time)); this._source = null; } return this; }; /** * Set the loop start and end. Will only loop if loop is * set to true. * @param {Time} loopStart The loop end time * @param {Time} loopEnd The loop end time * @returns {Tone.Player} this * @example * //loop 0.1 seconds of the file. * player.setLoopPoints(0.2, 0.3); * player.loop = true; */ Tone.Player.prototype.setLoopPoints = function (loopStart, loopEnd) { this.loopStart = loopStart; this.loopEnd = loopEnd; return this; }; /** * If loop is true, the loop will start at this position. * @memberOf Tone.Player# * @type {Time} * @name loopStart */ Object.defineProperty(Tone.Player.prototype, 'loopStart', { get: function () { return this._loopStart; }, set: function (loopStart) { this._loopStart = loopStart; if (this._source) { this._source.loopStart = this.toSeconds(loopStart); } } }); /** * If loop is true, the loop will end at this position. * @memberOf Tone.Player# * @type {Time} * @name loopEnd */ Object.defineProperty(Tone.Player.prototype, 'loopEnd', { get: function () { return this._loopEnd; }, set: function (loopEnd) { this._loopEnd = loopEnd; if (this._source) { this._source.loopEnd = this.toSeconds(loopEnd); } } }); /** * The audio buffer belonging to the player. * @memberOf Tone.Player# * @type {Tone.Buffer} * @name buffer */ Object.defineProperty(Tone.Player.prototype, 'buffer', { get: function () { return this._buffer; }, set: function (buffer) { this._buffer.set(buffer); } }); /** * If the buffer should loop once it's over. * @memberOf Tone.Player# * @type {boolean} * @name loop */ Object.defineProperty(Tone.Player.prototype, 'loop', { get: function () { return this._loop; }, set: function (loop) { this._loop = loop; if (this._source) { this._source.loop = loop; } } }); /** * The playback speed. 1 is normal speed. This is not a signal because * Safari and iOS currently don't support playbackRate as a signal. * @memberOf Tone.Player# * @type {number} * @name playbackRate */ Object.defineProperty(Tone.Player.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; if (this._source) { this._source.playbackRate.value = rate; } } }); /** * The direction the buffer should play in * @memberOf Tone.Player# * @type {boolean} * @name reverse */ Object.defineProperty(Tone.Player.prototype, 'reverse', { get: function () { return this._buffer.reverse; }, set: function (rev) { this._buffer.reverse = rev; } }); /** * Dispose and disconnect. * @return {Tone.Player} this */ Tone.Player.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); if (this._source !== null) { this._source.disconnect(); this._source = null; } this._buffer.dispose(); this._buffer = null; return this; }; return Tone.Player; }); Module(function (Tone) { /** * @class A sampler instrument which plays an audio buffer * through an amplitude envelope and a filter envelope. The sampler takes * an Object in the constructor which maps a sample name to the URL * of the sample. Nested Objects will be flattened and can be accessed using * a dot notation (see the example). * <img src="https://docs.google.com/drawings/d/1UK-gi_hxzKDz9Dh4ByyOptuagMOQxv52WxN12HwvtW8/pub?w=931&h=241"> * * @constructor * @extends {Tone.Instrument} * @param {Object|string} urls the urls of the audio file * @param {Object} [options] the options object for the synth * @example * var sampler = new Sampler({ * A : { * 1 : "./audio/casio/A1.mp3", * 2 : "./audio/casio/A2.mp3", * }, * "B.1" : "./audio/casio/B1.mp3", * }).toMaster(); * * //listen for when all the samples have loaded * Tone.Buffer.onload = function(){ * sampler.triggerAttack("A.1", time, velocity); * }; */ Tone.Sampler = function (urls, options) { options = this.defaultArg(options, Tone.Sampler.defaults); Tone.Instrument.call(this, options); /** * The sample player. * @type {Tone.Player} */ this.player = new Tone.Player(options.player); this.player.retrigger = true; /** * the buffers * @type {Object} * @private */ this._buffers = {}; /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); /** * The filter envelope. * @type {Tone.FrequencyEnvelope} */ this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); /** * The name of the current sample. * @type {string} * @private */ this._sample = options.sample; /** * the private reference to the pitch * @type {number} * @private */ this._pitch = options.pitch; /** * The filter. * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); //connections / setup this._loadBuffers(urls); this.pitch = options.pitch; this.player.chain(this.filter, this.envelope, this.output); this.filterEnvelope.connect(this.filter.frequency); this._readOnly([ 'player', 'filterEnvelope', 'envelope', 'filter' ]); }; Tone.extend(Tone.Sampler, Tone.Instrument); /** * the default parameters * @static */ Tone.Sampler.defaults = { 'sample': 0, 'pitch': 0, 'player': { 'loop': false }, 'envelope': { 'attack': 0.001, 'decay': 0, 'sustain': 1, 'release': 0.1 }, 'filterEnvelope': { 'attack': 0.001, 'decay': 0.001, 'sustain': 1, 'release': 0.5, 'baseFrequency': 20, 'octaves': 10 }, 'filter': { 'type': 'lowpass' } }; /** * load the buffers * @param {Object} urls the urls * @private */ Tone.Sampler.prototype._loadBuffers = function (urls) { if (this.isString(urls)) { this._buffers['0'] = new Tone.Buffer(urls, function () { this.sample = '0'; }.bind(this)); } else { urls = this._flattenUrls(urls); for (var buffName in urls) { this._sample = buffName; var urlString = urls[buffName]; this._buffers[buffName] = new Tone.Buffer(urlString); } } }; /** * Flatten an object into a single depth object. * thanks to https://gist.github.com/penguinboy/762197 * @param {Object} ob * @return {Object} * @private */ Tone.Sampler.prototype._flattenUrls = function (ob) { var toReturn = {}; for (var i in ob) { if (!ob.hasOwnProperty(i)) continue; if (this.isObject(ob[i])) { var flatObject = this._flattenUrls(ob[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; }; /** * Start the sample and simultaneously trigger the envelopes. * @param {string=} sample The name of the sample to trigger, defaults to * the last sample used. * @param {Time} [time=now] The time when the sample should start * @param {number} [velocity=1] The velocity of the note * @returns {Tone.Sampler} this * @example * sampler.triggerAttack("B.1"); */ Tone.Sampler.prototype.triggerAttack = function (name, time, velocity) { time = this.toSeconds(time); if (name) { this.sample = name; } this.player.start(time); this.envelope.triggerAttack(time, velocity); this.filterEnvelope.triggerAttack(time); return this; }; /** * Start the release portion of the sample. Will stop the sample once the * envelope has fully released. * * @param {Time} [time=now] The time when the note should release * @returns {Tone.Sampler} this * @example * sampler.triggerRelease(); */ Tone.Sampler.prototype.triggerRelease = function (time) { time = this.toSeconds(time); this.filterEnvelope.triggerRelease(time); this.envelope.triggerRelease(time); this.player.stop(this.toSeconds(this.envelope.release) + time); return this; }; /** * The name of the sample to trigger. * @memberOf Tone.Sampler# * @type {number|string} * @name sample * @example * //set the sample to "A.2" for next time the sample is triggered * sampler.sample = "A.2"; */ Object.defineProperty(Tone.Sampler.prototype, 'sample', { get: function () { return this._sample; }, set: function (name) { if (this._buffers.hasOwnProperty(name)) { this._sample = name; this.player.buffer = this._buffers[name]; } else { throw new Error('Sampler does not have a sample named ' + name); } } }); /** * The direction the buffer should play in * @memberOf Tone.Sampler# * @type {boolean} * @name reverse */ Object.defineProperty(Tone.Sampler.prototype, 'reverse', { get: function () { for (var i in this._buffers) { return this._buffers[i].reverse; } }, set: function (rev) { for (var i in this._buffers) { this._buffers[i].reverse = rev; } } }); /** * Repitch the sampled note by some interval (measured * in semi-tones). * @memberOf Tone.Sampler# * @type {Interval} * @name pitch * @example * sampler.pitch = -12; //down one octave * sampler.pitch = 7; //up a fifth */ Object.defineProperty(Tone.Sampler.prototype, 'pitch', { get: function () { return this._pitch; }, set: function (interval) { this._pitch = interval; this.player.playbackRate = this.intervalToFrequencyRatio(interval); } }); /** * Clean up. * @returns {Tone.Sampler} this */ Tone.Sampler.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._writable([ 'player', 'filterEnvelope', 'envelope', 'filter' ]); this.player.dispose(); this.filterEnvelope.dispose(); this.envelope.dispose(); this.filter.dispose(); this.player = null; this.filterEnvelope = null; this.envelope = null; this.filter = null; for (var sample in this._buffers) { this._buffers[sample].dispose(); this._buffers[sample] = null; } this._buffers = null; return this; }; return Tone.Sampler; }); Module(function (Tone) { /** * @class Tone.SimpleSynth is composed simply of a Tone.OmniOscillator * routed through a Tone.AmplitudeEnvelope. * <img src="https://docs.google.com/drawings/d/1-1_0YW2Z1J2EPI36P8fNCMcZG7N1w1GZluPs4og4evo/pub?w=1163&h=231"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.SimpleSynth().toMaster(); * synth.triggerAttackRelease("C4", "8n"); */ Tone.SimpleSynth = function (options) { //get the defaults options = this.defaultArg(options, Tone.SimpleSynth.defaults); Tone.Monophonic.call(this, options); /** * The oscillator. * @type {Tone.OmniOscillator} */ this.oscillator = new Tone.OmniOscillator(options.oscillator); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this.oscillator.frequency; /** * The detune control. * @type {Cents} * @signal */ this.detune = this.oscillator.detune; /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); //connect the oscillators to the output this.oscillator.chain(this.envelope, this.output); //start the oscillators this.oscillator.start(); this._readOnly([ 'oscillator', 'frequency', 'detune', 'envelope' ]); }; Tone.extend(Tone.SimpleSynth, Tone.Monophonic); /** * @const * @static * @type {Object} */ Tone.SimpleSynth.defaults = { 'oscillator': { 'type': 'triangle' }, 'envelope': { 'attack': 0.005, 'decay': 0.1, 'sustain': 0.3, 'release': 1 } }; /** * start the attack portion of the envelope * @param {Time} [time=now] the time the attack should start * @param {number} [velocity=1] the velocity of the note (0-1) * @returns {Tone.SimpleSynth} this * @private */ Tone.SimpleSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the envelopes this.envelope.triggerAttack(time, velocity); return this; }; /** * start the release portion of the envelope * @param {Time} [time=now] the time the release should start * @returns {Tone.SimpleSynth} this * @private */ Tone.SimpleSynth.prototype._triggerEnvelopeRelease = function (time) { this.envelope.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.SimpleSynth} this */ Tone.SimpleSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'oscillator', 'frequency', 'detune', 'envelope' ]); this.oscillator.dispose(); this.oscillator = null; this.envelope.dispose(); this.envelope = null; this.frequency = null; this.detune = null; return this; }; return Tone.SimpleSynth; }); Module(function (Tone) { /** * @class AMSynth uses the output of one Tone.SimpleSynth to modulate the * amplitude of another Tone.SimpleSynth. The harmonicity (the ratio between * the two signals) affects the timbre of the output signal the most. * Read more about Amplitude Modulation Synthesis on [SoundOnSound](http://www.soundonsound.com/sos/mar00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1p_os_As-N1bpnK8u55gXlgVw3U7BfquLX0Wj57kSZXY/pub?w=1009&h=457"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.SimpleAM().toMaster(); * synth.triggerAttackRelease("C4", "8n"); */ Tone.SimpleAM = function (options) { options = this.defaultArg(options, Tone.SimpleAM.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.SimpleSynth} */ this.carrier = new Tone.SimpleSynth(options.carrier); /** * The modulator voice. * @type {Tone.SimpleSynth} */ this.modulator = new Tone.SimpleSynth(options.modulator); /** * the frequency control * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * The ratio between the carrier and the modulator frequencies. A value of 1 * makes both voices in unison, a value of 0.5 puts the modulator an octave below * the carrier. * @type {Positive} * @signal * @example * //set the modulator an octave above the carrier frequency * simpleAM.harmonicity.value = 2; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * convert the -1,1 output to 0,1 * @type {Tone.AudioToGain} * @private */ this._modulationScale = new Tone.AudioToGain(); /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.modulator.chain(this._modulationScale, this._modulationNode.gain); this.carrier.chain(this._modulationNode, this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); }; Tone.extend(Tone.SimpleAM, Tone.Monophonic); /** * @static * @type {Object} */ Tone.SimpleAM.defaults = { 'harmonicity': 3, 'carrier': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0.01, 'sustain': 1, 'release': 0.5 } }, 'modulator': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.5, 'decay': 0.1, 'sustain': 1, 'release': 0.5 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {number} [velocity=1] the velocity of the note * @returns {Tone.SimpleAM} this * @private */ Tone.SimpleAM.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @returns {Tone.SimpleAM} this * @private */ Tone.SimpleAM.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.SimpleAM} this */ Tone.SimpleAM.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationScale.dispose(); this._modulationScale = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.SimpleAM; }); Module(function (Tone) { /** * @class SimpleFM is composed of two Tone.SimpleSynths where one Tone.SimpleSynth modulates * the frequency of a second Tone.SimpleSynth. A lot of spectral content * can be explored using the Tone.FMSynth.modulationIndex parameter. Read more about * frequency modulation synthesis on [SoundOnSound](http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1hSU25lLjDk_WJ59DSitQm6iCRpcMWVEAYqBjwmqtRVw/pub?w=902&h=462"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var fmSynth = new Tone.SimpleFM().toMaster(); * fmSynth.triggerAttackRelease("C4", "8n"); */ Tone.SimpleFM = function (options) { options = this.defaultArg(options, Tone.SimpleFM.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.SimpleSynth} */ this.carrier = new Tone.SimpleSynth(options.carrier); this.carrier.volume.value = -10; /** * The modulator voice. * @type {Tone.SimpleSynth} */ this.modulator = new Tone.SimpleSynth(options.modulator); this.modulator.volume.value = -10; /** * the frequency control * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * synth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the * ratio of the frequency of the modulating signal (mf) to the amplitude of the * modulating signal (ma) -- as in ma/mf. * @type {Positive} * @signal */ this.modulationIndex = new Tone.Multiply(options.modulationIndex); this.modulationIndex.units = Tone.Type.Positive; /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.frequency.chain(this.modulationIndex, this._modulationNode); this.modulator.connect(this._modulationNode.gain); this._modulationNode.gain.value = 0; this._modulationNode.connect(this.carrier.frequency); this.carrier.connect(this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); ; }; Tone.extend(Tone.SimpleFM, Tone.Monophonic); /** * @static * @type {Object} */ Tone.SimpleFM.defaults = { 'harmonicity': 3, 'modulationIndex': 10, 'carrier': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } }, 'modulator': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'triangle' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {number} [velocity=1] the velocity of the note * @returns {Tone.SimpleFM} this * @private */ Tone.SimpleFM.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @returns {Tone.SimpleFM} this * @private */ Tone.SimpleFM.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.SimpleFM} this */ Tone.SimpleFM.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.modulationIndex.dispose(); this.modulationIndex = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.SimpleFM; }); Module(function (Tone) { //polyfill for getUserMedia navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; /** * @class Tone.ExternalInput is a WebRTC Audio Input. Check * [Media Stream API Support](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_API) * to see which browsers are supported. As of * writing this, Chrome, Firefox, and Opera * support Media Stream. Chrome allows enumeration * of the sources, and access to device name over a * secure (HTTPS) connection. See [https://simpl.info](https://simpl.info/getusermedia/sources/index.html) * vs [http://simple.info](https://simpl.info/getusermedia/sources/index.html) * on a Chrome browser for the difference. * * @constructor * @extends {Tone.Source} * @param {number} [inputNum=0] If multiple inputs are present, select the input number. Chrome only. * @example * //select the third input * var motu = new Tone.ExternalInput(3); * * //opening the input asks the user to activate their mic * motu.open(function(){ * //opening is activates the microphone * //starting lets audio through * motu.start(10); * }); */ Tone.ExternalInput = function () { var options = this.optionsObject(arguments, ['inputNum'], Tone.ExternalInput.defaults); Tone.Source.call(this, options); /** * The MediaStreamNode * @type {MediaStreamAudioSourceNode} * @private */ this._mediaStream = null; /** * The media stream created by getUserMedia. * @type {LocalMediaStream} * @private */ this._stream = null; /** * The constraints argument for getUserMedia * @type {Object} * @private */ this._constraints = { 'audio': { mandatory: { "googEchoCancellation": "false", "googAutoGainControl": "false", "googNoiseSuppression": "false", "googHighpassFilter": "false" }, "optional": [] } }; /** * The input source position in Tone.ExternalInput.sources. * Set before ExternalInput.open(). * @type {Number} * @private */ this._inputNum = options.inputNum; /** * Gates the input signal for start/stop. * Initially closed. * @type {GainNode} * @private */ this._gate = new Tone.Gain(0).connect(this.output); }; Tone.extend(Tone.ExternalInput, Tone.Source); /** * the default parameters * @type {Object} */ Tone.ExternalInput.defaults = { 'inputNum': 0 }; /** * wrapper for getUserMedia function * @param {function} callback * @private */ Tone.ExternalInput.prototype._getUserMedia = function (callback) { if (!Tone.ExternalInput.supported) { throw new Error('browser does not support \'getUserMedia\''); } if (Tone.ExternalInput.sources[this._inputNum]) { this._constraints = { audio: { mandatory: { "googEchoCancellation": "false", "googAutoGainControl": "false", "googNoiseSuppression": "false", "googHighpassFilter": "false" }, optional: [{ sourceId: Tone.ExternalInput.sources[this._inputNum].id }] } }; } navigator.getUserMedia(this._constraints, function (stream) { this._onStream(stream); callback(); }.bind(this), function (err) { callback(err); }); }; /** * called when the stream is successfully setup * @param {LocalMediaStream} stream * @private */ Tone.ExternalInput.prototype._onStream = function (stream) { if (!this.isFunction(this.context.createMediaStreamSource)) { throw new Error('browser does not support the \'MediaStreamSourceNode\''); } //can only start a new source if the previous one is closed if (!this._stream) { this._stream = stream; //Wrap a MediaStreamSourceNode around the live input stream. this._mediaStream = this.context.createMediaStreamSource(stream); //Connect the MediaStreamSourceNode to a gate gain node this._mediaStream.connect(this._gate); } }; /** * Open the media stream * @param {function=} callback The callback function to * execute when the stream is open * @return {Tone.ExternalInput} this */ Tone.ExternalInput.prototype.open = function (callback) { callback = this.defaultArg(callback, Tone.noOp); Tone.ExternalInput.getSources(function () { this._getUserMedia(callback); }.bind(this)); return this; }; /** * Close the media stream * @return {Tone.ExternalInput} this */ Tone.ExternalInput.prototype.close = function () { if (this._stream) { var track = this._stream.getTracks()[this._inputNum]; if (!this.isUndef(track)) { track.stop(); } this._stream = null; } return this; }; /** * Start the stream * @private */ Tone.ExternalInput.prototype._start = function (time) { time = this.toSeconds(time); this._gate.gain.setValueAtTime(1, time); return this; }; /** * Stops the stream. * @private */ Tone.ExternalInput.prototype._stop = function (time) { time = this.toSeconds(time); this._gate.gain.setValueAtTime(0, time); return this; }; /** * Clean up. * @return {Tone.ExternalInput} this */ Tone.ExternalInput.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this.close(); if (this._mediaStream) { this._mediaStream.disconnect(); this._mediaStream = null; } this._constraints = null; this._gate.dispose(); this._gate = null; return this; }; /////////////////////////////////////////////////////////////////////////// // STATIC METHODS /////////////////////////////////////////////////////////////////////////// /** * The array of available sources, different depending on whether connection is secure * @type {Array} * @static */ Tone.ExternalInput.sources = []; /** * indicates whether browser supports MediaStreamTrack.getSources (i.e. Chrome vs Firefox) * @type {Boolean} * @private */ Tone.ExternalInput._canGetSources = !Tone.prototype.isUndef(window.MediaStreamTrack) && Tone.prototype.isFunction(MediaStreamTrack.getSources); /** * If getUserMedia is supported by the browser. * @type {Boolean} * @memberOf Tone.ExternalInput# * @name supported * @static * @readOnly */ Object.defineProperty(Tone.ExternalInput, 'supported', { get: function () { return Tone.prototype.isFunction(navigator.getUserMedia); } }); /** * Populates the source list. Invokes the callback with an array of * possible audio sources. * @param {function=} callback Callback to be executed after populating list * @return {Tone.ExternalInput} this * @static * @example * var soundflower = new Tone.ExternalInput(); * Tone.ExternalInput.getSources(selectSoundflower); * * function selectSoundflower(sources){ * for(var i = 0; i < sources.length; i++){ * if(sources[i].label === "soundflower"){ * soundflower.inputNum = i; * soundflower.open(function(){ * soundflower.start(); * }); * break; * } * } * }; */ Tone.ExternalInput.getSources = function (callback) { if (Tone.ExternalInput.sources.length === 0 && Tone.ExternalInput._canGetSources) { MediaStreamTrack.getSources(function (media_sources) { for (var i = 0; i < media_sources.length; i++) { if (media_sources[i].kind === 'audio') { Tone.ExternalInput.sources[i] = media_sources[i]; } } callback(Tone.ExternalInput.sources); }); } else { callback(Tone.ExternalInput.sources); } return this; }; return Tone.ExternalInput; }); Module(function (Tone) { /** * @class Opens up the default source (typically the microphone). * * @constructor * @extends {Tone.ExternalInput} * @example * //mic will feedback if played through master * var mic = new Tone.Microphone(); * mic.open(function(){ * //start the mic at ten seconds * mic.start(10); * }); * //stop the mic * mic.stop(20); */ Tone.Microphone = function () { Tone.ExternalInput.call(this, 0); }; Tone.extend(Tone.Microphone, Tone.ExternalInput); /** * If getUserMedia is supported by the browser. * @type {Boolean} * @memberOf Tone.Microphone# * @name supported * @static * @readOnly */ Object.defineProperty(Tone.Microphone, 'supported', { get: function () { return Tone.ExternalInput.supported; } }); return Tone.Microphone; }); Module(function (Tone) { /** * @class Clip the incoming signal so that the output is always between min and max. * * @constructor * @extends {Tone.SignalBase} * @param {number} min the minimum value of the outgoing signal * @param {number} max the maximum value of the outgoing signal * @example * var clip = new Tone.Clip(0.5, 1); * var osc = new Tone.Oscillator().connect(clip); * //clips the output of the oscillator to between 0.5 and 1. */ Tone.Clip = function (min, max) { //make sure the args are in the right order if (min > max) { var tmp = min; min = max; max = tmp; } /** * The min clip value * @type {Number} * @signal */ this.min = this.input = new Tone.Min(max); this._readOnly('min'); /** * The max clip value * @type {Number} * @signal */ this.max = this.output = new Tone.Max(min); this._readOnly('max'); this.min.connect(this.max); }; Tone.extend(Tone.Clip, Tone.SignalBase); /** * clean up * @returns {Tone.Clip} this */ Tone.Clip.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('min'); this.min.dispose(); this.min = null; this._writable('max'); this.max.dispose(); this.max = null; return this; }; return Tone.Clip; }); Module(function (Tone) { /** * @class Normalize takes an input min and max and maps it linearly to NormalRange [0,1] * * @extends {Tone.SignalBase} * @constructor * @param {number} inputMin the min input value * @param {number} inputMax the max input value * @example * var norm = new Tone.Normalize(2, 4); * var sig = new Tone.Signal(3).connect(norm); * //output of norm is 0.5. */ Tone.Normalize = function (inputMin, inputMax) { /** * the min input value * @type {number} * @private */ this._inputMin = this.defaultArg(inputMin, 0); /** * the max input value * @type {number} * @private */ this._inputMax = this.defaultArg(inputMax, 1); /** * subtract the min from the input * @type {Tone.Add} * @private */ this._sub = this.input = new Tone.Add(0); /** * divide by the difference between the input and output * @type {Tone.Multiply} * @private */ this._div = this.output = new Tone.Multiply(1); this._sub.connect(this._div); this._setRange(); }; Tone.extend(Tone.Normalize, Tone.SignalBase); /** * The minimum value the input signal will reach. * @memberOf Tone.Normalize# * @type {number} * @name min */ Object.defineProperty(Tone.Normalize.prototype, 'min', { get: function () { return this._inputMin; }, set: function (min) { this._inputMin = min; this._setRange(); } }); /** * The maximum value the input signal will reach. * @memberOf Tone.Normalize# * @type {number} * @name max */ Object.defineProperty(Tone.Normalize.prototype, 'max', { get: function () { return this._inputMax; }, set: function (max) { this._inputMax = max; this._setRange(); } }); /** * set the values * @private */ Tone.Normalize.prototype._setRange = function () { this._sub.value = -this._inputMin; this._div.value = 1 / (this._inputMax - this._inputMin); }; /** * clean up * @returns {Tone.Normalize} this */ Tone.Normalize.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sub.dispose(); this._sub = null; this._div.dispose(); this._div = null; return this; }; return Tone.Normalize; }); Module(function (Tone) { /** * @class Route a single input to the specified output. * * @constructor * @extends {Tone.SignalBase} * @param {number} [outputCount=2] the number of inputs the switch accepts * @example * var route = new Tone.Route(4); * var signal = new Tone.Signal(3).connect(route); * route.select(0); * //signal is routed through output 0 * route.select(3); * //signal is now routed through output 3 */ Tone.Route = function (outputCount) { outputCount = this.defaultArg(outputCount, 2); Tone.call(this, 1, outputCount); /** * The control signal. * @type {Number} * @signal */ this.gate = new Tone.Signal(0); this._readOnly('gate'); //make all the inputs and connect them for (var i = 0; i < outputCount; i++) { var routeGate = new RouteGate(i); this.output[i] = routeGate; this.gate.connect(routeGate.selecter); this.input.connect(routeGate); } }; Tone.extend(Tone.Route, Tone.SignalBase); /** * Routes the signal to one of the outputs and close the others. * @param {number} [which=0] Open one of the gates (closes the other). * @param {Time} [time=now] The time when the switch will open. * @returns {Tone.Route} this */ Tone.Route.prototype.select = function (which, time) { //make sure it's an integer which = Math.floor(which); this.gate.setValueAtTime(which, this.toSeconds(time)); return this; }; /** * Clean up. * @returns {Tone.Route} this */ Tone.Route.prototype.dispose = function () { this._writable('gate'); this.gate.dispose(); this.gate = null; for (var i = 0; i < this.output.length; i++) { this.output[i].dispose(); this.output[i] = null; } Tone.prototype.dispose.call(this); return this; }; ////////////START HELPER//////////// /** * helper class for Tone.Route representing a single gate * @constructor * @extends {Tone} * @private */ var RouteGate = function (num) { /** * the selector * @type {Tone.Equal} */ this.selecter = new Tone.Equal(num); /** * the gate * @type {GainNode} */ this.gate = this.input = this.output = this.context.createGain(); //connect the selecter to the gate gain this.selecter.connect(this.gate.gain); }; Tone.extend(RouteGate); /** * clean up * @private */ RouteGate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.selecter.dispose(); this.selecter = null; this.gate.disconnect(); this.gate = null; }; ////////////END HELPER//////////// //return Tone.Route return Tone.Route; }); Module(function (Tone) { /** * @class When the gate is set to 0, the input signal does not pass through to the output. * If the gate is set to 1, the input signal passes through. * the gate is initially closed. * * @constructor * @extends {Tone.SignalBase} * @param {Boolean} [open=false] If the gate is initially open or closed. * @example * var sigSwitch = new Tone.Switch(); * var signal = new Tone.Signal(2).connect(sigSwitch); * //initially no output from sigSwitch * sigSwitch.gate.value = 1; * //open the switch and allow the signal through * //the output of sigSwitch is now 2. */ Tone.Switch = function (open) { open = this.defaultArg(open, false); Tone.call(this); /** * The control signal for the switch. * When this value is 0, the input signal will NOT pass through, * when it is high (1), the input signal will pass through. * * @type {Number} * @signal */ this.gate = new Tone.Signal(0); this._readOnly('gate'); /** * thresh the control signal to either 0 or 1 * @type {Tone.GreaterThan} * @private */ this._thresh = new Tone.GreaterThan(0.5); this.input.connect(this.output); this.gate.chain(this._thresh, this.output.gain); //initially open if (open) { this.open(); } }; Tone.extend(Tone.Switch, Tone.SignalBase); /** * Open the switch at a specific time. * * @param {Time} [time=now] The time when the switch will be open. * @returns {Tone.Switch} this * @example * //open the switch to let the signal through * sigSwitch.open(); */ Tone.Switch.prototype.open = function (time) { this.gate.setValueAtTime(1, this.toSeconds(time)); return this; }; /** * Close the switch at a specific time. * * @param {Time} [time=now] The time when the switch will be closed. * @returns {Tone.Switch} this * @example * //close the switch a half second from now * sigSwitch.close("+0.5"); */ Tone.Switch.prototype.close = function (time) { this.gate.setValueAtTime(0, this.toSeconds(time)); return this; }; /** * Clean up. * @returns {Tone.Switch} this */ Tone.Switch.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('gate'); this.gate.dispose(); this.gate = null; this._thresh.dispose(); this._thresh = null; return this; }; return Tone.Switch; }); //UMD if ( typeof define === "function" && define.amd ) { define(function() { return Tone; }); } else if (typeof module === "object") { module.exports = Tone; } else { root.Tone = Tone; } } (this));
DeerMichel/pedalboard
js/tone.js
JavaScript
gpl-3.0
637,440
Ext.define('Healthsurvey.view.mobileview.login.ChangePasswordScreenController', { extend : 'Ext.app.ViewController', alias : 'controller.changePasswordScreenController', onChangePasswordClick : function(btn, opts) { debugger; var form = btn.up().up(); if (form.isValid()) { var formData = form.getValues(); delete formData.reTypeNewPassword; var entMask = new Ext.LoadMask({ msg : 'Updating...', target : this.getView() }).show(); Ext.Ajax.request({ timeout : 180000, url : "secure/PasswordGenerator/changePassword", method : 'PUT', waitMsg : 'Updating...', entMask : entMask, jsonData : formData, me : this, success : function(response, sender) { debugger; var responseText = Ext.JSON.decode(response.responseText); if (responseText.response.success) { Ext.Msg.alert("Info", responseText.response.message); sender.me.onResetClick(); } else { Ext.Msg.alert("Info", responseText.response.message); } sender.entMask.hide(); }, failure : function(response, sender) { debugger; Ext.Msg.alert("ERROR", "Cannot connect to server"); sender.entMask.hide(); } }); } }, onResetClick : function(btn, opts) { debugger; this.getView().getForm().reset(); } });
applifireAlgo/appApplifire
healthsurvey/src/main/webapp/app/view/mobileview/login/ChangePasswordScreenController.js
JavaScript
gpl-3.0
1,301
Joomla 3.6.4 = 5e60174db2edd61c1c32011464017d84 Joomla 3.7.0 = c7eeeb362de64acba3e76fd13e0ad6af Joomla 3.4.1 = 399117bc209c7f4eb16f72bfef504db7
gohdan/DFC
known_files/hashes/media/editors/codemirror/mode/yaml/yaml.min.js
JavaScript
gpl-3.0
144
'use strict'; function Boot() { } Boot.prototype = { preload: function () { this.load.image('preloader', 'assets/preloader.gif'); }, create: function () { this.game.input.maxPointers = 1; this.game.state.start('preload'); } }; module.exports = Boot;
robomatix/one-minute-shoot-em-up-v2
game/states/boot.js
JavaScript
gpl-3.0
273
/*global assert: false, refute: false */ var buster = require("buster"), huddle = require("../lib/huddle.js"), resources; buster.testCase('Huddle', { setUp: function () { resources = new huddle.Huddle(); }, "Empty input": function () { resources.read(''); assert.equals(resources.write(), ''); }, "Doctype should be preserved": function () { resources.read('<!DOCTYPE html>'); assert.equals(resources.write(), '<!DOCTYPE html>'); }, "Multi line doctype": function () { resources.read('<!DOCTYPE html line1\nline2>'); assert.equals(resources.write(), '<!DOCTYPE html line1\nline2>'); }, "Singleton tag": function () { resources.read('<div/>'); assert.equals(resources.write(), '<div/>'); }, "Strip whitespace": function () { resources.read(' <div/>'); assert.equals(resources.write(), '<div/>'); }, "Preserve whitespace": function () { resources = new huddle.Huddle({ignoreWhitespace: false}); resources.read(' <div/>'); assert.equals(resources.write(), ' <div/>'); }, "Open/Close tag without body": function () { resources.read('<div></div>'); assert.equals(resources.write(), '<div/>'); }, "Open/Close tag with body": function () { resources.read('<div>Test</div>'); assert.equals(resources.write(), '<div>Test</div>'); }, "Tag with attributes": function () { resources.read('<div a1="v1" a2="v2"/>'); assert.equals(resources.write(), '<div a1="v1" a2="v2"/>'); }, "Stylesheet link tag": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.write(), '<link href="app.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['app']['a.css'], 'text/css'); }, "Multiple stylesheet link tags": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css"/><link href="b.less" rel="stylesheet/less" type="text/css"/>'); assert.equals(resources.write(), '<link href="app.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['app']['a.css'], 'text/css'); assert.equals(resources.getStylesheets()['app']['b.less'], 'text/less'); }, "Stylesheet with module": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-module="mymod"/>'); assert.equals(resources.write(), '<link href="mymod.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['mymod']['a.css'], 'text/css'); refute(resources.getStylesheets()['app']); }, "Multiple stylesheet link tags with modules": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-module="mylib"/><link href="b.less" rel="stylesheet/less" type="text/css"/>'); assert.equals(resources.write(), '<link href="mylib.css" rel="stylesheet" type="text/css"/><link href="app.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['mylib']['a.css'], 'text/css'); assert.equals(resources.getStylesheets()['app']['b.less'], 'text/less'); }, "Drop stylesheet link tag": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-drop=""/>'); assert.equals(resources.write(), ''); refute(resources.getStylesheets()['app']); }, "Include remote stylesheet": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-remote="b.css"/>'); assert.equals(resources.write(), '<link href="b.css" rel="stylesheet" type="text/css"/>'); refute(resources.getStylesheets()['app']); }, "Script tag": function () { resources.read('<script type="text/javascript" src="a.js"></script>'); assert.equals(resources.write(), '<script type="text/javascript" src="app.js"></script>'); assert.equals(resources.getScripts()['app']['a.js'], 'text/javascript'); }, "Multiple script tags with modules": function () { resources.read('<script type="text/javascript" src="a.js"></script><script type="text/javascript" src="b.js" data-module="mylib"></script>'); assert.equals(resources.write(), '<script type="text/javascript" src="app.js"></script><script type="text/javascript" src="mylib.js"></script>'); assert.equals(resources.getScripts()['app']['a.js'], 'text/javascript'); assert.equals(resources.getScripts()['mylib']['b.js'], 'text/javascript'); }, "Drop script tag": function () { resources.read('<script type="text/javascript" src="a.js" data-drop=""/>'); assert.equals(resources.write(), ''); refute(resources.getScripts()['app']); }, "Include remote scripts": function () { resources.read('<script type="text/javascript" src="a.js" data-remote="b.js"/>'); assert.equals(resources.write(), '<script type="text/javascript" src="b.js"></script>'); refute(resources.getScripts()['app']); } });
robgietema/huddle
test/huddle-test.js
JavaScript
gpl-3.0
5,229
/* * This file is part of MystudiesMyteaching application. * * MystudiesMyteaching application is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MystudiesMyteaching application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MystudiesMyteaching application. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; describe('Event time span filter', function () { var eventTimeSpanFilter; beforeEach(module('directives.weekFeed')); beforeEach(module('ngResource')); beforeEach(function () { module(function ($provide) { $provide.constant('StateService', { getStateFromDomain: function () { } }); $provide.constant('LanguageService', { getLocale: function () { return 'en'; } }); }); }); beforeEach(inject(function ($filter) { eventTimeSpanFilter = $filter('eventTimeSpan'); })); it('Will show only startdate with english format', function () { var startDate = moment([2014, 2, 12, 13, 40]); var result = eventTimeSpanFilter(startDate); expect(result).toEqual('3/12/2014 13:40'); }); });
UH-StudentServices/mystudies-myteaching-frontend
main/test/spec/unit/directives/weekFeed/eventTimeSpanFilterEnSpec.js
JavaScript
gpl-3.0
1,516
(function () { 'use strict'; function Cat(name, color) { this.name = name; this.color = color; } Cat.prototype.age = 4; var huesitos = new Cat('huesitos', 'amarillo claro'); display(huesitos.__proto__); display(Cat.prototype ); display(huesitos.__proto__ == Cat.prototype ); Cat.prototype = { age: 5}; display(Cat.prototype); } ());
zaiboot/javascript-playground
public/prototypes/demo03/demo.js
JavaScript
gpl-3.0
409
// Parsley.js @@version // http://parsleyjs.org // (c) 20012-2014 Guillaume Potier, Wisembly // Parsley may be freely distributed under the MIT license. define([ // ### Requirements // Handy third party functions 'parsley/utils', // Parsley default configuration 'parsley/defaults', // An abstract class shared by `ParsleyField` and `ParsleyForm` 'parsley/abstract', // A proxy between Parsley and [Validator.js](http://validatorjs.org) 'parsley/validator', // `ParsleyUI` static class. Handle all UI and UX 'parsley/ui', // Handle default javascript config and DOM-API config 'parsley/factory/options', // `ParsleyForm` Class. Handle form validation 'parsley/form', // `ParsleyField` Class. Handle field validation 'parsley/field', // `Multiple` Class. Extend `ParsleyField` to generate `ParsleyFieldMultiple` 'parsley/multiple', // Tiny Parsley Pub / Sub mechanism, used for `ParsleyUI` and Listeners 'parsley/pubsub', // Default en constraints messages 'i18n/en' ], function (ParsleyUtils, ParsleyDefaults, ParsleyAbstract, ParsleyValidator, ParsleyUI, ParsleyOptionsFactory, ParsleyForm, ParsleyField, ParsleyMultiple) { // ### Parsley factory var Parsley = function (element, options, parsleyFormInstance) { this.__class__ = 'Parsley'; this.__version__ = '@@version'; this.__id__ = ParsleyUtils.hash(4); // Parsley must be instantiated with a DOM element or jQuery $element if ('undefined' === typeof element) throw new Error('You must give an element'); if ('undefined' !== typeof parsleyFormInstance && 'ParsleyForm' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a ParsleyForm instance'); return this.init($(element), options, parsleyFormInstance); }; Parsley.prototype = { init: function ($element, options, parsleyFormInstance) { if (!$element.length) throw new Error('You must bind Parsley on an existing element.'); this.$element = $element; // If element have already been binded, returns its saved Parsley instance if (this.$element.data('Parsley')) { var savedparsleyFormInstance = this.$element.data('Parsley'); // If saved instance have been binded without a ParsleyForm parent and there is one given in this call, add it if ('undefined' !== typeof parsleyFormInstance) savedparsleyFormInstance.parent = parsleyFormInstance; return savedparsleyFormInstance; } // Handle 'static' options this.OptionsFactory = new ParsleyOptionsFactory(ParsleyDefaults, ParsleyUtils.get(window, 'ParsleyConfig') || {}, options, this.getNamespace(options)); this.options = this.OptionsFactory.get(this); // A ParsleyForm instance is obviously a `<form>` elem but also every node that is not an input and have `data-parsley-validate` attribute if (this.$element.is('form') || (ParsleyUtils.attr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs))) return this.bind('parsleyForm'); // Every other supported element and not excluded element is binded as a `ParsleyField` or `ParsleyFieldMultiple` else if (this.$element.is(this.options.inputs) && !this.$element.is(this.options.excluded)) return this.isMultiple() ? this.handleMultiple(parsleyFormInstance) : this.bind('parsleyField', parsleyFormInstance); return this; }, isMultiple: function () { return (this.$element.is('input[type=radio], input[type=checkbox]') && 'undefined' === typeof this.options.multiple) || (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')); }, // Multiples fields are a real nightmare :( // Maybe some refacto would be appreciated here... handleMultiple: function (parsleyFormInstance) { var that = this, name, multiple, parsleyMultipleInstance; // Get parsleyFormInstance options if exist, mixed with element attributes this.options = $.extend(this.options, parsleyFormInstance ? parsleyFormInstance.OptionsFactory.get(parsleyFormInstance) : {}, ParsleyUtils.attr(this.$element, this.options.namespace)); // Handle multiple name if (this.options.multiple) multiple = this.options.multiple; else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) multiple = name = this.$element.attr('name'); else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) multiple = this.$element.attr('id'); // Special select multiple input if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) { return this.bind('parsleyFieldMultiple', parsleyFormInstance, multiple || this.__id__); // Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it } else if ('undefined' === typeof multiple) { if (window.console && window.console.warn) window.console.warn('To be binded by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element); return this; } // Remove special chars multiple = multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g, ''); // Add proper `data-parsley-multiple` to siblings if we have a valid multiple name if ('undefined' !== typeof name) { $('input[name="' + name + '"]').each(function () { if ($(this).is('input[type=radio], input[type=checkbox]')) $(this).attr(that.options.namespace + 'multiple', multiple); }); } // Check here if we don't already have a related multiple instance saved if ($('[' + this.options.namespace + 'multiple=' + multiple +']').length) { for (var i = 0; i < $('[' + this.options.namespace + 'multiple=' + multiple +']').length; i++) { if ('undefined' !== typeof $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley')) { parsleyMultipleInstance = $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley'); if (!this.$element.data('ParsleyFieldMultiple')) { parsleyMultipleInstance.addElement(this.$element); this.$element.attr(this.options.namespace + 'id', parsleyMultipleInstance.__id__); } break; } } } // Create a secret ParsleyField instance for every multiple field. It would be stored in `data('ParsleyFieldMultiple')` // And would be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance this.bind('parsleyField', parsleyFormInstance, multiple, true); return parsleyMultipleInstance || this.bind('parsleyFieldMultiple', parsleyFormInstance, multiple); }, // Retrieve namespace used for DOM-API getNamespace: function (options) { // `data-parsley-namespace=<namespace>` if ('undefined' !== typeof this.$element.data('parsleyNamespace')) return this.$element.data('parsleyNamespace'); if ('undefined' !== typeof ParsleyUtils.get(options, 'namespace')) return options.namespace; if ('undefined' !== typeof ParsleyUtils.get(window, 'ParsleyConfig.namespace')) return window.ParsleyConfig.namespace; return ParsleyDefaults.namespace; }, // Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple` bind: function (type, parentParsleyFormInstance, multiple, doNotStore) { var parsleyInstance; switch (type) { case 'parsleyForm': parsleyInstance = $.extend( new ParsleyForm(this.$element, this.OptionsFactory), new ParsleyAbstract(), window.ParsleyExtend )._bindFields(); break; case 'parsleyField': parsleyInstance = $.extend( new ParsleyField(this.$element, this.OptionsFactory, parentParsleyFormInstance), new ParsleyAbstract(), window.ParsleyExtend ); break; case 'parsleyFieldMultiple': parsleyInstance = $.extend( new ParsleyField(this.$element, this.OptionsFactory, parentParsleyFormInstance), new ParsleyAbstract(), new ParsleyMultiple(), window.ParsleyExtend )._init(multiple); break; default: throw new Error(type + 'is not a supported Parsley type'); } if ('undefined' !== typeof multiple) ParsleyUtils.setAttr(this.$element, this.options.namespace, 'multiple', multiple); if ('undefined' !== typeof doNotStore) { this.$element.data('ParsleyFieldMultiple', parsleyInstance); return parsleyInstance; } // Store instance if `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple` if (new RegExp('ParsleyF', 'i').test(parsleyInstance.__class__)) { // Store for later access the freshly binded instance in DOM element itself using jQuery `data()` this.$element.data('Parsley', parsleyInstance); // Tell the world we got a new ParsleyForm or ParsleyField instance! $.emit('parsley:' + ('parsleyForm' === type ? 'form' : 'field') + ':init', parsleyInstance); } return parsleyInstance; } }; // ### jQuery API // `$('.elem').parsley(options)` or `$('.elem').psly(options)` $.fn.parsley = $.fn.psly = function (options) { if (this.length > 1) { var instances = []; this.each(function () { instances.push($(this).parsley(options)); }); return instances; } // Return undefined if applied to non existing DOM element if (!$(this).length) { if (window.console && window.console.warn) window.console.warn('You must bind Parsley on an existing element.'); return; } return new Parsley(this, options); }; // ### ParsleyUI // UI is a class apart that only listen to some events and them modify DOM accordingly // Could be overriden by defining a `window.ParsleyConfig.ParsleyUI` appropriate class (with `listen()` method basically) window.ParsleyUI = 'function' === typeof ParsleyUtils.get(window, 'ParsleyConfig.ParsleyUI') ? new window.ParsleyConfig.ParsleyUI().listen() : new ParsleyUI().listen(); // ### ParsleyField and ParsleyForm extension // Ensure that defined if not already the case if ('undefined' === typeof window.ParsleyExtend) window.ParsleyExtend = {}; // ### ParsleyConfig // Ensure that defined if not already the case if ('undefined' === typeof window.ParsleyConfig) window.ParsleyConfig = {}; // ### Globals window.Parsley = window.psly = Parsley; window.ParsleyUtils = ParsleyUtils; window.ParsleyValidator = new ParsleyValidator(window.ParsleyConfig.validators, window.ParsleyConfig.i18n); // ### PARSLEY auto-binding // Prevent it by setting `ParsleyConfig.autoBind` to `false` if (false !== ParsleyUtils.get(window, 'ParsleyConfig.autoBind')) $(function () { // Works only on `data-parsley-validate`. if ($('[data-parsley-validate]').length) $('[data-parsley-validate]').parsley(); }); return Parsley; });
arout/halcyon
public/template/sing/assets/vendor/parsleyjs/src/parsley.js
JavaScript
gpl-3.0
11,659
"use strict"; class WellTile extends Tile { constructor(row, column) { super("brunnen.gif", row, column); this.tooltip_name = "WELL"; this.build_costs = { humansidle: 5 }; this.production = { water: 1 }; this.counter = 1; this.workingspeed = 5; } clone() { return new WellTile(this.row, this.column); } getUpgrades() { return [new GrassTile(),] } };
RitualTycoon/RitualTycoon
src/tiles/WellTile.js
JavaScript
gpl-3.0
441
/*global define*/ define(["hbs/handlebars"], function (Handlebars) { "use strict"; function debug (optionalValue) { console.log("===================="); console.log("Current Context"); console.log(this); if (optionalValue) { console.log("===================="); console.log("Value"); console.log(optionalValue); } console.log("===================="); } Handlebars.registerHelper("debug", debug); });
munvier/electron-higgins
app/public/js/app/templates/helpers/debug.js
JavaScript
gpl-3.0
562
/** * Copyright 2019 Google LLC * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import WebMidi from 'webmidi' import { EventEmitter } from 'events' export class MidiKeyboard extends EventEmitter { constructor(){ super() this.connectedDevices = new Map() if (WebMidi.supported){ this.ready = new Promise((done, error) => { WebMidi.enable((e) => { if (e){ error(e) } WebMidi.inputs.forEach(i => this._addListeners(i)) WebMidi.addListener('connected', (e) => { if (e.port.type === 'input'){ this._addListeners(e.port) } }) WebMidi.addListener('disconnected', (e) => { this._removeListeners(e.port) }) done() }) }) } else { this.ready = Promise.resolve() } } _addListeners(device){ if (!this.connectedDevices.has(device.id)){ this.connectedDevices.set(device.id, device) device.addListener('noteon', 'all', (event) => { this.emit('keyDown', `${event.note.name}${event.note.octave}`, event.velocity) }) device.addListener('noteoff', 'all', (event) => { this.emit('keyUp', `${event.note.name}${event.note.octave}`, event.velocity) }) device.addListener('controlchange', 'all', (event) => { if (event.controller.name === 'holdpedal'){ this.emit(event.value ? 'pedalDown' : 'pedalUp') } }) } } _removeListeners(event){ if (this.connectedDevices.has(event.id)){ const device = this.connectedDevices.get(event.id) this.connectedDevices.delete(event.id) device.removeListener('noteon') device.removeListener('noteoff') device.removeListener('controlchange') } } }
googlecreativelab/creatability-seeing-music
src/piano/Keyboard.js
JavaScript
gpl-3.0
2,031
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'kitchensink', 'vi', { block: 'Canh đều', center: 'Toggle Toolbars', left: 'Canh trái', right: 'Canh phải' });
jsnfwlr/editor27
lib/editor/ckeditor/ckeditor/plugins/kitchensink/lang/vi.js
JavaScript
gpl-3.0
303
var chrDesktopNotificationsView = new function () { 'use strict'; var that = this; this.ID = 'chrDesktopNotificationsView'; this.ns = {}; this.showChrRichNotificationProgress = function (title, body, sourceUrl, noturl, iconUrl) { try { var opt = { type: 'progress', title: title, message: body, iconUrl: iconUrl, contextMessage: sourceUrl, progress: 0 }; chrome.notifications.create(opt, function (nid) { try { that.ns[nid] = { clickUrl: noturl }; that.startUpdateChrNotificationProgress(nid); } catch (err) { console.error(err.stack); } }); } catch (err) { console.error(err.stack); } }; this.startUpdateChrNotificationProgress = function (nid) { try { var value = 0; var idInterval = setInterval(function () { value += 15; if (value > 100) { chrome.notifications.update(nid, { progress: 100 }, function (wasUpdated) {}); that.stopUpdateChrNotificationProgress(nid); } else { chrome.notifications.update(nid, { progress: value }, function (wasUpdated) {}); } }, 1000); this.ns[nid].updateIdInterval = idInterval; } catch (err) { console.error(err.stack); } }; this.stopUpdateChrNotificationProgress = function (nid) { try { if (this.ns[nid] && this.ns[nid].updateIdInterval) { clearInterval(this.ns[nid].updateIdInterval); } } catch (err) { console.error(err.stack); } }; this.onClosedNotification = function (nid) { try { that.stopUpdateChrNotificationProgress(nid); delete that.ns[nid]; } catch (err) { console.error(err.stack); } }; this.onClickedNotification = function (nid) { try { if (that.ns[nid]) { var url = that.ns[nid].clickUrl; var urlToSearch = sourceController.removePostMessageNumber(url); mediator.showTab(url, true, true, urlToSearch); chrome.notifications.clear(nid, function (wasCleared) {}); } else { chrome.notifications.clear(nid, function (wasCleared) {}); } } catch (err) { console.error(err.stack); } }; (function init() { try { chrome.notifications.onClosed.addListener(that.onClosedNotification); chrome.notifications.onClicked.addListener(that.onClickedNotification); } catch (err) { console.error(err.stack); } }()); };
alepolidori/chrome-discourse-notifications
src/js/chrDesktopNotificationsView.js
JavaScript
gpl-3.0
2,997
import React from 'react' import { Link } from 'react-router' import videos from './videos.json' const video = videos[Math.floor(Math.random() * videos.length)] export default ({ userLoaded, toSteps, toInfo }) => ( <div className='ext-home-cover' style={{ backgroundImage: `url("${video.image}")` }}> {window.innerWidth >= 768 && ( <div className='banner'> <div className='video'> <video playsInline autoPlay muted loop poster={video.image} id='bgvid'> <source src={video.video} type='video/mp4' /> </video> </div> </div> )} <div className='container'> <div className='ext-site-cover-isologo' style={{ backgroundImage: `url('/ext/lib/site/home-multiforum/consultas.svg')` }} /> <div> <h1>Consultas</h1> <h2>Queremos que seas parte de la celebración de la bandera y su creador. Sumate a decidir cómo ponemos linda nuestra ciudad.</h2> </div> </div> </div> )
RosarioCiudad/democracyos
ext/lib/site/home-consultas/cover/component.js
JavaScript
gpl-3.0
1,090
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'pagebreak', 'pt', { alt: 'Quebra de página', toolbar: 'Inserir quebra de página' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/pagebreak/lang/pt.js
JavaScript
gpl-3.0
280
var polymer_8cpp = [ [ "buf_mindist4", "polymer_8cpp.html#a2080040fff4e87f6c075beafbdf99c1e", null ], [ "collectBonds", "polymer_8cpp.html#a7f7eaba446fd0bed3b96996e0845fa4f", null ], [ "collision", "polymer_8cpp.html#a59b45a870af8c48e35778c1aa024784f", null ], [ "constraint_collision", "polymer_8cpp.html#a0b632b1caf95727fb65b7eb395c7b2b3", null ], [ "counterionsC", "polymer_8cpp.html#a534641660049999d598963032d7334b6", null ], [ "crosslinkC", "polymer_8cpp.html#a8d4e44f737092ed5f1dd1e57e75cb84d", null ], [ "diamondC", "polymer_8cpp.html#aba74355e1fc2212cc1efafbe1ed52e7a", null ], [ "icosaederC", "polymer_8cpp.html#a9277c343409d1d01bcd5cd3ef4ef1553", null ], [ "maxwell_velocitiesC", "polymer_8cpp.html#ae80b5af52b013104b77da5e4ed3eeb1a", null ], [ "mindist3", "polymer_8cpp.html#a8dd300667e521d08cedc144080ddc3be", null ], [ "mindist4", "polymer_8cpp.html#acb328614ba8fe11d2730d84d04bda328", null ], [ "polymerC", "polymer_8cpp.html#a4d8ccd239688d4c99efa5e93c9ece0c1", null ], [ "saltC", "polymer_8cpp.html#a112f62be89b958db2d7a193f1412deea", null ], [ "velocitiesC", "polymer_8cpp.html#aed6a16a4f76f416b38702918eb7e5b24", null ] ];
HaoZeke/espresso
doc/doxygen/html/polymer_8cpp.js
JavaScript
gpl-3.0
1,196
(function() { var Scope, extend, last, _ref; _ref = require('./helpers'), extend = _ref.extend, last = _ref.last; exports.Scope = Scope = (function() { Scope.root = null; function Scope(parent, expressions, method) { this.parent = parent; this.expressions = expressions; this.method = method; this.variables = [ { name: 'arguments', type: 'arguments' } ]; this.positions = {}; if (!this.parent) Scope.root = this; } Scope.prototype.add = function(name, type, immediate) { if (this.shared && !immediate) return this.parent.add(name, type, immediate); if (Object.prototype.hasOwnProperty.call(this.positions, name)) { return this.variables[this.positions[name]].type = type; } else { return this.positions[name] = this.variables.push({ name: name, type: type }) - 1; } }; Scope.prototype.find = function(name, options) { if (this.check(name, options)) return true; this.add(name, 'var'); return false; }; Scope.prototype.parameter = function(name) { if (this.shared && this.parent.check(name, true)) return; return this.add(name, 'param'); }; Scope.prototype.check = function(name, immediate) { var found, _ref2; found = !!this.type(name); if (found || immediate) return found; return !!((_ref2 = this.parent) != null ? _ref2.check(name) : void 0); }; Scope.prototype.temporary = function(name, index) { if (name.length > 1) { return '_' + name + (index > 1 ? index : ''); } else { return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a'); } }; Scope.prototype.type = function(name) { var v, _i, _len, _ref2; _ref2 = this.variables; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { v = _ref2[_i]; if (v.name === name) return v.type; } return null; }; Scope.prototype.freeVariable = function(name, reserve) { var index, temp; if (reserve == null) reserve = true; index = 0; while (this.check((temp = this.temporary(name, index)))) { index++; } if (reserve) this.add(temp, 'var', true); return temp; }; Scope.prototype.assign = function(name, value) { this.add(name, { value: value, assigned: true }, true); return this.hasAssignments = true; }; Scope.prototype.hasDeclarations = function() { return !!this.declaredVariables().length; }; Scope.prototype.declaredVariables = function() { var realVars, tempVars, v, _i, _len, _ref2; realVars = []; tempVars = []; _ref2 = this.variables; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { v = _ref2[_i]; if (v.type === 'var') { (v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name); } } return realVars.sort().concat(tempVars.sort()); }; Scope.prototype.assignedVariables = function() { var v, _i, _len, _ref2, _results; _ref2 = this.variables; _results = []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { v = _ref2[_i]; if (v.type.assigned) _results.push("" + v.name + " = " + v.type.value); } return _results; }; return Scope; })(); }).call(this);
tmad4000/ideamesh
node_modules/coffee-script/lib/coffee-script/scope.js
JavaScript
gpl-3.0
3,584
// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. function runner(f, expected) { for (var i = 0; i < 1000000; i++) { assertEquals(expected, f.call(this)); } } function test(n) { function MyFunction() { var result = n * 2 + arguments.length; return result; } runner(MyFunction, n * 2); } test(1); test(42); test(239);
chriskmanx/qmole
QMOLEDEV/node/deps/v8/test/mjsunit/closures.js
JavaScript
gpl-3.0
1,890
import fuzzy from 'fuzzy'; import { resolve } from 'redux-simple-promise'; import { FETCH_POSTS, FETCH_POST, FETCH_PAGE, FETCH_POSTS_CATEGORY, FETCH_POSTS_TAG } from '../actions/index'; const INITIAL_STATE = { all: {}, post: {}, page: {}, category: {} }; export default function (state = INITIAL_STATE, action) { switch (action.type) { case resolve(FETCH_POSTS): { const data = action.payload.data.entries; const payload = []; if (typeof action.meta.term !== 'undefined') { const options = { pre: '', post: '', extract(el) { return `${el.title} ${el.tags.map((tag) => `${tag} `)} `; } }; const results = fuzzy.filter(action.meta.term, data, options); results.map((el) => { if (el.score > 6) { payload.push(el.original); } }); return { ...state, all: payload }; } data.map((el) => { if (el.meta.type === 'post') { payload.push(el); } }); return { ...state, all: payload }; } case resolve(FETCH_POSTS_CATEGORY): { const data = action.payload.data.entries; const payload = []; data.map((el) => { if (el.meta.categories.includes(action.meta.category)) { payload.push(el); } }); return { ...state, category: payload }; } case resolve(FETCH_POSTS_TAG): { const data = action.payload.data.entries; const payload = []; data.map((el) => { if (el.tags.includes(action.meta.tag)) { payload.push(el); } }); return { ...state, category: payload }; } case resolve(FETCH_POST): { const data = action.payload.data.entries; let payload; data.map((el) => { if (el.title === action.meta.title) { payload = el; } }); return { ...state, post: payload }; } case resolve(FETCH_PAGE): { const data = action.payload.data; return { ...state, page: data }; } default: return state; } }
WDTAnyMore/WDTAnyMore.github.io
react-dev/reducers/reducer_posts.js
JavaScript
gpl-3.0
2,110
"use strict"; var SHOW_DATA = { "venue_name": "Merriweather Post Pavilion, Columbia, Maryland", "venue_id": 76, "show_date": "26th of Jun, 1984", "sets": [ {"set_title": "1st set", "encore": false, "songs": [ {"name": "Casey Jones", "length":"5:59", "trans":"/"}, {"name": "Feel Like A Stranger", "length":"7:32", "trans":"/"}, {"name": "Althea", "length":"8:00", "trans":"/"}, {"name": "Cassidy", "length":"6:08", "trans":"/"}, {"name": "Tennessee Jed", "length":"7:58", "trans":"/"}, {"name": "Looks Like Rain", "length":"6:32", "trans":"/"}, {"name": "Might As Well", "length":"4:47", "trans":"/"}, ]}, {"set_title": "2nd set", "encore": false, "songs": [ {"name": "China Cat Sunflower", "length":"3:32", "trans":">"}, {"name": "Weir's Segue", "length":"3:53", "trans":">"}, {"name": "I Know You Rider", "length":"5:37", "trans":"/"}, {"name": "Man Smart, Woman Smarter", "length":"6:30", "trans":"/"}, {"name": "He's Gone", "length":"12:02", "trans":">"}, {"name": "Improv", "length":"5:16", "trans":">"}, {"name": "Drums", "length":"9:49", "trans":">"}, {"name": "Space", "length":"10:01", "trans":">"}, {"name": "Don't Need Love", "length":"8:07", "trans":">"}, {"name": "Prelude", "length":"0:47", "trans":">"}, {"name": "Truckin'", "length":"5:11", "trans":">"}, {"name": "Truckin' Jam", "length":"1:21", "trans":">"}, {"name": "Improv", "length":"0:53", "trans":">"}, {"name": "Wang Dang Doodle", "length":"3:24", "trans":">"}, {"name": "Stella Blue", "length":"9:13", "trans":">"}, {"name": "Around & Around", "length":"3:44", "trans":"/"}, {"name": "Good Lovin'", "length":"7:28", "trans":"/"}, ]}, {"set_title": "3rd set", "encore": false, "songs": [ {"name": "Keep Your Day Job", "length":"4:14", "trans":"/"}, ]}, ], };
maximinus/grateful-dead-songs
gdsongs/static/data/shows/295.js
JavaScript
gpl-3.0
1,845
var __v=[ { "Id": 2257, "Panel": 1127, "Name": "刪除 舊 kernel", "Sort": 0, "Str": "" } ]
zuiwuchang/king-document
data/panels/1127.js
JavaScript
gpl-3.0
112
import { Template } from 'meteor/templating'; import { Academy } from '/imports/api/databasedriver.js'; import { Challenges } from '/imports/api/databasedriver.js'; import { Rooms } from '/imports/api/databasedriver.js'; import { Badges } from '/imports/api/databasedriver.js'; import { ROOMS_ACTIVE_ELEMENT_KEY } from '/client/management/rooms/TabRooms.js'; Template.NewRoomInfo.helpers({ badges(){ var badges = Badges.find({}).fetch(); return badges; }, teamBadge() { let roomType = "Team"; let roomBadges = Badges.find({'type': roomType }).fetch(); return roomBadges; } }); const TABLE_ROOMS_ACTIVE_TEMPLATE_NAME = "TableRoomInfo"; const NEW_ROOM_ACTIVE_TEMPLATE_NAME = "NewRoomInfo"; const EDIT_ROOM_ACTIVE_TEMPLATE_NAME = "EditRoomInfo"; Template.NewRoomInfo.events({ 'submit form' (event) { event.preventDefault(); let data = {}; let roomName = $("#roomName").val(); let roomDecision = $("#roomDecision").val(); let roomDescription = $("#roomDescription").val(); let roomBadge = $("#roomBadge").val(); data = { name: roomName, dailyDecision: roomDecision, description: roomDescription, badges: [{ badge: roomBadge }] }; //Modal.show('roomsInsertModal', this); Meteor.call("insertRoom", data, function(error, result) { if (error) { alert(error); } }); $("#addRoom")[0].reset(); Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME); }, 'click #nopRoom' (event){ event.preventDefault(); Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME); } });
LandOfKroilon/KroilonApp
client/management/rooms/newRoom/NewRoomInfo.js
JavaScript
gpl-3.0
1,694
import { createSelector } from 'reselect'; import { bindActionCreators, compose } from 'redux'; import { connect } from 'react-redux'; import { reduxForm } from 'redux-form'; import { requestContact, createContact, deleteContact, invalidate as invalidateContacts, } from '../../store/modules/contact'; import { requestUser } from '../../store/modules/user'; import { addAddressToContact, updateContact, getContact } from '../../modules/contact'; import { updateTagCollection as updateTagCollectionBase } from '../../modules/tags'; import { getNewContact } from '../../services/contact'; import { userSelector } from '../../modules/user'; import { withSearchParams } from '../../modules/routing'; import { contactValidation } from './services/contactValidation'; import Presenter from './presenter'; const contactIdSelector = (state, ownProps) => ownProps.match.params.contactId; const contactSelector = state => state.contact; const dirtyValuesSelector = createSelector( [ (state, ownProps) => ownProps.searchParams, ], ({ address, protocol, label }) => ({ address, protocol, label }) ); const mapStateToProps = createSelector( [userSelector, contactIdSelector, contactSelector, dirtyValuesSelector], (user, contactId, contactState, dirtyValues) => { const contact = contactState.contactsById[contactId] || getNewContact(); const { address, protocol, label } = dirtyValues; return { user, contactId, contact, form: `contact-${contactId || 'new'}`, // TODO: the following key fix this bug: https://github.com/erikras/redux-form/issues/2886#issuecomment-299426767 key: `contact-${contactId || 'new'}`, initialValues: { ...contact, ...(protocol ? addAddressToContact(contact, { address, protocol }) : {}), ...( label && label.length > 0 && (!contact.given_name || !contact.given_name.length) && (!contact.family_name || !contact.family_name.length) ? { given_name: label } : {} ), }, isFetching: contactState.isFetching, }; } ); const updateTagCollection = (i18n, { type, entity, tags: tagCollection, lazy, }) => async (dispatch, getState) => { const result = await dispatch(updateTagCollectionBase(i18n, { type, entity, tags: tagCollection, lazy, })); const userContact = userSelector(getState()).contact; if (userContact.contact_id === entity.contact_id) { dispatch(requestUser()); } return result; }; const mapDispatchToProps = dispatch => ({ ...bindActionCreators({ requestContact, getContact, updateContact, createContact, deleteContact, invalidateContacts, updateTagCollection, }, dispatch), onSubmit: values => Promise.resolve(values), }); export default compose( withSearchParams(), connect(mapStateToProps, mapDispatchToProps), reduxForm({ destroyOnUnmount: false, enableReinitialize: true, validate: contactValidation, }) )(Presenter);
CaliOpen/CaliOpen
src/frontend/web_application/src/scenes/Contact/index.js
JavaScript
gpl-3.0
2,978
'use strict'; var menu = angular.module('irc.views.menu', [ 'irc.networks', 'irc.views.menu.directives', ]); menu.controller( 'MenuCtrl', [ '$scope', '$timeout', '$state', 'networks', function MenuCtrl( $scope, $timeout, $state, networks) { $scope.networks = networks; var MainCtrl = $scope.MC; var activeRoom = null; function focus() { if (activeRoom) { activeRoom.focused = false; } activeRoom = MainCtrl.room; if (MainCtrl.room) { MainCtrl.room.focused = true; } if (MainCtrl.channel) { MainCtrl.network.collapsed = false; MainCtrl.channel.unreadCount = 0; } } $scope.$on('$stateChangeSuccess', function() { focus(); }); // Networks this.onNetClick = function(network) { if (!network.online) { network.connect(); $state.go('main.conversation', { network: network.name, channel: null }); return; } if (!network.focused) { $state.go('main.conversation', { network: network.name, channel: null }); } $scope.drawer.open = false; }; this.onNetContext = function(network) { $scope.networkDialog.network = network; $timeout(function() { $scope.networkDialog.open(); }); }; this.onNetworkDialogClosed = function() { $scope.networkDialog.network = null; }; this.onDelete = function() { var network = $scope.networkDialog.network; $scope.networkDialog.close(); $scope.confirmDialog.toBeDeleted = network; $scope.confirmDialog.open(); $scope.confirmDialog.onConfirm = function() { network.delete(); }; }; // Channels this.onChanClick = function(channel) { if (!channel.focused) { $state.go('main.conversation', { network: channel.network.name, channel: channel.name }); } if (channel.network.online) { channel.join(); $scope.drawer.open = false; } else { channel.network.connect().then(function() { channel.join(); $scope.drawer.open = false; }); } }; this.onChanContext = function(channel) { $scope.channelDialog.channel = channel; $scope.channelDialog.open(); }; this.onChannelDialogClosed = function() { $scope.channelDialog.channel = null; }; this.onRemove = function(channel) { channel.delete(); // One additional digest cycle, so it will notice the height change $timeout(); }; }]);
christopher-l/fxos-irc
app/views/menu/menu.js
JavaScript
gpl-3.0
2,535
import React from 'react'; // 参照界面,适合选中参照数据 export default class extends React.Component { }
saas-plat/saas-plat-appfx
src/components/widgets/md/Reference.js
JavaScript
gpl-3.0
123
Ext.define('Wif.setup.trend.trendnewEmploymentCard', { extend : 'Ext.form.Panel', project : null, title : 'Employment Trends', assocLuCbox : null, assocLuColIdx : 1, model : null, pendingChanges : null, sortKey : 'label', isEditing: true, isLoadingExisting: true, constructor : function(config) { var me = this; Ext.apply(this, config); var projectId = me.project.projectId; var isnew = me.project.isnew; me.isLoadingExisting = true; this.Output2 = []; this.gridfields = []; this.modelfields = []; this.modelfields.push("_id"); this.modelfields.push("item"); var gfield_id = { text : "_id", dataIndex : "_id", hidden: true }; var gfield = { text : "item", dataIndex : "item" }; this.gridfields.push(gfield_id); this.gridfields.push(gfield); var definition = this.project.getDefinition(); var rows =[]; var sortfields = []; var rows = definition.projections.sort(); _.log(me, 'projections', rows); for (var i = 0; i < rows.count(); i++) { sortfields.push(rows[i].label); } sortfields.sort(); for (var i = 0; i < sortfields.count(); i++) { var field = { text : sortfields[i], dataIndex : sortfields[i], editor: 'numberfield', type: 'number' }; this.gridfields.push(field); this.modelfields.push(sortfields[i]); } _.log(me, 'sortFields', sortfields); _.log(me, 'modelFields1', this.modelfields); _.log(me, 'gridFields', this.gridfields); var storeData = []; var sectors = definition.sectors; for (var i=0; i <sectors.length; i++) { var mjsonStr='{'; mjsonStr = mjsonStr + '\"_id\" :' + '\"' + sectors[i].label +'\",'; mjsonStr = mjsonStr + '\"item\" :' + '\"' + sectors[i].label +'\",'; for (var m = 2; m < me.modelfields.count(); m++) { var myear=me.modelfields[m]; mjsonStr = mjsonStr + '\"' + myear + '\"' + ':0,'; } mjsonStr = mjsonStr.substring(0,mjsonStr.length-1) + '}'; storeData.push(JSON.parse(mjsonStr)); } this.model = Ext.define('User', { extend: 'Ext.data.Model', fields: this.modelfields }); this.store = Ext.create('Ext.data.Store', { model: this.model, data : storeData }); this.grid = Ext.create('Ext.grid.Panel', { //title: 'Projection Population', selType: 'cellmodel', border : 0, margin : '0 5 5 5', store : this.store, height : 400, autoRender : true, columns : this.gridfields, flex: 1, viewConfig: { plugins: { ptype: 'gridviewdragdrop', dragText: 'Drag and drop to reorganize' } }, plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }) ] }); this.grid.reconfigure(this.store, this.gridfields); // var cmbData=[]; var cmbData ={}; var rows = definition.demographicTrends; // if (definition.demographicTrends2 == undefined) // { // definition.demographicTrends2= definition.demographicTrends; // } //this.Output2 = definition.demographicTrends; //var rows = this.Output2; var st='['; for (var i = 0; i< rows.length; i++) { st = st + '{\"label\":' + '\"' + rows[i].label+ '\"},'; } st = st.substring(0,st.length-1) + ']'; if (st == ']') { st = '[]'; } this.cmbStore = Ext.create('Ext.data.Store', { //autoLoad : true, fields: ['label'], data : JSON.parse(st) }); this.cmb=Ext.create('Ext.form.field.ComboBox', { extend : 'Aura.Util.RemoteComboBox', fieldLabel: 'Choose Trend', //width: 500, labelWidth: 200, store: this.cmbStore, //data : cmbData, queryMode: 'local', displayField: 'label', valueField: 'label', autoLoad : false, multiSelect : false, forceSelection: true, projectId : null, editable : true, allowBlank : false, emptyText : "Choose Trendo", //renderTo: Ext.getBody() listeners: { change: function (cb, newValue, oldValue, options) { console.log(newValue, oldValue); if (oldValue != undefined){ me.saveGrid(oldValue); } me.loadGrid(newValue); } } }); this.cmb.bindStore(this.cmbStore); var enumDistrictFieldSet = Ext.create('Ext.form.FieldSet', { columnWidth : 0.5, title : 'Trends', collapsible : true, margin : '15 5 5 0', defaults : { bodyPadding : 10, anchor : '90%' }, items : [this.cmb] }); this.items = [enumDistrictFieldSet,this.grid]; this.callParent(arguments); }, listeners : { activate : function() { _.log(this, 'activate'); //this.build(this.fillcombo()); this.build(); var definition = this.project.getDefinition(); this.Output2 = definition.demographicTrends; //this.Output2 = definition.demographicTrends; // if (definition.demographicTrends2 == undefined) // { // definition.demographicTrends2= definition.demographicTrends; // } // // this.Output2 = definition.demographicTrends2; //this.cmb.setValue(""); //this.build(function() { this.fillcombo; if (callback) { callback(); }}); } }, loadGrid : function(cmbValue) { var me = this, projectId = this.project.projectId; me.isLoadingExisting = true; var definition = this.project.getDefinition(); var storeDataNew = []; //if (definition.demographicTrends != undefined) if (this.Output2 != undefined) { //var mainrows = definition.demographicTrends; var mainrows = this.Output2; //for projection population var lsw1 = false; var storeData = []; var sectors = definition.sectors; for (var i=0; i <sectors.length; i++) { var mjson0Str='{'; mjson0Str = mjson0Str + '\"_id\" :' + '\"' + sectors[i].label +'\",'; mjson0Str = mjson0Str + '\"item\" :' + '\"' + sectors[i].label +'\",'; for (var m = 2; m < me.modelfields.count(); m++) { var myear=me.modelfields[m]; mjson0Str = mjson0Str + '\"' + myear + '\"' + ':0,'; } mjson0Str = mjson0Str.substring(0,mjson0Str.length-1) + '}'; storeData.push(JSON.parse(mjson0Str)); } this.store.removeAll(); this.grid.getSelectionModel().deselectAll(); this.store.loadData(storeData); this.grid.reconfigure(this.store, this.gridfields); this.store.each(function(record,idx){ val = record.get('_id'); var totalRows = mainrows.count(); for (var l = 0; l < totalRows; l++) { if (mainrows[l].label == cmbValue) { // var cnt0= mainrows[l].demographicData.count(); // for (var j = 0; j < cnt0; j++) // { // if (mainrows[l].demographicData[j]["@class"] == ".EmploymentDemographicData" ) // { var sectors = definition.sectors; for (var i=0; i <sectors.length; i++) { var jsonStr='{'; jsonStr = jsonStr + '\"_id\" :' + '\"' + sectors[i].label +'\",'; jsonStr = jsonStr + '\"item\" :' + '\"' + sectors[i].label +'\",'; if (val == sectors[i].label) { // if (lsw1 == false) // { for (var m = 0; m < me.modelfields.count(); m++) { var cnt01 = mainrows[l].demographicData.count(); for (var v = 0; v < cnt01; v++) { if (mainrows[l].demographicData[v]["@class"] == ".EmploymentDemographicData" ) { if ( me.modelfields[m] == mainrows[l].demographicData[v].projectionLabel) { var myear=me.modelfields[m]; if ( mainrows[l].demographicData[v].sectorLabel == sectors[i].label) { jsonStr = jsonStr + '\"' + myear + '\"' + ':' + mainrows[l].demographicData[v].employees + ','; } }//end if ( me.modelfields[m] }//end if (mainrows[l] }//end for (var v = 0 }//end for (var m = 0 jsonStr = jsonStr.substring(0,jsonStr.length-1) + '}'; storeDataNew.push(JSON.parse(jsonStr)); lsw1 = true; //}//end if lsw }//end if (sectors[i].label) }// end for sectors //}//end if (mainrows[l].demographicData[j]["@class"] //} //end for (var j = 0 }//end if (mainrows[l].label == cmbValue) }//end for (var l = 0) }); //end this.store }//end if definition.demographicTrends if (storeDataNew.length>0) { this.store.removeAll(); this.grid.getSelectionModel().deselectAll(); this.store.loadData(storeDataNew); this.grid.reconfigure(this.store, this.gridfields); } return true; }, //end build function saveGrid : function(cmbValue) { var me = this, projectId = this.project.projectId; me.isLoadingExisting = true; var definition = this.project.getDefinition(); var storeDataNew = []; var demographicData = []; //saving projection population var jsonStrTotal=''; for (var m = 2; m < this.modelfields.count(); m++) { // jsonStr='{'; // jsonStr = jsonStr + '\"@class\" :' + '\".EmploymentDemographicData\",'; // jsonStr = jsonStr + '\"projectionLabel\" :\"' +this.modelfields[m] + '\",'; var i = 0; var sectors = definition.sectors; for (var z=0; z <sectors.length; z++) { jsonStr='{'; jsonStr = jsonStr + '\"@class\" :' + '\".EmploymentDemographicData\",'; jsonStr = jsonStr + '\"projectionLabel\" :\"' +this.modelfields[m] + '\",'; var slbl = sectors[z].label; this.store.each(function(record,idx){ i = i + 1; //var x= '\"' +record.get('_id') + '\"'; if (record.get('_id') == slbl) { jsonStr = jsonStr + '\"sectorLabel\" :\"' +slbl + '\",'; var x1 = ':' + 0 +','; if (record.get(me.modelfields[m]) =='' || record.get(me.modelfields[m]) ==null) { x1 = ':' + 0 +','; } else { x1 = ':' + record.get(me.modelfields[m]) +','; } jsonStr = jsonStr + '\"employees\"' + x1; } }); jsonStr = jsonStr.substring(0,jsonStr.length-1); jsonStr = jsonStr + '}'; jsonStrTotal = jsonStrTotal + jsonStr + ','; //jsonStr = jsonStr.substring(0,jsonStr.length-1) + '}'; demographicData.push(JSON.parse(jsonStr)); } } var demographicTrends = []; jsonStrTotal = jsonStrTotal.substring(0,jsonStrTotal.length-1); var strNew = '[{'; //strNew = strNew + '\"label\" :' + '\"' + me.cmb.getValue() + '\",'; strNew = strNew + '\"label\" :' + '\"' + cmbValue + '\",'; var strOld = '\"' + 'demographicData' + '\"' + ':[' + jsonStrTotal +']'; strNew = strNew + strOld + '}]'; demographicTrends.push(JSON.parse(strNew)); for (var l = 0; l < this.Output2.count(); l++) { // if (this.Output2[l].label == cmbValue) // { // //this.Output2[l].demographicData.add = JSON.parse('[' + jsonStrTotal + ']'); // for(var t=0; t<this.Output2[l].demographicData.count(); t++) // { // if (this.Output2[l].demographicData[t]["@class"] == ".EmploymentDemographicData") // { // this.Output2[l].demographicData.removeAt(t); // } // } // } //this.Output2[l].demographicData.add(JSON.parse('[' + jsonStrTotal + ']')); //// this.Output2[l].demographicData = JSON.parse('[' + jsonStrTotal + ']'); } var emp =[]; emp.push(JSON.parse('[' + jsonStrTotal + ']')); for (var l = 0; l < this.Output2.count(); l++) { if (this.Output2[l].label == cmbValue) { ///this.Output[l].demographicData = JSON.parse('[' + jsonStrTotal + ']'); } if (this.Output2[l].label == cmbValue) { //this.Output[l].demographicData.add = JSON.parse('[' + jsonStrTotal + ']'); for(var t=0; t<this.Output2[l].demographicData.count(); t++) { if (this.Output2[l].demographicData[t]["@class"] == ".EmploymentDemographicData") { ////this.Output[l].demographicData.removeAt(t); } else if (this.Output2[l].demographicData[t]["@class"] == ".ResidentialDemographicData") { emp[0].push(this.Output2[l].demographicData[t]); } } } //////this.Output[l].demographicData.add(JSON.parse('[' + jsonStrTotal + ']')); } for (var l = 0; l < this.Output2.count(); l++) { if (this.Output2[l].label == cmbValue) { this.Output2[l].demographicData = emp[0]; } } var ccc=0; return true; }, //end build build : function() { var me = this, projectId = this.project.projectId; me.isLoadingExisting = true; var definition = this.project.getDefinition(); if (definition.demographicTrends != undefined) //if(this.Output2 != undefined) { var rows = definition.demographicTrends; //var rows = this.Output2; var st='['; for (var i = 0; i< rows.length; i++) { st = st + '{\"label\":' + '\"' + rows[i].label+ '\"},'; } st = st.substring(0,st.length-1) + ']'; var arr=[]; arr.push(JSON.parse(st)); this.cmbStore.removeAll(); this.cmbStore.load(JSON.parse(st)); this.cmb.store.loadData(JSON.parse(st),false); this.cmb.bindStore(this.cmbStore); } return true; }, //end build function validate : function(callback) { var me = this, gridValid = true; me.store.each(function(record) { if (!record.isValid()) { _.log(this, 'validate', 'record is not valid'); gridValid = false; } }); if (!gridValid) { Ext.Msg.alert('Status', 'All fields should have values!'); return false; } if (me.cmb.getValue() != undefined){ me.saveGrid(me.cmb.getValue()); } var definition = me.project.getDefinition(); Ext.merge(definition, { demographicTrends:this.Output2 }); me.project.setDefinition(definition); _.log(this, 'validate', _.translate3(this.store.data.items, me.sectorTranslators), me.project.getDefinition()); if (callback) { _.log(this, 'callback'); callback(); } return true; } });
AURIN/online-whatif-ui
src/main/webapp/js/wif/setup/trend/trendnewEmploymentCard.js
JavaScript
gpl-3.0
17,630
const Clutter = imports.gi.Clutter; const Lang = imports.lang; const ModalDialog = imports.ui.modalDialog; const Signals = imports.signals; const St = imports.gi.St; const Gettext = imports.gettext; const _ = Gettext.domain('gnome-shell-extensions-scriptproxies').gettext; const EditProxyDialog = new Lang.Class({ Name: 'EditProxyDialog', Extends: ModalDialog.ModalDialog, _init: function(callback, action) { this.callback = callback; this.action = action; this.parent({ styleClass: 'prompt-dialog' }); let label, buttons; if (this.action == 'add') { buttons = [{ label: _('Cancel'), action: Lang.bind(this, this._onCancelButton), key: Clutter.Escape }, { label: _('Add proxy'), action: Lang.bind(this, this._addButton) }]; label = new St.Label({ style_class: 'edit-proxy-dialog-label', text: _('Enter the name for the new proxy') }); } else if (this.action == 'edit') { buttons = [{ label: _('Cancel'), action: Lang.bind(this, this._onCancelButton), key: Clutter.Escape }, { label: _('Modify script'), action: Lang.bind(this, this._modifyButton) }, { label: _('Rename'), action: Lang.bind(this, this._renameButton) }]; label = new St.Label({ style_class: 'edit-proxy-dialog-label', text: _('Modify the proxy script.') + '\n' + _('Or rename it (leave blank to remove the proxy).') }); } else { // this should be this.action == 'editor' buttons = [{ label: _('Cancel'), action: Lang.bind(this, this._onCancelButton), key: Clutter.Escape }, { label: _('OK'), action: Lang.bind(this, this._onSetEditorButton) }]; label = new St.Label({ style_class: 'edit-proxy-dialog-label', text: _('To edit your proxy script,') + '\n' + _('please provide the binary name of your text editor.') }); } this.contentLayout.add(label, { y_align: St.Align.START }); let entry = new St.Entry({ style_class: 'edit-proxy-dialog-entry' }); entry.label_actor = label; this._entryText = entry.clutter_text; this.contentLayout.add(entry, { y_align: St.Align.START }); this.setInitialKeyFocus(this._entryText); this.setButtons(buttons); this._entryText.connect('key-press-event', Lang.bind(this, function(o, e) { let symbol = e.get_key_symbol(); if (symbol == Clutter.Return || symbol == Clutter.KP_Enter) { if (this.action == 'add') this._addButton(); else if (this.action == 'edit') this._renameButton(); else this._onSetEditorButton(); } })); }, close: function() { this.parent(); }, _onCancelButton: function() { this.close(); }, _addButton: function() { this.callback(this._entryText.get_text(), 'new'); this.close(); }, _modifyButton: function() { this.callback(this._entryText.get_text(), 'modify'); this.close(); }, _renameButton: function() { this.callback(this._entryText.get_text(), 'rename'); this.close(); }, _onSetEditorButton: function() { this.callback(this._entryText.get_text()); this.close(); }, open: function(initialText) { if (initialText === null) { this._entryText.set_text(''); } else { this._entryText.set_text(initialText); } this.parent(); } }); Signals.addSignalMethods(EditProxyDialog.prototype);
Eimji/gnome-shell-extension-scriptproxies
editProxyDialog.js
JavaScript
gpl-3.0
4,159
var nodeSass = require('node-sass'), fs = require('fs'); module.exports = class Sass { constructor(config){ this.config = config; if (this.config.compileAtBootup) { this.compile(); } if (this.config.watch) { this.startWatch(); } } get timeTaken(){ return parseInt(process.hrtime(this.timeBegun)[1] / 1000000) + 'ms'; } writeOutputFile(css) { let dst = this.config.arguments.outFile; fs.writeFile(dst, css, (err)=>{ err ? console.warn(this.getFormattedTime(), 'Error writing compiled SASS to outFile:', err) : console.log(this.getFormattedTime(), 'SASS re-compiled in', this.timeTaken); }); } compile() { this.timeBegun = process.hrtime(); nodeSass.render(this.config.arguments, (err, result)=>{ err ? console.warn(this.getFormattedTime(), 'Error compiling SASS:', err) : this.writeOutputFile(result.css.toString()); }); } startWatch() { let throttleId; fs.watch(this.config.arguments.watchFolder, { recursive: true }, (eventType, filename) => { if (throttleId) { clearTimeout(throttleId); } throttleId = setTimeout(() => { throttleId = null; this.compile(); }, 50); }); } getFormattedTime(){ let d = new Date(); return d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(); } }
DennisMajvall/magnets
modules/sass.js
JavaScript
gpl-3.0
1,379
import React, { Component } from "react"; import PropTypes from "prop-types"; import classnames from "classnames"; import { Components, registerComponent } from "@reactioncommerce/reaction-components"; class CardHeader extends Component { static defaultProps = { actAsExpander: false, expandable: false }; static propTypes = { actAsExpander: PropTypes.bool, children: PropTypes.node, expandOnSwitchOn: PropTypes.bool, expanded: PropTypes.bool, i18nKeyTitle: PropTypes.string, icon: PropTypes.string, imageView: PropTypes.node, onClick: PropTypes.func, onSwitchChange: PropTypes.func, showSwitch: PropTypes.bool, switchName: PropTypes.string, switchOn: PropTypes.bool, title: PropTypes.string }; handleClick = (event) => { event.preventDefault(); if (typeof this.props.onClick === "function") { this.props.onClick(event); } } handleSwitchChange = (event, isChecked, name) => { if (this.props.expandOnSwitchOn && this.props.actAsExpander && this.props.expanded === false && isChecked === true) { this.handleClick(event); } if (typeof this.props.onSwitchChange === "function") { this.props.onSwitchChange(event, isChecked, name); } } renderTitle() { if (this.props.title) { return ( <Components.CardTitle i18nKeyTitle={this.props.i18nKeyTitle} title={this.props.title} /> ); } return null; } renderImage() { if (this.props.icon) { return ( <div className="image"> <Components.Icon icon={this.props.icon} /> </div> ); } if (this.props.imageView) { return ( <div className="image"> {this.props.imageView} </div> ); } return null; } renderDisclsoureArrow() { const expanderClassName = classnames({ rui: true, expander: true, open: this.props.expanded }); return ( <div className={expanderClassName}> <Components.IconButton icon="fa fa-angle-down" bezelStyle="outline" style={{ borderColor: "#dddddd" }} onClick={this.handleClick} /> </div> ); } renderChildren() { if (this.props.showSwitch) { return ( <Components.Switch checked={this.props.switchOn} name={this.props.switchName} onChange={this.handleSwitchChange} /> ); } return this.props.children; } render() { const baseClassName = classnames({ "rui": true, "panel-heading": true, "card-header": true, "expandable": this.props.actAsExpander }); if (this.props.actAsExpander) { return ( <div className={baseClassName}> <div className="content-view" onClick={this.handleClick}> {this.renderImage()} {this.renderTitle()} </div> <div className="action-view"> {this.renderChildren()} </div> {this.renderDisclsoureArrow()} </div> ); } return ( <div className={baseClassName}> <div className="content-view"> {this.renderTitle()} </div> <div className="action-view"> {this.props.children} </div> </div> ); } } registerComponent("CardHeader", CardHeader); export default CardHeader;
xxbooking/reaction
imports/plugins/core/ui/client/components/cards/cardHeader.js
JavaScript
gpl-3.0
3,437
/** * Created by levchenko on 5/12/14. */ function Style(styles) { this.styles = styles; this.applyStyles = function (object) { for(var key in this.styles) { if(this.getStyleProperty(key) === false) { object.setAttribute('style', object.getAttribute('style') + key + ':' + this.styles[key] + ';'); } else { object.style[this.getStyleProperty(key)] = this.styles[key]; } } }; this.getStyleProperty = function (cssProperty) { var jsProperty = ''; var partOfProperty = cssProperty.split('-'); if(cssProperty.charAt(0) == '-') { return false; } for(var key = 0; key<partOfProperty.length; key++) { if(key == 0) { jsProperty = partOfProperty[key]; continue; } jsProperty += partOfProperty[key].charAt(0).toUpperCase() + partOfProperty[key].substr(1, partOfProperty[key].length-1);; } return jsProperty; } } Element.prototype.css = function (options) { var style = (options instanceof Style) ? options : new Style(options); style.applyStyles(this); return style; }
XNoval/jsSolutions
base/Style.js
JavaScript
gpl-3.0
1,213
var db = require('../db'); var User = db.model('User', { username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true, select: false }, created: { type: Date, default: Date.now }, color: { type: String }, active: { type: Boolean, default: true, select: false }, scores: [], resetToken: { type: String }, resetTokenValid: { type: Date } }); module.exports = User;
MICSTI/magellan
models/user.js
JavaScript
gpl-3.0
617
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains some common methods available to all log appenders. */ qx.Class.define("qx.log.appender.Util", { statics : { /** * Converts a single log entry to HTML * * @signature function(entry) * @param entry {Map} The entry to process * @return {void} */ toHtml : function(entry) { var output = []; var item, msg, sub, list; output.push("<span class='offset'>", this.formatOffset(entry.offset, 6), "</span> "); if (entry.object) { var obj = entry.win.qx.core.ObjectRegistry.fromHashCode(entry.object); if (obj) { output.push("<span class='object' title='Object instance with hash code: " + obj.$$hash + "'>", obj.classname, "[" , obj.$$hash, "]</span>: "); } } else if (entry.clazz) { output.push("<span class='object'>" + entry.clazz.classname, "</span>: "); } var items = entry.items; for (var i=0, il=items.length; i<il; i++) { item = items[i]; msg = item.text; if (msg instanceof Array) { var list = []; for (var j=0, jl=msg.length; j<jl; j++) { sub = msg[j]; if (typeof sub === "string") { list.push("<span>" + this.escapeHTML(sub) + "</span>"); } else if (sub.key) { list.push("<span class='type-key'>" + sub.key + "</span>:<span class='type-" + sub.type + "'>" + this.escapeHTML(sub.text) + "</span>"); } else { list.push("<span class='type-" + sub.type + "'>" + this.escapeHTML(sub.text) + "</span>"); } } output.push("<span class='type-" + item.type + "'>"); if (item.type === "map") { output.push("{", list.join(", "), "}"); } else { output.push("[", list.join(", "), "]"); } output.push("</span>"); } else { output.push("<span class='type-" + item.type + "'>" + this.escapeHTML(msg) + "</span> "); } } var wrapper = document.createElement("DIV"); wrapper.innerHTML = output.join(""); wrapper.className = "level-" + entry.level; return wrapper; }, /** * Formats a numeric time offset to 6 characters. * * @param offset {Integer} Current offset value * @param length {Integer?6} Refine the length * @return {String} Padded string */ formatOffset : function(offset, length) { var str = offset.toString(); var diff = (length||6) - str.length; var pad = ""; for (var i=0; i<diff; i++) { pad += "0"; } return pad+str; }, /** * Escapes the HTML in the given value * * @param value {String} value to escape * @return {String} escaped value */ escapeHTML : function(value) { return String(value).replace(/[<>&"']/g, this.__escapeHTMLReplace); }, /** * Internal replacement helper for HTML escape. * * @param ch {String} Single item to replace. * @return {String} Replaced item */ __escapeHTMLReplace : function(ch) { var map = { "<" : "&lt;", ">" : "&gt;", "&" : "&amp;", "'" : "&#39;", '"' : "&quot;" }; return map[ch] || "?"; }, /** * Converts a single log entry to plain text * * @param entry {Map} The entry to process * @return {String} the formatted log entry */ toText : function(entry) { return this.toTextArray(entry).join(" "); }, /** * Converts a single log entry to an array of plain text * * @param entry {Map} The entry to process * @return {Array} Argument list ready message array. */ toTextArray : function(entry) { var output = []; output.push(this.formatOffset(entry.offset, 6)); if (entry.object) { var obj = entry.win.qx.core.ObjectRegistry.fromHashCode(entry.object); if (obj) { output.push(obj.classname + "[" + obj.$$hash + "]:"); } } else if (entry.clazz) { output.push(entry.clazz.classname + ":"); } var items = entry.items; var item, msg; for (var i=0, il=items.length; i<il; i++) { item = items[i]; msg = item.text; if (item.trace && item.trace.length > 0) { if (typeof(this.FORMAT_STACK) == "function") { qx.log.Logger.deprecatedConstantWarning(qx.log.appender.Util, "FORMAT_STACK", "Use qx.dev.StackTrace.FORMAT_STACKTRACE instead"); msg += "\n" + this.FORMAT_STACK(item.trace); } else { msg += "\n" + item.trace; } } if (msg instanceof Array) { var list = []; for (var j=0, jl=msg.length; j<jl; j++) { list.push(msg[j].text); } if (item.type === "map") { output.push("{", list.join(", "), "}"); } else { output.push("[", list.join(", "), "]"); } } else { output.push(msg); } } return output; } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.log.appender.Util) #require(qx.bom.client.Html) -- defer calls Logger.register which calls Native.process which needs "html.console" implementation ************************************************************************ */ /** * Processes the incoming log entry and displays it by means of the native * logging capabilities of the client. * * Supported browsers: * * Firefox <4 using FireBug (if available). * * Firefox >=4 using the Web Console. * * WebKit browsers using the Web Inspector/Developer Tools. * * Internet Explorer 8+ using the F12 Developer Tools. * * Opera >=10.60 using either the Error Console or Dragonfly * * Currently unsupported browsers: * * Opera <10.60 */ qx.Class.define("qx.log.appender.Native", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Processes a single log entry * * @param entry {Map} The entry to process */ process : function(entry) { if (qx.core.Environment.get("html.console")) { // Firefox 4's Web Console doesn't support "debug" var level = console[entry.level] ? entry.level : "log"; if (console[level]) { var args = qx.log.appender.Util.toText(entry); console[level](args); } } } }, /* ***************************************************************************** DEFER ***************************************************************************** */ defer : function(statics) { qx.log.Logger.register(statics); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.event.handler.Window) #require(qx.event.handler.Keyboard) ************************************************************************ */ /** * Feature-rich console appender for the qooxdoo logging system. * * Creates a small inline element which is placed in the top-right corner * of the window. Prints all messages with a nice color highlighting. * * * Allows user command inputs. * * Command history enabled by default (Keyboard up/down arrows). * * Lazy creation on first open. * * Clearing the console using a button. * * Display of offset (time after loading) of each message * * Supports keyboard shortcuts F7 or Ctrl+D to toggle the visibility */ qx.Class.define("qx.log.appender.Console", { statics : { /* --------------------------------------------------------------------------- INITIALIZATION AND SHUTDOWN --------------------------------------------------------------------------- */ /** * Initializes the console, building HTML and pushing last * log messages to the output window. * * @return {void} */ init : function() { // Build style sheet content var style = [ '.qxconsole{z-index:10000;width:600px;height:300px;top:0px;right:0px;position:absolute;border-left:1px solid black;color:black;border-bottom:1px solid black;color:black;font-family:Consolas,Monaco,monospace;font-size:11px;line-height:1.2;}', '.qxconsole .control{background:#cdcdcd;border-bottom:1px solid black;padding:4px 8px;}', '.qxconsole .control a{text-decoration:none;color:black;}', '.qxconsole .messages{background:white;height:100%;width:100%;overflow:auto;}', '.qxconsole .messages div{padding:0px 4px;}', '.qxconsole .messages .user-command{color:blue}', '.qxconsole .messages .user-result{background:white}', '.qxconsole .messages .user-error{background:#FFE2D5}', '.qxconsole .messages .level-debug{background:white}', '.qxconsole .messages .level-info{background:#DEEDFA}', '.qxconsole .messages .level-warn{background:#FFF7D5}', '.qxconsole .messages .level-error{background:#FFE2D5}', '.qxconsole .messages .level-user{background:#E3EFE9}', '.qxconsole .messages .type-string{color:black;font-weight:normal;}', '.qxconsole .messages .type-number{color:#155791;font-weight:normal;}', '.qxconsole .messages .type-boolean{color:#15BC91;font-weight:normal;}', '.qxconsole .messages .type-array{color:#CC3E8A;font-weight:bold;}', '.qxconsole .messages .type-map{color:#CC3E8A;font-weight:bold;}', '.qxconsole .messages .type-key{color:#565656;font-style:italic}', '.qxconsole .messages .type-class{color:#5F3E8A;font-weight:bold}', '.qxconsole .messages .type-instance{color:#565656;font-weight:bold}', '.qxconsole .messages .type-stringify{color:#565656;font-weight:bold}', '.qxconsole .command{background:white;padding:2px 4px;border-top:1px solid black;}', '.qxconsole .command input{width:100%;border:0 none;font-family:Consolas,Monaco,monospace;font-size:11px;line-height:1.2;}', '.qxconsole .command input:focus{outline:none;}' ]; // Include stylesheet qx.bom.Stylesheet.createElement(style.join("")); // Build markup var markup = [ '<div class="qxconsole">', '<div class="control"><a href="javascript:qx.log.appender.Console.clear()">Clear</a> | <a href="javascript:qx.log.appender.Console.toggle()">Hide</a></div>', '<div class="messages">', '</div>', '<div class="command">', '<input type="text"/>', '</div>', '</div>' ]; // Insert HTML to access DOM node var wrapper = document.createElement("DIV"); wrapper.innerHTML = markup.join(""); var main = wrapper.firstChild; document.body.appendChild(wrapper.firstChild); // Make important DOM nodes available this.__main = main; this.__log = main.childNodes[1]; this.__cmd = main.childNodes[2].firstChild; // Correct height of messages frame this.__onResize(); // Finally register to log engine qx.log.Logger.register(this); // Register to object manager qx.core.ObjectRegistry.register(this); }, /** * Used by the object registry to dispose this instance e.g. remove listeners etc. * * @return {void} */ dispose : function() { qx.event.Registration.removeListener(document.documentElement, "keypress", this.__onKeyPress, this); qx.log.Logger.unregister(this); }, /* --------------------------------------------------------------------------- INSERT & CLEAR --------------------------------------------------------------------------- */ /** * Clears the current console output. * * @return {void} */ clear : function() { // Remove all messages this.__log.innerHTML = ""; }, /** * Processes a single log entry * * @signature function(entry) * @param entry {Map} The entry to process * @return {void} */ process : function(entry) { // Append new content this.__log.appendChild(qx.log.appender.Util.toHtml(entry)); // Scroll down this.__scrollDown(); }, /** * Automatically scroll down to the last line */ __scrollDown : function() { this.__log.scrollTop = this.__log.scrollHeight; }, /* --------------------------------------------------------------------------- VISIBILITY TOGGLING --------------------------------------------------------------------------- */ /** {Boolean} Flag to store last visibility status */ __visible : true, /** * Toggles the visibility of the console between visible and hidden. * * @return {void} */ toggle : function() { if (!this.__main) { this.init(); } else if (this.__main.style.display == "none") { this.show(); } else { this.__main.style.display = "none"; } }, /** * Shows the console. * * @return {void} */ show : function() { if (!this.__main) { this.init(); } else { this.__main.style.display = "block"; this.__log.scrollTop = this.__log.scrollHeight; } }, /* --------------------------------------------------------------------------- COMMAND LINE SUPPORT --------------------------------------------------------------------------- */ /** {Array} List of all previous commands. */ __history : [], /** * Executes the currently given command * * @return {void} */ execute : function() { var value = this.__cmd.value; if (value == "") { return; } if (value == "clear") { return this.clear(); } var command = document.createElement("div"); command.innerHTML = qx.log.appender.Util.escapeHTML(">>> " + value); command.className = "user-command"; this.__history.push(value); this.__lastCommand = this.__history.length; this.__log.appendChild(command); this.__scrollDown(); try { var ret = window.eval(value); } catch (ex) { qx.log.Logger.error(ex); } if (ret !== undefined) { qx.log.Logger.debug(ret); } }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Event handler for resize listener * * @param e {Event} Event object * @return {void} */ __onResize : function(e) { this.__log.style.height = (this.__main.clientHeight - this.__main.firstChild.offsetHeight - this.__main.lastChild.offsetHeight) + "px"; }, /** * Event handler for keydown listener * * @param e {Event} Event object * @return {void} */ __onKeyPress : function(e) { var iden = e.getKeyIdentifier(); // Console toggling if ((iden == "F7") || (iden == "D" && e.isCtrlPressed())) { this.toggle(); e.preventDefault(); } // Not yet created if (!this.__main) { return; } // Active element not in console if (!qx.dom.Hierarchy.contains(this.__main, e.getTarget())) { return; } // Command execution if (iden == "Enter" && this.__cmd.value != "") { this.execute(); this.__cmd.value = ""; } // History managment if (iden == "Up" || iden == "Down") { this.__lastCommand += iden == "Up" ? -1 : 1; this.__lastCommand = Math.min(Math.max(0, this.__lastCommand), this.__history.length); var entry = this.__history[this.__lastCommand]; this.__cmd.value = entry || ""; this.__cmd.select(); } } }, /* ***************************************************************************** DEFER ***************************************************************************** */ defer : function(statics) { qx.event.Registration.addListener(document.documentElement, "keypress", statics.__onKeyPress, statics); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin used for the bubbling events. If you want to use this in your own model * classes, be sure that every property will call the * {@link #_applyEventPropagation} function on every change. */ qx.Mixin.define("qx.data.marshal.MEventBubbling", { events : { /** * The change event which will be fired on every change in the model no * matter what property changes. This event bubbles so the root model will * fire a change event on every change of its children properties too. * * Note that properties are required to call * {@link #_applyEventPropagation} on apply for changes to be tracked as * desired. It is already taken care of that properties created with the * {@link qx.data.marshal.Json} marshaler call this method. * * The data will contain a map with the following three keys * <li>value: The new value of the property</li> * <li>old: The old value of the property.</li> * <li>name: The name of the property changed including its parent * properties separated by dots.</li> * <li>item: The item which has the changed property.</li> * Due to that, the <code>getOldData</code> method will always return null * because the old data is contained in the map. */ "changeBubble": "qx.event.type.Data" }, members : { /** * Apply function for every property created with the * {@link qx.data.marshal.Json} marshaler. It fires and * {@link #changeBubble} event on every change. It also adds the chaining * listener if possible which is necessary for the bubbling of the events. * * @param value {var} The new value of the property. * @param old {var} The old value of the property. * @param name {String} The name of the changed property. */ _applyEventPropagation : function(value, old, name) { this.fireDataEvent("changeBubble", { value: value, name: name, old: old, item: this }); this._registerEventChaining(value, old, name); }, /** * Registers for the given parameters the changeBubble listener, if * possible. It also removes the old listener, if an old item with * a changeBubble event is given. * * @param value {var} The new value of the property. * @param old {var} The old value of the property. * @param name {String} The name of the changed property. */ _registerEventChaining : function(value, old, name) { // if the child supports chaining if ((value instanceof qx.core.Object) && qx.Class.hasMixin(value.constructor, qx.data.marshal.MEventBubbling) ) { // create the listener var listener = qx.lang.Function.bind( this.__changePropertyListener, this, name ); // add the listener var id = value.addListener("changeBubble", listener, this); var listeners = value.getUserData("idBubble-" + this.$$hash); if (listeners == null) { listeners = []; value.setUserData("idBubble-" + this.$$hash, listeners); } listeners.push(id); } // if an old value is given, remove the old listener if possible if (old != null && old.getUserData && old.getUserData("idBubble-" + this.$$hash) != null) { var listeners = old.getUserData("idBubble-" + this.$$hash); for (var i = 0; i < listeners.length; i++) { old.removeListenerById(listeners[i]); } old.setUserData("idBubble-" + this.$$hash, null); } }, /** * Listener responsible for formating the name and firing the change event * for the changed property. * * @param name {String} The name of the former properties. * @param e {qx.event.type.Data} The date event fired by the property * change. */ __changePropertyListener : function(name, e) { var data = e.getData(); var value = data.value; var old = data.old; // if the target is an array if (qx.Class.hasInterface(e.getTarget().constructor, qx.data.IListData)) { if (data.name.indexOf) { var dotIndex = data.name.indexOf(".") != -1 ? data.name.indexOf(".") : data.name.length; var bracketIndex = data.name.indexOf("[") != -1 ? data.name.indexOf("[") : data.name.length; // braktes in the first spot is ok [BUG #5985] if (bracketIndex == 0) { var newName = name + data.name; } else if (dotIndex < bracketIndex) { var index = data.name.substring(0, dotIndex); var rest = data.name.substring(dotIndex + 1, data.name.length); if (rest[0] != "[") { rest = "." + rest; } var newName = name + "[" + index + "]" + rest; } else if (bracketIndex < dotIndex) { var index = data.name.substring(0, bracketIndex); var rest = data.name.substring(bracketIndex, data.name.length); var newName = name + "[" + index + "]" + rest; } else { var newName = name + "[" + data.name + "]"; } } else { var newName = name + "[" + data.name + "]"; } // if the target is not an array } else { // special case for array as first element of the chain [BUG #5985] if (parseInt(name) == name && name !== "") { name = "[" + name + "]"; } var newName = name + "." + data.name; } this.fireDataEvent( "changeBubble", { value: value, name: newName, old: old, item: data.item || e.getTarget() } ); } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The data array is a special array used in the data binding context of * qooxdoo. It does not extend the native array of JavaScript but its a wrapper * for it. All the native methods are included in the implementation and it * also fires events if the content or the length of the array changes in * any way. Also the <code>.length</code> property is available on the array. */ qx.Class.define("qx.data.Array", { extend : qx.core.Object, include : qx.data.marshal.MEventBubbling, implement : [qx.data.IListData], /** * Creates a new instance of an array. * * @param param {var} The parameter can be some types.<br/> * Without a parameter a new blank array will be created.<br/> * If there is more than one parameter is given, the parameter will be * added directly to the new array.<br/> * If the parameter is a number, a new Array with the given length will be * created.<br/> * If the parameter is a JavaScript array, a new array containing the given * elements will be created. */ construct : function(param) { this.base(arguments); // if no argument is given if (param == undefined) { this.__array = []; // check for elements (create the array) } else if (arguments.length > 1) { // create an empty array and go through every argument and push it this.__array = []; for (var i = 0; i < arguments.length; i++) { this.__array.push(arguments[i]); } // check for a number (length) } else if (typeof param == "number") { this.__array = new Array(param); // check for an array itself } else if (param instanceof Array) { this.__array = qx.lang.Array.clone(param); // error case } else { this.__array = []; this.dispose(); throw new Error("Type of the parameter not supported!"); } // propagate changes for (var i=0; i<this.__array.length; i++) { this._applyEventPropagation(this.__array[i], null, i); } // update the length at startup this.__updateLength(); // work against the console printout of the array if (qx.core.Environment.get("qx.debug")) { this[0] = "Please use 'toArray()' to see the content."; } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Flag to set the dispose behavior of the array. If the property is set to * <code>true</code>, the array will dispose its content on dispose, too. */ autoDisposeItems : { check : "Boolean", init : false } }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * The change event which will be fired if there is a change in the array. * The data contains a map with three key value pairs: * <li>start: The start index of the change.</li> * <li>end: The end index of the change.</li> * <li>type: The type of the change as a String. This can be 'add', * 'remove' or 'order'</li> * <li>items: The items which has been changed (as a JavaScript array).</li> */ "change" : "qx.event.type.Data", /** * The changeLength event will be fired every time the length of the * array changes. */ "changeLength": "qx.event.type.Data" }, members : { // private members __array : null, /** * Concatenates the current and the given array into a new one. * * @param array {Array} The javaScript array which should be concatenated * to the current array. * * @return {qx.data.Array} A new array containing the values of both former * arrays. */ concat: function(array) { if (array) { var newArray = this.__array.concat(array); } else { var newArray = this.__array.concat(); } return new qx.data.Array(newArray); }, /** * Returns the array as a string using the given connector string to * connect the values. * * @param connector {String} the string which should be used to past in * between of the array values. * * @return {String} The array as a string. */ join: function(connector) { return this.__array.join(connector); }, /** * Removes and returns the last element of the array. * An change event will be fired. * * @return {var} The last element of the array. */ pop: function() { var item = this.__array.pop(); this.__updateLength(); // remove the possible added event listener this._registerEventChaining(null, item, this.length - 1); // fire change bubble event this.fireDataEvent("changeBubble", { value: [], name: this.length + "", old: [item], item: this }); this.fireDataEvent("change", { start: this.length - 1, end: this.length - 1, type: "remove", items: [item] }, null ); return item; }, /** * Adds an element at the end of the array. * * @param varargs {var} Multiple elements. Every element will be added to * the end of the array. An change event will be fired. * * @return {Number} The new length of the array. */ push: function(varargs) { for (var i = 0; i < arguments.length; i++) { this.__array.push(arguments[i]); this.__updateLength(); // apply to every pushed item an event listener for the bubbling this._registerEventChaining(arguments[i], null, this.length - 1); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [arguments[i]], name: (this.length - 1) + "", old: [], item: this }); // fire change event this.fireDataEvent("change", { start: this.length - 1, end: this.length - 1, type: "add", items: [arguments[i]] }, null ); } return this.length; }, /** * Reverses the order of the array. An change event will be fired. */ reverse: function() { // ignore on empty arrays if (this.length == 0) { return; } var oldArray = this.__array.concat(); this.__array.reverse(); this.fireDataEvent("change", {start: 0, end: this.length - 1, type: "order", items: null}, null ); // fire change bubbles event this.fireDataEvent("changeBubble", { value: this.__array, name: "0-" + (this.__array.length - 1), old: oldArray, item: this }); }, /** * Removes the first element of the array and returns it. An change event * will be fired. * * @return {var} the former first element. */ shift: function() { // ignore on empty arrays if (this.length == 0) { return; } var item = this.__array.shift(); this.__updateLength(); // remove the possible added event listener this._registerEventChaining(null, item, this.length -1); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [], name: "0", old: [item], item: this }); // fire change event this.fireDataEvent("change", { start: 0, end: this.length -1, type: "remove", items: [item] }, null ); return item; }, /** * Returns a new array based on the range specified by the parameters. * * @param from {Number} The start index. * @param to {Number?null} The end index. If omitted, slice extracts to the * end of the array. * * @return {qx.data.Array} A new array containing the given range of values. */ slice: function(from, to) { return new qx.data.Array(this.__array.slice(from, to)); }, /** * Method to remove and add new elements to the array. For every remove or * add an event will be fired. * * @param startIndex {Integer} The index where the splice should start * @param amount {Integer} Defines number of elements which will be removed * at the given position. * @param varargs {var} All following parameters will be added at the given * position to the array. * @return {qx.data.Array} An data array containing the removed elements. * Keep in to dispose this one, even if you don't use it! */ splice: function(startIndex, amount, varargs) { // store the old length var oldLength = this.__array.length; // invoke the slice on the array var returnArray = this.__array.splice.apply(this.__array, arguments); // fire a change event for the length if (this.__array.length != oldLength) { this.__updateLength(); } // fire an event for the change var removed = amount > 0; var added = arguments.length > 2; var items = null; if (removed || added) { if (this.__array.length > oldLength) { var type = "add"; items = qx.lang.Array.fromArguments(arguments, 2); } else if (this.__array.length < oldLength) { var type = "remove"; items = returnArray; } else { var type = "order"; } this.fireDataEvent("change", { start: startIndex, end: this.length - 1, type: type, items: items }, null ); } // add listeners for (var i = 2; i < arguments.length; i++) { this._registerEventChaining(arguments[i], null, startIndex + i); } // fire the changeBubble event var value = []; for (var i=2; i < arguments.length; i++) { value[i-2] = arguments[i]; }; var endIndex = (startIndex + Math.max(arguments.length - 3 , amount - 1)); var name = startIndex == endIndex ? endIndex : startIndex + "-" + endIndex; this.fireDataEvent("changeBubble", { value: value, name: name + "", old: returnArray, item: this }); // remove the listeners for (var i = 0; i < returnArray.length; i++) { this._registerEventChaining(null, returnArray[i], i); } return (new qx.data.Array(returnArray)); }, /** * Sorts the array. If a function is given, this will be used to * compare the items. <code>changeBubble</code> event will only be fired, * if sorting result differs from original array. * * @param func {Function} A compare function comparing two parameters and * should return a number. */ sort: function(func) { // ignore if the array is empty if (this.length == 0) { return; } var oldArray = this.__array.concat(); this.__array.sort.apply(this.__array, arguments); // prevent changeBubble event if nothing has been changed if (qx.lang.Array.equals(this.__array, oldArray) === true){ return; } this.fireDataEvent("change", {start: 0, end: this.length - 1, type: "order", items: null}, null ); // fire change bubbles event this.fireDataEvent("changeBubble", { value: this.__array, name: "0-" + (this.length - 1), old: oldArray, item: this }); }, /** * Adds the given items to the beginning of the array. For every element, * a change event will be fired. * * @param varargs {var} As many elements as you want to add to the beginning. */ unshift: function(varargs) { for (var i = arguments.length - 1; i >= 0; i--) { this.__array.unshift(arguments[i]) this.__updateLength(); // apply to every pushed item an event listener for the bubbling this._registerEventChaining(arguments[i], null, 0); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [this.__array[0]], name: "0", old: [this.__array[1]], item: this }); // fire change event this.fireDataEvent("change", { start: 0, end: this.length - 1, type: "add", items: [arguments[i]] }, null ); } return this.length; }, /** * Returns the list data as native array. Beware of the fact that the * internal representation will be returnd and any manipulation of that * can cause a misbehavior of the array. This method should only be used for * debugging purposes. * * @return {Array} The native array. */ toArray: function() { return this.__array; }, /** * Replacement function for the getting of the array value. * array[0] should be array.getItem(0). * * @param index {Number} The index requested of the array element. * * @return {var} The element at the given index. */ getItem: function(index) { return this.__array[index]; }, /** * Replacement function for the setting of an array value. * array[0] = "a" should be array.setItem(0, "a"). * A change event will be fired if the value changes. Setting the same * value again will not lead to a change event. * * @param index {Number} The index of the array element. * @param item {var} The new item to set. */ setItem: function(index, item) { var oldItem = this.__array[index]; // ignore settings of already set items [BUG #4106] if (oldItem === item) { return; } this.__array[index] = item; // set an event listener for the bubbling this._registerEventChaining(item, oldItem, index); // only update the length if its changed if (this.length != this.__array.length) { this.__updateLength(); } // fire change bubbles event this.fireDataEvent("changeBubble", { value: [item], name: index + "", old: [oldItem], item: this }); // fire change event this.fireDataEvent("change", { start: index, end: index, type: "add", items: [item] }, null ); }, /** * This method returns the current length stored under .length on each * array. * * @return {Number} The current length of the array. */ getLength: function() { return this.length; }, /** * Returns the index of the item in the array. If the item is not in the * array, -1 will be returned. * * @param item {var} The item of which the index should be returned. * @return {Number} The Index of the given item. */ indexOf: function(item) { return this.__array.indexOf(item); }, /** * Returns the toString of the original Array * @return {String} The array as a string. */ toString: function() { if (this.__array != null) { return this.__array.toString(); } return ""; }, /* --------------------------------------------------------------------------- IMPLEMENTATION OF THE QX.LANG.ARRAY METHODS --------------------------------------------------------------------------- */ /** * Check if the given item is in the current array. * * @param item {var} The item which is possibly in the array. * @return {boolean} true, if the array contains the given item. */ contains: function(item) { return this.__array.indexOf(item) !== -1; }, /** * Return a copy of the given arr * * @return {qx.data.Array} copy of this */ copy : function() { return this.concat(); }, /** * Insert an element at a given position. * * @param index {Integer} Position where to insert the item. * @param item {var} The element to insert. */ insertAt : function(index, item) { this.splice(index, 0, item).dispose(); }, /** * Insert an item into the array before a given item. * * @param before {var} Insert item before this object. * @param item {var} The item to be inserted. */ insertBefore : function(before, item) { var index = this.indexOf(before); if (index == -1) { this.push(item); } else { this.splice(index, 0, item).dispose(); } }, /** * Insert an element into the array after a given item. * * @param after {var} Insert item after this object. * @param item {var} Object to be inserted. */ insertAfter : function(after, item) { var index = this.indexOf(after); if (index == -1 || index == (this.length - 1)) { this.push(item); } else { this.splice(index + 1, 0, item).dispose(); } }, /** * Remove an element from the array at the given index. * * @param index {Integer} Index of the item to be removed. * @return {var} The removed item. */ removeAt : function(index) { var returnArray = this.splice(index, 1); var item = returnArray.getItem(0); returnArray.dispose(); return item; }, /** * Remove all elements from the array. * * @return {Array} A native array containing the removed elements. */ removeAll : function() { // remove all possible added event listeners for (var i = 0; i < this.__array.length; i++) { this._registerEventChaining(null, this.__array[i], i); } // ignore if array is empty if (this.getLength() == 0) { return; } // store the old data var oldLength = this.getLength(); var items = this.__array.concat(); // change the length this.__array.length = 0; this.__updateLength(); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [], name: "0-" + (oldLength - 1), old: items, item: this }); // fire the change event this.fireDataEvent("change", { start: 0, end: oldLength - 1, type: "remove", items: items }, null ); return items; }, /** * Append the items of the given array. * * @param array {Array|qx.data.IListData} The items of this array will * be appended. * @throws An exception if the second argument is not an array. */ append : function(array) { // qooxdoo array support if (array instanceof qx.data.Array) { array = array.toArray(); } // this check is important because opera throws an uncatchable error if // apply is called without an array as argument. if (qx.core.Environment.get("qx.debug")) { qx.core.Assert.assertArray(array, "The parameter must be an array."); } Array.prototype.push.apply(this.__array, array); // add a listener to the new items for (var i = 0; i < array.length; i++) { this._registerEventChaining(array[i], null, this.__array.length + i); } var oldLength = this.length; this.__updateLength(); // fire change bubbles var name = oldLength == (this.length-1) ? oldLength : oldLength + "-" + (this.length-1); this.fireDataEvent("changeBubble", { value: array, name: name + "", old: [], item: this }); // fire the change event this.fireDataEvent("change", { start: oldLength, end: this.length - 1, type: "add", items: array }, null ); }, /** * Remove the given item. * * @param item {var} Item to be removed from the array. * @return {var} The removed item. */ remove : function(item) { var index = this.indexOf(item); if (index != -1) { this.splice(index, 1).dispose(); return item; } }, /** * Check whether the given array has the same content as this. * Checks only the equality of the arrays' content. * * @param array {qx.data.Array} The array to check. * @return {Boolean} Whether the two arrays are equal. */ equals : function(array) { if (this.length !== array.length) { return false; } for (var i = 0; i < this.length; i++) { if (this.getItem(i) !== array.getItem(i)) { return false; } } return true; }, /** * Returns the sum of all values in the array. Supports * numeric values only. * * @return {Number} The sum of all values. */ sum : function() { var result = 0; for (var i = 0; i < this.length; i++) { result += this.getItem(i); } return result; }, /** * Returns the highest value in the given array. * Supports numeric values only. * * @return {Number | null} The highest of all values or undefined if the * array is empty. */ max : function() { var result = this.getItem(0); for (var i = 1; i < this.length; i++) { if (this.getItem(i) > result) { result = this.getItem(i); } } return result === undefined ? null : result; }, /** * Returns the lowest value in the array. Supports * numeric values only. * * @return {Number | null} The lowest of all values or undefined * if the array is empty. */ min : function() { var result = this.getItem(0); for (var i = 1; i < this.length; i++) { if (this.getItem(i) < result) { result = this.getItem(i); } } return result === undefined ? null : result; }, /** * Invokes the given function for every item in the array. * * @param callback {Function} The function which will be call for every * item in the array. It will be invoked with three parameters: * the item, the index and the array itself. * @param context {var} The context in which the callback will be invoked. */ forEach : function(callback, context) { for (var i = 0; i < this.__array.length; i++) { callback.call(context, this.__array[i], i, this); } }, /* --------------------------------------------------------------------------- INTERNAL HELPERS --------------------------------------------------------------------------- */ /** * Internal function which updates the length property of the array. * Every time the length will be updated, a {@link #changeLength} data * event will be fired. */ __updateLength: function() { var oldLength = this.length; this.length = this.__array.length; this.fireDataEvent("changeLength", this.length, oldLength); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { for (var i = 0; i < this.__array.length; i++) { var item = this.__array[i]; this._applyEventPropagation(null, item, i); // dispose the items on auto dispose if (this.isAutoDisposeItems() && item && item instanceof qx.core.Object) { item.dispose(); } } this.__array = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A vertical box layout. * * The vertical box layout lays out widgets in a vertical column, from top * to bottom. * * *Features* * * * Minimum and maximum dimensions * * Prioritized growing/shrinking (flex) * * Margins (with vertical collapsing) * * Auto sizing (ignoring percent values) * * Percent heights (not relevant for size hint) * * Alignment (child property {@link qx.ui.core.LayoutItem#alignY} is ignored) * * Vertical spacing (collapsed with margins) * * Reversed children layout (from last to first) * * Horizontal children stretching (respecting size hints) * * *Item Properties* * * <ul> * <li><strong>flex</strong> <em>(Integer)</em>: The flexibility of a layout item determines how the container * distributes remaining empty space among its children. If items are made * flexible, they can grow or shrink accordingly. Their relative flex values * determine how the items are being resized, i.e. the larger the flex ratio * of two items, the larger the resizing of the first item compared to the * second. * * If there is only one flex item in a layout container, its actual flex * value is not relevant. To disallow items to become flexible, set the * flex value to zero. * </li> * <li><strong>height</strong> <em>(String)</em>: Allows to define a percent * height for the item. The height in percent, if specified, is used instead * of the height defined by the size hint. The minimum and maximum height still * takes care of the element's limits. It has no influence on the layout's * size hint. Percent values are mostly useful for widgets which are sized by * the outer hierarchy. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.VBox(); * layout.setSpacing(4); // apply spacing * * var container = new qx.ui.container.Composite(layout); * * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * </pre> * * *External Documentation* * * See <a href='http://manual.qooxdoo.org/${qxversion}/pages/layout/box.html'>extended documentation</a> * and links to demos for this layout. * */ qx.Class.define("qx.ui.layout.VBox", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacing {Integer?0} The spacing between child widgets {@link #spacing}. * @param alignY {String?"top"} Vertical alignment of the whole children * block {@link #alignY}. * @param separator {Decorator} A separator to render between the items */ construct : function(spacing, alignY, separator) { this.base(arguments); if (spacing) { this.setSpacing(spacing); } if (alignY) { this.setAlignY(alignY); } if (separator) { this.setSeparator(separator); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Vertical alignment of the whole children block. The vertical * alignment of the child is completely ignored in VBoxes ( * {@link qx.ui.core.LayoutItem#alignY}). */ alignY : { check : [ "top", "middle", "bottom" ], init : "top", apply : "_applyLayoutChange" }, /** * Horizontal alignment of each child. Can be overridden through * {@link qx.ui.core.LayoutItem#alignX}. */ alignX : { check : [ "left", "center", "right" ], init : "left", apply : "_applyLayoutChange" }, /** Vertical spacing between two children */ spacing : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** Separator lines to use between the objects */ separator : { check : "Decorator", nullable : true, apply : "_applyLayoutChange" }, /** Whether the actual children list should be laid out in reversed order. */ reversed : { check : "Boolean", init : false, apply : "_applyReversed" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __heights : null, __flexs : null, __enableFlex : null, __children : null, /* --------------------------------------------------------------------------- HELPER METHODS --------------------------------------------------------------------------- */ // property apply _applyReversed : function() { // easiest way is to invalidate the cache this._invalidChildrenCache = true; // call normal layout change this._applyLayoutChange(); }, /** * Rebuilds caches for flex and percent layout properties */ __rebuildCache : function() { var children = this._getLayoutChildren(); var length = children.length; var enableFlex = false; var reuse = this.__heights && this.__heights.length != length && this.__flexs && this.__heights; var props; // Sparse array (keep old one if lengths has not been modified) var heights = reuse ? this.__heights : new Array(length); var flexs = reuse ? this.__flexs : new Array(length); // Reverse support if (this.getReversed()) { children = children.concat().reverse(); } // Loop through children to preparse values for (var i=0; i<length; i++) { props = children[i].getLayoutProperties(); if (props.height != null) { heights[i] = parseFloat(props.height) / 100; } if (props.flex != null) { flexs[i] = props.flex; enableFlex = true; } else { // reset (in case the index of the children changed: BUG #3131) flexs[i] = 0; } } // Store data if (!reuse) { this.__heights = heights; this.__flexs = flexs; } this.__enableFlex = enableFlex this.__children = children; // Clear invalidation marker delete this._invalidChildrenCache; }, /* --------------------------------------------------------------------------- LAYOUT INTERFACE --------------------------------------------------------------------------- */ // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { this.assert(name === "flex" || name === "height", "The property '"+name+"' is not supported by the VBox layout!"); if (name =="height") { this.assertMatch(value, qx.ui.layout.Util.PERCENT_VALUE); } else { // flex this.assertNumber(value); this.assert(value >= 0); } }, "false" : null }), // overridden renderLayout : function(availWidth, availHeight) { // Rebuild flex/height caches if (this._invalidChildrenCache) { this.__rebuildCache(); } // Cache children var children = this.__children; var length = children.length; var util = qx.ui.layout.Util; // Compute gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeVerticalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeVerticalGaps(children, spacing, true); } // First run to cache children data and compute allocated height var i, child, height, percent; var heights = []; var allocatedHeight = gaps; for (i=0; i<length; i+=1) { percent = this.__heights[i]; height = percent != null ? Math.floor((availHeight - gaps) * percent) : children[i].getSizeHint().height; heights.push(height); allocatedHeight += height; } // Flex support (growing/shrinking) if (this.__enableFlex && allocatedHeight != availHeight) { var flexibles = {}; var flex, offset; for (i=0; i<length; i+=1) { flex = this.__flexs[i]; if (flex > 0) { hint = children[i].getSizeHint(); flexibles[i]= { min : hint.minHeight, value : heights[i], max : hint.maxHeight, flex : flex }; } } var result = util.computeFlexOffsets(flexibles, availHeight, allocatedHeight); for (i in result) { offset = result[i].offset; heights[i] += offset; allocatedHeight += offset; } } // Start with top coordinate var top = children[0].getMarginTop(); // Alignment support if (allocatedHeight < availHeight && this.getAlignY() != "top") { top = availHeight - allocatedHeight; if (this.getAlignY() === "middle") { top = Math.round(top / 2); } } // Layouting children var hint, left, width, height, marginBottom, marginLeft, marginRight; // Pre configure separators this._clearSeparators(); // Compute separator height if (separator) { var separatorInsets = qx.theme.manager.Decoration.getInstance().resolve(separator).getInsets(); var separatorHeight = separatorInsets.top + separatorInsets.bottom; } // Render children and separators for (i=0; i<length; i+=1) { child = children[i]; height = heights[i]; hint = child.getSizeHint(); marginLeft = child.getMarginLeft(); marginRight = child.getMarginRight(); // Find usable width width = Math.max(hint.minWidth, Math.min(availWidth-marginLeft-marginRight, hint.maxWidth)); // Respect horizontal alignment left = util.computeHorizontalAlignOffset(child.getAlignX()||this.getAlignX(), width, availWidth, marginLeft, marginRight); // Add collapsed margin if (i > 0) { // Whether a separator has been configured if (separator) { // add margin of last child and spacing top += marginBottom + spacing; // then render the separator at this position this._renderSeparator(separator, { top : top, left : 0, height : separatorHeight, width : availWidth }); // and finally add the size of the separator, the spacing (again) and the top margin top += separatorHeight + spacing + child.getMarginTop(); } else { // Support margin collapsing when no separator is defined top += util.collapseMargins(spacing, marginBottom, child.getMarginTop()); } } // Layout child child.renderLayout(left, top, width, height); // Add height top += height; // Remember bottom margin (for collapsing) marginBottom = child.getMarginBottom(); } }, // overridden _computeSizeHint : function() { // Rebuild flex/height caches if (this._invalidChildrenCache) { this.__rebuildCache(); } var util = qx.ui.layout.Util; var children = this.__children; // Initialize var minHeight=0, height=0, percentMinHeight=0; var minWidth=0, width=0; var child, hint, margin; // Iterate over children for (var i=0, l=children.length; i<l; i+=1) { child = children[i]; hint = child.getSizeHint(); // Sum up heights height += hint.height; // Detect if child is shrinkable or has percent height and update minHeight var flex = this.__flexs[i]; var percent = this.__heights[i]; if (flex) { minHeight += hint.minHeight; } else if (percent) { percentMinHeight = Math.max(percentMinHeight, Math.round(hint.minHeight/percent)); } else { minHeight += hint.height; } // Build horizontal margin sum margin = child.getMarginLeft() + child.getMarginRight(); // Find biggest width if ((hint.width+margin) > width) { width = hint.width + margin; } // Find biggest minWidth if ((hint.minWidth+margin) > minWidth) { minWidth = hint.minWidth + margin; } } minHeight += percentMinHeight; // Respect gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeVerticalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeVerticalGaps(children, spacing, true); } // Return hint return { minHeight : minHeight + gaps, height : height + gaps, minWidth : minWidth, width : width }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__heights = this.__flexs = this.__children = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The form object is responsible for managing form items. For that, it takes * advantage of two existing qooxdoo classes. * The {@link qx.ui.form.Resetter} is used for resetting and the * {@link qx.ui.form.validation.Manager} is used for all validation purposes. * * The view code can be found in the used renderer ({@link qx.ui.form.renderer}). */ qx.Class.define("qx.ui.form.Form", { extend : qx.core.Object, construct : function() { this.base(arguments); this.__groups = []; this._buttons = []; this._buttonOptions = []; this._validationManager = new qx.ui.form.validation.Manager(); this._resetter = this._createResetter(); }, members : { __groups : null, _validationManager : null, _groupCounter : 0, _buttons : null, _buttonOptions : null, _resetter : null, /* --------------------------------------------------------------------------- ADD --------------------------------------------------------------------------- */ /** * Adds a form item to the form including its internal * {@link qx.ui.form.validation.Manager} and {@link qx.ui.form.Resetter}. * * *Hint:* The order of all add calls represent the order in the layout. * * @param item {qx.ui.form.IForm} A supported form item. * @param label {String} The string, which should be used as label. * @param validator {Function | qx.ui.form.validation.AsyncValidator ? null} * The validator which is used by the validation * {@link qx.ui.form.validation.Manager}. * @param name {String?null} The name which is used by the data binding * controller {@link qx.data.controller.Form}. * @param validatorContext {var?null} The context of the validator. * @param options {Map?null} An additional map containin custom data which * will be available in your form renderer specific to the added item. */ add : function(item, label, validator, name, validatorContext, options) { if (this.__isFirstAdd()) { this.__groups.push({ title: null, items: [], labels: [], names: [], options: [], headerOptions: {} }); } // save the given arguments this.__groups[this._groupCounter].items.push(item); this.__groups[this._groupCounter].labels.push(label); this.__groups[this._groupCounter].options.push(options); // if no name is given, use the label without not working character if (name == null) { name = label.replace( /\s+|&|-|\+|\*|\/|\||!|\.|,|:|\?|;|~|%|\{|\}|\(|\)|\[|\]|<|>|=|\^|@|\\/g, "" ); } this.__groups[this._groupCounter].names.push(name); // add the item to the validation manager this._validationManager.add(item, validator, validatorContext); // add the item to the reset manager this._resetter.add(item); }, /** * Adds a group header to the form. * * *Hint:* The order of all add calls represent the order in the layout. * * @param title {String} The title of the group header. * @param options {Map?null} A special set of custom data which will be * given to the renderer. */ addGroupHeader : function(title, options) { if (!this.__isFirstAdd()) { this._groupCounter++; } this.__groups.push({ title: title, items: [], labels: [], names: [], options: [], headerOptions: options }); }, /** * Adds a button to the form. * * *Hint:* The order of all add calls represent the order in the layout. * * @param button {qx.ui.form.Button} The button to add. * @param options {Map?null} An additional map containin custom data which * will be available in your form renderer specific to the added button. */ addButton : function(button, options) { this._buttons.push(button); this._buttonOptions.push(options || null); }, /** * Returns whether something has already been added. * * @return {Boolean} true, if nothing has been added jet. */ __isFirstAdd : function() { return this.__groups.length === 0; }, /* --------------------------------------------------------------------------- RESET SUPPORT --------------------------------------------------------------------------- */ /** * Resets the form. This means reseting all form items and the validation. */ reset : function() { this._resetter.reset(); this._validationManager.reset(); }, /** * Redefines the values used for resetting. It calls * {@link qx.ui.form.Resetter#redefine} to get that. */ redefineResetter : function() { this._resetter.redefine(); }, /* --------------------------------------------------------------------------- VALIDATION --------------------------------------------------------------------------- */ /** * Validates the form using the * {@link qx.ui.form.validation.Manager#validate} method. * * @return {Boolean | null} The validation result. */ validate : function() { return this._validationManager.validate(); }, /** * Returns the internally used validation manager. If you want to do some * enhanced validation tasks, you need to use the validation manager. * * @return {qx.ui.form.validation.Manager} The used manager. */ getValidationManager : function() { return this._validationManager; }, /* --------------------------------------------------------------------------- RENDERER SUPPORT --------------------------------------------------------------------------- */ /** * Accessor method for the renderer which returns all added items in a * array containing a map of all items: * {title: title, items: [], labels: [], names: []} * * @return {Array} An array containing all necessary data for the renderer. * @internal */ getGroups : function() { return this.__groups; }, /** * Accessor method for the renderer which returns all added buttons in an * array. * @return {Array} An array containing all added buttons. * @internal */ getButtons : function() { return this._buttons; }, /** * Accessor method for the renderer which returns all added options for * the buttons in an array. * @return {Array} An array containing all added options for the buttons. * @internal */ getButtonOptions : function() { return this._buttonOptions; }, /* --------------------------------------------------------------------------- INTERNAL --------------------------------------------------------------------------- */ /** * Returns all added items as a map. * * @return {Map} A map containing for every item an entry with its name. * * @internal */ getItems : function() { var items = {}; // go threw all groups for (var i = 0; i < this.__groups.length; i++) { var group = this.__groups[i]; // get all items for (var j = 0; j < group.names.length; j++) { var name = group.names[j]; items[name] = group.items[j]; } } return items; }, /** * Creates and returns the used resetter class. * * @return {qx.ui.form.Resetter} the resetter class. * * @internal */ _createResetter : function() { return new qx.ui.form.Resetter(); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // holding references to widgets --> must set to null this.__groups = this._buttons = this._buttonOptions = null; this._validationManager.dispose(); this._resetter.dispose(); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This validation manager is responsible for validation of forms. */ qx.Class.define("qx.ui.form.validation.Manager", { extend : qx.core.Object, construct : function() { this.base(arguments); // storage for all form items this.__formItems = []; // storage for all results of async validation calls this.__asyncResults = {}; // set the default required field message this.setRequiredFieldMessage(qx.locale.Manager.tr("This field is required")); }, events : { /** * Change event for the valid state. */ "changeValid" : "qx.event.type.Data", /** * Signals that the validation is done. This is not needed on synchronous * validation (validation is done right after the call) but very important * in the case an asynchronous validator will be used. */ "complete" : "qx.event.type.Event" }, properties : { /** * {Function | AsyncValidator} * The validator of the form itself. You can set a function (for * synchronous validation) or a {@link qx.ui.form.validation.AsyncValidator}. * In both cases, the function can have all added form items as first * argument and the manager as a second argument. The manager should be used * to set the {@link #invalidMessage}. * * Keep in mind that the validator is optional if you don't need the * validation in the context of the whole form. */ validator : { check : "value instanceof Function || qx.Class.isSubClassOf(value.constructor, qx.ui.form.validation.AsyncValidator)", init : null, nullable : true }, /** * The invalid message should store the message why the form validation * failed. It will be added to the array returned by * {@link #getInvalidMessages}. */ invalidMessage : { check : "String", init: "" }, /** * This message will be shown if a required field is empty and no individual * {@link qx.ui.form.MForm#requiredInvalidMessage} is given. */ requiredFieldMessage : { check : "String", init : "" }, /** * The context for the form validation. */ context : { nullable : true } }, members : { __formItems : null, __valid : null, __asyncResults : null, __syncValid : null, /** * Add a form item to the validation manager. * * The form item has to implement at least two interfaces: * <ol> * <li>The {@link qx.ui.form.IForm} Interface</li> * <li>One of the following interfaces: * <ul> * <li>{@link qx.ui.form.IBooleanForm}</li> * <li>{@link qx.ui.form.IColorForm}</li> * <li>{@link qx.ui.form.IDateForm}</li> * <li>{@link qx.ui.form.INumberForm}</li> * <li>{@link qx.ui.form.IStringForm}</li> * </ul> * </li> * </ol> * The validator can be a synchronous or asynchronous validator. In * both cases the validator can either returns a boolean or fire an * {@link qx.core.ValidationError}. For synchronous validation, a plain * JavaScript function should be used. For all asynchronous validations, * a {@link qx.ui.form.validation.AsyncValidator} is needed to wrap the * plain function. * * @param formItem {qx.ui.core.Widget} The form item to add. * @param validator {Function | qx.ui.form.validation.AsyncValidator} * The validator. * @param context {var?null} The context of the validator. */ add: function(formItem, validator, context) { // check for the form API if (!this.__supportsInvalid(formItem)) { throw new Error("Added widget not supported."); } // check for the data type if (this.__supportsSingleSelection(formItem) && !formItem.getValue) { // check for a validator if (validator != null) { throw new Error("Widgets supporting selection can only be validated " + "in the form validator"); } } var dataEntry = { item : formItem, validator : validator, valid : null, context : context }; this.__formItems.push(dataEntry); }, /** * Remove a form item from the validation manager. * * @param formItem {qx.ui.core.Widget} The form item to remove. * @return {qx.ui.core.Widget?null} The removed form item or * <code>null</code> if the item could not be found. */ remove : function(formItem) { var items = this.__formItems; for (var i = 0, len = items.length; i < len; i++) { if (formItem === items[i].item) { items.splice(i, 1); return formItem; } } return null; }, /** * Returns registered form items from the validation manager. * * @return {Array} The form items which will be validated. */ getItems : function() { var items = []; for (var i=0; i < this.__formItems.length; i++) { items.push(this.__formItems[i].item); }; return items; }, /** * Invokes the validation. If only synchronous validators are set, the * result of the whole validation is available at the end of the method * and can be returned. If an asynchronous validator is set, the result * is still unknown at the end of this method so nothing will be returned. * In both cases, a {@link #complete} event will be fired if the validation * has ended. The result of the validation can then be accessed with the * {@link #getValid} method. * * @return {Boolean | void} The validation result, if available. */ validate : function() { var valid = true; this.__syncValid = true; // collaboration of all synchronous validations var items = []; // check all validators for the added form items for (var i = 0; i < this.__formItems.length; i++) { var formItem = this.__formItems[i].item; var validator = this.__formItems[i].validator; // store the items in case of form validation items.push(formItem); // ignore all form items without a validator if (validator == null) { // check for the required property var validatorResult = this.__validateRequired(formItem); valid = valid && validatorResult; this.__syncValid = validatorResult && this.__syncValid; continue; } var validatorResult = this.__validateItem( this.__formItems[i], formItem.getValue() ); // keep that order to ensure that null is returned on async cases valid = validatorResult && valid; if (validatorResult != null) { this.__syncValid = validatorResult && this.__syncValid; } } // check the form validator (be sure to invoke it even if the form // items are already false, so keep the order!) var formValid = this.__validateForm(items); if (qx.lang.Type.isBoolean(formValid)) { this.__syncValid = formValid && this.__syncValid; } valid = formValid && valid; this.__setValid(valid); if (qx.lang.Object.isEmpty(this.__asyncResults)) { this.fireEvent("complete"); } return valid; }, /** * Checks if the form item is required. If so, the value is checked * and the result will be returned. If the form item is not required, true * will be returned. * * @param formItem {qx.ui.core.Widget} The form item to check. */ __validateRequired : function(formItem) { if (formItem.getRequired()) { // if its a widget supporting the selection if (this.__supportsSingleSelection(formItem)) { var validatorResult = !!formItem.getSelection()[0]; // otherwise, a value should be supplied } else { var validatorResult = !!formItem.getValue(); } formItem.setValid(validatorResult); var individualMessage = formItem.getRequiredInvalidMessage(); var message = individualMessage ? individualMessage : this.getRequiredFieldMessage(); formItem.setInvalidMessage(message); return validatorResult; } return true; }, /** * Validates a form item. This method handles the differences of * synchronous and asynchronous validation and returns the result of the * validation if possible (synchronous cases). If the validation is * asynchronous, null will be returned. * * @param dataEntry {Object} The map stored in {@link #add} * @param value {var} The currently set value */ __validateItem : function(dataEntry, value) { var formItem = dataEntry.item; var context = dataEntry.context; var validator = dataEntry.validator; // check for asynchronous validation if (this.__isAsyncValidator(validator)) { // used to check if all async validations are done this.__asyncResults[formItem.toHashCode()] = null; validator.validate(formItem, formItem.getValue(), this, context); return null; } var validatorResult = null; try { var validatorResult = validator.call(context || this, value, formItem); if (validatorResult === undefined) { validatorResult = true; } } catch (e) { if (e instanceof qx.core.ValidationError) { validatorResult = false; if (e.message && e.message != qx.type.BaseError.DEFAULTMESSAGE) { var invalidMessage = e.message; } else { var invalidMessage = e.getComment(); } formItem.setInvalidMessage(invalidMessage); } else { throw e; } } formItem.setValid(validatorResult); dataEntry.valid = validatorResult; return validatorResult; }, /** * Validates the form. It checks for asynchronous validation and handles * the differences to synchronous validation. If no form validator is given, * true will be returned. If a synchronous validator is given, the * validation result will be returned. In asynchronous cases, null will be * returned cause the result is not available. * * @param items {qx.ui.core.Widget[]} An array of all form items. * @return {Boolean|null} description */ __validateForm: function(items) { var formValidator = this.getValidator(); var context = this.getContext() || this; if (formValidator == null) { return true; } // reset the invalidMessage this.setInvalidMessage(""); if (this.__isAsyncValidator(formValidator)) { this.__asyncResults[this.toHashCode()] = null; formValidator.validateForm(items, this, context); return null; } try { var formValid = formValidator.call(context, items, this); if (formValid === undefined) { formValid = true; } } catch (e) { if (e instanceof qx.core.ValidationError) { formValid = false; if (e.message && e.message != qx.type.BaseError.DEFAULTMESSAGE) { var invalidMessage = e.message; } else { var invalidMessage = e.getComment(); } this.setInvalidMessage(invalidMessage); } else { throw e; } } return formValid; }, /** * Helper function which checks, if the given validator is synchronous * or asynchronous. * * @param validator {Function||qx.ui.form.validation.Asyncvalidator} * The validator to check. * @return {Boolean} True, if the given validator is asynchronous. */ __isAsyncValidator : function(validator) { var async = false; if (!qx.lang.Type.isFunction(validator)) { async = qx.Class.isSubClassOf( validator.constructor, qx.ui.form.validation.AsyncValidator ); } return async; }, /** * Returns true, if the given item implements the {@link qx.ui.form.IForm} * interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsInvalid : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.ui.form.IForm); }, /** * Returns true, if the given item implements the * {@link qx.ui.core.ISingleSelection} interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsSingleSelection : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection); }, /** * Internal setter for the valid member. It generates the event if * necessary and stores the new value * * @param value {Boolean|null} The new valid value of the manager. */ __setValid: function(value) { var oldValue = this.__valid; this.__valid = value; // check for the change event if (oldValue != value) { this.fireDataEvent("changeValid", value, oldValue); } }, /** * Returns the valid state of the manager. * * @return {Boolean|null} The valid state of the manager. */ getValid: function() { return this.__valid; }, /** * Returns the valid state of the manager. * * @return {Boolean|null} The valid state of the manager. */ isValid: function() { return this.getValid(); }, /** * Returns an array of all invalid messages of the invalid form items and * the form manager itself. * * @return {String[]} All invalid messages. */ getInvalidMessages: function() { var messages = []; // combine the messages of all form items for (var i = 0; i < this.__formItems.length; i++) { var formItem = this.__formItems[i].item; if (!formItem.getValid()) { messages.push(formItem.getInvalidMessage()); } } // add the forms fail message if (this.getInvalidMessage() != "") { messages.push(this.getInvalidMessage()); } return messages; }, /** * Selects invalid form items * * @return {Array} invalid form items */ getInvalidFormItems : function() { var res = []; for (var i = 0; i < this.__formItems.length; i++) { var formItem = this.__formItems[i].item; if (!formItem.getValid()) { res.push(formItem); } } return res; }, /** * Resets the validator. */ reset: function() { // reset all form items for (var i = 0; i < this.__formItems.length; i++) { var dataEntry = this.__formItems[i]; // set the field to valid dataEntry.item.setValid(true); } // set the manager to its inital valid value this.__valid = null; }, /** * Internal helper method to set the given item to valid for asynchronous * validation calls. This indirection is used to determinate if the * validation process is completed or if other asynchronous validators * are still validating. {@link #__checkValidationComplete} checks if the * validation is complete and will be called at the end of this method. * * @param formItem {qx.ui.core.Widget} The form item to set the valid state. * @param valid {Boolean} The valid state for the form item. * * @internal */ setItemValid: function(formItem, valid) { // store the result this.__asyncResults[formItem.toHashCode()] = valid; formItem.setValid(valid); this.__checkValidationComplete(); }, /** * Internal helper method to set the form manager to valid for asynchronous * validation calls. This indirection is used to determinate if the * validation process is completed or if other asynchronous validators * are still validating. {@link #__checkValidationComplete} checks if the * validation is complete and will be called at the end of this method. * * @param valid {Boolean} The valid state for the form manager. * * @internal */ setFormValid : function(valid) { this.__asyncResults[this.toHashCode()] = valid; this.__checkValidationComplete(); }, /** * Checks if all asynchronous validators have validated so the result * is final and the {@link #complete} event can be fired. If that's not * the case, nothing will happen in the method. */ __checkValidationComplete : function() { var valid = this.__syncValid; // check if all async validators are done for (var hash in this.__asyncResults) { var currentResult = this.__asyncResults[hash]; valid = currentResult && valid; // the validation is not done so just do nothing if (currentResult == null) { return; } } // set the actual valid state of the manager this.__setValid(valid); // reset the results this.__asyncResults = {}; // fire the complete event (no entry in the results with null) this.fireEvent("complete"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__formItems = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for validation in all asynchronous cases and * should always be used with {@link qx.ui.form.validation.Manager}. * * * It acts like a wrapper for asynchronous validation functions. These * validation function must be set in the constructor. The form manager will * invoke the validation and the validator function will be called with two * arguments: * <ul> * <li>asyncValidator: A reference to the corresponding validator.</li> * <li>value: The value of the assigned input field.</li> * </ul> * These two parameters are needed to set the validation status of the current * validator. {@link #setValid} is responsible for doing that. * * * *Warning:* Instances of this class can only be used with one input * field at a time. Multi usage is not supported! * * *Warning:* Calling {@link #setValid} synchronously does not work. If you * have an synchronous validator, please check * {@link qx.ui.form.validation.Manager#add}. If you have both cases, you have * to wrap the synchronous call in a timeout to make it asychronous. */ qx.Class.define("qx.ui.form.validation.AsyncValidator", { extend : qx.core.Object, /** * @param validator {Function} The validator function, which has to be * asynchronous. */ construct : function(validator) { this.base(arguments); // save the validator function this.__validatorFunction = validator; }, members : { __validatorFunction : null, __item : null, __manager : null, __usedForForm : null, /** * The validate function should only be called by * {@link qx.ui.form.validation.Manager}. * * It stores the given information and calls the validation function set in * the constructor. The method is used for form fields only. Validating a * form itself will be invokes with {@link #validateForm}. * * @param item {qx.ui.core.Widget} The form item which should be validated. * @param value {var} The value of the form item. * @param manager {qx.ui.form.validation.Manager} A reference to the form * manager. * @param context {var?null} The context of the validator. * * @internal */ validate: function(item, value, manager, context) { // mark as item validator this.__usedForForm = false; // store the item and the manager this.__item = item; this.__manager = manager; // invoke the user set validator function this.__validatorFunction.call(context || this, this, value); }, /** * The validateForm function should only be called by * {@link qx.ui.form.validation.Manager}. * * It stores the given information and calls the validation function set in * the constructor. The method is used for forms only. Validating a * form item will be invokes with {@link #validate}. * * @param items {qx.ui.core.Widget[]} All form items of the form manager. * @param manager {qx.ui.form.validation.Manager} A reference to the form * manager. * @param context {var?null} The context of the validator. * * @internal */ validateForm : function(items, manager, context) { this.__usedForForm = true; this.__manager = manager; this.__validatorFunction.call(context, items, this); }, /** * This method should be called within the asynchronous callback to tell the * validator the result of the validation. * * @param valid {boolean} The boolean state of the validation. * @param message {String?} The invalidMessage of the validation. */ setValid: function(valid, message) { // valid processing if (this.__usedForForm) { // message processing if (message !== undefined) { this.__manager.setInvalidMessage(message); } this.__manager.setFormValid(valid); } else { // message processing if (message !== undefined) { this.__item.setInvalidMessage(message); } this.__manager.setItemValid(this.__item, valid); } } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__manager = this.__item = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Each object, which should support single selection have to * implement this interface. */ qx.Interface.define("qx.ui.core.ISingleSelection", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {qx.ui.core.Widget[]} List of items. */ getSelection : function() { return true; }, /** * Replaces current selection with the given items. * * @param items {qx.ui.core.Widget[]} Items to select. * @throws an exception if the item is not a child element. */ setSelection : function(items) { return arguments.length == 1; }, /** * Clears the whole selection at once. */ resetSelection : function() { return true; }, /** * Detects whether the given item is currently selected. * * @param item {qx.ui.core.Widget} Any valid selectable item * @return {Boolean} Whether the item is selected. * @throws an exception if the item is not a child element. */ isSelected : function(item) { return arguments.length == 1; }, /** * Whether the selection is empty. * * @return {Boolean} Whether the selection is empty. */ isSelectionEmpty : function() { return true; }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables: function(all) { return arguments.length == 1; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The resetter is responsible for managing a set of items and resetting these * items on a {@link #reset} call. It can handle all form items supplying a * value property and all widgets implementing the single selection linked list * or select box. */ qx.Class.define("qx.ui.form.Resetter", { extend : qx.core.Object, construct : function() { this.base(arguments); this.__items = []; }, members : { __items : null, /** * Adding a widget to the reseter will get its current value and store * it for resetting. To access the value, the given item needs to specify * a value property or implement the {@link qx.ui.core.ISingleSelection} * interface. * * @param item {qx.ui.core.Widget} The widget which should be added. */ add : function(item) { // check the init values if (this._supportsValue(item)) { var init = item.getValue(); } else if (this.__supportsSingleSelection(item)) { var init = item.getSelection(); } else if (this.__supportsDataBindingSelection(item)) { var init = item.getSelection().concat(); } else { throw new Error("Item " + item + " not supported for reseting."); } // store the item and its init value this.__items.push({item: item, init: init}); }, /** * Resets all added form items to their initial value. The initial value * is the value in the widget during the {@link #add}. */ reset: function() { // reset all form items for (var i = 0; i < this.__items.length; i++) { var dataEntry = this.__items[i]; // set the init value this.__setItem(dataEntry.item, dataEntry.init); } }, /** * Resets a single given item. The item has to be added to the resetter * instance before. Otherwise, an error is thrown. * * @param item {qx.ui.core.Widget} The widget, which should be resetted. */ resetItem : function(item) { // get the init value var init; for (var i = 0; i < this.__items.length; i++) { var dataEntry = this.__items[i]; if (dataEntry.item === item) { init = dataEntry.init; break; } }; // check for the available init value if (init === undefined) { throw new Error("The given item has not been added."); } this.__setItem(item, init); }, /** * Internal helper for setting an item to a given init value. It checks * for the supported APIs and uses the fitting API. * * @param item {qx.ui.core.Widget} The item to reset. * @param init {var} The value to set. */ __setItem : function(item, init) { // set the init value if (this._supportsValue(item)) { item.setValue(init); } else if ( this.__supportsSingleSelection(item) || this.__supportsDataBindingSelection(item) ) { item.setSelection(init); } }, /** * Takes the current values of all added items and uses these values as * init values for resetting. */ redefine: function() { // go threw all added items for (var i = 0; i < this.__items.length; i++) { var item = this.__items[i].item; // set the new init value for the item this.__items[i].init = this.__getCurrentValue(item); } }, /** * Takes the current value of the given item and stores this value as init * value for resetting. * * @param item {qx.ui.core.Widget} The item to redefine. */ redefineItem : function(item) { // get the data entry var dataEntry; for (var i = 0; i < this.__items.length; i++) { if (this.__items[i].item === item) { dataEntry = this.__items[i]; break; } }; // check for the available init value if (dataEntry === undefined) { throw new Error("The given item has not been added."); } // set the new init value for the item dataEntry.init = this.__getCurrentValue(dataEntry.item); }, /** * Internel helper top access the value of a given item. * * @param item {qx.ui.core.Widget} The item to access. */ __getCurrentValue : function(item) { if (this._supportsValue(item)) { return item.getValue(); } else if ( this.__supportsSingleSelection(item) || this.__supportsDataBindingSelection(item) ) { return item.getSelection(); } }, /** * Returns true, if the given item implements the * {@link qx.ui.core.ISingleSelection} interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsSingleSelection : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection); }, /** * Returns true, if the given item implements the * {@link qx.data.controller.ISelection} interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsDataBindingSelection : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.data.controller.ISelection); }, /** * Returns true, if the value property is supplied by the form item. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ _supportsValue : function(formItem) { var clazz = formItem.constructor; return ( qx.Class.hasInterface(clazz, qx.ui.form.IBooleanForm) || qx.Class.hasInterface(clazz, qx.ui.form.IColorForm) || qx.Class.hasInterface(clazz, qx.ui.form.IDateForm) || qx.Class.hasInterface(clazz, qx.ui.form.INumberForm) || qx.Class.hasInterface(clazz, qx.ui.form.IStringForm) ); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // holding references to widgets --> must set to null this.__items = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Interface for data binding classes offering a selection. */ qx.Interface.define("qx.data.controller.ISelection", { members : { /** * Setter for the selection. * @param value {qx.data.IListData} The data of the selection. */ setSelection : function(value) {}, /** * Getter for the selection list. * @return {qx.data.IListData} The current selection. */ getSelection : function() {}, /** * Resets the selection to its default value. */ resetSelection : function() {} } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which have boolean as their primary * data type like a checkbox. */ qx.Interface.define("qx.ui.form.IBooleanForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Boolean|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Boolean|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which have boolean as their primary * data type like a colorchooser. */ qx.Interface.define("qx.ui.form.IColorForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Color|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Color|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which have date as their primary * data type like datechooser's. */ qx.Interface.define("qx.ui.form.IDateForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Date|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Date|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which use a numeric value as their * primary data type like a spinner. */ qx.Interface.define("qx.ui.form.INumberForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Number|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Number|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This mixin is included by all widgets, which support an 'execute' like * buttons or menu entries. */ qx.Mixin.define("qx.ui.core.MExecutable", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired if the {@link #execute} method is invoked.*/ "execute" : "qx.event.type.Event" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * A command called if the {@link #execute} method is called, e.g. on a * button click. */ command : { check : "qx.ui.core.Command", apply : "_applyCommand", event : "changeCommand", nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __executableBindingIds : null, __semaphore : false, __executeListenerId : null, /** * {Map} Set of properties, which will by synced from the command to the * including widget * * @lint ignoreReferenceField(_bindableProperties) */ _bindableProperties : [ "enabled", "label", "icon", "toolTipText", "value", "menu" ], /** * Initiate the execute action. */ execute : function() { var cmd = this.getCommand(); if (cmd) { if (this.__semaphore) { this.__semaphore = false; } else { this.__semaphore = true; cmd.execute(this); } } this.fireEvent("execute"); }, /** * Handler for the execute event of the command. * * @param e {qx.event.type.Event} The execute event of the command. */ __onCommandExecute : function(e) { if (this.__semaphore) { this.__semaphore = false; return; } this.__semaphore = true; this.execute(); }, // property apply _applyCommand : function(value, old) { // execute forwarding if (old != null) { old.removeListenerById(this.__executeListenerId); } if (value != null) { this.__executeListenerId = value.addListener( "execute", this.__onCommandExecute, this ); } // binding stuff var ids = this.__executableBindingIds; if (ids == null) { this.__executableBindingIds = ids = {}; } var selfPropertyValue; for (var i = 0; i < this._bindableProperties.length; i++) { var property = this._bindableProperties[i]; // remove the old binding if (old != null && !old.isDisposed() && ids[property] != null) { old.removeBinding(ids[property]); ids[property] = null; } // add the new binding if (value != null && qx.Class.hasProperty(this.constructor, property)) { // handle the init value (dont sync the initial null) var cmdPropertyValue = value.get(property); if (cmdPropertyValue == null) { selfPropertyValue = this.get(property); // check also for themed values [BUG #5906] if (selfPropertyValue == null) { // update the appearance to make sure every themed property is up to date this.syncAppearance(); selfPropertyValue = qx.util.PropertyUtil.getThemeValue( this, property ); } } else { // Reset the self property value [BUG #4534] selfPropertyValue = null; } // set up the binding ids[property] = value.bind(property, this, property); // reapply the former value if (selfPropertyValue) { this.set(property, selfPropertyValue); } } } } }, destruct : function() { this._applyCommand(null, this.getCommand()); this.__executableBindingIds = null; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A helper class for accessing the property system directly. * * This class is rather to be used internally. For all regular usage of the * property system the default API should be sufficient. */ qx.Class.define("qx.util.PropertyUtil", { statics : { /** * Get the property map of the given class * * @param clazz {Class} a qooxdoo class * @return {Map} A properties map as defined in {@link qx.Class#define} * including the properties of included mixins and not including refined * properties. */ getProperties : function(clazz) { return clazz.$$properties; }, /** * Get the property map of the given class including the properties of all * superclasses! * * @param clazz {Class} a qooxdoo class * @return {Map} The properties map as defined in {@link qx.Class#define} * including the properties of included mixins of the current class and * all superclasses. */ getAllProperties : function(clazz) { var properties = {}; var superclass = clazz; // go threw the class hierarchy while (superclass != qx.core.Object) { var currentProperties = this.getProperties(superclass); for (var property in currentProperties) { properties[property] = currentProperties[property]; } superclass = superclass.superclass; } return properties; }, /* ------------------------------------------------------------------------- USER VALUES ------------------------------------------------------------------------- */ /** * Returns the user value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {var} The user value */ getUserValue : function(object, propertyName) { return object["$$user_" + propertyName]; }, /** * Sets the user value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setUserValue : function(object, propertyName, value) { object["$$user_" + propertyName] = value; }, /** * Deletes the user value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ deleteUserValue : function(object, propertyName) { delete(object["$$user_" + propertyName]); }, /* ------------------------------------------------------------------------- INIT VALUES ------------------------------------------------------------------------- */ /** * Returns the init value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {var} The init value */ getInitValue : function(object, propertyName) { return object["$$init_" + propertyName]; }, /** * Sets the init value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setInitValue : function(object, propertyName, value) { object["$$init_" + propertyName] = value; }, /** * Deletes the init value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ deleteInitValue : function(object, propertyName) { delete(object["$$init_" + propertyName]); }, /* ------------------------------------------------------------------------- THEME VALUES ------------------------------------------------------------------------- */ /** * Returns the theme value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {var} The theme value */ getThemeValue : function(object, propertyName) { return object["$$theme_" + propertyName]; }, /** * Sets the theme value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setThemeValue : function(object, propertyName, value) { object["$$theme_" + propertyName] = value; }, /** * Deletes the theme value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ deleteThemeValue : function(object, propertyName) { delete(object["$$theme_" + propertyName]); }, /* ------------------------------------------------------------------------- THEMED PROPERTY ------------------------------------------------------------------------- */ /** * Sets a themed property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setThemed : function(object, propertyName, value) { var styler = qx.core.Property.$$method.setThemed; object[styler[propertyName]](value); }, /** * Resets a themed property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ resetThemed : function(object, propertyName) { var unstyler = qx.core.Property.$$method.resetThemed; object[unstyler[propertyName]](); } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which are executable in some way. This * could be a button for example. */ qx.Interface.define("qx.ui.form.IExecutable", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * Fired when the widget is executed. Sets the "data" property of the * event to the object that issued the command. */ "execute" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- COMMAND PROPERTY --------------------------------------------------------------------------- */ /** * Set the command of this executable. * * @param command {qx.ui.core.Command} The command. */ setCommand : function(command) { return arguments.length == 1; }, /** * Return the current set command of this executable. * * @return {qx.ui.core.Command} The current set command. */ getCommand : function() {}, /** * Fire the "execute" event on the command. */ execute: function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Button widget which supports various states and allows it to be used * via the mouse and the keyboard. * * If the user presses the button by clicking on it, or the <code>Enter</code> or * <code>Space</code> keys, the button fires an {@link qx.ui.core.MExecutable#execute} event. * * If the {@link qx.ui.core.MExecutable#command} property is set, the * command is executed as well. * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var button = new qx.ui.form.Button("Hello World"); * * button.addListener("execute", function(e) { * alert("Button was clicked"); * }, this); * * this.getRoot.add(button); * </pre> * * This example creates a button with the label "Hello World" and attaches an * event listener to the {@link #execute} event. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/button.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.form.Button", { extend : qx.ui.basic.Atom, include : [qx.ui.core.MExecutable], implement : [qx.ui.form.IExecutable], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param label {String} label of the atom * @param icon {String?null} Icon URL of the atom * @param command {qx.ui.core.Command?null} Command instance to connect with */ construct : function(label, icon, command) { this.base(arguments, label, icon); if (command != null) { this.setCommand(command); } // Add listeners this.addListener("mouseover", this._onMouseOver); this.addListener("mouseout", this._onMouseOut); this.addListener("mousedown", this._onMouseDown); this.addListener("mouseup", this._onMouseUp); this.addListener("keydown", this._onKeyDown); this.addListener("keyup", this._onKeyUp); // Stop events this.addListener("dblclick", this._onStopEvent); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "button" }, // overridden focusable : { refine : true, init : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true, hovered : true, pressed : true, disabled : true }, /* --------------------------------------------------------------------------- USER API --------------------------------------------------------------------------- */ /** * Manually press the button */ press : function() { if (this.hasState("abandoned")) { return; } this.addState("pressed"); }, /** * Manually release the button */ release : function() { if (this.hasState("pressed")) { this.removeState("pressed"); } }, /** * Completely reset the button (remove all states) */ reset : function() { this.removeState("pressed"); this.removeState("abandoned"); this.removeState("hovered"); }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Listener method for "mouseover" event * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOver : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); } this.addState("hovered"); }, /** * Listener method for "mouseout" event * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" and removes "pressed" state (if "pressed" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOut : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { this.removeState("pressed"); this.addState("abandoned"); } }, /** * Listener method for "mousedown" event * <ul> * <li>Removes "abandoned" state</li> * <li>Adds "pressed" state</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseDown : function(e) { if (!e.isLeftPressed()) { return; } e.stopPropagation(); // Activate capturing if the button get a mouseout while // the button is pressed. this.capture(); this.removeState("abandoned"); this.addState("pressed"); }, /** * Listener method for "mouseup" event * <ul> * <li>Removes "pressed" state (if set)</li> * <li>Removes "abandoned" state (if set)</li> * <li>Adds "hovered" state (if "abandoned" state is not set)</li> *</ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseUp : function(e) { this.releaseCapture(); // We must remove the states before executing the command // because in cases were the window lost the focus while // executing we get the capture phase back (mouseout). var hasPressed = this.hasState("pressed"); var hasAbandoned = this.hasState("abandoned"); if (hasPressed) { this.removeState("pressed"); } if (hasAbandoned) { this.removeState("abandoned"); } else { this.addState("hovered"); if (hasPressed) { this.execute(); } } e.stopPropagation(); }, /** * Listener method for "keydown" event.<br/> * Removes "abandoned" and adds "pressed" state * for the keys "Enter" or "Space" * * @param e {Event} Key event * @return {void} */ _onKeyDown : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); } }, /** * Listener method for "keyup" event.<br/> * Removes "abandoned" and "pressed" state (if "pressed" state is set) * for the keys "Enter" or "Space" * * @param e {Event} Key event * @return {void} */ _onKeyUp : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": if (this.hasState("pressed")) { this.removeState("abandoned"); this.removeState("pressed"); this.execute(); e.stopPropagation(); } } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin handling the valid and required properties for the form widgets. */ qx.Mixin.define("qx.ui.form.MForm", { construct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener("changeLocale", this.__onChangeLocale, this); } }, properties : { /** * Flag signaling if a widget is valid. If a widget is invalid, an invalid * state will be set. */ valid : { check : "Boolean", init : true, apply : "_applyValid", event : "changeValid" }, /** * Flag signaling if a widget is required. */ required : { check : "Boolean", init : false, event : "changeRequired" }, /** * Message which is shown in an invalid tooltip. */ invalidMessage : { check : "String", init: "", event : "changeInvalidMessage" }, /** * Message which is shown in an invalid tooltip if the {@link #required} is * set to true. */ requiredInvalidMessage : { check : "String", nullable : true, event : "changeInvalidMessage" } }, members : { // apply method _applyValid: function(value, old) { value ? this.removeState("invalid") : this.addState("invalid"); }, /** * Locale change event handler * * @signature function(e) * @param e {Event} the change event */ __onChangeLocale : qx.core.Environment.select("qx.dynlocale", { "true" : function(e) { // invalid message var invalidMessage = this.getInvalidMessage(); if (invalidMessage && invalidMessage.translate) { this.setInvalidMessage(invalidMessage.translate()); } // required invalid message var requiredInvalidMessage = this.getRequiredInvalidMessage(); if (requiredInvalidMessage && requiredInvalidMessage.translate) { this.setRequiredInvalidMessage(requiredInvalidMessage.translate()); } }, "false" : null }) }, destruct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this.__onChangeLocale, this); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all widgets which deal with ranges. The spinner is a good * example for a range using widget. */ qx.Interface.define("qx.ui.form.IRange", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- MINIMUM PROPERTY --------------------------------------------------------------------------- */ /** * Set the minimum value of the range. * * @param min {Number} The minimum. */ setMinimum : function(min) { return arguments.length == 1; }, /** * Return the current set minimum of the range. * * @return {Number} The current set minimum. */ getMinimum : function() {}, /* --------------------------------------------------------------------------- MAXIMUM PROPERTY --------------------------------------------------------------------------- */ /** * Set the maximum value of the range. * * @param max {Number} The maximum. */ setMaximum : function(max) { return arguments.length == 1; }, /** * Return the current set maximum of the range. * * @return {Number} The current set maximum. */ getMaximum : function() {}, /* --------------------------------------------------------------------------- SINGLESTEP PROPERTY --------------------------------------------------------------------------- */ /** * Sets the value for single steps in the range. * * @param step {Number} The value of the step. */ setSingleStep : function(step) { return arguments.length == 1; }, /** * Returns the value which will be stepped in a single step in the range. * * @return {Number} The current value for single steps. */ getSingleStep : function() {}, /* --------------------------------------------------------------------------- PAGESTEP PROPERTY --------------------------------------------------------------------------- */ /** * Sets the value for page steps in the range. * * @param step {Number} The value of the step. */ setPageStep : function(step) { return arguments.length == 1; }, /** * Returns the value which will be stepped in a page step in the range. * * @return {Number} The current value for page steps. */ getPageStep : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This mixin defines the <code>contentPadding</code> property, which is used * by widgets like the window or group box, which must have a property, which * defines the padding of an inner pane. * * The including class must implement the method * <code>_getContentPaddingTarget</code>, which must return the widget on which * the padding should be applied. */ qx.Mixin.define("qx.ui.core.MContentPadding", { /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** Top padding of the content pane */ contentPaddingTop : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** Right padding of the content pane */ contentPaddingRight : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** Bottom padding of the content pane */ contentPaddingBottom : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** Left padding of the content pane */ contentPaddingLeft : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** * The 'contentPadding' property is a shorthand property for setting 'contentPaddingTop', * 'contentPaddingRight', 'contentPaddingBottom' and 'contentPaddingLeft' * at the same time. * * If four values are specified they apply to top, right, bottom and left respectively. * If there is only one value, it applies to all sides, if there are two or three, * the missing values are taken from the opposite side. */ contentPadding : { group : [ "contentPaddingTop", "contentPaddingRight", "contentPaddingBottom", "contentPaddingLeft" ], mode : "shorthand", themeable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * {Map} Maps property names of content padding to the setter of the padding * * @lint ignoreReferenceField(__contentPaddingSetter) */ __contentPaddingSetter : { contentPaddingTop : "setPaddingTop", contentPaddingRight : "setPaddingRight", contentPaddingBottom : "setPaddingBottom", contentPaddingLeft : "setPaddingLeft" }, /** * {Map} Maps property names of content padding to the resetter of the padding * * @lint ignoreReferenceField(__contentPaddingResetter) */ __contentPaddingResetter : { contentPaddingTop : "resetPaddingTop", contentPaddingRight : "resetPaddingRight", contentPaddingBottom : "resetPaddingBottom", contentPaddingLeft : "resetPaddingLeft" }, // property apply _applyContentPadding : function(value, old, name) { var target = this._getContentPaddingTarget(); if (value == null) { var resetter = this.__contentPaddingResetter[name]; target[resetter](); } else { var setter = this.__contentPaddingSetter[name]; target[setter](value); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) * Jonathan Weiß (jonathan_rass) ************************************************************************ */ /** * A *spinner* is a control that allows you to adjust a numerical value, * typically within an allowed range. An obvious example would be to specify the * month of a year as a number in the range 1 - 12. * * To do so, a spinner encompasses a field to display the current value (a * textfield) and controls such as up and down buttons to change that value. The * current value can also be changed by editing the display field directly, or * using mouse wheel and cursor keys. * * An optional {@link #numberFormat} property allows you to control the format of * how a value can be entered and will be displayed. * * A brief, but non-trivial example: * * <pre class='javascript'> * var s = new qx.ui.form.Spinner(); * s.set({ * maximum: 3000, * minimum: -3000 * }); * var nf = new qx.util.format.NumberFormat(); * nf.setMaximumFractionDigits(2); * s.setNumberFormat(nf); * </pre> * * A spinner instance without any further properties specified in the * constructor or a subsequent *set* command will appear with default * values and behaviour. * * @childControl textfield {qx.ui.form.TextField} holds the current value of the spinner * @childControl upbutton {qx.ui.form.Button} button to increase the value * @childControl downbutton {qx.ui.form.Button} button to decrease the value * */ qx.Class.define("qx.ui.form.Spinner", { extend : qx.ui.core.Widget, implement : [ qx.ui.form.INumberForm, qx.ui.form.IRange, qx.ui.form.IForm ], include : [ qx.ui.core.MContentPadding, qx.ui.form.MForm ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param min {Number} Minimum value * @param value {Number} Current value * @param max {Number} Maximum value */ construct : function(min, value, max) { this.base(arguments); // MAIN LAYOUT var layout = new qx.ui.layout.Grid(); layout.setColumnFlex(0, 1); layout.setRowFlex(0,1); layout.setRowFlex(1,1); this._setLayout(layout); // EVENTS this.addListener("keydown", this._onKeyDown, this); this.addListener("keyup", this._onKeyUp, this); this.addListener("mousewheel", this._onMouseWheel, this); if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener("changeLocale", this._onChangeLocale, this); } // CREATE CONTROLS this._createChildControl("textfield"); this._createChildControl("upbutton"); this._createChildControl("downbutton"); // INITIALIZATION if (min != null) { this.setMinimum(min); } if (max != null) { this.setMaximum(max); } if (value !== undefined) { this.setValue(value); } else { this.initValue(); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties: { // overridden appearance: { refine : true, init : "spinner" }, // overridden focusable : { refine : true, init : true }, /** The amount to increment on each event (keypress or mousedown) */ singleStep: { check : "Number", init : 1 }, /** The amount to increment on each pageup/pagedown keypress */ pageStep: { check : "Number", init : 10 }, /** minimal value of the Range object */ minimum: { check : "Number", apply : "_applyMinimum", init : 0, event: "changeMinimum" }, /** The value of the spinner. */ value: { check : "this._checkValue(value)", nullable : true, apply : "_applyValue", init : 0, event : "changeValue" }, /** maximal value of the Range object */ maximum: { check : "Number", apply : "_applyMaximum", init : 100, event: "changeMaximum" }, /** whether the value should wrap around */ wrap: { check : "Boolean", init : false, apply : "_applyWrap" }, /** Controls whether the textfield of the spinner is editable or not */ editable : { check : "Boolean", init : true, apply : "_applyEditable" }, /** Controls the display of the number in the textfield */ numberFormat : { check : "qx.util.format.NumberFormat", apply : "_applyNumberFormat", nullable : true }, // overridden allowShrinkY : { refine : true, init : false } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** Saved last value in case invalid text is entered */ __lastValidValue : null, /** Whether the page-up button has been pressed */ __pageUpMode : false, /** Whether the page-down button has been pressed */ __pageDownMode : false, /* --------------------------------------------------------------------------- WIDGET INTERNALS --------------------------------------------------------------------------- */ // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "textfield": control = new qx.ui.form.TextField(); control.setFilter(this._getFilterRegExp()); control.addState("inner"); control.setWidth(40); control.setFocusable(false); control.addListener("changeValue", this._onTextChange, this); this._add(control, {column: 0, row: 0, rowSpan: 2}); break; case "upbutton": control = new qx.ui.form.RepeatButton(); control.addState("inner"); control.setFocusable(false); control.addListener("execute", this._countUp, this); this._add(control, {column: 1, row: 0}); break; case "downbutton": control = new qx.ui.form.RepeatButton(); control.addState("inner"); control.setFocusable(false); control.addListener("execute", this._countDown, this); this._add(control, {column:1, row: 1}); break; } return control || this.base(arguments, id); }, /** * Returns the regular expression used as the text field's filter * * @return {RegExp} The filter RegExp. */ _getFilterRegExp : function() { var decimalSeparator = qx.locale.Number.getDecimalSeparator( qx.locale.Manager.getInstance().getLocale() ); var groupSeparator = qx.locale.Number.getGroupSeparator( qx.locale.Manager.getInstance().getLocale() ); var prefix = ""; var postfix = ""; if (this.getNumberFormat() !== null) { prefix = this.getNumberFormat().getPrefix() || ""; postfix = this.getNumberFormat().getPostfix() || ""; } var filterRegExp = new RegExp("[0-9" + qx.lang.String.escapeRegexpChars(decimalSeparator) + qx.lang.String.escapeRegexpChars(groupSeparator) + qx.lang.String.escapeRegexpChars(prefix) + qx.lang.String.escapeRegexpChars(postfix) + "\-]" ); return filterRegExp; }, // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true, invalid : true }, // overridden tabFocus : function() { var field = this.getChildControl("textfield"); field.getFocusElement().focus(); field.selectAllText(); }, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ /** * Apply routine for the minimum property. * * It sets the value of the spinner to the maximum of the current spinner * value and the given min property value. * * @param value {Number} The new value of the min property * @param old {Number} The old value of the min property */ _applyMinimum : function(value, old) { if (this.getMaximum() < value) { this.setMaximum(value); } if (this.getValue() < value) { this.setValue(value); } else { this._updateButtons(); } }, /** * Apply routine for the maximum property. * * It sets the value of the spinner to the minimum of the current spinner * value and the given max property value. * * @param value {Number} The new value of the max property * @param old {Number} The old value of the max property */ _applyMaximum : function(value, old) { if (this.getMinimum() > value) { this.setMinimum(value); } if (this.getValue() > value) { this.setValue(value); } else { this._updateButtons(); } }, // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); this._updateButtons(); }, /** * Check whether the value being applied is allowed. * * If you override this to change the allowed type, you will also * want to override {@link #_applyValue}, {@link #_applyMinimum}, * {@link #_applyMaximum}, {@link #_countUp}, {@link #_countDown}, and * {@link #_onTextChange} methods as those cater specifically to numeric * values. * * @param value {Any} * The value being set * @return {Boolean} * <i>true</i> if the value is allowed; * <i>false> otherwise. */ _checkValue : function(value) { return typeof value === "number" && value >= this.getMinimum() && value <= this.getMaximum(); }, /** * Apply routine for the value property. * * It checks the min and max values, disables / enables the * buttons and handles the wrap around. * * @param value {Number} The new value of the spinner * @param old {Number} The former value of the spinner */ _applyValue: function(value, old) { var textField = this.getChildControl("textfield"); this._updateButtons(); // save the last valid value of the spinner this.__lastValidValue = value; // write the value of the spinner to the textfield if (value !== null) { if (this.getNumberFormat()) { textField.setValue(this.getNumberFormat().format(value)); } else { textField.setValue(value + ""); } } else { textField.setValue(""); } }, /** * Apply routine for the editable property.<br/> * It sets the textfield of the spinner to not read only. * * @param value {Boolean} The new value of the editable property * @param old {Boolean} The former value of the editable property */ _applyEditable : function(value, old) { var textField = this.getChildControl("textfield"); if (textField) { textField.setReadOnly(!value); } }, /** * Apply routine for the wrap property.<br/> * Enables all buttons if the wrapping is enabled. * * @param value {Boolean} The new value of the wrap property * @param old {Boolean} The former value of the wrap property */ _applyWrap : function(value, old) { this._updateButtons(); }, /** * Apply routine for the numberFormat property.<br/> * When setting a number format, the display of the * value in the textfield will be changed immediately. * * @param value {Boolean} The new value of the numberFormat property * @param old {Boolean} The former value of the numberFormat property */ _applyNumberFormat : function(value, old) { var textfield = this.getChildControl("textfield"); textfield.setFilter(this._getFilterRegExp()); this.getNumberFormat().addListener("changeNumberFormat", this._onChangeNumberFormat, this); this._applyValue(this.__lastValidValue, undefined); }, /** * Returns the element, to which the content padding should be applied. * * @return {qx.ui.core.Widget} The content padding target. */ _getContentPaddingTarget : function() { return this.getChildControl("textfield"); }, /** * Checks the min and max values, disables / enables the * buttons and handles the wrap around. */ _updateButtons : function() { var upButton = this.getChildControl("upbutton"); var downButton = this.getChildControl("downbutton"); var value = this.getValue(); if (!this.getEnabled()) { // If Spinner is disabled -> disable buttons upButton.setEnabled(false); downButton.setEnabled(false); } else { if (this.getWrap()) { // If wraped -> always enable buttons upButton.setEnabled(true); downButton.setEnabled(true); } else { // check max value if (value !== null && value < this.getMaximum()) { upButton.setEnabled(true); } else { upButton.setEnabled(false); } // check min value if (value !== null && value > this.getMinimum()) { downButton.setEnabled(true); } else { downButton.setEnabled(false); } } } }, /* --------------------------------------------------------------------------- KEY EVENT-HANDLING --------------------------------------------------------------------------- */ /** * Callback for "keyDown" event.<br/> * Controls the interval mode ("single" or "page") * and the interval increase by detecting "Up"/"Down" * and "PageUp"/"PageDown" keys.<br/> * The corresponding button will be pressed. * * @param e {qx.event.type.KeySequence} keyDown event */ _onKeyDown: function(e) { switch(e.getKeyIdentifier()) { case "PageUp": // mark that the spinner is in page mode and process further this.__pageUpMode = true; case "Up": this.getChildControl("upbutton").press(); break; case "PageDown": // mark that the spinner is in page mode and process further this.__pageDownMode = true; case "Down": this.getChildControl("downbutton").press(); break; default: // Do not stop unused events return; } e.stopPropagation(); e.preventDefault(); }, /** * Callback for "keyUp" event.<br/> * Detecting "Up"/"Down" and "PageUp"/"PageDown" keys.<br/> * Releases the button and disabled the page mode, if necessary. * * @param e {qx.event.type.KeySequence} keyUp event * @return {void} */ _onKeyUp: function(e) { switch(e.getKeyIdentifier()) { case "PageUp": this.getChildControl("upbutton").release(); this.__pageUpMode = false; break; case "Up": this.getChildControl("upbutton").release(); break; case "PageDown": this.getChildControl("downbutton").release(); this.__pageDownMode = false; break; case "Down": this.getChildControl("downbutton").release(); break; } }, /* --------------------------------------------------------------------------- OTHER EVENT HANDLERS --------------------------------------------------------------------------- */ /** * Callback method for the "mouseWheel" event.<br/> * Increments or decrements the value of the spinner. * * @param e {qx.event.type.Mouse} mouseWheel event */ _onMouseWheel: function(e) { var delta = e.getWheelDelta("y"); if (delta > 0) { this._countDown(); } else if (delta < 0) { this._countUp(); } e.stop(); }, /** * Callback method for the "change" event of the textfield. * * @param e {qx.event.type.Event} text change event or blur event */ _onTextChange : function(e) { var textField = this.getChildControl("textfield"); var value; // if a number format is set if (this.getNumberFormat()) { // try to parse the current number using the number format try { value = this.getNumberFormat().parse(textField.getValue()); } catch(ex) { // otherwise, process further } } if (value === undefined) { // try to parse the number as a float value = parseFloat(textField.getValue()); } // if the result is a number if (!isNaN(value)) { // Fix range if (value > this.getMaximum()) { textField.setValue(this.getMaximum() + ""); return; } else if (value < this.getMinimum()) { textField.setValue(this.getMinimum() + ""); return; } // set the value in the spinner this.setValue(value); } else { // otherwise, reset the last valid value this._applyValue(this.__lastValidValue, undefined); } }, /** * Callback method for the locale Manager's "changeLocale" event. * * @param ev {qx.event.type.Event} locale change event */ _onChangeLocale : function(ev) { if (this.getNumberFormat() !== null) { this.setNumberFormat(this.getNumberFormat()); var textfield = this.getChildControl("textfield"); textfield.setFilter(this._getFilterRegExp()); textfield.setValue(this.getNumberFormat().format(this.getValue())); } }, /** * Callback method for the number format's "changeNumberFormat" event. * * @param ev {qx.event.type.Event} number format change event */ _onChangeNumberFormat : function(ev) { var textfield = this.getChildControl("textfield"); textfield.setFilter(this._getFilterRegExp()); textfield.setValue(this.getNumberFormat().format(this.getValue())); }, /* --------------------------------------------------------------------------- INTERVAL HANDLING --------------------------------------------------------------------------- */ /** * Checks if the spinner is in page mode and counts either the single * or page Step up. * */ _countUp: function() { if (this.__pageUpMode) { var newValue = this.getValue() + this.getPageStep(); } else { var newValue = this.getValue() + this.getSingleStep(); } // handle the case where wrapping is enabled if (this.getWrap()) { if (newValue > this.getMaximum()) { var diff = this.getMaximum() - newValue; newValue = this.getMinimum() + diff; } } this.gotoValue(newValue); }, /** * Checks if the spinner is in page mode and counts either the single * or page Step down. * */ _countDown: function() { if (this.__pageDownMode) { var newValue = this.getValue() - this.getPageStep(); } else { var newValue = this.getValue() - this.getSingleStep(); } // handle the case where wrapping is enabled if (this.getWrap()) { if (newValue < this.getMinimum()) { var diff = this.getMinimum() + newValue; newValue = this.getMaximum() - diff; } } this.gotoValue(newValue); }, /** * Normalizes the incoming value to be in the valid range and * applies it to the {@link #value} afterwards. * * @param value {Number} Any number * @return {Number} The normalized number */ gotoValue : function(value) { return this.setValue(Math.min(this.getMaximum(), Math.max(this.getMinimum(), value))); } }, destruct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this._onChangeLocale, this); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The grid layout manager arranges the items in a two dimensional * grid. Widgets can be placed into the grid's cells and may span multiple rows * and columns. * * *Features* * * * Flex values for rows and columns * * Minimal and maximal column and row sizes * * Manually setting of column and row sizes * * Horizontal and vertical alignment * * Horizontal and vertical spacing * * Column and row spans * * Auto-sizing * * *Item Properties* * * <ul> * <li><strong>row</strong> <em>(Integer)</em>: The row of the cell the * widget should occupy. Each cell can only contain one widget. This layout * property is mandatory. * </li> * <li><strong>column</strong> <em>(Integer)</em>: The column of the cell the * widget should occupy. Each cell can only contain one widget. This layout * property is mandatory. * </li> * <li><strong>rowSpan</strong> <em>(Integer)</em>: The number of rows, the * widget should span, starting from the row specified in the <code>row</code> * property. The cells in the spanned rows must be empty as well. * </li> * <li><strong>colSpan</strong> <em>(Integer)</em>: The number of columns, the * widget should span, starting from the column specified in the <code>column</code> * property. The cells in the spanned columns must be empty as well. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.Grid(); * layout.setRowFlex(0, 1); // make row 0 flexible * layout.setColumnWidth(1, 200); // set with of column 1 to 200 pixel * * var container = new qx.ui.container.Composite(layout); * container.add(new qx.ui.core.Widget(), {row: 0, column: 0}); * container.add(new qx.ui.core.Widget(), {row: 0, column: 1}); * container.add(new qx.ui.core.Widget(), {row: 1, column: 0, rowSpan: 2}); * </pre> * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/layout/grid.html'> * Extended documentation</a> and links to demos of this layout in the qooxdoo manual. */ qx.Class.define("qx.ui.layout.Grid", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacingX {Integer?0} The horizontal spacing between grid cells. * Sets {@link #spacingX}. * @param spacingY {Integer?0} The vertical spacing between grid cells. * Sets {@link #spacingY}. */ construct : function(spacingX, spacingY) { this.base(arguments); this.__rowData = []; this.__colData = []; if (spacingX) { this.setSpacingX(spacingX); } if (spacingY) { this.setSpacingY(spacingY); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The horizontal spacing between grid cells. */ spacingX : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** * The vertical spacing between grid cells. */ spacingY : { check : "Integer", init : 0, apply : "_applyLayoutChange" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {Array} 2D array of grid cell data */ __grid : null, __rowData : null, __colData : null, __colSpans : null, __rowSpans : null, __maxRowIndex : null, __maxColIndex : null, /** {Array} cached row heights */ __rowHeights : null, /** {Array} cached column widths */ __colWidths : null, // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { var layoutProperties = { "row" : 1, "column" : 1, "rowSpan" : 1, "colSpan" : 1 } this.assert(layoutProperties[name] == 1, "The property '"+name+"' is not supported by the Grid layout!"); this.assertInteger(value); this.assert(value >= 0, "Value must be positive"); }, "false" : null }), /** * Rebuild the internal representation of the grid */ __buildGrid : function() { var grid = []; var colSpans = []; var rowSpans = []; var maxRowIndex = -1; var maxColIndex = -1; var children = this._getLayoutChildren(); for (var i=0,l=children.length; i<l; i++) { var child = children[i]; var props = child.getLayoutProperties(); var row = props.row; var column = props.column; props.colSpan = props.colSpan || 1; props.rowSpan = props.rowSpan || 1; // validate arguments if (row == null || column == null) { throw new Error( "The layout properties 'row' and 'column' of the child widget '" + child + "' must be defined!" ); } if (grid[row] && grid[row][column]) { throw new Error( "Cannot add widget '" + child + "'!. " + "There is already a widget '" + grid[row][column] + "' in this cell (" + row + ", " + column + ") for '" + this + "'" ); } for (var x=column; x<column+props.colSpan; x++) { for (var y=row; y<row+props.rowSpan; y++) { if (grid[y] == undefined) { grid[y] = []; } grid[y][x] = child; maxColIndex = Math.max(maxColIndex, x); maxRowIndex = Math.max(maxRowIndex, y); } } if (props.rowSpan > 1) { rowSpans.push(child); } if (props.colSpan > 1) { colSpans.push(child); } } // make sure all columns are defined so that accessing the grid using // this.__grid[column][row] will never raise an exception for (var y=0; y<=maxRowIndex; y++) { if (grid[y] == undefined) { grid[y] = []; } } this.__grid = grid; this.__colSpans = colSpans; this.__rowSpans = rowSpans; this.__maxRowIndex = maxRowIndex; this.__maxColIndex = maxColIndex; this.__rowHeights = null; this.__colWidths = null; // Clear invalidation marker delete this._invalidChildrenCache; }, /** * Stores data for a grid row * * @param row {Integer} The row index * @param key {String} The key under which the data should be stored * @param value {var} data to store */ _setRowData : function(row, key, value) { var rowData = this.__rowData[row]; if (!rowData) { this.__rowData[row] = {}; this.__rowData[row][key] = value; } else { rowData[key] = value; } }, /** * Stores data for a grid column * * @param column {Integer} The column index * @param key {String} The key under which the data should be stored * @param value {var} data to store */ _setColumnData : function(column, key, value) { var colData = this.__colData[column]; if (!colData) { this.__colData[column] = {}; this.__colData[column][key] = value; } else { colData[key] = value; } }, /** * Shortcut to set both horizontal and vertical spacing between grid cells * to the same value. * * @param spacing {Integer} new horizontal and vertical spacing * @return {qx.ui.layout.Grid} This object (for chaining support). */ setSpacing : function(spacing) { this.setSpacingY(spacing); this.setSpacingX(spacing); return this; }, /** * Set the default cell alignment for a column. This alignment can be * overridden on a per cell basis by setting the cell's content widget's * <code>alignX</code> and <code>alignY</code> properties. * * If on a grid cell both row and a column alignment is set, the horizontal * alignment is taken from the column and the vertical alignment is taken * from the row. * * @param column {Integer} Column index * @param hAlign {String} The horizontal alignment. Valid values are * "left", "center" and "right". * @param vAlign {String} The vertical alignment. Valid values are * "top", "middle", "bottom" * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnAlign : function(column, hAlign, vAlign) { if (qx.core.Environment.get("qx.debug")) { this.assertInteger(column, "Invalid parameter 'column'"); this.assertInArray(hAlign, ["left", "center", "right"]); this.assertInArray(vAlign, ["top", "middle", "bottom"]); } this._setColumnData(column, "hAlign", hAlign); this._setColumnData(column, "vAlign", vAlign); this._applyLayoutChange(); return this; }, /** * Get a map of the column's alignment. * * @param column {Integer} The column index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal column alignment. */ getColumnAlign : function(column) { var colData = this.__colData[column] || {}; return { vAlign : colData.vAlign || "top", hAlign : colData.hAlign || "left" }; }, /** * Set the default cell alignment for a row. This alignment can be * overridden on a per cell basis by setting the cell's content widget's * <code>alignX</code> and <code>alignY</code> properties. * * If on a grid cell both row and a column alignment is set, the horizontal * alignment is taken from the column and the vertical alignment is taken * from the row. * * @param row {Integer} Row index * @param hAlign {String} The horizontal alignment. Valid values are * "left", "center" and "right". * @param vAlign {String} The vertical alignment. Valid values are * "top", "middle", "bottom" * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowAlign : function(row, hAlign, vAlign) { if (qx.core.Environment.get("qx.debug")) { this.assertInteger(row, "Invalid parameter 'row'"); this.assertInArray(hAlign, ["left", "center", "right"]); this.assertInArray(vAlign, ["top", "middle", "bottom"]); } this._setRowData(row, "hAlign", hAlign); this._setRowData(row, "vAlign", vAlign); this._applyLayoutChange(); return this; }, /** * Get a map of the row's alignment. * * @param row {Integer} The Row index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal row alignment. */ getRowAlign : function(row) { var rowData = this.__rowData[row] || {}; return { vAlign : rowData.vAlign || "top", hAlign : rowData.hAlign || "left" }; }, /** * Get the widget located in the cell. If a the cell is empty or the widget * has a {@link qx.ui.core.Widget#visibility} value of <code>exclude</code>, * <code>null</code> is returned. * * @param row {Integer} The cell's row index * @param column {Integer} The cell's column index * @return {qx.ui.core.Widget|null}The cell's widget. The value may be null. */ getCellWidget : function(row, column) { if (this._invalidChildrenCache) { this.__buildGrid(); } var row = this.__grid[row] || {}; return row[column] || null; }, /** * Get the number of rows in the grid layout. * * @return {Integer} The number of rows in the layout */ getRowCount : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } return this.__maxRowIndex + 1; }, /** * Get the number of columns in the grid layout. * * @return {Integer} The number of columns in the layout */ getColumnCount : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } return this.__maxColIndex + 1; }, /** * Get a map of the cell's alignment. For vertical alignment the row alignment * takes precedence over the column alignment. For horizontal alignment it is * the over way round. If an alignment is set on the cell widget using * {@link qx.ui.core.LayoutItem#setLayoutProperties}, this alignment takes * always precedence over row or column alignment. * * @param row {Integer} The cell's row index * @param column {Integer} The cell's column index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal cell alignment. */ getCellAlign : function(row, column) { var vAlign = "top"; var hAlign = "left"; var rowData = this.__rowData[row]; var colData = this.__colData[column]; var widget = this.__grid[row][column]; if (widget) { var widgetProps = { vAlign : widget.getAlignY(), hAlign : widget.getAlignX() } } else { widgetProps = {}; } // compute vAlign // precedence : widget -> row -> column if (widgetProps.vAlign) { vAlign = widgetProps.vAlign; } else if (rowData && rowData.vAlign) { vAlign = rowData.vAlign; } else if (colData && colData.vAlign) { vAlign = colData.vAlign; } // compute hAlign // precedence : widget -> column -> row if (widgetProps.hAlign) { hAlign = widgetProps.hAlign; } else if (colData && colData.hAlign) { hAlign = colData.hAlign; } else if (rowData && rowData.hAlign) { hAlign = rowData.hAlign; } return { vAlign : vAlign, hAlign : hAlign } }, /** * Set the flex value for a grid column. * By default the column flex value is <code>0</code>. * * @param column {Integer} The column index * @param flex {Integer} The column's flex value * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnFlex : function(column, flex) { this._setColumnData(column, "flex", flex); this._applyLayoutChange(); return this; }, /** * Get the flex value of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's flex value */ getColumnFlex : function(column) { var colData = this.__colData[column] || {}; return colData.flex !== undefined ? colData.flex : 0; }, /** * Set the flex value for a grid row. * By default the row flex value is <code>0</code>. * * @param row {Integer} The row index * @param flex {Integer} The row's flex value * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowFlex : function(row, flex) { this._setRowData(row, "flex", flex); this._applyLayoutChange(); return this; }, /** * Get the flex value of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's flex value */ getRowFlex : function(row) { var rowData = this.__rowData[row] || {}; var rowFlex = rowData.flex !== undefined ? rowData.flex : 0 return rowFlex; }, /** * Set the maximum width of a grid column. * The default value is <code>Infinity</code>. * * @param column {Integer} The column index * @param maxWidth {Integer} The column's maximum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnMaxWidth : function(column, maxWidth) { this._setColumnData(column, "maxWidth", maxWidth); this._applyLayoutChange(); return this; }, /** * Get the maximum width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's maximum width */ getColumnMaxWidth : function(column) { var colData = this.__colData[column] || {}; return colData.maxWidth !== undefined ? colData.maxWidth : Infinity; }, /** * Set the preferred width of a grid column. * The default value is <code>Infinity</code>. * * @param column {Integer} The column index * @param width {Integer} The column's width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnWidth : function(column, width) { this._setColumnData(column, "width", width); this._applyLayoutChange(); return this; }, /** * Get the preferred width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's width */ getColumnWidth : function(column) { var colData = this.__colData[column] || {}; return colData.width !== undefined ? colData.width : null; }, /** * Set the minimum width of a grid column. * The default value is <code>0</code>. * * @param column {Integer} The column index * @param minWidth {Integer} The column's minimum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnMinWidth : function(column, minWidth) { this._setColumnData(column, "minWidth", minWidth); this._applyLayoutChange(); return this; }, /** * Get the minimum width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's minimum width */ getColumnMinWidth : function(column) { var colData = this.__colData[column] || {}; return colData.minWidth || 0; }, /** * Set the maximum height of a grid row. * The default value is <code>Infinity</code>. * * @param row {Integer} The row index * @param maxHeight {Integer} The row's maximum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowMaxHeight : function(row, maxHeight) { this._setRowData(row, "maxHeight", maxHeight); this._applyLayoutChange(); return this; }, /** * Get the maximum height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's maximum width */ getRowMaxHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.maxHeight || Infinity; }, /** * Set the preferred height of a grid row. * The default value is <code>Infinity</code>. * * @param row {Integer} The row index * @param height {Integer} The row's width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowHeight : function(row, height) { this._setRowData(row, "height", height); this._applyLayoutChange(); return this; }, /** * Get the preferred height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's width */ getRowHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.height !== undefined ? rowData.height : null; }, /** * Set the minimum height of a grid row. * The default value is <code>0</code>. * * @param row {Integer} The row index * @param minHeight {Integer} The row's minimum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowMinHeight : function(row, minHeight) { this._setRowData(row, "minHeight", minHeight); this._applyLayoutChange(); return this; }, /** * Get the minimum height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's minimum width */ getRowMinHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.minHeight || 0; }, /** * Computes the widget's size hint including the widget's margins * * @param widget {qx.ui.core.LayoutItem} The widget to get the size for * @return {Map} a size hint map */ __getOuterSize : function(widget) { var hint = widget.getSizeHint(); var hMargins = widget.getMarginLeft() + widget.getMarginRight(); var vMargins = widget.getMarginTop() + widget.getMarginBottom(); var outerSize = { height: hint.height + vMargins, width: hint.width + hMargins, minHeight: hint.minHeight + vMargins, minWidth: hint.minWidth + hMargins, maxHeight: hint.maxHeight + vMargins, maxWidth: hint.maxWidth + hMargins } return outerSize; }, /** * Check whether all row spans fit with their preferred height into the * preferred row heights. If there is not enough space, the preferred * row sizes are increased. The distribution respects the flex and max * values of the rows. * * The same is true for the min sizes. * * The height array is modified in place. * * @param rowHeights {Map[]} The current row height array as computed by * {@link #_getRowHeights}. */ _fixHeightsRowSpan : function(rowHeights) { var vSpacing = this.getSpacingY(); for (var i=0, l=this.__rowSpans.length; i<l; i++) { var widget = this.__rowSpans[i]; var hint = this.__getOuterSize(widget); var widgetProps = widget.getLayoutProperties(); var widgetRow = widgetProps.row; var prefSpanHeight = vSpacing * (widgetProps.rowSpan - 1); var minSpanHeight = prefSpanHeight; var rowFlexes = {}; for (var j=0; j<widgetProps.rowSpan; j++) { var row = widgetProps.row+j; var rowHeight = rowHeights[row]; var rowFlex = this.getRowFlex(row); if (rowFlex > 0) { // compute flex array for the preferred height rowFlexes[row] = { min : rowHeight.minHeight, value : rowHeight.height, max : rowHeight.maxHeight, flex: rowFlex }; } prefSpanHeight += rowHeight.height; minSpanHeight += rowHeight.minHeight; } // If there is not enough space for the preferred size // increment the preferred row sizes. if (prefSpanHeight < hint.height) { if (!qx.lang.Object.isEmpty(rowFlexes)) { var rowIncrements = qx.ui.layout.Util.computeFlexOffsets( rowFlexes, hint.height, prefSpanHeight ); for (var k=0; k<widgetProps.rowSpan; k++) { var offset = rowIncrements[widgetRow+k] ? rowIncrements[widgetRow+k].offset : 0; rowHeights[widgetRow+k].height += offset; } // row is too small and we have no flex value set } else { var totalSpacing = vSpacing * (widgetProps.rowSpan - 1); var availableHeight = hint.height - totalSpacing; // get the row height which every child would need to share the // available hight equally var avgRowHeight = Math.floor(availableHeight / widgetProps.rowSpan); // get the hight already used and the number of children which do // not have at least that avg row height var usedHeight = 0; var rowsNeedAddition = 0; for (var k = 0; k < widgetProps.rowSpan; k++) { var currentHeight = rowHeights[widgetRow + k].height; usedHeight += currentHeight; if (currentHeight < avgRowHeight) { rowsNeedAddition++; } } // the difference of available and used needs to be shared among // those not having the min size var additionalRowHeight = Math.floor((availableHeight - usedHeight) / rowsNeedAddition); // add the extra height to the too small children for (var k = 0; k < widgetProps.rowSpan; k++) { if (rowHeights[widgetRow + k].height < avgRowHeight) { rowHeights[widgetRow + k].height += additionalRowHeight; } } } } // If there is not enough space for the min size // increment the min row sizes. if (minSpanHeight < hint.minHeight) { var rowIncrements = qx.ui.layout.Util.computeFlexOffsets( rowFlexes, hint.minHeight, minSpanHeight ); for (var j=0; j<widgetProps.rowSpan; j++) { var offset = rowIncrements[widgetRow+j] ? rowIncrements[widgetRow+j].offset : 0; rowHeights[widgetRow+j].minHeight += offset; } } } }, /** * Check whether all col spans fit with their preferred width into the * preferred column widths. If there is not enough space the preferred * column sizes are increased. The distribution respects the flex and max * values of the columns. * * The same is true for the min sizes. * * The width array is modified in place. * * @param colWidths {Map[]} The current column width array as computed by * {@link #_getColWidths}. */ _fixWidthsColSpan : function(colWidths) { var hSpacing = this.getSpacingX(); for (var i=0, l=this.__colSpans.length; i<l; i++) { var widget = this.__colSpans[i]; var hint = this.__getOuterSize(widget); var widgetProps = widget.getLayoutProperties(); var widgetColumn = widgetProps.column; var prefSpanWidth = hSpacing * (widgetProps.colSpan - 1); var minSpanWidth = prefSpanWidth; var colFlexes = {}; var offset; for (var j=0; j<widgetProps.colSpan; j++) { var col = widgetProps.column+j; var colWidth = colWidths[col]; var colFlex = this.getColumnFlex(col); // compute flex array for the preferred width if (colFlex > 0) { colFlexes[col] = { min : colWidth.minWidth, value : colWidth.width, max : colWidth.maxWidth, flex: colFlex }; } prefSpanWidth += colWidth.width; minSpanWidth += colWidth.minWidth; } // If there is not enought space for the preferred size // increment the preferred column sizes. if (prefSpanWidth < hint.width) { var colIncrements = qx.ui.layout.Util.computeFlexOffsets( colFlexes, hint.width, prefSpanWidth ); for (var j=0; j<widgetProps.colSpan; j++) { offset = colIncrements[widgetColumn+j] ? colIncrements[widgetColumn+j].offset : 0; colWidths[widgetColumn+j].width += offset; } } // If there is not enought space for the min size // increment the min column sizes. if (minSpanWidth < hint.minWidth) { var colIncrements = qx.ui.layout.Util.computeFlexOffsets( colFlexes, hint.minWidth, minSpanWidth ); for (var j=0; j<widgetProps.colSpan; j++) { offset = colIncrements[widgetColumn+j] ? colIncrements[widgetColumn+j].offset : 0; colWidths[widgetColumn+j].minWidth += offset; } } } }, /** * Compute the min/pref/max row heights. * * @return {Map[]} An array containg height information for each row. The * entries have the keys <code>minHeight</code>, <code>maxHeight</code> and * <code>height</code>. */ _getRowHeights : function() { if (this.__rowHeights != null) { return this.__rowHeights; } var rowHeights = []; var maxRowIndex = this.__maxRowIndex; var maxColIndex = this.__maxColIndex; for (var row=0; row<=maxRowIndex; row++) { var minHeight = 0; var height = 0; var maxHeight = 0; for (var col=0; col<=maxColIndex; col++) { var widget = this.__grid[row][col]; if (!widget) { continue; } // ignore rows with row spans at this place // these rows will be taken into account later var widgetRowSpan = widget.getLayoutProperties().rowSpan || 0; if (widgetRowSpan > 1) { continue; } var cellSize = this.__getOuterSize(widget); if (this.getRowFlex(row) > 0) { minHeight = Math.max(minHeight, cellSize.minHeight); } else { minHeight = Math.max(minHeight, cellSize.height); } height = Math.max(height, cellSize.height); } var minHeight = Math.max(minHeight, this.getRowMinHeight(row)); var maxHeight = this.getRowMaxHeight(row); if (this.getRowHeight(row) !== null) { var height = this.getRowHeight(row); } else { var height = Math.max(minHeight, Math.min(height, maxHeight)); } rowHeights[row] = { minHeight : minHeight, height : height, maxHeight : maxHeight }; } if (this.__rowSpans.length > 0) { this._fixHeightsRowSpan(rowHeights); } this.__rowHeights = rowHeights; return rowHeights; }, /** * Compute the min/pref/max column widths. * * @return {Map[]} An array containg width information for each column. The * entries have the keys <code>minWidth</code>, <code>maxWidth</code> and * <code>width</code>. */ _getColWidths : function() { if (this.__colWidths != null) { return this.__colWidths; } var colWidths = []; var maxColIndex = this.__maxColIndex; var maxRowIndex = this.__maxRowIndex; for (var col=0; col<=maxColIndex; col++) { var width = 0; var minWidth = 0; var maxWidth = Infinity; for (var row=0; row<=maxRowIndex; row++) { var widget = this.__grid[row][col]; if (!widget) { continue; } // ignore columns with col spans at this place // these columns will be taken into account later var widgetColSpan = widget.getLayoutProperties().colSpan || 0; if (widgetColSpan > 1) { continue; } var cellSize = this.__getOuterSize(widget); if (this.getColumnFlex(col) > 0) { minWidth = Math.max(minWidth, cellSize.minWidth); } else { minWidth = Math.max(minWidth, cellSize.width); } width = Math.max(width, cellSize.width); } minWidth = Math.max(minWidth, this.getColumnMinWidth(col)); maxWidth = this.getColumnMaxWidth(col); if (this.getColumnWidth(col) !== null) { var width = this.getColumnWidth(col); } else { var width = Math.max(minWidth, Math.min(width, maxWidth)); } colWidths[col] = { minWidth: minWidth, width : width, maxWidth : maxWidth }; } if (this.__colSpans.length > 0) { this._fixWidthsColSpan(colWidths); } this.__colWidths = colWidths; return colWidths; }, /** * Computes for each column by how many pixels it must grow or shrink, taking * the column flex values and min/max widths into account. * * @param width {Integer} The grid width * @return {Integer[]} Sparse array of offsets to add to each column width. If * an array entry is empty nothing should be added to the column. */ _getColumnFlexOffsets : function(width) { var hint = this.getSizeHint(); var diff = width - hint.width; if (diff == 0) { return {}; } // collect all flexible children var colWidths = this._getColWidths(); var flexibles = {}; for (var i=0, l=colWidths.length; i<l; i++) { var col = colWidths[i]; var colFlex = this.getColumnFlex(i); if ( (colFlex <= 0) || (col.width == col.maxWidth && diff > 0) || (col.width == col.minWidth && diff < 0) ) { continue; } flexibles[i] ={ min : col.minWidth, value : col.width, max : col.maxWidth, flex : colFlex }; } return qx.ui.layout.Util.computeFlexOffsets(flexibles, width, hint.width); }, /** * Computes for each row by how many pixels it must grow or shrink, taking * the row flex values and min/max heights into account. * * @param height {Integer} The grid height * @return {Integer[]} Sparse array of offsets to add to each row height. If * an array entry is empty nothing should be added to the row. */ _getRowFlexOffsets : function(height) { var hint = this.getSizeHint(); var diff = height - hint.height; if (diff == 0) { return {}; } // collect all flexible children var rowHeights = this._getRowHeights(); var flexibles = {}; for (var i=0, l=rowHeights.length; i<l; i++) { var row = rowHeights[i]; var rowFlex = this.getRowFlex(i); if ( (rowFlex <= 0) || (row.height == row.maxHeight && diff > 0) || (row.height == row.minHeight && diff < 0) ) { continue; } flexibles[i] = { min : row.minHeight, value : row.height, max : row.maxHeight, flex : rowFlex }; } return qx.ui.layout.Util.computeFlexOffsets(flexibles, height, hint.height); }, // overridden renderLayout : function(availWidth, availHeight) { if (this._invalidChildrenCache) { this.__buildGrid(); } var Util = qx.ui.layout.Util; var hSpacing = this.getSpacingX(); var vSpacing = this.getSpacingY(); // calculate column widths var prefWidths = this._getColWidths(); var colStretchOffsets = this._getColumnFlexOffsets(availWidth); var colWidths = []; var maxColIndex = this.__maxColIndex; var maxRowIndex = this.__maxRowIndex; var offset; for (var col=0; col<=maxColIndex; col++) { offset = colStretchOffsets[col] ? colStretchOffsets[col].offset : 0; colWidths[col] = prefWidths[col].width + offset; } // calculate row heights var prefHeights = this._getRowHeights(); var rowStretchOffsets = this._getRowFlexOffsets(availHeight); var rowHeights = []; for (var row=0; row<=maxRowIndex; row++) { offset = rowStretchOffsets[row] ? rowStretchOffsets[row].offset : 0; rowHeights[row] = prefHeights[row].height + offset; } // do the layout var left = 0; for (var col=0; col<=maxColIndex; col++) { var top = 0; for (var row=0; row<=maxRowIndex; row++) { var widget = this.__grid[row][col]; // ignore empty cells if (!widget) { top += rowHeights[row] + vSpacing; continue; } var widgetProps = widget.getLayoutProperties(); // ignore cells, which have cell spanning but are not the origin // of the widget if(widgetProps.row !== row || widgetProps.column !== col) { top += rowHeights[row] + vSpacing; continue; } // compute sizes width including cell spanning var spanWidth = hSpacing * (widgetProps.colSpan - 1); for (var i=0; i<widgetProps.colSpan; i++) { spanWidth += colWidths[col+i]; } var spanHeight = vSpacing * (widgetProps.rowSpan - 1); for (var i=0; i<widgetProps.rowSpan; i++) { spanHeight += rowHeights[row+i]; } var cellHint = widget.getSizeHint(); var marginTop = widget.getMarginTop(); var marginLeft = widget.getMarginLeft(); var marginBottom = widget.getMarginBottom(); var marginRight = widget.getMarginRight(); var cellWidth = Math.max(cellHint.minWidth, Math.min(spanWidth-marginLeft-marginRight, cellHint.maxWidth)); var cellHeight = Math.max(cellHint.minHeight, Math.min(spanHeight-marginTop-marginBottom, cellHint.maxHeight)); var cellAlign = this.getCellAlign(row, col); var cellLeft = left + Util.computeHorizontalAlignOffset(cellAlign.hAlign, cellWidth, spanWidth, marginLeft, marginRight); var cellTop = top + Util.computeVerticalAlignOffset(cellAlign.vAlign, cellHeight, spanHeight, marginTop, marginBottom); widget.renderLayout( cellLeft, cellTop, cellWidth, cellHeight ); top += rowHeights[row] + vSpacing; } left += colWidths[col] + hSpacing; } }, // overridden invalidateLayoutCache : function() { this.base(arguments); this.__colWidths = null; this.__rowHeights = null; }, // overridden _computeSizeHint : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } // calculate col widths var colWidths = this._getColWidths(); var minWidth=0, width=0; for (var i=0, l=colWidths.length; i<l; i++) { var col = colWidths[i]; if (this.getColumnFlex(i) > 0) { minWidth += col.minWidth; } else { minWidth += col.width; } width += col.width; } // calculate row heights var rowHeights = this._getRowHeights(); var minHeight=0, height=0; for (var i=0, l=rowHeights.length; i<l; i++) { var row = rowHeights[i]; if (this.getRowFlex(i) > 0) { minHeight += row.minHeight; } else { minHeight += row.height; } height += row.height; } var spacingX = this.getSpacingX() * (colWidths.length - 1); var spacingY = this.getSpacingY() * (rowHeights.length - 1); var hint = { minWidth : minWidth + spacingX, width : width + spacingX, minHeight : minHeight + spacingY, height : height + spacingY }; return hint; } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__grid = this.__rowData = this.__colData = this.__colSpans = this.__rowSpans = this.__colWidths = this.__rowHeights = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This is a basic form field with common functionality for * {@link TextArea} and {@link TextField}. * * On every keystroke the value is synchronized with the * value of the textfield. Value changes can be monitored by listening to the * {@link #input} or {@link #changeValue} events, respectively. */ qx.Class.define("qx.ui.form.AbstractField", { extend : qx.ui.core.Widget, implement : [ qx.ui.form.IStringForm, qx.ui.form.IForm ], include : [ qx.ui.form.MForm ], type : "abstract", /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param value {String} initial text value of the input field ({@link #setValue}). */ construct : function(value) { this.base(arguments); // shortcut for placeholder feature detection this.__useQxPlaceholder = !qx.core.Environment.get("css.placeholder") || (qx.core.Environment.get("engine.name") == "gecko" && parseFloat(qx.core.Environment.get("engine.version")) >= 2); if (value != null) { this.setValue(value); } this.getContentElement().addListener( "change", this._onChangeContent, this ); // use qooxdoo placeholder if no native placeholder is supported if (this.__useQxPlaceholder) { // assign the placeholder text after the appearance has been applied this.addListener("syncAppearance", this._syncPlaceholder, this); } // translation support if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener( "changeLocale", this._onChangeLocale, this ); } }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * The event is fired on every keystroke modifying the value of the field. * * The method {@link qx.event.type.Data#getData} returns the * current value of the text field. */ "input" : "qx.event.type.Data", /** * The event is fired each time the text field looses focus and the * text field values has changed. * * If you change {@link #liveUpdate} to true, the changeValue event will * be fired after every keystroke and not only after every focus loss. In * that mode, the changeValue event is equal to the {@link #input} event. * * The method {@link qx.event.type.Data#getData} returns the * current text value of the field. */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Alignment of the text */ textAlign : { check : [ "left", "center", "right" ], nullable : true, themeable : true, apply : "_applyTextAlign" }, /** Whether the field is read only */ readOnly : { check : "Boolean", apply : "_applyReadOnly", event : "changeReadOnly", init : false }, // overridden selectable : { refine : true, init : true }, // overridden focusable : { refine : true, init : true }, /** Maximal number of characters that can be entered in the TextArea. */ maxLength : { check : "PositiveInteger", init : Infinity }, /** * Whether the {@link #changeValue} event should be fired on every key * input. If set to true, the changeValue event is equal to the * {@link #input} event. */ liveUpdate : { check : "Boolean", init : false }, /** * String value which will be shown as a hint if the field is all of: * unset, unfocused and enabled. Set to null to not show a placeholder * text. */ placeholder : { check : "String", nullable : true, apply : "_applyPlaceholder" }, /** * RegExp responsible for filtering the value of the textfield. the RegExp * gives the range of valid values. * The following example only allows digits in the textfield. * <pre class='javascript'>field.setFilter(/[0-9]/);</pre> */ filter : { check : "RegExp", nullable : true, init : null } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __nullValue : true, __placeholder : null, __oldValue : null, __oldInputValue : null, __useQxPlaceholder : true, __font : null, __webfontListenerId : null, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden getFocusElement : function() { var el = this.getContentElement(); if (el) { return el; } }, /** * Creates the input element. Derived classes may override this * method, to create different input elements. * * @return {qx.html.Input} a new input element. */ _createInputElement : function() { return new qx.html.Input("text"); }, // overridden renderLayout : function(left, top, width, height) { var updateInsets = this._updateInsets; var changes = this.base(arguments, left, top, width, height); // Directly return if superclass has detected that no // changes needs to be applied if (!changes) { return; } var inner = changes.size || updateInsets; var pixel = "px"; if (inner || changes.local || changes.margin) { var insets = this.getInsets(); var innerWidth = width - insets.left - insets.right; var innerHeight = height - insets.top - insets.bottom; // ensure that the width and height never get negative innerWidth = innerWidth < 0 ? 0 : innerWidth; innerHeight = innerHeight < 0 ? 0 : innerHeight; } var input = this.getContentElement(); // we don't need to update positions on native placeholders if (updateInsets && this.__useQxPlaceholder) { // render the placeholder this.__getPlaceholderElement().setStyles({ "left": insets.left + pixel, "top": insets.top + pixel }); } if (inner) { // we don't need to update dimensions on native placeholders if (this.__useQxPlaceholder) { this.__getPlaceholderElement().setStyles({ "width": innerWidth + pixel, "height": innerHeight + pixel }); } input.setStyles({ "width": innerWidth + pixel, "height": innerHeight + pixel }); this._renderContentElement(innerHeight, input); } }, /** * Hook into {@link qx.ui.form.AbstractField#renderLayout} method. * Called after the contentElement has a width and an innerWidth. * * Note: This was introduced to fix BUG#1585 * * @param innerHeight {Integer} The inner height of the element. * @param element {Element} The element. */ _renderContentElement : function(innerHeight, element) { //use it in child classes }, // overridden _createContentElement : function() { // create and add the input element var el = this._createInputElement(); // Apply styles el.setStyles( { "border": "none", "padding": 0, "margin": 0, "display" : "block", "background" : "transparent", "outline": "none", "appearance": "none", "position": "absolute", "autoComplete": "off" }); // initialize the html input el.setSelectable(this.getSelectable()); el.setEnabled(this.getEnabled()); // Add listener for input event el.addListener("input", this._onHtmlInput, this); // Disable HTML5 spell checking el.setAttribute("spellcheck", "false"); // Block resize handle el.setStyle("resize", "none"); // IE8 in standard mode needs some extra love here to receive events. if ((qx.core.Environment.get("engine.name") == "mshtml")) { el.setStyles({ backgroundImage: "url(" + qx.util.ResourceManager.getInstance().toUri("qx/static/blank.gif") + ")" }); } return el; }, // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); this.getContentElement().setEnabled(value); if (this.__useQxPlaceholder) { if (value) { this._showPlaceholder(); } else { this._removePlaceholder(); } } else { var input = this.getContentElement(); // remove the placeholder on disabled input elements input.setAttribute("placeholder", value ? this.getPlaceholder() : ""); } }, // default text sizes /** * @lint ignoreReferenceField(__textSize) */ __textSize : { width : 16, height : 16 }, // overridden _getContentHint : function() { return { width : this.__textSize.width * 10, height : this.__textSize.height || 16 }; }, // overridden _applyFont : function(value, old) { if (old && this.__font && this.__webfontListenerId) { this.__font.removeListenerById(this.__webfontListenerId); this.__webfontListenerId = null; } // Apply var styles; if (value) { this.__font = qx.theme.manager.Font.getInstance().resolve(value); if (this.__font instanceof qx.bom.webfonts.WebFont) { this.__webfontListenerId = this.__font.addListener("changeStatus", this._onWebFontStatusChange, this); } styles = this.__font.getStyles(); } else { styles = qx.bom.Font.getDefaultStyles(); } // check if text color already set - if so this local value has higher priority if (this.getTextColor() != null) { delete styles["color"]; } // apply the font to the content element this.getContentElement().setStyles(styles); // the font will adjust automatically on native placeholders if (this.__useQxPlaceholder) { // don't apply the color to the placeholder delete styles["color"]; // apply the font to the placeholder this.__getPlaceholderElement().setStyles(styles); } // Compute text size if (value) { this.__textSize = qx.bom.Label.getTextSize("A", styles); } else { delete this.__textSize; } // Update layout qx.ui.core.queue.Layout.add(this); }, // overridden _applyTextColor : function(value, old) { if (value) { this.getContentElement().setStyle( "color", qx.theme.manager.Color.getInstance().resolve(value) ); } else { this.getContentElement().removeStyle("color"); } }, // overridden tabFocus : function() { this.base(arguments); this.selectAllText(); }, /** * Returns the text size. * @return {Map} The text size. */ _getTextSize : function() { return this.__textSize; }, /* --------------------------------------------------------------------------- EVENTS --------------------------------------------------------------------------- */ /** * Event listener for native input events. Redirects the event * to the widget. Also checks for the filter and max length. * * @param e {qx.event.type.Data} Input event */ _onHtmlInput : function(e) { var value = e.getData(); var fireEvents = true; this.__nullValue = false; // value unchanged; Firefox fires "input" when pressing ESC [BUG #5309] if (this.__oldInputValue && this.__oldInputValue === value) { fireEvents = false; } // check for the filter if (this.getFilter() != null) { var filteredValue = ""; var index = value.search(this.getFilter()); var processedValue = value; while(index >= 0) { filteredValue = filteredValue + (processedValue.charAt(index)); processedValue = processedValue.substring(index + 1, processedValue.length); index = processedValue.search(this.getFilter()); } if (filteredValue != value) { fireEvents = false; value = filteredValue; this.getContentElement().setValue(value); } } // check for the max length if (value.length > this.getMaxLength()) { fireEvents = false; this.getContentElement().setValue( value.substr(0, this.getMaxLength()) ); } // fire the events, if necessary if (fireEvents) { // store the old input value this.fireDataEvent("input", value, this.__oldInputValue); this.__oldInputValue = value; // check for the live change event if (this.getLiveUpdate()) { this.__fireChangeValueEvent(value); } } }, /** * Triggers text size recalculation after a web font was loaded * * @param ev {qx.event.type.Data} "changeStatus" event */ _onWebFontStatusChange : function(ev) { if (ev.getData().valid === true) { var styles = this.__font.getStyles(); this.__textSize = qx.bom.Label.getTextSize("A", styles); qx.ui.core.queue.Layout.add(this); } }, /** * Handles the firing of the changeValue event including the local cache * for sending the old value in the event. * * @param value {String} The new value. */ __fireChangeValueEvent : function(value) { var old = this.__oldValue; this.__oldValue = value; if (old != value) { this.fireNonBubblingEvent( "changeValue", qx.event.type.Data, [value, old] ); } }, /* --------------------------------------------------------------------------- TEXTFIELD VALUE API --------------------------------------------------------------------------- */ /** * Sets the value of the textfield to the given value. * * @param value {String} The new value */ setValue : function(value) { // handle null values if (value === null) { // just do nothing if null is already set if (this.__nullValue) { return value; } value = ""; this.__nullValue = true; } else { this.__nullValue = false; // native placeholders will be removed by the browser if (this.__useQxPlaceholder) { this._removePlaceholder(); } } if (qx.lang.Type.isString(value)) { var elem = this.getContentElement(); if (value.length > this.getMaxLength()) { value = value.substr(0, this.getMaxLength()); } if (elem.getValue() != value) { var oldValue = elem.getValue(); elem.setValue(value); var data = this.__nullValue ? null : value; this.__oldValue = oldValue; this.__fireChangeValueEvent(data); } // native placeholders will be shown by the browser if (this.__useQxPlaceholder) { this._showPlaceholder(); } return value; } throw new Error("Invalid value type: " + value); }, /** * Returns the current value of the textfield. * * @return {String|null} The current value */ getValue : function() { var value = this.getContentElement().getValue(); return this.__nullValue ? null : value; }, /** * Resets the value to the default */ resetValue : function() { this.setValue(null); }, /** * Event listener for change event of content element * * @param e {qx.event.type.Data} Incoming change event */ _onChangeContent : function(e) { this.__nullValue = e.getData() === null; this.__fireChangeValueEvent(e.getData()); }, /* --------------------------------------------------------------------------- TEXTFIELD SELECTION API --------------------------------------------------------------------------- */ /** * Returns the current selection. * This method only works if the widget is already created and * added to the document. * * @return {String|null} */ getTextSelection : function() { return this.getContentElement().getTextSelection(); }, /** * Returns the current selection length. * This method only works if the widget is already created and * added to the document. * * @return {Integer|null} */ getTextSelectionLength : function() { return this.getContentElement().getTextSelectionLength(); }, /** * Returns the start of the text selection * * @return {Integer|null} Start of selection or null if not available */ getTextSelectionStart : function() { return this.getContentElement().getTextSelectionStart(); }, /** * Returns the end of the text selection * * @return {Integer|null} End of selection or null if not available */ getTextSelectionEnd : function() { return this.getContentElement().getTextSelectionEnd(); }, /** * Set the selection to the given start and end (zero-based). * If no end value is given the selection will extend to the * end of the textfield's content. * This method only works if the widget is already created and * added to the document. * * @param start {Integer} start of the selection (zero-based) * @param end {Integer} end of the selection * @return {void} */ setTextSelection : function(start, end) { this.getContentElement().setTextSelection(start, end); }, /** * Clears the current selection. * This method only works if the widget is already created and * added to the document. * * @return {void} */ clearTextSelection : function() { this.getContentElement().clearTextSelection(); }, /** * Selects the whole content * * @return {void} */ selectAllText : function() { this.setTextSelection(0); }, /* --------------------------------------------------------------------------- PLACEHOLDER HELPER --------------------------------------------------------------------------- */ /** * Helper to show the placeholder text in the field. It checks for all * states and possible conditions and shows the placeholder only if allowed. */ _showPlaceholder : function() { var fieldValue = this.getValue() || ""; var placeholder = this.getPlaceholder(); if ( placeholder != null && fieldValue == "" && !this.hasState("focused") && !this.hasState("disabled") ) { if (this.hasState("showingPlaceholder")) { this._syncPlaceholder(); } else { // the placeholder will be set as soon as the appearance is applied this.addState("showingPlaceholder"); } } }, /** * Helper to remove the placeholder. Deletes the placeholder text from the * field and removes the state. */ _removePlaceholder: function() { if (this.hasState("showingPlaceholder")) { this.__getPlaceholderElement().setStyle("visibility", "hidden"); this.removeState("showingPlaceholder"); } }, /** * Updates the placeholder text with the DOM */ _syncPlaceholder : function () { if (this.hasState("showingPlaceholder")) { this.__getPlaceholderElement().setStyle("visibility", "visible"); } }, /** * Returns the placeholder label and creates it if necessary. */ __getPlaceholderElement : function() { if (this.__placeholder == null) { // create the placeholder this.__placeholder = new qx.html.Label(); var colorManager = qx.theme.manager.Color.getInstance(); this.__placeholder.setStyles({ "visibility" : "hidden", "zIndex" : 6, "position" : "absolute", "color" : colorManager.resolve("text-placeholder") }); this.getContainerElement().add(this.__placeholder); } return this.__placeholder; }, /** * Locale change event handler * * @signature function(e) * @param e {Event} the change event */ _onChangeLocale : qx.core.Environment.select("qx.dynlocale", { "true" : function(e) { var content = this.getPlaceholder(); if (content && content.translate) { this.setPlaceholder(content.translate()); } }, "false" : null }), /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyPlaceholder : function(value, old) { if (this.__useQxPlaceholder) { this.__getPlaceholderElement().setValue(value); if (value != null) { this.addListener("focusin", this._removePlaceholder, this); this.addListener("focusout", this._showPlaceholder, this); this._showPlaceholder(); } else { this.removeListener("focusin", this._removePlaceholder, this); this.removeListener("focusout", this._showPlaceholder, this); this._removePlaceholder(); } } else { // only apply if the widget is enabled if (this.getEnabled()) { this.getContentElement().setAttribute("placeholder", value); } } }, // property apply _applyTextAlign : function(value, old) { this.getContentElement().setStyle("textAlign", value); }, // property apply _applyReadOnly : function(value, old) { var element = this.getContentElement(); element.setAttribute("readOnly", value); if (value) { this.addState("readonly"); this.setFocusable(false); } else { this.removeState("readonly"); this.setFocusable(true); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__placeholder = this.__font = null; if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this._onChangeLocale, this); } if (this.__font && this.__webfontListenerId) { this.__font.removeListenerById(this.__webfontListenerId); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Input wrap any valid HTML input element and make it accessible * through the normalized qooxdoo element interface. */ qx.Class.define("qx.html.Input", { extend : qx.html.Element, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param type {String} The type of the input field. Valid values are * <code>text</code>, <code>textarea</code>, <code>select</code>, * <code>checkbox</code>, <code>radio</code>, <code>password</code>, * <code>hidden</code>, <code>submit</code>, <code>image</code>, * <code>file</code>, <code>search</code>, <code>reset</code>, * <code>select</code> and <code>textarea</code>. * @param styles {Map?null} optional map of CSS styles, where the key is the name * of the style and the value is the value to use. * @param attributes {Map?null} optional map of element attributes, where the * key is the name of the attribute and the value is the value to use. */ construct : function(type, styles, attributes) { // Update node name correctly if (type === "select" || type === "textarea") { var nodeName = type; } else { nodeName = "input"; } this.base(arguments, nodeName, styles, attributes); this.__type = type; }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __type : null, // used for webkit only __selectable : null, __enabled : null, /* --------------------------------------------------------------------------- ELEMENT API --------------------------------------------------------------------------- */ //overridden _createDomElement : function() { return qx.bom.Input.create(this.__type); }, // overridden _applyProperty : function(name, value) { this.base(arguments, name, value); var element = this.getDomElement(); if (name === "value") { qx.bom.Input.setValue(element, value); } else if (name === "wrap") { qx.bom.Input.setWrap(element, value); // qx.bom.Input#setWrap has the side-effect that the CSS property // overflow is set via DOM methods, causing queue and DOM to get // out of sync. Mirror all overflow properties to handle the case // when group and x/y property differ. this.setStyle("overflow", element.style.overflow, true); this.setStyle("overflowX", element.style.overflowX, true); this.setStyle("overflowY", element.style.overflowY, true); } }, /** * Set the input element enabled / disabled. * Webkit needs a special treatment because the set color of the input * field changes automatically. Therefore, we use * <code>-webkit-user-modify: read-only</code> and * <code>-webkit-user-select: none</code> * for disabling the fields in webkit. All other browsers use the disabled * attribute. * * @param value {Boolean} true, if the inpout element should be enabled. */ setEnabled : qx.core.Environment.select("engine.name", { "webkit" : function(value) { this.__enabled = value; if (!value) { this.setStyles({ "userModify": "read-only", "userSelect": "none" }); } else { this.setStyles({ "userModify": null, "userSelect": this.__selectable ? null : "none" }); } }, "default" : function(value) { this.setAttribute("disabled", value===false); } }), /** * Set whether the element is selectable. It uses the qooxdoo attribute * qxSelectable with the values 'on' or 'off'. * In webkit, a special css property will be used and checks for the * enabled state. * * @param value {Boolean} True, if the element should be selectable. */ setSelectable : qx.core.Environment.select("engine.name", { "webkit" : function(value) { this.__selectable = value; // Only apply the value when it is enabled this.base(arguments, this.__enabled && value); }, "default" : function(value) { this.base(arguments, value); } }), /* --------------------------------------------------------------------------- INPUT API --------------------------------------------------------------------------- */ /** * Sets the value of the input element. * * @param value {var} the new value * @return {qx.html.Input} This instance for for chaining support. */ setValue : function(value) { var element = this.getDomElement(); if (element) { // Do not overwrite when already correct (on input events) // This is needed to keep caret position while typing. if (element.value != value) { qx.bom.Input.setValue(element, value); } } else { this._setProperty("value", value); } return this; }, /** * Get the current value. * * @return {String} The element's current value. */ getValue : function() { var element = this.getDomElement(); if (element) { return qx.bom.Input.getValue(element); } return this._getProperty("value") || ""; }, /** * Sets the text wrap behavior of a text area element. * * This property uses the style property "wrap" (IE) respectively "whiteSpace" * * @param wrap {Boolean} Whether to turn text wrap on or off. * @param direct {Boolean?false} Whether the execution should be made * directly when possible * @return {qx.html.Input} This instance for for chaining support. */ setWrap : function(wrap, direct) { if (this.__type === "textarea") { this._setProperty("wrap", wrap, direct); } else { throw new Error("Text wrapping is only support by textareas!"); } return this; }, /** * Gets the text wrap behavior of a text area element. * * This property uses the style property "wrap" (IE) respectively "whiteSpace" * * @return {Boolean} Whether wrapping is enabled or disabled. */ getWrap : function() { if (this.__type === "textarea") { return this._getProperty("wrap"); } else { throw new Error("Text wrapping is only support by textareas!"); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array#contains) ************************************************************************ */ /** * Cross browser abstractions to work with input elements. */ qx.Bootstrap.define("qx.bom.Input", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structures with all supported input types */ __types : { text : 1, textarea : 1, select : 1, checkbox : 1, radio : 1, password : 1, hidden : 1, submit : 1, image : 1, file : 1, search : 1, reset : 1, button : 1 }, /** * Creates an DOM input/textarea/select element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Note: <code>select</code> and <code>textarea</code> elements are created * using the identically named <code>type</code>. * * @param type {String} Any valid type for HTML, <code>select</code> * and <code>textarea</code> * @param attributes {Map} Map of attributes to apply * @param win {Window} Window to create the element for * @return {Element} The created input node */ create : function(type, attributes, win) { if (qx.core.Environment.get("qx.debug")) { qx.core.Assert.assertKeyInMap(type, this.__types, "Unsupported input type."); } // Work on a copy to not modify given attributes map var attributes = attributes ? qx.lang.Object.clone(attributes) : {}; var tag; if (type === "textarea" || type === "select") { tag = type; } else { tag = "input"; attributes.type = type; } return qx.dom.Element.create(tag, attributes, win); }, /** * Applies the given value to the element. * * Normally the value is given as a string/number value and applied * to the field content (textfield, textarea) or used to * detect whether the field is checked (checkbox, radiobutton). * * Supports array values for selectboxes (multiple-selection) * and checkboxes or radiobuttons (for convenience). * * Please note: To modify the value attribute of a checkbox or * radiobutton use {@link qx.bom.element.Attribute#set} instead. * * @param element {Element} element to update * @param value {String|Number|Array} the value to apply */ setValue : function(element, value) { var tag = element.nodeName.toLowerCase(); var type = element.type; var Array = qx.lang.Array; var Type = qx.lang.Type; if (typeof value === "number") { value += ""; } if ((type === "checkbox" || type === "radio")) { if (Type.isArray(value)) { element.checked = Array.contains(value, element.value); } else { element.checked = element.value == value; } } else if (tag === "select") { var isArray = Type.isArray(value); var options = element.options; var subel, subval; for (var i=0, l=options.length; i<l; i++) { subel = options[i]; subval = subel.getAttribute("value"); if (subval == null) { subval = subel.text; } subel.selected = isArray ? Array.contains(value, subval) : value == subval; } if (isArray && value.length == 0) { element.selectedIndex = -1; } } else if ((type === "text" || type === "textarea") && (qx.core.Environment.get("engine.name") == "mshtml")) { // These flags are required to detect self-made property-change // events during value modification. They are used by the Input // event handler to filter events. element.$$inValueSet = true; element.value = value; element.$$inValueSet = null; } else { element.value = value; } }, /** * Returns the currently configured value. * * Works with simple input fields as well as with * select boxes or option elements. * * Returns an array in cases of multi-selection in * select boxes but in all other cases a string. * * @param element {Element} DOM element to query * @return {String|Array} The value of the given element */ getValue : function(element) { var tag = element.nodeName.toLowerCase(); if (tag === "option") { return (element.attributes.value || {}).specified ? element.value : element.text; } if (tag === "select") { var index = element.selectedIndex; // Nothing was selected if (index < 0) { return null; } var values = []; var options = element.options; var one = element.type == "select-one"; var clazz = qx.bom.Input; var value; // Loop through all the selected options for (var i=one ? index : 0, max=one ? index+1 : options.length; i<max; i++) { var option = options[i]; if (option.selected) { // Get the specifc value for the option value = clazz.getValue(option); // We don't need an array for one selects if (one) { return value; } // Multi-Selects return an array values.push(value); } } return values; } else { return (element.value || "").replace(/\r/g, ""); } }, /** * Sets the text wrap behaviour of a text area element. * This property uses the attribute "wrap" respectively * the style property "whiteSpace" * * @signature function(element, wrap) * @param element {Element} DOM element to modify * @param wrap {Boolean} Whether to turn text wrap on or off. */ setWrap : qx.core.Environment.select("engine.name", { "mshtml" : function(element, wrap) { var wrapValue = wrap ? "soft" : "off"; // Explicitly set overflow-y CSS property to auto when wrapped, // allowing the vertical scroll-bar to appear if necessary var styleValue = wrap ? "auto" : ""; element.wrap = wrapValue; element.style.overflowY = styleValue; }, "gecko|webkit" : function(element, wrap) { var wrapValue = wrap ? "soft" : "off"; var styleValue = wrap ? "" : "auto"; element.setAttribute("wrap", wrapValue); element.style.overflow = styleValue; }, "default" : function(element, wrap) { element.style.whiteSpace = wrap ? "normal" : "nowrap"; } }) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) * Adrian Olaru (adrianolaru) ************************************************************************ */ /** * The TextField is a single-line text input field. */ qx.Class.define("qx.ui.form.TextField", { extend : qx.ui.form.AbstractField, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "textfield" }, // overridden allowGrowY : { refine : true, init : false }, // overridden allowShrinkY : { refine : true, init : false } }, members : { // overridden _renderContentElement : function(innerHeight, element) { if ((qx.core.Environment.get("engine.name") == "mshtml") && (parseInt(qx.core.Environment.get("engine.version"), 10) < 9 || qx.core.Environment.get("browser.documentmode") < 9)) { element.setStyles({ "line-height" : innerHeight + 'px' }); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The RepeatButton is a special button, which fires repeatedly {@link #execute} * events, while the mouse button is pressed on the button. The initial delay * and the interval time can be set using the properties {@link #firstInterval} * and {@link #interval}. The {@link #execute} events will be fired in a shorter * amount of time if the mouse button is hold, until the min {@link #minTimer} * is reached. The {@link #timerDecrease} property sets the amount of milliseconds * which will decreased after every firing. * * <pre class='javascript'> * var button = new qx.ui.form.RepeatButton("Hello World"); * * button.addListener("execute", function(e) { * alert("Button is executed"); * }, this); * * this.getRoot.add(button); * </pre> * * This example creates a button with the label "Hello World" and attaches an * event listener to the {@link #execute} event. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/repeatbutton.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.form.RepeatButton", { extend : qx.ui.form.Button, /** * @param label {String} Label to use * @param icon {String?null} Icon to use */ construct : function(label, icon) { this.base(arguments, label, icon); // create the timer and add the listener this.__timer = new qx.event.AcceleratingTimer(); this.__timer.addListener("interval", this._onInterval, this); }, events : { /** * This event gets dispatched with every interval. The timer gets executed * as long as the user holds down the mouse button. */ "execute" : "qx.event.type.Event", /** * This event gets dispatched when the button is pressed. */ "press" : "qx.event.type.Event", /** * This event gets dispatched when the button is released. */ "release" : "qx.event.type.Event" }, properties : { /** * Interval used after the first run of the timer. Usually a smaller value * than the "firstInterval" property value to get a faster reaction. */ interval : { check : "Integer", init : 100 }, /** * Interval used for the first run of the timer. Usually a greater value * than the "interval" property value to a little delayed reaction at the first * time. */ firstInterval : { check : "Integer", init : 500 }, /** This configures the minimum value for the timer interval. */ minTimer : { check : "Integer", init : 20 }, /** Decrease of the timer on each interval (for the next interval) until minTimer reached. */ timerDecrease : { check : "Integer", init : 2 } }, members : { __executed : null, __timer : null, /** * Calling this function is like a click from the user on the * button with all consequences. * <span style='color: red'>Be sure to call the {@link #release} function.</span> * * @return {void} */ press : function() { // only if the button is enabled if (this.isEnabled()) { // if the state pressed must be applied (first call) if (!this.hasState("pressed")) { // start the timer this.__startInternalTimer(); } // set the states this.removeState("abandoned"); this.addState("pressed"); } }, /** * Calling this function is like a release from the user on the * button with all consequences. * Usually the {@link #release} function will be called before the call of * this function. * * @param fireExecuteEvent {Boolean?true} flag which signals, if an event should be fired * @return {void} */ release : function(fireExecuteEvent) { // only if the button is enabled if (!this.isEnabled()) { return; } // only if the button is pressed if (this.hasState("pressed")) { // if the button has not been executed if (!this.__executed) { this.execute(); } } // remove button states this.removeState("pressed"); this.removeState("abandoned"); // stop the repeat timer and therefore the execution this.__stopInternalTimer(); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); if (!value) { // remove button states this.removeState("pressed"); this.removeState("abandoned"); // stop the repeat timer and therefore the execution this.__stopInternalTimer(); } }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Listener method for "mouseover" event * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOver : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); this.__timer.start(); } this.addState("hovered"); }, /** * Listener method for "mouseout" event * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" and removes "pressed" state (if "pressed" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOut : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { this.removeState("pressed"); this.addState("abandoned"); this.__timer.stop(); } }, /** * Callback method for the "mouseDown" method. * * Sets the interval of the timer (value of firstInterval property) and * starts the timer. Additionally removes the state "abandoned" and adds the * state "pressed". * * @param e {qx.event.type.Mouse} mouseDown event * @return {void} */ _onMouseDown : function(e) { if (!e.isLeftPressed()) { return; } // Activate capturing if the button get a mouseout while // the button is pressed. this.capture(); this.__startInternalTimer(); e.stopPropagation(); }, /** * Callback method for the "mouseUp" event. * * Handles the case that the user is releasing the mouse button * before the timer interval method got executed. This way the * "execute" method get executed at least one time. * * @param e {qx.event.type.Mouse} mouseUp event * @return {void} */ _onMouseUp : function(e) { this.releaseCapture(); if (!this.hasState("abandoned")) { this.addState("hovered"); if (this.hasState("pressed") && !this.__executed) { this.execute(); } } this.__stopInternalTimer(); e.stopPropagation(); }, /** * Listener method for "keyup" event. * * Removes "abandoned" and "pressed" state (if "pressed" state is set) * for the keys "Enter" or "Space" and stopps the internal timer * (same like mouse up). * * @param e {Event} Key event * @return {void} */ _onKeyUp : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": if (this.hasState("pressed")) { if (!this.__executed) { this.execute(); } this.removeState("pressed"); this.removeState("abandoned"); e.stopPropagation(); this.__stopInternalTimer(); } } }, /** * Listener method for "keydown" event. * * Removes "abandoned" and adds "pressed" state * for the keys "Enter" or "Space". It also starts * the internal timer (same like mousedown). * * @param e {Event} Key event * @return {void} */ _onKeyDown : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); this.__startInternalTimer(); } }, /** * Callback for the interval event. * * Stops the timer and starts it with a new interval * (value of the "interval" property - value of the "timerDecrease" property). * Dispatches the "execute" event. * * @param e {qx.event.type.Event} interval event * @return {void} */ _onInterval : function(e) { this.__executed = true; this.fireEvent("execute"); }, /* --------------------------------------------------------------------------- INTERNAL TIMER --------------------------------------------------------------------------- */ /** * Starts the internal timer which causes firing of execution * events in an interval. It also presses the button. * * @return {void} */ __startInternalTimer : function() { this.fireEvent("press"); this.__executed = false; this.__timer.set({ interval: this.getInterval(), firstInterval: this.getFirstInterval(), minimum: this.getMinTimer(), decrease: this.getTimerDecrease() }).start(); this.removeState("abandoned"); this.addState("pressed"); }, /** * Stops the internal timer and releases the button. * * @return {void} */ __stopInternalTimer : function() { this.fireEvent("release"); this.__timer.stop(); this.removeState("abandoned"); this.removeState("pressed"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__timer"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Timer, which accelerates after each interval. The initial delay and the * interval time can be set using the properties {@link #firstInterval} * and {@link #interval}. The {@link #interval} events will be fired with * decreasing interval times while the timer is running, until the {@link #minimum} * is reached. The {@link #decrease} property sets the amount of milliseconds * which will decreased after every firing. * * This class is e.g. used in the {@link qx.ui.form.RepeatButton} and * {@link qx.ui.form.HoverButton} widgets. */ qx.Class.define("qx.event.AcceleratingTimer", { extend : qx.core.Object, construct : function() { this.base(arguments); this.__timer = new qx.event.Timer(this.getInterval()); this.__timer.addListener("interval", this._onInterval, this); }, events : { /** This event if fired each time the interval time has elapsed */ "interval" : "qx.event.type.Event" }, properties : { /** * Interval used after the first run of the timer. Usually a smaller value * than the "firstInterval" property value to get a faster reaction. */ interval : { check : "Integer", init : 100 }, /** * Interval used for the first run of the timer. Usually a greater value * than the "interval" property value to a little delayed reaction at the first * time. */ firstInterval : { check : "Integer", init : 500 }, /** This configures the minimum value for the timer interval. */ minimum : { check : "Integer", init : 20 }, /** Decrease of the timer on each interval (for the next interval) until minTimer reached. */ decrease : { check : "Integer", init : 2 } }, members : { __timer : null, __currentInterval : null, /** * Reset and start the timer. */ start : function() { this.__timer.setInterval(this.getFirstInterval()); this.__timer.start(); }, /** * Stop the timer */ stop : function() { this.__timer.stop(); this.__currentInterval = null; }, /** * Interval event handler */ _onInterval : function() { this.__timer.stop(); if (this.__currentInterval == null) { this.__currentInterval = this.getInterval(); } this.__currentInterval = Math.max( this.getMinimum(), this.__currentInterval - this.getDecrease() ); this.__timer.setInterval(this.__currentInterval); this.__timer.start(); this.fireEvent("interval"); } }, destruct : function() { this._disposeObjects("__timer"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /* #cldr */ /** * Provides information about locale-dependent number formatting (like the decimal * separator). */ qx.Class.define("qx.locale.Number", { statics : { /** * Get decimal separator for number formatting * * @param locale {String} optional locale to be used * @return {String} decimal separator. */ getDecimalSeparator : function(locale) { return qx.locale.Manager.getInstance().localize("cldr_number_decimal_separator", [], locale) }, /** * Get thousand grouping separator for number formatting * * @param locale {String} optional locale to be used * @return {String} group separator. */ getGroupSeparator : function(locale) { return qx.locale.Manager.getInstance().localize("cldr_number_group_separator", [], locale) }, /** * Get percent format string * * @param locale {String} optional locale to be used * @return {String} percent format string. */ getPercentFormat : function(locale) { return qx.locale.Manager.getInstance().localize("cldr_number_percent_format", [], locale) } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Each object, which should be managed by a {@link RadioGroup} have to * implement this interface. */ qx.Interface.define("qx.ui.form.IRadioItem", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the item was checked or unchecked */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Set whether the item is checked * * @param value {Boolean} whether the item should be checked */ setValue : function(value) {}, /** * Get whether the item is checked * * @return {Boolean} whether the item it checked */ getValue : function() {}, /** * Set the radiogroup, which manages this item * * @param value {qx.ui.form.RadioGroup} The radiogroup, which should * manage the item. */ setGroup : function(value) { this.assertInstance(value, qx.ui.form.RadioGroup); }, /** * Get the radiogroup, which manages this item * * @return {qx.ui.form.RadioGroup} The radiogroup, which manages the item. */ getGroup : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * This mixin links all methods to manage the single selection. * * The class which includes the mixin has to implements two methods: * * <ul> * <li><code>_getItems</code>, this method has to return a <code>Array</code> * of <code>qx.ui.core.Widget</code> that should be managed from the manager. * </li> * <li><code>_isAllowEmptySelection</code>, this method has to return a * <code>Boolean</code> value for allowing empty selection or not. * </li> * </ul> */ qx.Mixin.define("qx.ui.core.MSingleSelectionHandling", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.core.SingleSelectionManager} the single selection manager */ __manager : null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {qx.ui.core.Widget[]} List of items. */ getSelection : function() { var selected = this.__getManager().getSelected(); if (selected) { return [selected]; } else { return []; } }, /** * Replaces current selection with the given items. * * @param items {qx.ui.core.Widget[]} Items to select. * @throws an exception if one of the items is not a child element and if * items contains more than one elements. */ setSelection : function(items) { switch(items.length) { case 0: this.resetSelection(); break; case 1: this.__getManager().setSelected(items[0]); break; default: throw new Error("Could only select one item, but the selection" + " array contains " + items.length + " items!"); } }, /** * Clears the whole selection at once. */ resetSelection : function() { this.__getManager().resetSelected(); }, /** * Detects whether the given item is currently selected. * * @param item {qx.ui.core.Widget} Any valid selectable item. * @return {Boolean} Whether the item is selected. * @throws an exception if one of the items is not a child element. */ isSelected : function(item) { return this.__getManager().isSelected(item); }, /** * Whether the selection is empty. * * @return {Boolean} Whether the selection is empty. */ isSelectionEmpty : function() { return this.__getManager().isSelectionEmpty(); }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables: function(all) { return this.__getManager().getSelectables(all); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event listener for <code>changeSelected</code> event on single * selection manager. * * @param e {qx.event.type.Data} Data event. */ _onChangeSelected : function(e) { var newValue = e.getData(); var oldVlaue = e.getOldData(); newValue == null ? newValue = [] : newValue = [newValue]; oldVlaue == null ? oldVlaue = [] : oldVlaue = [oldVlaue]; this.fireDataEvent("changeSelection", newValue, oldVlaue); }, /** * Return the selection manager if it is already exists, otherwise creates * the manager. * * @return {qx.ui.core.SingleSelectionManager} Single selection manager. */ __getManager : function() { if (this.__manager == null) { var that = this; this.__manager = new qx.ui.core.SingleSelectionManager( { getItems : function() { return that._getItems(); }, isItemSelectable : function(item) { if (that._isItemSelectable) { return that._isItemSelectable(item); } else { return item.isVisible(); } } }); this.__manager.addListener("changeSelected", this._onChangeSelected, this); } this.__manager.setAllowEmptySelection(this._isAllowEmptySelection()); return this.__manager; } }, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__manager"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Responsible for the single selection management. * * The class manage a list of {@link qx.ui.core.Widget} which are returned from * {@link qx.ui.core.ISingleSelectionProvider#getItems}. * * @internal */ qx.Class.define("qx.ui.core.SingleSelectionManager", { extend : qx.core.Object, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Construct the single selection manager. * * @param selectionProvider {qx.ui.core.ISingleSelectionProvider} The provider * for selection. */ construct : function(selectionProvider) { this.base(arguments); if (qx.core.Environment.get("qx.debug")) { qx.core.Assert.assertInterface(selectionProvider, qx.ui.core.ISingleSelectionProvider, "Invalid selectionProvider!"); } this.__selectionProvider = selectionProvider; }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelected" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * If the value is <code>true</code> the manager allows an empty selection, * otherwise the first selectable element returned from the * <code>qx.ui.core.ISingleSelectionProvider</code> will be selected. */ allowEmptySelection : { check : "Boolean", init : true, apply : "__applyAllowEmptySelection" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.core.Widget} The selected widget. */ __selected : null, /** {qx.ui.core.ISingleSelectionProvider} The provider for selection management */ __selectionProvider : null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Returns the current selected element. * * @return {qx.ui.core.Widget | null} The current selected widget or * <code>null</code> if the selection is empty. */ getSelected : function() { return this.__selected; }, /** * Selects the passed element. * * @param item {qx.ui.core.Widget} Element to select. * @throws Error if the element is not a child element. */ setSelected : function(item) { if (!this.__isChildElement(item)) { throw new Error("Could not select " + item + ", because it is not a child element!"); } this.__setSelected(item); }, /** * Reset the current selection. If {@link #allowEmptySelection} is set to * <code>true</code> the first element will be selected. */ resetSelected : function(){ this.__setSelected(null); }, /** * Return <code>true</code> if the passed element is selected. * * @param item {qx.ui.core.Widget} Element to check if selected. * @return {Boolean} <code>true</code> if passed element is selected, * <code>false</code> otherwise. * @throws Error if the element is not a child element. */ isSelected : function(item) { if (!this.__isChildElement(item)) { throw new Error("Could not check if " + item + " is selected," + " because it is not a child element!"); } return this.__selected === item; }, /** * Returns <code>true</code> if selection is empty. * * @return {Boolean} <code>true</code> if selection is empty, * <code>false</code> otherwise. */ isSelectionEmpty : function() { return this.__selected == null; }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables : function(all) { var items = this.__selectionProvider.getItems(); var result = []; for (var i = 0; i < items.length; i++) { if (this.__selectionProvider.isItemSelectable(items[i])) { result.push(items[i]); } } // in case of an user selecable list, remove the enabled items if (!all) { for (var i = result.length -1; i >= 0; i--) { if (!result[i].getEnabled()) { result.splice(i, 1); } }; } return result; }, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ // apply method __applyAllowEmptySelection : function(value, old) { if (!value) { this.__setSelected(this.__selected); } }, /* --------------------------------------------------------------------------- HELPERS --------------------------------------------------------------------------- */ /** * Set selected element. * * If passes value is <code>null</code>, the selection will be reseted. * * @param item {qx.ui.core.Widget | null} element to select, or * <code>null</code> to reset selection. */ __setSelected : function(item) { var oldSelected = this.__selected; var newSelected = item; if (newSelected != null && oldSelected === newSelected) { return; } if (!this.isAllowEmptySelection() && newSelected == null) { var firstElement = this.getSelectables(true)[0]; if (firstElement) { newSelected = firstElement; } } this.__selected = newSelected; this.fireDataEvent("changeSelected", newSelected, oldSelected); }, /** * Checks if passed element is a child element. * * @param item {qx.ui.core.Widget} Element to check if child element. * @return {Boolean} <code>true</code> if element is child element, * <code>false</code> otherwise. */ __isChildElement : function(item) { var items = this.__selectionProvider.getItems(); for (var i = 0; i < items.length; i++) { if (items[i] === item) { return true; } } return false; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { if (this.__selectionProvider.toHashCode) { this._disposeObjects("__selectionProvider"); } else { this.__selectionProvider = null; } this._disposeObjects("__selected"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Defines the callback for the single selection manager. * * @internal */ qx.Interface.define("qx.ui.core.ISingleSelectionProvider", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Returns the elements which are part of the selection. * * @return {qx.ui.core.Widget[]} The widgets for the selection. */ getItems: function() {}, /** * Returns whether the given item is selectable. * * @param item {qx.ui.core.Widget} The item to be checked * @return {Boolean} Whether the given item is selectable */ isItemSelectable : function(item) {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This mixin offers the selection of the model properties. * It can only be included if the object including it implements the * {@link qx.ui.core.ISingleSelection} interface and the selectables implement * the {@link qx.ui.form.IModel} interface. */ qx.Mixin.define("qx.ui.form.MModelSelection", { construct : function() { // create the selection array this.__modelSelection = new qx.data.Array(); // listen to the changes this.__modelSelection.addListener("change", this.__onModelSelectionArrayChange, this); this.addListener("changeSelection", this.__onModelSelectionChange, this); }, events : { /** * Pseudo event. It will never be fired because the array itself can not * be changed. But the event description is needed for the data binding. */ changeModelSelection : "qx.event.type.Data" }, members : { __modelSelection : null, __inSelectionChange : false, /** * Handler for the selection change of the including class e.g. SelectBox, * List, ... * It sets the new modelSelection via {@link #setModelSelection}. */ __onModelSelectionChange : function() { if (this.__inSelectionChange) { return; } var data = this.getSelection(); // create the array with the modes inside var modelSelection = []; for (var i = 0; i < data.length; i++) { var item = data[i]; // fallback if getModel is not implemented var model = item.getModel ? item.getModel() : null; if (model !== null) { modelSelection.push(model); } }; // only change the selection if you are sure that its correct [BUG #3748] if (modelSelection.length === data.length) { try { this.setModelSelection(modelSelection); } catch (e) { throw new Error( "Could not set the model selection. Maybe your models are not unique?" ); } } }, /** * Listener for the change of the internal model selection data array. */ __onModelSelectionArrayChange : function() { this.__inSelectionChange = true; var selectables = this.getSelectables(true); var itemSelection = []; var modelSelection = this.__modelSelection.toArray(); for (var i = 0; i < modelSelection.length; i++) { var model = modelSelection[i]; for (var j = 0; j < selectables.length; j++) { var selectable = selectables[j]; // fallback if getModel is not implemented var selectableModel = selectable.getModel ? selectable.getModel() : null; if (model === selectableModel) { itemSelection.push(selectable); break; } } } this.setSelection(itemSelection); this.__inSelectionChange = false; // check if the setting has worked var currentSelection = this.getSelection(); if (!qx.lang.Array.equals(currentSelection, itemSelection)) { // if not, set the actual selection this.__onModelSelectionChange(); } }, /** * Returns always an array of the models of the selected items. If no * item is selected or no model is given, the array will be empty. * * *CAREFUL!* The model selection can only work if every item item in the * selection providing widget has a model property! * * @return {qx.data.Array} An array of the models of the selected items. */ getModelSelection : function() { return this.__modelSelection; }, /** * Takes the given models in the array and searches for the corresponding * selectables. If an selectable does have that model attached, it will be * selected. * * *Attention:* This method can have a time complexity of O(n^2)! * * *CAREFUL!* The model selection can only work if every item item in the * selection providing widget has a model property! * * @param modelSelection {Array} An array of models, which should be * selected. */ setModelSelection : function(modelSelection) { // check for null values if (!modelSelection) { this.__modelSelection.removeAll(); return; } if (qx.core.Environment.get("qx.debug")) { this.assertArray(modelSelection, "Please use an array as parameter."); } // add the first two parameter modelSelection.unshift(this.__modelSelection.getLength()); // remove index modelSelection.unshift(0); // start index var returnArray = this.__modelSelection.splice.apply(this.__modelSelection, modelSelection); returnArray.dispose(); } }, destruct : function() { this._disposeObjects("__modelSelection"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This interface should be used in all objects managing a set of items * implementing {@link qx.ui.form.IModel}. */ qx.Interface.define("qx.ui.form.IModelSelection", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Tries to set the selection using the given array containing the * representative models for the selectables. * * @param value {Array} An array of models. */ setModelSelection : function(value) {}, /** * Returns an array of the selected models. * * @return {Array} An array containing the models of the currently selected * items. */ getModelSelection : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The radio group handles a collection of items from which only one item * can be selected. Selection another item will deselect the previously selected * item. * * This class is e.g. used to create radio groups or {@link qx.ui.form.RadioButton} * or {@link qx.ui.toolbar.RadioButton} instances. * * We also offer a widget for the same purpose which uses this class. So if * you like to act with a widget instead of a pure logic coupling of the * widgets, take a look at the {@link qx.ui.form.RadioButtonGroup} widget. */ qx.Class.define("qx.ui.form.RadioGroup", { extend : qx.core.Object, implement : [ qx.ui.core.ISingleSelection, qx.ui.form.IForm, qx.ui.form.IModelSelection ], include : [ qx.ui.core.MSingleSelectionHandling, qx.ui.form.MModelSelection ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param varargs {qx.core.Object} A variable number of items, which are * initially added to the radio group, the first item will be selected. */ construct : function(varargs) { this.base(arguments); // create item array this.__items = []; // add listener before call add!!! this.addListener("changeSelection", this.__onChangeSelection, this); if (varargs != null) { this.add.apply(this, arguments); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Whether the radio group is enabled */ enabled : { check : "Boolean", apply : "_applyEnabled", event : "changeEnabled", init: true }, /** * Whether the selection should wrap around. This means that the successor of * the last item is the first item. */ wrap : { check : "Boolean", init: true }, /** * If is set to <code>true</code> the selection could be empty, * otherwise is always one <code>RadioButton</code> selected. */ allowEmptySelection : { check : "Boolean", init : false, apply : "_applyAllowEmptySelection" }, /** * Flag signaling if the group at all is valid. All children will have the * same state. */ valid : { check : "Boolean", init : true, apply : "_applyValid", event : "changeValid" }, /** * Flag signaling if the group is required. */ required : { check : "Boolean", init : false, event : "changeRequired" }, /** * Message which is shown in an invalid tooltip. */ invalidMessage : { check : "String", init: "", event : "changeInvalidMessage", apply : "_applyInvalidMessage" }, /** * Message which is shown in an invalid tooltip if the {@link #required} is * set to true. */ requiredInvalidMessage : { check : "String", nullable : true, event : "changeInvalidMessage" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.form.IRadioItem[]} The items of the radio group */ __items : null, /* --------------------------------------------------------------------------- UTILITIES --------------------------------------------------------------------------- */ /** * Get all managed items * * @return {qx.ui.form.IRadioItem[]} All managed items. */ getItems : function() { return this.__items; }, /* --------------------------------------------------------------------------- REGISTRY --------------------------------------------------------------------------- */ /** * Add the passed items to the radio group. * * @param varargs {qx.ui.form.IRadioItem} A variable number of items to add. */ add : function(varargs) { var items = this.__items; var item; for (var i=0, l=arguments.length; i<l; i++) { item = arguments[i]; if (qx.lang.Array.contains(items, item)) { continue; } // Register listeners item.addListener("changeValue", this._onItemChangeChecked, this); // Push RadioButton to array items.push(item); // Inform radio button about new group item.setGroup(this); // Need to update internal value? if (item.getValue()) { this.setSelection([item]); } } // Select first item when only one is registered if (!this.isAllowEmptySelection() && items.length > 0 && !this.getSelection()[0]) { this.setSelection([items[0]]); } }, /** * Remove an item from the radio group. * * @param item {qx.ui.form.IRadioItem} The item to remove. */ remove : function(item) { var items = this.__items; if (qx.lang.Array.contains(items, item)) { // Remove RadioButton from array qx.lang.Array.remove(items, item); // Inform radio button about new group if (item.getGroup() === this) { item.resetGroup(); } // Deregister listeners item.removeListener("changeValue", this._onItemChangeChecked, this); // if the radio was checked, set internal selection to null if (item.getValue()) { this.resetSelection(); } } }, /** * Returns an array containing the group's items. * * @return {qx.ui.form.IRadioItem[]} The item array */ getChildren : function() { return this.__items; }, /* --------------------------------------------------------------------------- LISTENER FOR ITEM CHANGES --------------------------------------------------------------------------- */ /** * Event listener for <code>changeValue</code> event of every managed item. * * @param e {qx.event.type.Data} Data event */ _onItemChangeChecked : function(e) { var item = e.getTarget(); if (item.getValue()) { this.setSelection([item]); } else if (this.getSelection()[0] == item) { this.resetSelection(); } }, /* --------------------------------------------------------------------------- APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyInvalidMessage : function(value, old) { for (var i = 0; i < this.__items.length; i++) { this.__items[i].setInvalidMessage(value); } }, // property apply _applyValid: function(value, old) { for (var i = 0; i < this.__items.length; i++) { this.__items[i].setValid(value); } }, // property apply _applyEnabled : function(value, old) { var items = this.__items; if (value == null) { for (var i=0, l=items.length; i<l; i++) { items[i].resetEnabled(); } } else { for (var i=0, l=items.length; i<l; i++) { items[i].setEnabled(value); } } }, // property apply _applyAllowEmptySelection : function(value, old) { if (!value && this.isSelectionEmpty()) { this.resetSelection(); } }, /* --------------------------------------------------------------------------- SELECTION --------------------------------------------------------------------------- */ /** * Select the item following the given item. */ selectNext : function() { var item = this.getSelection()[0]; var items = this.__items; var index = items.indexOf(item); if (index == -1) { return; } var i = 0; var length = items.length; // Find next enabled item if (this.getWrap()) { index = (index + 1) % length; } else { index = Math.min(index + 1, length - 1); } while (i < length && !items[index].getEnabled()) { index = (index + 1) % length; i++; } this.setSelection([items[index]]); }, /** * Select the item previous the given item. */ selectPrevious : function() { var item = this.getSelection()[0]; var items = this.__items; var index = items.indexOf(item); if (index == -1) { return; } var i = 0; var length = items.length; // Find previous enabled item if (this.getWrap()) { index = (index - 1 + length) % length; } else { index = Math.max(index - 1, 0); } while (i < length && !items[index].getEnabled()) { index = (index - 1 + length) % length; i++; } this.setSelection([items[index]]); }, /* --------------------------------------------------------------------------- HELPER METHODS FOR SELECTION API --------------------------------------------------------------------------- */ /** * Returns the items for the selection. * * @return {qx.ui.form.IRadioItem[]} Items to select. */ _getItems : function() { return this.getItems(); }, /** * Returns if the selection could be empty or not. * * @return {Boolean} <code>true</code> If selection could be empty, * <code>false</code> otherwise. */ _isAllowEmptySelection: function() { return this.isAllowEmptySelection(); }, /** * Returns whether the item is selectable. In opposite to the default * implementation (which checks for visible items) every radio button * which is part of the group is selected even if it is currently not visible. * * @param item {qx.ui.form.IRadioItem} The item to check if its selectable. * @return {Boolean} <code>true</code> if the item is part of the radio group * <code>false</code> otherwise. */ _isItemSelectable : function(item) { return this.__items.indexOf(item) != -1; }, /** * Event handler for <code>changeSelection</code>. * * @param e {qx.event.type.Data} Data event. */ __onChangeSelection : function(e) { var value = e.getData()[0]; var old = e.getOldData()[0]; if (old) { old.setValue(false); } if (value) { value.setValue(true); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeArray("__items"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * A toggle Button widget * * If the user presses the button by clicking on it pressing the enter or * space key, the button toggles between the pressed an not pressed states. * There is no execute event, only a {@link qx.ui.form.ToggleButton#changeValue} * event. */ qx.Class.define("qx.ui.form.ToggleButton", { extend : qx.ui.basic.Atom, include : [ qx.ui.core.MExecutable ], implement : [ qx.ui.form.IBooleanForm, qx.ui.form.IExecutable, qx.ui.form.IRadioItem ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Creates a ToggleButton. * * @param label {String} The text on the button. * @param icon {String} An URI to the icon of the button. */ construct : function(label, icon) { this.base(arguments, label, icon); // register mouse events this.addListener("mouseover", this._onMouseOver); this.addListener("mouseout", this._onMouseOut); this.addListener("mousedown", this._onMouseDown); this.addListener("mouseup", this._onMouseUp); // register keyboard events this.addListener("keydown", this._onKeyDown); this.addListener("keyup", this._onKeyUp); // register execute event this.addListener("execute", this._onExecute, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties: { // overridden appearance: { refine: true, init: "button" }, // overridden focusable : { refine : true, init : true }, /** The value of the widget. True, if the widget is checked. */ value : { check : "Boolean", nullable : true, event : "changeValue", apply : "_applyValue", init : false }, /** The assigned qx.ui.form.RadioGroup which handles the switching between registered buttons. */ group : { check : "qx.ui.form.RadioGroup", nullable : true, apply : "_applyGroup" }, /** * Whether the button has a third state. Use this for tri-state checkboxes. * * When enabled, the value null of the property value stands for "undetermined", * while true is mapped to "enabled" and false to "disabled" as usual. Note * that the value property is set to false initially. * */ triState : { check : "Boolean", apply : "_applyTriState", nullable : true, init : null } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** The assigned {@link qx.ui.form.RadioGroup} which handles the switching between registered buttons */ _applyGroup : function(value, old) { if (old) { old.remove(this); } if (value) { value.add(this); } }, /** * Changes the state of the button dependent on the checked value. * * @param value {Boolean} Current value * @param old {Boolean} Previous value */ _applyValue : function(value, old) { value ? this.addState("checked") : this.removeState("checked"); if (this.isTriState()) { if (value === null) { this.addState("undetermined"); } else if (old === null) { this.removeState("undetermined"); } } }, /** * Apply value property when triState property is modified. * * @param value {Boolean} Current value * @param old {Boolean} Previous value */ _applyTriState : function(value, old) { this._applyValue(this.getValue()); }, /** * Handler for the execute event. * * @param e {qx.event.type.Event} The execute event. */ _onExecute : function(e) { this.toggleValue(); }, /** * Listener method for "mouseover" event. * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOver : function(e) { if (e.getTarget() !== this) { return; } this.addState("hovered"); if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); } }, /** * Listener method for "mouseout" event. * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" state (if "pressed" state is set)</li> * <li>Removes "pressed" state (if "pressed" state is set and button is not checked) * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOut : function(e) { if (e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { if (!this.getValue()) { this.removeState("pressed"); } this.addState("abandoned"); } }, /** * Listener method for "mousedown" event. * <ul> * <li>Activates capturing</li> * <li>Removes "abandoned" state</li> * <li>Adds "pressed" state</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseDown : function(e) { if (!e.isLeftPressed()) { return; } // Activate capturing if the button get a mouseout while // the button is pressed. this.capture(); this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); }, /** * Listener method for "mouseup" event. * <ul> * <li>Releases capturing</li> * <li>Removes "pressed" state (if not "abandoned" state is set and "pressed" state is set)</li> * <li>Removes "abandoned" state (if set)</li> * <li>Toggles {@link #value} (if state "abandoned" is not set and state "pressed" is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseUp : function(e) { this.releaseCapture(); if (this.hasState("abandoned")) { this.removeState("abandoned"); } else if (this.hasState("pressed")) { this.execute(); } this.removeState("pressed"); e.stopPropagation(); }, /** * Listener method for "keydown" event.<br/> * Removes "abandoned" and adds "pressed" state * for the keys "Enter" or "Space" * * @param e {Event} Key event * @return {void} */ _onKeyDown : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); } }, /** * Listener method for "keyup" event.<br/> * Removes "abandoned" and "pressed" state (if "pressed" state is set) * for the keys "Enter" or "Space". It also toggles the {@link #value} property. * * @param e {Event} Key event * @return {void} */ _onKeyUp : function(e) { if (!this.hasState("pressed")) { return; } switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.execute(); this.removeState("pressed"); e.stopPropagation(); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Can be included for implementing {@link qx.ui.form.IModel}. It only contains * a nullable property named 'model' with a 'changeModel' event. */ qx.Mixin.define("qx.ui.form.MModelProperty", { properties : { /** * Model property for storing additional information for the including * object. It can act as value property on form items for example. * * Be careful using that property as this is used for the * {@link qx.ui.form.MModelSelection} it has some restrictions: * * * Don't use equal models in one widget using the * {@link qx.ui.form.MModelSelection}. * * * Avoid setting only some model properties if the widgets are added to * a {@link qx.ui.form.MModelSelection} widge. * * Both restrictions result of the fact, that the set models are deputies * for their widget. */ model : { nullable: true, event: "changeModel", dereference : true } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Each object which wants to store data representative for the real item * should implement this interface. */ qx.Interface.define("qx.ui.form.IModel", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the model data changes */ "changeModel" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Set the representative data for the item. * * @param value {var} The data. */ setModel : function(value) {}, /** * Returns the representative data for the item * * @return {var} The data. */ getModel : function() {}, /** * Sets the representative data to null. */ resetModel : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Andreas Ecker (ecker) ************************************************************************ */ /** * A check box widget with an optional label. */ qx.Class.define("qx.ui.form.CheckBox", { extend : qx.ui.form.ToggleButton, include : [ qx.ui.form.MForm, qx.ui.form.MModelProperty ], implement : [ qx.ui.form.IForm, qx.ui.form.IModel ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param label {String?null} An optional label for the check box. */ construct : function(label) { if (qx.core.Environment.get("qx.debug")) { this.assertArgumentsCount(arguments, 0, 1); } this.base(arguments, label); // Initialize the checkbox to a valid value (the default is null which // is invalid) this.setValue(false); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "checkbox" }, // overridden allowGrowX : { refine : true, init : false } }, /** * @lint ignoreReferenceField(_forwardStates,_bindableProperties) */ members : { // overridden _forwardStates : { invalid : true, focused : true, undetermined : true, checked : true, hovered : true }, // overridden (from MExecutable to keet the icon out of the binding) _bindableProperties : [ "enabled", "label", "toolTipText", "value", "menu" ] } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This mixin redirects all children handling methods to a child widget of the * including class. This is e.g. used in {@link qx.ui.window.Window} to add * child widgets directly to the window pane. * * The including class must implement the method <code>getChildrenContainer</code>, * which has to return the widget, to which the child widgets should be added. */ qx.Mixin.define("qx.ui.core.MRemoteChildrenHandling", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Forward the call with the given function name to the children container * * @param functionName {String} name of the method to forward * @param a1 {var} first argument of the method to call * @param a2 {var} second argument of the method to call * @param a3 {var} third argument of the method to call * @return {var} The return value of the forward method */ __forward : function(functionName, a1, a2, a3) { var container = this.getChildrenContainer(); if (container === this) { functionName = "_" + functionName; } return (container[functionName])(a1, a2, a3); }, /** * Returns the children list * * @return {LayoutItem[]} The children array (Arrays are * reference types, please to not modify them in-place) */ getChildren : function() { return this.__forward("getChildren"); }, /** * Whether the widget contains children. * * @return {Boolean} Returns <code>true</code> when the widget has children. */ hasChildren : function() { return this.__forward("hasChildren"); }, /** * Adds a new child widget. * * The supported keys of the layout options map depend on the layout manager * used to position the widget. The options are documented in the class * documentation of each layout manager {@link qx.ui.layout}. * * @param child {LayoutItem} the item to add. * @param options {Map?null} Optional layout data for item. * @return {Widget} This object (for chaining support) */ add : function(child, options) { return this.__forward("add", child, options); }, /** * Remove the given child item. * * @param child {LayoutItem} the item to remove * @return {Widget} This object (for chaining support) */ remove : function(child) { return this.__forward("remove", child); }, /** * Remove all children. * * @return {void} */ removeAll : function() { return this.__forward("removeAll"); }, /** * Returns the index position of the given item if it is * a child item. Otherwise it returns <code>-1</code>. * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} the item to query for * @return {Integer} The index position or <code>-1</code> when * the given item is no child of this layout. */ indexOf : function(child) { return this.__forward("indexOf", child); }, /** * Add a child at the specified index * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} item to add * @param index {Integer} Index, at which the item will be inserted * @param options {Map?null} Optional layout data for item. */ addAt : function(child, index, options) { this.__forward("addAt", child, index, options); }, /** * Add an item before another already inserted item * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} item to add * @param before {LayoutItem} item before the new item will be inserted. * @param options {Map?null} Optional layout data for item. */ addBefore : function(child, before, options) { this.__forward("addBefore", child, before, options); }, /** * Add an item after another already inserted item * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} item to add * @param after {LayoutItem} item, after which the new item will be inserted * @param options {Map?null} Optional layout data for item. */ addAfter : function(child, after, options) { this.__forward("addAfter", child, after, options); }, /** * Remove the item at the specified index. * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param index {Integer} Index of the item to remove. * @return {qx.ui.core.LayoutItem} The removed item */ removeAt : function(index) { return this.__forward("removeAt", index); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Generic selection manager to bring rich desktop like selection behavior * to widgets and low-level interactive controls. * * The selection handling supports both Shift and Ctrl/Meta modifies like * known from native applications. */ qx.Class.define("qx.ui.core.selection.Abstract", { type : "abstract", extend : qx.core.Object, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); // {Map} Internal selection storage this.__selection = {}; }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified. Contains the selection under the data property. */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Selects the selection mode to use. * * * single: One or no element is selected * * multi: Multi items could be selected. Also allows empty selections. * * additive: Easy Web-2.0 selection mode. Allows multiple selections without modifier keys. * * one: If possible always exactly one item is selected */ mode : { check : [ "single", "multi", "additive", "one" ], init : "single", apply : "_applyMode" }, /** * Enable drag selection (multi selection of items through * dragging the mouse in pressed states). * * Only possible for the modes <code>multi</code> and <code>additive</code> */ drag : { check : "Boolean", init : false }, /** * Enable quick selection mode, where no click is needed to change the selection. * * Only possible for the modes <code>single</code> and <code>one</code>. */ quick : { check : "Boolean", init : false } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __scrollStepX : 0, __scrollStepY : 0, __scrollTimer : null, __frameScroll : null, __lastRelX : null, __lastRelY : null, __frameLocation : null, __dragStartX : null, __dragStartY : null, __inCapture : null, __mouseX : null, __mouseY : null, __moveDirectionX : null, __moveDirectionY : null, __selectionModified : null, __selectionContext : null, __leadItem : null, __selection : null, __anchorItem : null, __mouseDownOnSelected : null, // A flag that signals an user interaction, which means the selection change // was triggered by mouse or keyboard [BUG #3344] _userInteraction : false, __oldScrollTop : null, /* --------------------------------------------------------------------------- USER APIS --------------------------------------------------------------------------- */ /** * Returns the selection context. One of <code>click</code>, * <code>quick</code>, <code>drag</code> or <code>key</code> or * <code>null</code>. * * @return {String} One of <code>click</code>, <code>quick</code>, * <code>drag</code> or <code>key</code> or <code>null</code> */ getSelectionContext : function() { return this.__selectionContext; }, /** * Selects all items of the managed object. * * @return {void} */ selectAll : function() { var mode = this.getMode(); if (mode == "single" || mode == "one") { throw new Error("Can not select all items in selection mode: " + mode); } this._selectAllItems(); this._fireChange(); }, /** * Selects the given item. Replaces current selection * completely with the new item. * * Use {@link #addItem} instead if you want to add new * items to an existing selection. * * @param item {Object} Any valid item * @return {void} */ selectItem : function(item) { this._setSelectedItem(item); var mode = this.getMode(); if (mode !== "single" && mode !== "one") { this._setLeadItem(item); this._setAnchorItem(item); } this._scrollItemIntoView(item); this._fireChange(); }, /** * Adds the given item to the existing selection. * * Use {@link #selectItem} instead if you want to replace * the current selection. * * @param item {Object} Any valid item * @return {void} */ addItem : function(item) { var mode = this.getMode(); if (mode === "single" || mode === "one") { this._setSelectedItem(item); } else { if (this._getAnchorItem() == null) { this._setAnchorItem(item); } this._setLeadItem(item); this._addToSelection(item); } this._scrollItemIntoView(item); this._fireChange(); }, /** * Removes the given item from the selection. * * Use {@link #clearSelection} when you want to clear * the whole selection at once. * * @param item {Object} Any valid item * @return {void} */ removeItem : function(item) { this._removeFromSelection(item); if (this.getMode() === "one" && this.isSelectionEmpty()) { var selected = this._applyDefaultSelection(); // Do not fire any event in this case. if (selected == item) { return; } } if (this.getLeadItem() == item) { this._setLeadItem(null); } if (this._getAnchorItem() == item) { this._setAnchorItem(null); } this._fireChange(); }, /** * Selects an item range between two given items. * * @param begin {Object} Item to start with * @param end {Object} Item to end at * @return {void} */ selectItemRange : function(begin, end) { var mode = this.getMode(); if (mode == "single" || mode == "one") { throw new Error("Can not select multiple items in selection mode: " + mode); } this._selectItemRange(begin, end); this._setAnchorItem(begin); this._setLeadItem(end); this._scrollItemIntoView(end); this._fireChange(); }, /** * Clears the whole selection at once. Also * resets the lead and anchor items and their * styles. * * @return {void} */ clearSelection : function() { if (this.getMode() == "one") { var selected = this._applyDefaultSelection(true); if (selected != null) { return; } } this._clearSelection(); this._setLeadItem(null); this._setAnchorItem(null); this._fireChange(); }, /** * Replaces current selection with given array of items. * * Please note that in single selection scenarios it is more * efficient to directly use {@link #selectItem}. * * @param items {Array} Items to select */ replaceSelection : function(items) { var mode = this.getMode(); if (mode == "one" || mode === "single") { if (items.length > 1) { throw new Error("Could not select more than one items in mode: " + mode + "!"); } if (items.length == 1) { this.selectItem(items[0]); } else { this.clearSelection(); } return; } else { this._replaceMultiSelection(items); } }, /** * Get the selected item. This method does only work in <code>single</code> * selection mode. * * @return {Object} The selected item. */ getSelectedItem : function() { var mode = this.getMode(); if (mode === "single" || mode === "one") { var result = this._getSelectedItem(); return result != undefined ? result : null; } throw new Error("The method getSelectedItem() is only supported in 'single' and 'one' selection mode!"); }, /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {Object[]} List of items. */ getSelection : function() { return qx.lang.Object.getValues(this.__selection); }, /** * Returns the selection sorted by the index in the * container of the selection (the assigned widget) * * @return {Object[]} Sorted list of items */ getSortedSelection : function() { var children = this.getSelectables(); var sel = qx.lang.Object.getValues(this.__selection); sel.sort(function(a, b) { return children.indexOf(a) - children.indexOf(b); }); return sel; }, /** * Detects whether the given item is currently selected. * * @param item {var} Any valid selectable item * @return {Boolean} Whether the item is selected */ isItemSelected : function(item) { var hash = this._selectableToHashCode(item); return this.__selection[hash] !== undefined; }, /** * Whether the selection is empty * * @return {Boolean} Whether the selection is empty */ isSelectionEmpty : function() { return qx.lang.Object.isEmpty(this.__selection); }, /** * Invert the selection. Select the non selected and deselect the selected. */ invertSelection: function() { var mode = this.getMode(); if (mode === "single" || mode === "one") { throw new Error("The method invertSelection() is only supported in 'multi' and 'additive' selection mode!"); } var selectables = this.getSelectables(); for (var i = 0; i < selectables.length; i++) { this._toggleInSelection(selectables[i]); } this._fireChange(); }, /* --------------------------------------------------------------------------- LEAD/ANCHOR SUPPORT --------------------------------------------------------------------------- */ /** * Sets the lead item. Generally the item which was last modified * by the user (clicked on etc.) * * @param value {Object} Any valid item or <code>null</code> * @return {void} */ _setLeadItem : function(value) { var old = this.__leadItem; if (old !== null) { this._styleSelectable(old, "lead", false); } if (value !== null) { this._styleSelectable(value, "lead", true); } this.__leadItem = value; }, /** * Returns the current lead item. Generally the item which was last modified * by the user (clicked on etc.) * * @return {Object} The lead item or <code>null</code> */ getLeadItem : function() { return this.__leadItem !== null ? this.__leadItem : null; }, /** * Sets the anchor item. This is the item which is the starting * point for all range selections. Normally this is the item which was * clicked on the last time without any modifier keys pressed. * * @param value {Object} Any valid item or <code>null</code> * @return {void} */ _setAnchorItem : function(value) { var old = this.__anchorItem; if (old != null) { this._styleSelectable(old, "anchor", false); } if (value != null) { this._styleSelectable(value, "anchor", true); } this.__anchorItem = value; }, /** * Returns the current anchor item. This is the item which is the starting * point for all range selections. Normally this is the item which was * clicked on the last time without any modifier keys pressed. * * @return {Object} The anchor item or <code>null</code> */ _getAnchorItem : function() { return this.__anchorItem !== null ? this.__anchorItem : null; }, /* --------------------------------------------------------------------------- BASIC SUPPORT --------------------------------------------------------------------------- */ /** * Whether the given item is selectable. * * @param item {var} Any item * @return {Boolean} <code>true</code> when the item is selectable */ _isSelectable : function(item) { throw new Error("Abstract method call: _isSelectable()"); }, /** * Finds the selectable instance from a mouse event * * @param event {qx.event.type.Mouse} The mouse event * @return {Object|null} The resulting selectable */ _getSelectableFromMouseEvent : function(event) { var target = event.getTarget(); // check for target (may be null when leaving the viewport) [BUG #4378] if (target && this._isSelectable(target)) { return target; } return null; }, /** * Returns an unique hashcode for the given item. * * @param item {var} Any item * @return {String} A valid hashcode */ _selectableToHashCode : function(item) { throw new Error("Abstract method call: _selectableToHashCode()"); }, /** * Updates the style (appearance) of the given item. * * @param item {var} Item to modify * @param type {String} Any of <code>selected</code>, <code>anchor</code> or <code>lead</code> * @param enabled {Boolean} Whether the given style should be added or removed. * @return {void} */ _styleSelectable : function(item, type, enabled) { throw new Error("Abstract method call: _styleSelectable()"); }, /** * Enables capturing of the container. * * @return {void} */ _capture : function() { throw new Error("Abstract method call: _capture()"); }, /** * Releases capturing of the container * * @return {void} */ _releaseCapture : function() { throw new Error("Abstract method call: _releaseCapture()"); }, /* --------------------------------------------------------------------------- DIMENSION AND LOCATION --------------------------------------------------------------------------- */ /** * Returns the location of the container * * @return {Map} Map with the keys <code>top</code>, <code>right</code>, * <code>bottom</code> and <code>left</code>. */ _getLocation : function() { throw new Error("Abstract method call: _getLocation()"); }, /** * Returns the dimension of the container (available scrolling space). * * @return {Map} Map with the keys <code>width</code> and <code>height</code>. */ _getDimension : function() { throw new Error("Abstract method call: _getDimension()"); }, /** * Returns the relative (to the container) horizontal location of the given item. * * @param item {var} Any item * @return {Map} A map with the keys <code>left</code> and <code>right</code>. */ _getSelectableLocationX : function(item) { throw new Error("Abstract method call: _getSelectableLocationX()"); }, /** * Returns the relative (to the container) horizontal location of the given item. * * @param item {var} Any item * @return {Map} A map with the keys <code>top</code> and <code>bottom</code>. */ _getSelectableLocationY : function(item) { throw new Error("Abstract method call: _getSelectableLocationY()"); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ /** * Returns the scroll position of the container. * * @return {Map} Map with the keys <code>left</code> and <code>top</code>. */ _getScroll : function() { throw new Error("Abstract method call: _getScroll()"); }, /** * Scrolls by the given offset * * @param xoff {Integer} Horizontal offset to scroll by * @param yoff {Integer} Vertical offset to scroll by * @return {void} */ _scrollBy : function(xoff, yoff) { throw new Error("Abstract method call: _scrollBy()"); }, /** * Scrolls the given item into the view (make it visible) * * @param item {var} Any item * @return {void} */ _scrollItemIntoView : function(item) { throw new Error("Abstract method call: _scrollItemIntoView()"); }, /* --------------------------------------------------------------------------- QUERY SUPPORT --------------------------------------------------------------------------- */ /** * Returns all selectable items of the container. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {Array} A list of items */ getSelectables : function(all) { throw new Error("Abstract method call: getSelectables()"); }, /** * Returns all selectable items between the two given items. * * The items could be given in any order. * * @param item1 {var} First item * @param item2 {var} Second item * @return {Array} List of items */ _getSelectableRange : function(item1, item2) { throw new Error("Abstract method call: _getSelectableRange()"); }, /** * Returns the first selectable item. * * @return {var} The first selectable item */ _getFirstSelectable : function() { throw new Error("Abstract method call: _getFirstSelectable()"); }, /** * Returns the last selectable item. * * @return {var} The last selectable item */ _getLastSelectable : function() { throw new Error("Abstract method call: _getLastSelectable()"); }, /** * Returns a selectable item which is related to the given * <code>item</code> through the value of <code>relation</code>. * * @param item {var} Any item * @param relation {String} A valid relation: <code>above</code>, * <code>right</code>, <code>under</code> or <code>left</code> * @return {var} The related item */ _getRelatedSelectable : function(item, relation) { throw new Error("Abstract method call: _getRelatedSelectable()"); }, /** * Returns the item which should be selected on pageUp/pageDown. * * May also scroll to the needed position. * * @param lead {var} The current lead item * @param up {Boolean?false} Which page key was pressed: * <code>up</code> or <code>down</code>. * @return {void} */ _getPage : function(lead, up) { throw new Error("Abstract method call: _getPage()"); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMode : function(value, old) { this._setLeadItem(null); this._setAnchorItem(null); this._clearSelection(); // Mode "one" requires one selected item if (value === "one") { this._applyDefaultSelection(true); } this._fireChange(); }, /* --------------------------------------------------------------------------- MOUSE SUPPORT --------------------------------------------------------------------------- */ /** * This method should be connected to the <code>mouseover</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseOver : function(event) { // All browsers (except Opera) fire a native "mouseover" event when a scroll appears // by keyboard interaction. We have to ignore the event to avoid a selection for // "mouseover" (quick selection). For more details see [BUG #4225] if(this.__oldScrollTop != null && this.__oldScrollTop != this._getScroll().top) { this.__oldScrollTop = null; return; } // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; if (!this.getQuick()) { this._userInteraction = false; return; } var mode = this.getMode(); if (mode !== "one" && mode !== "single") { this._userInteraction = false; return; } var item = this._getSelectableFromMouseEvent(event); if (item === null) { this._userInteraction = false; return; } this._setSelectedItem(item); // Be sure that item is in view // This does not feel good when mouseover is used // this._scrollItemIntoView(item); // Fire change event as needed this._fireChange("quick"); this._userInteraction = false; }, /** * This method should be connected to the <code>mousedown</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseDown : function(event) { // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; var item = this._getSelectableFromMouseEvent(event); if (item === null) { this._userInteraction = false; return; } // Read in keyboard modifiers var isCtrlPressed = event.isCtrlPressed() || (qx.core.Environment.get("os.name") == "osx" && event.isMetaPressed()); var isShiftPressed = event.isShiftPressed(); // Clicking on selected items deselect on mouseup, not on mousedown if (this.isItemSelected(item) && !isShiftPressed && !isCtrlPressed && !this.getDrag()) { this.__mouseDownOnSelected = item; this._userInteraction = false; return; } else { this.__mouseDownOnSelected = null; } // Be sure that item is in view this._scrollItemIntoView(item); // Action depends on selected mode switch(this.getMode()) { case "single": case "one": this._setSelectedItem(item); break; case "additive": this._setLeadItem(item); this._setAnchorItem(item); this._toggleInSelection(item); break; case "multi": // Update lead item this._setLeadItem(item); // Create/Update range selection if (isShiftPressed) { var anchor = this._getAnchorItem(); if (anchor === null) { anchor = this._getFirstSelectable(); this._setAnchorItem(anchor); } this._selectItemRange(anchor, item, isCtrlPressed); } // Toggle in selection else if (isCtrlPressed) { this._setAnchorItem(item); this._toggleInSelection(item); } // Replace current selection else { this._setAnchorItem(item); this._setSelectedItem(item); } break; } // Drag selection var mode = this.getMode(); if ( this.getDrag() && mode !== "single" && mode !== "one" && !isShiftPressed && !isCtrlPressed ) { // Cache location/scroll data this.__frameLocation = this._getLocation(); this.__frameScroll = this._getScroll(); // Store position at start this.__dragStartX = event.getDocumentLeft() + this.__frameScroll.left; this.__dragStartY = event.getDocumentTop() + this.__frameScroll.top; // Switch to capture mode this.__inCapture = true; this._capture(); } // Fire change event as needed this._fireChange("click"); this._userInteraction = false; }, /** * This method should be connected to the <code>mouseup</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseUp : function(event) { // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; // Read in keyboard modifiers var isCtrlPressed = event.isCtrlPressed() || (qx.core.Environment.get("os.name") == "osx" && event.isMetaPressed()); var isShiftPressed = event.isShiftPressed(); if (!isCtrlPressed && !isShiftPressed && this.__mouseDownOnSelected != null) { var item = this._getSelectableFromMouseEvent(event); if (item === null || !this.isItemSelected(item)) { this._userInteraction = false; return; } var mode = this.getMode(); if (mode === "additive") { // Remove item from selection this._removeFromSelection(item); } else { // Replace selection this._setSelectedItem(item); if (this.getMode() === "multi") { this._setLeadItem(item); this._setAnchorItem(item); } } this._userInteraction = false; } // Cleanup operation this._cleanup(); }, /** * This method should be connected to the <code>losecapture</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleLoseCapture : function(event) { this._cleanup(); }, /** * This method should be connected to the <code>mousemove</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseMove : function(event) { // Only relevant when capturing is enabled if (!this.__inCapture) { return; } // Update mouse position cache this.__mouseX = event.getDocumentLeft(); this.__mouseY = event.getDocumentTop(); // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; // Detect move directions var dragX = this.__mouseX + this.__frameScroll.left; if (dragX > this.__dragStartX) { this.__moveDirectionX = 1; } else if (dragX < this.__dragStartX) { this.__moveDirectionX = -1; } else { this.__moveDirectionX = 0; } var dragY = this.__mouseY + this.__frameScroll.top; if (dragY > this.__dragStartY) { this.__moveDirectionY = 1; } else if (dragY < this.__dragStartY) { this.__moveDirectionY = -1; } else { this.__moveDirectionY = 0; } // Update scroll steps var location = this.__frameLocation; if (this.__mouseX < location.left) { this.__scrollStepX = this.__mouseX - location.left; } else if (this.__mouseX > location.right) { this.__scrollStepX = this.__mouseX - location.right; } else { this.__scrollStepX = 0; } if (this.__mouseY < location.top) { this.__scrollStepY = this.__mouseY - location.top; } else if (this.__mouseY > location.bottom) { this.__scrollStepY = this.__mouseY - location.bottom; } else { this.__scrollStepY = 0; } // Dynamically create required timer instance if (!this.__scrollTimer) { this.__scrollTimer = new qx.event.Timer(100); this.__scrollTimer.addListener("interval", this._onInterval, this); } // Start interval this.__scrollTimer.start(); // Auto select based on new cursor position this._autoSelect(); event.stopPropagation(); this._userInteraction = false; }, /** * This method should be connected to the <code>addItem</code> event * of the managed object. * * @param e {qx.event.type.Data} The event object * @return {void} */ handleAddItem : function(e) { var item = e.getData(); if (this.getMode() === "one" && this.isSelectionEmpty()) { this.addItem(item); } }, /** * This method should be connected to the <code>removeItem</code> event * of the managed object. * * @param e {qx.event.type.Data} The event object * @return {void} */ handleRemoveItem : function(e) { this.removeItem(e.getData()); }, /* --------------------------------------------------------------------------- MOUSE SUPPORT INTERNALS --------------------------------------------------------------------------- */ /** * Stops all timers, release capture etc. to cleanup drag selection */ _cleanup : function() { if (!this.getDrag() && this.__inCapture) { return; } // Fire change event if needed if (this.__selectionModified) { this._fireChange("click"); } // Remove flags delete this.__inCapture; delete this.__lastRelX; delete this.__lastRelY; // Stop capturing this._releaseCapture(); // Stop timer if (this.__scrollTimer) { this.__scrollTimer.stop(); } }, /** * Event listener for timer used by drag selection * * @param e {qx.event.type.Event} Timer event */ _onInterval : function(e) { // Scroll by defined block size this._scrollBy(this.__scrollStepX, this.__scrollStepY); // TODO: Optimization: Detect real scroll changes first? // Update scroll cache this.__frameScroll = this._getScroll(); // Auto select based on new scroll position and cursor this._autoSelect(); }, /** * Automatically selects items based on the mouse movement during a drag selection */ _autoSelect : function() { var inner = this._getDimension(); // Get current relative Y position and compare it with previous one var relX = Math.max(0, Math.min(this.__mouseX - this.__frameLocation.left, inner.width)) + this.__frameScroll.left; var relY = Math.max(0, Math.min(this.__mouseY - this.__frameLocation.top, inner.height)) + this.__frameScroll.top; // Compare old and new relative coordinates (for performance reasons) if (this.__lastRelX === relX && this.__lastRelY === relY) { return; } this.__lastRelX = relX; this.__lastRelY = relY; // Cache anchor var anchor = this._getAnchorItem(); var lead = anchor; // Process X-coordinate var moveX = this.__moveDirectionX; var nextX, locationX; while (moveX !== 0) { // Find next item to process depending on current scroll direction nextX = moveX > 0 ? this._getRelatedSelectable(lead, "right") : this._getRelatedSelectable(lead, "left"); // May be null (e.g. first/last item) if (nextX !== null) { locationX = this._getSelectableLocationX(nextX); // Continue when the item is in the visible area if ( (moveX > 0 && locationX.left <= relX) || (moveX < 0 && locationX.right >= relX) ) { lead = nextX; continue; } } // Otherwise break break; } // Process Y-coordinate var moveY = this.__moveDirectionY; var nextY, locationY; while (moveY !== 0) { // Find next item to process depending on current scroll direction nextY = moveY > 0 ? this._getRelatedSelectable(lead, "under") : this._getRelatedSelectable(lead, "above"); // May be null (e.g. first/last item) if (nextY !== null) { locationY = this._getSelectableLocationY(nextY); // Continue when the item is in the visible area if ( (moveY > 0 && locationY.top <= relY) || (moveY < 0 && locationY.bottom >= relY) ) { lead = nextY; continue; } } // Otherwise break break; } // Differenciate between the two supported modes var mode = this.getMode(); if (mode === "multi") { // Replace current selection with new range this._selectItemRange(anchor, lead); } else if (mode === "additive") { // Behavior depends on the fact whether the // anchor item is selected or not if (this.isItemSelected(anchor)) { this._selectItemRange(anchor, lead, true); } else { this._deselectItemRange(anchor, lead); } // Improve performance. This mode does not rely // on full ranges as it always extend the old // selection/deselection. this._setAnchorItem(lead); } // Fire change event as needed this._fireChange("drag"); }, /* --------------------------------------------------------------------------- KEYBOARD SUPPORT --------------------------------------------------------------------------- */ /** * {Map} All supported navigation keys * * @lint ignoreReferenceField(__navigationKeys) */ __navigationKeys : { Home : 1, Down : 1 , Right : 1, PageDown : 1, End : 1, Up : 1, Left : 1, PageUp : 1 }, /** * This method should be connected to the <code>keypress</code> event * of the managed object. * * @param event {qx.event.type.KeySequence} A valid key sequence event * @return {void} */ handleKeyPress : function(event) { // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; var current, next; var key = event.getKeyIdentifier(); var mode = this.getMode(); // Support both control keys on Mac var isCtrlPressed = event.isCtrlPressed() || (qx.core.Environment.get("os.name") == "osx" && event.isMetaPressed()); var isShiftPressed = event.isShiftPressed(); var consumed = false; if (key === "A" && isCtrlPressed) { if (mode !== "single" && mode !== "one") { this._selectAllItems(); consumed = true; } } else if (key === "Escape") { if (mode !== "single" && mode !== "one") { this._clearSelection(); consumed = true; } } else if (key === "Space") { var lead = this.getLeadItem(); if (lead != null && !isShiftPressed) { if (isCtrlPressed || mode === "additive") { this._toggleInSelection(lead); } else { this._setSelectedItem(lead); } consumed = true; } } else if (this.__navigationKeys[key]) { consumed = true; if (mode === "single" || mode == "one") { current = this._getSelectedItem(); } else { current = this.getLeadItem(); } if (current !== null) { switch(key) { case "Home": next = this._getFirstSelectable(); break; case "End": next = this._getLastSelectable(); break; case "Up": next = this._getRelatedSelectable(current, "above"); break; case "Down": next = this._getRelatedSelectable(current, "under"); break; case "Left": next = this._getRelatedSelectable(current, "left"); break; case "Right": next = this._getRelatedSelectable(current, "right"); break; case "PageUp": next = this._getPage(current, true); break; case "PageDown": next = this._getPage(current, false); break; } } else { switch(key) { case "Home": case "Down": case "Right": case "PageDown": next = this._getFirstSelectable(); break; case "End": case "Up": case "Left": case "PageUp": next = this._getLastSelectable(); break; } } // Process result if (next !== null) { switch(mode) { case "single": case "one": this._setSelectedItem(next); break; case "additive": this._setLeadItem(next); break; case "multi": if (isShiftPressed) { var anchor = this._getAnchorItem(); if (anchor === null) { this._setAnchorItem(anchor = this._getFirstSelectable()); } this._setLeadItem(next); this._selectItemRange(anchor, next, isCtrlPressed); } else { this._setAnchorItem(next); this._setLeadItem(next); if (!isCtrlPressed) { this._setSelectedItem(next); } } break; } this.__oldScrollTop = this._getScroll().top; this._scrollItemIntoView(next); } } if (consumed) { // Stop processed events event.stop(); // Fire change event as needed this._fireChange("key"); } this._userInteraction = false; }, /* --------------------------------------------------------------------------- SUPPORT FOR ITEM RANGES --------------------------------------------------------------------------- */ /** * Adds all items to the selection */ _selectAllItems : function() { var range = this.getSelectables(); for (var i=0, l=range.length; i<l; i++) { this._addToSelection(range[i]); } }, /** * Clears current selection */ _clearSelection : function() { var selection = this.__selection; for (var hash in selection) { this._removeFromSelection(selection[hash]); } this.__selection = {}; }, /** * Select a range from <code>item1</code> to <code>item2</code>. * * @param item1 {Object} Start with this item * @param item2 {Object} End with this item * @param extend {Boolean?false} Whether the current * selection should be replaced or extended. */ _selectItemRange : function(item1, item2, extend) { var range = this._getSelectableRange(item1, item2); // Remove items which are not in the detected range if (!extend) { var selected = this.__selection; var mapped = this.__rangeToMap(range); for (var hash in selected) { if (!mapped[hash]) { this._removeFromSelection(selected[hash]); } } } // Add new items to the selection for (var i=0, l=range.length; i<l; i++) { this._addToSelection(range[i]); } }, /** * Deselect all items between <code>item1</code> and <code>item2</code>. * * @param item1 {Object} Start with this item * @param item2 {Object} End with this item */ _deselectItemRange : function(item1, item2) { var range = this._getSelectableRange(item1, item2); for (var i=0, l=range.length; i<l; i++) { this._removeFromSelection(range[i]); } }, /** * Internal method to convert a range to a map of hash * codes for faster lookup during selection compare routines. * * @param range {Array} List of selectable items */ __rangeToMap : function(range) { var mapped = {}; var item; for (var i=0, l=range.length; i<l; i++) { item = range[i]; mapped[this._selectableToHashCode(item)] = item; } return mapped; }, /* --------------------------------------------------------------------------- SINGLE ITEM QUERY AND MODIFICATION --------------------------------------------------------------------------- */ /** * Returns the first selected item. Only makes sense * when using manager in single selection mode. * * @return {var} The selected item (or <code>null</code>) */ _getSelectedItem : function() { for (var hash in this.__selection) { return this.__selection[hash]; } return null; }, /** * Replace current selection with given item. * * @param item {var} Any valid selectable item * @return {void} */ _setSelectedItem : function(item) { if (this._isSelectable(item)) { // If already selected try to find out if this is the only item var current = this.__selection; var hash = this._selectableToHashCode(item); if (!current[hash] || qx.lang.Object.hasMinLength(current, 2)) { this._clearSelection(); this._addToSelection(item); } } }, /* --------------------------------------------------------------------------- MODIFY ITEM SELECTION --------------------------------------------------------------------------- */ /** * Adds an item to the current selection. * * @param item {Object} Any item */ _addToSelection : function(item) { var hash = this._selectableToHashCode(item); if (this.__selection[hash] == null && this._isSelectable(item)) { this.__selection[hash] = item; this._styleSelectable(item, "selected", true); this.__selectionModified = true; } }, /** * Toggles the item e.g. remove it when already selected * or select it when currently not. * * @param item {Object} Any item */ _toggleInSelection : function(item) { var hash = this._selectableToHashCode(item); if (this.__selection[hash] == null) { this.__selection[hash] = item; this._styleSelectable(item, "selected", true); } else { delete this.__selection[hash]; this._styleSelectable(item, "selected", false); } this.__selectionModified = true; }, /** * Removes the given item from the current selection. * * @param item {Object} Any item */ _removeFromSelection : function(item) { var hash = this._selectableToHashCode(item); if (this.__selection[hash] != null) { delete this.__selection[hash]; this._styleSelectable(item, "selected", false); this.__selectionModified = true; } }, /** * Replaces current selection with items from given array. * * @param items {Array} List of items to select */ _replaceMultiSelection : function(items) { var modified = false; // Build map from hash codes and filter non-selectables var selectable, hash; var incoming = {}; for (var i=0, l=items.length; i<l; i++) { selectable = items[i]; if (this._isSelectable(selectable)) { hash = this._selectableToHashCode(selectable); incoming[hash] = selectable; } } // Remember last var first = items[0]; var last = selectable; // Clear old entries from map var current = this.__selection; for (var hash in current) { if (incoming[hash]) { // Reduce map to make next loop faster delete incoming[hash]; } else { // update internal map selectable = current[hash]; delete current[hash]; // apply styling this._styleSelectable(selectable, "selected", false); // remember that the selection has been modified modified = true; } } // Add remaining selectables to selection for (var hash in incoming) { // update internal map selectable = current[hash] = incoming[hash]; // apply styling this._styleSelectable(selectable, "selected", true); // remember that the selection has been modified modified = true; } // Do not do anything if selection is equal to previous one if (!modified) { return false; } // Scroll last incoming item into view this._scrollItemIntoView(last); // Reset anchor and lead item this._setLeadItem(first); this._setAnchorItem(first); // Finally fire change event this.__selectionModified = true; this._fireChange(); }, /** * Fires the selection change event if the selection has * been modified. * * @param context {String} One of <code>click</code>, <code>quick</code>, * <code>drag</code> or <code>key</code> or <code>null</code> */ _fireChange : function(context) { if (this.__selectionModified) { // Store context this.__selectionContext = context || null; // Fire data event which contains the current selection this.fireDataEvent("changeSelection", this.getSelection()); delete this.__selectionModified; } }, /** * Applies the default selection. The default item is the first item. * * @param force {Boolean} Whether the default selection sould forced. * * @return {var} The selected item. */ _applyDefaultSelection : function(force) { if (force === true || this.getMode() === "one" && this.isSelectionEmpty()) { var first = this._getFirstSelectable(); if (first != null) { this.selectItem(first); } return first; } return null; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__scrollTimer"); this.__selection = this.__mouseDownOnSelected = this.__anchorItem = null; this.__leadItem = null; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * A selection manager, which handles the selection in widgets. */ qx.Class.define("qx.ui.core.selection.Widget", { extend : qx.ui.core.selection.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param widget {qx.ui.core.Widget} The widget to connect to */ construct : function(widget) { this.base(arguments); this.__widget = widget; }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __widget : null, /* --------------------------------------------------------------------------- BASIC SUPPORT --------------------------------------------------------------------------- */ // overridden _isSelectable : function(item) { return this._isItemSelectable(item) && item.getLayoutParent() === this.__widget; }, // overridden _selectableToHashCode : function(item) { return item.$$hash; }, // overridden _styleSelectable : function(item, type, enabled) { enabled ? item.addState(type) : item.removeState(type); }, // overridden _capture : function() { this.__widget.capture(); }, // overridden _releaseCapture : function() { this.__widget.releaseCapture(); }, /** * Helper to return the selectability of the item concerning the * user interaaction. * * @param item {qx.ui.core.Widget} The item to check. * @return {Boolean} true, if the item is selectable. */ _isItemSelectable : function(item) { if (this._userInteraction) { return item.isVisible() && item.isEnabled(); } else { return item.isVisible(); } }, /** * Returns the connected widget. * @return {qx.ui.core.Widget} The widget */ _getWidget : function() { return this.__widget; }, /* --------------------------------------------------------------------------- DIMENSION AND LOCATION --------------------------------------------------------------------------- */ // overridden _getLocation : function() { var elem = this.__widget.getContentElement().getDomElement(); return elem ? qx.bom.element.Location.get(elem) : null; }, // overridden _getDimension : function() { return this.__widget.getInnerSize(); }, // overridden _getSelectableLocationX : function(item) { var computed = item.getBounds(); if (computed) { return { left : computed.left, right : computed.left + computed.width }; } }, // overridden _getSelectableLocationY : function(item) { var computed = item.getBounds(); if (computed) { return { top : computed.top, bottom : computed.top + computed.height }; } }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ // overridden _getScroll : function() { return { left : 0, top : 0 }; }, // overridden _scrollBy : function(xoff, yoff) { // empty implementation }, // overridden _scrollItemIntoView : function(item) { this.__widget.scrollChildIntoView(item); }, /* --------------------------------------------------------------------------- QUERY SUPPORT --------------------------------------------------------------------------- */ // overridden getSelectables : function(all) { // if only the user selectables should be returned var oldUserInteraction = false; if (!all) { oldUserInteraction = this._userInteraction; this._userInteraction = true; } var children = this.__widget.getChildren(); var result = []; var child; for (var i=0, l=children.length; i<l; i++) { child = children[i]; if (this._isItemSelectable(child)) { result.push(child); } } // reset to the former user interaction state this._userInteraction = oldUserInteraction; return result; }, // overridden _getSelectableRange : function(item1, item2) { // Fast path for identical items if (item1 === item2) { return [item1]; } // Iterate over children and collect all items // between the given two (including them) var children = this.__widget.getChildren(); var result = []; var active = false; var child; for (var i=0, l=children.length; i<l; i++) { child = children[i]; if (child === item1 || child === item2) { if (active) { result.push(child); break; } else { active = true; } } if (active && this._isItemSelectable(child)) { result.push(child); } } return result; }, // overridden _getFirstSelectable : function() { var children = this.__widget.getChildren(); for (var i=0, l=children.length; i<l; i++) { if (this._isItemSelectable(children[i])) { return children[i]; } } return null; }, // overridden _getLastSelectable : function() { var children = this.__widget.getChildren(); for (var i=children.length-1; i>0; i--) { if (this._isItemSelectable(children[i])) { return children[i]; } } return null; }, // overridden _getRelatedSelectable : function(item, relation) { var vertical = this.__widget.getOrientation() === "vertical"; var children = this.__widget.getChildren(); var index = children.indexOf(item); var sibling; if ((vertical && relation === "above") || (!vertical && relation === "left")) { for (var i=index-1; i>=0; i--) { sibling = children[i]; if (this._isItemSelectable(sibling)) { return sibling; } } } else if ((vertical && relation === "under") || (!vertical && relation === "right")) { for (var i=index+1; i<children.length; i++) { sibling = children[i]; if (this._isItemSelectable(sibling)) { return sibling; } } } return null; }, // overridden _getPage : function(lead, up) { if (up) { return this._getFirstSelectable(); } else { return this._getLastSelectable(); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__widget = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * A selection manager, which handles the selection in widgets extending * {@link qx.ui.core.scroll.AbstractScrollArea}. */ qx.Class.define("qx.ui.core.selection.ScrollArea", { extend : qx.ui.core.selection.Widget, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- BASIC SUPPORT --------------------------------------------------------------------------- */ // overridden _isSelectable : function(item) { return this._isItemSelectable(item) && item.getLayoutParent() === this._getWidget().getChildrenContainer(); }, /* --------------------------------------------------------------------------- DIMENSION AND LOCATION --------------------------------------------------------------------------- */ // overridden _getDimension : function() { return this._getWidget().getPaneSize(); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ // overridden _getScroll : function() { var widget = this._getWidget(); return { left : widget.getScrollX(), top : widget.getScrollY() }; }, // overridden _scrollBy : function(xoff, yoff) { var widget = this._getWidget(); widget.scrollByX(xoff); widget.scrollByY(yoff); }, /* --------------------------------------------------------------------------- QUERY SUPPORT --------------------------------------------------------------------------- */ // overridden _getPage : function(lead, up) { var selectables = this.getSelectables(); var length = selectables.length; var start = selectables.indexOf(lead); // Given lead is not a selectable?!? if (start === -1) { throw new Error("Invalid lead item: " + lead); } var widget = this._getWidget(); var scrollTop = widget.getScrollY(); var innerHeight = widget.getInnerSize().height; var top, bottom, found; if (up) { var min = scrollTop; var i=start; // Loop required to scroll pages up dynamically while(1) { // Iterate through all selectables from start for (; i>=0; i--) { top = widget.getItemTop(selectables[i]); // This item is out of the visible block if (top < min) { // Use previous one found = i+1; break; } } // Nothing found. Return first item. if (found == null) { var first = this._getFirstSelectable(); return first == lead ? null : first; } // Found item, but is identical to start or even before start item // Update min positon and try on previous page if (found >= start) { // Reduce min by the distance of the lead item to the visible // bottom edge. This is needed instead of a simple subtraction // of the inner height to keep the last lead visible on page key // presses. This is the behavior of native toolkits as well. min -= innerHeight + scrollTop - widget.getItemBottom(lead); found = null; continue; } // Return selectable return selectables[found]; } } else { var max = innerHeight + scrollTop; var i=start; // Loop required to scroll pages down dynamically while(1) { // Iterate through all selectables from start for (; i<length; i++) { bottom = widget.getItemBottom(selectables[i]); // This item is out of the visible block if (bottom > max) { // Use previous one found = i-1; break; } } // Nothing found. Return last item. if (found == null) { var last = this._getLastSelectable(); return last == lead ? null : last; } // Found item, but is identical to start or even before start item // Update max position and try on next page if (found <= start) { // Extend max by the distance of the lead item to the visible // top edge. This is needed instead of a simple addition // of the inner height to keep the last lead visible on page key // presses. This is the behavior of native toolkits as well. max += widget.getItemTop(lead) - scrollTop; found = null; continue; } // Return selectable return selectables[found]; } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * This mixin links all methods to manage the multi selection from the * internal selection manager to the widget. */ qx.Mixin.define("qx.ui.core.MMultiSelectionHandling", { /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { // Create selection manager var clazz = this.SELECTION_MANAGER; var manager = this.__manager = new clazz(this); // Add widget event listeners this.addListener("mousedown", manager.handleMouseDown, manager); this.addListener("mouseup", manager.handleMouseUp, manager); this.addListener("mouseover", manager.handleMouseOver, manager); this.addListener("mousemove", manager.handleMouseMove, manager); this.addListener("losecapture", manager.handleLoseCapture, manager); this.addListener("keypress", manager.handleKeyPress, manager); this.addListener("addItem", manager.handleAddItem, manager); this.addListener("removeItem", manager.handleRemoveItem, manager); // Add manager listeners manager.addListener("changeSelection", this._onSelectionChange, this); }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The selection mode to use. * * For further details please have a look at: * {@link qx.ui.core.selection.Abstract#mode} */ selectionMode : { check : [ "single", "multi", "additive", "one" ], init : "single", apply : "_applySelectionMode" }, /** * Enable drag selection (multi selection of items through * dragging the mouse in pressed states). * * Only possible for the selection modes <code>multi</code> and <code>additive</code> */ dragSelection : { check : "Boolean", init : false, apply : "_applyDragSelection" }, /** * Enable quick selection mode, where no click is needed to change the selection. * * Only possible for the modes <code>single</code> and <code>one</code>. */ quickSelection : { check : "Boolean", init : false, apply : "_applyQuickSelection" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.core.selection.Abstract} The selection manager */ __manager : null, /* --------------------------------------------------------------------------- USER API --------------------------------------------------------------------------- */ /** * Selects all items of the managed object. */ selectAll : function() { this.__manager.selectAll(); }, /** * Detects whether the given item is currently selected. * * @param item {qx.ui.core.Widget} Any valid selectable item. * @return {Boolean} Whether the item is selected. * @throws an exception if the item is not a child element. */ isSelected : function(item) { if (!qx.ui.core.Widget.contains(this, item)) { throw new Error("Could not test if " + item + " is selected, because it is not a child element!"); } return this.__manager.isItemSelected(item); }, /** * Adds the given item to the existing selection. * * Use {@link #setSelection} instead if you want to replace * the current selection. * * @param item {qx.ui.core.Widget} Any valid item. * @throws an exception if the item is not a child element. */ addToSelection : function(item) { if (!qx.ui.core.Widget.contains(this, item)) { throw new Error("Could not add + " + item + " to selection, because it is not a child element!"); } this.__manager.addItem(item); }, /** * Removes the given item from the selection. * * Use {@link #resetSelection} when you want to clear * the whole selection at once. * * @param item {qx.ui.core.Widget} Any valid item * @throws an exception if the item is not a child element. */ removeFromSelection : function(item) { if (!qx.ui.core.Widget.contains(this, item)) { throw new Error("Could not remove " + item + " from selection, because it is not a child element!"); } this.__manager.removeItem(item); }, /** * Selects an item range between two given items. * * @param begin {qx.ui.core.Widget} Item to start with * @param end {qx.ui.core.Widget} Item to end at */ selectRange : function(begin, end) { this.__manager.selectItemRange(begin, end); }, /** * Clears the whole selection at once. Also * resets the lead and anchor items and their * styles. */ resetSelection : function() { this.__manager.clearSelection(); }, /** * Replaces current selection with the given items. * * @param items {qx.ui.core.Widget[]} Items to select. * @throws an exception if one of the items is not a child element and if * the mode is set to <code>single</code> or <code>one</code> and * the items contains more than one item. */ setSelection : function(items) { for (var i = 0; i < items.length; i++) { if (!qx.ui.core.Widget.contains(this, items[i])) { throw new Error("Could not select " + items[i] + ", because it is not a child element!"); } } if (items.length === 0) { this.resetSelection(); } else { var currentSelection = this.getSelection(); if (!qx.lang.Array.equals(currentSelection, items)) { this.__manager.replaceSelection(items); } } }, /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {qx.ui.core.Widget[]} List of items. */ getSelection : function() { return this.__manager.getSelection(); }, /** * Returns an array of currently selected items sorted * by their index in the container. * * @return {qx.ui.core.Widget[]} Sorted list of items */ getSortedSelection : function() { return this.__manager.getSortedSelection(); }, /** * Whether the selection is empty * * @return {Boolean} Whether the selection is empty */ isSelectionEmpty : function() { return this.__manager.isSelectionEmpty(); }, /** * Returns the last selection context. * * @return {String | null} One of <code>click</code>, <code>quick</code>, * <code>drag</code> or <code>key</code> or <code>null</code>. */ getSelectionContext : function() { return this.__manager.getSelectionContext(); }, /** * Returns the internal selection manager. Use this with * caution! * * @return {qx.ui.core.selection.Abstract} The selection manager */ _getManager : function() { return this.__manager; }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables: function(all) { return this.__manager.getSelectables(all); }, /** * Invert the selection. Select the non selected and deselect the selected. */ invertSelection: function() { this.__manager.invertSelection(); }, /** * Returns the current lead item. Generally the item which was last modified * by the user (clicked on etc.) * * @return {qx.ui.core.Widget} The lead item or <code>null</code> */ _getLeadItem : function() { var mode = this.__manager.getMode(); if (mode === "single" || mode === "one") { return this.__manager.getSelectedItem(); } else { return this.__manager.getLeadItem(); } }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applySelectionMode : function(value, old) { this.__manager.setMode(value); }, // property apply _applyDragSelection : function(value, old) { this.__manager.setDrag(value); }, // property apply _applyQuickSelection : function(value, old) { this.__manager.setQuick(value); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event listener for <code>changeSelection</code> event on selection manager. * * @param e {qx.event.type.Data} Data event */ _onSelectionChange : function(e) { this.fireDataEvent("changeSelection", e.getData()); } }, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__manager"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Each object, which should support multiselection selection have to * implement this interface. */ qx.Interface.define("qx.ui.core.IMultiSelection", { extend: qx.ui.core.ISingleSelection, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Selects all items of the managed object. */ selectAll : function() { return true; }, /** * Adds the given item to the existing selection. * * @param item {qx.ui.core.Widget} Any valid item * @throws an exception if the item is not a child element. */ addToSelection : function(item) { return arguments.length == 1; }, /** * Removes the given item from the selection. * * Use {@link qx.ui.core.ISingleSelection#resetSelection} when you * want to clear the whole selection at once. * * @param item {qx.ui.core.Widget} Any valid item * @throws an exception if the item is not a child element. */ removeFromSelection : function(item) { return arguments.length == 1; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin holding the handler for the two axis mouse wheel scrolling. Please * keep in mind that the including widget has to have the scroll bars * implemented as child controls named <code>scrollbar-x</code> and * <code>scrollbar-y</code> to get the handler working. Also, you have to * attach the listener yourself. */ qx.Mixin.define("qx.ui.core.scroll.MWheelHandling", { members : { /** * Mouse wheel event handler * * @param e {qx.event.type.Mouse} Mouse event */ _onMouseWheel : function(e) { var showX = this._isChildControlVisible("scrollbar-x"); var showY = this._isChildControlVisible("scrollbar-y"); var scrollbarY = showY ? this.getChildControl("scrollbar-y", true) : null; var scrollbarX = showX ? this.getChildControl("scrollbar-x", true) : null; var deltaY = e.getWheelDelta("y"); var deltaX = e.getWheelDelta("x"); var endY = !showY; var endX = !showX; // y case if (scrollbarY) { var steps = parseInt(deltaY); if (steps !== 0) { scrollbarY.scrollBySteps(steps); } var position = scrollbarY.getPosition(); var max = scrollbarY.getMaximum(); // pass the event to the parent if the scrollbar is at an edge if (steps < 0 && position <= 0 || steps > 0 && position >= max) { endY = true; } } // x case if (scrollbarX) { var steps = parseInt(deltaX); if (steps !== 0) { scrollbarX.scrollBySteps(steps); } var position = scrollbarX.getPosition(); var max = scrollbarX.getMaximum(); // pass the event to the parent if the scrollbar is at an edge if (steps < 0 && position <= 0 || steps > 0 && position >= max) { endX = true; } } // pass the event to the parent if both scrollbars are at the end if (!endY || !endX) { // Stop bubbling and native event only if a scrollbar is visible e.stop(); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ qx.core.Environment.add("qx.nativeScrollBars", false); /** * Include this widget if you want to create scrollbars depending on the global * "qx.nativeScrollBars" setting. */ qx.Mixin.define("qx.ui.core.scroll.MScrollBarFactory", { members : { /** * Creates a new scrollbar. This can either be a styled qooxdoo scrollbar * or a native browser scrollbar. * * @param orientation {String?"horizontal"} The initial scroll bar orientation * @return {qx.ui.core.scroll.IScrollBar} The scrollbar instance */ _createScrollBar : function(orientation) { if (qx.core.Environment.get("qx.nativeScrollBars")) { return new qx.ui.core.scroll.NativeScrollBar(orientation); } else { return new qx.ui.core.scroll.ScrollBar(orientation); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * All widget used as scrollbars must implement this interface. */ qx.Interface.define("qx.ui.core.scroll.IScrollBar", { events : { /** Fired if the user scroll */ "scroll" : "qx.event.type.Data" }, properties : { /** * The scroll bar orientation */ orientation : {}, /** * The maximum value (difference between available size and * content size). */ maximum : {}, /** * Position of the scrollbar (which means the scroll left/top of the * attached area's pane) * * Strictly validates according to {@link #maximum}. * Does not apply any correction to the incoming value. If you depend * on this, please use {@link #scrollTo} instead. */ position : {}, /** * Factor to apply to the width/height of the knob in relation * to the dimension of the underlying area. */ knobFactor : {} }, members : { /** * Scrolls to the given position. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param position {Integer} Scroll to this position. Must be greater zero. * @return {void} */ scrollTo : function(position) { this.assertNumber(position); }, /** * Scrolls by the given offset. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param offset {Integer} Scroll by this offset * @return {void} */ scrollBy : function(offset) { this.assertNumber(offset); }, /** * Scrolls by the given number of steps. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param steps {Integer} Number of steps * @return {void} */ scrollBySteps : function(steps) { this.assertNumber(steps); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The scroll bar widget wraps the native browser scroll bars as a qooxdoo widget. * It can be uses instead of the styled qooxdoo scroll bars. * * Scroll bars are used by the {@link qx.ui.container.Scroll} container. Usually * a scroll bar is not used directly. * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var scrollBar = new qx.ui.core.scroll.NativeScrollBar("horizontal"); * scrollBar.set({ * maximum: 500 * }) * this.getRoot().add(scrollBar); * </pre> * * This example creates a horizontal scroll bar with a maximum value of 500. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/scrollbar.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.core.scroll.NativeScrollBar", { extend : qx.ui.core.Widget, implement : qx.ui.core.scroll.IScrollBar, /** * @param orientation {String?"horizontal"} The initial scroll bar orientation */ construct : function(orientation) { this.base(arguments); this.addState("native"); this.getContentElement().addListener("scroll", this._onScroll, this); this.addListener("mousedown", this._stopPropagation, this); this.addListener("mouseup", this._stopPropagation, this); this.addListener("mousemove", this._stopPropagation, this); this.addListener("appear", this._onAppear, this); this.getContentElement().add(this._getScrollPaneElement()); // Configure orientation if (orientation != null) { this.setOrientation(orientation); } else { this.initOrientation(); } }, properties : { // overridden appearance : { refine : true, init : "scrollbar" }, // interface implementation orientation : { check : [ "horizontal", "vertical" ], init : "horizontal", apply : "_applyOrientation" }, // interface implementation maximum : { check : "PositiveInteger", apply : "_applyMaximum", init : 100 }, // interface implementation position : { check : "Number", init : 0, apply : "_applyPosition", event : "scroll" }, /** * Step size for each click on the up/down or left/right buttons. */ singleStep : { check : "Integer", init : 20 }, // interface implementation knobFactor : { check : "PositiveNumber", nullable : true } }, members : { __isHorizontal : null, __scrollPaneElement : null, /** * Get the scroll pane html element. * * @return {qx.html.Element} The element */ _getScrollPaneElement : function() { if (!this.__scrollPaneElement) { this.__scrollPaneElement = new qx.html.Element(); } return this.__scrollPaneElement; }, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden renderLayout : function(left, top, width, height) { var changes = this.base(arguments, left, top, width, height); this._updateScrollBar(); return changes; }, // overridden _getContentHint : function() { var scrollbarWidth = qx.bom.element.Overflow.getScrollbarWidth(); return { width: this.__isHorizontal ? 100 : scrollbarWidth, maxWidth: this.__isHorizontal ? null : scrollbarWidth, minWidth: this.__isHorizontal ? null : scrollbarWidth, height: this.__isHorizontal ? scrollbarWidth : 100, maxHeight: this.__isHorizontal ? scrollbarWidth : null, minHeight: this.__isHorizontal ? scrollbarWidth : null } }, // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); this._updateScrollBar(); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMaximum : function(value) { this._updateScrollBar(); }, // property apply _applyPosition : function(value) { var content = this.getContentElement(); if (this.__isHorizontal) { content.scrollToX(value) } else { content.scrollToY(value); } }, // property apply _applyOrientation : function(value, old) { var isHorizontal = this.__isHorizontal = value === "horizontal"; this.set({ allowGrowX : isHorizontal, allowShrinkX : isHorizontal, allowGrowY : !isHorizontal, allowShrinkY : !isHorizontal }); if (isHorizontal) { this.replaceState("vertical", "horizontal"); } else { this.replaceState("horizontal", "vertical"); } this.getContentElement().setStyles({ overflowX: isHorizontal ? "scroll" : "hidden", overflowY: isHorizontal ? "hidden" : "scroll" }); // Update layout qx.ui.core.queue.Layout.add(this); }, /** * Update the scroll bar according to its current size, max value and * enabled state. */ _updateScrollBar : function() { var isHorizontal = this.__isHorizontal; var bounds = this.getBounds(); if (!bounds) { return; } if (this.isEnabled()) { var containerSize = isHorizontal ? bounds.width : bounds.height; var innerSize = this.getMaximum() + containerSize; } else { innerSize = 0; } // Scrollbars don't work properly in IE if the element with overflow has // excatly the size of the scrollbar. Thus we move the element one pixel // out of the view and increase the size by one. if ((qx.core.Environment.get("engine.name") == "mshtml")) { var bounds = this.getBounds(); this.getContentElement().setStyles({ left: isHorizontal ? "0" : "-1px", top: isHorizontal ? "-1px" : "0", width: (isHorizontal ? bounds.width : bounds.width + 1) + "px", height: (isHorizontal ? bounds.height + 1 : bounds.height) + "px" }); } this._getScrollPaneElement().setStyles({ left: 0, top: 0, width: (isHorizontal ? innerSize : 1) + "px", height: (isHorizontal ? 1 : innerSize) + "px" }); this.scrollTo(this.getPosition()); }, // interface implementation scrollTo : function(position) { this.setPosition(Math.max(0, Math.min(this.getMaximum(), position))); }, // interface implementation scrollBy : function(offset) { this.scrollTo(this.getPosition() + offset) }, // interface implementation scrollBySteps : function(steps) { var size = this.getSingleStep(); this.scrollBy(steps * size); }, /** * Scroll event handler * * @param e {qx.event.type.Event} the scroll event */ _onScroll : function(e) { var container = this.getContentElement(); var position = this.__isHorizontal ? container.getScrollX() : container.getScrollY(); this.setPosition(position); }, /** * Listener for appear which ensured the scroll bar is positioned right * on appear. * * @param e {qx.event.type.Data} Incoming event object */ _onAppear : function(e) { this._applyPosition(this.getPosition()); }, /** * Stops propagation on the given even * * @param e {qx.event.type.Event} the event */ _stopPropagation : function(e) { e.stopPropagation(); } }, destruct : function() { this._disposeObjects("__scrollPaneElement"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The scroll bar widget, is a special slider, which is used in qooxdoo instead * of the native browser scroll bars. * * Scroll bars are used by the {@link qx.ui.container.Scroll} container. Usually * a scroll bar is not used directly. * * @childControl slider {qx.ui.core.scroll.ScrollSlider} scroll slider component * @childControl button-begin {qx.ui.form.RepeatButton} button to scroll to top * @childControl button-end {qx.ui.form.RepeatButton} button to scroll to bottom * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var scrollBar = new qx.ui.core.scroll.ScrollBar("horizontal"); * scrollBar.set({ * maximum: 500 * }) * this.getRoot().add(scrollBar); * </pre> * * This example creates a horizontal scroll bar with a maximum value of 500. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/scrollbar.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.core.scroll.ScrollBar", { extend : qx.ui.core.Widget, implement : qx.ui.core.scroll.IScrollBar, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param orientation {String?"horizontal"} The initial scroll bar orientation */ construct : function(orientation) { this.base(arguments); // Create child controls this._createChildControl("button-begin"); this._createChildControl("slider").addListener("resize", this._onResizeSlider, this); this._createChildControl("button-end"); // Configure orientation if (orientation != null) { this.setOrientation(orientation); } else { this.initOrientation(); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "scrollbar" }, /** * The scroll bar orientation */ orientation : { check : [ "horizontal", "vertical" ], init : "horizontal", apply : "_applyOrientation" }, /** * The maximum value (difference between available size and * content size). */ maximum : { check : "PositiveInteger", apply : "_applyMaximum", init : 100 }, /** * Position of the scrollbar (which means the scroll left/top of the * attached area's pane) * * Strictly validates according to {@link #maximum}. * Does not apply any correction to the incoming value. If you depend * on this, please use {@link #scrollTo} instead. */ position : { check : "qx.lang.Type.isNumber(value)&&value>=0&&value<=this.getMaximum()", init : 0, apply : "_applyPosition", event : "scroll" }, /** * Step size for each click on the up/down or left/right buttons. */ singleStep : { check : "Integer", init : 20 }, /** * The amount to increment on each event. Typically corresponds * to the user pressing <code>PageUp</code> or <code>PageDown</code>. */ pageStep : { check : "Integer", init : 10, apply : "_applyPageStep" }, /** * Factor to apply to the width/height of the knob in relation * to the dimension of the underlying area. */ knobFactor : { check : "PositiveNumber", apply : "_applyKnobFactor", nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __offset : 2, __originalMinSize : 0, // overridden _computeSizeHint : function() { var hint = this.base(arguments); if (this.getOrientation() === "horizontal") { this.__originalMinSize = hint.minWidth; hint.minWidth = 0; } else { this.__originalMinSize = hint.minHeight; hint.minHeight = 0; } return hint; }, // overridden renderLayout : function(left, top, width, height) { var changes = this.base(arguments, left, top, width, height); var horizontal = this.getOrientation() === "horizontal"; if (this.__originalMinSize >= (horizontal ? width : height)) { this.getChildControl("button-begin").setVisibility("hidden"); this.getChildControl("button-end").setVisibility("hidden"); } else { this.getChildControl("button-begin").setVisibility("visible"); this.getChildControl("button-end").setVisibility("visible"); } return changes }, // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "slider": control = new qx.ui.core.scroll.ScrollSlider(); control.setPageStep(100); control.setFocusable(false); control.addListener("changeValue", this._onChangeSliderValue, this); this._add(control, {flex: 1}); break; case "button-begin": // Top/Left Button control = new qx.ui.form.RepeatButton(); control.setFocusable(false); control.addListener("execute", this._onExecuteBegin, this); this._add(control); break; case "button-end": // Bottom/Right Button control = new qx.ui.form.RepeatButton(); control.setFocusable(false); control.addListener("execute", this._onExecuteEnd, this); this._add(control); break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMaximum : function(value) { this.getChildControl("slider").setMaximum(value); }, // property apply _applyPosition : function(value) { this.getChildControl("slider").setValue(value); }, // property apply _applyKnobFactor : function(value) { this.getChildControl("slider").setKnobFactor(value); }, // property apply _applyPageStep : function(value) { this.getChildControl("slider").setPageStep(value); }, // property apply _applyOrientation : function(value, old) { // Dispose old layout var oldLayout = this._getLayout(); if (oldLayout) { oldLayout.dispose(); } // Reconfigure if (value === "horizontal") { this._setLayout(new qx.ui.layout.HBox()); this.setAllowStretchX(true); this.setAllowStretchY(false); this.replaceState("vertical", "horizontal"); this.getChildControl("button-begin").replaceState("up", "left"); this.getChildControl("button-end").replaceState("down", "right"); } else { this._setLayout(new qx.ui.layout.VBox()); this.setAllowStretchX(false); this.setAllowStretchY(true); this.replaceState("horizontal", "vertical"); this.getChildControl("button-begin").replaceState("left", "up"); this.getChildControl("button-end").replaceState("right", "down"); } // Sync slider orientation this.getChildControl("slider").setOrientation(value); }, /* --------------------------------------------------------------------------- METHOD REDIRECTION TO SLIDER --------------------------------------------------------------------------- */ /** * Scrolls to the given position. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param position {Integer} Scroll to this position. Must be greater zero. * @return {void} */ scrollTo : function(position) { this.getChildControl("slider").slideTo(position); }, /** * Scrolls by the given offset. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param offset {Integer} Scroll by this offset * @return {void} */ scrollBy : function(offset) { this.getChildControl("slider").slideBy(offset); }, /** * Scrolls by the given number of steps. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param steps {Integer} Number of steps * @return {void} */ scrollBySteps : function(steps) { var size = this.getSingleStep(); this.getChildControl("slider").slideBy(steps * size); }, /* --------------------------------------------------------------------------- EVENT LISTENER --------------------------------------------------------------------------- */ /** * Executed when the up/left button is executed (pressed) * * @param e {qx.event.type.Event} Execute event of the button * @return {void} */ _onExecuteBegin : function(e) { this.scrollBy(-this.getSingleStep()); }, /** * Executed when the down/right button is executed (pressed) * * @param e {qx.event.type.Event} Execute event of the button * @return {void} */ _onExecuteEnd : function(e) { this.scrollBy(this.getSingleStep()); }, /** * Change listener for slider value changes. * * @param e {qx.event.type.Data} The change event object * @return {void} */ _onChangeSliderValue : function(e) { this.setPosition(e.getData()); }, /** * Hide the knob of the slider if the slidebar is too small or show it * otherwise. * * @param e {qx.event.type.Data} event object */ _onResizeSlider : function(e) { var knob = this.getChildControl("slider").getChildControl("knob"); var knobHint = knob.getSizeHint(); var hideKnob = false; var sliderSize = this.getChildControl("slider").getInnerSize(); if (this.getOrientation() == "vertical") { if (sliderSize.height < knobHint.minHeight + this.__offset) { hideKnob = true; } } else { if (sliderSize.width < knobHint.minWidth + this.__offset) { hideKnob = true; } } if (hideKnob) { knob.exclude(); } else { knob.show(); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The Slider widget provides a vertical or horizontal slider. * * The Slider is the classic widget for controlling a bounded value. * It lets the user move a slider handle along a horizontal or vertical * groove and translates the handle's position into an integer value * within the defined range. * * The Slider has very few of its own functions. * The most useful functions are slideTo() to set the slider directly to some * value; setSingleStep(), setPageStep() to set the steps; and setMinimum() * and setMaximum() to define the range of the slider. * * A slider accepts focus on Tab and provides both a mouse wheel and * a keyboard interface. The keyboard interface is the following: * * * Left/Right move a horizontal slider by one single step. * * Up/Down move a vertical slider by one single step. * * PageUp moves up one page. * * PageDown moves down one page. * * Home moves to the start (minimum). * * End moves to the end (maximum). * * Here are the main properties of the class: * * # <code>value</code>: The bounded integer that {@link qx.ui.form.INumberForm} * maintains. * # <code>minimum</code>: The lowest possible value. * # <code>maximum</code>: The highest possible value. * # <code>singleStep</code>: The smaller of two natural steps that an abstract * sliders provides and typically corresponds to the user pressing an arrow key. * # <code>pageStep</code>: The larger of two natural steps that an abstract * slider provides and typically corresponds to the user pressing PageUp or * PageDown. * * @childControl knob {qx.ui.core.Widget} knob to set the value of the slider */ qx.Class.define("qx.ui.form.Slider", { extend : qx.ui.core.Widget, implement : [ qx.ui.form.IForm, qx.ui.form.INumberForm, qx.ui.form.IRange ], include : [qx.ui.form.MForm], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param orientation {String?"horizontal"} Configure the * {@link #orientation} property */ construct : function(orientation) { this.base(arguments); // Force canvas layout this._setLayout(new qx.ui.layout.Canvas()); // Add listeners this.addListener("keypress", this._onKeyPress); this.addListener("mousewheel", this._onMouseWheel); this.addListener("mousedown", this._onMouseDown); this.addListener("mouseup", this._onMouseUp); this.addListener("losecapture", this._onMouseUp); this.addListener("resize", this._onUpdate); // Stop events this.addListener("contextmenu", this._onStopEvent); this.addListener("click", this._onStopEvent); this.addListener("dblclick", this._onStopEvent); // Initialize orientation if (orientation != null) { this.setOrientation(orientation); } else { this.initOrientation(); } }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * Change event for the value. */ changeValue: 'qx.event.type.Data' }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "slider" }, // overridden focusable : { refine : true, init : true }, /** Whether the slider is horizontal or vertical. */ orientation : { check : [ "horizontal", "vertical" ], init : "horizontal", apply : "_applyOrientation" }, /** * The current slider value. * * Strictly validates according to {@link #minimum} and {@link #maximum}. * Do not apply any value correction to the incoming value. If you depend * on this, please use {@link #slideTo} instead. */ value : { check : "typeof value==='number'&&value>=this.getMinimum()&&value<=this.getMaximum()", init : 0, apply : "_applyValue", nullable: true }, /** * The minimum slider value (may be negative). This value must be smaller * than {@link #maximum}. */ minimum : { check : "Integer", init : 0, apply : "_applyMinimum", event: "changeMinimum" }, /** * The maximum slider value (may be negative). This value must be larger * than {@link #minimum}. */ maximum : { check : "Integer", init : 100, apply : "_applyMaximum", event : "changeMaximum" }, /** * The amount to increment on each event. Typically corresponds * to the user pressing an arrow key. */ singleStep : { check : "Integer", init : 1 }, /** * The amount to increment on each event. Typically corresponds * to the user pressing <code>PageUp</code> or <code>PageDown</code>. */ pageStep : { check : "Integer", init : 10 }, /** * Factor to apply to the width/height of the knob in relation * to the dimension of the underlying area. */ knobFactor : { check : "Number", apply : "_applyKnobFactor", nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __sliderLocation : null, __knobLocation : null, __knobSize : null, __dragMode : null, __dragOffset : null, __trackingMode : null, __trackingDirection : null, __trackingEnd : null, __timer : null, // event delay stuff during drag __dragTimer: null, __lastValueEvent: null, __dragValue: null, // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { invalid : true }, // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "knob": control = new qx.ui.core.Widget(); control.addListener("resize", this._onUpdate, this); control.addListener("mouseover", this._onMouseOver); control.addListener("mouseout", this._onMouseOut); this._add(control); break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event handler for mouseover events at the knob child control. * * Adds the 'hovered' state * * @param e {qx.event.type.Mouse} Incoming mouse event */ _onMouseOver : function(e) { this.addState("hovered"); }, /** * Event handler for mouseout events at the knob child control. * * Removes the 'hovered' state * * @param e {qx.event.type.Mouse} Incoming mouse event */ _onMouseOut : function(e) { this.removeState("hovered"); }, /** * Listener of mousewheel event * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseWheel : function(e) { var axis = this.getOrientation() === "horizontal" ? "x" : "y"; var delta = e.getWheelDelta(axis); var direction = delta > 0 ? 1 : delta < 0 ? -1 : 0; this.slideBy(direction * this.getSingleStep()); e.stop(); }, /** * Event handler for keypress events. * * Adds support for arrow keys, page up, page down, home and end keys. * * @param e {qx.event.type.KeySequence} Incoming keypress event * @return {void} */ _onKeyPress : function(e) { var isHorizontal = this.getOrientation() === "horizontal"; var backward = isHorizontal ? "Left" : "Up"; var forward = isHorizontal ? "Right" : "Down"; switch(e.getKeyIdentifier()) { case forward: this.slideForward(); break; case backward: this.slideBack(); break; case "PageDown": this.slidePageForward(); break; case "PageUp": this.slidePageBack(); break; case "Home": this.slideToBegin(); break; case "End": this.slideToEnd(); break; default: return; } // Stop processed events e.stop(); }, /** * Listener of mousedown event. Initializes drag or tracking mode. * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseDown : function(e) { // this can happen if the user releases the button while dragging outside // of the browser viewport if (this.__dragMode) { return; } var isHorizontal = this.__isHorizontal; var knob = this.getChildControl("knob"); var locationProperty = isHorizontal ? "left" : "top"; var cursorLocation = isHorizontal ? e.getDocumentLeft() : e.getDocumentTop(); var sliderLocation = this.__sliderLocation = qx.bom.element.Location.get(this.getContentElement().getDomElement())[locationProperty]; var knobLocation = this.__knobLocation = qx.bom.element.Location.get(knob.getContainerElement().getDomElement())[locationProperty]; if (e.getTarget() === knob) { // Switch into drag mode this.__dragMode = true; if (!this.__dragTimer){ // create a timer to fire delayed dragging events if dragging stops. this.__dragTimer = new qx.event.Timer(100); this.__dragTimer.addListener("interval", this._fireValue, this); } this.__dragTimer.start(); // Compute dragOffset (includes both: inner position of the widget and // cursor position on knob) this.__dragOffset = cursorLocation + sliderLocation - knobLocation; // add state knob.addState("pressed"); } else { // Switch into tracking mode this.__trackingMode = true; // Detect tracking direction this.__trackingDirection = cursorLocation <= knobLocation ? -1 : 1; // Compute end value this.__computeTrackingEnd(e); // Directly call interval method once this._onInterval(); // Initialize timer (when needed) if (!this.__timer) { this.__timer = new qx.event.Timer(100); this.__timer.addListener("interval", this._onInterval, this); } // Start timer this.__timer.start(); } // Register move listener this.addListener("mousemove", this._onMouseMove); // Activate capturing this.capture(); // Stop event e.stopPropagation(); }, /** * Listener of mouseup event. Used for cleanup of previously * initialized modes. * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseUp : function(e) { if (this.__dragMode) { // Release capture mode this.releaseCapture(); // Cleanup status flags delete this.__dragMode; // as we come out of drag mode, make // sure content gets synced this.__dragTimer.stop(); this._fireValue(); delete this.__dragOffset; // remove state this.getChildControl("knob").removeState("pressed"); // it's necessary to check whether the mouse cursor is over the knob widget to be able to // to decide whether to remove the 'hovered' state. if (e.getType() === "mouseup") { var deltaSlider; var deltaPosition; var positionSlider; if (this.__isHorizontal) { deltaSlider = e.getDocumentLeft() - (this._valueToPosition(this.getValue()) + this.__sliderLocation); positionSlider = qx.bom.element.Location.get(this.getContentElement().getDomElement())["top"]; deltaPosition = e.getDocumentTop() - (positionSlider + this.getChildControl("knob").getBounds().top); } else { deltaSlider = e.getDocumentTop() - (this._valueToPosition(this.getValue()) + this.__sliderLocation); positionSlider = qx.bom.element.Location.get(this.getContentElement().getDomElement())["left"]; deltaPosition = e.getDocumentLeft() - (positionSlider + this.getChildControl("knob").getBounds().left); } if (deltaPosition < 0 || deltaPosition > this.__knobSize || deltaSlider < 0 || deltaSlider > this.__knobSize) { this.getChildControl("knob").removeState("hovered"); } } } else if (this.__trackingMode) { // Stop timer interval this.__timer.stop(); // Release capture mode this.releaseCapture(); // Cleanup status flags delete this.__trackingMode; delete this.__trackingDirection; delete this.__trackingEnd; } // Remove move listener again this.removeListener("mousemove", this._onMouseMove); // Stop event if (e.getType() === "mouseup") { e.stopPropagation(); } }, /** * Listener of mousemove event for the knob. Only used in drag mode. * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseMove : function(e) { if (this.__dragMode) { var dragStop = this.__isHorizontal ? e.getDocumentLeft() : e.getDocumentTop(); var position = dragStop - this.__dragOffset; this.slideTo(this._positionToValue(position)); } else if (this.__trackingMode) { // Update tracking end on mousemove this.__computeTrackingEnd(e); } // Stop event e.stopPropagation(); }, /** * Listener of interval event by the internal timer. Only used * in tracking sequences. * * @param e {qx.event.type.Event} Incoming event object * @return {void} */ _onInterval : function(e) { // Compute new value var value = this.getValue() + (this.__trackingDirection * this.getPageStep()); // Limit value if (value < this.getMinimum()) { value = this.getMinimum(); } else if (value > this.getMaximum()) { value = this.getMaximum(); } // Stop at tracking position (where the mouse is pressed down) var slideBack = this.__trackingDirection == -1; if ((slideBack && value <= this.__trackingEnd) || (!slideBack && value >= this.__trackingEnd)) { value = this.__trackingEnd; } // Finally slide to the desired position this.slideTo(value); }, /** * Listener of resize event for both the slider itself and the knob. * * @param e {qx.event.type.Data} Incoming event object * @return {void} */ _onUpdate : function(e) { // Update sliding space var availSize = this.getInnerSize(); var knobSize = this.getChildControl("knob").getBounds(); var sizeProperty = this.__isHorizontal ? "width" : "height"; // Sync knob size this._updateKnobSize(); // Store knob size this.__slidingSpace = availSize[sizeProperty] - knobSize[sizeProperty]; this.__knobSize = knobSize[sizeProperty]; // Update knob position (sliding space must be updated first) this._updateKnobPosition(); }, /* --------------------------------------------------------------------------- UTILS --------------------------------------------------------------------------- */ /** {Boolean} Whether the slider is laid out horizontally */ __isHorizontal : false, /** * {Integer} Available space for knob to slide on, computed on resize of * the widget */ __slidingSpace : 0, /** * Computes the value where the tracking should end depending on * the current mouse position. * * @param e {qx.event.type.Mouse} Incoming mouse event * @return {void} */ __computeTrackingEnd : function(e) { var isHorizontal = this.__isHorizontal; var cursorLocation = isHorizontal ? e.getDocumentLeft() : e.getDocumentTop(); var sliderLocation = this.__sliderLocation; var knobLocation = this.__knobLocation; var knobSize = this.__knobSize; // Compute relative position var position = cursorLocation - sliderLocation; if (cursorLocation >= knobLocation) { position -= knobSize; } // Compute stop value var value = this._positionToValue(position); var min = this.getMinimum(); var max = this.getMaximum(); if (value < min) { value = min; } else if (value > max) { value = max; } else { var old = this.getValue(); var step = this.getPageStep(); var method = this.__trackingDirection < 0 ? "floor" : "ceil"; // Fix to page step value = old + (Math[method]((value - old) / step) * step); } // Store value when undefined, otherwise only when it follows the // current direction e.g. goes up or down if (this.__trackingEnd == null || (this.__trackingDirection == -1 && value <= this.__trackingEnd) || (this.__trackingDirection == 1 && value >= this.__trackingEnd)) { this.__trackingEnd = value; } }, /** * Converts the given position to a value. * * Does not respect single or page step. * * @param position {Integer} Position to use * @return {Integer} Resulting value (rounded) */ _positionToValue : function(position) { // Reading available space var avail = this.__slidingSpace; // Protect undefined value (before initial resize) and division by zero if (avail == null || avail == 0) { return 0; } // Compute and limit percent var percent = position / avail; if (percent < 0) { percent = 0; } else if (percent > 1) { percent = 1; } // Compute range var range = this.getMaximum() - this.getMinimum(); // Compute value return this.getMinimum() + Math.round(range * percent); }, /** * Converts the given value to a position to place * the knob to. * * @param value {Integer} Value to use * @return {Integer} Computed position (rounded) */ _valueToPosition : function(value) { // Reading available space var avail = this.__slidingSpace; if (avail == null) { return 0; } // Computing range var range = this.getMaximum() - this.getMinimum(); // Protect division by zero if (range == 0) { return 0; } // Translating value to distance from minimum var value = value - this.getMinimum(); // Compute and limit percent var percent = value / range; if (percent < 0) { percent = 0; } else if (percent > 1) { percent = 1; } // Compute position from available space and percent return Math.round(avail * percent); }, /** * Updates the knob position following the currently configured * value. Useful on reflows where the dimensions of the slider * itself have been modified. * * @return {void} */ _updateKnobPosition : function() { this._setKnobPosition(this._valueToPosition(this.getValue())); }, /** * Moves the knob to the given position. * * @param position {Integer} Any valid position (needs to be * greater or equal than zero) * @return {void} */ _setKnobPosition : function(position) { // Use DOM Element var container = this.getChildControl("knob").getContainerElement(); if (this.__isHorizontal) { container.setStyle("left", position+"px", true); } else { container.setStyle("top", position+"px", true); } // Alternative: Use layout system // Not used because especially in IE7/Firefox2 the // direct element manipulation is a lot faster /* if (this.__isHorizontal) { this.getChildControl("knob").setLayoutProperties({left:position}); } else { this.getChildControl("knob").setLayoutProperties({top:position}); } */ }, /** * Reconfigures the size of the knob depending on * the optionally defined {@link #knobFactor}. * * @return {void} */ _updateKnobSize : function() { // Compute knob size var knobFactor = this.getKnobFactor(); if (knobFactor == null) { return; } // Ignore when not rendered yet var avail = this.getInnerSize(); if (avail == null) { return; } // Read size property if (this.__isHorizontal) { this.getChildControl("knob").setWidth(Math.round(knobFactor * avail.width)); } else { this.getChildControl("knob").setHeight(Math.round(knobFactor * avail.height)); } }, /* --------------------------------------------------------------------------- SLIDE METHODS --------------------------------------------------------------------------- */ /** * Slides backward to the minimum value * * @return {void} */ slideToBegin : function() { this.slideTo(this.getMinimum()); }, /** * Slides forward to the maximum value * * @return {void} */ slideToEnd : function() { this.slideTo(this.getMaximum()); }, /** * Slides forward (right or bottom depending on orientation) * * @return {void} */ slideForward : function() { this.slideBy(this.getSingleStep()); }, /** * Slides backward (to left or top depending on orientation) * * @return {void} */ slideBack : function() { this.slideBy(-this.getSingleStep()); }, /** * Slides a page forward (to right or bottom depending on orientation) * * @return {void} */ slidePageForward : function() { this.slideBy(this.getPageStep()); }, /** * Slides a page backward (to left or top depending on orientation) * * @return {void} */ slidePageBack : function() { this.slideBy(-this.getPageStep()); }, /** * Slides by the given offset. * * This method works with the value, not with the coordinate. * * @param offset {Integer} Offset to scroll by * @return {void} */ slideBy : function(offset) { this.slideTo(this.getValue() + offset); }, /** * Slides to the given value * * This method works with the value, not with the coordinate. * * @param value {Integer} Scroll to a value between the defined * minimum and maximum. * @return {void} */ slideTo : function(value) { // Bring into allowed range or fix to single step grid if (value < this.getMinimum()) { value = this.getMinimum(); } else if (value > this.getMaximum()) { value = this.getMaximum(); } else { value = this.getMinimum() + Math.round((value - this.getMinimum()) / this.getSingleStep()) * this.getSingleStep() } // Sync with property this.setValue(value); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyOrientation : function(value, old) { var knob = this.getChildControl("knob"); // Update private flag for faster access this.__isHorizontal = value === "horizontal"; // Toggle states and knob layout if (this.__isHorizontal) { this.removeState("vertical"); knob.removeState("vertical"); this.addState("horizontal"); knob.addState("horizontal"); knob.setLayoutProperties({top:0, right:null, bottom:0}); } else { this.removeState("horizontal"); knob.removeState("horizontal"); this.addState("vertical"); knob.addState("vertical"); knob.setLayoutProperties({right:0, bottom:null, left:0}); } // Sync knob position this._updateKnobPosition(); }, // property apply _applyKnobFactor : function(value, old) { if (value != null) { this._updateKnobSize(); } else { if (this.__isHorizontal) { this.getChildControl("knob").resetWidth(); } else { this.getChildControl("knob").resetHeight(); } } }, // property apply _applyValue : function(value, old) { if (value != null) { this._updateKnobPosition(); if (this.__dragMode) { this.__dragValue = [value,old]; } else { this.fireEvent("changeValue", qx.event.type.Data, [value,old]); } } else { this.resetValue(); } }, /** * Helper for applyValue which fires the changeValue event. */ _fireValue: function(){ if (!this.__dragValue){ return; } var tmp = this.__dragValue; this.__dragValue = null; this.fireEvent("changeValue", qx.event.type.Data, tmp); }, // property apply _applyMinimum : function(value, old) { if (this.getValue() < value) { this.setValue(value); } this._updateKnobPosition(); }, // property apply _applyMaximum : function(value, old) { if (this.getValue() > value) { this.setValue(value); } this._updateKnobPosition(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Minimal modified version of the {@link qx.ui.form.Slider} to be * used by {@link qx.ui.core.scroll.ScrollBar}. * * @internal */ qx.Class.define("qx.ui.core.scroll.ScrollSlider", { extend : qx.ui.form.Slider, // overridden construct : function(orientation) { this.base(arguments, orientation); // Remove mousewheel/keypress events this.removeListener("keypress", this._onKeyPress); this.removeListener("mousewheel", this._onMouseWheel); }, members : { // overridden getSizeHint : function(compute) { // get the original size hint var hint = this.base(arguments); // set the width or height to 0 depending on the orientation. // this is necessary to prevent the ScrollSlider to change the size // hint of its parent, which can cause errors on outer flex layouts // [BUG #3279] if (this.getOrientation() === "horizontal") { hint.width = 0; } else { hint.height = 0; } return hint; } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A horizontal box layout. * * The horizontal box layout lays out widgets in a horizontal row, from left * to right. * * *Features* * * * Minimum and maximum dimensions * * Prioritized growing/shrinking (flex) * * Margins (with horizontal collapsing) * * Auto sizing (ignoring percent values) * * Percent widths (not relevant for size hint) * * Alignment (child property {@link qx.ui.core.LayoutItem#alignX} is ignored) * * Horizontal spacing (collapsed with margins) * * Reversed children layout (from last to first) * * Vertical children stretching (respecting size hints) * * *Item Properties* * * <ul> * <li><strong>flex</strong> <em>(Integer)</em>: The flexibility of a layout item determines how the container * distributes remaining empty space among its children. If items are made * flexible, they can grow or shrink accordingly. Their relative flex values * determine how the items are being resized, i.e. the larger the flex ratio * of two items, the larger the resizing of the first item compared to the * second. * * If there is only one flex item in a layout container, its actual flex * value is not relevant. To disallow items to become flexible, set the * flex value to zero. * </li> * <li><strong>width</strong> <em>(String)</em>: Allows to define a percent * width for the item. The width in percent, if specified, is used instead * of the width defined by the size hint. The minimum and maximum width still * takes care of the element's limits. It has no influence on the layout's * size hint. Percent values are mostly useful for widgets which are sized by * the outer hierarchy. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.HBox(); * layout.setSpacing(4); // apply spacing * * var container = new qx.ui.container.Composite(layout); * * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * </pre> * * *External Documentation* * * See <a href='http://manual.qooxdoo.org/${qxversion}/pages/layout/box.html'>extended documentation</a> * and links to demos for this layout. * */ qx.Class.define("qx.ui.layout.HBox", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacing {Integer?0} The spacing between child widgets {@link #spacing}. * @param alignX {String?"left"} Horizontal alignment of the whole children * block {@link #alignX}. * @param separator {Decorator} A separator to render between the items */ construct : function(spacing, alignX, separator) { this.base(arguments); if (spacing) { this.setSpacing(spacing); } if (alignX) { this.setAlignX(alignX); } if (separator) { this.setSeparator(separator); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Horizontal alignment of the whole children block. The horizontal * alignment of the child is completely ignored in HBoxes ( * {@link qx.ui.core.LayoutItem#alignX}). */ alignX : { check : [ "left", "center", "right" ], init : "left", apply : "_applyLayoutChange" }, /** * Vertical alignment of each child. Can be overridden through * {@link qx.ui.core.LayoutItem#alignY}. */ alignY : { check : [ "top", "middle", "bottom" ], init : "top", apply : "_applyLayoutChange" }, /** Horizontal spacing between two children */ spacing : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** Separator lines to use between the objects */ separator : { check : "Decorator", nullable : true, apply : "_applyLayoutChange" }, /** Whether the actual children list should be laid out in reversed order. */ reversed : { check : "Boolean", init : false, apply : "_applyReversed" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __widths : null, __flexs : null, __enableFlex : null, __children : null, /* --------------------------------------------------------------------------- HELPER METHODS --------------------------------------------------------------------------- */ // property apply _applyReversed : function() { // easiest way is to invalidate the cache this._invalidChildrenCache = true; // call normal layout change this._applyLayoutChange(); }, /** * Rebuilds caches for flex and percent layout properties */ __rebuildCache : function() { var children = this._getLayoutChildren(); var length = children.length; var enableFlex = false; var reuse = this.__widths && this.__widths.length != length && this.__flexs && this.__widths; var props; // Sparse array (keep old one if lengths has not been modified) var widths = reuse ? this.__widths : new Array(length); var flexs = reuse ? this.__flexs : new Array(length); // Reverse support if (this.getReversed()) { children = children.concat().reverse(); } // Loop through children to preparse values for (var i=0; i<length; i++) { props = children[i].getLayoutProperties(); if (props.width != null) { widths[i] = parseFloat(props.width) / 100; } if (props.flex != null) { flexs[i] = props.flex; enableFlex = true; } else { // reset (in case the index of the children changed: BUG #3131) flexs[i] = 0; } } // Store data if (!reuse) { this.__widths = widths; this.__flexs = flexs; } this.__enableFlex = enableFlex this.__children = children; // Clear invalidation marker delete this._invalidChildrenCache; }, /* --------------------------------------------------------------------------- LAYOUT INTERFACE --------------------------------------------------------------------------- */ // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { this.assert(name === "flex" || name === "width", "The property '"+name+"' is not supported by the HBox layout!"); if (name =="width") { this.assertMatch(value, qx.ui.layout.Util.PERCENT_VALUE); } else { // flex this.assertNumber(value); this.assert(value >= 0); } }, "false" : null }), // overridden renderLayout : function(availWidth, availHeight) { // Rebuild flex/width caches if (this._invalidChildrenCache) { this.__rebuildCache(); } // Cache children var children = this.__children; var length = children.length; var util = qx.ui.layout.Util; // Compute gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeHorizontalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeHorizontalGaps(children, spacing, true); } // First run to cache children data and compute allocated width var i, child, width, percent; var widths = []; var allocatedWidth = gaps; for (i=0; i<length; i+=1) { percent = this.__widths[i]; width = percent != null ? Math.floor((availWidth - gaps) * percent) : children[i].getSizeHint().width; widths.push(width); allocatedWidth += width; } // Flex support (growing/shrinking) if (this.__enableFlex && allocatedWidth != availWidth) { var flexibles = {}; var flex, offset; for (i=0; i<length; i+=1) { flex = this.__flexs[i]; if (flex > 0) { hint = children[i].getSizeHint(); flexibles[i]= { min : hint.minWidth, value : widths[i], max : hint.maxWidth, flex : flex }; } } var result = util.computeFlexOffsets(flexibles, availWidth, allocatedWidth); for (i in result) { offset = result[i].offset; widths[i] += offset; allocatedWidth += offset; } } // Start with left coordinate var left = children[0].getMarginLeft(); // Alignment support if (allocatedWidth < availWidth && this.getAlignX() != "left") { left = availWidth - allocatedWidth; if (this.getAlignX() === "center") { left = Math.round(left / 2); } } // Layouting children var hint, top, height, width, marginRight, marginTop, marginBottom; var spacing = this.getSpacing(); // Pre configure separators this._clearSeparators(); // Compute separator width if (separator) { var separatorInsets = qx.theme.manager.Decoration.getInstance().resolve(separator).getInsets(); var separatorWidth = separatorInsets.left + separatorInsets.right; } // Render children and separators for (i=0; i<length; i+=1) { child = children[i]; width = widths[i]; hint = child.getSizeHint(); marginTop = child.getMarginTop(); marginBottom = child.getMarginBottom(); // Find usable height height = Math.max(hint.minHeight, Math.min(availHeight-marginTop-marginBottom, hint.maxHeight)); // Respect vertical alignment top = util.computeVerticalAlignOffset(child.getAlignY()||this.getAlignY(), height, availHeight, marginTop, marginBottom); // Add collapsed margin if (i > 0) { // Whether a separator has been configured if (separator) { // add margin of last child and spacing left += marginRight + spacing; // then render the separator at this position this._renderSeparator(separator, { left : left, top : 0, width : separatorWidth, height : availHeight }); // and finally add the size of the separator, the spacing (again) and the left margin left += separatorWidth + spacing + child.getMarginLeft(); } else { // Support margin collapsing when no separator is defined left += util.collapseMargins(spacing, marginRight, child.getMarginLeft()); } } // Layout child child.renderLayout(left, top, width, height); // Add width left += width; // Remember right margin (for collapsing) marginRight = child.getMarginRight(); } }, // overridden _computeSizeHint : function() { // Rebuild flex/width caches if (this._invalidChildrenCache) { this.__rebuildCache(); } var util = qx.ui.layout.Util; var children = this.__children; // Initialize var minWidth=0, width=0, percentMinWidth=0; var minHeight=0, height=0; var child, hint, margin; // Iterate over children for (var i=0, l=children.length; i<l; i+=1) { child = children[i]; hint = child.getSizeHint(); // Sum up widths width += hint.width; // Detect if child is shrinkable or has percent width and update minWidth var flex = this.__flexs[i]; var percent = this.__widths[i]; if (flex) { minWidth += hint.minWidth; } else if (percent) { percentMinWidth = Math.max(percentMinWidth, Math.round(hint.minWidth/percent)); } else { minWidth += hint.width; } // Build vertical margin sum margin = child.getMarginTop() + child.getMarginBottom(); // Find biggest height if ((hint.height+margin) > height) { height = hint.height + margin; } // Find biggest minHeight if ((hint.minHeight+margin) > minHeight) { minHeight = hint.minHeight + margin; } } minWidth += percentMinWidth; // Respect gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeHorizontalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeHorizontalGaps(children, spacing, true); } // Return hint return { minWidth : minWidth + gaps, width : width + gaps, minHeight : minHeight, height : height }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__widths = this.__flexs = this.__children = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The ScrollArea provides a container widget with on demand scroll bars * if the content size exceeds the size of the container. * * @childControl pane {qx.ui.core.scroll.ScrollPane} pane which holds the content to scroll * @childControl scrollbar-x {qx.ui.core.scroll.ScrollBar?qx.ui.core.scroll.NativeScrollBar} horizontal scrollbar * @childControl scrollbar-y {qx.ui.core.scroll.ScrollBar?qx.ui.core.scroll.NativeScrollBar} vertical scrollbar * @childControl corner {qx.ui.core.Widget} corner where no scrollbar is shown */ qx.Class.define("qx.ui.core.scroll.AbstractScrollArea", { extend : qx.ui.core.Widget, include : [ qx.ui.core.scroll.MScrollBarFactory, qx.ui.core.scroll.MWheelHandling ], type : "abstract", /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); if (qx.core.Environment.get("os.scrollBarOverlayed")) { // use a plain canvas to overlay the scroll bars this._setLayout(new qx.ui.layout.Canvas()); } else { // Create 'fixed' grid layout var grid = new qx.ui.layout.Grid(); grid.setColumnFlex(0, 1); grid.setRowFlex(0, 1); this._setLayout(grid); } // Mousewheel listener to scroll vertically this.addListener("mousewheel", this._onMouseWheel, this); // touch support if (qx.core.Environment.get("event.touch")) { // touch move listener for touch scrolling this.addListener("touchmove", this._onTouchMove, this); // reset the delta on every touch session this.addListener("touchstart", function() { this.__old = {"x": 0, "y": 0}; }, this); this.__old = {}; this.__impulseTimerId = {}; } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "scrollarea" }, // overridden width : { refine : true, init : 100 }, // overridden height : { refine : true, init : 200 }, /** * The policy, when the horizontal scrollbar should be shown. * <ul> * <li><b>auto</b>: Show scrollbar on demand</li> * <li><b>on</b>: Always show the scrollbar</li> * <li><b>off</b>: Never show the scrollbar</li> * </ul> */ scrollbarX : { check : ["auto", "on", "off"], init : "auto", themeable : true, apply : "_computeScrollbars" }, /** * The policy, when the horizontal scrollbar should be shown. * <ul> * <li><b>auto</b>: Show scrollbar on demand</li> * <li><b>on</b>: Always show the scrollbar</li> * <li><b>off</b>: Never show the scrollbar</li> * </ul> */ scrollbarY : { check : ["auto", "on", "off"], init : "auto", themeable : true, apply : "_computeScrollbars" }, /** * Group property, to set the overflow of both scroll bars. */ scrollbar : { group : [ "scrollbarX", "scrollbarY" ] } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __old : null, __impulseTimerId : null, /* --------------------------------------------------------------------------- CHILD CONTROL SUPPORT --------------------------------------------------------------------------- */ // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "pane": control = new qx.ui.core.scroll.ScrollPane(); control.addListener("update", this._computeScrollbars, this); control.addListener("scrollX", this._onScrollPaneX, this); control.addListener("scrollY", this._onScrollPaneY, this); if (qx.core.Environment.get("os.scrollBarOverlayed")) { this._add(control, {edge: 0}); } else { this._add(control, {row: 0, column: 0}); } break; case "scrollbar-x": control = this._createScrollBar("horizontal"); control.setMinWidth(0); control.exclude(); control.addListener("scroll", this._onScrollBarX, this); control.addListener("changeVisibility", this._onChangeScrollbarXVisibility, this); if (qx.core.Environment.get("os.scrollBarOverlayed")) { control.setMinHeight(qx.bom.element.Overflow.DEFAULT_SCROLLBAR_WIDTH); this._add(control, {bottom: 0, right: 0, left: 0}); } else { this._add(control, {row: 1, column: 0}); } break; case "scrollbar-y": control = this._createScrollBar("vertical"); control.setMinHeight(0); control.exclude(); control.addListener("scroll", this._onScrollBarY, this); control.addListener("changeVisibility", this._onChangeScrollbarYVisibility, this); if (qx.core.Environment.get("os.scrollBarOverlayed")) { control.setMinWidth(qx.bom.element.Overflow.DEFAULT_SCROLLBAR_WIDTH); this._add(control, {right: 0, bottom: 0, top: 0}); } else { this._add(control, {row: 0, column: 1}); } break; case "corner": control = new qx.ui.core.Widget(); control.setWidth(0); control.setHeight(0); control.exclude(); if (!qx.core.Environment.get("os.scrollBarOverlayed")) { // only add for non overlayed scroll bars this._add(control, {row: 1, column: 1}); } break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- PANE SIZE --------------------------------------------------------------------------- */ /** * Returns the boundaries of the pane. * * @return {Map} The pane boundaries. */ getPaneSize : function() { return this.getChildControl("pane").getInnerSize(); }, /* --------------------------------------------------------------------------- ITEM LOCATION SUPPORT --------------------------------------------------------------------------- */ /** * Returns the top offset of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemTop : function(item) { return this.getChildControl("pane").getItemTop(item); }, /** * Returns the top offset of the end of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemBottom : function(item) { return this.getChildControl("pane").getItemBottom(item); }, /** * Returns the left offset of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemLeft : function(item) { return this.getChildControl("pane").getItemLeft(item); }, /** * Returns the left offset of the end of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Right offset */ getItemRight : function(item) { return this.getChildControl("pane").getItemRight(item); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ /** * Scrolls the element's content to the given left coordinate * * @param value {Integer} The vertical position to scroll to. */ scrollToX : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-x").scrollTo(value); }, /** * Scrolls the element's content by the given left offset * * @param value {Integer} The vertical position to scroll to. */ scrollByX : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-x").scrollBy(value); }, /** * Returns the scroll left position of the content * * @return {Integer} Horizontal scroll position */ getScrollX : function() { var scrollbar = this.getChildControl("scrollbar-x", true); return scrollbar ? scrollbar.getPosition() : 0; }, /** * Scrolls the element's content to the given top coordinate * * @param value {Integer} The horizontal position to scroll to. */ scrollToY : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-y").scrollTo(value); }, /** * Scrolls the element's content by the given top offset * * @param value {Integer} The horizontal position to scroll to. * @return {void} */ scrollByY : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-y").scrollBy(value); }, /** * Returns the scroll top position of the content * * @return {Integer} Vertical scroll position */ getScrollY : function() { var scrollbar = this.getChildControl("scrollbar-y", true); return scrollbar ? scrollbar.getPosition() : 0; }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Event handler for the scroll event of the horizontal scrollbar * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollBarX : function(e) { this.getChildControl("pane").scrollToX(e.getData()); }, /** * Event handler for the scroll event of the vertical scrollbar * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollBarY : function(e) { this.getChildControl("pane").scrollToY(e.getData()); }, /** * Event handler for the horizontal scroll event of the pane * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollPaneX : function(e) { this.scrollToX(e.getData()); }, /** * Event handler for the vertical scroll event of the pane * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollPaneY : function(e) { this.scrollToY(e.getData()); }, /** * Event handler for the touch move. * * @param e {qx.event.type.Touch} The touch event */ _onTouchMove : function(e) { this._onTouchMoveDirectional("x", e); this._onTouchMoveDirectional("y", e); // Stop bubbling and native event e.stop(); }, /** * Touch move handler for one direction. * * @param dir {String} Either 'x' or 'y' * @param e {qx.event.type.Touch} The touch event */ _onTouchMoveDirectional : function(dir, e) { var docDir = (dir == "x" ? "Left" : "Top"); // current scrollbar var scrollbar = this.getChildControl("scrollbar-" + dir, true); var show = this._isChildControlVisible("scrollbar-" + dir); if (show && scrollbar) { // get the delta for the current direction if(this.__old[dir] == 0) { var delta = 0; } else { var delta = -(e["getDocument" + docDir]() - this.__old[dir]); }; // save the old value for the current direction this.__old[dir] = e["getDocument" + docDir](); scrollbar.scrollBy(delta); // if we have an old timeout for the current direction, clear it if (this.__impulseTimerId[dir]) { clearTimeout(this.__impulseTimerId[dir]); this.__impulseTimerId[dir] = null; } // set up a new timer for the current direction this.__impulseTimerId[dir] = setTimeout(qx.lang.Function.bind(function(delta) { this.__handleScrollImpulse(delta, dir); }, this, delta), 100); } }, /** * Helper for momentum scrolling. * @param delta {Number} The delta from the last scrolling. * @param dir {String} Direction of the scrollbar ('x' or 'y'). */ __handleScrollImpulse : function(delta, dir) { // delete the old timer id this.__impulseTimerId[dir] = null; // do nothing if the scrollbar is not visible or we don't need to scroll var show = this._isChildControlVisible("scrollbar-" + dir); if (delta == 0 || !show) { return; } // linear momentum calculation if (delta > 0) { delta = Math.max(0, delta - 3); } else { delta = Math.min(0, delta + 3); } // set up a new timer with the new delta this.__impulseTimerId[dir] = setTimeout(qx.lang.Function.bind(function(delta, dir) { this.__handleScrollImpulse(delta, dir); }, this, delta, dir), 20); // scroll the desired new delta var scrollbar = this.getChildControl("scrollbar-" + dir, true); scrollbar.scrollBy(delta); }, /** * Event handler for visibility changes of horizontal scrollbar. * * @param e {qx.event.type.Event} Property change event * @return {void} */ _onChangeScrollbarXVisibility : function(e) { var showX = this._isChildControlVisible("scrollbar-x"); var showY = this._isChildControlVisible("scrollbar-y"); if (!showX) { this.scrollToX(0); } showX && showY ? this._showChildControl("corner") : this._excludeChildControl("corner"); }, /** * Event handler for visibility changes of horizontal scrollbar. * * @param e {qx.event.type.Event} Property change event * @return {void} */ _onChangeScrollbarYVisibility : function(e) { var showX = this._isChildControlVisible("scrollbar-x"); var showY = this._isChildControlVisible("scrollbar-y"); if (!showY) { this.scrollToY(0); } showX && showY ? this._showChildControl("corner") : this._excludeChildControl("corner"); }, /* --------------------------------------------------------------------------- HELPER METHODS --------------------------------------------------------------------------- */ /** * Computes the visibility state for scrollbars. * * @return {void} */ _computeScrollbars : function() { var pane = this.getChildControl("pane"); var content = pane.getChildren()[0]; if (!content) { this._excludeChildControl("scrollbar-x"); this._excludeChildControl("scrollbar-y"); return; } var innerSize = this.getInnerSize(); var paneSize = pane.getInnerSize(); var scrollSize = pane.getScrollSize(); // if the widget has not yet been rendered, return and try again in the // resize event if (!paneSize || !scrollSize) { return; } var scrollbarX = this.getScrollbarX(); var scrollbarY = this.getScrollbarY(); if (scrollbarX === "auto" && scrollbarY === "auto") { // Check if the container is big enough to show // the full content. var showX = scrollSize.width > innerSize.width; var showY = scrollSize.height > innerSize.height; // Dependency check // We need a special intelligence here when only one // of the autosized axis requires a scrollbar // This scrollbar may then influence the need // for the other one as well. if ((showX || showY) && !(showX && showY)) { if (showX) { showY = scrollSize.height > paneSize.height; } else if (showY) { showX = scrollSize.width > paneSize.width; } } } else { var showX = scrollbarX === "on"; var showY = scrollbarY === "on"; // Check auto values afterwards with already // corrected client dimensions if (scrollSize.width > (showX ? paneSize.width : innerSize.width) && scrollbarX === "auto") { showX = true; } if (scrollSize.height > (showX ? paneSize.height : innerSize.height) && scrollbarY === "auto") { showY = true; } } // Update scrollbars if (showX) { var barX = this.getChildControl("scrollbar-x"); barX.show(); barX.setMaximum(Math.max(0, scrollSize.width - paneSize.width)); barX.setKnobFactor((scrollSize.width === 0) ? 0 : paneSize.width / scrollSize.width); } else { this._excludeChildControl("scrollbar-x"); } if (showY) { var barY = this.getChildControl("scrollbar-y"); barY.show(); barY.setMaximum(Math.max(0, scrollSize.height - paneSize.height)); barY.setKnobFactor((scrollSize.height === 0) ? 0 : paneSize.height / scrollSize.height); } else { this._excludeChildControl("scrollbar-y"); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for checking the scrolling behavior of the client. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Scroll", { statics : { /** * Check if the scrollbars should be positioned on top of the content. This * is true of OSX Lion when the scrollbars dissapear automatically. * * @internal * * @return {Boolean} <code>true</code> if the scrollbars should be * positioned on top of the content. */ scrollBarOverlayed : function() { var scrollBarWidth = qx.bom.element.Overflow.getScrollbarWidth(); var osx = qx.bom.client.OperatingSystem.getName() === "osx"; var nativeScrollBars = qx.core.Environment.get("qx.nativeScrollBars"); return scrollBarWidth == 0 && osx && nativeScrollBars; } }, defer : function(statics) { qx.core.Environment.add("os.scrollBarOverlayed", statics.scrollBarOverlayed); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This class represents a scroll able pane. This means that this widget * may contain content which is bigger than the available (inner) * dimensions of this widget. The widget also offer methods to control * the scrolling position. It can only have exactly one child. */ qx.Class.define("qx.ui.core.scroll.ScrollPane", { extend : qx.ui.core.Widget, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); this.set({ minWidth: 0, minHeight: 0 }); // Automatically configure a "fixed" grow layout. this._setLayout(new qx.ui.layout.Grow()); // Add resize listener to "translate" event this.addListener("resize", this._onUpdate); var contentEl = this.getContentElement(); // Synchronizes the DOM scroll position with the properties contentEl.addListener("scroll", this._onScroll, this); // Fixed some browser quirks e.g. correcting scroll position // to the previous value on re-display of a pane contentEl.addListener("appear", this._onAppear, this); }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired on resize of both the container or the content. */ update : "qx.event.type.Event" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** The horizontal scroll position */ scrollX : { check : "qx.lang.Type.isNumber(value)&&value>=0&&value<=this.getScrollMaxX()", apply : "_applyScrollX", event : "scrollX", init : 0 }, /** The vertical scroll position */ scrollY : { check : "qx.lang.Type.isNumber(value)&&value>=0&&value<=this.getScrollMaxY()", apply : "_applyScrollY", event : "scrollY", init : 0 } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- CONTENT MANAGEMENT --------------------------------------------------------------------------- */ /** * Configures the content of the scroll pane. Replaces any existing child * with the newly given one. * * @param widget {qx.ui.core.Widget?null} The content widget of the pane * @return {void} */ add : function(widget) { var old = this._getChildren()[0]; if (old) { this._remove(old); old.removeListener("resize", this._onUpdate, this); } if (widget) { this._add(widget); widget.addListener("resize", this._onUpdate, this); } }, /** * Removes the given widget from the content. The pane is empty * afterwards as only one child is supported by the pane. * * @param widget {qx.ui.core.Widget?null} The content widget of the pane * @return {void} */ remove : function(widget) { if (widget) { this._remove(widget); widget.removeListener("resize", this._onUpdate, this); } }, /** * Returns an array containing the current content. * * @return {Object[]} The content array */ getChildren : function() { return this._getChildren(); }, /* --------------------------------------------------------------------------- EVENT LISTENER --------------------------------------------------------------------------- */ /** * Event listener for resize event of content and container * * @param e {Event} Resize event object */ _onUpdate : function(e) { this.fireEvent("update"); }, /** * Event listener for scroll event of content * * @param e {qx.event.type.Event} Scroll event object */ _onScroll : function(e) { var contentEl = this.getContentElement(); this.setScrollX(contentEl.getScrollX()); this.setScrollY(contentEl.getScrollY()); }, /** * Event listener for appear event of content * * @param e {qx.event.type.Event} Appear event object */ _onAppear : function(e) { var contentEl = this.getContentElement(); var internalX = this.getScrollX(); var domX = contentEl.getScrollX(); if (internalX != domX) { contentEl.scrollToX(internalX); } var internalY = this.getScrollY(); var domY = contentEl.getScrollY(); if (internalY != domY) { contentEl.scrollToY(internalY); } }, /* --------------------------------------------------------------------------- ITEM LOCATION SUPPORT --------------------------------------------------------------------------- */ /** * Returns the top offset of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemTop : function(item) { var top = 0; do { top += item.getBounds().top; item = item.getLayoutParent(); } while (item && item !== this); return top; }, /** * Returns the top offset of the end of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemBottom : function(item) { return this.getItemTop(item) + item.getBounds().height; }, /** * Returns the left offset of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemLeft : function(item) { var left = 0; var parent; do { left += item.getBounds().left; parent = item.getLayoutParent(); if (parent) { left += parent.getInsets().left; } item = parent; } while (item && item !== this); return left; }, /** * Returns the left offset of the end of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Right offset */ getItemRight : function(item) { return this.getItemLeft(item) + item.getBounds().width; }, /* --------------------------------------------------------------------------- DIMENSIONS --------------------------------------------------------------------------- */ /** * The size (identical with the preferred size) of the content. * * @return {Map} Size of the content (keys: <code>width</code> and <code>height</code>) */ getScrollSize : function() { return this.getChildren()[0].getBounds(); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ /** * The maximum horizontal scroll position. * * @return {Integer} Maximum horizontal scroll position. */ getScrollMaxX : function() { var paneSize = this.getInnerSize(); var scrollSize = this.getScrollSize(); if (paneSize && scrollSize) { return Math.max(0, scrollSize.width - paneSize.width); } return 0; }, /** * The maximum vertical scroll position. * * @return {Integer} Maximum vertical scroll position. */ getScrollMaxY : function() { var paneSize = this.getInnerSize(); var scrollSize = this.getScrollSize(); if (paneSize && scrollSize) { return Math.max(0, scrollSize.height - paneSize.height); } return 0; }, /** * Scrolls the element's content to the given left coordinate * * @param value {Integer} The vertical position to scroll to. * @return {void} */ scrollToX : function(value) { var max = this.getScrollMaxX(); if (value < 0) { value = 0; } else if (value > max) { value = max; } this.setScrollX(value); }, /** * Scrolls the element's content to the given top coordinate * * @param value {Integer} The horizontal position to scroll to. * @return {void} */ scrollToY : function(value) { var max = this.getScrollMaxY(); if (value < 0) { value = 0; } else if (value > max) { value = max; } this.setScrollY(value); }, /** * Scrolls the element's content horizontally by the given amount. * * @param x {Integer?0} Amount to scroll * @return {void} */ scrollByX : function(x) { this.scrollToX(this.getScrollX() + x); }, /** * Scrolls the element's content vertically by the given amount. * * @param y {Integer?0} Amount to scroll * @return {void} */ scrollByY : function(y) { this.scrollToY(this.getScrollY() + y); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyScrollX : function(value) { this.getContentElement().scrollToX(value); }, // property apply _applyScrollY : function(value) { this.getContentElement().scrollToY(value); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * A list of items. Displays an automatically scrolling list for all * added {@link qx.ui.form.ListItem} instances. Supports various * selection options: single, multi, ... */ qx.Class.define("qx.ui.form.List", { extend : qx.ui.core.scroll.AbstractScrollArea, implement : [ qx.ui.core.IMultiSelection, qx.ui.form.IForm, qx.ui.form.IModelSelection ], include : [ qx.ui.core.MRemoteChildrenHandling, qx.ui.core.MMultiSelectionHandling, qx.ui.form.MForm, qx.ui.form.MModelSelection ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param horizontal {Boolean?false} Whether the list should be horizontal. */ construct : function(horizontal) { this.base(arguments); // Create content this.__content = this._createListItemContainer(); // Used to fire item add/remove events this.__content.addListener("addChildWidget", this._onAddChild, this); this.__content.addListener("removeChildWidget", this._onRemoveChild, this); // Add to scrollpane this.getChildControl("pane").add(this.__content); // Apply orientation if (horizontal) { this.setOrientation("horizontal"); } else { this.initOrientation(); } // Add keypress listener this.addListener("keypress", this._onKeyPress); this.addListener("keyinput", this._onKeyInput); // initialize the search string this.__pressedString = ""; }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * This event is fired after a list item was added to the list. The * {@link qx.event.type.Data#getData} method of the event returns the * added item. */ addItem : "qx.event.type.Data", /** * This event is fired after a list item has been removed from the list. * The {@link qx.event.type.Data#getData} method of the event returns the * removed item. */ removeItem : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "list" }, // overridden focusable : { refine : true, init : true }, /** * Whether the list should be rendered horizontal or vertical. */ orientation : { check : ["horizontal", "vertical"], init : "vertical", apply : "_applyOrientation" }, /** Spacing between the items */ spacing : { check : "Integer", init : 0, apply : "_applySpacing", themeable : true }, /** Controls whether the inline-find feature is activated or not */ enableInlineFind : { check : "Boolean", init : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __pressedString : null, __lastKeyPress : null, /** {qx.ui.core.Widget} The children container */ __content : null, /** {Class} Pointer to the selection manager to use */ SELECTION_MANAGER : qx.ui.core.selection.ScrollArea, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden getChildrenContainer : function() { return this.__content; }, /** * Handle child widget adds on the content pane * * @param e {qx.event.type.Data} the event instance */ _onAddChild : function(e) { this.fireDataEvent("addItem", e.getData()); }, /** * Handle child widget removes on the content pane * * @param e {qx.event.type.Data} the event instance */ _onRemoveChild : function(e) { this.fireDataEvent("removeItem", e.getData()); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Used to route external <code>keypress</code> events to the list * handling (in fact the manager of the list) * * @param e {qx.event.type.KeySequence} KeyPress event */ handleKeyPress : function(e) { if (!this._onKeyPress(e)) { this._getManager().handleKeyPress(e); } }, /* --------------------------------------------------------------------------- PROTECTED API --------------------------------------------------------------------------- */ /** * This container holds the list item widgets. * * @return {qx.ui.container.Composite} Container for the list item widgets */ _createListItemContainer : function() { return new qx.ui.container.Composite; }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyOrientation : function(value, old) { // Create new layout var horizontal = value === "horizontal"; var layout = horizontal ? new qx.ui.layout.HBox() : new qx.ui.layout.VBox(); // Configure content var content = this.__content; content.setLayout(layout); content.setAllowGrowX(!horizontal); content.setAllowGrowY(horizontal); // Configure spacing this._applySpacing(this.getSpacing()); }, // property apply _applySpacing : function(value, old) { this.__content.getLayout().setSpacing(value); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event listener for <code>keypress</code> events. * * @param e {qx.event.type.KeySequence} KeyPress event * @return {Boolean} Whether the event was processed */ _onKeyPress : function(e) { // Execute action on press <ENTER> if (e.getKeyIdentifier() == "Enter" && !e.isAltPressed()) { var items = this.getSelection(); for (var i=0; i<items.length; i++) { items[i].fireEvent("action"); } return true; } return false; }, /* --------------------------------------------------------------------------- FIND SUPPORT --------------------------------------------------------------------------- */ /** * Handles the inline find - if enabled * * @param e {qx.event.type.KeyInput} key input event */ _onKeyInput : function(e) { // do nothing if the find is disabled if (!this.getEnableInlineFind()) { return; } // Only useful in single or one selection mode var mode = this.getSelectionMode(); if (!(mode === "single" || mode === "one")) { return; } // Reset string after a second of non pressed key if (((new Date).valueOf() - this.__lastKeyPress) > 1000) { this.__pressedString = ""; } // Combine keys the user pressed to a string this.__pressedString += e.getChar(); // Find matching item var matchedItem = this.findItemByLabelFuzzy(this.__pressedString); // if an item was found, select it if (matchedItem) { this.setSelection([matchedItem]); } // Store timestamp this.__lastKeyPress = (new Date).valueOf(); }, /** * Takes the given string and tries to find a ListItem * which starts with this string. The search is not case sensitive and the * first found ListItem will be returned. If there could not be found any * qualifying list item, null will be returned. * * @param search {String} The text with which the label of the ListItem should start with * @return {qx.ui.form.ListItem} The found ListItem or null */ findItemByLabelFuzzy : function(search) { // lower case search text search = search.toLowerCase(); // get all items of the list var items = this.getChildren(); // go threw all items for (var i=0, l=items.length; i<l; i++) { // get the label of the current item var currentLabel = items[i].getLabel(); // if the label fits with the search text (ignore case, begins with) if (currentLabel && currentLabel.toLowerCase().indexOf(search) == 0) { // just return the first found element return items[i]; } } // if no element was found, return null return null; }, /** * Find an item by its {@link qx.ui.basic.Atom#getLabel}. * * @param search {String} A label or any item * @param ignoreCase {Boolean?true} description * @return {qx.ui.form.ListItem} The found ListItem or null */ findItem : function(search, ignoreCase) { // lowercase search if (ignoreCase !== false) { search = search.toLowerCase(); }; // get all items of the list var items = this.getChildren(); var item; // go through all items for (var i=0, l=items.length; i<l; i++) { item = items[i]; // get the content of the label; text content when rich var label; if (item.isRich()) { var control = item.getChildControl("label", true); if (control) { var labelNode = control.getContentElement().getDomElement(); if (labelNode) { label = qx.bom.element.Attribute.get(labelNode, "text"); } } } else { label = item.getLabel(); } if (label != null) { if (label.translate) { label = label.translate(); } if (ignoreCase !== false) { label = label.toLowerCase(); } if (label.toString() == search.toString()) { return item; } } } return null; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__content"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Werner (wpbasti) * Jonathan Weiß (jonathan_rass) ************************************************************************ */ /** * Basic class for a selectbox like lists. Basically supports a popup * with a list and the whole children management. * * @childControl list {qx.ui.form.List} list component of the selectbox * @childControl popup {qx.ui.popup.Popup} popup which shows the list * */ qx.Class.define("qx.ui.form.AbstractSelectBox", { extend : qx.ui.core.Widget, include : [ qx.ui.core.MRemoteChildrenHandling, qx.ui.form.MForm ], implement : [ qx.ui.form.IForm ], type : "abstract", /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); // set the layout var layout = new qx.ui.layout.HBox(); this._setLayout(layout); layout.setAlignY("middle"); // Register listeners this.addListener("keypress", this._onKeyPress); this.addListener("blur", this._onBlur, this); // register mouse wheel listener var root = qx.core.Init.getApplication().getRoot(); root.addListener("mousewheel", this._onMousewheel, this, true); // register the resize listener this.addListener("resize", this._onResize, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden focusable : { refine : true, init : true }, // overridden width : { refine : true, init : 120 }, /** * The maximum height of the list popup. Setting this value to * <code>null</code> will set cause the list to be auto-sized. */ maxListHeight : { check : "Number", apply : "_applyMaxListHeight", nullable: true, init : 200 }, /** * Formatter which format the value from the selected <code>ListItem</code>. * Uses the default formatter {@link #_defaultFormat}. */ format : { check : "Function", init : function(item) { return this._defaultFormat(item); }, nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "list": control = new qx.ui.form.List().set({ focusable: false, keepFocus: true, height: null, width: null, maxHeight: this.getMaxListHeight(), selectionMode: "one", quickSelection: true }); control.addListener("changeSelection", this._onListChangeSelection, this); control.addListener("mousedown", this._onListMouseDown, this); break; case "popup": control = new qx.ui.popup.Popup(new qx.ui.layout.VBox); control.setAutoHide(false); control.setKeepActive(true); control.addListener("mouseup", this.close, this); control.add(this.getChildControl("list")); control.addListener("changeVisibility", this._onPopupChangeVisibility, this); break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMaxListHeight : function(value, old) { this.getChildControl("list").setMaxHeight(value); }, /* --------------------------------------------------------------------------- PUBLIC METHODS --------------------------------------------------------------------------- */ /** * Returns the list widget. * @return {qx.ui.form.List} the list */ getChildrenContainer : function() { return this.getChildControl("list"); }, /* --------------------------------------------------------------------------- LIST STUFF --------------------------------------------------------------------------- */ /** * Shows the list popup. */ open : function() { var popup = this.getChildControl("popup"); popup.placeToWidget(this, true); popup.show(); }, /** * Hides the list popup. */ close : function() { this.getChildControl("popup").hide(); }, /** * Toggles the popup's visibility. */ toggle : function() { var isListOpen = this.getChildControl("popup").isVisible(); if (isListOpen) { this.close(); } else { this.open(); } }, /* --------------------------------------------------------------------------- FORMAT HANDLING --------------------------------------------------------------------------- */ /** * Return the formatted label text from the <code>ListItem</code>. * The formatter removes all HTML tags and converts all HTML entities * to string characters when the rich property is <code>true</code>. * * @param item {ListItem} The list item to format. * @return {String} The formatted text. */ _defaultFormat : function(item) { var valueLabel = item ? item.getLabel() : ""; var rich = item ? item.getRich() : false; if (rich) { valueLabel = valueLabel.replace(/<[^>]+?>/g, ""); valueLabel = qx.bom.String.unescape(valueLabel); } return valueLabel; }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Handler for the blur event of the current widget. * * @param e {qx.event.type.Focus} The blur event. */ _onBlur : function(e) { this.close(); }, /** * Reacts on special keys and forwards other key events to the list widget. * * @param e {qx.event.type.KeySequence} Keypress event */ _onKeyPress : function(e) { // get the key identifier var identifier = e.getKeyIdentifier(); var listPopup = this.getChildControl("popup"); // disabled pageUp and pageDown keys if (listPopup.isHidden() && (identifier == "PageDown" || identifier == "PageUp")) { e.stopPropagation(); } // hide the list always on escape else if (!listPopup.isHidden() && identifier == "Escape") { this.close(); e.stop(); } // forward the rest of the events to the list else { this.getChildControl("list").handleKeyPress(e); } }, /** * Close the pop-up if the mousewheel event isn't on the pup-up window. * * @param e {qx.event.type.Mouse} Mousewheel event. */ _onMousewheel : function(e) { var target = e.getTarget(); var popup = this.getChildControl("popup", true); if (popup == null) { return; } if (qx.ui.core.Widget.contains(popup, target)) { // needed for ComboBox widget inside an inline application e.preventDefault(); } else { this.close(); } }, /** * Updates list minimum size. * * @param e {qx.event.type.Data} Data event */ _onResize : function(e){ this.getChildControl("popup").setMinWidth(e.getData().width); }, /** * Syncs the own property from the list change * * @param e {qx.event.type.Data} Data Event */ _onListChangeSelection : function(e) { throw new Error("Abstract method: _onListChangeSelection()"); }, /** * Redirects mousedown event from the list to this widget. * * @param e {qx.event.type.Mouse} Mouse Event */ _onListMouseDown : function(e) { throw new Error("Abstract method: _onListMouseDown()"); }, /** * Redirects changeVisibility event from the list to this widget. * * @param e {qx.event.type.Data} Property change event */ _onPopupChangeVisibility : function(e) { e.getData() == "visible" ? this.addState("popupOpen") : this.removeState("popupOpen"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { var root = qx.core.Init.getApplication().getRoot(); if (root) { root.removeListener("mousewheel", this._onMousewheel, this, true); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Collection of utility functions to escape and unescape strings. */ qx.Class.define("qx.bom.String", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Mapping of HTML entity names to the corresponding char code */ TO_CHARCODE : { "quot" : 34, // " - double-quote "amp" : 38, // & "lt" : 60, // < "gt" : 62, // > // http://www.w3.org/TR/REC-html40/sgml/entities.html // ISO 8859-1 characters "nbsp" : 160, // no-break space "iexcl" : 161, // inverted exclamation mark "cent" : 162, // cent sign "pound" : 163, // pound sterling sign "curren" : 164, // general currency sign "yen" : 165, // yen sign "brvbar" : 166, // broken (vertical) bar "sect" : 167, // section sign "uml" : 168, // umlaut (dieresis) "copy" : 169, // copyright sign "ordf" : 170, // ordinal indicator, feminine "laquo" : 171, // angle quotation mark, left "not" : 172, // not sign "shy" : 173, // soft hyphen "reg" : 174, // registered sign "macr" : 175, // macron "deg" : 176, // degree sign "plusmn" : 177, // plus-or-minus sign "sup2" : 178, // superscript two "sup3" : 179, // superscript three "acute" : 180, // acute accent "micro" : 181, // micro sign "para" : 182, // pilcrow (paragraph sign) "middot" : 183, // middle dot "cedil" : 184, // cedilla "sup1" : 185, // superscript one "ordm" : 186, // ordinal indicator, masculine "raquo" : 187, // angle quotation mark, right "frac14" : 188, // fraction one-quarter "frac12" : 189, // fraction one-half "frac34" : 190, // fraction three-quarters "iquest" : 191, // inverted question mark "Agrave" : 192, // capital A, grave accent "Aacute" : 193, // capital A, acute accent "Acirc" : 194, // capital A, circumflex accent "Atilde" : 195, // capital A, tilde "Auml" : 196, // capital A, dieresis or umlaut mark "Aring" : 197, // capital A, ring "AElig" : 198, // capital AE diphthong (ligature) "Ccedil" : 199, // capital C, cedilla "Egrave" : 200, // capital E, grave accent "Eacute" : 201, // capital E, acute accent "Ecirc" : 202, // capital E, circumflex accent "Euml" : 203, // capital E, dieresis or umlaut mark "Igrave" : 204, // capital I, grave accent "Iacute" : 205, // capital I, acute accent "Icirc" : 206, // capital I, circumflex accent "Iuml" : 207, // capital I, dieresis or umlaut mark "ETH" : 208, // capital Eth, Icelandic "Ntilde" : 209, // capital N, tilde "Ograve" : 210, // capital O, grave accent "Oacute" : 211, // capital O, acute accent "Ocirc" : 212, // capital O, circumflex accent "Otilde" : 213, // capital O, tilde "Ouml" : 214, // capital O, dieresis or umlaut mark "times" : 215, // multiply sign "Oslash" : 216, // capital O, slash "Ugrave" : 217, // capital U, grave accent "Uacute" : 218, // capital U, acute accent "Ucirc" : 219, // capital U, circumflex accent "Uuml" : 220, // capital U, dieresis or umlaut mark "Yacute" : 221, // capital Y, acute accent "THORN" : 222, // capital THORN, Icelandic "szlig" : 223, // small sharp s, German (sz ligature) "agrave" : 224, // small a, grave accent "aacute" : 225, // small a, acute accent "acirc" : 226, // small a, circumflex accent "atilde" : 227, // small a, tilde "auml" : 228, // small a, dieresis or umlaut mark "aring" : 229, // small a, ring "aelig" : 230, // small ae diphthong (ligature) "ccedil" : 231, // small c, cedilla "egrave" : 232, // small e, grave accent "eacute" : 233, // small e, acute accent "ecirc" : 234, // small e, circumflex accent "euml" : 235, // small e, dieresis or umlaut mark "igrave" : 236, // small i, grave accent "iacute" : 237, // small i, acute accent "icirc" : 238, // small i, circumflex accent "iuml" : 239, // small i, dieresis or umlaut mark "eth" : 240, // small eth, Icelandic "ntilde" : 241, // small n, tilde "ograve" : 242, // small o, grave accent "oacute" : 243, // small o, acute accent "ocirc" : 244, // small o, circumflex accent "otilde" : 245, // small o, tilde "ouml" : 246, // small o, dieresis or umlaut mark "divide" : 247, // divide sign "oslash" : 248, // small o, slash "ugrave" : 249, // small u, grave accent "uacute" : 250, // small u, acute accent "ucirc" : 251, // small u, circumflex accent "uuml" : 252, // small u, dieresis or umlaut mark "yacute" : 253, // small y, acute accent "thorn" : 254, // small thorn, Icelandic "yuml" : 255, // small y, dieresis or umlaut mark // Latin Extended-B "fnof" : 402, // latin small f with hook = function= florin, U+0192 ISOtech // Greek "Alpha" : 913, // greek capital letter alpha, U+0391 "Beta" : 914, // greek capital letter beta, U+0392 "Gamma" : 915, // greek capital letter gamma,U+0393 ISOgrk3 "Delta" : 916, // greek capital letter delta,U+0394 ISOgrk3 "Epsilon" : 917, // greek capital letter epsilon, U+0395 "Zeta" : 918, // greek capital letter zeta, U+0396 "Eta" : 919, // greek capital letter eta, U+0397 "Theta" : 920, // greek capital letter theta,U+0398 ISOgrk3 "Iota" : 921, // greek capital letter iota, U+0399 "Kappa" : 922, // greek capital letter kappa, U+039A "Lambda" : 923, // greek capital letter lambda,U+039B ISOgrk3 "Mu" : 924, // greek capital letter mu, U+039C "Nu" : 925, // greek capital letter nu, U+039D "Xi" : 926, // greek capital letter xi, U+039E ISOgrk3 "Omicron" : 927, // greek capital letter omicron, U+039F "Pi" : 928, // greek capital letter pi, U+03A0 ISOgrk3 "Rho" : 929, // greek capital letter rho, U+03A1 // there is no Sigmaf, and no U+03A2 character either "Sigma" : 931, // greek capital letter sigma,U+03A3 ISOgrk3 "Tau" : 932, // greek capital letter tau, U+03A4 "Upsilon" : 933, // greek capital letter upsilon,U+03A5 ISOgrk3 "Phi" : 934, // greek capital letter phi,U+03A6 ISOgrk3 "Chi" : 935, // greek capital letter chi, U+03A7 "Psi" : 936, // greek capital letter psi,U+03A8 ISOgrk3 "Omega" : 937, // greek capital letter omega,U+03A9 ISOgrk3 "alpha" : 945, // greek small letter alpha,U+03B1 ISOgrk3 "beta" : 946, // greek small letter beta, U+03B2 ISOgrk3 "gamma" : 947, // greek small letter gamma,U+03B3 ISOgrk3 "delta" : 948, // greek small letter delta,U+03B4 ISOgrk3 "epsilon" : 949, // greek small letter epsilon,U+03B5 ISOgrk3 "zeta" : 950, // greek small letter zeta, U+03B6 ISOgrk3 "eta" : 951, // greek small letter eta, U+03B7 ISOgrk3 "theta" : 952, // greek small letter theta,U+03B8 ISOgrk3 "iota" : 953, // greek small letter iota, U+03B9 ISOgrk3 "kappa" : 954, // greek small letter kappa,U+03BA ISOgrk3 "lambda" : 955, // greek small letter lambda,U+03BB ISOgrk3 "mu" : 956, // greek small letter mu, U+03BC ISOgrk3 "nu" : 957, // greek small letter nu, U+03BD ISOgrk3 "xi" : 958, // greek small letter xi, U+03BE ISOgrk3 "omicron" : 959, // greek small letter omicron, U+03BF NEW "pi" : 960, // greek small letter pi, U+03C0 ISOgrk3 "rho" : 961, // greek small letter rho, U+03C1 ISOgrk3 "sigmaf" : 962, // greek small letter final sigma,U+03C2 ISOgrk3 "sigma" : 963, // greek small letter sigma,U+03C3 ISOgrk3 "tau" : 964, // greek small letter tau, U+03C4 ISOgrk3 "upsilon" : 965, // greek small letter upsilon,U+03C5 ISOgrk3 "phi" : 966, // greek small letter phi, U+03C6 ISOgrk3 "chi" : 967, // greek small letter chi, U+03C7 ISOgrk3 "psi" : 968, // greek small letter psi, U+03C8 ISOgrk3 "omega" : 969, // greek small letter omega,U+03C9 ISOgrk3 "thetasym" : 977, // greek small letter theta symbol,U+03D1 NEW "upsih" : 978, // greek upsilon with hook symbol,U+03D2 NEW "piv" : 982, // greek pi symbol, U+03D6 ISOgrk3 // General Punctuation "bull" : 8226, // bullet = black small circle,U+2022 ISOpub // bullet is NOT the same as bullet operator, U+2219 "hellip" : 8230, // horizontal ellipsis = three dot leader,U+2026 ISOpub "prime" : 8242, // prime = minutes = feet, U+2032 ISOtech "Prime" : 8243, // double prime = seconds = inches,U+2033 ISOtech "oline" : 8254, // overline = spacing overscore,U+203E NEW "frasl" : 8260, // fraction slash, U+2044 NEW // Letterlike Symbols "weierp" : 8472, // script capital P = power set= Weierstrass p, U+2118 ISOamso "image" : 8465, // blackletter capital I = imaginary part,U+2111 ISOamso "real" : 8476, // blackletter capital R = real part symbol,U+211C ISOamso "trade" : 8482, // trade mark sign, U+2122 ISOnum "alefsym" : 8501, // alef symbol = first transfinite cardinal,U+2135 NEW // alef symbol is NOT the same as hebrew letter alef,U+05D0 although the same glyph could be used to depict both characters // Arrows "larr" : 8592, // leftwards arrow, U+2190 ISOnum "uarr" : 8593, // upwards arrow, U+2191 ISOnum--> "rarr" : 8594, // rightwards arrow, U+2192 ISOnum "darr" : 8595, // downwards arrow, U+2193 ISOnum "harr" : 8596, // left right arrow, U+2194 ISOamsa "crarr" : 8629, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW "lArr" : 8656, // leftwards double arrow, U+21D0 ISOtech // ISO 10646 does not say that lArr is the same as the 'is implied by' arrowbut also does not have any other character for that function. So ? lArr canbe used for 'is implied by' as ISOtech suggests "uArr" : 8657, // upwards double arrow, U+21D1 ISOamsa "rArr" : 8658, // rightwards double arrow,U+21D2 ISOtech // ISO 10646 does not say this is the 'implies' character but does not have another character with this function so ?rArr can be used for 'implies' as ISOtech suggests "dArr" : 8659, // downwards double arrow, U+21D3 ISOamsa "hArr" : 8660, // left right double arrow,U+21D4 ISOamsa // Mathematical Operators "forall" : 8704, // for all, U+2200 ISOtech "part" : 8706, // partial differential, U+2202 ISOtech "exist" : 8707, // there exists, U+2203 ISOtech "empty" : 8709, // empty set = null set = diameter,U+2205 ISOamso "nabla" : 8711, // nabla = backward difference,U+2207 ISOtech "isin" : 8712, // element of, U+2208 ISOtech "notin" : 8713, // not an element of, U+2209 ISOtech "ni" : 8715, // contains as member, U+220B ISOtech // should there be a more memorable name than 'ni'? "prod" : 8719, // n-ary product = product sign,U+220F ISOamsb // prod is NOT the same character as U+03A0 'greek capital letter pi' though the same glyph might be used for both "sum" : 8721, // n-ary summation, U+2211 ISOamsb // sum is NOT the same character as U+03A3 'greek capital letter sigma' though the same glyph might be used for both "minus" : 8722, // minus sign, U+2212 ISOtech "lowast" : 8727, // asterisk operator, U+2217 ISOtech "radic" : 8730, // square root = radical sign,U+221A ISOtech "prop" : 8733, // proportional to, U+221D ISOtech "infin" : 8734, // infinity, U+221E ISOtech "ang" : 8736, // angle, U+2220 ISOamso "and" : 8743, // logical and = wedge, U+2227 ISOtech "or" : 8744, // logical or = vee, U+2228 ISOtech "cap" : 8745, // intersection = cap, U+2229 ISOtech "cup" : 8746, // union = cup, U+222A ISOtech "int" : 8747, // integral, U+222B ISOtech "there4" : 8756, // therefore, U+2234 ISOtech "sim" : 8764, // tilde operator = varies with = similar to,U+223C ISOtech // tilde operator is NOT the same character as the tilde, U+007E,although the same glyph might be used to represent both "cong" : 8773, // approximately equal to, U+2245 ISOtech "asymp" : 8776, // almost equal to = asymptotic to,U+2248 ISOamsr "ne" : 8800, // not equal to, U+2260 ISOtech "equiv" : 8801, // identical to, U+2261 ISOtech "le" : 8804, // less-than or equal to, U+2264 ISOtech "ge" : 8805, // greater-than or equal to,U+2265 ISOtech "sub" : 8834, // subset of, U+2282 ISOtech "sup" : 8835, // superset of, U+2283 ISOtech // note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font encoding and is not included. Should it be, for symmetry?It is in ISOamsn --> <!ENTITY nsub": 8836, //not a subset of, U+2284 ISOamsn "sube" : 8838, // subset of or equal to, U+2286 ISOtech "supe" : 8839, // superset of or equal to,U+2287 ISOtech "oplus" : 8853, // circled plus = direct sum,U+2295 ISOamsb "otimes" : 8855, // circled times = vector product,U+2297 ISOamsb "perp" : 8869, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech "sdot" : 8901, // dot operator, U+22C5 ISOamsb // dot operator is NOT the same character as U+00B7 middle dot // Miscellaneous Technical "lceil" : 8968, // left ceiling = apl upstile,U+2308 ISOamsc "rceil" : 8969, // right ceiling, U+2309 ISOamsc "lfloor" : 8970, // left floor = apl downstile,U+230A ISOamsc "rfloor" : 8971, // right floor, U+230B ISOamsc "lang" : 9001, // left-pointing angle bracket = bra,U+2329 ISOtech // lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation mark' "rang" : 9002, // right-pointing angle bracket = ket,U+232A ISOtech // rang is NOT the same character as U+003E 'greater than' or U+203A 'single right-pointing angle quotation mark' // Geometric Shapes "loz" : 9674, // lozenge, U+25CA ISOpub // Miscellaneous Symbols "spades" : 9824, // black spade suit, U+2660 ISOpub // black here seems to mean filled as opposed to hollow "clubs" : 9827, // black club suit = shamrock,U+2663 ISOpub "hearts" : 9829, // black heart suit = valentine,U+2665 ISOpub "diams" : 9830, // black diamond suit, U+2666 ISOpub // Latin Extended-A "OElig" : 338, // -- latin capital ligature OE,U+0152 ISOlat2 "oelig" : 339, // -- latin small ligature oe, U+0153 ISOlat2 // ligature is a misnomer, this is a separate character in some languages "Scaron" : 352, // -- latin capital letter S with caron,U+0160 ISOlat2 "scaron" : 353, // -- latin small letter s with caron,U+0161 ISOlat2 "Yuml" : 376, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 // Spacing Modifier Letters "circ" : 710, // -- modifier letter circumflex accent,U+02C6 ISOpub "tilde" : 732, // small tilde, U+02DC ISOdia // General Punctuation "ensp" : 8194, // en space, U+2002 ISOpub "emsp" : 8195, // em space, U+2003 ISOpub "thinsp" : 8201, // thin space, U+2009 ISOpub "zwnj" : 8204, // zero width non-joiner,U+200C NEW RFC 2070 "zwj" : 8205, // zero width joiner, U+200D NEW RFC 2070 "lrm" : 8206, // left-to-right mark, U+200E NEW RFC 2070 "rlm" : 8207, // right-to-left mark, U+200F NEW RFC 2070 "ndash" : 8211, // en dash, U+2013 ISOpub "mdash" : 8212, // em dash, U+2014 ISOpub "lsquo" : 8216, // left single quotation mark,U+2018 ISOnum "rsquo" : 8217, // right single quotation mark,U+2019 ISOnum "sbquo" : 8218, // single low-9 quotation mark, U+201A NEW "ldquo" : 8220, // left double quotation mark,U+201C ISOnum "rdquo" : 8221, // right double quotation mark,U+201D ISOnum "bdquo" : 8222, // double low-9 quotation mark, U+201E NEW "dagger" : 8224, // dagger, U+2020 ISOpub "Dagger" : 8225, // double dagger, U+2021 ISOpub "permil" : 8240, // per mille sign, U+2030 ISOtech "lsaquo" : 8249, // single left-pointing angle quotation mark,U+2039 ISO proposed // lsaquo is proposed but not yet ISO standardized "rsaquo" : 8250, // single right-pointing angle quotation mark,U+203A ISO proposed // rsaquo is proposed but not yet ISO standardized "euro" : 8364 // -- euro sign, U+20AC NEW }, /** * Escapes the characters in a <code>String</code> using HTML entities. * * For example: <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>. * Supports all known HTML 4.0 entities, including funky accents. * * * <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a> * * <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a> * * <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a> * * <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a> * * @param str {String} the String to escape * @return {String} a new escaped String * @see #unescape */ escape : function(str) { return qx.util.StringEscape.escape(str, qx.bom.String.FROM_CHARCODE); }, /** * Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities. * * For example, the string "&amp;lt;Fran&amp;ccedil;ais&amp;gt;" * will become "&lt;Fran&ccedil;ais&gt;" * * If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&amp;gt;&amp;zzzz;x" will * become "&gt;&amp;zzzz;x". * * @param str {String} the String to unescape, may be null * @return {var} a new unescaped String * @see #escape */ unescape : function(str) { return qx.util.StringEscape.unescape(str, qx.bom.String.TO_CHARCODE); }, /** * Converts a plain text string into HTML. * This is similar to {@link #escape} but converts new lines to * <tt>&lt:br&gt:</tt> and preserves whitespaces. * * @param str {String} the String to convert * @return {String} a new converted String * @see #escape */ fromText : function(str) { return qx.bom.String.escape(str).replace(/( |\n)/g, function(chr) { var map = { " " : " &nbsp;", "\n" : "<br>" }; return map[chr] || chr; }); }, /** * Converts HTML to plain text. * * * Strips all HTML tags * * converts <tt>&lt:br&gt:</tt> to new line * * unescapes HTML entities * * @param str {String} HTML string to converts * @return {String} plain text representation of the HTML string */ toText : function(str) { return qx.bom.String.unescape(str.replace(/\s+|<([^>])+>/gi, function(chr) //return qx.bom.String.unescape(str.replace(/<\/?[^>]+(>|$)/gi, function(chr) { if (chr.indexOf("<br") === 0) { return "\n"; } else if (chr.length > 0 && chr.replace(/^\s*/, "").replace(/\s*$/, "") == "") { return " "; } else { return ""; } })); } }, /* ***************************************************************************** DEFER ***************************************************************************** */ defer : function(statics) { /** Mapping of char codes to HTML entity names */ statics.FROM_CHARCODE = qx.lang.Object.invert(statics.TO_CHARCODE) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Generic escaping and unescaping of DOM strings. * * {@link qx.bom.String} for (un)escaping of HTML strings. * {@link qx.xml.String} for (un)escaping of XML strings. */ qx.Class.define("qx.util.StringEscape", { statics : { /** * generic escaping method * * @param str {String} string to escape * @param charCodeToEntities {Map} entity to charcode map * @return {String} escaped string * @signature function(str, charCodeToEntities) */ escape : function(str, charCodeToEntities) { var entity, result = ""; for (var i=0, l=str.length; i<l; i++) { var chr = str.charAt(i); var code = chr.charCodeAt(0); if (charCodeToEntities[code]) { entity = "&" + charCodeToEntities[code] + ";"; } else { if (code > 0x7F) { entity = "&#" + code + ";"; } else { entity = chr; } } result += entity; } return result; }, /** * generic unescaping method * * @param str {String} string to unescape * @param entitiesToCharCode {Map} charcode to entity map * @return {String} unescaped string */ unescape : function(str, entitiesToCharCode) { return str.replace(/&[#\w]+;/gi, function(entity) { var chr = entity; var entity = entity.substring(1, entity.length - 1); var code = entitiesToCharCode[entity]; if (code) { chr = String.fromCharCode(code); } else { if (entity.charAt(0) == '#') { if (entity.charAt(1).toUpperCase() == 'X') { code = entity.substring(2); // match hex number if (code.match(/^[0-9A-Fa-f]+$/gi)) { chr = String.fromCharCode(parseInt(code, 16)); } } else { code = entity.substring(1); // match integer if (code.match(/^\d+$/gi)) { chr = String.fromCharCode(parseInt(code, 10)); } } } } return chr; }); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Werner (wpbasti) * Jonathan Weiß (jonathan_rass) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * A form widget which allows a single selection. Looks somewhat like * a normal button, but opens a list of items to select when clicking on it. * * Keep in mind that the SelectBox widget has always a selected item (due to the * single selection mode). Right after adding the first item a <code>changeSelection</code> * event is fired. * * <pre class='javascript'> * var selectBox = new qx.ui.form.SelectBox(); * * selectBox.addListener("changeSelection", function(e) { * // ... * }); * * // now the 'changeSelection' event is fired * selectBox.add(new qx.ui.form.ListItem("Item 1"); * </pre> * * @childControl spacer {qx.ui.core.Spacer} flexible spacer widget * @childControl atom {qx.ui.basic.Atom} shows the text and icon of the content * @childControl arrow {qx.ui.basic.Image} shows the arrow to open the popup */ qx.Class.define("qx.ui.form.SelectBox", { extend : qx.ui.form.AbstractSelectBox, implement : [ qx.ui.core.ISingleSelection, qx.ui.form.IModelSelection ], include : [qx.ui.core.MSingleSelectionHandling, qx.ui.form.MModelSelection], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); this._createChildControl("atom"); this._createChildControl("spacer"); this._createChildControl("arrow"); // Register listener this.addListener("mouseover", this._onMouseOver, this); this.addListener("mouseout", this._onMouseOut, this); this.addListener("click", this._onClick, this); this.addListener("mousewheel", this._onMouseWheel, this); this.addListener("keyinput", this._onKeyInput, this); this.addListener("changeSelection", this.__onChangeSelection, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "selectbox" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.form.ListItem} instance */ __preSelectedItem : null, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "spacer": control = new qx.ui.core.Spacer(); this._add(control, {flex: 1}); break; case "atom": control = new qx.ui.basic.Atom(" "); control.setCenter(false); control.setAnonymous(true); this._add(control, {flex:1}); break; case "arrow": control = new qx.ui.basic.Image(); control.setAnonymous(true); this._add(control); break; } return control || this.base(arguments, id); }, // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true }, /* --------------------------------------------------------------------------- HELPER METHODS FOR SELECTION API --------------------------------------------------------------------------- */ /** * Returns the list items for the selection. * * @return {qx.ui.form.ListItem[]} List itmes to select. */ _getItems : function() { return this.getChildrenContainer().getChildren(); }, /** * Returns if the selection could be empty or not. * * @return {Boolean} <code>true</code> If selection could be empty, * <code>false</code> otherwise. */ _isAllowEmptySelection: function() { return this.getChildrenContainer().getSelectionMode() !== "one"; }, /** * Event handler for <code>changeSelection</code>. * * @param e {qx.event.type.Data} Data event. */ __onChangeSelection : function(e) { var listItem = e.getData()[0]; var list = this.getChildControl("list"); if (list.getSelection()[0] != listItem) { if(listItem) { list.setSelection([listItem]); } else { list.resetSelection(); } } this.__updateIcon(); this.__updateLabel(); }, /** * Sets the icon inside the list to match the selected ListItem. */ __updateIcon : function() { var listItem = this.getChildControl("list").getSelection()[0]; var atom = this.getChildControl("atom"); var icon = listItem ? listItem.getIcon() : ""; icon == null ? atom.resetIcon() : atom.setIcon(icon); }, /** * Sets the label inside the list to match the selected ListItem. */ __updateLabel : function() { var listItem = this.getChildControl("list").getSelection()[0]; var atom = this.getChildControl("atom"); var label = listItem ? listItem.getLabel() : ""; var format = this.getFormat(); if (format != null) { label = format.call(this, listItem); } // check for translation if (label && label.translate) { label = label.translate(); } label == null ? atom.resetLabel() : atom.setLabel(label); }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Listener method for "mouseover" event * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event */ _onMouseOver : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); } this.addState("hovered"); }, /** * Listener method for "mouseout" event * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" and removes "pressed" state (if "pressed" state is set)</li> * </ul> * * @param e {Event} Mouse event */ _onMouseOut : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { this.removeState("pressed"); this.addState("abandoned"); } }, /** * Toggles the popup's visibility. * * @param e {qx.event.type.Mouse} Mouse event */ _onClick : function(e) { this.toggle(); }, /** * Event handler for mousewheel event * * @param e {qx.event.type.Mouse} Mouse event */ _onMouseWheel : function(e) { if (this.getChildControl("popup").isVisible()) { return; } var direction = e.getWheelDelta("y") > 0 ? 1 : -1; var children = this.getSelectables(); var selected = this.getSelection()[0]; if (!selected) { selected = children[0]; } var index = children.indexOf(selected) + direction; var max = children.length - 1; // Limit if (index < 0) { index = 0; } else if (index >= max) { index = max; } this.setSelection([children[index]]); // stop the propagation // prevent any other widget from receiving this event // e.g. place a selectbox widget inside a scroll container widget e.stopPropagation(); e.preventDefault(); }, // overridden _onKeyPress : function(e) { var iden = e.getKeyIdentifier(); if(iden == "Enter" || iden == "Space") { // Apply pre-selected item (translate quick selection to real selection) if (this.__preSelectedItem) { this.setSelection([this.__preSelectedItem]); this.__preSelectedItem = null; } this.toggle(); } else { this.base(arguments, e); } }, /** * Forwards key event to list widget. * * @param e {qx.event.type.KeyInput} Key event */ _onKeyInput : function(e) { // clone the event and re-calibrate the event var clone = e.clone(); clone.setTarget(this._list); clone.setBubbles(false); // forward it to the list this.getChildControl("list").dispatchEvent(clone); }, // overridden _onListMouseDown : function(e) { // Apply pre-selected item (translate quick selection to real selection) if (this.__preSelectedItem) { this.setSelection([this.__preSelectedItem]); this.__preSelectedItem = null; } }, // overridden _onListChangeSelection : function(e) { var current = e.getData(); var old = e.getOldData(); // Remove old listeners for icon and label changes. if (old && old.length > 0) { old[0].removeListener("changeIcon", this.__updateIcon, this); old[0].removeListener("changeLabel", this.__updateLabel, this); } if (current.length > 0) { // Ignore quick context (e.g. mouseover) // and configure the new value when closing the popup afterwards var popup = this.getChildControl("popup"); var list = this.getChildControl("list"); var context = list.getSelectionContext(); if (popup.isVisible() && (context == "quick" || context == "key")) { this.__preSelectedItem = current[0]; } else { this.setSelection([current[0]]); this.__preSelectedItem = null; } // Add listeners for icon and label changes current[0].addListener("changeIcon", this.__updateIcon, this); current[0].addListener("changeLabel", this.__updateLabel, this); } else { this.resetSelection(); } }, // overridden _onPopupChangeVisibility : function(e) { this.base(arguments, e); // Synchronize the current selection to the list selection // when the popup is closed. The list selection may be invalid // because of the quick selection handling which is not // directly applied to the selectbox var popup = this.getChildControl("popup"); if (!popup.isVisible()) { var list = this.getChildControl("list"); // check if the list has any children before selecting if (list.hasChildren()) { list.setSelection(this.getSelection()); } } else { // ensure that the list is never biger that the max list height and // the available space in the viewport var distance = popup.getLayoutLocation(this); var viewPortHeight = qx.bom.Viewport.getHeight(); // distance to the bottom and top borders of the viewport var toTop = distance.top; var toBottom = viewPortHeight - distance.bottom; var availableHeigth = toTop > toBottom ? toTop : toBottom; var maxListHeight = this.getMaxListHeight(); var list = this.getChildControl("list") if (maxListHeight == null || maxListHeight > availableHeigth) { list.setMaxHeight(availableHeigth); } else if (maxListHeight < availableHeigth) { list.setMaxHeight(maxListHeight); } } } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__preSelectedItem = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Spacer is a "virtual" widget, which can be placed into any layout and takes * the space a normal widget of the same size would take. * * Spacers are invisible and very light weight because they don't require any * DOM modifications. * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var container = new qx.ui.container.Composite(new qx.ui.layout.HBox()); * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Spacer(50)); * container.add(new qx.ui.core.Widget()); * </pre> * * This example places two widgets and a spacer into a container with a * horizontal box layout. In this scenario the spacer creates an empty area of * 50 pixel width between the two widgets. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/spacer.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.core.Spacer", { extend : qx.ui.core.LayoutItem, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param width {Integer?null} the initial width * @param height {Integer?null} the initial height */ construct : function(width, height) { this.base(arguments); // Initialize dimensions this.setWidth(width != null ? width : 0); this.setHeight(height != null ? height : 0); }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Helper method called from the visibility queue to detect outstanding changes * to the appearance. * * @internal */ checkAppearanceNeeds : function() { // placeholder to improve compatibility with Widget. }, /** * Recursively adds all children to the given queue * * @param queue {Map} The queue to add widgets to */ addChildrenToQueue : function(queue) { // placeholder to improve compatibility with Widget. }, /** * Removes this widget from its parent and dispose it. * * Please note that the widget is not disposed synchronously. The * real dispose happens after the next queue flush. * * @return {void} */ destroy : function() { if (this.$$disposed) { return; } var parent = this.$$parent; if (parent) { parent._remove(this); } qx.ui.core.queue.Dispose.add(this); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * A item for a list. Could be added to all List like widgets but also * to the {@link qx.ui.form.SelectBox} and {@link qx.ui.form.ComboBox}. */ qx.Class.define("qx.ui.form.ListItem", { extend : qx.ui.basic.Atom, implement : [qx.ui.form.IModel], include : [qx.ui.form.MModelProperty], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param label {String} Label to use * @param icon {String?null} Icon to use * @param model {String?null} The items value */ construct : function(label, icon, model) { this.base(arguments, label, icon); if (model != null) { this.setModel(model); } this.addListener("mouseover", this._onMouseOver, this); this.addListener("mouseout", this._onMouseOut, this); }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events: { /** (Fired by {@link qx.ui.form.List}) */ "action" : "qx.event.type.Event" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { appearance : { refine : true, init : "listitem" } }, members : { // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true, hovered : true, selected : true, dragover : true }, /** * Event handler for the mouse over event. */ _onMouseOver : function() { this.addState("hovered"); }, /** * Event handler for the mouse out event. */ _onMouseOut : function() { this.removeState("hovered"); } }, destruct : function() { this.removeListener("mouseover", this._onMouseOver, this); this.removeListener("mouseout", this._onMouseOut, this); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This interface defines the necessary features a form renderer should have. * Keep in mind that all renderes has to be widgets. */ qx.Interface.define("qx.ui.form.renderer.IFormRenderer", { members : { /** * Add a group of form items with the corresponding names. The names should * be displayed as hint for the user what to do with the form item. * The title is optional and can be used as grouping for the given form * items. * * @param items {qx.ui.core.Widget[]} An array of form items to render. * @param names {String[]} An array of names for the form items. * @param title {String?} A title of the group you are adding. * @param itemsOptions {Array?null} The added additional data. * @param headerOptions {Map?null} The options map as defined by the form * for the current group header. */ addItems : function(items, names, title, itemsOptions, headerOptions) {}, /** * Adds a button the form renderer. * * @param button {qx.ui.form.Button} A button which should be added to * the form. * @param options {Map?null} The added additional data. */ addButton : function(button, options) {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Abstract renderer for {@link qx.ui.form.Form}. This abstract rendere should * be the superclass of all form renderer. It takes the form, which is * supplied as constructor parameter and configures itself. So if you need to * set some additional information on your renderer before adding the widgets, * be sure to do that before calling this.base(arguments, form). */ qx.Class.define("qx.ui.form.renderer.AbstractRenderer", { type : "abstract", extend : qx.ui.core.Widget, implement : qx.ui.form.renderer.IFormRenderer, /** * @param form {qx.ui.form.Form} The form to render. */ construct : function(form) { this.base(arguments); this._visibilityBindingIds = []; this._labels = []; // translation support if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener( "changeLocale", this._onChangeLocale, this ); this._names = []; } // add the groups var groups = form.getGroups(); for (var i = 0; i < groups.length; i++) { var group = groups[i]; this.addItems( group.items, group.labels, group.title, group.options, group.headerOptions ); } // add the buttons var buttons = form.getButtons(); var buttonOptions = form.getButtonOptions(); for (var i = 0; i < buttons.length; i++) { this.addButton(buttons[i], buttonOptions[i]); } }, members : { _names : null, _visibilityBindingIds : null, _labels : null, /** * Helper to bind the item's visibility to the label's visibility. * @param item {qx.ui.core.Widget} The form element. * @param label {qx.ui.basic.Label} The label for the form element. */ _connectVisibility : function(item, label) { // map the items visibility to the label var id = item.bind("visibility", label, "visibility"); this._visibilityBindingIds.push({id: id, item: item}); }, /** * Locale change event handler * * @signature function(e) * @param e {Event} the change event */ _onChangeLocale : qx.core.Environment.select("qx.dynlocale", { "true" : function(e) { for (var i = 0; i < this._names.length; i++) { var entry = this._names[i]; if (entry.name && entry.name.translate) { entry.name = entry.name.translate(); } var newText = this._createLabelText(entry.name, entry.item); entry.label.setValue(newText); }; }, "false" : null }), /** * Creates the label text for the given form item. * * @param name {String} The content of the label without the * trailing * and : * @param item {qx.ui.form.IForm} The item, which has the required state. * @return {String} The text for the given item. */ _createLabelText : function(name, item) { var required = ""; if (item.getRequired()) { required = " <span style='color:red'>*</span> "; } // Create the label. Append a colon only if there's text to display. var colon = name.length > 0 || item.getRequired() ? " :" : ""; return name + required + colon; }, // interface implementation addItems : function(items, names, title) { throw new Error("Abstract method call"); }, // interface implementation addButton : function(button) { throw new Error("Abstract method call"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this._onChangeLocale, this); } this._names = null; // remove all created lables for (var i=0; i < this._labels.length; i++) { this._labels[i].dispose(); }; // remove the visibility bindings for (var i = 0; i < this._visibilityBindingIds.length; i++) { var entry = this._visibilityBindingIds[i]; entry.item.removeBinding(entry.id); }; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Single column renderer for {@link qx.ui.form.Form}. */ qx.Class.define("qx.ui.form.renderer.Single", { extend : qx.ui.form.renderer.AbstractRenderer, construct : function(form) { var layout = new qx.ui.layout.Grid(); layout.setSpacing(6); layout.setColumnFlex(0, 1); layout.setColumnAlign(0, "right", "top"); this._setLayout(layout); this.base(arguments, form); }, members : { _row : 0, _buttonRow : null, /** * Add a group of form items with the corresponding names. The names are * displayed as label. * The title is optional and is used as grouping for the given form * items. * * @param items {qx.ui.core.Widget[]} An array of form items to render. * @param names {String[]} An array of names for the form items. * @param title {String?} A title of the group you are adding. */ addItems : function(items, names, title) { // add the header if (title != null) { this._add( this._createHeader(title), {row: this._row, column: 0, colSpan: 2} ); this._row++; } // add the items for (var i = 0; i < items.length; i++) { var label = this._createLabel(names[i], items[i]); this._add(label, {row: this._row, column: 0}); var item = items[i]; label.setBuddy(item); this._add(item, {row: this._row, column: 1}); this._row++; this._connectVisibility(item, label); // store the names for translation if (qx.core.Environment.get("qx.dynlocale")) { this._names.push({name: names[i], label: label, item: items[i]}); } } }, /** * Adds a button the form renderer. All buttons will be added in a * single row at the bottom of the form. * * @param button {qx.ui.form.Button} The button to add. */ addButton : function(button) { if (this._buttonRow == null) { // create button row this._buttonRow = new qx.ui.container.Composite(); this._buttonRow.setMarginTop(5); var hbox = new qx.ui.layout.HBox(); hbox.setAlignX("right"); hbox.setSpacing(5); this._buttonRow.setLayout(hbox); // add the button row this._add(this._buttonRow, {row: this._row, column: 0, colSpan: 2}); // increase the row this._row++; } // add the button this._buttonRow.add(button); }, /** * Returns the set layout for configuration. * * @return {qx.ui.layout.Grid} The grid layout of the widget. */ getLayout : function() { return this._getLayout(); }, /** * Creates a label for the given form item. * * @param name {String} The content of the label without the * trailing * and : * @param item {qx.ui.core.Widget} The item, which has the required state. * @return {qx.ui.basic.Label} The label for the given item. */ _createLabel : function(name, item) { var label = new qx.ui.basic.Label(this._createLabelText(name, item)); // store lables for disposal this._labels.push(label); label.setRich(true); label.setAppearance("form-renderer-label"); return label; }, /** * Creates a header label for the form groups. * * @param title {String} Creates a header label. * @return {qx.ui.basic.Label} The header for the form groups. */ _createHeader : function(title) { var header = new qx.ui.basic.Label(title); // store lables for disposal this._labels.push(header); header.setFont("bold"); if (this._row != 0) { header.setMarginTop(10); } header.setAlignX("left"); return header; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // first, remove all buttons from the button row because they // should not be disposed if (this._buttonRow) { this._buttonRow.removeAll(); this._disposeObjects("_buttonRow"); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the selection in the data binding controller. * It contains an selection property which can be manipulated. * Remember to call the method {@link #_addChangeTargetListener} on every * change of the target. * It is also important that the elements stored in the target e.g. ListItems * do have the corresponding model stored as user data under the "model" key. */ qx.Mixin.define("qx.data.controller.MSelection", { /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { // check for a target property if (!qx.Class.hasProperty(this.constructor, "target")) { throw new Error("Target property is needed."); } // create a default selection array if (this.getSelection() == null) { this.__ownSelection = new qx.data.Array(); this.setSelection(this.__ownSelection); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Data array containing the selected model objects. This property can be * manipulated directly which means that a push to the selection will also * select the corresponding element in the target. */ selection : { check: "qx.data.Array", event: "changeSelection", apply: "_applySelection", init: null } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // private members // // set the semaphore-like variable for the selection change _modifingSelection : 0, __selectionListenerId : null, __selectionArrayListenerId : null, __ownSelection : null, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ /** * Apply-method for setting a new selection array. Only the change listener * will be removed from the old array and added to the new. * * @param value {qx.data.Array} The new data array for the selection. * @param old {qx.data.Array|null} The old data array for the selection. */ _applySelection: function(value, old) { // remove the old listener if necessary if (this.__selectionArrayListenerId != undefined && old != undefined) { old.removeListenerById(this.__selectionArrayListenerId); } // add a new change listener to the changeArray this.__selectionArrayListenerId = value.addListener( "change", this.__changeSelectionArray, this ); // apply the new selection this._updateSelection(); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event handler for the change of the data array holding the selection. * If a change is in the selection array, the selection update will be * invoked. */ __changeSelectionArray: function() { this._updateSelection(); }, /** * Event handler for a change in the target selection. * If the selection in the target has changed, the selected model objects * will be found and added to the selection array. */ _changeTargetSelection: function() { // dont do anything without a target if (this.getTarget() == null) { return; } // if a selection API is supported if (!this.__targetSupportsMultiSelection() && !this.__targetSupportsSingleSelection()) { return; } // if __changeSelectionArray is currently working, do nothing if (this._inSelectionModification()) { return; } // get both selections var targetSelection = this.getTarget().getSelection(); var selection = this.getSelection(); if (selection == null) { selection = new qx.data.Array(); this.__ownSelection = selection; this.setSelection(selection); } // go through the target selection var spliceArgs = [0, selection.getLength()]; for (var i = 0; i < targetSelection.length; i++) { spliceArgs.push(targetSelection[i].getModel()); } // use splice to ensure a correct change event [BUG #4728] selection.splice.apply(selection, spliceArgs).dispose(); // fire the change event manually this.fireDataEvent("changeSelection", this.getSelection()); }, /* --------------------------------------------------------------------------- SELECTION --------------------------------------------------------------------------- */ /** * Helper method which should be called by the classes including this * Mixin when the target changes. * * @param value {qx.ui.core.Widget|null} The new target. * @param old {qx.ui.core.Widget|null} The old target. */ _addChangeTargetListener: function(value, old) { // remove the old selection listener if (this.__selectionListenerId != undefined && old != undefined) { old.removeListenerById(this.__selectionListenerId); } if (value != null) { // if a selection API is supported if ( this.__targetSupportsMultiSelection() || this.__targetSupportsSingleSelection() ) { // add a new selection listener this.__selectionListenerId = value.addListener( "changeSelection", this._changeTargetSelection, this ); } } }, /** * Method for updating the selection. It checks for the case of single or * multi selection and after that checks if the selection in the selection * array is the same as in the target widget. */ _updateSelection: function() { // do not update if no target is given if (!this.getTarget()) { return; } // mark the change process in a flag this._startSelectionModification(); // if its a multi selection target if (this.__targetSupportsMultiSelection()) { var targetSelection = []; // go through the selection array for (var i = 0; i < this.getSelection().length; i++) { // store each item var model = this.getSelection().getItem(i); var selectable = this.__getSelectableForModel(model); if (selectable != null) { targetSelection.push(selectable); } } this.getTarget().setSelection(targetSelection); // get the selection of the target targetSelection = this.getTarget().getSelection(); // get all items selected in the list var targetSelectionItems = []; for (var i = 0; i < targetSelection.length; i++) { targetSelectionItems[i] = targetSelection[i].getModel(); } // go through the controller selection for (var i = this.getSelection().length - 1; i >= 0; i--) { // if the item in the controller selection is not selected in the list if (!qx.lang.Array.contains( targetSelectionItems, this.getSelection().getItem(i) )) { // remove the current element and get rid of the return array this.getSelection().splice(i, 1).dispose(); } } // if its a single selection target } else if (this.__targetSupportsSingleSelection()) { // get the model which should be selected var item = this.getSelection().getItem(this.getSelection().length - 1); if (item !== undefined) { // select the last selected item (old selection will be removed anyway) this.__selectItem(item); // remove the other items from the selection data array and get // rid of the return array this.getSelection().splice( 0, this.getSelection().getLength() - 1 ).dispose(); } else { // if there is no item to select (e.g. new model set [BUG #4125]), // reset the selection this.getTarget().resetSelection(); } } // reset the changing flag this._endSelectionModification(); }, /** * Helper-method returning true, if the target supports multi selection. * @return {boolean} true, if the target supports multi selection. */ __targetSupportsMultiSelection: function() { var targetClass = this.getTarget().constructor; return qx.Class.implementsInterface(targetClass, qx.ui.core.IMultiSelection); }, /** * Helper-method returning true, if the target supports single selection. * @return {boolean} true, if the target supports single selection. */ __targetSupportsSingleSelection: function() { var targetClass = this.getTarget().constructor; return qx.Class.implementsInterface(targetClass, qx.ui.core.ISingleSelection); }, /** * Internal helper for selecting an item in the target. The item to select * is defined by a given model item. * * @param item {qx.core.Object} A model element. */ __selectItem: function(item) { var selectable = this.__getSelectableForModel(item); // if no selectable could be found, just return if (selectable == null) { return; } // if the target is multi selection able if (this.__targetSupportsMultiSelection()) { // select the item in the target this.getTarget().addToSelection(selectable); // if the target is single selection able } else if (this.__targetSupportsSingleSelection()) { this.getTarget().setSelection([selectable]); } }, /** * Returns the list item storing the given model in its model property. * * @param model {var} The representing model of a selectable. */ __getSelectableForModel : function(model) { // get all list items var children = this.getTarget().getSelectables(true); // go through all children and search for the child to select for (var i = 0; i < children.length; i++) { if (children[i].getModel() == model) { return children[i]; } } // if no selectable was found return null; }, /** * Helper-Method signaling that currently the selection of the target is * in change. That will block the change of the internal selection. * {@link #_endSelectionModification} */ _startSelectionModification: function() { this._modifingSelection++; }, /** * Helper-Method signaling that the internal changing of the targets * selection is over. * {@link #_startSelectionModification} */ _endSelectionModification: function() { this._modifingSelection > 0 ? this._modifingSelection-- : null; }, /** * Helper-Method for checking the state of the selection modification. * {@link #_startSelectionModification} * {@link #_endSelectionModification} */ _inSelectionModification: function() { return this._modifingSelection > 0; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { if (this.__ownSelection) { this.__ownSelection.dispose(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>List Controller</h2> * * *General idea* * The list controller is responsible for synchronizing every list like widget * with a data array. It does not matter if the array contains atomic values * like strings of complete objects where one property holds the value for * the label and another property holds the icon url. You can even use converts * the make the label show a text corresponding to the icon by binding both, * label and icon to the same model property and converting one. * * *Features* * * * Synchronize the model and the target * * Label and icon are bindable * * Takes care of the selection * * Passes on the options used by the bindings * * *Usage* * * As model, only {@link qx.data.Array}s do work. The currently supported * targets are * * * {@link qx.ui.form.SelectBox} * * {@link qx.ui.form.List} * * {@link qx.ui.form.ComboBox} * * All the properties like model, target or any property path is bindable. * Especially the model is nice to bind to another selection for example. * The controller itself can only work if it has a model and a target set. The * rest of the properties may be empty. * * *Cross reference* * * * If you want to bind single values, use {@link qx.data.controller.Object} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} * * If you want to bind a form widget, use {@link qx.data.controller.Form} */ qx.Class.define("qx.data.controller.List", { extend : qx.core.Object, include: qx.data.controller.MSelection, implement : qx.data.controller.ISelection, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param model {qx.data.Array?null} The array containing the data. * * @param target {qx.ui.core.Widget?null} The widget which should show the * ListItems. * * @param labelPath {String?null} If the model contains objects, the labelPath * is the path reference to the property in these objects which should be * shown as label. */ construct : function(model, target, labelPath) { this.base(arguments); // lookup table for filtering and sorting this.__lookupTable = []; // register for bound target properties and onUpdate methods // from the binding options this.__boundProperties = []; this.__boundPropertiesReverse = []; this.__onUpdate = {}; if (labelPath != null) { this.setLabelPath(labelPath); } if (model != null) { this.setModel(model); } if (target != null) { this.setTarget(target); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** Data array containing the data which should be shown in the list. */ model : { check: "qx.data.IListData", apply: "_applyModel", event: "changeModel", nullable: true, dereference: true }, /** The target widget which should show the data. */ target : { apply: "_applyTarget", event: "changeTarget", nullable: true, init: null, dereference: true }, /** * The path to the property which holds the information that should be * shown as a label. This is only needed if objects are stored in the model. */ labelPath : { check: "String", apply: "_applyLabelPath", nullable: true }, /** * The path to the property which holds the information that should be * shown as an icon. This is only needed if objects are stored in the model * and if the icon should be shown. */ iconPath : { check: "String", apply: "_applyIconPath", nullable: true }, /** * A map containing the options for the label binding. The possible keys * can be found in the {@link qx.data.SingleValueBinding} documentation. */ labelOptions : { apply: "_applyLabelOptions", nullable: true }, /** * A map containing the options for the icon binding. The possible keys * can be found in the {@link qx.data.SingleValueBinding} documentation. */ iconOptions : { apply: "_applyIconOptions", nullable: true }, /** * Delegation object, which can have one or more functions defined by the * {@link IControllerDelegate} interface. */ delegate : { apply: "_applyDelegate", event: "changeDelegate", init: null, nullable: true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // private members __changeModelListenerId : null, __lookupTable : null, __onUpdate : null, __boundProperties : null, __boundPropertiesReverse : null, __syncTargetSelection : null, __syncModelSelection : null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Updates the filter and the target. This could be used if the filter * uses an additional parameter which changes the filter result. */ update: function() { this.__changeModelLength(); this.__renewBindings(); this._updateSelection(); }, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ /** * If a new delegate is set, it applies the stored configuration for the * list items to the already created list items once. * * @param value {qx.core.Object|null} The new delegate. * @param old {qx.core.Object|null} The old delegate. */ _applyDelegate: function(value, old) { this._setConfigureItem(value, old); this._setFilter(value, old); this._setCreateItem(value, old); this._setBindItem(value, old); }, /** * Apply-method which will be called if the icon options has been changed. * It invokes a renewing of all set bindings. * * @param value {Map|null} The new icon options. * @param old {Map|null} The old icon options. */ _applyIconOptions: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the label options has been changed. * It invokes a renewing of all set bindings. * * @param value {Map|null} The new label options. * @param old {Map|null} The old label options. */ _applyLabelOptions: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the icon path has been changed. * It invokes a renewing of all set bindings. * * @param value {String|null} The new icon path. * @param old {String|null} The old icon path. */ _applyIconPath: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the label path has been changed. * It invokes a renewing of all set bindings. * * @param value {String|null} The new label path. * @param old {String|null} The old label path. */ _applyLabelPath: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the model has been changed. It * removes all the listeners from the old model and adds the needed * listeners to the new model. It also invokes the initial filling of the * target widgets if there is a target set. * * @param value {qx.data.Array|null} The new model array. * @param old {qx.data.Array|null} The old model array. */ _applyModel: function(value, old) { // remove the old listener if (old != undefined) { if (this.__changeModelListenerId != undefined) { old.removeListenerById(this.__changeModelListenerId); } } // erase the selection if there is something selected if (this.getSelection() != undefined && this.getSelection().length > 0) { this.getSelection().splice(0, this.getSelection().length).dispose(); } // if a model is set if (value != null) { // add a new listener this.__changeModelListenerId = value.addListener("change", this.__changeModel, this); // renew the index lookup table this.__buildUpLookupTable(); // check for the new length this.__changeModelLength(); // as we only change the labels of the items, the selection change event // may be missing so we invoke it here if (old == null) { this._changeTargetSelection(); } else { // update the selection asynchronously this.__syncTargetSelection = true; qx.ui.core.queue.Widget.add(this); } } else { var target = this.getTarget(); // if the model is set to null, we should remove all items in the target if (target != null) { // we need to remove the bindings too so use the controller method // for removing items var length = target.getChildren().length; for (var i = 0; i < length; i++) { this.__removeItem(); }; } } }, /** * Apply-method which will be called if the target has been changed. * When the target changes, every binding needs to be reset and the old * target needs to be cleaned up. If there is a model, the target will be * filled with the data of the model. * * @param value {qx.ui.core.Widget|null} The new target. * @param old {qx.ui.core.Widget|null} The old target. */ _applyTarget: function(value, old) { // add a listener for the target change this._addChangeTargetListener(value, old); // if there was an old target if (old != undefined) { // remove all element of the old target var removed = old.removeAll(); for (var i=0; i<removed.length; i++) { removed[i].destroy(); } // remove all bindings this.removeAllBindings(); } if (value != null) { if (this.getModel() != null) { // add a binding for all elements in the model for (var i = 0; i < this.__lookupTable.length; i++) { this.__addItem(this.__lookup(i)); } } } }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event handler for the change event of the model. If the model changes, * Only the selection needs to be changed. The change of the data will * be done by the binding. */ __changeModel: function() { // need an asynchronous selection update because the bindings have to be // executed to update the selection probably (using the widget queue) // this.__syncTargetSelection = true; this.__syncModelSelection = true; qx.ui.core.queue.Widget.add(this); // update on filtered lists... (bindings need to be renewed) if (this.__lookupTable.length != this.getModel().getLength()) { this.update(); } }, /** * Internal method used to sync the selection. The controller uses the * widget queue to schedule the selection update. An asynchronous handling of * the selection is needed because the bindings (event listeners for the * binding) need to be executed before the selection is updated. * @internal */ syncWidget : function() { if (this.__syncTargetSelection) { this._changeTargetSelection(); } if (this.__syncModelSelection) { this._updateSelection(); } this.__syncModelSelection = this.__syncTargetSelection = null; }, /** * Event handler for the changeLength of the model. If the length changes * of the model, either ListItems need to be removed or added to the target. */ __changeModelLength: function() { // only do something if there is a target if (this.getTarget() == null) { return; } // build up the look up table this.__buildUpLookupTable(); // get the length var newLength = this.__lookupTable.length; var currentLength = this.getTarget().getChildren().length; // if there are more item if (newLength > currentLength) { // add the new elements for (var j = currentLength; j < newLength; j++) { this.__addItem(this.__lookup(j)); } // if there are less elements } else if (newLength < currentLength) { // remove the unnecessary items for (var j = currentLength; j > newLength; j--) { this.__removeItem(); } } // sync the target selection in case someone deleted a item in // selection mode "one" [BUG #4839] this.__syncTargetSelection = true; qx.ui.core.queue.Widget.add(this); }, /** * Helper method which removes and adds the change listener of the * controller to the model. This is sometimes necessary to ensure that the * listener of the controller is executed as the last listener of the chain. */ __moveChangeListenerAtTheEnd : function() { var model = this.getModel(); // it can be that the bindings has been reset without the model so // maybe there is no model in some scenarios if (model != null) { model.removeListenerById(this.__changeModelListenerId); this.__changeModelListenerId = model.addListener("change", this.__changeModel, this); } }, /* --------------------------------------------------------------------------- ITEM HANDLING --------------------------------------------------------------------------- */ /** * Creates a ListItem and delegates the configure method if a delegate is * set and the needed function (configureItem) is available. * * @return {qx.ui.form.ListItem} The created and configured ListItem. */ _createItem: function() { var delegate = this.getDelegate(); // check if a delegate and a create method is set if (delegate != null && delegate.createItem != null) { var item = delegate.createItem(); } else { var item = new qx.ui.form.ListItem(); } // if there is a configure method, invoke it if (delegate != null && delegate.configureItem != null) { delegate.configureItem(item); } return item; }, /** * Internal helper to add ListItems to the target including the creation * of the binding. * * @param index {Number} The index of the item to add. */ __addItem: function(index) { // create a new ListItem var listItem = this._createItem(); // set up the binding this._bindListItem(listItem, index); // add the ListItem to the target this.getTarget().add(listItem); }, /** * Internal helper to remove ListItems from the target. Also the binding * will be removed properly. */ __removeItem: function() { this._startSelectionModification(); var children = this.getTarget().getChildren(); // get the last binding id var index = children.length - 1; // get the item var oldItem = children[index]; this._removeBindingsFrom(oldItem); // remove the item this.getTarget().removeAt(index); oldItem.destroy(); this._endSelectionModification(); }, /** * Returns all models currently visible by the list. This method is only * useful if you use the filter via the {@link #delegate}. * * @return {qx.data.Array} A new data array container all the models * which representation items are currently visible. */ getVisibleModels : function() { var visibleModels = []; var target = this.getTarget(); if (target != null) { var items = target.getChildren(); for (var i = 0; i < items.length; i++) { visibleModels.push(items[i].getModel()); }; } return new qx.data.Array(visibleModels); }, /* --------------------------------------------------------------------------- BINDING STUFF --------------------------------------------------------------------------- */ /** * Sets up the binding for the given ListItem and index. * * @param item {qx.ui.form.ListItem} The internally created and used * ListItem. * @param index {Number} The index of the ListItem. */ _bindListItem: function(item, index) { var delegate = this.getDelegate(); // if a delegate for creating the binding is given, use it if (delegate != null && delegate.bindItem != null) { delegate.bindItem(this, item, index); // otherwise, try to bind the listItem by default } else { this.bindDefaultProperties(item, index); } }, /** * Helper-Method for binding the default properties (label, icon and model) * from the model to the target widget. * * This method should only be called in the * {@link qx.data.controller.IControllerDelegate#bindItem} function * implemented by the {@link #delegate} property. * * @param item {qx.ui.form.ListItem} The internally created and used * ListItem. * @param index {Number} The index of the ListItem. */ bindDefaultProperties : function(item, index) { // model this.bindProperty( "", "model", null, item, index ); // label this.bindProperty( this.getLabelPath(), "label", this.getLabelOptions(), item, index ); // if the iconPath is set if (this.getIconPath() != null) { this.bindProperty( this.getIconPath(), "icon", this.getIconOptions(), item, index ); } }, /** * Helper-Method for binding a given property from the model to the target * widget. * This method should only be called in the * {@link qx.data.controller.IControllerDelegate#bindItem} function * implemented by the {@link #delegate} property. * * @param sourcePath {String | null} The path to the property in the model. * If you use an empty string, the whole model item will be bound. * @param targetProperty {String} The name of the property in the target * widget. * @param options {Map | null} The options to use for the binding. * @param targetWidget {qx.ui.core.Widget} The target widget. * @param index {Number} The index of the current binding. */ bindProperty: function(sourcePath, targetProperty, options, targetWidget, index) { // create the options for the binding containing the old options // including the old onUpdate function if (options != null) { var options = qx.lang.Object.clone(options); this.__onUpdate[targetProperty] = options.onUpdate; delete options.onUpdate; } else { options = {}; this.__onUpdate[targetProperty] = null; } options.onUpdate = qx.lang.Function.bind(this._onBindingSet, this, index); // build up the path for the binding var bindPath = "model[" + index + "]"; if (sourcePath != null && sourcePath != "") { bindPath += "." + sourcePath; } // create the binding var id = this.bind(bindPath, targetWidget, targetProperty, options); targetWidget.setUserData(targetProperty + "BindingId", id); // save the bound property if (!qx.lang.Array.contains(this.__boundProperties, targetProperty)) { this.__boundProperties.push(targetProperty); } }, /** * Helper-Method for binding a given property from the target widget to * the model. * This method should only be called in the * {@link qx.data.controller.IControllerDelegate#bindItem} function * implemented by the {@link #delegate} property. * * @param targetPath {String | null} The path to the property in the model. * @param sourcePath {String} The name of the property in the target. * @param options {Map | null} The options to use for the binding. * @param sourceWidget {qx.ui.core.Widget} The source widget. * @param index {Number} The index of the current binding. */ bindPropertyReverse: function( targetPath, sourcePath, options, sourceWidget, index ) { // build up the path for the binding var targetBindPath = "model[" + index + "]"; if (targetPath != null && targetPath != "") { targetBindPath += "." + targetPath; } // create the binding var id = sourceWidget.bind(sourcePath, this, targetBindPath, options); sourceWidget.setUserData(targetPath + "ReverseBindingId", id); // save the bound property if (!qx.lang.Array.contains(this.__boundPropertiesReverse, targetPath)) { this.__boundPropertiesReverse.push(targetPath); } }, /** * Method which will be called on the invoke of every binding. It takes * care of the selection on the change of the binding. * * @param index {Number} The index of the current binding. * @param sourceObject {qx.core.Object} The source object of the binding. * @param targetObject {qx.core.Object} The target object of the binding. */ _onBindingSet: function(index, sourceObject, targetObject) { // ignore the binding set if the model is already set to null if (this.getModel() == null || this._inSelectionModification()) { return; } // go through all bound target properties for (var i = 0; i < this.__boundProperties.length; i++) { // if there is an onUpdate for one of it, invoke it if (this.__onUpdate[this.__boundProperties[i]] != null) { this.__onUpdate[this.__boundProperties[i]](); } } }, /** * Internal helper method to remove the binding of the given item. * * @param item {Number} The item of which the binding which should * be removed. */ _removeBindingsFrom: function(item) { // go through all bound target properties for (var i = 0; i < this.__boundProperties.length; i++) { // get the binding id and remove it, if possible var id = item.getUserData(this.__boundProperties[i] + "BindingId"); if (id != null) { this.removeBinding(id); } } // go through all reverse bound properties for (var i = 0; i < this.__boundPropertiesReverse.length; i++) { // get the binding id and remove it, if possible var id = item.getUserData( this.__boundPropertiesReverse[i] + "ReverseBindingId" ); if (id != null) { item.removeBinding(id); } }; }, /** * Internal helper method to renew all set bindings. */ __renewBindings: function() { // ignore, if no target is set (startup) if (this.getTarget() == null || this.getModel() == null) { return; } // get all children of the target var items = this.getTarget().getChildren(); // go through all items for (var i = 0; i < items.length; i++) { this._removeBindingsFrom(items[i]); // add the new binding this._bindListItem(items[i], this.__lookup(i)); } // move the controllers change handler for the model to the end of the // listeners queue this.__moveChangeListenerAtTheEnd(); }, /* --------------------------------------------------------------------------- DELEGATE HELPER --------------------------------------------------------------------------- */ /** * Helper method for applying the delegate It checks if a configureItem * is set end invokes the initial process to apply the given function. * * @param value {Object} The new delegate. * @param old {Object} The old delegate. */ _setConfigureItem: function(value, old) { if (value != null && value.configureItem != null && this.getTarget() != null) { var children = this.getTarget().getChildren(); for (var i = 0; i < children.length; i++) { value.configureItem(children[i]); } } }, /** * Helper method for applying the delegate It checks if a bindItem * is set end invokes the initial process to apply the given function. * * @param value {Object} The new delegate. * @param old {Object} The old delegate. */ _setBindItem: function(value, old) { // if a new bindItem function is set if (value != null && value.bindItem != null) { // do nothing if the bindItem function did not change if (old != null && old.bindItem != null && value.bindItem == old.bindItem) { return; } this.__renewBindings(); } }, /** * Helper method for applying the delegate It checks if a createItem * is set end invokes the initial process to apply the given function. * * @param value {Object} The new delegate. * @param old {Object} The old delegate. */ _setCreateItem: function(value, old) { if ( this.getTarget() == null || this.getModel() == null || value == null || value.createItem == null ) { return; } this._startSelectionModification(); // remove all bindings var children = this.getTarget().getChildren(); for (var i = 0, l = children.length; i < l; i++) { this._removeBindingsFrom(children[i]); } // remove all elements of the target var removed = this.getTarget().removeAll(); for (var i=0; i<removed.length; i++) { removed[i].destroy(); } // update this.update(); this._endSelectionModification(); this._updateSelection(); }, /** * Apply-Method for setting the filter. It removes all bindings, * check if the length has changed and adds or removes the items in the * target. After that, the bindings will be set up again and the selection * will be updated. * * @param value {Function|null} The new filter function. * @param old {Function|null} The old filter function. */ _setFilter: function(value, old) { // update the filter if it has been removed if ((value == null || value.filter == null) && (old != null && old.filter != null)) { this.__removeFilter(); } // check if it is necessary to do anything if ( this.getTarget() == null || this.getModel() == null || value == null || value.filter == null ) { return; } // if yes, continue this._startSelectionModification(); // remove all bindings var children = this.getTarget().getChildren(); for (var i = 0, l = children.length; i < l; i++) { this._removeBindingsFrom(children[i]); } // store the old lookup table var oldTable = this.__lookupTable; // generate a new lookup table this.__buildUpLookupTable(); // if there are lesser items if (oldTable.length > this.__lookupTable.length) { // remove the unnecessary items for (var j = oldTable.length; j > this.__lookupTable.length; j--) { this.getTarget().removeAt(j - 1).destroy(); } // if there are more items } else if (oldTable.length < this.__lookupTable.length) { // add the new elements for (var j = oldTable.length; j < this.__lookupTable.length; j++) { var tempItem = this._createItem(); this.getTarget().add(tempItem); } } // bind every list item again var listItems = this.getTarget().getChildren(); for (var i = 0; i < listItems.length; i++) { this._bindListItem(listItems[i], this.__lookup(i)); } // move the controllers change handler for the model to the end of the // listeners queue this.__moveChangeListenerAtTheEnd(); this._endSelectionModification(); this._updateSelection(); }, /** * This helper is responsible for removing the filter and setting the * controller to a valid state without a filtering. */ __removeFilter : function() { // renew the index lookup table this.__buildUpLookupTable(); // check for the new length this.__changeModelLength(); // renew the bindings this.__renewBindings(); // need an asynchronous selection update because the bindings have to be // executed to update the selection probably (using the widget queue) this.__syncModelSelection = true; qx.ui.core.queue.Widget.add(this); }, /* --------------------------------------------------------------------------- LOOKUP STUFF --------------------------------------------------------------------------- */ /** * Helper-Method which builds up the index lookup for the filter feature. * If no filter is set, the lookup table will be a 1:1 mapping. */ __buildUpLookupTable: function() { var model = this.getModel(); if (model == null) { return; } var delegate = this.getDelegate(); if (delegate != null) { var filter = delegate.filter; } this.__lookupTable = []; for (var i = 0; i < model.getLength(); i++) { if (filter == null || filter(model.getItem(i))) { this.__lookupTable.push(i); } } }, /** * Function for accessing the lookup table. * * @param index {Integer} The index of the lookup table. */ __lookup: function(index) { return this.__lookupTable[index]; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__lookupTable = this.__onUpdate = this.__boundProperties = null; this.__boundPropertiesReverse = null; // remove yourself from the widget queue qx.ui.core.queue.Widget.remove(this); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>Form Controller</h2> * * *General idea* * * The form controller is responsible for connecting a form with a model. If no * model is given, a model can be created. This created model will fit exactly * to the given form and can be used for serialization. All the connections * between the form items and the model are handled by an internal * {@link qx.data.controller.Object}. * * *Features* * * * Connect a form to a model (bidirectional) * * Create a model for a given form * * *Usage* * * The controller only works if both a controller and a model are set. * Creating a model will automatically set the created model. * * *Cross reference* * * * If you want to bind single values, use {@link qx.data.controller.Object} * * If you want to bind a list like widget, use {@link qx.data.controller.List} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} */ qx.Class.define("qx.data.controller.Form", { extend : qx.core.Object, /** * @param model {qx.core.Object | null} The model to bind the target to. The * given object will be set as {@link #model} property. * @param target {qx.ui.form.Form | null} The form which contains the form * items. The given form will be set as {@link #target} property. * @param selfUpdate {Boolean?false} If set to true, you need to call the * {@link #updateModel} method to get the data in the form to the model. * Otherwise, the data will be synced automatically on every change of * the form. */ construct : function(model, target, selfUpdate) { this.base(arguments); this._selfUpdate = !!selfUpdate; this.__bindingOptions = {}; if (model != null) { this.setModel(model); } if (target != null) { this.setTarget(target); } }, properties : { /** Data object containing the data which should be shown in the target. */ model : { check: "qx.core.Object", apply: "_applyModel", event: "changeModel", nullable: true, dereference: true }, /** The target widget which should show the data. */ target : { check: "qx.ui.form.Form", apply: "_applyTarget", event: "changeTarget", nullable: true, init: null, dereference: true } }, members : { __objectController : null, __bindingOptions : null, /** * The form controller uses for setting up the bindings the fundamental * binding layer, the {@link qx.data.SingleValueBinding}. To achieve a * binding in both directions, two bindings are neede. With this method, * you have the opportunity to set the options used for the bindings. * * @param name {String} The name of the form item for which the options * should be used. * @param model2target {Map} Options map used for the binding from model * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * @param target2model {Map} Options map used for the binding from target * to model. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ addBindingOptions : function(name, model2target, target2model) { this.__bindingOptions[name] = [model2target, target2model]; // return if not both, model and target are given if (this.getModel() == null || this.getTarget() == null) { return; } // renew the affected binding var item = this.getTarget().getItems()[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; // remove the binding this.__objectController.removeTarget(item, targetProperty, name); // set up the new binding with the options this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, model2target, target2model ); }, /** * Creates and sets a model using the {@link qx.data.marshal.Json} object. * Remember that this method can only work if the form is set. The created * model will fit exactly that form. Changing the form or adding an item to * the form will need a new model creation. * * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. * @return {qx.core.Object} The created model. */ createModel : function(includeBubbleEvents) { var target = this.getTarget(); // throw an error if no target is set if (target == null) { throw new Error("No target is set."); } var items = target.getItems(); var data = {}; for (var name in items) { var names = name.split("."); var currentData = data; for (var i = 0; i < names.length; i++) { // if its the last item if (i + 1 == names.length) { // check if the target is a selection var clazz = items[name].constructor; var itemValue = null; if (qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection)) { // use the first element of the selection because passed to the // marshaler (and its single selection anyway) [BUG #3541] itemValue = items[name].getModelSelection().getItem(0) || null; } else { itemValue = items[name].getValue(); } // call the converter if available [BUG #4382] if (this.__bindingOptions[name] && this.__bindingOptions[name][1]) { itemValue = this.__bindingOptions[name][1].converter(itemValue); } currentData[names[i]] = itemValue; } else { // if its not the last element, check if the object exists if (!currentData[names[i]]) { currentData[names[i]] = {}; } currentData = currentData[names[i]]; } } } var model = qx.data.marshal.Json.createModel(data, includeBubbleEvents); this.setModel(model); return model; }, /** * Responsible for synching the data from entered in the form to the model. * Please keep in mind that this method only works if you create the form * with <code>selfUpdate</code> set to true. Otherwise, this method will * do nothing because updates will be synched automatically on every * change. */ updateModel: function(){ // only do stuff if self update is enabled and a model or target is set if (!this._selfUpdate || !this.getModel() || !this.getTarget()) { return; } var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var sourceProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; options = options && this.__bindingOptions[name][1]; qx.data.SingleValueBinding.updateTarget( item, sourceProperty, this.getModel(), name, options ); } }, // apply method _applyTarget : function(value, old) { // if an old target is given, remove the binding if (old != null) { this.__tearDownBinding(old); } // do nothing if no target is set if (this.getModel() == null) { return; } // target and model are available if (value != null) { this.__setUpBinding(); } }, // apply method _applyModel : function(value, old) { // first, get rid off all bindings (avoids whong data population) if (this.__objectController != null) { var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } } // set the model of the object controller if available if (this.__objectController != null) { this.__objectController.setModel(value); } // do nothing is no target is set if (this.getTarget() == null) { return; } // model and target are available if (value != null) { this.__setUpBinding(); } }, /** * Internal helper for setting up the bindings using * {@link qx.data.controller.Object#addTarget}. All bindings are set * up bidirectional. */ __setUpBinding : function() { // create the object controller if (this.__objectController == null) { this.__objectController = new qx.data.controller.Object(this.getModel()); } // get the form items var items = this.getTarget().getItems(); // connect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; // try to bind all given items in the form try { if (options == null) { this.__objectController.addTarget(item, targetProperty, name, !this._selfUpdate); } else { this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, options[0], options[1] ); } // ignore not working items } catch (ex) { if (qx.core.Environment.get("qx.debug")) { this.warn("Could not bind property " + name + " of " + this.getModel()); } } } // make sure the initial values of the model are taken for resetting [BUG #5874] this.getTarget().redefineResetter(); }, /** * Internal helper for removing all set up bindings using * {@link qx.data.controller.Object#removeTarget}. * * @param oldTarget {qx.ui.form.Form} The form which has been removed. */ __tearDownBinding : function(oldTarget) { // do nothing if the object controller has not been created if (this.__objectController == null) { return; } // get the items var items = oldTarget.getItems(); // disconnect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } }, /** * Returns whether the given item implements * {@link qx.ui.core.ISingleSelection} and * {@link qx.ui.form.IModelSelection}. * * @param item {qx.ui.form.IForm} The form item to check. * * @return {true} true, if given item fits. */ __isModelSelectable : function(item) { return qx.Class.hasInterface(item.constructor, qx.ui.core.ISingleSelection) && qx.Class.hasInterface(item.constructor, qx.ui.form.IModelSelection); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // dispose the object controller because the bindings need to be removed if (this.__objectController) { this.__objectController.dispose(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Defines the methods needed by every marshaler which should work with the * qooxdoo data stores. */ qx.Interface.define("qx.data.marshal.IMarshaler", { members : { /** * Creates for the given data the needed classes. The classes contain for * every key in the data a property. The classname is always the prefix * <code>qx.data.model</code>. Two objects containing the same keys will not * create two different classes. * * @param data {Object} The object for which classes should be created. * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. */ toClass : function(data, includeBubbleEvents) {}, /** * Creates for the given data the needed models. Be sure to have the classes * created with {@link #toClass} before calling this method. * * @param data {Object} The object for which models should be created. * * @return {qx.core.Object} The created model object. */ toModel : function(data) {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for converting json data to class instances * including the creation of the classes. */ qx.Class.define("qx.data.marshal.Json", { extend : qx.core.Object, implement : [qx.data.marshal.IMarshaler], /** * @param delegate {Object} An object containing one of the methods described * in {@link qx.data.marshal.IMarshalerDelegate}. */ construct : function(delegate) { this.base(arguments); this.__delegate = delegate; }, statics : { $$instance : null, /** * Creates a qooxdoo object based on the given json data. This function * is just a static wrapper. If you want to configure the creation * process of the class, use {@link qx.data.marshal.Json} directly. * * @param data {Object} The object for which classes should be created. * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. * * @return {qx.core.Object} An instance of the corresponding class. */ createModel : function(data, includeBubbleEvents) { // singleton for the json marshaler if (this.$$instance === null) { this.$$instance = new qx.data.marshal.Json(); } // be sure to create the classes first this.$$instance.toClass(data, includeBubbleEvents); // return the model return this.$$instance.toModel(data); } }, members : { __delegate : null, /** * Converts a given object into a hash which will be used to identify the * classes under the namespace <code>qx.data.model</code>. * * @param data {Object} The JavaScript object from which the hash is * required. * @return {String} The hash representation of the given JavaScript object. */ __jsonToHash: function(data) { return qx.Bootstrap.getKeys(data).sort().join('"'); }, /** * Creates for the given data the needed classes. The classes contain for * every key in the data a property. The classname is always the prefix * <code>qx.data.model</code> and the hash of the data created by * {@link #__jsonToHash}. Two objects containing the same keys will not * create two different classes. The class creation process also supports * the functions provided by its delegate. * * Important, please keep in mind that only valid JavaScript identifiers * can be used as keys in the data map. For convenience '-' in keys will * be removed (a-b will be ab in the end). * * @see qx.data.store.IStoreDelegate * * @param data {Object} The object for which classes should be created. * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. */ toClass: function(data, includeBubbleEvents) { // break on all primitive json types and qooxdoo objects if ( !qx.lang.Type.isObject(data) || !!data.$$isString // check for localized strings || data instanceof qx.core.Object ) { // check for arrays if (data instanceof Array || qx.Bootstrap.getClass(data) == "Array") { for (var i = 0; i < data.length; i++) { this.toClass(data[i], includeBubbleEvents); } } // ignore arrays and primitive types return; } var hash = this.__jsonToHash(data); // check for the possible child classes for (var key in data) { this.toClass(data[key], includeBubbleEvents); } // class already exists if (qx.Class.isDefined("qx.data.model." + hash)) { return; } // class is defined by the delegate if ( this.__delegate && this.__delegate.getModelClass && this.__delegate.getModelClass(hash) != null ) { return; } // create the properties map var properties = {}; // include the disposeItem for the dispose process. var members = {__disposeItem : this.__disposeItem}; for (var key in data) { // apply the property names mapping if (this.__delegate && this.__delegate.getPropertyMapping) { key = this.__delegate.getPropertyMapping(key, hash); } // stip the unwanted characters key = key.replace(/-|\.|\s+/g, ""); // check for valid JavaScript identifier (leading numbers are ok) if (qx.core.Environment.get("qx.debug")) { this.assertTrue((/^[$0-9A-Za-z_]*$/).test(key), "The key '" + key + "' is not a valid JavaScript identifier.") } properties[key] = {}; properties[key].nullable = true; properties[key].event = "change" + qx.lang.String.firstUp(key); // bubble events if (includeBubbleEvents) { properties[key].apply = "_applyEventPropagation"; } // validation rules if (this.__delegate && this.__delegate.getValidationRule) { var rule = this.__delegate.getValidationRule(hash, key); if (rule) { properties[key].validate = "_validate" + key; members["_validate" + key] = rule; } } } // try to get the superclass, qx.core.Object as default if (this.__delegate && this.__delegate.getModelSuperClass) { var superClass = this.__delegate.getModelSuperClass(hash) || qx.core.Object; } else { var superClass = qx.core.Object; } // try to get the mixins var mixins = []; if (this.__delegate && this.__delegate.getModelMixins) { var delegateMixins = this.__delegate.getModelMixins(hash); // check if its an array if (!qx.lang.Type.isArray(delegateMixins)) { if (delegateMixins != null) { mixins = [delegateMixins]; } } else { mixins = delegateMixins; } } // include the mixin for the event bubbling if (includeBubbleEvents) { mixins.push(qx.data.marshal.MEventBubbling); } // create the map for the class var newClass = { extend : superClass, include : mixins, properties : properties, members : members, destruct : this.__disposeProperties }; qx.Class.define("qx.data.model." + hash, newClass); }, /** * Destructor for all created classes which disposes all stuff stored in * the properties. */ __disposeProperties : function() { var properties = qx.util.PropertyUtil.getAllProperties(this.constructor); for (var desc in properties) { this.__disposeItem(this.get(properties[desc].name)); }; }, /** * Helper for disposing items of the created class. * * @param item {var} The item to dispose. */ __disposeItem : function(item) { if (!(item instanceof qx.core.Object)) { // ignore all non objects return; } // ignore already disposed items (could happen during shutdown) if (item.isDisposed()) { return; } item.dispose(); }, /** * Creates an instance for the given data hash. * * @param hash {String} The hash of the data for which an instance should * be created. * @return {qx.core.Object} An instance of the corresponding class. */ __createInstance: function(hash) { var delegateClass; // get the class from the delegate if (this.__delegate && this.__delegate.getModelClass) { delegateClass = this.__delegate.getModelClass(hash); } if (delegateClass != null) { return (new delegateClass()); } else { var clazz = qx.Class.getByName("qx.data.model." + hash); return (new clazz()); } }, /** * Creates for the given data the needed models. Be sure to have the classes * created with {@link #toClass} before calling this method. The creation * of the class itself is delegated to the {@link #__createInstance} method, * which could use the {@link qx.data.store.IStoreDelegate} methods, if * given. * * @param data {Object} The object for which models should be created. * * @return {qx.core.Object} The created model object. */ toModel: function(data) { var isObject = qx.lang.Type.isObject(data); var isArray = data instanceof Array || qx.Bootstrap.getClass(data) == "Array"; if ( (!isObject && !isArray) || !!data.$$isString // check for localized strings || data instanceof qx.core.Object ) { return data; } else if (isArray) { var array = new qx.data.Array(); // set the auto dispose for the array array.setAutoDisposeItems(true); for (var i = 0; i < data.length; i++) { array.push(this.toModel(data[i])); } return array; } else if (isObject) { // create an instance for the object var hash = this.__jsonToHash(data); var model = this.__createInstance(hash); // go threw all element in the data for (var key in data) { // apply the property names mapping var propertyName = key; if (this.__delegate && this.__delegate.getPropertyMapping) { propertyName = this.__delegate.getPropertyMapping(key, hash); } var propertyNameReplaced = propertyName.replace(/-|\.|\s+/g, ""); // warn if there has been a replacement if ( (qx.core.Environment.get("qx.debug")) && qx.core.Environment.get("qx.debug.databinding") ) { if (propertyNameReplaced != propertyName) { this.warn( "The model contained an illegal name: '" + key + "'. Replaced it with '" + propertyName + "'." ); } } propertyName = propertyNameReplaced; // only set the properties if they are available [BUG #5909] var setterName = "set" + qx.lang.String.firstUp(propertyName); if (model[setterName]) { model[setterName](this.toModel(data[key])); } } return model; } throw new Error("Unsupported type!"); } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__delegate = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>Object Controller</h2> * * *General idea* * * The idea of the object controller is to make the binding of one model object * containing one or more properties as easy as possible. Therefore the * controller can take a model as property. Every property in that model can be * bound to one or more target properties. The binding will be for * atomic types only like Numbers, Strings, ... * * *Features* * * * Manages the bindings between the model properties and the different targets * * No need for the user to take care of the binding ids * * Can create an bidirectional binding (read- / write-binding) * * Handles the change of the model which means adding the old targets * * *Usage* * * The controller only can work if a model is set. If the model property is * null, the controller is not working. But it can be null on any time. * * *Cross reference* * * * If you want to bind a list like widget, use {@link qx.data.controller.List} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} * * If you want to bind a form widget, use {@link qx.data.controller.Form} */ qx.Class.define("qx.data.controller.Object", { extend : qx.core.Object, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param model {qx.core.Object?null} The model for the model property. */ construct : function(model) { this.base(arguments); // create a map for all created binding ids this.__bindings = {}; // create an array to store all current targets this.__targets = []; if (model != null) { this.setModel(model); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** The model object which does have the properties for the binding. */ model : { check: "qx.core.Object", event: "changeModel", apply: "_applyModel", nullable: true, dereference: true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // private members __targets : null, __bindings : null, /** * Apply-method which will be called if a new model has been set. * All bindings will be moved to the new model. * * @param value {qx.core.Object|null} The new model. * @param old {qx.core.Object|null} The old model. */ _applyModel: function(value, old) { // for every target for (var i = 0; i < this.__targets.length; i++) { // get the properties var targetObject = this.__targets[i][0]; var targetProperty = this.__targets[i][1]; var sourceProperty = this.__targets[i][2]; var bidirectional = this.__targets[i][3]; var options = this.__targets[i][4]; var reverseOptions = this.__targets[i][5]; // remove it from the old if possible if (old != undefined && !old.isDisposed()) { this.__removeTargetFrom(targetObject, targetProperty, sourceProperty, old); } // add it to the new if available if (value != undefined) { this.__addTarget( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ); } else { // in shutdown situations, it may be that something is already // disposed [BUG #4343] if (targetObject.isDisposed() || qx.core.ObjectRegistry.inShutDown) { continue; } // if the model is null, reset the current target if (targetProperty.indexOf("[") == -1) { targetObject["reset" + qx.lang.String.firstUp(targetProperty)](); } else { var open = targetProperty.indexOf("["); var index = parseInt( targetProperty.substring(open + 1, targetProperty.length - 1), 10 ); targetProperty = targetProperty.substring(0, open); var targetArray = targetObject["get" + qx.lang.String.firstUp(targetProperty)](); if (index == "last") { index = targetArray.length; } if (targetArray) { targetArray.setItem(index, null); } } } } }, /** * Adds a new target to the controller. After adding the target, the given * property of the model will be bound to the targets property. * * @param targetObject {qx.core.Object} The object on which the property * should be bound. * * @param targetProperty {String} The property to which the binding should * go. * * @param sourceProperty {String} The name of the property in the model. * * @param bidirectional {Boolean?false} Signals if the binding should also work * in the reverse direction, from the target to source. * * @param options {Map?null} The options Map used by the binding from source * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * * @param reverseOptions {Map?null} The options used by the binding in the * reverse direction. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ addTarget: function( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ) { // store the added target this.__targets.push([ targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ]); // delegate the adding this.__addTarget( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ); }, /** * Does the work for {@link #addTarget} but without saving the target * to the internal target registry. * * @param targetObject {qx.core.Object} The object on which the property * should be bound. * * @param targetProperty {String} The property to which the binding should * go. * * @param sourceProperty {String} The name of the property in the model. * * @param bidirectional {Boolean?false} Signals if the binding should also work * in the reverse direction, from the target to source. * * @param options {Map?null} The options Map used by the binding from source * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * * @param reverseOptions {Map?null} The options used by the binding in the * reverse direction. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ __addTarget: function( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ) { // do nothing if no model is set if (this.getModel() == null) { return; } // create the binding var id = this.getModel().bind( sourceProperty, targetObject, targetProperty, options ); // create the reverse binding if necessary var idReverse = null if (bidirectional) { idReverse = targetObject.bind( targetProperty, this.getModel(), sourceProperty, reverseOptions ); } // save the binding var targetHash = targetObject.toHashCode(); if (this.__bindings[targetHash] == undefined) { this.__bindings[targetHash] = []; } this.__bindings[targetHash].push( [id, idReverse, targetProperty, sourceProperty, options, reverseOptions] ); }, /** * Removes the target identified by the three properties. * * @param targetObject {qx.core.Object} The target object on which the * binding exist. * * @param targetProperty {String} The targets property name used by the * adding of the target. * * @param sourceProperty {String} The name of the property of the model. */ removeTarget: function(targetObject, targetProperty, sourceProperty) { this.__removeTargetFrom( targetObject, targetProperty, sourceProperty, this.getModel() ); // delete the target in the targets reference for (var i = 0; i < this.__targets.length; i++) { if ( this.__targets[i][0] == targetObject && this.__targets[i][1] == targetProperty && this.__targets[i][2] == sourceProperty ) { this.__targets.splice(i, 1); } } }, /** * Does the work for {@link #removeTarget} but without removing the target * from the internal registry. * * @param targetObject {qx.core.Object} The target object on which the * binding exist. * * @param targetProperty {String} The targets property name used by the * adding of the target. * * @param sourceProperty {String} The name of the property of the model. * * @param sourceObject {String} The source object from which the binding * comes. */ __removeTargetFrom: function( targetObject, targetProperty, sourceProperty, sourceObject ) { // check for not fitting targetObjects if (!(targetObject instanceof qx.core.Object)) { // just do nothing return; } var currentListing = this.__bindings[targetObject.toHashCode()]; // if no binding is stored if (currentListing == undefined || currentListing.length == 0) { return; } // go threw all listings for the object for (var i = 0; i < currentListing.length; i++) { // if it is the listing if ( currentListing[i][2] == targetProperty && currentListing[i][3] == sourceProperty ) { // remove the binding var id = currentListing[i][0]; sourceObject.removeBinding(id); // check for the reverse binding if (currentListing[i][1] != null) { targetObject.removeBinding(currentListing[i][1]); } // delete the entry and return currentListing.splice(i, 1); return; } } } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { // set the model to null to get the bindings removed if (this.getModel() != null && !this.getModel().isDisposed()) { this.setModel(null); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * Tango icons */ qx.Theme.define("qx.theme.icon.Tango", { title : "Tango", aliases : { "icon" : "qx/icon/Tango" } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A very complex decoration using two, partly combined and clipped images * to render a graphically impressive borders with gradients. * * The decoration supports all forms of vertical gradients. The gradients must * be stretchable to support different heights. * * The edges could use different styles of rounded borders. Even different * edge sizes are supported. The sizes are automatically detected by * the build system using the image meta data. * * The decoration uses clipped images to reduce the number of external * resources to load. */ qx.Class.define("qx.ui.decoration.Grid", { extend: qx.core.Object, implement : [qx.ui.decoration.IDecorator], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param baseImage {String} Base image to use * @param insets {Integer|Array} Insets for the grid */ construct : function(baseImage, insets) { this.base(arguments); if (qx.ui.decoration.css3.BorderImage.IS_SUPPORTED) { this.__impl = new qx.ui.decoration.css3.BorderImage(); if (baseImage) { this.__setBorderImage(baseImage); } } else { this.__impl = new qx.ui.decoration.GridDiv(baseImage); } if (insets != null) { this.__impl.setInsets(insets); } // ignore the internal used implementation in the dispose debugging [BUG #5343] if (qx.core.Environment.get("qx.debug.dispose")) { this.__impl.$$ignoreDisposeWarning = true; } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Base image URL. There must be an image with this name and the sliced * and the nine sliced images. The sliced images must be named according to * the following scheme: * * ${baseImageWithoutExtension}-${imageName}.${baseImageExtension} * * These image names are used: * * * tl (top-left edge) * * t (top side) * * tr (top-right edge) * * bl (bottom-left edge) * * b (bottom side) * * br (bottom-right edge) * * * l (left side) * * c (center image) * * r (right side) */ baseImage : { check : "String", nullable : true, apply : "_applyBaseImage" }, /** Width of the left inset (keep this margin to the outer box) */ insetLeft : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Width of the right inset (keep this margin to the outer box) */ insetRight : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Width of the bottom inset (keep this margin to the outer box) */ insetBottom : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Width of the top inset (keep this margin to the outer box) */ insetTop : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Property group for insets */ insets : { group : [ "insetTop", "insetRight", "insetBottom", "insetLeft" ], mode : "shorthand" }, /** Width of the left slice */ sliceLeft : { check : "Number", nullable: true, apply : "_applySlices" }, /** Width of the right slice */ sliceRight : { check : "Number", nullable: true, apply : "_applySlices" }, /** Width of the bottom slice */ sliceBottom : { check : "Number", nullable: true, apply : "_applySlices" }, /** Width of the top slice */ sliceTop : { check : "Number", nullable: true, apply : "_applySlices" }, /** Property group for slices */ slices : { group : [ "sliceTop", "sliceRight", "sliceBottom", "sliceLeft" ], mode : "shorthand" }, /** Only used for the CSS3 implementation, see {@link qx.ui.decoration.css3.BorderImage#fill} **/ fill : { apply : "_applyFill" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __impl : null, // interface implementation getMarkup : function() { return this.__impl.getMarkup(); }, // interface implementation resize : function(element, width, height) { this.__impl.resize(element, width, height); }, // interface implementation tint : function(element, bgcolor) { // do nothing }, // interface implementation getInsets : function() { return this.__impl.getInsets(); }, // property apply _applyInsets : function(value, old, name) { var setter = "set" + qx.lang.String.firstUp(name); this.__impl[setter](value); }, // property apply _applySlices : function(value, old, name) { var setter = "set" + qx.lang.String.firstUp(name); // The GridDiv implementation doesn't have slice properties, // slices are obtained from the sizes of the images instead if (this.__impl[setter]) { this.__impl[setter](value); } }, //property apply _applyFill : function(value, old, name) { if (this.__impl.setFill) { this.__impl.setFill(value); } }, // property apply _applyBaseImage : function(value, old) { if (this.__impl instanceof qx.ui.decoration.GridDiv) { this.__impl.setBaseImage(value); } else { this.__setBorderImage(value); } }, /** * Configures the border image decorator * * @param baseImage {String} URL of the base image */ __setBorderImage : function(baseImage) { this.__impl.setBorderImage(baseImage); var base = qx.util.AliasManager.getInstance().resolve(baseImage); var split = /(.*)(\.[a-z]+)$/.exec(base); var prefix = split[1]; var ext = split[2]; var ResourceManager = qx.util.ResourceManager.getInstance(); var topSlice = ResourceManager.getImageHeight(prefix + "-t" + ext); var rightSlice = ResourceManager.getImageWidth(prefix + "-r" + ext); var bottomSlice = ResourceManager.getImageHeight(prefix + "-b" + ext); var leftSlice = ResourceManager.getImageWidth(prefix + "-l" + ext); if (qx.core.Environment.get("qx.debug") && !this.__impl instanceof qx.ui.decoration.css3.BorderImage) { var assertMessageTop = "The value of the property 'topSlice' is null! " + "Please verify the image '" + prefix + "-t" + ext + "' is present."; var assertMessageRight = "The value of the property 'rightSlice' is null! " + "Please verify the image '" + prefix + "-r" + ext + "' is present."; var assertMessageBottom = "The value of the property 'bottomSlice' is null! " + "Please verify the image '" + prefix + "-b" + ext + "' is present."; var assertMessageLeft = "The value of the property 'leftSlice' is null! " + "Please verify the image '" + prefix + "-l" + ext + "' is present."; qx.core.Assert.assertNotNull(topSlice, assertMessageTop); qx.core.Assert.assertNotNull(rightSlice, assertMessageRight); qx.core.Assert.assertNotNull(bottomSlice, assertMessageBottom); qx.core.Assert.assertNotNull(leftSlice, assertMessageLeft); } if (topSlice && rightSlice && bottomSlice && leftSlice) { this.__impl.setSlice([topSlice, rightSlice, bottomSlice, leftSlice]); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__impl.dispose(); this.__impl = null; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Decorator, which uses the CSS3 border image properties. * * This decorator can be used as replacement for {@link qx.ui.layout.Grid}, * {@link qx.ui.layout.HBox} and {@link qx.ui.layout.VBox} decorators in * browsers, which support it. * * Supported browsers are: * <ul> * <li>Firefox >= 3.5</li> * <li>Safari >= 4</li> * <li>Chrome >= 3</li> * <ul> */ qx.Class.define("qx.ui.decoration.css3.BorderImage", { extend : qx.ui.decoration.Abstract, /** * @param borderImage {String} Base image to use * @param slice {Integer|Array} Sets the {@link #slice} property */ construct : function(borderImage, slice) { this.base(arguments); // Initialize properties if (borderImage != null) { this.setBorderImage(borderImage); } if (slice != null) { this.setSlice(slice); } }, statics : { /** * Whether the browser supports this decorator */ IS_SUPPORTED : qx.bom.element.Style.isPropertySupported("borderImage") }, properties : { /** * Base image URL. */ borderImage : { check : "String", nullable : true, apply : "_applyStyle" }, /** * The top slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceTop : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The right slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceRight : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The bottom slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceBottom : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The left slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceLeft : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The slice properties divide the image into nine regions, which define the * corner, edge and the center images. */ slice : { group : [ "sliceTop", "sliceRight", "sliceBottom", "sliceLeft" ], mode : "shorthand" }, /** * This property specifies how the images for the sides and the middle part * of the border image are scaled and tiled horizontally. * * Values have the following meanings: * <ul> * <li><strong>stretch</strong>: The image is stretched to fill the area.</li> * <li><strong>repeat</strong>: The image is tiled (repeated) to fill the area.</li> * <li><strong>round</strong>: The image is tiled (repeated) to fill the area. If it does not * fill the area with a whole number of tiles, the image is rescaled so * that it does.</li> * </ul> */ repeatX : { check : ["stretch", "repeat", "round"], init : "stretch", apply : "_applyStyle" }, /** * This property specifies how the images for the sides and the middle part * of the border image are scaled and tiled vertically. * * Values have the following meanings: * <ul> * <li><strong>stretch</strong>: The image is stretched to fill the area.</li> * <li><strong>repeat</strong>: The image is tiled (repeated) to fill the area.</li> * <li><strong>round</strong>: The image is tiled (repeated) to fill the area. If it does not * fill the area with a whole number of tiles, the image is rescaled so * that it does.</li> * </ul> */ repeatY : { check : ["stretch", "repeat", "round"], init : "stretch", apply : "_applyStyle" }, /** * This property specifies how the images for the sides and the middle part * of the border image are scaled and tiled. */ repeat : { group : ["repeatX", "repeatY"], mode : "shorthand" }, /** * If set to <code>false</code>, the center image will be omitted and only * the border will be drawn. */ fill : { check : "Boolean", init : true } }, members : { __markup : null, // overridden _getDefaultInsets : function() { return { top : 0, right : 0, bottom : 0, left : 0 }; }, // overridden _isInitialized: function() { return !!this.__markup; }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this.__markup) { return this.__markup; } var source = this._resolveImageUrl(this.getBorderImage()); var slice = [ this.getSliceTop(), this.getSliceRight(), this.getSliceBottom(), this.getSliceLeft() ]; var repeat = [ this.getRepeatX(), this.getRepeatY() ].join(" ") var fill = this.getFill() && qx.core.Environment.get("css.borderimage.standardsyntax") ? " fill" : ""; this.__markup = [ "<div style='", qx.bom.element.Style.compile({ "borderImage" : 'url("' + source + '") ' + slice.join(" ") + fill + " " + repeat, "borderStyle" : "solid", "borderColor" : "transparent", position: "absolute", lineHeight: 0, fontSize: 0, overflow: "hidden", boxSizing: "border-box", borderWidth: slice.join("px ") + "px" }), ";'></div>" ].join(""); // Store return this.__markup; }, // interface implementation resize : function(element, width, height) { element.style.width = width + "px"; element.style.height = height + "px"; }, // interface implementation tint : function(element, bgcolor) { // not implemented }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyStyle : function(value, old, name) { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } }, /** * Resolve the url of the given image * * @param image {String} base image URL * @return {String} the resolved image URL */ _resolveImageUrl : function(image) { return qx.util.ResourceManager.getInstance().toUri( qx.util.AliasManager.getInstance().resolve(image) ); } }, destruct : function() { this.__markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A very complex decoration using two, partly combined and clipped images * to render a graphically impressive borders with gradients. * * The decoration supports all forms of vertical gradients. The gradients must * be stretchable to support different heights. * * The edges could use different styles of rounded borders. Even different * edge sizes are supported. The sizes are automatically detected by * the build system using the image meta data. * * The decoration uses clipped images to reduce the number of external * resources to load. */ qx.Class.define("qx.ui.decoration.GridDiv", { extend : qx.ui.decoration.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param baseImage {String} Base image to use * @param insets {Integer|Array} Insets for the grid */ construct : function(baseImage, insets) { this.base(arguments); // Initialize properties if (baseImage != null) { this.setBaseImage(baseImage); } if (insets != null) { this.setInsets(insets); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Base image URL. All the different images needed are named by the default * naming scheme: * * ${baseImageWithoutExtension}-${imageName}.${baseImageExtension} * * These image names are used: * * * tl (top-left edge) * * t (top side) * * tr (top-right edge) * * bl (bottom-left edge) * * b (bottom side) * * br (bottom-right edge) * * * l (left side) * * c (center image) * * r (right side) */ baseImage : { check : "String", nullable : true, apply : "_applyBaseImage" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { _markup : null, _images : null, _edges : null, // overridden _getDefaultInsets : function() { return { top : 0, right : 0, bottom : 0, left : 0 }; }, // overridden _isInitialized: function() { return !!this._markup; }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this._markup) { return this._markup; } var Decoration = qx.bom.element.Decoration; var images = this._images; var edges = this._edges; // Create edges and vertical sides // Order: tl, t, tr, bl, b, bt, l, c, r var html = []; // Outer frame // Note: Overflow=hidden is needed for Safari 3.1 to omit scrolling through // dragging when the cursor is in the text field in Spinners etc. html.push('<div style="position:absolute;top:0;left:0;overflow:hidden;font-size:0;line-height:0;">'); // Top: left, center, right html.push(Decoration.create(images.tl, "no-repeat", { top: 0, left: 0 })); html.push(Decoration.create(images.t, "scale-x", { top: 0, left: edges.left + "px" })); html.push(Decoration.create(images.tr, "no-repeat", { top: 0, right : 0 })); // Bottom: left, center, right html.push(Decoration.create(images.bl, "no-repeat", { bottom: 0, left:0 })); html.push(Decoration.create(images.b, "scale-x", { bottom: 0, left: edges.left + "px" })); html.push(Decoration.create(images.br, "no-repeat", { bottom: 0, right: 0 })); // Middle: left, center, right html.push(Decoration.create(images.l, "scale-y", { top: edges.top + "px", left: 0 })); html.push(Decoration.create(images.c, "scale", { top: edges.top + "px", left: edges.left + "px" })); html.push(Decoration.create(images.r, "scale-y", { top: edges.top + "px", right: 0 })); // Outer frame html.push('</div>'); // Store return this._markup = html.join(""); }, // interface implementation resize : function(element, width, height) { // Compute inner sizes var edges = this._edges; var innerWidth = width - edges.left - edges.right; var innerHeight = height - edges.top - edges.bottom; // Set the inner width or height to zero if negative if (innerWidth < 0) {innerWidth = 0;} if (innerHeight < 0) {innerHeight = 0;} // Update nodes element.style.width = width + "px"; element.style.height = height + "px"; element.childNodes[1].style.width = innerWidth + "px"; element.childNodes[4].style.width = innerWidth + "px"; element.childNodes[7].style.width = innerWidth + "px"; element.childNodes[6].style.height = innerHeight + "px"; element.childNodes[7].style.height = innerHeight + "px"; element.childNodes[8].style.height = innerHeight + "px"; if ((qx.core.Environment.get("engine.name") == "mshtml")) { // Internet Explorer as of version 6 or version 7 in quirks mode // have rounding issues when working with odd dimensions: // right and bottom positioned elements are rendered with a // one pixel negative offset which results into some ugly // render effects. if ( parseFloat(qx.core.Environment.get("engine.version")) < 7 || (qx.core.Environment.get("browser.quirksmode") && parseFloat(qx.core.Environment.get("engine.version")) < 8) ) { if (width%2==1) { element.childNodes[2].style.marginRight = "-1px"; element.childNodes[5].style.marginRight = "-1px"; element.childNodes[8].style.marginRight = "-1px"; } else { element.childNodes[2].style.marginRight = "0px"; element.childNodes[5].style.marginRight = "0px"; element.childNodes[8].style.marginRight = "0px"; } if (height%2==1) { element.childNodes[3].style.marginBottom = "-1px"; element.childNodes[4].style.marginBottom = "-1px"; element.childNodes[5].style.marginBottom = "-1px"; } else { element.childNodes[3].style.marginBottom = "0px"; element.childNodes[4].style.marginBottom = "0px"; element.childNodes[5].style.marginBottom = "0px"; } } } }, // interface implementation tint : function(element, bgcolor) { // not implemented }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyBaseImage : function(value, old) { if (qx.core.Environment.get("qx.debug")) { if (this._markup) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } if (value) { var base = this._resolveImageUrl(value); var split = /(.*)(\.[a-z]+)$/.exec(base); var prefix = split[1]; var ext = split[2]; // Store images var images = this._images = { tl : prefix + "-tl" + ext, t : prefix + "-t" + ext, tr : prefix + "-tr" + ext, bl : prefix + "-bl" + ext, b : prefix + "-b" + ext, br : prefix + "-br" + ext, l : prefix + "-l" + ext, c : prefix + "-c" + ext, r : prefix + "-r" + ext }; // Store edges this._edges = this._computeEdgeSizes(images); } }, /** * Resolve the url of the given image * * @param image {String} base image URL * @return {String} the resolved image URL */ _resolveImageUrl : function(image) { return qx.util.AliasManager.getInstance().resolve(image); }, /** * Returns the sizes of the "top" and "bottom" heights and the "left" and * "right" widths of the grid. * * @param images {Map} Map of image URLs * @return {Map} the edge sizes */ _computeEdgeSizes : function(images) { var ResourceManager = qx.util.ResourceManager.getInstance(); return { top : ResourceManager.getImageHeight(images.t), bottom : ResourceManager.getImageHeight(images.b), left : ResourceManager.getImageWidth(images.l), right : ResourceManager.getImageWidth(images.r) }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._markup = this._images = this._edges = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the border radius CSS property. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. * * Keep in mind that this is not supported by all browsers: * * * Firefox 3,5+ * * IE9+ * * Safari 3.0+ * * Opera 10.5+ * * Chrome 4.0+ */ qx.Mixin.define("qx.ui.decoration.MBorderRadius", { properties : { /** top left corner radius */ radiusTopLeft : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** top right corner radius */ radiusTopRight : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** bottom left corner radius */ radiusBottomLeft : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** bottom right corner radius */ radiusBottomRight : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** Property group to set the corner radius of all sides */ radius : { group : [ "radiusTopLeft", "radiusTopRight", "radiusBottomRight", "radiusBottomLeft" ], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the border radius styles in place to the * given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleBorderRadius : function(styles) { // Fixing the background bleed in Webkits // http://tumble.sneak.co.nz/post/928998513/fixing-the-background-bleed styles["-webkit-background-clip"] = "padding-box"; // radius handling var radius = this.getRadiusTopLeft(); if (radius > 0) { styles["-moz-border-radius-topleft"] = radius + "px"; styles["-webkit-border-top-left-radius"] = radius + "px"; styles["border-top-left-radius"] = radius + "px"; } radius = this.getRadiusTopRight(); if (radius > 0) { styles["-moz-border-radius-topright"] = radius + "px"; styles["-webkit-border-top-right-radius"] = radius + "px"; styles["border-top-right-radius"] = radius + "px"; } radius = this.getRadiusBottomLeft(); if (radius > 0) { styles["-moz-border-radius-bottomleft"] = radius + "px"; styles["-webkit-border-bottom-left-radius"] = radius + "px"; styles["border-bottom-left-radius"] = radius + "px"; } radius = this.getRadiusBottomRight(); if (radius > 0) { styles["-moz-border-radius-bottomright"] = radius + "px"; styles["-webkit-border-bottom-right-radius"] = radius + "px"; styles["border-bottom-right-radius"] = radius + "px"; } }, // property apply _applyBorderRadius : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin responsible for setting the background color of a widget. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MBackgroundColor", { properties : { /** Color of the background */ backgroundColor : { check : "Color", nullable : true, apply : "_applyBackgroundColor" } }, members : { /** * Tint function for the background color. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param bgcolor {Color} The new background color. * @param styles {Map} A map of styles to apply. */ _tintBackgroundColor : function(element, bgcolor, styles) { if (bgcolor == null) { bgcolor = this.getBackgroundColor(); } if (qx.core.Environment.get("qx.theme")) { bgcolor = qx.theme.manager.Color.getInstance().resolve(bgcolor); } styles.backgroundColor = bgcolor || ""; }, /** * Resize function for the background color. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension * (width, height, top, left). */ _resizeBackgroundColor : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; return { left : insets.left, top : insets.top, width : width, height : height }; }, // property apply _applyBackgroundColor : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for supporting the background images on decorators. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MBackgroundImage", { properties : { /** The URL of the background image */ backgroundImage : { check : "String", nullable : true, apply : "_applyBackgroundImage" }, /** How the background image should be repeated */ backgroundRepeat : { check : ["repeat", "repeat-x", "repeat-y", "no-repeat", "scale"], init : "repeat", apply : "_applyBackgroundImage" }, /** * Either a string or a number, which defines the horizontal position * of the background image. * * If the value is an integer it is interpreted as a pixel value, otherwise * the value is taken to be a CSS value. For CSS, the values are "center", * "left" and "right". */ backgroundPositionX : { nullable : true, apply : "_applyBackgroundImage" }, /** * Either a string or a number, which defines the vertical position * of the background image. * * If the value is an integer it is interpreted as a pixel value, otherwise * the value is taken to be a CSS value. For CSS, the values are "top", * "center" and "bottom". */ backgroundPositionY : { nullable : true, apply : "_applyBackgroundImage" }, /** * Property group to define the background position */ backgroundPosition : { group : ["backgroundPositionY", "backgroundPositionX"] } }, members : { /** * Mapping for the dynamic decorator. */ _generateMarkup : this._generateBackgroundMarkup, /** * Responsible for generating the markup for the background. * This method just uses the settings in the properties to generate * the markup. * * @param styles {Map} CSS styles as map * @param content {String?null} The content of the created div as HTML * @return {String} The generated HTML fragment */ _generateBackgroundMarkup: function(styles, content) { var markup = ""; var image = this.getBackgroundImage(); var repeat = this.getBackgroundRepeat(); var top = this.getBackgroundPositionY(); if (top == null) { top = 0; } var left = this.getBackgroundPositionX(); if (left == null) { left = 0; } styles.backgroundPosition = left + " " + top; // Support for images if (image) { var resolved = qx.util.AliasManager.getInstance().resolve(image); markup = qx.bom.element.Decoration.create(resolved, repeat, styles); } else { if ((qx.core.Environment.get("engine.name") == "mshtml")) { /* * Internet Explorer as of version 6 for quirks and standards mode, * or version 7 in quirks mode adds an empty string to the "div" * node. This behavior causes rendering problems, because the node * would then have a minimum size determined by the font size. * To be able to set the "div" node height to a certain (small) * value independent of the minimum font size, an "overflow:hidden" * style is added. * */ if (parseFloat(qx.core.Environment.get("engine.version")) < 7 || qx.core.Environment.get("browser.quirksmode")) { // Add additionally style styles.overflow = "hidden"; } } if (!content) { content = ""; } markup = '<div style="' + qx.bom.element.Style.compile(styles) + '">' + content + '</div>'; } return markup; }, // property apply _applyBackgroundImage : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * A basic decorator featuring simple borders based on CSS styles. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MSingleBorder", { properties : { /* --------------------------------------------------------------------------- PROPERTY: WIDTH --------------------------------------------------------------------------- */ /** top width of border */ widthTop : { check : "Number", init : 0, apply : "_applyWidth" }, /** right width of border */ widthRight : { check : "Number", init : 0, apply : "_applyWidth" }, /** bottom width of border */ widthBottom : { check : "Number", init : 0, apply : "_applyWidth" }, /** left width of border */ widthLeft : { check : "Number", init : 0, apply : "_applyWidth" }, /* --------------------------------------------------------------------------- PROPERTY: STYLE --------------------------------------------------------------------------- */ /** top style of border */ styleTop : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /** right style of border */ styleRight : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /** bottom style of border */ styleBottom : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /** left style of border */ styleLeft : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /* --------------------------------------------------------------------------- PROPERTY: COLOR --------------------------------------------------------------------------- */ /** top color of border */ colorTop : { nullable : true, check : "Color", apply : "_applyStyle" }, /** right color of border */ colorRight : { nullable : true, check : "Color", apply : "_applyStyle" }, /** bottom color of border */ colorBottom : { nullable : true, check : "Color", apply : "_applyStyle" }, /** left color of border */ colorLeft : { nullable : true, check : "Color", apply : "_applyStyle" }, /* --------------------------------------------------------------------------- PROPERTY GROUP: EDGE --------------------------------------------------------------------------- */ /** Property group to configure the left border */ left : { group : [ "widthLeft", "styleLeft", "colorLeft" ] }, /** Property group to configure the right border */ right : { group : [ "widthRight", "styleRight", "colorRight" ] }, /** Property group to configure the top border */ top : { group : [ "widthTop", "styleTop", "colorTop" ] }, /** Property group to configure the bottom border */ bottom : { group : [ "widthBottom", "styleBottom", "colorBottom" ] }, /* --------------------------------------------------------------------------- PROPERTY GROUP: TYPE --------------------------------------------------------------------------- */ /** Property group to set the border width of all sides */ width : { group : [ "widthTop", "widthRight", "widthBottom", "widthLeft" ], mode : "shorthand" }, /** Property group to set the border style of all sides */ style : { group : [ "styleTop", "styleRight", "styleBottom", "styleLeft" ], mode : "shorthand" }, /** Property group to set the border color of all sides */ color : { group : [ "colorTop", "colorRight", "colorBottom", "colorLeft" ], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the border styles styles in place * to the given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleBorder : function(styles) { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var colorTop = Color.resolve(this.getColorTop()); var colorRight = Color.resolve(this.getColorRight()); var colorBottom = Color.resolve(this.getColorBottom()); var colorLeft = Color.resolve(this.getColorLeft()); } else { var colorTop = this.getColorTop(); var colorRight = this.getColorRight(); var colorBottom = this.getColorBottom(); var colorLeft = this.getColorLeft(); } // Add borders var width = this.getWidthTop(); if (width > 0) { styles["border-top"] = width + "px " + this.getStyleTop() + " " + (colorTop || ""); } var width = this.getWidthRight(); if (width > 0) { styles["border-right"] = width + "px " + this.getStyleRight() + " " + (colorRight || ""); } var width = this.getWidthBottom(); if (width > 0) { styles["border-bottom"] = width + "px " + this.getStyleBottom() + " " + (colorBottom || ""); } var width = this.getWidthLeft(); if (width > 0) { styles["border-left"] = width + "px " + this.getStyleLeft() + " " + (colorLeft || ""); } // Check if valid if (qx.core.Environment.get("qx.debug")) { if (styles.length === 0) { throw new Error("Invalid Single decorator (zero border width). Use qx.ui.decorator.Background instead!"); } } // Add basic styles styles.position = "absolute"; styles.top = 0; styles.left = 0; }, /** * Resize function for the decorator. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension. * (width, height, top, left). */ _resizeBorder : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; // Fix to keep applied size above zero // Makes issues in IE7 when applying value like '-4px' if (width < 0) { width = 0; } if (height < 0) { height = 0; } return { left : insets.left - this.getWidthLeft(), top : insets.top - this.getWidthTop(), width : width, height : height }; }, /** * Implementation of the interface for the single border. * * @return {Map} A map containing the default insets. * (top, right, bottom, left) */ _getDefaultInsetsForBorder : function() { return { top : this.getWidthTop(), right : this.getWidthRight(), bottom : this.getWidthBottom(), left : this.getWidthLeft() }; }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyWidth : function() { this._applyStyle(); this._resetInsets(); }, // property apply _applyStyle : function() { if (qx.core.Environment.get("qx.debug")) { if (this._markup) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A basic decorator featuring background colors and simple borders based on * CSS styles. */ qx.Class.define("qx.ui.decoration.Single", { extend : qx.ui.decoration.Abstract, include : [ qx.ui.decoration.MBackgroundImage, qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MSingleBorder ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param width {Integer} Width of the border * @param style {String} Any supported border style * @param color {Color} The border color */ construct : function(width, style, color) { this.base(arguments); // Initialize properties if (width != null) { this.setWidth(width); } if (style != null) { this.setStyle(style); } if (color != null) { this.setColor(color); } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { _markup : null, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this._markup) { return this._markup; } var styles = {}; // get the single border styles this._styleBorder(styles); var html = this._generateBackgroundMarkup(styles); return this._markup = html; }, // interface implementation resize : function(element, width, height) { // get the width and height of the mixins var pos = this._resizeBorder(element, width, height); element.style.width = pos.width + "px"; element.style.height = pos.height + "px"; element.style.left = pos.left + "px"; element.style.top = pos.top + "px"; }, // interface implementation tint : function(element, bgcolor) { this._tintBackgroundColor(element, bgcolor, element.style); }, // overridden _isInitialized: function() { return !!this._markup; }, // overridden _getDefaultInsets : function() { return this._getDefaultInsetsForBorder(); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A very simple decorator featuring background images and colors. No * border is supported. */ qx.Class.define("qx.ui.decoration.Background", { extend : qx.ui.decoration.Abstract, include : [ qx.ui.decoration.MBackgroundImage, qx.ui.decoration.MBackgroundColor ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param backgroundColor {Color} Initialize with background color */ construct : function(backgroundColor) { this.base(arguments); if (backgroundColor != null) { this.setBackgroundColor(backgroundColor); } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __markup : null, // overridden _getDefaultInsets : function() { return { top : 0, right : 0, bottom : 0, left : 0 }; }, // overridden _isInitialized: function() { return !!this.__markup; }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this.__markup) { return this.__markup; } var styles = { position: "absolute", top: 0, left: 0 }; var html = this._generateBackgroundMarkup(styles); // Store return this.__markup = html; }, // interface implementation resize : function(element, width, height) { var insets = this.getInsets(); element.style.width = (width - insets.left - insets.right) + "px"; element.style.height = (height - insets.top - insets.bottom) + "px"; element.style.left = -insets.left + "px"; element.style.top = -insets.top + "px"; }, // interface implementation tint : function(element, bgcolor) { this._tintBackgroundColor(element, bgcolor, element.style); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A simple decorator featuring background images and colors and a simple * uniform border based on CSS styles. */ qx.Class.define("qx.ui.decoration.Uniform", { extend : qx.ui.decoration.Single, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param width {Integer} Width of the border * @param style {String} Any supported border style * @param color {Color} The border color */ construct : function(width, style, color) { this.base(arguments); // Initialize properties if (width != null) { this.setWidth(width); } if (style != null) { this.setStyle(style); } if (color != null) { this.setColor(color); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Beveled is a variant of a rounded decorator which is quite optimal * regarding performance and still delivers a good set of features: * * * One pixel rounded border * * Inner glow color with optional transparency * * Repeated or scaled background image */ qx.Class.define("qx.ui.decoration.Beveled", { extend : qx.ui.decoration.Abstract, include : [qx.ui.decoration.MBackgroundImage, qx.ui.decoration.MBackgroundColor], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param outerColor {Color} The outer border color * @param innerColor {Color} The inner border color * @param innerOpacity {Float} Opacity of inner border */ construct : function(outerColor, innerColor, innerOpacity) { this.base(arguments); // Initialize properties if (outerColor != null) { this.setOuterColor(outerColor); } if (innerColor != null) { this.setInnerColor(innerColor); } if (innerOpacity != null) { this.setInnerOpacity(innerOpacity); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The color of the inner frame. */ innerColor : { check : "Color", nullable : true, apply : "_applyStyle" }, /** * The opacity of the inner frame. As this inner frame * is rendered above the background image this may be * intersting to configure as semi-transparent e.g. <code>0.4</code>. */ innerOpacity : { check : "Number", init : 1, apply : "_applyStyle" }, /** * Color of the outer frame. The corners are automatically * rendered with a slight opacity to fade into the background */ outerColor : { check : "Color", nullable : true, apply : "_applyStyle" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __markup : null, // overridden _getDefaultInsets : function() { return { top : 2, right : 2, bottom : 2, left : 2 }; }, // overridden _isInitialized: function() { return !!this.__markup; }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyStyle : function() { if (qx.core.Environment.get("qx.debug")) { if (this.__markup) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this.__markup) { return this.__markup; } var Color = qx.theme.manager.Color.getInstance(); var html = []; // Prepare border styles var outerStyle = "1px solid " + Color.resolve(this.getOuterColor()) + ";"; var innerStyle = "1px solid " + Color.resolve(this.getInnerColor()) + ";"; // Outer frame html.push('<div style="overflow:hidden;font-size:0;line-height:0;">'); // Background frame html.push('<div style="'); html.push('border:', outerStyle); html.push(qx.bom.element.Opacity.compile(0.35)); html.push('"></div>'); // Horizontal frame html.push('<div style="position:absolute;top:1px;left:0px;'); html.push('border-left:', outerStyle); html.push('border-right:', outerStyle); html.push(qx.bom.element.Opacity.compile(1)); html.push('"></div>'); // Vertical frame html.push('<div style="'); html.push('position:absolute;top:0px;left:1px;'); html.push('border-top:', outerStyle); html.push('border-bottom:', outerStyle); html.push(qx.bom.element.Opacity.compile(1)); html.push('"></div>'); // Inner background frame var backgroundStyle = { position: "absolute", top: "1px", left: "1px", opacity: 1 }; html.push(this._generateBackgroundMarkup(backgroundStyle)); // Inner overlay frame html.push('<div style="position:absolute;top:1px;left:1px;'); html.push('border:', innerStyle); html.push(qx.bom.element.Opacity.compile(this.getInnerOpacity())); html.push('"></div>'); // Outer frame html.push('</div>'); // Store return this.__markup = html.join(""); }, // interface implementation resize : function(element, width, height) { // Fix to keep applied size above zero // Makes issues in IE7 when applying value like '-4px' if (width < 4) { width = 4; } if (height < 4) { height = 4; } // Fix box model if (qx.core.Environment.get("css.boxmodel") == "content") { var outerWidth = width - 2; var outerHeight = height - 2; var frameWidth = outerWidth; var frameHeight = outerHeight; var innerWidth = width - 4; var innerHeight = height - 4; } else { var outerWidth = width; var outerHeight = height; var frameWidth = width - 2; var frameHeight = height - 2; var innerWidth = frameWidth; var innerHeight = frameHeight; } var pixel = "px"; var backgroundFrame = element.childNodes[0].style; backgroundFrame.width = outerWidth + pixel; backgroundFrame.height = outerHeight + pixel; var horizontalFrame = element.childNodes[1].style; horizontalFrame.width = outerWidth + pixel; horizontalFrame.height = frameHeight + pixel; var verticalFrame = element.childNodes[2].style; verticalFrame.width = frameWidth + pixel; verticalFrame.height = outerHeight + pixel; var innerBackground = element.childNodes[3].style; innerBackground.width = frameWidth + pixel; innerBackground.height = frameHeight + pixel; var innerOverlay = element.childNodes[4].style; innerOverlay.width = innerWidth + pixel; innerOverlay.height = innerHeight + pixel; }, // interface implementation tint : function(element, bgcolor) { this._tintBackgroundColor(element, bgcolor, element.childNodes[3].style); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the linear background gradient CSS property. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. * * Keep in mind that this is not supported by all browsers: * * * Safari 4.0+ * * Chrome 4.0+ * * Firefox 3.6+ * * Opera 11.1+ * * IE 10+ * * IE 5.5+ (with limitations) * * For IE 5.5 to IE 9,this class uses the filter rules to create the gradient. This * has some limitations: The start and end position property can not be used. For * more details, see the original documentation: * http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx */ qx.Mixin.define("qx.ui.decoration.MLinearBackgroundGradient", { properties : { /** Start start color of the background */ startColor : { check : "Color", nullable : true, apply : "_applyLinearBackgroundGradient" }, /** End end color of the background */ endColor : { check : "Color", nullable : true, apply : "_applyLinearBackgroundGradient" }, /** The orientation of the gradient. */ orientation : { check : ["horizontal", "vertical"], init : "vertical", apply : "_applyLinearBackgroundGradient" }, /** Position in percent where to start the color. */ startColorPosition : { check : "Number", init : 0, apply : "_applyLinearBackgroundGradient" }, /** Position in percent where to start the color. */ endColorPosition : { check : "Number", init : 100, apply : "_applyLinearBackgroundGradient" }, /** Defines if the given positions are in % or px.*/ colorPositionUnit : { check : ["px", "%"], init : "%", apply : "_applyLinearBackgroundGradient" }, /** Property group to set the start color including its start position. */ gradientStart : { group : ["startColor", "startColorPosition"], mode : "shorthand" }, /** Property group to set the end color including its end position. */ gradientEnd : { group : ["endColor", "endColorPosition"], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the linear background styles in place to the * given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleLinearBackgroundGradient : function(styles) { var colors = this.__getColors(); var startColor = colors.start; var endColor = colors.end; var unit = this.getColorPositionUnit(); // new implementation for webkit is available since chrome 10 --> version if (qx.core.Environment.get("css.gradient.legacywebkit")) { // webkit uses px values if non are given unit = unit === "px" ? "" : unit; if (this.getOrientation() == "horizontal") { var startPos = this.getStartColorPosition() + unit +" 0" + unit; var endPos = this.getEndColorPosition() + unit + " 0" + unit; } else { var startPos = "0" + unit + " " + this.getStartColorPosition() + unit; var endPos = "0" + unit +" " + this.getEndColorPosition() + unit; } var color = "from(" + startColor + "),to(" + endColor + ")"; var value = "-webkit-gradient(linear," + startPos + "," + endPos + "," + color + ")"; styles["background"] = value; } else if (qx.core.Environment.get("css.gradient.filter") && !qx.core.Environment.get("css.gradient.linear")) { // make sure the overflow is hidden for border radius usage [BUG #6318] styles["overflow"] = "hidden"; // spec like syntax } else { var deg = this.getOrientation() == "horizontal" ? 0 : 270; // Bugfix for IE10 which seems to use the deg values wrong [BUG #6513] if (qx.core.Environment.get("browser.name") == "ie") { deg = deg - 90; } var start = startColor + " " + this.getStartColorPosition() + unit; var end = endColor + " " + this.getEndColorPosition() + unit; var prefixedName = qx.core.Environment.get("css.gradient.linear"); styles["background-image"] = prefixedName + "(" + deg + "deg, " + start + "," + end + ")"; } }, /** * Helper to get start and end color. * @return {Map} A map containing start and end color. */ __getColors : function() { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var startColor = Color.resolve(this.getStartColor()); var endColor = Color.resolve(this.getEndColor()); } else { var startColor = this.getStartColor(); var endColor = this.getEndColor(); } return {start: startColor, end: endColor}; }, /** * Helper for IE which applies the filter used for the gradient to a separate * DIV element which will be put into the decorator. This is necessary in case * the decorator has rounded corners. * @return {String} The HTML for the inner gradient DIV. */ _getContent : function() { // IE filter syntax // http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx // It needs to be wrapped in a separate div bug #6318 if (qx.core.Environment.get("css.gradient.filter") && !qx.core.Environment.get("css.gradient.linear")) { var colors = this.__getColors(); var type = this.getOrientation() == "horizontal" ? 1 : 0; // convert all hex3 to hex6 var startColor = qx.util.ColorUtil.hex3StringToHex6String(colors.start); var endColor = qx.util.ColorUtil.hex3StringToHex6String(colors.end); // get rid of the starting '#' startColor = startColor.substring(1, startColor.length); endColor = endColor.substring(1, endColor.length); return "<div style=\"position: absolute; width: 100%; height: 100%; filter:progid:DXImageTransform.Microsoft.Gradient" + "(GradientType=" + type + ", " + "StartColorStr='#FF" + startColor + "', " + "EndColorStr='#FF" + endColor + "';)\"></div>"; } return ""; }, /** * Resize function for the background color. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension * (width, height, top, left). */ _resizeLinearBackgroundGradient : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; return { left : insets.left, top : insets.top, width : width, height : height }; }, // property apply _applyLinearBackgroundGradient : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Border implementation with two CSS borders. Both borders can be styled * independent of each other. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MDoubleBorder", { include : [qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBackgroundImage], construct : function() { // override the methods of single border and background image this._getDefaultInsetsForBorder = this.__getDefaultInsetsForDoubleBorder; this._resizeBorder = this.__resizeDoubleBorder; this._styleBorder = this.__styleDoubleBorder; this._generateMarkup = this.__generateMarkupDoubleBorder; }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /* --------------------------------------------------------------------------- PROPERTY: INNER WIDTH --------------------------------------------------------------------------- */ /** top width of border */ innerWidthTop : { check : "Number", init : 0 }, /** right width of border */ innerWidthRight : { check : "Number", init : 0 }, /** bottom width of border */ innerWidthBottom : { check : "Number", init : 0 }, /** left width of border */ innerWidthLeft : { check : "Number", init : 0 }, /** Property group to set the inner border width of all sides */ innerWidth : { group : [ "innerWidthTop", "innerWidthRight", "innerWidthBottom", "innerWidthLeft" ], mode : "shorthand" }, /* --------------------------------------------------------------------------- PROPERTY: INNER COLOR --------------------------------------------------------------------------- */ /** top inner color of border */ innerColorTop : { nullable : true, check : "Color" }, /** right inner color of border */ innerColorRight : { nullable : true, check : "Color" }, /** bottom inner color of border */ innerColorBottom : { nullable : true, check : "Color" }, /** left inner color of border */ innerColorLeft : { nullable : true, check : "Color" }, /** * Property group for the inner color properties. */ innerColor : { group : [ "innerColorTop", "innerColorRight", "innerColorBottom", "innerColorLeft" ], mode : "shorthand" } }, members : { __ownMarkup : null, /** * Takes a styles map and adds the inner border styles styles in place * to the given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ __styleDoubleBorder : function(styles) { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var innerColorTop = Color.resolve(this.getInnerColorTop()); var innerColorRight = Color.resolve(this.getInnerColorRight()); var innerColorBottom = Color.resolve(this.getInnerColorBottom()); var innerColorLeft = Color.resolve(this.getInnerColorLeft()); } else { var innerColorTop = this.getInnerColorTop(); var innerColorRight = this.getInnerColorRight(); var innerColorBottom = this.getInnerColorBottom(); var innerColorLeft = this.getInnerColorLeft(); } // Inner styles // Inner image must be relative to be compatible with qooxdoo 0.8.x // See http://bugzilla.qooxdoo.org/show_bug.cgi?id=3450 for details styles.position = "relative"; // Add inner borders var width = this.getInnerWidthTop(); if (width > 0) { styles["border-top"] = width + "px " + this.getStyleTop() + " " + innerColorTop; } var width = this.getInnerWidthRight(); if (width > 0) { styles["border-right"] = width + "px " + this.getStyleRight() + " " + innerColorRight; } var width = this.getInnerWidthBottom(); if (width > 0) { styles["border-bottom"] = width + "px " + this.getStyleBottom() + " " + innerColorBottom; } var width = this.getInnerWidthLeft(); if (width > 0) { styles["border-left"] = width + "px " + this.getStyleLeft() + " " + innerColorLeft; } if (qx.core.Environment.get("qx.debug")) { if (!styles["border-top"] && !styles["border-right"] && !styles["border-bottom"] && !styles["border-left"]) { throw new Error("Invalid Double decorator (zero inner border width). Use qx.ui.decoration.Single instead!"); } } }, /** * Special generator for the markup which creates the containing div and * the sourrounding div as well. * * @param styles {Map} The styles for the inner * @return {String} The generated decorator HTML. */ __generateMarkupDoubleBorder : function(styles) { var innerHtml = this._generateBackgroundMarkup( styles, this._getContent ? this._getContent() : "" ); if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var colorTop = Color.resolve(this.getColorTop()); var colorRight = Color.resolve(this.getColorRight()); var colorBottom = Color.resolve(this.getColorBottom()); var colorLeft = Color.resolve(this.getColorLeft()); } else { var colorTop = this.getColorTop(); var colorRight = this.getColorRight(); var colorBottom = this.getColorBottom(); var colorLeft = this.getColorLeft(); } // get rid of the old borders styles["border-top"] = ''; styles["border-right"] = ''; styles["border-bottom"] = ''; styles["border-left"] = ''; // Generate outer HTML styles["line-height"] = 0; // Do not set the line-height on IE6, IE7, IE8 in Quirks Mode and IE8 in IE7 Standard Mode // See http://bugzilla.qooxdoo.org/show_bug.cgi?id=3450 for details if ( (qx.core.Environment.get("engine.name") == "mshtml" && parseFloat(qx.core.Environment.get("engine.version")) < 8) || (qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("browser.documentmode") < 8) ) { styles["line-height"] = ''; } var width = this.getWidthTop(); if (width > 0) { styles["border-top"] = width + "px " + this.getStyleTop() + " " + colorTop; } var width = this.getWidthRight(); if (width > 0) { styles["border-right"] = width + "px " + this.getStyleRight() + " " + colorRight; } var width = this.getWidthBottom(); if (width > 0) { styles["border-bottom"] = width + "px " + this.getStyleBottom() + " " + colorBottom; } var width = this.getWidthLeft(); if (width > 0) { styles["border-left"] = width + "px " + this.getStyleLeft() + " " + colorLeft; } if (qx.core.Environment.get("qx.debug")) { if (styles["border-top"] == '' && styles["border-right"] == '' && styles["border-bottom"] == '' && styles["border-left"] == '') { throw new Error("Invalid Double decorator (zero outer border width). Use qx.ui.decoration.Single instead!"); } } // final default styles styles["position"] = "absolute"; styles["top"] = 0; styles["left"] = 0; // Store return this.__ownMarkup = this._generateBackgroundMarkup(styles, innerHtml); }, /** * Resize function for the decorator. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension and a * emelent to resize. * (width, height, top, left, elementToApplyDimensions). */ __resizeDoubleBorder : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; var left = insets.left - this.getWidthLeft() - this.getInnerWidthLeft(); var top = insets.top - this.getWidthTop() - this.getInnerWidthTop(); return { left: left, top: top, width: width, height: height, elementToApplyDimensions : element.firstChild }; }, /** * Implementation of the interface for the double border. * * @return {Map} A map containing the default insets. * (top, right, bottom, left) */ __getDefaultInsetsForDoubleBorder : function() { return { top : this.getWidthTop() + this.getInnerWidthTop(), right : this.getWidthRight() + this.getInnerWidthRight(), bottom : this.getWidthBottom() + this.getInnerWidthBottom(), left : this.getWidthLeft() + this.getInnerWidthLeft() }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the box shadow CSS property. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. * * Keep in mind that this is not supported by all browsers: * * * Firefox 3,5+ * * IE9+ * * Safari 3.0+ * * Opera 10.5+ * * Chrome 4.0+ */ qx.Mixin.define("qx.ui.decoration.MBoxShadow", { properties : { /** Horizontal length of the shadow. */ shadowHorizontalLength : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** Vertical length of the shadow. */ shadowVerticalLength : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** The blur radius of the shadow. */ shadowBlurRadius : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** The spread radius of the shadow. */ shadowSpreadRadius : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** The color of the shadow. */ shadowColor : { nullable : true, check : "Color", apply : "_applyBoxShadow" }, /** Inset shadows are drawn inside the border. */ inset : { init : false, check : "Boolean", apply : "_applyBoxShadow" }, /** Property group to set the shadow length. */ shadowLength : { group : ["shadowHorizontalLength", "shadowVerticalLength"], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the box shadow styles in place to the * given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleBoxShadow : function(styles) { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var color = Color.resolve(this.getShadowColor()); } else { var color = this.getShadowColor(); } if (color != null) { var vLength = this.getShadowVerticalLength() || 0; var hLength = this.getShadowHorizontalLength() || 0; var blur = this.getShadowBlurRadius() || 0; var spread = this.getShadowSpreadRadius() || 0; var inset = this.getInset() ? "inset " : ""; var value = inset + hLength + "px " + vLength + "px " + blur + "px " + spread + "px " + color; styles["-moz-box-shadow"] = value; styles["-webkit-box-shadow"] = value; styles["box-shadow"] = value; } }, // property apply _applyBoxShadow : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de 2006 STZ-IDA, Germany, http://www.stz-ida.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Alexander Steitz (aback) * Martin Wittemann (martinwittemann) ************************************************************************* */ /* ************************************************************************ #asset(qx/decoration/Modern/*) ************************************************************************ */ /** * The modern decoration theme. */ qx.Theme.define("qx.theme.modern.Decoration", { aliases : { decoration : "qx/decoration/Modern" }, decorations : { /* --------------------------------------------------------------------------- CORE --------------------------------------------------------------------------- */ "main" : { decorator: qx.ui.decoration.Uniform, style : { width : 1, color : "border-main" } }, "selected" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/selection.png", backgroundRepeat : "scale" } }, "selected-css" : { decorator : [ qx.ui.decoration.MLinearBackgroundGradient ], style : { startColorPosition : 0, endColorPosition : 100, startColor : "selected-start", endColor : "selected-end" } }, "selected-dragover" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/selection.png", backgroundRepeat : "scale", bottom: [2, "solid", "border-dragover"] } }, "dragover" : { decorator : qx.ui.decoration.Single, style : { bottom: [2, "solid", "border-dragover"] } }, "pane" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/pane/pane.png", insets : [0, 2, 3, 0] } }, "pane-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MLinearBackgroundGradient ], style : { width: 1, color: "tabview-background", radius : 3, shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 0, gradientStart : ["pane-start", 0], gradientEnd : ["pane-end", 100] } }, "group" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/groupbox/groupbox.png" } }, "group-css" : { decorator : [ qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder ], style : { backgroundColor : "group-background", radius : 4, color : "group-border", width: 1 } }, "border-invalid" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "invalid", innerColor : "border-inner-input", innerOpacity : 0.5, backgroundImage : "decoration/form/input.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, "keyboard-focus" : { decorator : qx.ui.decoration.Single, style : { width : 1, color : "keyboard-focus", style : "dotted" } }, /* --------------------------------------------------------------------------- CSS RADIO BUTTON --------------------------------------------------------------------------- */ "radiobutton" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow ], style : { backgroundColor : "radiobutton-background", radius : 5, width: 1, innerWidth : 2, color : "checkbox-border", innerColor : "radiobutton-background", shadowLength : 0, shadowBlurRadius : 0, shadowColor : "checkbox-focus", insetLeft: 5 // used for the shadow (3 border + 2 extra for the shadow) } }, "radiobutton-checked" : { include : "radiobutton", style : { backgroundColor : "radiobutton-checked" } }, "radiobutton-checked-focused" : { include : "radiobutton-checked", style : { shadowBlurRadius : 4 } }, "radiobutton-checked-hovered" : { include : "radiobutton-checked", style : { innerColor : "checkbox-hovered" } }, "radiobutton-focused" : { include : "radiobutton", style : { shadowBlurRadius : 4 } }, "radiobutton-hovered" : { include : "radiobutton", style : { backgroundColor : "checkbox-hovered", innerColor : "checkbox-hovered" } }, "radiobutton-disabled" : { include : "radiobutton", style : { innerColor : "radiobutton-disabled", backgroundColor : "radiobutton-disabled", color : "checkbox-disabled-border" } }, "radiobutton-checked-disabled" : { include : "radiobutton-disabled", style : { backgroundColor : "radiobutton-checked-disabled" } }, "radiobutton-invalid" : { include : "radiobutton", style : { color : "invalid" } }, "radiobutton-checked-invalid" : { include : "radiobutton-checked", style : { color : "invalid" } }, "radiobutton-checked-focused-invalid" : { include : "radiobutton-checked-focused", style : { color : "invalid", shadowColor : "invalid" } }, "radiobutton-checked-hovered-invalid" : { include : "radiobutton-checked-hovered", style : { color : "invalid", innerColor : "radiobutton-hovered-invalid" } }, "radiobutton-focused-invalid" : { include : "radiobutton-focused", style : { color : "invalid", shadowColor : "invalid" } }, "radiobutton-hovered-invalid" : { include : "radiobutton-hovered", style : { color : "invalid", innerColor : "radiobutton-hovered-invalid", backgroundColor : "radiobutton-hovered-invalid" } }, /* --------------------------------------------------------------------------- SEPARATOR --------------------------------------------------------------------------- */ "separator-horizontal" : { decorator: qx.ui.decoration.Single, style : { widthLeft : 1, colorLeft : "border-separator" } }, "separator-vertical" : { decorator: qx.ui.decoration.Single, style : { widthTop : 1, colorTop : "border-separator" } }, /* --------------------------------------------------------------------------- TOOLTIP --------------------------------------------------------------------------- */ "tooltip-error" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/tooltip-error.png", insets : [ 2, 5, 5, 2 ] } }, "tooltip-error-css" : { decorator : [ qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow ], style : { backgroundColor : "tooltip-error", radius : 4, shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 1, insets: [-2, 0, 0, -2] } }, "tooltip-error-css-left" : { include : "tooltip-error-css", style : { insets : [1, 0, 0, 2] } }, "tooltip-error-arrow" : { decorator: qx.ui.decoration.Background, style: { backgroundImage: "decoration/form/tooltip-error-arrow.png", backgroundPositionY: "top", backgroundRepeat: "no-repeat", insets: [-4, 0, 0, 13] } }, "tooltip-error-arrow-left" : { decorator: qx.ui.decoration.Background, style: { backgroundImage: "decoration/form/tooltip-error-arrow-right.png", backgroundPositionY: "top", backgroundPositionX: "right", backgroundRepeat: "no-repeat", insets: [-4, -13, 0, 0] } }, "tooltip-error-arrow-left-css" : { decorator: qx.ui.decoration.Background, style: { backgroundImage: "decoration/form/tooltip-error-arrow-right.png", backgroundPositionY: "top", backgroundPositionX: "right", backgroundRepeat: "no-repeat", insets: [-6, -13, 0, 0] } }, /* --------------------------------------------------------------------------- SHADOWS --------------------------------------------------------------------------- */ "shadow-window" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/shadow/shadow.png", insets : [ 4, 8, 8, 4 ] } }, "shadow-window-css" : { decorator : [ qx.ui.decoration.MBoxShadow, qx.ui.decoration.MBackgroundColor ], style : { shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 1 } }, "shadow-popup" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/shadow/shadow-small.png", insets : [ 0, 3, 3, 0 ] } }, "popup-css" : { decorator: [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MBackgroundColor ], style : { width : 1, color : "border-main", shadowColor : "shadow", shadowBlurRadius : 3, shadowLength : 1 } }, /* --------------------------------------------------------------------------- SCROLLBAR --------------------------------------------------------------------------- */ "scrollbar-horizontal" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/scrollbar/scrollbar-bg-horizontal.png", backgroundRepeat : "repeat-x" } }, "scrollbar-vertical" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/scrollbar/scrollbar-bg-vertical.png", backgroundRepeat : "repeat-y" } }, "scrollbar-slider-horizontal" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-horizontal.png", backgroundRepeat : "scale", outerColor : "border-main", innerColor : "border-inner-scrollbar", innerOpacity : 0.5 } }, "scrollbar-slider-horizontal-disabled" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-horizontal.png", backgroundRepeat : "scale", outerColor : "border-disabled", innerColor : "border-inner-scrollbar", innerOpacity : 0.3 } }, "scrollbar-slider-vertical" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-vertical.png", backgroundRepeat : "scale", outerColor : "border-main", innerColor : "border-inner-scrollbar", innerOpacity : 0.5 } }, "scrollbar-slider-vertical-disabled" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-vertical.png", backgroundRepeat : "scale", outerColor : "border-disabled", innerColor : "border-inner-scrollbar", innerOpacity : 0.3 } }, // PLAIN CSS SCROLLBAR "scrollbar-horizontal-css" : { decorator : [qx.ui.decoration.MLinearBackgroundGradient], style : { gradientStart : ["scrollbar-start", 0], gradientEnd : ["scrollbar-end", 100] } }, "scrollbar-vertical-css" : { include : "scrollbar-horizontal-css", style : { orientation : "horizontal" } }, "scrollbar-slider-horizontal-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["scrollbar-slider-start", 0], gradientEnd : ["scrollbar-slider-end", 100], color : "border-main", width: 1 } }, "scrollbar-slider-vertical-css" : { include : "scrollbar-slider-horizontal-css", style : { orientation : "horizontal" } }, "scrollbar-slider-horizontal-disabled-css" : { include : "scrollbar-slider-horizontal-css", style : { color : "button-border-disabled" } }, "scrollbar-slider-vertical-disabled-css" : { include : "scrollbar-slider-vertical-css", style : { color : "button-border-disabled" } }, /* --------------------------------------------------------------------------- PLAIN CSS BUTTON --------------------------------------------------------------------------- */ "button-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBorderRadius ], style : { radius: 3, color: "border-button", width: 1, startColor: "button-start", endColor: "button-end", startColorPosition: 35, endColorPosition: 100 } }, "button-disabled-css" : { include : "button-css", style : { color : "button-border-disabled", startColor: "button-disabled-start", endColor: "button-disabled-end" } }, "button-hovered-css" : { include : "button-css", style : { startColor : "button-hovered-start", endColor : "button-hovered-end" } }, "button-checked-css" : { include : "button-css", style : { endColor: "button-start", startColor: "button-end" } }, "button-pressed-css" : { include : "button-css", style : { endColor : "button-hovered-start", startColor : "button-hovered-end" } }, "button-focused-css" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBorderRadius ], style : { radius: 3, color: "border-button", width: 1, innerColor: "button-focused", innerWidth: 2, startColor: "button-start", endColor: "button-end", startColorPosition: 30, endColorPosition: 100 } }, "button-checked-focused-css" : { include : "button-focused-css", style : { endColor: "button-start", startColor: "button-end" } }, // invalid "button-invalid-css" : { include : "button-css", style : { color: "border-invalid" } }, "button-disabled-invalid-css" : { include : "button-disabled-css", style : { color : "border-invalid" } }, "button-hovered-invalid-css" : { include : "button-hovered-css", style : { color : "border-invalid" } }, "button-checked-invalid-css" : { include : "button-checked-css", style : { color : "border-invalid" } }, "button-pressed-invalid-css" : { include : "button-pressed-css", style : { color : "border-invalid" } }, "button-focused-invalid-css" : { include : "button-focused-css", style : { color : "border-invalid" } }, "button-checked-focused-invalid-css" : { include : "button-checked-focused-css", style : { color : "border-invalid" } }, /* --------------------------------------------------------------------------- BUTTON --------------------------------------------------------------------------- */ "button" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button.png", insets : 2 } }, "button-disabled" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-disabled.png", insets : 2 } }, "button-focused" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-focused.png", insets : 2 } }, "button-hovered" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-hovered.png", insets : 2 } }, "button-pressed" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-pressed.png", insets : 2 } }, "button-checked" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-checked.png", insets : 2 } }, "button-checked-focused" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-checked-focused.png", insets : 2 } }, "button-invalid-shadow" : { decorator : qx.ui.decoration.Single, style : { color : "invalid", width : 1 } }, /* --------------------------------------------------------------------------- CHECKBOX --------------------------------------------------------------------------- */ "checkbox-invalid-shadow" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "invalid", innerColor : "border-focused-invalid", insets: [0] } }, /* --------------------------------------------------------------------------- PLAIN CSS CHECK BOX --------------------------------------------------------------------------- */ "checkbox" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBoxShadow ], style : { width: 1, color: "checkbox-border", innerWidth : 1, innerColor : "checkbox-inner", gradientStart : ["checkbox-start", 0], gradientEnd : ["checkbox-end", 100], shadowLength : 0, shadowBlurRadius : 0, shadowColor : "checkbox-focus", insetLeft: 4 // (2 for the border and two for the glow effect) } }, "checkbox-hovered" : { include : "checkbox", style : { innerColor : "checkbox-hovered-inner", // use the same color to get a single colored background gradientStart : ["checkbox-hovered", 0], gradientEnd : ["checkbox-hovered", 100] } }, "checkbox-focused" : { include : "checkbox", style : { shadowBlurRadius : 4 } }, "checkbox-disabled" : { include : "checkbox", style : { color : "checkbox-disabled-border", innerColor : "checkbox-disabled-inner", gradientStart : ["checkbox-disabled-start", 0], gradientEnd : ["checkbox-disabled-end", 100] } }, "checkbox-invalid" : { include : "checkbox", style : { color : "invalid" } }, "checkbox-hovered-invalid" : { include : "checkbox-hovered", style : { color : "invalid", innerColor : "checkbox-hovered-inner-invalid", gradientStart : ["checkbox-hovered-invalid", 0], gradientEnd : ["checkbox-hovered-invalid", 100] } }, "checkbox-focused-invalid" : { include : "checkbox-focused", style : { color : "invalid", shadowColor : "invalid" } }, /* --------------------------------------------------------------------------- PLAIN CSS TEXT FIELD --------------------------------------------------------------------------- */ "input-css" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBackgroundColor ], style : { color : "border-input", innerColor : "border-inner-input", innerWidth: 1, width : 1, backgroundColor : "background-light", startColor : "input-start", endColor : "input-end", startColorPosition : 0, endColorPosition : 12, colorPositionUnit : "px" } }, "border-invalid-css" : { include : "input-css", style : { color : "border-invalid" } }, "input-focused-css" : { include : "input-css", style : { startColor : "input-focused-start", innerColor : "input-focused-end", endColorPosition : 4 } }, "input-focused-invalid-css" : { include : "input-focused-css", style : { innerColor : "input-focused-inner-invalid", color : "border-invalid" } }, "input-disabled-css" : { include : "input-css", style : { color: "input-border-disabled" } }, /* --------------------------------------------------------------------------- TEXT FIELD --------------------------------------------------------------------------- */ "input" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-input", innerColor : "border-inner-input", innerOpacity : 0.5, backgroundImage : "decoration/form/input.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, "input-focused" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-input", innerColor : "border-focused", backgroundImage : "decoration/form/input-focused.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, "input-focused-invalid" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "invalid", innerColor : "border-focused-invalid", backgroundImage : "decoration/form/input-focused.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light", insets: [2] } }, "input-disabled" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-disabled", innerColor : "border-inner-input", innerOpacity : 0.5, backgroundImage : "decoration/form/input.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, /* --------------------------------------------------------------------------- TOOLBAR --------------------------------------------------------------------------- */ "toolbar" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/toolbar/toolbar-gradient.png", backgroundRepeat : "scale" } }, "toolbar-css" : { decorator : [qx.ui.decoration.MLinearBackgroundGradient], style : { startColorPosition : 40, endColorPosition : 60, startColor : "toolbar-start", endColor : "toolbar-end" } }, "toolbar-button-hovered" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-toolbar-button-outer", innerColor : "border-toolbar-border-inner", backgroundImage : "decoration/form/button-c.png", backgroundRepeat : "scale" } }, "toolbar-button-checked" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-toolbar-button-outer", innerColor : "border-toolbar-border-inner", backgroundImage : "decoration/form/button-checked-c.png", backgroundRepeat : "scale" } }, "toolbar-button-hovered-css" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBorderRadius ], style : { color : "border-toolbar-button-outer", width: 1, innerWidth: 1, innerColor : "border-toolbar-border-inner", radius : 2, gradientStart : ["button-start", 30], gradientEnd : ["button-end", 100] } }, "toolbar-button-checked-css" : { include : "toolbar-button-hovered-css", style : { gradientStart : ["button-end", 30], gradientEnd : ["button-start", 100] } }, "toolbar-separator" : { decorator : qx.ui.decoration.Single, style : { widthLeft : 1, widthRight : 1, colorLeft : "border-toolbar-separator-left", colorRight : "border-toolbar-separator-right", styleLeft : "solid", styleRight : "solid" } }, "toolbar-part" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/toolbar/toolbar-part.gif", backgroundRepeat : "repeat-y" } }, /* --------------------------------------------------------------------------- TABVIEW --------------------------------------------------------------------------- */ "tabview-pane" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tabview-pane.png", insets : [ 4, 6, 7, 4 ] } }, "tabview-pane-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MSingleBorder ], style : { width: 1, color: "window-border", radius : 3, gradientStart : ["tabview-start", 90], gradientEnd : ["tabview-end", 100] } }, "tabview-page-button-top-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-top-active.png" } }, "tabview-page-button-top-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-top-inactive.png" } }, "tabview-page-button-bottom-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-bottom-active.png" } }, "tabview-page-button-bottom-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-bottom-inactive.png" } }, "tabview-page-button-left-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-left-active.png" } }, "tabview-page-button-left-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-left-inactive.png" } }, "tabview-page-button-right-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-right-active.png" } }, "tabview-page-button-right-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-right-inactive.png" } }, // CSS TABVIEW BUTTONS "tabview-page-button-top-active-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBoxShadow ], style : { radius : [3, 3, 0, 0], width: [1, 1, 0, 1], color: "tabview-background", backgroundColor : "tabview-start", shadowLength: 1, shadowColor: "shadow", shadowBlurRadius: 2 } }, "tabview-page-button-top-inactive-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { radius : [3, 3, 0, 0], color: "tabview-inactive", colorBottom : "tabview-background", width: 1, gradientStart : ["tabview-inactive-start", 0], gradientEnd : ["tabview-inactive-end", 100] } }, "tabview-page-button-bottom-active-css" : { include : "tabview-page-button-top-active-css", style : { radius : [0, 0, 3, 3], width: [0, 1, 1, 1], backgroundColor : "tabview-inactive-start" } }, "tabview-page-button-bottom-inactive-css" : { include : "tabview-page-button-top-inactive-css", style : { radius : [0, 0, 3, 3], width: [0, 1, 1, 1], colorBottom : "tabview-inactive", colorTop : "tabview-background" } }, "tabview-page-button-left-active-css" : { include : "tabview-page-button-top-active-css", style : { radius : [3, 0, 0, 3], width: [1, 0, 1, 1], shadowLength: 0, shadowBlurRadius: 0 } }, "tabview-page-button-left-inactive-css" : { include : "tabview-page-button-top-inactive-css", style : { radius : [3, 0, 0, 3], width: [1, 0, 1, 1], colorBottom : "tabview-inactive", colorRight : "tabview-background" } }, "tabview-page-button-right-active-css" : { include : "tabview-page-button-top-active-css", style : { radius : [0, 3, 3, 0], width: [1, 1, 1, 0], shadowLength: 0, shadowBlurRadius: 0 } }, "tabview-page-button-right-inactive-css" : { include : "tabview-page-button-top-inactive-css", style : { radius : [0, 3, 3, 0], width: [1, 1, 1, 0], colorBottom : "tabview-inactive", colorLeft : "tabview-background" } }, /* --------------------------------------------------------------------------- SPLITPANE --------------------------------------------------------------------------- */ "splitpane" : { decorator : qx.ui.decoration.Uniform, style : { backgroundColor : "background-pane", width : 3, color : "background-splitpane", style : "solid" } }, /* --------------------------------------------------------------------------- WINDOW --------------------------------------------------------------------------- */ "window" : { decorator: qx.ui.decoration.Single, style : { backgroundColor : "background-pane", width : 1, color : "border-main", widthTop : 0 } }, "window-captionbar-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/window/captionbar-active.png" } }, "window-captionbar-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/window/captionbar-inactive.png" } }, "window-statusbar" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/window/statusbar.png" } }, // CSS WINDOW "window-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MSingleBorder ], style : { radius : [5, 5, 0, 0], shadowBlurRadius : 4, shadowLength : 2, shadowColor : "shadow" } }, "window-incl-statusbar-css" : { include : "window-css", style : { radius : [5, 5, 5, 5] } }, "window-resize-frame-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder ], style : { radius : [5, 5, 0, 0], width : 1, color : "border-main" } }, "window-resize-frame-incl-statusbar-css" : { include : "window-resize-frame-css", style : { radius : [5, 5, 5, 5] } }, "window-captionbar-active-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MLinearBackgroundGradient ], style : { width : 1, color : "window-border", colorBottom : "window-border-caption", radius : [5, 5, 0, 0], gradientStart : ["window-caption-active-start", 30], gradientEnd : ["window-caption-active-end", 70] } }, "window-captionbar-inactive-css" : { include : "window-captionbar-active-css", style : { gradientStart : ["window-caption-inactive-start", 30], gradientEnd : ["window-caption-inactive-end", 70] } }, "window-statusbar-css" : { decorator : [ qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBorderRadius ], style : { backgroundColor : "window-statusbar-background", width: [0, 1, 1, 1], color: "window-border", radius : [0, 0, 5, 5] } }, "window-pane-css" : { decorator: [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBackgroundColor ], style : { backgroundColor : "background-pane", width : 1, color : "window-border", widthTop : 0 } }, /* --------------------------------------------------------------------------- TABLE --------------------------------------------------------------------------- */ "table" : { decorator : qx.ui.decoration.Single, style : { width : 1, color : "border-main", style : "solid" } }, "table-statusbar" : { decorator : qx.ui.decoration.Single, style : { widthTop : 1, colorTop : "border-main", style : "solid" } }, "table-scroller-header" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/table/header-cell.png", backgroundRepeat : "scale", widthBottom : 1, colorBottom : "border-main", style : "solid" } }, "table-scroller-header-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["table-header-start", 10], gradientEnd : ["table-header-end", 90], widthBottom : 1, colorBottom : "border-main" } }, "table-header-cell" : { decorator : qx.ui.decoration.Single, style : { widthRight : 1, colorRight : "border-separator", styleRight : "solid" } }, "table-header-cell-hovered" : { decorator : qx.ui.decoration.Single, style : { widthRight : 1, colorRight : "border-separator", styleRight : "solid", widthBottom : 1, colorBottom : "table-header-hovered", styleBottom : "solid" } }, "table-scroller-focus-indicator" : { decorator : qx.ui.decoration.Single, style : { width : 2, color : "table-focus-indicator", style : "solid" } }, /* --------------------------------------------------------------------------- PROGRESSIVE --------------------------------------------------------------------------- */ "progressive-table-header" : { decorator : qx.ui.decoration.Single, style : { width : 1, color : "border-main", style : "solid" } }, "progressive-table-header-cell" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/table/header-cell.png", backgroundRepeat : "scale", widthRight : 1, colorRight : "progressive-table-header-border-right", style : "solid" } }, "progressive-table-header-cell-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["table-header-start", 10], gradientEnd : ["table-header-end", 90], widthRight : 1, colorRight : "progressive-table-header-border-right" } }, /* --------------------------------------------------------------------------- MENU --------------------------------------------------------------------------- */ "menu" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/menu/background.png", backgroundRepeat : "scale", width : 1, color : "border-main", style : "solid" } }, "menu-css" : { decorator : [ qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MSingleBorder ], style : { gradientStart : ["menu-start", 0], gradientEnd : ["menu-end", 100], shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 1, width : 1, color : "border-main" } }, "menu-separator" : { decorator : qx.ui.decoration.Single, style : { widthTop : 1, colorTop : "menu-separator-top", widthBottom : 1, colorBottom : "menu-separator-bottom" } }, /* --------------------------------------------------------------------------- MENU BAR --------------------------------------------------------------------------- */ "menubar" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/menu/bar-background.png", backgroundRepeat : "scale", width : 1, color : "border-separator", style : "solid" } }, "menubar-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["menubar-start", 0], gradientEnd : ["menu-end", 100], width : 1, color : "border-separator" } }, /* --------------------------------------------------------------------------- APPLICATION --------------------------------------------------------------------------- */ "app-header": { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/app-header.png", backgroundRepeat : "scale" } }, /* --------------------------------------------------------------------------- PROGRESSBAR --------------------------------------------------------------------------- */ "progressbar" : { decorator: qx.ui.decoration.Single, style: { width: 1, color: "border-input" } }, /* --------------------------------------------------------------------------- VIRTUAL WIDGETS --------------------------------------------------------------------------- */ "group-item" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/group-item.png", backgroundRepeat : "scale" } }, "group-item-css" : { decorator : [ qx.ui.decoration.MLinearBackgroundGradient ], style : { startColorPosition : 0, endColorPosition : 100, startColor : "groupitem-start", endColor : "groupitem-end" } } } });
icarusfactor/lugDBwizard
qooxdoo_source/lugwizupdate/source/script/lugwiz.10a10b4d8340.js
JavaScript
gpl-3.0
775,345
(function (angular) { angular.module("rmApp", ["ui.router", "rmApp.templates", "rmApp.controllers"]) .config(["$stateProvider", "$urlRouterProvider", "$locationProvider", function ($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider.otherwise("/"); $locationProvider.html5Mode(false); // $stateProvider .state("index", { url: "/", templateUrl: "index.tpl.html", controller: "rmCtrl" }) .state("home", { url: "/home", templateUrl: "home.tpl.html", controller: "rmCtrl" }).state("about", { url: "/about", templateUrl: "about.tpl.html", controller: "rmCtrl" }).state("contact", { url: "/contact", templateUrl: "contact.tpl.html", controller: "rmCtrl" }).state("spinner1", { url: "/spinner1", templateUrl: "spinner1.tpl.html", controller: "rmCtrl" }).state("spinner2", { url: "/spinner2", templateUrl: "spinner2.tpl.html", controller: "rmCtrl" }); }]); })(angular);
rawlinsmethod/ProAngularJS
app/www/js/routers/index.rtr.js
JavaScript
gpl-3.0
1,378
/** * */ var $info = false; function LoadServerStats() { $.getJSON("phpsysinfo/xml.php?plugin=complete&json", function (data) { $info = data; updateCPU($info.Vitals["@attributes"].LoadAvg, $info.Vitals["@attributes"].Processes); updateRAM($info.Memory["@attributes"].Percent); updateHDD($info.FileSystem.Mount[0]["@attributes"].Percent); /** OTHER INFO **/ updateIP($info.Network.NetDevice); updateUptime($info.Vitals["@attributes"].Uptime); updateUSB($info.Hardware.USB.Device); }); setTimeout(LoadServerStats, 10000); } function updateUSB(devices) { var $html = ""; $.each(devices, function (i, val) { $html += '<div class="row"><span class="value">' + val['@attributes'].Name + '</span></div>'; }); $('.other-info-stats .usb-devices .usb-list').html($html); } function updateUptime(value) { var d = new Date(0, 0, 0, 0, 0, value); var s = d.getSeconds(); var m = d.getMinutes(); var h = d.getHours(); var D = d.getDate(); var M = d.getMonth(); var Y = d.getYear(); var formated = ''; if (Y > 0) formated += ' ' + Y + 'Y' if (M > 0) formated += ' ' + M + 'M' if (D > 0) formated += ' ' + D + 'D' if (h > 0) formated += ' ' + h + 'h' if (m > 0) formated += ' ' + m + 'm' if (s > 0) formated += ' ' + s + 's' $('.other-info-stats .uptime span.value').html(formated); } function updateIP(value) { var ipadd = "" if ($.isArray(value)) { $.each(value, function (i, val) { var list = val['@attributes'].Info; var arr = list.split(';'); ipadd += ' ' + arr[1]; }); } else { var list = value['@attributes'].Info; var arr = list.split(';'); ipadd += ' ' + arr[1]; } $('.other-info-stats .ip-address span.value').html(ipadd); } function updateHDD(value) { $('.usage .disk .progress-bar').css('width', value + '%'); $('.usage .disk .progress-bar span.value').html(value + '%'); } function updateRAM(value) { $('.ram.chart').data('easyPieChart').update(Math.round(value)); } function updateCPU(loadavg, processesCount) { var data = loadavg; var arr = data.split(' '); var $value = (arr[0] / processesCount) * 100; $('.cpu.chart').data('easyPieChart').update(Math.round($value)); }
volrathxiii/Avy
js/serverstats.js
JavaScript
gpl-3.0
2,489
import React from "react"; import PropTypes from "prop-types"; import styled from "@emotion/styled"; import { insertEmbeddedImages } from "../../../utils/embedded-images"; const RichTextareaFieldResponseWrapper = styled("div")(props => ({ // TODO: fluid video lineHeight: "1.3rem", "& img": { maxWidth: "100%", margin: "16px 0 0 0", }, "& ul": { marginTop: 0, marginBottom: "16px", fontWeight: "normal", }, "& p": { fontFamily: props.theme.text.bodyFontFamily, marginTop: 0, marginBottom: "16px", fontWeight: "normal", }, "& li": { fontFamily: props.theme.text.bodyFontFamily, fontWeight: "normal", }, "& a": { textDectoration: "none", fontWeight: "normal", }, "& h1,h2,h3,h4,h5,h6": { fontFamily: props.theme.text.titleFontFamily, margin: "16px 0 8px 0", }, })); const RichTextareaFieldResponse = props => { return ( <RichTextareaFieldResponseWrapper> <div className="rich-textarea-field-response" dangerouslySetInnerHTML={{ __html: insertEmbeddedImages(props.value, props.attachments), }} /> </RichTextareaFieldResponseWrapper> ); }; RichTextareaFieldResponse.propTypes = { attachments: PropTypes.array, value: PropTypes.string.isRequired, }; export default RichTextareaFieldResponse;
smartercleanup/platform
src/base/static/components/form-fields/types/rich-textarea-field-response.js
JavaScript
gpl-3.0
1,342
// ********************************************************************************** // Websocket backend for the Raspberry Pi IoT Framework // ********************************************************************************** // Modified from the Moteino IoT Framework - http://lowpowerlab.com/gateway // By Felix Rusu, Low Power Lab LLC (2015), http://lowpowerlab.com/contact // ********************************************************************************** // Based on Node.js, socket.io, NeDB // This is a work in progress and is released without any warranties expressed or implied. // Please read the details below. // Also ensure you change the settings in this file to match your hardware and email settings etc. // ********************************************************************************** // NeDB is Node Embedded Database - a persistent database for Node.js, with no dependency // Specs and documentation at: https://github.com/louischatriot/nedb // // Under the hood, NeDB's persistence uses an append-only format, meaning that all updates // and deletes actually result in lines added at the end of the datafile. The reason for // this is that disk space is very cheap and appends are much faster than rewrites since // they don't do a seek. The database is automatically compacted (i.e. put back in the // one-line-per-document format) everytime your application restarts. // // This script is configured to compact the database every 24 hours since time of start. // ******************************************************************************************** // Copyright Brian Ladner // ******************************************************************************************** // LICENSE // ******************************************************************************************** // This source code is released under GPL 3.0 with the following ammendments: // You are free to use, copy, distribute and transmit this Software for non-commercial purposes. // - You cannot sell this Software for profit while it was released freely to you by Low Power Lab LLC. // - You may freely use this Software commercially only if you also release it freely, // without selling this Software portion of your system for profit to the end user or entity. // If this Software runs on a hardware system that you sell for profit, you must not charge // any fees for this Software, either upfront or for retainer/support purposes // - If you want to resell this Software or a derivative you must get permission from Low Power Lab LLC. // - You must maintain the attribution and copyright notices in any forks, redistributions and // include the provided links back to the original location where this work is published, // even if your fork or redistribution was initially an N-th tier fork of this original release. // - You must release any derivative work under the same terms and license included here. // - This Software is released without any warranty expressed or implied, and Low Power Lab LLC // will accept no liability for your use of the Software (except to the extent such liability // cannot be excluded as required by law). // - Low Power Lab LLC reserves the right to adjust or replace this license with one // that is more appropriate at any time without any prior consent. // Otherwise all other non-conflicting and overlapping terms of the GPL terms below will apply. // ******************************************************************************************** // This program is free software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software Foundation; // either version 3 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program. // If not license can be viewed at: http://www.gnu.org/licenses/gpl-3.0.txt // // Please maintain this license information along with authorship // and copyright notices in any redistribution of this code // ********************************************************************************** //var io = require('socket.io').listen(8080); var io = require('socket.io').listen(8888); var Datastore = require('nedb'); var globalFunctions = require('./globals'); var alerts = require('./alerts'); var clients = require('./clients'); var logger = require("./logger"); var cfg = require('./config.default'); var alertsDef = new alerts(); var clientsDef = new clients(); // db to keep all devices and changes var db = new Datastore({ filename: __dirname + '/databases/DBclients.db', autoload: true }); db.persistence.setAutocompactionInterval(86400000); //daily // authorize handshake - make sure the request is coming from nginx, // not from the outside world. If you comment out this section, you // will be able to hit this socket directly at the port it's running // at, from anywhere! This was tested on Socket.IO v1.2.1 and will // not work on older versions io.use(function(socket, next) { var handshakeData = socket.request; var remoteAddress = handshakeData.connection.remoteAddress; var remotePort = handshakeData.connection.remotePort; logger.info("AUTHORIZING CONNECTION FROM " + remoteAddress + ":" + remotePort); if (remoteAddress == "localhost" || remoteAddress == "127.0.0.1") { logger.info('IDENTITY ACCEPTED: from local host'); next(); } else { var remote_add = remoteAddress.split(".",3); var compare_str = cfg.locnet.start.split(".",3); if (remote_add[0] == compare_str[0] && remote_add[1] == compare_str[1] && remote_add[2] == compare_str[2]) { logger.info('IDENTITY ACCEPTED: from local network'); next(); } else { logger.error('REJECTED IDENTITY, not coming from local network'); next(new Error('REJECTED IDENTITY, not coming from local network')); } } }); io.on('connection', function (socket) { logger.info("Socket connected!"); socket.emit('ALERTSDEF', alertsDef.availableAlerts); socket.emit('CLIENTSDEF', clientsDef); db.find({ _id : { $exists: true } }, function (err, entries) { io.emit('UPDATENODES', entries); }); socket.on('SEND_DATA', function (deviceData) { logger.info("Updating node info for node: " + deviceData.name); db.find({ _id : deviceData.deviceID }, function (err, entries) { var existingNode = new Object(); if (entries.length == 1) existingNode = entries[0]; existingNode._id = deviceData.deviceID; //existingNode.rssi = deviceData.signalStrength; //update signal strength we last heard from this node, regardless of any matches existingNode.type = deviceData.type; existingNode.label = deviceData.name; existingNode.Status = deviceData.Status; existingNode.lastStateChange = deviceData.lastStateChange; existingNode.updated = new Date().getTime(); //update timestamp we last heard from this node, regardless of any matches // set up existing alert schedules if (existingNode.alerts) { for (var alertKey in existingNode.alerts) { if (existingNode.alerts[alertKey].alertStatus) { if (existingNode.Status == existingNode.alerts[alertKey].clientStatus) { addSchedule(existingNode, alertKey); } else { removeSchedule(existingNode._id, alertKey); } } } } // add entry into database if (entries.length == 0) { db.insert(existingNode); logger.info(' [' + existingNode._id + '] DB-Insert new _id:' + id); } else { db.update({_id:existingNode._id},{$set:existingNode},{}, function (err,numReplaced) { logger.info(' [' + existingNode._id + '] DB-Updates:' + numReplaced); }); } io.emit('LOG', existingNode); io.emit('UPDATENODE', existingNode); alertsDef.handleNodeAlerts(existingNode); }); }); socket.on('CLIENT_INFO', function (deviceData) { logger.info("Updating client info for node: " + deviceData.nodeID); db.find({ _id : deviceData.nodeID }, function (err, entries) { if (entries.length == 1) { var existingNode = entries[0]; existingNode.infoUpdate = deviceData.lastUpdate||undefined; existingNode.rssi = deviceData.wifi||undefined; existingNode.uptime = deviceData.uptime||undefined; existingNode.cpuTemp = deviceData.cpuTemp||undefined; existingNode.temperature = deviceData.temperature||undefined; existingNode.humidity = deviceData.humidity||undefined; existingNode.photo = deviceData.photo||undefined; db.update({_id:deviceData.nodeID},{$set:existingNode},{}, function (err,numReplaced) { //logger.info(' [' + deviceData.nodeID + '] CLIENT_INFO records replaced:' + numReplaced); }); io.emit('UPDATENODE', existingNode); } }); }); socket.on('CONSOLE', function (msg) { logger.info(msg); }); socket.on('UPDATE_DB_ENTRY', function (node) { db.find({ _id : node._id }, function (err, entries) { if (entries.length == 1) { var dbNode = entries[0]; dbNode.type = node.type||undefined; dbNode.label = node.label||undefined; dbNode.descr = node.descr||undefined; dbNode.hidden = (node.hidden == 1 ? 1 : undefined); db.update({ _id: dbNode._id }, { $set : dbNode}, {}, function (err, numReplaced) { logger.info('UPDATE_DB_ENTRY records replaced:' + numReplaced); }); io.emit('UPDATENODE', dbNode); //post it back to all clients to confirm UI changes logger.debug("UPDATE DB ENTRY found docs:" + entries.length); } }); }); socket.on('EDITNODEALERT', function (nodeId, alertKey, newAlert) { logger.debug('**** EDITNODEALERT **** key:' + alertKey); db.find({ _id : nodeId }, function (err, entries) { if (entries.length == 1) { var dbNode = entries[0]; if (newAlert == null) { if (dbNode.alerts[alertKey]) delete dbNode.alerts[alertKey]; } else { if (!dbNode.alerts) { dbNode.alerts = {}; } dbNode.alerts[alertKey] = newAlert; } db.update({ _id: dbNode._id }, { $set : dbNode}, {}, function (err, numReplaced) { logger.debug('DB alert Updated:' + numReplaced); }); if (dbNode.alerts[alertKey] && dbNode.alerts[alertKey].alertStatus) { addSchedule(dbNode, alertKey); } else { removeSchedule(dbNode._id, alertKey); } io.emit('UPDATENODE', dbNode); //post it back to all clients to confirm UI changes } }); }); socket.on('NODEACTION', function (node) { if (node.nodeId && node.action) { logger.info('NODEACTION sent: ' + JSON.stringify(node)); io.emit('ACTION', node); } }); socket.on('DELETENODE', function (nodeId) { db.remove({ _id : nodeId }, function (err, removedCount) { logger.info('DELETED entries: ' + removedCount); db.find({ _id : { $exists: true } }, function (err, entries) { io.emit('UPDATENODES', entries); }); }); removeSchedule(nodeId, null); }); socket.on('SCHEDULE', function () { logger.info("Scheduled Alerts: " + scheduledAlerts); //io.emit('LOG', scheduledAlerts); }); }); // ************************************ // ********** SCHEDULE SETUP ********** // ************************************ //keep track of scheduler based events - these need to be kept in sych with the UI //if UI removes an event, it needs to be cancelled from here as well; // if UI adds a scheduled event it needs to be scheduled and added here also scheduledAlerts = []; //each entry should be defined like this: {nodeId, eventKey, timer} //schedule and register a scheduled type event //function schedule(node, alertKey) { function addSchedule(node, alertKey) { var nextRunTimeout = node.alerts[alertKey].timeout; logger.info('**** ADDING ALERT - nodeId:' + node._id + ' event:' + alertKey + ' to run ' + (nextRunTimeout/60000).toFixed(2) + ' minutes after status is ' + node.alerts[alertKey].clientStatus); var theTimer = setTimeout(function() { var currentTime = new Date().getTime(); logger.debug('Alert Timeout Function for node ' + node._id + ', alert for ' + alertKey); if (node.alerts[alertKey].clientStatus == node.Status && currentTime - node.lastStateChange >= node.alerts[alertKey].timeout) { alertsDef.testAlert(node, alertKey); } removeSchedule(node._id, alertKey); }, nextRunTimeout); //http://www.w3schools.com/jsref/met_win_settimeout.asp scheduledAlerts.push({nodeId:node._id, alertKey:alertKey, timer:theTimer}); //save nodeId, eventKey and timer (needs to be removed if the event is disabled/removed from the UI) } function removeSchedule(nodeId, alertKey) { for (var s in scheduledAlerts) { if (scheduledAlerts[s].nodeId == nodeId) { if (alertKey == null || scheduledAlerts[s].alertKey == alertKey){ logger.info('**** REMOVING SCHEDULED ALERT - nodeId:' + nodeId + 'alert:' + scheduledAlerts[s].alertKey); clearTimeout(scheduledAlerts[s].timer); scheduledAlerts.splice(scheduledAlerts.indexOf(scheduledAlerts[s]), 1) } } } } // ************************************
bjladner/IoPiGateway
gateway.js
JavaScript
gpl-3.0
14,853
/* * This file is part of ARSnova Mobile. * Copyright (C) 2011-2012 Christian Thomas Weber * Copyright (C) 2012-2017 The ARSnova Team * * ARSnova Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ARSnova Mobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ARSnova Mobile. If not, see <http://www.gnu.org/licenses/>. */ Ext.define("ARSnova.controller.Sessions", { extend: 'Ext.app.Controller', requires: [ 'ARSnova.model.Session', 'ARSnova.view.speaker.TabPanel', 'ARSnova.view.feedback.TabPanel', 'ARSnova.view.feedbackQuestions.TabPanel', 'ARSnova.view.user.TabPanel', 'ARSnova.view.user.QuestionPanel' ], launch: function () { /* (Re)join session on Socket.IO connect event */ ARSnova.app.socket.addListener("arsnova/socket/connect", function () { var keyword = sessionStorage.getItem('keyword'); if (keyword) { ARSnova.app.socket.setSession(keyword); ARSnova.app.getController('Feature').lastUpdate = Date.now(); } }); }, login: function (options) { console.debug("Controller: Sessions.login", options); if (options.keyword.length !== 8) { Ext.Msg.alert(Messages.NOTIFICATION, Messages.SESSION_ID_INVALID_LENGTH); sessionStorage.clear(); return; } if (options.keyword.match(/[^0-9]/)) { Ext.Msg.alert(Messages.NOTIFICATION, Messages.SESSION_ID_INVALID); sessionStorage.clear(); return; } /* do login stuff */ var hideLoadMask = ARSnova.app.showLoadIndicator(Messages.LOAD_MASK_LOGIN); var res = ARSnova.app.sessionModel.checkSessionLogin(options.keyword, { success: function (obj) { // check if user is creator of this session if (ARSnova.app.userRole === ARSnova.app.USER_ROLE_SPEAKER) { ARSnova.app.isSessionOwner = true; } else { // check if session is open if (!obj.active) { Ext.Msg.alert(Messages.NOTIFICATION, Messages.SESSION_IS_CLOSED.replace(/###/, obj.name)); sessionStorage.clear(); return; } ARSnova.app.userRole = ARSnova.app.USER_ROLE_STUDENT; ARSnova.app.isSessionOwner = false; } // set local variables localStorage.setItem('sessionId', obj._id); localStorage.setItem('name', obj.name); localStorage.setItem('shortName', obj.shortName); localStorage.setItem('courseId', obj.courseId || ""); localStorage.setItem('courseType', obj.courseType || ""); localStorage.setItem('active', obj.active ? 1 : 0); localStorage.setItem('creationTime', obj.creationTime); sessionStorage.setItem('keyword', obj.keyword); sessionStorage.setItem('features', Ext.encode(obj.features)); ARSnova.app.feedbackModel.lock = obj.feedbackLock; // initialize MathJax ARSnova.app.getController('MathJaxMarkdown').initializeMathJax(); // deactivate several about tabs ARSnova.app.mainTabPanel.tabPanel.deactivateAboutTabs(); ARSnova.app.socket.setSession(obj.keyword); ARSnova.app.getController('Feature').lastUpdate = Date.now(); // start task to update the feedback tab in tabBar ARSnova.app.feedbackModel.on("arsnova/session/feedback/count", ARSnova.app.mainTabPanel.tabPanel.updateFeedbackBadge, ARSnova.app.mainTabPanel.tabPanel); ARSnova.app.feedbackModel.on("arsnova/session/feedback/average", ARSnova.app.mainTabPanel.tabPanel.updateFeedbackIcon, ARSnova.app.mainTabPanel.tabPanel); ARSnova.app.taskManager.start(ARSnova.app.mainTabPanel.tabPanel.config.updateHomeTask); ARSnova.app.mainTabPanel.tabPanel.updateHomeBadge(); ARSnova.app.getController('Sessions').reloadData(false, hideLoadMask); }, notFound: function () { Ext.Msg.alert(Messages.NOTIFICATION, Messages.SESSION_NOT_FOUND); sessionStorage.clear(); hideLoadMask(); }, forbidden: function () { Ext.Msg.alert(Messages.NOTIFICATION, Messages.SESSION_LOCKED); sessionStorage.clear(); hideLoadMask(); }, failure: function () { Ext.Msg.alert(Messages.NOTIFICATION, Messages.CONNECTION_PROBLEM); sessionStorage.clear(); hideLoadMask(); } }); }, logout: function (prevFeatures) { ARSnova.app.socket.setSession(null); ARSnova.app.sessionModel.fireEvent(ARSnova.app.sessionModel.events.sessionLeave); ARSnova.app.loggedInModel.resetActiveUserCount(); // stop task to update the feedback tab in tabBar ARSnova.app.feedbackModel.un("arsnova/session/feedback/count", ARSnova.app.mainTabPanel.tabPanel.updateFeedbackBadge); ARSnova.app.feedbackModel.un("arsnova/session/feedback/average", ARSnova.app.mainTabPanel.tabPanel.updateFeedbackIcon); // online counter badge ARSnova.app.taskManager.stop(ARSnova.app.mainTabPanel.tabPanel.config.updateHomeTask); sessionStorage.removeItem("keyword"); sessionStorage.removeItem("features"); sessionStorage.removeItem("answeredCanceledPiQuestions"); localStorage.removeItem("sessionId"); localStorage.removeItem("name"); localStorage.removeItem("shortName"); localStorage.removeItem("active"); localStorage.removeItem("session"); localStorage.removeItem("courseId"); localStorage.removeItem("courseType"); localStorage.removeItem("creationTime"); ARSnova.app.isSessionOwner = false; /* show about tab panels */ ARSnova.app.mainTabPanel.tabPanel.activateAboutTabs(); ARSnova.app.sessionModel.isLearningProgessOptionsInitialized = false; var tabPanel = ARSnova.app.mainTabPanel.tabPanel; /* show home Panel */ tabPanel.animateActiveItem(tabPanel.homeTabPanel, { type: 'slide', direction: 'right', duration: 700 }); if (ARSnova.app.userRole === ARSnova.app.USER_ROLE_SPEAKER) { /* hide speaker tab panel and destroy listeners */ tabPanel.speakerTabPanel.tab.hide(); tabPanel.speakerTabPanel.inClassPanel.destroyListeners(); /* hide feedback questions panel */ tabPanel.feedbackQuestionsPanel.tab.hide(); } else { /* hide user tab panel and destroy listeners */ if (tabPanel.userTabPanel) { tabPanel.userTabPanel.tab.hide(); tabPanel.userTabPanel.inClassPanel.destroyListeners(); } if (tabPanel.userQuestionsPanel) { tabPanel.userQuestionsPanel.tab.hide(); } if (localStorage.getItem('lastVisitedRole') === ARSnova.app.USER_ROLE_SPEAKER) { localStorage.setItem('role', ARSnova.app.USER_ROLE_SPEAKER); ARSnova.app.userRole = ARSnova.app.USER_ROLE_SPEAKER; localStorage.removeItem('lastVisitedRole'); } } /* hide feedback statistic panel */ tabPanel.feedbackTabPanel.tab.hide(); }, liveClickerSessionReload: function (prevFeatures) { var keyword = sessionStorage.getItem("keyword"); Ext.toast('Session wird neu geladen...', 3000); ARSnova.app.getController('Sessions').logout(prevFeatures); ARSnova.app.getController('Sessions').login({keyword: keyword}); }, reloadData: function (animation, hideLoadMask) { var features = ARSnova.app.getController('Feature').getActiveFeatures(); hideLoadMask = hideLoadMask || Ext.emptyFn; animation = animation || { type: 'slide', duration: 700 }; if (features.liveClicker && ARSnova.app.userRole !== ARSnova.app.USER_ROLE_SPEAKER && localStorage.getItem('lastVisitedRole') !== ARSnova.app.USER_ROLE_SPEAKER) { this.loadClickerSession(animation, hideLoadMask); } else { this.loadDefaultSession(animation, hideLoadMask); } }, loadClickerSession: function (animation, hideLoadMask) { var tabPanel = ARSnova.app.mainTabPanel.tabPanel; /* add feedback statistic panel*/ if (!tabPanel.feedbackTabPanel) { tabPanel.feedbackTabPanel = Ext.create('ARSnova.view.feedback.TabPanel'); tabPanel.insert(3, tabPanel.feedbackTabPanel); } else { tabPanel.feedbackTabPanel.tab.show(); tabPanel.feedbackTabPanel.renew(); } if (tabPanel.userTabPanel) { tabPanel.userTabPanel.tab.hide(); } if (tabPanel.userQuestionsPanel) { tabPanel.userQuestionsPanel.tab.hide(); } if (ARSnova.app.feedbackModel.lock) { tabPanel.feedbackTabPanel.setActiveItem(tabPanel.feedbackTabPanel.statisticPanel); } else { tabPanel.feedbackTabPanel.setActiveItem(tabPanel.feedbackTabPanel.votePanel); } tabPanel.animateActiveItem(tabPanel.feedbackTabPanel, animation); ARSnova.app.getController('Feature').applyFeatures(); ARSnova.app.sessionModel.sessionIsActive = true; hideLoadMask(); }, loadDefaultSession: function (animation, hideLoadMask) { var tabPanel = ARSnova.app.mainTabPanel.tabPanel; var features = ARSnova.app.getController('Feature').getActiveFeatures(); var target; if (ARSnova.app.isSessionOwner && ARSnova.app.userRole === ARSnova.app.USER_ROLE_SPEAKER) { ARSnova.app.sessionModel.fireEvent(ARSnova.app.sessionModel.events.sessionJoinAsSpeaker); /* add speaker in class panel */ if (!tabPanel.speakerTabPanel) { tabPanel.speakerTabPanel = Ext.create('ARSnova.view.speaker.TabPanel'); tabPanel.insert(1, tabPanel.speakerTabPanel); } else { tabPanel.speakerTabPanel.tab.show(); tabPanel.speakerTabPanel.renew(); } /* add feedback statistic panel*/ if (!tabPanel.feedbackTabPanel) { tabPanel.feedbackTabPanel = Ext.create('ARSnova.view.feedback.TabPanel'); tabPanel.insert(3, tabPanel.feedbackTabPanel); } else { tabPanel.feedbackTabPanel.tab.show(); tabPanel.feedbackTabPanel.renew(); } target = features.liveClicker ? tabPanel.feedbackTabPanel : tabPanel.speakerTabPanel; tabPanel.animateActiveItem(target, animation); tabPanel.speakerTabPanel.inClassPanel.registerListeners(); } else { ARSnova.app.sessionModel.fireEvent(ARSnova.app.sessionModel.events.sessionJoinAsStudent); /* add user in class panel */ if (!tabPanel.userTabPanel) { tabPanel.userTabPanel = Ext.create('ARSnova.view.user.TabPanel'); tabPanel.insert(0, tabPanel.userTabPanel); } else { tabPanel.userTabPanel.tab.show(); tabPanel.userTabPanel.renew(); } tabPanel.userTabPanel.inClassPanel.registerListeners(); /* add skill questions panel*/ if (!tabPanel.userQuestionsPanel) { tabPanel.userQuestionsPanel = Ext.create('ARSnova.view.user.QuestionPanel'); tabPanel.insert(1, tabPanel.userQuestionsPanel); } else { tabPanel.userQuestionsPanel.tab.show(); } /* add feedback statistic panel*/ if (!tabPanel.feedbackTabPanel) { tabPanel.feedbackTabPanel = Ext.create('ARSnova.view.feedback.TabPanel'); tabPanel.insert(2, tabPanel.feedbackTabPanel); } else { tabPanel.feedbackTabPanel.tab.show(); tabPanel.feedbackTabPanel.renew(); } target = features.liveClicker ? tabPanel.feedbackTabPanel : tabPanel.userTabPanel; tabPanel.animateActiveItem(target, animation); } /* add feedback questions panel*/ if (!tabPanel.feedbackQuestionsPanel) { tabPanel.feedbackQuestionsPanel = Ext.create('ARSnova.view.feedbackQuestions.TabPanel'); if (ARSnova.app.userRole === ARSnova.app.USER_ROLE_SPEAKER) { tabPanel.insert(2, tabPanel.feedbackQuestionsPanel); } else { tabPanel.insert(4, tabPanel.feedbackQuestionsPanel); } } if (ARSnova.app.userRole === ARSnova.app.USER_ROLE_SPEAKER) { tabPanel.feedbackQuestionsPanel.tab.show(); } else { tabPanel.feedbackQuestionsPanel.tab.hide(); } ARSnova.app.getController('Feature').applyFeatures(); ARSnova.app.sessionModel.sessionIsActive = true; tabPanel.feedbackQuestionsPanel.questionsPanel.prepareQuestionList(); hideLoadMask(); }, update: function (sessionInfo) { var session = ARSnova.app.sessionModel; session.setData(sessionInfo); session.validate(); session.update({ success: function (response) { var fullSession = Ext.decode(response.responseText); localStorage.setItem('sessionId', fullSession._id); localStorage.setItem('name', fullSession.name); localStorage.setItem('shortName', fullSession.shortName); localStorage.setItem('active', fullSession.active ? 1 : 0); localStorage.setItem('courseId', fullSession.courseId || ""); localStorage.setItem('courseType', fullSession.courseType || ""); localStorage.setItem('creationTime', fullSession.creationTime); localStorage.setItem('keyword', fullSession.keyword); ARSnova.app.isSessionOwner = true; }, failure: function (response) { Ext.Msg.alert("Hinweis!", "Die Verbindung zum Server konnte nicht hergestellt werden"); } }); }, loadFeatureOptions: function (options, sessionCreation) { var activePanel = ARSnova.app.mainTabPanel.tabPanel.getActiveItem(); var useCasePanel = Ext.create('ARSnova.view.diagnosis.UseCasePanel', { options: options, sessionCreationMode: sessionCreation, inClassSessionEntry: !sessionCreation }); activePanel.animateActiveItem(useCasePanel, 'slide'); }, validateSessionOptions: function (options) { var session = ARSnova.app.sessionModel; session.setData({ type: 'session', name: options.name.trim(), shortName: options.shortName.trim(), creator: localStorage.getItem('login'), courseId: options.courseId, courseType: options.courseType, creationTime: Date.now(), ppAuthorName: options.ppAuthorName, ppAuthorMail: options.ppAuthorMail, ppUniversity: options.ppUniversity, ppLogo: options.ppLogo, ppSubject: options.ppSubject, ppLicense: options.ppLicense, ppDescription: options.ppDescription, ppFaculty: options.ppFaculty, ppLevel: options.ppLevel, sessionType: options.sessionType }); session.set('_id', undefined); var validation = session.validate(); if (!validation.isValid()) { Ext.Msg.alert('Hinweis', 'Bitte alle markierten Felder ausfüllen.'); var panel = ARSnova.app.mainTabPanel.tabPanel.homeTabPanel.newSessionPanel; panel.down('fieldset').items.items.forEach(function (el) { if (el.xtype === 'textfield') { el.removeCls("required"); } }); validation.items.forEach(function (el) { panel.down('textfield[name=' + el.getField() + ']').addCls("required"); }); /* activate inputElements in newSessionPanel */ if (options.lastPanel && typeof options.lastPanel.enableInputElements() === 'function') { options.lastPanel.enableInputElements(); } return false; } return session; }, create: function (options) { var session = this.validateSessionOptions(options); var hideLoadMask = ARSnova.app.showLoadIndicator(Messages.LOAD_MASK_SAVE, 10000); if (!session) { return; } session.create({ success: function (response) { var fullSession = Ext.decode(response.responseText); var loginName = ""; var loginMode = localStorage.getItem("loginMode"); sessionStorage.setItem('keyword', fullSession.keyword); localStorage.setItem('sessionId', fullSession._id); ARSnova.app.getController('Auth').services.then(function (services) { services.forEach(function (service) { if (loginMode === service.id) { loginName = "guest" === service.id ? Messages.GUEST : service.name; } }); var messageBox = Ext.create('Ext.MessageBox', { title: Messages.SESSION + ' ID: ' + fullSession.keyword, message: Messages.ON_SESSION_CREATION_1.replace(/###/, fullSession.keyword), cls: 'newSessionMessageBox', listeners: { show: hideLoadMask, hide: function () { ARSnova.app.getController('Sessions').login({keyword: fullSession.keyword}); var panel = ARSnova.app.mainTabPanel.tabPanel.homeTabPanel; panel.setActiveItem(panel.mySessionsPanel); /* activate inputElements in newSessionPanel */ if (options.lastPanel && typeof options.lastPanel.enableInputElements() === 'function') { options.lastPanel.enableInputElements(); } this.destroy(); } } }); messageBox.setButtons([{ text: Messages.CONTINUE, itemId: 'continue', ui: 'action', handler: function () { if (!this.readyToClose) { messageBox.setMessage(''); messageBox.setTitle(Messages.SESSION + ' ID: ' + fullSession.keyword); messageBox.setHtml("<div class='x-msgbox-text x-layout-box-item' +" + " style='margin-top: -10px;'>" + Messages.ON_SESSION_CREATION_2.replace(/###/, loginName + "-Login " + "<div style='display: inline-block;'" + "class='text-icons login-icon-" + loginMode + "'></div> " + (loginMode === "guest" ? Messages.ON_THIS_DEVICE : "")) + ".</div>"); this.readyToClose = true; } else { messageBox.hide(); if (messageBox.showFeatureError) { Ext.Msg.alert("", Messages.FEATURE_SETTINGS_COULD_NOT_BE_SAVED); } } } }]); if (options.features) { ARSnova.app.sessionModel.changeFeatures(sessionStorage.getItem("keyword"), options.features, { success: function () { messageBox.show(); }, failure: function () { messageBox.showFeatureError = true; messageBox.show(); } }); } else { messageBox.show(); } }); }, failure: function (records, operation) { Ext.Msg.alert("Hinweis!", "Die Verbindung zum Server konnte nicht hergestellt werden"); if (options.lastPanel && typeof options.lastPanel.enableInputElements() === 'function') { options.lastPanel.enableInputElements(); } } }); }, changeRole: function () { var tabPanel = ARSnova.app.mainTabPanel.tabPanel; var hideLoadMask = ARSnova.app.showLoadIndicator(Messages.CHANGE_ROLE + '...', 2000); var reloadSession = function (animationDirection, onAnimationEnd) { tabPanel.updateHomeBadge(); ARSnova.app.socket.setSession(null); ARSnova.app.socket.setSession(sessionStorage.getItem('keyword')); ARSnova.app.getController('Feature').lastUpdate = Date.now(); onAnimationEnd = (typeof onAnimationEnd === 'function') ? onAnimationEnd : hideLoadMask; tabPanel.feedbackQuestionsPanel.initializeQuestionsPanel(); ARSnova.app.getController('Sessions').reloadData({ listeners: {animationend: onAnimationEnd}, direction: animationDirection, type: 'flip' }); }; if (ARSnova.app.userRole === ARSnova.app.USER_ROLE_SPEAKER) { localStorage.setItem('lastVisitedRole', ARSnova.app.USER_ROLE_SPEAKER); localStorage.setItem('role', ARSnova.app.USER_ROLE_STUDENT); ARSnova.app.userRole = ARSnova.app.USER_ROLE_STUDENT; /* hide speaker tab panel and destroy listeners */ tabPanel.speakerTabPanel.tab.hide(); tabPanel.speakerTabPanel.inClassPanel.destroyListeners(); reloadSession('right'); } else { if (localStorage.getItem('lastVisitedRole') === ARSnova.app.USER_ROLE_SPEAKER) { localStorage.setItem('role', ARSnova.app.USER_ROLE_SPEAKER); ARSnova.app.userRole = ARSnova.app.USER_ROLE_SPEAKER; localStorage.removeItem('lastVisitedRole'); /* hide user tab panels and destroy listeners */ tabPanel.userTabPanel.tab.hide(); tabPanel.userQuestionsPanel.tab.hide(); tabPanel.userTabPanel.inClassPanel.destroyListeners(); reloadSession('left', function () { /* remove user tab panel and user questions panel*/ tabPanel.remove(tabPanel.userQuestionsPanel); tabPanel.remove(tabPanel.userTabPanel); delete tabPanel.userQuestionsPanel; delete tabPanel.userTabPanel; hideLoadMask(); }); } } }, checkExistingSessionLogin: function () { if (localStorage.getItem('lastVisitedRole') === ARSnova.app.USER_ROLE_SPEAKER) { localStorage.setItem('role', ARSnova.app.USER_ROLE_SPEAKER); ARSnova.app.userRole = ARSnova.app.USER_ROLE_SPEAKER; localStorage.removeItem('lastVisitedRole'); } if (sessionStorage.getItem("keyword")) { return true; } return false; }, setActive: function (options) { ARSnova.app.sessionModel.lock(sessionStorage.getItem("keyword"), options.active, { success: function () { var sessionStatus = ARSnova.app.mainTabPanel.tabPanel.speakerTabPanel.inClassPanel.inClassActions.sessionStatusButton; if (options.active) { sessionStatus.sessionOpenedSuccessfully(); } else { sessionStatus.sessionClosedSuccessfully(); } }, failure: function (records, operation) { Ext.Msg.alert("Hinweis!", "Session speichern war nicht erfolgreich"); } }); }, setLearningProgressOptions: function (options) { ARSnova.app.sessionModel.setLearningProgressOptions(options); }, getLearningProgressOptions: function () { return ARSnova.app.sessionModel.getLearningProgress(); }, getCourseLearningProgress: function (options) { ARSnova.app.sessionModel.getCourseLearningProgressWithOptions( sessionStorage.getItem("keyword"), options.progress, options.callbacks ); }, getMyLearningProgress: function (options) { ARSnova.app.sessionModel.getMyLearningProgressWithOptions( sessionStorage.getItem("keyword"), options.progress, options.callbacks ); } });
dhx/arsnova-mobile
src/main/webapp/app/controller/Sessions.js
JavaScript
gpl-3.0
21,215