_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q54000
|
train
|
function() {
var obj;
// not that the modal viewer is no longer active
DataSaver.updateValue('modalActive', 'false');
modalViewer.active = false;
//Add active class to modal
$('#sg-modal-container').removeClass('active');
// remove the active class from all of the checkbox items
$('.sg-checkbox').removeClass('active');
// hide the modal
modalViewer.hide();
// update the wording
$('#sg-t-patterninfo').html("Show Pattern Info");
// tell the styleguide to close
obj = JSON.stringify({ 'event': 'patternLab.patternModalClose' });
document.getElementById('sg-viewport').contentWindow.postMessage(obj, modalViewer.targetOrigin);
}
|
javascript
|
{
"resource": ""
}
|
|
q54001
|
train
|
function(patternData, iframePassback, switchText) {
// if this is a styleguide view close the modal
if (iframePassback) {
modalViewer.hide();
}
// gather the data that will fill the modal window
panelsViewer.gatherPanels(patternData, iframePassback, switchText);
}
|
javascript
|
{
"resource": ""
}
|
|
q54002
|
train
|
function(pos) {
// remove active class
els = document.querySelectorAll('#sg-annotations > .sg-annotations-list > li');
for (i = 0; i < els.length; ++i) {
els[i].classList.remove('active');
}
// add active class to called element and scroll to it
for (i = 0; i < els.length; ++i) {
if ((i+1) == pos) {
els[i].classList.add('active');
$('.sg-pattern-extra-info').animate({scrollTop: els[i].offsetTop - 10}, 600);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54003
|
train
|
function(switchText) {
// note that the modal is active and set switchText
if ((switchText === undefined) || (switchText)) {
switchText = true;
DataSaver.updateValue('modalActive', 'true');
modalViewer.active = true;
}
// send a message to the pattern
var obj = JSON.stringify({ 'event': 'patternLab.patternQuery', 'switchText': switchText });
document.getElementById('sg-viewport').contentWindow.postMessage(obj, modalViewer.targetOrigin);
}
|
javascript
|
{
"resource": ""
}
|
|
q54004
|
train
|
function(templateRendered, patternPartial) {
var els = templateRendered.querySelectorAll('#sg-'+patternPartial+'-tabs li');
for (var i = 0; i < els.length; ++i) {
els[i].onclick = function(e) {
e.preventDefault();
var patternPartial = this.getAttribute('data-patternpartial');
var panelID = this.getAttribute('data-panelid');
panelsUtil.show(patternPartial, panelID);
};
}
return templateRendered;
}
|
javascript
|
{
"resource": ""
}
|
|
q54005
|
train
|
function(panels, patternData, iframePassback, switchText) {
// count how many panels have rendered content
var panelContentCount = 0;
for (var i = 0; i < panels.length; ++i) {
if (panels[i].content !== undefined) {
panelContentCount++;
}
}
// see if the count of panels with content matches number of panels
if (panelContentCount === Panels.count()) {
panelsViewer.renderPanels(panels, patternData, iframePassback, switchText);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54006
|
sizeiframe
|
train
|
function sizeiframe(size,animate) {
var theSize;
if(size>maxViewportWidth) { //If the entered size is larger than the max allowed viewport size, cap value at max vp size
theSize = maxViewportWidth;
} else if(size<minViewportWidth) { //If the entered size is less than the minimum allowed viewport size, cap value at min vp size
theSize = minViewportWidth;
} else {
theSize = size;
}
//Conditionally remove CSS animation class from viewport
if(animate===false) {
$('#sg-gen-container,#sg-viewport').removeClass("vp-animate"); //If aninate is set to false, remove animate class from viewport
} else {
$('#sg-gen-container,#sg-viewport').addClass("vp-animate");
}
$('#sg-gen-container').width(theSize+viewportResizeHandleWidth); //Resize viewport wrapper to desired size + size of drag resize handler
$sgViewport.width(theSize); //Resize viewport to desired size
var targetOrigin = (window.location.protocol === "file:") ? "*" : window.location.protocol+"//"+window.location.host;
var obj = JSON.stringify({ "event": "patternLab.resize", "resize": "true" });
document.getElementById('sg-viewport').contentWindow.postMessage(obj,targetOrigin);
updateSizeReading(theSize); //Update values in toolbar
saveSize(theSize); //Save current viewport to cookie
}
|
javascript
|
{
"resource": ""
}
|
q54007
|
reservoirStream
|
train
|
function reservoirStream(collection, size, opts) {
opts = _defaults(opts || {}, {
chunkSize: RESERVOIR_CHUNK_SIZE,
promoteValues: true
});
var reservoir = new Reservoir(size);
var stream = es.through(
function write(data) {
// fill reservoir with ids
reservoir.pushSome(data);
},
function end() {
// split the reservoir of ids into smaller chunks
var chunks = _chunk(reservoir, opts.chunkSize);
// create cursors for chunks
var cursors = chunks.map(function(ids) {
var cursor = collection.find({ _id: { $in: ids }}, { promoteValues: opts.promoteValues, raw: opts.raw });
if (opts.fields) {
cursor.project(opts.fields);
}
if (opts.maxTimeMS) {
cursor.maxTimeMS(opts.maxTimeMS);
}
return cursor.stream();
});
// merge all cursors (order arbitrary) and emit docs
es.merge(cursors).pipe(es.through(function(doc) {
stream.emit('data', doc);
})).on('end', function() {
stream.emit('end');
});
}
);
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q54008
|
transform
|
train
|
function transform(chunk, encoding, cb) {
// only transform for raw bytes
if (raw) {
var response = BSON.deserialize(chunk);
response.cursor.firstBatch.forEach(function(doc) {
this.push(BSON.serialize(doc));
}.bind(this));
return cb();
}
// otherwise go back to the main stream
return cb(null, chunk);
}
|
javascript
|
{
"resource": ""
}
|
q54009
|
gulpWPpot
|
train
|
function gulpWPpot (options) {
if (options !== undefined && !isObject(options)) {
throw new PluginError('gulp-wp-pot', 'Require a argument of type object.');
}
const files = [];
const stream = through.obj(function (file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError('gulp-wp-pot', 'Streams are not supported.'));
}
files.push(file.path);
cb();
}, function (cb) {
if (!options) {
options = {};
}
options.src = files;
options.writeFile = false;
try {
const potContents = wpPot(options);
const potFile = new Vinyl({
contents: Buffer.from(potContents),
path: '.'
});
this.push(potFile);
this.emit('end');
cb();
} catch (error) {
this.emit('error', new PluginError('gulp-wp-pot', error));
}
});
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q54010
|
replaceEndian
|
train
|
function replaceEndian (options, matchedPart, first, separator, second, third) {
var parts
var hasSingleDigit = Math.min(first.length, second.length, third.length) === 1
var hasQuadDigit = Math.max(first.length, second.length, third.length) === 4
var preferredOrder = typeof options.preferredOrder === 'string' ? options.preferredOrder : options.preferredOrder[separator]
first = parseInt(first, 10)
second = parseInt(second, 10)
third = parseInt(third, 10)
parts = [first, second, third]
preferredOrder = preferredOrder.toUpperCase()
// If first is a year, order will always be Year-Month-Day
if (first > 31) {
parts[0] = hasQuadDigit ? 'YYYY' : 'YY'
parts[1] = hasSingleDigit ? 'M' : 'MM'
parts[2] = hasSingleDigit ? 'D' : 'DD'
return parts.join(separator)
}
// Second will never be the year. And if it is a day,
// the order will always be Month-Day-Year
if (second > 12) {
parts[0] = hasSingleDigit ? 'M' : 'MM'
parts[1] = hasSingleDigit ? 'D' : 'DD'
parts[2] = hasQuadDigit ? 'YYYY' : 'YY'
return parts.join(separator)
}
// if third is a year ...
if (third > 31) {
parts[2] = hasQuadDigit ? 'YYYY' : 'YY'
// ... try to find day in first and second.
// If found, the remaining part is the month.
if (preferredOrder[0] === 'M' && first < 13) {
parts[0] = hasSingleDigit ? 'M' : 'MM'
parts[1] = hasSingleDigit ? 'D' : 'DD'
return parts.join(separator)
}
parts[0] = hasSingleDigit ? 'D' : 'DD'
parts[1] = hasSingleDigit ? 'M' : 'MM'
return parts.join(separator)
}
// if we had no luck until here, we use the preferred order
parts[preferredOrder.indexOf('D')] = hasSingleDigit ? 'D' : 'DD'
parts[preferredOrder.indexOf('M')] = hasSingleDigit ? 'M' : 'MM'
parts[preferredOrder.indexOf('Y')] = hasQuadDigit ? 'YYYY' : 'YY'
return parts.join(separator)
}
|
javascript
|
{
"resource": ""
}
|
q54011
|
CircleButton
|
train
|
function CircleButton(props) {
let icon;
if (props.icon) {
const Icon = props.icon;
icon = (
<Icon
className={classnames(styles.icon, props.iconClassName)}
width={props.iconWidth}
height={props.iconHeight}
x={props.iconX}
y={props.iconY}
/>
);
}
const circleClass = classnames(
styles.circle,
!props.showBorder && styles.noBorder,
);
const onClick = props.disabled ? null : props.onClick;
return (
<svg
data-sign={props.dataSign}
xmlns="http://www.w3.org/2000/svg"
className={classnames(styles.btnSvg, props.className)}
viewBox="0 0 500 500"
onClick={(e) => {
if ((e.target && e.target.tagName !== 'svg') && onClick) {
onClick(e);
}
}}
width={props.width}
height={props.height}
x={props.x}
y={props.y}
>
{props.title ? <title>{props.title}</title> : null}
<g
className={styles.btnSvgGroup}
>
<circle
className={circleClass}
cx="250"
cy="250"
r="245"
/>
{icon}
{
props.showRipple
? <circle
className={styles.ripple}
cx="250"
cy="250"
r="245"
/>
: null
}
</g>
</svg>
);
}
|
javascript
|
{
"resource": ""
}
|
q54012
|
RecentActivityPanel
|
train
|
function RecentActivityPanel(props) {
const { title, expanded, onPanelToggle } = props;
const toggleButton = {
label: <ToggleIcon expanded={expanded} />,
onClick: onPanelToggle,
placement: 'right'
};
if (!props.currentContact) {
return null;
}
const containerClass = classnames(styles.container, props.className);
return (
<div className={containerClass}>
<div className={styles.header} onClick={onPanelToggle}>
<Header buttons={[toggleButton]} className={styles.header}>{title}</Header>
</div>
<RecentActivityView {...props} />
</div>
);
}
|
javascript
|
{
"resource": ""
}
|
q54013
|
hasProperty
|
train
|
function hasProperty(obj, propName) {
return obj != null && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && propName in obj;
}
|
javascript
|
{
"resource": ""
}
|
q54014
|
train
|
function (options) {
// Initialize the Faye client if it hasn't been initialized
if (_.isUndefined(this._fayeClient)) {
var pushUrl = new URI(this.apiURL).subdomain('push').path('faye').toString();
this._fayeClient = new Faye.Client(pushUrl);
// We don't support websockets
this._fayeClient.disable('websocket');
// Add extensions to Faye client
this._fayeClient.addExtension({
'outgoing': function(message, callback) {
message.ext = message.ext || {};
message.ext = {
private_pub_signature: options.signature,
private_pub_timestamp: options.timestamp
};
callback(message);
}
});
}
return this._fayeClient;
}
|
javascript
|
{
"resource": ""
}
|
|
q54015
|
oauth2TokenParser
|
train
|
function oauth2TokenParser(options) {
function parseOauth2Token(req, res, next) {
req.oauth2 = { accessToken: null};
var tokenFromHeader = parseHeader(req);
if (tokenFromHeader) {
req.oauth2.accessToken = tokenFromHeader;
}
var tokenFromBody = null;
if (typeof req.body === 'object') {
tokenFromBody = req.body.access_token;
}
// more than one method to transmit the token in each request
// is not allowed - return 400
if (tokenFromBody && tokenFromHeader) {
return next(new errors.makeErrFromCode(400,
'multiple tokens disallowed'));
}
if (tokenFromBody && req.contentType().toLowerCase()
=== 'application/x-www-form-urlencoded') {
req.oauth2.accessToken = tokenFromBody;
}
return (next());
}
return (parseOauth2Token);
}
|
javascript
|
{
"resource": ""
}
|
q54016
|
acceptParser
|
train
|
function acceptParser(accepts) {
var acceptable = accepts;
if (!Array.isArray(acceptable)) {
acceptable = [acceptable];
}
assert.arrayOfString(acceptable, 'acceptable');
acceptable = acceptable.filter(function (a) {
return (a);
}).map(function (a) {
return ((a.indexOf('/') === -1) ? mime.lookup(a) : a);
}).filter(function (a) {
return (a);
});
var e = new NotAcceptableError('Server accepts: ' + acceptable.join());
function parseAccept(req, res, next) {
if (req.accepts(acceptable)) {
next();
return;
}
res.json(e);
next(false);
}
return (parseAccept);
}
|
javascript
|
{
"resource": ""
}
|
q54017
|
authorizationParser
|
train
|
function authorizationParser(options) {
function parseAuthorization(req, res, next) {
req.authorization = {};
req.username = 'anonymous';
if (!req.headers.authorization) {
return (next());
}
var pieces = req.headers.authorization.split(' ', 2);
if (!pieces || pieces.length !== 2) {
var e = new InvalidHeaderError('BasicAuth content ' +
'is invalid.');
return (next(e));
}
req.authorization.scheme = pieces[0];
req.authorization.credentials = pieces[1];
try {
switch (pieces[0].toLowerCase()) {
case 'basic':
req.authorization.basic = parseBasic(pieces[1]);
req.username = req.authorization.basic.username;
break;
case 'signature':
req.authorization.signature =
parseSignature(req, options);
req.username =
req.authorization.signature.keyId;
break;
default:
break;
}
} catch (e2) {
return (next(e2));
}
return (next());
}
return (parseAuthorization);
}
|
javascript
|
{
"resource": ""
}
|
q54018
|
createReqIdHeaders
|
train
|
function createReqIdHeaders(opts) {
assert.object(opts, 'opts');
assert.arrayOfString(opts.headers, 'opts.headers');
var headers = opts.headers.concat(DEFAULT_HEADERS);
return function reqIdHeaders(req, res, next) {
for (var i = 0; i < headers.length; i++) {
var val = req.header(headers[i]);
if (val) {
req.id(val);
break;
}
}
return next();
};
}
|
javascript
|
{
"resource": ""
}
|
q54019
|
queryParser
|
train
|
function queryParser(options) {
var opts = options || {};
assert.object(opts, 'opts');
function parseQueryString(req, res, next) {
if (!req.getQuery()) {
req.query = {};
return next();
}
req.query = qs.parse(req.getQuery(), opts);
if (opts.mapParams === true) {
Object.keys(req.query).forEach(function (k) {
if (req.params[k] && !opts.overrideParams) {
return;
}
req.params[k] = req.query[k];
});
}
return next();
}
return parseQueryString;
}
|
javascript
|
{
"resource": ""
}
|
q54020
|
rangeParser
|
train
|
function rangeParser (size, str, options) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string')
}
var index = str.indexOf('=')
if (index === -1) {
return -2
}
// split the range string
var arr = str.slice(index + 1).split(',')
var ranges = []
// add ranges type
ranges.type = str.slice(0, index)
// parse all ranges
for (var i = 0; i < arr.length; i++) {
var range = arr[i].split('-')
var start = parseInt(range[0], 10)
var end = parseInt(range[1], 10)
// -nnn
if (isNaN(start)) {
start = size - end
end = size - 1
// nnn-
} else if (isNaN(end)) {
end = size - 1
}
// limit last-byte-pos to current length
if (end > size - 1) {
end = size - 1
}
// invalid or unsatisifiable
if (isNaN(start) || isNaN(end) || start > end || start < 0) {
continue
}
// add range
ranges.push({
start: start,
end: end
})
}
if (ranges.length < 1) {
// unsatisifiable
return -1
}
return options && options.combine
? combineRanges(ranges)
: ranges
}
|
javascript
|
{
"resource": ""
}
|
q54021
|
combineRanges
|
train
|
function combineRanges (ranges) {
var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart)
for (var j = 0, i = 1; i < ordered.length; i++) {
var range = ordered[i]
var current = ordered[j]
if (range.start > current.end + 1) {
// next range
ordered[++j] = range
} else if (range.end > current.end) {
// extend range
current.end = range.end
current.index = Math.min(current.index, range.index)
}
}
// trim ordered array
ordered.length = j + 1
// generate combined range
var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex)
// copy ranges type
combined.type = ranges.type
return combined
}
|
javascript
|
{
"resource": ""
}
|
q54022
|
mapWithIndex
|
train
|
function mapWithIndex (range, index) {
return {
start: range.start,
end: range.end,
index: index
}
}
|
javascript
|
{
"resource": ""
}
|
q54023
|
sourceList
|
train
|
function sourceList(manifest) {
const sourceTypes = [
["desktop", "js"],
["desktop", "css"],
["mobile", "js"],
["config", "js"],
["config", "css"]
];
const list = sourceTypes
.map(t => manifest[t[0]] && manifest[t[0]][t[1]])
.filter(i => !!i)
.reduce((a, b) => a.concat(b), [])
.filter(file => !/^https?:\/\//.test(file));
if (manifest.config && manifest.config.html) {
list.push(manifest.config.html);
}
list.push("manifest.json", manifest.icon);
// Make the file list unique
return [...new Set(list)];
}
|
javascript
|
{
"resource": ""
}
|
q54024
|
createContentsZip
|
train
|
function createContentsZip(pluginDir, manifest) {
return new Promise((res, rej) => {
const output = new streamBuffers.WritableStreamBuffer();
const zipFile = new ZipFile();
let size = null;
output.on("finish", () => {
debug(`plugin.zip: ${size} bytes`);
res(output.getContents());
});
zipFile.outputStream.pipe(output);
sourceList(manifest).forEach(src => {
zipFile.addFile(path.join(pluginDir, src), src);
});
zipFile.end(finalSize => {
size = finalSize;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54025
|
fileMapToBuffer
|
train
|
function fileMapToBuffer(fileMap) {
return Promise.all(
Array.from(fileMap.entries()).map(([path, file]) =>
readArrayBuffer(file).then(buffer => ({ buffer, path }))
)
)
.then(results => {
const zipFile = new yazl.ZipFile();
results.forEach(result => {
zipFile.addBuffer(Buffer.from(result.buffer), result.path);
});
zipFile.end();
return zipFile;
})
.then(
zipFile =>
new Promise(resolve => {
const output = new streamBuffers.WritableStreamBuffer();
output.on("finish", () => {
resolve(output.getContents());
});
zipFile.outputStream.pipe(output);
})
);
}
|
javascript
|
{
"resource": ""
}
|
q54026
|
zip
|
train
|
function zip(contentsZip, publicKey, signature) {
debug(`zip(): start`);
return new Promise((res, rej) => {
const output = new streamBuffers.WritableStreamBuffer();
const zipFile = new ZipFile();
output.on("finish", () => {
debug(`zip(): output finish event`);
res(output.getContents());
});
zipFile.outputStream.pipe(output);
zipFile.addBuffer(contentsZip, "contents.zip");
zipFile.addBuffer(publicKey, "PUBKEY");
zipFile.addBuffer(signature, "SIGNATURE");
zipFile.end(finalSize => {
debug(`zip(): ZipFile end event: finalSize ${finalSize} bytes`);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54027
|
rezip
|
train
|
function rezip(contentsZip) {
return preprocessToRezip(contentsZip).then(
({ zipFile, entries, manifestJson, manifestPath }) => {
validateManifest(entries, manifestJson, manifestPath);
return rezipContents(zipFile, entries, manifestJson, manifestPath);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q54028
|
validateContentsZip
|
train
|
function validateContentsZip(contentsZip) {
return preprocessToRezip(contentsZip).then(
({ entries, manifestJson, manifestPath }) =>
validateManifest(entries, manifestJson, manifestPath)
);
}
|
javascript
|
{
"resource": ""
}
|
q54029
|
preprocessToRezip
|
train
|
function preprocessToRezip(contentsZip) {
return zipEntriesFromBuffer(contentsZip).then(result => {
const manifestList = Array.from(result.entries.keys()).filter(
file => path.basename(file) === "manifest.json"
);
if (manifestList.length === 0) {
throw new Error("The zip file has no manifest.json");
} else if (manifestList.length > 1) {
throw new Error("The zip file has many manifest.json files");
}
result.manifestPath = manifestList[0];
const manifestEntry = result.entries.get(result.manifestPath);
return getManifestJsonFromEntry(result.zipFile, manifestEntry).then(json =>
Object.assign(result, { manifestJson: json })
);
});
}
|
javascript
|
{
"resource": ""
}
|
q54030
|
validateRelativePath
|
train
|
function validateRelativePath(pluginDir) {
return str => {
try {
const stat = fs.statSync(path.join(pluginDir, str));
return stat.isFile();
} catch (e) {
return false;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q54031
|
validateMaxFileSize
|
train
|
function validateMaxFileSize(pluginDir) {
return (maxBytes, filePath) => {
try {
const stat = fs.statSync(path.join(pluginDir, filePath));
return stat.size <= maxBytes;
} catch (e) {
return false;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q54032
|
hex2a
|
train
|
function hex2a(hex) {
return Array.from(hex)
.map(s => {
if (s >= "0" && s <= "9") {
return String.fromCharCode(s.charCodeAt(0) + N_TO_A);
} else if (s >= "a" && s <= "f") {
return String.fromCharCode(s.charCodeAt(0) + A_TO_K);
}
throw new Error(`invalid char: ${s}`);
})
.join("");
}
|
javascript
|
{
"resource": ""
}
|
q54033
|
index
|
train
|
function index(options) {
return {
kronos: {
position: 'relative',
display: 'flex',
color: 'hsl(0, 0%, 50%)',
'& *': {
fontFamily: options.font,
boxSizing: 'border-box',
userSelect: 'none',
},
},
input: {
border: '1px solid transparent',
borderRadius: options.corners,
borderColor: color(options.color)
.alpha(0.2)
.rgbString(),
fontSize: 16,
padding: '3px 6px',
background: 'white',
'&.outside-range': {
color: 'white',
background: '#d0021b',
},
'&:hover': {
cursor: options.inputDisabled ? 'not-allowed' : 'default',
},
'&:focus': {
outline: 'none',
borderColor: color(options.color)
.alpha(0.5)
.rgbString(),
},
},
}
}
|
javascript
|
{
"resource": ""
}
|
q54034
|
train
|
function(name, source){
var oldSource = this.sources[name];
if (name in this.fields.sources == false)
{
/** @cut */ basis.dev.warn('basis.data.object.Merge#setSource: can\'t set source with name `' + name + '` as not specified by fields configuration');
return;
}
// ignore set source for self fields
if (name == '-')
return;
// create context for name if not exists yet
if (name in this.sourcesContext_ == false)
this.sourcesContext_[name] = {
host: this,
name: name,
adapter: null
};
// resolve object from value
source = resolveObject(this.sourcesContext_[name], resolveSetSource, source, 'adapter', this);
// main part
if (oldSource !== source)
{
var listenHandler = this.listen['source:' + name];
// remove handler from old source if present
if (oldSource)
{
if (listenHandler)
oldSource.removeHandler(listenHandler, this);
oldSource.removeHandler(MERGE_SOURCE_HANDLER, this.sourcesContext_[name]);
}
// set new source value
this.sources[name] = source;
// add handler to new source
if (source)
{
source.addHandler(MERGE_SOURCE_HANDLER, this.sourcesContext_[name]);
if (listenHandler)
source.addHandler(listenHandler, this);
// apply new source data
var newData = this.fields.sources[name](source.data);
// reset properties missed in new source if source is defaultSource
if (this.fields.defaultSource == name)
for (var key in this.data)
if (!this.fields.fieldSource.hasOwnProperty(key) && !newData.hasOwnProperty(key))
newData[key] = undefined;
this.update(newData);
}
this.emit_sourceChanged(name, oldSource);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54035
|
compatibleStyleSheetInsertRule
|
train
|
function compatibleStyleSheetInsertRule(rule, index){
// fetch selector and style from rule description
var m = rule.match(/^([^{]+)\{(.*)\}\s*$/);
if (m)
{
var selectors = m[1].trim().split(/\s*,\s*/);
for (var i = 0; i < selectors.length; i++)
this.addRule(selectors[i], m[2] || null, index++);
return index - 1;
}
/** @cut */ throw new Error('Syntax error in CSS rule to be added');
}
|
javascript
|
{
"resource": ""
}
|
q54036
|
getStyleSheet
|
train
|
function getStyleSheet(id, createIfNotExists){
if (!id)
id = 'DefaultGenericStyleSheet';
if (!cssStyleSheets[id])
if (createIfNotExists)
cssStyleSheets[id] = new StyleSheet(addStyleSheet());
return cssStyleSheets[id];
}
|
javascript
|
{
"resource": ""
}
|
q54037
|
setStyleProperty
|
train
|
function setStyleProperty(node, property, value){
var mapping = styleMapping[property];
var key = mapping ? mapping.key : camelize(property.replace(/^-ms-/, 'ms-'));
if (!key)
return;
if (mapping && mapping.getter)
value = mapping.getter(value);
var imp = !!IMPORTANT_REGEXP.test(value);
var style = node.style;
if (imp || isPropertyImportant(style, property))
{
value = value.replace(IMPORTANT_REGEXP, '');
if (style.setProperty)
{
// W3C scheme
// if property exists and important, remove it
if (!imp)
// Can't use removeProperty() because it wont remove !important rules in Chrome.
style.setProperty(property, '');
// set new value for property
style.setProperty(property, value, (imp ? IMPORTANT : ''));
}
else
{
// IE8- scheme
var newValue = key + ': ' + value + (imp ? ' !' + IMPORTANT : '') + ';';
var rxText = style[key] ? property + '\\s*:\\s*' + style[key] + '(\\s*!' + IMPORTANT + ')?\\s*;?' : '^';
try {
style.cssText = style.cssText.replace(new RegExp(rxText, 'i'), newValue);
} catch(e) {
/** @cut */ basis.dev.warn('basis.cssom.setStyleProperty: Can\'t set wrong value `' + value + '` for ' + key + ' property');
}
}
}
else
{
if (SET_STYLE_EXCEPTION_BUG)
{
// IE6-8 throw exception when assign wrong value to style, but standart
// says just ignore this assignments
// try/catch is speedless, therefore wrap this statement only for ie
// it makes code safe and more compatible
try {
node.style[key] = value;
} catch(e) {
/** @cut */ basis.dev.warn('basis.cssom.setStyleProperty: Can\'t set wrong value `' + value + '` for ' + key + ' property');
}
}
else
node.style[key] = value;
return node.style[key];
}
}
|
javascript
|
{
"resource": ""
}
|
q54038
|
setStyle
|
train
|
function setStyle(node, style){
for (var key in style)
setStyleProperty(node, key, style[key]);
return node;
}
|
javascript
|
{
"resource": ""
}
|
q54039
|
train
|
function(){
var headerElement = this.header.element;
var footerElement = this.footer ? this.footer.element : null;
//
// Sync header html
//
var headerOuterHTML = domUtils.outerHTML(headerElement);
if (this.shadowHeaderHTML_ != headerOuterHTML)
{
this.shadowHeaderHTML_ = headerOuterHTML;
replaceTemplateNode(this, 'shadowHeader', headerElement.cloneNode(true));
}
//
// Sync footer html
//
if (footerElement)
{
var footerOuterHTML = domUtils.outerHTML(footerElement);
if (this.shadowFooterHtml_ != footerOuterHTML)
{
this.shadowFooterHtml_ = footerOuterHTML;
replaceTemplateNode(this, 'shadowFooter', footerElement.cloneNode(true));
}
}
//
// Sync column width
//
for (var i = 0, column, columnWidth; column = this.columnWidthSync_[i]; i++)
{
columnWidth = column.measure.offsetWidth + 'px';
cssom.setStyleProperty(column.header.firstChild, 'width', columnWidth);
if (footerElement)
cssom.setStyleProperty(column.footer.firstChild, 'width', columnWidth);
}
//
// Calc metrics boxes
//
var tableWidth = this.tmpl.boundElement.offsetWidth || 0;
var headerHeight = headerElement.offsetHeight || 0;
var footerHeight = (footerElement && footerElement.offsetHeight) || 0;
//
// Update style properties
//
this.tmpl.headerExpandCell.style.left = tableWidth + 'px';
this.tmpl.footerExpandCell.style.left = tableWidth + 'px';
this.tmpl.tableElement.style.margin = '-' + headerHeight + 'px 0 -' + footerHeight + 'px';
if (this.fitToContainer)
this.element.style.paddingBottom = (headerHeight + footerHeight) + 'px';
// reset timer
// it should be at the end of relayout to prevent relayout call while relayout
this.timer_ = basis.clearImmediate(this.timer_);
}
|
javascript
|
{
"resource": ""
}
|
|
q54040
|
getLocation
|
train
|
function getLocation(template, loc){
if (loc)
return (template.sourceUrl || '') + ':' + loc.start.line + ':' + (loc.start.column + 1);
}
|
javascript
|
{
"resource": ""
}
|
q54041
|
handleInsert
|
train
|
function handleInsert(node, newNode, refChild){
return newNode != null
? node.insertBefore(isNode(newNode) ? newNode : createText(newNode), refChild || null)
: null;
}
|
javascript
|
{
"resource": ""
}
|
q54042
|
train
|
function(filter, result){
var node;
if (!result)
result = [];
this.reset();
while (node = this.next(filter))
result.push(node);
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q54043
|
train
|
function(filter){
filter = filter || this.filter;
var cursor = this.cursor_ || this.root_;
do
{
var node = cursor[this.a]; // next child
while (!node)
{
if (cursor === this.root_)
return this.cursor_ = null;
node = cursor[this.b]; // next sibling
if (!node)
cursor = cursor[PARENT_NODE];
}
}
while (!filter(cursor = node));
return this.cursor_ = cursor;
}
|
javascript
|
{
"resource": ""
}
|
|
q54044
|
train
|
function(filter){
filter = filter || this.filter;
var cursor = this.cursor_;
var prevSibling = this.c; // previous sibling
var prevChild = this.d; // previous child
do
{
var node = cursor ? cursor[prevSibling] : this.root_[prevChild];
if (node)
{
while (node[prevChild])
node = node[prevChild];
cursor = node;
}
else
if (cursor)
cursor = cursor[PARENT_NODE];
if (!cursor || cursor === this.root_)
{
cursor = null;
break;
}
}
while (!filter(cursor));
return this.cursor_ = cursor;
}
|
javascript
|
{
"resource": ""
}
|
|
q54045
|
tag
|
train
|
function tag(node, tagName){
var element = get(node) || document;
if (tagName == '*' && element.all)
return arrayFrom(element.all);
else
return arrayFrom(element.getElementsByTagName(tagName || '*'));
}
|
javascript
|
{
"resource": ""
}
|
q54046
|
axis
|
train
|
function axis(root, axis, filter){
var result = [];
var walker;
var cursor;
filter = typeof filter == 'string' ? getter(filter) : filter || basis.fn.$true;
if (axis & (AXIS_SELF | AXIS_ANCESTOR_OR_SELF | AXIS_DESCENDANT_OR_SELF))
if (filter(root))
result.push(root);
switch (axis)
{
case AXIS_ANCESTOR:
case AXIS_ANCESTOR_OR_SELF:
cursor = root;
while ((cursor = cursor[PARENT_NODE]) && cursor !== root.document)
if (filter(cursor))
result.push(cursor);
break;
case AXIS_CHILD:
cursor = root[FIRST_CHILD];
while (cursor)
{
if (filter(cursor))
result.push(cursor);
cursor = cursor[NEXT_SIBLING];
}
break;
case AXIS_DESCENDANT:
case AXIS_DESCENDANT_OR_SELF:
if (root[FIRST_CHILD])
{
walker = new TreeWalker(root);
walker.nodes(filter, result);
}
break;
case AXIS_FOLLOWING:
walker = new TreeWalker(root, filter);
walker.cursor_ = root[NEXT_SIBLING] || root[PARENT_NODE];
while (cursor = walker.next())
result.push(cursor);
break;
case AXIS_FOLLOWING_SIBLING:
cursor = root;
while (cursor = cursor[NEXT_SIBLING])
if (filter(cursor))
result.push(cursor);
break;
case AXIS_PARENT:
if (filter(root[PARENT_NODE]))
result.push(root[PARENT_NODE]);
break;
case AXIS_PRECEDING:
walker = new TreeWalker(root, filter, TreeWalker.BACKWARD);
walker.cursor_ = root[PREVIOUS_SIBLING] || root[PARENT_NODE];
while (cursor = walker.next())
result.push(cursor);
break;
case AXIS_PRECEDING_SIBLING:
cursor = root;
while (cursor = cursor[PREVIOUS_SIBLING])
if (filter(cursor))
result.push(cursor);
break;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q54047
|
findAncestor
|
train
|
function findAncestor(node, matchFunction, bound){
while (node && node !== bound)
{
if (matchFunction(node))
break;
node = node.parentNode;
}
return node || null;
}
|
javascript
|
{
"resource": ""
}
|
q54048
|
createFragment
|
train
|
function createFragment(){
var result = document.createDocumentFragment();
var len = arguments.length;
var array = createFragment.array = [];
for (var i = 0; i < len; i++)
array.push(handleInsert(result, arguments[i]));
return result;
}
|
javascript
|
{
"resource": ""
}
|
q54049
|
createElement
|
train
|
function createElement(config){
var isConfig = config != undefined && typeof config != 'string';
var description = (isConfig ? config.description : config) || '';
var elementName = 'div'; // modern browsers become case sensetive for tag names for xhtml
var element;
// fetch tag name
var m = description.match(/^([a-z0-9_\-]+)(.*)$/i);
if (m)
{
elementName = m[1];
description = m[2];
}
// create an element
if (description != '')
{
// extract properties
var classNames = [];
var attributes = {};
var entryName;
while (m = DESCRIPTION_PART_REGEXP.exec(description))
{
if (m[8])
{
throw new Error(
'Create element error in basis.dom.createElement()' +
'\n\nDescription:\n> ' + description +
'\n\nProblem place:\n> ' + description.substr(0, m.index) + '-->' + description.substr(m.index) + '<--'
);
}
entryName = m[1] || m[2] || m[3];
if (m[1]) // id
attributes.id = entryName;
else
if (m[2]) // class
classNames.push(entryName);
else
{ // attribute
if (entryName != 'class')
attributes[entryName] = m[4] ? m[5] || m[6] || m[7] || '' : entryName;
}
}
// create element
if (IS_ATTRIBUTE_BUG_NAME && attributes.name && /^(input|textarea|select)$/i.test(elementName))
elementName = '<' + elementName + ' name=' + attributes.name + '>';
}
// create element
element = document.createElement(elementName);
// set attributes
if (attributes)
{
if (attributes.style && IS_ATTRIBUTE_BUG_STYLE)
element.style.cssText = attributes.style;
for (var attrName in attributes)
element.setAttribute(attrName, attributes[attrName], 0);
}
// set css classes
if (classNames && classNames.length)
element.className = classNames.join(' ');
// append child nodes
if (arguments.length > 1)
handleInsert(element, createFragment.apply(0, basis.array.flatten(arrayFrom(arguments, 1))));
// attach event handlers
if (isConfig)
{
if (config.css)
{
if (!cssom)
cssom = require('basis.cssom');
cssom.setStyle(element, config.css);
}
for (var event in config)
if (typeof config[event] == 'function')
eventUtils.addHandler(element, event, config[event], element);
}
// return an element
return element;
}
|
javascript
|
{
"resource": ""
}
|
q54050
|
insert
|
train
|
function insert(node, source, insertPoint, refChild){
node = get(node) || node; // TODO: remove
switch (insertPoint) {
case undefined: // insertPoint omitted
case INSERT_END:
refChild = null;
break;
case INSERT_BEGIN:
refChild = node[FIRST_CHILD];
break;
case INSERT_BEFORE:
break;
case INSERT_AFTER:
refChild = refChild[NEXT_SIBLING];
break;
default:
insertPoint = Number(insertPoint);
refChild = insertPoint >= 0 && insertPoint < node.childNodes.length ? node.childNodes[insertPoint] : null;
}
var isDOMLikeObject = !isNode(node);
var result;
if (!source || !Array.isArray(source))
result = isDOMLikeObject ? source && node.insertBefore(source, refChild) : handleInsert(node, source, refChild);
else
{
if (isDOMLikeObject)
{
result = [];
for (var i = 0, len = source.length; i < len; i++)
result[i] = node.insertBefore(source[i], refChild);
}
else
{
node.insertBefore(createFragment.apply(0, source), refChild);
result = createFragment.array;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q54051
|
replace
|
train
|
function replace(oldNode, newNode){
return oldNode[PARENT_NODE] ? oldNode[PARENT_NODE].replaceChild(newNode, oldNode) : oldNode;
}
|
javascript
|
{
"resource": ""
}
|
q54052
|
swap
|
train
|
function swap(nodeA, nodeB){
if (nodeA === nodeB || comparePosition(nodeA, nodeB) & (POSITION_CONTAINED_BY | POSITION_CONTAINS | POSITION_DISCONNECTED))
return false;
replace(nodeA, testElement);
replace(nodeB, nodeA);
replace(testElement, nodeB);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54053
|
clone
|
train
|
function clone(node, noChildren){
var result = node.cloneNode(!noChildren);
if (result.attachEvent) // clear event handlers for IE
axis(result, AXIS_DESCENDANT_OR_SELF).forEach(eventUtils.clearHandlers);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q54054
|
clear
|
train
|
function clear(node){
node = get(node);
while (node[LAST_CHILD])
node.removeChild(node[LAST_CHILD]);
return node;
}
|
javascript
|
{
"resource": ""
}
|
q54055
|
focus
|
train
|
function focus(node, select){
// try catch block here because browsers throw unexpected exeption in some cases
try {
node = get(node);
node.focus();
if (select && node.select) // && typeof node.select == 'function'
// temporary removed because IE returns 'object' for DOM object methods, instead of 'function'
node.select();
} catch(e) {}
}
|
javascript
|
{
"resource": ""
}
|
q54056
|
toBytes
|
train
|
function toBytes(input){
var output = [];
var len = input.length;
for (var i = 0; i < len; i++)
{
var c = input.charCodeAt(i);
output.push(c & 0xFF, c >> 8);
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q54057
|
fromBytes
|
train
|
function fromBytes(input){
var output = '';
var len = input.length;
var i = 0;
var b1;
var b2;
while (i < len)
{
b1 = input[i++] || 0;
b2 = input[i++] || 0;
output += String.fromCharCode((b2 << 8) | b1);
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q54058
|
toUTF8
|
train
|
function toUTF8(input){
var output = '';
var len = input.length;
for (var i = 0; i < len; i++)
{
var c = input.charCodeAt(i);
if (c < 128)
output += chars[c];
else
if (c < 2048)
output += chars[(c >> 6) | 192] +
chars[(c & 63) | 128];
else
output += chars[(c >> 12) | 224] +
chars[((c >> 6) & 63) | 128] +
chars[(c & 63) | 128];
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q54059
|
toUTF8Bytes
|
train
|
function toUTF8Bytes(input){
// utf16 -> utf8
input = toUTF8(input);
// string -> array of bytes
var len = input.length;
var output = new Array(len);
for (var i = 0; i < len; i++)
output[i] = input.charCodeAt(i);
return output;
}
|
javascript
|
{
"resource": ""
}
|
q54060
|
fromUTF8
|
train
|
function fromUTF8(input){
var output = '';
var len = input.length;
var i = 0;
var c1;
var c2;
var c3;
while (i < len)
{
c1 = input.charCodeAt(i++);
if (c1 < 128)
output += chars[c1];
else
{
c2 = input.charCodeAt(i++);
if (c1 & 32)
{
c3 = input.charCodeAt(i++);
output += String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
}
else
output += String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
}
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q54061
|
extendBinding
|
train
|
function extendBinding(binding, extension){
/** @cut */ var info = basis.dev.getInfo(extension, 'map');
binding.bindingId = bindingSeed++;
for (var key in extension)
{
var def = null;
var value = extension[key];
// NOTE: check for Node, because first extendBinding invoke before Node class declared
if ((Node && value instanceof Node) || basis.resource.isResource(value))
{
def = {
events: 'satelliteChanged',
getter: (function(key, satellite){
var resource = typeof satellite == 'function' ? satellite : null;
var init = function(node){
init = false;
if (resource)
{
satellite = resource();
if (satellite instanceof Node == false)
return;
resource = null;
}
node.setSatellite(key, satellite);
/** @cut */ if (node.satellite[key] !== satellite)
/** @cut */ basis.dev.warn('basis.ui.binding: implicit satellite `' + key + '` attach to owner failed');
};
return function(node){
if (init)
init(node);
return resource || (node.satellite[key] ? node.satellite[key].element : null);
};
})(key, value)
};
}
else
{
if (value)
{
if (typeof value == 'string')
value = BINDING_PRESET.process(key, value);
else
// if value has bindingBridge means that it can update itself
if (value.bindingBridge)
value = basis.fn.$const(value);
if (typeof value != 'object')
{
def = {
getter: typeof value == 'function' ? value : basis.getter(value)
};
}
else
if (Array.isArray(value))
{
def = {
events: value[0],
getter: basis.getter(value[1])
};
}
else
{
def = {
events: value.events,
getter: basis.getter(value.getter)
};
}
}
}
/** @cut */ if (def && info && info.hasOwnProperty(key))
/** @cut */ def.loc = info[key];
binding[key] = def;
}
}
|
javascript
|
{
"resource": ""
}
|
q54062
|
train
|
function(actionName, event){
var action = this.action[actionName];
if (action)
action.call(this, event);
/** @cut */ if (!action)
/** @cut */ basis.dev.warn('template call `' + actionName + '` action, but it isn\'t defined in action list');
}
|
javascript
|
{
"resource": ""
}
|
|
q54063
|
train
|
function(select){
var focusElement = this.tmpl ? this.tmpl.focus || this.element : null;
if (focusElement)
{
if (focusTimer)
focusTimer = basis.clearImmediate(focusTimer);
focusTimer = basis.setImmediate(function(){
try {
focusElement.focus();
if (select)
focusElement.select();
} catch(e) {}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54064
|
train
|
function(){
var focusElement = this.tmpl ? this.tmpl.focus || this.element : null;
if (focusElement)
try {
focusElement.blur();
} catch(e) {}
}
|
javascript
|
{
"resource": ""
}
|
|
q54065
|
train
|
function(super_){
return {
// methods
insertBefore: function(newChild, refChild){
/** @cut */ if (this.noChildNodesElement_)
/** @cut */ {
/** @cut */ delete this.noChildNodesElement_;
/** @cut */ basis.dev.warn('basis.ui: Template has no childNodesElement container, but insertBefore method called; probably it\'s a bug');
/** @cut */ }
// inherit
newChild = super_.insertBefore.call(this, newChild, refChild);
var target = newChild.groupNode || this;
var container = target.childNodesElement || this.childNodesElement;
var nextSibling = newChild.nextSibling;
var insertPoint = nextSibling && nextSibling.element.parentNode == container ? nextSibling.element : null;
var childElement = newChild.element;
var refNode = insertPoint || container.insertPoint || null; // NOTE: null at the end for IE
if (childElement.parentNode !== container || childElement.nextSibling !== refNode) // prevent dom update
container.insertBefore(childElement, refNode);
return newChild;
},
removeChild: function(oldChild){
// inherit
super_.removeChild.call(this, oldChild);
// remove from dom
var element = oldChild.element;
var parent = element.parentNode;
if (parent)
parent.removeChild(element);
return oldChild;
},
clear: function(alive){
// if not alive mode node element will be removed on node destroy
if (alive)
{
var node = this.firstChild;
while (node)
{
var element = node.element;
var parent = element.parentNode;
if (parent)
parent.removeChild(element);
node = node.nextSibling;
}
}
// inherit
super_.clear.call(this, alive);
},
setChildNodes: function(childNodes, keepAlive){
/** @cut */ if (this.noChildNodesElement_)
/** @cut */ {
/** @cut */ delete this.noChildNodesElement_;
/** @cut */ basis.dev.warn('basis.ui: Template has no childNodesElement container, but setChildNodes method called; probably it\'s a bug');
/** @cut */ }
// reallocate childNodesElement to new DocumentFragment
var domFragment = document.createDocumentFragment();
var target = this.grouping || this;
var container = target.childNodesElement;
// set child nodes element points to DOM fragment
target.childNodesElement = domFragment;
// call inherit method
// NOTE: make sure that dispatching childNodesModified event handlers are not sensetive
// for child node positions at real DOM (html document), because all new child nodes
// will be inserted into temporary DocumentFragment that will be inserted into html document
// later (after inherited method call)
super_.setChildNodes.call(this, childNodes, keepAlive);
// flush dom fragment nodes into container
container.insertBefore(domFragment, container.insertPoint || null); // NOTE: null at the end for IE
// restore childNodesElement
target.childNodesElement = container;
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q54066
|
track
|
train
|
function track(event){
try {
// TODO look up for event.data.transformer before setting data
tracker.set(event);
} catch(e) {
/** @cut */ basis.dev.error(namespace + '.track(): Error during tracking event processing', event, e);
}
}
|
javascript
|
{
"resource": ""
}
|
q54067
|
getCssSelectorFromPath
|
train
|
function getCssSelectorFromPath(path, selector){
return parsePath(path).map(function(role){
if (!role.role)
return '';
var start = escapeQuotes(role.role);
var end = (role.subrole ? '/' + escapeQuotes(role.subrole) : '') + '"]';
if (role.roleId)
{
if (selector && role.roleId == '*')
start = '[role-marker^="' + start + '("][role-marker$=")';
else
start = '[role-marker="' + start + '(' + escapeQuotes(role.roleId) + ')';
}
else
{
start = '[role-marker="' + start;
}
return start + end;
}).join(' ');
}
|
javascript
|
{
"resource": ""
}
|
q54068
|
checkShow
|
train
|
function checkShow(){
/**
* Checks visibility of an element on a page in a browser
* @param {HTMLElement} element some DOM node
* @private
* @return {boolean}
*/
function isVisible(element){
if (getComputedStyle(element, 'visibility') != 'visible')
return false;
var box = getBoundingRect(element);
if (!box.width || !box.height)
return false;
return true;
}
var list = getSelectorList(SHOW_EVENT);
for (var i = 0; i < list.length; i++)
{
var selector = list[i];
var elements = document.querySelectorAll(getCssSelectorFromPath(selector.selector, true));
var visibleElement = basis.array.search(basis.array(elements), true, isVisible);
var visible = Boolean(visibleElement);
var state;
if (!hasOwnProperty.call(list.visible, selector.selectorStr))
state = list.visible[selector.selectorStr] = false;
else
state = list.visible[selector.selectorStr];
list.visible[selector.selectorStr] = visible;
if (state == false && visible)
track({
type: 'ui',
path: stringifyPath(getPathByNode(visibleElement)),
selector: selector.selectorStr,
event: SHOW_EVENT,
data: selector.data
});
}
}
|
javascript
|
{
"resource": ""
}
|
q54069
|
isVisible
|
train
|
function isVisible(element){
if (getComputedStyle(element, 'visibility') != 'visible')
return false;
var box = getBoundingRect(element);
if (!box.width || !box.height)
return false;
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54070
|
getSelectorList
|
train
|
function getSelectorList(eventName){
if (hasOwnProperty.call(eventMap, eventName))
return eventMap[eventName];
var selectorList = eventMap[eventName] = [];
var inputTimeout = null;
switch (eventName) {
case SHOW_EVENT:
selectorList.visible = {};
setInterval(checkShow, VISIBLE_CHECK_INTERVAL);
break;
default:
eventUtils.addGlobalHandler(eventName, function(event){
var path = event.path.reduce(function(res, node){
var role = node.getAttribute ? node.getAttribute('role-marker') : null;
if (role)
res.unshift(parseRole(role));
return res;
}, []);
// if there is at least one `role-marker` attribute in the DOM [x]path for the clicked (or hovered or `event`ed) element
// then lets search a matching selector in our loaded track map
if (path.length)
selectorList.forEach(function(item){
var result = handleEventFor(path, item, event);
if (result)
if (result.debounce)
{
clearTimeout(inputTimeout);
inputTimeout = setTimeout(function(){
track(result.dataToTrack);
}, INPUT_DEBOUNCE_TIMEOUT);
}
else
{
track(result.dataToTrack);
}
});
});
}
return selectorList;
}
|
javascript
|
{
"resource": ""
}
|
q54071
|
getEventList
|
train
|
function getEventList(selector){
var selectorStr = stringifyPath(selector);
if (hasOwnProperty.call(selectorMap, selectorStr))
return selectorMap[selectorStr];
var eventList = selectorMap[selectorStr] = [];
eventList.selectorStr = selectorStr;
eventList.selector = selector;
return eventList;
}
|
javascript
|
{
"resource": ""
}
|
q54072
|
stringifyRole
|
train
|
function stringifyRole(role){
if (typeof role == 'string')
return role;
if (!role)
return '';
return [
role.role || '',
role.roleId ? '(' + role.roleId + ')' : '',
role.subrole ? '/' + role.subrole : ''
].join('');
}
|
javascript
|
{
"resource": ""
}
|
q54073
|
parsePath
|
train
|
function parsePath(value){
if (!Array.isArray(value))
value = String(value || '').trim().split(/\s+/);
return value.map(function(part){
if (typeof part == 'string')
return parseRole(part);
return part || {
role: '',
roleId: '',
subrole: ''
};
});
}
|
javascript
|
{
"resource": ""
}
|
q54074
|
isPathMatchSelector
|
train
|
function isPathMatchSelector(path, selector){
function isMatch(path, selector){
path = typeof path == 'string' ? parseRole(path) : path || '';
selector = typeof selector == 'string' ? parseRole(selector) : selector || '';
return selector.role == path.role &&
(selector.roleId == '*' || selector.roleId == path.roleId) &&
selector.subrole == path.subrole;
}
var pathIndex = path.length;
var selectorIndex = selector.length;
if (!selectorIndex)
return true;
if (!isMatch(path[--pathIndex], selector[--selectorIndex]))
return false;
while (pathIndex > 0 && selectorIndex > 0)
if (!isMatch(path[--pathIndex], selector[--selectorIndex]))
selectorIndex++;
return selectorIndex === 0;
}
|
javascript
|
{
"resource": ""
}
|
q54075
|
getInfo
|
train
|
function getInfo(path){
var result = [];
if (typeof path == 'string')
path = parsePath(path);
for (var key in selectorMap)
if (isPathMatchSelector(path, selectorMap[key].selector))
result.push.apply(result, selectorMap[key].map(function(item){
return basis.object.extend({
selector: selectorMap[key].selector,
selectorStr: selectorMap[key].selectorStr
}, item);
}));
return result.length ? result : false;
}
|
javascript
|
{
"resource": ""
}
|
q54076
|
getPathByNode
|
train
|
function getPathByNode(node){
var cursor = node;
var path = [];
var role;
while (cursor && cursor !== document)
{
if (role = cursor.getAttribute('role-marker'))
path.unshift(parseRole(role));
cursor = cursor.parentNode;
}
return path;
}
|
javascript
|
{
"resource": ""
}
|
q54077
|
loadMap
|
train
|
function loadMap(map){
if (!map)
{
/** @cut */ basis.dev.warn(namespace + '.loadMap(): Wrong value for map');
return;
}
for (var key in map)
{
var eventsMap = map[key];
if (!eventsMap)
{
/** @cut */ basis.dev.warn(namespace + '.loadMap(): Value of map should be an object for path: ' + key);
continue;
}
var selector = parsePath(key);
for (var events in eventsMap)
{
var data = eventsMap[events];
events.trim().split(/\s+/).forEach(function(eventName){
registrateSelector(selector, eventName, data);
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54078
|
addDispatcher
|
train
|
function addDispatcher(dispatcher, events, transformer){
if (!dispatcher || typeof dispatcher.addHandler != 'function')
{
/** @cut */ basis.dev.warn(namespace + '.addDispatcher(): First argument should have `addHandler` method');
return;
}
if (typeof events == 'string')
events = events.split(/\s+/);
if (!Array.isArray(events))
{
/** @cut */ basis.dev.warn(namespace + '.addDispatcher(): Second argument should be a list of events');
return;
}
if (typeof transformer != 'function')
{
/** @cut */ basis.dev.warn(namespace + '.addDispatcher(): Third argument should be a function');
return;
}
dispatcher.addHandler({
'*': function(event){
if (events.indexOf(event.type) != -1)
{
var eventName = event.type;
var selectorList = getSelectorList(eventName);
selectorList.forEach(function(item){
var data = transformer(event, item);
if (data)
track(data);
});
}
}
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54079
|
fromBytes
|
train
|
function fromBytes(input){
var len = input.length;
var output = '';
for (var i = 0; i < len; i++)
output += chars[input[i]];
return output;
}
|
javascript
|
{
"resource": ""
}
|
q54080
|
getDelta
|
train
|
function getDelta(inserted, deleted){
var delta = {};
var result;
if (inserted && inserted.length)
result = delta.inserted = inserted;
if (deleted && deleted.length)
result = delta.deleted = deleted;
if (result)
return delta;
}
|
javascript
|
{
"resource": ""
}
|
q54081
|
train
|
function(minuend, subtrahend){
var delta;
var operandsChanged = false;
var oldMinuend = this.minuend;
var oldSubtrahend = this.subtrahend;
minuend = resolveDataset(this, this.setMinuend, minuend, 'minuendRA_');
subtrahend = resolveDataset(this, this.setSubtrahend, subtrahend, 'subtrahendRA_');
// set new minuend if changed
if (oldMinuend !== minuend)
{
operandsChanged = true;
this.minuend = minuend;
var listenHandler = this.listen.minuend;
if (listenHandler)
{
if (oldMinuend)
oldMinuend.removeHandler(listenHandler, this);
if (minuend)
minuend.addHandler(listenHandler, this);
}
this.emit_minuendChanged(oldMinuend);
}
// set new subtrahend if changed
if (oldSubtrahend !== subtrahend)
{
operandsChanged = true;
this.subtrahend = subtrahend;
var listenHandler = this.listen.subtrahend;
if (listenHandler)
{
if (oldSubtrahend)
oldSubtrahend.removeHandler(listenHandler, this);
if (subtrahend)
subtrahend.addHandler(listenHandler, this);
}
this.emit_subtrahendChanged(oldSubtrahend);
}
if (!operandsChanged)
return false;
/** @cut */ basis.dev.setInfo(this, 'sourceInfo', {
/** @cut */ type: 'Subtract',
/** @cut */ source: [minuend, subtrahend]
/** @cut */ });
// apply changes
if (!minuend || !subtrahend)
{
if (this.itemCount)
this.emit_itemsChanged(delta = {
deleted: this.getItems()
});
}
else
{
var deleted = [];
var inserted = [];
for (var key in this.items_)
if (!minuend.items_[key] || subtrahend.items_[key])
deleted.push(this.items_[key]);
for (var key in minuend.items_)
if (!this.items_[key] && !subtrahend.items_[key])
inserted.push(minuend.items_[key]);
if (delta = getDelta(inserted, deleted))
this.emit_itemsChanged(delta);
}
return delta;
}
|
javascript
|
{
"resource": ""
}
|
|
q54082
|
resolveResource
|
train
|
function resolveResource(ref, baseURI){
// ref ~ "#123"
if (/^#\d+$/.test(ref))
return templateList[ref.substr(1)];
// ref ~ "id:foo"
if (/^id:/.test(ref))
return resolveSourceByDocumentId(ref.substr(3));
// ref ~ "foo.bar.baz"
if (/^[a-z0-9\.]+$/i.test(ref) && !/\.tmpl$/.test(ref))
return getSourceByPath(ref);
// ref ~ "./path/to/file.tmpl"
return basis.resource(basis.resource.resolveURI(ref, baseURI, '<b:include src=\"{url}\"/>'));
}
|
javascript
|
{
"resource": ""
}
|
q54083
|
templateSourceUpdate
|
train
|
function templateSourceUpdate(){
if (this.destroyBuilder)
buildTemplate.call(this);
var cursor = this;
while (cursor = cursor.attaches_)
cursor.handler.call(cursor.context);
}
|
javascript
|
{
"resource": ""
}
|
q54084
|
buildTemplate
|
train
|
function buildTemplate(){
// build new declaration
var declaration = getDeclFromSource(this.source, this.baseURI, false, {
isolate: this.getIsolatePrefix()
});
// make functions and assign to template
var destroyBuilder = this.destroyBuilder;
var instances = {};
var funcs = this.builder(declaration.tokens, instances);
this.createInstance = funcs.createInstance;
this.clearInstance = funcs.destroyInstance;
this.destroyBuilder = funcs.destroy;
store.add(this.templateId, this, instances);
// for debug purposes only
/** @cut */ this.instances_ = instances;
/** @cut */ this.decl_ = declaration;
// process dependencies
var newDeps = declaration.deps;
var oldDeps = this.deps_;
this.deps_ = newDeps;
// detach old deps
if (oldDeps)
for (var i = 0, dep; dep = oldDeps[i]; i++)
dep.bindingBridge.detach(dep, templateSourceUpdate, this);
// attach new deps
if (newDeps)
for (var i = 0, dep; dep = newDeps[i]; i++)
dep.bindingBridge.attach(dep, templateSourceUpdate, this);
// apply resources
// start use new resource list and than stop use old resource list,
// in this order FOUC is less possible
var newResources = declaration.resources;
var oldResources = this.resources;
this.resources = newResources;
if (newResources)
for (var i = 0, item; item = newResources[i]; i++)
{
var resource = basis.resource(item.url).fetch();
if (typeof resource.startUse == 'function')
resource.startUse();
}
if (oldResources)
for (var i = 0, item; item = oldResources[i]; i++)
{
var resource = basis.resource(item.url).fetch();
if (typeof resource.stopUse == 'function')
resource.stopUse();
}
// destroy old instances if any
if (destroyBuilder)
destroyBuilder(true);
}
|
javascript
|
{
"resource": ""
}
|
q54085
|
train
|
function(object, actionCallback, updateCallback, bindings, bindingInterface){
buildTemplate.call(this);
return this.createInstance(object, actionCallback, updateCallback, bindings, bindingInterface);
}
|
javascript
|
{
"resource": ""
}
|
|
q54086
|
train
|
function(source){
var oldSource = this.source;
if (oldSource != source)
{
if (typeof source == 'string')
{
var m = source.match(/^([a-z]+):/);
if (m)
{
source = source.substr(m[0].length);
switch (m[1])
{
case 'id':
// source from script element
source = resolveSourceByDocumentId(source);
break;
case 'path':
source = getSourceByPath(source);
break;
default:
/** @cut */ basis.dev.warn(namespace + '.Template.setSource: Unknown prefix ' + m[1] + ' for template source was ingnored.');
}
}
}
if (oldSource && oldSource.bindingBridge)
{
this.url = '';
this.baseURI = '';
oldSource.bindingBridge.detach(oldSource, templateSourceUpdate, this);
}
if (source && source.bindingBridge)
{
if (source.url)
{
this.url = source.url;
this.baseURI = path.dirname(source.url) + '/';
}
source.bindingBridge.attach(source, templateSourceUpdate, this);
}
this.source = source;
templateSourceUpdate.call(this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54087
|
train
|
function(config){
this.ruleRet_ = [];
this.templates_ = [];
this.rule = config.rule;
var events = config.events;
if (events && events.length)
{
this.ruleEvents = {};
for (var i = 0, eventName; eventName = events[i]; i++)
this.ruleEvents[eventName] = true;
}
cleaner.add(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q54088
|
switcher
|
train
|
function switcher(events, rule){
if (!rule)
{
rule = events;
events = null;
}
if (typeof events == 'string')
events = events.split(/\s+/);
return new TemplateSwitchConfig({
rule: rule,
events: events
});
}
|
javascript
|
{
"resource": ""
}
|
q54089
|
createDispatcher
|
train
|
function createDispatcher(eventName){
var eventFunction = events[eventName];
if (!eventFunction)
{
eventFunction = function(){
var cursor = this;
var args;
var fn;
while (cursor = cursor.handler)
{
// callback call
fn = cursor.callbacks[eventName];
if (typeof fn == 'function')
{
if (!args)
{
// it should be better for browser optimizations
// (instead of [this].concat(slice.call(arguments)))
args = [this];
for (var i = 0; i < arguments.length; i++)
args.push(arguments[i]);
}
fn.apply(cursor.context || this, args);
}
// any event callback call
fn = cursor.callbacks['*'];
if (typeof fn == 'function')
{
if (!args)
{
// it should be better for browser optimizations
// (instead of [this].concat(slice.call(arguments)))
args = [this];
for (var i = 0; i < arguments.length; i++)
args.push(arguments[i]);
}
fn.call(cursor.context || this, {
sender: this,
type: eventName,
args: args
});
}
}
// feature available in development mode only
/** @cut */ if (this.debug_emit)
/** @cut */ {
/** @cut */ args = []; // avoid optimization warnings about arguments
/** @cut */ for (var i = 0; i < arguments.length; i++)
/** @cut */ args.push(arguments[i]);
/** @cut */ this.debug_emit({
/** @cut */ sender: this,
/** @cut */ type: eventName,
/** @cut */ args: args
/** @cut */ });
/** @cut */ }
};
// function wrapper for more verbose in development mode
/** @cut */ eventFunction = new Function(
/** @cut */ 'return {"' + namespace + '.events.' + eventName + '":\n\n ' +
/** @cut */
/** @cut */ 'function(' + basis.array(arguments, 1).join(', ') + '){' +
/** @cut */ eventFunction.toString()
/** @cut */ .replace(/\beventName\b/g, '"' + eventName + '"')
/** @cut */ .replace(/^function[^(]*\(\)[^{]*\{|\}$/g, '') +
/** @cut */ '}' +
/** @cut */
/** @cut */ '\n\n}["' + namespace + '.events.' + eventName + '"];'
/** @cut */ )();
events[eventName] = eventFunction;
}
return eventFunction;
}
|
javascript
|
{
"resource": ""
}
|
q54090
|
train
|
function(callbacks, context){
/** @cut */ if (!callbacks)
/** @cut */ basis.dev.warn(namespace + '.Emitter#addHandler: callbacks is not an object (', callbacks, ')');
context = context || this;
// warn about duplicates
/** @cut */ var cursor = this;
/** @cut */ while (cursor = cursor.handler)
/** @cut */ {
/** @cut */ if (cursor.callbacks === callbacks && cursor.context === context)
/** @cut */ {
/** @cut */ basis.dev.warn(namespace + '.Emitter#addHandler: add duplicate event callbacks', callbacks, 'to Emitter instance:', this);
/** @cut */ break;
/** @cut */ }
/** @cut */ }
// add handler
this.handler = {
callbacks: callbacks,
context: context,
handler: this.handler
};
}
|
javascript
|
{
"resource": ""
}
|
|
q54091
|
checkUrl
|
train
|
function checkUrl(){
var newPath = location.hash.substr(1) || '';
if (newPath != currentPath)
{
// check for recursion
if (preventRecursion(newPath))
return;
// save current path
currentPath = newPath;
var routesToLeave = [];
var routesToEnter = [];
var routesToMatch = [];
allRoutes.forEach(function(route){
var flags = route.processLocation_(newPath);
if (flags & ROUTE_LEAVE)
routesToLeave.push(route);
if (flags & ROUTE_ENTER)
routesToEnter.push(route);
if (flags & ROUTE_MATCH)
routesToMatch.push(route);
});
for (var i = 0; i < routesToLeave.length; i++)
routeLeave(routesToLeave[i]);
for (var i = 0; i < routesToEnter.length; i++)
routeEnter(routesToEnter[i]);
for (var i = 0; i < routesToMatch.length; i++)
routeMatch(routesToMatch[i]);
/** @cut */ flushLog(namespace + ': hash changed to "' + newPath + '"');
}
else
{
allRoutes.forEach(function(route){
if (route.value)
{
routeEnter(route, true);
routeMatch(route, true);
}
});
/** @cut */ flushLog(namespace + ': checkUrl()');
}
}
|
javascript
|
{
"resource": ""
}
|
q54092
|
get
|
train
|
function get(params){
var path = params.path;
var config = params.config;
if (path instanceof Route)
return path;
var route;
// If there is no config specified - it should be a plain route, so we try to reuse it
if (!config)
route = plainRoutesByPath[path];
if (!route && params.autocreate)
{
var parseInfo = Object.prototype.toString.call(path) == '[object RegExp]'
? { path: path, regexp: path, ast: null, params: [] }
: parsePath(path);
route = createRoute(parseInfo, config);
allRoutes.push(route);
if (route instanceof ParametrizedRoute == false)
plainRoutesByPath[path] = route;
if (typeof currentPath == 'string')
{
var flags = route.processLocation_(currentPath);
if (flags & ROUTE_ENTER)
routeEnter(route);
if (flags & ROUTE_MATCH)
routeMatch(route);
}
}
return route;
}
|
javascript
|
{
"resource": ""
}
|
q54093
|
add
|
train
|
function add(path, callback, context){
var route = get({
path: path,
autocreate: true
});
route.callbacks_.push({
cb_: callback,
context: context,
callback: typeof callback != 'function' ? callback || {} : {
match: callback
}
});
initSchedule.add(route);
return route;
}
|
javascript
|
{
"resource": ""
}
|
q54094
|
remove
|
train
|
function remove(route, callback, context){
var route = get({
path: route
});
if (!route)
return;
for (var i = 0, cb; cb = route.callbacks_[i]; i++)
{
if (cb.cb_ === callback && cb.context === context)
{
route.callbacks_.splice(i, 1);
if (route.value && callback && callback.leave)
{
callback.leave.call(context);
/** @cut */ if (module.exports.debug)
/** @cut */ basis.dev.info(
/** @cut */ namespace + ': add handler for route `' + path + '`\n',
/** @cut */ { type: 'leave', path: route.path, cb: callback.leave, route: route }
/** @cut */ );
}
if (!route.callbacks_.length)
{
// check no attaches to route
if ((!route.handler || !route.handler.handler) && !route.matched.handler)
{
basis.array.remove(allRoutes, route);
if (!(route instanceof ParametrizedRoute))
delete plainRoutesByPath[route.path];
}
}
return;
}
}
/** @cut */ basis.dev.warn(namespace + ': no callback removed', { callback: callback, context: context });
}
|
javascript
|
{
"resource": ""
}
|
q54095
|
navigate
|
train
|
function navigate(path, replace){
if (replace)
location.replace(location.pathname + '#' + path);
else
location.hash = path;
if (started)
checkUrl();
}
|
javascript
|
{
"resource": ""
}
|
q54096
|
train
|
function(rule){
rule = basis.getter(rule || UNION);
if (this.rule !== rule)
{
var oldRule = this.rule;
this.rule = rule;
this.emit_ruleChanged(oldRule);
return this.applyRule();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54097
|
train
|
function(scope){
var memberMap = this.members_;
var rule = this.rule;
var sourceCount = this.sources.length;
var inserted = [];
var deleted = [];
var memberCounter;
var isMember;
var delta;
if (!scope)
scope = memberMap;
for (var objectId in scope)
{
memberCounter = memberMap[objectId];
isMember = sourceCount && memberCounter.count && rule(memberCounter.count, sourceCount);
if (isMember != memberCounter.isMember)
{
if (isMember)
{
// not in items -> insert
memberCounter.isMember = true;
inserted.push(memberCounter.object);
}
else
{
// already in items -> delete
memberCounter.isMember = false;
deleted.push(memberCounter.object);
}
}
if (memberCounter.count == 0)
delete memberMap[objectId];
}
// fire event if delta found
if (delta = getDelta(inserted, deleted))
this.emit_itemsChanged(delta);
return delta;
}
|
javascript
|
{
"resource": ""
}
|
|
q54098
|
train
|
function(source){
// this -> sourceInfo
var merge = this.owner;
var sourcesMap_ = merge.sourcesMap_;
var dataset = resolveDataset(this, merge.updateDataset_, source, 'adapter', merge);
var inserted;
var deleted;
var delta;
if (this.dataset === dataset)
return;
if (dataset)
{
var count = (sourcesMap_[dataset.basisObjectId] || 0) + 1;
sourcesMap_[dataset.basisObjectId] = count;
if (count == 1)
{
merge.addDataset_(dataset);
inserted = [dataset];
}
}
if (this.dataset)
{
var count = (sourcesMap_[this.dataset.basisObjectId] || 0) - 1;
sourcesMap_[this.dataset.basisObjectId] = count;
if (count == 0)
{
merge.removeDataset_(this.dataset);
deleted = [this.dataset];
}
}
this.dataset = dataset;
// build delta and fire event
merge.applyRule();
// fire sources changes event
if (delta = getDelta(inserted, deleted))
{
var setSourcesTransaction = merge.sourceDelta_;
if (setSourcesTransaction)
{
if (delta.inserted)
delta.inserted.forEach(function(item){
if (!arrayRemove(this.deleted, item))
arrayAdd(this.inserted, item);
}, setSourcesTransaction);
if (delta.deleted)
delta.deleted.forEach(function(item){
if (!arrayRemove(this.inserted, item))
arrayAdd(this.deleted, item);
}, setSourcesTransaction);
}
else
{
merge.emit_sourcesChanged(delta);
}
}
return delta;
}
|
javascript
|
{
"resource": ""
}
|
|
q54099
|
train
|
function(source){
if (!source || (typeof source != 'object' && typeof source != 'function'))
{
/** @cut */ basis.dev.warn(this.constructor.className + '.addSource: value should be a dataset instance or to be able to resolve in dataset');
return;
}
if (this.hasSource(source))
{
/** @cut */ basis.dev.warn(this.constructor.className + '.addSource: value is already in source list');
return;
}
var sourceInfo = {
owner: this,
source: source,
adapter: null,
dataset: null
};
this.sourceValues_.push(sourceInfo);
this.updateDataset_.call(sourceInfo, source);
if (this.listen.sourceValue && source instanceof Emitter)
source.addHandler(this.listen.sourceValue, this);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.