Merge branch 'master' into mediafoundation

# Conflicts:
#	assets/webconfig/content/dashboard.html
#	assets/webconfig/i18n/en.json
#	assets/webconfig/js/content_dashboard.js
#	assets/webconfig/js/content_logging.js
#	assets/webconfig/js/hyperion.js
#	assets/webconfig/js/ui_utils.js
This commit is contained in:
LordGrey
2021-05-02 21:12:00 +02:00
139 changed files with 9391 additions and 4785 deletions

179
assets/webconfig/js/content_colors.js Normal file → Executable file
View File

@@ -1,84 +1,105 @@
$(document).ready( function() {
performTranslation();
var editor_color = null;
var editor_smoothing = null;
var editor_blackborder = null;
if(window.showOptHelp)
{
//color
$('#conf_cont').append(createRow('conf_cont_color'));
$('#conf_cont_color').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont_color').append(createHelpTable(window.schema.color.properties, $.i18n("edt_conf_color_heading_title")));
//smoothing
$('#conf_cont').append(createRow('conf_cont_smoothing'));
$('#conf_cont_smoothing').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont_smoothing').append(createHelpTable(window.schema.smoothing.properties, $.i18n("edt_conf_smooth_heading_title")));
//blackborder
$('#conf_cont').append(createRow('conf_cont_blackborder'));
$('#conf_cont_blackborder').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
$('#conf_cont_blackborder').append(createHelpTable(window.schema.blackborderdetector.properties, $.i18n("edt_conf_bb_heading_title")));
}
else
{
$('#conf_cont').addClass('row');
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
}
//color
editor_color = createJsonEditor('editor_container_color', {
color : window.schema.color
}, true, true);
$(document).ready(function () {
performTranslation();
editor_color.on('change',function() {
editor_color.validate().length || window.readOnlyMode ? $('#btn_submit_color').attr('disabled', true) : $('#btn_submit_color').attr('disabled', false);
});
$('#btn_submit_color').off().on('click',function() {
requestWriteConfig(editor_color.getValue());
});
//smoothing
editor_smoothing = createJsonEditor('editor_container_smoothing', {
smoothing : window.schema.smoothing
}, true, true);
// update instance listing
updateHyperionInstanceListing();
editor_smoothing.on('change',function() {
editor_smoothing.validate().length || window.readOnlyMode ? $('#btn_submit_smoothing').attr('disabled', true) : $('#btn_submit_smoothing').attr('disabled', false);
});
$('#btn_submit_smoothing').off().on('click',function() {
requestWriteConfig(editor_smoothing.getValue());
});
var editor_color = null;
var editor_smoothing = null;
var editor_blackborder = null;
//blackborder
editor_blackborder = createJsonEditor('editor_container_blackborder', {
blackborderdetector: window.schema.blackborderdetector
}, true, true);
if (window.showOptHelp) {
//color
$('#conf_cont').append(createRow('conf_cont_color'));
$('#conf_cont_color').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont_color').append(createHelpTable(window.schema.color.properties, $.i18n("edt_conf_color_heading_title")));
editor_blackborder.on('change',function() {
editor_blackborder.validate().length || window.readOnlyMode ? $('#btn_submit_blackborder').attr('disabled', true) : $('#btn_submit_blackborder').attr('disabled', false);
});
$('#btn_submit_blackborder').off().on('click',function() {
requestWriteConfig(editor_blackborder.getValue());
});
//wiki links
$('#editor_container_blackborder').append(buildWL("user/moretopics/bbmode","edt_conf_bb_mode_title",true));
//create introduction
if(window.showOptHelp)
{
createHint("intro", $.i18n('conf_colors_color_intro'), "editor_container_color");
createHint("intro", $.i18n('conf_colors_smoothing_intro'), "editor_container_smoothing");
createHint("intro", $.i18n('conf_colors_blackborder_intro'), "editor_container_blackborder");
}
removeOverlay();
//smoothing
$('#conf_cont').append(createRow('conf_cont_smoothing'));
$('#conf_cont_smoothing').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont_smoothing').append(createHelpTable(window.schema.smoothing.properties, $.i18n("edt_conf_smooth_heading_title"), "smoothingHelpPanelId"));
//blackborder
$('#conf_cont').append(createRow('conf_cont_blackborder'));
$('#conf_cont_blackborder').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
$('#conf_cont_blackborder').append(createHelpTable(window.schema.blackborderdetector.properties, $.i18n("edt_conf_bb_heading_title"), "blackborderHelpPanelId"))
}
else {
$('#conf_cont').addClass('row');
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
}
//color
editor_color = createJsonEditor('editor_container_color', {
color: window.schema.color
}, true, true);
editor_color.on('change', function () {
editor_color.validate().length || window.readOnlyMode ? $('#btn_submit_color').attr('disabled', true) : $('#btn_submit_color').attr('disabled', false);
});
$('#btn_submit_color').off().on('click', function () {
requestWriteConfig(editor_color.getValue());
});
//smoothing
editor_smoothing = createJsonEditor('editor_container_smoothing', {
smoothing: window.schema.smoothing
}, true, true);
editor_smoothing.on('change', function () {
var smoothingEnable = editor_smoothing.getEditor("root.smoothing.enable").getValue();
if (smoothingEnable) {
showInputOptionsForKey(editor_smoothing, "smoothing", "enable", true);
$('#smoothingHelpPanelId').show();
} else {
showInputOptionsForKey(editor_smoothing, "smoothing", "enable", false);
$('#smoothingHelpPanelId').hide();
}
editor_smoothing.validate().length || window.readOnlyMode ? $('#btn_submit_smoothing').attr('disabled', true) : $('#btn_submit_smoothing').attr('disabled', false);
});
$('#btn_submit_smoothing').off().on('click', function () {
requestWriteConfig(editor_smoothing.getValue());
});
//blackborder
editor_blackborder = createJsonEditor('editor_container_blackborder', {
blackborderdetector: window.schema.blackborderdetector
}, true, true);
editor_blackborder.on('change', function () {
var blackborderEnable = editor_blackborder.getEditor("root.blackborderdetector.enable").getValue();
if (blackborderEnable) {
showInputOptionsForKey(editor_blackborder, "blackborderdetector", "enable", true);
$('#blackborderHelpPanelId').show();
$('#blackborderWikiLinkId').show();
} else {
showInputOptionsForKey(editor_blackborder, "blackborderdetector", "enable", false);
$('#blackborderHelpPanelId').hide();
$('#blackborderWikiLinkId').hide();
}
editor_blackborder.validate().length || window.readOnlyMode ? $('#btn_submit_blackborder').attr('disabled', true) : $('#btn_submit_blackborder').attr('disabled', false);
});
$('#btn_submit_blackborder').off().on('click', function () {
requestWriteConfig(editor_blackborder.getValue());
});
//wiki links
var wikiElement = $(buildWL("user/advanced/Advanced.html#blackbar-detection", "edt_conf_bb_mode_title", true));
wikiElement.attr('id', 'blackborderWikiLinkId');
$('#editor_container_blackborder').append(wikiElement);
//create introduction
if (window.showOptHelp) {
createHint("intro", $.i18n('conf_colors_color_intro'), "editor_container_color");
createHint("intro", $.i18n('conf_colors_smoothing_intro'), "editor_container_smoothing");
createHint("intro", $.i18n('conf_colors_blackborder_intro'), "editor_container_blackborder");
}
removeOverlay();
});

View File

@@ -1,106 +1,127 @@
$(document).ready( function() {
performTranslation();
$(document).ready(function () {
performTranslation();
// function newsCont(t,e,l)
// {
// var h = '<div style="padding-left:9px;border-left:6px solid #0088cc;">';
// h += '<h4 style="font-weight:bold;font-size:17px">'+t+'</h4>';
// h += e;
// h += '<a href="'+l+'" class="" target="_blank"><i class="fa fa-fw fa-newspaper-o"></i>'+$.i18n('dashboard_newsbox_readmore')+'</a>';
// h += '</div><hr/>';
// $('#dash_news').append(h);
// }
function updateComponents() {
$("div[class*='currentInstance']").remove();
// function createNews(d)
// {
// for(var i = 0; i<d.length; i++)
// {
// if(i > 5)
// break;
//
// var title = d[i].title.rendered;
// var excerpt = d[i].excerpt.rendered;
// var link = d[i].link+'?pk_campaign=WebUI&pk_kwd=news_'+d[i].slug;
//
// newsCont(title,excerpt,link);
// }
// }
var instances_html = '<div class="col-md-6 col-xxl-4 currentInstance-"><div class="panel panel-default">';
instances_html += '<div class="panel-heading panel-instance">';
instances_html += '<div class="dropdown">';
instances_html += '<a id="active_instance_dropdown" class="dropdown-toggle" data-toggle="dropdown" href="#" style="text-decoration:none;display:flex;align-items:center;">';
instances_html += '<div id="active_instance_friendly_name"></div>';
instances_html += '<div id="btn_hypinstanceswitch" style="white-space:nowrap;"><span class="mdi mdi-lightbulb-group mdi-24px" style="margin-right:0;margin-left:5px;"></span><span class="mdi mdi-menu-down mdi-24px"></span></div>';
instances_html += '</a><ul id="hyp_inst_listing" class="dropdown-menu dropdown-alerts" style="cursor:pointer;"></ul>'
instances_html += '</div></div>';
// function getNews()
// {
// var h = '<span style="color:red;font-weight:bold">'+$.i18n('dashboard_newsbox_noconn')+'</span>';
// $.ajax({
// url: 'https://hyperion-project.org/wp-json/wp/v2/posts?_embed',
// dataType: 'json',
// type: 'GET',
// timeout: 2000
// })
// .done( function( data, textStatus, jqXHR ) {
// if(jqXHR.status == 200)
// createNews(data);
// else
// $('#dash_news').html(h);
// })
// .fail( function( jqXHR, textStatus ) {
// $('#dash_news').html(h);
// });
// }
// getNews();
instances_html += '<div class="panel-body">';
instances_html += '<table class="table borderless">';
instances_html += '<thead><tr><th style="vertical-align:middle"><i class="mdi mdi-lightbulb-on fa-fw"></i>';
instances_html += '<span>' + $.i18n('dashboard_componentbox_label_status') + '</span></th>';
function updateComponents()
{
var components = window.comps;
var components_html = "";
for (var idx=0; idx<components.length;idx++)
{
if(components[idx].name != "ALL")
components_html += '<tr><td>'+$.i18n('general_comp_'+components[idx].name)+'</td><td><i class="fa fa-circle component-'+(components[idx].enabled?"on":"off")+'"></i></td></tr>';
}
$("#tab_components").html(components_html);
var components = window.comps;
var hyperion_enabled = true;
components.forEach(function (obj) {
if (obj.name == "ALL") {
hyperion_enabled = obj.enabled;
}
});
//info
var hyperion_enabled = true;
var instBtn = '<span style="display:block; margin:3px"><input id="instanceButton"'
+ (hyperion_enabled ? "checked" : "") + ' type="checkbox" data-toggle="toggle" data-size="small" data-onstyle="success" data-on="'
+ $.i18n('general_btn_on') + '" data-off="'
+ $.i18n('general_btn_off') + '"></span>';
components.forEach( function(obj) {
if (obj.name == "ALL")
{
hyperion_enabled = obj.enabled
}
});
instances_html += '<th style="width:1px;text-align:right">' + instBtn + '</th></tr></thead></table>';
var instancename = window.currentHyperionInstanceName;
instances_html += '<table class="table borderless">';
instances_html += '<thead><tr><th colspan="3">';
instances_html += '<i class="fa fa-info-circle fa-fw"></i>';
instances_html += '<span>' + $.i18n('dashboard_infobox_label_title') + '</span>';
instances_html += '</th></tr></thead>';
instances_html += '<tbody><tr><td></td>';
instances_html += '<td>' + $.i18n('conf_leds_contr_label_contrtype') + '</td>';
instances_html += '<td style="text-align:right">' + window.serverConfig.device.type + '</td>';
instances_html += '</tr><tr></tbody></table>';
$('#dash_statush').html(hyperion_enabled ? '<span style="color:green">'+$.i18n('general_btn_on')+'</span>' : '<span style="color:red">'+$.i18n('general_btn_off')+'</span>');
$('#btn_hsc').html(hyperion_enabled ? '<button class="btn btn-sm btn-danger" onClick="requestSetComponentState(\'ALL\',false)">'+$.i18n('dashboard_infobox_label_disableh', instancename)+'</button>' : '<button class="btn btn-sm btn-success" onClick="requestSetComponentState(\'ALL\',true)">'+$.i18n('dashboard_infobox_label_enableh', instancename)+'</button>');
}
instances_html += '<table class="table first_cell_borderless">';
instances_html += '<thead><tr><th colspan="3">';
instances_html += '<i class="fa fa-eye fa-fw"></i>';
instances_html += '<span>' + $.i18n('dashboard_componentbox_label_title') + '</span>';
instances_html += '</th></tr></thead>';
// add more info
$('#dash_leddevice').html(window.serverConfig.device.type);
$('#dash_currv').html(window.currentVersion);
$('#dash_instance').html(window.currentHyperionInstanceName);
$('#dash_ports').html(window.serverConfig.flatbufServer.port+' | '+window.serverConfig.protoServer.port);
$('#dash_watchedversionbranch').html(window.serverConfig.general.watchedVersionBranch);
var tab_components = "";
for (var idx = 0; idx < components.length; idx++) {
if (components[idx].name != "ALL") {
var comp_enabled = components[idx].enabled ? "checked" : "";
const general_comp = "general_comp_" + components[idx].name;
var componentBtn = '<input ' +
'id="' + general_comp + '" ' + comp_enabled +
' type="checkbox" ' +
'data-toggle="toggle" ' +
'data-size="mini" ' +
'data-onstyle="success" ' +
'data-on="' + $.i18n('general_btn_on') + '" ' +
'data-off="' + $.i18n('general_btn_off') + '">';
getReleases(function(callback){
if(callback)
{
$('#dash_latev').html(window.latestVersion.tag_name);
tab_components += '<tr><td></td><td>' + $.i18n('general_comp_' + components[idx].name) + '</td><td style="text-align:right">' + componentBtn + '</td></tr>';
}
}
if (semverLite.gt(window.latestVersion.tag_name, window.currentVersion))
$('#versioninforesult').html('<div class="bs-callout bs-callout-warning" style="margin:0px"><a target="_blank" href="' + window.latestVersion.html_url + '">'+$.i18n('dashboard_infobox_message_updatewarning', window.latestVersion.tag_name) + '</a></div>');
else
$('#versioninforesult').html('<div class="bs-callout bs-callout-success" style="margin:0px">'+$.i18n('dashboard_infobox_message_updatesuccess')+'</div>');
instances_html += '<tbody>' + tab_components + '</tbody></table>';
instances_html += '</div></div></div>';
}
});
$('.instances').prepend(instances_html);
updateUiOnInstance(window.currentHyperionInstance);
updateHyperionInstanceListing();
//interval update
updateComponents();
$(window.hyperion).on("components-updated",updateComponents);
$('#instanceButton').bootstrapToggle();
$('#instanceButton').change(e => {
requestSetComponentState('ALL', e.currentTarget.checked);
});
if(window.showOptHelp)
createHintH("intro", $.i18n('dashboard_label_intro'), "dash_intro");
for (var idx = 0; idx < components.length; idx++) {
if (components[idx].name != "ALL") {
$("#general_comp_" + components[idx].name).bootstrapToggle();
$("#general_comp_" + components[idx].name).bootstrapToggle(hyperion_enabled ? "enable" : "disable")
$("#general_comp_" + components[idx].name).change(e => {
requestSetComponentState(e.currentTarget.id.split('_')[2], e.currentTarget.checked);
});
}
}
}
removeOverlay();
// add more info
var fbPort = window.serverConfig.flatbufServer.enable ? window.serverConfig.flatbufServer.port : $.i18n('general_disabled');
$('#dash_fbPort').html(fbPort);
var pbPort = window.serverConfig.protoServer.enable ? window.serverConfig.protoServer.port : $.i18n('general_disabled');
$('#dash_pbPort').html(pbPort);
var jsonPort = window.serverConfig.jsonServer.port;
$('#dash_jsonPort').html(jsonPort);
var wsPorts = window.serverConfig.webConfig.port + ' | ' + window.serverConfig.webConfig.sslPort
$('#dash_wsPorts').html(wsPorts);
$('#dash_currv').html(window.currentVersion);
$('#dash_watchedversionbranch').html(window.serverConfig.general.watchedVersionBranch);
getReleases(function (callback) {
if (callback) {
$('#dash_latev').html(window.latestVersion.tag_name);
if (semverLite.gt(window.latestVersion.tag_name, window.currentVersion))
$('#versioninforesult').html('<div class="bs-callout bs-callout-warning" style="margin:0px"><a target="_blank" href="' + window.latestVersion.html_url + '">' + $.i18n('dashboard_infobox_message_updatewarning', window.latestVersion.tag_name) + '</a></div>');
else
$('#versioninforesult').html('<div class="bs-callout bs-callout-info" style="margin:0px">' + $.i18n('dashboard_infobox_message_updatesuccess') + '</div>');
}
});
//interval update
updateComponents();
$(window.hyperion).on("components-updated", updateComponents);
if (window.showOptHelp)
createHintH("intro", $.i18n('dashboard_label_intro'), "dash_intro");
removeOverlay();
});

View File

@@ -1,5 +1,9 @@
$(document).ready( function() {
performTranslation();
// update instance listing
updateHyperionInstanceListing();
var oldEffects = [];
var effects_editor = null;
var confFgEff = window.serverConfig.foregroundEffect.effect;
@@ -12,12 +16,12 @@ $(document).ready( function() {
//foreground effect
$('#conf_cont').append(createRow('conf_cont_fge'));
$('#conf_cont_fge').append(createOptPanel('fa-spinner', $.i18n("edt_conf_fge_heading_title"), 'editor_container_foregroundEffect', 'btn_submit_foregroundEffect'));
$('#conf_cont_fge').append(createHelpTable(window.schema.foregroundEffect.properties, $.i18n("edt_conf_fge_heading_title")));
$('#conf_cont_fge').append(createHelpTable(window.schema.foregroundEffect.properties, $.i18n("edt_conf_fge_heading_title"), "foregroundEffectHelpPanelId"));
//background effect
$('#conf_cont').append(createRow('conf_cont_bge'));
$('#conf_cont_bge').append(createOptPanel('fa-spinner', $.i18n("edt_conf_bge_heading_title"), 'editor_container_backgroundEffect', 'btn_submit_backgroundEffect'));
$('#conf_cont_bge').append(createHelpTable(window.schema.backgroundEffect.properties, $.i18n("edt_conf_bge_heading_title")));
$('#conf_cont_bge').append(createHelpTable(window.schema.backgroundEffect.properties, $.i18n("edt_conf_bge_heading_title"), "backgroundEffectHelpPanelId"));
//effect path
if(storedAccess != 'default')
@@ -64,11 +68,31 @@ $(document).ready( function() {
updateEffectlist();
});
foregroundEffect_editor.on('change',function() {
foregroundEffect_editor.on('change', function () {
var foregroundEffectEnable = foregroundEffect_editor.getEditor("root.foregroundEffect.enable").getValue();
if (foregroundEffectEnable) {
showInputOptionsForKey(foregroundEffect_editor, "foregroundEffect", "enable", true);
$('#foregroundEffectHelpPanelId').show();
} else {
showInputOptionsForKey(foregroundEffect_editor, "foregroundEffect", "enable", false);
$('#foregroundEffectHelpPanelId').hide();
}
foregroundEffect_editor.validate().length || window.readOnlyMode ? $('#btn_submit_foregroundEffect').attr('disabled', true) : $('#btn_submit_foregroundEffect').attr('disabled', false);
});
backgroundEffect_editor.on('change',function() {
backgroundEffect_editor.on('change', function () {
var backgroundEffectEnable = backgroundEffect_editor.getEditor("root.backgroundEffect.enable").getValue();
if (backgroundEffectEnable) {
showInputOptionsForKey(backgroundEffect_editor, "backgroundEffect", "enable", true);
$('#backgroundEffectHelpPanelId').show();
} else {
showInputOptionsForKey(backgroundEffect_editor, "backgroundEffect", "enable", false);
$('#backgroundEffectHelpPanelId').hide();
}
backgroundEffect_editor.validate().length || window.readOnlyMode ? $('#btn_submit_backgroundEffect').attr('disabled', true) : $('#btn_submit_backgroundEffect').attr('disabled', false);
});

View File

@@ -1,5 +1,9 @@
$(document).ready(function () {
performTranslation();
// update instance listing
updateHyperionInstanceListing();
var oldDelList = [];
var effectName = "";
var imageData = "";
@@ -92,7 +96,7 @@ $(document).ready(function () {
var desc = $.i18n(effects[idx].schemaContent.title + '_desc');
if (desc === effects[idx].schemaContent.title + '_desc') {
desc = ""
desc = "";
}
$("#eff_desc").html(createEffHint($.i18n(effects[idx].schemaContent.title), desc));

View File

@@ -5,7 +5,7 @@ $(document).ready( function() {
var confName;
var conf_editor = null;
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_gen_heading_title"), 'editor_container', 'btn_submit'));
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_gen_heading_title"), 'editor_container', 'btn_submit', 'panel-system'));
if(window.showOptHelp)
{
$('#conf_cont').append(createHelpTable(window.schema.general.properties, $.i18n("edt_conf_gen_heading_title")));
@@ -28,12 +28,12 @@ $(document).ready( function() {
// Instance handling
function handleInstanceRename(e)
{
conf_editor.on('change',function() {
window.readOnlyMode ? $('#btn_cl_save').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#btn_ma_save').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
var inst = e.currentTarget.id.split("_")[1];
showInfoDialog('renInst', $.i18n('conf_general_inst_renreq_t'), getInstanceNameByIndex(inst));
@@ -46,13 +46,6 @@ $(document).ready( function() {
});
}
function handleInstanceStartStop(e)
{
var inst = e.currentTarget.id.split("_")[1];
var start = (e.currentTarget.className == "btn btn-danger")
requestInstanceStartStop(inst, start)
}
function handleInstanceDelete(e)
{
var inst = e.currentTarget.id.split("_")[1];
@@ -68,22 +61,25 @@ $(document).ready( function() {
$('.itbody').html("");
for(var key in inst)
{
var startBtnColor = inst[key].running ? "success" : "danger";
var startBtnIcon = inst[key].running ? "stop" : "play";
var startBtnText = inst[key].running ? $.i18n('general_btn_stop') : $.i18n('general_btn_start');
var renameBtn = '<button id="instren_'+inst[key].instance+'" type="button" class="btn btn-primary"><i class="fa fa-fw fa-pencil"></i>'+$.i18n('general_btn_rename')+'</button>';
var enable_style = inst[key].running ? "checked" : "";
var renameBtn = '<button id="instren_'+inst[key].instance+'" type="button" class="btn btn-primary"><i class="mdi mdi-lead-pencil""></i></button>';
var startBtn = ""
var delBtn = "";
if(inst[key].instance > 0)
{
delBtn = '<button id="instdel_'+inst[key].instance+'" type="button" class="btn btn-warning"><i class="fa fa-fw fa-remove"></i>'+$.i18n('general_btn_delete')+'</button>';
startBtn = '<button id="inst_'+inst[key].instance+'" type="button" class="btn btn-'+startBtnColor+'"><i class="fa fa-fw fa-'+startBtnIcon+'"></i>'+startBtnText+'</button>';
delBtn = '<button id="instdel_'+inst[key].instance+'" type="button" class="btn btn-danger"><i class="mdi mdi-delete-forever""></i></button>';
startBtn = '<input id="inst_'+inst[key].instance+'"'+enable_style+' type="checkbox" data-toggle="toggle" data-onstyle="success font-weight-bold" data-on="'+$.i18n('general_btn_on')+'" data-offstyle="default font-weight-bold" data-off="'+$.i18n('general_btn_off')+'">';
}
$('.itbody').append(createTableRow([inst[key].friendly_name, renameBtn, startBtn, delBtn], false, true));
$('.itbody').append(createTableRow([inst[key].friendly_name, startBtn, renameBtn, delBtn], false, true));
$('#instren_'+inst[key].instance).off().on('click', handleInstanceRename);
$('#inst_'+inst[key].instance).off().on('click', handleInstanceStartStop);
$('#inst_'+inst[key].instance).bootstrapToggle();
$('#inst_'+inst[key].instance).change(e => {
requestInstanceStartStop(e.currentTarget.id.split('_').pop(), e.currentTarget.checked);
});
$('#instdel_'+inst[key].instance).off().on('click', handleInstanceDelete);
window.readOnlyMode ? $('#instren_'+inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#inst_'+inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#instdel_'+inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);

578
assets/webconfig/js/content_index.js Normal file → Executable file
View File

@@ -1,354 +1,362 @@
var instNameInit = false
$(document).ready(function () {
var darkModeOverwrite = getStorage("darkModeOverwrite", true);
var darkModeOverwrite = getStorage("darkModeOverwrite", true);
if (darkModeOverwrite == "false" || darkModeOverwrite == null) {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
handleDarkMode();
}
if(darkModeOverwrite == "false" || darkModeOverwrite == null)
{
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
handleDarkMode();
}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
setStorage("darkMode", "off", false);
}
}
if(getStorage("darkMode", false) == "on")
{
handleDarkMode();
}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
setStorage("darkMode", "off", false);
}
}
loadContentTo("#container_connection_lost", "connection_lost");
loadContentTo("#container_restart", "restart");
initWebSocket();
if (getStorage("darkMode", false) == "on") {
handleDarkMode();
}
$(window.hyperion).on("cmd-serverinfo", function (event) {
window.serverInfo = event.response.info;
window.readOnlyMode = window.sysInfo.hyperion.readOnlyMode;
// comps
window.comps = event.response.info.components
loadContentTo("#container_connection_lost", "connection_lost");
loadContentTo("#container_restart", "restart");
initWebSocket();
$(window.hyperion).trigger("ready");
$(window.hyperion).on("cmd-serverinfo", function (event) {
window.serverInfo = event.response.info;
window.comps.forEach(function (obj) {
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
});
// comps
window.comps = event.response.info.components
// determine button visibility
var running = window.serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// update listing at button
updateHyperionInstanceListing()
if (!instNameInit) {
window.currentHyperionInstanceName = getInstanceNameByIndex(0);
instNameInit = true;
}
$(window.hyperion).trigger("ready");
updateSessions();
}); // end cmd-serverinfo
window.comps.forEach(function (obj) {
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
});
// Update language selection
$("#language-select").on('changed.bs.select',function (e, clickedIndex, isSelected, previousValue){
var newLang = availLang[clickedIndex-1];
if (newLang !== storedLang)
{
setStorage("langcode", newLang);
reload();
}
});
// determine button visibility
var running = window.serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// update listing at button
updateHyperionInstanceListing()
if (!instNameInit) {
window.currentHyperionInstanceName = getInstanceNameByIndex(0);
instNameInit = true;
}
$("#language-select").selectpicker(
{
container: 'body'
});
updateSessions();
}); // end cmd-serverinfo
$(".bootstrap-select").click(function () {
$(this).addClass("open");
});
// Update language selection
$("#language-select").on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
var newLang = availLang[clickedIndex - 1];
if (newLang !== storedLang) {
setStorage("langcode", newLang);
reload();
}
});
$(document).click(function(){
$(".bootstrap-select").removeClass("open");
});
$("#language-select").selectpicker(
{
container: 'body'
});
$(".bootstrap-select").click(function(e){
e.stopPropagation();
});
//End language selection
$(window.hyperion).on("cmd-sessions-update", function (event) {
window.serverInfo.sessions = event.response.data;
updateSessions();
});
$(".bootstrap-select").click(function () {
$(this).addClass("open");
});
$(window.hyperion).on("cmd-authorize-tokenRequest cmd-authorize-getPendingTokenRequests", function (event) {
var val = event.response.info;
if (Array.isArray(event.response.info)) {
if (event.response.info.length == 0) {
return
}
val = event.response.info[0]
if (val.comment == '')
$('#modal_dialog').modal('hide');
}
$(document).click(function () {
$(".bootstrap-select").removeClass("open");
});
showInfoDialog("grantToken", $.i18n('conf_network_tok_grantT'), $.i18n('conf_network_tok_grantMsg') + '<br><span style="font-weight:bold">App: ' + val.comment + '</span><br><span style="font-weight:bold">Code: ' + val.id + '</span>')
$("#tok_grant_acc").off().on('click', function () {
tokenList.push(val)
// forward event, in case we need to rebuild the list now
$(window.hyperion).trigger({ type: "build-token-list" });
requestHandleTokenRequest(val.id, true)
});
$("#tok_deny_acc").off().on('click', function () {
requestHandleTokenRequest(val.id, false)
});
});
$(".bootstrap-select").click(function (e) {
e.stopPropagation();
});
$(window.hyperion).one("cmd-authorize-getTokenList", function (event) {
tokenList = event.response.info;
requestServerInfo();
});
//End language selection
$(window.hyperion).on("cmd-sysinfo", function (event) {
requestServerInfo();
window.sysInfo = event.response.info;
$(window.hyperion).on("cmd-sessions-update", function (event) {
window.serverInfo.sessions = event.response.data;
updateSessions();
});
window.currentVersion = window.sysInfo.hyperion.version;
window.currentChannel = window.sysInfo.hyperion.channel;
});
$(window.hyperion).on("cmd-authorize-tokenRequest cmd-authorize-getPendingTokenRequests", function (event) {
var val = event.response.info;
if (Array.isArray(event.response.info)) {
if (event.response.info.length == 0) {
return
}
val = event.response.info[0]
if (val.comment == '')
$('#modal_dialog').modal('hide');
}
$(window.hyperion).one("cmd-config-getschema", function (event) {
window.serverSchema = event.response.info;
requestServerConfig();
showInfoDialog("grantToken", $.i18n('conf_network_tok_grantT'), $.i18n('conf_network_tok_grantMsg') + '<br><span style="font-weight:bold">App: ' + val.comment + '</span><br><span style="font-weight:bold">Code: ' + val.id + '</span>')
$("#tok_grant_acc").off().on('click', function () {
tokenList.push(val)
// forward event, in case we need to rebuild the list now
$(window.hyperion).trigger({ type: "build-token-list" });
requestHandleTokenRequest(val.id, true)
});
$("#tok_deny_acc").off().on('click', function () {
requestHandleTokenRequest(val.id, false)
});
});
$(window.hyperion).one("cmd-authorize-getTokenList", function (event) {
tokenList = event.response.info;
requestServerInfo();
});
$(window.hyperion).on("cmd-sysinfo", function (event) {
requestServerInfo();
window.sysInfo = event.response.info;
window.currentVersion = window.sysInfo.hyperion.version;
window.currentChannel = window.sysInfo.hyperion.channel;
window.readOnlyMode = window.sysInfo.hyperion.readOnlyMode;
});
$(window.hyperion).one("cmd-config-getschema", function (event) {
window.serverSchema = event.response.info;
requestServerConfig();
requestTokenInfo();
requestGetPendingTokenRequests();
window.schema = window.serverSchema.properties;
});
window.schema = window.serverSchema.properties;
});
$(window.hyperion).on("cmd-config-getconfig", function (event) {
window.serverConfig = event.response.info;
requestSysInfo();
$(window.hyperion).on("cmd-config-getconfig", function (event) {
window.serverConfig = event.response.info;
requestSysInfo();
window.showOptHelp = window.serverConfig.general.showOptHelp;
});
window.showOptHelp = window.serverConfig.general.showOptHelp;
});
$(window.hyperion).on("cmd-config-setconfig", function (event) {
if (event.response.success === true) {
showNotification('success', $.i18n('dashboard_alert_message_confsave_success'), $.i18n('dashboard_alert_message_confsave_success_t'))
}
});
$(window.hyperion).on("cmd-config-setconfig", function (event) {
if (event.response.success === true) {
showNotification('success', $.i18n('dashboard_alert_message_confsave_success'), $.i18n('dashboard_alert_message_confsave_success_t'))
}
});
$(window.hyperion).on("cmd-authorize-login", function (event) {
$("#main-nav").removeAttr('style')
$("#top-navbar").removeAttr('style')
$(window.hyperion).on("cmd-authorize-login", function (event) {
$("#main-nav").removeAttr('style')
$("#top-navbar").removeAttr('style')
if (window.defaultPasswordIsSet === true && getStorage("suppressDefaultPwWarning") !== "true" )
{
var supprPwWarnCheckbox = '<div class="text-right">'+$.i18n('dashboard_message_do_not_show_again')
+ ' <input id="chk_suppressDefaultPw" type="checkbox" onChange="suppressDefaultPwWarning()"> </div>'
showNotification('warning', $.i18n('dashboard_message_default_password'), $.i18n('dashboard_message_default_password_t'), '<a style="cursor:pointer" onClick="changePassword()">'
+ $.i18n('InfoDialog_changePassword_title') + '</a>' + supprPwWarnCheckbox)
}
else
//if logged on and pw != default show option to lock ui
$("#btn_lock_ui").removeAttr('style')
if (window.defaultPasswordIsSet === true && getStorage("suppressDefaultPwWarning") !== "true") {
var supprPwWarnCheckbox = '<div class="text-right">' + $.i18n('dashboard_message_do_not_show_again')
+ ' <input id="chk_suppressDefaultPw" type="checkbox" onChange="suppressDefaultPwWarning()"> </div>'
showNotification('warning', $.i18n('dashboard_message_default_password'), $.i18n('dashboard_message_default_password_t'), '<a style="cursor:pointer" onClick="changePassword()">'
+ $.i18n('InfoDialog_changePassword_title') + '</a>' + supprPwWarnCheckbox)
}
else
//if logged on and pw != default show option to lock ui
$("#btn_lock_ui").removeAttr('style')
if (event.response.hasOwnProperty('info'))
setStorage("loginToken", event.response.info.token, true);
if (event.response.hasOwnProperty('info'))
setStorage("loginToken", event.response.info.token, true);
requestServerConfigSchema();
});
requestServerConfigSchema();
});
$(window.hyperion).on("cmd-authorize-newPassword", function (event) {
if (event.response.success === true) {
showInfoDialog("success", $.i18n('InfoDialog_changePassword_success'));
// not necessarily true, but better than nothing
window.defaultPasswordIsSet = false;
}
});
$(window.hyperion).on("cmd-authorize-newPassword", function (event) {
if (event.response.success === true) {
showInfoDialog("success", $.i18n('InfoDialog_changePassword_success'));
// not necessarily true, but better than nothing
window.defaultPasswordIsSet = false;
}
});
$(window.hyperion).on("cmd-authorize-newPasswordRequired", function (event) {
var loginToken = getStorage("loginToken", true)
$(window.hyperion).on("cmd-authorize-newPasswordRequired", function (event) {
var loginToken = getStorage("loginToken", true)
if (event.response.info.newPasswordRequired == true) {
window.defaultPasswordIsSet = true;
if (event.response.info.newPasswordRequired == true) {
window.defaultPasswordIsSet = true;
if (loginToken)
requestTokenAuthorization(loginToken)
else
requestAuthorization('hyperion');
}
else {
$("#main-nav").attr('style', 'display:none')
$("#top-navbar").attr('style', 'display:none')
if (loginToken)
requestTokenAuthorization(loginToken)
else
requestAuthorization('hyperion');
}
else {
$("#main-nav").attr('style', 'display:none')
$("#top-navbar").attr('style', 'display:none')
if (loginToken)
requestTokenAuthorization(loginToken)
else
loadContentTo("#page-content", "login")
}
});
if (loginToken)
requestTokenAuthorization(loginToken)
else
loadContentTo("#page-content", "login")
}
});
$(window.hyperion).on("cmd-authorize-adminRequired", function (event) {
//Check if a admin login is required.
//If yes: check if default pw is set. If no: go ahead to get server config and render page
if (event.response.info.adminRequired === true)
requestRequiresDefaultPasswortChange();
else
requestServerConfigSchema();
});
$(window.hyperion).on("cmd-authorize-adminRequired", function (event) {
//Check if a admin login is required.
//If yes: check if default pw is set. If no: go ahead to get server config and render page
if (event.response.info.adminRequired === true)
requestRequiresDefaultPasswortChange();
else
requestServerConfigSchema();
});
$(window.hyperion).on("error", function (event) {
//If we are getting an error "No Authorization" back with a set loginToken we will forward to new Login (Token is expired.
//e.g.: hyperiond was started new in the meantime)
if (event.reason == "No Authorization" && getStorage("loginToken", true)) {
removeStorage("loginToken", true);
requestRequiresAdminAuth();
}
else {
showInfoDialog("error", "Error", event.reason);
}
});
$(window.hyperion).on("error", function (event) {
//If we are getting an error "No Authorization" back with a set loginToken we will forward to new Login (Token is expired.
//e.g.: hyperiond was started new in the meantime)
if (event.reason == "No Authorization" && getStorage("loginToken", true)) {
removeStorage("loginToken", true);
requestRequiresAdminAuth();
}
else {
showInfoDialog("error", "Error", event.reason);
}
});
$(window.hyperion).on("open", function (event) {
requestRequiresAdminAuth();
});
$(window.hyperion).on("open", function (event) {
requestRequiresAdminAuth();
});
$(window.hyperion).one("ready", function (event) {
loadContent();
});
$(window.hyperion).one("ready", function (event) {
loadContent();
});
$(window.hyperion).on("cmd-adjustment-update", function (event) {
window.serverInfo.adjustment = event.response.data
});
$(window.hyperion).on("cmd-adjustment-update", function (event) {
window.serverInfo.adjustment = event.response.data
});
$(window.hyperion).on("cmd-videomode-update", function (event) {
window.serverInfo.videomode = event.response.data.videomode
});
$(window.hyperion).on("cmd-videomode-update", function (event) {
window.serverInfo.videomode = event.response.data.videomode
});
$(window.hyperion).on("cmd-components-update", function (event) {
let obj = event.response.data
$(window.hyperion).on("cmd-components-update", function (event) {
let obj = event.response.data
// notfication in index
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
// notfication in index
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
window.comps.forEach((entry, index) => {
if (entry.name === obj.name) {
window.comps[index] = obj;
}
});
// notify the update
$(window.hyperion).trigger("components-updated", event.response.data);
});
window.comps.forEach((entry, index) => {
if (entry.name === obj.name) {
window.comps[index] = obj;
}
});
// notify the update
$(window.hyperion).trigger("components-updated", event.response.data);
});
$(window.hyperion).on("cmd-instance-update", function (event) {
window.serverInfo.instance = event.response.data
var avail = event.response.data;
// notify the update
$(window.hyperion).trigger("instance-updated");
$(window.hyperion).on("cmd-instance-update", function (event) {
window.serverInfo.instance = event.response.data
var avail = event.response.data;
// notify the update
$(window.hyperion).trigger("instance-updated");
// if our current instance is no longer available we are at instance 0 again.
var isInData = false;
for (var key in avail) {
if (avail[key].instance == currentHyperionInstance && avail[key].running) {
isInData = true;
}
}
// if our current instance is no longer available we are at instance 0 again.
var isInData = false;
for (var key in avail) {
if (avail[key].instance == currentHyperionInstance && avail[key].running) {
isInData = true;
}
}
if (!isInData) {
//Delete Storage information about the last used but now stopped instance
if (getStorage('lastSelectedInstance', false))
removeStorage('lastSelectedInstance', false)
if (!isInData) {
//Delete Storage information about the last used but now stopped instance
if (getStorage('lastSelectedInstance', false))
removeStorage('lastSelectedInstance', false)
currentHyperionInstance = 0;
currentHyperionInstanceName = getInstanceNameByIndex(0);
requestServerConfig();
setTimeout(requestServerInfo, 100)
setTimeout(requestTokenInfo, 200)
setTimeout(loadContent, 300, undefined, true)
}
currentHyperionInstance = 0;
currentHyperionInstanceName = getInstanceNameByIndex(0);
requestServerConfig();
setTimeout(requestServerInfo, 100)
setTimeout(requestTokenInfo, 200)
setTimeout(loadContent, 300, undefined, true)
}
// determine button visibility
var running = serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// determine button visibility
var running = serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// update listing for button
updateHyperionInstanceListing()
});
// update listing for button
updateHyperionInstanceListing()
});
$(window.hyperion).on("cmd-instance-switchTo", function (event) {
requestServerConfig();
setTimeout(requestServerInfo, 200)
setTimeout(requestTokenInfo, 400)
setTimeout(loadContent, 400, undefined, true)
});
$(window.hyperion).on("cmd-instance-switchTo", function (event) {
requestServerConfig();
setTimeout(requestServerInfo, 200)
setTimeout(requestTokenInfo, 400)
setTimeout(loadContent, 400, undefined, true)
});
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects
});
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects
});
$(".mnava").bind('click.menu', function (e) {
loadContent(e);
window.scrollTo(0, 0);
});
$(".mnava").bind('click.menu', function (e) {
loadContent(e);
window.scrollTo(0, 0);
});
$(window).scroll(function(){
if ($(window).scrollTop() > 65)
$("#navbar_brand_logo").css("display", "none");
else
$("#navbar_brand_logo").css("display", "");
});
});
function suppressDefaultPwWarning(){
if (document.getElementById('chk_suppressDefaultPw').checked)
setStorage("suppressDefaultPwWarning", "true");
else
setStorage("suppressDefaultPwWarning", "false");
function suppressDefaultPwWarning() {
if (document.getElementById('chk_suppressDefaultPw').checked)
setStorage("suppressDefaultPwWarning", "true");
else
setStorage("suppressDefaultPwWarning", "false");
}
$(function () {
var sidebar = $('#side-menu'); // cache sidebar to a variable for performance
sidebar.delegate('a.inactive', 'click', function () {
sidebar.find('.active').toggleClass('active inactive');
$(this).toggleClass('active inactive');
});
var sidebar = $('#side-menu'); // cache sidebar to a variable for performance
sidebar.delegate('a.inactive', 'click', function () {
sidebar.find('.active').toggleClass('active inactive');
$(this).toggleClass('active inactive');
});
});
// hotfix body padding when bs modals overlap
$(document.body).on('hide.bs.modal,hidden.bs.modal', function () {
$('body').css('padding-right', '0');
$('body').css('padding-right', '0');
});
//Dark Mode
$("#btn_darkmode").off().on("click",function(e){
if(getStorage("darkMode", false) != "on")
{
handleDarkMode();
setStorage("darkModeOverwrite", true, true);
}
else {
setStorage("darkMode", "off", false);
setStorage("darkModeOverwrite", true, true);
location.reload();
}
$("#btn_darkmode").off().on("click", function (e) {
if (getStorage("darkMode", false) != "on") {
handleDarkMode();
setStorage("darkModeOverwrite", true, true);
}
else {
setStorage("darkMode", "off", false);
setStorage("darkModeOverwrite", true, true);
location.reload();
}
});
// Menuitem toggle;
function SwitchToMenuItem(target) {
document.getElementById(target).click(); // Get <a href menu item;
let sidebar = $('#side-menu'); // Get sidebar menu;
sidebar.find('.active').toggleClass('inactive'); // find all active classes and set inactive;
sidebar.find('.in').removeClass("in"); // Find all collapsed menu items and close it by remove "in" class;
$('#' + target).removeClass('inactive'); // Remove inactive state by classname;
$('#' + target).addClass('active'); // Add active state by classname;
let cl_object = $('#' + target).closest('ul'); // Find closest ul sidemenu header;
cl_object.addClass('in'); // add class "in" to expand header in sidebar menu;
};

2026
assets/webconfig/js/content_leds.js Normal file → Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -1,224 +1,184 @@
var conf_editor = null;
var createdCont = false;
var isScroll = true;
performTranslation();
requestLoggingStop();
requestLoggingStart();
$(document).ready(function() {
var messages;
var loguplmess = "";
var reportUrl = 'https://report.hyperion-project.org/#';
$(document).ready(function () {
$('#conf_cont').append(createOptPanel('fa-reorder', $.i18n("edt_conf_log_heading_title"), 'editor_container', 'btn_submit'));
if(window.showOptHelp)
{
$('#conf_cont').append(createHelpTable(window.schema.logger.properties, $.i18n("edt_conf_log_heading_title")));
createHintH("intro", $.i18n('conf_logging_label_intro'), "log_head");
}
$("#log_upl_pol").append('<span style="color:grey;font-size:80%">'+$.i18n("conf_logging_uplpolicy")+' '+buildWL("user/support#report_privacy_policy",$.i18n("conf_logging_contpolicy")));
$('#conf_cont').append(createOptPanel('fa-reorder', $.i18n("edt_conf_log_heading_title"), 'editor_container', 'btn_submit'));
if (window.showOptHelp) {
$('#conf_cont').append(createHelpTable(window.schema.logger.properties, $.i18n("edt_conf_log_heading_title")));
createHintH("intro", $.i18n('conf_logging_label_intro'), "log_head");
}
conf_editor = createJsonEditor('editor_container', {
logger : window.schema.logger
}, true, true);
conf_editor = createJsonEditor('editor_container', {
logger: window.schema.logger
}, true, true);
conf_editor.on('change',function() {
conf_editor.validate().length || window.readOnlyMode ? $('#btn_submit').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
conf_editor.on('change', function () {
conf_editor.validate().length || window.readOnlyMode ? $('#btn_submit').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
$('#btn_submit').off().on('click',function() {
requestWriteConfig(conf_editor.getValue());
});
$('#btn_submit').off().on('click', function () {
$('#btn_logupload').off().on('click',function() {
uploadLog();
$(this).attr("disabled", true);
$('#upl_link').html($.i18n('conf_logging_uploading'))
});
var displayedLogLevel = conf_editor.getEditor("root.logger.level").getValue();
var newLogLevel = {logger:{}};
newLogLevel.logger.level = displayedLogLevel;
//show prev uploads
var ent;
requestWriteConfig(newLogLevel);
});
if(getStorage("prev_reports"))
{
ent = JSON.parse(getStorage("prev_reports"));
$('#prev_reports').append('<h4 style="margin-top:30px">'+$.i18n('conf_logging_lastreports')+'</h4>');
for(var i = 0; i<ent.length; i++)
{
$('#prev_reports').append('<p><a href="'+reportUrl+ent[i].id+'" target="_blank">'+ent[i].title+'('+ent[i].time+')</a></p>');
}
}
else
ent = [];
function infoSummary() {
var info = "";
function updateLastReports(id,time,title)
{
if(ent.length > 4)
ent.pop();
ent.unshift({"id": id ,"time": time,"title": title})
setStorage("prev_reports",JSON.stringify(ent));
}
info += 'Hyperion System Summary Report (' + window.serverConfig.general.name + '), Reported instance: ' + window.currentHyperionInstanceName + '\n';
function uploadLog()
{
var log = "";
var config = JSON.stringify(window.serverConfig, null).replace(/"/g, '\\"');
var prios = window.serverInfo.priorities;
var comps = window.serverInfo.components;
var sys = window.sysInfo.system;
var shy = window.sysInfo.hyperion;
var info;
info += "\n< ----- System information -------------------- >\n";
info += getSystemInfo() + '\n';
//create log
log = (messages ? loguplmess : "Log was empty!");
info += "\n< ----- Configured Instances ------------------ >\n";
var instances = window.serverInfo.instance;
for (var i = 0; i < instances.length; i++) {
info += instances[i].instance + ': ' + instances[i].friendly_name + ' Running: ' + instances[i].running + '\n';
}
//create general info
info = "### GENERAL ### \n";
info += 'Build: '+shy.build+'\n';
info += 'Build time: '+shy.time+'\n';
info += 'Version: '+shy.version+'\n';
info += 'UI Lang: '+storedLang+' (BrowserL: '+navigator.language+')\n';
info += 'UI Access: '+storedAccess+'\n';
info += 'Log lvl: '+window.serverConfig.logger.level+'\n';
info += 'Avail Capt: '+window.serverInfo.grabbers.available+'\n';
info += 'Database: '+(shy.readOnlyMode ? "ready-only" : "read/write")+'\n';
info += '\n';
info += "\n< ----- This instance's priorities ------------ >\n";
var prios = window.serverInfo.priorities;
for (var i = 0; i < prios.length; i++) {
info += prios[i].priority + ': ';
if (prios[i].visible) {
info += ' VISIBLE!';
}
else {
info += ' ';
}
info += ' (' + prios[i].componentId + ') Owner: ' + prios[i].owner + '\n';
}
info += 'priorities_autoselect: ' + window.serverInfo.priorities_autoselect + '\n';
info += 'Distribution: '+sys.prettyName+'\n';
info += 'Architecture: '+sys.architecture+'\n';
info += "\n< ----- This instance components' status ------->\n";
var comps = window.serverInfo.components;
for (var i = 0; i < comps.length; i++) {
info += comps[i].name + ' - ' + comps[i].enabled + '\n';
}
if (sys.cpuModelName)
info += 'CPU Model: ' + sys.cpuModelName + '\n';
if (sys.cpuModelType)
info += 'CPU Type: ' + sys.cpuModelType + '\n';
if (sys.cpuRevision)
info += 'CPU Revision: ' + sys.cpuRevision + '\n';
if (sys.cpuHardware)
info += 'CPU Hardware: ' + sys.cpuHardware + '\n';
info += "\n< ----- This instance's configuration --------- >\n";
info += JSON.stringify(window.serverConfig) + '\n';
info += 'Kernel: ' + sys.kernelType+' ('+sys.kernelVersion+' (WS: '+sys.wordSize+'))' + '\n';
info += 'Qt Version: ' + sys.qtVersion + '\n';
info += 'Python Version: ' + sys.pyVersion + '\n';
info += 'Browser/OS: ' + navigator.userAgent + '\n\n';
info += "\n< ----- Current Log --------------------------- >\n";
var logMsgs = document.getElementById("logmessages").textContent;
if (logMsgs.length !== 0) {
info += logMsgs;
} else {
info += "Log is empty!";
}
//create prios
info += "### PRIORITIES ### \n";
for(var i = 0; i<prios.length; i++)
{
info += prios[i].priority;
if(prios[i].visible)
info += ' VISIBLE!';
else
info += ' ';
info += ' ('+prios[i].component+') Owner: '+prios[i].owner+'\n';
}
info += '\npriorities_autoselect: '+window.serverInfo.priorities_autoselect+'\n\n';
return info;
}
//create comps
info += '### COMPONENTS ### \n';
for(var i = 0; i<comps.length; i++)
{
info += comps[i].enabled+' - '+comps[i].name+'\n';
}
function createLogContainer() {
//escape data
info = JSON.stringify(info);
log = JSON.stringify(log);
config = JSON.stringify(config);
var title = 'Hyperion '+window.currentVersion+' Report ('+window.serverConfig.general.name+' ('+window.serverInfo.ledDevices.active+'))';
const isScrollEnableStyle = (isScroll ? "checked" : "");
$.ajax({
url: 'https://api.hyperion-project.org/report.php',
crossDomain: true,
contentType: 'application/json',
type: 'POST',
timeout: 7000,
data: '{"title":"'+title+'","info":'+info+',"log":'+log+',"config":'+config+'}'
})
.done( function( data, textStatus, jqXHR ) {
reportUrl += data.id;
if(textStatus == "success")
{
$('#upl_link').html($.i18n('conf_logging_yourlink')+': <a href="'+reportUrl+'" target="_blank">'+reportUrl+'</a>');
$("html, body").animate({ scrollTop: 9999 }, "fast");
updateLastReports(data.id,data.time,title);
}
else
{
$('#btn_logupload').attr("disabled", false);
$('#upl_link').html('<span style="color:red">'+$.i18n('conf_logging_uplfailed')+'<span>');
}
})
.fail( function( jqXHR, textStatus ) {
console.log(jqXHR,textStatus);
$('#btn_logupload').attr("disabled", false);
$('#upl_link').html('<span style="color:red">'+$.i18n('conf_logging_uplfailed')+'<span>');
});
}
$('#log_content').html('<pre><div id="logmessages" style="overflow:scroll;max-height:400px"></div></pre>');
$('#log_footer').append('<label class="checkbox-inline">'
+ '<input id = "btn_scroll"' + isScrollEnableStyle + ' type = "checkbox"'
+ 'data-toggle="toggle" data-onstyle="success" data-on="' + $.i18n('general_btn_on') + '" data-off="' + $.i18n('general_btn_off') + '">'
+ $.i18n('conf_logging_btn_autoscroll') + '</label>'
);
if (!window.loggingHandlerInstalled)
{
window.loggingHandlerInstalled = true;
$(window.hyperion).on("cmd-logging-update",function(event){
$(`#btn_scroll`).bootstrapToggle();
$(`#btn_scroll`).change(e => {
if (e.currentTarget.checked) {
//Scroll to end of log
isScroll = true;
if ($("#logmessages").length > 0) {
$('#logmessages')[0].scrollTop = $('#logmessages')[0].scrollHeight;
}
} else {
isScroll = false;
}
});
if ($("#logmessages").length == 0 && window.loggingStreamActive)
{
requestLoggingStop();
window.loggingStreamActive = false;
}
$('#log_footer').append('<button class="btn btn-primary pull-right" id="btn_clipboard"><i class="fa fa-fw fa-clipboard"></i>Copy Log to Clipboard</button>');
messages = (event.response.result.messages);
if(messages.length != 0 && !createdCont)
{
$('#log_content').html('\
<pre><div id="logmessages" style="overflow:scroll;max-height:400px"></div></pre>\
<button class="btn btn-danger" id="btn_autoscroll"><i class="fa fa-long-arrow-down fa-fw"></i>'+$.i18n('conf_logging_btn_autoscroll')+'</button>\
<button class="btn btn-primary" id="btn_clipboard"><i class="fa fa-clipboard fa-fw"></i>Copy Log to Clipboard</button>');
createdCont = true;
$('#btn_clipboard').off().on('click', function () {
const temp = document.createElement('textarea');
temp.textContent = infoSummary();
document.body.append(temp);
temp.select();
document.execCommand("copy");
temp.remove();
});
}
$('#btn_autoscroll').off().on('click',function() {
toggleClass('#btn_autoscroll', "btn-success", "btn-danger");
});
function updateLogOutput(messages) {
$('#btn_clipboard').off().on('click',function() {
const temp = document.createElement('textarea');
temp.textContent = document.getElementById("logmessages").textContent;
document.body.append(temp);
temp.select();
document.execCommand("copy");
temp.remove();
});
}
if (messages.length != 0) {
for(var idx = 0; idx < messages.length; idx++)
{
var app_name = messages[idx].appName;
var logger_name = messages[idx].loggerName;
var function_ = messages[idx].function;
var line = messages[idx].line;
var file_name = messages[idx].fileName;
var msg = messages[idx].message;
var level_string = messages[idx].levelString;
var utime = messages[idx].utime;
for (var idx = 0; idx < messages.length; idx++) {
var app_name = messages[idx].appName;
var logger_name = messages[idx].loggerName;
var function_ = messages[idx].function;
var line = messages[idx].line;
var file_name = messages[idx].fileName;
var msg = messages[idx].message;
var level_string = messages[idx].levelString;
var utime = messages[idx].utime;
var debug = "";
if(level_string == "DEBUG") {
debug = "("+file_name+":"+line+":"+function_+"()) ";
}
var debug = "";
if (level_string == "DEBUG") {
debug = "(" + file_name + ":" + line + ":" + function_ + "()) ";
}
var date = new Date(parseInt(utime));
var date = new Date(parseInt(utime));
var newLogLine = date.toISOString() + " [" + app_name + " " + logger_name + "] (" + level_string + ") " + debug + msg;
$("#logmessages").append("\n <code>"+date.toISOString()+" ["+app_name+" "+logger_name+"] ("+level_string+") "+debug+msg+"</code>");
loguplmess += "["+app_name+" "+logger_name+"] ("+level_string+") "+debug+msg+"\n";
}
$("#logmessages").append("<code>" + newLogLine + "</code>\n");
}
if($("#btn_autoscroll").hasClass('btn-success'))
{
$('#logmessages').stop().animate({
scrollTop: $('#logmessages')[0].scrollHeight
}, 800);
}
});
}
if (isScroll && $("#logmessages").length > 0) {
$('#logmessages').stop().animate({
scrollTop: $('#logmessages')[0].scrollHeight
}, 800);
}
}
}
removeOverlay();
if (!window.loggingHandlerInstalled) {
window.loggingHandlerInstalled = true;
$(window.hyperion).on("cmd-logging-update", function (event) {
var messages = (event.response.result.messages);
if (messages.length != 0) {
if (!createdCont) {
createLogContainer();
createdCont = true;
}
updateLogOutput(messages)
}
});
}
$(window.hyperion).on("cmd-settings-update", function (event) {
var obj = event.response.data
if (obj.logger) {
Object.getOwnPropertyNames(obj).forEach(function (val, idx, array) {
window.serverConfig[val] = obj[val];
});
var currentlogLevel = window.serverConfig.logger.level;
conf_editor.getEditor("root.logger.level").setValue(currentlogLevel);
location.reload();
}
});
removeOverlay();
});

View File

@@ -12,35 +12,35 @@ $(document).ready( function() {
{
//network
$('#conf_cont').append(createRow('conf_cont_net'))
$('#conf_cont_net').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_net_heading_title"), 'editor_container_net', 'btn_submit_net'));
$('#conf_cont_net').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_net_heading_title"), 'editor_container_net', 'btn_submit_net', 'panel-system'));
$('#conf_cont_net').append(createHelpTable(window.schema.network.properties, $.i18n("edt_conf_net_heading_title")));
//jsonserver
$('#conf_cont').append(createRow('conf_cont_json'))
$('#conf_cont_json').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_js_heading_title"), 'editor_container_jsonserver', 'btn_submit_jsonserver'));
$('#conf_cont_json').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_js_heading_title"), 'editor_container_jsonserver', 'btn_submit_jsonserver', 'panel-system'));
$('#conf_cont_json').append(createHelpTable(window.schema.jsonServer.properties, $.i18n("edt_conf_js_heading_title")));
//flatbufserver
$('#conf_cont').append(createRow('conf_cont_flatbuf'))
$('#conf_cont_flatbuf').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fbs_heading_title"), 'editor_container_fbserver', 'btn_submit_fbserver'));
$('#conf_cont_flatbuf').append(createHelpTable(window.schema.flatbufServer.properties, $.i18n("edt_conf_fbs_heading_title")));
$('#conf_cont_flatbuf').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fbs_heading_title"), 'editor_container_fbserver', 'btn_submit_fbserver', 'panel-system'));
$('#conf_cont_flatbuf').append(createHelpTable(window.schema.flatbufServer.properties, $.i18n("edt_conf_fbs_heading_title"),"flatbufServerHelpPanelId"));
//protoserver
$('#conf_cont').append(createRow('conf_cont_proto'))
$('#conf_cont_proto').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_pbs_heading_title"), 'editor_container_protoserver', 'btn_submit_protoserver'));
$('#conf_cont_proto').append(createHelpTable(window.schema.protoServer.properties, $.i18n("edt_conf_pbs_heading_title")));
$('#conf_cont_proto').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_pbs_heading_title"), 'editor_container_protoserver', 'btn_submit_protoserver', 'panel-system'));
$('#conf_cont_proto').append(createHelpTable(window.schema.protoServer.properties, $.i18n("edt_conf_pbs_heading_title"),"protoServerHelpPanelId"));
//boblight
$('#conf_cont').append(createRow('conf_cont_bobl'))
$('#conf_cont_bobl').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_bobls_heading_title"), 'editor_container_boblightserver', 'btn_submit_boblightserver'));
$('#conf_cont_bobl').append(createHelpTable(window.schema.boblightServer.properties, $.i18n("edt_conf_bobls_heading_title")));
$('#conf_cont_bobl').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_bobls_heading_title"), 'editor_container_boblightserver', 'btn_submit_boblightserver', 'panel-system'));
$('#conf_cont_bobl').append(createHelpTable(window.schema.boblightServer.properties, $.i18n("edt_conf_bobls_heading_title"), "boblightServerHelpPanelId"));
//forwarder
if(storedAccess != 'default')
{
$('#conf_cont').append(createRow('conf_cont_fw'))
$('#conf_cont_fw').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fw_heading_title"), 'editor_container_forwarder', 'btn_submit_forwarder'));
$('#conf_cont_fw').append(createHelpTable(window.schema.forwarder.properties, $.i18n("edt_conf_fw_heading_title")));
$('#conf_cont_fw').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fw_heading_title"), 'editor_container_forwarder', 'btn_submit_forwarder', 'panel-system'));
$('#conf_cont_fw').append(createHelpTable(window.schema.forwarder.properties, $.i18n("edt_conf_fw_heading_title"),"forwarderHelpPanelId"));
}
}
else
@@ -87,7 +87,15 @@ $(document).ready( function() {
flatbufServer : window.schema.flatbufServer
}, true, true);
conf_editor_fbs.on('change',function() {
conf_editor_fbs.on('change', function () {
var flatbufServerEnable = conf_editor_fbs.getEditor("root.flatbufServer.enable").getValue();
if (flatbufServerEnable) {
showInputOptionsForKey(conf_editor_fbs, "flatbufServer", "enable", true);
$('#flatbufServerHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_fbs, "flatbufServer", "enable", false);
$('#flatbufServerHelpPanelId').hide();
}
conf_editor_fbs.validate().length || window.readOnlyMode ? $('#btn_submit_fbserver').attr('disabled', true) : $('#btn_submit_fbserver').attr('disabled', false);
});
@@ -100,7 +108,15 @@ $(document).ready( function() {
protoServer : window.schema.protoServer
}, true, true);
conf_editor_proto.on('change',function() {
conf_editor_proto.on('change', function () {
var protoServerEnable = conf_editor_proto.getEditor("root.protoServer.enable").getValue();
if (protoServerEnable) {
showInputOptionsForKey(conf_editor_proto, "protoServer", "enable", true);
$('#protoServerHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_proto, "protoServer", "enable", false);
$('#protoServerHelpPanelId').hide();
}
conf_editor_proto.validate().length || window.readOnlyMode ? $('#btn_submit_protoserver').attr('disabled', true) : $('#btn_submit_protoserver').attr('disabled', false);
});
@@ -113,11 +129,19 @@ $(document).ready( function() {
boblightServer : window.schema.boblightServer
}, true, true);
conf_editor_bobl.on('change',function() {
conf_editor_bobl.on('change', function () {
var boblightServerEnable = conf_editor_bobl.getEditor("root.boblightServer.enable").getValue();
if (boblightServerEnable) {
showInputOptionsForKey(conf_editor_bobl, "boblightServer", "enable", true);
$('#boblightServerHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_bobl, "boblightServer", "enable", false);
$('#boblightServerHelpPanelId').hide();
}
conf_editor_bobl.validate().length || window.readOnlyMode ? $('#btn_submit_boblightserver').attr('disabled', true) : $('#btn_submit_boblightserver').attr('disabled', false);
});
$('#btn_submit_boblightserver').off().on('click',function() {
$('#btn_submit_boblightserver').off().on('click', function () {
requestWriteConfig(conf_editor_bobl.getValue());
});
@@ -128,7 +152,15 @@ $(document).ready( function() {
forwarder : window.schema.forwarder
}, true, true);
conf_editor_forw.on('change',function() {
conf_editor_forw.on('change', function () {
var forwarderEnable = conf_editor_forw.getEditor("root.forwarder.enable").getValue();
if (forwarderEnable) {
showInputOptionsForKey(conf_editor_forw, "forwarder", "enable", true);
$('#forwarderHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_forw, "forwarder", "enable", false);
$('#forwarderHelpPanelId').hide();
}
conf_editor_forw.validate().length || window.readOnlyMode ? $('#btn_submit_forwarder').attr('disabled', true) : $('#btn_submit_forwarder').attr('disabled', false);
});
@@ -213,6 +245,6 @@ $(document).ready( function() {
})
checkApiTokenState(window.serverConfig.network.apiAuth);
removeOverlay();
});

View File

@@ -1,13 +1,16 @@
$(document).ready(function() {
$(document).ready(function () {
performTranslation();
// update instance listing
updateHyperionInstanceListing();
var oldEffects = [];
var cpcolor = '#B500FF';
var mappingList = window.serverSchema.properties.color.properties.imageToLedMappingType.enum;
var duration = 0;
var rgb = {r:255,g:0,b:0};
var rgb = { r: 255, g: 0, b: 0 };
var lastImgData = "";
var lastFileName= "";
var lastFileName = "";
//create html
createTable('ssthead', 'sstbody', 'sstcont');
@@ -16,8 +19,7 @@ $(document).ready(function() {
//create introduction
if(window.showOptHelp)
{
if (window.showOptHelp) {
createHint("intro", $.i18n('remote_color_intro', $.i18n('remote_losthint')), "color_intro");
createHint("intro", $.i18n('remote_input_intro', $.i18n('remote_losthint')), "sstcont");
createHint("intro", $.i18n('remote_adjustment_intro', $.i18n('remote_losthint')), "adjust_content");
@@ -30,83 +32,73 @@ $(document).ready(function() {
var sColor = sortProperties(window.serverSchema.properties.color.properties.channelAdjustment.items.properties);
var values = window.serverInfo.adjustment[0];
for(var key in sColor)
{
if(sColor[key].key != "id" && sColor[key].key != "leds")
{
var title = '<label for="cr_'+sColor[key].key+'">'+$.i18n(sColor[key].title)+'</label>';
for (var key in sColor) {
if (sColor[key].key != "id" && sColor[key].key != "leds") {
var title = '<label for="cr_' + sColor[key].key + '">' + $.i18n(sColor[key].title) + '</label>';
var property;
var value = values[sColor[key].key];
if(sColor[key].type == "array")
{
property = '<div id="cr_'+sColor[key].key+'" class="input-group colorpicker-component" ><input type="text" class="form-control" /><span class="input-group-addon"><i></i></span></div>';
if (sColor[key].type == "array") {
property = '<div id="cr_' + sColor[key].key + '" class="input-group colorpicker-component" ><input type="text" class="form-control" /><span class="input-group-addon"><i></i></span></div>';
$('.crtbody').append(createTableRow([title, property], false, true));
createCP('cr_'+sColor[key].key, value, function(rgb,hex,e){
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), '['+rgb.r+','+rgb.g+','+rgb.b+']');
createCP('cr_' + sColor[key].key, value, function (rgb, hex, e) {
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), '[' + rgb.r + ',' + rgb.g + ',' + rgb.b + ']');
});
}
else if(sColor[key].type == "boolean")
{
property = '<div class="checkbox"><input id="cr_'+sColor[key].key+'" type="checkbox" value="'+value+'"/><label></label></div>';
else if (sColor[key].type == "boolean") {
property = '<div class="checkbox"><input id="cr_' + sColor[key].key + '" type="checkbox" value="' + value + '"/><label></label></div>';
$('.crtbody').append(createTableRow([title, property], false, true));
$('#cr_'+sColor[key].key).off().on('change', function(e){
$('#cr_' + sColor[key].key).off().on('change', function (e) {
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), e.currentTarget.checked);
});
}
else
{
if(sColor[key].key == "brightness" || sColor[key].key == "brightnessCompensation" || sColor[key].key == "backlightThreshold")
property = '<div class="input-group"><input id="cr_'+sColor[key].key+'" type="number" class="form-control" min="0" max="100" step="10" value="'+value+'"/><span class="input-group-addon">'+$.i18n("edt_append_percent")+'</span></div>';
else {
if (sColor[key].key == "brightness" || sColor[key].key == "brightnessCompensation" || sColor[key].key == "backlightThreshold")
property = '<div class="input-group"><input id="cr_' + sColor[key].key + '" type="number" class="form-control" min="0" max="100" step="10" value="' + value + '"/><span class="input-group-addon">' + $.i18n("edt_append_percent") + '</span></div>';
else
property = '<input id="cr_'+sColor[key].key+'" type="number" class="form-control" min="0.1" max="4.0" step="0.1" value="'+value+'"/>';
property = '<input id="cr_' + sColor[key].key + '" type="number" class="form-control" min="0.1" max="4.0" step="0.1" value="' + value + '"/>';
$('.crtbody').append(createTableRow([title, property], false, true));
$('#cr_'+sColor[key].key).off().on('change', function(e){
valValue(this.id,this.value,this.min,this.max);
$('#cr_' + sColor[key].key).off().on('change', function (e) {
valValue(this.id, this.value, this.min, this.max);
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), e.currentTarget.value);
});
}
}
}
function sendEffect()
{
function sendEffect() {
var efx = $("#effect_select").val();
if(efx != "__none__")
{
if (efx != "__none__") {
requestPriorityClear();
$(window.hyperion).one("cmd-clear", function(event) {
setTimeout(function() {requestPlayEffect(efx,duration)}, 100);
$(window.hyperion).one("cmd-clear", function (event) {
setTimeout(function () { requestPlayEffect(efx, duration) }, 100);
});
}
}
function sendColor()
{
requestSetColor(rgb.r, rgb.g, rgb.b,duration);
function sendColor() {
requestSetColor(rgb.r, rgb.g, rgb.b, duration);
}
function updateInputSelect()
{
function updateInputSelect() {
$('.sstbody').html("");
var prios = window.serverInfo.priorities;
var clearAll = false;
for(var i = 0; i < prios.length; i++)
{
var origin = prios[i].origin ? prios[i].origin : "System";
for (var i = 0; i < prios.length; i++) {
var origin = prios[i].origin ? prios[i].origin : "System";
origin = origin.split("@");
var ip = origin[1];
origin = origin[0];
var owner = prios[i].owner;
var active = prios[i].active;
var visible = prios[i].visible;
var owner = prios[i].owner;
var active = prios[i].active;
var visible = prios[i].visible;
var priority = prios[i].priority;
var compId = prios[i].componentId;
var duration = prios[i].duration_ms/1000;
var compId = prios[i].componentId;
var duration = prios[i].duration_ms / 1000;
var value = "0,0,0";
var btn_type = "default";
var btn_text = $.i18n('remote_input_setsource_btn');
@@ -115,40 +107,38 @@ $(document).ready(function() {
if (active)
btn_type = "primary";
if(priority > 254)
if (priority > 254)
continue;
if(priority < 254 && (compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE") )
if (priority < 254 && (compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE"))
clearAll = true;
if (visible)
{
if (visible) {
btn_state = "disabled";
btn_type = "success";
btn_text = $.i18n('remote_input_sourceactiv_btn');
}
if(ip)
origin += '<br/><span style="font-size:80%; color:grey;">'+$.i18n('remote_input_ip')+' '+ip+'</span>';
if (ip)
origin += '<br/><span style="font-size:80%; color:grey;">' + $.i18n('remote_input_ip') + ' ' + ip + '</span>';
if("value" in prios[i])
if ("value" in prios[i])
value = prios[i].value.RGB;
switch (compId)
{
switch (compId) {
case "EFFECT":
owner = $.i18n('remote_effects_label_effects')+' '+owner;
owner = $.i18n('remote_effects_label_effects') + ' ' + owner;
break;
case "COLOR":
owner = $.i18n('remote_color_label_color')+' '+'<div style="width:18px; height:18px; border-radius:20px; margin-bottom:-4px; border:1px grey solid; background-color: rgb('+value+'); display:inline-block" title="RGB: ('+value+')"></div>';
owner = $.i18n('remote_color_label_color') + ' ' + '<div style="width:18px; height:18px; border-radius:20px; margin-bottom:-4px; border:1px grey solid; background-color: rgb(' + value + '); display:inline-block" title="RGB: (' + value + ')"></div>';
break;
case "IMAGE":
owner = $.i18n('remote_effects_label_picture')+' '+owner;
owner = $.i18n('remote_effects_label_picture') + ' ' + owner;
break;
case "GRABBER":
owner = $.i18n('general_comp_GRABBER')+': ('+owner+')';
case "GRABBER":
owner = $.i18n('general_comp_GRABBER') + ': (' + owner + ')';
break;
case "V4L":
owner = $.i18n('general_comp_V4L')+': ('+owner+')';
owner = $.i18n('general_comp_V4L') + ': (' + owner + ')';
break;
case "BOBLIGHTSERVER":
owner = $.i18n('general_comp_BOBLIGHTSERVER');
@@ -161,126 +151,112 @@ $(document).ready(function() {
break;
}
if(duration && compId != "GRABBER" && compId != "FLATBUFSERVER" && compId != "PROTOSERVER")
owner += '<br/><span style="font-size:80%; color:grey;">'+$.i18n('remote_input_duration')+' '+duration.toFixed(0)+$.i18n('edt_append_s')+'</span>';
if (duration && compId != "GRABBER" && compId != "FLATBUFSERVER" && compId != "PROTOSERVER")
owner += '<br/><span style="font-size:80%; color:grey;">' + $.i18n('remote_input_duration') + ' ' + duration.toFixed(0) + $.i18n('edt_append_s') + '</span>';
var btn = '<button id="srcBtn'+i+'" type="button" '+btn_state+' class="btn btn-'+btn_type+' btn_input_selection" onclick="requestSetSource('+priority+');">'+btn_text+'</button>';
var btn = '<button id="srcBtn' + i + '" type="button" ' + btn_state + ' class="btn btn-' + btn_type + ' btn_input_selection" onclick="requestSetSource(' + priority + ');">' + btn_text + '</button>';
if((compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE") && priority < 254)
btn += '<button type="button" class="btn btn-sm btn-danger" style="margin-left:10px;" onclick="requestPriorityClear('+priority+');"><i class="fa fa-close"></button>';
if ((compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE") && priority < 254)
btn += '<button type="button" class="btn btn-sm btn-danger" style="margin-left:10px;" onclick="requestPriorityClear(' + priority + ');"><i class="fa fa-close"></button>';
if(btn_type != 'default')
if (btn_type != 'default')
$('.sstbody').append(createTableRow([origin, owner, priority, btn], false, true));
}
var btn_auto_color = (window.serverInfo.priorities_autoselect? "btn-success" : "btn-danger");
var btn_auto_state = (window.serverInfo.priorities_autoselect? "disabled" : "enabled");
var btn_auto_text = (window.serverInfo.priorities_autoselect? $.i18n('general_btn_on') : $.i18n('general_btn_off'));
var btn_call_state = (clearAll? "enabled" : "disabled");
$('#auto_btn').html('<button id="srcBtn'+i+'" type="button" '+btn_auto_state+' class="btn '+btn_auto_color+'" style="margin-right:5px;display:inline-block;" onclick="requestSetSource(\'auto\');">'+$.i18n('remote_input_label_autoselect')+' ('+btn_auto_text+')</button>');
$('#auto_btn').append('<button type="button" '+btn_call_state+' class="btn btn-danger" style="display:inline-block;" onclick="requestClearAll();">'+$.i18n('remote_input_clearall')+'</button>');
var btn_auto_color = (window.serverInfo.priorities_autoselect ? "btn-success" : "btn-danger");
var btn_auto_state = (window.serverInfo.priorities_autoselect ? "disabled" : "enabled");
var btn_auto_text = (window.serverInfo.priorities_autoselect ? $.i18n('general_btn_on') : $.i18n('general_btn_off'));
var btn_call_state = (clearAll ? "enabled" : "disabled");
$('#auto_btn').html('<button id="srcBtn' + i + '" type="button" ' + btn_auto_state + ' class="btn ' + btn_auto_color + '" style="margin-right:5px;display:inline-block;" onclick="requestSetSource(\'auto\');">' + $.i18n('remote_input_label_autoselect') + ' (' + btn_auto_text + ')</button>');
$('#auto_btn').append('<button type="button" ' + btn_call_state + ' class="btn btn-danger" style="display:inline-block;" onclick="requestClearAll();">' + $.i18n('remote_input_clearall') + '</button>');
var max_width=100;
$('.btn_input_selection').each(function() {
var max_width = 100;
$('.btn_input_selection').each(function () {
if ($(this).innerWidth() > max_width)
max_width = $(this).innerWidth();
});
$('.btn_input_selection').css("min-width",max_width+"px");
$('.btn_input_selection').css("min-width", max_width + "px");
}
function updateLedMapping()
{
function updateLedMapping() {
var mapping = window.serverInfo.imageToLedMappingType;
$('#mappingsbutton').html("");
for(var ix = 0; ix < mappingList.length; ix++)
{
if(mapping == mappingList[ix])
for (var ix = 0; ix < mappingList.length; ix++) {
if (mapping == mappingList[ix])
var btn_style = 'btn-success';
else
var btn_style = 'btn-primary';
$('#mappingsbutton').append('<button type="button" id="lmBtn_'+mappingList[ix]+'" class="btn '+btn_style+'" style="margin:3px;min-width:200px" onclick="requestMappingType(\''+mappingList[ix]+'\');">'+$.i18n('remote_maptype_label_'+mappingList[ix])+'</button><br/>');
$('#mappingsbutton').append('<button type="button" id="lmBtn_' + mappingList[ix] + '" class="btn ' + btn_style + '" style="margin:3px;min-width:200px" onclick="requestMappingType(\'' + mappingList[ix] + '\');">' + $.i18n('remote_maptype_label_' + mappingList[ix]) + '</button><br/>');
}
}
function initComponents()
{
function initComponents() {
var components = window.comps;
var hyperionEnabled = true;
components.forEach( function(obj) {
if (obj.name == "ALL")
{
components.forEach(function (obj) {
if (obj.name == "ALL") {
hyperionEnabled = obj.enabled;
}
});
for (const comp of components)
{
if(comp.name === "ALL")
for (const comp of components) {
if (comp.name === "ALL")
continue;
const enable_style = (comp.enabled? "checked" : "");
const comp_btn_id = "comp_btn_"+comp.name;
const enable_style = (comp.enabled ? "checked" : "");
const comp_btn_id = "comp_btn_" + comp.name;
if ($("#"+comp_btn_id).length === 0)
{
var d='<span style="display:block;margin:3px">'
+'<input id="'+comp_btn_id+'"'+enable_style+' type="checkbox"'
+'data-toggle="toggle" data-onstyle="success" data-on="'+$.i18n('general_btn_on')+'" data-off="'+$.i18n('general_btn_off')+'">'
+'&nbsp;&nbsp;&nbsp;<label>'+$.i18n('general_comp_'+comp.name)+'</label>'
+'</span>';
if ($("#" + comp_btn_id).length === 0) {
var d = '<span style="display:block;margin:3px">'
+ '<label class="checkbox-inline">'
+ '<input id = "' + comp_btn_id + '"' + enable_style + ' type = "checkbox"'
+ 'data-toggle="toggle" data-onstyle="success" data-on="' + $.i18n('general_btn_on') + '" data-off="' + $.i18n('general_btn_off') + '">'
+ $.i18n('general_comp_' + comp.name) + '</label > '
+ '</span>';
$('#componentsbutton').append(d);
$(`#${comp_btn_id}`).bootstrapToggle();
$(`#${comp_btn_id}`).bootstrapToggle((hyperionEnabled ? "enable" : "disable"));
$(`#${comp_btn_id}`).change(e => {
requestSetComponentState(e.currentTarget.id.split('_').pop(), e.currentTarget.checked);
//console.log(e.currentTarget.checked)
requestSetComponentState(e.currentTarget.id.split('_').pop(), e.currentTarget.checked);
});
}
}
}
function updateComponent( component )
{
if (component.name == "ALL")
{
function updateComponent(component) {
if (component.name == "ALL") {
var components = window.comps;
var hyperionEnabled = component.enabled;
for (const comp of components)
{
for (const comp of components) {
if(comp.name === "ALL")
continue;
if (comp.name === "ALL")
continue;
const comp_btn_id = "comp_btn_"+comp.name;
const comp_btn_id = "comp_btn_" + comp.name;
if ( !hyperionEnabled )
{
if (!hyperionEnabled) {
$(`#${comp_btn_id}`).bootstrapToggle('off');
$(`#${comp_btn_id}`).bootstrapToggle("disable");
}
else
{
else {
$(`#${comp_btn_id}`).bootstrapToggle("enable");
if ( comp.enabled !== $(`#${comp_btn_id}`).prop("checked") )
{
if (comp.enabled !== $(`#${comp_btn_id}`).prop("checked")) {
$(`#${comp_btn_id}`).bootstrapToggle().prop('checked', comp.enabled).change();
}
}
}
}
else
{
const comp_btn_id = "comp_btn_"+component.name;
else {
const comp_btn_id = "comp_btn_" + component.name;
//console.log ("updateComponent: ", component.name, "Current Checked: ", $(`#${comp_btn_id}`).prop("checked"), "New Checked: ", component.enabled, );
// In case Buttons were disabled before, status may be different to component status
if ( component.enabled != $(`#${comp_btn_id}`).prop("checked") )
{
if (component.enabled != $(`#${comp_btn_id}`).prop("checked")) {
// console.log ("Update status to Checked = ", component.enabled);
if ( component.enabled )
if (component.enabled)
$(`#${comp_btn_id}`).bootstrapToggle("on");
else
$(`#${comp_btn_id}`).bootstrapToggle("off");
@@ -288,21 +264,19 @@ $(document).ready(function() {
}
}
function updateEffectlist()
{
function updateEffectlist() {
var newEffects = window.serverInfo.effects;
if (newEffects.length != oldEffects.length)
{
if (newEffects.length != oldEffects.length) {
$('#effect_select').html('<option value="__none__"></option>');
var usrEffArr = [];
var sysEffArr = [];
for(var i = 0; i < newEffects.length; i++) {
for (var i = 0; i < newEffects.length; i++) {
var effectName = newEffects[i].name;
if(!/^\:/.test(newEffects[i].file)){
if (!/^\:/.test(newEffects[i].file)) {
usrEffArr.push(effectName);
}
else{
else {
sysEffArr.push(effectName);
}
}
@@ -312,74 +286,70 @@ $(document).ready(function() {
}
}
function updateVideoMode()
{
var videoModes = ["2D","3DSBS","3DTAB"];
function updateVideoMode() {
var videoModes = ["2D", "3DSBS", "3DTAB"];
var currVideoMode = window.serverInfo.videomode;
$('#videomodebtns').html("");
for(var ix = 0; ix < videoModes.length; ix++)
{
if(currVideoMode == videoModes[ix])
for (var ix = 0; ix < videoModes.length; ix++) {
if (currVideoMode == videoModes[ix])
var btn_style = 'btn-success';
else
var btn_style = 'btn-primary';
$('#videomodebtns').append('<button type="button" id="vModeBtn_'+videoModes[ix]+'" class="btn '+btn_style+'" style="margin:3px;min-width:200px" onclick="requestVideoMode(\''+videoModes[ix]+'\');">'+$.i18n('remote_videoMode_'+videoModes[ix])+'</button><br/>');
$('#videomodebtns').append('<button type="button" id="vModeBtn_' + videoModes[ix] + '" class="btn ' + btn_style + '" style="margin:3px;min-width:200px" onclick="requestVideoMode(\'' + videoModes[ix] + '\');">' + $.i18n('remote_videoMode_' + videoModes[ix]) + '</button><br/>');
}
}
// colorpicker and effect
if (getStorage('rmcpcolor') != null)
{
if (getStorage('rmcpcolor') != null) {
cpcolor = getStorage('rmcpcolor');
rgb = hexToRgb(cpcolor);
}
if (getStorage('rmduration') != null)
{
if (getStorage('rmduration') != null) {
$("#remote_duration").val(getStorage('rmduration'));
duration = getStorage('rmduration');
}
createCP('cp2', cpcolor, function(rgbT,hex){
createCP('cp2', cpcolor, function (rgbT, hex) {
rgb = rgbT;
sendColor();
setStorage('rmcpcolor', hex);
updateInputSelect();
});
$("#reset_color").off().on("click", function(){
$("#reset_color").off().on("click", function () {
requestPriorityClear();
lastImgData = "";
$("#effect_select").val("__none__");
$("#remote_input_img").val("");
});
$("#remote_duration").off().on("change", function(){
duration = valValue(this.id,this.value,this.min,this.max);
$("#remote_duration").off().on("change", function () {
duration = valValue(this.id, this.value, this.min, this.max);
setStorage('rmduration', duration);
});
$("#effect_select").off().on("change", function(event) {
$("#effect_select").off().on("change", function (event) {
sendEffect();
});
$("#remote_input_reseff, #remote_input_rescol").off().on("click", function(){
if(this.id == "remote_input_rescol")
$("#remote_input_reseff, #remote_input_rescol").off().on("click", function () {
if (this.id == "remote_input_rescol")
sendColor();
else
sendEffect();
});
$("#remote_input_repimg").off().on("click", function(){
if(lastImgData != "")
$("#remote_input_repimg").off().on("click", function () {
if (lastImgData != "")
requestSetImage(lastImgData, duration, lastFileName);
});
$("#remote_input_img").change(function(){
readImg(this, function(src,fileName){
$("#remote_input_img").change(function () {
readImg(this, function (src, fileName) {
lastFileName = fileName;
if(src.includes(","))
if (src.includes(","))
lastImgData = src.split(",")[1];
else
lastImgData = src;
@@ -397,27 +367,27 @@ $(document).ready(function() {
// interval updates
$(window.hyperion).on('components-updated', function(e, comp){
$(window.hyperion).on('components-updated', function (e, comp) {
//console.log ("components-updated", e, comp);
updateComponent (comp);
updateComponent(comp);
});
$(window.hyperion).on("cmd-priorities-update", function(event){
$(window.hyperion).on("cmd-priorities-update", function (event) {
window.serverInfo.priorities = event.response.data.priorities;
window.serverInfo.priorities_autoselect = event.response.data.priorities_autoselect;
updateInputSelect();
});
$(window.hyperion).on("cmd-imageToLedMapping-update", function(event){
$(window.hyperion).on("cmd-imageToLedMapping-update", function (event) {
window.serverInfo.imageToLedMappingType = event.response.data.imageToLedMappingType;
updateLedMapping();
});
$(window.hyperion).on("cmd-videomode-update", function(event){
$(window.hyperion).on("cmd-videomode-update", function (event) {
window.serverInfo.videomode = event.response.data.videomode;
updateVideoMode();
});
$(window.hyperion).on("cmd-effects-update", function(event){
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects;
updateEffectlist();
});

View File

@@ -3,7 +3,7 @@
var conf_editor = null;
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_webc_heading_title"), 'editor_container', 'btn_submit'));
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_webc_heading_title"), 'editor_container', 'btn_submit', 'panel-system'));
if(window.showOptHelp)
{
$('#conf_cont').append(createHelpTable(window.schema.webConfig.properties, $.i18n("edt_conf_webc_heading_title")));

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,607 @@
/**
* cldrpluralparser.js
* A parser engine for CLDR plural rules.
*
* Copyright 2012-2014 Santhosh Thottingal and other contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
* @source https://github.com/santhoshtr/CLDRPluralRuleParser
* @author Santhosh Thottingal <santhosh.thottingal@gmail.com>
* @author Timo Tijhof
* @author Amir Aharoni
*/
/**
* Evaluates a plural rule in CLDR syntax for a number
* @param {string} rule
* @param {integer} number
* @return {boolean} true if evaluation passed, false if evaluation failed.
*/
// UMD returnExports https://github.com/umdjs/umd/blob/master/returnExports.js
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.pluralRuleParser = factory();
}
}(this, function() {
function pluralRuleParser(rule, number) {
'use strict';
/*
Syntax: see http://unicode.org/reports/tr35/#Language_Plural_Rules
-----------------------------------------------------------------
condition = and_condition ('or' and_condition)*
('@integer' samples)?
('@decimal' samples)?
and_condition = relation ('and' relation)*
relation = is_relation | in_relation | within_relation
is_relation = expr 'is' ('not')? value
in_relation = expr (('not')? 'in' | '=' | '!=') range_list
within_relation = expr ('not')? 'within' range_list
expr = operand (('mod' | '%') value)?
operand = 'n' | 'i' | 'f' | 't' | 'v' | 'w'
range_list = (range | value) (',' range_list)*
value = digit+
digit = 0|1|2|3|4|5|6|7|8|9
range = value'..'value
samples = sampleRange (',' sampleRange)* (',' ('…'|'...'))?
sampleRange = decimalValue '~' decimalValue
decimalValue = value ('.' value)?
*/
// We don't evaluate the samples section of the rule. Ignore it.
rule = rule.split('@')[0].replace(/^\s*/, '').replace(/\s*$/, '');
if (!rule.length) {
// Empty rule or 'other' rule.
return true;
}
// Indicates the current position in the rule as we parse through it.
// Shared among all parsing functions below.
var pos = 0,
operand,
expression,
relation,
result,
whitespace = makeRegexParser(/^\s+/),
value = makeRegexParser(/^\d+/),
_n_ = makeStringParser('n'),
_i_ = makeStringParser('i'),
_f_ = makeStringParser('f'),
_t_ = makeStringParser('t'),
_v_ = makeStringParser('v'),
_w_ = makeStringParser('w'),
_is_ = makeStringParser('is'),
_isnot_ = makeStringParser('is not'),
_isnot_sign_ = makeStringParser('!='),
_equal_ = makeStringParser('='),
_mod_ = makeStringParser('mod'),
_percent_ = makeStringParser('%'),
_not_ = makeStringParser('not'),
_in_ = makeStringParser('in'),
_within_ = makeStringParser('within'),
_range_ = makeStringParser('..'),
_comma_ = makeStringParser(','),
_or_ = makeStringParser('or'),
_and_ = makeStringParser('and');
function debug() {
// console.log.apply(console, arguments);
}
debug('pluralRuleParser', rule, number);
// Try parsers until one works, if none work return null
function choice(parserSyntax) {
return function() {
var i, result;
for (i = 0; i < parserSyntax.length; i++) {
result = parserSyntax[i]();
if (result !== null) {
return result;
}
}
return null;
};
}
// Try several parserSyntax-es in a row.
// All must succeed; otherwise, return null.
// This is the only eager one.
function sequence(parserSyntax) {
var i, parserRes,
originalPos = pos,
result = [];
for (i = 0; i < parserSyntax.length; i++) {
parserRes = parserSyntax[i]();
if (parserRes === null) {
pos = originalPos;
return null;
}
result.push(parserRes);
}
return result;
}
// Run the same parser over and over until it fails.
// Must succeed a minimum of n times; otherwise, return null.
function nOrMore(n, p) {
return function() {
var originalPos = pos,
result = [],
parsed = p();
while (parsed !== null) {
result.push(parsed);
parsed = p();
}
if (result.length < n) {
pos = originalPos;
return null;
}
return result;
};
}
// Helpers - just make parserSyntax out of simpler JS builtin types
function makeStringParser(s) {
var len = s.length;
return function() {
var result = null;
if (rule.substr(pos, len) === s) {
result = s;
pos += len;
}
return result;
};
}
function makeRegexParser(regex) {
return function() {
var matches = rule.substr(pos).match(regex);
if (matches === null) {
return null;
}
pos += matches[0].length;
return matches[0];
};
}
/**
* Integer digits of n.
*/
function i() {
var result = _i_();
if (result === null) {
debug(' -- failed i', parseInt(number, 10));
return result;
}
result = parseInt(number, 10);
debug(' -- passed i ', result);
return result;
}
/**
* Absolute value of the source number (integer and decimals).
*/
function n() {
var result = _n_();
if (result === null) {
debug(' -- failed n ', number);
return result;
}
result = parseFloat(number, 10);
debug(' -- passed n ', result);
return result;
}
/**
* Visible fractional digits in n, with trailing zeros.
*/
function f() {
var result = _f_();
if (result === null) {
debug(' -- failed f ', number);
return result;
}
result = (number + '.').split('.')[1] || 0;
debug(' -- passed f ', result);
return result;
}
/**
* Visible fractional digits in n, without trailing zeros.
*/
function t() {
var result = _t_();
if (result === null) {
debug(' -- failed t ', number);
return result;
}
result = (number + '.').split('.')[1].replace(/0$/, '') || 0;
debug(' -- passed t ', result);
return result;
}
/**
* Number of visible fraction digits in n, with trailing zeros.
*/
function v() {
var result = _v_();
if (result === null) {
debug(' -- failed v ', number);
return result;
}
result = (number + '.').split('.')[1].length || 0;
debug(' -- passed v ', result);
return result;
}
/**
* Number of visible fraction digits in n, without trailing zeros.
*/
function w() {
var result = _w_();
if (result === null) {
debug(' -- failed w ', number);
return result;
}
result = (number + '.').split('.')[1].replace(/0$/, '').length || 0;
debug(' -- passed w ', result);
return result;
}
// operand = 'n' | 'i' | 'f' | 't' | 'v' | 'w'
operand = choice([n, i, f, t, v, w]);
// expr = operand (('mod' | '%') value)?
expression = choice([mod, operand]);
function mod() {
var result = sequence(
[operand, whitespace, choice([_mod_, _percent_]), whitespace, value]
);
if (result === null) {
debug(' -- failed mod');
return null;
}
debug(' -- passed ' + parseInt(result[0], 10) + ' ' + result[2] + ' ' + parseInt(result[4], 10));
return parseFloat(result[0]) % parseInt(result[4], 10);
}
function not() {
var result = sequence([whitespace, _not_]);
if (result === null) {
debug(' -- failed not');
return null;
}
return result[1];
}
// is_relation = expr 'is' ('not')? value
function is() {
var result = sequence([expression, whitespace, choice([_is_]), whitespace, value]);
if (result !== null) {
debug(' -- passed is : ' + result[0] + ' == ' + parseInt(result[4], 10));
return result[0] === parseInt(result[4], 10);
}
debug(' -- failed is');
return null;
}
// is_relation = expr 'is' ('not')? value
function isnot() {
var result = sequence(
[expression, whitespace, choice([_isnot_, _isnot_sign_]), whitespace, value]
);
if (result !== null) {
debug(' -- passed isnot: ' + result[0] + ' != ' + parseInt(result[4], 10));
return result[0] !== parseInt(result[4], 10);
}
debug(' -- failed isnot');
return null;
}
function not_in() {
var i, range_list,
result = sequence([expression, whitespace, _isnot_sign_, whitespace, rangeList]);
if (result !== null) {
debug(' -- passed not_in: ' + result[0] + ' != ' + result[4]);
range_list = result[4];
for (i = 0; i < range_list.length; i++) {
if (parseInt(range_list[i], 10) === parseInt(result[0], 10)) {
return false;
}
}
return true;
}
debug(' -- failed not_in');
return null;
}
// range_list = (range | value) (',' range_list)*
function rangeList() {
var result = sequence([choice([range, value]), nOrMore(0, rangeTail)]),
resultList = [];
if (result !== null) {
resultList = resultList.concat(result[0]);
if (result[1][0]) {
resultList = resultList.concat(result[1][0]);
}
return resultList;
}
debug(' -- failed rangeList');
return null;
}
function rangeTail() {
// ',' range_list
var result = sequence([_comma_, rangeList]);
if (result !== null) {
return result[1];
}
debug(' -- failed rangeTail');
return null;
}
// range = value'..'value
function range() {
var i, array, left, right,
result = sequence([value, _range_, value]);
if (result !== null) {
debug(' -- passed range');
array = [];
left = parseInt(result[0], 10);
right = parseInt(result[2], 10);
for (i = left; i <= right; i++) {
array.push(i);
}
return array;
}
debug(' -- failed range');
return null;
}
function _in() {
var result, range_list, i;
// in_relation = expr ('not')? 'in' range_list
result = sequence(
[expression, nOrMore(0, not), whitespace, choice([_in_, _equal_]), whitespace, rangeList]
);
if (result !== null) {
debug(' -- passed _in:' + result);
range_list = result[5];
for (i = 0; i < range_list.length; i++) {
if (parseInt(range_list[i], 10) === parseFloat(result[0])) {
return (result[1][0] !== 'not');
}
}
return (result[1][0] === 'not');
}
debug(' -- failed _in ');
return null;
}
/**
* The difference between "in" and "within" is that
* "in" only includes integers in the specified range,
* while "within" includes all values.
*/
function within() {
var range_list, result;
// within_relation = expr ('not')? 'within' range_list
result = sequence(
[expression, nOrMore(0, not), whitespace, _within_, whitespace, rangeList]
);
if (result !== null) {
debug(' -- passed within');
range_list = result[5];
if ((result[0] >= parseInt(range_list[0], 10)) &&
(result[0] < parseInt(range_list[range_list.length - 1], 10))) {
return (result[1][0] !== 'not');
}
return (result[1][0] === 'not');
}
debug(' -- failed within ');
return null;
}
// relation = is_relation | in_relation | within_relation
relation = choice([is, not_in, isnot, _in, within]);
// and_condition = relation ('and' relation)*
function and() {
var i,
result = sequence([relation, nOrMore(0, andTail)]);
if (result) {
if (!result[0]) {
return false;
}
for (i = 0; i < result[1].length; i++) {
if (!result[1][i]) {
return false;
}
}
return true;
}
debug(' -- failed and');
return null;
}
// ('and' relation)*
function andTail() {
var result = sequence([whitespace, _and_, whitespace, relation]);
if (result !== null) {
debug(' -- passed andTail' + result);
return result[3];
}
debug(' -- failed andTail');
return null;
}
// ('or' and_condition)*
function orTail() {
var result = sequence([whitespace, _or_, whitespace, and]);
if (result !== null) {
debug(' -- passed orTail: ' + result[3]);
return result[3];
}
debug(' -- failed orTail');
return null;
}
// condition = and_condition ('or' and_condition)*
function condition() {
var i,
result = sequence([and, nOrMore(0, orTail)]);
if (result) {
for (i = 0; i < result[1].length; i++) {
if (result[1][i]) {
return true;
}
}
return result[0];
}
return false;
}
result = condition();
/**
* For success, the pos must have gotten to the end of the rule
* and returned a non-null.
* n.b. This is part of language infrastructure,
* so we do not throw an internationalizable message.
*/
if (result === null) {
throw new Error('Parse error at position ' + pos.toString() + ' for rule: ' + rule);
}
if (pos !== rule.length) {
debug('Warning: Rule not parsed completely. Parser stopped at ' + rule.substr(0, pos) + ' for rule: ' + rule);
}
return result;
}
return pluralRuleParser;
}));

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2011-2013 Santhosh Thottingal, Neil Kandalgaonkar
@@ -17,7 +17,7 @@
'use strict';
var MessageParserEmitter = function () {
this.language = $.i18n.languages[String.locale] || $.i18n.languages['default'];
this.language = $.i18n.languages[ String.locale ] || $.i18n.languages[ 'default' ];
};
MessageParserEmitter.prototype = {
@@ -38,36 +38,36 @@
messageParserEmitter = this;
switch ( typeof node ) {
case 'string':
case 'number':
ret = node;
break;
case 'object':
case 'string':
case 'number':
ret = node;
break;
case 'object':
// node is an array of nodes
subnodes = $.map( node.slice( 1 ), function ( n ) {
return messageParserEmitter.emit( n, replacements );
} );
subnodes = $.map( node.slice( 1 ), function ( n ) {
return messageParserEmitter.emit( n, replacements );
} );
operation = node[0].toLowerCase();
operation = node[ 0 ].toLowerCase();
if ( typeof messageParserEmitter[operation] === 'function' ) {
ret = messageParserEmitter[operation]( subnodes, replacements );
} else {
throw new Error( 'unknown operation "' + operation + '"' );
}
if ( typeof messageParserEmitter[ operation ] === 'function' ) {
ret = messageParserEmitter[ operation ]( subnodes, replacements );
} else {
throw new Error( 'unknown operation "' + operation + '"' );
}
break;
case 'undefined':
break;
case 'undefined':
// Parsing the empty string (as an entire expression, or as a
// paramExpression in a template) results in undefined
// Perhaps a more clever parser can detect this, and return the
// empty string? Or is that useful information?
// The logical thing is probably to return the empty string here
// when we encounter undefined.
ret = '';
break;
default:
throw new Error( 'unexpected type in AST: ' + typeof node );
ret = '';
break;
default:
throw new Error( 'unexpected type in AST: ' + typeof node );
}
return ret;
@@ -80,7 +80,7 @@
* in our children and pass them upwards
*
* @param {Array} nodes Mixed, some single nodes, some arrays of nodes.
* @return String
* @return {string}
*/
concat: function ( nodes ) {
var result = '';
@@ -106,11 +106,11 @@
* @return {string} replacement
*/
replace: function ( nodes, replacements ) {
var index = parseInt( nodes[0], 10 );
var index = parseInt( nodes[ 0 ], 10 );
if ( index < replacements.length ) {
// replacement is not a string, don't touch!
return replacements[index];
return replacements[ index ];
} else {
// index not found, fallback to displaying variable
return '$' + ( index + 1 );
@@ -124,11 +124,11 @@
* convertNumber.
*
* @param {Array} nodes List [ {String|Number}, {String}, {String} ... ]
* @return {String} selected pluralized form according to current
* @return {string} selected pluralized form according to current
* language.
*/
plural: function ( nodes ) {
var count = parseFloat( this.language.convertNumber( nodes[0], 10 ) ),
var count = parseFloat( this.language.convertNumber( nodes[ 0 ], 10 ) ),
forms = nodes.slice( 1 );
return forms.length ? this.language.convertPlural( count, forms ) : '';
@@ -139,10 +139,10 @@
* {{gender:gender|masculine|feminine|neutral}}.
*
* @param {Array} nodes List [ {String}, {String}, {String} , {String} ]
* @return {String} selected gender form according to current language
* @return {string} selected gender form according to current language
*/
gender: function ( nodes ) {
var gender = nodes[0],
var gender = nodes[ 0 ],
forms = nodes.slice( 1 );
return this.language.gender( gender, forms );
@@ -153,12 +153,12 @@
* putting {{grammar:form|word}} in a message
*
* @param {Array} nodes List [{Grammar case eg: genitive}, {String word}]
* @return {String} selected grammatical form according to current
* @return {string} selected grammatical form according to current
* language.
*/
grammar: function ( nodes ) {
var form = nodes[0],
word = nodes[1];
var form = nodes[ 0 ],
word = nodes[ 1 ];
return word && form && this.language.convertGrammar( word, form );
}

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2012 Santhosh Thottingal
@@ -11,7 +11,7 @@
* @licence GNU General Public Licence 2.0 or later
* @licence MIT License
*/
( function ( $, undefined ) {
( function ( $ ) {
'use strict';
$.i18n = $.i18n || {};
@@ -45,7 +45,6 @@
'crh-cyrl': [ 'ru' ],
csb: [ 'pl' ],
cv: [ 'ru' ],
'de-DE': [ 'de' ],
'de-at': [ 'de' ],
'de-ch': [ 'de' ],
'de-formal': [ 'de' ],

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2012 Santhosh Thottingal
@@ -16,7 +16,7 @@
( function ( $ ) {
'use strict';
var nav, I18N,
var I18N,
slice = Array.prototype.slice;
/**
* @constructor
@@ -30,61 +30,52 @@
this.locale = this.options.locale;
this.messageStore = this.options.messageStore;
this.languages = {};
this.init();
};
I18N.prototype = {
/**
* Initialize by loading locales and setting up
* String.prototype.toLocaleString and String.locale.
* Localize a given messageKey to a locale.
* @param {string} messageKey
* @return {string} Localized message
*/
init: function () {
var i18n = this;
localize: function ( messageKey ) {
var localeParts, localePartIndex, locale, fallbackIndex,
tryingLocale, message;
// Set locale of String environment
String.locale = i18n.locale;
locale = this.locale;
fallbackIndex = 0;
// Override String.localeString method
String.prototype.toLocaleString = function () {
var localeParts, localePartIndex, value, locale, fallbackIndex,
tryingLocale, message;
while ( locale ) {
// Iterate through locales starting at most-specific until
// localization is found. As in fi-Latn-FI, fi-Latn and fi.
localeParts = locale.split( '-' );
localePartIndex = localeParts.length;
value = this.valueOf();
locale = i18n.locale;
fallbackIndex = 0;
do {
tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' );
message = this.messageStore.get( tryingLocale, messageKey );
while ( locale ) {
// Iterate through locales starting at most-specific until
// localization is found. As in fi-Latn-FI, fi-Latn and fi.
localeParts = locale.split( '-' );
localePartIndex = localeParts.length;
do {
tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' );
message = i18n.messageStore.get( tryingLocale, value );
if ( message ) {
return message;
}
localePartIndex--;
} while ( localePartIndex );
if ( locale === 'en' ) {
break;
if ( message ) {
return message;
}
locale = ( $.i18n.fallbacks[i18n.locale] && $.i18n.fallbacks[i18n.locale][fallbackIndex] ) ||
i18n.options.fallbackLocale;
$.i18n.log( 'Trying fallback locale for ' + i18n.locale + ': ' + locale );
localePartIndex--;
} while ( localePartIndex );
fallbackIndex++;
if ( locale === this.options.fallbackLocale ) {
break;
}
// key not found
return '';
};
locale = ( $.i18n.fallbacks[ this.locale ] &&
$.i18n.fallbacks[ this.locale ][ fallbackIndex ] ) ||
this.options.fallbackLocale;
$.i18n.log( 'Trying fallback locale for ' + this.locale + ': ' + locale + ' (' + messageKey + ')' );
fallbackIndex++;
}
// key not found
return '';
},
/*
@@ -132,26 +123,28 @@
* If the data argument is null/undefined/false,
* all cached messages for the i18n instance will get reset.
*
* @param {String|Object} source
* @param {String} locale Language tag
* @returns {jQuery.Promise}
* @param {string|Object} source
* @param {string} locale Language tag
* @return {jQuery.Promise}
*/
load: function ( source, locale ) {
var fallbackLocales, locIndex, fallbackLocale, sourceMap = {};
if ( !source && !locale ) {
source = 'i18n';
source = 'i18n/' + $.i18n().locale + '.json';
locale = $.i18n().locale;
}
if ( typeof source === 'string' &&
source.split( '.' ).pop() !== 'json'
if ( typeof source === 'string' &&
// source extension should be json, but can have query params after that.
source.split( '?' )[ 0 ].split( '.' ).pop() !== 'json'
) {
// Load specified locale then check for fallbacks when directory is specified in load()
sourceMap[locale] = source + '/' + locale + '.json';
fallbackLocales = ( $.i18n.fallbacks[locale] || [] )
// Load specified locale then check for fallbacks when directory is
// specified in load()
sourceMap[ locale ] = source + '/' + locale + '.json';
fallbackLocales = ( $.i18n.fallbacks[ locale ] || [] )
.concat( this.options.fallbackLocale );
for ( locIndex in fallbackLocales ) {
fallbackLocale = fallbackLocales[locIndex];
sourceMap[fallbackLocale] = source + '/' + fallbackLocale + '.json';
for ( locIndex = 0; locIndex < fallbackLocales.length; locIndex++ ) {
fallbackLocale = fallbackLocales[ locIndex ];
sourceMap[ fallbackLocale ] = source + '/' + fallbackLocale + '.json';
}
return this.load( sourceMap );
} else {
@@ -168,11 +161,11 @@
* @return {string}
*/
parse: function ( key, parameters ) {
var message = key.toLocaleString();
var message = this.localize( key );
// FIXME: This changes the state of the I18N object,
// should probably not change the 'this.parser' but just
// pass it to the parser.
this.parser.language = $.i18n.languages[$.i18n().locale] || $.i18n.languages['default'];
this.parser.language = $.i18n.languages[ $.i18n().locale ] || $.i18n.languages[ 'default' ];
if ( message === '' ) {
message = key;
}
@@ -202,7 +195,7 @@
// NOTE: It should only change language for this one call.
// Then cache instances of I18N somewhere.
if ( options && options.locale && i18n && i18n.locale !== options.locale ) {
String.locale = i18n.locale = options.locale;
i18n.locale = options.locale;
}
if ( !i18n ) {
@@ -231,28 +224,38 @@
i18n = new I18N();
$.data( document, 'i18n', i18n );
}
String.locale = i18n.locale;
return this.each( function () {
var $this = $( this ),
messageKey = $this.data( 'i18n' );
messageKey = $this.data( 'i18n' ),
lBracket, rBracket, type, key;
if ( messageKey ) {
$this.text( i18n.parse( messageKey ) );
lBracket = messageKey.indexOf( '[' );
rBracket = messageKey.indexOf( ']' );
if ( lBracket !== -1 && rBracket !== -1 && lBracket < rBracket ) {
type = messageKey.slice( lBracket + 1, rBracket );
key = messageKey.slice( rBracket + 1 );
if ( type === 'html' ) {
$this.html( i18n.parse( key ) );
} else {
$this.attr( type, i18n.parse( key ) );
}
} else {
$this.text( i18n.parse( messageKey ) );
}
} else {
$this.find( '[data-i18n]' ).i18n();
}
} );
};
String.locale = String.locale || $( 'html' ).attr( 'lang' );
if ( !String.locale ) {
if ( typeof window.navigator !== 'undefined' ) {
nav = window.navigator;
String.locale = nav.language || nav.userLanguage || '';
} else {
String.locale = '';
function getDefaultLocale() {
var locale = $( 'html' ).attr( 'lang' );
if ( !locale ) {
locale = navigator.language || navigator.userLanguage || '';
}
return locale;
}
$.i18n.languages = {};
@@ -262,7 +265,7 @@
parse: function ( message, parameters ) {
return message.replace( /\$(\d+)/g, function ( str, match ) {
var index = parseInt( match, 10 ) - 1;
return parameters[index] !== undefined ? parameters[index] : '$' + match;
return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
} );
},
emitter: {}
@@ -276,7 +279,7 @@
};
/* Static members */
I18N.defaults = {
locale: String.locale,
locale: getDefaultLocale(),
fallbackLocale: 'en',
parser: $.i18n.parser,
messageStore: $.i18n.messageStore

View File

@@ -1,7 +1,8 @@
/*global pluralRuleParser */
/* global pluralRuleParser */
( function ( $ ) {
'use strict';
// jscs:disable
var language = {
// CLDR plural rules generated using
// libs/CLDRPluralRuleParser/tools/PluralXML2JSON.html
@@ -19,6 +20,16 @@
few: 'n % 100 = 3..10',
many: 'n % 100 = 11..99'
},
ars: {
zero: 'n = 0',
one: 'n = 1',
two: 'n = 2',
few: 'n % 100 = 3..10',
many: 'n % 100 = 11..99'
},
as: {
one: 'i = 0 or n = 1'
},
be: {
one: 'n % 10 = 1 and n % 100 != 11',
few: 'n % 10 = 2..4 and n % 100 != 12..14',
@@ -55,6 +66,11 @@
da: {
one: 'n = 1 or t != 0 and i = 0,1'
},
dsb: {
one: 'v = 0 and i % 100 = 1 or f % 100 = 1',
two: 'v = 0 and i % 100 = 2 or f % 100 = 2',
few: 'v = 0 and i % 100 = 3..4 or f % 100 = 3..4'
},
fa: {
one: 'i = 0 or n = 1'
},
@@ -62,7 +78,7 @@
one: 'i = 0,1'
},
fil: {
one: 'i = 0..1 and v = 0'
one: 'v = 0 and i = 1,2,3 or v = 0 and i % 10 != 4,6,9 or v != 0 and f % 10 != 4,6,9'
},
fr: {
one: 'i = 0,1'
@@ -85,9 +101,10 @@
one: 'n = 0..1'
},
gv: {
one: 'n % 10 = 1',
two: 'n % 10 = 2',
few: 'n % 100 = 0,20,40,60'
one: 'v = 0 and i % 10 = 1',
two: 'v = 0 and i % 10 = 2',
few: 'v = 0 and i % 100 = 0,20,40,60,80',
many: 'v != 0'
},
he: {
one: 'i = 1 and v = 0',
@@ -101,6 +118,11 @@
one: 'v = 0 and i % 10 = 1 and i % 100 != 11 or f % 10 = 1 and f % 100 != 11',
few: 'v = 0 and i % 10 = 2..4 and i % 100 != 12..14 or f % 10 = 2..4 and f % 100 != 12..14'
},
hsb: {
one: 'v = 0 and i % 100 = 1 or f % 100 = 1',
two: 'v = 0 and i % 100 = 2 or f % 100 = 2',
few: 'v = 0 and i % 100 = 3..4 or f % 100 = 3..4'
},
hy: {
one: 'i = 0,1'
},
@@ -175,20 +197,20 @@
few: 'v = 0 and i % 10 = 2..4 and i % 100 != 12..14',
many: 'v = 0 and i != 1 and i % 10 = 0..1 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 12..14'
},
prg: {
zero: 'n % 10 = 0 or n % 100 = 11..19 or v = 2 and f % 100 = 11..19',
one: 'n % 10 = 1 and n % 100 != 11 or v = 2 and f % 10 = 1 and f % 100 != 11 or v != 2 and f % 10 = 1'
},
pt: {
one: 'i = 1 and v = 0 or i = 0 and t = 1'
one: 'i = 0..1'
},
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
pt_PT: {
one: 'n = 1 and v = 0'
},
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
ro: {
one: 'i = 1 and v = 0',
few: 'v != 0 or n = 0 or n != 1 and n % 100 = 1..19'
},
ru: {
one: 'v = 0 and i % 10 = 1 and i % 100 != 11',
few: 'v = 0 and i % 10 = 2..4 and i % 100 != 12..14',
many: 'v = 0 and i % 10 = 0 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 11..14'
},
se: {
@@ -244,7 +266,7 @@
one: 'n = 0..1'
},
tl: {
one: 'i = 0..1 and v = 0'
one: 'v = 0 and i = 1,2,3 or v = 0 and i % 10 != 4,6,9 or v != 0 and f % 10 != 4,6,9'
},
tzm: {
one: 'n = 0..1 or n = 11..99'
@@ -261,21 +283,22 @@
one: 'i = 0 or n = 1'
}
},
// jscs:enable
/**
* Plural form transformations, needed for some languages.
*
* @param count
* integer Non-localized quantifier
* @param forms
* array List of plural forms
* @return string Correct form for quantifier in this language
* @param {integer} count
* Non-localized quantifier
* @param {Array} forms
* List of plural forms
* @return {string} Correct form for quantifier in this language
*/
convertPlural: function ( count, forms ) {
var pluralRules,
pluralFormIndex,
index,
explicitPluralPattern = new RegExp( '\\d+=', 'i' ),
explicitPluralPattern = /\d+=/i,
formCount,
form;
@@ -285,13 +308,13 @@
// Handle for Explicit 0= & 1= values
for ( index = 0; index < forms.length; index++ ) {
form = forms[index];
form = forms[ index ];
if ( explicitPluralPattern.test( form ) ) {
formCount = parseInt( form.substring( 0, form.indexOf( '=' ) ), 10 );
formCount = parseInt( form.slice( 0, form.indexOf( '=' ) ), 10 );
if ( formCount === count ) {
return ( form.substr( form.indexOf( '=' ) + 1 ) );
return ( form.slice( form.indexOf( '=' ) + 1 ) );
}
forms[index] = undefined;
forms[ index ] = undefined;
}
}
@@ -301,25 +324,25 @@
}
} );
pluralRules = this.pluralRules[$.i18n().locale];
pluralRules = this.pluralRules[ $.i18n().locale ];
if ( !pluralRules ) {
// default fallback.
return ( count === 1 ) ? forms[0] : forms[1];
return ( count === 1 ) ? forms[ 0 ] : forms[ 1 ];
}
pluralFormIndex = this.getPluralForm( count, pluralRules );
pluralFormIndex = Math.min( pluralFormIndex, forms.length - 1 );
return forms[pluralFormIndex];
return forms[ pluralFormIndex ];
},
/**
* For the number, get the plural for index
*
* @param number
* @param pluralRules
* @return plural form index
* @param {integer} number
* @param {Object} pluralRules
* @return {integer} plural form index
*/
getPluralForm: function ( number, pluralRules ) {
var i,
@@ -327,8 +350,8 @@
pluralFormIndex = 0;
for ( i = 0; i < pluralForms.length; i++ ) {
if ( pluralRules[pluralForms[i]] ) {
if ( pluralRuleParser( pluralRules[pluralForms[i]], number ) ) {
if ( pluralRules[ pluralForms[ i ] ] ) {
if ( pluralRuleParser( pluralRules[ pluralForms[ i ] ], number ) ) {
return pluralFormIndex;
}
@@ -344,6 +367,7 @@
*
* @param {number} num Value to be converted
* @param {boolean} integer Convert the return value to an integer
* @return {string} The number converted into a String.
*/
convertNumber: function ( num, integer ) {
var tmp, item, i,
@@ -360,28 +384,28 @@
// Check if the restore to Latin number flag is set:
if ( integer ) {
if ( parseFloat( num ) === num ) {
if ( parseFloat( num, 10 ) === num ) {
return num;
}
tmp = [];
for ( item in transformTable ) {
tmp[transformTable[item]] = item;
tmp[ transformTable[ item ] ] = item;
}
transformTable = tmp;
}
for ( i = 0; i < numberString.length; i++ ) {
if ( transformTable[numberString[i]] ) {
convertedNumber += transformTable[numberString[i]];
if ( transformTable[ numberString[ i ] ] ) {
convertedNumber += transformTable[ numberString[ i ] ];
} else {
convertedNumber += numberString[i];
convertedNumber += numberString[ i ];
}
}
return integer ? parseFloat( convertedNumber ) : convertedNumber;
return integer ? parseFloat( convertedNumber, 10 ) : convertedNumber;
},
/**
@@ -390,11 +414,12 @@
* Override this method for languages that need special grammar rules
* applied dynamically.
*
* @param word {String}
* @param form {String}
* @return {String}
* @param {string} word
* @param {string} form
* @return {string}
*/
convertGrammar: function ( word, form ) { /*jshint unused: false */
// eslint-disable-next-line no-unused-vars
convertGrammar: function ( word, form ) {
return word;
},
@@ -405,12 +430,12 @@
*
* These details may be overriden per language.
*
* @param gender
* string male, female, or anything else for neutral.
* @param forms
* array List of gender forms
* @param {string} gender
* male, female, or anything else for neutral.
* @param {Array} forms
* List of gender forms
*
* @return string
* @return {string}
*/
gender: function ( gender, forms ) {
if ( !forms || forms.length === 0 ) {
@@ -418,25 +443,26 @@
}
while ( forms.length < 2 ) {
forms.push( forms[forms.length - 1] );
forms.push( forms[ forms.length - 1 ] );
}
if ( gender === 'male' ) {
return forms[0];
return forms[ 0 ];
}
if ( gender === 'female' ) {
return forms[1];
return forms[ 1 ];
}
return ( forms.length === 3 ) ? forms[2] : forms[0];
return ( forms.length === 3 ) ? forms[ 2 ] : forms[ 0 ];
},
/**
* Get the digit transform table for the given language
* See http://cldr.unicode.org/translation/numbering-systems
* @param language
* @returns {Array|boolean} List of digits in the passed language or false
*
* @param {string} language
* @return {Array|boolean} List of digits in the passed language or false
* representation, or boolean false if there is no information.
*/
digitTransformTable: function ( language ) {
@@ -448,6 +474,7 @@
lo: '໐໑໒໓໔໕໖໗໘໙',
or: '୦୧୨୩୪୫୬୭୮୯',
kh: '០១២៣៤៥៦៧៨៩',
nqo: '߀߁߂߃߄߅߆߇߈߉', // Note that the digits go right to left
pa: '੦੧੨੩੪੫੬੭੮੯',
gu: '૦૧૨૩૪૫૬૭૮૯',
hi: '०१२३४५६७८९',
@@ -458,15 +485,15 @@
bo: '༠༡༢༣༤༥༦༧༨༩' // FIXME use iso 639 codes
};
if ( !tables[language] ) {
if ( !tables[ language ] ) {
return false;
}
return tables[language].split( '' );
return tables[ language ].split( '' );
}
};
$.extend( $.i18n.languages, {
'default': language
default: language
} );
}( jQuery ) );

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library - Message Store
*
* Copyright (C) 2012 Santhosh Thottingal
@@ -12,7 +12,7 @@
* @licence MIT License
*/
( function ( $, window, undefined ) {
( function ( $ ) {
'use strict';
var MessageStore = function () {
@@ -20,6 +20,20 @@
this.sources = {};
};
function jsonMessageLoader( url ) {
var deferred = $.Deferred();
$.getJSON( url )
.done( deferred.resolve )
.fail( function ( jqxhr, settings, exception ) {
$.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception );
// Ignore 404 exception, because we are handling fallabacks explicitly
deferred.resolve();
} );
return deferred.promise();
}
/**
* See https://github.com/wikimedia/jquery.i18n/wiki/Specification#wiki-Message_File_Loading
*/
@@ -41,25 +55,22 @@
* null/undefined/false,
* all cached messages for the i18n instance will get reset.
*
* @param {String|Object} source
* @param {String} locale Language tag
* @param {string|Object} source
* @param {string} locale Language tag
* @return {jQuery.Promise}
*/
load: function ( source, locale ) {
var key = null,
deferred = null,
deferreds = [],
messageStore = this;
if ( typeof source === 'string' ) {
// This is a URL to the messages file.
$.i18n.log( 'Loading messages from: ' + source );
deferred = jsonMessageLoader( source )
.done( function ( localization ) {
messageStore.set( locale, localization );
return jsonMessageLoader( source )
.then( function ( localization ) {
return messageStore.load( localization, locale );
} );
return deferred.promise();
}
if ( locale ) {
@@ -74,7 +85,7 @@
locale = key;
// No {locale} given, assume data is a group of languages,
// call this function again for each language.
deferreds.push( messageStore.load( source[key], locale ) );
deferreds.push( messageStore.load( source[ key ], locale ) );
}
}
return $.when.apply( $, deferreds );
@@ -85,41 +96,28 @@
/**
* Set messages to the given locale.
* If locale exists, add messages to the locale.
* @param locale
* @param messages
*
* @param {string} locale
* @param {Object} messages
*/
set: function ( locale, messages ) {
if ( !this.messages[locale] ) {
this.messages[locale] = messages;
if ( !this.messages[ locale ] ) {
this.messages[ locale ] = messages;
} else {
this.messages[locale] = $.extend( this.messages[locale], messages );
this.messages[ locale ] = $.extend( this.messages[ locale ], messages );
}
},
/**
*
* @param locale
* @param messageKey
* @returns {Boolean}
* @param {string} locale
* @param {string} messageKey
* @return {boolean}
*/
get: function ( locale, messageKey ) {
return this.messages[locale] && this.messages[locale][messageKey];
return this.messages[ locale ] && this.messages[ locale ][ messageKey ];
}
};
function jsonMessageLoader( url ) {
var deferred = $.Deferred();
$.getJSON( url )
.done( deferred.resolve )
.fail( function ( jqxhr, settings, exception ) {
$.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception );
// Ignore 404 exception, because we are handling fallabacks explicitly
deferred.resolve();
} );
return deferred.promise();
}
$.extend( $.i18n.messageStore, new MessageStore() );
}( jQuery, window ) );
}( jQuery ) );

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2011-2013 Santhosh Thottingal, Neil Kandalgaonkar
@@ -18,7 +18,7 @@
var MessageParser = function ( options ) {
this.options = $.extend( {}, $.i18n.parser.defaults, options );
this.language = $.i18n.languages[String.locale] || $.i18n.languages['default'];
this.language = $.i18n.languages[ String.locale ] || $.i18n.languages[ 'default' ];
this.emitter = $.i18n.parser.emitter;
};
@@ -30,7 +30,7 @@
return message.replace( /\$(\d+)/g, function ( str, match ) {
var index = parseInt( match, 10 ) - 1;
return parameters[index] !== undefined ? parameters[index] : '$' + match;
return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
} );
},
@@ -39,8 +39,8 @@
return this.simpleParse( message, replacements );
}
this.emitter.language = $.i18n.languages[$.i18n().locale] ||
$.i18n.languages['default'];
this.emitter.language = $.i18n.languages[ $.i18n().locale ] ||
$.i18n.languages[ 'default' ];
return this.emitter.emit( this.ast( message ), replacements );
},
@@ -58,7 +58,7 @@
var i, result;
for ( i = 0; i < parserSyntax.length; i++ ) {
result = parserSyntax[i]();
result = parserSyntax[ i ]();
if ( result !== null ) {
return result;
@@ -78,7 +78,7 @@
result = [];
for ( i = 0; i < parserSyntax.length; i++ ) {
res = parserSyntax[i]();
res = parserSyntax[ i ]();
if ( res === null ) {
pos = originalPos;
@@ -123,7 +123,7 @@
return function () {
var result = null;
if ( message.substr( pos, len ) === s ) {
if ( message.slice( pos, pos + len ) === s ) {
result = s;
pos += len;
}
@@ -134,15 +134,15 @@
function makeRegexParser( regex ) {
return function () {
var matches = message.substr( pos ).match( regex );
var matches = message.slice( pos ).match( regex );
if ( matches === null ) {
return null;
}
pos += matches[0].length;
pos += matches[ 0 ].length;
return matches[0];
return matches[ 0 ];
};
}
@@ -152,9 +152,9 @@
anyCharacter = makeRegexParser( /^./ );
dollar = makeStringParser( '$' );
digits = makeRegexParser( /^\d+/ );
regularLiteral = makeRegexParser( /^[^{}\[\]$\\]/ );
regularLiteralWithoutBar = makeRegexParser( /^[^{}\[\]$\\|]/ );
regularLiteralWithoutSpace = makeRegexParser( /^[^{}\[\]$\s]/ );
regularLiteral = makeRegexParser( /^[^{}[\]$\\]/ );
regularLiteralWithoutBar = makeRegexParser( /^[^{}[\]$\\|]/ );
regularLiteralWithoutSpace = makeRegexParser( /^[^{}[\]$\s]/ );
// There is a general pattern:
// parse a thing;
@@ -189,7 +189,7 @@
function escapedLiteral() {
var result = sequence( [ backslash, anyCharacter ] );
return result === null ? null : result[1];
return result === null ? null : result[ 1 ];
}
choice( [ escapedLiteral, regularLiteralWithoutSpace ] );
@@ -203,13 +203,13 @@
return null;
}
return [ 'REPLACE', parseInt( result[1], 10 ) - 1 ];
return [ 'REPLACE', parseInt( result[ 1 ], 10 ) - 1 ];
}
templateName = transform(
// see $wgLegalTitleChars
// not allowing : due to the need to catch "PLURAL:$1"
makeRegexParser( /^[ !"$&'()*,.\/0-9;=?@A-Z\^_`a-z~\x80-\xFF+\-]+/ ),
makeRegexParser( /^[ !"$&'()*,./0-9;=?@A-Z^_`a-z~\x80-\xFF+-]+/ ),
function ( result ) {
return result.toString();
@@ -224,23 +224,23 @@
return null;
}
expr = result[1];
expr = result[ 1 ];
// use a "CONCAT" operator if there are multiple nodes,
// otherwise return the first node, raw.
return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[0];
return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[ 0 ];
}
function templateWithReplacement() {
var result = sequence( [ templateName, colon, replacement ] );
return result === null ? null : [ result[0], result[2] ];
return result === null ? null : [ result[ 0 ], result[ 2 ] ];
}
function templateWithOutReplacement() {
var result = sequence( [ templateName, colon, paramExpression ] );
return result === null ? null : [ result[0], result[2] ];
return result === null ? null : [ result[ 0 ], result[ 2 ] ];
}
templateContents = choice( [
@@ -254,7 +254,7 @@
nOrMore( 0, templateParam )
] );
return res === null ? null : res[0].concat( res[1] );
return res === null ? null : res[ 0 ].concat( res[ 1 ] );
},
function () {
var res = sequence( [ templateName, nOrMore( 0, templateParam ) ] );
@@ -263,7 +263,7 @@
return null;
}
return [ res[0] ].concat( res[1] );
return [ res[ 0 ] ].concat( res[ 1 ] );
}
] );
@@ -273,7 +273,7 @@
function template() {
var result = sequence( [ openTemplate, templateContents, closeTemplate ] );
return result === null ? null : result[1];
return result === null ? null : result[ 1 ];
}
expression = choice( [ template, replacement, literal ] );
@@ -294,7 +294,8 @@
/*
* For success, the pos must have gotten to the end of the input
* and returned a non-null.
* n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
* n.b. This is part of language infrastructure, so we do not throw an
* internationalizable message.
*/
if ( result === null || pos !== message.length ) {
throw new Error( 'Parse error at position ' + pos.toString() + ' in input: ' + message );

View File

@@ -0,0 +1,22 @@
/**
* Bosnian (bosanski) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.bs = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'instrumental': // instrumental
word = 's ' + word;
break;
case 'lokativ': // locative
word = 'o ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,22 @@
/**
* Lower Sorbian (Dolnoserbski) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.dsb = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'instrumental': // instrumental
word = 'z ' + word;
break;
case 'lokatiw': // lokatiw
word = 'wo ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,49 @@
/**
* Finnish (Suomi) language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.fi = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
// vowel harmony flag
var aou = word.match( /[aou][^äöy]*$/i ),
origWord = word;
if ( word.match( /wiki$/i ) ) {
aou = false;
}
// append i after final consonant
if ( word.match( /[bcdfghjklmnpqrstvwxz]$/i ) ) {
word += 'i';
}
switch ( form ) {
case 'genitive':
word += 'n';
break;
case 'elative':
word += ( aou ? 'sta' : 'stä' );
break;
case 'partitive':
word += ( aou ? 'a' : 'ä' );
break;
case 'illative':
// Double the last letter and add 'n'
word += word.slice( -1 ) + 'n';
break;
case 'inessive':
word += ( aou ? 'ssa' : 'ssä' );
break;
default:
word = origWord;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,38 @@
/**
* Irish (Gaeilge) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.ga = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
if ( form === 'ainmlae' ) {
switch ( word ) {
case 'an Domhnach':
word = 'Dé Domhnaigh';
break;
case 'an Luan':
word = 'Dé Luain';
break;
case 'an Mháirt':
word = 'Dé Mháirt';
break;
case 'an Chéadaoin':
word = 'Dé Chéadaoin';
break;
case 'an Déardaoin':
word = 'Déardaoin';
break;
case 'an Aoine':
word = 'Dé hAoine';
break;
case 'an Satharn':
word = 'Dé Sathairn';
break;
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,31 @@
/**
* Hebrew (עברית) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.he = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'prefixed':
case 'תחילית': // the same word in Hebrew
// Duplicate prefixed "Waw", but only if it's not already double
if ( word.slice( 0, 1 ) === 'ו' && word.slice( 0, 2 ) !== 'וו' ) {
word = 'ו' + word;
}
// Remove the "He" if prefixed
if ( word.slice( 0, 1 ) === 'ה' ) {
word = word.slice( 1 );
}
// Add a hyphen (maqaf) before numbers and non-Hebrew letters
if ( word.slice( 0, 1 ) < 'א' || word.slice( 0, 1 ) > 'ת' ) {
word = '־' + word;
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,21 @@
/**
* Upper Sorbian (Hornjoserbsce) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.hsb = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'instrumental': // instrumental
word = 'z ' + word;
break;
case 'lokatiw': // lokatiw
word = 'wo ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,26 @@
/**
* Hungarian language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.hu = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'rol':
word += 'ról';
break;
case 'ba':
word += 'ba';
break;
case 'k':
word += 'k';
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,25 @@
/**
* Armenian (Հայերեն) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.hy = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
if ( form === 'genitive' ) { // սեռական հոլով
if ( word.slice( -1 ) === 'ա' ) {
word = word.slice( 0, -1 ) + 'այի';
} else if ( word.slice( -1 ) === 'ո' ) {
word = word.slice( 0, -1 ) + 'ոյի';
} else if ( word.slice( -4 ) === 'գիրք' ) {
word = word.slice( 0, -4 ) + 'գրքի';
} else {
word = word + 'ի';
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,54 @@
/**
* Latin (lingua Latina) language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.la = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'genitive':
// only a few declensions, and even for those mostly the singular only
word = word.replace( /u[ms]$/i, 'i' ); // 2nd declension singular
word = word.replace( /ommunia$/i, 'ommunium' ); // 3rd declension neuter plural (partly)
word = word.replace( /a$/i, 'ae' ); // 1st declension singular
word = word.replace( /libri$/i, 'librorum' ); // 2nd declension plural (partly)
word = word.replace( /nuntii$/i, 'nuntiorum' ); // 2nd declension plural (partly)
word = word.replace( /tio$/i, 'tionis' ); // 3rd declension singular (partly)
word = word.replace( /ns$/i, 'ntis' );
word = word.replace( /as$/i, 'atis' );
word = word.replace( /es$/i, 'ei' ); // 5th declension singular
break;
case 'accusative':
// only a few declensions, and even for those mostly the singular only
word = word.replace( /u[ms]$/i, 'um' ); // 2nd declension singular
word = word.replace( /ommunia$/i, 'am' ); // 3rd declension neuter plural (partly)
word = word.replace( /a$/i, 'ommunia' ); // 1st declension singular
word = word.replace( /libri$/i, 'libros' ); // 2nd declension plural (partly)
word = word.replace( /nuntii$/i, 'nuntios' );// 2nd declension plural (partly)
word = word.replace( /tio$/i, 'tionem' ); // 3rd declension singular (partly)
word = word.replace( /ns$/i, 'ntem' );
word = word.replace( /as$/i, 'atem' );
word = word.replace( /es$/i, 'em' ); // 5th declension singular
break;
case 'ablative':
// only a few declensions, and even for those mostly the singular only
word = word.replace( /u[ms]$/i, 'o' ); // 2nd declension singular
word = word.replace( /ommunia$/i, 'ommunibus' ); // 3rd declension neuter plural (partly)
word = word.replace( /a$/i, 'a' ); // 1st declension singular
word = word.replace( /libri$/i, 'libris' ); // 2nd declension plural (partly)
word = word.replace( /nuntii$/i, 'nuntiis' ); // 2nd declension plural (partly)
word = word.replace( /tio$/i, 'tione' ); // 3rd declension singular (partly)
word = word.replace( /ns$/i, 'nte' );
word = word.replace( /as$/i, 'ate' );
word = word.replace( /es$/i, 'e' ); // 5th declension singular
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,98 @@
/**
* Malayalam language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.ml = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
form = form.toLowerCase();
switch ( form ) {
case 'ഉദ്ദേശിക':
case 'dative':
if ( word.slice( -1 ) === 'ു' ||
word.slice( -1 ) === 'ൂ' ||
word.slice( -1 ) === 'ൗ' ||
word.slice( -1 ) === 'ൌ'
) {
word += 'വിന്';
} else if ( word.slice( -1 ) === '' ) {
word = word.slice( 0, -1 ) + 'ത്തിന്';
} else if ( word.slice( -1 ) === 'ൻ' ) {
// Atomic chillu n. അവൻ -> അവന്
word = word.slice( 0, -1 ) + 'ന്';
} else if ( word.slice( -3 ) === 'ന്\u200d' ) {
// chillu n. അവൻ -> അവന്
word = word.slice( 0, -1 );
} else if ( word.slice( -1 ) === 'ൾ' || word.slice( -3 ) === 'ള്\u200d' ) {
word += 'ക്ക്';
} else if ( word.slice( -1 ) === 'ർ' || word.slice( -3 ) === 'ര്\u200d' ) {
word += 'ക്ക്';
} else if ( word.slice( -1 ) === 'ൽ' ) {
// Atomic chillu ൽ , ഫയൽ -> ഫയലിന്
word = word.slice( 0, -1 ) + 'ലിന്';
} else if ( word.slice( -3 ) === 'ല്\u200d' ) {
// chillu ല്\u200d , ഫയല്\u200d -> ഫയലിന്
word = word.slice( 0, -2 ) + 'ിന്';
} else if ( word.slice( -2 ) === 'ു്' ) {
word = word.slice( 0, -2 ) + 'ിന്';
} else if ( word.slice( -1 ) === '്' ) {
word = word.slice( 0, -1 ) + 'ിന്';
} else {
// കാവ്യ -> കാവ്യയ്ക്ക്, ഹരി -> ഹരിയ്ക്ക്, മല -> മലയ്ക്ക്
word += 'യ്ക്ക്';
}
break;
case 'സംബന്ധിക':
case 'genitive':
if ( word.slice( -1 ) === '' ) {
word = word.slice( 0, -1 ) + 'ത്തിന്റെ';
} else if ( word.slice( -2 ) === 'ു്' ) {
word = word.slice( 0, -2 ) + 'ിന്റെ';
} else if ( word.slice( -1 ) === '്' ) {
word = word.slice( 0, -1 ) + 'ിന്റെ';
} else if ( word.slice( -1 ) === 'ു' ||
word.slice( -1 ) === 'ൂ' ||
word.slice( -1 ) === 'ൗ' ||
word.slice( -1 ) === 'ൌ'
) {
word += 'വിന്റെ';
} else if ( word.slice( -1 ) === 'ൻ' ) {
// Atomic chillu n. അവൻ -> അവന്റെ
word = word.slice( 0, -1 ) + 'ന്റെ';
} else if ( word.slice( -3 ) === 'ന്\u200d' ) {
// chillu n. അവൻ -> അവന്റെ
word = word.slice( 0, -1 ) + 'റെ';
} else if ( word.slice( -3 ) === 'ള്\u200d' ) {
// chillu n. അവൾ -> അവളുടെ
word = word.slice( 0, -2 ) + 'ുടെ';
} else if ( word.slice( -1 ) === 'ൾ' ) {
// Atomic chillu n. അവള്\u200d -> അവളുടെ
word = word.slice( 0, -1 ) + 'ളുടെ';
} else if ( word.slice( -1 ) === 'ൽ' ) {
// Atomic l. മുയല്\u200d -> മുയലിന്റെ
word = word.slice( 0, -1 ) + 'ലിന്റെ';
} else if ( word.slice( -3 ) === 'ല്\u200d' ) {
// chillu l. മുയല്\u200d -> അവളുടെ
word = word.slice( 0, -2 ) + 'ിന്റെ';
} else if ( word.slice( -3 ) === 'ര്\u200d' ) {
// chillu r. അവര്\u200d -> അവരുടെ
word = word.slice( 0, -2 ) + 'ുടെ';
} else if ( word.slice( -1 ) === 'ർ' ) {
// Atomic chillu r. അവർ -> അവരുടെ
word = word.slice( 0, -1 ) + 'രുടെ';
} else {
word += 'യുടെ';
}
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,75 @@
/**
* Ossetian (Ирон) language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.os = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
var endAllative, jot, hyphen, ending;
// Ending for allative case
endAllative = 'мæ';
// Variable for 'j' beetwen vowels
jot = '';
// Variable for "-" for not Ossetic words
hyphen = '';
// Variable for ending
ending = '';
if ( word.match( /тæ$/i ) ) {
// Checking if the $word is in plural form
word = word.slice( 0, -1 );
endAllative = 'æм';
} else if ( word.match( /[аæеёиоыэюя]$/i ) ) {
// Works if word is in singular form.
// Checking if word ends on one of the vowels: е, ё, и, о, ы, э, ю,
// я.
jot = 'й';
} else if ( word.match( /у$/i ) ) {
// Checking if word ends on 'у'. 'У' can be either consonant 'W' or
// vowel 'U' in cyrillic Ossetic.
// Examples: {{grammar:genitive|аунеу}} = аунеуы,
// {{grammar:genitive|лæппу}} = лæппуйы.
if ( !word.slice( -2, -1 ).match( /[аæеёиоыэюя]$/i ) ) {
jot = 'й';
}
} else if ( !word.match( /[бвгджзйклмнопрстфхцчшщьъ]$/i ) ) {
hyphen = '-';
}
switch ( form ) {
case 'genitive':
ending = hyphen + jot + 'ы';
break;
case 'dative':
ending = hyphen + jot + 'æн';
break;
case 'allative':
ending = hyphen + endAllative;
break;
case 'ablative':
if ( jot === 'й' ) {
ending = hyphen + jot + 'æ';
} else {
ending = hyphen + jot + 'æй';
}
break;
case 'superessive':
ending = hyphen + jot + 'ыл';
break;
case 'equative':
ending = hyphen + jot + 'ау';
break;
case 'comitative':
ending = hyphen + 'имæ';
break;
}
return word + ending;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,29 @@
/**
* Russian (Русский) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.ru = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
if ( form === 'genitive' ) { // родительный падеж
if ( word.slice( -1 ) === 'ь' ) {
word = word.slice( 0, -1 ) + 'я';
} else if ( word.slice( -2 ) === 'ия' ) {
word = word.slice( 0, -2 ) + 'ии';
} else if ( word.slice( -2 ) === 'ка' ) {
word = word.slice( 0, -2 ) + 'ки';
} else if ( word.slice( -2 ) === 'ти' ) {
word = word.slice( 0, -2 ) + 'тей';
} else if ( word.slice( -2 ) === 'ды' ) {
word = word.slice( 0, -2 ) + 'дов';
} else if ( word.slice( -3 ) === 'ник' ) {
word = word.slice( 0, -3 ) + 'ника';
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,26 @@
/**
* Slovenian (Slovenščina) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.sl = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
// locative
case 'mestnik':
word = 'o ' + word;
break;
// instrumental
case 'orodnik':
word = 'z ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,39 @@
/**
* Ukrainian (Українська) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.uk = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'genitive': // родовий відмінок
if ( word.slice( -1 ) === 'ь' ) {
word = word.slice( 0, -1 ) + 'я';
} else if ( word.slice( -2 ) === 'ія' ) {
word = word.slice( 0, -2 ) + 'ії';
} else if ( word.slice( -2 ) === 'ка' ) {
word = word.slice( 0, -2 ) + 'ки';
} else if ( word.slice( -2 ) === 'ти' ) {
word = word.slice( 0, -2 ) + 'тей';
} else if ( word.slice( -2 ) === 'ды' ) {
word = word.slice( 0, -2 ) + 'дов';
} else if ( word.slice( -3 ) === 'ник' ) {
word = word.slice( 0, -3 ) + 'ника';
}
break;
case 'accusative': // знахідний відмінок
if ( word.slice( -2 ) === 'ія' ) {
word = word.slice( 0, -2 ) + 'ію';
}
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -1,8 +1,9 @@
var storedAccess;
var storedLang;
var availLang = ['cs','de','en','es','fr','it','nl','pl','ro','sv','vi','ru','tr','zh-CN'];
var availLangText = ['Čeština', 'Deutsch', 'English', 'Español', 'Français', 'Italiano', 'Nederlands', 'Polski', 'Română', 'Svenska', 'Tiếng Việt', 'русский', 'Türkçe', '汉语'];
var availAccess = ['default','advanced','expert'];
var availLang = ['cs', 'de', 'en', 'es', 'fr', 'it', 'nl', 'nb', 'pl', 'pt', 'ro', 'sv', 'vi', 'ru', 'tr', 'zh-CN'];
var availLangText = ['Čeština', 'Deutsch', 'English', 'Español', 'Français', 'Italiano', 'Nederlands', 'Norsk Bokmål', 'Polski', 'Português', 'Română', 'Svenska', 'Tiếng Việt', 'русский', 'Türkçe', '汉语'];
var availAccess = ['default', 'advanced', 'expert'];
//$.i18n.debug = true;
//Change Password

135
assets/webconfig/js/ui_utils.js Normal file → Executable file
View File

@@ -183,25 +183,22 @@ function initLanguageSelection() {
langText = availLangText[langIdx];
}
}
$('#language-select').prop('title', langText);
$("#language-select").val(langIdx);
$("#language-select").selectpicker("refresh");
}
function updateUiOnInstance(inst) {
if (inst != 0) {
var currentURL = $(location).attr("href");
if (currentURL.indexOf('#conf_network') != -1 || currentURL.indexOf('#update') != -1 || currentURL.indexOf('#conf_webconfig') != -1 || currentURL.indexOf('#conf_grabber') != -1 || currentURL.indexOf('#conf_logging') != -1)
$("#hyperion_global_setting_notify").fadeIn("fast");
else
$("#hyperion_global_setting_notify").attr("style", "display:none");
$("#dashboard_active_instance_friendly_name").html($.i18n('dashboard_active_instance') + ': ' + window.serverInfo.instance[inst].friendly_name);
$("#dashboard_active_instance").removeAttr("style");
}
else {
$("#hyperion_global_setting_notify").fadeOut("fast");
$("#dashboard_active_instance").attr("style", "display:none");
$("#active_instance_friendly_name").text(window.serverInfo.instance[inst].friendly_name);
if (window.serverInfo.instance.filter(entry => entry.running).length > 1) {
$('#btn_hypinstanceswitch').toggle(true);
$('#active_instance_dropdown').prop('disabled', false);
$('#active_instance_dropdown').css('cursor', 'pointer');
} else {
$('#btn_hypinstanceswitch').toggle(false);
$('#active_instance_dropdown').prop('disabled', true);
$("#active_instance_dropdown").css('cursor', 'default');
}
}
@@ -259,17 +256,17 @@ function showInfoDialog(type, header, message) {
$('#id_footer').html('<button type="button" class="btn btn-danger" data-dismiss="modal">' + $.i18n('general_btn_ok') + '</button>');
}
else if (type == "select") {
$('#id_body').html('<img style="margin-bottom:20px" src="img/hyperion/hyperionlogo.png" alt="Redefine ambient light!">');
$('#id_body').html('<img style="margin-bottom:20px" id="id_logo" src="img/hyperion/logo_positiv.png" alt="Redefine ambient light!">');
$('#id_footer').html('<button type="button" id="id_btn_saveset" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_saveandreload') + '</button>');
$('#id_footer').append('<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
}
else if (type == "iswitch") {
$('#id_body').html('<img style="margin-bottom:20px" src="img/hyperion/hyperionlogo.png" alt="Redefine ambient light!">');
$('#id_body').html('<img style="margin-bottom:20px" id="id_logo" src="img/hyperion/logo_positiv.png" alt="Redefine ambient light!">');
$('#id_footer').html('<button type="button" id="id_btn_saveset" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-fw fa-exchange"></i>' + $.i18n('general_btn_iswitch') + '</button>');
$('#id_footer').append('<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
}
else if (type == "uilock") {
$('#id_body').html('<img src="img/hyperion/hyperionlogo.png" alt="Redefine ambient light!">');
$('#id_body').html('<img id="id_logo" src="img/hyperion/logo_positiv.png" alt="Redefine ambient light!">');
$('#id_footer').html('<b>' + $.i18n('InfoDialog_nowrite_foottext') + '</b>');
}
else if (type == "import") {
@@ -293,22 +290,22 @@ function showInfoDialog(type, header, message) {
$('#id_body_rename').html('<i style="margin-bottom:20px" class="fa fa-key modal-icon-edit"><br>');
$('#id_body_rename').append('<h4>' + header + '</h4>');
$('#id_body_rename').append('<input class="form-control" id="oldPw" placeholder="Old" type="text"> <br />');
$('#id_body_rename').append('<input class="form-control" id="newPw" placeholder="New" type="text">');
$('#id_body_rename').append('<input class="form-control" id="newPw" placeholder="New" type="password">');
$('#id_footer_rename').html('<button type="button" id="id_btn_ok" class="btn btn-success" data-dismiss-modal="#modal_dialog_rename" disabled><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_ok') + '</button>');
$('#id_footer_rename').append('<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
}
else if (type == "checklist") {
$('#id_body').html('<img style="margin-bottom:20px" src="img/hyperion/hyperionlogo.png" alt="Redefine ambient light!">');
$('#id_body').html('<img style="margin-bottom:20px" id="id_logo" src="img/hyperion/logo_positiv.png" alt="Redefine ambient light!">');
$('#id_body').append('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n('infoDialog_checklist_title') + '</h4>');
$('#id_body').append(header);
$('#id_footer').html('<button type="button" class="btn btn-primary" data-dismiss="modal">' + $.i18n('general_btn_ok') + '</button>');
}
else if (type == "newToken") {
$('#id_body').html('<img style="margin-bottom:20px" src="img/hyperion/hyperionlogo.png" alt="Redefine ambient light!">');
$('#id_body').html('<img style="margin-bottom:20px" id="id_logo" src="img/hyperion/logo_positiv.png" alt="Redefine ambient light!">');
$('#id_footer').html('<button type="button" class="btn btn-primary" data-dismiss="modal">' + $.i18n('general_btn_ok') + '</button>');
}
else if (type == "grantToken") {
$('#id_body').html('<img style="margin-bottom:20px" src="img/hyperion/hyperionlogo.png" alt="Redefine ambient light!">');
$('#id_body').html('<img style="margin-bottom:20px" id="id_logo" src="img/hyperion/logo_positiv.png" alt="Redefine ambient light!">');
$('#id_footer').html('<button type="button" class="btn btn-primary" data-dismiss="modal" id="tok_grant_acc">' + $.i18n('general_btn_grantAccess') + '</button>');
$('#id_footer').append('<button type="button" class="btn btn-danger" data-dismiss="modal" id="tok_deny_acc">' + $.i18n('general_btn_denyAccess') + '</button>');
}
@@ -321,6 +318,9 @@ function showInfoDialog(type, header, message) {
if (type == "select" || type == "iswitch")
$('#id_body').append('<select id="id_select" class="form-control" style="margin-top:10px;width:auto;"></select>');
if (getStorage("darkMode", false) == "on")
$('#id_logo').attr("src", 'img/hyperion/logo_negativ.png');
$(type == "renInst" || type == "changePassword" ? "#modal_dialog_rename" : "#modal_dialog").modal({
backdrop: "static",
keyboard: false,
@@ -329,7 +329,7 @@ function showInfoDialog(type, header, message) {
$(document).on('click', '[data-dismiss-modal]', function () {
var target = $(this).attr('data-dismiss-modal');
$.find(target).modal.hide();
$(target).modal('hide'); // lgtm [js/xss-through-dom]
});
}
@@ -807,14 +807,14 @@ function createRow(id) {
return el;
}
function createOptPanel(phicon, phead, bodyid, footerid) {
function createOptPanel(phicon, phead, bodyid, footerid, css) {
phead = '<i class="fa ' + phicon + ' fa-fw"></i>' + phead;
var pfooter = document.createElement('button');
pfooter.className = "btn btn-primary";
pfooter.setAttribute("id", footerid);
pfooter.innerHTML = '<i class="fa fa-fw fa-save"></i>' + $.i18n('general_button_savesettings');
return createPanel(phead, "", pfooter, "panel-default", bodyid);
return createPanel(phead, "", pfooter, "panel-default", bodyid, css);
}
function compareTwoValues(key1, key2, order = 'asc') {
@@ -871,7 +871,7 @@ function sortProperties(list) {
});
}
function createHelpTable(list, phead) {
function createHelpTable(list, phead, panelId) {
var table = document.createElement('table');
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
@@ -910,10 +910,10 @@ function createHelpTable(list, phead) {
table.appendChild(thead);
table.appendChild(tbody);
return createPanel(phead, table);
return createPanel(phead, table, undefined, undefined, undefined, undefined, panelId);
}
function createPanel(head, body, footer, type, bodyid) {
function createPanel(head, body, footer, type, bodyid, css, panelId) {
var cont = document.createElement('div');
var p = document.createElement('div');
var phead = document.createElement('div');
@@ -926,7 +926,11 @@ function createPanel(head, body, footer, type, bodyid) {
type = 'panel-default';
p.className = 'panel ' + type;
phead.className = 'panel-heading';
if (typeof panelId != 'undefined') {
p.setAttribute("id", panelId);
}
phead.className = 'panel-heading ' + css;
pbody.className = 'panel-body';
pfooter.className = 'panel-footer';
@@ -1069,6 +1073,43 @@ function getReleases(callback) {
});
}
function getSystemInfo() {
var sys = window.sysInfo.system;
var shy = window.sysInfo.hyperion;
var info = "Hyperion Server: \n";
info += '- Build: ' + shy.build + '\n';
info += '- Build time: ' + shy.time + '\n';
info += '- Git Remote: ' + shy.gitremote + '\n';
info += '- Version: ' + shy.version + '\n';
info += '- UI Lang: ' + storedLang + ' (BrowserLang: ' + navigator.language + ')\n';
info += '- UI Access: ' + storedAccess + '\n';
//info += '- Log lvl: ' + window.serverConfig.logger.level + '\n';
info += '- Avail Capt: ' + window.serverInfo.grabbers.available + '\n';
info += '- Database: ' + (shy.readOnlyMode ? "ready-only" : "read/write") + '\n';
info += '\n';
info += 'Hyperion Server OS: \n';
info += '- Distribution: ' + sys.prettyName + '\n';
info += '- Architecture: ' + sys.architecture + '\n';
if (sys.cpuModelName)
info += '- CPU Model: ' + sys.cpuModelName + '\n';
if (sys.cpuModelType)
info += '- CPU Type: ' + sys.cpuModelType + '\n';
if (sys.cpuRevision)
info += '- CPU Revision: ' + sys.cpuRevision + '\n';
if (sys.cpuHardware)
info += '- CPU Hardware: ' + sys.cpuHardware + '\n';
info += '- Kernel: ' + sys.kernelType + ' (' + sys.kernelVersion + ' (WS: ' + sys.wordSize + '))\n';
info += '- Qt Version: ' + sys.qtVersion + '\n';
info += '- Python Version: ' + sys.pyVersion + '\n';
info += '- Browser: ' + navigator.userAgent;
return info;
}
function handleDarkMode() {
$("<link/>", {
rel: "stylesheet",
@@ -1078,5 +1119,43 @@ function handleDarkMode() {
setStorage("darkMode", "on", false);
$('#btn_darkmode_icon').removeClass('fa fa-moon-o');
$('#btn_darkmode_icon').addClass('fa fa-sun-o');
$('#btn_darkmode_icon').addClass('mdi mdi-white-balance-sunny');
$('#navbar_brand_logo').attr("src", 'img/hyperion/logo_negativ.png');
}
function isAccessLevelCompliant(accessLevel) {
var isOK = true;
if (accessLevel) {
if (accessLevel === 'system') {
isOK = false;
}
else if (accessLevel === 'advanced' && storedAccess === 'default') {
isOK = false;
}
else if (accessLevel === 'expert' && storedAccess !== 'expert') {
isOK = false;
}
}
return isOK
}
function showInputOptions(path, elements, state) {
for (var i = 0; i < elements.length; i++) {
$('[data-schemapath="' + path + '.' + elements[i] + '"]').toggle(state);
}
}
function showInputOptionsForKey(editor, item, showForKey, state) {
var elements = [];
for (var key in editor.schema.properties[item].properties) {
if (showForKey !== key) {
var accessLevel = editor.schema.properties[item].properties[key].access;
//Always disable all elements, but only enable elements, if access level compliant
if (!state || isAccessLevelCompliant(accessLevel)) {
elements.push(key);
}
}
}
showInputOptions("root." + item, elements, state);
}

456
assets/webconfig/js/wizard.js Normal file → Executable file
View File

@@ -53,6 +53,9 @@ function startWizardRGB() {
$('#wizp2_body').append('<table class="table borderless" style="width:200px"><tbody><tr><td class="ltd"><label>' + $.i18n('wiz_rgb_qrend') + '</label></td><td class="itd"><select id="wiz_r_select" class="form-control wselect"></select></td></tr><tr><td class="ltd"><label>' + $.i18n('wiz_rgb_qgend') + '</label></td><td class="itd"><select id="wiz_g_select" class="form-control wselect"></select></td></tr></tbody></table>');
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_save') + '</button><button type="button" class="btn btn-primary" id="btn_wiz_checkok" style="display:none" data-dismiss="modal"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_ok') + '</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
@@ -424,11 +427,14 @@ function startWizardCC() {
}
//create html
$('#wiz_header').html('<i class="fa fa-magic fa-fw"></i>' + $.i18n('wiz_cc_title'));
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n('wiz_cc_title') + '</h4><p>' + $.i18n('wiz_cc_intro1') + '</p><label>' + $.i18n('wiz_cc_kwebs') + '</label><input class="form-control" style="width:170px;margin:auto" id="wiz_cc_kodiip" type="text" placeholder="' + kodiAddress + '" value="' + kodiAddress + '" /><span id="kodi_status"></span><span id="multi_cali"></span>');
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n('wiz_cc_title') + '</h4><p>' + $.i18n('wiz_cc_intro1') + '</p><label>' + $.i18n('wiz_cc_kwebs') + '</label><input class="form-control" style="width:170px;margin:auto" id="wiz_cc_kodiip" type="text" placeholder="' + kodiAddress + '" value="' + kodiAddress + '" /><span id="kodi_status"></span><span id="multi_cali"></span>');
$('#wizp1_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_cont" disabled="disabled"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_continue') + '</button><button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
$('#wizp2_body').html('<div id="wiz_cc_desc" style="font-weight:bold"></div><div id="editor_container_wiz"></div>');
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_back"><i class="fa fa-fw fa-chevron-left"></i>' + $.i18n('general_btn_back') + '</button><button type="button" class="btn btn-primary" id="btn_wiz_next">' + $.i18n('general_btn_next') + '<i style="margin-left:4px;"class="fa fa-fw fa-chevron-right"></i></button><button type="button" class="btn btn-warning" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_save') + '</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
@@ -437,10 +443,9 @@ function startWizardCC() {
});
$('#wiz_cc_kodiip').off().on('change', function () {
kodiAddress = $(this).val().trim();
$('#wizp1_body').find("kodiAddress").val(kodiAddress);
$('#kodi_status').html('');
// Remove Kodi's default Web-Socket port (9090) from display and ensure Kodi's default REST-API port (8080) is mapped to web-socket port to ease migration
@@ -670,6 +675,9 @@ function startWizardPhilipsHue(e) {
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_save') + '</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
$('#wizp3_body').html('<span>' + $.i18n('wiz_hue_press_link') + '</span> <br /><br /><center><span id="connectionTime"></span><br /><i class="fa fa-cog fa-spin" style="font-size:100px"></i></center>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
@@ -788,8 +796,6 @@ async function discover_hue_bridges() {
const r = res.info;
// Process devices returned by discovery
console.log(r);
if (r.devices.length == 0)
$('#wiz_hue_ipstate').html($.i18n('wiz_hue_failure_ip'));
else {
@@ -832,11 +838,11 @@ async function identify_hue_device(hostAddress, username, id) {
$('#btn_wiz_save').attr('disabled', true);
let params = { host: hostAddress, user: username, lightId: id };
const res = await requestLedDeviceIdentification('philipshue', params);
await requestLedDeviceIdentification('philipshue', params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
$('#btn_wiz_save').attr('disabled', false);
}
}
function getHueIPs() {
@@ -1187,7 +1193,6 @@ function get_hue_lights() {
}
(cC == 0 || window.readOnlyMode) ? $('#btn_wiz_save').attr("disabled", true) : $('#btn_wiz_save').attr("disabled", false);
});
}
$('.hue_sel_watch').trigger('change');
@@ -1208,108 +1213,6 @@ function abortConnection(UserInterval) {
$("#wiz_hue_usrstate").html($.i18n('wiz_hue_failure_connection'));
}
//****************************
// Wizard WLED
//****************************
var lights = null;
function startWizardWLED(e) {
//create html
var wled_title = 'wiz_wled_title';
var wled_intro1 = 'wiz_wled_intro1';
$('#wiz_header').html('<i class="fa fa-magic fa-fw"></i>' + $.i18n(wled_title));
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n(wled_title) + '</h4><p>' + $.i18n(wled_intro1) + '</p>');
$('#wizp1_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_cont"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_continue') + '</button><button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
/*$('#wizp2_body').html('<div id="wh_topcontainer"></div>');
$('#wh_topcontainer').append('<div class="form-group" id="usrcont" style="display:none"></div>');
$('#wizp2_body').append('<div id="hue_ids_t" style="display:none"><p style="font-weight:bold" id="hue_id_headline">'+$.i18n('wiz_wled_desc2')+'</p></div>');
createTable("lidsh", "lidsb", "hue_ids_t");
$('.lidsh').append(createTableRow([$.i18n('edt_dev_spec_lights_title'),$.i18n('wiz_pos'),$.i18n('wiz_identify')], true));
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>'+$.i18n('general_btn_save')+'</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'+$.i18n('general_btn_cancel')+'</button>');
*/
//open modal
$("#wizard_modal").modal({
backdrop: "static",
keyboard: false,
show: true
});
//listen for continue
$('#btn_wiz_cont').off().on('click', function () {
/* For testing only
discover_wled();
var hostAddress = conf_editor.getEditor("root.specificOptions.host").getValue();
if(hostAddress != "")
{
getProperties_wled(hostAddress,"info");
identify_wled(hostAddress)
}
For testing only */
});
}
async function discover_wled() {
const res = await requestLedDeviceDiscovery('wled');
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process devices returned by discovery
console.log(r);
if (r.devices.length == 0)
$('#wiz_hue_ipstate').html($.i18n('wiz_hue_failure_ip'));
else {
for (const device of r.devices) {
console.log("Device:", device);
var ip = device.hostname + ":" + device.port;
console.log("Host:", ip);
//wledIPs.push({internalipaddress : ip});
}
}
}
}
async function getProperties_wled(hostAddress, resourceFilter) {
let params = { host: hostAddress, filter: resourceFilter };
const res = await requestLedDeviceProperties('wled', params);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process properties returned
console.log(r);
}
}
async function identify_wled(hostAddress) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { host: hostAddress };
const res = await requestLedDeviceIdentification('wled', params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}
//****************************
// Wizard Yeelight
//****************************
@@ -1339,6 +1242,9 @@ function startWizardYeelight(e) {
+ $.i18n('general_btn_save') + '</button><buttowindow.serverConfig.device = d;n type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'
+ $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({ backdrop: "static", keyboard: false, show: true });
@@ -1438,8 +1344,17 @@ async function discover_yeelight_lights() {
var light = {};
light.host = device.hostname;
light.port = device.port;
light.name = device.other.name;
light.model = device.other.model;
if (device.txt) {
light.name = device.name;
light.model = device.txt.md;
//Yeelight does not provide correct API port with mDNS response, use default one
light.port = 55443;
}
else {
light.name = device.other.name;
light.model = device.other.model;
}
lights.push(light);
}
}
@@ -1469,7 +1384,8 @@ async function discover_yeelight_lights() {
}
function assign_yeelight_lights() {
var models = ['color', 'color1', 'color2', 'color4', 'stripe', 'strip1'];
// Model mappings, see https://www.home-assistant.io/integrations/yeelight/
var models = ['color', 'color1', 'YLDP02YL', 'YLDP02YL', 'color2', 'YLDP06YL', 'color4', 'YLDP13YL', 'stripe', 'YLDD04YL', 'strip1', 'YLDD01YL', 'YLDD02YL'];
// If records are left for configuration
if (Object.keys(lights).length > 0) {
@@ -1534,7 +1450,7 @@ function assign_yeelight_lights() {
$('.yee_sel_watch').trigger('change');
}
else {
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights','Yeelights') + '</p>';
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights', 'Yeelights') + '</p>';
$('#wizp2_body').append(noLightsTxt);
}
}
@@ -1555,15 +1471,14 @@ async function getProperties_yeelight(hostname, port) {
}
async function identify_yeelight_device(hostname, port) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { hostname: hostname, port: port };
const res = await requestLedDeviceIdentification("yeelight", params);
await requestLedDeviceIdentification("yeelight", params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
$('#btn_wiz_save').attr('disabled', false);
}
}
@@ -1596,6 +1511,9 @@ function startWizardAtmoOrb(e) {
+ $.i18n('general_btn_save') + '</button><buttowindow.serverConfig.device = d;n type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'
+ $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({ backdrop: "static", keyboard: false, show: true });
@@ -1675,14 +1593,12 @@ async function discover_atmoorb_lights(multiCastGroup, multiCastPort) {
var light = {};
var params = {};
if (multiCastGroup !== "")
{
if (multiCastGroup !== "") {
params.multiCastGroup = multiCastGroup;
}
if (multiCastPort !== 0)
{
params.multiCastPort = multiCastPort;
if (multiCastPort !== 0) {
params.multiCastPort = multiCastPort;
}
// Get discovered lights
@@ -1692,7 +1608,7 @@ async function discover_atmoorb_lights(multiCastGroup, multiCastPort) {
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info;
// Process devices returned by discovery
for (const device of r.devices) {
if (device.id !== "") {
@@ -1774,7 +1690,7 @@ function assign_atmoorb_lights() {
$('.lidsb').append(createTableRow([orbId + lightAnnotation, '<select id="orb_' + lightid + '" ' + enabled + ' class="orb_sel_watch form-control">'
+ options
+ '</select>', '<button class="btn btn-sm btn-primary" ' + enabled + ' onClick=identify_atmoorb_device(' + orbId + ')>'
+ '</select>', '<button class="btn btn-sm btn-primary" ' + enabled + ' onClick=identify_atmoorb_device("' + orbId + '")>'
+ $.i18n('wiz_identify_light', orbId) + '</button>']));
}
@@ -1793,303 +1709,19 @@ function assign_atmoorb_lights() {
$('.orb_sel_watch').trigger('change');
}
else {
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights','AtmoOrbs') + '</p>';
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights', 'AtmoOrbs') + '</p>';
$('#wizp2_body').append(noLightsTxt);
}
}
async function identify_atmoorb_device(orbId) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { id: orbId };
const res = await requestLedDeviceIdentification("atmoorb", params);
await requestLedDeviceIdentification("atmoorb", params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}
//****************************
// Wizard/Routines Nanoleaf
//****************************
async function discover_nanoleaf() {
const res = await requestLedDeviceDiscovery('nanoleaf');
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process devices returned by discovery
console.log(r);
if (r.devices.length == 0)
$('#wiz_hue_ipstate').html($.i18n('wiz_hue_failure_ip'));
else {
for (const device of r.devices) {
console.log("Device:", device);
var ip = device.hostname + ":" + device.port;
console.log("Host:", ip);
//nanoleafIPs.push({internalipaddress : ip});
}
}
}
}
async function getProperties_nanoleaf(hostAddress, authToken, resourceFilter) {
let params = { host: hostAddress, token: authToken, filter: resourceFilter };
const res = await requestLedDeviceProperties('nanoleaf', params);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process properties returned
console.log(r);
}
}
async function identify_nanoleaf(hostAddress, authToken) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { host: hostAddress, token: authToken };
const res = await requestLedDeviceIdentification('nanoleaf', params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}
//****************************
// Wizard Cololight
//****************************
var lights = null;
var selectedLightId = null;
function startWizardCololight(e) {
//create html
var cololight_title = 'wiz_cololight_title';
var cololight_intro1 = 'wiz_cololight_intro1';
$('#wiz_header').html('<i class="fa fa-magic fa-fw"></i>' + $.i18n(cololight_title));
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n(cololight_title) + '</h4><p>' + $.i18n(cololight_intro1) + '</p>');
$('#wizp1_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_cont"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_continue') + '</button><button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
$('#wizp2_body').html('<div id="wh_topcontainer"></div>');
$('#wh_topcontainer').append('<div class="form-group" id="usrcont" style="display:none"></div>');
$('#wizp2_body').append('<div id="colo_ids_t" style="display:none"><p style="font-weight:bold" id="colo_id_headline">' + $.i18n('wiz_cololight_desc2') + '</p></div>');
createTable("lidsh", "lidsb", "colo_ids_t");
$('.lidsh').append(createTableRow([$.i18n('edt_dev_spec_lights_title'), $.i18n('wiz_identify')], true));
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>'
+ $.i18n('general_btn_save') + '</button><buttowindow.serverConfig.device = d;n type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'
+ $.i18n('general_btn_cancel') + '</button>');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
keyboard: false,
show: true
});
//listen for continue
$('#btn_wiz_cont').off().on('click', function () {
beginWizardCololight();
$('#wizp1').toggle(false);
$('#wizp2').toggle(true);
});
}
function beginWizardCololight() {
lights = [];
discover_cololights();
$('#btn_wiz_save').off().on("click", function () {
//LED device config
//Start with a clean configuration
var d = {};
d.type = 'cololight';
//Cololight does not resolve into stable hostnames (as devices named the same), therefore use IP
if (!lights[selectedLightId].ip) {
d.host = lights[selectedLightId].host;
} else {
d.host = lights[selectedLightId].ip;
}
var coloLightProperties = lights[selectedLightId].props.properties;
if (Object.keys(coloLightProperties).length === 0) {
alert($.i18n('wiz_cololight_noprops'));
d.hardwareLedCount = 1;
}
else {
d.hardwareLedCount = coloLightProperties.ledCount;
}
d.colorOrder = conf_editor.getEditor("root.generalOptions.colorOrder").getValue();
d.latchTime = parseInt(conf_editor.getEditor("root.specificOptions.latchTime").getValue());;
window.serverConfig.device = d;
//LED layout - have initial layout prepared matching the LED-count
var coloLightLedConfig = [];
if (coloLightProperties.modelType === "Strip") {
coloLightLedConfig = createClassicLedLayoutSimple(d.hardwareLedCount / 2, d.hardwareLedCount / 4, d.hardwareLedCount / 4, 0, d.hardwareLedCount / 4 * 3, false);
} else {
coloLightLedConfig = createClassicLedLayoutSimple(0, 0, 0, d.hardwareLedCount, 0, true);
}
window.serverConfig.leds = coloLightLedConfig;
//smoothing off
window.serverConfig.smoothing.enable = false;
requestWriteConfig(window.serverConfig, true);
resetWizard();
});
$('#btn_wiz_abort').off().on('click', resetWizard);
}
async function discover_cololights() {
const res = await requestLedDeviceDiscovery('cololight');
if (res && !res.error) {
const r = res.info;
// Process devices returned by discovery
for (const device of r.devices) {
if (device.ip !== "") {
if (getIpInLights(device.ip).length === 0) {
var light = {};
light.ip = device.ip;
light.host = device.hostname;
light.name = device.name;
light.type = device.type;
lights.push(light);
}
}
}
assign_cololight_lights();
}
}
function assign_cololight_lights() {
// If records are left for configuration
if (Object.keys(lights).length > 0) {
$('#wh_topcontainer').toggle(false);
$('#colo_ids_t, #btn_wiz_save').toggle(true);
$('.lidsb').html("");
var options = "";
for (var lightid in lights) {
lights[lightid].id = lightid;
var lightHostname = lights[lightid].host;
var lightIP = lights[lightid].ip;
var val = lightHostname + " (" + lightIP + ")";
options += '<option value="' + lightid + '">' + val + '</option>';
}
var enabled = 'enabled';
$('.lidsb').append(createTableRow(['<select id="colo_select_id" ' + enabled + ' class="colo_sel_watch form-control">'
+ options
+ '</select>', '<button id="wiz_identify_btn" class="btn btn-sm btn-primary">'
+ $.i18n('wiz_identify') + '</button>']));
$('.colo_sel_watch').bind("change", function () {
selectedLightId = $('#colo_select_id').val();
var lightIP = lights[selectedLightId].ip;
$('#wiz_identify_btn').unbind().bind('click', function (event) { identify_cololight_device(lightIP); });
if (!lights[selectedLightId].props) {
getProperties_cololight(lightIP);
}
});
$('.colo_sel_watch').trigger('change');
}
else {
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights','Cololights') + '</p>';
$('#wizp2_body').append(noLightsTxt);
}
}
async function getProperties_cololight(ip) {
let params = { host: ip };
const res = await requestLedDeviceProperties('cololight', params);
if (res && !res.error) {
var coloLightProperties = res.info;
//Store properties along light with given IP-address
var id = getIpInLights(ip)[0].id;
lights[id].props = coloLightProperties;
}
}
async function identify_cololight_device(hostAddress) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { host: hostAddress };
const res = await requestLedDeviceIdentification('cololight', params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}
//****************************
// Wizard/Routines RS232-Devices
//****************************
async function discover_providerRs232(rs232Type) {
const res = await requestLedDeviceDiscovery(rs232Type);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process serialPorts returned by discover
console.log(r);
}
}
//****************************
// Wizard/Routines HID (USB)-Devices
//****************************
async function discover_providerHid(hidType) {
const res = await requestLedDeviceDiscovery(hidType);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process HID returned by discover
console.log(r);
$('#btn_wiz_save').attr('disabled', false);
}
}