code stringlengths 2 1.05M |
|---|
'use strict';
const Cashy = require('../../index.js');
module.exports = (program) => program
.command('dropAccount <account_id>')
.description('closes stated account')
.action(dropAccount);
function dropAccount (id, opts) {
Cashy({
create: false,
file: opts.parent.file
}).getAccounts({ id: id }).then((accounts) => {
if (!accounts.length) {
return Promise.reject(
new Error(`Account ${id} not found`)
);
}
return accounts[0].delete();
}).catch((e) => {
console.error(e.message);
process.exit(1);
});
}
|
(function($){
$.suggest = function(term){
if($.suggest.timer) {
clearTimeout($.suggest.timer);}
list = [];
reg = new RegExp('^'+term,'i');
for(i=0,j=terms.length;i<j;i++){
if(reg.exec(terms[i])) list.push(terms[i]);}
o="<ul>";
for(i=0,j=list.length;i<j;i++){
o+='<li>'+list[i]+'</li>';}
$('#suggest').html(o+'</ul>');
$('#suggest ul li:first').addClass('selected');
$('#suggest').show();
$('#suggest li').mouseover(function(){
$('#suggest li.selected').removeClass('selected');
$(this).addClass('selected');
})
$('#suggest li').click(function(){
$('#suggest').hide();
$('#suggest').html('');
});
$.suggest.timer = setTimeout(function(){select_rest();},$.suggest.timeout);
}
$.suggest.timeout = 300;
function select_rest(){
var len=$.suggest.input.value.length;
if($.suggest.suggestions.firstChild && $.suggest.suggestions.firstChild.firstChild){
$.suggest.input.value=$.suggest.suggestions.firstChild.firstChild.firstChild.nodeValue;
if($.suggest.input.createTextRange){
var oRange = $.suggest.input.createTextRange();
oRange.moveStart("character", len);
oRange.moveEnd("character", $.suggest.input.value.length);
oRange.select();
$.suggest.input.focus();
}
else{
$.suggest.input.setSelectionRange(len,$.suggest.input.value.length);
}
}
}
$(function(){
$('#searchInput').keyup(function(oEvent){
var iKeyCode = oEvent.keyCode;
if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
switch (iKeyCode){
case 40: //down
var obj=$('#suggest .selected').get(0);
if(obj.nextSibling){
$(obj.nextSibling).addClass('selected');
$(obj).removeClass('selected');
this.value=obj.nextSibling.firstChild.nodeValue;}
break;
case 38: //up
var obj=$('#suggest .selected').get(0);
if(obj.previousSibling){
$(obj.previousSibling).addClass('selected');
$(obj).removeClass('selected');
this.value=obj.previousSibling.firstChild.nodeValue;}
break;
case 8: //backspace
if(this.value){$.suggest(this.value);}
else{$('#suggest').hide();}
break;
case 46: //delete
if(this.value){$.suggest(this.value);}
else{$('#suggest').hide();}
break;
case 13: //enter
actSearch=this.value;
$('#suggest').hide();
$('#suggest').html('');
$('#searchInput').get(0).value=$('#searchInput').get(0).value;
document.location.href='#'+getId(this.value);
break;
case 27: //esc
$('#suggest').hide();
$('#suggest').html('');
break;
}
}
else{
if(this.value && this.value!=' '){
$.suggest(this.value);}
else{$('#suggest').hide();}}
});
$('input').blur(function(){setTimeout("$('#suggest').hide();",200)});
$.suggest.suggestions=$('#suggest')[0];
$.suggest.input=$('#searchInput')[0];
});
})(jQuery); |
'use strict';
import React, { Component } from 'react';
import {
ActivityIndicator,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View
} from 'react-native';
import Register from './Register';
import styles from '../style/FormStyles';
export default class Login extends Component {
constructor(props) {
super(props);
this.socket = this.props.socket;
this.state = {
uname: '',
pass: '',
loggedIn: false,
isLoading: false,
message: ''
};
}
updateUserData(resp) {
if (typeof(resp) !== 'object') {
this.setState({
message: 'Wrong username or password',
uname: '', pass: '',
isLoading: false
});
} else {
this.setState({
loggedIn: true, isLoading: false,
userData: resp
})
};
}
onLogin() {
this.setState({ isLoading: true });
this.socket.emit('login', {username: this.state.uname, password: this.state.pass});
this.socket.on('login_resp', this.updateUserData.bind(this));
}
justLoggedIn(userData) {
this.setState({ loggedIn: true, userData: userData, isLoading: false});
}
componentDidUpdate(prevProps, prevState) {
if (this.state.loggedIn)
this.props.justLoggedIn(this.state.userData);
}
onRegister() {
this.props.navigator.push({
title: 'Register',
component: Register,
passProps: {
socket: this.socket,
justLoggedIn: this.justLoggedIn.bind(this)
}
});
}
onUsernameChanged(ev) {
this.setState({ uname: ev.nativeEvent.text });
}
onPasswordChanged(ev) {
this.setState({ pass: ev.nativeEvent.text });
}
render() {
const pie = (
this.state.isLoading ?
<ActivityIndicator
style={styles.loading}
size='large'/> :
<View/>
);
return (
<View style={styles.container}>
<TextInput
style={styles.textInput}
value={this.state.uname}
onChange={this.onUsernameChanged.bind(this)}
underlineColorAndroid={'transparent'}
placeholder='Username'/>
<TextInput
secureTextEntry={true}
style={styles.textInput}
value={this.state.pass}
onChange={this.onPasswordChanged.bind(this)}
underlineColorAndroid={'transparent'}
placeholder='Password'/>
<TouchableHighlight style={styles.button}
onPress={this.onLogin.bind(this)}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Login</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.button}
onPress={this.onRegister.bind(this)}
underlayColor='#1219FF'>
<Text style={styles.buttonText}>Register</Text>
</TouchableHighlight>
{pie}
<Text style={styles.description}>{this.state.message}</Text>
</View>
);
}
} |
// Main vuex store
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import intro from './modules/intro'
import weeks from './modules/weeks'
import switches from './modules/switches'
import models from './modules/models'
import scores from './modules/scores'
import * as types from './mutation-types'
import configYaml from 'json!yaml!../../config.yaml'
Vue.use(Vuex)
const state = {
// D3 plot objects
timeChart: null,
choropleth: null,
distributionChart: null,
seasonData: [], // Container for season data
scoresData: [], // Container for score data
distData: [], // Container for dist data
history: null,
metadata: null,
seasonDataUrls: null,
scoresDataUrls: null,
distDataUrls: null,
branding: Object.assign({logo: ''}, configYaml.branding)
}
// mutations
const mutations = {
[types.ADD_SEASON_DATA] (state, val) {
state.seasonData.push(val)
// TODO: Remove data if short on memory
},
[types.ADD_SCORES_DATA] (state, val) {
state.scoresData.push(val)
// TODO: Remove data if short on memory
},
[types.ADD_DIST_DATA] (state, val) {
state.distData.push(val)
// TODO: Remove data if short on memory
},
[types.SET_SEASON_DATA_URLS] (state, val) {
state.seasonDataUrls = val
},
[types.SET_SCORES_DATA_URLS] (state, val) {
state.scoresDataUrls = val
},
[types.SET_DIST_DATA_URLS] (state, val) {
state.distDataUrls = val
},
[types.SET_HISTORY] (state, val) {
state.history = val
},
[types.SET_METADATA] (state, val) {
state.metadata = val
},
[types.SET_TIMECHART] (state, val) {
state.timeChart = val
},
[types.SET_CHOROPLETH] (state, val) {
state.choropleth = val
},
[types.SET_DISTRIBUTIONCHART] (state, val) {
state.distributionChart = val
},
[types.SET_BRAND_LOGO] (state, val) {
state.branding.logo = val
}
}
export default new Vuex.Store({
state,
actions,
getters,
mutations,
modules: {
intro,
weeks,
switches,
models,
scores
}
})
|
'use strict';
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "etsy"); |
Ext.define('Packt.model.sakila.Sakila', {
extend: 'Ext.data.Model',
fields: [
{
name: 'last_update',
type: 'date',
dateFormat: 'Y-m-j H:i:s'
}
]
}); |
var five = require("johnny-five");
module.exports = ShiftSeven;
var numbers = {
0: "11111100",
1: "01100000",
2: "11011010",
3: "11110010",
4: "01100110",
5: "10110110",
6: "10111110",
7: "11100000",
8: "11111110",
9: "11110110",
};
// Right-pad `string` with `char`
function pad(string, length, char) {
while (string.length < length) {
string = char + string;
}
return string;
}
function ShiftSeven(options) {
this.register = new five.ShiftRegister(options);
}
ShiftSeven.prototype.draw = function(number) {
this.write(numbers[number]);
};
ShiftSeven.prototype.write = function(value) {
// Convert numbers to 8-bit binary strings
if (typeof value === "number") {
value = pad(value.toString(2), 8, "0");
}
// Reverse the binary string so the shit register gets the values
// in the correct order
value = value.split("").reverse().join("");
value = parseInt(value, 2);
this.register.send(value);
};
ShiftSeven.prototype.off = function() {
this.write(0);
};
ShiftSeven.Multi = function(options) {
this.leadingZeros = options.leadingZeros || false;
this.displays = options.displays.map(function(displayOptions) {
return new ShiftSeven(displayOptions);
});
};
ShiftSeven.Multi.prototype.draw = function(value) {
value = pad(value.toString(), this.displays.length, this.leadingZeros ? "0" : " ");
value.split("").forEach(function(value, index) {
if (value === " ") {
this.displays[index].off();
} else {
this.displays[index].draw(value);
}
}, this);
};
ShiftSeven.Multi.prototype.off = function() {
this.displays.forEach(function(display) {
display.off();
});
};
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', '$state', 'Authentication',
function($scope, $state, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
if ($scope.authentication.user) $state.go('main');
}
]);
|
($ || jQuery || django.jQuery)(function($) {
var DATA_BOUND_FIELDS = 'data-dynamic-choices-bound-fields',
DATA_FORMSET = 'data-dynamic-choices-formset';
var error = (function() {
if ('console' in window && $.isFunction(console.error))
return function(e) {
console.error(e);
};
else return function(e) {
throw new Error(e);
};
})();
function getFieldNames(fields) {
return fields.map(function(index, field) {
return field.name;
}).toArray();
}
$.fn.updateFields = function(url, form) {
var handlers = $.fn.updateFields.widgetHandlers;
if (this.length) {
form = $(form ? form : this[0].form);
var fields = $(this).addClass('loading'),
data = $(form).serializeArray(),
boundFields = [];
// Make sure fields bound to these ones are updated right after
fields.each(function(i, field) {
var selector = $(field).attr(DATA_BOUND_FIELDS);
if (selector) boundFields.push(selector);
var formset = $(field).closest('[' + DATA_FORMSET + ']').attr(DATA_FORMSET);
if (formset) boundFields.push($.fn.bindFieldset.formsetsBindings[formset](field));
});
fields.addClass('loading');
data.push({
name: 'DYNAMIC_CHOICES_FIELDS',
value: getFieldNames(fields).join(',')
});
$.getJSON(url, $.param(data), function(json) {
fields.each(function(index, field) {
if (field.name in json) {
var data = json[field.name];
if (data.widget in handlers) {
handlers[data.widget](field, data.value);
$(field).trigger('change', {
'triggeredByDynamicChoices': true
});
} else error('Missing handler for "' + data.widget + '" widget.');
}
$(field).removeClass('loading');
});
$(boundFields.join(', ')).updateFields(url, form);
});
}
return this;
};
function assignOptions(element, options) {
$(options).each(function(index, option) {
if ($.isArray(option[1])) {
var optGroup = $('<optgroup></optgroup>').attr({
label: option[0]
});
assignOptions(optGroup, option[1]);
element.append(optGroup);
} else {
element.append($('<option></option>').attr({
value: option[0]
}).html(option[1]));
}
});
}
function selectWidgetHandler(select, options) {
select = $(select);
var value = select.val();
select.empty();
assignOptions(select, options);
select.val(value);
}
$.fn.updateFields.widgetHandlers = {
'default': selectWidgetHandler
};
$.fn.bindFields = function(url, fields) {
var handlers = $.fn.bindFields.widgetHandlers;
return this.each(function(index, field) {
$(field).change(function(event, data) {
if (data && 'triggeredByDynamicChoices' in data) return;
$(fields).updateFields(url, field.form);
}).attr(DATA_BOUND_FIELDS, fields);
});
};
function defaultFieldNameExtractor(fieldset, field) {
var match = field.match(/^([\w_]+)-(\w+)-([\w_]+)$/);
if (match && match[1] == fieldset) {
return {
index: match[2],
name: match[3]
};
} else error('Can\'t resolve field "' + field + '" of specified fieldset "' + fieldset + '".');
}
function defaultFieldSelectorBuilder(fieldset, field, index) {
return '#id_' + fieldset + '-' + index + '-' + field;
}
function curryBuilder(fieldset, index, builder) {
return function(i, field) {
return builder(fieldset, field, index);
};
}
function formsetFieldBoundFields(fieldset, field, fields, extractor, builder) {
field = extractor(fieldset, field.name);
if (field.name in fields) {
var selectors = $(fields[field.name]).map(curryBuilder(fieldset, field.index, builder));
return selectors.toArray().join(', ');
} else return '';
}
$.fn.bindFieldset = function(url, fieldset, fields, extractor, builder) {
extractor = $.isFunction(extractor) ? extractor : defaultFieldNameExtractor;
builder = $.isFunction(builder) ? builder : defaultFieldSelectorBuilder;
$.fn.bindFieldset.formsetsBindings[fieldset] = function(field) {
return formsetFieldBoundFields(fieldset, field, fields, extractor, builder);
};
return this.each(function(index, container) {
$(container).change(function(event, data) {
if (data && 'triggeredByDynamicChoices' in data) return;
var target = event.target,
selectors = formsetFieldBoundFields(fieldset, target, fields, extractor, builder);
$(selectors).updateFields(url, target.form);
}).attr(DATA_FORMSET, fieldset);
});
};
$.fn.bindFieldset.formsetsBindings = {};
}); |
define([
'shared',
'./controllers/DashboardController',
'./views/ContentView',
'./views/DashboardView'
], function (
shared, DashboardController, ContentView, DashboardView
) {
'use strict';
return shared.application.Module.extend({
contentView: ContentView,
navigate: function () {
this.view.setNavigationVisibility(false);
this.Controller = new DashboardController({});
this.moduleRegion.show(this.Controller.dashboardView);
}
});
}); |
const SolverAbstract = require('./solver_abstract');
class ReconsiderationWorkProcess extends SolverAbstract {
static checkSolved () {
throw new Error('must be implemented');
}
static get title () {
return '作業手順の見直し';
}
static get description () {
return '作業手順を見なおして合意を得ましょう。';
}
}
module.exports = ReconsiderationWorkProcess;
|
/*
* Boardfarm Management application
* Copyright (c) 2016 Heiko Stuebner <heiko@sntech.de>
*
* License:
* MIT: https://opensource.org/licenses/MIT
* See the LICENSE file in the project's top-level directory for details.
*/
var qx = require("qooxdoo");
require('./source/class/sn/boardfarm/backend/Backend');
/* Create and run backend instance.
* Run with
* nodejs boardfarm-backend.js
*/
var backend = new sn.boardfarm.backend.Backend();
backend.main();
|
/**
* Created by mjbrooks on 3/14/14.
*/
(function (win) {
var models = win.namespace.get('thermometer.models');
var utils = win.namespace.get('thermometer.utils');
var libs = win.namespace.get('libs');
//For the moving average
var window_sizes = [9];
models.TweetGroup = libs.Backbone.Model.extend({
idAttribute: "feeling_id",
defaults: function () {
return {
recent_series: [],
examples: []
};
},
parse: function (raw) {
//Tasks:
// Compute percent change
// Convert to Date
// Calculate a smoothed value
// If there are examples, copy the smoothed percent change onto them
var normal = raw.normal;
if (raw.recent_series.length &&
_.has(raw.recent_series[0], 'percent')) {
//Toss all the incomplete points
raw.recent_series = _.filter(raw.recent_series, function(point) {
return !point.missing_data
});
var percent_smoothed = undefined;
_.each(window_sizes, function(window_size) {
if (percent_smoothed) {
percent_smoothed = utils.moving_average(window_size, percent_smoothed);
} else {
percent_smoothed = utils.moving_average(window_size, raw.recent_series, function(d) {
return d.percent;
});
}
});
_.each(raw.recent_series, function (point, i) {
point.start_time = utils.date_parse(point.start_time);
if ('percent' in point) {
point.percent_change = (point.percent - normal) / normal;
point.percent_smoothed = percent_smoothed[i];
point.percent_change_smoothed = (point.percent_smoothed - normal) / normal;
}
});
if (raw.examples) {
var point_index = _.indexBy(raw.recent_series, 'frame_id');
_.each(raw.examples, function(example) {
var point = point_index[example.frame_id];
example.percent_change_smoothed = point.percent_change_smoothed;
example.start_time = point.start_time;
example.created_at = utils.date_parse(example.created_at);
example.word = raw.word;
});
}
}
return raw;
},
toggle_selected: function() {
if (this.collection) {
if (this.is_selected()) {
this.collection.selected_group = undefined
} else {
if (this.collection.selected_group) {
var old_selection = this.collection.selected_group;
this.collection.selected_group = this;
old_selection.trigger('change');
} else {
this.collection.selected_group = this;
}
}
this.trigger('change');
}
},
is_selected: function() {
if (this.collection) {
return this.collection.selected_group == this;
}
return false;
}
});
models.TweetGroupCollection = libs.Backbone.Collection.extend({
model: models.TweetGroup,
set: function() {
//Call through to parent
libs.Backbone.Collection.prototype.set.apply(this, arguments);
//Just send one change event
this.trigger('change');
}
});
})(window); |
version https://git-lfs.github.com/spec/v1
oid sha256:78290fc804412a6cefe17ed43dfa8a6d8c6ec9ebebe20802c4110f19a3b36e14
size 10385
|
/* jshint strict: false, undef: true, unused: true */
// Dom based routing
// ------------------
// Based on Paul Irish' code, please read blogpost
// http://www.paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution///
// Does 2 jobs:
// * Page dependend execution of functions
// * Gives a more fine-grained control in which order stuff is executed
//
// Adding a page dependend function:
// 1. add class to body <body class="superPage">
// 2. add functions to the IFSLoader object IFSLoader = { superPage : init : function() {}};
//
// For now this will suffice, if complexity increases we might look at a more complex loader like requireJs.
// Please think before adding javascript, this project should work without any of this scripts.
if (typeof (IFS) === 'undefined') { var IFS = {} } // eslint-disable-line
IFS.projectSetup = {}
IFS.projectSetup.loadOrder = {
'spend-profile': {
init: function () {
IFS.core.finance.init()
IFS.projectSetup.spendProfile.init()
}
},
common: {
init: function () {
IFS.projectSetup.clearInputs.init()
}
}
}
|
module.exports = function (api) {
const validEnv = ['development', 'test', 'production']
const currentEnv = api.env()
const isDevelopmentEnv = api.env('development')
const isProductionEnv = api.env('production')
const isTestEnv = api.env('test')
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
)
}
return {
presets: [
isTestEnv && [
'@babel/preset-env',
{
targets: {
node: 'current'
}
}
],
(isProductionEnv || isDevelopmentEnv) && [
'@babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: 3,
modules: false,
exclude: ['transform-typeof-symbol']
}
]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'@babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'@babel/plugin-transform-destructuring',
[
'@babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'@babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'@babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
corejs: false
}
],
[
'@babel/plugin-transform-regenerator',
{
async: false
}
]
].filter(Boolean)
}
}
|
//burst bullet returns array of five bullets
function rpBurst(o) {
var result = [];
for (var i=0; i<5; i++) {
result.push(
{ r: 5,
pos: {x:o.pos.x,y:o.pos.y},
v: {x:(i-2)*0.1,y:0.1}
}
);
}
return result;
};
function aimed(o,target) {
}
function bseek(o,target,vx,vy) {
var self = {};
self.r = 5;
self.target = target;
self.pos = {x:o.pos.x,y:o.pos.y};
self.v = {};
self.v.x = o.v.x;
self.v.y = o.v.y;
self.a = {x:0,y:0};
self.aFunc = function() {
var self = this;
var mass = 1;
var c = 30;
var r2 = Math.pow((self.target.pos.x - self.pos.x),2) + Math.pow((self.target.pos.y - self.pos.y),2);
var sum = Math.abs(self.target.pos.x - self.pos.x) + Math.abs((self.target.pos.y - self.pos.y));
var ratioX = (self.target.pos.x - self.pos.x)/sum;
var ratioY = (self.target.pos.y - self.pos.y)/sum;
self.a.x = ratioX * 1/r2 * c;
self.a.y = ratioY * 1/r2 * c;
};
return self;
}
function bseek02(o,target,vx,vy) {
var self = {};
self.r = 5;
self.target = target;
self.pos = {x:o.pos.x,y:o.pos.y};
self.v = {};
self.v.x = o.v.x;
self.v.y = o.v.y;
self.a = {x:0,y:0};
self.aFunc = function() {
var self = this;
if (self.pos.x < self.target.pos.x) {
self.a.x = 0.001;
}
else if (self.pos.x > self.target.pos.x) {
self.a.x = -0.0001;
}
};
return self;
}
function bseek01(o,target,vx,vy) {
var self = {};
self.r = 5;
self.target = target;
self.pos = {x:o.pos.x,y:o.pos.y};
self.v = {};
self.v.x = o.v.x;
self.v.y = o.v.y;
self.vFunc = function() {
var self = this;
if (self.pos.x < self.target.pos.x) {
self.v.x = self.v.x + 0.01;
}
else if (self.pos.x > self.target.pos.x) {
self.v.x = self.v.x - 0.01;
}
};
return self;
}
function bs02(o) {
return {
parent: o,
frame: 0,
delay: 500, //delay in milliseconds
spawn: function() {
return rp02(this.parent);
}
};
}
function bs01(o) {
return {
parent: o,
frame: 0,
delay: 500, //delay in milliseconds
spawn: function() {
return rp01(this.parent);
}
};
}
//add a little umph
function rp02(o) {
var self = {};
self.r = 5;
self.pos = {x:o.pos.x,y:o.pos.y};
self.v = {};
self.v.x = o.v.x - 0.1;
self.v.y = o.v.y - 0.1;
if (self.v.x < 0.05) {
self.v.x = 0.05;
}
if (self.v.y < 0.05) {
self.v.y = 0.1;
}
return self;
}
function eb1() {
return {
r: 10,
v: {x:0.1,y:0.1},
pos: {x:0,y:0},
a: {x:0,y:-0.00005}
}
}
|
const express = require('express');
const app = express();
const version = require('./api/version');
const getEmbed = require('./api/get-embed');
const parseEmbeds = require('./api/parse-embeds');
const listProviders = require('./api/list-providers');
app.get('/', version);
app.get('/embed', getEmbed);
app.get('/providers', listProviders);
app.post('/parse-embeds', parseEmbeds);
module.exports = app;
|
/*!
* address - lib/address.js
* Copyright(c) 2013 fengmk2 <fengmk2@gmail.com>
* MIT Licensed
*/
"use strict";
/**
* Module dependencies.
*/
var os = require('os');
var fs = require('fs');
var child = require('child_process');
var DEFAULT_RESOLV_FILE = '/etc/resolv.conf';
var DEFAULT_INTERFACE = 'eth';
var IFCONFIG_CMD = '/sbin/ifconfig';
var platform = os.platform();
if (platform === 'darwin') {
DEFAULT_INTERFACE = 'en';
} else if (platform === 'win32') {
IFCONFIG_CMD = 'ipconfig';
}
/**
* Get all addresses.
*
* @param {String} [interfaceName] interface name, default is 'eth' on linux, 'en' on mac os.
* @param {Function(err, addr)} callback
* - {Object} addr {
* - {String} ip
* - {String} ipv6
* - {String} mac
* }
*/
function address(interfaceName, callback) {
if (typeof interfaceName === 'function') {
callback = interfaceName;
interfaceName = null;
}
var addr = {
ip: address.ip(interfaceName),
ipv6: address.ipv6(interfaceName),
mac: null
};
address.mac(interfaceName, function (err, mac) {
if (mac) {
addr.mac = mac;
}
callback(err, addr);
});
}
address.interface = function (family, name) {
var interfaces = os.networkInterfaces();
name = name || DEFAULT_INTERFACE;
family = family || 'IPv4';
var networks;
for (var i = -1; i < 8; i++) {
var items = interfaces[name + (i >= 0 ? i : '')]; // support 'lo' and 'lo0'
if (items) {
networks = items;
break;
}
}
if (!networks || !networks.length) {
return;
}
for (var j = 0; j < networks.length; j++) {
var item = networks[j];
if (item.family === family) {
return item;
}
}
};
/**
* Get current machine IPv4
*
* @param {String} [interfaceName] interface name, default is 'eth' on linux, 'en' on mac os.
* @return {String} IP address
*/
address.ip = function (interfaceName) {
var item = address.interface('IPv4', interfaceName);
return item && item.address;
};
/**
* Get current machine IPv6
*
* @param {String} [interfaceName] interface name, default is 'eth' on linux, 'en' on mac os.
* @return {String} IP address
*/
address.ipv6 = function (interfaceName) {
var item = address.interface('IPv6', interfaceName);
return item && item.address;
};
// osx start line 'en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500'
// linux start line 'eth0 Link encap:Ethernet HWaddr 00:16:3E:00:0A:29 '
var MAC_OSX_START_LINE = /^(\w+)\:\s+flags=/;
var MAC_LINUX_START_LINE = /^(\w+)\s{2,}link encap:\w+/i;
// ether 78:ca:39:b0:e6:7d
// HWaddr 00:16:3E:00:0A:29
var MAC_RE = address.MAC_RE = /(?:ether|HWaddr)\s+((?:[a-z0-9]{2}\:){5}[a-z0-9]{2})/i;
// osx: inet 192.168.2.104 netmask 0xffffff00 broadcast 192.168.2.255
// linux: inet addr:10.125.5.202 Bcast:10.125.15.255 Mask:255.255.240.0
var MAC_IP_RE = address.MAC_IP_RE = /inet\s(?:addr\:)?(\d+\.\d+\.\d+\.\d+)/;
function getMAC(content, interfaceName, matchIP) {
var lines = content.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trimRight();
var m = MAC_OSX_START_LINE.exec(line) || MAC_LINUX_START_LINE.exec(line);
if (!m) {
continue;
}
// check interface name
var name = m[1];
if (name.indexOf(interfaceName) !== 0) {
continue;
}
var ip = null;
var mac = null;
var match = MAC_RE.exec(line);
if (match) {
mac = match[1];
}
i++;
while (true) {
line = lines[i];
if (!line || MAC_OSX_START_LINE.exec(line) || MAC_LINUX_START_LINE.exec(line)) {
i--;
break; // hit next interface, handle next interface
}
if (!mac) {
match = MAC_RE.exec(line);
if (match) {
mac = match[1];
}
}
if (!ip) {
match = MAC_IP_RE.exec(line);
if (match) {
ip = match[1];
}
}
i++;
}
if (ip === matchIP) {
return mac;
}
}
}
/**
* Get current machine MAC address
*
* @param {String} [interfaceName] interface name, default is 'eth' on linux, 'en' on mac os.
* @param {Function(err, address)} callback
*/
address.mac = function (interfaceName, callback) {
if (typeof interfaceName === 'function') {
callback = interfaceName;
interfaceName = null;
}
interfaceName = interfaceName || DEFAULT_INTERFACE;
var item = address.interface('IPv4', interfaceName);
if (!item) {
return callback();
}
if (item.mac) {
return callback(null, item.mac);
}
child.exec(IFCONFIG_CMD, {timeout: 5000}, function (err, stdout, stderr) {
if (err || !stdout) {
return callback(err);
}
var mac = getMAC(stdout || '', interfaceName, item.address);
callback(null, mac);
});
};
// nameserver 172.24.102.254
var DNS_SERVER_RE = /^nameserver\s+(\d+\.\d+\.\d+\.\d+)$/i;
/**
* Get DNS servers.
*
* @param {String} [filepath] resolv config file path. default is '/etc/resolv.conf'.
* @param {Function(err, servers)} callback
*/
address.dns = function (filepath, callback) {
if (typeof filepath === 'function') {
callback = filepath;
filepath = null;
}
filepath = filepath || DEFAULT_RESOLV_FILE;
fs.readFile(filepath, 'utf8', function (err, content) {
if (err) {
return callback(err);
}
var servers = [];
content = content || '';
var lines = content.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
var m = DNS_SERVER_RE.exec(line);
if (m) {
servers.push(m[1]);
}
}
callback(null, servers);
});
};
module.exports = address;
|
'use strict';
var path = require('path');
module.exports = {
basedir: path.normalize(path.join(__dirname, 'schemas')),
debug: console.log,
arguments: [
'A default text'
]
};
|
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
fbid: { type: String, index: { unique: true }},
schedule: [{
course: {},
section: {},
color: String
}],
majors: [],
courseCandidates: []
});
mongoose.model('User', UserSchema);
|
/**
* # fieldValidation.js
*
* Define the validation rules for various fields such as email, username,
* and passwords. If the rules are not passed, the appropriate
* message is displayed to the user
*
*/
'use strict'
import validate from 'validate.js'
import _ from 'underscore'
import I18n from './I18n'
const emailConstraints = {
from: {
email: true
}
}
const usernamePattern = /^[a-zA-Z0-9]{6,12}$/
const usernameConstraints = {
username: {
format: {
pattern: usernamePattern,
flags: 'i'
}
}
}
const passwordPattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,12}$/
const passwordConstraints = {
password: {
format: {
pattern: passwordPattern,
flags: 'i'
}
}
}
const passwordAgainConstraints = {
confirmPassword: {
equality: 'password'
}
}
/**
* ## Field Validation
* @param {Object} state Redux state
* @param {Object} action type & payload
*/
export default function fieldValidation (state, action) {
const {field, value} = action.payload
switch (field) {
/**
* ### username validation
* set the form field error
*/
case ('username'): {
let validUsername = _.isUndefined(validate({username: value},
usernameConstraints))
if (validUsername) {
return state.setIn(['form', 'fields', 'usernameHasError'],
false)
.setIn(['form', 'fields', 'usernameErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'usernameHasError'], true)
.setIn(['form', 'fields', 'usernameErrorMsg'],
I18n.t('FieldValidation.valid_user_name'))
}
}
/**
* ### email validation
* set the form field error
*/
case ('email'): {
let validEmail = _.isUndefined(validate({from: value},
emailConstraints))
if (validEmail) {
return state.setIn(['form', 'fields', 'emailHasError'], false)
} else {
return state.setIn(['form', 'fields', 'emailHasError'], true)
.setIn(['form', 'fields', 'emailErrorMsg'],
I18n.t('FieldValidation.valid_email'))
}
}
/**
* ### password validation
* set the form field error
*/
case ('password'): {
let validPassword = _.isUndefined(validate({password: value},
passwordConstraints))
if (validPassword) {
return state.setIn(['form', 'fields', 'passwordHasError'],
false)
.setIn(['form', 'fields', 'passwordErrorMsg'],
'')
} else {
return state.setIn(['form', 'fields', 'passwordHasError'], true)
.setIn(['form', 'fields', 'passwordErrorMsg'],
I18n.t('FieldValidation.valid_password'))
}
}
/**
* ### passwordAgain validation
* set the form field error
*/
case ('passwordAgain'):
var validPasswordAgain =
_.isUndefined(validate({password: state.form.fields.password,
confirmPassword: value}, passwordAgainConstraints))
if (validPasswordAgain) {
return state.setIn(['form', 'fields', 'passwordAgainHasError'],
false)
.setIn(['form', 'fields', 'passwordAgainErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'passwordAgainHasError'],
true)
.setIn(['form', 'fields', 'passwordAgainErrorMsg'],
I18n.t('FieldValidation.valid_password_again'))
}
/**
* ### showPassword
* toggle the display of the password
*/
case ('showPassword'):
return state.setIn(['form', 'fields',
'showPassword'], value)
}
return state
}
|
/**
* Node.js API Starter Kit (https://reactstarter.com/nodejs)
*
* Copyright © 2016-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* @flow */
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import session from 'express-session';
import flash from 'express-flash';
import expressGraphQL from 'express-graphql';
import PrettyError from 'pretty-error';
import passport from './passport';
import schema from './schema';
import { isAuthenticated } from './middlewares';
// routes
import accountRoutes from './routes/account';
import membersRoutes from './routes/members';
const app = express();
app.set('trust proxy', 'loopback');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(session({
name: 'sid',
resave: true,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept');
if ('OPTIONS' === req.method) {
res.sendStatus(200);
} else {
next();
}
});
app.use(accountRoutes);
app.use('/members', isAuthenticated, membersRoutes);
app.use('/graphql', expressGraphQL(req => ({
schema,
context: {
user: req.user,
},
graphiql: process.env.NODE_ENV !== 'production',
pretty: process.env.NODE_ENV !== 'production',
})));
app.get('/', (req, res) => {
if (req.user) {
res.send(`<p>Bem vindo, ${req.user.name}! (<a href="/logout">logout</a>)</p>`);
console.log(req.user);
} else {
res.send('<p>Seja bem-vindo! (<a href="/login/facebook" style="color: blue;">Login com FACEBOOK</a>)</p>');
// res.json({"project": "VaniAPI"});
}
});
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) => {
process.stderr.write(pe.render(err));
next();
});
export default app;
|
import Ember from 'ember';
import Paginate from '../mixins/table-pager/route';
const {
Route,
computed,
inject
} = Ember;
const { reads } = computed;
export default Route.extend(Paginate, {
modelName: 'item',
// the name of the current controller since I don't know how to auto detect
controllerName: 'old',
queryParams: {
quickSearchField: {
refreshModel: true
},
q: {
refreshModel: true
}
}
});
|
//Tracks the spots taken by a player
var playerTaken = {
1: false,
2: false,
3: false,
4: false,
5: false,
6: false,
7: false,
8: false,
9: false
}
//Tracks the running tally of pairs for a player (potentially one move away from a win)
, playerPairs = {
3: false,
4: false,
5: false,
6: false,
7: false,
8: false,
9: false,
10: false,
11: false,
12: false,
13: false,
14: false,
15: false,
16: false,
17: false
}
//Does the player choose a corner first?
, firstCorner = false
//Does the player choose a side first?
, firstSide = false
//Does the player go on to choose the opposite side? The AI uses this info to set up a fork.
, oppositeSide = false;
function playerTurn(cellValue) {
var id = getKey(squareNumberToCellValue, cellValue); //Parse the cell's value back into the view's id
$("#" + id).text("X"); //place an "X" in that square
//Check if the player has won
if (playerPairs[15 - cellValue]) {
gameOver("Player wins!"); //If the player's move would be the third in a row, win.
};
// Update the player's 'pairs' object
for (var k = 1; k < 10; k++) {
if ((playerTaken[k]) && (k + cellValue < 15)) {
playerPairs[k + cellValue] = true;
};
};
playerTaken[cellValue] = true; //Update the player's 'taken' object
spotsTaken.push(cellValue); //Update the overall spots taken on the game board
turn += 1; //Increment the turn counter
};
//Player behavioral tracking (to be used by the AI)
function playerFirstCorner() {
if ((turn == 1) && (playerTaken[8] || playerTaken[6] || playerTaken[4] || playerTaken[2])) {
firstCorner = true; //Does the player take a corner on the first move?
};
};
function playerFirstSide() {
if ((turn == 1) && (playerTaken[1] || playerTaken[7] || playerTaken[9] || playerTaken[3])) {
firstSide = true; //Does the player take a side on the first move?
};
};
function playerOppositeSide() {
if (turn == 3 && firstSide && ((playerTaken[3] && playerTaken[7]) || (playerTaken[1] && playerTaken[9]))) {
oppositeSide = true; //Does the player take a side and then the opposite side on the next turn?
};
}; |
// # boot - mongoose plugin
var _ = require('underscore')
var jsonSelect = require('mongoose-json-select')
exports = module.exports = function() {
return function(Schema) {
// NOTE: To allow `.sort('-created_at')` to work
// we need to have these as actual paths
Schema.add({
updated_at: Date,
created_at: Date
})
Schema.pre('save', function(next) {
var that = this
that.updated_at = _.isUndefined(that.created_at) ? that._id.getTimestamp() : new Date();
if (!that.created_at)
that.created_at = that._id.getTimestamp()
next()
})
Schema.set('toObject', {
virtuals: true,
getters: true
})
Schema.set('toJSON', {
virtuals: true,
getters: true
})
Schema.plugin(jsonSelect, '-_id')
return Schema
}
}
exports['@singleton'] = true
|
/**
* # SizeManager
* Copyright(c) 2016 Stefano Balietti
* MIT Licensed
*
* Handles changes in the number of connected players.
*/
(function(exports, parent) {
"use strict";
// ## Global scope
// Exposing SizeManager constructor
exports.SizeManager = SizeManager;
var J = parent.JSUS;
/**
* ## SizeManager constructor
*
* Creates a new instance of SizeManager
*
* @param {NodeGameClient} node A valid NodeGameClient object
*/
function SizeManager(node) {
/**
* ### SizeManager.node
*
* Reference to a nodegame-client instance
*/
this.node = node;
/**
* ### SizeManager.checkSize
*
* Checks if the current number of players is right
*
* This function is recreated each step based on the values
* of properties `min|max|exactPlayers` found in the Stager.
*
* It is used by `Game.shouldStep` to determine if we go to the
* next step.
*
* Unlike `SizeManager.changeHandler` this method does not
* accept parameters nor execute callbacks, just returns TRUE/FALSE.
*
* @return {boolean} TRUE if all checks are passed
*
* @see Game.shouldStep
* @see Game.shouldEmitPlaying
* @see SizeManager.init
* @see SizeManager.changeHandler
*/
this.checkSize = function() { return true; };
/**
* ### SizeManager.changeHandler
*
* Handles changes in the number of players
*
* This function is recreated each step based on the values
* of properties `min|max|exactPlayers` found in the Stager.
*
* Unlike `SizeManager.checkSize` this method requires input
* parameters and executes the appropriate callback functions
* in case a threshold is hit.
*
* @param {string} op The name of the operation:
* 'pdisconnect', 'pconnect', 'pupdate', 'replace'
* @param {Player|PlayerList} obj The object causing the update
*
* @return {boolean} TRUE, if no player threshold is passed
*
* @see SizeManager.min|max|exactPlayers
* @see SizeManager.min|max|exactCbCalled
* @see SizeManager.init
* @see SizeManager.checkSize
*/
this.changeHandler = function(op, obj) { return true; };
/**
* ### SizeManager.minThresold
*
* The min-players threshold currently set
*/
this.minThresold = null;
/**
* ### SizeManager.minCb
*
* The callback to execute once the min threshold is hit
*/
this.minCb = null;
/**
* ### SizeManager.minCb
*
* The callback to execute once the min threshold is restored
*/
this.minRecoveryCb = null;
/**
* ### SizeManager.maxThreshold
*
* The max-players threshold currently set
*/
this.maxThreshold = null;
/**
* ### SizeManager.minCbCalled
*
* TRUE, if the minimum-player callback has already been called
*
* This is reset when the max-condition is satisfied again.
*
* @see SizeManager.changeHandler
*/
this.minCbCalled = false;
/**
* ### SizeManager.maxCb
*
* The callback to execute once the max threshold is hit
*/
this.maxCb = null;
/**
* ### SizeManager.maxCb
*
* The callback to execute once the max threshold is restored
*/
this.maxRecoveryCb = null;
/**
* ### SizeManager.maxCbCalled
*
* TRUE, if the maximum-player callback has already been called
*
* This is reset when the max-condition is satisfied again.
*
* @see SizeManager.changeHandler
*/
this.maxCbCalled = false;
/**
* ### SizeManager.exactThreshold
*
* The exact-players threshold currently set
*/
this.exactThreshold = null;
/**
* ### SizeManager.exactCb
*
* The callback to execute once the exact threshold is hit
*/
this.exactCb = null;
/**
* ### SizeManager.exactCb
*
* The callback to execute once the exact threshold is restored
*/
this.exactRecoveryCb = null;
/**
* ### SizeManager.exactCbCalled
*
* TRUE, if the exact-player callback has already been called
*
* This is reset when the exact-condition is satisfied again.
*
* @see SizeManager.changeHandler
*/
this.exactCbCalled = false;
}
/**
* ### SizeManager.init
*
* Sets all internal references to null
*
* @see SizeManager.init
*/
SizeManager.prototype.clear = function() {
this.minThreshold = null;
this.minCb = null;
this.minRecoveryCb = null;
this.minCbCalled = false;
this.maxThreshold = null;
this.maxCb = null;
this.maxRecoveryCb = null;
this.maxCbCalled = false;
this.exactThreshold = null;
this.exactCb = null;
this.exactRecoveryCb = null;
this.exactCbCalled = false;
this.changeHandler = function(op, obj) { return true; };
this.checkSize = function() { return true; };
};
/**
* ### SizeManager.init
*
* Evaluates the requirements for the step and store references internally
*
* If required, it adds a listener to changes in the size of player list.
*
* At the beginning, calls `SizeManager.clear`
*
* @param {GameStage} step Optional. The step to evaluate.
* Default: node.player.stage
*
* @return {boolean} TRUE if a full handler was added
*
* @see SizeManager.changeHandlerFull
* @see SizeManager.clear
*/
SizeManager.prototype.init = function(step) {
var node, property, doPlChangeHandler;
this.clear();
node = this.node;
step = step || node.player.stage;
property = node.game.plot.getProperty(step, 'minPlayers');
if (property) {
this.setHandler('min', property);
doPlChangeHandler = true;
}
property = node.game.plot.getProperty(step, 'maxPlayers');
if (property) {
this.setHandler('max', property);
if (this.minThreshold === '*') {
throw new Error('SizeManager.init: maxPlayers cannot be' +
'"*" if minPlayers is "*"');
}
if (this.maxThreshold <= this.minThreshold) {
throw new Error('SizeManager.init: maxPlayers must be ' +
'greater than minPlayers: ' +
this.maxThreshold + '<=' + this.minThreshold);
}
doPlChangeHandler = true;
}
property = node.game.plot.getProperty(step, 'exactPlayers');
if (property) {
if (doPlChangeHandler) {
throw new Error('SizeManager.init: exactPlayers ' +
'cannot be set if either minPlayers or ' +
'maxPlayers is set.');
}
this.setHandler('exact', property);
doPlChangeHandler = true;
}
if (doPlChangeHandler) {
this.changeHandler = this.changeHandlerFull;
// Maybe this should be a parameter.
// this.changeHandler('init');
this.addListeners();
this.checkSize = this.checkSizeFull;
}
else {
// Set bounds-checking function.
this.checkSize = function() { return true; };
this.changeHandler = function() { return true; };
}
return doPlChangeHandler;
};
/**
* ### SizeManager.checkSizeFull
*
* Implements SizeManager.checkSize
*
* @see SizeManager.checkSize
*/
SizeManager.prototype.checkSizeFull = function() {
var nPlayers, limit;
nPlayers = this.node.game.pl.size();
// Players should count themselves too.
if (!this.node.player.admin) nPlayers++;
limit = this.minThreshold;
if (limit && limit !== '*' && nPlayers < limit) {
return false;
}
limit = this.maxThreshold;
if (limit && limit !== '*' && nPlayers > limit) {
return false;
}
limit = this.exacThreshold;
if (limit && limit !== '*' && nPlayers !== limit) {
return false;
}
return true;
};
/**
* ### SizeManager.changeHandlerFull
*
* Implements SizeManager.changeHandler
*
* @see SizeManager.changeHandler
*/
SizeManager.prototype.changeHandlerFull = function(op, player) {
var threshold, cb, nPlayers;
var game, res;
res = true;
game = this.node.game;
nPlayers = game.pl.size();
// Players should count themselves too.
if (!this.node.player.admin) nPlayers++;
threshold = this.minThreshold;
if (threshold) {
if (op === 'pdisconnect') {
if (threshold === '*' || nPlayers < threshold) {
if (!this.minCbCalled) {
this.minCbCalled = true;
cb = game.getProperty('onWrongPlayerNum');
cb.call(game, 'min', this.minCb, player);
}
res = false;
}
}
else if (op === 'pconnect') {
if (this.minCbCalled) {
cb = game.getProperty('onCorrectPlayerNum');
cb.call(game, 'min', this.minRecoveryCb, player);
}
// Must stay outside if.
this.minCbCalled = false;
}
}
threshold = this.maxThreshold;
if (threshold) {
if (op === 'pconnect') {
if (threshold === '*' || nPlayers > threshold) {
if (!this.maxCbCalled) {
this.maxCbCalled = true;
cb = game.getProperty('onWrongPlayerNum');
cb.call(game, 'max', this.maxCb, player);
}
res = false;
}
}
else if (op === 'pdisconnect') {
if (this.maxCbCalled) {
cb = game.getProperty('onCorrectPlayerNum');
cb.call(game, 'max', this.maxRecoveryCb, player);
}
// Must stay outside if.
this.maxCbCalled = false;
}
}
threshold = this.exactThreshold;
if (threshold) {
if (nPlayers !== threshold) {
if (!this.exactCbCalled) {
this.exactCbCalled = true;
cb = game.getProperty('onWrongPlayerNum');
cb.call(game, 'exact', this.exactCb, player);
}
res = false;
}
else {
if (this.exactCbCalled) {
cb = game.getProperty('onCorrectPlayerNum');
cb.call(game, 'exact', this.exactRecoveryCb, player);
}
// Must stay outside if.
this.exactCbCalled = false;
}
}
return res;
};
/**
* ### SizeManager.setHandler
*
* Sets the desired handler
*
* @param {string} type One of the available types: 'min', 'max', 'exact'
* @param {number|array} The value/s for the handler
*/
SizeManager.prototype.setHandler = function(type, values) {
values = checkMinMaxExactParams(type, values, this.node);
this[type + 'Threshold'] = values[0];
this[type + 'Cb'] = values[1];
this[type + 'RecoveryCb'] = values[2];
};
/**
* ### SizeManager.addListeners
*
* Adds listeners to disconnect and connect to the `step` event manager
*
* Notice: PRECONNECT is not added and must handled manually.
*
* @see SizeManager.removeListeners
*/
SizeManager.prototype.addListeners = function() {
var that;
that = this;
this.node.events.step.on('in.say.PCONNECT', function(p) {
that.changeHandler('pconnect', p.data);
}, 'plManagerCon');
this.node.events.step.on('in.say.PDISCONNECT', function(p) {
that.changeHandler('pdisconnect', p.data);
}, 'plManagerDis');
};
/**
* ### SizeManager.removeListeners
*
* Removes the listeners to disconnect and connect
*
* Notice: PRECONNECT is not added and must handled manually.
*
* @see SizeManager.addListeners
*/
SizeManager.prototype.removeListeners = function() {
this.node.events.step.off('in.say.PCONNECT', 'plManagerCon');
this.node.events.step.off('in.say.PDISCONNECT', 'plManagerDis');
};
// ## Helper methods.
/**
* ### checkMinMaxExactParams
*
* Checks the parameters of min|max|exactPlayers property of a step
*
* @param {string} name The name of the parameter: min|max|exact
* @param {number|array} property The property to check
* @param {NodeGameClient} node Reference to the node instance
*
* @see SizeManager.init
*/
function checkMinMaxExactParams(name, property, node) {
var num, cb, recoverCb, newArray;
if ('number' === typeof property) {
newArray = true;
property = [property];
}
else if (!J.isArray(property)) {
throw new TypeError('SizeManager.init: ' + name +
'Players property must be number or ' +
'non-empty array. Found: ' + property);
}
num = property[0];
cb = property[1] || null;
recoverCb = property[2] || null;
if (num === '@') {
num = node.game.pl.size() || 1;
// Recreate the array to avoid altering the reference.
if (!newArray) {
property = property.slice(0);
property[0] = num;
}
}
else if (num !== '*' &&
('number' !== typeof num || !isFinite(num) || num < 1)) {
throw new TypeError('SizeManager.init: ' + name +
'Players must be a finite number greater ' +
'than 1 or a wildcard (*,@). Found: ' + num);
}
if (!cb) {
property[1] = null;
}
else if ('function' !== typeof cb) {
throw new TypeError('SizeManager.init: ' + name +
'Players cb must be ' +
'function or undefined. Found: ' + cb);
}
if (!recoverCb) {
property[2] = null;
}
else if ('function' !== typeof cb) {
throw new TypeError('SizeManager.init: ' + name +
'Players recoverCb must be ' +
'function or undefined. Found: ' + recoverCb);
}
return property;
}
// ## Closure
})(
'undefined' != typeof node ? node : module.exports,
'undefined' != typeof node ? node : module.parent.exports
);
|
var externalLib = exports;
externalLib.message = 'it works';
|
/**
* Timeplot
*
* @fileOverview Timeplot
* @name Timeplot
*/
Timeline.Debug = SimileAjax.Debug; // timeline uses it's own debug system which is not as advanced
var log = SimileAjax.Debug.log; // shorter name is easier to use
/*
* This function is used to implement a raw but effective OOP-like inheritance
* in various Timeplot classes.
*/
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
// ---------------------------------------------
/**
* Create a timeplot attached to the given element and using the configuration from the given array of PlotInfos
*/
Timeplot.create = function(elmt, plotInfos) {
return new Timeplot._Impl(elmt, plotInfos);
};
/**
* Create a PlotInfo configuration from the given map of params
*/
Timeplot.createPlotInfo = function(params) {
return {
id: ("id" in params) ? params.id : "p" + Math.round(Math.random() * 1000000),
name: ("name" in params) ? params.name : "",
dataSource: ("dataSource" in params) ? params.dataSource : null,
eventSource: ("eventSource" in params) ? params.eventSource : null,
timeGeometry: ("timeGeometry" in params) ? params.timeGeometry : new Timeplot.DefaultTimeGeometry(),
valueGeometry: ("valueGeometry" in params) ? params.valueGeometry : new Timeplot.DefaultValueGeometry(),
timeZone: ("timeZone" in params) ? params.timeZone : 0,
fillColor: ("fillColor" in params) ? ((params.fillColor == "string") ? new Timeplot.Color(params.fillColor) : params.fillColor) : null,
fillGradient: ("fillGradient" in params) ? params.fillGradient : true,
fillFrom: ("fillFrom" in params) ? params.fillFrom : Number.NEGATIVE_INFINITY,
lineColor: ("lineColor" in params) ? ((params.lineColor == "string") ? new Timeplot.Color(params.lineColor) : params.lineColor) : new Timeplot.Color("#606060"),
lineWidth: ("lineWidth" in params) ? params.lineWidth : 1.0,
dotRadius: ("dotRadius" in params) ? params.dotRadius : 2.0,
dotColor: ("dotColor" in params) ? params.dotColor : null,
eventLineWidth: ("eventLineWidth" in params) ? params.eventLineWidth : 1.0,
showValues: ("showValues" in params) ? params.showValues : false,
roundValues: ("roundValues" in params) ? params.roundValues : true,
valuesOpacity: ("valuesOpacity" in params) ? params.valuesOpacity : 75,
bubbleWidth: ("bubbleWidth" in params) ? params.bubbleWidth : 300,
bubbleHeight: ("bubbleHeight" in params) ? params.bubbleHeight : 200,
toolTipFormat: ("toolTipFormat" in params) ? params.toolTipFormat : undefined,
headerFormat: ("headerFormat" in params) ? params.headerFormat : undefined,
getSelectedRegion: ("getSelectedRegion" in params) ? params.getSelectedRegion : undefined,
hideZeroToolTipValues: ("hideZeroToolTipValues" in params) ? params.hideZeroToolTipValues : undefined,
showValuesMode: ("showValuesMode" in params) ? params.showValuesMode : undefined,
rangeColor: ("rangeColor" in params) ? params.rangeColor : "#00FF00"
};
};
// -------------------------------------------------------
/**
* This is the implementation of the Timeplot object.
*
* @constructor
*/
Timeplot._Impl = function(elmt, plotInfos) {
this._id = "t" + Math.round(Math.random() * 1000000);
this._containerDiv = elmt;
this._plotInfos = plotInfos;
this._painters = {
background: [],
foreground: []
};
this._painter = null;
this._active = false;
this._upright = false;
this._initialize();
};
Timeplot._Impl.prototype = {
dispose: function() {
for (var i = 0; i < this._plots.length; i++) {
this._plots[i].dispose();
}
this._plots = null;
this._plotsInfos = null;
this._containerDiv.innerHTML = "";
},
/**
* Returns the main container div this timeplot is operating on.
*/
getElement: function() {
return this._containerDiv;
},
/**
* Returns document this timeplot belongs to.
*/
getDocument: function() {
return this._containerDiv.ownerDocument;
},
/**
* Append the given element to the timeplot DOM
*/
add: function(div) {
this._containerDiv.appendChild(div);
},
/**
* Remove the given element to the timeplot DOM
*/
remove: function(div) {
this._containerDiv.removeChild(div);
},
/**
* Add a painter to the timeplot
*/
addPainter: function(layerName, painter) {
var layer = this._painters[layerName];
if (layer) {
for (var i = 0; i < layer.length; i++) {
if (layer[i].context._id == painter.context._id) {
return;
}
}
layer.push(painter);
}
},
/**
* Remove a painter from the timeplot
*/
removePainter: function(layerName, painter) {
var layer = this._painters[layerName];
if (layer) {
for (var i = 0; i < layer.length; i++) {
if (layer[i].context._id == painter.context._id) {
layer.splice(i, 1);
break;
}
}
}
},
/**
* Get the width in pixels of the area occupied by the entire timeplot in the page
*/
getWidth: function() {
return this._containerDiv.clientWidth;
},
/**
* Get the height in pixels of the area occupied by the entire timeplot in the page
*/
getHeight: function() {
return this._containerDiv.clientHeight;
},
/**
* Get the drawing canvas associated with this timeplot
*/
getCanvas: function() {
return this._canvas;
},
/**
* <p>Load the data from the given url into the given eventSource, using
* the given separator to parse the columns and preprocess it before parsing
* thru the optional filter function. The filter is useful for when
* the data is row-oriented but the format is not compatible with the
* one that Timeplot expects.</p>
*
* <p>Here is an example of a filter that changes dates in the form 'yyyy/mm/dd'
* in the required 'yyyy-mm-dd' format:
* <pre>var dataFilter = function(data) {
* for (var i = 0; i < data.length; i++) {
* var row = data[i];
* row[0] = row[0].replace(/\//g,"-");
* }
* return data;
* };</pre></p>
*/
loadText: function(url, separator, eventSource, filter, format, callbackFunction) {
if (this._active) {
var tp = this;
var fError = function(statusText, status, xmlhttp) {
alert("Failed to load data xml from " + url + "\n" + statusText);
tp.hideLoadingMessage();
};
var fDone = function(xmlhttp) {
try {
eventSource.loadText(xmlhttp.responseText, separator, url, filter, format);
if(callbackFunction != undefined)callbackFunction(eventSource.getRange());
} catch (e) {
SimileAjax.Debug.exception(e);
} finally {
tp.hideLoadingMessage();
}
};
this.showLoadingMessage();
window.setTimeout(function() { SimileAjax.XmlHttp.get(url, fError, fDone); }, 0);
}
},
/**
* Load event data from the given url into the given eventSource, using
* the Timeline XML event format.
*/
loadXML: function(url, eventSource) {
if (this._active) {
var tl = this;
var fError = function(statusText, status, xmlhttp) {
alert("Failed to load data xml from " + url + "\n" + statusText);
tl.hideLoadingMessage();
};
var fDone = function(xmlhttp) {
try {
var xml = xmlhttp.responseXML;
if (!xml.documentElement && xmlhttp.responseStream) {
xml.load(xmlhttp.responseStream);
}
eventSource.loadXML(xml, url);
} finally {
tl.hideLoadingMessage();
}
};
this.showLoadingMessage();
window.setTimeout(function() { SimileAjax.XmlHttp.get(url, fError, fDone); }, 0);
}
},
/**
* Load event data from the given url into the given eventSource, using
* the Timeline JSON event format.
*/
loadJSON: function(url, eventSource, eventFunction) {
if (this._active) {
var tl = this;
var fError = function(statusText, status, xmlhttp) {
alert("Failed to load data json from " + url + "\n" + statusText);
tl.hideLoadingMessage();
};
var fDone = function(xmlhttp) {
try {
var data = eval('(' + xmlhttp.responseText + ')');
if(eventFunction != undefined) eventFunction(data);
eventSource.loadJSON(data, url);
} finally {
tl.hideLoadingMessage();
}
};
this.showLoadingMessage();
window.setTimeout(function() { SimileAjax.XmlHttp.get(url, fError, fDone); }, 0);
}
},
/**
* Overlay a 'div' element filled with the given text and styles to this timeplot
* This is used to implement labels since canvas does not support drawing text.
*/
putText: function(id, text, clazz, styles) {
var div = this.putDiv(id, "timeplot-div " + clazz, styles);
div.innerHTML = text;
return div;
},
/**
* Overlay a 'div' element, with the given class and the given styles to this timeplot.
* This is used for labels and horizontal and vertical grids.
*/
putDiv: function(id, clazz, styles) {
var tid = this._id + "-" + id;
var div = document.getElementById(tid);
if (!div) {
var container = this._containerDiv.firstChild; // get the divs container
div = document.createElement("div");
div.setAttribute("id",tid);
container.appendChild(div);
}
div.setAttribute("class","timeplot-div " + clazz);
div.setAttribute("className","timeplot-div " + clazz);
this.placeDiv(div,styles);
return div;
},
/**
* Associate the given map of styles to the given element.
* In case such styles indicate position (left,right,top,bottom) correct them
* with the padding information so that they align to the 'internal' area
* of the timeplot.
*/
placeDiv: function(div, styles) {
if (styles) {
for (style in styles) {
if (style == "left") {
styles[style] += this._paddingX;
styles[style] += "px";
} else if (style == "right") {
styles[style] += this._paddingX;
styles[style] += "px";
} else if (style == "top") {
styles[style] += this._paddingY;
styles[style] += "px";
} else if (style == "bottom") {
styles[style] += this._paddingY;
styles[style] += "px";
} else if (style == "width") {
if (styles[style] < 0) styles[style] = 0;
styles[style] += "px";
} else if (style == "height") {
if (styles[style] < 0) styles[style] = 0;
styles[style] += "px";
}
div.style[style] = styles[style];
}
}
},
/**
* return a {x,y} map with the location of the given element relative to the 'internal' area of the timeplot
* (that is, without the container padding)
*/
locate: function(div) {
return {
x: div.offsetLeft - this._paddingX,
y: div.offsetTop - this._paddingY
}
},
/**
* Forces timeplot to re-evaluate the various value and time geometries
* associated with its plot layers and repaint accordingly. This should
* be invoked after the data in any of the data sources has been
* modified.
*/
update: function() {
if (this._active) {
for (var i = 0; i < this._plots.length; i++) {
var plot = this._plots[i];
var dataSource = plot.getDataSource();
if (dataSource) {
var range = dataSource.getRange();
if (range) {
plot._valueGeometry.setRange(range);
plot._timeGeometry.setRange(range);
}
}
plot.hideValues();
}
this.paint();
}
},
/**
* Forces timeplot to re-evaluate its own geometry, clear itself and paint.
* This should be used instead of paint() when you're not sure if the
* geometry of the page has changed or not.
*/
repaint: function() {
if (this._active) {
this._prepareCanvas();
for (var i = 0; i < this._plots.length; i++) {
var plot = this._plots[i];
if (plot._timeGeometry) plot._timeGeometry.reset();
if (plot._valueGeometry) plot._valueGeometry.reset();
}
this.paint();
}
},
/**
* Calls all the painters that were registered to this timeplot and makes them
* paint the timeplot. This should be used only when you're sure that the geometry
* of the page hasn't changed.
* NOTE: painting is performed by a different thread and it's safe to call this
* function in bursts (as in mousemove or during window resizing
*/
paint: function() {
if (this._active && this._painter == null) {
var timeplot = this;
this._painter = window.setTimeout(function() {
timeplot._clearCanvas();
var run = function(action,context) {
try {
if (context.setTimeplot) context.setTimeplot(timeplot);
action.apply(context,[]);
} catch (e) {
SimileAjax.Debug.exception(e);
}
}
var background = timeplot._painters.background;
for (var i = 0; i < background.length; i++) {
run(background[i].action, background[i].context);
}
var foreground = timeplot._painters.foreground;
for (var i = 0; i < foreground.length; i++) {
run(foreground[i].action, foreground[i].context);
}
timeplot._painter = null;
}, 20);
}
},
_clearCanvas: function() {
var canvas = this.getCanvas();
var ctx = canvas.getContext('2d');
ctx.clearRect(0,0,canvas.width,canvas.height);
},
_clearLabels: function() {
var labels = this._containerDiv.firstChild;
if (labels) this._containerDiv.removeChild(labels);
labels = document.createElement("div");
this._containerDiv.appendChild(labels);
},
_prepareCanvas: function() {
var canvas = this.getCanvas();
// using jQuery. note we calculate the average padding; if your
// padding settings are not symmetrical, the labels will be off
// since they expect to be centered on the canvas.
var con = SimileAjax.jQuery(this._containerDiv);
this._paddingX = (parseInt(con.css('paddingLeft')) +
parseInt(con.css('paddingRight'))) / 2;
this._paddingY = (parseInt(con.css('paddingTop')) +
parseInt(con.css('paddingBottom'))) / 2;
canvas.width = this.getWidth() - (this._paddingX * 2);
canvas.height = this.getHeight() - (this._paddingY * 2);
var ctx = canvas.getContext('2d');
this._setUpright(ctx, canvas);
ctx.globalCompositeOperation = 'source-over';
},
_setUpright: function(ctx, canvas) {
// excanvas+IE requires this to be done only once, ever; actual canvas
// implementations reset and require this for each call to re-layout
if (!SimileAjax.Platform.browser.isIE) this._upright = false;
if (!this._upright) {
this._upright = true;
ctx.translate(0, canvas.height);
ctx.scale(1,-1);
}
},
_isBrowserSupported: function(canvas) {
var browser = SimileAjax.Platform.browser;
if ((canvas.getContext && window.getComputedStyle) ||
(browser.isIE && browser.majorVersion >= 6)) {
return true;
} else {
return false;
}
},
_initialize: function() {
// initialize the window manager (used to handle the popups)
// NOTE: this is a singleton and it's safe to call multiple times
SimileAjax.WindowManager.initialize();
var containerDiv = this._containerDiv;
var doc = containerDiv.ownerDocument;
// make sure the timeplot div has the right class
containerDiv.className = "timeplot-container " + containerDiv.className;
// clean it up if it contains some content
while (containerDiv.firstChild) {
containerDiv.removeChild(containerDiv.firstChild);
}
var canvas = doc.createElement("canvas");
if (this._isBrowserSupported(canvas)) {
this._clearLabels();
this._canvas = canvas;
canvas.className = "timeplot-canvas";
containerDiv.appendChild(canvas);
if(!canvas.getContext && G_vmlCanvasManager) {
canvas = G_vmlCanvasManager.initElement(this._canvas);
this._canvas = canvas;
}
this._prepareCanvas();
// inserting copyright and link to simile
var elmtCopyright = SimileAjax.Graphics.createTranslucentImage(Timeplot.urlPrefix + "images/copyright.png");
elmtCopyright.className = "timeplot-copyright";
elmtCopyright.title = "Timeplot (c) SIMILE - http://simile.mit.edu/timeplot/";
SimileAjax.DOM.registerEvent(elmtCopyright, "click", function() { window.location = "http://simile.mit.edu/timeplot/"; });
containerDiv.appendChild(elmtCopyright);
var timeplot = this;
var painter = {
onAddMany: function() { timeplot.update(); },
onAddOne: function() { timeplot.update(); },
onClear: function() { timeplot.update(); }
}
// creating painters
this._plots = [];
if (this._plotInfos) {
for (var i = 0; i < this._plotInfos.length; i++) {
var plot = new Timeplot.Plot(this, this._plotInfos[i]);
var dataSource = plot.getDataSource();
if (dataSource) {
dataSource.addListener(painter);
}
this.addPainter("background", {
context: plot.getTimeGeometry(),
action: plot.getTimeGeometry().paint
});
this.addPainter("background", {
context: plot.getValueGeometry(),
action: plot.getValueGeometry().paint
});
this.addPainter("foreground", {
context: plot,
action: plot.paint
});
this._plots.push(plot);
plot.initialize();
}
}
// creating loading UI
var message = SimileAjax.Graphics.createMessageBubble(doc);
message.containerDiv.className = "timeplot-message-container";
containerDiv.appendChild(message.containerDiv);
message.contentDiv.className = "timeplot-message";
message.contentDiv.innerHTML = "<img src='" + Timeplot.urlPrefix + "images/progress-running.gif' /> Loading...";
this.showLoadingMessage = function() { message.containerDiv.style.display = "block"; };
this.hideLoadingMessage = function() { message.containerDiv.style.display = "none"; };
this._active = true;
} else {
this._message = SimileAjax.Graphics.createMessageBubble(doc);
this._message.containerDiv.className = "timeplot-message-container";
this._message.containerDiv.style.top = "15%";
this._message.containerDiv.style.left = "20%";
this._message.containerDiv.style.right = "20%";
this._message.containerDiv.style.minWidth = "20em";
this._message.contentDiv.className = "timeplot-message";
this._message.contentDiv.innerHTML = "We're terribly sorry, but your browser is not currently supported by <a href='http://simile.mit.edu/timeplot/'>Timeplot</a>.<br><br> We are working on supporting it in the near future but, for now, see the <a href='http://simile.mit.edu/wiki/Timeplot_Limitations'>list of currently supported browsers</a>.";
this._message.containerDiv.style.display = "block";
containerDiv.appendChild(this._message.containerDiv);
}
}
};
|
module.exports = (p={}) => `<svg version="1.1" data-js="${p.name || 'checkmark'}" class="checkmark" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="97.619px" height="97.618px" viewBox="0 0 97.619 97.618" style="enable-background:new 0 0 97.619 97.618;"
xml:space="preserve">
<g>
<path d="M96.939,17.358L83.968,5.959c-0.398-0.352-0.927-0.531-1.449-0.494C81.99,5.5,81.496,5.743,81.146,6.142L34.1,59.688
L17.372,37.547c-0.319-0.422-0.794-0.701-1.319-0.773c-0.524-0.078-1.059,0.064-1.481,0.385L0.794,47.567
c-0.881,0.666-1.056,1.92-0.39,2.801l30.974,40.996c0.362,0.479,0.922,0.771,1.522,0.793c0.024,0,0.049,0,0.073,0
c0.574,0,1.122-0.246,1.503-0.68l62.644-71.297C97.85,19.351,97.769,18.086,96.939,17.358z"/>
</g></svg>`
|
angularApp.factory('cookieService', function()
{
var cookieService = {};
cookieService.readCookie = function(name)
{
return $.cookie(name);
};
cookieService.deleteCookie = function(name, path)
{
return $.removeCookie(name,{ path: path });
};
cookieService.writeCookie = function(name, value, path)
{
$.cookie(name, value, { path: path });
};
return cookieService;
}); |
'use strict'
const should = require('chai').should()
global.should = should
|
const slugify = require('slugify');
const path = require('path');
const CommandQueue = require('./lib/CommandQueue');
const Registry = require('./lib/Registry');
const Switch = require('./lib/Switch');
const COMMAND_DELAY = 1000;
let Service, Characteristic;
let command_queue, registry;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
command_queue = new CommandQueue(COMMAND_DELAY);
const registry_dir = path.dirname(homebridge.user.configPath());
registry = new Registry(path.join(registry_dir, "registry.kvs"));
registry.reset();
homebridge.registerAccessory("homebridge-energenie", "Energenie", EnergenieAccessory);
}
function EnergenieAccessory(log, config) {
var self = this;
self.log = log;
self.name = config["name"];
self.registry_name = slugify(self.name, "_").toLowerCase();
self.type = config["type"];
self.device_id = config["device_id"];
self.state = false;
self.service = new Service.Switch(self.name);
self.service.getCharacteristic(Characteristic.On).value = self.state;
self.service.getCharacteristic(Characteristic.On).on('get', function(cb) {
cb(null, self.state);
}.bind(self));
self.service.getCharacteristic(Characteristic.On).on('set', function(state, cb) {
self.state = state;
command_queue.queue(function() {
Switch(registry, self.state ? 'on' : 'off', self.registry_name, cb);
});
}.bind(self));
registry.add(self);
}
EnergenieAccessory.prototype.getServices = function() {
return [ this.service ];
}
|
marriageMapApp.factory('IGoService', ['$uibModal', '$log', 'md5', '$sce', function($uibModal, $log, md5, $sce) {
var iGoTypes = {
VIN_HONNEUR: "VIN_HONNEUR_SOIREE",
VIN_HONNEUR_SOIREE : "VIN_HONNEUR_SOIREE",
TOTALE : "TOTALE"
};
var getHashIGoCode = function(iGoCode) {
return md5.createHash(iGoCode || '');
}
/**
* Renvoie type d'invitation en fonction du code.
*/
var getIGoType = function(iGoCode) {
var hashIGoCode = getHashIGoCode(iGoCode);
if(hashIGoCode == "503235f2a9d9215777ae08edc35733b1") {
// Choix 1 : vin honneur
return iGoTypes.VIN_HONNEUR;
} else if(hashIGoCode == "0b675a7e649da044ab4a95c974a6a9b5") {
// Choix 2 : vin honneur soirée
return iGoTypes.VIN_HONNEUR_SOIREE;
} else if(hashIGoCode == "6e3e0be8e56cecf2472e03049cbf496a") {
// Choix 3 : tout
return iGoTypes.TOTALE;
}
console.warn("Code erroné !");
return null;
};
var service = {
/**
* Ouvre la popup pour participer au mariage
*/
openIGo : function() {
var modalInstance = $uibModal.open({
templateUrl: 'angular/iGo/iGo.html',
controller: 'IGoController',
size: 'md',
backdrop : true,
});
return modalInstance.result;
},
/**
* Check si code autorisé
*/
isIGoCodeAuthorized : function(iGoCode) {
if(getIGoType(iGoCode)) {
return true;
}
return false;
},
/**
* Retourne l'url du formulaire adéquat en fonction du code saisi
*/
getIGoFormAction : function(iGoCode) {
return $sce.trustAsResourceUrl("https://docs.google.com/forms/d/1lMd8U93sH6yyvz3SS9vsmm6-d7OMpVcTc8jXmePJnmU/viewform?entry.743673421&entry.238974991&entry.1513214179=" + getHashIGoCode(iGoCode) +"&entry.438709898");
}
}
return service;
}]); |
import React from 'react'
//whatever text props it is given will be displayed in marker
export const Marker = ({ text }) => (
<img src="orange.png" height="50"/>
);
|
var helpers = require('../helpers.js');
var mongoose = require('mongoose');
var Link = require('./link.js');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var accountSchema = new Schema({
id: {
type: String,
default: 'ac_' + helpers.generateBase62(24)
},
object: {
type: String,
default: 'account'
},
created: {
type: Date,
default: Date.now
},
apiKey: {
type: String,
default: helpers.generateBase62(24)
}
});
// Remove meta data from toJSON
if (!accountSchema.options.toJSON) accountSchema.options.toJSON = {};
accountSchema.options.toJSON.transform = function (doc, ret, options) {
delete ret._id;
delete ret.__v;
};
module.exports = mongoose.model('Account', accountSchema);
|
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open("http://www.freepeople.com/fp-movement/", function(status) {
if ( status === "success" ) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
console.log("width: -> " + $("img").first().width());
});
phantom.exit();
});
}
});
|
/**
* ueditor完整配置项
* 可以在这里配置整个编辑器的特性
*/
/**************************提示********************************
* 所有被注释的配置项均为UEditor默认值。
* 修改默认配置请首先确保已经完全明确该参数的真实用途。
* 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。
* 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。
**************************提示********************************/
(function () {
/**
* 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。
* 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。
* "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。
* 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。
* 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。
* window.UEDITOR_HOME_URL = "/xxxx/xxxx/";
*/
var URL = window.UEDITOR_HOME_URL || getUEBasePath();
/**
* 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
*/
window.UEDITOR_CONFIG = {
//为编辑器实例添加一个路径,这个不能被注释
UEDITOR_HOME_URL: URL
// 服务器统一请求接口路径
, serverUrl: "/ueditor/"
//工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的重新定义
, toolbars: [[
'fullscreen', 'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
'print', 'preview', 'searchreplace', 'drafts', 'help'
]]
//当鼠标放在工具栏上时显示的tooltip提示,留空支持自动多语言配置,否则以配置值为准
//,labelMap:{
// 'anchor':'', 'undo':''
//}
//语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件:
//lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase()
//,lang:"zh-cn"
//,langPath:URL +"lang/"
//主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件:
//现有如下皮肤:default
//,theme:'default'
//,themePath:URL +"themes/"
//,zIndex : 900 //编辑器层级的基数,默认是900
//针对getAllHtml方法,会在对应的head标签中增加该编码设置。
//,charset:"utf-8"
//若实例化编辑器的页面手动修改的domain,此处需要设置为true
//,customDomain:false
//常用配置项目
//,isShow : true //默认显示编辑器
//,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值
//,initialContent:'欢迎使用ueditor!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子
//,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了
//,focus:false //初始化时,是否让编辑器获得焦点true或false
//如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感
//,initialStyle:'p{line-height:1em}'//编辑器层级的基数,可以用来改变字体等
//,iframeCssUrl: URL + '/themes/iframe.css' //给编辑区域的iframe引入一个css文件
//indentValue
//首行缩进距离,默认是2em
//,indentValue:'2em'
//,initialFrameWidth:1000 //初始化编辑器宽度,默认1000
//,initialFrameHeight:320 //初始化编辑器高度,默认320
//,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false
//,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况)
//启用自动保存
//,enableAutoSave: true
//自动保存间隔时间, 单位ms
//,saveInterval: 500
//,fullscreen : false //是否开启初始化时即全屏,默认关闭
//,imagePopup:true //图片操作的浮层开关,默认打开
//,autoSyncData:true //自动同步编辑器要提交的数据
//,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹
//粘贴只保留标签,去除标签所有属性
//,retainOnlyLabelPasted: false
//,pasteplain:false //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴
//纯文本粘贴模式下的过滤规则
//'filterTxtRules' : function(){
// function transP(node){
// node.tagName = 'p';
// node.setStyle();
// }
// return {
// //直接删除及其字节点内容
// '-' : 'script style object iframe embed input select',
// 'p': {$:{}},
// 'br':{$:{}},
// 'div':{'$':{}},
// 'li':{'$':{}},
// 'caption':transP,
// 'th':transP,
// 'tr':transP,
// 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
// 'td':function(node){
// //没有内容的td直接删掉
// var txt = !!node.innerText();
// if(txt){
// node.parentNode.insertAfter(UE.uNode.createText(' '),node);
// }
// node.parentNode.removeChild(node,node.innerText())
// }
// }
//}()
//,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串
//insertorderedlist
//有序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准
//,'insertorderedlist':{
// //自定的样式
// 'num':'1,2,3...',
// 'num1':'1),2),3)...',
// 'num2':'(1),(2),(3)...',
// 'cn':'一,二,三....',
// 'cn1':'一),二),三)....',
// 'cn2':'(一),(二),(三)....',
// //系统自带
// 'decimal' : '' , //'1,2,3...'
// 'lower-alpha' : '' , // 'a,b,c...'
// 'lower-roman' : '' , //'i,ii,iii...'
// 'upper-alpha' : '' , lang //'A,B,C'
// 'upper-roman' : '' //'I,II,III...'
//}
//insertunorderedlist
//无序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准
//,insertunorderedlist : { //自定的样式
// 'dash' :'— 破折号', //-破折号
// 'dot':' 。 小圆圈', //系统自带
// 'circle' : '', // '○ 小圆圈'
// 'disc' : '', // '● 小圆点'
// 'square' : '' //'■ 小方块'
//}
//,listDefaultPaddingLeft : '30'//默认的左边缩进的基数倍
//,listiconpath : 'http://bs.baidu.com/listicon/'//自定义标号的路径
//,maxListLevel : 3 //限制可以tab的级数, 设置-1为不限制
//,autoTransWordToList:false //禁止word中粘贴进来的列表自动变成列表标签
//fontfamily
//字体设置 label留空支持多语言自动切换,若配置,则以配置值为准
//,'fontfamily':[
// { label:'',name:'songti',val:'宋体,SimSun'},
// { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
// { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'},
// { label:'',name:'heiti',val:'黑体, SimHei'},
// { label:'',name:'lishu',val:'隶书, SimLi'},
// { label:'',name:'andaleMono',val:'andale mono'},
// { label:'',name:'arial',val:'arial, helvetica,sans-serif'},
// { label:'',name:'arialBlack',val:'arial black,avant garde'},
// { label:'',name:'comicSansMs',val:'comic sans ms'},
// { label:'',name:'impact',val:'impact,chicago'},
// { label:'',name:'timesNewRoman',val:'times new roman'}
//]
//fontsize
//字号
//,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36]
//paragraph
//段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准
//,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''}
//rowspacingtop
//段间距 值和显示的名字相同
//,'rowspacingtop':['5', '10', '15', '20', '25']
//rowspacingBottom
//段间距 值和显示的名字相同
//,'rowspacingbottom':['5', '10', '15', '20', '25']
//lineheight
//行内间距 值和显示的名字相同
//,'lineheight':['1', '1.5','1.75','2', '3', '4', '5']
//customstyle
//自定义样式,不支持国际化,此处配置值即可最后显示值
//block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置
//尽量使用一些常用的标签
//参数说明
//tag 使用的标签名字
//label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同,
//style 添加的样式
//每一个对象就是一个自定义的样式
//,'customstyle':[
// {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
// {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'},
// {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'},
// {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'}
//]
//打开右键菜单功能
//,enableContextMenu: true
//右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准
//,contextMenu:[
// {
// label:'', //显示的名称
// cmdName:'selectall',//执行的command命令,当点击这个右键菜单时
// //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName
// exec:function () {
// //this是当前编辑器的实例
// //this.ui._dialogs['inserttableDialog'].open();
// }
// }
//]
//快捷菜单
//,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"]
//elementPathEnabled
//是否启用元素路径,默认是显示
//,elementPathEnabled : true
//wordCount
//,wordCount:true //是否开启字数统计
//,maximumWords:10000 //允许的最大字符数
//字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示
//,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符
//超出字数限制提示 留空支持多语言自动切换,否则按此配置显示
//,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span>
//tab
//点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位
//,tabSize:4
//,tabNode:' '
//removeFormat
//清除格式时可以删除的标签和属性
//removeForamtTags标签
//,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var'
//removeFormatAttributes属性
//,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign'
//undo
//可以最多回退的次数,默认20
//,maxUndoCount:20
//当输入的字符数超过该值时,保存一次现场
//,maxInputCount:1
//autoHeightEnabled
// 是否自动长高,默认true
//,autoHeightEnabled:true
//scaleEnabled
//是否可以拉伸长高,默认true(当开启时,自动长高失效)
//,scaleEnabled:false
//,minFrameWidth:800 //编辑器拖动时最小宽度,默认800
//,minFrameHeight:220 //编辑器拖动时最小高度,默认220
//autoFloatEnabled
//是否保持toolbar的位置不动,默认true
//,autoFloatEnabled:true
//浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面
//,topOffset:30
//编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效)
//,toolbarTopOffset:400
//设置远程图片是否抓取到本地保存
//,catchRemoteImageEnable: true //设置是否抓取远程图片
//pageBreakTag
//分页标识符,默认是_ueditor_page_break_tag_
//,pageBreakTag:'_ueditor_page_break_tag_'
//autotypeset
//自动排版参数
//,autotypeset: {
// mergeEmptyline: true, //合并空行
// removeClass: true, //去掉冗余的class
// removeEmptyline: false, //去掉空行
// textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
// imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
// pasteFilter: false, //根据规则过滤没事粘贴进来的内容
// clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
// clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
// removeEmptyNode: false, // 去掉空节点
// //可以去掉的标签
// removeTagNames: {标签名字:1},
// indent: false, // 行首缩进
// indentValue : '2em', //行首缩进的大小
// bdc2sb: false,
// tobdc: false
//}
//tableDragable
//表格是否可以拖拽
//,tableDragable: true
//sourceEditor
//源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror
//注意默认codemirror只能在ie8+和非ie中使用
//,sourceEditor:"codemirror"
//如果sourceEditor是codemirror,还用配置一下两个参数
//codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js"
//,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js"
//codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css"
//,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css"
//编辑器初始化完成后是否进入源码模式,默认为否。
//,sourceEditorFirst:false
//iframeUrlMap
//dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径
//,iframeUrlMap:{
// 'anchor':'~/dialogs/anchor/anchor.html',
//}
//allowLinkProtocol 允许的链接地址,有这些前缀的链接地址不会自动添加http
//, allowLinkProtocols: ['http:', 'https:', '#', '/', 'ftp:', 'mailto:', 'tel:', 'git:', 'svn:']
//webAppKey 百度应用的APIkey,每个站长必须首先去百度官网注册一个key后方能正常使用app功能,注册介绍,http://app.baidu.com/static/cms/getapikey.html
//, webAppKey: ""
//默认过滤规则相关配置项目
//,disabledTableInTable:true //禁止表格嵌套
//,allowDivTransToP:true //允许进入编辑器的div标签自动变成p标签
//,rgb2Hex:true //默认产出的数据中的color自动从rgb格式变成16进制格式
// xss 过滤是否开启,inserthtml等操作
,xssFilterRules: true
//input xss过滤
,inputXssFilter: true
//output xss过滤
,outputXssFilter: true
// xss过滤白名单 名单来源: https://raw.githubusercontent.com/leizongmin/js-xss/master/lib/default.js
,whitList: {
a: ['target', 'href', 'title', 'class', 'style'],
abbr: ['title', 'class', 'style'],
address: ['class', 'style'],
area: ['shape', 'coords', 'href', 'alt'],
article: [],
aside: [],
audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'],
b: ['class', 'style'],
bdi: ['dir'],
bdo: ['dir'],
big: [],
blockquote: ['cite', 'class', 'style'],
br: [],
caption: ['class', 'style'],
center: [],
cite: [],
code: ['class', 'style'],
col: ['align', 'valign', 'span', 'width', 'class', 'style'],
colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'],
dd: ['class', 'style'],
del: ['datetime'],
details: ['open'],
div: ['class', 'style'],
dl: ['class', 'style'],
dt: ['class', 'style'],
em: ['class', 'style'],
font: ['color', 'size', 'face'],
footer: [],
h1: ['class', 'style'],
h2: ['class', 'style'],
h3: ['class', 'style'],
h4: ['class', 'style'],
h5: ['class', 'style'],
h6: ['class', 'style'],
header: [],
hr: [],
i: ['class', 'style'],
img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass', 'class', 'data-latex'],
ins: ['datetime'],
li: ['class', 'style'],
mark: [],
nav: [],
ol: ['class', 'style'],
p: ['class', 'style'],
pre: ['class', 'style'],
s: [],
section:[],
small: [],
span: ['class', 'style'],
sub: ['class', 'style'],
sup: ['class', 'style'],
strong: ['class', 'style'],
table: ['width', 'border', 'align', 'valign', 'class', 'style'],
tbody: ['align', 'valign', 'class', 'style'],
td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
tfoot: ['align', 'valign', 'class', 'style'],
th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
thead: ['align', 'valign', 'class', 'style'],
tr: ['rowspan', 'align', 'valign', 'class', 'style'],
tt: [],
u: [],
ul: ['class', 'style'],
video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style']
}
};
function getUEBasePath(docUrl, confUrl) {
return getBasePath(docUrl || self.document.URL || self.location.href, confUrl || getConfigFilePath());
}
function getConfigFilePath() {
var configPath = document.getElementsByTagName('script');
return configPath[ configPath.length - 1 ].src;
}
function getBasePath(docUrl, confUrl) {
var basePath = confUrl;
if (/^(\/|\\\\)/.test(confUrl)) {
basePath = /^.+?\w(\/|\\\\)/.exec(docUrl)[0] + confUrl.replace(/^(\/|\\\\)/, '');
} else if (!/^[a-z]+:/i.test(confUrl)) {
docUrl = docUrl.split("#")[0].split("?")[0].replace(/[^\\\/]+$/, '');
basePath = docUrl + "" + confUrl;
}
return optimizationPath(basePath);
}
function optimizationPath(path) {
var protocol = /^[a-z]+:\/\//.exec(path)[ 0 ],
tmp = null,
res = [];
path = path.replace(protocol, "").split("?")[0].split("#")[0];
path = path.replace(/\\/g, '/').split(/\//);
path[ path.length - 1 ] = "";
while (path.length) {
if (( tmp = path.shift() ) === "..") {
res.pop();
} else if (tmp !== ".") {
res.push(tmp);
}
}
return protocol + res.join("/");
}
window.UE = {
getUEBasePath: getUEBasePath
};
})();
|
/*
*
* ProfilePage reducer
*
*/
import { fromJS } from 'immutable';
import {
PROFILE_FORM_UPDATED,
} from './constants';
const initialState = fromJS({});
function profilePageReducer(state = initialState, action) {
switch (action.type) {
case PROFILE_FORM_UPDATED: {
// TODO Should this be state.profile[action.formElement] = value (but immutable style)
const newState = state.set(action.storeName, action.value);
console.log('profilePage newState', newState.toJS());
return newState;
}
default: {
return state;
}
}
}
export default profilePageReducer;
|
module.exports={
return{
area:function(r){
return Math.pi*r*r;
}
};
}
|
angular.module('Scout.routes', [])
.config(function ($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('tabs', {
url: '/tabs',
templateUrl: 'client/templates/tabs.html',
abstract: true
})
// Configure the event info. List of teams and matches.
.state('tabs.configure', {
url: '/configure',
views: {
'tab-configure': {
templateUrl: 'client/templates/configuration.html',
controller: 'configurationCtrl as configuration'
}
}
})
// Setup info for a match (i.e. one three-on-three robot competition)
.state('tabs.setup', {
url: '/setup',
views: {
'tab-setup': {
templateUrl: 'client/templates/setup.html',
controller: 'SetupCtrl as setup'
}
}
})
.state('tabs.autonomous', {
url: '/autonomous',
views: {
'tab-autonomous': {
templateUrl: 'client/templates/autonomous.html',
controller: 'AutonomousCtrl'
}
}
})
.state('tabs.chats', {
url: '/chats',
templateUrl: 'client/templates/chats.html'
})
.state('tabs.cloud', {
url: '/cloud',
views: {
'tab-cloud': {
templateUrl: 'client/templates/cloud.html',
controller: 'CloudCtrl'
}
}
})
.state('tabs.teleop', {
url: '/teleop',
views: {
'tab-teleop': {
templateUrl: 'client/templates/teleOp.html',
controller: 'TeleOpCtrl as teleOp'
}
}
})
.state('tabs.match', {
url: '/match',
views: {
'tab-match': {
templateUrl: 'client/templates/match.html',
controller: 'MatchCtrl'
}
}
})
.state('tabs.pit', {
url: '/pit',
views: {
'tab-pit': {
templateUrl: 'client/templates/pitScouting.html',
controller: 'PitScoutingCtrl as pitScouting'
}
}
})
.state('tab7DefaultPage', {
url: '/page8',
templateUrl: 'client/templates/tab7DefaultPage.html',
controller: 'Tab7DefaultPageCtrl'
})
.state('login', {
url: '/page10',
templateUrl: 'client/templates/login.html',
controller: 'LoginCtrl'
})
.state('signup', {
url: '/page11',
templateUrl: 'client/templates/signup.html',
controller: 'SignupCtrl'
});
$urlRouterProvider.otherwise('/tabs/configure');
}); |
import _ from "underscore";
import $ from "jquery";
import context from "context-utils";
import BaseView from "../BaseView";
export default class TextField extends BaseView {
className(){
return 'ui-input ui-input-text ' + (_.result(this, "addClass") || '');
}
constructor(options) {
super(options);
if (!options || !_.isObject(options) )
throw new Error('No options provided');
if (!options.field)
throw new Error('The field option is required');
this.options = _.defaults(this.options, {
field: null,
fieldId: null,
multiline: false,
label: '',
maxLength: null,
id: null, // Deprecated
type: 'text',
addClass: null,
filled: false ,
autocorrect: false,
spellcheck: null,
autocomplete: null, // off, on, name, ecc @Ref: https://developer.mozilla.org/it/docs/Web/HTML/Element/input
inputmode: null,
invalid: null,
formatCharacterCount: null,
accessoryBar: true,
placeholder: null,
value: null,
disabled: false,
selectAll: false,
autocapitalize: null, // off, characters, words, sentences. @Ref: https://developers.google.com/web/updates/2015/04/autocapitalize
step: null,
min: null,
max: null,
tabindex: null,
pattern: null
});
this.isAndroid = false;
this.enableCharacterCount = false;
this.textFieldAttributes = {
'data-field': this.options.field
};
let os = context.device.getOS();
if (os.name == 'Android' ){
this.isAndroid = true;
if ( os.version < 5 )
this.options.filled = true;
}
if (this.options.fieldId && !this.options.id) {
this.options.id = this.options.fieldId;
}
if (!this.options.id && this.options.field) {
this.options.id = this.options.field;
}
if (this.options.id) {
this.textFieldAttributes['id'] = this.options.id;
}
if (this.options.maxLength) {
this.textFieldAttributes['maxlength'] = this.options.maxLength;
}
if (this.options.step) {
this.textFieldAttributes['step'] = this.options.step;
}
if ( _.isFunction(this.options.formatCharacterCount) ){
var cbFormatCharacterCount = _.bind(this.options.formatCharacterCount, this);
this.formatCharacterCount = _.bind(function (fieldLength) {
if ( this.formatCharacterCount )
cbFormatCharacterCount(fieldLength);
}, this);
}
if ( this.options.addClass )
this.$el.addClass( this.options.addClass );
if ( !this.options.autocorrect )
this.textFieldAttributes['autocorrect'] = 'off';
if ( this.options.autocomplete )
this.textFieldAttributes['autocomplete'] = this.options.autocomplete;
if ( _.isBoolean(this.options.spellcheck) )
this.textFieldAttributes['spellcheck'] = this.options.spellcheck.toString();
if (this.options.pattern){
this.textFieldAttributes['pattern'] = this.options.pattern;
}
if (this.options.inputmode) {
this.textFieldAttributes['inputmode'] = this.options.inputmode;
if (this.options.inputmode == 'numeric')
this.textFieldAttributes['pattern'] = '[0-9]*';
}
// Events
let events = {
'touchstart': 'onTouchStart',
'click label': 'onClickLabel'
};
if ( this.options.multiline ){
events['focus textarea'] = 'onFocus';
events['blur textarea'] = 'onBlur';
events['change textarea'] = 'onChange';
events['keyup textarea'] = 'onChange';
}else{
events['focus input'] = 'onFocus';
events['blur input'] = 'onBlur';
events['change input'] = 'onChange';
events['keyup input'] = 'onChange';
}
this.addEvents(events);
}
onRender(rendered) {
if ( rendered ) return this;
this.$characterCount = null;
this.$label = null;
// this.$el.empty();
if (this.options.label) {
this.$label = $("<label>").attr({ "for": this.options.id }).text(this.options.label);
this.$el.append(this.$label);
}
if (this.options.multiline)
this.$textfield = $('<textarea>').attr(this.textFieldAttributes);
else
this.$textfield = $('<input type="' + this.options.type + '">').attr(this.textFieldAttributes);
if (this.options.placeholder)
this.$textfield.attr('placeholder', this.options.placeholder);
if ( this.options.disabled ){
this.$textfield.attr( 'disabled', 'disabled' );
this.el.classList.add('disabled');
}
if ( this.options.autocapitalize )
this.$textfield.attr( 'autocapitalize', this.options.autocapitalize );
if ( !_.isUndefined(this.options.min) || !_.isNull(this.options.min) )
this.$textfield.attr('min', this.options.min);
if ( !_.isUndefined(this.options.max) || !_.isNull(this.options.max) )
this.$textfield.attr('max', this.options.max);
if ( !_.isUndefined(this.options.tabindex) || !_.isNull(this.options.tabindex) )
this.$textfield.attr('tabindex', this.options.tabindex);
this.$el.append(this.$textfield);
if(this.options.maxLength) {
this.enableCharacterCount = true;
this.$characterCount = $('<span>').addClass('ui-input-character-count');
this.$el.addClass('ui-input-character-count-enabled').append(this.$characterCount);
this.formatCharacterCount(0);
}
if(this.options.invalid)
this.$el.append($('<div>').addClass('ui-input-invalid').attr('data-invalid-field', this.options.field));
if (this.options.filled) {
this.$el.addClass("filled");
}
this.setValue( this.options.value );
return this;
}
onTouchStart() {
let hideFormAccessoryBar;
if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.Keyboard && cordova.plugins.Keyboard.hideKeyboardAccessoryBar ) {
hideFormAccessoryBar = cordova.plugins.Keyboard.hideKeyboardAccessoryBar;
}else if ( window.Keyboard && window.Keyboard.hideFormAccessoryBar ){
hideFormAccessoryBar = window.Keyboard.hideFormAccessoryBar;
}
if (!_.isFunction(hideFormAccessoryBar))
hideFormAccessoryBar = ()=>{};
hideFormAccessoryBar(!this.options.accessoryBar);
}
onFocus(e) {
if (e) e.preventDefault();
if (this.options.selectAll) {
$(e.currentTarget).select();
}
this.$el.addClass('active');
this.trigger('focus', this);
}
onBlur() {
this.$el.removeClass('active');
if ( this.textFieldLength() > 0 || this.options.filled)
this.$el.addClass('filled');
else
this.$el.removeClass('filled');
this.trigger('blur', this);
}
onChange(e) {
let fieldLength = this.textFieldLength();
this.formatCharacterCount( this.textFieldLength() );
if ( fieldLength > 0 )
this.$el.addClass('filled');
else
this.$el.removeClass('filled');
// FIX: Android non interpreta maxlength pertanto lo controllo via javascript
if ( this.isAndroid && _.isNumber(this.options.maxLength) ) {
let max = this.options.maxLength;
if (this.$textfield.val().length > max) {
this.$textfield.val(this.$textfield.val().substr(0, max));
}
}
this.trigger('change', e, this );
}
onClickLabel(){
this.focus();
}
focus(delay){
if ( !delay )
delay = 0;
if ( this.cache.focusTO )
clearTimeout(this.cache.focusTO);
this.cache.focusTO =
setTimeout(() => {
this.$textfield.focus();
this.cache.focusTO = null;
}, delay);
return this;
}
blur() {
if (this.$textfield)
this.$textfield.blur();
}
formatCharacterCount(fieldLength) {
if ( this.enableCharacterCount )
this.$characterCount.text(this.textFieldAttributes.maxlength - fieldLength);
}
textFieldLength() {
let str = this.$textfield.val();
if (!str)
return 0;
let lns = str.match(/\n/g);
if (lns)
return str.length + lns.length;
return str.length;
}
setLabel(newLabel) {
this.options.label = newLabel;
if (!this.$label) {
this.$label = $('<label>').attr({ 'for': this.options.id }).text(this.options.label);
this.$el.prepend(this.$label);
} else {
this.$label.text(this.options.label);
}
}
setValue(value, options) {
options = _.defaults(options || {}, {
silent: false
});
this.$textfield.val( value );
// let event = document.createEvent("KeyboardEvent");
// event.initKeyboardEvent("keypress",
let event = new KeyboardEvent("keypress", {
"ctrlKey": false,
"shiftKey": false,
"altKey": false,
"metaKey": false,
"repeat": false,
"isComposing": false,
"charCode": 0,
"keyCode": 115,
});
if (!options.silent) this.onChange(event);
return this;
}
getValue() {
if (!this.$textfield) return null;
return this.$textfield.val();
}
getFieldName(){
return this.options.field;
}
enable(action) {
this.disabled(!action);
}
disabled(value) {
this.options.disabled = value;
if (this.$textfield) {
this.requestAnimationFrame(() => {
if (value) {
this.$textfield.attr('disabled', true);
this.el.classList.add('disabled');
} else {
this.$textfield.removeAttr('disabled');
this.el.classList.remove('disabled');
}
});
}
}
clear() {
if (this.$textfield) {
this.$textfield.val('');
}
}
};
|
#!/usr/bin/env node
const path = require('path')
const { execSync } = require('child_process')
const { name, version } = require('../../package.json')
const rootDirectory = path.join(__dirname, '../..')
// 1. Remove all *.tgz before install
execSync('rm -rf *.tgz', { cwd: rootDirectory })
// 2. Do npm pack
execSync('npm pack', { cwd: rootDirectory })
|
var splitter = /(<=|<|>=|>|!=|=|[?])/
function isNumber(s) {
return !isNaN(+s)
}
var operators = {
"<=": "lte",
"<" : "lt",
">=": "gte",
">" : "gt",
"=" : "eq",
'!=': "neq",
"?" : 'ok'
}
function coearse(n) {
return isNumber(n) ? +n : n
}
function parse (str) {
return str
.split(',')
.map(function (subquery) {
//split on operator
subquery = subquery.split(splitter).map(function (s) {
return s.trim()
})
var q = {
path: subquery.shift().split('.').map(function (e) {
return e === '*' ? true : e
})
}
while(subquery.length) {
var s
var op = operators[s = subquery.shift()]
if(!op)
throw new Error(s + 'is not a valid operator, expected: < <= > >= or =')
if(!subquery[0])
throw new Error('missing operand for ' + s)
q[op] = coearse(subquery.shift())
}
return q
})
}
module.exports = parse
if(!module.parent && process.title != 'browser')
console.log(parse(process.argv.slice(2).join(' ')))
|
/*------------------------------------------------------------------------------------------------\
draw/update the summaryTable
\------------------------------------------------------------------------------------------------*/
import indicateLoading from '../util/indicateLoading';
export function draw(codebook) {
/*
indicateLoading(
codebook,
'.web-codebook .summaryTable .variable-row .row-title'
);
*/
//enter/update/exit for variableDivs
//BIND the newest data
var varRows = codebook.summaryTable.wrap
.selectAll('div.variable-row')
.data(codebook.data.summary, d => d.value_col);
//ENTER
varRows
.enter()
.append('div')
.attr('class', function(d) {
return 'variable-row ' + d.type;
});
//Hide variable rows corresponding to variables specified in settings.hiddenVariables.
varRows.classed(
'hidden',
d => codebook.config.hiddenVariables.indexOf(d.value_col) > -1
);
//Set chart visibility (on initial load only - then keep user settings)
if (codebook.config.chartVisibility != 'user-defined') {
varRows.classed(
'hiddenDetails',
codebook.config.chartVisibility != 'visible'
);
}
codebook.config.chartVisibility =
codebook.config.chartVisibility == 'hidden' ? 'hidden' : 'user-defined';
//ENTER + Update
varRows.each(codebook.summaryTable.renderRow);
//EXIT
varRows.exit().remove();
codebook.summaryTable.wrap.selectAll('div.status.error').remove();
if (varRows[0].length == 0) {
codebook.summaryTable.wrap
.append('div')
.attr('class', 'status error')
.text(
'No values selected. Update the filters above or load a different data set.'
);
}
}
|
'use strict';
const fs = require('fs-extra');
const p = require('path');
const marked = require('marked');
const parser = require('./littlePostParser');
const namePost = require('./namePost');
const handleFiles = require('./handleFiles');
module.exports = function(blogDir) {
if (fs.statSync(blogDir).isDirectory()) {
const result = {};
fs.readdirSync(blogDir).map(file => {
let date = file.match(
/^(\d{4})-(\d\d?)-(\d\d?)-(.+)\.(md|markdown|html)$/
);
if (!date) {
return;
}
const d = `${date[1]}-${date[2]}-${date[3]}`;
const post = parser(p.join(blogDir, file));
const _id = namePost(file);
const Post = Object.assign(post, {
main: marked(post.main),
date: d,
name: file
});
result[_id] = Post;
});
return result;
} else if (fs.statSync(blogDir).isFile()) {
return blogDir;
} else {
throw new Error(`Incorrect file-type in ${blogDir}`);
}
};
|
(function(global) {
var Demo = global.Demo
Demo.add({
name: 'Slice.'
,messageString: "Right click and drag to slice up the block."
,init: function() {
/*cpSpace*/ var space = this.space
space.setIterations(30);
space.gravity = (cp.v(0, -500));
space.sleepTimeThreshold = (0.5);
space.collisionSlop = (0.5);
var body, staticBody = space.staticBody
/*cpShape*/ var shape
// Create segments around the edge of the screen.
shape = space.addShape(new cp.SegmentShape(staticBody, cp.v(-1000,-240), cp.v(1000,-240), 0.0));
shape.setElasticity(1.0);
shape.setFriction(1.0);
shape.layers = Demo.NOT_GRABABLE_MASK;
/*cpFloat*/ var width = 200.0;
/*cpFloat*/ var height = 300.0;
/*cpFloat*/ var mass = width*height*DENSITY;
/*cpFloat*/ var moment = cp.momentForBox(mass, width, height);
body = space.addBody(new cp.Body(mass, moment));
shape = space.addShape(new cp.BoxShape(body, width, height));
shape.setFriction(0.6);
return space;
}
,update: function(/*double*/ dt) {
var space = this.space
space.step(dt);
// Annoying state tracking code that you wouldn't need
// in a real event driven system.
if(Demo.rightClick != lastClickState){
if(Demo.rightClick){
// MouseDown
sliceStart = cp.v(Demo.mouse.x, Demo.mouse.y);
} else {
// MouseUp
/*struct SliceContext*/ var context = new SliceContext(sliceStart, Demo.mouse, space);
space.segmentQuery(sliceStart, Demo.mouse, Demo.GRABABLE_MASK_BIT, cp.NO_GROUP, /*(cpSpaceSegmentQueryFunc)*/SliceQuery, context);
}
lastClickState = Demo.rightClick;
}
if(Demo.rightClick){
Demo.renderer.drawSegment(sliceStart, Demo.mouse, new Demo.Color(255, 0, 0, 1));
}
}
})
var DENSITY = (1.0/10000.0)
var lastClickState = false
var sliceStart = cp.v(0, 0)
//static void
var ClipPoly = function(/*cpSpace*/ space, /*cpShape*/ shape, /*cpVect*/ n, /*cpFloat*/ dist) {
/*cpBody*/ var body = shape.getBody();
/*int*/ var count = shape.getNumVerts();
/*int*/ var clippedCount = 0;
// /*cpVect*/ var clipped = (cpVect *)alloca((count + 1)*sizeof(cpVect));
/*cpVect*/ var clipped = [];
for(var i=0, j=count-1; i<count; j=i, i++){
/*cpVect*/ var a = body.local2World(shape.getVert(j));
/*cpFloat*/ var a_dist = cp.v.dot(a, n) - dist;
if(a_dist < 0.0){
clipped[clippedCount] = a;
clippedCount++;
}
/*cpVect*/ var b = body.local2World(shape.getVert(i));
/*cpFloat*/ var b_dist = cp.v.dot(b, n) - dist;
if(a_dist*b_dist < 0.0){
/*cpFloat*/ var t = cp.fabs(a_dist)/(cp.fabs(a_dist) + cp.fabs(b_dist));
clipped[clippedCount] = cp.v.lerp(a, b, t);
clippedCount++;
}
}
/*cpVect*/ var centroid = cp.centroidForPoly(clipped);
/*cpFloat*/ var mass = cp.areaForPoly(clipped)*DENSITY;
/*cpFloat*/ var moment = cp.momentForPoly(mass, clipped, cp.v.neg(centroid));
/*cpBody*/ var new_body = space.addBody(new cp.Body(mass, moment));
new_body.setPos(centroid);
new_body.setVel(body.getVelAtWorldPoint(centroid));
new_body.setAngVel(body.getAngVel());
/*cpShape*/ var new_shape = space.addShape(new cp.PolyShape(new_body, clipped, cp.v.neg(centroid)));
// Copy whatever properties you have set on the original shape that are important
new_shape.setFriction(shape.getFriction());
}
// Context structs are annoying, use blocks or closures instead if your compiler supports them.
/*var*/ var SliceContext = function(/*cpVect*/ a, b, /*cpSpace*/ space) {
this.a = a;
this.b = b;
this.space = space;
};
//static void
var SliceShapePostStep = function(/*cpSpace*/ space, /*cpShape*/ shape, /*struct SliceContext*/ context) {
/*cpVect*/ var a = context.a;
/*cpVect*/ var b = context.b;
// Clipping plane normal and distance.
/*cpVect*/ var n = cp.v.normalize(cp.v.perp(cp.v.sub(b, a)));
/*cpFloat*/ var dist = cp.v.dot(a, n);
ClipPoly(space, shape, n, dist);
ClipPoly(space, shape, cp.v.neg(n), -dist);
/*cpBody*/ var body = shape.getBody();
space.removeShape(shape);
space.removeBody(body);
}
//static void
var SliceQuery = function(/*cpShape*/ shape, /*cpFloat*/ t, /*cpVect*/ n, /*struct SliceContext*/ context) {
/*cpVect*/ var a = context.a;
/*cpVect*/ var b = context.b;
// Check that the slice was complete by checking that the endpoints aren't in the sliced shape.
if(!shape.pointQuery(a) && !shape.pointQuery(b)){
// Can't modify the space during a query.
// Must make a post-step callback to do the actual slicing.
context.space.addPostStepCallback(/*(cpPostStepFunc)*/SliceShapePostStep, shape, context);
}
}
})(function() {
return this;
}()) |
/**
* Created by senntyou on 2017/11/30.
*/
require('../../util/change_cwd_to')(__dirname + '/demo');
require('../../util/exec')('lilacs add test/index');
|
(function(){
'use strict';
// Criando o module
angular.module('myApp.beers', ['ngRoute'
, 'myApp.beers.filters'
, 'myApp.beers.services'
, 'myApp.beers.controllers'
, 'myApp.beers.directives'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/beers', {
templateUrl: 'beers/beers.html',
controller: 'BeerListController'
})
.when('/beers/create', {
templateUrl: 'beers/create.html',
controller: 'BeerCreateController'
})
.when('/beers/:id', {
templateUrl: 'beers/get.html',
controller: 'BeerGetController'
})
.when('/beers/:id/edit', {
templateUrl: 'beers/edit.html',
controller: 'BeerEditController'
})
;
}])
;
})(); |
define([ "Segment" ], function(Segment)
{
function Segment6UI()
{
this.createGeometry = function()
{
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(0, 0, 0)); // 0
geometry.vertices.push(new THREE.Vector3(0, 3, 0)); // 1
geometry.vertices.push(new THREE.Vector3(3, 3, 0)); // 2
geometry.vertices.push(new THREE.Vector3(0, 0, -3)); // 3
geometry.vertices.push(new THREE.Vector3(-3, 3, -3)); // 4
geometry.vertices.push(new THREE.Vector3(3, 3, -3));// 5
geometry.vertices.push(new THREE.Vector3(3, -3, -3)); // 6
geometry.vertices.push(new THREE.Vector3(0, -3, -3)); // 7
geometry.faces.push(new THREE.Face3(0, 1, 4));
geometry.faces.push(new THREE.Face3(0, 2, 1));
geometry.faces.push(new THREE.Face3(0, 3, 7));
geometry.faces.push(new THREE.Face3(0, 4, 3));
geometry.faces.push(new THREE.Face3(0, 5, 2));
geometry.faces.push(new THREE.Face3(0, 6, 5));
geometry.faces.push(new THREE.Face3(0, 7, 6));
geometry.faces.push(new THREE.Face3(1, 2, 5));
geometry.faces.push(new THREE.Face3(1, 5, 4));
geometry.faces.push(new THREE.Face3(3, 4, 5));
geometry.faces.push(new THREE.Face3(3, 5, 6));
geometry.faces.push(new THREE.Face3(3, 6, 7));
geometry.computeFaceNormals();
geometry.computeVertexNormals();
return geometry;
};
var geometry = this.createGeometry();
this.geometry = function()
{
return geometry;
};
this.segmentKey = function()
{
return Segment.SIX;
};
}
if (Object.freeze)
{
Object.freeze(Segment6UI);
}
return Segment6UI;
});
|
/*jslint node: true */
/*global angular */
'use strict';
angular.module('canvassTrac')
.directive('cnvtrcAddrWidget', function() {
return {
restrict: 'E', // restrict the directive declaration style to element name
scope: { // new "isolate" scope
'addrInfo': '=info', // bidirectional binding
'showBadge': '=badge',
'debug': '='
},
templateUrl: 'canvasses/address.element.html'
};
})
.controller('CanvassAddressController', CanvassAddressController);
/* Manually Identify Dependencies
https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y091
*/
CanvassAddressController.$inject = ['$scope', '$state', '$stateParams', '$filter', 'addressFactory', 'NgDialogFactory', 'utilFactory', 'miscUtilFactory', 'controllerUtilFactory', 'pagerFactory', 'storeFactory', 'consoleService', 'resourceFactory', 'RES', 'RESOURCE_CONST', 'SCHEMA_CONST'];
function CanvassAddressController($scope, $state, $stateParams, $filter, addressFactory, NgDialogFactory, utilFactory, miscUtilFactory, controllerUtilFactory, pagerFactory, storeFactory, consoleService, resourceFactory, RES, RESOURCE_CONST, SCHEMA_CONST) {
var con = consoleService.getLogger('CanvassAddressController');
con.log('CanvassAddressController id', $stateParams.id);
pagerFactory.addPerPageOptions($scope, 5, 5, 4, 1); // 4 opts, from 5 inc 5, dflt 10
setupGroup(RES.ASSIGNED_ADDR, 'Assigned');
setupGroup(RES.UNASSIGNED_ADDR, 'Unassigned');
// Bindable Members Up Top, https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y033
$scope.filterList = filterList;
$scope.updateList = updateList;
$scope.sortList = sortList;
var anyNonBlankQuery = resourceFactory.buildMultiValModelPropQuery(
// $or=field1=value1,field2=value2....
RESOURCE_CONST.QUERY_OR,
addressFactory.getModelPropList({
type: SCHEMA_CONST.FIELD_TYPES.STRING, // get list of properties of type STRING
}),
function () {
return RESOURCE_CONST.QUERY_NBLANK;
}
);
requestAddressCount(); // get database total address count
/* function implementation
-------------------------- */
function setupGroup(id, label) {
$scope[id] = addressFactory.newList(id, {
title: label,
flags: storeFactory.CREATE_INIT
});
var filter = RES.getFilterName(id);
$scope[filter] = storeFactory.newObj(filter, newFilter, storeFactory.CREATE_INIT);
var pager = RES.getPagerName(id);
$scope[pager] = pagerFactory.newPager(pager, [], 1, $scope.perPage, 5);
setFilter(id, $scope[filter]);
addressFactory.setPager(id, $scope[pager]);
}
function newFilter (base) {
// new filter no blanks
return addressFactory.newFilter(base, { allowBlank: false });
}
function setFilter (id, filter) {
// unassignedAddrFilterStr or assignedAddrFilterStr
var filterStr = RES.getFilterStrName(id);
if (!filter) {
filter = newFilter();
}
$scope[filterStr] = filter.toString();
return addressFactory.setFilter(id, filter);
}
function sortList (resList) {
return resList.sort();
}
function filterList (resList, btn) {
var action = btn.cmd;
if (action === 'c') { // clear filter
setFilter(resList.id);
if (resList.id === RES.UNASSIGNED_ADDR) {
resList.setList([]); // clear list of addresses
}
resList.applyFilter();
} else if (action === 'a') { // no filter, get all
setFilter(resList.id);
requestAddresses(resList, anyNonBlankQuery); // request all addresses
} else { // set filter
var filter = angular.copy(resList.filter.getFilterValue());
var dialog = NgDialogFactory.open({ template: 'address/addressfilter.html', scope: $scope, className: 'ngdialog-theme-default', controller: 'AddressFilterController',
data: {action: resList.id, title: resList.title, filter: filter}});
dialog.closePromise.then(function (data) {
if (!NgDialogFactory.isNgDialogCancel(data.value)) {
var filter = newFilter(data.value.filter);
var resList = setFilter(data.value.action, filter);
if (resList) {
if (resList.id === RES.UNASSIGNED_ADDR) {
// request filtered addresses from server
requestAddresses(resList, filter);
} else {
resList.applyFilter();
}
}
}
});
}
}
function requestAddresses (resList, filter) {
addressFactory.getFilteredResource('address', resList, filter,
// success function
function (response) {
if (!response.length) {
NgDialogFactory.message('No addresses found', 'No addresses matched the specified criteria');
}
$scope.setItemSel(resList, miscUtilFactory.CLR_SEL);
requestAddressCount();
},
// error function
function (response) {
NgDialogFactory.error(response, 'Unable to retrieve addresses');
}
); // get database total address count
}
function requestAddressCount () {
$scope.dbAddrCount = addressFactory.get('count', anyNonBlankQuery,
// success function
function (response) {
$scope.dbAddrCount = response.count; // total count
},
// error function
function (response) {
NgDialogFactory.error(response, 'Unable to retrieve address count');
}
);
}
function updateList (fromList, toList) {
controllerUtilFactory.moveListSelected(fromList, toList, function (item1, item2) {
return (item1._id === item2._id);
});
}
}
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["id", "buttonProps", "buttonText", "canCancel", "cancelButtonText", "disabled", "errorText", "fileInputProps", "fileName", "loaderAnimation", "onCancel", "onUpload", "status", "statusText"];
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import COLORS from '../../../../constants/colors-config';
import { pxToRem } from '../../../../helpers/utils/typography';
import { Button } from '../../../action/button';
import { modifierStyles } from '../../../action/button/helpers/modifier-styles';
import { Text } from '../../../typography/text';
import classNames from 'classnames';
import { UploadIcon } from '../../../graphics/icons/upload-icon';
import { CheckedCircleIcon } from '../../../graphics/icons/checked-circle-icon';
import { CrossCircleIcon } from '../../../graphics/icons/cross-circle-icon';
import { ClockCircleIcon } from '../../../graphics/icons/clock-circle-icon';
import { CrossIcon } from '../../../graphics/icons/cross-icon';
import { VisuallyHidden } from '../../../accessibility/visually-hidden';
import { Loader } from '../../../graphics/animations/loader';
var StyledBasicUploader = styled.div.withConfig({
displayName: "basic-uploader__StyledBasicUploader",
componentId: "sc-5ptyqe-0"
})(["input[type='file']{border:0;clip-path:inset(100%);height:1px;overflow:hidden;padding:0;position:absolute !important;white-space:nowrap;width:1px;}input[type='file']:focus + label{background-color:", ";border-color:", ";color:", ";svg,path{fill:", ";}}input[type='file']:focus-visible + label{outline:auto;}&:not(.k-BasicUploader--loading){input[type='file']:disabled + label{border-color:", ";background-color:", ";color:", ";pointer-events:none;svg,path{fill:", ";}}}.k-BasicUploader__statusBlock{margin-top:", ";display:flex;& > * + *{margin-left:", ";}}.k-BasicUploader__cancelButton{width:", ";height:", ";cursor:pointer;padding:0;display:flex;justify-content:center;align-items:center;", "}"], COLORS.primary2, COLORS.primary2, COLORS.background1, COLORS.background1, COLORS.line2, COLORS.line2, COLORS.background1, COLORS.background1, pxToRem(15), pxToRem(10), pxToRem(20), pxToRem(20), modifierStyles('beryllium'));
var statusesWithIcons = ['error', 'valid', 'wait'];
export var BasicUploader = function BasicUploader(_ref) {
var id = _ref.id,
_ref$buttonProps = _ref.buttonProps,
buttonProps = _ref$buttonProps === void 0 ? {} : _ref$buttonProps,
_ref$buttonText = _ref.buttonText,
buttonText = _ref$buttonText === void 0 ? 'Document' : _ref$buttonText,
_ref$canCancel = _ref.canCancel,
canCancel = _ref$canCancel === void 0 ? false : _ref$canCancel,
_ref$cancelButtonText = _ref.cancelButtonText,
cancelButtonText = _ref$cancelButtonText === void 0 ? 'Cancel and reupload' : _ref$cancelButtonText,
_ref$disabled = _ref.disabled,
disabled = _ref$disabled === void 0 ? false : _ref$disabled,
_ref$errorText = _ref.errorText,
errorText = _ref$errorText === void 0 ? '' : _ref$errorText,
_ref$fileInputProps = _ref.fileInputProps,
fileInputProps = _ref$fileInputProps === void 0 ? {} : _ref$fileInputProps,
_ref$fileName = _ref.fileName,
fileName = _ref$fileName === void 0 ? '' : _ref$fileName,
_ref$loaderAnimation = _ref.loaderAnimation,
loaderAnimation = _ref$loaderAnimation === void 0 ? /*#__PURE__*/React.createElement(Loader, null) : _ref$loaderAnimation,
_ref$onCancel = _ref.onCancel,
onCancel = _ref$onCancel === void 0 ? function () {} : _ref$onCancel,
_ref$onUpload = _ref.onUpload,
onUpload = _ref$onUpload === void 0 ? function () {} : _ref$onUpload,
_ref$status = _ref.status,
status = _ref$status === void 0 ? 'ready' : _ref$status,
_ref$statusText = _ref.statusText,
statusText = _ref$statusText === void 0 ? '' : _ref$statusText,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
var _useState = useState(status),
internalStatus = _useState[0],
setInternalStatus = _useState[1];
useEffect(function () {
setInternalStatus(status);
}, [status]);
var _useState2 = useState(disabled),
internalDisabled = _useState2[0],
setInternalDisabled = _useState2[1];
useEffect(function () {
setInternalDisabled(disabled);
}, [disabled]);
var _useState3 = useState(''),
internalFileName = _useState3[0],
setInternalFileName = _useState3[1];
var _useState4 = useState(canCancel),
internalCanCancel = _useState4[0],
setInternalCanCancel = _useState4[1];
useEffect(function () {
setInternalCanCancel(canCancel);
}, [canCancel]);
useEffect(function () {
if (errorText !== '') {
setInternalStatus('error');
}
}, [errorText]);
var onFileInputChange = function onFileInputChange(event) {
var files = event.currentTarget.files;
if (files.length < 1) return;
var tempFileName = files[0].name;
var tempText = files.length > 1 ? tempFileName + " + " + (files.length - 1) : tempFileName;
setInternalStatus('file-selected');
setInternalCanCancel(true);
setInternalFileName(tempText);
setInternalDisabled(true);
onUpload(event);
};
var onCancelButtonClick = function onCancelButtonClick(event) {
setInternalStatus('ready');
setInternalCanCancel(false);
setInternalDisabled(false);
setInternalFileName('');
onCancel(event);
};
return /*#__PURE__*/React.createElement(StyledBasicUploader, _extends({}, props, {
className: classNames('k-BasicUploader', props.className, "k-BasicUploader--" + internalStatus)
}), /*#__PURE__*/React.createElement("input", _extends({}, fileInputProps, {
type: "file",
id: id,
onChange: onFileInputChange,
disabled: internalDisabled || internalStatus === 'loading'
})), /*#__PURE__*/React.createElement(Button, _extends({
fit: "fluid"
}, buttonProps, {
as: "label",
htmlFor: id,
className: classNames('k-BasicUploader__button', buttonProps.className)
}), internalStatus === 'loading' ? loaderAnimation : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UploadIcon, {
"aria-hidden": true,
className: "k-BasicUploader__button__uploadIcon k-u-margin-right-singleHalf"
}), /*#__PURE__*/React.createElement("span", null, buttonText))), internalStatus !== 'ready' && /*#__PURE__*/React.createElement("div", {
className: "k-BasicUploader__statusBlock"
}, internalCanCancel && /*#__PURE__*/React.createElement("button", {
className: "k-BasicUploader__cancelButton",
onClick: onCancelButtonClick
}, /*#__PURE__*/React.createElement(CrossIcon, null), /*#__PURE__*/React.createElement(VisuallyHidden, null, cancelButtonText)), !internalCanCancel && statusesWithIcons.includes(internalStatus) && /*#__PURE__*/React.createElement("div", {
className: "k-BasicUploader__statusIcon"
}, internalStatus === 'valid' && /*#__PURE__*/React.createElement(CheckedCircleIcon, {
circleColor: COLORS.valid,
checkedColor: COLORS.background1,
width: 20,
height: 20,
"aria-hidden": true
}), internalStatus === 'error' && /*#__PURE__*/React.createElement(CrossCircleIcon, {
circleColor: COLORS.error,
crossColor: COLORS.background1,
width: 20,
height: 20,
"aria-hidden": true
}), internalStatus === 'wait' && /*#__PURE__*/React.createElement(ClockCircleIcon, {
circleColor: COLORS.primary1,
clockColor: COLORS.background1,
width: 20,
height: 20,
"aria-hidden": true
})), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Text, {
tag: "p",
weight: "regular",
color: internalStatus === 'error' ? 'error' : 'font1',
size: "tiny",
lineHeight: "normal",
className: "k-BasicUploader__statusTitle k-u-margin-none k-u-line-height-1-3"
}, internalStatus === 'file-selected' ? internalFileName : errorText === '' ? fileName : errorText), /*#__PURE__*/React.createElement(Text, {
tag: "p",
weight: "light",
color: internalStatus === 'error' ? 'error' : 'font1',
size: "micro",
lineHeight: "normal",
className: "k-BasicUploader__statusSubtitle k-u-margin-none k-u-margin-top-noneHalf k-u-line-height-1-3"
}, statusesWithIcons.includes(internalStatus) && statusText))));
};
BasicUploader.propTypes = {
id: PropTypes.string.isRequired,
buttonProps: PropTypes.object,
buttonText: PropTypes.string,
canCancel: PropTypes.bool,
cancelButtonText: PropTypes.string,
disabled: PropTypes.bool,
errorText: PropTypes.string,
fileInputProps: PropTypes.object,
fileName: PropTypes.string,
onCancel: PropTypes.func,
onUpload: PropTypes.func,
status: PropTypes.oneOf(['ready', 'error', 'valid', 'wait', 'loading']),
statusText: PropTypes.string
}; |
var util = require('util');
var stream = require('stream');
var syslog = require('strong-fork-syslog');
var initialized = false;
module.exports = SysLogStream;
function SysLogStream(options) {
if (!(this instanceof SysLogStream)) return new SysLogStream(options);
stream.Writable.call(this);
this.level = syslog.LOG_NOTICE;
if (typeof options.level === 'number') {
this.level = options.level;
} else if (typeof options.level === 'string') {
if (options.level.toUpperCase() in syslog) {
this.level = syslog[options.level];
} else if ('LOG_' + options.level.toUpperCase() in syslog) {
this.level = syslog['LOG_' + options.level.toUpperCase()];
}
}
if (!initialized) {
// XXX(rmg): would be nice to use the same name as strong-agent does,
// ideally without duplicating the logic for deriving it.
syslog.init(process.title,
syslog.LOG_PID | syslog.LOG_ODELAY,
syslog.LOG_USER);
initialized = true;
}
}
util.inherits(SysLogStream, stream.Writable);
SysLogStream.prototype.reOpen = function SysLogStreamReOpen() {
// no-op!
};
SysLogStream.prototype._write = function _write(chunk, encoding, callback) {
syslog.log(this.level, chunk.toString().trim());
setImmediate(callback);
return true;
};
|
import React, { PropTypes } from "react";
import DocumentTitle from "react-document-title";
import { connect } from "react-redux";
import { Link } from "react-router";
import { bindActionCreators } from "redux";
import * as PhotoActions from "actions/FiveHundredPx/PhotoActions";
import PhotoList from "components/PhotoList/PhotoList";
import styles from "./PhotosPage.sass";
import fa from "font-awesome/css/font-awesome.css";
@connect(({ fivehundredpx }) => {
return {
loading: fivehundredpx.loading,
photos: fivehundredpx.photos,
error: fivehundredpx.error,
};
})
class PhotosPage extends React.Component {
static propTypes = {
loading: PropTypes.bool.isRequired,
photos: PropTypes.arrayOf(PropTypes.object).isRequired,
error: PropTypes.object,
};
loadPhotos(event) {
event.preventDefault();
const { error, dispatch } = this.props;
const actions = bindActionCreators(PhotoActions, dispatch);
actions.getNextPage();
}
render() {
const { loading, error, photos } = this.props;
return (
<DocumentTitle title="Photos from 500px">
<div>
<h1>Photos</h1>
<Link to="/">Home</Link>
<hr />
{
error
? <p className={styles.error}>{error.status} - {error.statusText}</p>
: null
}
{
loading
? <p>
<i className={`${fa.fa} ${fa["fa-spinner"]} ${fa["fa-spin"]} ${styles.spinner}`} />
Loading...
</p>
: null
}
{
photos.length == 0 && !loading
? <button type="button" onClick={::this.loadPhotos}>
Load Photos
</button>
: null
}
<PhotoList photos={photos} />
</div>
</DocumentTitle>
);
}
}
export default PhotosPage;
|
'use strict';
var path = require('path');
var passport = require('passport');
var async = require('async');
var _ = require('lodash');
var Loader = require('strider-extension-loader');
var globalTunnel = require('global-tunnel');
var app = require('./lib/app');
var common = require('./lib/common');
var config = require('./lib/config');
var middleware = require('./lib/middleware');
var auth = require('./lib/auth');
var models = require('./lib/models');
var pluginTemplates = require('./lib/plugin-templates');
var utils = require('./lib/utils');
var apiConfig = require('./lib/routes/api/config');
var upgrade = require('./lib/models/upgrade').ensure;
var loadExtensions = require('./lib/utils/load-extensions');
var pkg = require('./package');
var Job = models.Job;
var Config = models.Config;
common.extensions = {};
//
// Use globa-tunnel to provide proxy support.
// The http_proxy environment variable will be used if the first parameter to globalTunnel.initialize is null.
//
globalTunnel.initialize();
//
// ### Register panel
//
// A panel is simply a snippet of HTML associated with a given key.
// Strider will output panels registered for specific template.
//
function registerPanel(key, value) {
// Nothing yet registered for this panel
key = value.id;
console.log('!! registerPanel', key)
if (common.extensions[key] === undefined) {
common.extensions[key] = { panel: value };
} else {
if (common.extensions[key].panel) {
console.log('!!', key, common.extensions[key], value);
throw 'Multiple Panels for ' + key;
}
common.extensions[key].panel = value;
}
}
module.exports = function(extdir, c, callback) {
var appConfig = config;
var k;
// override with c
for (k in c) {
appConfig[k] = c[k];
}
// Initialize the (web) app
var appInstance = app.init(appConfig);
var cb = callback || function(err) {
if (err) throw err;
}
if (typeof Loader !== 'function') {
throw new Error('Your version of strider-extension-loader is out of date');
}
var loader = new Loader([path.join(__dirname, 'client/styles')], true);
appInstance.loader = loader;
common.loader = loader;
//
// ### Strider Context Object
//
// Context object is passed to each extension. It carries various config
// settings, as well as handles to enable functions to register things.
// Context can also be accessed as a singleton within Strider as
// common.context.
var context = {
serverName: appConfig.strider_server_name,
config: appConfig,
enablePty: config.enablePty,
emitter: common.emitter,
extensionRoutes: [],
extensionPaths: extdir,
extdir: extdir,
loader: loader,
models: models,
logger: console,
middleware: middleware,
auth: auth, //TODO - may want to make this a subset of the auth module
passport: passport,
registerPanel: registerPanel,
registerBlock: pluginTemplates.registerBlock,
app: appInstance
};
// Make extension context available throughout application.
common.context = context;
var SCHEMA_VERSION = Config.SCHEMA_VERSION;
upgrade(SCHEMA_VERSION, function (err) {
if (err) return cb(err)
loadExtensions(loader, extdir, context, appInstance, function (err) {
// kill zombie jobs
killZombies(function () {
var tasks = [];
if (!common.extensions.runner || 'object' !== typeof common.extensions.runner) {
console.error('Strider seems to have been misconfigured - there are no available runner plugins. ' +
'Please make sure all dependencies are up to date.');
process.exit(1);
}
Object.keys(common.extensions.runner).forEach(function (name) {
var runner = common.extensions.runner[name];
if (!runner) {
console.log('no runner', name);
return;
}
tasks.push(function (next) {
Job.find({
'runner.id': name,
finished: null
}, function (err, jobs) {
if (err) {
return next(err);
}
runner.findZombies(jobs, next);
});
})
});
async.parallel(tasks, function (err, zombies) {
if (err) return cb(err);
var ids = [].concat.apply([], zombies).map(function (job) { return job._id });
var now = new Date();
Job.update({_id: {$in: ids}}, {$set: {finished: now, errored: true, error: {message: 'Job timeout', stack: ''}}}, function (err) {
Job.update({_id: {$in: ids}, started: null}, {$set: {started: now}}, function (err) {
cb(err, appInstance);
});
});
});
});
});
});
return appInstance;
}
function killZombies(done) {
console.log('Marking zombie jobs as finished...');
Job.update({archived: null, finished: null},
{$set: {finished: new Date(), errored: true}}, {multi: true},
function(err, count) {
if (err) throw err;
console.log('%d zombie jobs marked as finished', count);
done();
}
);
}
|
const lineClient = {
post: jest.fn(),
get: jest.fn(),
};
export default lineClient;
|
var _ = require("underscore");
var fs = require("fs");
function Juego(){
this.nombre="Niveles";
this.niveles=[];
this.usuarios=[];
this.resultados=[];
this.agregarNivel=function(nivel){
this.niveles.push(nivel);
}
this.agregarUsuario=function(usuario){
this.usuarios.push(usuario);
}
this.obtenerUsuario=function(id){
return _.find(this.usuarios,function(usu){
return usu._id==id;
});
}
this.obtenerUsuarioLogin=function(email,password){
return _.find(this.usuarios,function(usu){
return (usu.email==email && usu.password==password);
});
}
this.agregarResultado=function(resultado){
this.resultados.push(resultado);
}
}
function JuegoFM(archivo){
this.juego=new Juego();
this.array=leerCoordenadas(archivo);
this.makeJuego=function(juego,array){
var indi=0;
array.forEach(function(ele){
console.log(ele.gravedad);
console.log(ele.coord);
var nivel=new Nivel(indi,ele.coord,ele.gravedad);
juego.agregarNivel(nivel);
indi++;
});
return juego;
}
}
function leerCoordenadas(archivo){
var array=JSON.parse(fs.readFileSync(archivo));
//console.log(array);
return array;
}
function Nivel(num,coord,gravedad){
this.nivel=num;
this.coordenadas=coord;
this.gravedad=gravedad;
}
function Usuario(nombre){
this.nombre=nombre;
this.nivel=0;
this.esil=nombre;
this.password=undefined;
}
function Usuario(nombre,password){
this.nombre=nombre;
this.nivel=0;
this.email=nombre;
this.password=password;
}
function Resultado(nombre,nivel,tiempo){
this.nombre=nombre;
this.email=nombre;
this.nivel=nivel;
this.tiempo=tiempo;
}
module.exports.JuegoFM=JuegoFM;
module.exports.Juego=Juego;
module.exports.Usuario=Usuario;
module.exports.Resultado=Resultado;
|
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './ArticleContent.scss';
const ArticleContent = function(props) {
return (
<article styleName="container">
<h1 styleName="title">{ props.article.title }</h1>
<div styleName="content" dangerouslySetInnerHTML={{ __html: props.article.body }} />
</article>
);
};
export default CSSModules(ArticleContent, styles);
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(228);
module.exports = __webpack_require__(228);
/***/ }),
/***/ 228:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["ku-Arab"] = {
name: "ku-Arab",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-%n","%n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "٪"
},
currency: {
name: "",
abbr: "",
pattern: ["$-n","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "د.ع."
}
},
calendars: {
standard: {
days: {
names: ["یەکشەممە","دووشەممە","سێشەممە","چوارشەممە","پێنجشەممە","ھەینی","شەممە"],
namesAbbr: ["یەکشەممە","دووشەممە","سێشەممە","چوارشەممە","پێنجشەممە","ھەینی","شەممە"],
namesShort: ["ی","د","س","چ","پ","ھ","ش"]
},
months: {
names: ["کانوونی دووەم","شوبات","ئازار","نیسان","ئایار","حوزەیران","تەمووز","ئاب","ئەیلوول","تشرینی یەکەم","تشرینی دووەم","کانونی یەکەم"],
namesAbbr: ["کانوونی دووەم","شوبات","ئازار","نیسان","ئایار","حوزەیران","تەمووز","ئاب","ئەیلوول","تشرینی یەکەم","تشرینی دووەم","کانونی یەکەم"]
},
AM: ["پ.ن","پ.ن","پ.ن"],
PM: ["د.ن","د.ن","د.ن"],
patterns: {
d: "yyyy/MM/dd",
D: "dddd, dd MMMM, yyyy",
F: "dddd, dd MMMM, yyyy hh:mm:ss tt",
g: "yyyy/MM/dd hh:mm tt",
G: "yyyy/MM/dd hh:mm:ss tt",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "hh:mm tt",
T: "hh:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
/***/ })
/******/ }); |
import { conditional, raw } from 'ember-awesome-macros';
import { computed } from '@ember/object';
import { module, test } from 'qunit';
import { compute } from 'ember-macro-helpers/test-support';
import sinon from 'sinon';
module('Integration | Macro | conditional', function() {
test('returns undefined when doesn\'t exist', function(assert) {
compute({
assert,
computed: conditional('condition', 'expr1', 'expr2'),
strictEqual: undefined
});
});
test('returns first value when true', function(assert) {
compute({
assert,
computed: conditional('condition', 'expr1', 'expr2'),
properties: {
condition: true,
expr1: 'val 1',
expr2: 'val 2'
},
strictEqual: 'val 1'
});
});
test('returns second value when false', function(assert) {
compute({
assert,
computed: conditional('condition', 'expr1', 'expr2'),
properties: {
condition: false,
expr1: 'val 1',
expr2: 'val 2'
},
strictEqual: 'val 2'
});
});
test('doesn\'t calculate when unnecessary', function(assert) {
let callback = sinon.spy();
compute({
computed: conditional(
'condition',
computed(callback),
'expr2'
),
properties: {
condition: false
}
});
assert.notOk(callback.called);
});
test('doesn\'t break when missing third param', function(assert) {
compute({
assert,
computed: conditional('condition', 'expr1'),
properties: {
condition: true,
expr1: 'val 1'
},
strictEqual: 'val 1'
});
});
test('allows third param implicit false', function(assert) {
compute({
assert,
computed: conditional('condition', 'expr1'),
properties: {
condition: false,
expr1: 'val 1'
},
strictEqual: undefined
});
});
test('composable: returns first value when true', function(assert) {
compute({
assert,
computed: conditional(true, raw('val 1'), raw('val 2')),
strictEqual: 'val 1'
});
});
});
|
/* globals blanket, module */
var options = {
modulePrefix: 'ember-web-api',
filter: '//.*ember-web-api/.*/',
antifilter: '//.*(tests|template).*/',
loaderExclusions: [],
enableCoverage: true,
cliOptions: {
lcovOptions: {
outputFile: 'coverage/coverage.dat',
renamer: function(moduleName) {
var expression = /^ember-web-api/;
return moduleName.replace(expression, 'addon') + '.js';
}
},
reporters: ['lcov'],
autostart: true
}
};
if (typeof exports === 'undefined') {
blanket.options(options);
} else {
module.exports = options;
}
|
module.exports = require('./lib/deploy'); |
angular.module('DessertService', []).service('DessertService', function($http,$q, pzConfig) {
function handleResponse(response) {
return response.data
}
this.getDessertList=function(){
return $http.get(pzConfig.DESSERT_RESOURCE_URL)
.then(handleResponse)
}
});
|
BB.Models.TestModel = Backbone.Model.extend({
initialize: function(attributes, config) {
this.id = attributes.name;
this.config = config;
this.view = new BB.Views.TestView({
id: this.id,
model: this,
parent: config.collection.view.el
});
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:3f29521e27b1ef19b97ffa757175e29f2f855ac4cf4e02b62a49aac13caf04b8
size 22885
|
function logout() {
firebase.auth().signOut().then(function() {
window.location.href = "test_unauthorised.html";
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}
function dashboard() {
var user = firebase.auth().currentUser;
if (user!= null) {
user.providerData.forEach(function (profile) {
window.alert("Email: " + profile.email);
});
}
}
|
/* eslint-env browser */
/**
* This class handles logic for opening and closing the navigation drawer
*/
class NavigationController {
/**
* This method sets up the navigation for the site and throws an error is
* anything can't be completed.
*/
constructor() {
this._navDrawer = new window.__npmPublishScripts.NavDrawer();
this._jsdocCollapse = new window.__npmPublishScripts.JSDocCollapse();
this._configureMenuBtn();
}
/**
* This sets up the menu btn to open / close the nav drawer.
*/
_configureMenuBtn() {
const menuBtn = document.querySelector('.js-menu-btn');
if (!menuBtn) {
throw new Error('Unable to find js-menu-btn.');
}
menuBtn.addEventListener('click', () => {
this.toggleNavDrawer();
});
}
/**
* This toggles the nav drawer open and closed
*/
toggleNavDrawer() {
this._navDrawer.toggle();
}
}
window.addEventListener('load', () => {
if (!window.__npmPublishScripts || !window.__npmPublishScripts.NavDrawer) {
throw new Error('self.__npmPublishScripts.NavDrawer is not defined.');
}
window.__npmPublishScripts = window.__npmPublishScripts || {};
window.__npmPublishScripts.navController = new NavigationController();
});
|
'use strict';
class Headers {
constructor(source = null) {
if(!process.env.production && typeof source !== 'object' && !Array.isArray(source)) {
throw new Error(`Header source must be an object, instead found type ${typeof source}`);
}
this._private = {
headers: null,
headerKeys: null,
headerCaseMap: null,
xhr: null,
fetchHeader: null
};
if(source != null) {
if(source instanceof XMLHttpRequest) {
this._private.xhr = source;
}
else if(window.Headers && source instanceof window.Headers) {
this._private.fetchHeader = source;
}
else {
this._private.headers = {};
for(let i in source) {
this._private.headers[i] = source[i];
}
this._private.headerKeys = [];
this._private.headerCaseMap = {};
for(let i in source) {
if(source.hasOwnProperty(i)) {
let _i = i.toLowerCase();
this._private.headerKeys.push(_i);
this._private.headerCaseMap[_i] = i;
}
}
}
}
else {
this._private.headerKeys = [];
this._private.headers = {};
this._private.headerCaseMap = {};
}
}
keys() {
let ret = null;
if(this._private.xhr) {
// XHR responses are stupid and don't return a list of header names. Instead parse them from the getAllResponseHeaders() value
if(this._private.headerKeys == null) {
this._private.headerKeys = this._private.xhr.getAllResponseHeaders().split('\n').map(v => {
let pos = v.indexOf(':');
return v.slice(0, pos === -1 ? null : pos).toLowerCase();
}).filter(v => v);
}
}
else if(this._private.fetchHeader) {
ret = Array.from(this._private.fetchHeader.keys());
}
if(ret == null) {
ret = this._private.headerKeys;
}
return ret;
}
has(name) {
let ret = false;
if(this._private.fetchHeader) {
ret = this._private.fetchHeader.has(name);
}
else {
ret = this.keys().indexOf(name.toLowerCase()) !== -1;
}
return ret;
}
get(name) {
let ret = null;
if(this._private.xhr) {
ret = this._private.xhr.getResponseHeader(name);
}
else if(this._private.fetchHeader) {
ret = this._private.fetchHeader.get(name);
}
else if(this._private.headers) {
let actualName = this._private.headerCaseMap[name.toLowerCase()];
if(actualName) {
ret = this._private.headers[actualName];
}
}
return ret;
}
set(name, value) {
if(!process.env.production && (this._private.xhr || this._private.fetchHeader)) {
throw new Error('Cannot set headers for request object instances');
}
else {
let lowerCaseName = name.toLowerCase();
if(this._private.headerCaseMap[lowerCaseName] != null) {
delete this._private.headers[this._private.headerCaseMap[lowerCaseName]];
}
else {
this._private.headerKeys.push(lowerCaseName);
}
this._private.headerCaseMap[lowerCaseName] = name;
this._private.headers[name] = value;
}
}
remove(name) {
if(!process.env.production && (this._private.xhr || this._private.fetchHeader)) {
throw new Error('Cannot delete headers for request object instances');
}
else {
let lowerCaseName = name.toLowerCase();
if(this._private.headerCaseMap[lowerCaseName] != null) {
this._private.headerKeys.splice(this._private.headerKeys.indexOf(lowerCaseName), 1);
let actualName = this._private.headerCaseMap[lowerCaseName];
delete this._private.headerCaseMap[lowerCaseName];
delete this._private.headers[actualName];
}
}
}
entries() {
let ret = this._private.headers;
if(!ret) {
ret = {};
for(let i of this.keys()) {
ret[i] = this.get(i);
}
}
return ret;
}
[Symbol.iterator]() {
let keys = this.keys(),
index = 0;
return {
next: () => {
let value = null,
done = index >= keys.length;
if(!done) {
value = {
name: keys[index],
value: this.get(keys[index++])
}
}
return {
value: value,
done: done
};
}
}
}
}
module.exports = Headers; |
var path = require('path');
describe("If", function() {
var data = '';
beforeEach(function(done) {
neutrino.run(path.resolve('./examples/if/test.neu'), function(result) {
data = result;
done();
});
});
it("should parse an if statement", function(done) {
expect(data.match(/if/)[0]).toBe('if');
done();
});
}); |
import React from "react";
import { Link } from "@curi/react-dom";
import {
HashSection,
Paragraph,
CodeBlock,
IJS
} from "../../../../../components/package/common";
let routesArgMeta = { title: "routes", hash: "options-routes" };
let argumentsMeta = {
title: "Arguments",
hash: "prepareRoutes-arguments",
children: [routesArgMeta]
};
export let meta = {
title: "prepareRoutes",
hash: "prepareRoutes"
};
export function PrepareRoutesAPI() {
return (
<HashSection meta={meta} tag="h2">
<Paragraph>
The <IJS>prepareRoutes</IJS> function takes an application's routes and
route interactions and returns an object. The returned object will be
passed to <IJS>createRouter</IJS>.
</Paragraph>
<CodeBlock>
{`import { prepareRoutes } from '@curi/router';
let routes = prepareRoutes([
{ name: "Home", path: "" },
// ...
{ name: "Not Found", path: "(.*)" }
]);`}
</CodeBlock>
<Paragraph>
<IJS>prepareRoutes</IJS> creates a reusable routing object, which means
that it can be reused on the server instead of recompiling it for every
request.
</Paragraph>
<HashSection tag="h3" meta={argumentsMeta}>
<HashSection tag="h4" meta={routesArgMeta}>
An array of <Link hash="route-objects">route objects</Link>.
</HashSection>
</HashSection>
</HashSection>
);
}
|
/**
* Taken from jQuery 1
*
* @param obj
* @returns {*}
*/
var $isplainobject = function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || typeof obj !== "object" || obj.nodeType || obj === window ) {
return false;
}
// Not own constructor property must be Object
if (obj.constructor &&
!obj.hasOwnProperty('constructor') &&
!obj.constructor.prototype.hasOwnProperty('isPrototypeOf')) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!obj.hasOwnProperty("constructor") &&
!obj.constructor.prototype.hasOwnProperty('isPrototypeOf') ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( /msie 8\.0/i.test( window.navigator.userAgent ) ) {
for ( key in obj ) {
return obj.hasOwnProperty(key);
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || obj.hasOwnProperty(key);
};
var $extend = function(destination) {
var source, i,property;
for(i=1; i<arguments.length; i++) {
source = arguments[i];
for (property in source) {
if(!source.hasOwnProperty(property)) continue;
if(source[property] && $isplainobject(source[property])) {
if(!destination.hasOwnProperty(property)) destination[property] = {};
$extend(destination[property], source[property]);
}
else {
destination[property] = source[property];
}
}
}
return destination;
};
var $each = function(obj,callback) {
if(!obj) return;
var i;
if(typeof obj.length === 'number') {
for(i=0; i<obj.length; i++) {
if(callback(i,obj[i])===false) return;
}
}
else {
for(i in obj) {
if(!obj.hasOwnProperty(i)) continue;
if(callback(i,obj[i])===false) return;
}
}
};
var $trigger = function(el,event) {
var e = document.createEvent('HTMLEvents');
e.initEvent(event, true, true);
el.dispatchEvent(e);
};
var $triggerc = function(el,event) {
var e = new CustomEvent(event,{
bubbles: true,
cancelable: true
});
el.dispatchEvent(e);
};
|
Alloy.Globals.pageStack = {
navigationWindow: null,
pages: [],
open: function(page) {
Alloy.Globals.pageStack.pages.push(page);
if (OS_IOS) {
if (Alloy.Globals.pageStack.navigationWindow === null) {
Alloy.Globals.pageStack.navigationWindow = Ti.UI.iOS.createNavigationWindow({
window: page
});
Alloy.Globals.pageStack.navigationWindow.open();
} else {
Alloy.Globals.pageStack.navigationWindow.openWindow(page);
}
} else if (OS_MOBILEWEB) {
Alloy.Globals.pageStack.navigationWindow.open(page);
} else {
page.open();
}
},
close: function(page) {
if (OS_IOS) {
Alloy.Globals.pageStack.navigationWindow.closeWindow(page);
} else if (OS_MOBILEWEB) {
Alloy.Globals.pageStack.navigationWindow.close(page);
} else {
page.close();
}
Alloy.Globals.pageStack.pages = _.without(Alloy.Globals.pageStack.pages, page);
},
back: function() {
var page = _.last(Alloy.Globals.pageStack.pages);
Alloy.Globals.pageStack.close(page);
if (Alloy.Globals.pageStack.pages.length == 0 && OS_IOS) {
Alloy.Globals.pageStack.navigationWindow.close();
Alloy.Globals.pageStack.navigationWindow = null;
}
},
home: function() {
while (Alloy.Globals.pageStack.pages.length >= 2) {
Alloy.Globals.pageStack.back();
}
}
};
|
// @Some tuning up after all scripts
//import {playerControls} from './playercontrols'
// // Autoexec History update initiation before page closing/leaving, both to localStorage and DB
window.addEventListener('beforeunload', function(e) {
console.log('Leaving the page');
var scope = angular.element(document.getElementById("historywrapper")).scope();
scope.$apply(function() {
scope.updateHistory();
})
});
// // Return an element index in scope and expand detailed popup/modal
function expand (index) {
let id = index.getAttribute("href").toString();
id = id.slice(1);
var scope = angular.element(document.getElementById("MovieCarousel")).scope();
scope.$apply(function() {
scope.expand(id);
});
return false;
};
// // Expand detailed popup/modal from history dropdowns
function popupme (index) {
var scope = angular.element(document.getElementById("MovieCarousel")).scope();
scope.$apply(function() {
scope.expand(index);
});
return false;
};
// // Carousel pause / cycle upon modal events
$('#MovieModal').on('show.bs.modal', function () {
$('#MovieCarousel').carousel('pause');
});
$('#MovieModal').on('hidden.bs.modal', function () {
$('#MovieCarousel').carousel('cycle');
//$("#mmVideo")[0].pause(); // that works as well as trigger below
if (!($("#mmVideo").prop('paused'))) $("#mmVideo").trigger('pause');
$("#mmVideo").unbind('pause');
$("#mmVideo").unbind('ended');
});
// // Navigation for modals && body
$().ready(function(){
// Helper function for focusing
function focusit(obj) {
return setTimeout(function() {
obj.focus();
//console.log('Focus transferred to:', obj);
}, 10);
};
// Binding focus handlers to History elements
var histbtn = $('#dropdownHistory');
$(".dropdown").on("show.bs.dropdown", function(event) {
var dropdown = $(event.target).children('ul.dropdown-menu');
var clearbtn = dropdown.children('li.btn.btn-warning');
var links = dropdown.children('div#dropHistoryContent').children('li').find('span.btn.btn-link');
focusit(clearbtn);
// history clear button
clearbtn.keydown(function(e){
if (e.which == 13) {
this.click()
.off('click');
focusit(histbtn);
};
if (e.which == 38) {
if (links.length != 0) focusit(links[links.length-1]);
};
if (((e.which == 40) || (e.which == 9)) && links.length != 0) {
e.stopPropagation();
focusit(links[0]);
};
});
// movie instances events
if (links.length > 0) {
links.each(function(index){
$(this).keydown(function(e){
if (e.which == 13) {
this.click()
//.off('click');
};
if (e.which == 38) {
if (index !=0) {
focusit(links[index-1]);
} else {
focusit(clearbtn);
}
};
if ((e.which == 40) || (e.which == 9)) {
e.stopPropagation();
if (index < (links.length-1)) {
focusit(links[index+1]);
} else {
focusit(clearbtn);
}
};
});
});
}
});
$(".dropdown").on("hidden.bs.dropdown", function(event) {
focusit(histbtn);
});
// Binding focus handlers for movie box
$('#MovieModal').on('shown.bs.modal', function () {
var closebtn = $('.modal-footer>button');
var play = $('#mmPlay'),
progress = $('#mmProgress'),
mute = $('#mmMute'),
volume = $('#mmVolume'),
sized = $('#mmFull');
focusit(play);
// Controls
play.keydown(function(e){
if ((e.which == 9) || (e.which == 39)) {
e.preventDefault();
focusit(progress);
}
if (e.which == 37) {
focusit(closebtn);
}
});
progress.keydown(function(e){
if ((e.which == 39) || (e.which == 9)) {
e.preventDefault();
focusit(mute);
}
if (e.which == 37) {
e.preventDefault();
focusit(play);
}
});
mute.keydown(function(e){
if ((e.which == 9) || (e.which == 39)) {
e.preventDefault();
focusit(volume);
}
if (e.which == 37) {
focusit(progress);
}
});
volume.keydown(function(e){
if ((e.which == 39) || (e.which == 9)) {
e.preventDefault();
focusit(sized);
}
if (e.which == 37) {
e.preventDefault();
focusit(mute);
}
});
sized.keydown(function(e){
if ((e.which == 9) || (e.which == 39)) {
e.preventDefault();
focusit(closebtn);
}
if (e.which == 37) {
focusit(volume);
}
});
// Close modal button
closebtn.keydown(function(e){
e.stopPropagation();
if ((e.which == 40) || (e.which == 39) || (e.which == 9)) {
focusit(play);
}
if ((e.which == 37) || (e.which == 38)) {
focusit(sized);
}
});
});
$('#MovieModal').on('hide.bs.modal', function () {
focusit(histbtn); // temporary
});
// Other body active elements events
var mylink = $('#myRepLink');
var leftControl = $('a.left.carousel-control');
var rightControl = $('a.right.carousel-control');
histbtn.keydown(function(e){
e.stopPropagation();
if ((e.which == 38) || (e.which == 40)) {
e.preventDefault();
focusit(mylink);
}
if ((e.which == 37) || (e.which == 9)) {
focusit(leftControl);
}
if (e.which == 39) {
focusit(rightControl);
}
});
mylink.keydown(function(e){
if ((e.which == 38) || (e.which == 40) || (e.which == 9)) {
e.preventDefault();
focusit(histbtn);
}
if (e.which == 37) {
focusit(leftControl);
}
if (e.which == 39) {
focusit(rightControl);
}
});
leftControl.keydown(function(e){
if (e.which == 38) {
focusit(histbtn);
}
if (e.which == 40) {
focusit(mylink);
}
if ((e.which == 39) || (e.which == 9)) {
e.stopPropagation();
$('#MovieCarousel').carousel('pause');
focusit(firstSlide);
return false;
}
});
rightControl.keydown(function(e){
if (e.which == 38) {
focusit(histbtn);
}
if (e.which == 40) {
focusit(mylink);
}
if (e.which == 37) {
e.stopPropagation();
$('#MovieCarousel').carousel('pause');
focusit(lastSlide);
return false;
}
});
// Binding focus hadlers to slides
var firstSlide = '';
var lastSlide = '';
$('#MovieCarousel').bind('slid.bs.carousel', function (event) {
var activeSlider = $('div.item.active').children();
var slides = [];
$.each(activeSlider, function() {
if ($(this).css('display') == 'block') slides.push($(this).children('a').first());
});
firstSlide = slides[0];
lastSlide = slides[slides.length-1];
$.each(slides, function(index){
$(this).keydown(function(e){
e.stopPropagation();
if (((e.which == 39) || (e.which == 9)) && (index != (slides.length-1))) {
focusit(slides[index+1]);
return false;
}
if (((e.which == 39) || (e.which == 9)) && (index = (slides.length-1))) {
$('#MovieCarousel').carousel('cycle');
focusit(rightControl);
return false;
}
if ((e.which == 37) && (index != 0)) {
focusit(slides[index-1]);
return false;
}
if ((e.which == 37) && (index = 1)) {
$('#MovieCarousel').carousel('cycle');
focusit(leftControl);
return false;
}
});
});
});
});
// @@Custom player controls for video player
window.onload = function () {
var video = document.getElementById('mmVideo');
var play = document.getElementById('mmPlay');
var cTime = document.getElementById('mmCurrentTime');
var tTime = document.getElementById('mmTotalTime');
var progress = document.getElementById('mmProgress');
var mute = document.getElementById('mmMute');
var volume = document.getElementById('mmVolume');
var sized = document.getElementById('mmFull');
// Play/Pause cycle
play.addEventListener("click", function() {
if (video.paused) {
video.play();
play.innerHTML = '<span class="glyphicon glyphicon-pause" aria-hidden="false"></span>';
//setTimeout(function(){cTime.innerHTML = parseTime(video.currentTime)},1000); // or move to timeupdate listener below
} else {
video.pause();
play.innerHTML = '<span class="glyphicon glyphicon-play" aria-hidden="false"></span>';
}
});
// Volume on / off checker
mute.addEventListener("click", function() {
if (video.muted) {
video.muted = false;
mute.innerHTML = '<span class="glyphicon glyphicon-volume-up" aria-hidden="false"></span>';
} else {
video.muted = true;
mute.innerHTML = '<span class="glyphicon glyphicon-volume-off" aria-hidden="false"></span>';
}
});
// Full screen on / off checker
sized.addEventListener("click", function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen();
}
});
// Movie progress bar tracking / adjustment
progress.addEventListener("change", function() {
var time = (video.duration * (progress.value / 100));
video.currentTime = time;
});
progress.addEventListener("mousedown", function() {
if (!video.paused) {
video.pause(); // to prevent stuck on dragging
play.innerHTML = '<span class="glyphicon glyphicon-play" aria-hidden="false"></span>';
}
});
progress.addEventListener("mouseup", function() {
if (video.paused) {
video.play();
play.innerHTML = '<span class="glyphicon glyphicon-pause" aria-hidden="false"></span>';
}
});
video.addEventListener("timeupdate", function() {
var value = ((100 / video.duration) * video.currentTime);
cTime.innerHTML = parseTime(video.currentTime);
tTime.innerHTML = parseTime(video.duration);
progress.value = value;
});
// Volume bar low / high
volume.addEventListener("change", function() {
video.volume = volume.value;
});
// Helper for time tracking
function m2(time) {
let t = time;
if ((t < 10) && (t > 0)) t = '0' + t;
if (t == 0) t = '00';
return t;
}
function parseTime(time) {
time = Math.floor(time);
let st = '';
let h = 0,
m = 0,
s = 0;
if (time > 3600) {
h = Math.floor(time / 3600);
h = m2(h);
time -= (3600 * h);
st += h + ':';
} else {
st += '00:';
}
if (time > 60) {
m = Math.floor(time / 60);
m = m2(m);
time -= (60 * m);
st += m + ':';
} else {
st += '00:';
}
s = Math.floor(time);
s = m2(s);
st += s;
return st;
}
}
// EOF
|
// Karma configuration
// Generated on Tue Feb 03 2015 18:57:18 GMT+0900 (JST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jspm', 'jasmine'],
// //list of files / patterns to load in the browser
// files: [
// 'client/**/*.js'
// ],
jspm: {
//useBundles: true,
config: 'client/config.js',
packages: 'client/jspm_packages/',
loadFiles: [
'client/app/**/*.spec.js'
],
serveFiles: [
'client/app/**/!(*spec|*mock).js',
'client/**/*.png',
'client/**/*.ico',
'client/**/*.css',
]
},
proxies: {
'/base/jspm_packages/': '/base/client/jspm_packages/',
},
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
//reporters: ['mocha','progress'],
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
//'Firefox', 'Chrome', 'PhantomJS'
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
|
'use strict';
//---------------------------------------------------------------------------
// File Interface
// Provides the interface between the agent process and the hosts file system
//---------------------------------------------------------------------------
(function() {
//-------------
// Dependencies
//-------------
var chokidar = require('chokidar');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
//------------
// Constructor
//------------
var create = function(config, agentState, adminState) {
//-----------------------------------------------
// Initialize and start the file system interface
//-----------------------------------------------
// config.triggers.forEach(function(trigger){
// console.log("Monitoring: " + trigger.dir);
// var watcher = chokidar.watch(trigger.dir, {ignored: /[\/\\]\./});
// watcher
// .on('add', function(path, event){
// state.addFile(path, trigger.targets);
// });
// });
var watchers = [];
//------------
// Subscribe to adminState events
//------------
adminState.transfer.on('add', function onAdd(resource) {
transferCreated(resource.transfer);
});
adminState.transfer.on('update', function onUpdate(resource, old) {
transferUpdated(resource.transfer, old);
});
adminState.transfer.on('delete', function onDelete(resource, old) {
transferDeleted(old);
});
//------------
// Externals
//------------
function start() {
adminState.transfer.findResources(null , function load(err, transfers) {
if (err) {
console.log('client.onStart error: ' + JSON.stringify(err));
}
else {
_.each(transfers, loadTransfer);
}
});
}
function getFileReadStream(filePath) {
console.log('Getting file read stream: ', filePath);
var rs;
try {
rs = fs.createReadStream(filePath);
} catch (err) {
console.log('Getting file read stream. Encountered error: ', JSON.stringify(err) );
throw err;
}
// rs.on('error', function(err) {
// });
return rs;
}
function moveFile(oldPath, newPath){
console.log('Moving file %s to %s.', oldPath, newPath );
if ( !fs.existsSync(path.dirname(newPath)) ) {
fs.mkdirSync(path.dirname(newPath));
}
fs.rename(oldPath, newPath, function(err){
if (err) {
console.log('Error moving file %s to %s.', oldPath, newPath );
}
});
}
function pushToFile(readableStream, filename, transfer) {
var tmpFolder = (config.runtimeDir.charAt(
config.runtimeDir.length - 1) === '/') ?
config.runtimeDir :
config.runtimeDir + '/';
var finalFolder = (config.outboundDir.charAt(
config.outboundDir.length - 1) === '/') ?
config.outboundDir :
config.outboundDir + '/';
finalFolder += transfer.name + '/';
var file = fs.createWriteStream(tmpFolder + filename);
console.log('Created file readableStream: ' + tmpFolder + filename);
readableStream.pipe(file);
file
.on('finish', function() {
file.close();
})
// TODO may need to be replaced with an event update to hook
// in post processing through agentState.
.on('finish', function() {
moveFile(tmpFolder + filename, finalFolder + filename);
});
return file;
}
//------------
//Internals
//------------
function loadTransfer(transfer) {
var isSource = _.some(transfer.sources, function us(source) {
return source.agentId === config.id;
});
if (isSource) {
console.log('fileinterface.loadTransfer found source');
var dir = config.inboundDir + '/' + transfer.name;
if ( !fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
console.log('Monitoring: ' + dir);
var watcher = chokidar.watch(dir, {ignored: /[\/\\]\./, interval: 5});
watcher.on('add', function(path, event){
console.log('Found new file: %s', path);
agentState.file.addResource({path: path, transferId: transfer.id});
});
}
}
function transferCreated(transfer) {
console.log('transferCreated: ' + transfer.id + ' we are ' + config.id);
loadTransfer(transfer);
}
function transferUpdated(transfer) {
console.log('transferUpdated: ' + transfer.id);
}
function transferDeleted(transfer) {
console.log('transferDeleted: ' + transfer.id);
}
//------------------------------------
// Return the newly created "instance"
//------------------------------------
return {
start : start,
getFileReadStream : getFileReadStream,
pushToFile : pushToFile
};
};
//---------------
// Module exports
//---------------
module.exports.create = function(config, agentState, adminState) {
return create(config, agentState, adminState);
};
}());
|
define('exports-priority@*', [], function(require, exports, module){
exports.a = 2;
module.exports = {
a: 1
};
exports.a = 2;
}); |
angular.module('toptrumps').controller('DuelCtrl', ['$scope', '$state', '$q', 'ngDialog', 'ttGame', 'ttDecks', 'ttBots', function ($scope, $state, $q, ngDialog, ttGame, ttDecks, ttBots) {
/* true when we're getting data we need to set up */
$scope.loading = true;
/* true while waiting for the current player's turn */
$scope.thinking = true;
/* true while submitting training data, so the player doesn't move on to the next card until this finishes */
$scope.learning = false;
/* this should be 'player' or 'computer' depending on whose turn it is next */
$scope.nextturn = 'player';
/* current win streak the computer player has had so far in this game */
$scope.winstreak = 0;
/* best win streak the computer player has had so far in this game */
$scope.beststreak = 0;
/* how many hands of the game has this bot got in it's training data so far? */
$scope.computertraining = 0;
/* matches the values used by the API */
var WIN = 1;
var DRAW = 0;
var LOSE = -1;
/* required info about the game */
$scope.botname = $state.params.botname;
$scope.deckname = $state.params.deckname;
$scope.enemybotname = $state.params.enemybotname;
if (!$state.params.botname || !$state.params.deckname){
return $state.go('welcome');
}
/* does the user have to click between every move? */
$scope.autodraw = $scope.enemybotname ? true : false;
/* the pile of cards for each player */
$scope.decks = {
player : [],
computer : []
};
/* true if we should show the card face, false if we should show the back of the card. */
$scope.show = {
player : true,
computer : false
};
/* messages to cycle around in the UI */
$scope.didyouknow = [
'The player which wins the turn gets to choose for the next turn.',
$scope.botname + ' learns from every turn of the game. With each new card, it should get a little better at knowing what to choose.',
'The information ' + $scope.botname + ' uses to learn from are the numbers on it\'s card, the choice that was made (whether the choice was made by ' + $scope.botname + ' or you), and whether or not it won.',
'When it is ' + $scope.botname + '\'s turn, the only information it uses to choose are the numbers on it\'s own card. It isn\'t peeking at your card. Honest!',
'People have trained machine learning systems to play lots of games before. With about a day\'s training, you can train a ML system to play Super Mario.',
'You are only training ' + $scope.botname + '. This means that if you want to go back to playing against a bot that doesn\'t know how to play, start again with a new bot name.',
'The more examples that ' + $scope.botname + ' has to learn from, the better it can get.',
'The type of machine learning that is being used to train ' + $scope.botname + ' is called a decision tree.',
'Winning or losing a turn are both useful to train ' + $scope.botname + '. Losing isn\'t bad, as it helps train ' + $scope.botname + ' what it should avoid doing.',
'If you want a new bot to learn quickly, give it examples of every attribute choice. If there is any attribute that it has never seen chosen in it\'s training, it wont know when it is good to choose it.',
$scope.botname + ' hasn\'t been given any info about what the values in the deck are for each attribute, or what the rules are. It it learning that from you.'
];
/* Helper function to get the card attributes as a
single object of key/value pairs. This excludes
the name and picture, and keeps only the ones
that are used in playing the game. */
function getCardAttrs (card) {
var values = {};
var attrs = Object.keys($scope.rules);
for (var i = 0; i < attrs.length; i++) {
values[attrs[i]] = card[attrs[i]];
}
return values;
}
/* Helper function to decide which player wins a hand.
Bigger isn't always better, so this uses the rules
for the deck to decide which player wins. */
function calculateResult(key) {
if ($scope.rules[key] === 'higher') {
if ($scope.decks.player[0][key] > $scope.decks.computer[0][key]) {
return WIN;
}
else if ($scope.decks.player[0][key] < $scope.decks.computer[0][key]) {
return LOSE;
}
else if ($scope.decks.player[0][key] === $scope.decks.computer[0][key]) {
return DRAW;
}
}
else if ($scope.rules[key] === 'lower') {
if ($scope.decks.player[0][key] < $scope.decks.computer[0][key]) {
return WIN;
}
else if ($scope.decks.player[0][key] > $scope.decks.computer[0][key]) {
return LOSE;
}
else if ($scope.decks.player[0][key] === $scope.decks.computer[0][key]) {
return DRAW;
}
}
}
function handleGameOver () {
// hacky workaround to disable buttons to stop the game
$scope.learning = true;
// store the winner's name so we can display it
$scope.winner = '';
if ($scope.decks.computer.length === 0) {
$scope.winner = $scope.enemybotname ? $scope.enemybotname : 'You';
}
else {
$scope.winner = $scope.botname;
}
return ngDialog.open({
template : 'app/views/duel/gameover.html',
showClose : false,
closeByEscape : false,
scope : $scope
});
}
function waitForPlayerMove () {
$scope.thinking = true;
if ($scope.enemybotname) {
ttBots.slowPredict($scope.deckname, $scope.enemybotname, getCardAttrs($scope.decks.player[0]))
.then(function (data) {
// decide if the computer won
handleMove(data.choice);
// automatically move on to the next card
setTimeout($scope.drawCard, 600);
});
}
}
function handleMove (key) {
// reveal the computer's card
$scope.show.computer = true;
// work out who won
$scope.selection = key;
$scope.outcome = calculateResult(key);
// display the results
$scope.thinking = false;
}
/* Handles a player's move - invoked when they click on one of
the attributes on their card. */
$scope.userMove = function (key) {
// ignore if it's not their turn!
if ($scope.nextturn === 'player' && $scope.thinking) {
// decide if the player won
handleMove(key);
// wait for the next-card button to be clicked
}
};
/* Makes a move for the computer using the ML model
for this bot. It opens a dialog to display the
computer's move and the outcome. */
function computerMove () {
// displays a placeholder message while getting the prediction
$scope.thinking = true;
ttBots.slowPredict($scope.deckname, $scope.botname, getCardAttrs($scope.decks.computer[0]))
.then(function (data) {
// decide if the computer won
handleMove(data.choice);
// keep track of computer's performance
if ($scope.outcome === LOSE) {
// if the player lost, this means the computer won
// so we increment it's streak counter
$scope.winstreak += 1;
// if this is our best ever score, increment it too
if ($scope.winstreak > $scope.beststreak) {
$scope.beststreak = $scope.winstreak;
}
}
else if ($scope.outcome === WIN) {
// if the player won, this means the computer made
// the wrong choice. so it's streak counter gets reset
$scope.winstreak = 0;
}
if ($scope.autodraw) {
// automatically move on to the next card
setTimeout($scope.drawCard, 600);
}
else {
// wait for the next-card button to be clicked
}
});
}
/* Adds these cards to the training data and then builds a new
ML model using the updated training data */
function learnFromTurn (playercard, computercard) {
var training = [
// learning from the player's hand
{
card : getCardAttrs(playercard),
choice : $scope.selection,
outcome : $scope.outcome
},
// learning from the computer's hand
{
card : getCardAttrs(computercard),
choice : $scope.selection,
// if the player won, the computer lost
// and vice versa.
// if the player drew, then leave the outcome as-is
outcome : $scope.outcome === 0 ? 0 : -($scope.outcome)
}
];
return ttBots.learn($scope.deckname, $scope.botname, training)
.then(function () {
return ttBots.train($scope.deckname, $scope.botname);
})
.then(function (data) {
if (data.status === 'complete') {
// we submit two rows of training data for each
// turn of the game (one representing the player's
// card and outcome, the other representing the
// computer's card and their outcome)
$scope.computertraining = data.hands / 2;
}
});
}
/* Moves on to the next card. Called when the user clicks on the
next-card button. It takes the cards of the top of the two
decks and moves them to the back of the deck for whoever
won the last hand.
It submits the outcome of the last hand to the API to be
added to the training data for the bot.
Once this is all finished, it starts the next move */
$scope.drawCard = function () {
// disable the next-card button so the user can't click
// multiple times and submit duplicate training data
$scope.learning = true;
// hide the computer's card first before changing it
// so we don't give it away
$scope.show.computer = false;
// take the cards off the top of the decks
var playercard = $scope.decks.player.shift();
var computercard = $scope.decks.computer.shift();
// put them to the back of the appropriate decks
if ($scope.outcome === WIN) {
$scope.decks.player.push(playercard);
$scope.decks.player.push(computercard);
}
else if ($scope.outcome === LOSE) {
$scope.decks.computer.push(playercard);
$scope.decks.computer.push(computercard);
}
else {
$scope.decks.player.push(playercard);
$scope.decks.computer.push(computercard);
}
// add these cards to the training data and train a new ML model
learnFromTurn(playercard, computercard)
.then(function () {
$scope.learning = false;
// has the game finished?
// are there any more cards to draw?
if ($scope.decks.player.length === 0 ||
$scope.decks.computer.length === 0)
{
return handleGameOver();
}
if ($scope.outcome === WIN) {
$scope.nextturn = 'player';
}
else if ($scope.outcome === LOSE) {
$scope.nextturn = 'computer';
}
// else if DRAW the nextturn stays the same
// reset the result for this turn
$scope.outcome = undefined;
if ($scope.nextturn === 'player') {
waitForPlayerMove();
}
else if ($scope.nextturn === 'computer') {
computerMove();
}
})
};
//----------------------------------------------
// START THE GAME!
//----------------------------------------------
// get the rules for the deck, needed to know who wins each hand
var decksPromise = ttDecks.get($scope.deckname);
// gets the shuffled, dealt deck
var gamePromise = ttGame.start($scope.deckname);
// wait until both of these are ready before starting
$q.all([ decksPromise, gamePromise ])
.then(function (data) {
$scope.rules = data[0].rules;
$scope.explanations = data[0].explanations;
$scope.decks.player = data[1].playerone;
$scope.decks.computer = data[1].playertwo;
$scope.loading = false;
// wait for the first player to make their move
waitForPlayerMove();
});
}]);
|
var IncomingWebhook = require('@slack/client').IncomingWebhook;
var url = process.env.SLACK_WEBHOOK_URL || ''
var webhook = new IncomingWebhook(url)
var through = require('through2')
var COLORS = {
'FAIL': '#f60000',
'RECOVER': '#36a64f'
}
function sendMail (type, lastPing, ping) {
var text = type + ' ' + ping.url + ' (HTTP ' + ping.status + ')'
var attachments = [
{color: COLORS[type], text: text}
]
if (lastPing) {
attachments.push({color: COLORS[type], text: 'Last success at: ' + new Date(lastPing.timestamp)})
}
var params = {
username: 'upmon-bot',
attachments: attachments
}
webhook.send(params, function(err, res) {
if (err) {
console.err('Error:', err);
}
});
}
var sendFailMail = sendMail.bind(null, 'FAIL')
var sendRecoverMail = sendMail.bind(null, 'RECOVER')
module.exports = function (opts) {
opts = opts || {}
var lastPings = {}
return through.obj(function (ping, enc, cb) {
var lastPing = lastPings[ping.url]
if ((!lastPing || lastPing.status == 200) && ping.status != 200) {
sendFailMail(lastPing, ping)
} else if (lastPing && lastPing.status != 200 && ping.status == 200) {
sendRecoverMail(lastPing, ping)
}
lastPings[ping.url] = ping
this.push(ping)
cb()
})
}
|
import {observable} from 'mobx';
export default class EmailTemplateModel {
@observable id;
@observable subject;
@observable body;
@observable stagingsubject;
@observable stagingbody;
@observable description;
@observable modified;
@observable ModifierID;
@observable published;
@observable PublisherID;
@observable isactived;
@observable categoryID;
constructor(value) {
this.id = id;
this.subject = subject;
this.body = body;
this.stagingsubject = stagingsubject;
this.stagingbody = stagingbody;
this.description = description;
this.modified = modified;
this.ModifierID = ModifierID;
this.published = published;
this.PublisherID = PublisherID;
this.isactived = isactived;
this.categoryID = categoryID;
}
}
|
var express = require('express');
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
passphrase: "thegeeksnextdoor"
};
var app = express();
app.use(express.static(__dirname));
var server = https.createServer(options, app)
var io = require("socket.io").listen(server);
var request = require("request");
//user stores all the sockets
var user = {};
//room stores all the room id
var room = {};
var admin;
var configuration;
var xirsys_details = {
ident : "qwerty",
secret : "53253e00-31f8-11e6-ae89-abe6e64b2707",
domain : "www.thegeeksnextdoor.co",
application : "default",
room : "default",
secure : 0,
}
var opts = {
method: 'GET',
uri: 'https://service.xirsys.com/ice',
body: xirsys_details,
json: true
};
request.get(opts, function(error, response, body){
configuration = body.d;
});
server.listen(8080);
io.on("connection", function(socket){
// new user login
socket.on("login", function(userName){
console.log("User " + userName + " logins");
try {
if (user[userName]){
socket.emit("login", {
type: "login",
userName: userName,
status: "fail"
});
} else{
user[userName] = socket;
user[userName].userName = userName;
socket.emit("login", {
type: "login",
userName: userName,
config: configuration,
status: "success"
});
}}catch (e){
console.log(e);
}
})
// a host create a new room
socket.on("createRoom", function(roomId){
try {
/*if (room[roomId]){
socket.emit("createRoom", {
type: "createRoom",
userName: socket.userName,
room: roomId,
status: "fail"
});
} else{*/
room[roomId] = {};
room[roomId].roomId = roomId;
room[roomId].host = socket.userName;
user[socket.userName].room = roomId;
user[socket.userName].join(roomId);
admin.emit("host", {
type: "host",
host: socket.userName
});
socket.emit("createRoom", {
type: "createRoom",
userName: socket.userName,
room: roomId,
status: "success"
});
// }
}catch (e){
console.log(e);
}
})
// an user join a room
socket.on("joinRoom", function(roomId){
try {
if (room[roomId]){
socket.emit("host", {
type: "host",
host: room[roomId].host
});
user[socket.userName].room = roomId;
user[socket.userName].join(roomId);
/*admin.emit("newUser", {
type: "newUser",
userName: socket.userName,
host: room[roomId].host
});*/
var clientSockets = io.sockets.adapter.rooms[roomId].sockets;
var userList = {};
for (var clientSocket in clientSockets){
userName = io.sockets.connected[clientSocket].userName;
if (socket.userName !== userName){
userList[userName] = userName;
}
}
socket.emit("joinRoom", {
type: "joinRoom",
userList: userList,
userName: socket.userName,
status: "success"
});
} else{
socket.emit("joinRoom", {
type: "joinRoom",
userName: socket.userName,
room: roomId,
status: "fail"
});
}}catch (e){
console.log(e);
}
})
// an user send an offer to peer
socket.on("SDPOffer", function(sdpOffer){
try {
if (user[sdpOffer.remote]){
user[sdpOffer.remote].emit("SDPOffer", {
type: "SDPOffer",
local: sdpOffer.remote,
remote: sdpOffer.local,
offer: sdpOffer.offer
});
}else{
socket.emit("feedback", "Sending Offer: User does not exist or currently offline");
}} catch(e){
console.log(e);
}
})
// an user send an answer to peer
socket.on("SDPAnswer", function(sdpAnswer){
try {
if (user[sdpAnswer.remote]){
user[sdpAnswer.remote].emit("SDPAnswer",{
type: "SDPAnswer",
local: sdpAnswer.remote,
remote: sdpAnswer.local,
answer: sdpAnswer.answer
});
}else{
socket.emit("feedback", "Sending Answer: User does not exist or currently offline");
}} catch(e){
console.log(e);
}
})
// an user send an ICECandidate to peer
socket.on("candidate", function(iceCandidate){
user[iceCandidate.remote].emit("candidate", {
type: "candidate",
local: iceCandidate.remote,
remote: iceCandidate.local,
candidate: iceCandidate.candidate
});
});
// an user disconnect
socket.on("disconnect", function(){
if (socket.userName){
admin.emit("disconnectedUser", {
type: "disconnectedUser",
userName: socket.userName,
host: room[socket.room].host
});
socket.broadcast.to(socket.room).emit("message", {
type: "message",
action: "disconnect",
user: socket.userName,
content: ""
});
user[socket.userName] = null;
}
})
// a new peer connection is asked to be built
socket.on("newPeerConnection", function(userData){
try {
user[userData.host].emit("initConnection", userData.userName);
// console.log("User " + command[1] + " initialise connection to user " + command[2]);
} catch(e){
console.log(e);
}
})
// a peer connection is asked to be deleted
socket.on("deletePeerConnection", function(userData){
try {
user[userData.userName].emit("deleteConnection", userData.userName);
// console.log("User " + command[1] + " initialise connection to user " + command[2]);
} catch(e){
console.log(e);
}
})
// a user send a message
socket.on("message", function(messageData){
socket.broadcast.to(socket.room).emit("message", messageData);
});
// admin is connected
socket.on("admin", function(){
try {
admin = socket;
} catch(e){
console.log(e);
}
});
// when a datachannel of a user is set up ready
socket.on("dataChannelStatus", function(dataChannelStatusData){
socket.emit("dataChannelStatus", dataChannelStatusData);
});
// when user and peer finish transfering their time stamp
socket.on("timeStamp", function(timeStampData){
socket.emit("timeStamp", timeStampData);
});
socket.on("newUser", function(newUserData){
var self = this;
var roomId = user[socket.userName].room;
console.log(roomId);
var host = room[roomId].host;
console.log(host);
admin.emit("newUser", {
type: "newUser",
user: newUserData.user,
room: roomId,
host: host,
latency: newUserData.latency
});
});
})
|
(function() {
console.log("Starting Demo...");
var ctx = window.getContext('2d');
var img = window.getImage("examples/logo.png");
if (ctx && img)
window.setInterval(paint, 50); // paint in 20Hz
function paint() {
ctx.clear();
ctx.fillStyle = 'rgb(255, 100, 50)';
ctx.globalAlpha = 0.5;
ctx.fillRect(10, 10, 100, 100);
ctx.drawImage(img, 120, 10);
ctx.drawImage(img, 120, 74, 64, 32);
ctx.beginPath();
ctx.moveTo(200, 200);
ctx.lineTo(300, 200);
ctx.quadraticCurveTo(300, 300, 200, 300);
ctx.rect(700, 10, 90, 90);
ctx.closePath();
ctx.strokeStyle = 'white';
ctx.lineWidth = 10.0;
ctx.lineCap = 'round';
ctx.stroke();
}
})();
|
'use strict';
const five = require('johnny-five');
const PiIO = require('..');
const board = new five.Board({
io: new PiIO()
});
board.on('ready', function() {
const servo = new five.Servo({
pin: 'GPIO27',
type: 'continuous'
});
servo.cw(0.8);
});
|
var jqImpress = function(jqi, $, undefined) {
$.fn.jqImpress = function(options) {
var settings = $.extend({height:768, width:1024}, options);
return this.each(function() {
var $this = $(this);
$this.children().each(function(index, item) {
var classes = $this.attr("class");
console.log(classes);
if(!classes) {
return
}
var classList = classes.split(/\s+/);
for(var i = 0, length = classList.length;i < length;i++) {
var currentclass = classList[i];
console.log(currentClass)
}
})
})
};
return jqImpress
}(jqImpress, jQuery);
(function(jqi, $, undefined) {
})(jqImpress, jQuery);
|
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/org.apache.cordova.device/www/device.js",
"id": "org.apache.cordova.device.device",
"clobbers": [
"device"
]
},
{
"file": "plugins/org.apache.cordova.splashscreen/www/splashscreen.js",
"id": "org.apache.cordova.splashscreen.SplashScreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"file": "plugins/com.phonegap.plugins.speech/SpeechRecognizer.js",
"id": "com.phonegap.plugins.speech.SpeechRecognizer",
"clobbers": [
"plugins.speechrecognizer"
]
},
{
"file": "plugins/org.apache.cordova.device-motion/www/Acceleration.js",
"id": "org.apache.cordova.device-motion.Acceleration",
"clobbers": [
"Acceleration"
]
},
{
"file": "plugins/org.apache.cordova.device-motion/www/accelerometer.js",
"id": "org.apache.cordova.device-motion.accelerometer",
"clobbers": [
"navigator.accelerometer"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"org.apache.cordova.device": "0.3.0",
"org.apache.cordova.splashscreen": "1.0.0",
"org.apache.cordova.console": "0.2.13",
"com.phonegap.plugins.speech": "1.0.0",
"org.apache.cordova.device-motion": "0.2.11"
}
// BOTTOM OF METADATA
}); |
// _props = {};
/** @param {Entity} e */
// function _onCreate(e, c)
// {
// }
/** @param {Entity} e */
// function _onEnable(e, c)
// {
// }
/** @param {Entity} e @param {number} dt */
// function _onUpdate(e, c, dt)
// {
// }
/** @param {Entity} e */
// function _onDisable(e, c)
// {
// }
/** @param {Entity} e */
// function _onDestroy(e, c)
// {
// }
|
import React, {Component,PropTypes} from 'react';
import {
StyleSheet,
ART,
View,
Easing,
Animated,
LayoutAnimation,
} from 'react-native';
import Svg,{
Circle,
Ellipse,
G,
LinearGradient,
RadialGradient,
Line,
Path,
Polygon,
Polyline,
Rect,
Symbol,
Text,
Use,
Defs,
Stop,
ClipPath,
} from 'react-native-svg';
export default class TestSVG extends Component {
constructor(props) {
super(props);
this._x = -80;
this._y = 50;
this.state = {
animator: new Animated.Value(0),
waterX: 0,
};
}
deduct=(value)=>{
if(value>0){
let _v = Math.min(50, value);
if(this._y<60) this._y +=value;
}
}
componentDidMount() {
this.state.animator.addListener((p) => {
if(this._x>=-1) this._x = -80;
else this._x +=0.3;
requestAnimationFrame(()=>{
if(this._y>-10){
this._y -=0.05;
this.setState({ waterX: -p.value, });
}
else{
//TODO:水满了 闪烁提示用户
}
});
});
this._wave();
}
render() {
return (
<View style={this.props.style}>
<Svg height="100" width="100">
<G id="mediumorchid_group">
<Defs>
<RadialGradient id="grad" cx="45%" cy="45%" r="50%" fx="44%" fy="44%" fr="49%">
<Stop
offset="100%"
stopColor="#fff"
stopOpacity="0.25"
/>
<Stop
offset="88%"
stopColor="#fff"
stopOpacity="0.15"
/>
</RadialGradient>
</Defs>
<Circle cx="25" cy="25" r="25" fill="url(#grad)" />
<Defs>
<RadialGradient id="second_grad" cx="70%" cy="50%" rx="73%" ry="60%" fx="56%" fy="54%" fr="60%">
<Stop
offset="80%"
stopColor="#fff"
stopOpacity="0.03"
/>
<Stop
offset="100%"
stopColor="#fff"
stopOpacity="0.1"
/>
</RadialGradient>
</Defs>
<G rotate="50" origin="18, 8">
<Ellipse cx="25" cy="12.5" rx="12" ry="16" fill="url(#second_grad)" />
</G>
<Defs>
<RadialGradient id="third_grad" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<Stop
offset="10%"
stopColor="#fff"
stopOpacity="0.7"
/>
<Stop
offset="100%"
stopColor="#fff"
stopOpacity="0.1"
/>
</RadialGradient>
</Defs>
<G rotate="-40" origin="16, 8">
<Ellipse cx="12" cy="8" rx="4" ry="2" fill="url(#third_grad)" />
</G>
<Defs>
<LinearGradient id="text_grad" x1="50%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="#fff" stopOpacity="0.5" />
<Stop offset="100%" stopColor="white" stopOpacity="0.6" />
</LinearGradient>
</Defs>
<Defs>
<LinearGradient id="text_stroke" x1="50%" y1="0%" x2="100%" y2="0%">
<Stop offset="80%" stopColor="#fff" stopOpacity="0" />
<Stop offset="100%" stopColor="mediumorchid" stopOpacity="0.2" />
</LinearGradient>
</Defs>
</G>
<Use href="#mediumorchid_group"/>
</Svg>
</View>
);
}
_wave=()=>{
this.state.animator.setValue(0);
Animated.timing(this.state.animator, {
duration: 2000,
toValue: 79,
}).start(this._wave);
}
} |
import { assert } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
// This method is taken from
// https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/src/ajax/parseXML.js
export default function parseXML(data) {
let xml;
if (!data || typeof data !== 'string') {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = (new window.DOMParser()).parseFromString(data, 'text/xml');
} catch (e) {
xml = undefined;
}
if (DEBUG) {
if (!xml || xml.getElementsByTagName('parsererror').length) {
assert(`Invalid XML: ${data}`);
}
}
return xml;
}
|
(function (Behavior, util) {
Behavior.postMessage = function (config) {
var targetOrigin = config.remoteOrigin,
postFnHost = { postMessage: function () {} };
util.dom.on(window, 'message', function (event) {
if (event.data.indexOf(config.channel) === 0) { // {{ config.channel }}_{{ message }}
var origin = util.url.getDomain(getOrigin(event));
var message = event.data.substr(config.channel.length+1);
if (util.checkACL(config.acl, origin)) {
if (message === 'ready') {
targetOrigin = getOrigin(event); // set up new target
if (config.isHost) {
pub.outgoing('ready');
}
pub.up.ready();
} else {
pub.incoming(message);
}
} else {
throw new Error(origin + ' is not in Access Control List!');
}
}
});
var pub = {
incoming: function (message) {
pub.up.incoming(message);
},
outgoing: function (message) {
postFnHost.postMessage(config.channel + "_" + message, targetOrigin);
},
init: function () {
if (config.isHost) {
var i = config.iframe;
postFnHost = ("postMessage" in i.contentWindow) ? i.contentWindow : i.contentWindow.document;
} else {
postFnHost = ("postMessage" in window.parent) ? window.parent : window.parent.document;
util.dom.ready(function () {
pub.outgoing('ready');
});
}
},
ready: function () {
pub.up.ready();
},
reset: function () {
},
destroy: function () {
config.iframe.parentNode.removeChild(config.iframe);
}
};
return pub;
};
function getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return util.url.getOrigin(event.origin);
}
if (event.uri) {
// From earlier implementations
return util.url.getOrigin(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
}) (RPC.behavior, RPC._util); |
const { METHODS } = require('http')
const routing = require('routing2');
const Router = app => {
const { routes: rules } = app.config;
app.routes = app.routes || [];
app.router = METHODS.reduce((api, method) => {
// app.router.get('/').to('home', 'index');
api[method.toLowerCase()] = path => {
return {
to(controller, action) {
return app.registerRoute({ method, path, controller, action })
}
};
};
return api;
}, {});
app.registerRoute = route => {
if (typeof route === 'string')
route = routing.parseLine(route);
app.routes.push(routing.create(route));
return route;
};
// routes
rules.forEach(app.registerRoute.bind(app));
return async (req, res, next) => {
const { status, route } = routing.find(app.routes, req);
res.statusCode = status;
req.route = route;
await next();
};
};
module.exports = Object.assign(Router, routing); |
var finalhandler = require('finalhandler');
var http = require('http');
var serveStatic = require('serve-static');
// Serve up public folder
var serve = serveStatic('../webapps/mobile/');
// Create server
var server = http.createServer(function(req, res) {
var done = finalhandler(req, res);
serve(req, res, done);
});
// Listen
server.listen(8080);
console.log('Server running at http://localhost:8080/');
|
import compose from '../../utils/compose';
/**
Le principe d'un atomic est que sur change, une nouvelle valeur est initialisée sans tenir compte de la valeur précédente
*/
var AtomicOrderableList = compose(function(item) {
this._item = item;
}, {
initValue: function(initArg) {
if (!initArg) {
return [];
}
var item = this._item;
return initArg.map(function(itemArg) {
return item.initValue(itemArg);
});
},
computeValue: function(changeArg, initValue) {
return this.initValue(changeArg);
},
computeChangeArg: function(changeArg, initValue) {
var item = this._item;
return changeArg.map(function(itemArg) {
return item.computeChangeArg(itemArg);
});
},
});
export default AtomicOrderableList; |
/* global $ */
import {englandData, niData} from './map-data'
const Highcharts = require('highcharts')
const {stringToLowerCase, recursiveObjectKeysLoop, request, spacesToDashes,
capitalizeEachFirstLetter, padInt, calcAspectRatio, isIOS } = require('./chart-helpers')
const {DataNation, DataCcgCode, API_KEY} = require('./url-helpers')
require('highcharts/highcharts-more')(Highcharts)
require('highcharts/modules/exporting')(Highcharts)
require('highcharts/modules/map')(Highcharts)
const chartHeight = () => {
const docWidth = $(document).width()
const containerWidth = $('.container').eq(0).width()
const calculated = docWidth > containerWidth ? containerWidth : docWidth
const nationAspectRatio = DataNation !== 'england' ? [16, 9] : [1, 1]
return calcAspectRatio(calculated, nationAspectRatio[0], nationAspectRatio[1])
}
const initChart = (el, obj) => {
let settings = {
title: '',
subtitle: '',
legend: '',
series: [],
type: 'map',
height: chartHeight(),
legendMin: 0,
legendMax: 100,
formater: ''
}
$.extend(settings, obj)
let config = {
title: {
text: settings.title,
align: 'left'
},
subtitle: {
text: settings.subtitle,
align: 'left'
},
mapNavigation: {
enabled: true
},
colorAxis: {
min: settings.legendMin,
max: settings.legendMax,
type: 'linear',
minColor: '#E3F0D1',
maxColor: '#005C46'
},
legend: {
title: {
text: settings.legend
},
align: 'left',
verticalAlign: 'top',
layout: 'vertical',
x: 0,
y: 100,
reversed: true
},
chart: {
type: settings.type,
renderTo: el,
height: settings.height,
resetZoomButton: {
theme: {
display: 'none'
}
},
events: {
load: function () {
this.myTooltip = new Highcharts.Tooltip(this, this.options.tooltip)
}
}
},
tooltip: {
enabled: isIOS,
backgroundColor: 'white',
borderWidth: 0,
shadow: true,
useHTML: true,
padding: 8,
style: {
pointerEvents: 'auto'
},
formatter: settings.formater
},
series: settings.series
}
if (!isIOS) {
$.extend(config, {
plotOptions: {
series: {
stickyTracking: false,
events: {
click: function (evt) {
this.chart.myTooltip.refresh(evt.point, evt)
},
mouseOut: function () {
this.chart.myTooltip.hide()
}
}
}
}
})
}
let chart = Highcharts.mapChart(config)
return chart
}
const generateOptionElems = questions => questions && questions.map(x => `
<option value="${x.QuestionNo}">${x.Label}</option>`)
// Get all chart elements in the page
const elems = document.querySelectorAll('.pes-map')
const ENDPOINT = `${API_KEY}/patientexperience/GetMap?nation=${DataNation}`
const QUESTIONS_ENDPOINT = `${API_KEY}/patientexperience/GetTable?nation=${DataNation}`
Array.prototype.map.call(elems, el => {
let title = ''
let subtitle = ''
let questionsList = request(QUESTIONS_ENDPOINT)
let mainRequest = request(`${ENDPOINT}&questionNo=1`)
let filterElem = $(el).prev('.pes-mapform')[0]
let selectedValue = ''
if (DataCcgCode !== 'all') return false
filterElem.innerHTML = `<div class="chart__filter background--light-green content--dark-green">
<form class="chart__form">
<div class="form-group chart__el">
<label for="questionSelect">Select a Question</label>
<select class="form__select" name="questionSelect" id="questionSelect" data-filter-target="list">
</select>
</div>
<button title="Update chart" type="submit" class="btn chart__el">Update map</button>
</form>
</div>`
let formElem = $(filterElem).find('.chart__form')
let selectElem = document.getElementById('questionSelect')
formElem.on('submit', function (e) {
e.preventDefault()
selectedValue = selectElem.value
request(`${ENDPOINT}&questionNo=${selectedValue}`).done(data => {
data = recursiveObjectKeysLoop(data, stringToLowerCase)
data.patientExperienceList.map(x => {
x.value = x.score
return x
})
initChart(el, {
title: title,
subtitle: subtitle,
legendMin: data.legendMin,
legendMax: data.legendMax,
formater: function () {
let percentage = DataNation !== 'england'
? '%'
: selectedValue === '59' ? '' : '%'
let tableLink = DataNation !== 'england'
? `${this.point.cCG16CD}/patientexperience`
: `${this.point.cCG16CDH}/patientexperience`
let formattedString = `<b>Q${padInt(this.point.questionNo, 2)}</b><br />
${this.point.cCG16NM} - <b>${this.point.score === 0 ? 'N/A' : this.point.score + percentage}</b><br />
All ${capitalizeEachFirstLetter(DataNation)} - <b>${this.point.englandAverage === 0 ? 'N/A' : this.point.englandAverage + percentage}</b><br />
<a href="/${spacesToDashes(DataNation)}/${tableLink}"><b>See all questions for ${this.point.cCG16NM}</b></a><br />
<a href="${this.point.link}" target="_blank"><b>Download the full report for ${this.point.cCG16NM}</b></a>
`
return formattedString
},
series: [{
data: data.patientExperienceList,
mapData: DataNation !== 'england' ? niData : englandData,
joinBy: ['ccg16cd', 'cCG16CD'],
name: 'CCG',
states: {
hover: {
color: '#86221A'
}
}
}]
})
})
})
$.when(questionsList, mainRequest).done((res1, res2) => {
let mainResponse = recursiveObjectKeysLoop(res2[0], stringToLowerCase)
let questionsList = res1[0]
let optionsElems = generateOptionElems(questionsList)
selectElem.innerHTML += optionsElems
mainResponse.patientExperienceList.map(x => {
x.value = x.score
return x
})
initChart(el, {
title: title,
subtitle: subtitle,
legendMin: mainResponse.legendMin,
legendMax: mainResponse.legendMax,
formater: function () {
let percentage = DataNation !== 'england'
? '%'
: selectedValue === '59' ? '' : '%'
let tableLink = DataNation !== 'england'
? `${this.point.cCG16CD}/patientexperience`
: `${this.point.cCG16CDH}/patientexperience`
let formattedString = `<b>Q${padInt(this.point.questionNo, 2)}</b><br />
${this.point.cCG16NM} - <b>${this.point.score === 0 ? 'N/A' : this.point.score + percentage}</b><br />
All ${capitalizeEachFirstLetter(DataNation)} - <b>${this.point.englandAverage === 0 ? 'N/A' : this.point.englandAverage + percentage}</b><br />
<a href="/${spacesToDashes(DataNation)}/${tableLink}"><b>See all questions for ${this.point.cCG16NM}</b></a><br />
<a href="${this.point.link}" target="_blank"><b>Download the full report for ${this.point.cCG16NM}</b></a>
`
return formattedString
},
series: [{
data: mainResponse.patientExperienceList,
mapData: DataNation !== 'england' ? niData : englandData,
joinBy: ['ccg16cd', 'cCG16CD'],
name: 'CCG',
states: {
hover: {
color: '#86221A'
}
}
}]
})
$(filterElem).removeClass('is-hidden')
let tabContentEl = $(el).parents('.tabs__content').get(0)
if (tabContentEl) {
let tabEl = $(`a[href="#${tabContentEl.id}"]`)
tabEl.removeClass('is-hidden')
}
})
})
|
let _socket;
const onSlideInit = socket => {
_socket = socket;
_socket.on( 'new-subscriber', function( data ) {
_socket.broadcast.emit( 'new-subscriber', data );
});
_socket.on( 'statechanged', function( data ) {
// console.log('statechanged', data);
// data = {notes: HTML notes, _socketId, state: {indexh, indexv, overview: false}}
// @TODO the user manually moved to the next or previous slide.
// Update the stage mate here.
delete data.state.overview;
_socket.broadcast.emit( 'statechanged', data );
});
// socket.on( 'statechanged-speaker', function( data ) {
// // console.log('statechanged-speaker'); // NOT CALLED!
// delete data.state.overview;
// socket.broadcast.emit( 'statechanged-speaker', data );
// });
};
// Catch state changes, especially when changing slides.
const onStateChanged = callback => {
if (!_socket) throw Error('Initialize the socket first!');
_socket.on( 'statechanged', function( data ) {
callback(data);
});
};
// Send an arbitrary command to reveal.js.
const sendCommand = cmd => {
// console.log(`Sending Reveal.${cmd}()`);
_socket.broadcast.emit('reveal-function', {cmd});
};
module.exports = {
onSlideInit,
onStateChanged,
sendCommand
};
|
var crypto = require('crypto');
var path = require('path');
var _ = require('lodash');
module.exports = function page(options) {
//
// ## page
//
// This is a paginator based on collections.
//
// defaults: {
// collection: 'posts',
// perPage: 3,
// target: 'blog',
// template: 'page',
// permga: false
// }
//
// The page's entries will be exposed under the collection attribute provided.
//
return function _page(files, metalsmith) {
var opts = _.extend({}, {collection: 'posts', perPage: 3, target: 'blog', template: 'page', perma: false}, options);
var filtered = _.reject(metalsmith._metadata[opts.collection], 'draft');
var pages = _.chunk(filtered, opts.perPage);
var page_count = _.size(pages);
_.forEach(pages, function(page_entries, i) {
var file = paged_file(opts.collection, page_entries, opts.template, opts.target, page_count, i);
files[path.join(opts.target, (i === 0 ? '' : i + 1).toString(), 'index.html')] = file;
});
if(opts.perma) {
_.forEach(metalsmith._metadata[opts.collection], function(page) {
var file = paged_file(opts.collection, [page], opts.template, opts.target);
files[path.join(file[opts.collection][0].perma_link.slice(1), 'index.html')] = file;
});
}
}
}
function paged_file(collection, entries, template, target, page_count, i) {
var file = {
template: template,
prev: i > 0 ? i : null,
next: i < page_count - 1 ? i + 2 : null,
contents: Buffer(''),
target: target
};
file[collection] = _.map(entries, function(entry) {
var date_string = _.isObject(entry.date) ? entry.date.toISOString().split('T')[0] : entry.date;
return _.extend(_.omit(entry, 'mode', 'stats', 'next', 'previous', 'collection'), {
perma_link: '/' + perma_link(target, [entry.title, date_string].join('')),
date_string: date_string
});
});
return file;
}
function perma_link(target, contents) {
var hash = crypto.createHash('sha1').update(contents).digest('hex');
return path.join(target, 'archive', hash);
}
|
"use strict";
var database;
var connect = require('camo').connect;
var dataPath = __dirname + '/data';
var uriConnection = 'nedb://' + dataPath;
var ProvinceModel = require('./models/Province');
var CityModel = require('./models/City');
var _ = require('underscore');
var async = require('async');
/**
* Get provinces
* @param {Function} callback
* @return {Array}
*/
exports.getProvinces = (callback) => {
connect(uriConnection).then(function(db) {
var res = [];
database = db;
ProvinceModel.find({}, { populate : false }).then(function(p) {
async.eachOf(p, function(value, key, cb) {
res.push(_.pick(value, 'name', 'iso'));
cb();
}, function(err) {
callback(_.sortBy(res, 'name'));
});
}).catch(err => {
callback(err);
});
}).catch(err => {
callback(err);
});
};
/**
* Get province by name
* @param {String} name
* @param {Boolean} withCities
* @param {Function} callback
* @return {Object}
*/
exports.getProvince = (name, withCities, callback) => {
if(Object.prototype.toString.call(withCities) == "[object Function]"){
callback = withCities;
withCities = false;
}
else{
withCities = _.isBoolean(withCities) ? withCities : false;
}
connect(uriConnection).then(function(db) {
database = db;
var cities = [];
var query = {
name : {
$regex : new RegExp('^'+ name.toLowerCase() + '$', 'i')
}
};
ProvinceModel.findOne(query).then(function(p) {
if(p){
if(withCities){
CityModel.find({ province: p._id }, { populate : false }).then(function(c) {
async.eachOf(c, function(value, key, cb) {
cities.push(_.pick(value, 'name'));
cb();
}, function(err) {
p.cities = _.sortBy(cities, 'name');
callback(_.pick(p, 'name', 'iso', 'cities'));
});
});
}
else {
callback(_.pick(p, 'name', 'iso'));
}
} else {
callback({});
}
});
}).catch(err => {
callback(err);
});
};
/**
* Search province
* @param {String} name
* @param {Function} callback
* @return {Array}
*/
exports.searchProvince = (name, callback) => {
connect(uriConnection).then(function(db) {
database = db;
var res = [];
var query = {
name : new RegExp(name, 'i')
};
ProvinceModel.find(query, { populate : false }).then(function(p) {
async.eachOf(p, function(value, key, cb) {
res.push(_.pick(value, 'name', 'iso'));
cb();
}, function(err) {
callback(_.sortBy(res, 'name'));
});
});
}).catch(err => {
callback(err);
});
};
/**
* Get cities and regencies
* @param {Function} callback
* @return {Array}
*/
exports.getCities = (callback) => {
connect(uriConnection).then(function(db) {
var res = [];
database = db;
CityModel.find({}, { populate : true }).then(function(p) {
async.eachOf(p, function(value, key, cb) {
var pr = _.pick(value, 'province');
var ci = _.pick(value, 'name');
ci.province = pr.province.name;
res.push(ci);
cb();
}, function(err) {
callback(_.chain(res).sortBy('name').sortBy('province').value());
});
}).catch(err => {
callback(err);
});
}).catch(err => {
callback(err);
});
};
/**
* Get city or regency by name
* @param {String} name
* @param {Function} callback
* @return {Object}
*/
exports.getCity = (name, callback) => {
connect(uriConnection).then(function(db) {
database = db;
var query = {
name : {
$regex : new RegExp('^'+ name.toLowerCase() + '$', 'i')
}
};
CityModel.findOne(query, { populate : true }).then(function(p) {
if(p){
var pr = _.pick(p, 'province');
var ci = _.pick(p, 'name');
ci.province = pr.province.name;
callback(ci);
} else {
callback({});
}
}).catch(err => {
callback(err);
});
}).catch(err => {
callback(err);
});
};
/**
* Search city or regency
* @param {String} name
* @param {Function} callback
* @return {Array}
*/
exports.searchCity = (name, callback) => {
connect(uriConnection).then(function(db) {
database = db;
var res = [];
var query = {
name : new RegExp(name, 'i')
};
CityModel.find(query, { populate : true }).then(function(p) {
async.eachOf(p, function(value, key, cb) {
var pr = _.pick(value, 'province');
var ci = _.pick(value, 'name');
ci.province = pr.province.name;
res.push(ci);
cb();
}, function(err) {
callback(_.chain(res).sortBy('name').sortBy('province').value());
});
});
}).catch(err => {
callback(err);
});
};
|
var CastleCSS_Forms_FileInput=webpackJsonpCastleCSS_Forms__name_([3],{2:function(t,e,n){"use strict";var s=n(0),i=function(t){var e=t||"[data-castlecss-field]";navigator.userAgent.indexOf("MSIE")>0&&s(e).on("mousedown","input[type='file']",function(){s(this).trigger("click")})};t.exports=i}},[2]); |
/*
* grunt-dictator
* https://github.com/justspamjustin/grunt-dictator
*
* Copyright (c) 2013 Justin Martin
* Licensed under the MIT license.
*/
'use strict';
var Handlebars = require('handlebars');
var fileset = require('fileset');
var _ = require('underscore');
var fs = require('fs');
Handlebars.registerHelper('toLower', function(value) {
return new Handlebars.SafeString(value.toLowerCase());
});
Handlebars.registerHelper('className', function(value) {
return new Handlebars.SafeString(value.split(/(?=[A-Z])/g).join('-').toLowerCase());
});
var Dictator = function (grunt, opts) {
this.grunt = grunt;
this.options = opts;
if (_.isUndefined(this.options.templates)) {
grunt.fail.fatal('The "templates" property must be defined');
}
this.templateArgs = _.defaults(this.convertArgsToObject(), opts.templateDefaults);
this.destination = this.templateArgs['dest'] ? this.options.baseDest + '/' + this.templateArgs['dest'] : this.options.baseDest;
this.handleFiles();
};
Dictator.prototype.handleFiles = function () {
var self = this;
fileset(this.options.templates + '/**/*', function (err, files) {
files.forEach(function (fileName) {
self.handleFileOrDirectory(fileName.replace(self.options.templates, ''));
});
});
};
Dictator.prototype.handleFile = function (fileName) {
var newFileName = Handlebars.compile(fileName)(this.templateArgs);
var templateContent = fs.readFileSync('./' + this.options.templates + fileName).toString();
var newFileContent = Handlebars.compile(templateContent)(this.templateArgs);
fs.writeFileSync( './' + this.destination + newFileName, newFileContent);
};
Dictator.prototype.handleDirectory = function (directoryName) {
var newDirectoryName = Handlebars.compile(directoryName)(this.templateArgs);
try {
fs.mkdirSync( './' + this.destination + newDirectoryName);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
};
Dictator.prototype.handleFileOrDirectory = function (fileName) {
if (fileName.indexOf('.') != -1) {
this.handleFile(fileName);
} else {
this.handleDirectory(fileName);
}
};
Dictator.prototype.convertArgsToObject = function () {
var rawArgs = process.argv.splice(3);
var argObj = {};
for (var i = 0; i < rawArgs.length; i++) {
var argPair = rawArgs[i];
if (_.isNull(argPair.match(/--[^\=]*=.*/))) {
this.grunt.fail.fatal('Template arguments need to be of the format "--name=value"');
}
var key = argPair.split('=')[0].replace('--', '');
var value = argPair.split('=')[1];
argObj[key] = value;
}
return argObj;
};
module.exports = function(grunt) {
grunt.registerMultiTask('dictator', 'Your task description goes here.', function() {
var opts = this.options({
baseDest: ''
});
new Dictator(grunt, opts);
});
};
|
import BMedia from './media'
import BMediaAside from './media-aside'
import BMediaBody from './media-body'
import { installFactory } from '../../utils/plugins'
const components = {
BMedia,
BMediaAside,
BMediaBody
}
export { BMedia, BMediaAside, BMediaBody }
export default {
install: installFactory({ components })
}
|
// This file has been generated by the SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ui.layout.library-all');
if ( !jQuery.sap.isDeclared('sap.ui.layout.DynamicSideContent') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.DynamicSideContent.
jQuery.sap.declare('sap.ui.layout.DynamicSideContent'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.ResizeHandler'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/DynamicSideContent",['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/ResizeHandler'],
function (jQuery, Control, ResizeHandler) {
"use strict";
/**
* Constructor for a new DynamicSideContent.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* The DynamicSideContent control allows additional (side) content to be displayed alongside or below the main
* content, within the container the control is used in. There are different size ratios between the main and
* the side content for the different breakpoints. The side content position (alongside/below the main content)
* and visibility (visible/hidden) can be configured per breakpoint. There are 4 predefined breakpoints:
* - Screen width > 1440 px (XL breakpoint)
* - Screen width <= 1440 px (L breakpoint)
* - Main content width <= 600 px (M breakpoint)
* - Screen width <= 720 px (S breakpoint)
*
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.30
* @alias sap.ui.layout.DynamicSideContent
*/
var DynamicSideContent = Control.extend("sap.ui.layout.DynamicSideContent", /** @lends sap.ui.layout.DynamicSideContent.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Determines whether the side content is visible or hidden.
*/
showSideContent : {type : "boolean", group : "Appearance", defaultValue : true},
/**
* Determines whether the main content is visible or hidden.
*/
showMainContent : {type : "boolean", group : "Appearance", defaultValue : true},
/**
* Determines on which breakpoints the side content is visible.
*/
sideContentVisibility : {type : "sap.ui.layout.SideContentVisibility", group : "Appearance", defaultValue : sap.ui.layout.SideContentVisibility.ShowAboveS},
/**
* Determines on which breakpoints the side content falls down below the main content.
*/
sideContentFallDown : {type : "sap.ui.layout.SideContentFallDown", group : "Appearance", defaultValue : sap.ui.layout.SideContentFallDown.OnMinimumWidth},
/**
* Defines whether the control is in equal split mode. In this mode, the side and the main content
* take 50:50 percent of the container on all screen sizes except for phone, where the main and
* side contents are switching visibility using the toggle method.
*/
equalSplit : {type : "boolean", group : "Appearance", defaultValue : false},
/**
* If set to TRUE, then not the media Query (device screen size) but the size of the container, surrounding the control, defines the current range.
*/
containerQuery : {type : "boolean", group : "Behavior", defaultValue : false}
},
defaultAggregation : "mainContent",
events : {
/**
* Fires when the current breakpoint has been changed.
* @since 1.32
*/
breakpointChanged : {
parameters : {
currentBreakpoint : {type : "string"}
}
}
},
aggregations : {
/**
* Main content controls.
*/
mainContent : {type: "sap.ui.core.Control", multiple: true},
/**
* Side content controls.
*/
sideContent : {type: "sap.ui.core.Control", multiple: true}
}
}});
var S = "S",
M = "M",
L = "L",
XL = "XL",
HIDDEN_CLASS = "sapUiHidden",
SPAN_SIZE_12_CLASS = "sapUiDSCSpan12",
MC_FIXED_CLASS = "sapUiDSCMCFixed",
SC_FIXED_CLASS = "sapUiDSCSCFixed",
SPAN_SIZE_3 = 3,
SPAN_SIZE_4 = 4,
SPAN_SIZE_6 = 6,
SPAN_SIZE_8 = 8,
SPAN_SIZE_9 = 9,
SPAN_SIZE_12 = 12,
INVALID_BREAKPOINT_ERROR_MSG = "Invalid Breakpoint. Expected: S, M, L or XL",
INVALID_PARENT_WIDTH_ERROR_MSG = "Invalid input. Only values greater then 0 are allowed",
SC_GRID_CELL_SELECTOR = "SCGridCell",
MC_GRID_CELL_SELECTOR = "MCGridCell",
S_M_BREAKPOINT = 720,
M_L_BREAKPOINT = 1024,
L_XL_BREAKPOINT = 1440;
DynamicSideContent.prototype.init = function () {
this._bSuppressInitialFireBreakPointChange = true;
};
/**
* Sets the showSideContent property.
* @param {boolean} bVisible Determines if the side content part is visible
* @param {boolean} bSuppressVisualUpdate Determines if the visual state is updated
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @override
* @public
*/
DynamicSideContent.prototype.setShowSideContent = function (bVisible, bSuppressVisualUpdate) {
this.setProperty("showSideContent", bVisible, true);
this._SCVisible = bVisible;
if (!bSuppressVisualUpdate && this.$().length) {
this._setResizeData(this.getCurrentBreakpoint(), this.getEqualSplit());
if (this._currentBreakpoint === S) {
this._MCVisible = true;
}
this._changeGridState();
}
return this;
};
/**
* Sets the showMainContent property.
* @param {boolean} bVisible Determines if the main content part is visible
* @param {boolean} bSuppressVisualUpdate Determines if the visual state is updated
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @override
* @public
*/
DynamicSideContent.prototype.setShowMainContent = function (bVisible, bSuppressVisualUpdate) {
this.setProperty("showMainContent", bVisible, true);
this._MCVisible = bVisible;
if (!bSuppressVisualUpdate && this.$().length) {
this._setResizeData(this.getCurrentBreakpoint(), this.getEqualSplit());
if (this._currentBreakpoint === S) {
this._SCVisible = true;
}
this._changeGridState();
}
return this;
};
/**
* Gets the value of showSideContent property.
* @returns {boolean} Side content visibility state
* @override
* @public
*/
DynamicSideContent.prototype.getShowSideContent = function () {
if (this._currentBreakpoint === S) {
return this._SCVisible && this.getProperty("showSideContent");
} else {
return this.getProperty("showSideContent");
}
};
/**
* Gets the value of showMainContent property.
* @returns {boolean} Side content visibility state
* @override
* @public
*/
DynamicSideContent.prototype.getShowMainContent = function () {
if (this._currentBreakpoint === S) {
return this._MCVisible && this.getProperty("showMainContent");
} else {
return this.getProperty("showMainContent");
}
};
/**
* Sets or unsets the page in equalSplit mode.
* @param {boolean}[bState] Determines if the page is set to equalSplit mode
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @override
* @public
*/
DynamicSideContent.prototype.setEqualSplit = function (bState) {
this._MCVisible = true;
this._SCVisible = true;
this.setProperty("equalSplit", bState, true);
if (this._currentBreakpoint) {
this._setResizeData(this._currentBreakpoint, bState);
this._changeGridState();
}
return this;
};
/**
* Adds a control to the side content area.
* Only the side content part in the aggregation is re-rendered.
* @param {object} oControl Object to be added in the aggregation
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @override
* @public
*/
DynamicSideContent.prototype.addSideContent = function (oControl) {
this.addAggregation("sideContent", oControl, true);
// Rerender only the part of the control that is changed
this._rerenderControl(this.getAggregation("sideContent"), this.$(SC_GRID_CELL_SELECTOR));
return this;
};
/**
* Adds a control to the main content area.
* Only the main content part in the aggregation is re-rendered.
* @param {object} oControl Object to be added in the aggregation
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @override
* @public
*/
DynamicSideContent.prototype.addMainContent = function (oControl) {
this.addAggregation("mainContent", oControl, true);
// Rerender only the part of the control that is changed
this._rerenderControl(this.getAggregation("mainContent"), this.$(MC_GRID_CELL_SELECTOR));
return this;
};
/**
* Used for the toggle button functionality.
* When the control is on a phone screen size only, one control area is visible.
* This helper method is used to implement a button/switch for changing
* between the main and side content areas.
* Only works if the current breakpoint is "S".
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @public
*/
DynamicSideContent.prototype.toggle = function () {
if (this._currentBreakpoint === S) {
if (!this.getProperty("showMainContent")) {
this.setShowMainContent(true, true);
this._MCVisible = false;
}
if (!this.getProperty("showSideContent")) {
this.setShowSideContent(true, true);
this._SCVisible = false;
}
if (this._MCVisible && !this._SCVisible) {
this._SCVisible = true;
this._MCVisible = false;
} else if (!this._MCVisible && this._SCVisible) {
this._MCVisible = true;
this._SCVisible = false;
}
this._changeGridState();
}
return this;
};
/**
* Returns the breakpoint for the current state of the control.
* @returns {String} currentBreakpoint
* @public
*/
DynamicSideContent.prototype.getCurrentBreakpoint = function () {
return this._currentBreakpoint;
};
/**
* Function is called before the control is rendered.
* @private
* @override
*/
DynamicSideContent.prototype.onBeforeRendering = function () {
this._detachContainerResizeListener();
this._SCVisible = this.getProperty("showSideContent");
this._MCVisible = this.getProperty("showMainContent");
if (!this.getContainerQuery()) {
this._iWindowWidth = jQuery(window).width();
this._setBreakpointFromWidth(this._iWindowWidth);
this._setResizeData(this._currentBreakpoint, this.getEqualSplit());
}
};
/**
* Function is called after the control is rendered.
* @private
* @override
*/
DynamicSideContent.prototype.onAfterRendering = function () {
if (this.getContainerQuery()) {
this._attachContainerResizeListener();
} else {
var that = this;
jQuery(window).resize(function() {
that._handleMediaChange();
});
}
this._changeGridState();
this._initScrolling();
};
/**
* Function is called when exiting the control.
* @private
*/
DynamicSideContent.prototype.exit = function () {
this._detachContainerResizeListener();
if (this._oSCScroller) {
this._oSCScroller.destroy();
this._oSCScroller = null;
}
if (this._oMCScroller) {
this._oMCScroller.destroy();
this._oMCScroller = null;
}
};
/**
* Re-renders only part of the control that is changed.
* @param {object} aControls Array containing the passed aggregation controls
* @param {object} $domElement DOM reference of the control to be re-rendered
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @private
*/
DynamicSideContent.prototype._rerenderControl = function (aControls, $domElement) {
if (this.getDomRef()) {
var oRm = sap.ui.getCore().createRenderManager();
this.getRenderer().renderControls(oRm, aControls);
oRm.flush($domElement[0]);
oRm.destroy();
}
return this;
};
/**
* Initializes scroll for side and main content.
* @private
*/
DynamicSideContent.prototype._initScrolling = function () {
var sControlId = this.getId(),
sSideContentId = sControlId + "-" + SC_GRID_CELL_SELECTOR,
sMainContentId = sControlId + "-" + MC_GRID_CELL_SELECTOR;
if (!this._oSCScroller && !this._oMCScroller) {
jQuery.sap.require("sap.ui.core.delegate.ScrollEnablement");
this._oSCScroller = new sap.ui.core.delegate.ScrollEnablement(this, null, {
scrollContainerId: sSideContentId,
horizontal: false,
vertical: true
});
this._oMCScroller = new sap.ui.core.delegate.ScrollEnablement(this, null, {
scrollContainerId: sMainContentId,
horizontal: false,
vertical: true
});
}
};
/**
* Attaches event listener for the needed breakpoints to the container.
* @private
*/
DynamicSideContent.prototype._attachContainerResizeListener = function () {
if (!this._sContainerResizeListener) {
this._sContainerResizeListener = ResizeHandler.register(this, jQuery.proxy(this._handleMediaChange, this));
}
};
/**
* Detaches event listener for the needed breakpoints to the container.
* @private
*/
DynamicSideContent.prototype._detachContainerResizeListener = function () {
if (this._sContainerResizeListener) {
ResizeHandler.deregister(this._sContainerResizeListener);
this._sContainerResizeListener = null;
}
};
/**
* Gets the current breakpoint, related to the width, which is passed to the method.
* @private
* @param {integer} iWidth The parent container width
* @returns {String} Breakpoint corresponding to the width passed
*/
DynamicSideContent.prototype._getBreakPointFromWidth = function (iWidth) {
if (iWidth <= 0) {
throw new Error(INVALID_PARENT_WIDTH_ERROR_MSG);
}
if (iWidth <= S_M_BREAKPOINT && this._currentBreakpoint !== S) {
return S;
} else if ((iWidth > S_M_BREAKPOINT) && (iWidth <= M_L_BREAKPOINT) && this._currentBreakpoint !== M) {
return M;
} else if ((iWidth > M_L_BREAKPOINT) && (iWidth <= L_XL_BREAKPOINT) && this._currentBreakpoint !== L) {
return L;
} else if (iWidth > L_XL_BREAKPOINT && this._currentBreakpoint !== XL) {
return XL;
}
return this._currentBreakpoint;
};
/**
* Sets the current breakpoint, related to the width, which is passed to the method.
* @private
* @param {integer} iWidth is the parent container width
*/
DynamicSideContent.prototype._setBreakpointFromWidth = function (iWidth) {
if (iWidth <= 0) {
throw new Error(INVALID_PARENT_WIDTH_ERROR_MSG);
}
this._currentBreakpoint = this._getBreakPointFromWidth(iWidth);
if (this._bSuppressInitialFireBreakPointChange) {
this._bSuppressInitialFireBreakPointChange = false;
} else {
this.fireBreakpointChanged({currentBreakpoint : this._currentBreakpoint});
}
};
/**
* Handles the screen size breakpoints.
* @private
*/
DynamicSideContent.prototype._handleMediaChange = function () {
if (this.getContainerQuery()){
this._iWindowWidth = this.$().parent().width();
} else {
this._iWindowWidth = jQuery(window).width();
}
if (this._iWindowWidth !== this._iOldWindowWidth) {
this._iOldWindowWidth = this._iWindowWidth;
this._oldBreakPoint = this._currentBreakpoint;
this._setBreakpointFromWidth(this._iWindowWidth);
if ((this._oldBreakPoint !== this._currentBreakpoint)
|| (this._currentBreakpoint === M
&& this.getSideContentFallDown() === sap.ui.layout.SideContentFallDown.OnMinimumWidth)) {
this._setResizeData(this._currentBreakpoint, this.getEqualSplit());
this._changeGridState();
}
}
};
/**
* Returns object with data about the size of the main and the side content, based on the screen breakpoint and
* control mode.
* @param {string} sSizeName Possible values S, M, L, XL
* @param {boolean} bComparison Checks if the page is in equalSplit mode
* @returns {sap.m.DynamicSideContent} this pointer for chaining
* @private
*/
DynamicSideContent.prototype._setResizeData = function (sSizeName, bComparison) {
var sideContentVisibility = this.getSideContentVisibility(),
sideContentFallDown = this.getSideContentFallDown();
if (!bComparison) {
// Normal mode
switch (sSizeName) {
case S:
this._setSpanSize(SPAN_SIZE_12, SPAN_SIZE_12);
if (this.getProperty("showSideContent") && this.getProperty("showMainContent")) {
this._SCVisible = sideContentVisibility === sap.ui.layout.SideContentVisibility.AlwaysShow;
}
this._bFixedSideContent = false;
break;
case M:
var iSideContentWidth = Math.ceil((33.333 / 100) * this._iWindowWidth);
if (sideContentFallDown === sap.ui.layout.SideContentFallDown.BelowL ||
sideContentFallDown === sap.ui.layout.SideContentFallDown.BelowXL ||
(iSideContentWidth <= 320 && sideContentFallDown === sap.ui.layout.SideContentFallDown.OnMinimumWidth)) {
this._setSpanSize(SPAN_SIZE_12, SPAN_SIZE_12);
this._bFixedSideContent = false;
} else {
this._setSpanSize(SPAN_SIZE_4, SPAN_SIZE_8);
this._bFixedSideContent = true;
}
this._SCVisible = sideContentVisibility === sap.ui.layout.SideContentVisibility.ShowAboveS ||
sideContentVisibility === sap.ui.layout.SideContentVisibility.AlwaysShow;
this._MCVisible = true;
break;
case L:
if (sideContentFallDown === sap.ui.layout.SideContentFallDown.BelowXL) {
this._setSpanSize(SPAN_SIZE_12, SPAN_SIZE_12);
} else {
this._setSpanSize(SPAN_SIZE_4, SPAN_SIZE_8);
}
this._SCVisible = sideContentVisibility === sap.ui.layout.SideContentVisibility.ShowAboveS ||
sideContentVisibility === sap.ui.layout.SideContentVisibility.ShowAboveM ||
sideContentVisibility === sap.ui.layout.SideContentVisibility.AlwaysShow;
this._MCVisible = true;
this._bFixedSideContent = false;
break;
case XL:
this._setSpanSize(SPAN_SIZE_3, SPAN_SIZE_9);
this._SCVisible = sideContentVisibility !== sap.ui.layout.SideContentVisibility.NeverShow;
this._MCVisible = true;
this._bFixedSideContent = false;
break;
default:
throw new Error(INVALID_BREAKPOINT_ERROR_MSG);
}
} else {
// Equal split mode
switch (sSizeName) {
case S:
this._setSpanSize(SPAN_SIZE_12, SPAN_SIZE_12);
this._SCVisible = false;
break;
default:
this._setSpanSize(SPAN_SIZE_6, SPAN_SIZE_6);
this._SCVisible = true;
this._MCVisible = true;
}
this._bFixedSideContent = false;
}
return this;
};
/**
* Determines if the control sets height, based on the control state.
* @private
* @return {boolean} If the control sets height
*/
DynamicSideContent.prototype._shouldSetHeight = function () {
var bSameLine,
bBothVisible,
bOnlyScVisible,
bOnlyMcVisible,
bOneVisible,
bFixedSC,
bSCNeverShow;
bSameLine = (this._iScSpan + this._iMcSpan) === SPAN_SIZE_12;
bBothVisible = this._MCVisible && this._SCVisible;
bOnlyScVisible = !this._MCVisible && this._SCVisible;
bOnlyMcVisible = this._MCVisible && !this._SCVisible;
bOneVisible = bOnlyScVisible || bOnlyMcVisible;
bFixedSC = this._fixedSideContent;
bSCNeverShow = this.getSideContentVisibility() === sap.ui.layout.SideContentVisibility.NeverShow;
return ((bSameLine && bBothVisible) || bOneVisible || bFixedSC || bSCNeverShow);
};
/**
* Changes the state of the grid without re-rendering the control.
* Shows and hides the main and side content.
* @private
*/
DynamicSideContent.prototype._changeGridState = function () {
var $sideContent = this.$(SC_GRID_CELL_SELECTOR),
$mainContent = this.$(MC_GRID_CELL_SELECTOR),
bMainContentVisibleProperty = this.getProperty("showMainContent"),
bSideContentVisibleProperty = this.getProperty("showSideContent");
if (this._bFixedSideContent) {
$sideContent.removeClass().addClass(SC_FIXED_CLASS);
$mainContent.removeClass().addClass(MC_FIXED_CLASS);
} else {
$sideContent.removeClass(SC_FIXED_CLASS);
$mainContent.removeClass(MC_FIXED_CLASS);
}
if (this._SCVisible && this._MCVisible && bSideContentVisibleProperty && bMainContentVisibleProperty) {
if (!this._bFixedSideContent) {
$mainContent.removeClass().addClass("sapUiDSCSpan" + this._iMcSpan);
$sideContent.removeClass().addClass("sapUiDSCSpan" + this._iScSpan);
}
if (this._shouldSetHeight()) {
$sideContent.css("height", "100%").css("float", "left");
$mainContent.css("height", "100%").css("float", "left");
} else {
$sideContent.css("height", "auto").css("float", "none");
$mainContent.css("height", "auto").css("float", "none");
}
} else if (!this._SCVisible && !this._MCVisible) {
$mainContent.addClass(HIDDEN_CLASS);
$sideContent.addClass(HIDDEN_CLASS);
} else if (this._MCVisible && bMainContentVisibleProperty) {
$mainContent.removeClass().addClass(SPAN_SIZE_12_CLASS);
$sideContent.addClass(HIDDEN_CLASS);
} else if (this._SCVisible && bSideContentVisibleProperty) {
$sideContent.removeClass().addClass(SPAN_SIZE_12_CLASS);
$mainContent.addClass(HIDDEN_CLASS);
} else if (!bMainContentVisibleProperty && !bSideContentVisibleProperty) {
$mainContent.addClass(HIDDEN_CLASS);
$sideContent.addClass(HIDDEN_CLASS);
}
};
/**
* Sets the main and side content span size.
* @param {integer} iScSpan Side content span size
* @param {integer} iMcSpan Main content span size
* @private
*/
DynamicSideContent.prototype._setSpanSize = function (iScSpan, iMcSpan) {
this._iScSpan = iScSpan;
this._iMcSpan = iMcSpan;
};
return DynamicSideContent;
}, /* bExport= */ true);
}; // end of sap/ui/layout/DynamicSideContent.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.DynamicSideContentRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides default renderer for control sap.ui.layout.DynamicSideContent
jQuery.sap.declare('sap.ui.layout.DynamicSideContentRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/layout/DynamicSideContentRenderer",[],
function() {
"use strict";
var SIDE_CONTENT_LABEL = "SIDE_CONTENT_LABEL";
/**
* Renderer for sap.ui.layout.DynamicSideContent.
* @namespace
*/
var DynamicSideContentRenderer = {};
DynamicSideContentRenderer.render = function (oRm, oSideContent) {
oRm.write("<div");
oRm.writeControlData(oSideContent);
oRm.addClass("sapUiDSC");
oRm.writeClasses();
oRm.addStyle("height", "100%");
oRm.writeStyles();
oRm.write(">");
this.renderSubControls(oRm, oSideContent);
oRm.write("</div>");
};
DynamicSideContentRenderer.renderSubControls = function (oRm, oSideControl) {
var iSideContentId = oSideControl.getId(),
bShouldSetHeight = oSideControl._shouldSetHeight(),
// on firefox the 'aside' side content is not shown when below the main content; use div instead
sSideContentTag = sap.ui.Device.browser.firefox ? "div" : "aside";
oRm.write("<div id='" + iSideContentId + "-MCGridCell'");
if (oSideControl._iMcSpan) {
oRm.addClass("sapUiDSCSpan" + oSideControl._iMcSpan);
oRm.writeClasses();
}
if (bShouldSetHeight) {
oRm.addStyle("height", "100%");
oRm.writeStyles();
}
oRm.write(">");
this.renderControls(oRm, oSideControl.getMainContent());
oRm.write("</div>");
oRm.write("<" + sSideContentTag + " id='" + iSideContentId + "-SCGridCell'");
var oMessageBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.layout");
oRm.writeAttribute("aria-label", oMessageBundle.getText(SIDE_CONTENT_LABEL));
oRm.writeAccessibilityState(oSideControl, {
role: "complementary"
});
if (oSideControl._iScSpan) {
oRm.addClass("sapUiDSCSpan" + oSideControl._iScSpan);
oRm.writeClasses();
}
if (bShouldSetHeight) {
oRm.addStyle("height", "100%");
oRm.writeStyles();
}
oRm.write(">");
this.renderControls(oRm, oSideControl.getSideContent());
oRm.write("</" + sSideContentTag + ">");
};
DynamicSideContentRenderer.renderControls = function (oRM, aContent) {
var iLength = aContent.length,
i = 0;
for (; i < iLength; i++) {
oRM.renderControl(aContent[i]);
}
};
return DynamicSideContentRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/DynamicSideContentRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.FixFlexRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.FixFlexRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/FixFlexRenderer",['jquery.sap.global'],
function (jQuery) {
"use strict";
/**
* FixFlex renderer
* @namespace
*/
var FixFlexRenderer = {};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
FixFlexRenderer.render = function (oRm, oControl) {
// Control container
oRm.write('<div');
oRm.writeControlData(oControl);
oRm.addClass('sapUiFixFlex');
if (oControl.getMinFlexSize() !== 0) {
oRm.addClass('sapUiFixFlexInnerScrolling');
}
// Setting css class for horizontal layout
if (!oControl.getVertical()) {
oRm.addClass('sapUiFixFlexRow');
}
// Setting css class for older browsers
if (!jQuery.support.hasFlexBoxSupport) {
oRm.addClass('sapUiFixFlex-Legacy');
}
oRm.writeClasses();
oRm.write('>');
// Defines the rendering sequence - fix/flex or flex/fix
if (oControl.getFixFirst()) {
this.renderFixChild(oRm, oControl);
this.renderFlexChild(oRm, oControl);
} else {
this.renderFlexChild(oRm, oControl);
this.renderFixChild(oRm, oControl);
}
// Close the FixFlex Control container
oRm.write('</div>');
};
/**
* Render the controls in the flex container
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
FixFlexRenderer.renderFixChild = function (oRm, oControl) {
var aFixContent = oControl.getFixContent();
oRm.write('<div id="' + oControl.getId() + '-Fixed" class="sapUiFixFlexFixed"');
// Set specific height/width to the element depending of the orientation of the layout
if (oControl.getFixContentSize() !== 'auto') {
if (oControl.getVertical()) {
oRm.addStyle('height', oControl.getFixContentSize());
} else {
oRm.addStyle('width', oControl.getFixContentSize());
}
oRm.writeStyles();
}
oRm.write('>');
// Render the children
for (var i = 0; i < aFixContent.length; i++) {
oRm.renderControl(aFixContent[i]);
}
oRm.write('</div>');
};
/**
* Render the controls in the fix container
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
FixFlexRenderer.renderFlexChild = function (oRm, oControl) {
var oFlexContent = oControl.getFlexContent();
oRm.write('<div id="' + oControl.getId() + '-Flexible" class="sapUiFixFlexFlexible">');
oRm.write('<div id="' + oControl.getId() + '-FlexibleContainer" class="sapUiFixFlexFlexibleContainer"');
if (oControl.getMinFlexSize() !== 0) {
if (oControl.getVertical()) {
oRm.write('style="min-height:' + oControl.getMinFlexSize() + 'px"');
} else {
oRm.write('style="min-width:' + oControl.getMinFlexSize() + 'px"');
}
}
oRm.write('>');
// Render the child
oRm.renderControl(oFlexContent);
oRm.write('</div>');
oRm.write('</div>');
};
return FixFlexRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/FixFlexRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.GridRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.GridRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/GridRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* @author SAP SE
* @version
* 1.32.10
* @namespace
*/
var GridRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* oRm the RenderManager that can be used for writing to the render
* output buffer
* @param {sap.ui.core.Control}
* oControl an object representation of the control that should be
* rendered
*/
GridRenderer.render = function(oRm, oControl) {
var INDENTPATTERN = /^([X][L](?:[0-9]|1[0-1]))? ?([L](?:[0-9]|1[0-1]))? ?([M](?:[0-9]|1[0-1]))? ?([S](?:[0-9]|1[0-1]))?$/i;
var SPANPATTERN = /^([X][L](?:[1-9]|1[0-2]))? ?([L](?:[1-9]|1[0-2]))? ?([M](?:[1-9]|1[0-2]))? ?([S](?:[1-9]|1[0-2]))?$/i;
// write the HTML into the render manager
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUiRespGrid");
var sMedia = sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED).name;
oRm.addClass("sapUiRespGridMedia-Std-" + sMedia);
var fHSpacing = oControl.getHSpacing();
// Check for allowed values, if not matching, set to to default 1 rem.
if (fHSpacing == 0.5) {
fHSpacing = "05";
} else if ((fHSpacing !== 0) && (fHSpacing !== 1) && (fHSpacing !== 2)) {
fHSpacing = 1;
}
oRm.addClass("sapUiRespGridHSpace" + fHSpacing);
var fVSpacing = oControl.getVSpacing();
// Check for allowed values, if not matching, set to to default 1 rem.
if (fVSpacing == 0.5) {
fVSpacing = "05";
} else if ((fVSpacing !== 0) && (fVSpacing !== 1) && (fVSpacing !== 2)) {
fVSpacing = 1;
}
oRm.addClass("sapUiRespGridVSpace" + fVSpacing);
var sPosition = oControl.getPosition();
if (sPosition) {
sPosition = sPosition.toUpperCase();
if (sPosition === sap.ui.layout.GridPosition.Center.toUpperCase()) {
oRm.addClass("sapUiRespGridPosCenter");
} else if (sPosition === sap.ui.layout.GridPosition.Right.toUpperCase()) {
oRm.addClass("sapUiRespGridPosRight");
}
}
oRm.writeClasses();
var sWidth = oControl.getWidth();
if (sWidth !== "100%" && sWidth !== "auto" && sWidth !== "inherit") {
if (fHSpacing == 0) {
sWidth = "width: " + sWidth;
} else {
sWidth = "width: -webkit-calc(" + sWidth + " - " + fHSpacing + "rem); width: calc(" + sWidth + " - " + fHSpacing + "rem); ";
}
oRm.writeAttribute("style", sWidth);
}
var sRole = oControl._getAccessibleRole();
var mAriaProps;
if (sRole) {
mAriaProps = {role: sRole};
}
oRm.writeAccessibilityState(oControl, mAriaProps);
oRm.write(">");
var aItems = oControl.getContent();
var defaultSpan = oControl.getDefaultSpan();
// Default Span if nothing is specified at all, not on Grid , not on the
// cell.
var aInitialSpan = [ "", "XL3", "L3", "M6", "S12"];
// Default Indent if nothing is specified at all, not on Grid , not on the
// cell.
var aInitialIndent = [ "", "XL0", "L0", "M0", "S0"];
// Default Span values defined on the whole Grid, that is used if there is
// no individual span defined for the cell.
var aDefaultSpan = SPANPATTERN.exec(defaultSpan);
// Determinate if default span value for XL was changed.
var bDefaultSpanXLChanged = oControl._getSpanXLChanged();
// Determinate if default indent value for Indent was changed.
var bDefaultIndentXLChanged = oControl._getIndentXLChanged();
// Default indent of the whole Grid control
var sDefaultIndent = oControl.getDefaultIndent();
var aDefaultIndent = INDENTPATTERN.exec(sDefaultIndent);
for ( var i = 0; i < aItems.length; i++) { // loop over all child controls
oRm.write("<div");
var oLay = oControl._getLayoutDataForControl(aItems[i]);
if (oLay) {
//************************************************************************
// LINE BREAK
//************************************************************************
var bBreakXLChanged = false;
if (oLay.getLinebreak() === true) {
oRm.addClass("sapUiRespGridBreak");
} else {
if (oLay.getLinebreakXL() === true) {
bBreakXLChanged = true;
oRm.addClass("sapUiRespGridBreakXL");
}
if (oLay.getLinebreakL() === true) {
if (!bBreakXLChanged && !oLay._getLinebreakXLChanged()){
oRm.addClass("sapUiRespGridBreakXL");
}
oRm.addClass("sapUiRespGridBreakL");
}
if (oLay.getLinebreakM() === true) {
oRm.addClass("sapUiRespGridBreakM");
}
if (oLay.getLinebreakS() === true) {
oRm.addClass("sapUiRespGridBreakS");
}
}
//************************************************************************
// SPAN
//************************************************************************
// array of spans
var aSpan;
// sSpanL needed for XL if XL is not defined at all
var sSpanL;
var sSpan = oLay.getSpan();
if (!sSpan || !sSpan.lenght == 0) {
aSpan = aDefaultSpan;
} else {
aSpan = SPANPATTERN.exec(sSpan);
if (/XL/gi.test(sSpan)) {
bDefaultSpanXLChanged = true;
}
}
if (aSpan) {
for ( var j = 1; j < aSpan.length; j++) {
var span = aSpan[j];
if (!span) {
span = aDefaultSpan[j];
if (!span) {
span = aInitialSpan[j];
}
}
if (span.substr(0, 1) === "L") {
sSpanL = span.substr(1, 2);
}
// Catch the Individual Spans
var iSpanXLarge = oLay.getSpanXL();
var iSpanLarge = oLay.getSpanL();
var iSpanMedium = oLay.getSpanM();
var iSpanSmall = oLay.getSpanS();
span = span.toUpperCase();
if ((span.substr(0, 2) === "XL") && (iSpanXLarge > 0) && (iSpanXLarge < 13)) {
oRm.addClass("sapUiRespGridSpanXL" + iSpanXLarge);
bDefaultSpanXLChanged = true;
} else if ((span.substr(0, 1) === "L") && (iSpanLarge > 0) && (iSpanLarge < 13)) {
oRm.addClass("sapUiRespGridSpanL" + iSpanLarge);
sSpanL = iSpanLarge;
} else if ((span.substr(0, 1) === "M") && (iSpanMedium > 0) && (iSpanMedium < 13)) {
oRm.addClass("sapUiRespGridSpanM" + iSpanMedium);
} else if ((span.substr(0, 1) === "S") && (iSpanSmall > 0) && (iSpanSmall < 13)) {
oRm.addClass("sapUiRespGridSpanS" + iSpanSmall);
} else {
if ((span.substr(0, 2) !== "XL") || bDefaultSpanXLChanged ){
oRm.addClass("sapUiRespGridSpan" + span);
}
}
}
if (!bDefaultSpanXLChanged) {
// Backwards compatibility - if the XL not defined - it should be as L.
oRm.addClass("sapUiRespGridSpanXL" + sSpanL);
}
}
//************************************************************************
// INDENT
//************************************************************************
var aIndent;
var sIndentL;
var sIndent = oLay.getIndent();
if (!sIndent || sIndent.length == 0) {
aIndent = aDefaultIndent;
} else {
aIndent = INDENTPATTERN.exec(sIndent);
if (/XL/gi.test(sIndent)) {
bDefaultIndentXLChanged = true;
}
}
if (!aIndent) {
aIndent = aDefaultIndent;
if (!aIndent) {
aIndent = undefined; // no indent
}
}
// Catch the Individual Indents
var iIndentXLarge = oLay.getIndentXL();
var iIndentLarge = oLay.getIndentL();
var iIndentMedium = oLay.getIndentM();
var iIndentSmall = oLay.getIndentS();
if (aIndent) {
for ( var j = 1; j < aIndent.length; j++) {
var indent = aIndent[j];
if (!indent) {
if (aDefaultIndent && aDefaultIndent[j]) {
indent = aDefaultIndent[j];
} else {
indent = aInitialIndent[j];
}
}
if (indent) {
indent = indent.toUpperCase();
if (indent.substr(0, 1) === "L") {
sIndentL = indent.substr(1, 2);
}
if ((indent.substr(0, 2) === "XL") && (iIndentXLarge > 0) && (iIndentXLarge < 12)) {
oRm.addClass("sapUiRespGridIndentXL" + iIndentXLarge);
bDefaultIndentXLChanged = true;
} else if ((indent.substr(0, 1) === "L") && (iIndentLarge > 0)
&& (iIndentLarge < 12)) {
oRm.addClass("sapUiRespGridIndentL" + iIndentLarge);
sIndentL = iIndentLarge;
} else if ((indent.substr(0, 1) === "M")
&& (iIndentMedium > 0) && (iIndentMedium < 12)) {
oRm.addClass("sapUiRespGridIndentM" + iIndentMedium);
} else if ((indent.substr(0, 1) === "S")
&& (iIndentSmall > 0) && (iIndentSmall < 12)) {
oRm.addClass("sapUiRespGridIndentS" + iIndentSmall);
} else {
if (!(/^(XL0)? ?(L0)? ?(M0)? ?(S0)?$/.exec(indent))) {
oRm.addClass("sapUiRespGridIndent" + indent);
}
}
}
}
if (!bDefaultIndentXLChanged) {
// Backwards compatibility - if the XL not defined - it should be as L.
if (sIndentL && sIndentL > 0) {
oRm.addClass("sapUiRespGridIndentXL" + sIndentL);
}
}
}
// Visibility
var
l = oLay.getVisibleL(),
m = oLay.getVisibleM(),
s = oLay.getVisibleS();
// TODO: visibility of XL different to L
if (!l && m && s) {
oRm.addClass("sapUiRespGridHiddenL");
oRm.addClass("sapUiRespGridHiddenXL");
} else if (!l && !m && s) {
oRm.addClass("sapUiRespGridVisibleS");
} else if (l && !m && !s) {
oRm.addClass("sapUiRespGridVisibleL");
oRm.addClass("sapUiRespGridVisibleXL");
} else if (!l && m && !s) {
oRm.addClass("sapUiRespGridVisibleM");
} else if (l && !m && s) {
oRm.addClass("sapUiRespGridHiddenM");
} else if (l && m && !s) {
oRm.addClass("sapUiRespGridHiddenS");
}
// Move - moveBwd shifts a grid element to the left in LTR mode and
// opposite in RTL mode
var sMoveB = oLay.getMoveBackwards();
if (sMoveB && sMoveB.length > 0) {
var aMoveB = INDENTPATTERN.exec(sMoveB);
if (aMoveB) {
for ( var j = 1; j < aMoveB.length; j++) {
var moveB = aMoveB[j];
if (moveB) {
oRm.addClass("sapUiRespGridBwd" + moveB.toUpperCase());
}
}
}
}
// ... while moveFwd shifts it to the right in LTR mode and opposite
// in RTL
var sMoveF = oLay.getMoveForward();
if (sMoveF && sMoveF.length > 0) {
var aMoveF = INDENTPATTERN.exec(sMoveF);
if (aMoveF) {
for ( var j = 1; j < aMoveF.length; j++) {
var moveF = aMoveF[j];
if (moveF) {
oRm.addClass("sapUiRespGridFwd" + moveF.toUpperCase());
}
}
}
}
// Internal additional classes
if (oLay._sStylesInternal) {
oRm.addClass(oLay._sStylesInternal);
}
}
// No layoutData - apply default values. it could be
// default value defined on Grid control, or id it is does not exist default parameter value "XL3 L3 M6 S12"
// XL default value changes if L is defined.
if (!oLay) {
var span = "";
if (aDefaultSpan) {
for ( var j = 1; j < aDefaultSpan.length; j++) {
span = aDefaultSpan[j];
if (!span) {
if ((j == 1) && (aDefaultSpan[j + 1])) {
span = "X" + aDefaultSpan[j + 1];
} else {
span = aInitialSpan[j];
}
}
oRm.addClass("sapUiRespGridSpan" + span.toUpperCase());
}
} else {
for ( var j = 1; j < aInitialSpan.length; j++) {
span = aInitialSpan[j];
oRm.addClass("sapUiRespGridSpan" + span.toUpperCase());
}
}
var indent = "";
if (aDefaultIndent) {
for ( var j = 1; j < aDefaultIndent.length; j++) {
indent = aDefaultIndent[j];
if (!indent) {
if ((j == 1) && (aDefaultIndent[j + 1])) {
indent = "X" + aDefaultIndent[j + 1];
} else {
indent = aInitialIndent[j];
}
}
if (((indent.substr(0,1) !== "X") && (indent.substr(1,1) !== "0")) || ((indent.substr(0,1) == "X") && (indent.substr(2,1) !== "0"))) {
oRm.addClass("sapUiRespGridIndent" + indent.toUpperCase());
}
}
}
}
oRm.writeClasses();
oRm.write(">");
oRm.renderControl(aItems[i]); // render the child control (could even
// be a big control tree, but you don't
// need to care)
oRm.write("</div>"); // end of the box around the respective child
}
oRm.write("</div>"); // end of the complete grid control
};
return GridRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/GridRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.HorizontalLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.HorizontalLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/HorizontalLayoutRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* HorizontalLayout renderer.
* @namespace
*/
var HorizontalLayoutRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
HorizontalLayoutRenderer.render = function(oRenderManager, oControl){
// convenience variable
var rm = oRenderManager;
var bNoWrap = !oControl.getAllowWrapping();
// write the HTML into the render manager
rm.write("<div");
rm.writeControlData(oControl);
rm.addClass("sapUiHLayout");
if (bNoWrap) {
rm.addClass("sapUiHLayoutNoWrap");
}
rm.writeClasses();
rm.write(">"); // div element
var aChildren = oControl.getContent();
for (var i = 0; i < aChildren.length; i++) {
if (bNoWrap) {
rm.write("<div class='sapUiHLayoutChildWrapper'>");
}
rm.renderControl(aChildren[i]);
if (bNoWrap) {
rm.write("</div>");
}
}
rm.write("</div>");
};
return HorizontalLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/HorizontalLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.ResponsiveFlowLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.ResponsiveFlowLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/ResponsiveFlowLayoutRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* ResponsiveFlowLayout renderer.
* @namespace
*/
var ResponsiveFlowLayoutRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* oRm the RenderManager that can be used for writing to the render
* output buffer
* @param {sap.ui.core.Control}
* oControl an object representation of the control that should be
* rendered
*/
(function() {
ResponsiveFlowLayoutRenderer.render = function(oRm, oControl) {
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUiRFL");
oRm.writeClasses();
var sRole = oControl._getAccessibleRole();
var mAriaProps;
if (sRole) {
mAriaProps = {role: sRole};
}
oRm.writeAccessibilityState(oControl, mAriaProps);
oRm.write(">"); // div element
// rendering of content happens in oControl.fnRenderContent
oRm.write("</div>");
};
}());
return ResponsiveFlowLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/ResponsiveFlowLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.SplitterRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.SplitterRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/SplitterRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* Splitter renderer.
* @namespace
*/
var SplitterRenderer = {
};
/**
* Renders the main HTML element for the Splitter control and everything else is rendered in a
* hidden area inside the splitter. The content of that hidden area is shown after rendering to
* avoid flickering.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
SplitterRenderer.render = function(oRm, oControl){
var bHorizontal = oControl.getOrientation() === sap.ui.core.Orientation.Horizontal;
var sOrientationClass = bHorizontal ? "sapUiLoSplitterH" : "sapUiLoSplitterV";
var bAnimate = sap.ui.getCore().getConfiguration().getAnimation();
// Make sure we have the main element available before rendering the children so we can use
// the element width to calculate before rendering the children.
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUiLoSplitter");
oRm.addClass(sOrientationClass);
if (bAnimate && !oControl._liveResize) {
// Do not animate via CSS when liveResize is enabled
oRm.addClass("sapUiLoSplitterAnimated");
}
oRm.writeClasses();
oRm.addStyle("width", oControl.getWidth());
oRm.addStyle("height", oControl.getHeight());
oRm.writeStyles();
oRm.write(">"); // main div
this.renderInitialContent(oRm, oControl);
oRm.write("</div>"); // main control
};
SplitterRenderer.renderInitialContent = function(oRm, oControl) {
var sId = oControl.getId();
var bHorizontal = oControl.getOrientation() === sap.ui.core.Orientation.Horizontal;
var sSizeType = bHorizontal ? "width" : "height";
var sGripIcon = "sap-icon://" + (bHorizontal ? "horizontal" : "vertical") + "-grip";
var aContents = oControl.getContentAreas();
var iLen = aContents.length;
var aCalculatedSizes = oControl.getCalculatedSizes();
for (var i = 0; i < iLen; ++i) {
var oLayoutData = aContents[i].getLayoutData();
var sSize = "0";
if (aCalculatedSizes[i]) {
// Use precalculated sizes if available
sSize = aCalculatedSizes[i] + "px";
} else if (oLayoutData) {
sSize = oLayoutData.getSize();
}
// Render content control
oRm.write(
"<section " +
"id=\"" + sId + "-content-" + i + "\" " +
"style=\"" + sSizeType + ": " + sSize + ";\" " +
"class=\"sapUiLoSplitterContent\">"
);
oRm.renderControl(aContents[i]);
oRm.write("</section>");
if (i < iLen - 1) {
// Render splitter if this is not the last control
oRm.write(
"<div id=\"" + sId + "-splitbar-" + i + "\" " +
"role=\"separator\" " +
"title=\"" + oControl._getText("SPLITTER_MOVE") + "\" " +
"class=\"sapUiLoSplitterBar\" " +
"aria-orientation=\"" + (bHorizontal ? "vertical" : "horizontal") + "\" " +
"tabindex=\"0\">"
);
// Icon ID must start with sId + "-splitbar-" + i so that the target is recognized for resizing
oRm.writeIcon(sGripIcon, "sapUiLoSplitterBarIcon", {
"id" : sId + "-splitbar-" + i + "-icon",
// prevent any tooltip / ARIA attributes on the icon as they
// are already set on the outer div
"title" : null,
"aria-label" : null
});
oRm.write("</div>");
}
}
oRm.write(
"<div id=\"" + sId + "-overlay\" class=\"sapUiLoSplitterOverlay\" style=\"display: none;\">" +
"<div id=\"" + sId + "-overlayBar\" class=\"sapUiLoSplitterOverlayBar\">"
);
// Icon ID must start with sId + "-splitbar" so that the target is recognized for resizing
oRm.writeIcon(sGripIcon, "sapUiLoSplitterBarIcon", {
"id" : sId + "-splitbar-Overlay-icon",
// prevent any tooltip / ARIA attributes on the icon as they
// are already set on the outer div
"title" : null,
"aria-label" : null
});
oRm.write(
"</div>" +
"</div>"
);
};
return SplitterRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/SplitterRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.VerticalLayout.designtime') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides the Design Time Metadata for the sap.ui.layout.VerticalLayout control
jQuery.sap.declare('sap.ui.layout.VerticalLayout.designtime'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/layout/VerticalLayout.designtime",[],
function() {
"use strict";
return {
defaultSettings : {
width : "100%"
},
aggregations : {
content : {
cssSelector : ":sap-domref"
}
},
name: "{name}",
description: "{description}"
};
}, /* bExport= */ false);
}; // end of sap/ui/layout/VerticalLayout.designtime.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.VerticalLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides default renderer for control sap.ui.layout.VerticalLayout
jQuery.sap.declare('sap.ui.layout.VerticalLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/VerticalLayoutRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* layout/VerticalLayout renderer.
* @namespace
*/
var VerticalLayoutRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
VerticalLayoutRenderer.render = function(oRenderManager, oVerticalLayout){
// convenience variable
var rm = oRenderManager;
// write the HTML into the render manager
rm.write("<DIV");
rm.writeControlData(oVerticalLayout);
rm.addClass("sapUiVlt");
rm.addClass("sapuiVlt"); // for compatibility keep the old, wrong class name
if (oVerticalLayout.getWidth() && oVerticalLayout.getWidth() != '') {
rm.addStyle("width", oVerticalLayout.getWidth());
}
rm.writeStyles();
rm.writeClasses();
rm.write(">"); // DIV element
// render content
var aContent = oVerticalLayout.getContent();
for ( var i = 0; i < aContent.length; i++) {
rm.write("<DIV class=\"sapUiVltCell sapuiVltCell\">"); // for compatibility keep the old, wrong class name
rm.renderControl(aContent[i]);
rm.write("</DIV>");
}
rm.write("</DIV>");
};
return VerticalLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/VerticalLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.Form.designtime') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides the Design Time Metadata for the sap.ui.layout.form.Form control
jQuery.sap.declare('sap.ui.layout.form.Form.designtime'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/layout/form/Form.designtime",[],
function() {
"use strict";
return {
aggregations : {
formContainers : {
getAggregationDomRef : function(sAggregationName) {
if (this.getLayout() instanceof sap.ui.layout.form.GridLayout) {
return ":sap-domref tbody";
} else {
return ":sap-domref > div";
}
}
}
},
name: "{name}",
description: "{description}"
};
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/Form.designtime.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.FormContainer.designtime') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides the Design Time Metadata for the sap.ui.layout.form.FormContainer control
jQuery.sap.declare('sap.ui.layout.form.FormContainer.designtime'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/layout/form/FormContainer.designtime",[],
function() {
"use strict";
return {
aggregations : {
formElements : {
domRef : ":sap-domref"
}
},
name: "{name}",
description: "{description}"
};
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/FormContainer.designtime.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.FormLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.form.FormLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/FormLayoutRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* FormLayout renderer.
* @namespace
*/
var FormLayoutRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oLayout an object representation of the control that should be rendered
*/
FormLayoutRenderer.render = function(oRenderManager, oLayout){
// convenience variable
var rm = oRenderManager;
var oForm = oLayout.getParent();
if (oForm && oForm instanceof sap.ui.layout.form.Form) {
this.renderForm(rm, oLayout, oForm);
}
};
/**
* Renders the HTML for the given form content, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} rm the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oLayout an object representation of the Layout control that should be rendered
* @param {sap.ui.layout.form.Form} oForm, a form control to render its content
*/
FormLayoutRenderer.renderForm = function(rm, oLayout, oForm){
rm.write("<div");
rm.writeControlData(oLayout);
rm.addClass(this.getMainClass());
rm.writeClasses();
rm.write(">");
// Form header
var sSize = sap.ui.core.theming.Parameters.get('sap.ui.layout.FormLayout:sapUiFormTitleSize');
this.renderTitle(rm, oForm.getTitle(), undefined, false, sSize, oForm.getId());
this.renderContainers(rm, oLayout, oForm);
rm.write("</div>");
};
FormLayoutRenderer.getMainClass = function(){
return "sapUiFormLayout";
};
FormLayoutRenderer.renderContainers = function(rm, oLayout, oForm){
var aContainers = oForm.getFormContainers();
for (var i = 0, il = aContainers.length; i < il; i++) {
var oContainer = aContainers[i];
if (oContainer.getVisible()) {
this.renderContainer(rm, oLayout, oContainer);
}
}
};
FormLayoutRenderer.renderContainer = function(rm, oLayout, oContainer){
var bExpandable = oContainer.getExpandable();
rm.write("<section");
rm.writeElementData(oContainer);
rm.addClass("sapUiFormContainer");
if (oContainer.getTooltip_AsString()) {
rm.writeAttributeEscaped('title', oContainer.getTooltip_AsString());
}
rm.writeClasses();
this.writeAccessibilityStateContainer(rm, oContainer);
rm.write(">");
this.renderTitle(rm, oContainer.getTitle(), oContainer._oExpandButton, bExpandable, sap.ui.core.TitleLevel.H4, oContainer.getId());
if (bExpandable) {
rm.write("<div id='" + oContainer.getId() + "-content'");
if (!oContainer.getExpanded()) {
rm.addStyle("display", "none");
rm.writeStyles();
}
rm.write(">");
}
var aElements = oContainer.getFormElements();
for (var j = 0, jl = aElements.length; j < jl; j++) {
var oElement = aElements[j];
if (oElement.getVisible()) {
this.renderElement(rm, oLayout, oElement);
}
}
if (bExpandable) {
rm.write("</div>");
}
rm.write("</section>");
};
FormLayoutRenderer.renderElement = function(rm, oLayout, oElement){
var oLabel = oElement.getLabelControl();
rm.write("<div");
rm.writeElementData(oElement);
rm.addClass("sapUiFormElement");
if (oLabel) {
rm.addClass("sapUiFormElementLbl");
}
rm.writeClasses();
rm.write(">");
if (oLabel) {
rm.renderControl(oLabel);
}
var aFields = oElement.getFields();
if (aFields && aFields.length > 0) {
for (var k = 0, kl = aFields.length; k < kl; k++) {
var oField = aFields[k];
rm.renderControl(oField);
}
}
rm.write("</div>");
};
/*
* Renders the title for a Form or a FormContainer
* If this function is overwritten in a Layout please use the right IDs to be sure aria-describedby works fine
*/
FormLayoutRenderer.renderTitle = function(rm, oTitle, oExpandButton, bExpander, sLevelDefault, sContentId){
if (oTitle) {
//determine title level -> if not set use H4 as default
var sLevel = sap.ui.core.theming.Parameters.get('sap.ui.layout.FormLayout:sapUiFormSubTitleSize');
if (sLevelDefault) {
sLevel = sLevelDefault;
}
if (typeof oTitle !== "string" && oTitle.getLevel() != sap.ui.core.TitleLevel.Auto) {
sLevel = oTitle.getLevel();
}
// just reuse TextView class because there font size & co. is already defined
rm.write("<" + sLevel + " ");
rm.addClass("sapUiFormTitle");
rm.addClass("sapUiFormTitle" + sLevel);
if (typeof oTitle !== "string") {
rm.writeElementData(oTitle);
if (oTitle.getTooltip_AsString()) {
rm.writeAttributeEscaped('title', oTitle.getTooltip_AsString());
}
if (oTitle.getEmphasized()) {
rm.addClass("sapUiFormTitleEmph");
}
} else {
rm.writeAttribute("id", sContentId + "--title");
}
rm.writeClasses();
rm.write(">");
if (bExpander && oExpandButton) {
rm.renderControl(oExpandButton);
}
if (typeof oTitle === "string") {
// Title is just a string
rm.writeEscaped(oTitle, true);
} else {
// title control
var sIcon = oTitle.getIcon();
if (sIcon) {
var aClasses = [];
var mAttributes = {
"title": null // prevent default icon tooltip
};
mAttributes["id"] = oTitle.getId() + "-ico";
rm.writeIcon(sIcon, aClasses, mAttributes);
}
rm.writeEscaped(oTitle.getText(), true);
}
rm.write("</" + sLevel + ">");
}
};
/*
* Writes the accessibility attributes for FormContainers
*/
FormLayoutRenderer.writeAccessibilityStateContainer = function(rm, oContainer){
var mAriaProps = {role: "form"};
var oTitle = oContainer.getTitle();
if (oTitle) {
var sId = "";
if (typeof oTitle == "string") {
sId = oContainer.getId() + "--title";
} else {
sId = oTitle.getId();
}
mAriaProps["labelledby"] = sId;
}
rm.writeAccessibilityState(oContainer, mAriaProps);
};
return FormLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/FormLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.FormRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.form.FormRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/FormRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* Form renderer.
* @namespace
*/
var FormRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oForm an object representation of the control that should be rendered
*/
FormRenderer.render = function(oRenderManager, oForm){
// convenience variable
var rm = oRenderManager;
var oLayout = oForm.getLayout();
// write only a DIV for the form and let the layout render the rest
rm.write("<div");
rm.writeControlData(oForm);
rm.addClass("sapUiForm");
rm.writeAttribute("data-sap-ui-customfastnavgroup", "true");
var sClass = sap.ui.layout.form.FormHelper.addFormClass();
if (sClass) {
rm.addClass(sClass);
}
if (oForm.getEditable()) {
rm.addClass("sapUiFormEdit");
rm.addClass("sapUiFormEdit-CTX");
}
if (oForm.getWidth()) {
rm.addStyle("width", oForm.getWidth());
}
if (oForm.getTooltip_AsString()) {
rm.writeAttributeEscaped('title', oForm.getTooltip_AsString());
}
rm.writeClasses();
rm.writeStyles();
var mAriaProps = {role: "form"};
var oTitle = oForm.getTitle();
if (oTitle) {
var sId = "";
if (typeof oTitle == "string") {
sId = oForm.getId() + "--title";
} else {
sId = oTitle.getId();
}
mAriaProps["labelledby"] = {value: sId, append: true};
}
rm.writeAccessibilityState(oForm, mAriaProps);
rm.write(">");
if (oLayout) {
// render the layout with the content of this form control
rm.renderControl(oLayout);
} else {
jQuery.sap.log.warning("Form \"" + oForm.getId() + "\" - Layout missing!", "Renderer", "Form");
}
rm.write("</div>");
};
return FormRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/FormRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.GridLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.form.GridLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/GridLayoutRenderer",['jquery.sap.global', 'sap/ui/core/Renderer', './FormLayoutRenderer'],
function(jQuery, Renderer, FormLayoutRenderer) {
"use strict";
/**
* form/GridLayout renderer.
* @namespace
*/
var GridLayoutRenderer = Renderer.extend(FormLayoutRenderer);
/**
* Renders the HTML for the given form content, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} rm the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oLayout an object representation of the Layout control that should be rendered
* @param {sap.ui.layout.form.Form} oForm, a form control to render its content
*/
GridLayoutRenderer.renderForm = function(rm, oLayout, oForm){
var bSingleColumn = oLayout.getSingleColumn();
var iColumns = 16;
var bSeparatorColumn = false;
var iColumnsHalf = 0;
var aContainers = oForm.getFormContainers();
var iContainerLength = aContainers.length;
var i = 0;
var oContainer;
var oContainerData;
if (bSingleColumn) {
iColumns = iColumns / 2;
iColumnsHalf = iColumns;
} else {
iColumnsHalf = iColumns / 2;
//check if the separator column is needed -> if there are half containers
for ( i = 0; i < iContainerLength; i++) {
oContainerData = this.getContainerData(oLayout, aContainers[i]);
if (oContainerData && oContainerData.getHalfGrid()) {
bSeparatorColumn = true;
break;
}
}
}
rm.write("<table role=\"presentation\"");
rm.writeControlData(oLayout);
rm.write(" cellpadding=\"0\" cellspacing=\"0\"");
rm.addStyle("border-collapse", "collapse");
rm.addStyle("table-layout", "fixed");
rm.addStyle("width", "100%");
rm.addClass("sapUiGrid");
rm.writeStyles();
rm.writeClasses();
rm.write(">");
rm.write("<colgroup>");
rm.write("<col span=" + iColumnsHalf + ">");
if (bSeparatorColumn) {
rm.write("<col class = \"sapUiGridSpace\"span=1>");
}
if (!bSingleColumn) {
rm.write("<col span=" + iColumnsHalf + ">");
}
rm.write("</colgroup><tbody>");
// form header as table header
if (oForm.getTitle()) {
var iTitleCells = iColumns;
if (bSeparatorColumn) {
iTitleCells++;
}
rm.write("<tr class=\"sapUiGridTitle\"><th colspan=" + iTitleCells + ">");
var sSize = sap.ui.core.theming.Parameters.get('sap.ui.layout.FormLayout:sapUiFormTitleSize');
this.renderTitle(rm, oForm.getTitle(), undefined, false, sSize, oForm.getId());
rm.write("</th></tr>");
}
i = 0;
var oContainer2;
var oContainerData2;
while (i < iContainerLength) {
oContainer = aContainers[i];
oContainer._checkProperties();
if (oContainer.getVisible()) {
oContainerData = this.getContainerData(oLayout, oContainer);
if (oContainerData && oContainerData.getHalfGrid() && !bSingleColumn) {
oContainer2 = aContainers[i + 1];
oContainerData2 = undefined;
if (oContainer2 && oContainer2.getVisible()) {
oContainerData2 = this.getContainerData(oLayout, oContainer2);
}
if (oContainerData2 && oContainerData2.getHalfGrid()) {
oContainer2._checkProperties();
this.renderContainerHalfSize(rm, oLayout, oContainer, oContainer2, iColumns);
i++;
} else {
// second container is full size or does not exist -> render only 1 container as half size
this.renderContainerHalfSize(rm, oLayout, oContainer, undefined, iColumns);
}
} else {
this.renderContainerFullSize(rm, oLayout, oContainer, iColumns, bSeparatorColumn);
}
}
i++;
}
if (!!sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version >= 9) {
// As IE9 is buggy with colspan and layout fixed if not all columns are defined least once
rm.write("<tr style=\"visibility:hidden;\">");
for ( i = 0; i < iColumns; i++) {
rm.write("<td style=\"visibility:hidden; padding:0; height: 0;\"></td>");
}
if (bSeparatorColumn) {
rm.write("<td style=\"visibility:hidden; padding:0; height: 0;\"></td>");
}
rm.write("</tr>");
}
rm.write("</tbody></table>");
};
GridLayoutRenderer.renderContainerFullSize = function(rm, oLayout, oContainer, iColumns, bSeparatorColumn){
var bExpandable = oContainer.getExpandable();
// as container has no own DOM Element no element data is rendered.
// This should not be a problem as it is an element, not a control.
// render Container tooltip at header cell
var sTooltip = oContainer.getTooltip_AsString();
// container header
if (oContainer.getTitle()) {
var iTitleCells = iColumns;
if (bSeparatorColumn) {
iTitleCells++;
}
rm.write("<tr><td colspan=" + iTitleCells + " class=\"sapUiGridHeader\"");
if (sTooltip) {
rm.writeAttributeEscaped('title', sTooltip);
}
rm.write(">");
this.renderTitle(rm, oContainer.getTitle(), oContainer._oExpandButton, bExpandable, false, oContainer.getId());
rm.write("</td></tr>");
}
if (!bExpandable || oContainer.getExpanded()) {
// container is not expandable or is expanded -> render elements
var aElements = oContainer.getFormElements();
var oElement;
var aReservedCells = [];
var bEmptyRow;
for (var j = 0, jl = aElements.length; j < jl; j++) {
oElement = aElements[j];
if (oElement.getVisible()) {
bEmptyRow = aReservedCells[0] && (aReservedCells[0][0] == iColumns);
rm.write("<tr");
if (!this.checkFullSizeElement(oLayout, oElement) && aReservedCells[0] != "full" && !bEmptyRow) {
rm.writeElementData(oElement);
rm.addClass("sapUiFormElement");
}
rm.writeClasses();
rm.write(">");
if (!bEmptyRow) {
aReservedCells = this.renderElement(rm, oLayout, oElement, false, iColumns, bSeparatorColumn, aReservedCells);
} else {
// the complete line is reserved -> render only an empty row
aReservedCells.splice(0,1);
}
rm.write("</tr>");
if (aReservedCells[0] == "full" || bEmptyRow) {
// this is a full size element -> just render it again in the next line
j = j - 1;
}
}
}
if (aReservedCells.length > 0) {
// still rowspans left -> render dummy rows to fill up
for ( var i = 0; i < aReservedCells.length; i++) {
rm.write("<tr></tr>");
}
}
}
};
// no bSeparartor needed because between 2 containers there must be a separator
GridLayoutRenderer.renderContainerHalfSize = function(rm, oLayout, oContainer1, oContainer2, iColumns){
var iContainerColumns = iColumns / 2;
var bExpandable1 = oContainer1.getExpandable();
var sTooltip1 = oContainer1.getTooltip_AsString();
var sTooltip2;
var oTitle1 = oContainer1.getTitle();
var oTitle2;
var aElements1 = [];
if (!bExpandable1 || oContainer1.getExpanded()) {
aElements1 = oContainer1.getFormElements();
}
var iLength1 = aElements1.length;
var aElements2 = [];
var iLength2 = 0;
var bExpandable2 = false;
if (oContainer2) {
bExpandable2 = oContainer2.getExpandable();
sTooltip2 = oContainer2.getTooltip_AsString();
oTitle2 = oContainer2.getTitle();
if (!bExpandable2 || oContainer2.getExpanded()) {
aElements2 = oContainer2.getFormElements();
}
iLength2 = aElements2.length;
}
if (oTitle1 || oTitle2) {
// render title row (if one container has a title, the other has none leave the cells empty)
rm.write("<tr><td colspan=" + iContainerColumns + " class=\"sapUiGridHeader\"");
if (sTooltip1) {
rm.writeAttributeEscaped('title', sTooltip1);
}
rm.write(">");
if (oTitle1) {
this.renderTitle(rm, oTitle1, oContainer1._oExpandButton, bExpandable1, false, oContainer1.getId());
}
rm.write("</td><td></td><td colspan=" + iContainerColumns + " class=\"sapUiGridHeader\"");
if (sTooltip2) {
rm.writeAttributeEscaped('title', sTooltip2);
}
rm.write(">");
if (oTitle2) {
this.renderTitle(rm, oTitle2, oContainer2._oExpandButton, bExpandable2, false, oContainer2.getId());
}
rm.write("</td></tr>");
}
if ((!bExpandable1 || oContainer1.getExpanded()) || (!bExpandable2 || oContainer2.getExpanded())) {
var aReservedCells1 = [],
aReservedCells2 = [];
var i1 = 0, i2 = 0;
var oElement1;
var oElement2;
var bEmptyRow1;
var bEmptyRow2;
while (i1 < iLength1 || i2 < iLength2) {
oElement1 = aElements1[i1];
oElement2 = aElements2[i2];
bEmptyRow1 = aReservedCells1[0] && (aReservedCells1[0][0] == iContainerColumns);
bEmptyRow2 = aReservedCells2[0] && (aReservedCells2[0][0] == iContainerColumns);
if ((oElement1 && oElement1.getVisible()) || (oElement2 && oElement2.getVisible()) || bEmptyRow1 || bEmptyRow2) {
rm.write("<tr>");
if (!bEmptyRow1) {
if (oElement1 && oElement1.getVisible() && (!bExpandable1 || oContainer1.getExpanded())) {
aReservedCells1 = this.renderElement(rm, oLayout, oElement1, true, iContainerColumns, false, aReservedCells1);
} else {
rm.write("<td colspan=" + iContainerColumns + "></td>");
}
if (aReservedCells1[0] != "full") {
i1++;
}
} else {
if (aReservedCells1[0][2] > 0) {
// render empty label cell
rm.write("<td colspan=" + aReservedCells1[0][2] + "></td>");
}
aReservedCells1.splice(0,1);
}
rm.write("<td></td>"); // separator column
if (!bEmptyRow2) {
if (oElement2 && oElement2.getVisible() && (!bExpandable2 || oContainer2.getExpanded())) {
aReservedCells2 = this.renderElement(rm, oLayout, oElement2, true, iContainerColumns, false, aReservedCells2);
} else {
rm.write("<td colspan=" + iContainerColumns + "></td>");
}
if (aReservedCells2[0] != "full") {
i2++;
}
} else {
if (aReservedCells2[0][2] > 0) {
// render empty label cell
rm.write("<td colspan=" + aReservedCells2[0][2] + "></td>");
}
aReservedCells2.splice(0,1);
}
rm.write("</tr>");
} else {
i1++;
i2++;
}
}
if (aReservedCells1.length > 0 || aReservedCells2.length > 0) {
// still rowspans left -> render dummy rows to fill up
for ( var i = 0; i < aReservedCells1.length || i < aReservedCells2.length; i++) {
rm.write("<tr></tr>");
}
}
}
};
/*
* aReservedCells : Array of already used cells of vCells (Rowspan) of previous elements, "full" if a full-size field
*/
GridLayoutRenderer.renderElement = function(rm, oLayout, oElement, bHalf, iCells, bSeparatorColumn, aReservedCells){
var oLabel = oElement.getLabelControl(); // do not use getLabel() because it returns just text if only text is maintained
var iLabelFromRowspan = 0;
var aFields = oElement.getFields();
var iCellsUsed = 0;
var iAutoCellsUsed = 0;
var bMiddleSet = false;
var iColspan = 1;
var iRowspan = 1;
var x = 0;
if (this.checkFullSizeElement(oLayout, oElement)) {
// field must be full size - render label in a separate row
if (aReservedCells.length > 0 && aReservedCells[0] != "full") {
// already rowspans left -> ignore full line and raise error
jQuery.sap.log.error("Element \"" + oElement.getId() + "\" - Too much fields for one row!", "Renderer", "GridLayout");
return aReservedCells;
}
if (bSeparatorColumn) {
iCells = iCells + 1;
}
if (oLabel && aReservedCells[0] != "full") {
rm.write("<td colspan=" + iCells + " class=\"sapUiFormElementLbl sapUiGridLabelFull\">");
rm.renderControl(oLabel);
rm.write("</td>");
return ["full"];
} else {
aReservedCells.splice(0,1);
iRowspan = this.getElementData(oLayout, aFields[0]).getVCells();
rm.write("<td colspan=" + iCells);
if (iRowspan > 1 && bHalf) {
// Rowspan on full size cells -> reserve cells for next line (makes only sense in half size containers);
rm.write(" rowspan=" + iRowspan);
for ( x = 0; x < iRowspan - 1; x++) {
aReservedCells.push([iCells, undefined, false]);
}
}
rm.write(" >");
rm.renderControl(aFields[0]);
rm.write("</td>");
return aReservedCells;
}
}
if (aReservedCells.length > 0 && aReservedCells[0][0] > 0) {
// already cells reserved by previous lines via vCells
// add label cells to free cells because they are reduced by rendering the label
iCells = iCells - aReservedCells[0][0] + aReservedCells[0][2];
bMiddleSet = aReservedCells[0][1];
iLabelFromRowspan = aReservedCells[0][2];
aReservedCells.splice(0,1);
}
var iLabelCells = iLabelFromRowspan;
var oElementData;
var sColspan = "";
if (oLabel || iLabelFromRowspan > 0) {
iLabelCells = 3;
if (oLabel && iLabelFromRowspan == 0) {
// if there is a rowspan in rows above, the label can not have a different size
oElementData = this.getElementData(oLayout, oLabel);
if (oElementData) {
sColspan = oElementData.getHCells();
if (sColspan != "auto" && sColspan != "full") {
iLabelCells = parseInt(sColspan, 10);
}
}
}
rm.write("<td colspan=" + iLabelCells + " class=\"sapUiFormElementLbl\">");
if (oLabel) {
rm.renderControl(oLabel);
}
iCells = iCells - iLabelCells;
rm.write("</td>");
}
if (aFields && aFields.length > 0) {
// calculate free cells for auto size
var iAutoCells = iCells;
var iAutoFields = aFields.length;
var oField;
var i = 0;
var il = 0;
for (i = 0, il = aFields.length; i < il; i++) {
oField = aFields[i];
oElementData = this.getElementData(oLayout, oField);
if (oElementData && oElementData.getHCells() != "auto") {
iAutoCells = iAutoCells - parseInt(oElementData.getHCells(), 10);
iAutoFields = iAutoFields - 1;
}
}
var iAutoI = 0;
for (i = 0, iAutoI = 0, il = aFields.length; i < il; i++) {
oField = aFields[i];
oElementData = this.getElementData(oLayout, oField);
sColspan = "auto";
iColspan = 1;
iRowspan = 1;
if (oElementData) {
sColspan = oElementData.getHCells();
iRowspan = oElementData.getVCells();
}
// calculate real colspan
if (sColspan == "auto") {
if (iAutoCells > 0) {
iColspan = Math.floor(iAutoCells / iAutoFields);
if (iColspan < 1) {
iColspan = 1;
}
iAutoI++;
iAutoCellsUsed = iAutoCellsUsed + iColspan;
if ((iAutoI == iAutoFields) && (iAutoCells > iAutoCellsUsed)) {
iColspan = iColspan + (iAutoCells - iAutoCellsUsed);
}
} else {
// no space for auto cells -> render it with 1 cell
iColspan = 1;
}
} else {
iColspan = parseInt(sColspan, 10);
}
iCellsUsed = iCellsUsed + iColspan;
if (iCellsUsed > iCells) {
// too much cells
jQuery.sap.log.error("Element \"" + oElement.getId() + "\" - Too much fields for one row!", "Renderer", "GridLayout");
iCellsUsed = iCellsUsed - iColspan; // to add empty dummy cell
break;
}
if (iRowspan > 1) {
// Rowspan is used -> reserve cells for next line
for ( x = 0; x < iRowspan - 1; x++) {
if (oLabel) {
iLabelFromRowspan = iLabelCells;
}
if (aReservedCells.length > x) {
aReservedCells[x][0] = aReservedCells[x][0] + iColspan;
aReservedCells[x][2] = iLabelFromRowspan;
} else {
aReservedCells.push([iLabelCells + iColspan, undefined, iLabelFromRowspan]);
}
}
}
if (bSeparatorColumn && iCellsUsed >= Math.floor(iCells / 2) && !bMiddleSet) {
// for the middle cell add the separator column
iColspan = iColspan + 1;
bMiddleSet = true;
if (iRowspan > 1) {
// Rowspan is used -> reserve cells for next line
for ( x = 0; x < iRowspan - 1; x++) {
aReservedCells[x][1] = true;
}
}
}
rm.write("<td");
if (iColspan > 1) {
rm.write(" colspan=" + iColspan);
}
if (iRowspan > 1) {
rm.write(" rowspan=" + iRowspan);
}
rm.write(" >");
rm.renderControl(oField);
rm.write("</td>");
}
}
if (iCellsUsed < iCells) {
// add an empty cell if not all cells are filled
var iEmpty = iCells - iCellsUsed;
if (!bHalf && bSeparatorColumn && !bMiddleSet) {
iEmpty++;
}
rm.write("<td colspan=" + iEmpty + " ></td>");
}
return aReservedCells;
};
GridLayoutRenderer.checkFullSizeElement = function(oLayout, oElement){
var aFields = oElement.getFields();
if (aFields.length == 1 && this.getElementData(oLayout, aFields[0]) && this.getElementData(oLayout, aFields[0]).getHCells() == "full") {
return true;
}else {
return false;
}
};
GridLayoutRenderer.getContainerData = function(oLayout, oContainer){
return oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.form.GridContainerData");
};
GridLayoutRenderer.getElementData = function(oLayout, oControl){
return oLayout.getLayoutDataForElement(oControl, "sap.ui.layout.form.GridElementData");
};
return GridLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/GridLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.ResponsiveGridLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.form.ResponsiveGridLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/ResponsiveGridLayoutRenderer",['jquery.sap.global', 'sap/ui/core/Renderer', './FormLayoutRenderer'],
function(jQuery, Renderer, FormLayoutRenderer) {
"use strict";
/**
* form/ResponsiveGridLayout renderer.
* @namespace
*/
var ResponsiveGridLayoutRenderer = Renderer.extend(FormLayoutRenderer);
ResponsiveGridLayoutRenderer.getMainClass = function(){
return "sapUiFormResGrid";
};
ResponsiveGridLayoutRenderer.renderContainers = function(rm, oLayout, oForm){
var aContainers = oForm.getFormContainers();
var aVisibleContainers = [];
var iLength = 0;
for ( var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
if (oContainer.getVisible()) {
iLength++;
aVisibleContainers.push(oContainer);
}
}
if (iLength > 0) {
// special case: only one container -> do not render an outer Grid
if (iLength > 1) {
//render Grid
rm.renderControl(oLayout._mainGrid);
} else if (oLayout.mContainers[aVisibleContainers[0].getId()][0]) {
// render panel
rm.renderControl(oLayout.mContainers[aVisibleContainers[0].getId()][0]);
} else {
// render Grid of container
rm.renderControl(oLayout.mContainers[aVisibleContainers[0].getId()][1]);
}
}
};
return ResponsiveGridLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/ResponsiveGridLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.ResponsiveLayoutRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.form.ResponsiveLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/ResponsiveLayoutRenderer",['jquery.sap.global', 'sap/ui/core/Renderer', './FormLayoutRenderer'],
function(jQuery, Renderer, FormLayoutRenderer) {
"use strict";
/**
* ResponsiveLayout renderer.
* @namespace
*/
var ResponsiveLayoutRenderer = Renderer.extend(FormLayoutRenderer);
ResponsiveLayoutRenderer.getMainClass = function(){
return "sapUiFormResLayout";
};
ResponsiveLayoutRenderer.renderContainers = function(rm, oLayout, oForm){
var aContainers = oForm.getFormContainers();
var iLength = 0;
for ( var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
if (oContainer.getVisible()) {
iLength++;
}
}
if (iLength > 0) {
// special case: only one container -> do not render an outer ResponsiveFlowLayout
if (iLength > 1) {
//render ResponsiveFlowLayout
rm.renderControl(oLayout._mainRFLayout);
} else if (oLayout.mContainers[aContainers[0].getId()][0]) {
// render panel
rm.renderControl(oLayout.mContainers[aContainers[0].getId()][0]);
} else {
// render ResponsiveFlowLayout of container
rm.renderControl(oLayout.mContainers[aContainers[0].getId()][1]);
}
}
};
return ResponsiveLayoutRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/ResponsiveLayoutRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.SimpleFormRenderer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare('sap.ui.layout.form.SimpleFormRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/SimpleFormRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* SimpleForm renderer.
* @namespace
*/
var SimpleFormRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
SimpleFormRenderer.render = function(oRm, oControl){
oControl._bChangedByMe = true;
// write the HTML into the render manager
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUiSimpleForm");
if (oControl.getWidth()) {
oRm.addStyle("width", oControl.getWidth());
}
oRm.writeStyles();
oRm.writeClasses();
oRm.write(">"); // div element
var oForm = oControl.getAggregation("form");
oRm.renderControl(oForm);
oRm.write("</div>");
oControl._bChangedByMe = false;
};
return SimpleFormRenderer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/SimpleFormRenderer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.library') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
/**
* Initialization Code and shared classes of library sap.ui.layout.
*/
jQuery.sap.declare('sap.ui.layout.library'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.base.DataType'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.library'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/library",['jquery.sap.global', 'sap/ui/base/DataType',
'sap/ui/core/library'], // library dependency
function(jQuery, DataType) {
"use strict";
/**
* SAPUI5 library with layout controls.
*
* @namespace
* @name sap.ui.layout
* @author SAP SE
* @version 1.32.10
* @public
*/
// delegate further initialization of this library to the Core
sap.ui.getCore().initLibrary({
name : "sap.ui.layout",
version: "1.32.10",
dependencies : ["sap.ui.core"],
types: [
"sap.ui.layout.GridIndent",
"sap.ui.layout.GridPosition",
"sap.ui.layout.GridSpan",
"sap.ui.layout.form.GridElementCells",
"sap.ui.layout.form.SimpleFormLayout"
],
interfaces: [],
controls: [
"sap.ui.layout.DynamicSideContent",
"sap.ui.layout.FixFlex",
"sap.ui.layout.Grid",
"sap.ui.layout.HorizontalLayout",
"sap.ui.layout.ResponsiveFlowLayout",
"sap.ui.layout.Splitter",
"sap.ui.layout.VerticalLayout",
"sap.ui.layout.form.Form",
"sap.ui.layout.form.FormLayout",
"sap.ui.layout.form.GridLayout",
"sap.ui.layout.form.ResponsiveGridLayout",
"sap.ui.layout.form.ResponsiveLayout",
"sap.ui.layout.form.SimpleForm"
],
elements: [
"sap.ui.layout.GridData",
"sap.ui.layout.ResponsiveFlowLayoutData",
"sap.ui.layout.SplitterLayoutData",
"sap.ui.layout.form.FormContainer",
"sap.ui.layout.form.FormElement",
"sap.ui.layout.form.GridContainerData",
"sap.ui.layout.form.GridElementData"
]
});
/**
* @classdesc A string type that represents Grid's indent values for large, medium and small screens. Allowed values are separated by space Letters L, M or S followed by number of columns from 1 to 11 that the container has to take, for example: "L2 M4 S6", "M11", "s10" or "l4 m4". Note that the parameters have to be provided in the order large medium small.
*
* @final
* @namespace
* @public
* @ui5-metamodel This simple type also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.GridIndent = DataType.createType('sap.ui.layout.GridIndent', {
isValid : function(vValue) {
return /^(([Xx][Ll](?:[0-9]|1[0-1]))? ?([Ll](?:[0-9]|1[0-1]))? ?([Mm](?:[0-9]|1[0-1]))? ?([Ss](?:[0-9]|1[0-1]))?)$/.test(vValue);
}
},
DataType.getType('string')
);
/**
* Position of the Grid. Can be "Left", "Center" or "Right". "Left" is default.
*
* @enum {string}
* @public
* @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.GridPosition = {
/**
* Grid is aligned left.
* @public
*/
Left : "Left",
/**
* Grid is aligned to the right.
* @public
*/
Right : "Right",
/**
* Grid is centered on the screen.
* @public
*/
Center : "Center"
};
/**
* @classdesc A string type that represents Grid's span values for large, medium and small screens. Allowed values are separated by space Letters L, M or S followed by number of columns from 1 to 12 that the container has to take, for example: "L2 M4 S6", "M12", "s10" or "l4 m4". Note that the parameters have to be provided in the order large medium small.
*
* @final
* @namespace
* @public
* @ui5-metamodel This simple type also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.GridSpan = DataType.createType('sap.ui.layout.GridSpan', {
isValid : function(vValue) {
return /^(([Xx][Ll](?:[1-9]|1[0-2]))? ?([Ll](?:[1-9]|1[0-2]))? ?([Mm](?:[1-9]|1[0-2]))? ?([Ss](?:[1-9]|1[0-2]))?)$/.test(vValue);
}
},
DataType.getType('string')
);
sap.ui.layout.form = sap.ui.layout.form || {};
/**
* @classdesc A string that defines the number of used cells in a <code>GridLayout</code>. This can be a number from 1 to 16, "auto" or "full".
* If set to "auto" the size is determined by the number of fields and the available cells. For labels the auto size is 3 cells.
* If set to "full" only one field is allowed within the <code>FormElement</code>. It gets the full width of the row and the label is displayed above. <b>Note:</b> For labels full size has no effect.
*
* @namespace
* @public
* @ui5-metamodel This simple type also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.form.GridElementCells = DataType.createType('sap.ui.layout.form.GridElementCells', {
isValid : function(vValue) {
return /^(auto|full|([1-9]|1[0-6]))$/.test(vValue);
}
},
DataType.getType('string')
);
/**
* Available <code>FormLayouts</code> used to render a <code>SimpleForm</code>.
*
* @enum {string}
* @public
* @since 1.16.0
* @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.form.SimpleFormLayout = {
/**
* Uses the <code>ResponsiveLayout</code> to render the <code>SimpleForm</code>
* @public
*/
ResponsiveLayout : "ResponsiveLayout",
/**
* Uses the <code>GridLayout</code> to render the <code>SimpleForm</code>
* @public
*/
GridLayout : "GridLayout",
/**
* Uses the <code>ResponsiveGridLayout</code> to render the <code>SimpleForm</code>
* @public
* @since 1.16.0
*/
ResponsiveGridLayout : "ResponsiveGridLayout"
};
/**
* Types of the DynamicSideContent Visibility options
*
* @enum {string}
* @public
* @since 1.30
* @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.SideContentVisibility = {
/**
* Show the side content on any breakpoint
* @public
*/
AlwaysShow: "AlwaysShow",
/**
* Show the side content on XL breakpoint
* @public
*/
ShowAboveL: "ShowAboveL",
/**
* Show the side content on L and XL breakpoints
* @public
*/
ShowAboveM: "ShowAboveM",
/**
* Show the side content on M, L and XL breakpoints
* @public
*/
ShowAboveS: "ShowAboveS",
/**
* Don't show the side content on any breakpoints
* @public
*/
NeverShow: "NeverShow"
};
/**
* Types of the DynamicSideContent FallDown options
*
* @enum {string}
* @public
* @since 1.30
* @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.layout.SideContentFallDown = {
/**
* Side content falls down on breakpoints below XL
* @public
*/
BelowXL: "BelowXL",
/**
* Side content falls down on breakpoints below L
* @public
*/
BelowL: "BelowL",
/**
* Side content falls down on breakpoints below M
* @public
*/
BelowM: "BelowM",
/**
* Side content falls down on breakpoint M and the minimum width for the side content
* @public
*/
OnMinimumWidth: "OnMinimumWidth"
};
// factory for Form to create labels an buttons to be overwritten by commons and mobile library
if (!sap.ui.layout.form.FormHelper) {
sap.ui.layout.form.FormHelper = {
createLabel: function(sText){ throw new Error("no Label control available!"); }, /* must return a Label control */
createButton: function(sId, fPressFunction, oThis){ throw new Error("no Button control available!"); }, /* must return a button control */
setButtonContent: function(oButton, sText, sTooltip, sIcon, sIconHovered){ throw new Error("no Button control available!"); },
addFormClass: function(){ return null; },
bArrowKeySupport: true, /* enables the keyboard support for arrow keys */
bFinal: false /* if true, the helper must not be overwritten by an other library */
};
}
return sap.ui.layout;
});
}; // end of sap/ui/layout/library.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.FixFlex') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.FixFlex.
jQuery.sap.declare('sap.ui.layout.FixFlex'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.EnabledPropagator'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.ResizeHandler'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/FixFlex",["jquery.sap.global", "sap/ui/core/Control", "sap/ui/core/EnabledPropagator", "sap/ui/core/ResizeHandler", "./library"],
function (jQuery, Control, EnabledPropagator, ResizeHandler, library) {
"use strict";
/**
* Constructor for a new FixFlex.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* The FixFlex control builds the container for a layout with a fixed and a flexible part. The flexible container adapts its size to the fix container. The fix container can hold any number of controls, while the flexible container can hold only one.
*
* In order for the FixFlex to stretch properly, the parent element, in which the control is placed, needs to have a specified height or needs to have an absolute position.
*
* Warning: Avoid nesting FixFlex in other flexbox based layout controls (FixFlex, FlexBox, Hbox, Vbox). Otherwise contents may be not accessible or multiple scrollbars can appear.
*
* Note: If the child control of the flex or the fix container has width/height bigger than the container itself, the child control will be cropped in the view. If minFlexSize is set, then a scrollbar is shown in the flexible part, depending on the vertical property.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.25.0
* @alias sap.ui.layout.FixFlex
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FixFlex = Control.extend("sap.ui.layout.FixFlex", /** @lends sap.ui.layout.FixFlex.prototype */ {
metadata: {
library: "sap.ui.layout",
properties: {
/**
* Determines the direction of the layout of child elements. True for vertical and false for horizontal layout.
*/
vertical: {type: "boolean", group: "Appearance", defaultValue: true},
/**
* Determines whether the fixed-size area should be on the beginning/top ( if the value is "true") or beginning/bottom ( if the value is "false").
*/
fixFirst: {type: "boolean", group: "Misc", defaultValue: true},
/**
* Determines the height (if the vertical property is "true") or the width (if the vertical property is "false") of the fixed area. If left at the default value "auto", the fixed-size area will be as large as its content. In this case the content cannot use percentage sizes.
*/
fixContentSize: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "auto"},
/**
* Enables scrolling inside the flexible part. The given size is calculated in "px". If the child control in the flexible part is larger then the available flexible size on the screen and if the available size for the flexible part is smaller or equal to the minFlexSize value, the scroll will be for the entire FixFlex control.
*
* @since 1.29
*/
minFlexSize: {type: "int", defaultValue: 0}
},
aggregations: {
/**
* Controls in the fixed part of the layout.
*/
fixContent: {type: "sap.ui.core.Control", multiple: true, singularName: "fixContent"},
/**
* Control in the stretching part of the layout.
*/
flexContent: {type: "sap.ui.core.Control", multiple: false}
}
}
});
EnabledPropagator.call(FixFlex.prototype);
/**
* Calculate height/width on the flex part when flexbox is not supported
*
* @private
*/
FixFlex.prototype._handlerResizeNoFlexBoxSupport = function () {
var $Control = this.$(),
$FixChild,
$FlexChild;
// Exit if the container is invisible
if (!$Control.is(":visible")) {
return;
}
$FixChild = this.$("Fixed");
$FlexChild = this.$("Flexible");
// Remove the style attribute from previous calculations
$FixChild.removeAttr("style");
$FlexChild.removeAttr("style");
if (this.getVertical()) {
$FlexChild.height(Math.floor($Control.height() - $FixChild.height()));
} else {
$FlexChild.width(Math.floor($Control.width() - $FixChild.width()));
$FixChild.width(Math.floor($FixChild.width()));
}
};
/**
* Deregister the control
*
* @private
*/
FixFlex.prototype._deregisterControl = function () {
// Deregister resize event
if (this.sResizeListenerNoFlexBoxSupportId) {
ResizeHandler.deregister(this.sResizeListenerNoFlexBoxSupportId);
this.sResizeListenerNoFlexBoxSupportId = null;
}
// Deregister resize event for Fixed part
if (this.sResizeListenerNoFlexBoxSupportFixedId) {
ResizeHandler.deregister(this.sResizeListenerNoFlexBoxSupportFixedId);
this.sResizeListenerNoFlexBoxSupportFixedId = null;
}
// Deregister resize event for FixFlex scrolling
if (this.sResizeListenerFixFlexScroll) {
ResizeHandler.deregister(this.sResizeListenerFixFlexScroll);
this.sResizeListenerFixFlexScroll = null;
}
// Deregister resize event for FixFlex scrolling for Flex part
if (this.sResizeListenerFixFlexScrollFlexPart) {
ResizeHandler.deregister(this.sResizeListenerFixFlexScrollFlexPart);
this.sResizeListenerFixFlexScrollFlexPart = null;
}
};
/**
* Change FixFlex scrolling position
* @private
*/
FixFlex.prototype._changeScrolling = function () {
var nFlexSize,
sDirection,
$this = this.$(),
nMinFlexSize = this.getMinFlexSize();
if (this.getVertical() === true) {
nFlexSize = this.$().height() - this.$("Fixed").height();
sDirection = "height";
} else {
nFlexSize = this.$().width() - this.$("Fixed").width();
sDirection = "width";
}
// Add scrolling inside Flexible container
if (nFlexSize < parseInt(this.getMinFlexSize(), 10)) {
$this.addClass("sapUiFixFlexScrolling");
$this.removeClass("sapUiFixFlexInnerScrolling");
// BCP Incident-ID: 1570246771
if (this.$("FlexibleContainer").children().height() > nMinFlexSize) {
this.$("Flexible").attr("style", "min-" + sDirection + ":" + nMinFlexSize + "px");
} else {
// If the child control is smaller then the content,
// the flexible part need to have set height/width, else the child control can"t resize to max
this.$("Flexible").attr("style", sDirection + ":" + nMinFlexSize + "px");
}
} else { // Add scrolling for entire FixFlex
$this.addClass("sapUiFixFlexInnerScrolling");
$this.removeClass("sapUiFixFlexScrolling");
this.$("Flexible").removeAttr("style");
}
};
/**
* @private
*/
FixFlex.prototype.exit = function () {
this._deregisterControl();
};
/**
* @private
*/
FixFlex.prototype.onBeforeRendering = function () {
this._deregisterControl();
};
/**
* @private
*/
FixFlex.prototype.onAfterRendering = function () {
// Fallback for older browsers
if (!jQuery.support.hasFlexBoxSupport) {
this.sResizeListenerNoFlexBoxSupportFixedId = ResizeHandler.register(this.getDomRef("Fixed"), jQuery.proxy(this._handlerResizeNoFlexBoxSupport, this));
this.sResizeListenerNoFlexBoxSupportId = ResizeHandler.register(this.getDomRef(), jQuery.proxy(this._handlerResizeNoFlexBoxSupport, this));
this._handlerResizeNoFlexBoxSupport();
}
// Add handler for FixFlex scrolling option
if (this.getMinFlexSize() !== 0) {
this.sResizeListenerFixFlexScroll = ResizeHandler.register(this.getDomRef(), jQuery.proxy(this._changeScrolling, this));
this.sResizeListenerFixFlexScrollFlexPart = ResizeHandler.register(this.getDomRef("Fixed"), jQuery.proxy(this._changeScrolling, this));
if (sap.ui.Device.browser.edge === true) {
// In some cases the resize handlers are not triggered in "Edge" browser on initial render and
// a manual trigger is needed
// BCP: 1570807842
this._changeScrolling();
}
}
};
/**
* @private
* @param {Object} oEvent
*/
FixFlex.prototype.ontouchmove = function (oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
};
return FixFlex;
}, /* bExport= */ true);
}; // end of sap/ui/layout/FixFlex.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.Grid') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.Grid.
jQuery.sap.declare('sap.ui.layout.Grid'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/Grid",['jquery.sap.global', 'sap/ui/core/Control', './library'],
function(jQuery, Control, library) {
"use strict";
/**
* Constructor for a new Grid.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* The Grid control is a layout which positions its child controls in a 12 column flow layout. Its children can be specified to take on a variable amount of columns depending on available screen size. With this control it is possible to achieve flexible layouts and line-breaks for extra large-, large-, medium- and small-sized screens, such as large desktop, desktop, tablet, and mobile. The Grid control's width can be percentage- or pixel-based and the spacing between its columns can be set to various pre-defined values.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.15.0
* @alias sap.ui.layout.Grid
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Grid = Control.extend("sap.ui.layout.Grid", /** @lends sap.ui.layout.Grid.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Optional. Width of the Grid. If not specified, then 100%.
*/
width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : '100%'},
/**
* Optional. Vertical spacing between the rows in the Grid. In rem, allowed values are 0, 0.5, 1 and 2.
*/
vSpacing : {type : "float", group : "Dimension", defaultValue : 1},
/**
* Optional. Horizontal spacing between the content in the Grid. In rem, allowed values are 0, 0.5 , 1 or 2.
*/
hSpacing : {type : "float", group : "Dimension", defaultValue : 1},
/**
* Optional. Position of the Grid in the window or surrounding container. Possible values are "Center", "Left" and "Right".
*/
position : {type : "sap.ui.layout.GridPosition", group : "Dimension", defaultValue : "Left"},
/**
* Optional. A string type that represents Grid's default span values for large, medium and small screens for the whole Grid. Allowed values are separated by space Letters L, M or S followed by number of columns from 1 to 12 that the container has to take, for example: "L2 M4 S6", "M12", "s10" or "l4 m4". Note that the parameters has to be provided in the order large medium small.
*/
defaultSpan : {type : "sap.ui.layout.GridSpan", group : "Behavior", defaultValue : "XL3 L3 M6 S12"},
/**
* Optional. Defines default for the whole Grid numbers of empty columns before the current span begins. It can be defined for large, medium and small screens. Allowed values are separated by space Letters L, M or S followed by number of columns from 0 to 11 that the container has to take, for example: "L2 M4 S6", "M11", "s10" or "l4 m4". Note that the parameters has to be provided in the order large medium small.
*/
defaultIndent : {type : "sap.ui.layout.GridIndent", group : "Behavior", defaultValue : "XL0 L0 M0 S0"},
/**
* If true then not the media Query ( device screen size), but the size of the container surrounding the grid defines the current range (large, medium or small).
*/
containerQuery : {type : "boolean", group : "Behavior", defaultValue : false}
},
defaultAggregation : "content",
aggregations : {
/**
* Controls that are placed into Grid layout.
*/
content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"}
}
}});
/**
* This file defines behavior for the control
*/
(function() {
Grid.prototype.init = function() {
this._iBreakPointTablet = sap.ui.Device.media._predefinedRangeSets[sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED].points[0];
this._iBreakPointDesktop = sap.ui.Device.media._predefinedRangeSets[sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED].points[1];
this._iBreakPointLargeDesktop = sap.ui.Device.media._predefinedRangeSets[sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED].points[2];
// Backward compatibility - if no any settings for XL - the settings for L are used
this._indentXLChanged = false;
this._spanXLChanged = false;
};
/**
* Used for after-rendering initialization.
*
* @private
*/
Grid.prototype.onAfterRendering = function() {
if (this.getContainerQuery()) {
this._sContainerResizeListener = sap.ui.core.ResizeHandler.register(this, jQuery.proxy(this._onParentResize, this));
this._onParentResize();
} else {
sap.ui.Device.media.attachHandler(this._handleMediaChange, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED);
}
};
Grid.prototype.onBeforeRendering = function() {
// Cleanup resize event registration before re-rendering
this._cleanup();
};
Grid.prototype.exit = function() {
// Cleanup resize event registration on exit
this._cleanup();
};
/**
* Clean up the control.
*
* @private
*/
Grid.prototype._cleanup = function() {
// Cleanup resize event registration
if (this._sContainerResizeListener) {
sap.ui.core.ResizeHandler.deregister(this._sContainerResizeListener);
this._sContainerResizeListener = null;
}
// Device Media Change handler
sap.ui.Device.media.detachHandler(this._handleMediaChange, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED);
};
Grid.prototype._handleMediaChange = function(oParams) {
this._toggleClass(oParams.name);
};
Grid.prototype._setBreakPointTablet = function( breakPoint) {
this._iBreakPointTablet = breakPoint;
};
Grid.prototype._setBreakPointDesktop = function( breakPoint) {
this._iBreakPointDesktop = breakPoint;
};
Grid.prototype._setBreakPointLargeDesktop = function( breakPoint) {
this._iBreakPointLargeDesktop = breakPoint;
};
Grid.prototype.setDefaultIndent = function( sDefaultIndent) {
if (/XL/gi.test(sDefaultIndent)) {
this._setIndentXLChanged(true);
}
this.setProperty("defaultIndent", sDefaultIndent);
};
Grid.prototype._setIndentXLChanged = function( bChanged) {
this._indentXLChanged = bChanged;
};
Grid.prototype._getIndentXLChanged = function() {
return this._indentXLChanged;
};
Grid.prototype.setDefaultSpan = function( sDefaultSpan) {
if (/XL/gi.test(sDefaultSpan)) {
this._setSpanXLChanged(true);
}
this.setProperty("defaultSpan", sDefaultSpan);
};
Grid.prototype._setSpanXLChanged = function( bChanged) {
this._spanXLChanged = bChanged;
};
Grid.prototype._getSpanXLChanged = function() {
return this._spanXLChanged;
};
Grid.prototype._onParentResize = function() {
var oDomRef = this.getDomRef();
// Prove if Dom reference exist, and if not - clean up the references.
if (!oDomRef) {
this._cleanup();
return;
}
if (!jQuery(oDomRef).is(":visible")) {
return;
}
var iCntWidth = oDomRef.clientWidth;
if (iCntWidth <= this._iBreakPointTablet) {
this._toggleClass("Phone");
} else if ((iCntWidth > this._iBreakPointTablet) && (iCntWidth <= this._iBreakPointDesktop)) {
this._toggleClass("Tablet");
} else if ((iCntWidth > this._iBreakPointDesktop) && (iCntWidth <= this._iBreakPointLargeDesktop)) {
this._toggleClass("Desktop");
} else {
this._toggleClass("LargeDesktop");
}
};
Grid.prototype._toggleClass = function(sMedia) {
var $DomRef = this.$();
if (!$DomRef) {
return;
}
if ($DomRef.hasClass("sapUiRespGridMedia-Std-" + sMedia)) {
return;
}
$DomRef.toggleClass("sapUiRespGridMedia-Std-" + sMedia, true);
if (sMedia === "Phone") {
$DomRef.toggleClass("sapUiRespGridMedia-Std-Desktop", false).toggleClass("sapUiRespGridMedia-Std-Tablet", false).toggleClass("sapUiRespGridMedia-Std-LargeDesktop", false);
} else if (sMedia === "Tablet") {
$DomRef.toggleClass("sapUiRespGridMedia-Std-Desktop", false).toggleClass("sapUiRespGridMedia-Std-Phone", false).toggleClass("sapUiRespGridMedia-Std-LargeDesktop", false);
} else if (sMedia === "LargeDesktop") {
$DomRef.toggleClass("sapUiRespGridMedia-Std-Desktop", false).toggleClass("sapUiRespGridMedia-Std-Phone", false).toggleClass("sapUiRespGridMedia-Std-Tablet", false);
} else {
$DomRef.toggleClass("sapUiRespGridMedia-Std-Phone", false).toggleClass("sapUiRespGridMedia-Std-Tablet", false).toggleClass("sapUiRespGridMedia-Std-LargeDesktop", false);
}
this.fireEvent("mediaChanged", {media: sMedia});
};
/*
* Get span information for the Control
* @param {sap.ui.core.Control} Control instance
* @return {Object} Grid layout data
* @private
*/
Grid.prototype._getLayoutDataForControl = function(oControl) {
var oLayoutData = oControl.getLayoutData();
if (!oLayoutData) {
return undefined;
} else if (oLayoutData instanceof sap.ui.layout.GridData) {
return oLayoutData;
} else if (oLayoutData.getMetadata().getName() == "sap.ui.core.VariantLayoutData") {
// multiple LayoutData available - search here
var aLayoutData = oLayoutData.getMultipleLayoutData();
for ( var i = 0; i < aLayoutData.length; i++) {
var oLayoutData2 = aLayoutData[i];
if (oLayoutData2 instanceof sap.ui.layout.GridData) {
return oLayoutData2;
}
}
}
};
/*
* If LayoutData is changed on one inner control, the whole grid needs to re-render
* because it may influence other rows and columns
*/
Grid.prototype.onLayoutDataChange = function(oEvent){
if (this.getDomRef()) {
// only if already rendered
this.invalidate();
}
};
/**
* Gets the role used for accessibility
* Set by the Form control if Grid represents a FormContainer
* @return {string} sRole accessibility role
* @since 1.28.0
* @private
*/
Grid.prototype._getAccessibleRole = function() {
return null;
};
}());
return Grid;
}, /* bExport= */ true);
}; // end of sap/ui/layout/Grid.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.GridData') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.GridData.
jQuery.sap.declare('sap.ui.layout.GridData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.LayoutData'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/GridData",['jquery.sap.global', 'sap/ui/core/LayoutData', './library'],
function(jQuery, LayoutData, library) {
"use strict";
/**
* Constructor for a new GridData.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Grid layout data
* @extends sap.ui.core.LayoutData
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.15.0
* @alias sap.ui.layout.GridData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var GridData = LayoutData.extend("sap.ui.layout.GridData", /** @lends sap.ui.layout.GridData.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* A string type that represents Grid's span values for large, medium and small screens. Allowed values are separated by space Letters L, M or S followed by number of columns from 1 to 12 that the container has to take, for example: "L2 M4 S6", "M12", "s10" or "l4 m4". Note that the parameters has to be provided in the order large medium small.
*/
span : {type : "sap.ui.layout.GridSpan", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for extra large screens. This value overwrites the value for extra large screens defined in the parameter "span".
*/
spanXL : {type : "int", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for large screens. This value overwrites the value for large screens defined in the parameter "span".
*/
spanL : {type : "int", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for medium size screens. This value overwrites the value for medium screens defined in the parameter "span".
*/
spanM : {type : "int", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for small screens. This value overwrites the value for small screens defined in the parameter "span".
*/
spanS : {type : "int", group : "Behavior", defaultValue : null},
/**
* A string type that represents Grid's span values for large, medium and small screens. Allowed values are separated by space Letters L, M or S followed by number of columns from 1 to 12 that the container has to take, for example: "L2 M4 S6", "M12", "s10" or "l4 m4". Note that the parameters has to be provided in the order large medium small.
*/
indent : {type : "sap.ui.layout.GridIndent", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for extra large screens. This value overwrites the value for extra large screens defined in the parameter "indent".
*/
indentXL : {type : "int", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for large screens. This value overwrites the value for large screens defined in the parameter "indent".
*/
indentL : {type : "int", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for medium size screens. This value overwrites the value for medium screens defined in the parameter "indent".
*/
indentM : {type : "int", group : "Behavior", defaultValue : null},
/**
* Optional. Defines a span value for small screens. This value overwrites the value for small screens defined in the parameter "indent".
*/
indentS : {type : "int", group : "Behavior", defaultValue : null},
/**
* Defines if this Control is visible on XL - extra Large screens.
*/
visibleXL : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* Defines if this Control is visible on Large screens.
*/
visibleL : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* Defines if this Control is visible on Medium size screens.
*/
visibleM : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* Defines if this Control is visible on small screens.
*/
visibleS : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* Optional. Moves a cell backwards so many columns as specified.
*/
moveBackwards : {type : "sap.ui.layout.GridIndent", group : "Misc", defaultValue : null},
/**
* Optional. Moves a cell forwards so many columns as specified.
*/
moveForward : {type : "sap.ui.layout.GridIndent", group : "Misc", defaultValue : null},
/**
* Optional. If this property is set to true, the control on all-size screens causes a line break within the Grid and becomes the first within the next line.
*/
linebreak : {type : "boolean", group : "Misc", defaultValue : false},
/**
* Optional. If this property is set to true, the control on extra large screens causes a line break within the Grid and becomes the first within the next line.
*/
linebreakXL : {type : "boolean", group : "Misc", defaultValue : false},
/**
* Optional. If this property is set to true, the control on large screens causes a line break within the Grid and becomes the first within the next line.
*/
linebreakL : {type : "boolean", group : "Misc", defaultValue : false},
/**
* Optional. If this property is set to true, the control on medium sized screens causes a line break within the Grid and becomes the first within the next line.
*/
linebreakM : {type : "boolean", group : "Misc", defaultValue : false},
/**
* Optional. If this property is set to true, the control on small screens causes a line break within the Grid and becomes the first within the next line.
*/
linebreakS : {type : "boolean", group : "Misc", defaultValue : false},
/**
* Deprecated. Defines a span value for large screens. This value overwrites the value for large screens defined in the parameter "span".
* @deprecated Since version 1.17.1.
* Use spanL instead.
*/
spanLarge : {type : "int", group : "Behavior", defaultValue : null, deprecated: true},
/**
* Deprecated. Defines a span value for medium size screens. This value overwrites the value for medium screens defined in the parameter "span".
* @deprecated Since version 1.17.1.
* Use spanM instead.
*/
spanMedium : {type : "int", group : "Behavior", defaultValue : null, deprecated: true},
/**
* Deprecated. Defines a span value for small screens. This value overwrites the value for small screens defined in the parameter "span".
* @deprecated Since version 1.17.1.
* Use spanS instead.
*/
spanSmall : {type : "int", group : "Behavior", defaultValue : null, deprecated: true},
/**
* Deprecated. Defines a span value for large screens. This value overwrites the value for large screens defined in the parameter "indent".
* @deprecated Since version 1.17.1.
* Use indentL instead.
*/
indentLarge : {type : "int", group : "Behavior", defaultValue : null, deprecated: true},
/**
* Deprecated. Defines a span value for medium size screens. This value overwrites the value for medium screens defined in the parameter "indent".
* @deprecated Since version 1.17.1.
* Use indentM instead.
*/
indentMedium : {type : "int", group : "Behavior", defaultValue : null, deprecated: true},
/**
* Deprecated. Defines a span value for small screens. This value overwrites the value for small screens defined in the parameter "indent".
* @deprecated Since version 1.17.1.
* Use indentS instead.
*/
indentSmall : {type : "int", group : "Behavior", defaultValue : null, deprecated: true},
/**
* Deprecated. Defines if this Control is visible on Large screens.
* @deprecated Since version 1.17.1.
* Use visibleL instead.
*/
visibleOnLarge : {type : "boolean", group : "Behavior", defaultValue : true, deprecated: true},
/**
* Deprecated. Defines if this Control is visible on Medium size screens.
* @deprecated Since version 1.17.1.
* Use visibleM instead.
*/
visibleOnMedium : {type : "boolean", group : "Behavior", defaultValue : true, deprecated: true},
/**
* Deprecated. Defines if this Control is visible on small screens.
* @deprecated Since version 1.17.1.
* Use visibleS instead.
*/
visibleOnSmall : {type : "boolean", group : "Behavior", defaultValue : true, deprecated: true}
}
}});
/**
* This file defines behavior for the control
*/
(function() {
GridData.prototype._setStylesInternal = function(sStyles) {
if (sStyles && sStyles.length > 0) {
this._sStylesInternal = sStyles;
} else {
this._sStylesInternal = undefined;
}
};
/*
* Get span information for the large screens
* @return {int} the value of the span
* @private
*/
GridData.prototype._getEffectiveSpanXLarge = function() {
var iSpan = this.getSpanXL();
if (iSpan && (iSpan > 0) && (iSpan < 13)) {
return iSpan;
}
var SPANPATTERN = /XL([1-9]|1[0-2])(?:\s|$)/i;
var aSpan = SPANPATTERN.exec(this.getSpan());
if (aSpan) {
var span = aSpan[0];
if (span) {
span = span.toUpperCase();
if (span.substr(0,2) === "XL") {
return parseInt(span.substr(1), 10);
}
}
}
return undefined;
};
/*
* Get span information for the large screens
* @return {int} the value of the span
* @private
*/
GridData.prototype._getEffectiveSpanLarge = function() {
var iSpan = this.getSpanL();
if (iSpan && (iSpan > 0) && (iSpan < 13)) {
return iSpan;
}
var SPANPATTERN = /L([1-9]|1[0-2])(?:\s|$)/i;
var aSpan = SPANPATTERN.exec(this.getSpan());
if (aSpan) {
var span = aSpan[0];
if (span) {
span = span.toUpperCase();
if (span.substr(0,1) === "L") {
return parseInt(span.substr(1), 10);
}
}
}
return undefined;
};
/*
* Get span information for the medium screens
* @return {int} the value of the span
* @private
*/
GridData.prototype._getEffectiveSpanMedium = function() {
var iSpan = this.getSpanM();
if (iSpan && (iSpan > 0) && (iSpan < 13)) {
return iSpan;
}
var SPANPATTERN = /M([1-9]|1[0-2])(?:\s|$)/i;
var aSpan = SPANPATTERN.exec(this.getSpan());
if (aSpan) {
var span = aSpan[0];
if (span) {
span = span.toUpperCase();
if (span.substr(0,1) === "M") {
return parseInt(span.substr(1), 10);
}
}
}
return undefined;
};
/*
* Get span information for the small screens
* @return {int} the value of the span
* @private
*/
GridData.prototype._getEffectiveSpanSmall = function() {
var iSpan = this.getSpanS();
if (iSpan && (iSpan > 0) && (iSpan < 13)) {
return iSpan;
}
var SPANPATTERN = /S([1-9]|1[0-2])(?:\s|$)/i;
var aSpan = SPANPATTERN.exec(this.getSpan());
if (aSpan) {
var span = aSpan[0];
if (span) {
span = span.toUpperCase();
if (span.substr(0,1) === "S") {
return parseInt(span.substr(1), 10);
}
}
}
return undefined;
};
// Identifier for explicit changed line break property for XL size
var _bLinebreakXLChanged = false;
// Finds out if the line break for XL was explicitly set
GridData.prototype.setLinebreakXL = function(bLinebreak) {
//set property XL
this.setProperty("linebreakXL", bLinebreak);
_bLinebreakXLChanged = true;
};
// Internal function. Informs the Grid Renderer if the line break property for XL size was changed explicitly
GridData.prototype._getLinebreakXLChanged = function(bLinebreak) {
return _bLinebreakXLChanged;
};
// Deprecated properties handling
//Setter
GridData.prototype.setSpanLarge = function(iSpan) {
this.setSpanL(iSpan);
jQuery.sap.log.warning("Deprecated property spanLarge is used, please use spanL instead.");
};
GridData.prototype.setSpanMedium = function(iSpan) {
this.setSpanM(iSpan);
jQuery.sap.log.warning("Deprecated property spanMedium is used, please use spanM instead.");
};
GridData.prototype.setSpanSmall = function(iSpan) {
this.setSpanS(iSpan);
jQuery.sap.log.warning("Deprecated property spanSmall is used, please use spanS instead.");
};
GridData.prototype.setIndentLarge = function(iIndent) {
this.setIndentL(iIndent);
jQuery.sap.log.warning("Deprecated property indentLarge is used, please use indentL instead.");
};
GridData.prototype.setIndentMedium = function(iIndent) {
this.setIndentM(iIndent);
jQuery.sap.log.warning("Deprecated property indentMedium is used, please use indentM instead.");
};
GridData.prototype.setIndentSmall = function(iIndent) {
this.setIndentS(iIndent);
jQuery.sap.log.warning("Deprecated property indentSmall is used, please use indentS instead.");
};
GridData.prototype.setVisibleOnLarge = function(bVisible) {
this.setVisibleL(bVisible);
jQuery.sap.log.warning("Deprecated property visibleOnLarge is used, please use visibleL instead.");
};
GridData.prototype.setVisibleOnMedium = function(bVisible) {
this.setVisibleM(bVisible);
jQuery.sap.log.warning("Deprecated property visibleOnMedium is used, please use visibleM instead.");
};
GridData.prototype.setVisibleOnSmall = function(bVisible) {
this.setVisibleS(bVisible);
jQuery.sap.log.warning("Deprecated property visibleOnSmall is used, please use visibleS instead.");
};
// Getter
GridData.prototype.getSpanLarge = function() {
jQuery.sap.log.warning("Deprecated property spanLarge is used, please use spanL instead.");
return this.getSpanL();
};
GridData.prototype.getSpanMedium = function() {
jQuery.sap.log.warning("Deprecated property spanMedium is used, please use spanM instead.");
return this.getSpanM();
};
GridData.prototype.getSpanSmall = function() {
jQuery.sap.log.warning("Deprecated property spanSmall is used, please use spanS instead.");
return this.getSpanS();
};
GridData.prototype.getIndentLarge = function() {
jQuery.sap.log.warning("Deprecated property indentLarge is used, please use indentL instead.");
return this.getIndentL();
};
GridData.prototype.getIndentMedium = function() {
jQuery.sap.log.warning("Deprecated property indentMedium is used, please use indentM instead.");
return this.getIndentM();
};
GridData.prototype.getIndentSmall = function() {
jQuery.sap.log.warning("Deprecated property indentSmall is used, please use indentS instead.");
return this.getIndentS();
};
GridData.prototype.getVisibleOnLarge = function() {
jQuery.sap.log.warning("Deprecated property visibleOnLarge is used, please use visibleL instead.");
return this.getVisibleL();
};
GridData.prototype.getVisibleOnMedium = function() {
jQuery.sap.log.warning("Deprecated property visibleOnMedium is used, please use visibleM instead.");
return this.getVisibleM();
};
GridData.prototype.getVisibleOnSmall = function() {
jQuery.sap.log.warning("Deprecated property visibleOnSmall is used, please use visibleS instead.");
return this.getVisibleS();
};
}());
return GridData;
}, /* bExport= */ true);
}; // end of sap/ui/layout/GridData.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.HorizontalLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.HorizontalLayout.
jQuery.sap.declare('sap.ui.layout.HorizontalLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/HorizontalLayout",['jquery.sap.global', 'sap/ui/core/Control', './library'],
function(jQuery, Control, library) {
"use strict";
/**
* Constructor for a new HorizontalLayout.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A layout that provides support for horizontal alignment of controls
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.HorizontalLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var HorizontalLayout = Control.extend("sap.ui.layout.HorizontalLayout", /** @lends sap.ui.layout.HorizontalLayout.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Specifies whether the content inside the Layout shall be line-wrapped in the case that there is less horizontal space available than required.
*/
allowWrapping : {type : "boolean", group : "Misc", defaultValue : false}
},
defaultAggregation : "content",
aggregations : {
/**
* The controls inside this layout
*/
content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"}
}
}});
return HorizontalLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/HorizontalLayout.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.ResponsiveFlowLayoutData') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.ResponsiveFlowLayoutData.
jQuery.sap.declare('sap.ui.layout.ResponsiveFlowLayoutData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.LayoutData'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/ResponsiveFlowLayoutData",['jquery.sap.global', 'sap/ui/core/LayoutData', './library'],
function(jQuery, LayoutData, library) {
"use strict";
/**
* Constructor for a new ResponsiveFlowLayoutData.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* This is a LayoutData Element that can be added to a control if this control is used within a ResponsiveFlowLayout
* @extends sap.ui.core.LayoutData
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.ResponsiveFlowLayoutData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ResponsiveFlowLayoutData = LayoutData.extend("sap.ui.layout.ResponsiveFlowLayoutData", /** @lends sap.ui.layout.ResponsiveFlowLayoutData.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* This is the minimal size in pixels of an ResponsiveFlowLayout element. The element will be shrinked till this value.
*/
minWidth : {type : "int", group : "Misc", defaultValue : 100},
/**
* This is the weight of the element that influences the resulting width. If there are several elements within a row of the ResponsiveFlowLayout each element could have another weight. The bigger the weight of a single element the wider it will be pumped up --> a bigger weight result a bigger width.
*/
weight : {type : "int", group : "Misc", defaultValue : 1},
/**
* If this property is set the control where this LayoutData is added to will always cause a linebreak within the ResponsiveFlowLayout
*/
linebreak : {type : "boolean", group : "Misc", defaultValue : false},
/**
* This property prevents any margin of the element if set to false
*/
margin : {type : "boolean", group : "Misc", defaultValue : true},
/**
* If this value shows if an element can be wrapped into a new line. If this value is set to false, the min-width will be set to 0 and the wrapping is up to the previous element.
*/
linebreakable : {type : "boolean", group : "Misc", defaultValue : true}
}
}});
ResponsiveFlowLayoutData.MIN_WIDTH = 100;
ResponsiveFlowLayoutData.WEIGHT = 1;
ResponsiveFlowLayoutData.LINEBREAK = false;
ResponsiveFlowLayoutData.MARGIN = true;
ResponsiveFlowLayoutData.LINEBREAKABLE = true;
ResponsiveFlowLayoutData.prototype.setWeight = function(iWeight) {
if (iWeight >= 1) {
this.setProperty("weight", iWeight);
} else {
jQuery.sap.log.warning("Values smaller than 1 are not valid. Default value '1' is used instead", this);
this.setProperty("weight", ResponsiveFlowLayoutData.WEIGHT);
}
return this;
};
ResponsiveFlowLayoutData.prototype.setLinebreak = function(bLinebreak) {
// if the element should not be linebreakable and a forced linebreak should
// be set
if (this.getLinebreakable() == false && bLinebreak) {
jQuery.sap.log.warning("Setting 'linebreak' AND 'linebreakable' doesn't make any sense! Please set either 'linebreak' or 'linebreakable'", this);
} else {
this.setProperty("linebreak", bLinebreak);
}
};
ResponsiveFlowLayoutData.prototype.setLinebreakable = function(bLinebreakable) {
// if the element has a forced linebreak and the element should be set to
// not linebreakable
if (this.getLinebreak() === true && bLinebreakable === false) {
jQuery.sap.log.warning("Setting 'linebreak' AND 'linebreakable' doesn't make any sense! Please set either 'linebreak' or 'linebreakable'", this);
} else {
this.setProperty("linebreakable", bLinebreakable);
// this.setMinWidth(0);
}
};
return ResponsiveFlowLayoutData;
}, /* bExport= */ true);
}; // end of sap/ui/layout/ResponsiveFlowLayoutData.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.Splitter') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.Splitter.
jQuery.sap.declare('sap.ui.layout.Splitter'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/Splitter",['jquery.sap.global', 'sap/ui/core/Control', './library'],
function(jQuery, Control, library) {
"use strict";
/**
* Constructor for a new Splitter.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
*
* A layout that contains several content areas. The content that is added to the splitter should contain LayoutData of the type SplitterLayoutData that defines its size and size contraints.
*
* By adding or changing SplitterLayoutData to the controls that make up the content areas, the size can be changed programatically. Additionally the contents can be made non-resizable individually and a minimal size (in px) can be set.
*
* The orientation of the splitter can be set to horizontal (default) or vertical. All content areas of the splitter will be arranged in that way. In order to split vertically and horizontally at the same time, Splitters need to be nested.
*
* The splitter bars can be focused to enable resizing of the content areas via keyboard. The contents size can be manipulated when the splitter bar is focused and Shift-Left/Down/Right/Up are pressed. When Shift-Home/End are pressed, the contents are set their minimum or maximum size (keep in mind though, that resizing an auto-size content-area next to another auto-size one might lead to the effect that the former does not take its maximum size but only the maximum size before recalculating auto sizes).
*
* The splitter bars used for resizing the contents by the user can be set to different widths (or heights in vertical mode) and the splitter will automatically resize the other contents accordingly. In case the splitter bar is resized after the splitter has rendered, a manual resize has to be triggered by invoking triggerResize() on the Splitter.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.22.0
* @alias sap.ui.layout.Splitter
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Splitter = Control.extend("sap.ui.layout.Splitter", /** @lends sap.ui.layout.Splitter.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Whether to split the contents horizontally (default) or vertically.
*/
orientation : {type : "sap.ui.core.Orientation", group : "Behavior", defaultValue : sap.ui.core.Orientation.Horizontal},
/**
* The width of the control
*/
width : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '100%'},
/**
* The height of the control
*/
height : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '100%'}
},
defaultAggregation : "contentAreas",
aggregations : {
/**
* The content areas to be split. The control will show n-1 splitter bars between n controls in this aggregation.
*/
contentAreas : {type : "sap.ui.core.Control", multiple : true, singularName : "contentArea"}
},
events : {
/**
* Event is fired when contents are resized.
*/
resize : {
parameters : {
/**
* The ID of the splitter control. The splitter control can also be accessed by calling getSource() on the event.
*/
id : {type : "string"},
/**
* An array of values representing the old (pixel-)sizes of the splitter contents
*/
oldSizes : {type : "int[]"},
/**
* An array of values representing the new (pixel-)sizes of the splitter contents
*/
newSizes : {type : "int[]"}
}
}
}
}});
// "Hidden" resource bundle instance
var oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.layout");
//////////////////////////////////////// "Static" Properties ///////////////////////////////////////
////////////////////////////////////////// Public Methods //////////////////////////////////////////
Splitter.prototype.init = function() {
this._needsInvalidation = false;
this._liveResize = true;
this._keyboardEnabled = true;
this._bHorizontal = true;
/** @type {Number[]} */
this._calculatedSizes = [];
this._move = {};
this._resizeTimeout = null;
// Context bound method for easy (de-)registering at the ResizeHandler
this._resizeCallback = this._delayedResize.bind(this);
this._resizeHandlerId = null;
// We need the information whether auto resize is enabled to temporarily disable it
// during live resize and then set it back to the value before
this._autoResize = true;
this.enableAutoResize();
// Bound versions for event handler registration
this._boundBarMoveEnd = this._onBarMoveEnd.bind(this);
this._boundBarMove = this._onBarMove.bind(this);
// Switch resizing parameters based on orientation - this must be done to initialize the values
this._switchOrientation();
this._bRtl = sap.ui.getCore().getConfiguration().getRTL();
// Create bound listener functions for keyboard event handling
this._keyListeners = {
increase : this._onKeyboardResize.bind(this, "inc"),
decrease : this._onKeyboardResize.bind(this, "dec"),
increaseMore : this._onKeyboardResize.bind(this, "incMore"),
decreaseMore : this._onKeyboardResize.bind(this, "decMore"),
max : this._onKeyboardResize.bind(this, "max"),
min : this._onKeyboardResize.bind(this, "min")
};
this._enableKeyboardListeners();
// Flag tracking the preserved state of this control. In case the control is preserved, no resizing attempts should be made.
this._isPreserved = false;
sap.ui.getCore().getEventBus().subscribe("sap.ui","__preserveContent", this._preserveHandler, this);
};
Splitter.prototype.exit = function() {
sap.ui.getCore().getEventBus().unsubscribe("sap.ui","__preserveContent", this._preserveHandler);
this.disableAutoResize();
delete this._resizeCallback;
delete this._boundBarMoveEnd;
delete this._boundBarMove;
delete this._$SplitterOverlay;
delete this._$SplitterOverlayBar;
};
/**
* This method triggers a resize on the Splitter - meaning it forces the Splitter to recalculate
* all sizes.
* This method should only be used in rare cases, for example when the CSS that defines the sizes
* of the splitter bars changes without triggering a rerendering of the splitter.
*
* @param {boolean} [forceDirectly=false] Do not delay the resize, trigger it right now.
* @public
*/
Splitter.prototype.triggerResize = function(forceDirectly) {
if (forceDirectly) {
this._resize();
} else {
this._delayedResize();
}
};
//////////////////////////////////////// "Protected" Methods ///////////////////////////////////////
/**
* Returns the current actual content sizes as pixel value - these values can change with every
* resize.
*
* @returns {Number[]} Array of px values that correspond to the content area sizes
* @protected
* @deprecated This method is declared as protected in order to assess the need for this feature. It is declared as deprecated because the API might change in case the need for this is high enough to make it part of the official Splitter interface
*/
Splitter.prototype.getCalculatedSizes = function() {
return this._calculatedSizes;
};
/**
* Enables the resize handler for this control, this leads to an automatic resize of
* the contents whenever the control changes its size. The resize handler is enabled
* in every control instance by default.
* For performance reasons this behavior can be disabled by calling disableAutoResize()
*
* @param {bool} [bTemporarily=false] Only enables autoResize if it was previously disabled temporarily (used for live resize)
* @protected
* @deprecated This method is declared as protected in order to assess the need for this feature. It is declared as deprecated because the API might change in case the need for this is high enough to make it part of the official Splitter interface
*/
Splitter.prototype.enableAutoResize = function(bTemporarily) {
// Do not enable autoResize if it was deactivated temporarily and wasn't enabled before
if (bTemporarily && !this._autoResize) {
return;
}
this._autoResize = true;
var that = this;
sap.ui.getCore().attachInit(function() {
that._resizeHandlerId = sap.ui.core.ResizeHandler.register(that, that._resizeCallback);
});
this._delayedResize();
};
/**
* Disables the resize handler for this control, this leads to an automatic resize of
* the contents whenever the control changes its size. The resize handler is enabled
* in every control instance by default.
* For performance reasons this behavior can be disabled by calling disableAutoResize()
*
* @param {bool} [bTemporarily=false] Only disable autoResize temporarily (used for live resize), so that the previous status can be restored afterwards
* @protected
* @deprecated This method is declared as protected in order to assess the need for this feature. It is declared as deprecated because the API might change in case the need for this is high enough to make it part of the official Splitter interface
*/
Splitter.prototype.disableAutoResize = function(bTemporarily) {
sap.ui.core.ResizeHandler.deregister(this._resizeHandlerId);
if (!bTemporarily) {
this._autoResize = false;
}
};
/**
* Enables recalculation and resize of the splitter contents while dragging the splitter bar.
* This means that the contents are resized several times per second when moving the splitter bar.
*
* @protected
* @deprecated This method is declared as protected in order to assess the need for this feature. It is declared as deprecated because the API might change in case the need for this is high enough to make it part of the official Splitter interface
*/
Splitter.prototype.enableLiveResize = function() {
this._liveResize = true;
this.$().toggleClass("sapUiLoSplitterAnimated", false);
};
/**
* Disables recalculation and resize of the splitter contents while dragging the splitter bar.
* This means that the contents are resized only once after moving the splitter bar.
*
* @protected
* @deprecated This method is declared as protected in order to assess the need for this feature. It is declared as deprecated because the API might change in case the need for this is high enough to make it part of the official Splitter interface
*/
Splitter.prototype.disableLiveResize = function() {
this._liveResize = false;
this.$().toggleClass("sapUiLoSplitterAnimated", true);
};
/**
* Enables the resizing of the Splitter contents via keyboard. This makes the Splitter bars
* focussable elements.
*
* @protected
*/
Splitter.prototype.enableKeyboardSupport = function() {
// TODO: Decide whether to move this functionality to a property.
var $Bars = this.$().find(".sapUiLoSplitterBar");
$Bars.attr("tabindex", "0");
this._enableKeyboardListeners();
};
/**
* Disables the resizing of the Splitter contents via keyboard. This changes the Splitter bars
* to non-focussable elements.
*
* @protected
*/
Splitter.prototype.disableKeyboardSupport = function() {
// TODO: Decide whether to move this functionality to a property.
var $Bars = this.$().find(".sapUiLoSplitterBar");
$Bars.attr("tabindex", "-1");
this._disableKeyboardListeners();
};
////////////////////////////////////////// onEvent Methods /////////////////////////////////////////
Splitter.prototype.onBeforeRendering = function() {
this._switchOrientation();
};
/**
* After Rendering, this method is called, it can be used to manipulate the DOM which has already
* been written. Its main function is to move the previously rendered DOM from the hidden area to
* the main splitter area and apply correct sizing.
*/
Splitter.prototype.onAfterRendering = function() {
// Create overlay DOM element for resizing
this._$SplitterOverlay = this.$("overlay");
this._$SplitterOverlayBar = this.$("overlayBar");
this._$SplitterOverlay.detach();
// Upon new rendering, the DOM cannot be preserved any more
this._isPreserved = false;
// Calculate and apply correct sizes to the Splitter contents
this._resize();
};
/**
* When one or several of the child controls change their layoutData, the Splitter must
* recalculate the sizes of its content areas.
*
* @private
*/
Splitter.prototype.onLayoutDataChange = function() {
this._delayedResize();
};
/**
* Starts the resize of splitter contents (when the bar is moved by touch)
*
* @param {jQuery.Event} [oJEv] The jQuery event
* @private
*/
Splitter.prototype.ontouchstart = function(oJEv) {
if (this._ignoreTouch) {
return;
}
var sId = this.getId();
if (!oJEv.target.id || oJEv.target.id.indexOf(sId + "-splitbar") != 0) {
// The clicked element was not one of my splitter bars
return;
}
if (!oJEv.changedTouches || !oJEv.changedTouches[0]) {
// No touch in event
return;
}
this._ignoreMouse = true;
this._onBarMoveStart(oJEv.changedTouches[0], true);
};
/**
* Starts the resize of splitter contents (when the bar is moved by mouse)
*
* @param {jQuery.Event} [oJEv] The jQuery event
* @private
*/
Splitter.prototype.onmousedown = function(oJEv) {
if (this._ignoreMouse) {
return;
}
var sId = this.getId();
if (!oJEv.target.id || oJEv.target.id.indexOf(sId + "-splitbar") != 0) {
// The clicked element was not one of my splitter bars
return;
}
this._ignoreTouch = true;
this._onBarMoveStart(oJEv);
};
/**
* Starts a resize (for touch and click)
*
* @param {jQuery.Event} [oJEv] The jQuery event
* @param {bool} [bTouch] Whether the first parameter is a touch event
* @private
*/
Splitter.prototype._onBarMoveStart = function(oJEv, bTouch) {
var sId = this.getId();
// Disable auto resize during bar move
this.disableAutoResize(/* temporarily: */ true);
var iPos = oJEv[this._moveCord];
var iBar = parseInt(oJEv.target.id.substr((sId + "-splitbar-").length), 10);
var $Bar = jQuery(oJEv.target);
var mCalcSizes = this.getCalculatedSizes();
var iBarSize = this._bHorizontal ? $Bar.innerWidth() : $Bar.innerHeight();
var aContentAreas = this.getContentAreas();
var oLd1 = aContentAreas[iBar].getLayoutData();
var oLd2 = aContentAreas[iBar + 1].getLayoutData();
if (!oLd1.getResizable() || !oLd2.getResizable()) {
// One of the contentAreas is not resizable, do not resize
// Also: disallow text-marking behavior when not moving bar
_preventTextSelection(bTouch);
return;
}
// Calculate relative starting position of the bar for virtual bar placement
var iRelStart = 0 - iBarSize;
for (var i = 0; i <= iBar; ++i) {
iRelStart += mCalcSizes[i] + iBarSize;
}
this._move = {
// Start coordinate
start : iPos,
// Relative starting position of the bar
relStart : iRelStart,
// The number of the bar that is moved
barNum : iBar,
// The splitter bar that is moved
bar : jQuery(oJEv.target),
// The content sizes for fast resize bound calculation
c1Size : mCalcSizes[iBar],
c1MinSize : oLd1 ? parseInt(oLd1.getMinSize(), 10) : 0,
c2Size : mCalcSizes[iBar + 1],
c2MinSize : oLd2 ? parseInt(oLd2.getMinSize(), 10) : 0
};
// Event handlers use bound handler methods - see init()
if (bTouch) {
// this._ignoreMouse = true; // Ignore mouse-events until touch is done
document.addEventListener("touchend", this._boundBarMoveEnd);
document.addEventListener("touchmove", this._boundBarMove);
} else {
document.addEventListener("mouseup", this._boundBarMoveEnd);
document.addEventListener("mousemove", this._boundBarMove);
}
this._$SplitterOverlay.css("display", "block"); // Needed because it is set to none in renderer
this._$SplitterOverlay.appendTo(this.getDomRef());
this._$SplitterOverlayBar.css(this._sizeDirNot, "");
this._move["bar"].css("visibility", "hidden");
this._onBarMove(oJEv);
};
Splitter.prototype._onBarMove = function(oJEv) {
if (oJEv.preventDefault) { oJEv.preventDefault(); } // Do not select text
var oEvent = oJEv;
if (oJEv.changedTouches && oJEv.changedTouches[0]) {
// Touch me baby!
oEvent = oJEv.changedTouches[0];
}
var iPos = oEvent[this._moveCord];
var iDelta = (iPos - this._move.start);
iDelta = this._bRtl ? -iDelta : iDelta;
var c1NewSize = this._move.c1Size + iDelta;
var c2NewSize = this._move.c2Size - iDelta;
var bInBounds = (
c1NewSize >= 0
&& c2NewSize >= 0
&& c1NewSize >= this._move.c1MinSize
&& c2NewSize >= this._move.c2MinSize
);
// Move virtual splitter bar
if (bInBounds) {
this._$SplitterOverlayBar.css(this._sizeDir, this._move.relStart + iDelta);
if (this._liveResize) {
var fMove = (this._move["start"] - oEvent[this._moveCord]);
this._resizeContents(
/* left content number: */ this._move["barNum"],
/* number of pixels: */ this._bRtl ? fMove : -fMove,
/* also change layoutData: */ false
);
}
}
};
/**
* Ends the resize of splitter contents (when the bar is moved)
*
* @param {jQuery.Event} [oJEv] The jQuery event
* @private
*/
Splitter.prototype._onBarMoveEnd = function(oJEv) {
this._ignoreMouse = false;
this._ignoreTouch = false;
var oEvent = oJEv;
if (oJEv.changedTouches && oJEv.changedTouches[0]) {
// Touch me baby!
oEvent = oJEv.changedTouches[0];
}
var iPos = oEvent[this._moveCord];
var fMove = this._move["start"] - iPos;
this._resizeContents(
/* left content number: */ this._move["barNum"],
/* number of pixels: */ this._bRtl ? fMove : -fMove,
/* also change layoutData: */ true
);
// Remove resizing overlay
this._move["bar"].css("visibility", "");
this._$SplitterOverlay.css("display", ""); // Remove?
this._$SplitterOverlay.detach();
// Uses bound handler methods - see init()
document.removeEventListener("mouseup", this._boundBarMoveEnd);
document.removeEventListener("mousemove", this._boundBarMove);
document.removeEventListener("touchend", this._boundBarMoveEnd);
document.removeEventListener("touchmove", this._boundBarMove);
// Enable auto resize after bar move if it was enabled before
this.enableAutoResize(/* temporarily: */ true);
jQuery.sap.focus(this._move.bar);
};
/**
* Resizes the contents after a bar has been moved
*
* @param {Number} [iLeftContent] Number of the first (left) content that is resized
* @param {Number} [iPixels] Number of pixels to increase the first and decrease the second content
* @param {bool} [bFinal] Whether this is the final position (sets the size in the layoutData of the
* content areas)
*/
Splitter.prototype._resizeContents = function(iLeftContent, iPixels, bFinal) {
if (isNaN(iPixels)) {
jQuery.sap.log.warning("Splitter: Received invalid resizing values - resize aborted.");
return;
}
var aContentAreas = this.getContentAreas();
var oLd1 = aContentAreas[iLeftContent].getLayoutData();
var oLd2 = aContentAreas[iLeftContent + 1].getLayoutData();
var sSize1 = oLd1.getSize();
var sSize2 = oLd2.getSize();
var $Cnt1 = this.$("content-" + iLeftContent);
var $Cnt2 = this.$("content-" + (iLeftContent + 1));
var iNewSize1 = this._move.c1Size + iPixels;
var iNewSize2 = this._move.c2Size - iPixels;
var iMinSize1 = parseInt(oLd1.getMinSize(), 10);
var iMinSize2 = parseInt(oLd2.getMinSize(), 10);
// Adhere to size constraints
var iDiff;
if (iNewSize1 < iMinSize1) {
iDiff = iMinSize1 - iNewSize1;
iPixels += iDiff;
iNewSize1 = iMinSize1;
iNewSize2 -= iDiff;
} else if (iNewSize2 < iMinSize2) {
iDiff = iMinSize2 - iNewSize2;
iPixels -= iDiff;
iNewSize2 = iMinSize2;
iNewSize1 -= iDiff;
}
if (bFinal) {
// Resize finished, set layout data in content areas
if (sSize1 === "auto" && sSize2 !== "auto") {
// First pane has auto size - only change size of second pane
oLd2.setSize(iNewSize2 + "px");
} else if (sSize1 !== "auto" && sSize2 === "auto") {
// Second pane has auto size - only change size of first pane
oLd1.setSize(iNewSize1 + "px");
} else {
// TODO: What do we do if both are "auto"?
oLd1.setSize(iNewSize1 + "px");
oLd2.setSize(iNewSize2 + "px");
}
} else {
// Live-Resize, resize contents in Dom
$Cnt1.css(this._sizeType, iNewSize1 + "px");
$Cnt2.css(this._sizeType, iNewSize2 + "px");
}
// TODO: When resizing everything gets absolute sizes - %-values should resize to % etc.
};
////////////////////////////////////////// Private Methods /////////////////////////////////////////
Splitter.prototype._preserveHandler = function(sChannelId, sEventId, oData) {
var oDom = this.getDomRef();
if (oDom && oData.domNode.contains(oDom)) {
// Our HTML has been preserved...
this._isPreserved = true;
}
};
/**
* Resizes as soon as the current stack is done. Can be used in cases where several resize-relevant
* actions are done in a loop to make sure only one resize calculation is done at the end.
*
* @param {Number} [iDelay=0] Number of milliseconds to wait before doing the resize
* @private
*/
Splitter.prototype._delayedResize = function(iDelay) {
if (iDelay === undefined) {
iDelay = 0;
}
// If we are not rendered, we do not need to resize since resizing is done after rendering
if (this.getDomRef()) {
jQuery.sap.clearDelayedCall(this._resizeTimeout);
jQuery.sap.delayedCall(iDelay, this, this._resize, []);
}
};
/**
* Resizes the Splitter bars to fit the current content height. Must be done before and after content sizes have
* been calculated.
*
* @param {sap.ui.core.Control[]} aContentAreas - The content areas of the Splitter
* @returns {void}
* @private
*/
Splitter.prototype._resizeBars = function(aContentAreas) {
var i, $Bar;
// In case the Splitter has a relative height or width set (like "100%"), and the surrounding
// container does not have a size set, the content of the Splitter defines the height/width,
// in which case the size of the splitter bars is incorrect.
var $this = this.$();
// First remove the size from the splitter bar so it does not lead to growing the content
for (i = 0; i < aContentAreas.length - 1; ++i) {
$Bar = this.$("splitbar-" + i);
$Bar.css(this._sizeTypeNot, "");
}
// Now measure the content and adapt the size of the Splitter bar
for (i = 0; i < aContentAreas.length - 1; ++i) {
$Bar = this.$("splitbar-" + i);
var iSize = this._bHorizontal ? $this.height() : $this.width();
$Bar.css(this._sizeType, "");
$Bar.css(this._sizeTypeNot, iSize + "px");
}
};
/**
* Recalculates the content sizes and manipulates the DOM accordingly.
*
* @private
*/
Splitter.prototype._resize = function() {
if (this._isPreserved) {
// Do not attempt to resize the content areas in case we are in the preserved area
return;
}
var i = 0, $Bar;
var aContentAreas = this.getContentAreas();
// Resize Splitter bars so that they do not influence the content sizes the wrong way
this._resizeBars(aContentAreas);
// Save calculated sizes to be able to tell whether a resize occurred
var oldCalculatedSizes = this.getCalculatedSizes();
this._recalculateSizes();
var newCalculatedSizes = this.getCalculatedSizes();
var bSizesValid = false;
for (i = 0; i < newCalculatedSizes.length; ++i) {
if (newCalculatedSizes[i] !== 0) {
bSizesValid = true;
break;
}
}
if (!bSizesValid) {
// TODO: What if all sizes are set to 0 on purpose...?
this._delayedResize(100);
return;
}
var bLastContentResizable = true;
for (i = 0; i < aContentAreas.length; ++i) {
var $Content = this.$("content-" + i);
var oContent = aContentAreas[i];
$Content.css(this._sizeType, newCalculatedSizes[i] + "px");
$Content.css(this._sizeTypeNot, ""); // Remove other sizes.
// TODO: Remove all wrong sizes when switching orientation instead of here?
// Check whether bar should be movable
var oLd = oContent.getLayoutData();
var bContentResizable = oLd && oLd.getResizable();
if (i > 0) {
var bResizable = bContentResizable && bLastContentResizable;
$Bar = this.$("splitbar-" + (i - 1));
$Bar.toggleClass("sapUiLoSplitterNoResize", !bResizable);
$Bar.attr("tabindex", bResizable && this._keyboardEnabled ? "0" : "-1");
$Bar.attr("title", bResizable ? this._getText("SPLITTER_MOVE") : "");
}
bLastContentResizable = bContentResizable;
}
// Resize Splitter bars again so that the updated content sizes are calculated correctly
this._resizeBars(aContentAreas);
// In case something was resized, change sizes and fire resize event
if (_sizeArraysDiffer(oldCalculatedSizes, newCalculatedSizes)) {
this.fireResize({
oldSizes : oldCalculatedSizes,
newSizes : newCalculatedSizes
});
}
};
/**
* Calculates how much space is actually available inside the splitter to distribute the content
* areas in.
*
* @param {string[]} [aSizes] The list of size values from the LayoutData of the content areas
* @returns {Number} The available space in px
* @private
*/
Splitter.prototype._calculateAvailableContentSize = function(aSizes) {
var i = 0;
var $Splitter = this.$();
var iFullSize = this._bHorizontal ? $Splitter.innerWidth() : $Splitter.innerHeight();
// Due to rounding errors when zoom is activated, we need 1px of error margin for every element
// that is automatically sized...
var iAutosizedAreas = 0;
var bHasAutoSizedContent = false;
for (i = 0; i < aSizes.length; ++i) {
var sSize = aSizes[i];
if (sSize.indexOf("%") > -1) {
iAutosizedAreas++;
}
if (aSizes[i] == "auto") {
bHasAutoSizedContent = true;
}
}
iAutosizedAreas += bHasAutoSizedContent ? 1 : 0;
iFullSize -= iAutosizedAreas;
// Due to zoom rounding erros, we cannot assume that all SplitBars have the same sizes, even
// though they have the same CSS size set.
var iSplitters = aSizes.length - 1;
var iSplitBarsWidth = 0;
for (i = 0; i < iSplitters; ++i) {
iSplitBarsWidth += this._bHorizontal
? this.$("splitbar-" + i).innerWidth()
: this.$("splitbar-" + i).innerHeight();
}
return iFullSize - iSplitBarsWidth;
};
/**
* Recalculates the content sizes in three steps:
* 1. Searches for all absolute values ("px") and deducts them from the available space.
* 2. Searches for all percent values and interprets them as % of the available space after step 1
* 3. Divides the rest of the space uniformly between all contents with "auto" size values
*
* @private
*/
Splitter.prototype._recalculateSizes = function() {
// TODO: (?) Use maxSize value from layoutData
var i, sSize, oLayoutData, iColSize, idx;
// Read all content sizes from the layout data
var aSizes = [];
var aContentAreas = this.getContentAreas();
for (i = 0; i < aContentAreas.length; ++i) {
oLayoutData = aContentAreas[i].getLayoutData();
sSize = oLayoutData ? oLayoutData.getSize() : "auto";
aSizes.push(sSize);
}
this._calculatedSizes = [];
var iAvailableSize = this._calculateAvailableContentSize(aSizes);
var aAutosizeIdx = [];
var aAutoMinsizeIdx = [];
var aPercentsizeIdx = [];
// Remove fixed sizes from available size
for (i = 0; i < aSizes.length; ++i) {
sSize = aSizes[i];
var iSize;
if (sSize.indexOf("px") > -1) {
// Pixel based Value - deduct it from available size
iSize = parseInt(sSize, 10);
iAvailableSize -= iSize;
this._calculatedSizes[i] = iSize;
} else if (sSize.indexOf("%") > -1) {
aPercentsizeIdx.push(i);
} else if (aSizes[i] == "auto") {
oLayoutData = aContentAreas[i].getLayoutData();
if (oLayoutData && parseInt(oLayoutData.getMinSize(), 10) != 0) {
aAutoMinsizeIdx.push(i);
} else {
aAutosizeIdx.push(i);
}
} else {
jQuery.sap.log.error("Illegal size value: " + aSizes[i]);
}
}
var bWarnSize = false; // Warn about sizes being too big for the available space
// If more than the available size if assigned to fixed width content, the rest will get no
// space at all
if (iAvailableSize < 0) { bWarnSize = true; iAvailableSize = 0; }
// Now calculate % of the available space
var iRest = iAvailableSize;
var iPercentSizes = aPercentsizeIdx.length;
for (i = 0; i < iPercentSizes; ++i) {
idx = aPercentsizeIdx[i];
// Percent based Value - deduct it from available size
iColSize = Math.floor(parseFloat(aSizes[idx]) / 100 * iAvailableSize, 0);
iAvailableSize -= iColSize;
this._calculatedSizes[idx] = iColSize;
iRest -= iColSize;
}
iAvailableSize = iRest;
if (iAvailableSize < 0) { bWarnSize = true; iAvailableSize = 0; }
// Calculate auto sizes
iColSize = Math.floor(iAvailableSize / (aAutoMinsizeIdx.length + aAutosizeIdx.length), 0);
// First calculate auto-sizes with a minSize constraint
var iAutoMinSizes = aAutoMinsizeIdx.length;
for (i = 0; i < iAutoMinSizes; ++i) {
idx = aAutoMinsizeIdx[i];
var iMinSize = parseInt(aContentAreas[idx].getLayoutData().getMinSize(), 10);
if (iMinSize > iColSize) {
this._calculatedSizes[idx] = iMinSize;
iAvailableSize -= iMinSize;
} else {
this._calculatedSizes[idx] = iColSize;
iAvailableSize -= iColSize;
}
}
if (iAvailableSize < 0) { bWarnSize = true; iAvailableSize = 0; }
// Now calculate "auto"-sizes
iRest = iAvailableSize;
var iAutoSizes = aAutosizeIdx.length;
iColSize = Math.floor(iAvailableSize / iAutoSizes, 0);
for (i = 0; i < iAutoSizes; ++i) {
idx = aAutosizeIdx[i];
this._calculatedSizes[idx] = iColSize;
iRest -= iColSize;
// if (i == iAutoSizes - 1 && iRest != 0) {
// // In case of rounding errors, change the last auto-size column
// this._calculatedSizes[idx] += iRest;
// }
}
if (bWarnSize) {
// TODO: Decide if the warning should be kept - might spam the console but on the other
// hand it might make analyzing of splitter bugs easier, since we can just ask
// developers if there was a [Splitter] output on the console if the splitter looks
// weird in their application.
jQuery.sap.log.info(
"[Splitter] The set sizes and minimal sizes of the splitter contents are bigger " +
"than the available space in the UI."
);
}
};
/**
* Stores the respective values that differ when resizing the splitter in horizontal vs. vertical
* mode
*
* @private
*/
Splitter.prototype._switchOrientation = function() {
this._bHorizontal = this.getOrientation() === sap.ui.core.Orientation.Horizontal;
if (this._bHorizontal) {
this._sizeDirNot = "top";
this._sizeTypeNot = "height";
this._sizeType = "width";
this._moveCord = "pageX";
if (this._bRtl) {
this._sizeDir = "right";
} else {
this._sizeDir = "left";
}
} else {
this._moveCord = "pageY";
this._sizeType = "height";
this._sizeTypeNot = "width";
this._sizeDir = "top";
this._sizeDirNot = "left";
}
var $This = this.$();
$This.toggleClass("sapUiLoSplitterH", this._bHorizontal);
$This.toggleClass("sapUiLoSplitterV", !this._bHorizontal);
};
/**
* Handles events that are generated from the keyboard that should trigger a resize (on the
* Splitter bars).
*
* @param {string} [sType] The type of resize step ("inc", "dec", "max", "min")
* @param {jQuery.Event} [oEvent] The original keyboard event
*/
Splitter.prototype._onKeyboardResize = function(sType, oEvent) {
var sBarId = this.getId() + "-splitbar-";
if (!oEvent || !oEvent.target || !oEvent.target.id || oEvent.target.id.indexOf(sBarId) !== 0) {
return;
}
var iStepSize = 20;
var iBigStep = 999999;
var iBar = parseInt(oEvent.target.id.substr(sBarId.length), 10);
var mCalcSizes = this.getCalculatedSizes();
// TODO: These two lines are incomprehensible magic - find better solution
this._move.c1Size = mCalcSizes[iBar];
this._move.c2Size = mCalcSizes[iBar + 1];
var iStep = 0;
switch (sType) {
case "inc":
iStep = iStepSize;
break;
case "incMore":
iStep = iStepSize * 10;
break;
case "dec":
iStep = 0 - iStepSize;
break;
case "decMore":
iStep = 0 - iStepSize * 10;
break;
case "max":
iStep = iBigStep;
break;
case "min":
iStep = 0 - iBigStep;
break;
default:
jQuery.sap.log.warn("[Splitter] Invalid keyboard resize type");
break;
}
this._resizeContents(iBar, iStep, true);
};
/**
* Connects the keyboard event listeners so resizing via keyboard will be possible
*/
Splitter.prototype._enableKeyboardListeners = function() {
this.onsapright = this._keyListeners.increase;
this.onsapdown = this._keyListeners.increase;
this.onsapleft = this._keyListeners.decrease;
this.onsapup = this._keyListeners.decrease;
this.onsappageup = this._keyListeners.decreaseMore;
this.onsappagedown = this._keyListeners.increaseMore;
this.onsapend = this._keyListeners.max;
this.onsaphome = this._keyListeners.min;
this._keyboardEnabled = true;
};
/**
* Disconnects the keyboard event listeners so resizing via keyboard will not be possible anymore
*/
Splitter.prototype._disableKeyboardListeners = function() {
delete this.onsapincreasemodifiers;
delete this.onsapdecreasemodifiers;
delete this.onsapendmodifiers;
delete this.onsaphomemodifiers;
this._keyboardEnabled = false;
};
/**
* Gets the text for the given key from the current resourcebundle
*
* @param {string} [sKey] Text key to look for in the resource bundle
* @param {array} [aArgs] Additional arguments for the getText method of the ResourceBundle
* @returns {string} The translated string
* @private
*/
Splitter.prototype._getText = function(sKey, aArgs) {
return (oResourceBundle ? oResourceBundle.getText(sKey, aArgs) : sKey);
};
///////////////////////////////////////// Hidden Functions /////////////////////////////////////////
/**
* Compares two (simple, one-dimensional) arrays. If all values are the same, false is returned -
* If values differ or at least one of the values is no array, true is returned.
*
* @param {Number[]} [aSizes1] The array of numbers to compare against
* @param {Number[]} [aSizes2] The array of numbers that is compared to the first one
* @returns {bool} True if the size-arrays differ, false otherwise
* @private
*/
function _sizeArraysDiffer(aSizes1, aSizes2) {
if (aSizes1 === aSizes2) {
// The same thing. No difference.
return false;
}
if (!aSizes1 || !aSizes2 || aSizes1.length === undefined || aSizes2.length === undefined) {
// At lease one of the two is not an array
return true;
}
if (aSizes1.length != aSizes2.length) {
return true;
}
for (var i = 0; i < aSizes1.length; ++i) {
if (aSizes1[i] !== aSizes2[i]) {
return true;
}
}
return false;
}
/**
* Prevents the selection of text while the mouse is moving when pressed
*
* @param {bool} [bTouch] If set to true, touch events instead of mouse events are captured
*/
function _preventTextSelection(bTouch) {
var fnPreventSelection = function(oEvent) {
oEvent.preventDefault();
};
var fnAllowSelection = null;
fnAllowSelection = function() {
document.removeEventListener("touchend", fnAllowSelection);
document.removeEventListener("touchmove", fnPreventSelection);
document.removeEventListener("mouseup", fnAllowSelection);
document.removeEventListener("mousemove", fnPreventSelection);
};
if (bTouch) {
this._ignoreMouse = true; // Ignore mouse-events until touch is done
document.addEventListener("touchend", fnAllowSelection);
document.addEventListener("touchmove", fnPreventSelection);
} else {
document.addEventListener("mouseup", fnAllowSelection);
document.addEventListener("mousemove", fnPreventSelection);
}
}
/**
* Makes sure the LayoutData for the given control is set and compatible. In case nothing is set,
* a default sap.ui.layout.SplitterLayoutData is set on the Element
*
* @param {sap.ui.core.Element} [oContent] The Element for which the existance of LayoutData should be ensured
* @private
*/
function _ensureLayoutData(oContent) {
var oLd = oContent.getLayoutData();
// Make sure LayoutData is set on the content
// TODO: There should be a better way to verify that it's the correct type of LayoutData
// But this approach has the advantage that "compatible" LayoutData can be used.
if (oLd && (!oLd.getResizable || !oLd.getSize || !oLd.getMinSize)) {
jQuery.sap.log.warning(
"Content \"" + oContent.getId() + "\" for the Splitter contained wrong LayoutData. " +
"The LayoutData has been replaced with default values."
);
oLd = null;
}
if (!oLd) {
oContent.setLayoutData(new sap.ui.layout.SplitterLayoutData());
}
}
//////////////////////////////////////// Overridden Methods ////////////////////////////////////////
Splitter.prototype.invalidate = function(oOrigin) {
var bForce =
// In case the content invalidates and bubbles up (for example an invisible button being
// shown), we need to rerender
// TODO: Render only the contentArea where the invalidate originated from
(oOrigin && this.indexOfContentArea(oOrigin) != -1)
// CustomData that needs to be updated in the DOM has been set on the splitter
// TODO: Programatically write CustomData on this control to the DOM
|| (oOrigin && oOrigin instanceof sap.ui.core.CustomData && oOrigin.getWriteToDom())
// We do not know where the invalidate originated from. We will pretty much have to rerender
|| (oOrigin === undefined);
// Only really invalidate/rerender if needed
if (bForce || this._needsInvalidation) {
this._needsInvalidation = false;
Control.prototype.invalidate.apply(this, arguments);
}
};
//////////////////////////////////// Property "orientation" ///////////////////////////////////
Splitter.prototype.setOrientation = function(sOrientation) {
var vReturn = this.setProperty("orientation", sOrientation, true);
this._switchOrientation();
this._delayedResize();
this.$().find(".sapUiLoSplitterBar").attr("aria-orientation", this._bHorizontal ? "vertical" : "horizontal");
return vReturn;
};
///////////////////////////////////// Property "width" ///////////////////////////////
Splitter.prototype.setWidth = function(sWidth) {
// Do not invalidate for size change
this.setProperty("width", sWidth, true);
// Set validated width on control
this.$().css("width", this.getProperty("width"));
return this;
};
///////////////////////////////////// Property "height" ///////////////////////////////
Splitter.prototype.setHeight = function(sHeight) {
// Do not invalidate for size change
this.setProperty("height", sHeight, true);
// Set validated height on control
this.$().css("height", this.getProperty("height"));
return this;
};
//////////////////////////////////////// Event "xxx" ///////////////////////////////////////
///////////////////////////////////// Aggregation "contents" ///////////////////////////////
Splitter.prototype.addContentArea = function(oContent) {
this._needsInvalidation = true;
_ensureLayoutData(oContent);
return this.addAggregation("contentAreas", oContent);
};
Splitter.prototype.removeContentArea = function(oContent) {
this._needsInvalidation = true;
return this.removeAggregation("contentAreas", oContent);
};
Splitter.prototype.removeAllContentArea = function() {
this._needsInvalidation = true;
return this.destroyAllAggregation("contentAreas");
};
Splitter.prototype.destroyContentArea = function() {
this._needsInvalidation = true;
return this.destroyAggregation("contentAreas");
};
Splitter.prototype.insertContentArea = function(oContent, iIndex) {
this._needsInvalidation = true;
_ensureLayoutData(oContent);
return this.insertAggregation("contentAreas", oContent, iIndex);
};
///////////////////////////////////// Association "xxx" ////////////////////////////////////
return Splitter;
}, /* bExport= */ true);
}; // end of sap/ui/layout/Splitter.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.SplitterLayoutData') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.SplitterLayoutData.
jQuery.sap.declare('sap.ui.layout.SplitterLayoutData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.LayoutData'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/SplitterLayoutData",['jquery.sap.global', 'sap/ui/core/LayoutData', './library'],
function(jQuery, LayoutData, library) {
"use strict";
/**
* Constructor for a new SplitterLayoutData.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Holds layout data for the splitter contents.
* Allowed size values are numeric values ending in "px" and "%" and the
* special case "auto".
* (The CSS value "auto" is used internally to recalculate the size of the content
* dynamically and is not directly set as style property.)
* @extends sap.ui.core.LayoutData
* @version 1.32.10
*
* @constructor
* @public
* @since 1.22.0
* @experimental Since version 1.22.0.
* API is not yet finished and might change completely
* @alias sap.ui.layout.SplitterLayoutData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var SplitterLayoutData = LayoutData.extend("sap.ui.layout.SplitterLayoutData", /** @lends sap.ui.layout.SplitterLayoutData.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Determines whether the control in the splitter can be resized or not.
*/
resizable : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* Sets the size of the splitter content.
*/
size : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : 'auto'},
/**
* Sets the minimum size of the splitter content in px.
*/
minSize : {type : "int", group : "Dimension", defaultValue : 0}
}
}});
/*** NOTHING ***/
return SplitterLayoutData;
}, /* bExport= */ true);
}; // end of sap/ui/layout/SplitterLayoutData.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.VerticalLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.VerticalLayout.
jQuery.sap.declare('sap.ui.layout.VerticalLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.EnabledPropagator'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/VerticalLayout",['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator', './library'],
function(jQuery, Control, EnabledPropagator, library) {
"use strict";
/**
* Constructor for a new VerticalLayout.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* In this layout the content controls are rendered one below the other.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.VerticalLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var VerticalLayout = Control.extend("sap.ui.layout.VerticalLayout", /** @lends sap.ui.layout.VerticalLayout.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Width of the <code>VerticalLayout</code>. If no width is set, the width of the content is used.
* If the content of the layout has a larger width than the layout, it is cut off.
* There is no scrolling inside the layout.
*/
width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
/**
*
* If not enabled, all controls inside are not enabled automatically.
*/
enabled : {type : "boolean", group : "Behavior", defaultValue : true}
},
defaultAggregation : "content",
aggregations : {
/**
* Content controls within the layout.
*/
content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"}
},
designTime : true
}});
EnabledPropagator.call(VerticalLayout.prototype);
return VerticalLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/VerticalLayout.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.Form') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.Form.
jQuery.sap.declare('sap.ui.layout.form.Form'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/Form",['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/layout/library'],
function(jQuery, Control, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.Form.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Form control.
* A <code>Form</code> is structured into <code>FormContainers</code>. Each <code>FormContainer</code> consists of <code>FormElements</code>.
* The <code>FormElements</code> consists of a label and the form fields.
* A <code>Form</code> doesn't render its content by itself. The rendering is done by the assigned <code>FormLayout</code>.
* This is so that the rendering can be adopted to new UI requirements without changing the Form itself.
*
* For the content of a <code>Form</code>, <code>VariantLayoutData</code> are supported to allow simple switching of the <code>FormLayout</code>.
* <code>LayoutData</code> on the content can be used to overwrite the default layout of the code>Form</code>.
*
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.Form
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Form = Control.extend("sap.ui.layout.form.Form", /** @lends sap.ui.layout.form.Form.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Width of the <code>Form</code>.
*/
width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
/**
* Applies a device and theme specific line-height to the form rows if the form has editable content.
* If set, all (not only the editable) rows of the form will get the line height of editable fields.
* The accessibility aria-readonly attribute is set according to this property.
* <b>Note:</b> The setting of the property has no influence on the editable functionality of the form's content.
* @since 1.20.0
*/
editable : {type : "boolean", group : "Misc", defaultValue : false}
},
defaultAggregation : "formContainers",
aggregations : {
/**
* Containers with the content of the form. A <code>FormContainer</code> represents a group inside the <code>Form</code>.
*/
formContainers : {type : "sap.ui.layout.form.FormContainer", multiple : true, singularName : "formContainer"},
/**
* Title of the <code>Form</code>. Can either be a <code>Title</code> object, or a string.
* If a <code>Title</code> object it used, the style of the title can be set.
*/
title : {type : "sap.ui.core.Title", altTypes : ["string"], multiple : false},
/**
* Layout of the <code>Form</code>. The assigned <code>Layout</code> renders the <code>Form</code>.
* We suggest using the <code>ResponsiveGridLayout</code> for rendering a <code>Form</code>, as its responsiveness allows the available space to be used in the best way possible.
*/
layout : {type : "sap.ui.layout.form.FormLayout", multiple : false}
},
associations: {
/**
* Association to controls / IDs that label this control (see WAI-ARIA attribute aria-labelledby).
* @since 1.28.0
*/
ariaLabelledBy: { type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy" }
},
designTime : true
}});
/**
* This file defines behavior for the control,
*/
(function() {
// sap.ui.commons.Form.prototype.init = function(){
// // do something for initialization...
// };
Form.prototype.toggleContainerExpanded = function(oContainer){
var oLayout = this.getLayout();
if (oLayout) {
oLayout.toggleContainerExpanded(oContainer);
}
};
/*
* If onAfterRendering of a field is processed the layout might need to change it.
*/
Form.prototype.contentOnAfterRendering = function(oFormElement, oControl){
// call function of the layout
var oLayout = this.getLayout();
if (oLayout && oLayout.contentOnAfterRendering) {
oLayout.contentOnAfterRendering( oFormElement, oControl);
}
};
/*
* If LayoutData changed on control this may need changes on the layout. So bubble to the Layout
*/
Form.prototype.onLayoutDataChange = function(oEvent){
// call function of the layout
var oLayout = this.getLayout();
if (oLayout && oLayout.onLayoutDataChange) {
oLayout.onLayoutDataChange(oEvent);
}
};
Form.prototype.onBeforeFastNavigationFocus = function(oEvent){
var oLayout = this.getLayout();
if (oLayout && oLayout.onBeforeFastNavigationFocus) {
oLayout.onBeforeFastNavigationFocus(oEvent);
}
};
Form.prototype.setEditable = function(bEditable) {
var bOldEditable = this.getEditable();
this.setProperty("editable", bEditable, true);
if (bEditable != bOldEditable && this.getDomRef()) {
if (bEditable) {
this.$().addClass("sapUiFormEdit").addClass("sapUiFormEdit-CTX");
this.$().removeAttr("aria-readonly");
} else {
this.$().removeClass("sapUiFormEdit").removeClass("sapUiFormEdit-CTX");
this.$().attr("aria-readonly", "true");
}
}
return this;
};
/*
* Overwrite of INVALIDATE
* do not invalidate Form during rendering. Because there the Layout may update the content
* otherwise the Form will render twice
*/
Form.prototype.invalidate = function(oOrigin) {
if (!this._bNoInvalidate) {
Control.prototype.invalidate.apply(this, arguments);
}
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* If the <code>FormContainer</code> has a DOM representation this function returns it,
* independent from the ID of this DOM element
* @param {sap.ui.layout.form.FormContainer} oContainer <code>FormContainer</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
Form.prototype.getContainerRenderedDomRef = function(oContainer) {
var oLayout = this.getLayout();
if (oLayout && oLayout.getContainerRenderedDomRef) {
return oLayout.getContainerRenderedDomRef(oContainer);
}else {
return null;
}
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* If the <code>FormElement</code> has a DOM representation this function returns it,
* independent from the ID of this DOM element
* @param {sap.ui.layout.form.FormElement} oElement <code>FormElement</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
Form.prototype.getElementRenderedDomRef = function(oElement) {
var oLayout = this.getLayout();
if (oLayout && oLayout.getElementRenderedDomRef) {
return oLayout.getElementRenderedDomRef(oElement);
}else {
return null;
}
};
}());
return Form;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/Form.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.FormContainer') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.FormContainer.
jQuery.sap.declare('sap.ui.layout.form.FormContainer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.EnabledPropagator'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.theming.Parameters'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/FormContainer",['jquery.sap.global', 'sap/ui/core/Element', 'sap/ui/core/EnabledPropagator', 'sap/ui/core/theming/Parameters', 'sap/ui/layout/library'],
function(jQuery, Element, EnabledPropagator, Parameters, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.FormContainer.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A <code>FormContainer</code> represents a group inside a <code>Form</code>. It consists of <code>FormElements</code>.
* The rendering of the <code>FormContainer</code> is done by the <code>FormLayout</code> assigned to the <code>Form</code>.
* @extends sap.ui.core.Element
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.FormContainer
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FormContainer = Element.extend("sap.ui.layout.form.FormContainer", /** @lends sap.ui.layout.form.FormContainer.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Container is expanded.
* <b>Note:</b> This property only works if <code>expandable</code> is set to <code>true</code>.
*/
expanded : {type : "boolean", group : "Misc", defaultValue : true},
/**
* Defines if the <code>FormContainer</code> is expandable.
* <b>Note:</b> The expander icon will only be shown if a <code>title</code> is set for the <code>FormContainer</code>.
*/
expandable : {type : "boolean", group : "Misc", defaultValue : false},
/**
* If set to <code>false</code>, the <code>FormContainer</code> is not rendered.
*/
visible : {type : "boolean", group : "Misc", defaultValue : true}
},
defaultAggregation : "formElements",
aggregations : {
/**
* The <code>FormElements</code> contain the content (labels and fields) of the <code>FormContainers</code>.
*/
formElements : {type : "sap.ui.layout.form.FormElement", multiple : true, singularName : "formElement"},
/**
* Title of the <code>FormContainer</code>. Can either be a <code>Title</code> object, or a string.
* If a <code>Title</code> object is used, the style of the title can be set.
*/
title : {type : "sap.ui.core.Title", altTypes : ["string"], multiple : false}
},
designTime : true
}});
/**
* This file defines behavior for the control,
*/
//sap.ui.core.EnabledPropagator.call(sap.ui.layout.form.FormContainer.prototype);
(function() {
FormContainer.prototype.init = function(){
this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.layout");
};
FormContainer.prototype.exit = function(){
if (this._oExpandButton) {
this._oExpandButton.destroy();
delete this._oExpandButton;
}
this._rb = undefined;
};
FormContainer.prototype.setExpandable = function(bExpandable){
this.setProperty("expandable", bExpandable);
if (bExpandable) {
var that = this;
if (!this._oExpandButton) {
this._oExpandButton = sap.ui.layout.form.FormHelper.createButton(this.getId() + "--Exp", _handleExpButtonPress, that);
this._oExpandButton.setParent(this);
}
_setExpanderIcon(that);
}
return this;
};
FormContainer.prototype.setExpanded = function(bExpanded){
this.setProperty("expanded", bExpanded, true); // no automatic rerendering
var that = this;
_setExpanderIcon(that);
var oForm = this.getParent();
if (oForm && oForm.toggleContainerExpanded) {
oForm.toggleContainerExpanded(that);
}
return this;
};
/*
* If onAfterRendering of a field is processed the Form (layout) might need to change it.
*/
FormContainer.prototype.contentOnAfterRendering = function(oFormElement, oControl){
// call function of parent (if assigned)
var oParent = this.getParent();
if (oParent && oParent.contentOnAfterRendering) {
oParent.contentOnAfterRendering( oFormElement, oControl);
}
};
/*
* If LayoutData changed on control this may need changes on the layout. So bubble to the form
*/
FormContainer.prototype.onLayoutDataChange = function(oEvent){
// call function of parent (if assigned)
var oParent = this.getParent();
if (oParent && oParent.onLayoutDataChange) {
oParent.onLayoutDataChange(oEvent);
}
};
/*
* Checks if properties are fine
* Expander only visible if title is set -> otherwise give warning
* @return 0 = no problem, 1 = warning, 2 = error
* @private
*/
FormContainer.prototype._checkProperties = function(){
var iReturn = 0;
if (this.getExpandable() && !this.getTitle()) {
jQuery.sap.log.warning("Expander only displayed if title is set", this.getId(), "FormContainer");
iReturn = 1;
}
return iReturn;
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* If the FormContainer has a DOM representation this function returns it,
* independent from the ID of this DOM element
* @return {Element} The Element's DOM representation or null
* @private
*/
FormContainer.prototype.getRenderedDomRef = function(){
var that = this;
var oForm = this.getParent();
if (oForm && oForm.getContainerRenderedDomRef) {
return oForm.getContainerRenderedDomRef(that);
}else {
return null;
}
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* If the FormElement has a DOM representation this function returns it,
* independent from the ID of this DOM element
* @param {sap.ui.layout.form.FormElement} oElement FormElement
* @return {Element} The Element's DOM representation or null
* @private
*/
FormContainer.prototype.getElementRenderedDomRef = function(oElement){
var oForm = this.getParent();
if (oForm && oForm.getElementRenderedDomRef) {
return oForm.getElementRenderedDomRef(oElement);
}else {
return null;
}
};
function _setExpanderIcon(oContainer){
if (!oContainer._oExpandButton) {
return;
}
var sIcon, sIconHovered, sText, sTooltip;
if (oContainer.getExpanded()) {
sIcon = Parameters.get('sapUiFormContainerColImageURL');
sIconHovered = Parameters.get('sapUiFormContainerColImageDownURL');
sText = "-";
sTooltip = oContainer._rb.getText("FORM_COLLAPSE");
} else {
sIcon = Parameters.get('sapUiFormContainerExpImageURL');
sIconHovered = Parameters.get('sapUiFormContainerExpImageDownURL');
sText = "+";
sTooltip = oContainer._rb.getText("FORM_EXPAND");
}
var sModulePath = "sap.ui.layout.themes." + sap.ui.getCore().getConfiguration().getTheme();
if (sIcon) {
sIcon = jQuery.sap.getModulePath(sModulePath, sIcon);
sText = "";
}
if (sIconHovered) {
sIconHovered = jQuery.sap.getModulePath(sModulePath, sIconHovered);
}
sap.ui.layout.form.FormHelper.setButtonContent(oContainer._oExpandButton, sText, sTooltip, sIcon, sIconHovered);
}
function _handleExpButtonPress(oEvent){
this.setExpanded(!this.getExpanded());
}
}());
return FormContainer;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/FormContainer.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.FormElement') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.FormElement.
jQuery.sap.declare('sap.ui.layout.form.FormElement'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.EnabledPropagator'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/FormElement",['jquery.sap.global', 'sap/ui/core/Element', 'sap/ui/core/EnabledPropagator', 'sap/ui/layout/library'],
function(jQuery, Element, EnabledPropagator, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.FormElement.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A <code>FormElement</code> represents a row in a <code>FormContainer</code>.
* A <code>FormElement</code> is a combination of one label and different controls associated to this label.
* @extends sap.ui.core.Element
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.FormElement
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FormElement = Element.extend("sap.ui.layout.form.FormElement", /** @lends sap.ui.layout.form.FormElement.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* If set to <code>false</code>, the <code>FormElement</code> is not rendered.
*/
visible : {type : "boolean", group : "Misc", defaultValue : true}
},
defaultAggregation : "fields",
aggregations : {
/**
* Label of the fields. Can either be a <code>Label</code> object, or a string.
* If a <code>Label</code> object is used, the properties of the <code>Label</code> can be set.
* If no assignment between <code>Label</code> and the fields is set, it will be done automatically by the
* <code>FormElement</code>. In this case the <code>Label</code> is assigned to the fields of the <code>FormElement</code>.
*/
label : {type : "sap.ui.core.Label", altTypes : ["string"], multiple : false},
/**
* Formular controls that belong together to be displayed in one row of a <code>Form</code>.
*/
fields : {type : "sap.ui.core.Control", multiple : true, singularName : "field"}
}
}});
/**
* This file defines behavior for the control,
*/
// TODO deactivated until Element/Control has been clarified: sap.ui.core.EnabledPropagator.call(sap.ui.layout.form.FormElement.prototype);
(function() {
FormElement.prototype.init = function(){
this._oFieldDelegate = {oElement: this, onAfterRendering: _fieldOnAfterRendering};
};
FormElement.prototype.exit = function(){
if (this._oLabel) {
this._oLabel.destroy();
delete this._oLabel;
}
this._oFieldDelegate = undefined;
};
/*
* sets the label for the FormElement. If it's only a string an internal label is created.
* overwrite the isRequired and the getLabelForRendering functions with Form specific ones.
*/
FormElement.prototype.setLabel = function(vAny) {
if (!this._oLabel) {
var oOldLabel = this.getLabel();
if (oOldLabel && oOldLabel.isRequired) {
oOldLabel.isRequired = oOldLabel._sapuiIsRequired;
oOldLabel._sapuiIsRequired = undefined;
}
}
this.setAggregation("label", vAny);
var oLabel = vAny;
if (typeof oLabel === "string") {
if (!this._oLabel) {
this._oLabel = sap.ui.layout.form.FormHelper.createLabel(oLabel);
this._oLabel.setParent(this);
if (oLabel.isRequired) {
this._oLabel.isRequired = _labelIsRequired;
}
} else {
this._oLabel.setText(oLabel);
}
} else {
if (this._oLabel) {
this._oLabel.destroy();
delete this._oLabel;
}
if (oLabel && oLabel.isRequired) {
oLabel._sapuiIsRequired = oLabel.isRequired;
oLabel.isRequired = _labelIsRequired;
}
}
_updateLabelFor(this);
return this;
};
/**
* Returns the <code>Label</code> of the <code>FormElement</code>, even if the <code>Label</code> is assigned as string.
* The <code>FormLayout</code> needs the information of the label to render the <code>Form</code>.
*
* @returns {sap.ui.core.Label} <code>Label</code> control used to render the label
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
FormElement.prototype.getLabelControl = function() {
if (this._oLabel) {
return this._oLabel;
} else {
return this.getLabel();
}
};
FormElement.prototype.addField = function(oField) {
this.addAggregation("fields", oField);
oField.addDelegate(this._oFieldDelegate);
_updateLabelFor(this);
return this;
};
FormElement.prototype.insertField = function(oField, iIndex) {
this.insertAggregation("fields", oField, iIndex);
oField.addDelegate(this._oFieldDelegate);
_updateLabelFor(this);
return this;
};
FormElement.prototype.removeField = function(oField) {
var oRemovedField = this.removeAggregation("fields", oField);
oRemovedField.removeDelegate(this._oFieldDelegate);
_updateLabelFor(this);
return oRemovedField;
};
FormElement.prototype.removeAllFields = function() {
var aRemovedFields = this.removeAllAggregation("fields");
for ( var i = 0; i < aRemovedFields.length; i++) {
var oRemovedField = aRemovedFields[i];
oRemovedField.removeDelegate(this._oFieldDelegate);
}
_updateLabelFor(this);
return aRemovedFields;
};
FormElement.prototype.destroyFields = function() {
var aFields = this.getFields();
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
oField.removeDelegate(this._oFieldDelegate);
}
this.destroyAggregation("fields");
_updateLabelFor(this);
return this;
};
FormElement.prototype.updateFields = function() {
var aFields = this.getFields();
var oField;
var i = 0;
for (i = 0; i < aFields.length; i++) {
oField = aFields[i];
oField.removeDelegate(this._oFieldDelegate);
}
this.updateAggregation("fields");
aFields = this.getFields();
for (i = 0; i < aFields.length; i++) {
oField = aFields[i];
oField.addDelegate(this._oFieldDelegate);
}
_updateLabelFor(this);
return this;
};
/*
* Enhance Aria properties of fields to set aria-labelledby to FormElements label if not set otherwise
* Set aria-describedby to the title of the container, but only for the first field in the container
* This function is called during rendering.
*/
FormElement.prototype.enhanceAccessibilityState = function(oElement, mAriaProps) {
var oLabel = this.getLabelControl();
if (oLabel && oLabel != oElement) {
var sLabelledBy = mAriaProps["labelledby"];
if (!sLabelledBy) {
sLabelledBy = oLabel.getId();
} else {
var aLabels = sLabelledBy.split(" ");
if (jQuery.inArray(oLabel.getId(), aLabels) < 0) {
aLabels.splice(0, 0, oLabel.getId());
sLabelledBy = aLabels.join(" ");
}
}
mAriaProps["labelledby"] = sLabelledBy;
}
return mAriaProps;
};
/*
* If LayoutData changed on control this may need changes on the layout. So bubble to the form
*/
FormElement.prototype.onLayoutDataChange = function(oEvent){
// call function of parent (if assigned)
var oParent = this.getParent();
if (oParent && oParent.onLayoutDataChange) {
oParent.onLayoutDataChange(oEvent);
}
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* If the FormElement has a DOM representation this function returns it,
* independent from the ID of this DOM element
* @return {Element} The Element's DOM representation or null
* @private
*/
FormElement.prototype.getRenderedDomRef = function(){
var that = this;
var oContainer = this.getParent();
if (oContainer && oContainer.getElementRenderedDomRef) {
return oContainer.getElementRenderedDomRef(that);
}else {
return null;
}
};
// *** Private helper functions ***
/*
* overwrite Labels isRequired function to check if one of the fields in the element is required,
* not only the one directly assigned.
*/
function _labelIsRequired(){
var oFormElement = this.getParent();
var aFields = oFormElement.getFields();
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
if (oField.getRequired && oField.getRequired() === true) {
return true;
}
}
return false;
}
/*
* Update the for association of the related label
*/
function _updateLabelFor(oFormElement){
var aFields = oFormElement.getFields();
var oField = aFields.length > 0 ? aFields[0] : null;
var oLabel = oFormElement._oLabel;
if (oLabel) {
oLabel.setAlternativeLabelFor(oField);
}
oLabel = oFormElement.getLabel();
if (oLabel instanceof sap.ui.core.Control /*might also be a string*/) {
oLabel.setAlternativeLabelFor(oField);
}
}
/*
* If onAfterRendering of a field is processed the Form (layout) might need to change it.
*/
function _fieldOnAfterRendering(oEvent){
// call function of parent (if assigned)
var oParent = this.oElement.getParent();
if (oParent && oParent.contentOnAfterRendering) {
oParent.contentOnAfterRendering( this.oElement, oEvent.srcControl);
}
}
}());
return FormElement;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/FormElement.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.FormLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.FormLayout.
jQuery.sap.declare('sap.ui.layout.form.FormLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/FormLayout",['jquery.sap.global', 'sap/ui/core/Control', './Form', 'sap/ui/layout/library'],
function(jQuery, Control, Form, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.FormLayout.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Base layout to render a <code>Form</code>.
* Other layouts to render a <code>Form</code> must inherit from this one.
* <b>Note:</b> This control must not be used to render a <code>Form</code> in productive applications as it does not fulfill any
* design guidelines and usability standards.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.FormLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FormLayout = Control.extend("sap.ui.layout.form.FormLayout", /** @lends sap.ui.layout.form.FormLayout.prototype */ { metadata : {
library : "sap.ui.layout"
}});
/**
* This file defines behavior for the control,
*/
(function() {
/* eslint-disable no-lonely-if */
FormLayout.prototype.contentOnAfterRendering = function(oFormElement, oControl){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
jQuery(oControl.getFocusDomRef()).data("sap.InNavArea", true);
}
};
FormLayout.prototype.toggleContainerExpanded = function(oContainer){
var bExpanded = oContainer.getExpanded();
if (this.getDomRef()) {
if (bExpanded) {
//show content
oContainer.$("content").css("display", "");
} else {
//hide content
oContainer.$("content").css("display", "none");
}
}
};
/*
* gets the layout data of a element (container, control...) for the needed layout data type
*/
FormLayout.prototype.getLayoutDataForElement = function(oElement, sType){
var oLayoutData = oElement.getLayoutData();
var oClass = jQuery.sap.getObject(sType);
if (!oLayoutData) {
return undefined;
} else if (oLayoutData instanceof oClass) {
return oLayoutData;
} else if (oLayoutData.getMetadata().getName() == "sap.ui.core.VariantLayoutData") {
// multiple LayoutData available - search here
var aLayoutData = oLayoutData.getMultipleLayoutData();
for ( var i = 0; i < aLayoutData.length; i++) {
var oLayoutData2 = aLayoutData[i];
if (oLayoutData2 instanceof oClass) {
return oLayoutData2;
}
}
}
};
/* Keyboard handling
* In the FormLayout just a basic keyboard handling is implemented.
* This must be enhanced in the other Layouts if needed.
*
* The main idea is to navigate via arrow keys from control to control
* using Tab only the editable/active controls are reached. So the tab-chain is short
* Via F6 the navigation goes to the next container
* There is an "edit mode" to allow arrow key navigation inside of controls.
* For mobile application the Arrow-key navigation should be disabled
*/
FormLayout.prototype.onsapright = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var that = this;
if (!bRtl) {
this.navigateForward(oEvent, that);
} else {
this.navigateBack(oEvent, that);
}
}
};
FormLayout.prototype.onsapleft = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var that = this;
if (!bRtl) {
this.navigateBack(oEvent, that);
} else {
this.navigateForward(oEvent, that);
}
}
};
FormLayout.prototype.onsapdown = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var oControl = oEvent.srcControl;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
oNewDomRef = this.findFieldBelow(oControl, oElement);
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oNewDomRef = this.findFirstFieldOfNextElement(oElement, 0);
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
}
};
FormLayout.prototype.onsapup = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
oNewDomRef = this.findFieldAbove(oControl, oElement);
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
var oForm = oElement.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oElement);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1);
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
}
};
FormLayout.prototype.onsaphome = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
var oContainer = oElement.getParent();
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
// actually it's within the same container
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex);
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
}
};
FormLayout.prototype.onsaptop = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var oControl = oEvent.srcControl;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
var oNewDomRef;
var oContainer;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
oContainer = oElement.getParent();
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oContainer = oElement;
}
var oForm = oContainer.getParent();
oNewDomRef = this.findFirstFieldOfForm(oForm);
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
}
};
FormLayout.prototype.onsapend = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
var oContainer = oElement.getParent();
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex);
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
}
};
FormLayout.prototype.onsapbottom = function(oEvent){
if (sap.ui.layout.form.FormHelper.bArrowKeySupport) {
var oControl = oEvent.srcControl;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
var oNewDomRef;
var oContainer;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
oContainer = oElement.getParent();
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oContainer = oElement;
}
var oForm = oContainer.getParent();
var aContainers = oForm.getFormContainers();
var iLength = aContainers.length;
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iLength - 1);
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
}
};
FormLayout.prototype.onsapexpand = function(oEvent){
var oControl = oEvent.srcControl;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
var oContainer = oElement.getParent();
if (oContainer.getExpandable()) {
oContainer.setExpanded(true);
}
};
FormLayout.prototype.onsapcollapse = function(oEvent){
var oControl = oEvent.srcControl;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
var oContainer = oElement.getParent();
if (oContainer.getExpandable()) {
oContainer.setExpanded(false);
}
};
FormLayout.prototype.onsapskipforward = function(oEvent){
var oControl = oEvent.srcControl;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
var oNewDomRef;
var oContainer;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
oContainer = oElement.getParent();
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oContainer = oElement;
}
var oForm = oContainer.getParent();
var iCurrentIndex = oForm.indexOfFormContainer(oContainer);
// goto next container
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex + 1);
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
};
FormLayout.prototype.onsapskipback = function(oEvent){
var oControl = oEvent.srcControl;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
var oNewDomRef;
var oContainer;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
oContainer = oElement.getParent();
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oContainer = oElement;
}
var oForm = oContainer.getParent();
var aContainers = oForm.getFormContainers();
var iCurrentIndex = oForm.indexOfFormContainer(oContainer);
// goto previous container
while (!oNewDomRef && iCurrentIndex >= 0) {
var oPrevContainer = aContainers[iCurrentIndex - 1];
if (!oPrevContainer.getExpandable() || oPrevContainer.getExpanded()) {
oNewDomRef = this.findFirstFieldOfFirstElementInPrevContainer(oForm, iCurrentIndex - 1);
}
iCurrentIndex = iCurrentIndex - 1;
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
};
FormLayout.prototype.onBeforeFastNavigationFocus = function(oEvent){
if (jQuery.contains(this.getDomRef(), oEvent.source)) {
oEvent.srcControl = jQuery(oEvent.source).control(0);
if (oEvent.forward) {
this.onsapskipforward(oEvent);
} else {
this.onsapskipback(oEvent);
}
} else {
var oNewDomRef = oEvent.forward ? this.findFirstFieldOfForm(this.getParent()) : this.findFirstFieldOfLastContainerOfForm(this.getParent());
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault();
}
}
};
FormLayout.prototype.findElement = function(oControl){
// since the source control can be part of a child control or layout we have to look in the control tree
// to find the FormElement where the control is assigned
var oElement = oControl.getParent();
var oRootControl = oControl;
while (oElement && !(oElement instanceof sap.ui.layout.form.FormElement) &&
!(oElement && oElement instanceof sap.ui.layout.form.FormContainer) &&
!(oElement && oElement instanceof Form)) {
oRootControl = oElement;
oElement = oElement.getParent();
}
return ({rootControl: oRootControl, element: oElement});
};
FormLayout.prototype.navigateForward = function(oEvent){
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
if (oControl == oElement.getLabelControl()) {
iCurrentIndex = -1;
} else {
iCurrentIndex = oElement.indexOfField(oControl);
}
oNewDomRef = this.findNextFieldOfElement(oElement, iCurrentIndex + 1);
if (!oNewDomRef) {
// use 1st field of next Element
var oContainer = oElement.getParent();
iCurrentIndex = oContainer.indexOfFormElement(oElement);
oNewDomRef = this.findFirstFieldOfNextElement(oContainer, iCurrentIndex + 1);
if (!oNewDomRef) {
// no next element -> look in next container
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex + 1);
}
}
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oNewDomRef = this.findFirstFieldOfNextElement(oElement, 0);
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
};
FormLayout.prototype.tabForward = function(oEvent){
var oForm;
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
if (oControl == oElement.getLabelControl()) {
iCurrentIndex = -1;
} else {
iCurrentIndex = oElement.indexOfField(oControl);
}
oNewDomRef = this.findNextFieldOfElement(oElement, iCurrentIndex + 1, true);
if (!oNewDomRef) {
// use 1st field of next Element
var oContainer = oElement.getParent();
iCurrentIndex = oContainer.indexOfFormElement(oElement);
oNewDomRef = this.findFirstFieldOfNextElement(oContainer, iCurrentIndex + 1, true);
if (!oNewDomRef) {
// no next element -> look in next container
oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex + 1, true);
}
}
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oNewDomRef = this.findFirstFieldOfNextElement(oElement, 0, true);
if (!oNewDomRef) {
// no next element -> look in next container
oForm = oElement.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oElement);
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex + 1, true);
}
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
};
FormLayout.prototype.findNextFieldOfElement = function(oElement, iStartIndex, bTabOver){
var aFields = oElement.getFields();
var iLength = aFields.length;
var oNewDomRef;
for ( var i = iStartIndex; i < iLength; i++) {
// find the next enabled control thats rendered
var oField = aFields[i];
var oDomRef = this._getDomRef(oField);
if (bTabOver == true) {
if ((!oField.getEditable || oField.getEditable()) && (!oField.getEnabled || oField.getEnabled()) && oDomRef) {
oNewDomRef = oDomRef;
break;
}
} else {
if ((!oField.getEnabled || oField.getEnabled()) && oDomRef) {
oNewDomRef = oDomRef;
break;
}
}
}
return oNewDomRef;
};
FormLayout.prototype.findFirstFieldOfNextElement = function(oContainer, iStartIndex, bTabOver){
var aElements = oContainer.getFormElements();
var iLength = aElements.length;
var oNewDomRef;
var i = iStartIndex;
while (!oNewDomRef && i < iLength) {
var oElement = aElements[i];
if (bTabOver == true) {
oNewDomRef = this.findNextFieldOfElement(oElement, 0, true);
} else {
oNewDomRef = this.findNextFieldOfElement(oElement, 0);
}
i++;
}
return oNewDomRef;
};
FormLayout.prototype.findFirstFieldOfForm = function(oForm){
var aContainers = oForm.getFormContainers();
var oNewDomRef;
var oContainer = aContainers[0];
if (!oContainer.getExpandable() || oContainer.getExpanded()) {
oNewDomRef = this.findFirstFieldOfNextElement(oContainer, 0);
}
return oNewDomRef;
};
FormLayout.prototype.findFirstFieldOfLastContainerOfForm = function(oForm){
var oNewDomRef;
var aContainers = oForm.getFormContainers();
var iCurrentIndex = aContainers.length;
// goto previous container
while (!oNewDomRef && iCurrentIndex >= 0) {
var oPrevContainer = aContainers[iCurrentIndex - 1];
if (!oPrevContainer.getExpandable() || oPrevContainer.getExpanded()) {
oNewDomRef = this.findFirstFieldOfFirstElementInPrevContainer(oForm, iCurrentIndex - 1);
}
iCurrentIndex = iCurrentIndex - 1;
}
return oNewDomRef;
};
FormLayout.prototype.findFirstFieldOfFirstElementInNextContainer = function(oForm, iStartIndex, bTabOver){
var aContainers = oForm.getFormContainers();
var iLength = aContainers.length;
var oNewDomRef;
var i = iStartIndex;
while (!oNewDomRef && i < iLength) {
var oContainer = aContainers[i];
if (oContainer.getExpandable() && bTabOver) {
oNewDomRef = oContainer._oExpandButton.getFocusDomRef();
if (oNewDomRef) {
break;
}
}
if (!oContainer.getExpandable() || oContainer.getExpanded()) {
if (bTabOver == true) {
oNewDomRef = this.findFirstFieldOfNextElement(oContainer, 0, true);
} else {
oNewDomRef = this.findFirstFieldOfNextElement(oContainer, 0);
}
}
i++;
}
return oNewDomRef;
};
FormLayout.prototype.findFirstFieldOfFirstElementInPrevContainer = function(oForm, iStartIndex){
var aContainers = oForm.getFormContainers();
var iLength = aContainers.length;
var oNewDomRef;
var i = iStartIndex;
while (!oNewDomRef && i < iLength && i >= 0) {
var oContainer = aContainers[i];
if (!oContainer.getExpandable() || oContainer.getExpanded()) {
oNewDomRef = this.findFirstFieldOfNextElement(oContainer, 0);
}
i++;
}
return oNewDomRef;
};
FormLayout.prototype.navigateBack = function(oEvent){
var oForm;
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
if (oControl == oElement.getLabelControl()) {
iCurrentIndex = 0;
} else {
iCurrentIndex = oElement.indexOfField(oControl);
}
oNewDomRef = this.findPrevFieldOfElement(oElement, iCurrentIndex - 1);
if (!oNewDomRef) {
// use 1st field of next Element
var oContainer = oElement.getParent();
iCurrentIndex = oContainer.indexOfFormElement(oElement);
oNewDomRef = this.findLastFieldOfPrevElement(oContainer, iCurrentIndex - 1);
if (!oNewDomRef) {
// no next element -> look in next container
oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1);
}
}
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oForm = oElement.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oElement);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1);
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
};
FormLayout.prototype.tabBack = function(oEvent){
var oForm;
var oControl = oEvent.srcControl;
var iCurrentIndex = 0;
var oNewDomRef;
var oRoot = this.findElement(oControl);
var oElement = oRoot.element;
oControl = oRoot.rootControl;
if (oElement && oElement instanceof sap.ui.layout.form.FormElement) {
if (oControl == oElement.getLabelControl()) {
iCurrentIndex = 0;
} else {
iCurrentIndex = oElement.indexOfField(oControl);
}
oNewDomRef = this.findPrevFieldOfElement(oElement, iCurrentIndex - 1, true);
if (!oNewDomRef) {
// use 1st field of next Element
var oContainer = oElement.getParent();
iCurrentIndex = oContainer.indexOfFormElement(oElement);
oNewDomRef = this.findLastFieldOfPrevElement(oContainer, iCurrentIndex - 1, true);
if (!oNewDomRef) {
// no next element -> look in next container
oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
if (oContainer.getExpandable()) {
oNewDomRef = oContainer._oExpandButton.getFocusDomRef();
}
if (!oNewDomRef) {
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1, true);
}
}
}
} else if (oElement && oElement instanceof sap.ui.layout.form.FormContainer) {
// current control is not inside an Element - maybe a title or expander?
oForm = oElement.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oElement);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1, true);
}
if (oNewDomRef) {
jQuery.sap.focus(oNewDomRef);
oEvent.preventDefault(); // to avoid moving cursor in next field
}
};
FormLayout.prototype.findPrevFieldOfElement = function(oElement, iStartIndex, bTabOver){
var aFields = oElement.getFields();
var oNewDomRef;
for ( var i = iStartIndex; i >= 0; i--) {
// find the next enabled control thats rendered
var oField = aFields[i];
var oDomRef = this._getDomRef(oField);
if (bTabOver == true) {
if ((!oField.getEditable || oField.getEditable()) && (!oField.getEnabled || oField.getEnabled()) && oDomRef) {
oNewDomRef = oDomRef;
break;
}
} else {
if ((!oField.getEnabled || oField.getEnabled()) && oDomRef) {
oNewDomRef = oDomRef;
break;
}
}
}
return oNewDomRef;
};
FormLayout.prototype.findLastFieldOfPrevElement = function(oContainer, iStartIndex, bTabOver){
var aElements = oContainer.getFormElements();
var oNewDomRef;
var i = iStartIndex;
while (!oNewDomRef && i >= 0) {
var oElement = aElements[i];
var iLength = oElement.getFields().length;
if (bTabOver == true) {
oNewDomRef = this.findPrevFieldOfElement(oElement, iLength - 1, true);
} else {
oNewDomRef = this.findPrevFieldOfElement(oElement, iLength - 1);
}
i--;
}
return oNewDomRef;
};
FormLayout.prototype.findLastFieldOfLastElementInPrevContainer = function(oForm, iStartIndex, bTabOver){
var aContainers = oForm.getFormContainers();
var oNewDomRef;
var i = iStartIndex;
while (!oNewDomRef && i >= 0) {
var oContainer = aContainers[i];
if (oContainer.getExpandable() && !oContainer.getExpanded() && bTabOver) {
oNewDomRef = oContainer._oExpandButton.getFocusDomRef();
if (oNewDomRef) {
break;
}
}
if (!oContainer.getExpandable() || oContainer.getExpanded()) {
var iLength = oContainer.getFormElements().length;
if (bTabOver == true) {
oNewDomRef = this.findLastFieldOfPrevElement(oContainer, iLength - 1, true);
} else {
oNewDomRef = this.findLastFieldOfPrevElement(oContainer, iLength - 1, 0);
}
}
i--;
}
return oNewDomRef;
};
FormLayout.prototype.findFieldBelow = function(oControl, oElement){
var oContainer = oElement.getParent();
var iCurrentIndex = oContainer.indexOfFormElement(oElement);
var oNewDomRef = this.findFirstFieldOfNextElement(oContainer, iCurrentIndex + 1);
if (!oNewDomRef) {
// no next element -> look in next container
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex + 1);
}
return oNewDomRef;
};
FormLayout.prototype.findFieldAbove = function(oControl, oElement){
var oContainer = oElement.getParent();
var iCurrentIndex = oContainer.indexOfFormElement(oElement);
var aElements = oContainer.getFormElements();
var oNewDomRef;
var i = iCurrentIndex - 1;
while (!oNewDomRef && i >= 0) {
var oMyElement = aElements[i];
oNewDomRef = this.findPrevFieldOfElement(oMyElement, 0);
i--;
}
if (!oNewDomRef) {
// no next element -> look in previous container
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1);
}
return oNewDomRef;
};
FormLayout.prototype._getDomRef = function( oControl ){
// get focusDOMRef of the control, but only if it's focusable
var oDomRef = oControl.getFocusDomRef();
if (!jQuery(oDomRef).is(":sapFocusable")) {
oDomRef = undefined;
}
return oDomRef;
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* In this basic <code>FormLayout</code> each <code>FormContainer</code> has its own DOM.
* @param {sap.ui.layout.form.FormContainer} oContainer <code>FormContainer</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
FormLayout.prototype.getContainerRenderedDomRef = function(oContainer) {
if (this.getDomRef()) {
return jQuery.sap.domById(oContainer.getId());
}else {
return null;
}
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* In this basic <code>FormLayout</code> each <code>FormElement</code> has its own DOM.
* @param {sap.ui.layout.form.FormElement} oElement <code>FormElement</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
FormLayout.prototype.getElementRenderedDomRef = function(oElement) {
if (this.getDomRef()) {
return jQuery.sap.domById(oElement.getId());
}else {
return null;
}
};
}());
return FormLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/FormLayout.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.GridContainerData') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.GridContainerData.
jQuery.sap.declare('sap.ui.layout.form.GridContainerData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.LayoutData'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/GridContainerData",['jquery.sap.global', 'sap/ui/core/LayoutData', 'sap/ui/layout/library'],
function(jQuery, LayoutData, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.GridContainerData.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* <code>GridLayout</code>-specific properties for <code>FormContainers</code>.
* @extends sap.ui.core.LayoutData
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.GridContainerData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var GridContainerData = LayoutData.extend("sap.ui.layout.form.GridContainerData", /** @lends sap.ui.layout.form.GridContainerData.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* If set, the container takes half the width of the <code>Form</code> (8 cells), if not it takes the full width (16 cells).
* If the <code>GridLayout</code> is set to <code>singleColumn</code>, the full width of the grid is only 8 cells. So containers are rendered only once per row.
*/
halfGrid : {type : "boolean", group : "Misc", defaultValue : false}
}
}});
///**
// * This file defines behavior for the control,
// */
//sap.ui.commons.form.GridLayoutdata.prototype.init = function(){
// // do something for initialization...
//};
return GridContainerData;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/GridContainerData.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.GridElementData') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.GridElementData.
jQuery.sap.declare('sap.ui.layout.form.GridElementData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.LayoutData'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/GridElementData",['jquery.sap.global', 'sap/ui/core/LayoutData', 'sap/ui/layout/library'],
function(jQuery, LayoutData, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.GridElementData.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* The <code>GridLayout</code>-specific layout data for <code>FormElement</code> fields.
* @extends sap.ui.core.LayoutData
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.GridElementData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var GridElementData = LayoutData.extend("sap.ui.layout.form.GridElementData", /** @lends sap.ui.layout.form.GridElementData.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Number of cells in horizontal direction.
* If set to "auto" the size is determined by the number of fields and the available cells. For labels the auto size is 3 cells.
* If set to "full" only one field is allowed within the <code>FormElement</code>. It gets the full width of the row and the label is displayed above. <b>Note:</b> For labels full size has no effect.
*/
hCells : {type : "sap.ui.layout.form.GridElementCells", group : "Appearance", defaultValue : 'auto'},
/**
* Number of cells in vertical direction.
* <b>Note:</b> This property has no effect for labels.
*/
vCells : {type : "int", group : "Appearance", defaultValue : 1}
}
}});
///**
// * This file defines behavior for the control,
// */
//sap.ui.commons.form.GridElementData.prototype.init = function(){
// // do something for initialization...
//};
return GridElementData;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/GridElementData.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.GridLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.GridLayout.
jQuery.sap.declare('sap.ui.layout.form.GridLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/GridLayout",['jquery.sap.global', './FormLayout', './GridContainerData', './GridElementData', 'sap/ui/layout/library'],
function(jQuery, FormLayout, GridContainerData, GridElementData, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.GridLayout.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* This <code>FormLayout</code> renders a <code>Form</code> using a HTML-table based grid.
* This can be a 16 column grid or an 8 column grid. The grid is stable, so the alignment of the fields is the same for all screen sizes or widths of the <code>Form</code>.
* Only the width of the single grid columns depends on the available width.
*
* To adjust the appearance inside the <code>GridLayout</code>, you can use <code>GridContainerData</code> for <code>FormContainers</code>
* and <code>GridElementData</code> for content fields.
*
* <b>Note:</b> If content fields have a <code>width</code> property this will be ignored, as the width of the controls is set by the grid cells.
*
* This control cannot be used stand alone, it only renders a <code>Form</code>, so it must be assigned to a <code>Form</code>.
* @extends sap.ui.layout.form.FormLayout
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.GridLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var GridLayout = FormLayout.extend("sap.ui.layout.form.GridLayout", /** @lends sap.ui.layout.form.GridLayout.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* If set, the grid renders only one <code>FormContainer</code> per column. That means one <code>FormContainer</code> is below the other. The whole grid has 8 cells per row.
*
* If not set, <code>FormContainer</code> can use the full width of the grid or two <code>FormContainers</code> can be placed beside each other. In this case the whole grid has 16 cells per row.
*/
singleColumn : {type : "boolean", group : "Misc", defaultValue : false}
}
}});
/**
* This file defines behavior for the control
*/
(function() {
GridLayout.prototype.toggleContainerExpanded = function(oContainer){
// rerendering of the form is needed
this.invalidate();
};
GridLayout.prototype.onAfterRendering = function(){
// set tabindex of expander buttons to -1 to prevent tabbing from outside the Form
// directly to the expander
var oForm = this.getParent();
if (oForm) {
var aContainers = oForm.getFormContainers();
for ( var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
if (oContainer.getExpandable()) {
oContainer._oExpandButton.$().attr("tabindex", "-1");
}
}
}
};
/*
* If onAfterRendering of a field is processed the width must be set to 100%
*/
GridLayout.prototype.contentOnAfterRendering = function(oFormElement, oControl){
FormLayout.prototype.contentOnAfterRendering.apply(this, arguments);
if (oControl.getMetadata().getName() != "sap.ui.commons.Image" ) {
oControl.$().css("width", "100%");
}
};
/*
* If LayoutData changed on one control this needs to rerender the whole table
* because it may influence other rows and columns
*/
GridLayout.prototype.onLayoutDataChange = function(oEvent){
if (this.getDomRef()) {
// only if already rendered
this.rerender();
}
};
GridLayout.prototype.onsaptabnext = function(oEvent){
this.tabForward(oEvent);
};
GridLayout.prototype.onsaptabprevious = function(oEvent){
this.tabBack(oEvent);
};
GridLayout.prototype.findFieldOfElement = function(oElement, iStartIndex, iLeft){
if (!iLeft) {
return FormLayout.prototype.findPrevFieldOfElement.apply(this, arguments);
}
if (!oElement.getVisible()) {
return null;
}
var aFields = oElement.getFields();
var oNewDomRef;
var iIndex = aFields.length;
iStartIndex = iIndex - 1;
for ( var i = iStartIndex; i >= 0; i--) {
// find the next enabled control thats rendered
var oField = aFields[i];
var iLeftnew = oField.$().offset().left;
if (iLeft < iLeftnew && i != 0) {
continue;
}
var oDomRef = this._getDomRef(oField);
if ((!oField.getEnabled || oField.getEnabled()) && oDomRef) {
oNewDomRef = oDomRef;
break;
}
}
return oNewDomRef;
};
GridLayout.prototype.findFieldBelow = function(oControl, oElement){
var oContainer = oElement.getParent();
var iCurrentIndex = oContainer.indexOfFormElement(oElement);
var oNewDomRef;
if (oContainer.getVisible()) {
var aElements = oContainer.getFormElements();
var iMax = aElements.length;
var i = iCurrentIndex + 1;
var iLeft = oControl.$().offset().left;
while (!oNewDomRef && i < iMax) {
var oNewElement = aElements[i];
oNewDomRef = this.findFieldOfElement(oNewElement, 0, iLeft);
i++;
}
}
if (!oNewDomRef) {
// no next element -> look in next container
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findFirstFieldOfFirstElementInNextContainer(oForm, iCurrentIndex + 1);
}
return oNewDomRef;
};
GridLayout.prototype.findFieldAbove = function(oControl, oElement){
var oContainer = oElement.getParent();
var iCurrentIndex = oContainer.indexOfFormElement(oElement);
var oNewDomRef;
if (oContainer.getVisible()) {
var aElements = oContainer.getFormElements();
var i = iCurrentIndex - 1;
var iLeft = oControl.$().offset().left;
while (!oNewDomRef && i >= 0) {
var oNewElement = aElements[i];
oNewDomRef = this.findFieldOfElement(oNewElement, 0, iLeft);
i--;
}
}
if (!oNewDomRef) {
// no next element -> look in previous container
var oForm = oContainer.getParent();
iCurrentIndex = oForm.indexOfFormContainer(oContainer);
oNewDomRef = this.findLastFieldOfLastElementInPrevContainer(oForm, iCurrentIndex - 1);
}
return oNewDomRef;
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* In <code>GridLayout</code> a <code>FormContainer</code> can't have a surrounding DOM element,
* so it always returns null
* @param {sap.ui.layout.form.FormContainer} oContainer <code>FormContainer</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
GridLayout.prototype.getContainerRenderedDomRef = function(oContainer) {
return null;
};
/**
* As Elements must not have a DOM reference it is not sure if one exists.
* In this layout a <code>FormElement</code> only has a DOM representation if its <code>FormContainer</code>
* has the whole width
* @param {sap.ui.layout.form.FormElement} oElement <code>FormElement</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
GridLayout.prototype.getElementRenderedDomRef = function(oElement) {
if (this.getDomRef()) {
var bSingleColumn = this.getSingleColumn();
var oContainer = oElement.getParent();
var oContainerData = this.getLayoutDataForElement(oContainer, "sap.ui.layout.form.GridContainerData");
var that = this;
if ((bSingleColumn || !oContainerData || !oContainerData.getHalfGrid()) && !this.getRenderer().checkFullSizeElement(that, oElement) ) {
return jQuery.sap.domById(oElement.getId());
}
}
return null;
};
}());
return GridLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/GridLayout.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.ResponsiveGridLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.ResponsiveGridLayout.
jQuery.sap.declare('sap.ui.layout.form.ResponsiveGridLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/ResponsiveGridLayout",['jquery.sap.global', 'sap/ui/layout/Grid', 'sap/ui/layout/GridData', './FormLayout', 'sap/ui/layout/library'],
function(jQuery, Grid, GridData, FormLayout, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.ResponsiveGridLayout.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* Renders a <code>Form</code> using a responsive grid. Internally the <code>Grid</code> control is used for rendering.
* Using this layout, the <code>Form</code> is rendered in a responsive way.
* Depending on the available space, the <code>FormContainers</code> are rendered in one or different columns and the labels are rendered in the same row as the fields or above the fields.
* This behavior can be influenced by the properties of this layout control.
*
* On the <code>FormContainers</code>, labels and content fields, <code>GridData</code> can be used to change the default rendering.
* <code>GridData</code> is not supported for <code>FormElements</code>.
*
* <b>Note:</b> If <code>GridData</code> is used, this may result in a much more complex layout than the default one.
* This means that in some cases, the calculation for the other content may not bring the expected result.
* In such cases, <code>GridData</code> should be used for all content controls to disable the default behavior.
*
* This control cannot be used standalone, it only renders a <code>Form</code>, so it must be assigned to a <code>Form</code>.
* @extends sap.ui.layout.form.FormLayout
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.ResponsiveGridLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ResponsiveGridLayout = FormLayout.extend("sap.ui.layout.form.ResponsiveGridLayout", /** @lends sap.ui.layout.form.ResponsiveGridLayout.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* Default span for labels in large size.
* This span is only used if more than 1 <code>FormContainer</code> is in one line. If only 1 <code>FormContainer</code> is in the line, then the <code>labelSpanM</code> value is used.
* @since 1.16.3
*/
labelSpanL : {type : "int", group : "Misc", defaultValue : 4},
/**
* Default span for labels in medium size.
* This property is used for full-size <code>FormContainers</code>. If more than one <code>FormContainer</code> is in one line, <code>labelSpanL</code> is used.
* @since 1.16.3
*/
labelSpanM : {type : "int", group : "Misc", defaultValue : 2},
/**
* Default span for labels in small size.
* @since 1.16.3
*/
labelSpanS : {type : "int", group : "Misc", defaultValue : 12},
/**
* Number of grid cells that are empty at the end of each line on large size.
* @since 1.16.3
*/
emptySpanL : {type : "int", group : "Misc", defaultValue : 0},
/**
* Number of grid cells that are empty at the end of each line on medium size.
* @since 1.16.3
*/
emptySpanM : {type : "int", group : "Misc", defaultValue : 0},
/**
* Number of grid cells that are empty at the end of each line on small size.
* @since 1.16.3
*/
emptySpanS : {type : "int", group : "Misc", defaultValue : 0},
/**
* Number of columns for large size.
* The number of columns for large size must not be smaller than the number of columns for medium size
* @since 1.16.3
*/
columnsL : {type : "int", group : "Misc", defaultValue : 2},
/**
* Number of columns for medium size.
* @since 1.16.3
*/
columnsM : {type : "int", group : "Misc", defaultValue : 1},
/**
* Breakpoint (in pixel) between Medium size and Large size.
* @since 1.16.3
*/
breakpointL : {type : "int", group : "Misc", defaultValue : 1024},
/**
* Breakpoint (in pixel) between Small size and Medium size.
* @since 1.16.3
*/
breakpointM : {type : "int", group : "Misc", defaultValue : 600}
}
}});
/*
* The ResponsiveGridLayout uses Grid controls to render the Form
* If more than one FormContainer is used, there is an outer Grid (mainGrid) that holds the FormContainers.
* Each FormContainer holds its own Grid where the FormElements content is placed.
* If a FormContainer has a Title or is expandable it is rendered as a ResponsiveGridLayoutPanel.
* The panels and Grid layouts are stored in this.mContainers. This has the following structure:
* - For each FormContainer there is an entry inside the object. (this.mContainers[FormContainerId])
* - For each FormContainer there is an array with 2 entries:
* - [0]: The Panel that renders the Container (undefined if no panel is used)
* - [1]: The Grid that holds the Containers content
* - the getLayoutData function of this Grid is overwritten to get the LayoutData of the FormContainer
* (If no panel is used)
*
* It must make sure that this object is kept up to date, so for this reason it is filled onBeforeRendering. Entries that are no longer used are deleted.
*
*/
sap.ui.core.Control.extend("sap.ui.layout.form.ResponsiveGridLayoutPanel", {
metadata : {
aggregations: {
"content" : {type: "sap.ui.layout.Grid", multiple: false}
},
associations: {
"container" : {type: "sap.ui.layout.form.FormContainer", multiple: false},
"layout" : {type: "sap.ui.layout.form.ResponsiveLayout", multiple: false}
}
},
getLayoutData : function(){
// only ResponsiveFlowLayoutData are interesting
var oContainer = sap.ui.getCore().byId(this.getContainer());
var oLayout = sap.ui.getCore().byId(this.getLayout());
var oLD;
if (oLayout && oContainer) {
oLD = oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.GridData");
}
if (oLD) {
return oLD;
} else {
return this.getAggregation("layoutData");
}
},
getCustomData : function(){
var oContainer = sap.ui.getCore().byId(this.getContainer());
if (oContainer) {
return oContainer.getCustomData();
}
},
refreshExpanded : function(){
var oContainer = sap.ui.getCore().byId(this.getContainer());
if (oContainer) {
if (oContainer.getExpanded()) {
this.$().removeClass("sapUiRGLContainerColl");
} else {
this.$().addClass("sapUiRGLContainerColl");
}
}
},
renderer : function(oRm, oPanel) {
var oContainer = sap.ui.getCore().byId(oPanel.getContainer());
var oLayout = sap.ui.getCore().byId(oPanel.getLayout());
var oContent = oPanel.getContent();
var bExpandable = oContainer.getExpandable();
var sTooltip = oContainer.getTooltip_AsString();
oRm.write("<div");
oRm.writeControlData(oPanel);
oRm.addClass("sapUiRGLContainer");
if (bExpandable && !oContainer.getExpanded()) {
oRm.addClass("sapUiRGLContainerColl");
}
if (sTooltip) {
oRm.writeAttributeEscaped('title', sTooltip);
}
oRm.writeClasses();
oLayout.getRenderer().writeAccessibilityStateContainer(oRm, oContainer);
oRm.write(">");
// container header
if (oContainer.getTitle()) {
oLayout.getRenderer().renderTitle(oRm, oContainer.getTitle(), oContainer._oExpandButton, bExpandable, false, oContainer.getId());
}
if (oContent) {
oRm.write("<div");
oRm.addClass("sapUiRGLContainerCont");
oRm.writeClasses();
oRm.write(">");
// container is not expandable or is expanded -> render elements
oRm.renderControl(oContent);
oRm.write("</div>");
}
oRm.write("</div>");
}
});
(function() {
/* eslint-disable no-lonely-if */
ResponsiveGridLayout.prototype.init = function(){
this.mContainers = {}; //association of container to panel and Grid
this.oDummyLayoutData = new GridData(this.getId() + "--Dummy");
this.SPANPATTERN = /^([X][L](?:[1-9]|1[0-2]))? ?([L](?:[1-9]|1[0-2]))? ?([M](?:[1-9]|1[0-2]))? ?([S](?:[1-9]|1[0-2]))?$/i;
};
ResponsiveGridLayout.prototype.exit = function(){
var that = this;
// clear panels
for ( var sContainerId in this.mContainers) {
_cleanContainer(that, sContainerId);
}
// clear main Grid
if (this._mainGrid) {
this._mainGrid.destroy();
delete this._mainGrid;
}
this.oDummyLayoutData.destroy();
this.oDummyLayoutData = undefined;
};
ResponsiveGridLayout.prototype.onBeforeRendering = function( oEvent ){
var oForm = this.getParent();
if (!oForm || !(oForm instanceof sap.ui.layout.form.Form)) {
// layout not assigned to form - nothing to do
return;
}
oForm._bNoInvalidate = true; // don't invalidate Form if only the Grids, Panels and LayoutData are created or changed)
var that = this;
_createPanels(that, oForm);
_createMainGrid(that, oForm);
oForm._bNoInvalidate = false;
};
ResponsiveGridLayout.prototype.onAfterRendering = function( oEvent ){
// if main grid is used, deregister resize listeners of container grids. Because resize is triggered from main grid
// container grids can't resize if main grid is not resized.
if (this._mainGrid && this._mainGrid.__bIsUsed ) {
for ( var sContainerId in this.mContainers) {
if (this.mContainers[sContainerId][1]._sContainerResizeListener) {
sap.ui.core.ResizeHandler.deregister(this.mContainers[sContainerId][1]._sContainerResizeListener);
this.mContainers[sContainerId][1]._sContainerResizeListener = null;
}
}
}
};
/*
* If onAfterRendering of a field is processed, the width must be set to 100% (if no other width set)
*/
ResponsiveGridLayout.prototype.contentOnAfterRendering = function(oFormElement, oControl){
FormLayout.prototype.contentOnAfterRendering.apply(this, arguments);
if (oControl.getWidth && ( !oControl.getWidth() || oControl.getWidth() == "auto" ) && oControl.getMetadata().getName() != "sap.ui.commons.Image") {
oControl.$().css("width", "100%");
}
};
ResponsiveGridLayout.prototype.toggleContainerExpanded = function(oContainer){
//adapt the corresponding panel
var sContainerId = oContainer.getId();
if (this.mContainers[sContainerId] && this.mContainers[sContainerId][0]) {
var oPanel = this.mContainers[sContainerId][0];
oPanel.refreshExpanded();
}
};
ResponsiveGridLayout.prototype.onLayoutDataChange = function(oEvent){
var oSource = oEvent.srcControl;
// if layoutData changed for a Container, Element, or Field call the
// onLayoutDataChange function of the parent ResponsiveFlowLayout
if (oSource instanceof sap.ui.layout.form.FormContainer) {
if (this._mainGrid) {
this._mainGrid.onLayoutDataChange(oEvent);
}
} else if (!(oSource instanceof sap.ui.layout.form.FormElement)) { // LayoutData on FormElement not supported in ResponsiveGridLayout
var oParent = oSource.getParent();
if (oParent instanceof sap.ui.layout.form.FormElement) {
var oContainer = oParent.getParent();
var sContainerId = oContainer.getId();
if (this.mContainers[sContainerId] && this.mContainers[sContainerId][1]) {
this.mContainers[sContainerId][1].onLayoutDataChange(oEvent);
}
}
}
};
ResponsiveGridLayout.prototype.onsapup = function(oEvent){
this.onsapleft(oEvent);
};
ResponsiveGridLayout.prototype.onsapdown = function(oEvent){
this.onsapright(oEvent);
};
/**
* As Elements must not have a DOM reference it is not clear if one exists.
* If the <code>FormContainer</code> has a title or is expandable an internal panel is rendered.
* In this case, the panel's DOM reference is returned, otherwise the DOM reference
* of the <code>Grid</code> rendering the container's content.
* @param {sap.ui.layout.form.FormContainer} oContainer <code>FormContainer</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
ResponsiveGridLayout.prototype.getContainerRenderedDomRef = function(oContainer) {
if (this.getDomRef()) {
var sContainerId = oContainer.getId();
if (this.mContainers[sContainerId]) {
if (this.mContainers[sContainerId][0]) {
var oPanel = this.mContainers[sContainerId][0];
return oPanel.getDomRef();
}else if (this.mContainers[sContainerId][1]){
// no panel used -> return Grid
var oGrid = this.mContainers[sContainerId][1];
return oGrid.getDomRef();
}
}
}
return null;
};
/**
* As Elements must not have a DOM reference it is not clear if one exists.
* In this Layout a <code>FormElement</code> has no DOM representation,
* so null will always be returned
* @param {sap.ui.layout.form.FormElement} oElement <code>FormElement</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
ResponsiveGridLayout.prototype.getElementRenderedDomRef = function(oElement) {
return null;
};
function _createPanels( oLayout, oForm ) {
var aContainers = oForm.getFormContainers();
var iLength = aContainers.length;
var iVisibleContainers = 0;
var iVisibleContainer = 0;
var aVisibleContainers = [];
var oPanel;
var oGrid;
var oContainer;
var sContainerId;
var i = 0;
for ( i = 0; i < iLength; i++) {
oContainer = aContainers[i];
oContainer._checkProperties();
if (oContainer.getVisible()) {
iVisibleContainers++;
aVisibleContainers.push(oContainer);
}
}
for ( i = 0; i < iVisibleContainers; i++) {
oContainer = aVisibleContainers[i];
if (oContainer.getVisible()) {
iVisibleContainer++;
sContainerId = oContainer.getId();
oPanel = undefined;
oGrid = undefined;
var oContainerNext = aVisibleContainers[i + 1];
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][1]) {
// Grid already created
oGrid = oLayout.mContainers[sContainerId][1];
} else {
oGrid = _createGrid(oLayout, oContainer);
}
var oTitle = oContainer.getTitle();
if (oTitle || oContainer.getExpandable()) {
// only if container has a title a panel is used
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][0]) {
// Panel already created
oPanel = oLayout.mContainers[sContainerId][0];
} else {
oPanel = _createPanel(oLayout, oContainer, oGrid);
_changeGetLayoutDataOfGrid(oGrid, true);
}
_setLayoutDataForLinebreak(oPanel, oContainer, iVisibleContainer, oContainerNext, iVisibleContainers);
} else {
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][0]) {
// panel not longer needed
_deletePanel(oLayout.mContainers[sContainerId][0]);
}
_changeGetLayoutDataOfGrid(oGrid, false);
_setLayoutDataForLinebreak(oGrid, oContainer, iVisibleContainer, oContainerNext, iVisibleContainers);
}
oLayout.mContainers[sContainerId] = [oPanel, oGrid];
}
}
var iObjectLength = _objectLength(oLayout.mContainers);
if (iVisibleContainers < iObjectLength) {
// delete old containers panels
for ( sContainerId in oLayout.mContainers) {
var bFound = false;
for ( i = 0; i < iLength; i++) {
oContainer = aContainers[i];
if (sContainerId == oContainer.getId() && oContainer.getVisible()) {
bFound = true;
break;
}
}
if (!bFound) {
_cleanContainer(oLayout, sContainerId);
}
}
}
}
function _createPanel( oLayout, oContainer, oGrid ) {
var sContainerId = oContainer.getId();
var oPanel = new sap.ui.layout.form.ResponsiveGridLayoutPanel(sContainerId + "---Panel", {
container: oContainer,
layout : oLayout,
content : oGrid
});
return oPanel;
}
/*
* clear content before delete panel
*/
function _deletePanel( oPanel ) {
oPanel.setContent("");
oPanel.setLayout("");
oPanel.setContainer("");
oPanel.destroy();
}
function _createGrid( oLayout, oContainer ) {
var sId = oContainer.getId() + "--Grid";
var oGrid = new Grid(sId, {vSpacing: 0, hSpacing: 0, containerQuery: true});
oGrid.__myParentLayout = oLayout;
oGrid.__myParentContainerId = oContainer.getId();
oGrid.addStyleClass("sapUiFormResGridCont");
oGrid.getContent = function(){
var oContainer = sap.ui.getCore().byId(this.__myParentContainerId);
if (oContainer) {
var aContent = [];
var aElements = oContainer.getFormElements();
var aFields;
var oLabel;
for ( var i = 0; i < aElements.length; i++) {
var oElement = aElements[i];
if (oElement.getVisible()) {
oLabel = oElement.getLabelControl();
if (oLabel) {
aContent.push(oLabel);
}
aFields = oElement.getFields();
for ( var j = 0; j < aFields.length; j++) {
aContent.push(aFields[j]);
}
}
}
return aContent;
} else {
return false;
}
};
oGrid._getLayoutDataForControl = function(oControl) {
var oLayout = this.__myParentLayout;
var oLD = oLayout.getLayoutDataForElement(oControl, "sap.ui.layout.GridData");
var oElement = oControl.getParent();
var oLabel = oElement.getLabelControl();
if (oLD) {
if (oLabel == oControl) {
oLD._setStylesInternal("sapUiFormElementLbl");
}
return oLD;
} else {
// calculate Layout Data for control
var oContainer = sap.ui.getCore().byId(this.__myParentContainerId);
var oContainerLD = oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.GridData");
var oForm = oContainer.getParent();
// for overall grid, label has default Span of 2, but in L 2 Containers are in one line, so 2 Grids are in one line
var iLabelLSpan = oLayout.getLabelSpanL();
var iLabelMSpan = oLayout.getLabelSpanM();
var iLabelSSpan = oLayout.getLabelSpanS();
if (oForm.getFormContainers().length >= 1 && oLayout.getColumnsM() > 1) {
// More than one Container in line
iLabelMSpan = oLayout.getLabelSpanL();
}
if (oContainerLD) {
if (oContainerLD._getEffectiveSpanLarge() == 12) {
// If Container has the Full width in large Screen, use 2 as Label Span to be in line
iLabelLSpan = oLayout.getLabelSpanM();
iLabelMSpan = oLayout.getLabelSpanM();
}
}
if (oForm.getFormContainers().length == 1 || oLayout.getColumnsL() == 1) {
// only one container -> it's full size
iLabelLSpan = oLayout.getLabelSpanM();
iLabelMSpan = oLayout.getLabelSpanM();
}
if (oLabel == oControl) {
oLayout.oDummyLayoutData.setSpan("L" + iLabelLSpan + " M" + iLabelMSpan + " S" + iLabelSSpan);
oLayout.oDummyLayoutData.setLinebreak(true);
oLayout.oDummyLayoutData._setStylesInternal("sapUiFormElementLbl");
return oLayout.oDummyLayoutData;
} else {
var iLSpan = 12 - oLayout.getEmptySpanL();
var iMSpan = 12 - oLayout.getEmptySpanM();
var iSSpan = 12 - oLayout.getEmptySpanS();
var iEffectiveSpan;
if (oLabel) {
var oLabelLD = oLayout.getLayoutDataForElement(oLabel, "sap.ui.layout.GridData");
if (oLabelLD) {
iEffectiveSpan = oLabelLD._getEffectiveSpanLarge();
if (iEffectiveSpan) {
iLabelLSpan = iEffectiveSpan;
}
iEffectiveSpan = oLabelLD._getEffectiveSpanMedium();
if (iEffectiveSpan) {
iLabelMSpan = iEffectiveSpan;
}
iEffectiveSpan = oLabelLD._getEffectiveSpanSmall();
if (iEffectiveSpan) {
iLabelSSpan = iEffectiveSpan;
}
}
if (iLabelLSpan < 12) {
iLSpan = iLSpan - iLabelLSpan;
}
if (iLabelMSpan < 12) {
iMSpan = iMSpan - iLabelMSpan;
}
if (iLabelSSpan < 12) {
iSSpan = iSSpan - iLabelSSpan;
}
}
var aFields = oElement.getFields();
var iLength = aFields.length;
var iDefaultFields = 1; // because current field has no LayoutData
var bFirstField = false;
for ( var i = 0; i < iLength; i++) {
var oField = aFields[i];
if (oField != oControl) {
// check if other fields have layoutData
var oFieldLD = oLayout.getLayoutDataForElement(oField, "sap.ui.layout.GridData");
// is Spans are too large - ignore in calculation....
if (oFieldLD) {
iEffectiveSpan = oFieldLD._getEffectiveSpanLarge();
if (iEffectiveSpan && iEffectiveSpan < iLSpan) {
iLSpan = iLSpan - iEffectiveSpan;
}
iEffectiveSpan = oFieldLD._getEffectiveSpanMedium();
if (iEffectiveSpan && iEffectiveSpan < iMSpan) {
iMSpan = iMSpan - iEffectiveSpan;
}
iEffectiveSpan = oFieldLD._getEffectiveSpanSmall();
if (iEffectiveSpan && iEffectiveSpan < iSSpan) {
iSSpan = iSSpan - iEffectiveSpan;
}
} else {
iDefaultFields++;
}
} else {
if (iDefaultFields == 1) {
bFirstField = true;
}
}
}
var iMyLSpan, iMyMSpan, iMySSpan = 12;
if (bFirstField) {
var iRest = iLSpan - Math.floor(iLSpan / iDefaultFields) * iDefaultFields;
iMyLSpan = Math.floor(iLSpan / iDefaultFields) + iRest;
iRest = iMSpan - Math.floor(iMSpan / iDefaultFields) * iDefaultFields;
iMyMSpan = Math.floor(iMSpan / iDefaultFields) + iRest;
if (iLabelSSpan < 12) {
// label is defined to not be full size -> make fields left of it
iRest = iSSpan - Math.floor(iSSpan / iDefaultFields) * iDefaultFields;
iMySSpan = Math.floor(iSSpan / iDefaultFields) + iRest;
}
} else {
iMyLSpan = Math.floor(iLSpan / iDefaultFields);
iMyMSpan = Math.floor(iMSpan / iDefaultFields);
if (iLabelSSpan < 12) {
// label is defined to not be full size -> make fields left of it
iMySSpan = Math.floor(iSSpan / iDefaultFields);
}
}
oLayout.oDummyLayoutData.setSpan("L" + iMyLSpan + " M" + iMyMSpan + " S" + iMySSpan);
oLayout.oDummyLayoutData.setLinebreak(bFirstField && !oLabel);
oLayout.oDummyLayoutData._setStylesInternal(undefined);
return oLayout.oDummyLayoutData;
}
return oLD;
}
};
// change resize handler so that the container Grids always get the same Media size like the main grid
oGrid._onParentResizeOrig = oGrid._onParentResize;
oGrid._onParentResize = function() {
// Prove if Dom reference exist, and if not - clean up the references.
if (!this.getDomRef()) {
this._cleanup();
return;
}
if (!jQuery(this.getDomRef()).is(":visible")) {
return;
}
var oLayout = this.__myParentLayout;
if (!oLayout._mainGrid || !oLayout._mainGrid.__bIsUsed ) {
// no main grid used -> only 1 container
var aContainers = oLayout.getParent().getFormContainers();
if (!oLayout.mContainers[aContainers[0].getId()] || aContainers[0].getId() != this.__myParentContainerId) {
// Form seems to be invalidated (container changed) but rerendering still not done
// -> ignore resize, it will be rerendered soon
return;
}
if (oLayout.mContainers[this.__myParentContainerId][0]) {
// panel used -> get size from panel
var oDomRef = oLayout.mContainers[this.__myParentContainerId][0].getDomRef();
var iCntWidth = oDomRef.clientWidth;
if (iCntWidth <= oLayout.getBreakpointM()) {
this._toggleClass("Phone");
} else if ((iCntWidth > oLayout.getBreakpointM()) && (iCntWidth <= oLayout.getBreakpointL())) {
this._toggleClass("Tablet");
} else {
this._toggleClass("Desktop");
}
} else {
this._setBreakPointTablet(oLayout.getBreakpointM());
this._setBreakPointDesktop(oLayout.getBreakpointL());
this._onParentResizeOrig();
}
} else {
var $DomRefMain = oLayout._mainGrid.$();
if ($DomRefMain.hasClass("sapUiRespGridMedia-Std-Phone")) {
this._toggleClass("Phone");
} else if ($DomRefMain.hasClass("sapUiRespGridMedia-Std-Tablet")) {
this._toggleClass("Tablet");
} else {
this._toggleClass("Desktop");
}
}
};
oGrid._getAccessibleRole = function() {
var oContainer = sap.ui.getCore().byId(this.__myParentContainerId);
if (!oContainer.getTitle() && !oContainer.getExpandable()) {
return "form";
}
};
return oGrid;
}
/*
* clear internal variables before delete grid
*/
function _deleteGrid( oGrid ) {
if (oGrid.__myParentContainerId) {
oGrid.__myParentContainerId = undefined;
}
oGrid.__myParentLayout = undefined;
oGrid.destroy();
}
function _changeGetLayoutDataOfGrid( oGrid, bOriginal ) {
// only GridData are from interest
if (bOriginal) {
if (oGrid.__originalGetLayoutData) {
oGrid.getLayoutData = oGrid.__originalGetLayoutData;
delete oGrid.__originalGetLayoutData;
}
} else if (!oGrid.__originalGetLayoutData) {
oGrid.__originalGetLayoutData = oGrid.getLayoutData;
oGrid.getLayoutData = function(){
var oLayout = this.__myParentLayout;
var oContainer = sap.ui.getCore().byId(this.__myParentContainerId);
var oLD;
if (oContainer) {
oLD = oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.GridData");
}
if (oLD) {
return oLD;
} else {
return this.getAggregation("layoutData");
}
};
}
}
// every second container gets a Linebreak for large screens
// oControl could be a Panel or a Grid( if no panel used)
function _setLayoutDataForLinebreak( oControl, oContainer, iVisibleContainer, oContainerNext, iVisibleContainers ) {
var oLayout;
if (oControl instanceof sap.ui.layout.form.ResponsiveGridLayoutPanel) {
oLayout = sap.ui.getCore().byId(oControl.getLayout());
} else {
oLayout = oControl.__myParentLayout;
}
var iColumnsL = oLayout.getColumnsL();
var iColumnsM = oLayout.getColumnsM();
var oLD = oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.GridData");
if (!oLD) {
// only needed if container has no own LayoutData
var bLinebreakL = (iVisibleContainer % iColumnsL) == 1;
var bLastL = (iVisibleContainer % iColumnsL) == 0;
var bLastRowL = iVisibleContainer > (iVisibleContainers - iColumnsL + (iVisibleContainers % iColumnsL));
var bLinebreakM = (iVisibleContainer % iColumnsM) == 1;
var bLastM = (iVisibleContainer % iColumnsM) == 0;
var bLastRowM = iVisibleContainer > (iVisibleContainers - iColumnsM + (iVisibleContainers % iColumnsM));
if (oContainerNext) {
var oLDNext = oLayout.getLayoutDataForElement(oContainerNext, "sap.ui.layout.GridData");
if (oLDNext && ( oLDNext.getLinebreak() || oLDNext.getLinebreakL() )) {
bLastL = true;
bLastRowL = false;
}
if (oLDNext && ( oLDNext.getLinebreak() || oLDNext.getLinebreakM() )) {
bLastM = true;
bLastRowM = false;
}
}
var sStyle = "";
if (bLastL) {
sStyle = "sapUiFormResGridLastContL";
}
if (bLastM) {
if (sStyle) {
sStyle = sStyle + " ";
}
sStyle = sStyle + "sapUiFormResGridLastContM";
}
if (bLastRowL) {
if (sStyle) {
sStyle = sStyle + " ";
}
sStyle = sStyle + "sapUiFormResGridLastRowL";
}
if (bLastRowM) {
if (sStyle) {
sStyle = sStyle + " ";
}
sStyle = sStyle + "sapUiFormResGridLastRowM";
}
oLD = oControl.getLayoutData();
if (!oLD) {
oLD = new GridData(oControl.getId() + "--LD", { linebreakL: bLinebreakL, linebreakM: bLinebreakM });
oControl.setLayoutData( oLD );
} else {
oLD.setLinebreakL(bLinebreakL);
oLD.setLinebreakM(bLinebreakM);
}
oLD._setStylesInternal(sStyle);
}
}
function _cleanContainer( oLayout, sContainerId ) {
var aContainerContent = oLayout.mContainers[sContainerId];
//delete Grid
var oGrid = aContainerContent[1];
if (oGrid) {
_deleteGrid(oGrid);
}
//delete panel
var oPanel = aContainerContent[0];
if (oPanel) {
_deletePanel(oPanel);
}
delete oLayout.mContainers[sContainerId];
}
function _createMainGrid( oLayout, oForm ) {
var aContainers = oForm.getFormContainers();
var aVisibleContainers = [];
var oContainer;
var iLength = 0;
var iContentLenght = 0;
var i = 0;
var j = 0;
// count only visible containers
for ( i = 0; i < aContainers.length; i++) {
oContainer = aContainers[i];
if (oContainer.getVisible()) {
iLength++;
aVisibleContainers.push(oContainer);
}
}
// special case: only one container -> do not render an outer ResponsiveFlowLayout
if (iLength > 1) {
var iSpanL = Math.floor(12 / oLayout.getColumnsL());
var iSpanM = Math.floor(12 / oLayout.getColumnsM());
if (!oLayout._mainGrid) {
oLayout._mainGrid = new Grid(oForm.getId() + "--Grid",{
defaultSpan: "L" + iSpanL + " M" + iSpanM + " S12",
hSpacing: 0,
vSpacing: 0,
containerQuery: true
}).setParent(oLayout);
oLayout._mainGrid.addStyleClass("sapUiFormResGridMain");
// change resize handler so that the main grid triggers the resize of it's children
oLayout._mainGrid._onParentResizeOrig = oLayout._mainGrid._onParentResize;
oLayout._mainGrid._onParentResize = function() {
this._onParentResizeOrig();
for ( var sContainerId in oLayout.mContainers) {
oLayout.mContainers[sContainerId][1]._onParentResize();
}
};
} else {
oLayout._mainGrid.setDefaultSpan("L" + iSpanL + " M" + iSpanM + " S12");
// update containers
var aLayoutContent = oLayout._mainGrid.getContent();
iContentLenght = aLayoutContent.length;
var bExchangeContent = false;
// check if content has changed
for ( i = 0; i < iContentLenght; i++) {
var oContentElement = aLayoutContent[i];
oContainer = undefined;
if (oContentElement.getContainer) {
// it's a panel
oContainer = sap.ui.getCore().byId(oContentElement.getContainer());
} else {
// it's a Grid
oContainer = sap.ui.getCore().byId(oContentElement.__myParentContainerId);
}
if (oContainer && oContainer.getVisible()) {
var oVisibleContainer = aVisibleContainers[j];
if (oContainer != oVisibleContainer) {
// order of containers has changed
bExchangeContent = true;
break;
}
var aContainerContent = oLayout.mContainers[oContainer.getId()];
if (aContainerContent[0] && aContainerContent[0] != oContentElement) {
// container uses panel but panel not the same element in content
bExchangeContent = true;
break;
}
if (!aContainerContent[0] && aContainerContent[1] && aContainerContent[1] != oContentElement) {
// container uses no panel but Grid not the same element in content
bExchangeContent = true;
break;
}
j++;
} else {
// no container exits for content -> just remove this content
oLayout._mainGrid.removeContent(oContentElement);
}
}
if (bExchangeContent) {
// remove all content and add it new.
oLayout._mainGrid.removeAllContent();
iContentLenght = 0;
}
}
oLayout._mainGrid._setBreakPointTablet(oLayout.getBreakpointM());
oLayout._mainGrid._setBreakPointDesktop(oLayout.getBreakpointL());
oLayout._mainGrid.__bIsUsed = true;
if (iContentLenght < iLength) {
// new containers added
var iStartIndex = 0;
if (iContentLenght > 0) {
iStartIndex = iContentLenght--;
}
for ( i = iStartIndex; i < aContainers.length; i++) {
oContainer = aContainers[i];
if (oContainer.getVisible()) {
var sContainerId = oContainer.getId();
if (oLayout.mContainers[sContainerId]) {
if (oLayout.mContainers[sContainerId][0]) {
// panel used
oLayout._mainGrid.addContent(oLayout.mContainers[sContainerId][0]);
} else if (oLayout.mContainers[sContainerId][1]) {
// no panel - used Grid directly
oLayout._mainGrid.addContent(oLayout.mContainers[sContainerId][1]);
}
}
}
}
}
} else if ( oLayout._mainGrid ) {
oLayout._mainGrid.__bIsUsed = false;
}
}
function _objectLength(oObject){
var iLength = 0;
if (!Object.keys) {
jQuery.each(oObject, function(){
iLength++;
});
} else {
iLength = Object.keys(oObject).length;
}
return iLength;
}
}());
return ResponsiveGridLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/ResponsiveGridLayout.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.SimpleForm') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.SimpleForm.
jQuery.sap.declare('sap.ui.layout.form.SimpleForm'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/SimpleForm",['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/layout/ResponsiveFlowLayoutData', './Form', './FormContainer', './FormElement', './FormLayout', 'sap/ui/layout/library'],
function(jQuery, Control, ResponsiveFlowLayoutData, Form, FormContainer, FormElement, FormLayout, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.SimpleForm.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* The <code>SimpleForm</code> provides an easy to use API to create simple forms.
* Inside a <code>SimpleForm</code>, a <code>Form</code> control is created along with its <code>FormContainers</code> and <code>FormElements</code>, but the complexity in the API is removed.
* <ul>
* <li>A new title starts a new group (<code>FormContainer</code>) in the form.</li>
* <li>A new label starts a new row (<code>FormElement</code>) in the form.</li>
* <li>All other controls will be assigned to the row (<code>FormElement</code>) started with the last label.</li>
* </ul>
* Use <code>LayoutData</code> to influence the layout for special cases in the Input/Display controls.
* <b>Note:</b> If a more complex form is needed, use <code>Form</code> instead.
* @extends sap.ui.core.Control
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.SimpleForm
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var SimpleForm = Control.extend("sap.ui.layout.form.SimpleForm", /** @lends sap.ui.layout.form.SimpleForm.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* The maximum amount of groups (<code>FormContainers</code>) per row that is used before a new row is started.
* <b>Note:</b> If a <code>ResponsiveGridLayout</code> is used as a layout, this property is not used. Please use the properties <code>ColumnsL</code> and <code>ColumnsM</code> in this case.
*/
maxContainerCols : {type : "int", group : "Appearance", defaultValue : 2},
/**
* The overall minimum width in pixels that is used for the <code>SimpleForm</code>. If the available width is below the given minWidth the SimpleForm will create a new row for the next group (<code>FormContainer</code>).
* The default value is -1, meaning that inner groups (<code>FormContainers</code>) will be stacked until maxCols is reached, irrespective of whether a maxWidth is reached or the available parents width is reached.
* <b>Note:</b> This property is only used if a <code>ResponsiveLayout</code> is used as a layout.
*/
minWidth : {type : "int", group : "Appearance", defaultValue : -1},
/**
* Width of the form.
* @since 1.28.0
*/
width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
/**
* Applies a device-specific and theme-specific line-height to the form rows if the form has editable content.
* If set, all (not only the editable) rows of the form will get the line height of editable fields.
* The accessibility aria-readonly attribute is set according to this property.
* <b>Note:</b> The setting of the property has no influence on the editable functionality of the form's content.
*/
editable : {type : "boolean", group : "Misc", defaultValue : null},
/**
* Specifies the min-width in pixels of the label in all form containers.
* <b>Note:</b> This property is only used if a <code>ResponsiveLayout</code> is used as a layout.
*/
labelMinWidth : {type : "int", group : "Misc", defaultValue : 192},
/**
* The <code>FormLayout</code> that is used to render the <code>SimpleForm</code>.
* We suggest using the <code>ResponsiveGridLayout</code> for rendering a <code>SimpleForm</code>, as its responsiveness uses the space available in the best way possible.
*/
layout : {type : "sap.ui.layout.form.SimpleFormLayout", group : "Misc", defaultValue : sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout},
/**
* Default span for labels in large size.
* This span is only used if more than 1 group (<code>FormContainer</code>) is in one row. If only 1 group (<code>FormContainer</code>) is in the row the <code>labelSpanM</code> value is used.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
labelSpanL : {type : "int", group : "Misc", defaultValue : 4},
/**
* Default span for labels in medium size.
* This property is used for full-size groups (<code>FormContainers</code>). If more than one group (<code>FormContainer</code>) is in one line, <code>labelSpanL</code> is used.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
labelSpanM : {type : "int", group : "Misc", defaultValue : 2},
/**
* Default span for labels in small size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
labelSpanS : {type : "int", group : "Misc", defaultValue : 12},
/**
* Number of grid cells that are empty at the end of each line on large size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
emptySpanL : {type : "int", group : "Misc", defaultValue : 0},
/**
* Number of grid cells that are empty at the end of each line on medium size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
emptySpanM : {type : "int", group : "Misc", defaultValue : 0},
/**
* Number of grid cells that are empty at the end of each line on small size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
emptySpanS : {type : "int", group : "Misc", defaultValue : 0},
/**
* Form columns for large size.
* The number of columns for large size must not be smaller than the number of columns for medium size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
columnsL : {type : "int", group : "Misc", defaultValue : 2},
/**
* Form columns for medium size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
columnsM : {type : "int", group : "Misc", defaultValue : 1},
/**
* Breakpoint between Medium size and Large size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
breakpointL : {type : "int", group : "Misc", defaultValue : 1024},
/**
* Breakpoint between Small size and Medium size.
* <b>Note:</b> This property is only used if a <code>ResponsiveGridLayout</code> is used as a layout.
* @since 1.16.3
*/
breakpointM : {type : "int", group : "Misc", defaultValue : 600}
},
defaultAggregation : "content",
aggregations : {
/**
* The content of the form is structured in the following way:
* <ul>
* <li>Add a <code>Title</code> control to start a new group (<code>FormContainer</code>).</li>
* <li>Add a <code>Label</code> control to start a new row (<code>FormElement</code>).</li>
* <li>Add controls as input fields, text fields or other as needed.</li>
* <li>Use <code>LayoutData</code> to influence the layout for special cases in the single controls.
* For example, if a <code>ResponsiveLayout</code> is used as a layout, the form content is weighted using weight 3 for the labels and weight 5 for the fields part. By default the label column is 192 pixels wide.
* If your input controls should influence their width, you can add <code>sap.ui.layout.ResponsiveFlowLayoutData</code> to them via <code>setLayoutData</code> method.
* Ensure that the sum of the weights in the <code>ResponsiveFlowLayoutData</code> is not more than 5, as this is the total width of the input control part of each form row.</li>
* </ul>
* Example for a row where the <code>TextField</code> takes 4 and the <code>TextView</code> takes 1 weight (using <code>ResponsiveLayout</code>):
* <pre>
* new sap.ui.commons.Label({text:"Label"});
* new sap.ui.commons.TextField({value:"Weight 4",
* layoutData:new sap.ui.layout.ResponsiveFlowLayoutData({weight:4})}),
* new sap.ui.commons.TextView({text:"Weight 1",
* layoutData: new sap.ui.layout.ResponsiveFlowLayoutData({weight:1})}),
* </pre>
*/
content : {type : "sap.ui.core.Element", multiple : true, singularName : "content"},
/**
* Hidden, for internal use only.
*/
form : {type : "sap.ui.layout.form.Form", multiple : false, visibility : "hidden"},
/**
* Title element of the <code>SimpleForm</code>. Can either be a <code>Title</code> control, or a string.
* @since 1.16.3
*/
title : {type : "sap.ui.core.Title", altTypes : ["string"], multiple : false}
},
associations: {
/**
* Association to controls / IDs which label this control (see WAI-ARIA attribute aria-labelledby).
* @since 1.32.0
*/
ariaLabelledBy: { type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy" }
}
}});
///**
//* This file defines behavior for the control,
//*/
(function() {
SimpleForm.prototype.init = function() {
this._iMaxWeight = 8;
this._iLabelWeight = 3;
this._iCurrentWidth = 0;
var oForm = new Form(this.getId() + "--Form");
// use title of SimpleForm in Form
oForm.getTitle = function(){
return this.getParent().getTitle();
};
oForm._origInvalidate = oForm.invalidate;
oForm.invalidate = function(oOrigin) {
this._origInvalidate(arguments);
if (this._bIsBeingDestroyed) {
return;
}
var oSimpleForm = this.getParent();
if (oSimpleForm) {
oSimpleForm._formInvalidated(oOrigin);
}
};
oForm.getAriaLabelledBy = function(){
var oSimpleForm = this.getParent();
if (oSimpleForm) {
return oSimpleForm.getAriaLabelledBy();
}else {
return null;
}
};
this.setAggregation("form",oForm);
this._aElements = null;
this._aLayouts = [];
this._changedFormContainers = [];
this._changedFormElements = [];
};
SimpleForm.prototype.exit = function() {
var oForm = this.getAggregation("form");
oForm.invalidate = oForm._origInvalidate;
if (this._sResizeListenerId) {
sap.ui.core.ResizeHandler.deregister(this._sResizeListenerId);
this._sResizeListenerId = null;
}
for (var i = 0;i < this._aLayouts.length;i++) {
var oLayout = sap.ui.getCore().byId(this._aLayouts[i]);
if (oLayout && oLayout.destroy) {
oLayout.destroy();
}
}
this._aLayouts = [];
this._aElements = null;
this._changedFormContainers = [];
this._changedFormElements = [];
};
/*
* Update FormContainers, FormElements and LayoutData before controls are rendered
*/
SimpleForm.prototype.onBeforeRendering = function() {
this._bChangedByMe = true;
//unregister resize
if (this._sResizeListenerId) {
sap.ui.core.ResizeHandler.deregister(this._sResizeListenerId);
this._sResizeListenerId = null;
}
var that = this;
var oForm = this.getAggregation("form");
if (!oForm.getLayout()) {
_setFormLayout(that);
}
_updateFormContainers(that);
this._bChangedByMe = false;
};
SimpleForm.prototype.onAfterRendering = function() {
if (this.getLayout() == sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout) {
this._bChangedByMe = true;
this.$().css("visibility", "hidden"); //avoid that a wrong layouting is visible
this._applyLinebreaks();
//attach the resize handler
this._sResizeListenerId = sap.ui.core.ResizeHandler.register(this.getDomRef(), jQuery.proxy(this._resize, this));
this._bChangedByMe = false;
}
};
SimpleForm.prototype.setEditable = function(bEditable) {
this._bChangedByMe = true;
this.setProperty("editable", bEditable, true);
var oForm = this.getAggregation("form");
oForm.setEditable(bEditable);
this._bChangedByMe = false;
return this;
};
/*
* Overwrite generated functions to use internal array to look for aggregation
*/
SimpleForm.prototype.indexOfContent = function(oObject) {
var aChildren = this._aElements;
if (aChildren) {
for (var i = 0; i < aChildren.length; i++) {
if (aChildren[i] == oObject) {
return i;
}
}
}
return -1;
};
SimpleForm.prototype.addContent = function(oElement) {
this._bChangedByMe = true;
oElement = this.validateAggregation("content", oElement, /* multiple */ true);
if (!this._aElements) {
this._aElements = [];
}
// try to find corresponding FormElement and FormContainer to update them
var iLength = this._aElements.length;
var oLastElement;
var oForm = this.getAggregation("form");
var oFormContainer;
var oFormElement;
var oParent;
var oLayoutData;
if (oElement instanceof sap.ui.core.Title) {
//start a new container with a title
oFormContainer = _createFormContainer(this, oElement);
oForm.addFormContainer(oFormContainer);
this._changedFormContainers.push(oFormContainer);
} else if (oElement.getMetadata().isInstanceOf("sap.ui.core.Label")) { // if the control implements the label interface
// new label -> create new FormElement
// determine Container from last Content element
if (iLength > 0) {
oLastElement = this._aElements[iLength - 1];
oParent = oLastElement.getParent();
if (oParent instanceof FormElement) {
oFormContainer = oParent.getParent();
} else if (oParent instanceof FormContainer) {
oFormContainer = oParent;
}
}
if (!oFormContainer) {
oFormContainer = _createFormContainer(this);
oForm.addFormContainer(oFormContainer);
this._changedFormContainers.push(oFormContainer);
}
oFormElement = _addFormElement(this, oFormContainer, oElement);
} else {
// new Field -> add to last FormElement
if (iLength > 0) {
oLastElement = this._aElements[iLength - 1];
oParent = oLastElement.getParent();
if (oParent instanceof FormElement) {
oFormContainer = oParent.getParent();
oFormElement = oParent;
oLayoutData = _getFieldLayoutData(this, oElement);
if (oLayoutData instanceof ResponsiveFlowLayoutData && !_isMyLayoutData(this, oLayoutData)) {
if (oLayoutData.getLinebreak()) {
oFormElement = _addFormElement(this, oFormContainer);
}
}
} else if (oParent instanceof FormContainer) {
oFormContainer = oParent;
oFormElement = _addFormElement(this, oFormContainer);
}
} else {
// no FormContainer and FormElement exists
oFormContainer = _createFormContainer(this);
oForm.addFormContainer(oFormContainer);
this._changedFormContainers.push(oFormContainer);
oFormElement = _addFormElement(this, oFormContainer);
}
_createFieldLayoutData(this, oElement, 5, false, true);
oFormElement.addField(oElement);
_markFormElementForUpdate(this._changedFormElements, oFormElement);
}
this._aElements.push(oElement);
oElement.attachEvent("_change", _handleContentChange, this);
this.invalidate();
this._bChangedByMe = false;
return this;
};
SimpleForm.prototype.insertContent = function(oElement, iIndex) {
oElement = this.validateAggregation("content", oElement, /* multiple */ true);
if (!this._aElements) {
this._aElements = [];
}
var iLength = this._aElements.length;
var iNewIndex;
if (iIndex < 0) {
iNewIndex = 0;
} else if (iIndex > iLength) {
iNewIndex = iLength;
} else {
iNewIndex = iIndex;
}
if (iNewIndex !== iIndex) {
jQuery.sap.log.warning("SimpleForm.insertContent: index '" + iIndex + "' out of range [0," + iLength + "], forced to " + iNewIndex);
}
if (iNewIndex == iLength) {
// just added to the end -> use add function
this.addContent(oElement);
return this;
}
this._bChangedByMe = true;
var oOldElement = this._aElements[iNewIndex];
var oForm = this.getAggregation("form");
var oFormContainer;
var oFormElement;
var oOldFormContainer;
var oOldFormElement;
var iContainerIndex;
var iElementIndex = 0;
var iFieldIndex;
var aFields;
var aFormElements;
var aFormContainers;
var i = 0;
var oField;
if (oElement instanceof sap.ui.core.Title) {
//start a new container with a title
if (iIndex == 0 && !(oOldElement instanceof sap.ui.core.Title)) {
// special case - index==0 and first container has no title -> just add title to Container
oFormContainer = oOldElement.getParent().getParent();
oFormContainer.setTitle(oElement);
} else {
oFormContainer = _createFormContainer(this, oElement);
if (oOldElement instanceof sap.ui.core.Title) {
// insert before old container
oOldFormContainer = oOldElement.getParent();
iContainerIndex = oForm.indexOfFormContainer(oOldFormContainer);
} else {
// insert after old container
oOldFormElement = oOldElement.getParent();
oOldFormContainer = oOldFormElement.getParent();
iContainerIndex = oForm.indexOfFormContainer(oOldFormContainer) + 1;
iElementIndex = oOldFormContainer.indexOfFormElement(oOldFormElement);
// check if old FormElement must be splited
if (!oOldElement.getMetadata().isInstanceOf("sap.ui.core.Label")) {
iFieldIndex = oOldFormElement.indexOfField(oOldElement);
if (iFieldIndex > 0 || oOldFormElement.getLabel()) {
// split FormElement
oFormElement = _addFormElement(this, oFormContainer);
this._changedFormElements.push(oFormElement);
_markFormElementForUpdate(this._changedFormElements, oOldFormElement);
// move all Fields after index into new FormElement
aFields = oOldFormElement.getFields();
for ( i = iFieldIndex; i < aFields.length; i++) {
oField = aFields[i];
oFormElement.addField(oField);
}
iElementIndex++;
}
}
// move all FormElements after the new content into the new container
aFormElements = oOldFormContainer.getFormElements();
for ( i = iElementIndex; i < aFormElements.length; i++) {
oFormContainer.addFormElement(aFormElements[i]);
}
}
oForm.insertFormContainer(oFormContainer, iContainerIndex);
}
this._changedFormContainers.push(oFormContainer);
} else if (oElement.getMetadata().isInstanceOf("sap.ui.core.Label")) {
if (oOldElement instanceof sap.ui.core.Title) {
// add new FormElement to previous container
oOldFormContainer = oOldElement.getParent();
iContainerIndex = oForm.indexOfFormContainer(oOldFormContainer);
aFormContainers = oForm.getFormContainers();
oFormContainer = aFormContainers[iContainerIndex - 1];
oFormElement = _addFormElement(this, oFormContainer, oElement);
} else if (oOldElement.getMetadata().isInstanceOf("sap.ui.core.Label")) {
// insert new form element before this one
oOldFormContainer = oOldElement.getParent().getParent();
iElementIndex = oOldFormContainer.indexOfFormElement(oOldElement.getParent());
oFormElement = _insertFormElement(this, oOldFormContainer, oElement, iElementIndex);
} else {
// split FormElement
oOldFormElement = oOldElement.getParent();
oOldFormContainer = oOldFormElement.getParent();
iElementIndex = oOldFormContainer.indexOfFormElement(oOldFormElement) + 1;
iFieldIndex = oOldFormElement.indexOfField(oOldElement);
if (iFieldIndex == 0 && !oOldFormElement.getLabel()) {
// special case: Form Element has no label and inserted before first Field
oFormElement = oOldFormElement;
oFormElement.setLabel(oElement);
_createFieldLayoutData(this, oElement, this._iLabelWeight, false, true, this.getLabelMinWidth());
} else {
oFormElement = _insertFormElement(this, oOldFormContainer, oElement, iElementIndex);
_markFormElementForUpdate(this._changedFormElements, oOldFormElement);
// move all Fields after index into new FormElement
aFields = oOldFormElement.getFields();
for ( i = iFieldIndex; i < aFields.length; i++) {
oField = aFields[i];
oFormElement.addField(oField);
}
}
}
this._changedFormElements.push(oFormElement);
} else { // new field
if (oOldElement instanceof sap.ui.core.Title) {
// add new Field to last FormElement of previous FormContainer
oOldFormContainer = oOldElement.getParent();
iContainerIndex = oForm.indexOfFormContainer(oOldFormContainer);
if (iContainerIndex == 0) {
// it's the first container - insert new container before
oFormContainer = _createFormContainer(this);
oForm.insertFormContainer(oFormContainer, iContainerIndex);
this._changedFormContainers.push(oFormContainer);
} else {
aFormContainers = oForm.getFormContainers();
oFormContainer = aFormContainers[iContainerIndex - 1];
}
aFormElements = oFormContainer.getFormElements();
if (aFormElements.length == 0) {
// container has no FormElements -> create one
oFormElement = _addFormElement(this, oFormContainer);
} else {
oFormElement = aFormElements[aFormElements.length - 1];
}
oFormElement.addField(oElement);
} else if (oOldElement.getMetadata().isInstanceOf("sap.ui.core.Label")) {
// add new field to previous FormElement
oOldFormElement = oOldElement.getParent();
oFormContainer = oOldFormElement.getParent();
iElementIndex = oFormContainer.indexOfFormElement(oOldFormElement);
if (iElementIndex == 0) {
// it's already the first FormElement -> insert a new one before
oFormElement = _insertFormElement(this, oFormContainer, null, 0);
} else {
aFormElements = oFormContainer.getFormElements();
oFormElement = aFormElements[iElementIndex - 1];
}
oFormElement.addField(oElement);
} else {
// insert new field into same FormElement before old field
oFormElement = oOldElement.getParent();
iFieldIndex = oFormElement.indexOfField(oOldElement);
oFormElement.insertField(oElement, iFieldIndex);
}
_markFormElementForUpdate(this._changedFormElements, oFormElement);
_createFieldLayoutData(this, oElement, 5, false, true);
}
this._aElements.splice(iNewIndex, 0, oElement);
oElement.attachEvent("_change", _handleContentChange, this);
this.invalidate();
this._bChangedByMe = false;
return this;
};
SimpleForm.prototype.removeContent = function(vElement) {
var oElement = null;
var iIndex = -1;
var i = 0;
if (this._aElements) {
if (typeof (vElement) == "string") { // ID of the element is given
vElement = sap.ui.getCore().byId(vElement);
}
if (typeof (vElement) == "object") { // the element itself is given or has just been retrieved
for (i = 0; i < this._aElements.length; i++) {
if (this._aElements[i] == vElement) {
vElement = i;
break;
}
}
}
if (typeof (vElement) == "number") { // "vElement" is the index now
if (vElement < 0 || vElement >= this._aElements.length) {
jQuery.sap.log.warning("Element.removeAggregation called with invalid index: Items, " + vElement);
} else {
iIndex = vElement;
oElement = this._aElements[iIndex];
}
}
}
if (oElement) {
this._bChangedByMe = true;
var oForm = this.getAggregation("form");
var oFormContainer;
var oFormElement;
var aFormElements;
var aFields;
if (oElement instanceof sap.ui.core.Title) {
oFormContainer = oElement.getParent();
oFormContainer.setTitle(null);
if (iIndex > 0) {
// if it's the first container -> just remove title
// remove container and add content to previous container
aFormElements = oFormContainer.getFormElements();
var iContainerIndex = oForm.indexOfFormContainer(oFormContainer);
var oPrevFormContainer = oForm.getFormContainers()[iContainerIndex - 1];
if (aFormElements.length > 0 && !aFormElements[0].getLabel()) {
// first Form Element has no label -> add its fields to last Form Element of previous container
var aPrevFormElements = oPrevFormContainer.getFormElements();
var oLastFormElement = aPrevFormElements[aPrevFormElements.length - 1];
aFields = aFormElements[0].getFields();
for (i = 0; i < aFields.length; i++) {
oLastFormElement.addField(aFields[i]);
}
_markFormElementForUpdate(this._changedFormElements, oLastFormElement);
oFormContainer.removeFormElement(aFormElements[0]);
aFormElements[0].destroy();
aFormElements.splice(0,1);
}
for (i = 0; i < aFormElements.length; i++) {
oPrevFormContainer.addFormElement(aFormElements[i]);
}
_markFormElementForUpdate(this._changedFormContainers, oPrevFormContainer);
oForm.removeFormContainer(oFormContainer);
oFormContainer.destroy();
}
} else if (oElement.getMetadata().isInstanceOf("sap.ui.core.Label")) {
oFormElement = oElement.getParent();
oFormContainer = oFormElement.getParent();
oFormElement.setLabel(null);
var iElementIndex = oFormContainer.indexOfFormElement(oFormElement);
if (iElementIndex == 0) {
// its the first Element of the container -> just remove label
if (!oFormElement.getFields()) {
// FormElement has no fields -> just delete
oFormContainer.removeFormElement(oFormElement);
oFormElement.destroy();
} else {
_markFormElementForUpdate(this._changedFormElements, oFormElement);
}
} else {
// add fields to previous FormElement
aFormElements = oFormContainer.getFormElements();
var oPrevFormElement = aFormElements[iElementIndex - 1];
aFields = oFormElement.getFields();
for (i = 0; i < aFields.length; i++) {
oPrevFormElement.addField(aFields[i]);
}
_markFormElementForUpdate(this._changedFormElements, oPrevFormElement);
oFormContainer.removeFormElement(oFormElement);
oFormElement.destroy();
}
} else { // remove field
oFormElement = oElement.getParent();
oFormElement.removeField(oElement);
if (!oFormElement.getFields() && !oFormElement.getLabel()) {
// FormElement has no more fields and no label -> just delete
oFormContainer = oFormElement.getParent();
oFormContainer.removeFormElement(oFormElement);
oFormElement.destroy();
} else {
_markFormElementForUpdate(this._changedFormElements, oFormElement);
}
}
this._aElements.splice(iIndex, 1);
oElement.setParent(null);
oElement.detachEvent("_change", _handleContentChange, this);
_removeLayoutData(this, oElement);
this.invalidate();
this._bChangedByMe = false;
return oElement;
}
return null;
};
SimpleForm.prototype.removeAllContent = function() {
var i = 0;
if (this._aElements) {
this._bChangedByMe = true;
var oForm = this.getAggregation("form");
var aFormContainers = oForm.getFormContainers();
for (i = 0; i < aFormContainers.length; i++) {
var oFormContainer = aFormContainers[i];
oFormContainer.setTitle(null);
var aFormElements = oFormContainer.getFormElements();
for ( var j = 0; j < aFormElements.length; j++) {
var oFormElement = aFormElements[j];
oFormElement.setLabel(null);
oFormElement.removeAllFields();
}
oFormContainer.destroyFormElements();
}
oForm.destroyFormContainers();
for (i = 0; i < this._aElements.length; i++) {
var oElement = this._aElements[i];
_removeLayoutData(this, oElement);
oElement.detachEvent("_change", _handleContentChange, this);
}
var aElements = this._aElements;
this._aElements = null;
this.invalidate();
this._bChangedByMe = false;
return aElements;
} else {
return [];
}
};
SimpleForm.prototype.destroyContent = function() {
var aElements = this.removeAllContent();
if (aElements) {
this._bChangedByMe = true;
for (var i = 0; i < aElements.length; i++) {
aElements[i].destroy();
}
this.invalidate();
this._bChangedByMe = false;
}
return this;
};
SimpleForm.prototype.getContent = function() {
if (!this._aElements) {
this._aElements = this.getAggregation("content", []);
}
return this._aElements;
};
/*
* Set the FormLayout to the Form. If a FormLayout is already set, just set a new one.
*/
SimpleForm.prototype.setLayout = function(sLayout) {
this._bChangedByMe = true;
var sOldLayout = this.getLayout();
this.setProperty("layout", sLayout);
if (sLayout != sOldLayout) {
var that = this;
_setFormLayout(that);
// update LayoutData for Containers, Elements and Fields
var oForm = this.getAggregation("form");
var aContainers = oForm.getFormContainers();
var aElements;
var aFields;
var oLayoutData;
for ( var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
this._changedFormContainers.push(oContainer);
oLayoutData = oContainer.getLayoutData();
if (oLayoutData) {
oLayoutData.destroy();
}
_createContainerLayoutData(this, oContainer);
aElements = oContainer.getFormElements();
for ( var j = 0; j < aElements.length; j++) {
var oElement = aElements[j];
_markFormElementForUpdate(this._changedFormElements, oElement);
oLayoutData = oElement.getLayoutData();
if (oLayoutData) {
oLayoutData.destroy();
}
_createElementLayoutData(this, oElement);
var oLabel = oElement.getLabel();
if (oLabel) {
_removeLayoutData(this, oLabel);
_createFieldLayoutData(this, oLabel, this._iLabelWeight, false, true, this.getLabelMinWidth());
}
aFields = oElement.getFields();
for ( var k = 0; k < aFields.length; k++) {
var oField = aFields[k];
_removeLayoutData(this, oField);
_createFieldLayoutData(this, oField, 5, false, true);
}
}
}
}
this._bChangedByMe = false;
return this;
};
/*
* Overwrite the clone function because content will not be cloned in default one
*/
SimpleForm.prototype.clone = function(sIdSuffix) {
this._bChangedByMe = true;
var oClone = Control.prototype.clone.apply(this, arguments);
var aContent = this.getContent();
for ( var i = 0; i < aContent.length; i++) {
var oElement = aContent[i];
var oLayoutData = oElement.getLayoutData();
var oElementClone = oElement.clone(sIdSuffix);
if (oLayoutData) {
// mark private LayoutData
if (oLayoutData.getMetadata().getName() == "sap.ui.core.VariantLayoutData") {
var aLayoutData = oLayoutData.getMultipleLayoutData();
for ( var j = 0; j < aLayoutData.length; j++) {
if (_isMyLayoutData(this, aLayoutData[j])) {
oClone._aLayouts.push(oElementClone.getLayoutData().getMultipleLayoutData()[j].getId());
}
}
} else if (_isMyLayoutData(this, oLayoutData)) {
oClone._aLayouts.push(oElementClone.getLayoutData().getId());
}
}
oClone.addContent(oElementClone);
}
this._bChangedByMe = false;
return oClone;
};
function _setFormLayout(oThis) {
var oForm = oThis.getAggregation("form");
var oLayout = oForm.getLayout();
if (oLayout) {
oLayout.destroy();
}
switch (oThis.getLayout()) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
jQuery.sap.require("sap.ui.layout.form.ResponsiveLayout");
oForm.setLayout(new sap.ui.layout.form.ResponsiveLayout(oThis.getId() + "--Layout"));
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
jQuery.sap.require("sap.ui.layout.form.GridLayout");
jQuery.sap.require("sap.ui.layout.form.GridContainerData");
jQuery.sap.require("sap.ui.layout.form.GridElementData");
oForm.setLayout(new sap.ui.layout.form.GridLayout(oThis.getId() + "--Layout"));
break;
case sap.ui.layout.form.SimpleFormLayout.ResponsiveGridLayout:
jQuery.sap.require("sap.ui.layout.form.ResponsiveGridLayout");
jQuery.sap.require("sap.ui.layout.GridData");
oForm.setLayout(new sap.ui.layout.form.ResponsiveGridLayout(oThis.getId() + "--Layout"));
break;
default:
break;
}
}
/*
* Updates the FormContainers of the simple form.
*/
function _updateFormContainers(oThis) {
oThis._changedFormContainers = [];
var sLayout = oThis.getLayout();
var oLayout;
switch (sLayout) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
// set the default values for linebreakes to avoid flickering for default case
oThis._applyLinebreaks();
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
_applyContainerSize(oThis);
break;
case sap.ui.layout.form.SimpleFormLayout.ResponsiveGridLayout:
oLayout = oThis.getAggregation("form").getLayout();
oLayout.setLabelSpanL(oThis.getLabelSpanL());
oLayout.setLabelSpanM(oThis.getLabelSpanM());
oLayout.setLabelSpanS(oThis.getLabelSpanS());
oLayout.setEmptySpanL(oThis.getEmptySpanL());
oLayout.setEmptySpanM(oThis.getEmptySpanM());
oLayout.setEmptySpanS(oThis.getEmptySpanS());
oLayout.setColumnsL(oThis.getColumnsL());
oLayout.setColumnsM(oThis.getColumnsM());
oLayout.setBreakpointL(oThis.getBreakpointL());
oLayout.setBreakpointM(oThis.getBreakpointM());
break;
default:
break;
}
for ( var i = 0; i < oThis._changedFormElements.length; i++) {
var oFormElement = oThis._changedFormElements[i];
switch (sLayout) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
_applyFieldWeight(oThis, oFormElement);
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
break;
default:
break;
}
_updateVisibility(oThis, oFormElement);
}
oThis._changedFormElements = [];
}
/*
* Checks whether the given LayoutData is created and added by this Simple Form
* @param { sap.ui.layout.ResponsiveFlowLayoutData} optional (interface) The layout data
* @returns {boolean} Whether the given layout was created by this Simple Form
* @private
*/
function _isMyLayoutData(oThis, oLayoutData) {
var sId = oLayoutData.getId(),
sLayouts = " " + oThis._aLayouts.join(" ") + " ";
return sLayouts.indexOf(" " + sId + " ") > -1;
}
/*
* Creates new sap.ui.layout.ResponsiveFlowLayoutData with the given parameters
* @param {int} iWeight the weight for the layout data
* @param {boolean} bLinebreak Whether the layout data has a linebreak
* @param {boolean} bLinebreakable Whether the layout data is linebreakable
* @returns {sap.ui.layout.ResponsiveFlowLayoutData} The newly created ResponsiveFlowLayoutData
* @private
*/
function _createRFLayoutData(oThis, iWeight, bLinebreak, bLinebreakable, iMinWidth) {
var oLayout = new ResponsiveFlowLayoutData({weight:iWeight,linebreak:bLinebreak === true,linebreakable: bLinebreakable === true});
if (iMinWidth) {
oLayout.setMinWidth(iMinWidth);
}
oThis._aLayouts.push(oLayout.getId());
return oLayout;
}
/*
* There may be VariantLayoutData used -> so get the right one for the used Layout
*/
function _getFieldLayoutData(oThis, oField){
var oLayoutData;
switch (oThis.getLayout()) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
oLayoutData = FormLayout.prototype.getLayoutDataForElement(oField, "sap.ui.layout.ResponsiveFlowLayoutData");
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
oLayoutData = FormLayout.prototype.getLayoutDataForElement(oField, "sap.ui.layout.form.GridElementData");
break;
case sap.ui.layout.form.SimpleFormLayout.ResponsiveGridLayout:
oLayoutData = FormLayout.prototype.getLayoutDataForElement(oField, "sap.ui.layout.GridData");
break;
default:
break;
}
return oLayoutData;
}
function _createFieldLayoutData(oThis, oField, iWeight, bLinebreak, bLinebreakable, iMinWidth) {
var oLayoutData;
switch (oThis.getLayout()) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
oLayoutData = _getFieldLayoutData(oThis, oField);
if (!oLayoutData || !_isMyLayoutData(oThis, oLayoutData)) {
oLayoutData = oField.getLayoutData();
if (oLayoutData && oLayoutData.getMetadata().getName() == "sap.ui.core.VariantLayoutData") {
oLayoutData.addMultipleLayoutData(_createRFLayoutData(oThis, iWeight, bLinebreak, bLinebreakable, iMinWidth));
} else if (!oLayoutData) {
oField.setLayoutData(_createRFLayoutData(oThis, iWeight, bLinebreak, bLinebreakable, iMinWidth));
} else {
jQuery.sap.log.warning("ResponsiveFlowLayoutData can not be set on Field " + oField.getId(), "_createFieldLayoutData", "SimpleForm");
}
}
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
// no default LayoutData needed"
break;
default:
break;
}
}
function _createElementLayoutData(oThis, oElement) {
switch (oThis.getLayout()) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
oElement.setLayoutData(new ResponsiveFlowLayoutData({linebreak:true, margin:false}));
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
// no default LayoutData needed"
break;
default:
break;
}
}
function _createContainerLayoutData(oThis, oContainer) {
switch (oThis.getLayout()) {
case sap.ui.layout.form.SimpleFormLayout.ResponsiveLayout:
oContainer.setLayoutData(new ResponsiveFlowLayoutData({minWidth:280}));
break;
case sap.ui.layout.form.SimpleFormLayout.GridLayout:
if (oThis.getMaxContainerCols() > 1) {
oContainer.setLayoutData(new sap.ui.layout.form.GridContainerData({halfGrid: true}));
} else {
oContainer.setLayoutData(new sap.ui.layout.form.GridContainerData({halfGrid: false}));
}
break;
default:
break;
}
}
function _removeLayoutData(oThis, oElement) {
var oLayout = _getFieldLayoutData(oThis, oElement);
if (oLayout) {
var sLayoutId = oLayout.getId();
for ( var i = 0; i < oThis._aLayouts.length; i++) {
var sId = oThis._aLayouts[i];
if (sLayoutId == sId) {
oLayout.destroy(); // is removed from parent during destroy
oThis._aLayouts.splice(i, 1);
break;
}
}
}
}
/*
* Adds a new form element to the given FormContainer and adds the given label to it.
* @param {sap.ui.layout.form.FormContainer} The form container
* @param {sap.ui.core.Label} optional (interface) The label of the element
* @returns {sap.ui.layout.form.FormElement} The newly created FormElement
* @private
*/
function _addFormElement(oThis, oFormContainer, oLabel) {
var oElement = _createFormElement(oThis, oLabel);
oFormContainer.addFormElement(oElement);
return oElement;
}
function _insertFormElement(oThis, oFormContainer, oLabel, iIndex) {
var oElement = _createFormElement(oThis, oLabel);
oFormContainer.insertFormElement(oElement, iIndex);
return oElement;
}
function _createFormElement(oThis, oLabel) {
var oElement = new FormElement();
_createElementLayoutData(oThis, oElement);
if (oLabel) {
oLabel.addStyleClass("sapUiFormLabel-CTX");
oElement.setLabel(oLabel);
if (!_getFieldLayoutData(oThis, oLabel)) {
_createFieldLayoutData(oThis, oLabel, oThis._iLabelWeight, false, true, oThis.getLabelMinWidth());
}
}
oElement.setVisible(false);
return oElement;
}
/*
* Creates a new form container and adds the given title to it.
* @param {sap.ui.core.Title} optional The title of the container
* @returns {sap.ui.layout.form.FormContainer} The newly created FormContainer
* @private
*/
function _createFormContainer(oThis, oTitle) {
var oContainer = new FormContainer();
_createContainerLayoutData(oThis, oContainer);
if (oTitle) {
oContainer.setTitle(oTitle);
}
return oContainer;
}
/*
* Applies the weight property for the fields in the responsive layout.
* @param {sap.ui.layout.form.FormElement} oElement The FormElement where the weight is applied.
* @private
*/
function _applyFieldWeight(oThis, oElement){
var iMaxWeight = oThis._iMaxWeight;
var aFields = oElement.getFields();
var oField;
var iLength = aFields.length;
var oLabel = oElement.getLabel();
var oLayoutData;
var i = 0;
if (oLabel && _getFieldLayoutData(oThis, oLabel)) {
iMaxWeight = iMaxWeight - _getFieldLayoutData(oThis, oLabel).getWeight();
}
// determine weights set from application
for (i = 0; i < aFields.length; i++) {
oField = aFields[i];
oLayoutData = _getFieldLayoutData(oThis, oField);
if (oLayoutData instanceof ResponsiveFlowLayoutData && !_isMyLayoutData(oThis, oLayoutData)) {
iMaxWeight = iMaxWeight - oLayoutData.getWeight();
iLength--;
}
}
var iWeight = Math.floor(iMaxWeight / iLength);
var iRest = iMaxWeight % iLength;
for (i = 0; i < aFields.length; i++) {
oField = aFields[i];
oLayoutData = _getFieldLayoutData(oThis, oField);
var iCurrentWeight = iWeight;
if (!oLayoutData) {
_createFieldLayoutData(oThis, oField, iCurrentWeight, false, i == 0);
} else if (_isMyLayoutData(oThis, oLayoutData) && oLayoutData instanceof ResponsiveFlowLayoutData) {
// devide rest to first fields (not only to last one) (fist because to ignore manual set weigths)
if (iRest > 0) {
iCurrentWeight++;
iRest--;
}
oLayoutData.setWeight(iCurrentWeight);
}
}
}
function _updateVisibility(oThis, oElement){
var aFields = oElement.getFields();
var bVisible = false;
for (var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
if (!oField.getVisible || oField.getVisible()) {
// at least one Field is visible
bVisible = true;
break;
}
}
if (oElement.getVisible() != bVisible) {
// set visibility of FormElement
oElement.setVisible(bVisible);
}
}
/*
* Applies the linebreaks of form containers according to the minWidth and maxContainerCol settings of the SimpleForm
* @private
*/
SimpleForm.prototype._applyLinebreaks = function(){
var oForm = this.getAggregation("form"),
aContainers = oForm.getFormContainers();
// set line break on every container if Form is smaller than getMinWidth pixel
// and reset it if it's larger
var oDomRef = this.getDomRef();
var o$ = this.$();
for (var i = 1; i < aContainers.length; i++) {
var oContainer = aContainers[i],
oLayoutData = oContainer.getLayoutData();
if (!oDomRef || o$.outerWidth(true) > this.getMinWidth()) {
// if not already rendered use default values according to column number
if (i % this.getMaxContainerCols() == 0) {
oLayoutData.setLinebreak(true);
} else {
oLayoutData.setLinebreak(false);
}
} else {
oLayoutData.setLinebreak(true);
}
}
if (oDomRef && o$.css("visibility") == "hidden") {
var that = this;
setTimeout(function() {
if (that.getDomRef()) {
that.$().css("visibility", "");
}
},10);
}
};
/*
* Applies size of the containers in GridLayout: if only one container is in the last line -> make it full size
* @private
*/
function _applyContainerSize(oThis){
var oForm = oThis.getAggregation("form");
var aContainers = oForm.getFormContainers();
var iLength = aContainers.length;
if (iLength % 2 > 0) {
aContainers[iLength - 1].getLayoutData().setHalfGrid(false);
}
}
/*
* Handles the resize event
* @private
*/
SimpleForm.prototype._resize = function(){
this._bChangedByMe = true;
if (this._iCurrentWidth == this.$().outerWidth()) {
return;
}
this._iCurrentWidth = this.$().outerWidth();
this._applyLinebreaks();
this._bChangedByMe = false;
};
function _markFormElementForUpdate(aFormElements, oFormElement){
var bFound = false;
for ( var i = 0; i < aFormElements.length; i++) {
var oChangedFormElement = aFormElements[i];
if (oChangedFormElement == oFormElement) {
bFound = true;
break;
}
}
if (!bFound) {
aFormElements.push(oFormElement);
}
}
function _handleContentChange(oEvent) {
if (oEvent.getParameter("name") == "visible") {
var oFormElement = oEvent.oSource.getParent();
_updateVisibility(this, oFormElement);
}
}
function _getFormContent(oForm) {
var aElements = [];
var aFormContainers = oForm.getFormContainers();
for ( var i = 0; i < aFormContainers.length; i++) {
var oFormContainer = aFormContainers[i];
var oTitle = oFormContainer.getTitle();
if (oTitle) {
aElements.push(oTitle);
}
var aFormElements = oFormContainer.getFormElements();
for ( var j = 0; j < aFormElements.length; j++) {
var oFormElement = aFormElements[j];
var oLabel = oFormElement.getLabel();
if (oLabel) {
aElements.push(oLabel);
}
var aFields = oFormElement.getFields();
for (var k = 0; k < aFields.length; k++) {
var oField = aFields[k];
aElements.push(oField);
}
}
}
return aElements;
}
SimpleForm.prototype._formInvalidated = function(oOrigin){
if (!this._bChangedByMe) {
// check if content is still the same like in array
// maybe ca Control was destroyed or removed without using the SimpleForm API
// as invalidate is fired for every single object only one object can be changed
var aContent = _getFormContent(this.getAggregation("form"));
var i = 0;
var j = 0;
var bCreateNew = false;
if (aContent.length < this._aElements.length) {
// at least one element must be removed -> create completely new,
// because for deleted controls it's hard to find out the old parent.
bCreateNew = true;
} else {
for (i = 0; i < aContent.length; i++) {
var oElement1 = aContent[i];
var oElement2 = this._aElements[j];
if (oElement1 === oElement2) {
j++;
} else {
// check if Element1 is new
var oElementNext = aContent[i + 1];
if (oElementNext === oElement2) {
this.insertContent(oElement1, i);
break;
}
// check if Element2 is removed
oElementNext = this._aElements[j + 1];
if (oElementNext === oElement1) {
// difficult to find out old Formelement or FormContainer -> create content completely new.
bCreateNew = true;
break;
}
break;
}
}
}
if (bCreateNew) {
this.removeAllContent();
for (i = 0; i < aContent.length; i++) {
var oElement = aContent[i];
this.addContent(oElement);
}
}
}
};
}());
return SimpleForm;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/SimpleForm.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.ResponsiveFlowLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.ResponsiveFlowLayout.
jQuery.sap.declare('sap.ui.layout.ResponsiveFlowLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.IntervalTrigger'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.theming.Parameters'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/ResponsiveFlowLayout",['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/IntervalTrigger', 'sap/ui/core/theming/Parameters', './ResponsiveFlowLayoutData', './library'],
function(jQuery, Control, IntervalTrigger, Parameters, ResponsiveFlowLayoutData, library) {
"use strict";
/**
* Constructor for a new ResponsiveFlowLayout.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* This is a layout where several controls can be added. These controls are blown up to fit a whole line. If the window resizes the controls are moved between the lines and resized again.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.ResponsiveFlowLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ResponsiveFlowLayout = Control.extend("sap.ui.layout.ResponsiveFlowLayout", /** @lends sap.ui.layout.ResponsiveFlowLayout.prototype */ { metadata : {
library : "sap.ui.layout",
properties : {
/**
* If this property is 'false' all added controls keep their widths. Otherwise all added controls will be extended to the possible width of a row.
*/
responsive : {type : "boolean", group : "Misc", defaultValue : true}
},
defaultAggregation : "content",
aggregations : {
/**
* Added content that should be positioned. Every content item should have a ResponsiveFlowLayoutData attached otherwise the default values are used.
*/
content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"}
}
}});
(function() {
ResponsiveFlowLayout.prototype.init = function() {
this._rows = [];
this._bIsRegistered = false;
this._proxyComputeWidths = jQuery.proxy(computeWidths, this);
this.oRm = sap.ui.getCore().createRenderManager();
this.oRm.writeStylesAndClasses = function() {
this.writeStyles();
this.writeClasses();
};
this.oRm.writeHeader = function(sId, oStyles, aClasses) {
this.write('<div id="' + sId + '"');
if (oStyles) {
for ( var key in oStyles) {
if (key === "width" && oStyles[key] === "100%") {
this.addClass("sapUiRFLFullLength");
}
this.addStyle(key, oStyles[key]);
}
}
for (var i = 0; i < aClasses.length; i++) {
this.addClass(aClasses[i]);
}
this.writeStylesAndClasses();
this.write(">");
};
this._iRowCounter = 0;
};
ResponsiveFlowLayout.prototype.exit = function() {
delete this._rows;
if (this._IntervalCall) {
jQuery.sap.clearDelayedCall(this._IntervalCall);
this._IntervalCall = undefined;
}
if (this._resizeHandlerComputeWidthsID) {
sap.ui.core.ResizeHandler.deregister(this._resizeHandlerComputeWidthsID);
}
delete this._resizeHandlerComputeWidthsID;
delete this._proxyComputeWidths;
this.oRm.destroy();
delete this.oRm;
delete this._$DomRef;
delete this._oDomRef;
delete this._iRowCounter;
};
var updateRows = function(oThis) {
var aControls = oThis.getContent();
var aRows = [];
var iRow = -1;
var oItem = {}, oLast = {};
var sId = "";
var oLD;
var minWidth = 0, weight = 0, length = 0;
var bBreak = false, bMargin = false, bLinebreakable = false;
for (var i = 0; i < aControls.length; i++) {
// use default values -> are overwritten if LayoutData exists
minWidth = ResponsiveFlowLayoutData.MIN_WIDTH;
weight = ResponsiveFlowLayoutData.WEIGHT;
bBreak = ResponsiveFlowLayoutData.LINEBREAK;
bMargin = ResponsiveFlowLayoutData.MARGIN;
bLinebreakable = ResponsiveFlowLayoutData.LINEBREAKABLE;
// set the values of the layout data if available
oLD = _getLayoutDataForControl(aControls[i]);
if (oLD instanceof ResponsiveFlowLayoutData) {
bBreak = oLD.getLinebreak();
minWidth = oLD.getMinWidth();
weight = oLD.getWeight();
bMargin = oLD.getMargin();
bLinebreakable = oLD.getLinebreakable();
}
if (iRow < 0 || bBreak) {
/*
* if first run OR current control should cause a linebreak the
* control will be placed in a new row
*/
iRow++;
aRows.push({
height : -1,
cont : []
});
}
length = aRows[iRow].cont.length;
sId = aControls[i].getId() + "-cont" + iRow + "_" + length;
oItem = {
minWidth : minWidth,
weight : weight,
linebreakable : bLinebreakable,
// since the margin of the element is used outside of it it
// becomes padding
padding : bMargin,
control : aControls[i],
id : sId,
breakWith : []
};
// check if item has been pushed needed if no element was found that
// is allowed to be wrapped into a new line
var bPushed = false;
if (!bLinebreakable) {
// if an element mustn't break -> find any previous element that
// is allowed to do wrapping
for (var br = length; br > 0; br--) {
oLast = aRows[iRow].cont[br - 1];
if (oLast.linebreakable) {
oLast.breakWith.push(oItem);
bPushed = true;
break;
}
}
}
if (!bPushed) {
aRows[iRow].cont.push(oItem);
}
}
oThis._rows = aRows;
};
var getCurrentWrapping = function(oRow, $Row, oThis) {
var r = [];
var lastOffsetLeft = 10000000;
var currentRow = -1;
var fnCurrentWrapping = function(j) {
var $cont = jQuery.sap.byId(oRow.cont[j].id);
if ($cont.length > 0) {
var offset = $cont[0].offsetLeft;
if (lastOffsetLeft >= offset) {
r.push({
cont : []
});
currentRow++;
}
lastOffsetLeft = offset;
r[currentRow].cont.push(oRow.cont[j]);
}
};
// Find out the "rows" within a row
if (sap.ui.getCore().getConfiguration().getRTL()) {
// for RTL-mode the elements have to be checked the other way round
for (var i = oRow.cont.length - 1; i >= 0; i--) {
fnCurrentWrapping(i);
}
} else {
for (var i = 0; i < oRow.cont.length; i++) {
fnCurrentWrapping(i);
}
}
return r;
};
/**
* @param {object}
* [oRow] is the corresponding row of possible controls
* @param {int}
* [iWidth] is the width of the row in pixels
*/
var getTargetWrapping = function(oRow, iWidth) {
/*
* initiating all required variables to increase speed and memory
* efficiency
*/
var r = [];
var currentRow = -1;
var currentWidth = 0;
var totalWeight = 0;
var indexLinebreak = 0;
var w1 = 0, w2 = 0;
var j = 0, k = 0;
// Find out the "rows" within a row
for (j = 0; j < oRow.cont.length; j++) {
currentWidth = 0;
totalWeight = 0;
for (k = indexLinebreak; k <= j; k++) {
totalWeight = totalWeight + oRow.cont[k].weight;
}
for (k = indexLinebreak; k <= j; k++) {
w1 = iWidth / totalWeight * oRow.cont[k].weight;
w1 = Math.floor(w1);
w2 = oRow.cont[k].minWidth;
currentWidth += Math.max(w1, w2);
}
if (currentRow == -1 || currentWidth > iWidth) {
r.push({
cont : []
});
if (currentRow !== -1) {
/*
* if this is NOT the first run -> all coming iterations
* needn't to start from '0' since the calculation of a new
* row has begun
*/
indexLinebreak = j;
}
currentRow++;
}
r[currentRow].cont.push(oRow.cont[j]);
}
return r;
};
var checkWrappingDiff = function(wrap1, wrap2) {
if (wrap1.length != wrap2.length) {
return true;
}
for (var i = 0; i < wrap1.length; i++) {
if (wrap1[i].cont.length != wrap2[i].cont.length) {
return true;
}
}
return false;
};
/**
* Creates the corresponding content of the targeted wrapping and pushes it
* to the RenderManager instance.
*
* @param {object}
* [oTargetWrapping] is the wrapping how it should be (may differ
* from current wrapping)
* @param {int}
* [iWidth] the available inner width of the row
* @private
*/
ResponsiveFlowLayout.prototype.renderContent = function(oTargetWrapping, iWidth) {
var r = oTargetWrapping;
var iRowProcWidth = 0;
var aWidths = [];
var i = 0, ii = 0, j = 0, jj = 0;
var totalWeight = 0;
var iProcWidth = 0;
var oCont;
var tWeight = 0, tMinWidth = 0;
var aBreakWidths = [];
var aClasses = [];
var sId = this.getId();
var sHeaderId = "";
for (i = 0; i < r.length; i++) {
/*
* reset all corresponding values for each row
*/
iProcWidth = 0;
aWidths.length = 0;
iRowProcWidth = 100; // subtract the used values from a whole row
aClasses.length = 0;
aClasses.push("sapUiRFLRow");
if (r[i].cont.length <= 1) {
aClasses.push("sapUiRFLCompleteRow");
}
var sRowId = sId + "-row" + this._iRowCounter;
var oStyles = {};
this.oRm.writeHeader(sRowId, oStyles, aClasses);
totalWeight = 0;
for (ii = 0; ii < r[i].cont.length; ii++) {
totalWeight += r[i].cont[ii].weight;
}
for (j = 0; j < r[i].cont.length; j++) {
oCont = r[i].cont[j];
tWeight = 0;
tMinWidth = 0;
if (oCont.breakWith.length > 0) {
tWeight = oCont.weight;
tMinWidth = oCont.minWidth;
for (var br = 0; br < oCont.breakWith.length; br++) {
tWeight += oCont.breakWith[br].weight;
tMinWidth += oCont.breakWith[br].minWidth;
}
}
/*
* Render Container
*/
sHeaderId = r[i].cont[j].id;
aClasses.length = 0;
// clear all other values from the object
oStyles = {
// the unit "px" is added below to be able to calculate with
// the value of min-width
"min-width" : oCont.breakWith.length > 0 ? tMinWidth : oCont.minWidth
};
iProcWidth = 100 / totalWeight * oCont.weight;
var iProcMinWidth = oStyles["min-width"] / iWidth * 100;
// round the values BEFORE they are used for the percental value
// because if the un-rounded values don't need the percental
// value
// of the min-width the percentage value of the calculated width
// might be lower
// after it is floored.
var iPMinWidth = Math.ceil(iProcMinWidth);
var iPWidth = Math.floor(iProcWidth);
if (iPWidth !== 100 && iPMinWidth > iPWidth) {
// if the percentage of the element's width will lead
// into a too small element use the corresponding
// percentage value of the min-width
iProcWidth = iPMinWidth;
} else {
iProcWidth = iPWidth;
}
// check how many percentage points are still left. If there
// are less available than calculated just use the rest of
// the row
iProcWidth = iRowProcWidth < iProcWidth ? iRowProcWidth : iProcWidth;
iRowProcWidth -= iProcWidth;
aWidths.push(iProcWidth);
// if possible percentage amount is not 0% and this is the
// last item
if (iRowProcWidth > 0 && j === (r[i].cont.length - 1)) {
iProcWidth += iRowProcWidth;
}
aClasses.push("sapUiRFLContainer");
oStyles["width"] = iProcWidth + "%";
oStyles["min-width"] = oStyles["min-width"] + "px";
this.oRm.writeHeader(sHeaderId, oStyles, aClasses);
/*
* content rendering (render control)
*/
aClasses.length = 0;
aClasses.push("sapUiRFLContainerContent");
if (oCont.breakWith.length > 0) {
aClasses.push("sapUiRFLMultiContainerContent");
}
if (oCont.padding) {
aClasses.push("sapUiRFLPaddingClass");
}
var sClass = this._addContentClass(oCont.control, j);
if (sClass) {
aClasses.push(sClass);
}
oStyles = {};
this.oRm.writeHeader("", oStyles, aClasses);
/*
* Render all following elements into same container if there
* are any that should wrap together with container. Else simply
* render the control.
*/
if (oCont.breakWith.length > 0) {
/*
* Render first element of wrap-together-group
*/
sHeaderId = r[i].cont[j].id + "-multi0";
aClasses.length = 0;
oStyles = {
"min-width" : tMinWidth + "px"
};
// set width of first element
var percW = 100 / tWeight * oCont.weight;
percW = Math.floor(percW);
aBreakWidths.push(percW);
aClasses.push("sapUiRFLMultiContent");
oStyles["width"] = percW + "%";
if (r[i].cont[j].padding) {
aClasses.push("sapUiRFLPaddingClass");
}
this.oRm.writeHeader(sHeaderId, oStyles, aClasses);
// total percentage for all elements
var tPercentage = percW;
this.oRm.renderControl(oCont.control);
this.oRm.write("</div>");
/*
* Render all following elements that should wrap with the
* trailing one
*/
for (jj = 0; jj < oCont.breakWith.length; jj++) {
sHeaderId = oCont.breakWith[jj].id + '-multi' + (jj + 1);
aClasses.length = 0;
oStyles = {
"min-width" : oCont.breakWith[jj].minWidth + "px"
};
percW = 100 / tWeight * oCont.breakWith[jj].weight;
percW = Math.floor(percW);
aBreakWidths.push(percW);
tPercentage += percW;
// if percentage is not 100% and this is the last
// item
if (tPercentage < 100 && jj === (oCont.breakWith.length - 1)) {
percW += 100 - tPercentage;
}
aClasses.push("sapUiRFLMultiContent");
oStyles["width"] = percW + "%";
if (oCont.breakWith[jj].padding) {
aClasses.push("sapUiRFLPaddingClass");
}
this.oRm.writeHeader(sHeaderId, oStyles, aClasses);
this.oRm.renderControl(oCont.breakWith[jj].control);
this.oRm.write("</div>");
}
} else {
this.oRm.renderControl(oCont.control);
}
this.oRm.write("</div>"); // content
this.oRm.write("</div>"); // container
}
this.oRm.write("</div>"); // row
this._iRowCounter++;
}
};
var computeWidths = function(bInitial) {
this._iRowCounter = 0;
this._oDomRef = this.getDomRef();
if (this._oDomRef) {
var sId = this.getId();
var iInnerWidth = jQuery(this._oDomRef).width(); //width without the padding
var bRender = false;
if (this._rows) {
for (var i = 0; i < this._rows.length; i++) {
var $Row = this._$DomRef.find("#" + sId + "-row" + i);
var oTargetWrapping = getTargetWrapping(this._rows[i], iInnerWidth);
var oCurrentWrapping = getCurrentWrapping(this._rows[i], $Row, this);
// render if wrapping differs
bRender = checkWrappingDiff(oCurrentWrapping, oTargetWrapping);
// if the width/height changed so the sizes need to be
// recalculated
var oRowRect = $Row.rect();
var oPrevRect = this._rows[i].oRect;
if (oRowRect && oPrevRect) {
bRender = bRender || (oRowRect.width !== oPrevRect.width) && (oRowRect.height !== oPrevRect.height);
}
// if this should be the initial rendering -> do it
bRender = bRender || (typeof (bInitial) === "boolean" && bInitial);
if (this._bLayoutDataChanged || bRender) {
//in IE when setting the innerHTML property to "" the changes do not take effect correctly and all the children are gone
if (sap.ui.Device.browser.internet_explorer){
jQuery(this._oDomRef).empty();
} else {
this._oDomRef.innerHTML = "";
}
// reset this to be clean for next check interval
this._bLayoutDataChanged = false;
this.renderContent(oTargetWrapping, iInnerWidth);
}
}
if (this._oDomRef.innerHTML === "") {
this.oRm.flush(this._oDomRef);
for (var i = 0; i < this._rows.length; i++) {
var oTmpRect = jQuery.sap.byId(sId + "-row" + i).rect();
this._rows[i].oRect = oTmpRect;
}
}
if (this._rows.length === 0) {
if (this._resizeHandlerComputeWidthsID) {
sap.ui.core.ResizeHandler.deregister(this._resizeHandlerComputeWidthsID);
delete this._resizeHandlerComputeWidthsID;
}
}
}
}
};
/**
* Before all controls are rendered it is needed to update the internal
* structure of the rows
*/
ResponsiveFlowLayout.prototype.onBeforeRendering = function() {
// update the internal structure of the rows
updateRows(this);
if (this._resizeHandlerFullLengthID) {
sap.ui.core.ResizeHandler.deregister(this._resizeHandlerFullLengthID);
delete this._resizeHandlerFullLengthID;
}
};
/**
* If the layout should be responsive it is necessary to fix the content's
* items' widths corresponding to the layout's width
*/
ResponsiveFlowLayout.prototype.onAfterRendering = function(oEvent) {
this._oDomRef = this.getDomRef();
this._$DomRef = jQuery(this._oDomRef);
// Initial Width Adaptation
this._proxyComputeWidths(true);
if (this.getResponsive()) {
if (!this._resizeHandlerComputeWidthsID) {
this._resizeHandlerComputeWidthsID = sap.ui.core.ResizeHandler.register(this, this._proxyComputeWidths);
}
} else {
if (this._resizeHandlerComputeWidthsID) {
sap.ui.core.ResizeHandler.deregister(this._resizeHandlerComputeWidthsID);
delete this._resizeHandlerComputeWidthsID;
}
}
};
ResponsiveFlowLayout.prototype.onThemeChanged = function(oEvent) {
if (oEvent.type === "LayoutDataChange") {
this._bLayoutDataChanged = true;
}
if (!this._resizeHandlerComputeWidthsID) {
this._resizeHandlerComputeWidthsID = sap.ui.core.ResizeHandler.register(this, this._proxyComputeWidths);
}
updateRows(this);
this._proxyComputeWidths();
};
/**
* If any LayoutData was changed the samte stuff like 'onThemeChanged' has
* to be done
*/
ResponsiveFlowLayout.prototype.onLayoutDataChange = ResponsiveFlowLayout.prototype.onThemeChanged;
var _getLayoutDataForControl = function(oControl) {
var oLayoutData = oControl.getLayoutData();
if (!oLayoutData) {
return undefined;
} else if (oLayoutData instanceof ResponsiveFlowLayoutData) {
return oLayoutData;
} else if (oLayoutData.getMetadata().getName() == "sap.ui.core.VariantLayoutData") {
// multiple LayoutData available - search here
var aLayoutData = oLayoutData.getMultipleLayoutData();
for (var i = 0; i < aLayoutData.length; i++) {
var oLayoutData2 = aLayoutData[i];
if (oLayoutData2 instanceof ResponsiveFlowLayoutData) {
return oLayoutData2;
}
}
}
};
/**
* This function needs to be overridden to prevent any rendering while some
* content is still being added.
*
* @param {sap.ui.core.Control}
* oContent the content that should be added to the layout
* @public
*/
ResponsiveFlowLayout.prototype.addContent = function(oContent) {
if (oContent && this._IntervalCall) {
jQuery.sap.clearDelayedCall(this._IntervalCall);
this._IntervalCall = undefined;
}
this.addAggregation("content", oContent);
};
/**
* These function needs to be overridden to prevent any rendering while some
* content is still being added.
*
* @param {sap.ui.core.Control}
* oContent the content that should be inserted to the layout
* @param {int}
* iIndex the index where the content should be inserted into
* @public
*/
ResponsiveFlowLayout.prototype.insertContent = function(oContent, iIndex) {
if (oContent && this._IntervalCall) {
jQuery.sap.clearDelayedCall(this._IntervalCall);
this._IntervalCall = undefined;
}
this.insertAggregation("content", oContent, iIndex);
};
/**
* These function needs to be overridden to prevent any rendering while some
* content is still being added.
*
* @param {int|string|sap.ui.core.Control}
* oContent the content that should be removed from the layout
* @returns {sap.ui.core.Control} the removed control
* @public
*/
ResponsiveFlowLayout.prototype.removeContent = function(oContent) {
if (oContent && this._IntervalCall) {
jQuery.sap.clearDelayedCall(this._IntervalCall);
this._IntervalCall = undefined;
}
this.removeAggregation("content", oContent);
};
/**
* Gets the role used for accessibility.
* Set by the Form control if ResponsiveFlowLayout represents a FormContainer.
* @return {string} sRole Accessibility role
* @since 1.28.0
* @private
*/
ResponsiveFlowLayout.prototype._getAccessibleRole = function() {
return null;
};
/**
* Sets a class at the content container
* Set by the Form control if ResponsiveFlowLayout represents a FormElement.
* @return {string} sClass CSS class
* @since 1.28.22
* @private
*/
ResponsiveFlowLayout.prototype._addContentClass = function(oControl, iIndex) {
return null;
};
}());
return ResponsiveFlowLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/ResponsiveFlowLayout.js
if ( !jQuery.sap.isDeclared('sap.ui.layout.form.ResponsiveLayout') ) {
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.layout.form.ResponsiveLayout.
jQuery.sap.declare('sap.ui.layout.form.ResponsiveLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/layout/form/ResponsiveLayout",['jquery.sap.global', 'sap/ui/layout/ResponsiveFlowLayout', 'sap/ui/layout/ResponsiveFlowLayoutData', './FormLayout', 'sap/ui/layout/library'],
function(jQuery, ResponsiveFlowLayout, ResponsiveFlowLayoutData, FormLayout, library) {
"use strict";
/**
* Constructor for a new sap.ui.layout.form.ResponsiveLayout.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Renders a <code>Form</code> with a responsive layout. Internally the <code>ResponsiveFlowLayout</code> is used.
* The responsiveness of this layout tries to best use the available space. This means that the order of the <code>FormContainers</code>, labels and fields depends on the available space.
*
* On the <code>FormContainers</code>, <code>FormElements</code>, labels and content fields, <code>ResponsiveFlowLayoutData</code> can be used to change the default rendering.
*
* We suggest using the <code>ResponsiveGridLayout</code> instead of this layout because this is easier to consume and brings more stable responsive output.
*
* <b>Note:</b> If <code>ResponsiveFlowLayoutData</code> are used this may result in a much more complex layout than the default one. This means that in some cases, the calculation for the other content may not bring the expected result.
* In such cases, <code>ResponsiveFlowLayoutData</code> should be used for all content controls to disable the default behavior.
*
* This control cannot be used stand alone, it only renders a <code>Form</code>, so it must be assigned to a <code>Form</code>.
* @extends sap.ui.layout.form.FormLayout
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @since 1.16.0
* @alias sap.ui.layout.form.ResponsiveLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ResponsiveLayout = FormLayout.extend("sap.ui.layout.form.ResponsiveLayout", /** @lends sap.ui.layout.form.ResponsiveLayout.prototype */ { metadata : {
library : "sap.ui.layout"
}});
/*
* The ResponsiveLayout for forms inside is using ResponsiveFlowLayouts to render the form.
* There is no own rendering for FormContainers or FormElements.
* The whole Layout has a Responsive FlowLayout inside to make the FormContainers responsive.
* Only if there is only one FormContainer inside the Form there is no ResponsiveFlowLayout
* for the whole layout.
* A FormContainer is rendered as a Panel if it has a title or an expander. Inside the panel there
* is a ResponsiveFlowLayout for the single FormElements. If the FormContainer has no title or
* expander, just the ResponsiveFlowLayout is rendered.
* A FormElement is rendered as ResponsiveFlowLayout to make the label and the fields responsive.
* If the Element has a label and more than 1 Field a ResponsiveFlowLayout including the fields is rendered.
* The Panels and ResponsiveFlowLayouts are stored in object this.mContainers. This has the following
* structure:
* - For each FormContainer there is an entry inside the object. (this.mContainers[FormContainerId])
* - For each FormContainer there is an array with 3 entries:
* - [0]: The Panel that renders the Container (undefined if no panel is used)
* - It's not the standard Panel, is an special panel defined for the ResponsiveLayout
* - [1]: The ResponsiveFlowLayout that holds the Containers content
* - the getLayoutData function of this ResponsiveFlowLayouts is overwritten to get the LayoutData of the FormContainer
* (If no panel is used)
* - [2]: An object that holds the ResponsiveFlowLayouts for the FormElements:
* - For each FormElement there is an entry inside the object. (this.mContainers[FormElementId])
* - Each object includes an array with 2 entries:
* - [0]: The ResponsiveFlowLayout for the FormElement
* - [1]: If more than 1 Field and a label, here the ResponsiveFlowLayout for the fields is stored
* - the getContent function of this ResponsiveFlowLayouts is overwritten to get the content of the FormElement
* - the getLayoutData function of this ResponsiveFlowLayouts is overwritten to get the LayoutData of the FormElement
*
* It must be made sure to hold this object up to date. So it is filled onBeforeRendering. Entries no longer used are deleted
*
* In this._mainRFLayout the ResponsiveFlowLayout of the whole layout is stored. (If more than one Container.)
*/
/*
* as the panel can not be used in mobile environment a own internal control is needed to render the containers
* use FormContainer as association to have access to it's content directly. So no mapping of properties and aggregations needed
*/
sap.ui.core.Control.extend("sap.ui.layout.form.ResponsiveLayoutPanel", {
metadata : {
aggregations: {
"content" : {type: "sap.ui.layout.ResponsiveFlowLayout", multiple: false}
},
associations: {
"container" : {type: "sap.ui.layout.form.FormContainer", multiple: false},
"layout" : {type: "sap.ui.layout.form.ResponsiveLayout", multiple: false}
}
},
getLayoutData : function(){
// only ResponsiveFlowLayoutData are interesting
var oContainer = sap.ui.getCore().byId(this.getContainer());
var oLayout = sap.ui.getCore().byId(this.getLayout());
var oLD;
if (oLayout && oContainer) {
oLD = oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.ResponsiveFlowLayoutData");
}
return oLD;
},
getCustomData : function(){
var oContainer = sap.ui.getCore().byId(this.getContainer());
if (oContainer) {
return oContainer.getCustomData();
}
},
refreshExpanded : function(){
var oContainer = sap.ui.getCore().byId(this.getContainer());
if (oContainer) {
if (oContainer.getExpanded()) {
this.$().removeClass("sapUiRLContainerColl");
} else {
this.$().addClass("sapUiRLContainerColl");
}
}
},
renderer : function(oRm, oPanel) {
var oContainer = sap.ui.getCore().byId(oPanel.getContainer());
var oLayout = sap.ui.getCore().byId(oPanel.getLayout());
var oContent = oPanel.getContent();
if (!oContainer || !oLayout) {
// Container might be removed, but ResponsiveFlowLayout still calls a rerendering with old content
return;
}
var bExpandable = oContainer.getExpandable();
var sTooltip = oContainer.getTooltip_AsString();
oRm.write("<div");
oRm.writeControlData(oPanel);
oRm.addClass("sapUiRLContainer");
if (bExpandable && !oContainer.getExpanded()) {
oRm.addClass("sapUiRLContainerColl");
}
if (sTooltip) {
oRm.writeAttributeEscaped('title', sTooltip);
}
oRm.writeClasses();
oLayout.getRenderer().writeAccessibilityStateContainer(oRm, oContainer);
oRm.write(">");
// container header
if (oContainer.getTitle()) {
oLayout.getRenderer().renderTitle(oRm, oContainer.getTitle(), oContainer._oExpandButton, bExpandable, false, oContainer.getId());
}
if (oContent) {
oRm.write("<div");
oRm.addClass("sapUiRLContainerCont");
oRm.writeClasses();
oRm.write(">");
// container is not expandable or is expanded -> render elements
oRm.renderControl(oContent);
oRm.write("</div>");
}
oRm.write("</div>");
}
});
(function() {
/* eslint-disable no-lonely-if */
ResponsiveLayout.prototype.init = function(){
this.mContainers = {}; //association of container to panel and ResponsiveFlowLayout
this._defaultLayoutData = new ResponsiveFlowLayoutData({margin: false});
};
ResponsiveLayout.prototype.exit = function(){
var that = this;
// clear panels
for ( var sContainerId in this.mContainers) {
_cleanContainer(that, sContainerId);
}
// clear ResponsiveFlowLayouts
if (this._mainRFLayout) {
this._mainRFLayout.destroy();
delete this._mainRFLayout;
}
this._defaultLayoutData.destroy();
delete this._defaultLayoutData;
};
ResponsiveLayout.prototype.onBeforeRendering = function( oEvent ){
var oForm = this.getParent();
if (!oForm || !(oForm instanceof sap.ui.layout.form.Form)) {
// layout not assigned to form - nothing to do
return;
}
oForm._bNoInvalidate = true; // don't invalidate Form if only the Grids, Panels and LayoutData are created or changed)
var that = this;
_createPanels(that, oForm);
_createMainResponsiveFlowLayout(that, oForm);
oForm._bNoInvalidate = false;
};
/*
* If onAfterRendering of a field is processed the width must be set to 100% (if no other width set)
*/
ResponsiveLayout.prototype.contentOnAfterRendering = function(oFormElement, oControl){
FormLayout.prototype.contentOnAfterRendering.apply(this, arguments);
if (oControl.getWidth && ( !oControl.getWidth() || oControl.getWidth() == "auto" ) && oControl.getMetadata().getName() != "sap.ui.commons.Image") {
oControl.$().css("width", "100%");
}
};
ResponsiveLayout.prototype.toggleContainerExpanded = function(oContainer){
//adapt the corresponding panel
var sContainerId = oContainer.getId();
if (this.mContainers[sContainerId] && this.mContainers[sContainerId][0]) {
var oPanel = this.mContainers[sContainerId][0];
oPanel.refreshExpanded();
}
};
ResponsiveLayout.prototype.onLayoutDataChange = function(oEvent){
var oSource = oEvent.srcControl;
var oContainer;
var sContainerId;
var sElementId;
// if layoutData changed for a Container, Element, or Field call the
// onLayoutDataChange function of the parent ResponsiveFlowLayout
if (oSource instanceof sap.ui.layout.form.FormContainer) {
if (this._mainRFLayout) {
this._mainRFLayout.onLayoutDataChange(oEvent);
}
} else if (oSource instanceof sap.ui.layout.form.FormElement) {
sContainerId = oSource.getParent().getId();
if (this.mContainers[sContainerId] && this.mContainers[sContainerId][1]) {
this.mContainers[sContainerId][1].onLayoutDataChange(oEvent);
}
} else {
var oParent = oSource.getParent();
if (oParent instanceof sap.ui.layout.form.FormElement) {
oContainer = oParent.getParent();
sContainerId = oContainer.getId();
sElementId = oParent.getId();
if (this.mContainers[sContainerId] && this.mContainers[sContainerId][2] &&
this.mContainers[sContainerId][2][sElementId]) {
this.mContainers[sContainerId][2][sElementId][0].onLayoutDataChange(oEvent);
}
}
}
};
ResponsiveLayout.prototype.onsapup = function(oEvent){
this.onsapleft(oEvent);
};
ResponsiveLayout.prototype.onsapdown = function(oEvent){
this.onsapright(oEvent);
};
/**
* As Elements must not have a DOM reference it is not sure if one exists
* If the <code>FormContainer</code> has a title or is expandable an internal panel is rendered.
* In this case, the panel's DOM reference is returned, otherwise the DOM reference
* of the <code>ResponsiveFlowLayout</code> rendering the container's content.
* @param {sap.ui.layout.form.FormContainer} oContainer <code>FormContainer</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
ResponsiveLayout.prototype.getContainerRenderedDomRef = function(oContainer) {
if (this.getDomRef()) {
var sContainerId = oContainer.getId();
if (this.mContainers[sContainerId]) {
if (this.mContainers[sContainerId][0]) {
var oPanel = this.mContainers[sContainerId][0];
return oPanel.getDomRef();
}else if (this.mContainers[sContainerId][1]){
// no panel used -> return RFLayout
var oRFLayout = this.mContainers[sContainerId][1];
return oRFLayout.getDomRef();
}
}
}
return null;
};
/**
* As Elements must not have a DOM reference it is not sure if one exists.
* In this Layout each <code>FormElement</code> is represented by an own ResponsiveFlowLayout.
* So the DOM of this <code>ResponsiveFlowLayout</code> is returned
* @param {sap.ui.layout.form.FormElement} oElement <code>FormElement</code>
* @return {Element} The Element's DOM representation or null
* @private
*/
ResponsiveLayout.prototype.getElementRenderedDomRef = function(oElement) {
if (this.getDomRef()) {
var oContainer = oElement.getParent();
var sElementId = oElement.getId();
var sContainerId = oContainer.getId();
if (this.mContainers[sContainerId]) {
if (this.mContainers[sContainerId][2]){
var mRFLayouts = this.mContainers[sContainerId][2];
if (mRFLayouts[sElementId]) {
var oRFLayout = mRFLayouts[sElementId][0];
return oRFLayout.getDomRef();
}
}
}
}
return null;
};
function _createPanels( oLayout, oForm ) {
var aContainers = oForm.getFormContainers();
var oContainer;
var sContainerId;
var iLength = aContainers.length;
var iVisibleContainers = 0;
var oPanel;
var oRFLayout;
var i = 0;
for ( i = 0; i < iLength; i++) {
oContainer = aContainers[i];
oContainer._checkProperties();
if (oContainer.getVisible()) {
iVisibleContainers++;
sContainerId = oContainer.getId();
oPanel = undefined;
oRFLayout = undefined;
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][1]) {
// ResponsiveFlowLayout already created
oRFLayout = oLayout.mContainers[sContainerId][1];
} else {
oRFLayout = _createResponsiveFlowLayout(oLayout, oContainer, undefined);
}
var oTitle = oContainer.getTitle();
if (oTitle || oContainer.getExpandable()) {
// only if container has a title a panel is used
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][0]) {
// Panel already created
oPanel = oLayout.mContainers[sContainerId][0];
} else {
oPanel = _createPanel(oLayout, oContainer, oRFLayout);
_changeGetLayoutDataOfResponsiveFlowLayout(oRFLayout, true);
}
} else {
// panel not longer needed
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][0]) {
_deletePanel(oLayout.mContainers[sContainerId][0]);
_changeGetLayoutDataOfResponsiveFlowLayout(oRFLayout, false);
}
}
var mContent = _createContent(oLayout, oContainer, oRFLayout);
oLayout.mContainers[sContainerId] = [oPanel, oRFLayout, mContent];
}
}
var iObjectLength = _objectLength(oLayout.mContainers);
if (iVisibleContainers < iObjectLength) {
// delete old containers panels
for ( sContainerId in oLayout.mContainers) {
var bFound = false;
for ( i = 0; i < iLength; i++) {
oContainer = aContainers[i];
if (sContainerId == oContainer.getId() && oContainer.getVisible()) {
bFound = true;
break;
}
}
if (!bFound) {
_cleanContainer(oLayout, sContainerId);
}
}
}
}
function _createPanel( oLayout, oContainer, oRFLayout ) {
var sContainerId = oContainer.getId();
var oPanel = new sap.ui.layout.form.ResponsiveLayoutPanel(sContainerId + "--Panel", {
container: oContainer,
layout : oLayout,
content : oRFLayout
});
return oPanel;
}
/*
* clear variables before delete it
*/
function _deletePanel( oPanel ) {
oPanel.setContent("");
oPanel.setLayout("");
oPanel.setContainer("");
oPanel.destroy();
}
function _createContent( oLayout, oContainer, oContainerLayout ) {
var sContainerId = oContainer.getId();
var aElements = oContainer.getFormElements();
var iLength = aElements.length;
var iVisibleElements = 0;
var mRFLayouts = {};
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][2]) {
mRFLayouts = oLayout.mContainers[sContainerId][2];
}
var oRFLayout;
var oFieldsRFLayout;
var iLastIndex = -1;
var oElement;
var sElementId;
var i = 0;
for (i = 0; i < iLength; i++) {
oElement = aElements[i];
if (oElement.getVisible()) {
sElementId = oElement.getId();
_checkElementMoved(oLayout, oContainer, oElement, mRFLayouts, oContainerLayout, i);
if (mRFLayouts[sElementId]) {
// ResponsiveFlowLayout already created
oRFLayout = mRFLayouts[sElementId][0];
iLastIndex = oContainerLayout.indexOfContent(oRFLayout);
} else {
oRFLayout = _createResponsiveFlowLayout(oLayout, oContainer, oElement);
oRFLayout.addStyleClass("sapUiRLElement");
if (oElement.getLabel()) {
oRFLayout.addStyleClass("sapUiRLElementWithLabel");
}
mRFLayouts[sElementId] = [oRFLayout, undefined];
iLastIndex++;
oContainerLayout.insertContent(oRFLayout, iLastIndex);
}
// if more fields after a label put the fields in an additional ResponsiveFlowLayout
var aFields = oElement.getFields();
if (oElement.getLabel() && aFields.length > 1) {
if (mRFLayouts[sElementId][1]) {
oFieldsRFLayout = mRFLayouts[sElementId][1];
} else {
oFieldsRFLayout = _createResponsiveFlowLayout(oLayout, oContainer, oElement, true);
oFieldsRFLayout.addStyleClass("sapUiRLElementFields");
mRFLayouts[sElementId][1] = oFieldsRFLayout;
}
_updateLayoutDataOfContentResponsiveFlowLayout(oLayout, oFieldsRFLayout, aFields);
} else {
if (mRFLayouts[sElementId][1]) {
// ResponsiveFlowLayout for fields not longer needed
oFieldsRFLayout = mRFLayouts[sElementId][1];
_deleteResponsiveFlowLayout(oFieldsRFLayout);
mRFLayouts[sElementId][1] = undefined;
}
}
iVisibleElements++;
}
}
var iObjectLength = _objectLength(mRFLayouts);
if (iVisibleElements < iObjectLength) {
// delete old elements RFLayouts
for ( sElementId in mRFLayouts) {
var bFound = false;
for ( i = 0; i < iLength; i++) {
oElement = aElements[i];
if (sElementId == oElement.getId() && oElement.getVisible()) {
bFound = true;
break;
}
}
if (!bFound) {
if (mRFLayouts[sElementId][1]) {
// ResponsiveFlowLayout for fields not longer needed
oFieldsRFLayout = mRFLayouts[sElementId][1];
_deleteResponsiveFlowLayout(oFieldsRFLayout);
}
oRFLayout = mRFLayouts[sElementId][0];
oContainerLayout.removeContent(oRFLayout);
_deleteResponsiveFlowLayout(oRFLayout);
delete mRFLayouts[sElementId];
}
}
}
return mRFLayouts;
}
function _createResponsiveFlowLayout( oLayout, oContainer, oElement, bElementContent ) {
var sId;
if (oElement && !bElementContent) {
sId = oElement.getId() + "--RFLayout";
} else if (oElement && bElementContent) {
sId = oElement.getId() + "--content--RFLayout";
} else if (oContainer) {
sId = oContainer.getId() + "--RFLayout";
} else {
return false;
}
var oRFLayout = new ResponsiveFlowLayout(sId);
oRFLayout.__myParentLayout = oLayout;
oRFLayout.__myParentContainerId = oContainer.getId();
if (oElement) {
oRFLayout.__myParentElementId = oElement.getId();
// assign Elements content -> overwrite getContent function of responsiveFlowLayout
// to not change parent assignment of controls
if (!bElementContent) {
oRFLayout.getContent = function(){
var oElement = sap.ui.getCore().byId(this.__myParentElementId);
if (oElement) {
var aContent = [];
var oLabel = oElement.getLabelControl();
var aFields = oElement.getFields();
if (!oLabel || aFields.length <= 1) {
aContent = aFields;
if (oLabel) {
aContent.unshift(oLabel);
}
} else {
// more than one field -> put in the content RFLayout
var oLayout = this.__myParentLayout;
var sContainerId = this.__myParentContainerId;
var sElementId = oElement.getId();
if (oLabel) {
aContent.push(oLabel);
}
if (oLayout.mContainers[sContainerId] && oLayout.mContainers[sContainerId][2] &&
oLayout.mContainers[sContainerId][2][sElementId] &&
oLayout.mContainers[sContainerId][2][sElementId][1]) {
aContent.push(oLayout.mContainers[sContainerId][2][sElementId][1]);
}
}
return aContent;
} else {
return false;
}
};
oRFLayout._addContentClass = function(oControl, iIndex) {
if (iIndex == 0) {
// check if it's the label of the FormElement
var oElement = sap.ui.getCore().byId(this.__myParentElementId);
if (oElement) {
var oLabel = oElement.getLabelControl();
if (oControl == oLabel) {
return "sapUiFormElementLbl";
}
}
}
return null;
};
} else {
oRFLayout.getContent = function(){
var oElement = sap.ui.getCore().byId(this.__myParentElementId);
if (oElement) {
return oElement.getFields();
} else {
return false;
}
};
}
}else if (oContainer) {
oRFLayout._getAccessibleRole = function() {
var oContainer = sap.ui.getCore().byId(this.__myParentContainerId);
if (!oContainer.getTitle() && !oContainer.getExpandable()) {
return "form";
}
};
}
if ((oElement && !bElementContent) || (!oElement && !oContainer.getTitle() && !oContainer.getExpandable())) {
// use LayoutData of container only if no panel is used
_changeGetLayoutDataOfResponsiveFlowLayout(oRFLayout, false);
} else {
// create LayoutData to disable margins
oRFLayout.setLayoutData(new ResponsiveFlowLayoutData({margin: false}));
}
return oRFLayout;
}
function _changeGetLayoutDataOfResponsiveFlowLayout( oRFLayout, bOriginal ) {
// only ResponsiveFlowLayoutData are from interest
// if none maintained use default one to disable margins
if (bOriginal) {
if (oRFLayout.__originalGetLayoutData) {
oRFLayout.getLayoutData = oRFLayout.__originalGetLayoutData;
delete oRFLayout.__originalGetLayoutData;
}
} else if (!oRFLayout.__originalGetLayoutData) {
oRFLayout.__originalGetLayoutData = oRFLayout.getLayoutData;
oRFLayout.getLayoutData = function(){
var oLayout = this.__myParentLayout;
var oContainer = sap.ui.getCore().byId(this.__myParentContainerId);
var oElement = sap.ui.getCore().byId(this.__myParentElementId);
var oLD;
if (oElement) {
oLD = oLayout.getLayoutDataForElement(oElement, "sap.ui.layout.ResponsiveFlowLayoutData");
} else if (oContainer) {
oLD = oLayout.getLayoutDataForElement(oContainer, "sap.ui.layout.ResponsiveFlowLayoutData");
}
if (oLD) {
return oLD;
} else {
return oLayout._defaultLayoutData;
}
};
}
}
/*
* If a ResponsiveFlowLayout for the fields of an FormElement is used it must get the weight
* of all fields to have the right weight relative to the label.
*/
function _updateLayoutDataOfContentResponsiveFlowLayout( oLayout, oRFLayout, aFields ) {
var oLD;
var iWeight = 0;
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
oLD = oLayout.getLayoutDataForElement(oField, "sap.ui.layout.ResponsiveFlowLayoutData");
if (oLD) {
iWeight = iWeight + oLD.getWeight();
} else {
iWeight++;
}
}
oLD = oRFLayout.getLayoutData();
if (oLD) {
oLD.setWeight(iWeight);
} else {
oRFLayout.setLayoutData(
new ResponsiveFlowLayoutData({weight: iWeight})
);
}
}
/*
* clear variables before delete it
*/
function _deleteResponsiveFlowLayout( oRFLayout ) {
if (oRFLayout.__myParentContainerId) {
oRFLayout.__myParentContainerId = undefined;
}
if (oRFLayout.__myParentElementId) {
oRFLayout.__myParentElementId = undefined;
}
oRFLayout.__myParentLayout = undefined;
oRFLayout.destroy();
}
function _cleanContainer( oLayout, sContainerId ) {
var aContainerContent = oLayout.mContainers[sContainerId];
var oRFLayout;
//delete Elements Content
var oElementRFLayouts = aContainerContent[2];
if (oElementRFLayouts) {
for ( var sElementId in oElementRFLayouts) {
if (oElementRFLayouts[sElementId][1]) {
// ResponsiveFlowLayout for fields not longer needed
_deleteResponsiveFlowLayout(oElementRFLayouts[sElementId][1]);
}
oRFLayout = oElementRFLayouts[sElementId][0];
_deleteResponsiveFlowLayout(oRFLayout);
delete oElementRFLayouts[sElementId];
}
}
//delete ResponsiveFlowLayout
oRFLayout = aContainerContent[1];
if (oRFLayout) {
oRFLayout.removeAllContent();
_deleteResponsiveFlowLayout(oRFLayout);
}
//delete panel
var oPanel = aContainerContent[0];
if (oPanel) {
_deletePanel(oPanel);
}
delete oLayout.mContainers[sContainerId];
}
function _checkElementMoved(oLayout, oContainer, oElement, mRFLayouts, oContainerLayout, iIndex){
// if a Element is just moved from one Container to an other this is not recognized
// so the ResponsiveFlowLayouts must be updated and the control object must be adjusted
var sElementId = oElement.getId();
var sId = sElementId + "--RFLayout";
var oRFLayout = sap.ui.getCore().byId(sId);
if (!mRFLayouts[sElementId] && oRFLayout) {
// Element not maintained in control object of container but already has a RFLayout
// find old container id
var sOldContainerId = oRFLayout.__myParentContainerId;
// move to new containers control object
mRFLayouts[sElementId] = oLayout.mContainers[sOldContainerId][2][sElementId];
oContainerLayout.insertContent(oRFLayout, iIndex);
oRFLayout.__myParentContainerId = oContainer.getId();
if (mRFLayouts[sElementId][1]) {
mRFLayouts[sElementId][1].__myParentContainerId = oContainer.getId();
}
// delete from old container in control object
delete oLayout.mContainers[sOldContainerId][2][sElementId];
}
}
function _createMainResponsiveFlowLayout( oLayout, oForm ) {
var aContainers = oForm.getFormContainers();
var aVisibleContainers = [];
var oContainer;
var iLength = 0;
var iContentLenght = 0;
var i = 0;
var j = 0;
// count only visible containers
for ( i = 0; i < aContainers.length; i++) {
oContainer = aContainers[i];
if (oContainer.getVisible()) {
iLength++;
aVisibleContainers.push(oContainer);
}
}
// special case: only one container -> do not render an outer ResponsiveFlowLayout
if (iLength > 1) {
if (!oLayout._mainRFLayout) {
oLayout._mainRFLayout = new ResponsiveFlowLayout(oForm.getId() + "--RFLayout").setParent(oLayout);
} else {
// update containers
var aLayoutContent = oLayout._mainRFLayout.getContent();
iContentLenght = aLayoutContent.length;
var bExchangeContent = false;
// check if content has changed
for ( i = 0; i < iContentLenght; i++) {
var oContentElement = aLayoutContent[i];
oContainer = undefined;
if (oContentElement.getContainer) {
// it's a panel
oContainer = sap.ui.getCore().byId(oContentElement.getContainer());
} else {
// it's a RFLayout
oContainer = sap.ui.getCore().byId(oContentElement.__myParentContainerId);
}
if (oContainer && oContainer.getVisible()) {
var oVisibleContainer = aVisibleContainers[j];
if (oContainer != oVisibleContainer) {
// order of containers has changed
bExchangeContent = true;
break;
}
var aContainerContent = oLayout.mContainers[oContainer.getId()];
if (aContainerContent[0] && aContainerContent[0] != oContentElement) {
// container uses panel but panel not the same element in content
bExchangeContent = true;
break;
}
if (!aContainerContent[0] && aContainerContent[1] && aContainerContent[1] != oContentElement) {
// container uses no panel but RFLayout not the same element in content
bExchangeContent = true;
break;
}
j++;
} else {
// no container exits for content -> just remove this content
oLayout._mainRFLayout.removeContent(oContentElement);
}
}
if (bExchangeContent) {
// remove all content and add it new.
oLayout._mainRFLayout.removeAllContent();
iContentLenght = 0;
}
}
if (iContentLenght < iLength) {
// new containers added
var iStartIndex = 0;
if (iContentLenght > 0) {
iStartIndex = iContentLenght--;
}
for ( i = iStartIndex; i < iLength; i++) {
oContainer = aVisibleContainers[i];
var sContainerId = oContainer.getId();
if (oLayout.mContainers[sContainerId]) {
if (oLayout.mContainers[sContainerId][0]) {
// panel used
oLayout._mainRFLayout.addContent(oLayout.mContainers[sContainerId][0]);
} else if (oLayout.mContainers[sContainerId][1]) {
// no panel - used ResponsiveFlowLayot directly
oLayout._mainRFLayout.addContent(oLayout.mContainers[sContainerId][1]);
}
}
}
}
}
}
function _objectLength(oObject){
var iLength = 0;
if (!Object.keys) {
jQuery.each(oObject, function(){
iLength++;
});
} else {
iLength = Object.keys(oObject).length;
}
return iLength;
}
}());
return ResponsiveLayout;
}, /* bExport= */ true);
}; // end of sap/ui/layout/form/ResponsiveLayout.js
|
import React, { Component, PropTypes} from 'react';
import DevTools from './DevTools';
var Link = require('react-router').Link;
export default class App extends Component {
static propTypes = {
children: PropTypes.element.isRequired
};
render() {
return (
<div>
<div className="header">
<ul className="horizontal">
<li><Link to="/"><i className="fa fa-fw fa-edit mode"></i></Link></li>
<li><Link to="/wechat"><i className="fa fa-fw fa-wechat mode"></i></Link></li>
<li><Link to="/markdown"><i className="fa fa-fw fa-medium mode"></i></Link></li>
<li><Link to="/setting"><i className="fa fa-fw fa-gears mode"></i></Link></li>
</ul>
</div>
{this.props.children}
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.