id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
7,700
matrix-org/matrix-js-sdk
src/client.js
_encryptEventIfNeeded
function _encryptEventIfNeeded(client, event, room) { if (event.isEncrypted()) { // this event has already been encrypted; this happens if the // encryption step succeeded, but the send step failed on the first // attempt. return null; } if (!client.isRoomEncrypted(event.getRoomId())) { // looks like this room isn't encrypted. return null; } if (!client._crypto) { throw new Error( "This room is configured to use encryption, but your client does " + "not support encryption.", ); } return client._crypto.encryptEvent(event, room); }
javascript
function _encryptEventIfNeeded(client, event, room) { if (event.isEncrypted()) { // this event has already been encrypted; this happens if the // encryption step succeeded, but the send step failed on the first // attempt. return null; } if (!client.isRoomEncrypted(event.getRoomId())) { // looks like this room isn't encrypted. return null; } if (!client._crypto) { throw new Error( "This room is configured to use encryption, but your client does " + "not support encryption.", ); } return client._crypto.encryptEvent(event, room); }
[ "function", "_encryptEventIfNeeded", "(", "client", ",", "event", ",", "room", ")", "{", "if", "(", "event", ".", "isEncrypted", "(", ")", ")", "{", "// this event has already been encrypted; this happens if the", "// encryption step succeeded, but the send step failed on the first", "// attempt.", "return", "null", ";", "}", "if", "(", "!", "client", ".", "isRoomEncrypted", "(", "event", ".", "getRoomId", "(", ")", ")", ")", "{", "// looks like this room isn't encrypted.", "return", "null", ";", "}", "if", "(", "!", "client", ".", "_crypto", ")", "{", "throw", "new", "Error", "(", "\"This room is configured to use encryption, but your client does \"", "+", "\"not support encryption.\"", ",", ")", ";", "}", "return", "client", ".", "_crypto", ".", "encryptEvent", "(", "event", ",", "room", ")", ";", "}" ]
Encrypt an event according to the configuration of the room, if necessary. @param {MatrixClient} client @param {module:models/event.MatrixEvent} event event to be sent @param {module:models/room?} room destination room. Null if the destination is not a room we have seen over the sync pipe. @return {module:client.Promise?} Promise which resolves when the event has been encrypted, or null if nothing was needed
[ "Encrypt", "an", "event", "according", "to", "the", "configuration", "of", "the", "room", "if", "necessary", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/client.js#L1817-L1838
7,701
matrix-org/matrix-js-sdk
src/crypto/index.js
_maybeUploadOneTimeKeys
function _maybeUploadOneTimeKeys(crypto) { // frequency with which to check & upload one-time keys const uploadPeriod = 1000 * 60; // one minute // max number of keys to upload at once // Creating keys can be an expensive operation so we limit the // number we generate in one go to avoid blocking the application // for too long. const maxKeysPerCycle = 5; if (crypto._oneTimeKeyCheckInProgress) { return; } const now = Date.now(); if (crypto._lastOneTimeKeyCheck !== null && now - crypto._lastOneTimeKeyCheck < uploadPeriod ) { // we've done a key upload recently. return; } crypto._lastOneTimeKeyCheck = now; // We need to keep a pool of one time public keys on the server so that // other devices can start conversations with us. But we can only store // a finite number of private keys in the olm Account object. // To complicate things further then can be a delay between a device // claiming a public one time key from the server and it sending us a // message. We need to keep the corresponding private key locally until // we receive the message. // But that message might never arrive leaving us stuck with duff // private keys clogging up our local storage. // So we need some kind of enginering compromise to balance all of // these factors. // Check how many keys we can store in the Account object. const maxOneTimeKeys = crypto._olmDevice.maxNumberOfOneTimeKeys(); // Try to keep at most half that number on the server. This leaves the // rest of the slots free to hold keys that have been claimed from the // server but we haven't recevied a message for. // If we run out of slots when generating new keys then olm will // discard the oldest private keys first. This will eventually clean // out stale private keys that won't receive a message. const keyLimit = Math.floor(maxOneTimeKeys / 2); function uploadLoop(keyCount) { if (keyLimit <= keyCount) { // If we don't need to generate any more keys then we are done. return Promise.resolve(); } const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle); // Ask olm to generate new one time keys, then upload them to synapse. return crypto._olmDevice.generateOneTimeKeys(keysThisLoop).then(() => { return _uploadOneTimeKeys(crypto); }).then((res) => { if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) { // if the response contains a more up to date value use this // for the next loop return uploadLoop(res.one_time_key_counts.signed_curve25519); } else { throw new Error("response for uploading keys does not contain " + "one_time_key_counts.signed_curve25519"); } }); } crypto._oneTimeKeyCheckInProgress = true; Promise.resolve().then(() => { if (crypto._oneTimeKeyCount !== undefined) { // We already have the current one_time_key count from a /sync response. // Use this value instead of asking the server for the current key count. return Promise.resolve(crypto._oneTimeKeyCount); } // ask the server how many keys we have return crypto._baseApis.uploadKeysRequest({}, { device_id: crypto._deviceId, }).then((res) => { return res.one_time_key_counts.signed_curve25519 || 0; }); }).then((keyCount) => { // Start the uploadLoop with the current keyCount. The function checks if // we need to upload new keys or not. // If there are too many keys on the server then we don't need to // create any more keys. return uploadLoop(keyCount); }).catch((e) => { logger.error("Error uploading one-time keys", e.stack || e); }).finally(() => { // reset _oneTimeKeyCount to prevent start uploading based on old data. // it will be set again on the next /sync-response crypto._oneTimeKeyCount = undefined; crypto._oneTimeKeyCheckInProgress = false; }).done(); }
javascript
function _maybeUploadOneTimeKeys(crypto) { // frequency with which to check & upload one-time keys const uploadPeriod = 1000 * 60; // one minute // max number of keys to upload at once // Creating keys can be an expensive operation so we limit the // number we generate in one go to avoid blocking the application // for too long. const maxKeysPerCycle = 5; if (crypto._oneTimeKeyCheckInProgress) { return; } const now = Date.now(); if (crypto._lastOneTimeKeyCheck !== null && now - crypto._lastOneTimeKeyCheck < uploadPeriod ) { // we've done a key upload recently. return; } crypto._lastOneTimeKeyCheck = now; // We need to keep a pool of one time public keys on the server so that // other devices can start conversations with us. But we can only store // a finite number of private keys in the olm Account object. // To complicate things further then can be a delay between a device // claiming a public one time key from the server and it sending us a // message. We need to keep the corresponding private key locally until // we receive the message. // But that message might never arrive leaving us stuck with duff // private keys clogging up our local storage. // So we need some kind of enginering compromise to balance all of // these factors. // Check how many keys we can store in the Account object. const maxOneTimeKeys = crypto._olmDevice.maxNumberOfOneTimeKeys(); // Try to keep at most half that number on the server. This leaves the // rest of the slots free to hold keys that have been claimed from the // server but we haven't recevied a message for. // If we run out of slots when generating new keys then olm will // discard the oldest private keys first. This will eventually clean // out stale private keys that won't receive a message. const keyLimit = Math.floor(maxOneTimeKeys / 2); function uploadLoop(keyCount) { if (keyLimit <= keyCount) { // If we don't need to generate any more keys then we are done. return Promise.resolve(); } const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle); // Ask olm to generate new one time keys, then upload them to synapse. return crypto._olmDevice.generateOneTimeKeys(keysThisLoop).then(() => { return _uploadOneTimeKeys(crypto); }).then((res) => { if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) { // if the response contains a more up to date value use this // for the next loop return uploadLoop(res.one_time_key_counts.signed_curve25519); } else { throw new Error("response for uploading keys does not contain " + "one_time_key_counts.signed_curve25519"); } }); } crypto._oneTimeKeyCheckInProgress = true; Promise.resolve().then(() => { if (crypto._oneTimeKeyCount !== undefined) { // We already have the current one_time_key count from a /sync response. // Use this value instead of asking the server for the current key count. return Promise.resolve(crypto._oneTimeKeyCount); } // ask the server how many keys we have return crypto._baseApis.uploadKeysRequest({}, { device_id: crypto._deviceId, }).then((res) => { return res.one_time_key_counts.signed_curve25519 || 0; }); }).then((keyCount) => { // Start the uploadLoop with the current keyCount. The function checks if // we need to upload new keys or not. // If there are too many keys on the server then we don't need to // create any more keys. return uploadLoop(keyCount); }).catch((e) => { logger.error("Error uploading one-time keys", e.stack || e); }).finally(() => { // reset _oneTimeKeyCount to prevent start uploading based on old data. // it will be set again on the next /sync-response crypto._oneTimeKeyCount = undefined; crypto._oneTimeKeyCheckInProgress = false; }).done(); }
[ "function", "_maybeUploadOneTimeKeys", "(", "crypto", ")", "{", "// frequency with which to check & upload one-time keys", "const", "uploadPeriod", "=", "1000", "*", "60", ";", "// one minute", "// max number of keys to upload at once", "// Creating keys can be an expensive operation so we limit the", "// number we generate in one go to avoid blocking the application", "// for too long.", "const", "maxKeysPerCycle", "=", "5", ";", "if", "(", "crypto", ".", "_oneTimeKeyCheckInProgress", ")", "{", "return", ";", "}", "const", "now", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "crypto", ".", "_lastOneTimeKeyCheck", "!==", "null", "&&", "now", "-", "crypto", ".", "_lastOneTimeKeyCheck", "<", "uploadPeriod", ")", "{", "// we've done a key upload recently.", "return", ";", "}", "crypto", ".", "_lastOneTimeKeyCheck", "=", "now", ";", "// We need to keep a pool of one time public keys on the server so that", "// other devices can start conversations with us. But we can only store", "// a finite number of private keys in the olm Account object.", "// To complicate things further then can be a delay between a device", "// claiming a public one time key from the server and it sending us a", "// message. We need to keep the corresponding private key locally until", "// we receive the message.", "// But that message might never arrive leaving us stuck with duff", "// private keys clogging up our local storage.", "// So we need some kind of enginering compromise to balance all of", "// these factors.", "// Check how many keys we can store in the Account object.", "const", "maxOneTimeKeys", "=", "crypto", ".", "_olmDevice", ".", "maxNumberOfOneTimeKeys", "(", ")", ";", "// Try to keep at most half that number on the server. This leaves the", "// rest of the slots free to hold keys that have been claimed from the", "// server but we haven't recevied a message for.", "// If we run out of slots when generating new keys then olm will", "// discard the oldest private keys first. This will eventually clean", "// out stale private keys that won't receive a message.", "const", "keyLimit", "=", "Math", ".", "floor", "(", "maxOneTimeKeys", "/", "2", ")", ";", "function", "uploadLoop", "(", "keyCount", ")", "{", "if", "(", "keyLimit", "<=", "keyCount", ")", "{", "// If we don't need to generate any more keys then we are done.", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "const", "keysThisLoop", "=", "Math", ".", "min", "(", "keyLimit", "-", "keyCount", ",", "maxKeysPerCycle", ")", ";", "// Ask olm to generate new one time keys, then upload them to synapse.", "return", "crypto", ".", "_olmDevice", ".", "generateOneTimeKeys", "(", "keysThisLoop", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "_uploadOneTimeKeys", "(", "crypto", ")", ";", "}", ")", ".", "then", "(", "(", "res", ")", "=>", "{", "if", "(", "res", ".", "one_time_key_counts", "&&", "res", ".", "one_time_key_counts", ".", "signed_curve25519", ")", "{", "// if the response contains a more up to date value use this", "// for the next loop", "return", "uploadLoop", "(", "res", ".", "one_time_key_counts", ".", "signed_curve25519", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"response for uploading keys does not contain \"", "+", "\"one_time_key_counts.signed_curve25519\"", ")", ";", "}", "}", ")", ";", "}", "crypto", ".", "_oneTimeKeyCheckInProgress", "=", "true", ";", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "crypto", ".", "_oneTimeKeyCount", "!==", "undefined", ")", "{", "// We already have the current one_time_key count from a /sync response.", "// Use this value instead of asking the server for the current key count.", "return", "Promise", ".", "resolve", "(", "crypto", ".", "_oneTimeKeyCount", ")", ";", "}", "// ask the server how many keys we have", "return", "crypto", ".", "_baseApis", ".", "uploadKeysRequest", "(", "{", "}", ",", "{", "device_id", ":", "crypto", ".", "_deviceId", ",", "}", ")", ".", "then", "(", "(", "res", ")", "=>", "{", "return", "res", ".", "one_time_key_counts", ".", "signed_curve25519", "||", "0", ";", "}", ")", ";", "}", ")", ".", "then", "(", "(", "keyCount", ")", "=>", "{", "// Start the uploadLoop with the current keyCount. The function checks if", "// we need to upload new keys or not.", "// If there are too many keys on the server then we don't need to", "// create any more keys.", "return", "uploadLoop", "(", "keyCount", ")", ";", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "logger", ".", "error", "(", "\"Error uploading one-time keys\"", ",", "e", ".", "stack", "||", "e", ")", ";", "}", ")", ".", "finally", "(", "(", ")", "=>", "{", "// reset _oneTimeKeyCount to prevent start uploading based on old data.", "// it will be set again on the next /sync-response", "crypto", ".", "_oneTimeKeyCount", "=", "undefined", ";", "crypto", ".", "_oneTimeKeyCheckInProgress", "=", "false", ";", "}", ")", ".", "done", "(", ")", ";", "}" ]
check if it's time to upload one-time keys, and do so if so.
[ "check", "if", "it", "s", "time", "to", "upload", "one", "-", "time", "keys", "and", "do", "so", "if", "so", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/crypto/index.js#L515-L611
7,702
matrix-org/matrix-js-sdk
src/crypto/index.js
_uploadOneTimeKeys
async function _uploadOneTimeKeys(crypto) { const oneTimeKeys = await crypto._olmDevice.getOneTimeKeys(); const oneTimeJson = {}; const promises = []; for (const keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { const k = { key: oneTimeKeys.curve25519[keyId], }; oneTimeJson["signed_curve25519:" + keyId] = k; promises.push(crypto._signObject(k)); } } await Promise.all(promises); const res = await crypto._baseApis.uploadKeysRequest({ one_time_keys: oneTimeJson, }, { // for now, we set the device id explicitly, as we may not be using the // same one as used in login. device_id: crypto._deviceId, }); await crypto._olmDevice.markKeysAsPublished(); return res; }
javascript
async function _uploadOneTimeKeys(crypto) { const oneTimeKeys = await crypto._olmDevice.getOneTimeKeys(); const oneTimeJson = {}; const promises = []; for (const keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { const k = { key: oneTimeKeys.curve25519[keyId], }; oneTimeJson["signed_curve25519:" + keyId] = k; promises.push(crypto._signObject(k)); } } await Promise.all(promises); const res = await crypto._baseApis.uploadKeysRequest({ one_time_keys: oneTimeJson, }, { // for now, we set the device id explicitly, as we may not be using the // same one as used in login. device_id: crypto._deviceId, }); await crypto._olmDevice.markKeysAsPublished(); return res; }
[ "async", "function", "_uploadOneTimeKeys", "(", "crypto", ")", "{", "const", "oneTimeKeys", "=", "await", "crypto", ".", "_olmDevice", ".", "getOneTimeKeys", "(", ")", ";", "const", "oneTimeJson", "=", "{", "}", ";", "const", "promises", "=", "[", "]", ";", "for", "(", "const", "keyId", "in", "oneTimeKeys", ".", "curve25519", ")", "{", "if", "(", "oneTimeKeys", ".", "curve25519", ".", "hasOwnProperty", "(", "keyId", ")", ")", "{", "const", "k", "=", "{", "key", ":", "oneTimeKeys", ".", "curve25519", "[", "keyId", "]", ",", "}", ";", "oneTimeJson", "[", "\"signed_curve25519:\"", "+", "keyId", "]", "=", "k", ";", "promises", ".", "push", "(", "crypto", ".", "_signObject", "(", "k", ")", ")", ";", "}", "}", "await", "Promise", ".", "all", "(", "promises", ")", ";", "const", "res", "=", "await", "crypto", ".", "_baseApis", ".", "uploadKeysRequest", "(", "{", "one_time_keys", ":", "oneTimeJson", ",", "}", ",", "{", "// for now, we set the device id explicitly, as we may not be using the", "// same one as used in login.", "device_id", ":", "crypto", ".", "_deviceId", ",", "}", ")", ";", "await", "crypto", ".", "_olmDevice", ".", "markKeysAsPublished", "(", ")", ";", "return", "res", ";", "}" ]
returns a promise which resolves to the response
[ "returns", "a", "promise", "which", "resolves", "to", "the", "response" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/crypto/index.js#L614-L642
7,703
matrix-org/matrix-js-sdk
src/models/event-timeline-set.js
EventTimelineSet
function EventTimelineSet(room, opts) { this.room = room; this._timelineSupport = Boolean(opts.timelineSupport); this._liveTimeline = new EventTimeline(this); // just a list - *not* ordered. this._timelines = [this._liveTimeline]; this._eventIdToTimeline = {}; this._filter = opts.filter || null; }
javascript
function EventTimelineSet(room, opts) { this.room = room; this._timelineSupport = Boolean(opts.timelineSupport); this._liveTimeline = new EventTimeline(this); // just a list - *not* ordered. this._timelines = [this._liveTimeline]; this._eventIdToTimeline = {}; this._filter = opts.filter || null; }
[ "function", "EventTimelineSet", "(", "room", ",", "opts", ")", "{", "this", ".", "room", "=", "room", ";", "this", ".", "_timelineSupport", "=", "Boolean", "(", "opts", ".", "timelineSupport", ")", ";", "this", ".", "_liveTimeline", "=", "new", "EventTimeline", "(", "this", ")", ";", "// just a list - *not* ordered.", "this", ".", "_timelines", "=", "[", "this", ".", "_liveTimeline", "]", ";", "this", ".", "_eventIdToTimeline", "=", "{", "}", ";", "this", ".", "_filter", "=", "opts", ".", "filter", "||", "null", ";", "}" ]
Construct a set of EventTimeline objects, typically on behalf of a given room. A room may have multiple EventTimelineSets for different levels of filtering. The global notification list is also an EventTimelineSet, but lacks a room. <p>This is an ordered sequence of timelines, which may or may not be continuous. Each timeline lists a series of events, as well as tracking the room state at the start and the end of the timeline (if appropriate). It also tracks forward and backward pagination tokens, as well as containing links to the next timeline in the sequence. <p>There is one special timeline - the 'live' timeline, which represents the timeline to which events are being added in real-time as they are received from the /sync API. Note that you should not retain references to this timeline - even if it is the current timeline right now, it may not remain so if the server gives us a timeline gap in /sync. <p>In order that we can find events from their ids later, we also maintain a map from event_id to timeline and index. @constructor @param {?Room} room the optional room for this timelineSet @param {Object} opts hash of options inherited from Room. opts.timelineSupport gives whether timeline support is enabled opts.filter is the filter object, if any, for this timelineSet.
[ "Construct", "a", "set", "of", "EventTimeline", "objects", "typically", "on", "behalf", "of", "a", "given", "room", ".", "A", "room", "may", "have", "multiple", "EventTimelineSets", "for", "different", "levels", "of", "filtering", ".", "The", "global", "notification", "list", "is", "also", "an", "EventTimelineSet", "but", "lacks", "a", "room", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event-timeline-set.js#L62-L73
7,704
matrix-org/matrix-js-sdk
src/models/event.js
async function(crypto) { // start with a couple of sanity checks. if (!this.isEncrypted()) { throw new Error("Attempt to decrypt event which isn't encrypted"); } if ( this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype !== "m.bad.encrypted" ) { // we may want to just ignore this? let's start with rejecting it. throw new Error( "Attempt to decrypt event which has already been encrypted", ); } // if we already have a decryption attempt in progress, then it may // fail because it was using outdated info. We now have reason to // succeed where it failed before, but we don't want to have multiple // attempts going at the same time, so just set a flag that says we have // new info. // if (this._decryptionPromise) { console.log( `Event ${this.getId()} already being decrypted; queueing a retry`, ); this._retryDecryption = true; return this._decryptionPromise; } this._decryptionPromise = this._decryptionLoop(crypto); return this._decryptionPromise; }
javascript
async function(crypto) { // start with a couple of sanity checks. if (!this.isEncrypted()) { throw new Error("Attempt to decrypt event which isn't encrypted"); } if ( this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype !== "m.bad.encrypted" ) { // we may want to just ignore this? let's start with rejecting it. throw new Error( "Attempt to decrypt event which has already been encrypted", ); } // if we already have a decryption attempt in progress, then it may // fail because it was using outdated info. We now have reason to // succeed where it failed before, but we don't want to have multiple // attempts going at the same time, so just set a flag that says we have // new info. // if (this._decryptionPromise) { console.log( `Event ${this.getId()} already being decrypted; queueing a retry`, ); this._retryDecryption = true; return this._decryptionPromise; } this._decryptionPromise = this._decryptionLoop(crypto); return this._decryptionPromise; }
[ "async", "function", "(", "crypto", ")", "{", "// start with a couple of sanity checks.", "if", "(", "!", "this", ".", "isEncrypted", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"Attempt to decrypt event which isn't encrypted\"", ")", ";", "}", "if", "(", "this", ".", "_clearEvent", "&&", "this", ".", "_clearEvent", ".", "content", "&&", "this", ".", "_clearEvent", ".", "content", ".", "msgtype", "!==", "\"m.bad.encrypted\"", ")", "{", "// we may want to just ignore this? let's start with rejecting it.", "throw", "new", "Error", "(", "\"Attempt to decrypt event which has already been encrypted\"", ",", ")", ";", "}", "// if we already have a decryption attempt in progress, then it may", "// fail because it was using outdated info. We now have reason to", "// succeed where it failed before, but we don't want to have multiple", "// attempts going at the same time, so just set a flag that says we have", "// new info.", "//", "if", "(", "this", ".", "_decryptionPromise", ")", "{", "console", ".", "log", "(", "`", "${", "this", ".", "getId", "(", ")", "}", "`", ",", ")", ";", "this", ".", "_retryDecryption", "=", "true", ";", "return", "this", ".", "_decryptionPromise", ";", "}", "this", ".", "_decryptionPromise", "=", "this", ".", "_decryptionLoop", "(", "crypto", ")", ";", "return", "this", ".", "_decryptionPromise", ";", "}" ]
Start the process of trying to decrypt this event. (This is used within the SDK: it isn't intended for use by applications) @internal @param {module:crypto} crypto crypto module @returns {Promise} promise which resolves (to undefined) when the decryption attempt is completed.
[ "Start", "the", "process", "of", "trying", "to", "decrypt", "this", "event", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event.js#L347-L379
7,705
matrix-org/matrix-js-sdk
src/models/event.js
function(crypto, userId) { const wireContent = this.getWireContent(); return crypto.requestRoomKey({ algorithm: wireContent.algorithm, room_id: this.getRoomId(), session_id: wireContent.session_id, sender_key: wireContent.sender_key, }, this.getKeyRequestRecipients(userId), true); }
javascript
function(crypto, userId) { const wireContent = this.getWireContent(); return crypto.requestRoomKey({ algorithm: wireContent.algorithm, room_id: this.getRoomId(), session_id: wireContent.session_id, sender_key: wireContent.sender_key, }, this.getKeyRequestRecipients(userId), true); }
[ "function", "(", "crypto", ",", "userId", ")", "{", "const", "wireContent", "=", "this", ".", "getWireContent", "(", ")", ";", "return", "crypto", ".", "requestRoomKey", "(", "{", "algorithm", ":", "wireContent", ".", "algorithm", ",", "room_id", ":", "this", ".", "getRoomId", "(", ")", ",", "session_id", ":", "wireContent", ".", "session_id", ",", "sender_key", ":", "wireContent", ".", "sender_key", ",", "}", ",", "this", ".", "getKeyRequestRecipients", "(", "userId", ")", ",", "true", ")", ";", "}" ]
Cancel any room key request for this event and resend another. @param {module:crypto} crypto crypto module @param {string} userId the user who received this event @returns {Promise} a promise that resolves when the request is queued
[ "Cancel", "any", "room", "key", "request", "for", "this", "event", "and", "resend", "another", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event.js#L389-L397
7,706
matrix-org/matrix-js-sdk
src/models/event.js
function(userId) { // send the request to all of our own devices, and the // original sending device if it wasn't us. const wireContent = this.getWireContent(); const recipients = [{ userId, deviceId: '*', }]; const sender = this.getSender(); if (sender !== userId) { recipients.push({ userId: sender, deviceId: wireContent.device_id, }); } return recipients; }
javascript
function(userId) { // send the request to all of our own devices, and the // original sending device if it wasn't us. const wireContent = this.getWireContent(); const recipients = [{ userId, deviceId: '*', }]; const sender = this.getSender(); if (sender !== userId) { recipients.push({ userId: sender, deviceId: wireContent.device_id, }); } return recipients; }
[ "function", "(", "userId", ")", "{", "// send the request to all of our own devices, and the", "// original sending device if it wasn't us.", "const", "wireContent", "=", "this", ".", "getWireContent", "(", ")", ";", "const", "recipients", "=", "[", "{", "userId", ",", "deviceId", ":", "'*'", ",", "}", "]", ";", "const", "sender", "=", "this", ".", "getSender", "(", ")", ";", "if", "(", "sender", "!==", "userId", ")", "{", "recipients", ".", "push", "(", "{", "userId", ":", "sender", ",", "deviceId", ":", "wireContent", ".", "device_id", ",", "}", ")", ";", "}", "return", "recipients", ";", "}" ]
Calculate the recipients for keyshare requests. @param {string} userId the user who received this event. @returns {Array} array of recipients
[ "Calculate", "the", "recipients", "for", "keyshare", "requests", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event.js#L406-L420
7,707
matrix-org/matrix-js-sdk
src/models/event.js
function(decryptionResult) { this._clearEvent = decryptionResult.clearEvent; this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null; this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null; this._forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || []; }
javascript
function(decryptionResult) { this._clearEvent = decryptionResult.clearEvent; this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null; this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null; this._forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || []; }
[ "function", "(", "decryptionResult", ")", "{", "this", ".", "_clearEvent", "=", "decryptionResult", ".", "clearEvent", ";", "this", ".", "_senderCurve25519Key", "=", "decryptionResult", ".", "senderCurve25519Key", "||", "null", ";", "this", ".", "_claimedEd25519Key", "=", "decryptionResult", ".", "claimedEd25519Key", "||", "null", ";", "this", ".", "_forwardingCurve25519KeyChain", "=", "decryptionResult", ".", "forwardingCurve25519KeyChain", "||", "[", "]", ";", "}" ]
Update the cleartext data on this event. (This is used after decrypting an event; it should not be used by applications). @internal @fires module:models/event.MatrixEvent#"Event.decrypted" @param {module:crypto~EventDecryptionResult} decryptionResult the decryption result, including the plaintext and some key info
[ "Update", "the", "cleartext", "data", "on", "this", "event", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event.js#L538-L546
7,708
matrix-org/matrix-js-sdk
src/models/event.js
function(redaction_event) { // quick sanity-check if (!redaction_event.event) { throw new Error("invalid redaction_event in makeRedacted"); } // we attempt to replicate what we would see from the server if // the event had been redacted before we saw it. // // The server removes (most of) the content of the event, and adds a // "redacted_because" key to the unsigned section containing the // redacted event. if (!this.event.unsigned) { this.event.unsigned = {}; } this.event.unsigned.redacted_because = redaction_event.event; let key; for (key in this.event) { if (!this.event.hasOwnProperty(key)) { continue; } if (!_REDACT_KEEP_KEY_MAP[key]) { delete this.event[key]; } } const keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {}; const content = this.getContent(); for (key in content) { if (!content.hasOwnProperty(key)) { continue; } if (!keeps[key]) { delete content[key]; } } }
javascript
function(redaction_event) { // quick sanity-check if (!redaction_event.event) { throw new Error("invalid redaction_event in makeRedacted"); } // we attempt to replicate what we would see from the server if // the event had been redacted before we saw it. // // The server removes (most of) the content of the event, and adds a // "redacted_because" key to the unsigned section containing the // redacted event. if (!this.event.unsigned) { this.event.unsigned = {}; } this.event.unsigned.redacted_because = redaction_event.event; let key; for (key in this.event) { if (!this.event.hasOwnProperty(key)) { continue; } if (!_REDACT_KEEP_KEY_MAP[key]) { delete this.event[key]; } } const keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {}; const content = this.getContent(); for (key in content) { if (!content.hasOwnProperty(key)) { continue; } if (!keeps[key]) { delete content[key]; } } }
[ "function", "(", "redaction_event", ")", "{", "// quick sanity-check", "if", "(", "!", "redaction_event", ".", "event", ")", "{", "throw", "new", "Error", "(", "\"invalid redaction_event in makeRedacted\"", ")", ";", "}", "// we attempt to replicate what we would see from the server if", "// the event had been redacted before we saw it.", "//", "// The server removes (most of) the content of the event, and adds a", "// \"redacted_because\" key to the unsigned section containing the", "// redacted event.", "if", "(", "!", "this", ".", "event", ".", "unsigned", ")", "{", "this", ".", "event", ".", "unsigned", "=", "{", "}", ";", "}", "this", ".", "event", ".", "unsigned", ".", "redacted_because", "=", "redaction_event", ".", "event", ";", "let", "key", ";", "for", "(", "key", "in", "this", ".", "event", ")", "{", "if", "(", "!", "this", ".", "event", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "_REDACT_KEEP_KEY_MAP", "[", "key", "]", ")", "{", "delete", "this", ".", "event", "[", "key", "]", ";", "}", "}", "const", "keeps", "=", "_REDACT_KEEP_CONTENT_MAP", "[", "this", ".", "getType", "(", ")", "]", "||", "{", "}", ";", "const", "content", "=", "this", ".", "getContent", "(", ")", ";", "for", "(", "key", "in", "content", ")", "{", "if", "(", "!", "content", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "keeps", "[", "key", "]", ")", "{", "delete", "content", "[", "key", "]", ";", "}", "}", "}" ]
Update the content of an event in the same way it would be by the server if it were redacted before it was sent to us @param {module:models/event.MatrixEvent} redaction_event event causing the redaction
[ "Update", "the", "content", "of", "an", "event", "in", "the", "same", "way", "it", "would", "be", "by", "the", "server", "if", "it", "were", "redacted", "before", "it", "was", "sent", "to", "us" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event.js#L647-L684
7,709
matrix-org/matrix-js-sdk
src/models/event-timeline.js
EventTimeline
function EventTimeline(eventTimelineSet) { this._eventTimelineSet = eventTimelineSet; this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null; this._events = []; this._baseIndex = 0; this._startState = new RoomState(this._roomId); this._startState.paginationToken = null; this._endState = new RoomState(this._roomId); this._endState.paginationToken = null; this._prevTimeline = null; this._nextTimeline = null; // this is used by client.js this._paginationRequests = {'b': null, 'f': null}; this._name = this._roomId + ":" + new Date().toISOString(); }
javascript
function EventTimeline(eventTimelineSet) { this._eventTimelineSet = eventTimelineSet; this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null; this._events = []; this._baseIndex = 0; this._startState = new RoomState(this._roomId); this._startState.paginationToken = null; this._endState = new RoomState(this._roomId); this._endState.paginationToken = null; this._prevTimeline = null; this._nextTimeline = null; // this is used by client.js this._paginationRequests = {'b': null, 'f': null}; this._name = this._roomId + ":" + new Date().toISOString(); }
[ "function", "EventTimeline", "(", "eventTimelineSet", ")", "{", "this", ".", "_eventTimelineSet", "=", "eventTimelineSet", ";", "this", ".", "_roomId", "=", "eventTimelineSet", ".", "room", "?", "eventTimelineSet", ".", "room", ".", "roomId", ":", "null", ";", "this", ".", "_events", "=", "[", "]", ";", "this", ".", "_baseIndex", "=", "0", ";", "this", ".", "_startState", "=", "new", "RoomState", "(", "this", ".", "_roomId", ")", ";", "this", ".", "_startState", ".", "paginationToken", "=", "null", ";", "this", ".", "_endState", "=", "new", "RoomState", "(", "this", ".", "_roomId", ")", ";", "this", ".", "_endState", ".", "paginationToken", "=", "null", ";", "this", ".", "_prevTimeline", "=", "null", ";", "this", ".", "_nextTimeline", "=", "null", ";", "// this is used by client.js", "this", ".", "_paginationRequests", "=", "{", "'b'", ":", "null", ",", "'f'", ":", "null", "}", ";", "this", ".", "_name", "=", "this", ".", "_roomId", "+", "\":\"", "+", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ";", "}" ]
Construct a new EventTimeline <p>An EventTimeline represents a contiguous sequence of events in a room. <p>As well as keeping track of the events themselves, it stores the state of the room at the beginning and end of the timeline, and pagination tokens for going backwards and forwards in the timeline. <p>In order that clients can meaningfully maintain an index into a timeline, the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is incremented when events are prepended to the timeline. The index of an event relative to baseIndex therefore remains constant. <p>Once a timeline joins up with its neighbour, they are linked together into a doubly-linked list. @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of @constructor
[ "Construct", "a", "new", "EventTimeline" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/event-timeline.js#L44-L61
7,710
matrix-org/matrix-js-sdk
src/content-repo.js
function(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks) { if (typeof mxc !== "string" || !mxc) { return ''; } if (mxc.indexOf("mxc://") !== 0) { if (allowDirectLinks) { return mxc; } else { return ''; } } let serverAndMediaId = mxc.slice(6); // strips mxc:// let prefix = "/_matrix/media/v1/download/"; const params = {}; if (width) { params.width = width; } if (height) { params.height = height; } if (resizeMethod) { params.method = resizeMethod; } if (utils.keys(params).length > 0) { // these are thumbnailing params so they probably want the // thumbnailing API... prefix = "/_matrix/media/v1/thumbnail/"; } const fragmentOffset = serverAndMediaId.indexOf("#"); let fragment = ""; if (fragmentOffset >= 0) { fragment = serverAndMediaId.substr(fragmentOffset); serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset); } return baseUrl + prefix + serverAndMediaId + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))) + fragment; }
javascript
function(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks) { if (typeof mxc !== "string" || !mxc) { return ''; } if (mxc.indexOf("mxc://") !== 0) { if (allowDirectLinks) { return mxc; } else { return ''; } } let serverAndMediaId = mxc.slice(6); // strips mxc:// let prefix = "/_matrix/media/v1/download/"; const params = {}; if (width) { params.width = width; } if (height) { params.height = height; } if (resizeMethod) { params.method = resizeMethod; } if (utils.keys(params).length > 0) { // these are thumbnailing params so they probably want the // thumbnailing API... prefix = "/_matrix/media/v1/thumbnail/"; } const fragmentOffset = serverAndMediaId.indexOf("#"); let fragment = ""; if (fragmentOffset >= 0) { fragment = serverAndMediaId.substr(fragmentOffset); serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset); } return baseUrl + prefix + serverAndMediaId + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))) + fragment; }
[ "function", "(", "baseUrl", ",", "mxc", ",", "width", ",", "height", ",", "resizeMethod", ",", "allowDirectLinks", ")", "{", "if", "(", "typeof", "mxc", "!==", "\"string\"", "||", "!", "mxc", ")", "{", "return", "''", ";", "}", "if", "(", "mxc", ".", "indexOf", "(", "\"mxc://\"", ")", "!==", "0", ")", "{", "if", "(", "allowDirectLinks", ")", "{", "return", "mxc", ";", "}", "else", "{", "return", "''", ";", "}", "}", "let", "serverAndMediaId", "=", "mxc", ".", "slice", "(", "6", ")", ";", "// strips mxc://", "let", "prefix", "=", "\"/_matrix/media/v1/download/\"", ";", "const", "params", "=", "{", "}", ";", "if", "(", "width", ")", "{", "params", ".", "width", "=", "width", ";", "}", "if", "(", "height", ")", "{", "params", ".", "height", "=", "height", ";", "}", "if", "(", "resizeMethod", ")", "{", "params", ".", "method", "=", "resizeMethod", ";", "}", "if", "(", "utils", ".", "keys", "(", "params", ")", ".", "length", ">", "0", ")", "{", "// these are thumbnailing params so they probably want the", "// thumbnailing API...", "prefix", "=", "\"/_matrix/media/v1/thumbnail/\"", ";", "}", "const", "fragmentOffset", "=", "serverAndMediaId", ".", "indexOf", "(", "\"#\"", ")", ";", "let", "fragment", "=", "\"\"", ";", "if", "(", "fragmentOffset", ">=", "0", ")", "{", "fragment", "=", "serverAndMediaId", ".", "substr", "(", "fragmentOffset", ")", ";", "serverAndMediaId", "=", "serverAndMediaId", ".", "substr", "(", "0", ",", "fragmentOffset", ")", ";", "}", "return", "baseUrl", "+", "prefix", "+", "serverAndMediaId", "+", "(", "utils", ".", "keys", "(", "params", ")", ".", "length", "===", "0", "?", "\"\"", ":", "(", "\"?\"", "+", "utils", ".", "encodeParams", "(", "params", ")", ")", ")", "+", "fragment", ";", "}" ]
Get the HTTP URL for an MXC URI. @param {string} baseUrl The base homeserver url which has a content repo. @param {string} mxc The mxc:// URI. @param {Number} width The desired width of the thumbnail. @param {Number} height The desired height of the thumbnail. @param {string} resizeMethod The thumbnail resize method to use, either "crop" or "scale". @param {Boolean} allowDirectLinks If true, return any non-mxc URLs directly. Fetching such URLs will leak information about the user to anyone they share a room with. If false, will return the emptry string for such URLs. @return {string} The complete URL to the content.
[ "Get", "the", "HTTP", "URL", "for", "an", "MXC", "URI", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/content-repo.js#L37-L77
7,711
matrix-org/matrix-js-sdk
src/content-repo.js
function(baseUrl, identiconString, width, height) { if (!identiconString) { return null; } if (!width) { width = 96; } if (!height) { height = 96; } const params = { width: width, height: height, }; const path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", { $ident: identiconString, }); return baseUrl + path + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))); }
javascript
function(baseUrl, identiconString, width, height) { if (!identiconString) { return null; } if (!width) { width = 96; } if (!height) { height = 96; } const params = { width: width, height: height, }; const path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", { $ident: identiconString, }); return baseUrl + path + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))); }
[ "function", "(", "baseUrl", ",", "identiconString", ",", "width", ",", "height", ")", "{", "if", "(", "!", "identiconString", ")", "{", "return", "null", ";", "}", "if", "(", "!", "width", ")", "{", "width", "=", "96", ";", "}", "if", "(", "!", "height", ")", "{", "height", "=", "96", ";", "}", "const", "params", "=", "{", "width", ":", "width", ",", "height", ":", "height", ",", "}", ";", "const", "path", "=", "utils", ".", "encodeUri", "(", "\"/_matrix/media/v1/identicon/$ident\"", ",", "{", "$ident", ":", "identiconString", ",", "}", ")", ";", "return", "baseUrl", "+", "path", "+", "(", "utils", ".", "keys", "(", "params", ")", ".", "length", "===", "0", "?", "\"\"", ":", "(", "\"?\"", "+", "utils", ".", "encodeParams", "(", "params", ")", ")", ")", ";", "}" ]
Get an identicon URL from an arbitrary string. @param {string} baseUrl The base homeserver url which has a content repo. @param {string} identiconString The string to create an identicon for. @param {Number} width The desired width of the image in pixels. Default: 96. @param {Number} height The desired height of the image in pixels. Default: 96. @return {string} The complete URL to the identicon.
[ "Get", "an", "identicon", "URL", "from", "an", "arbitrary", "string", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/content-repo.js#L87-L108
7,712
matrix-org/matrix-js-sdk
src/store/memory.js
function(room) { this.rooms[room.roomId] = room; // add listeners for room member changes so we can keep the room member // map up-to-date. room.currentState.on("RoomState.members", this._onRoomMember.bind(this)); // add existing members const self = this; room.currentState.getMembers().forEach(function(m) { self._onRoomMember(null, room.currentState, m); }); }
javascript
function(room) { this.rooms[room.roomId] = room; // add listeners for room member changes so we can keep the room member // map up-to-date. room.currentState.on("RoomState.members", this._onRoomMember.bind(this)); // add existing members const self = this; room.currentState.getMembers().forEach(function(m) { self._onRoomMember(null, room.currentState, m); }); }
[ "function", "(", "room", ")", "{", "this", ".", "rooms", "[", "room", ".", "roomId", "]", "=", "room", ";", "// add listeners for room member changes so we can keep the room member", "// map up-to-date.", "room", ".", "currentState", ".", "on", "(", "\"RoomState.members\"", ",", "this", ".", "_onRoomMember", ".", "bind", "(", "this", ")", ")", ";", "// add existing members", "const", "self", "=", "this", ";", "room", ".", "currentState", ".", "getMembers", "(", ")", ".", "forEach", "(", "function", "(", "m", ")", "{", "self", ".", "_onRoomMember", "(", "null", ",", "room", ".", "currentState", ",", "m", ")", ";", "}", ")", ";", "}" ]
Store the given room. @param {Room} room The room to be stored. All properties must be stored.
[ "Store", "the", "given", "room", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/memory.js#L113-L123
7,713
matrix-org/matrix-js-sdk
src/store/memory.js
function(event, state, member) { if (member.membership === "invite") { // We do NOT add invited members because people love to typo user IDs // which would then show up in these lists (!) return; } const user = this.users[member.userId] || new User(member.userId); if (member.name) { user.setDisplayName(member.name); if (member.events.member) { user.setRawDisplayName( member.events.member.getDirectionalContent().displayname, ); } } if (member.events.member && member.events.member.getContent().avatar_url) { user.setAvatarUrl(member.events.member.getContent().avatar_url); } this.users[user.userId] = user; }
javascript
function(event, state, member) { if (member.membership === "invite") { // We do NOT add invited members because people love to typo user IDs // which would then show up in these lists (!) return; } const user = this.users[member.userId] || new User(member.userId); if (member.name) { user.setDisplayName(member.name); if (member.events.member) { user.setRawDisplayName( member.events.member.getDirectionalContent().displayname, ); } } if (member.events.member && member.events.member.getContent().avatar_url) { user.setAvatarUrl(member.events.member.getContent().avatar_url); } this.users[user.userId] = user; }
[ "function", "(", "event", ",", "state", ",", "member", ")", "{", "if", "(", "member", ".", "membership", "===", "\"invite\"", ")", "{", "// We do NOT add invited members because people love to typo user IDs", "// which would then show up in these lists (!)", "return", ";", "}", "const", "user", "=", "this", ".", "users", "[", "member", ".", "userId", "]", "||", "new", "User", "(", "member", ".", "userId", ")", ";", "if", "(", "member", ".", "name", ")", "{", "user", ".", "setDisplayName", "(", "member", ".", "name", ")", ";", "if", "(", "member", ".", "events", ".", "member", ")", "{", "user", ".", "setRawDisplayName", "(", "member", ".", "events", ".", "member", ".", "getDirectionalContent", "(", ")", ".", "displayname", ",", ")", ";", "}", "}", "if", "(", "member", ".", "events", ".", "member", "&&", "member", ".", "events", ".", "member", ".", "getContent", "(", ")", ".", "avatar_url", ")", "{", "user", ".", "setAvatarUrl", "(", "member", ".", "events", ".", "member", ".", "getContent", "(", ")", ".", "avatar_url", ")", ";", "}", "this", ".", "users", "[", "user", ".", "userId", "]", "=", "user", ";", "}" ]
Called when a room member in a room being tracked by this store has been updated. @param {MatrixEvent} event @param {RoomState} state @param {RoomMember} member
[ "Called", "when", "a", "room", "member", "in", "a", "room", "being", "tracked", "by", "this", "store", "has", "been", "updated", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/memory.js#L132-L152
7,714
matrix-org/matrix-js-sdk
src/store/memory.js
function(filter) { if (!filter) { return; } if (!this.filters[filter.userId]) { this.filters[filter.userId] = {}; } this.filters[filter.userId][filter.filterId] = filter; }
javascript
function(filter) { if (!filter) { return; } if (!this.filters[filter.userId]) { this.filters[filter.userId] = {}; } this.filters[filter.userId][filter.filterId] = filter; }
[ "function", "(", "filter", ")", "{", "if", "(", "!", "filter", ")", "{", "return", ";", "}", "if", "(", "!", "this", ".", "filters", "[", "filter", ".", "userId", "]", ")", "{", "this", ".", "filters", "[", "filter", ".", "userId", "]", "=", "{", "}", ";", "}", "this", ".", "filters", "[", "filter", ".", "userId", "]", "[", "filter", ".", "filterId", "]", "=", "filter", ";", "}" ]
Store a filter. @param {Filter} filter
[ "Store", "a", "filter", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/memory.js#L243-L251
7,715
matrix-org/matrix-js-sdk
src/store/memory.js
function(userId, filterId) { if (!this.filters[userId] || !this.filters[userId][filterId]) { return null; } return this.filters[userId][filterId]; }
javascript
function(userId, filterId) { if (!this.filters[userId] || !this.filters[userId][filterId]) { return null; } return this.filters[userId][filterId]; }
[ "function", "(", "userId", ",", "filterId", ")", "{", "if", "(", "!", "this", ".", "filters", "[", "userId", "]", "||", "!", "this", ".", "filters", "[", "userId", "]", "[", "filterId", "]", ")", "{", "return", "null", ";", "}", "return", "this", ".", "filters", "[", "userId", "]", "[", "filterId", "]", ";", "}" ]
Retrieve a filter. @param {string} userId @param {string} filterId @return {?Filter} A filter or null.
[ "Retrieve", "a", "filter", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/memory.js#L259-L264
7,716
matrix-org/matrix-js-sdk
src/store/memory.js
function(events) { const self = this; events.forEach(function(event) { self.accountData[event.getType()] = event; }); }
javascript
function(events) { const self = this; events.forEach(function(event) { self.accountData[event.getType()] = event; }); }
[ "function", "(", "events", ")", "{", "const", "self", "=", "this", ";", "events", ".", "forEach", "(", "function", "(", "event", ")", "{", "self", ".", "accountData", "[", "event", ".", "getType", "(", ")", "]", "=", "event", ";", "}", ")", ";", "}" ]
Store user-scoped account data events. N.B. that account data only allows a single event per type, so multiple events with the same type will replace each other. @param {Array<MatrixEvent>} events The events to store.
[ "Store", "user", "-", "scoped", "account", "data", "events", ".", "N", ".", "B", ".", "that", "account", "data", "only", "allows", "a", "single", "event", "per", "type", "so", "multiple", "events", "with", "the", "same", "type", "will", "replace", "each", "other", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/memory.js#L301-L306
7,717
matrix-org/matrix-js-sdk
spec/integ/matrix-client-event-timeline.spec.js
startClient
function startClient(httpBackend, client) { httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" }); httpBackend.when("GET", "/sync").respond(200, INITIAL_SYNC_DATA); client.startClient(); // set up a promise which will resolve once the client is initialised const deferred = Promise.defer(); client.on("sync", function(state) { console.log("sync", state); if (state != "SYNCING") { return; } deferred.resolve(); }); return Promise.all([ httpBackend.flushAllExpected(), deferred.promise, ]); }
javascript
function startClient(httpBackend, client) { httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" }); httpBackend.when("GET", "/sync").respond(200, INITIAL_SYNC_DATA); client.startClient(); // set up a promise which will resolve once the client is initialised const deferred = Promise.defer(); client.on("sync", function(state) { console.log("sync", state); if (state != "SYNCING") { return; } deferred.resolve(); }); return Promise.all([ httpBackend.flushAllExpected(), deferred.promise, ]); }
[ "function", "startClient", "(", "httpBackend", ",", "client", ")", "{", "httpBackend", ".", "when", "(", "\"GET\"", ",", "\"/pushrules\"", ")", ".", "respond", "(", "200", ",", "{", "}", ")", ";", "httpBackend", ".", "when", "(", "\"POST\"", ",", "\"/filter\"", ")", ".", "respond", "(", "200", ",", "{", "filter_id", ":", "\"fid\"", "}", ")", ";", "httpBackend", ".", "when", "(", "\"GET\"", ",", "\"/sync\"", ")", ".", "respond", "(", "200", ",", "INITIAL_SYNC_DATA", ")", ";", "client", ".", "startClient", "(", ")", ";", "// set up a promise which will resolve once the client is initialised", "const", "deferred", "=", "Promise", ".", "defer", "(", ")", ";", "client", ".", "on", "(", "\"sync\"", ",", "function", "(", "state", ")", "{", "console", ".", "log", "(", "\"sync\"", ",", "state", ")", ";", "if", "(", "state", "!=", "\"SYNCING\"", ")", "{", "return", ";", "}", "deferred", ".", "resolve", "(", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "[", "httpBackend", ".", "flushAllExpected", "(", ")", ",", "deferred", ".", "promise", ",", "]", ")", ";", "}" ]
start the client, and wait for it to initialise
[ "start", "the", "client", "and", "wait", "for", "it", "to", "initialise" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-event-timeline.spec.js#L77-L98
7,718
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
selectQuery
function selectQuery(store, keyRange, resultMapper) { const query = store.openCursor(keyRange); return new Promise((resolve, reject) => { const results = []; query.onerror = (event) => { reject(new Error("Query failed: " + event.target.errorCode)); }; // collect results query.onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { resolve(results); return; // end of results } results.push(resultMapper(cursor)); cursor.continue(); }; }); }
javascript
function selectQuery(store, keyRange, resultMapper) { const query = store.openCursor(keyRange); return new Promise((resolve, reject) => { const results = []; query.onerror = (event) => { reject(new Error("Query failed: " + event.target.errorCode)); }; // collect results query.onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { resolve(results); return; // end of results } results.push(resultMapper(cursor)); cursor.continue(); }; }); }
[ "function", "selectQuery", "(", "store", ",", "keyRange", ",", "resultMapper", ")", "{", "const", "query", "=", "store", ".", "openCursor", "(", "keyRange", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "results", "=", "[", "]", ";", "query", ".", "onerror", "=", "(", "event", ")", "=>", "{", "reject", "(", "new", "Error", "(", "\"Query failed: \"", "+", "event", ".", "target", ".", "errorCode", ")", ")", ";", "}", ";", "// collect results", "query", ".", "onsuccess", "=", "(", "event", ")", "=>", "{", "const", "cursor", "=", "event", ".", "target", ".", "result", ";", "if", "(", "!", "cursor", ")", "{", "resolve", "(", "results", ")", ";", "return", ";", "// end of results", "}", "results", ".", "push", "(", "resultMapper", "(", "cursor", ")", ")", ";", "cursor", ".", "continue", "(", ")", ";", "}", ";", "}", ")", ";", "}" ]
Helper method to collect results from a Cursor and promiseify it. @param {ObjectStore|Index} store The store to perform openCursor on. @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor. @param {Function} resultMapper A function which is repeatedly called with a Cursor. Return the data you want to keep. @return {Promise<T[]>} Resolves to an array of whatever you returned from resultMapper.
[ "Helper", "method", "to", "collect", "results", "from", "a", "Cursor", "and", "promiseify", "it", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L61-L79
7,719
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
LocalIndexedDBStoreBackend
function LocalIndexedDBStoreBackend( indexedDBInterface, dbName, ) { this.indexedDB = indexedDBInterface; this._dbName = "matrix-js-sdk:" + (dbName || "default"); this.db = null; this._disconnected = true; this._syncAccumulator = new SyncAccumulator(); this._isNewlyCreated = false; }
javascript
function LocalIndexedDBStoreBackend( indexedDBInterface, dbName, ) { this.indexedDB = indexedDBInterface; this._dbName = "matrix-js-sdk:" + (dbName || "default"); this.db = null; this._disconnected = true; this._syncAccumulator = new SyncAccumulator(); this._isNewlyCreated = false; }
[ "function", "LocalIndexedDBStoreBackend", "(", "indexedDBInterface", ",", "dbName", ",", ")", "{", "this", ".", "indexedDB", "=", "indexedDBInterface", ";", "this", ".", "_dbName", "=", "\"matrix-js-sdk:\"", "+", "(", "dbName", "||", "\"default\"", ")", ";", "this", ".", "db", "=", "null", ";", "this", ".", "_disconnected", "=", "true", ";", "this", ".", "_syncAccumulator", "=", "new", "SyncAccumulator", "(", ")", ";", "this", ".", "_isNewlyCreated", "=", "false", ";", "}" ]
Does the actual reading from and writing to the indexeddb Construct a new Indexed Database store backend. This requires a call to <code>connect()</code> before this store can be used. @constructor @param {Object} indexedDBInterface The Indexed DB interface e.g <code>window.indexedDB</code> @param {string=} dbName Optional database name. The same name must be used to open the same database.
[ "Does", "the", "actual", "reading", "from", "and", "writing", "to", "the", "indexeddb" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L125-L134
7,720
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function() { if (!this._disconnected) { console.log( `LocalIndexedDBStoreBackend.connect: already connected or connecting`, ); return Promise.resolve(); } this._disconnected = false; console.log( `LocalIndexedDBStoreBackend.connect: connecting...`, ); const req = this.indexedDB.open(this._dbName, VERSION); req.onupgradeneeded = (ev) => { const db = ev.target.result; const oldVersion = ev.oldVersion; console.log( `LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`, ); if (oldVersion < 1) { // The database did not previously exist. this._isNewlyCreated = true; createDatabase(db); } if (oldVersion < 2) { upgradeSchemaV2(db); } if (oldVersion < 3) { upgradeSchemaV3(db); } // Expand as needed. }; req.onblocked = () => { console.log( `can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`, ); }; console.log( `LocalIndexedDBStoreBackend.connect: awaiting connection...`, ); return reqAsEventPromise(req).then((ev) => { console.log( `LocalIndexedDBStoreBackend.connect: connected`, ); this.db = ev.target.result; // add a poorly-named listener for when deleteDatabase is called // so we can close our db connections. this.db.onversionchange = () => { this.db.close(); }; return this._init(); }); }
javascript
function() { if (!this._disconnected) { console.log( `LocalIndexedDBStoreBackend.connect: already connected or connecting`, ); return Promise.resolve(); } this._disconnected = false; console.log( `LocalIndexedDBStoreBackend.connect: connecting...`, ); const req = this.indexedDB.open(this._dbName, VERSION); req.onupgradeneeded = (ev) => { const db = ev.target.result; const oldVersion = ev.oldVersion; console.log( `LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`, ); if (oldVersion < 1) { // The database did not previously exist. this._isNewlyCreated = true; createDatabase(db); } if (oldVersion < 2) { upgradeSchemaV2(db); } if (oldVersion < 3) { upgradeSchemaV3(db); } // Expand as needed. }; req.onblocked = () => { console.log( `can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`, ); }; console.log( `LocalIndexedDBStoreBackend.connect: awaiting connection...`, ); return reqAsEventPromise(req).then((ev) => { console.log( `LocalIndexedDBStoreBackend.connect: connected`, ); this.db = ev.target.result; // add a poorly-named listener for when deleteDatabase is called // so we can close our db connections. this.db.onversionchange = () => { this.db.close(); }; return this._init(); }); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "_disconnected", ")", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "this", ".", "_disconnected", "=", "false", ";", "console", ".", "log", "(", "`", "`", ",", ")", ";", "const", "req", "=", "this", ".", "indexedDB", ".", "open", "(", "this", ".", "_dbName", ",", "VERSION", ")", ";", "req", ".", "onupgradeneeded", "=", "(", "ev", ")", "=>", "{", "const", "db", "=", "ev", ".", "target", ".", "result", ";", "const", "oldVersion", "=", "ev", ".", "oldVersion", ";", "console", ".", "log", "(", "`", "${", "oldVersion", "}", "`", ",", ")", ";", "if", "(", "oldVersion", "<", "1", ")", "{", "// The database did not previously exist.", "this", ".", "_isNewlyCreated", "=", "true", ";", "createDatabase", "(", "db", ")", ";", "}", "if", "(", "oldVersion", "<", "2", ")", "{", "upgradeSchemaV2", "(", "db", ")", ";", "}", "if", "(", "oldVersion", "<", "3", ")", "{", "upgradeSchemaV3", "(", "db", ")", ";", "}", "// Expand as needed.", "}", ";", "req", ".", "onblocked", "=", "(", ")", "=>", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "}", ";", "console", ".", "log", "(", "`", "`", ",", ")", ";", "return", "reqAsEventPromise", "(", "req", ")", ".", "then", "(", "(", "ev", ")", "=>", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "this", ".", "db", "=", "ev", ".", "target", ".", "result", ";", "// add a poorly-named listener for when deleteDatabase is called", "// so we can close our db connections.", "this", ".", "db", ".", "onversionchange", "=", "(", ")", "=>", "{", "this", ".", "db", ".", "close", "(", ")", ";", "}", ";", "return", "this", ".", "_init", "(", ")", ";", "}", ")", ";", "}" ]
Attempt to connect to the database. This can fail if the user does not grant permission. @return {Promise} Resolves if successfully connected.
[ "Attempt", "to", "connect", "to", "the", "database", ".", "This", "can", "fail", "if", "the", "user", "does", "not", "grant", "permission", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L147-L203
7,721
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function() { return Promise.all([ this._loadAccountData(), this._loadSyncData(), ]).then(([accountData, syncData]) => { console.log( `LocalIndexedDBStoreBackend: loaded initial data`, ); this._syncAccumulator.accumulate({ next_batch: syncData.nextBatch, rooms: syncData.roomsData, groups: syncData.groupsData, account_data: { events: accountData, }, }); }); }
javascript
function() { return Promise.all([ this._loadAccountData(), this._loadSyncData(), ]).then(([accountData, syncData]) => { console.log( `LocalIndexedDBStoreBackend: loaded initial data`, ); this._syncAccumulator.accumulate({ next_batch: syncData.nextBatch, rooms: syncData.roomsData, groups: syncData.groupsData, account_data: { events: accountData, }, }); }); }
[ "function", "(", ")", "{", "return", "Promise", ".", "all", "(", "[", "this", ".", "_loadAccountData", "(", ")", ",", "this", ".", "_loadSyncData", "(", ")", ",", "]", ")", ".", "then", "(", "(", "[", "accountData", ",", "syncData", "]", ")", "=>", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "this", ".", "_syncAccumulator", ".", "accumulate", "(", "{", "next_batch", ":", "syncData", ".", "nextBatch", ",", "rooms", ":", "syncData", ".", "roomsData", ",", "groups", ":", "syncData", ".", "groupsData", ",", "account_data", ":", "{", "events", ":", "accountData", ",", "}", ",", "}", ")", ";", "}", ")", ";", "}" ]
Having connected, load initial data from the database and prepare for use @return {Promise} Resolves on success
[ "Having", "connected", "load", "initial", "data", "from", "the", "database", "and", "prepare", "for", "use" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L213-L230
7,722
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function(roomId) { return new Promise((resolve, reject) =>{ const tx = this.db.transaction(["oob_membership_events"], "readonly"); const store = tx.objectStore("oob_membership_events"); const roomIndex = store.index("room"); const range = IDBKeyRange.only(roomId); const request = roomIndex.openCursor(range); const membershipEvents = []; // did we encounter the oob_written marker object // amongst the results? That means OOB member // loading already happened for this room // but there were no members to persist as they // were all known already let oobWritten = false; request.onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { // Unknown room if (!membershipEvents.length && !oobWritten) { return resolve(null); } return resolve(membershipEvents); } const record = cursor.value; if (record.oob_written) { oobWritten = true; } else { membershipEvents.push(record); } cursor.continue(); }; request.onerror = (err) => { reject(err); }; }).then((events) => { console.log(`LL: got ${events && events.length}` + ` membershipEvents from storage for room ${roomId} ...`); return events; }); }
javascript
function(roomId) { return new Promise((resolve, reject) =>{ const tx = this.db.transaction(["oob_membership_events"], "readonly"); const store = tx.objectStore("oob_membership_events"); const roomIndex = store.index("room"); const range = IDBKeyRange.only(roomId); const request = roomIndex.openCursor(range); const membershipEvents = []; // did we encounter the oob_written marker object // amongst the results? That means OOB member // loading already happened for this room // but there were no members to persist as they // were all known already let oobWritten = false; request.onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { // Unknown room if (!membershipEvents.length && !oobWritten) { return resolve(null); } return resolve(membershipEvents); } const record = cursor.value; if (record.oob_written) { oobWritten = true; } else { membershipEvents.push(record); } cursor.continue(); }; request.onerror = (err) => { reject(err); }; }).then((events) => { console.log(`LL: got ${events && events.length}` + ` membershipEvents from storage for room ${roomId} ...`); return events; }); }
[ "function", "(", "roomId", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "tx", "=", "this", ".", "db", ".", "transaction", "(", "[", "\"oob_membership_events\"", "]", ",", "\"readonly\"", ")", ";", "const", "store", "=", "tx", ".", "objectStore", "(", "\"oob_membership_events\"", ")", ";", "const", "roomIndex", "=", "store", ".", "index", "(", "\"room\"", ")", ";", "const", "range", "=", "IDBKeyRange", ".", "only", "(", "roomId", ")", ";", "const", "request", "=", "roomIndex", ".", "openCursor", "(", "range", ")", ";", "const", "membershipEvents", "=", "[", "]", ";", "// did we encounter the oob_written marker object", "// amongst the results? That means OOB member", "// loading already happened for this room", "// but there were no members to persist as they", "// were all known already", "let", "oobWritten", "=", "false", ";", "request", ".", "onsuccess", "=", "(", "event", ")", "=>", "{", "const", "cursor", "=", "event", ".", "target", ".", "result", ";", "if", "(", "!", "cursor", ")", "{", "// Unknown room", "if", "(", "!", "membershipEvents", ".", "length", "&&", "!", "oobWritten", ")", "{", "return", "resolve", "(", "null", ")", ";", "}", "return", "resolve", "(", "membershipEvents", ")", ";", "}", "const", "record", "=", "cursor", ".", "value", ";", "if", "(", "record", ".", "oob_written", ")", "{", "oobWritten", "=", "true", ";", "}", "else", "{", "membershipEvents", ".", "push", "(", "record", ")", ";", "}", "cursor", ".", "continue", "(", ")", ";", "}", ";", "request", ".", "onerror", "=", "(", "err", ")", "=>", "{", "reject", "(", "err", ")", ";", "}", ";", "}", ")", ".", "then", "(", "(", "events", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "events", "&&", "events", ".", "length", "}", "`", "+", "`", "${", "roomId", "}", "`", ")", ";", "return", "events", ";", "}", ")", ";", "}" ]
Returns the out-of-band membership events for this room that were previously loaded. @param {string} roomId @returns {Promise<event[]>} the events, potentially an empty array if OOB loading didn't yield any new members @returns {null} in case the members for this room haven't been stored yet
[ "Returns", "the", "out", "-", "of", "-", "band", "membership", "events", "for", "this", "room", "that", "were", "previously", "loaded", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L239-L280
7,723
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
async function(roomId, membershipEvents) { console.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`); const tx = this.db.transaction(["oob_membership_events"], "readwrite"); const store = tx.objectStore("oob_membership_events"); membershipEvents.forEach((e) => { store.put(e); }); // aside from all the events, we also write a marker object to the store // to mark the fact that OOB members have been written for this room. // It's possible that 0 members need to be written as all where previously know // but we still need to know whether to return null or [] from getOutOfBandMembers // where null means out of band members haven't been stored yet for this room const markerObject = { room_id: roomId, oob_written: true, state_key: 0, }; store.put(markerObject); await txnAsPromise(tx); console.log(`LL: backend done storing for ${roomId}!`); }
javascript
async function(roomId, membershipEvents) { console.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`); const tx = this.db.transaction(["oob_membership_events"], "readwrite"); const store = tx.objectStore("oob_membership_events"); membershipEvents.forEach((e) => { store.put(e); }); // aside from all the events, we also write a marker object to the store // to mark the fact that OOB members have been written for this room. // It's possible that 0 members need to be written as all where previously know // but we still need to know whether to return null or [] from getOutOfBandMembers // where null means out of band members haven't been stored yet for this room const markerObject = { room_id: roomId, oob_written: true, state_key: 0, }; store.put(markerObject); await txnAsPromise(tx); console.log(`LL: backend done storing for ${roomId}!`); }
[ "async", "function", "(", "roomId", ",", "membershipEvents", ")", "{", "console", ".", "log", "(", "`", "${", "membershipEvents", ".", "length", "}", "`", "+", "`", "${", "roomId", "}", "`", ")", ";", "const", "tx", "=", "this", ".", "db", ".", "transaction", "(", "[", "\"oob_membership_events\"", "]", ",", "\"readwrite\"", ")", ";", "const", "store", "=", "tx", ".", "objectStore", "(", "\"oob_membership_events\"", ")", ";", "membershipEvents", ".", "forEach", "(", "(", "e", ")", "=>", "{", "store", ".", "put", "(", "e", ")", ";", "}", ")", ";", "// aside from all the events, we also write a marker object to the store", "// to mark the fact that OOB members have been written for this room.", "// It's possible that 0 members need to be written as all where previously know", "// but we still need to know whether to return null or [] from getOutOfBandMembers", "// where null means out of band members haven't been stored yet for this room", "const", "markerObject", "=", "{", "room_id", ":", "roomId", ",", "oob_written", ":", "true", ",", "state_key", ":", "0", ",", "}", ";", "store", ".", "put", "(", "markerObject", ")", ";", "await", "txnAsPromise", "(", "tx", ")", ";", "console", ".", "log", "(", "`", "${", "roomId", "}", "`", ")", ";", "}" ]
Stores the out-of-band membership events for this room. Note that it still makes sense to store an empty array as the OOB status for the room is marked as fetched, and getOutOfBandMembers will return an empty array instead of null @param {string} roomId @param {event[]} membershipEvents the membership events to store
[ "Stores", "the", "out", "-", "of", "-", "band", "membership", "events", "for", "this", "room", ".", "Note", "that", "it", "still", "makes", "sense", "to", "store", "an", "empty", "array", "as", "the", "OOB", "status", "for", "the", "room", "is", "marked", "as", "fetched", "and", "getOutOfBandMembers", "will", "return", "an", "empty", "array", "instead", "of", "null" ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L289-L310
7,724
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function() { return new Promise((resolve, reject) => { console.log(`Removing indexeddb instance: ${this._dbName}`); const req = this.indexedDB.deleteDatabase(this._dbName); req.onblocked = () => { console.log( `can't yet delete indexeddb ${this._dbName}` + ` because it is open elsewhere`, ); }; req.onerror = (ev) => { // in firefox, with indexedDB disabled, this fails with a // DOMError. We treat this as non-fatal, so that we can still // use the app. console.warn( `unable to delete js-sdk store indexeddb: ${ev.target.error}`, ); resolve(); }; req.onsuccess = () => { console.log(`Removed indexeddb instance: ${this._dbName}`); resolve(); }; }); }
javascript
function() { return new Promise((resolve, reject) => { console.log(`Removing indexeddb instance: ${this._dbName}`); const req = this.indexedDB.deleteDatabase(this._dbName); req.onblocked = () => { console.log( `can't yet delete indexeddb ${this._dbName}` + ` because it is open elsewhere`, ); }; req.onerror = (ev) => { // in firefox, with indexedDB disabled, this fails with a // DOMError. We treat this as non-fatal, so that we can still // use the app. console.warn( `unable to delete js-sdk store indexeddb: ${ev.target.error}`, ); resolve(); }; req.onsuccess = () => { console.log(`Removed indexeddb instance: ${this._dbName}`); resolve(); }; }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "this", ".", "_dbName", "}", "`", ")", ";", "const", "req", "=", "this", ".", "indexedDB", ".", "deleteDatabase", "(", "this", ".", "_dbName", ")", ";", "req", ".", "onblocked", "=", "(", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "this", ".", "_dbName", "}", "`", "+", "`", "`", ",", ")", ";", "}", ";", "req", ".", "onerror", "=", "(", "ev", ")", "=>", "{", "// in firefox, with indexedDB disabled, this fails with a", "// DOMError. We treat this as non-fatal, so that we can still", "// use the app.", "console", ".", "warn", "(", "`", "${", "ev", ".", "target", ".", "error", "}", "`", ",", ")", ";", "resolve", "(", ")", ";", "}", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "this", ".", "_dbName", "}", "`", ")", ";", "resolve", "(", ")", ";", "}", ";", "}", ")", ";", "}" ]
Clear the entire database. This should be used when logging out of a client to prevent mixing data between accounts. @return {Promise} Resolved when the database is cleared.
[ "Clear", "the", "entire", "database", ".", "This", "should", "be", "used", "when", "logging", "out", "of", "a", "client", "to", "prevent", "mixing", "data", "between", "accounts", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L355-L382
7,725
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function(accountData) { return Promise.try(() => { const txn = this.db.transaction(["accountData"], "readwrite"); const store = txn.objectStore("accountData"); for (let i = 0; i < accountData.length; i++) { store.put(accountData[i]); // put == UPSERT } return txnAsPromise(txn); }); }
javascript
function(accountData) { return Promise.try(() => { const txn = this.db.transaction(["accountData"], "readwrite"); const store = txn.objectStore("accountData"); for (let i = 0; i < accountData.length; i++) { store.put(accountData[i]); // put == UPSERT } return txnAsPromise(txn); }); }
[ "function", "(", "accountData", ")", "{", "return", "Promise", ".", "try", "(", "(", ")", "=>", "{", "const", "txn", "=", "this", ".", "db", ".", "transaction", "(", "[", "\"accountData\"", "]", ",", "\"readwrite\"", ")", ";", "const", "store", "=", "txn", ".", "objectStore", "(", "\"accountData\"", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "accountData", ".", "length", ";", "i", "++", ")", "{", "store", ".", "put", "(", "accountData", "[", "i", "]", ")", ";", "// put == UPSERT", "}", "return", "txnAsPromise", "(", "txn", ")", ";", "}", ")", ";", "}" ]
Persist a list of account data events. Events with the same 'type' will be replaced. @param {Object[]} accountData An array of raw user-scoped account data events @return {Promise} Resolves if the events were persisted.
[ "Persist", "a", "list", "of", "account", "data", "events", ".", "Events", "with", "the", "same", "type", "will", "be", "replaced", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L457-L466
7,726
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function() { console.log( `LocalIndexedDBStoreBackend: loading account data...`, ); return Promise.try(() => { const txn = this.db.transaction(["accountData"], "readonly"); const store = txn.objectStore("accountData"); return selectQuery(store, undefined, (cursor) => { return cursor.value; }).then((result) => { console.log( `LocalIndexedDBStoreBackend: loaded account data`, ); return result; }); }); }
javascript
function() { console.log( `LocalIndexedDBStoreBackend: loading account data...`, ); return Promise.try(() => { const txn = this.db.transaction(["accountData"], "readonly"); const store = txn.objectStore("accountData"); return selectQuery(store, undefined, (cursor) => { return cursor.value; }).then((result) => { console.log( `LocalIndexedDBStoreBackend: loaded account data`, ); return result; }); }); }
[ "function", "(", ")", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "return", "Promise", ".", "try", "(", "(", ")", "=>", "{", "const", "txn", "=", "this", ".", "db", ".", "transaction", "(", "[", "\"accountData\"", "]", ",", "\"readonly\"", ")", ";", "const", "store", "=", "txn", ".", "objectStore", "(", "\"accountData\"", ")", ";", "return", "selectQuery", "(", "store", ",", "undefined", ",", "(", "cursor", ")", "=>", "{", "return", "cursor", ".", "value", ";", "}", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "return", "result", ";", "}", ")", ";", "}", ")", ";", "}" ]
Load all the account data events from the database. This is not cached. @return {Promise<Object[]>} A list of raw global account events.
[ "Load", "all", "the", "account", "data", "events", "from", "the", "database", ".", "This", "is", "not", "cached", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L510-L526
7,727
matrix-org/matrix-js-sdk
src/store/indexeddb-local-backend.js
function() { console.log( `LocalIndexedDBStoreBackend: loading sync data...`, ); return Promise.try(() => { const txn = this.db.transaction(["sync"], "readonly"); const store = txn.objectStore("sync"); return selectQuery(store, undefined, (cursor) => { return cursor.value; }).then((results) => { console.log( `LocalIndexedDBStoreBackend: loaded sync data`, ); if (results.length > 1) { console.warn("loadSyncData: More than 1 sync row found."); } return (results.length > 0 ? results[0] : {}); }); }); }
javascript
function() { console.log( `LocalIndexedDBStoreBackend: loading sync data...`, ); return Promise.try(() => { const txn = this.db.transaction(["sync"], "readonly"); const store = txn.objectStore("sync"); return selectQuery(store, undefined, (cursor) => { return cursor.value; }).then((results) => { console.log( `LocalIndexedDBStoreBackend: loaded sync data`, ); if (results.length > 1) { console.warn("loadSyncData: More than 1 sync row found."); } return (results.length > 0 ? results[0] : {}); }); }); }
[ "function", "(", ")", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "return", "Promise", ".", "try", "(", "(", ")", "=>", "{", "const", "txn", "=", "this", ".", "db", ".", "transaction", "(", "[", "\"sync\"", "]", ",", "\"readonly\"", ")", ";", "const", "store", "=", "txn", ".", "objectStore", "(", "\"sync\"", ")", ";", "return", "selectQuery", "(", "store", ",", "undefined", ",", "(", "cursor", ")", "=>", "{", "return", "cursor", ".", "value", ";", "}", ")", ".", "then", "(", "(", "results", ")", "=>", "{", "console", ".", "log", "(", "`", "`", ",", ")", ";", "if", "(", "results", ".", "length", ">", "1", ")", "{", "console", ".", "warn", "(", "\"loadSyncData: More than 1 sync row found.\"", ")", ";", "}", "return", "(", "results", ".", "length", ">", "0", "?", "results", "[", "0", "]", ":", "{", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Load the sync data from the database. @return {Promise<Object>} An object with "roomsData" and "nextBatch" keys.
[ "Load", "the", "sync", "data", "from", "the", "database", "." ]
ee8a4698a94a4a6bfaded61d6108492a04aa0d4e
https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb-local-backend.js#L532-L551
7,728
plotly/react-chart-editor
src/lib/walkObject.js
_walkObject
function _walkObject(object, callback, path, config) { const {walkArrays, walkArraysMatchingKeys} = config; Object.keys(object).forEach(key => { // Callback can force traversal to stop by returning `true`. if (callback(key, object, path.get(object, key))) { return; } const value = object[key]; if (isPlainObject(value) || doArrayWalk(key, value, walkArrays, walkArraysMatchingKeys)) { _walkObject(value, callback, path.set(object, key), config); } }); }
javascript
function _walkObject(object, callback, path, config) { const {walkArrays, walkArraysMatchingKeys} = config; Object.keys(object).forEach(key => { // Callback can force traversal to stop by returning `true`. if (callback(key, object, path.get(object, key))) { return; } const value = object[key]; if (isPlainObject(value) || doArrayWalk(key, value, walkArrays, walkArraysMatchingKeys)) { _walkObject(value, callback, path.set(object, key), config); } }); }
[ "function", "_walkObject", "(", "object", ",", "callback", ",", "path", ",", "config", ")", "{", "const", "{", "walkArrays", ",", "walkArraysMatchingKeys", "}", "=", "config", ";", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "key", "=>", "{", "// Callback can force traversal to stop by returning `true`.", "if", "(", "callback", "(", "key", ",", "object", ",", "path", ".", "get", "(", "object", ",", "key", ")", ")", ")", "{", "return", ";", "}", "const", "value", "=", "object", "[", "key", "]", ";", "if", "(", "isPlainObject", "(", "value", ")", "||", "doArrayWalk", "(", "key", ",", "value", ",", "walkArrays", ",", "walkArraysMatchingKeys", ")", ")", "{", "_walkObject", "(", "value", ",", "callback", ",", "path", ".", "set", "(", "object", ",", "key", ")", ",", "config", ")", ";", "}", "}", ")", ";", "}" ]
The function that walkObject calls at each node. @callback walkObjectCallback @param {string|number} key The current key, which may be nested. @param {object} parent The object which owns the 'key' as a prop. @param {Array} path The keys that lead to the 'parent' object. @returns {boolean} True if the value at 'key' should *not* be traversed into if it happens to be an object. I.e., you don't need to return anything if you want the default traversal of the whole object. Walks through object and recurses if necessary. @param {object} object The top-level or nested object we're walking through. @param {walkObjectCallback} callback Called at each object node. @param {Array} path The keys that lead from to top-level object to this one. @param {object} config configuration object @param {string} config.walkArrays flag allowing array walking @param {Array} config.walkArraysMatchingKeys An array of keys permitting array walking @param {string} config.pathType Either 'array' or 'nestedProperty'. Array based paths return string keys in an array up until the current key position. NestedProperty style returns a single concatenated "nestedProperty" style string. @returns {void} @private
[ "The", "function", "that", "walkObject", "calls", "at", "each", "node", "." ]
584b6b94237f1f22597025fd8b5d8f69d49bef95
https://github.com/plotly/react-chart-editor/blob/584b6b94237f1f22597025fd8b5d8f69d49bef95/src/lib/walkObject.js#L129-L142
7,729
sindresorhus/execa
index.js
handleEscaping
function handleEscaping(tokens, token, index) { if (index === 0) { return [token]; } const previousToken = tokens[index - 1]; if (!previousToken.endsWith('\\')) { return [...tokens, token]; } return [...tokens.slice(0, index - 1), `${previousToken.slice(0, -1)} ${token}`]; }
javascript
function handleEscaping(tokens, token, index) { if (index === 0) { return [token]; } const previousToken = tokens[index - 1]; if (!previousToken.endsWith('\\')) { return [...tokens, token]; } return [...tokens.slice(0, index - 1), `${previousToken.slice(0, -1)} ${token}`]; }
[ "function", "handleEscaping", "(", "tokens", ",", "token", ",", "index", ")", "{", "if", "(", "index", "===", "0", ")", "{", "return", "[", "token", "]", ";", "}", "const", "previousToken", "=", "tokens", "[", "index", "-", "1", "]", ";", "if", "(", "!", "previousToken", ".", "endsWith", "(", "'\\\\'", ")", ")", "{", "return", "[", "...", "tokens", ",", "token", "]", ";", "}", "return", "[", "...", "tokens", ".", "slice", "(", "0", ",", "index", "-", "1", ")", ",", "`", "${", "previousToken", ".", "slice", "(", "0", ",", "-", "1", ")", "}", "${", "token", "}", "`", "]", ";", "}" ]
Allow spaces to be escaped by a backslash if not meant as a delimiter
[ "Allow", "spaces", "to", "be", "escaped", "by", "a", "backslash", "if", "not", "meant", "as", "a", "delimiter" ]
659f4444795c8c20c5b4ef61c8b9d744136604c0
https://github.com/sindresorhus/execa/blob/659f4444795c8c20c5b4ef61c8b9d744136604c0/index.js#L21-L33
7,730
ampproject/ampstart
webpack.config.js
isEnv
function isEnv(envAlias) { // Check for default case if (envAlias === ENV_ALIAS.DEV && Object.keys(env).length === 0) { return true; } return envAlias.some(alias => env[alias]); }
javascript
function isEnv(envAlias) { // Check for default case if (envAlias === ENV_ALIAS.DEV && Object.keys(env).length === 0) { return true; } return envAlias.some(alias => env[alias]); }
[ "function", "isEnv", "(", "envAlias", ")", "{", "// Check for default case", "if", "(", "envAlias", "===", "ENV_ALIAS", ".", "DEV", "&&", "Object", ".", "keys", "(", "env", ")", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "return", "envAlias", ".", "some", "(", "alias", "=>", "env", "[", "alias", "]", ")", ";", "}" ]
Function to return if the environment matched the environment alias
[ "Function", "to", "return", "if", "the", "environment", "matched", "the", "environment", "alias" ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/webpack.config.js#L33-L40
7,731
ampproject/ampstart
functions/index.js
cors
function cors(req, res, next) { const port = process.env.NODE_ENV === 'production' ? null : new url.URL(req.query.__amp_source_origin).port; const host = process.env.NODE_ENV === 'production' ? `https://${req.hostname}` : `http://${req.hostname}:${port}`; res.header('amp-access-control-allow-source-origin', host); next(); }
javascript
function cors(req, res, next) { const port = process.env.NODE_ENV === 'production' ? null : new url.URL(req.query.__amp_source_origin).port; const host = process.env.NODE_ENV === 'production' ? `https://${req.hostname}` : `http://${req.hostname}:${port}`; res.header('amp-access-control-allow-source-origin', host); next(); }
[ "function", "cors", "(", "req", ",", "res", ",", "next", ")", "{", "const", "port", "=", "process", ".", "env", ".", "NODE_ENV", "===", "'production'", "?", "null", ":", "new", "url", ".", "URL", "(", "req", ".", "query", ".", "__amp_source_origin", ")", ".", "port", ";", "const", "host", "=", "process", ".", "env", ".", "NODE_ENV", "===", "'production'", "?", "`", "${", "req", ".", "hostname", "}", "`", ":", "`", "${", "req", ".", "hostname", "}", "${", "port", "}", "`", ";", "res", ".", "header", "(", "'amp-access-control-allow-source-origin'", ",", "host", ")", ";", "next", "(", ")", ";", "}" ]
cors is HTTP middleware that sets an AMP-specific cross origin resource sharing HTTP header on our response. @param {Object} req - The HTTP request object. @param {Object} res - The HTTP response object. @param {Function} next - The next HTTP handler to execute.
[ "cors", "is", "HTTP", "middleware", "that", "sets", "an", "AMP", "-", "specific", "cross", "origin", "resource", "sharing", "HTTP", "header", "on", "our", "response", "." ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/functions/index.js#L19-L31
7,732
ampproject/ampstart
functions/index.js
filter
function filter(data, query) { var results = []; var push = true; // omit every result that doesn't pass _every_ filter data.forEach((val) => { var push = true; // if we fail a filter condition, then don't push // check if we're over the max price if (query.maxPrice > 0) { if (val.price.value > query.maxPrice) { push = false; } } // check if the city is included if (query.cities.length > 0) { if (!query.cities.includes(val.location.city)) { push = false; } } // check if the type is anywhere to be found var found = false; if (query.types.length > 0) { query.types.forEach((type) => { if (val.types.includes(type)) found = true; }); } else { // assume it's found if there's no `query.types` on the request found = true; } if (!found) { push = false; } // if we found something, then push it to the results array if (push) { results.push(val); } }); return results; }
javascript
function filter(data, query) { var results = []; var push = true; // omit every result that doesn't pass _every_ filter data.forEach((val) => { var push = true; // if we fail a filter condition, then don't push // check if we're over the max price if (query.maxPrice > 0) { if (val.price.value > query.maxPrice) { push = false; } } // check if the city is included if (query.cities.length > 0) { if (!query.cities.includes(val.location.city)) { push = false; } } // check if the type is anywhere to be found var found = false; if (query.types.length > 0) { query.types.forEach((type) => { if (val.types.includes(type)) found = true; }); } else { // assume it's found if there's no `query.types` on the request found = true; } if (!found) { push = false; } // if we found something, then push it to the results array if (push) { results.push(val); } }); return results; }
[ "function", "filter", "(", "data", ",", "query", ")", "{", "var", "results", "=", "[", "]", ";", "var", "push", "=", "true", ";", "// omit every result that doesn't pass _every_ filter", "data", ".", "forEach", "(", "(", "val", ")", "=>", "{", "var", "push", "=", "true", ";", "// if we fail a filter condition, then don't push", "// check if we're over the max price", "if", "(", "query", ".", "maxPrice", ">", "0", ")", "{", "if", "(", "val", ".", "price", ".", "value", ">", "query", ".", "maxPrice", ")", "{", "push", "=", "false", ";", "}", "}", "// check if the city is included", "if", "(", "query", ".", "cities", ".", "length", ">", "0", ")", "{", "if", "(", "!", "query", ".", "cities", ".", "includes", "(", "val", ".", "location", ".", "city", ")", ")", "{", "push", "=", "false", ";", "}", "}", "// check if the type is anywhere to be found", "var", "found", "=", "false", ";", "if", "(", "query", ".", "types", ".", "length", ">", "0", ")", "{", "query", ".", "types", ".", "forEach", "(", "(", "type", ")", "=>", "{", "if", "(", "val", ".", "types", ".", "includes", "(", "type", ")", ")", "found", "=", "true", ";", "}", ")", ";", "}", "else", "{", "// assume it's found if there's no `query.types` on the request", "found", "=", "true", ";", "}", "if", "(", "!", "found", ")", "{", "push", "=", "false", ";", "}", "// if we found something, then push it to the results array", "if", "(", "push", ")", "{", "results", ".", "push", "(", "val", ")", ";", "}", "}", ")", ";", "return", "results", ";", "}" ]
filter returns the travel data that matches the given query. @param {Array} data - Array of objects containing the travel data to filter. @param {Object} query - An HTTP request query object. @return {Array} - An array of travelData objects.
[ "filter", "returns", "the", "travel", "data", "that", "matches", "the", "given", "query", "." ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/functions/index.js#L61-L105
7,733
ampproject/ampstart
functions/index.js
selectedCities
function selectedCities(travelData, cities) { var selected = []; travelData.activities.forEach((data) => { const isSelected = cities.includes(data.location.city); // check if the city already exists in our cities array var existsIdx = -1; selected.forEach((city, idx) => { if (city.name === data.location.city) { existsIdx = idx; } }); const city = travelData.cities.find((city) => city.name === data.location.city); // if it doesn't exist already, add it if (existsIdx === -1) { selected.push({ img: city ? city.img : '', name: data.location.city, isSelected: isSelected, }); // otherwise update the existing entry only if it's currently false, // otherwise we could overwrite a previous match } else { if (!selected[existsIdx].isSelected) { selected[existsIdx].isSelected = isSelected; } } }); return selected; }
javascript
function selectedCities(travelData, cities) { var selected = []; travelData.activities.forEach((data) => { const isSelected = cities.includes(data.location.city); // check if the city already exists in our cities array var existsIdx = -1; selected.forEach((city, idx) => { if (city.name === data.location.city) { existsIdx = idx; } }); const city = travelData.cities.find((city) => city.name === data.location.city); // if it doesn't exist already, add it if (existsIdx === -1) { selected.push({ img: city ? city.img : '', name: data.location.city, isSelected: isSelected, }); // otherwise update the existing entry only if it's currently false, // otherwise we could overwrite a previous match } else { if (!selected[existsIdx].isSelected) { selected[existsIdx].isSelected = isSelected; } } }); return selected; }
[ "function", "selectedCities", "(", "travelData", ",", "cities", ")", "{", "var", "selected", "=", "[", "]", ";", "travelData", ".", "activities", ".", "forEach", "(", "(", "data", ")", "=>", "{", "const", "isSelected", "=", "cities", ".", "includes", "(", "data", ".", "location", ".", "city", ")", ";", "// check if the city already exists in our cities array", "var", "existsIdx", "=", "-", "1", ";", "selected", ".", "forEach", "(", "(", "city", ",", "idx", ")", "=>", "{", "if", "(", "city", ".", "name", "===", "data", ".", "location", ".", "city", ")", "{", "existsIdx", "=", "idx", ";", "}", "}", ")", ";", "const", "city", "=", "travelData", ".", "cities", ".", "find", "(", "(", "city", ")", "=>", "city", ".", "name", "===", "data", ".", "location", ".", "city", ")", ";", "// if it doesn't exist already, add it", "if", "(", "existsIdx", "===", "-", "1", ")", "{", "selected", ".", "push", "(", "{", "img", ":", "city", "?", "city", ".", "img", ":", "''", ",", "name", ":", "data", ".", "location", ".", "city", ",", "isSelected", ":", "isSelected", ",", "}", ")", ";", "// otherwise update the existing entry only if it's currently false,", "// otherwise we could overwrite a previous match", "}", "else", "{", "if", "(", "!", "selected", "[", "existsIdx", "]", ".", "isSelected", ")", "{", "selected", "[", "existsIdx", "]", ".", "isSelected", "=", "isSelected", ";", "}", "}", "}", ")", ";", "return", "selected", ";", "}" ]
Checks to see if any the given cities exist in our travel data, returning all the ones that are. @param {Array} travelData - Array of objects containing the travel data to filter. @param {Array} cities - Array of strings containing city names. @return {Array} The selected cities.
[ "Checks", "to", "see", "if", "any", "the", "given", "cities", "exist", "in", "our", "travel", "data", "returning", "all", "the", "ones", "that", "are", "." ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/functions/index.js#L116-L148
7,734
ampproject/ampstart
functions/index.js
sortResults
function sortResults(val, results) { const sortPopularity = (a, b) => { if (a.reviews.count < b.reviews.count) { return 1; } else if (a.reviews.count > b.reviews.count) { return -1; } return 0; }; const sortRating = (a, b) => { if (a.reviews.averageRating.value < b.reviews.averageRating.value) { return 1; } else if (a.reviews.averageRating.value > b.reviews.averageRating.value) { return -1; } return sortPopularity(a, b); }; const sortPrice = (a, b) => { if (a.price.value > b.price.value) { return 1; } else if (a.price.value < b.price.value) { return -1; } return sortRating(a, b); }; const sortNew = (a, b) => { if (!a.flags.new && b.flags.new) { return 1; } else if (a.flags.new && !b.flags.new) { return -1; } return sortRating(a, b); }; switch (val.toLowerCase()) { case "popularity-desc": return results.slice().sort(sortPopularity); case "rating-desc": return results.slice().sort(sortRating); case "age-asc": return results.slice().sort(sortNew); case "price-asc": return results.slice().sort(sortPrice); default: return results; } }
javascript
function sortResults(val, results) { const sortPopularity = (a, b) => { if (a.reviews.count < b.reviews.count) { return 1; } else if (a.reviews.count > b.reviews.count) { return -1; } return 0; }; const sortRating = (a, b) => { if (a.reviews.averageRating.value < b.reviews.averageRating.value) { return 1; } else if (a.reviews.averageRating.value > b.reviews.averageRating.value) { return -1; } return sortPopularity(a, b); }; const sortPrice = (a, b) => { if (a.price.value > b.price.value) { return 1; } else if (a.price.value < b.price.value) { return -1; } return sortRating(a, b); }; const sortNew = (a, b) => { if (!a.flags.new && b.flags.new) { return 1; } else if (a.flags.new && !b.flags.new) { return -1; } return sortRating(a, b); }; switch (val.toLowerCase()) { case "popularity-desc": return results.slice().sort(sortPopularity); case "rating-desc": return results.slice().sort(sortRating); case "age-asc": return results.slice().sort(sortNew); case "price-asc": return results.slice().sort(sortPrice); default: return results; } }
[ "function", "sortResults", "(", "val", ",", "results", ")", "{", "const", "sortPopularity", "=", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "a", ".", "reviews", ".", "count", "<", "b", ".", "reviews", ".", "count", ")", "{", "return", "1", ";", "}", "else", "if", "(", "a", ".", "reviews", ".", "count", ">", "b", ".", "reviews", ".", "count", ")", "{", "return", "-", "1", ";", "}", "return", "0", ";", "}", ";", "const", "sortRating", "=", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "a", ".", "reviews", ".", "averageRating", ".", "value", "<", "b", ".", "reviews", ".", "averageRating", ".", "value", ")", "{", "return", "1", ";", "}", "else", "if", "(", "a", ".", "reviews", ".", "averageRating", ".", "value", ">", "b", ".", "reviews", ".", "averageRating", ".", "value", ")", "{", "return", "-", "1", ";", "}", "return", "sortPopularity", "(", "a", ",", "b", ")", ";", "}", ";", "const", "sortPrice", "=", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "a", ".", "price", ".", "value", ">", "b", ".", "price", ".", "value", ")", "{", "return", "1", ";", "}", "else", "if", "(", "a", ".", "price", ".", "value", "<", "b", ".", "price", ".", "value", ")", "{", "return", "-", "1", ";", "}", "return", "sortRating", "(", "a", ",", "b", ")", ";", "}", ";", "const", "sortNew", "=", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "!", "a", ".", "flags", ".", "new", "&&", "b", ".", "flags", ".", "new", ")", "{", "return", "1", ";", "}", "else", "if", "(", "a", ".", "flags", ".", "new", "&&", "!", "b", ".", "flags", ".", "new", ")", "{", "return", "-", "1", ";", "}", "return", "sortRating", "(", "a", ",", "b", ")", ";", "}", ";", "switch", "(", "val", ".", "toLowerCase", "(", ")", ")", "{", "case", "\"popularity-desc\"", ":", "return", "results", ".", "slice", "(", ")", ".", "sort", "(", "sortPopularity", ")", ";", "case", "\"rating-desc\"", ":", "return", "results", ".", "slice", "(", ")", ".", "sort", "(", "sortRating", ")", ";", "case", "\"age-asc\"", ":", "return", "results", ".", "slice", "(", ")", ".", "sort", "(", "sortNew", ")", ";", "case", "\"price-asc\"", ":", "return", "results", ".", "slice", "(", ")", ".", "sort", "(", "sortPrice", ")", ";", "default", ":", "return", "results", ";", "}", "}" ]
sortResults checks to see if the value is one of the parameters we know how to sort by. @param {String} val - The value to check. @param {Array} results - Array of object to sort. @return {Array} The sorted results.
[ "sortResults", "checks", "to", "see", "if", "the", "value", "is", "one", "of", "the", "parameters", "we", "know", "how", "to", "sort", "by", "." ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/functions/index.js#L158-L214
7,735
ampproject/ampstart
functions/index.js
getSVGGraphPathData
function getSVGGraphPathData(data, width, height) { var max = Math.max.apply(null, data); var width = 800; var height = 100; var scaleH = width / (data.length - 1) var scaleV = height / max; var factor = 0.25; var commands = [`m0,${applyScaleV(data[0])}`]; function round(val) { return Math.round(val * 1000) / 1000; } function applyScaleH(val) { return round(val * scaleH); } function applyScaleV(val) { return round(100 - val * scaleV); } for (let i = 0, max = data.length - 1; i < max; i++) { current = data[i]; next = data[i + 1]; let x = (i + 0.5); let y = current + (next - current) * 0.5 let sX = (i + (0.5 - factor)); let sY = current + (next - current) * (0.5 - factor); commands.push(`S${applyScaleH(sX)} ${applyScaleV(sY)},${applyScaleH(x)} ${applyScaleV(y)}`); } var finalY = data[data.length - 1]; commands.push(`S${width} ${applyScaleV(finalY)},${width} ${applyScaleV(finalY)}`); return commands.join(' '); }
javascript
function getSVGGraphPathData(data, width, height) { var max = Math.max.apply(null, data); var width = 800; var height = 100; var scaleH = width / (data.length - 1) var scaleV = height / max; var factor = 0.25; var commands = [`m0,${applyScaleV(data[0])}`]; function round(val) { return Math.round(val * 1000) / 1000; } function applyScaleH(val) { return round(val * scaleH); } function applyScaleV(val) { return round(100 - val * scaleV); } for (let i = 0, max = data.length - 1; i < max; i++) { current = data[i]; next = data[i + 1]; let x = (i + 0.5); let y = current + (next - current) * 0.5 let sX = (i + (0.5 - factor)); let sY = current + (next - current) * (0.5 - factor); commands.push(`S${applyScaleH(sX)} ${applyScaleV(sY)},${applyScaleH(x)} ${applyScaleV(y)}`); } var finalY = data[data.length - 1]; commands.push(`S${width} ${applyScaleV(finalY)},${width} ${applyScaleV(finalY)}`); return commands.join(' '); }
[ "function", "getSVGGraphPathData", "(", "data", ",", "width", ",", "height", ")", "{", "var", "max", "=", "Math", ".", "max", ".", "apply", "(", "null", ",", "data", ")", ";", "var", "width", "=", "800", ";", "var", "height", "=", "100", ";", "var", "scaleH", "=", "width", "/", "(", "data", ".", "length", "-", "1", ")", "var", "scaleV", "=", "height", "/", "max", ";", "var", "factor", "=", "0.25", ";", "var", "commands", "=", "[", "`", "${", "applyScaleV", "(", "data", "[", "0", "]", ")", "}", "`", "]", ";", "function", "round", "(", "val", ")", "{", "return", "Math", ".", "round", "(", "val", "*", "1000", ")", "/", "1000", ";", "}", "function", "applyScaleH", "(", "val", ")", "{", "return", "round", "(", "val", "*", "scaleH", ")", ";", "}", "function", "applyScaleV", "(", "val", ")", "{", "return", "round", "(", "100", "-", "val", "*", "scaleV", ")", ";", "}", "for", "(", "let", "i", "=", "0", ",", "max", "=", "data", ".", "length", "-", "1", ";", "i", "<", "max", ";", "i", "++", ")", "{", "current", "=", "data", "[", "i", "]", ";", "next", "=", "data", "[", "i", "+", "1", "]", ";", "let", "x", "=", "(", "i", "+", "0.5", ")", ";", "let", "y", "=", "current", "+", "(", "next", "-", "current", ")", "*", "0.5", "let", "sX", "=", "(", "i", "+", "(", "0.5", "-", "factor", ")", ")", ";", "let", "sY", "=", "current", "+", "(", "next", "-", "current", ")", "*", "(", "0.5", "-", "factor", ")", ";", "commands", ".", "push", "(", "`", "${", "applyScaleH", "(", "sX", ")", "}", "${", "applyScaleV", "(", "sY", ")", "}", "${", "applyScaleH", "(", "x", ")", "}", "${", "applyScaleV", "(", "y", ")", "}", "`", ")", ";", "}", "var", "finalY", "=", "data", "[", "data", ".", "length", "-", "1", "]", ";", "commands", ".", "push", "(", "`", "${", "width", "}", "${", "applyScaleV", "(", "finalY", ")", "}", "${", "width", "}", "${", "applyScaleV", "(", "finalY", ")", "}", "`", ")", ";", "return", "commands", ".", "join", "(", "' '", ")", ";", "}" ]
getSVGGraphPath data converts an array of numbers to valid SVG graph path data. @param {Array} data - The data to convert to SVG graph path format. @param {Integer} width - The width of the SVG. @param {Integer} height - The height of the SVG. @return {String} The string representing the SVG path.
[ "getSVGGraphPath", "data", "converts", "an", "array", "of", "numbers", "to", "valid", "SVG", "graph", "path", "data", "." ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/functions/index.js#L308-L349
7,736
ampproject/ampstart
www/configurator/src/index.js
handleHashChange_
function handleHashChange_() { cssTranspiler.getCssWithVars(getUrlCssVars()).then(updatedStyles => { iframeManager.setStyle(updatedStyles); }).catch(error => { // Don't set the styles, log the error console.error(error); }); }
javascript
function handleHashChange_() { cssTranspiler.getCssWithVars(getUrlCssVars()).then(updatedStyles => { iframeManager.setStyle(updatedStyles); }).catch(error => { // Don't set the styles, log the error console.error(error); }); }
[ "function", "handleHashChange_", "(", ")", "{", "cssTranspiler", ".", "getCssWithVars", "(", "getUrlCssVars", "(", ")", ")", ".", "then", "(", "updatedStyles", "=>", "{", "iframeManager", ".", "setStyle", "(", "updatedStyles", ")", ";", "}", ")", ".", "catch", "(", "error", "=>", "{", "// Don't set the styles, log the error", "console", ".", "error", "(", "error", ")", ";", "}", ")", ";", "}" ]
Function to handle URL hash changes. This is not used until the initialization of the configurator is completed. Also, this will simply get the latest URL params, pass them to the transpiler, and set the styles in the iframe manager.
[ "Function", "to", "handle", "URL", "hash", "changes", ".", "This", "is", "not", "used", "until", "the", "initialization", "of", "the", "configurator", "is", "completed", ".", "Also", "this", "will", "simply", "get", "the", "latest", "URL", "params", "pass", "them", "to", "the", "transpiler", "and", "set", "the", "styles", "in", "the", "iframe", "manager", "." ]
40c3d7750f3406ab3e73cf0b31e99987dfd89506
https://github.com/ampproject/ampstart/blob/40c3d7750f3406ab3e73cf0b31e99987dfd89506/www/configurator/src/index.js#L92-L99
7,737
clientIO/joint
plugins/layout/ports/joint.layout.port.js
argPoint
function argPoint(bbox, args) { var x = args.x; if (util.isString(x)) { x = parseFloat(x) / 100 * bbox.width; } var y = args.y; if (util.isString(y)) { y = parseFloat(y) / 100 * bbox.height; } return g.point(x || 0, y || 0); }
javascript
function argPoint(bbox, args) { var x = args.x; if (util.isString(x)) { x = parseFloat(x) / 100 * bbox.width; } var y = args.y; if (util.isString(y)) { y = parseFloat(y) / 100 * bbox.height; } return g.point(x || 0, y || 0); }
[ "function", "argPoint", "(", "bbox", ",", "args", ")", "{", "var", "x", "=", "args", ".", "x", ";", "if", "(", "util", ".", "isString", "(", "x", ")", ")", "{", "x", "=", "parseFloat", "(", "x", ")", "/", "100", "*", "bbox", ".", "width", ";", "}", "var", "y", "=", "args", ".", "y", ";", "if", "(", "util", ".", "isString", "(", "y", ")", ")", "{", "y", "=", "parseFloat", "(", "y", ")", "/", "100", "*", "bbox", ".", "height", ";", "}", "return", "g", ".", "point", "(", "x", "||", "0", ",", "y", "||", "0", ")", ";", "}" ]
Creates a point stored in arguments
[ "Creates", "a", "point", "stored", "in", "arguments" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/layout/ports/joint.layout.port.js#L56-L69
7,738
clientIO/joint
plugins/connectors/joint.connectors.jumpover.js
findLineIntersections
function findLineIntersections(line, crossCheckLines) { return util.toArray(crossCheckLines).reduce(function(res, crossCheckLine) { var intersection = line.intersection(crossCheckLine); if (intersection) { res.push(intersection); } return res; }, []); }
javascript
function findLineIntersections(line, crossCheckLines) { return util.toArray(crossCheckLines).reduce(function(res, crossCheckLine) { var intersection = line.intersection(crossCheckLine); if (intersection) { res.push(intersection); } return res; }, []); }
[ "function", "findLineIntersections", "(", "line", ",", "crossCheckLines", ")", "{", "return", "util", ".", "toArray", "(", "crossCheckLines", ")", ".", "reduce", "(", "function", "(", "res", ",", "crossCheckLine", ")", "{", "var", "intersection", "=", "line", ".", "intersection", "(", "crossCheckLine", ")", ";", "if", "(", "intersection", ")", "{", "res", ".", "push", "(", "intersection", ")", ";", "}", "return", "res", ";", "}", ",", "[", "]", ")", ";", "}" ]
Utility function to collect all intersection poinst of a single line against group of other lines. @param {g.line} line where to find points @param {g.line[]} crossCheckLines lines to cross @return {g.point[]} list of intersection points
[ "Utility", "function", "to", "collect", "all", "intersection", "poinst", "of", "a", "single", "line", "against", "group", "of", "other", "lines", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/connectors/joint.connectors.jumpover.js#L79-L87
7,739
clientIO/joint
plugins/connectors/joint.connectors.jumpover.js
createJumps
function createJumps(line, intersections, jumpSize) { return intersections.reduce(function(resultLines, point, idx) { // skipping points that were merged with the previous line // to make bigger arc over multiple lines that are close to each other if (point.skip === true) { return resultLines; } // always grab the last line from buffer and modify it var lastLine = resultLines.pop() || line; // calculate start and end of jump by moving by a given size of jump var jumpStart = g.point(point).move(lastLine.start, -(jumpSize)); var jumpEnd = g.point(point).move(lastLine.start, +(jumpSize)); // now try to look at the next intersection point var nextPoint = intersections[idx + 1]; if (nextPoint != null) { var distance = jumpEnd.distance(nextPoint); if (distance <= jumpSize) { // next point is close enough, move the jump end by this // difference and mark the next point to be skipped jumpEnd = nextPoint.move(lastLine.start, distance); nextPoint.skip = true; } } else { // this block is inside of `else` as an optimization so the distance is // not calculated when we know there are no other intersection points var endDistance = jumpStart.distance(lastLine.end); // if the end is too close to possible jump, draw remaining line instead of a jump if (endDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { resultLines.push(lastLine); return resultLines; } } var startDistance = jumpEnd.distance(lastLine.start); if (startDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { // if the start of line is too close to jump, draw that line instead of a jump resultLines.push(lastLine); return resultLines; } // finally create a jump line var jumpLine = g.line(jumpStart, jumpEnd); // it's just simple line but with a `isJump` property jumpLine.isJump = true; resultLines.push( g.line(lastLine.start, jumpStart), jumpLine, g.line(jumpEnd, lastLine.end) ); return resultLines; }, []); }
javascript
function createJumps(line, intersections, jumpSize) { return intersections.reduce(function(resultLines, point, idx) { // skipping points that were merged with the previous line // to make bigger arc over multiple lines that are close to each other if (point.skip === true) { return resultLines; } // always grab the last line from buffer and modify it var lastLine = resultLines.pop() || line; // calculate start and end of jump by moving by a given size of jump var jumpStart = g.point(point).move(lastLine.start, -(jumpSize)); var jumpEnd = g.point(point).move(lastLine.start, +(jumpSize)); // now try to look at the next intersection point var nextPoint = intersections[idx + 1]; if (nextPoint != null) { var distance = jumpEnd.distance(nextPoint); if (distance <= jumpSize) { // next point is close enough, move the jump end by this // difference and mark the next point to be skipped jumpEnd = nextPoint.move(lastLine.start, distance); nextPoint.skip = true; } } else { // this block is inside of `else` as an optimization so the distance is // not calculated when we know there are no other intersection points var endDistance = jumpStart.distance(lastLine.end); // if the end is too close to possible jump, draw remaining line instead of a jump if (endDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { resultLines.push(lastLine); return resultLines; } } var startDistance = jumpEnd.distance(lastLine.start); if (startDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { // if the start of line is too close to jump, draw that line instead of a jump resultLines.push(lastLine); return resultLines; } // finally create a jump line var jumpLine = g.line(jumpStart, jumpEnd); // it's just simple line but with a `isJump` property jumpLine.isJump = true; resultLines.push( g.line(lastLine.start, jumpStart), jumpLine, g.line(jumpEnd, lastLine.end) ); return resultLines; }, []); }
[ "function", "createJumps", "(", "line", ",", "intersections", ",", "jumpSize", ")", "{", "return", "intersections", ".", "reduce", "(", "function", "(", "resultLines", ",", "point", ",", "idx", ")", "{", "// skipping points that were merged with the previous line", "// to make bigger arc over multiple lines that are close to each other", "if", "(", "point", ".", "skip", "===", "true", ")", "{", "return", "resultLines", ";", "}", "// always grab the last line from buffer and modify it", "var", "lastLine", "=", "resultLines", ".", "pop", "(", ")", "||", "line", ";", "// calculate start and end of jump by moving by a given size of jump", "var", "jumpStart", "=", "g", ".", "point", "(", "point", ")", ".", "move", "(", "lastLine", ".", "start", ",", "-", "(", "jumpSize", ")", ")", ";", "var", "jumpEnd", "=", "g", ".", "point", "(", "point", ")", ".", "move", "(", "lastLine", ".", "start", ",", "+", "(", "jumpSize", ")", ")", ";", "// now try to look at the next intersection point", "var", "nextPoint", "=", "intersections", "[", "idx", "+", "1", "]", ";", "if", "(", "nextPoint", "!=", "null", ")", "{", "var", "distance", "=", "jumpEnd", ".", "distance", "(", "nextPoint", ")", ";", "if", "(", "distance", "<=", "jumpSize", ")", "{", "// next point is close enough, move the jump end by this", "// difference and mark the next point to be skipped", "jumpEnd", "=", "nextPoint", ".", "move", "(", "lastLine", ".", "start", ",", "distance", ")", ";", "nextPoint", ".", "skip", "=", "true", ";", "}", "}", "else", "{", "// this block is inside of `else` as an optimization so the distance is", "// not calculated when we know there are no other intersection points", "var", "endDistance", "=", "jumpStart", ".", "distance", "(", "lastLine", ".", "end", ")", ";", "// if the end is too close to possible jump, draw remaining line instead of a jump", "if", "(", "endDistance", "<", "jumpSize", "*", "2", "+", "CLOSE_PROXIMITY_PADDING", ")", "{", "resultLines", ".", "push", "(", "lastLine", ")", ";", "return", "resultLines", ";", "}", "}", "var", "startDistance", "=", "jumpEnd", ".", "distance", "(", "lastLine", ".", "start", ")", ";", "if", "(", "startDistance", "<", "jumpSize", "*", "2", "+", "CLOSE_PROXIMITY_PADDING", ")", "{", "// if the start of line is too close to jump, draw that line instead of a jump", "resultLines", ".", "push", "(", "lastLine", ")", ";", "return", "resultLines", ";", "}", "// finally create a jump line", "var", "jumpLine", "=", "g", ".", "line", "(", "jumpStart", ",", "jumpEnd", ")", ";", "// it's just simple line but with a `isJump` property", "jumpLine", ".", "isJump", "=", "true", ";", "resultLines", ".", "push", "(", "g", ".", "line", "(", "lastLine", ".", "start", ",", "jumpStart", ")", ",", "jumpLine", ",", "g", ".", "line", "(", "jumpEnd", ",", "lastLine", ".", "end", ")", ")", ";", "return", "resultLines", ";", "}", ",", "[", "]", ")", ";", "}" ]
Split input line into multiple based on intersection points. @param {g.line} line input line to split @param {g.point[]} intersections poinst where to split the line @param {number} jumpSize the size of jump arc (length empty spot on a line) @return {g.line[]} list of lines being split
[ "Split", "input", "line", "into", "multiple", "based", "on", "intersection", "points", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/connectors/joint.connectors.jumpover.js#L106-L161
7,740
clientIO/joint
plugins/routers/joint.routers.manhattan.js
function() { var step = this.step; return { x: -step, y: -step, width: 2 * step, height: 2 * step }; }
javascript
function() { var step = this.step; return { x: -step, y: -step, width: 2 * step, height: 2 * step }; }
[ "function", "(", ")", "{", "var", "step", "=", "this", ".", "step", ";", "return", "{", "x", ":", "-", "step", ",", "y", ":", "-", "step", ",", "width", ":", "2", "*", "step", ",", "height", ":", "2", "*", "step", "}", ";", "}" ]
padding applied on the element bounding boxes
[ "padding", "applied", "on", "the", "element", "bounding", "boxes" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L77-L87
7,741
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getTargetBBox
function getTargetBBox(linkView, opt) { // expand by padding box if (opt && opt.paddingBox) return linkView.targetBBox.clone().moveAndExpand(opt.paddingBox); return linkView.targetBBox.clone(); }
javascript
function getTargetBBox(linkView, opt) { // expand by padding box if (opt && opt.paddingBox) return linkView.targetBBox.clone().moveAndExpand(opt.paddingBox); return linkView.targetBBox.clone(); }
[ "function", "getTargetBBox", "(", "linkView", ",", "opt", ")", "{", "// expand by padding box", "if", "(", "opt", "&&", "opt", ".", "paddingBox", ")", "return", "linkView", ".", "targetBBox", ".", "clone", "(", ")", ".", "moveAndExpand", "(", "opt", ".", "paddingBox", ")", ";", "return", "linkView", ".", "targetBBox", ".", "clone", "(", ")", ";", "}" ]
return target bbox
[ "return", "target", "bbox" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L276-L282
7,742
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getSourceAnchor
function getSourceAnchor(linkView, opt) { if (linkView.sourceAnchor) return linkView.sourceAnchor; // fallback: center of bbox var sourceBBox = getSourceBBox(linkView, opt); return sourceBBox.center(); }
javascript
function getSourceAnchor(linkView, opt) { if (linkView.sourceAnchor) return linkView.sourceAnchor; // fallback: center of bbox var sourceBBox = getSourceBBox(linkView, opt); return sourceBBox.center(); }
[ "function", "getSourceAnchor", "(", "linkView", ",", "opt", ")", "{", "if", "(", "linkView", ".", "sourceAnchor", ")", "return", "linkView", ".", "sourceAnchor", ";", "// fallback: center of bbox", "var", "sourceBBox", "=", "getSourceBBox", "(", "linkView", ",", "opt", ")", ";", "return", "sourceBBox", ".", "center", "(", ")", ";", "}" ]
return source anchor
[ "return", "source", "anchor" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L285-L292
7,743
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getTargetAnchor
function getTargetAnchor(linkView, opt) { if (linkView.targetAnchor) return linkView.targetAnchor; // fallback: center of bbox var targetBBox = getTargetBBox(linkView, opt); return targetBBox.center(); // default }
javascript
function getTargetAnchor(linkView, opt) { if (linkView.targetAnchor) return linkView.targetAnchor; // fallback: center of bbox var targetBBox = getTargetBBox(linkView, opt); return targetBBox.center(); // default }
[ "function", "getTargetAnchor", "(", "linkView", ",", "opt", ")", "{", "if", "(", "linkView", ".", "targetAnchor", ")", "return", "linkView", ".", "targetAnchor", ";", "// fallback: center of bbox", "var", "targetBBox", "=", "getTargetBBox", "(", "linkView", ",", "opt", ")", ";", "return", "targetBBox", ".", "center", "(", ")", ";", "// default", "}" ]
return target anchor
[ "return", "target", "anchor" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L295-L302
7,744
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getDirectionAngle
function getDirectionAngle(start, end, numDirections, grid, opt) { var quadrant = 360 / numDirections; var angleTheta = start.theta(fixAngleEnd(start, end, grid, opt)); var normalizedAngle = g.normalizeAngle(angleTheta + (quadrant / 2)); return quadrant * Math.floor(normalizedAngle / quadrant); }
javascript
function getDirectionAngle(start, end, numDirections, grid, opt) { var quadrant = 360 / numDirections; var angleTheta = start.theta(fixAngleEnd(start, end, grid, opt)); var normalizedAngle = g.normalizeAngle(angleTheta + (quadrant / 2)); return quadrant * Math.floor(normalizedAngle / quadrant); }
[ "function", "getDirectionAngle", "(", "start", ",", "end", ",", "numDirections", ",", "grid", ",", "opt", ")", "{", "var", "quadrant", "=", "360", "/", "numDirections", ";", "var", "angleTheta", "=", "start", ".", "theta", "(", "fixAngleEnd", "(", "start", ",", "end", ",", "grid", ",", "opt", ")", ")", ";", "var", "normalizedAngle", "=", "g", ".", "normalizeAngle", "(", "angleTheta", "+", "(", "quadrant", "/", "2", ")", ")", ";", "return", "quadrant", "*", "Math", ".", "floor", "(", "normalizedAngle", "/", "quadrant", ")", ";", "}" ]
returns a direction index from start point to end point corrects for grid deformation between start and end
[ "returns", "a", "direction", "index", "from", "start", "point", "to", "end", "point", "corrects", "for", "grid", "deformation", "between", "start", "and", "end" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L306-L312
7,745
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getDirectionChange
function getDirectionChange(angle1, angle2) { var directionChange = Math.abs(angle1 - angle2); return (directionChange > 180) ? (360 - directionChange) : directionChange; }
javascript
function getDirectionChange(angle1, angle2) { var directionChange = Math.abs(angle1 - angle2); return (directionChange > 180) ? (360 - directionChange) : directionChange; }
[ "function", "getDirectionChange", "(", "angle1", ",", "angle2", ")", "{", "var", "directionChange", "=", "Math", ".", "abs", "(", "angle1", "-", "angle2", ")", ";", "return", "(", "directionChange", ">", "180", ")", "?", "(", "360", "-", "directionChange", ")", ":", "directionChange", ";", "}" ]
return the change in direction between two direction angles
[ "return", "the", "change", "in", "direction", "between", "two", "direction", "angles" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L336-L340
7,746
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getGridOffsets
function getGridOffsets(directions, grid, opt) { var step = opt.step; util.toArray(opt.directions).forEach(function(direction) { direction.gridOffsetX = (direction.offsetX / step) * grid.x; direction.gridOffsetY = (direction.offsetY / step) * grid.y; }); }
javascript
function getGridOffsets(directions, grid, opt) { var step = opt.step; util.toArray(opt.directions).forEach(function(direction) { direction.gridOffsetX = (direction.offsetX / step) * grid.x; direction.gridOffsetY = (direction.offsetY / step) * grid.y; }); }
[ "function", "getGridOffsets", "(", "directions", ",", "grid", ",", "opt", ")", "{", "var", "step", "=", "opt", ".", "step", ";", "util", ".", "toArray", "(", "opt", ".", "directions", ")", ".", "forEach", "(", "function", "(", "direction", ")", "{", "direction", ".", "gridOffsetX", "=", "(", "direction", ".", "offsetX", "/", "step", ")", "*", "grid", ".", "x", ";", "direction", ".", "gridOffsetY", "=", "(", "direction", ".", "offsetY", "/", "step", ")", "*", "grid", ".", "y", ";", "}", ")", ";", "}" ]
fix direction offsets according to current grid
[ "fix", "direction", "offsets", "according", "to", "current", "grid" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L343-L352
7,747
clientIO/joint
plugins/routers/joint.routers.manhattan.js
getGrid
function getGrid(step, source, target) { return { source: source.clone(), x: getGridDimension(target.x - source.x, step), y: getGridDimension(target.y - source.y, step) }; }
javascript
function getGrid(step, source, target) { return { source: source.clone(), x: getGridDimension(target.x - source.x, step), y: getGridDimension(target.y - source.y, step) }; }
[ "function", "getGrid", "(", "step", ",", "source", ",", "target", ")", "{", "return", "{", "source", ":", "source", ".", "clone", "(", ")", ",", "x", ":", "getGridDimension", "(", "target", ".", "x", "-", "source", ".", "x", ",", "step", ")", ",", "y", ":", "getGridDimension", "(", "target", ".", "y", "-", "source", ".", "y", ",", "step", ")", "}", ";", "}" ]
get grid size in x and y dimensions, adapted to source and target positions
[ "get", "grid", "size", "in", "x", "and", "y", "dimensions", "adapted", "to", "source", "and", "target", "positions" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L355-L362
7,748
clientIO/joint
plugins/routers/joint.routers.manhattan.js
snapToGrid
function snapToGrid(point, grid) { var source = grid.source; var snappedX = g.snapToGrid(point.x - source.x, grid.x) + source.x; var snappedY = g.snapToGrid(point.y - source.y, grid.y) + source.y; return new g.Point(snappedX, snappedY); }
javascript
function snapToGrid(point, grid) { var source = grid.source; var snappedX = g.snapToGrid(point.x - source.x, grid.x) + source.x; var snappedY = g.snapToGrid(point.y - source.y, grid.y) + source.y; return new g.Point(snappedX, snappedY); }
[ "function", "snapToGrid", "(", "point", ",", "grid", ")", "{", "var", "source", "=", "grid", ".", "source", ";", "var", "snappedX", "=", "g", ".", "snapToGrid", "(", "point", ".", "x", "-", "source", ".", "x", ",", "grid", ".", "x", ")", "+", "source", ".", "x", ";", "var", "snappedY", "=", "g", ".", "snapToGrid", "(", "point", ".", "y", "-", "source", ".", "y", ",", "grid", ".", "y", ")", "+", "source", ".", "y", ";", "return", "new", "g", ".", "Point", "(", "snappedX", ",", "snappedY", ")", ";", "}" ]
return a clone of point snapped to grid
[ "return", "a", "clone", "of", "point", "snapped", "to", "grid" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L385-L393
7,749
clientIO/joint
plugins/routers/joint.routers.manhattan.js
align
function align(point, grid, precision) { return round(snapToGrid(point.clone(), grid), precision); }
javascript
function align(point, grid, precision) { return round(snapToGrid(point.clone(), grid), precision); }
[ "function", "align", "(", "point", ",", "grid", ",", "precision", ")", "{", "return", "round", "(", "snapToGrid", "(", "point", ".", "clone", "(", ")", ",", "grid", ")", ",", "precision", ")", ";", "}" ]
snap to grid and then round the point
[ "snap", "to", "grid", "and", "then", "round", "the", "point" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L402-L405
7,750
clientIO/joint
plugins/routers/joint.routers.manhattan.js
normalizePoint
function normalizePoint(point) { return new g.Point( point.x === 0 ? 0 : Math.abs(point.x) / point.x, point.y === 0 ? 0 : Math.abs(point.y) / point.y ); }
javascript
function normalizePoint(point) { return new g.Point( point.x === 0 ? 0 : Math.abs(point.x) / point.x, point.y === 0 ? 0 : Math.abs(point.y) / point.y ); }
[ "function", "normalizePoint", "(", "point", ")", "{", "return", "new", "g", ".", "Point", "(", "point", ".", "x", "===", "0", "?", "0", ":", "Math", ".", "abs", "(", "point", ".", "x", ")", "/", "point", ".", "x", ",", "point", ".", "y", "===", "0", "?", "0", ":", "Math", ".", "abs", "(", "point", ".", "y", ")", "/", "point", ".", "y", ")", ";", "}" ]
return a normalized vector from given point used to determine the direction of a difference of two points
[ "return", "a", "normalized", "vector", "from", "given", "point", "used", "to", "determine", "the", "direction", "of", "a", "difference", "of", "two", "points" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L416-L422
7,751
clientIO/joint
plugins/routers/joint.routers.manhattan.js
estimateCost
function estimateCost(from, endPoints) { var min = Infinity; for (var i = 0, len = endPoints.length; i < len; i++) { var cost = from.manhattanDistance(endPoints[i]); if (cost < min) min = cost; } return min; }
javascript
function estimateCost(from, endPoints) { var min = Infinity; for (var i = 0, len = endPoints.length; i < len; i++) { var cost = from.manhattanDistance(endPoints[i]); if (cost < min) min = cost; } return min; }
[ "function", "estimateCost", "(", "from", ",", "endPoints", ")", "{", "var", "min", "=", "Infinity", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "endPoints", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "cost", "=", "from", ".", "manhattanDistance", "(", "endPoints", "[", "i", "]", ")", ";", "if", "(", "cost", "<", "min", ")", "min", "=", "cost", ";", "}", "return", "min", ";", "}" ]
heuristic method to determine the distance between two points
[ "heuristic", "method", "to", "determine", "the", "distance", "between", "two", "points" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L466-L476
7,752
clientIO/joint
plugins/routers/joint.routers.manhattan.js
resolveOptions
function resolveOptions(opt) { opt.directions = util.result(opt, 'directions'); opt.penalties = util.result(opt, 'penalties'); opt.paddingBox = util.result(opt, 'paddingBox'); opt.padding = util.result(opt, 'padding'); if (opt.padding) { // if both provided, opt.padding wins over opt.paddingBox var sides = util.normalizeSides(opt.padding); opt.paddingBox = { x: -sides.left, y: -sides.top, width: sides.left + sides.right, height: sides.top + sides.bottom }; } util.toArray(opt.directions).forEach(function(direction) { var point1 = new g.Point(0, 0); var point2 = new g.Point(direction.offsetX, direction.offsetY); direction.angle = g.normalizeAngle(point1.theta(point2)); }); }
javascript
function resolveOptions(opt) { opt.directions = util.result(opt, 'directions'); opt.penalties = util.result(opt, 'penalties'); opt.paddingBox = util.result(opt, 'paddingBox'); opt.padding = util.result(opt, 'padding'); if (opt.padding) { // if both provided, opt.padding wins over opt.paddingBox var sides = util.normalizeSides(opt.padding); opt.paddingBox = { x: -sides.left, y: -sides.top, width: sides.left + sides.right, height: sides.top + sides.bottom }; } util.toArray(opt.directions).forEach(function(direction) { var point1 = new g.Point(0, 0); var point2 = new g.Point(direction.offsetX, direction.offsetY); direction.angle = g.normalizeAngle(point1.theta(point2)); }); }
[ "function", "resolveOptions", "(", "opt", ")", "{", "opt", ".", "directions", "=", "util", ".", "result", "(", "opt", ",", "'directions'", ")", ";", "opt", ".", "penalties", "=", "util", ".", "result", "(", "opt", ",", "'penalties'", ")", ";", "opt", ".", "paddingBox", "=", "util", ".", "result", "(", "opt", ",", "'paddingBox'", ")", ";", "opt", ".", "padding", "=", "util", ".", "result", "(", "opt", ",", "'padding'", ")", ";", "if", "(", "opt", ".", "padding", ")", "{", "// if both provided, opt.padding wins over opt.paddingBox", "var", "sides", "=", "util", ".", "normalizeSides", "(", "opt", ".", "padding", ")", ";", "opt", ".", "paddingBox", "=", "{", "x", ":", "-", "sides", ".", "left", ",", "y", ":", "-", "sides", ".", "top", ",", "width", ":", "sides", ".", "left", "+", "sides", ".", "right", ",", "height", ":", "sides", ".", "top", "+", "sides", ".", "bottom", "}", ";", "}", "util", ".", "toArray", "(", "opt", ".", "directions", ")", ".", "forEach", "(", "function", "(", "direction", ")", "{", "var", "point1", "=", "new", "g", ".", "Point", "(", "0", ",", "0", ")", ";", "var", "point2", "=", "new", "g", ".", "Point", "(", "direction", ".", "offsetX", ",", "direction", ".", "offsetY", ")", ";", "direction", ".", "angle", "=", "g", ".", "normalizeAngle", "(", "point1", ".", "theta", "(", "point2", ")", ")", ";", "}", ")", ";", "}" ]
resolve some of the options
[ "resolve", "some", "of", "the", "options" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L725-L750
7,753
clientIO/joint
plugins/routers/joint.routers.manhattan.js
router
function router(vertices, opt, linkView) { resolveOptions(opt); // enable/disable linkView perpendicular option linkView.options.perpendicular = !!opt.perpendicular; var sourceBBox = getSourceBBox(linkView, opt); var targetBBox = getTargetBBox(linkView, opt); var sourceAnchor = getSourceAnchor(linkView, opt); //var targetAnchor = getTargetAnchor(linkView, opt); // pathfinding var map = (new ObstacleMap(opt)).build(linkView.paper.model, linkView.model); var oldVertices = util.toArray(vertices).map(g.Point); var newVertices = []; var tailPoint = sourceAnchor; // the origin of first route's grid, does not need snapping // find a route by concatenating all partial routes (routes need to pass through vertices) // source -> vertex[1] -> ... -> vertex[n] -> target var to, from; for (var i = 0, len = oldVertices.length; i <= len; i++) { var partialRoute = null; from = to || sourceBBox; to = oldVertices[i]; if (!to) { // this is the last iteration // we ran through all vertices in oldVertices // 'to' is not a vertex. to = targetBBox; // If the target is a point (i.e. it's not an element), we // should use dragging route instead of main routing method if it has been provided. var isEndingAtPoint = !linkView.model.get('source').id || !linkView.model.get('target').id; if (isEndingAtPoint && util.isFunction(opt.draggingRoute)) { // Make sure we are passing points only (not rects). var dragFrom = (from === sourceBBox) ? sourceAnchor : from; var dragTo = to.origin(); partialRoute = opt.draggingRoute.call(linkView, dragFrom, dragTo, opt); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute.call(linkView, from, to, map, opt); if (partialRoute === null) { // the partial route cannot be found return opt.fallbackRouter(vertices, opt, linkView); } var leadPoint = partialRoute[0]; // remove the first point if the previous partial route had the same point as last if (leadPoint && leadPoint.equals(tailPoint)) partialRoute.shift(); // save tailPoint for next iteration tailPoint = partialRoute[partialRoute.length - 1] || tailPoint; Array.prototype.push.apply(newVertices, partialRoute); } return newVertices; }
javascript
function router(vertices, opt, linkView) { resolveOptions(opt); // enable/disable linkView perpendicular option linkView.options.perpendicular = !!opt.perpendicular; var sourceBBox = getSourceBBox(linkView, opt); var targetBBox = getTargetBBox(linkView, opt); var sourceAnchor = getSourceAnchor(linkView, opt); //var targetAnchor = getTargetAnchor(linkView, opt); // pathfinding var map = (new ObstacleMap(opt)).build(linkView.paper.model, linkView.model); var oldVertices = util.toArray(vertices).map(g.Point); var newVertices = []; var tailPoint = sourceAnchor; // the origin of first route's grid, does not need snapping // find a route by concatenating all partial routes (routes need to pass through vertices) // source -> vertex[1] -> ... -> vertex[n] -> target var to, from; for (var i = 0, len = oldVertices.length; i <= len; i++) { var partialRoute = null; from = to || sourceBBox; to = oldVertices[i]; if (!to) { // this is the last iteration // we ran through all vertices in oldVertices // 'to' is not a vertex. to = targetBBox; // If the target is a point (i.e. it's not an element), we // should use dragging route instead of main routing method if it has been provided. var isEndingAtPoint = !linkView.model.get('source').id || !linkView.model.get('target').id; if (isEndingAtPoint && util.isFunction(opt.draggingRoute)) { // Make sure we are passing points only (not rects). var dragFrom = (from === sourceBBox) ? sourceAnchor : from; var dragTo = to.origin(); partialRoute = opt.draggingRoute.call(linkView, dragFrom, dragTo, opt); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute.call(linkView, from, to, map, opt); if (partialRoute === null) { // the partial route cannot be found return opt.fallbackRouter(vertices, opt, linkView); } var leadPoint = partialRoute[0]; // remove the first point if the previous partial route had the same point as last if (leadPoint && leadPoint.equals(tailPoint)) partialRoute.shift(); // save tailPoint for next iteration tailPoint = partialRoute[partialRoute.length - 1] || tailPoint; Array.prototype.push.apply(newVertices, partialRoute); } return newVertices; }
[ "function", "router", "(", "vertices", ",", "opt", ",", "linkView", ")", "{", "resolveOptions", "(", "opt", ")", ";", "// enable/disable linkView perpendicular option", "linkView", ".", "options", ".", "perpendicular", "=", "!", "!", "opt", ".", "perpendicular", ";", "var", "sourceBBox", "=", "getSourceBBox", "(", "linkView", ",", "opt", ")", ";", "var", "targetBBox", "=", "getTargetBBox", "(", "linkView", ",", "opt", ")", ";", "var", "sourceAnchor", "=", "getSourceAnchor", "(", "linkView", ",", "opt", ")", ";", "//var targetAnchor = getTargetAnchor(linkView, opt);", "// pathfinding", "var", "map", "=", "(", "new", "ObstacleMap", "(", "opt", ")", ")", ".", "build", "(", "linkView", ".", "paper", ".", "model", ",", "linkView", ".", "model", ")", ";", "var", "oldVertices", "=", "util", ".", "toArray", "(", "vertices", ")", ".", "map", "(", "g", ".", "Point", ")", ";", "var", "newVertices", "=", "[", "]", ";", "var", "tailPoint", "=", "sourceAnchor", ";", "// the origin of first route's grid, does not need snapping", "// find a route by concatenating all partial routes (routes need to pass through vertices)", "// source -> vertex[1] -> ... -> vertex[n] -> target", "var", "to", ",", "from", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "oldVertices", ".", "length", ";", "i", "<=", "len", ";", "i", "++", ")", "{", "var", "partialRoute", "=", "null", ";", "from", "=", "to", "||", "sourceBBox", ";", "to", "=", "oldVertices", "[", "i", "]", ";", "if", "(", "!", "to", ")", "{", "// this is the last iteration", "// we ran through all vertices in oldVertices", "// 'to' is not a vertex.", "to", "=", "targetBBox", ";", "// If the target is a point (i.e. it's not an element), we", "// should use dragging route instead of main routing method if it has been provided.", "var", "isEndingAtPoint", "=", "!", "linkView", ".", "model", ".", "get", "(", "'source'", ")", ".", "id", "||", "!", "linkView", ".", "model", ".", "get", "(", "'target'", ")", ".", "id", ";", "if", "(", "isEndingAtPoint", "&&", "util", ".", "isFunction", "(", "opt", ".", "draggingRoute", ")", ")", "{", "// Make sure we are passing points only (not rects).", "var", "dragFrom", "=", "(", "from", "===", "sourceBBox", ")", "?", "sourceAnchor", ":", "from", ";", "var", "dragTo", "=", "to", ".", "origin", "(", ")", ";", "partialRoute", "=", "opt", ".", "draggingRoute", ".", "call", "(", "linkView", ",", "dragFrom", ",", "dragTo", ",", "opt", ")", ";", "}", "}", "// if partial route has not been calculated yet use the main routing method to find one", "partialRoute", "=", "partialRoute", "||", "findRoute", ".", "call", "(", "linkView", ",", "from", ",", "to", ",", "map", ",", "opt", ")", ";", "if", "(", "partialRoute", "===", "null", ")", "{", "// the partial route cannot be found", "return", "opt", ".", "fallbackRouter", "(", "vertices", ",", "opt", ",", "linkView", ")", ";", "}", "var", "leadPoint", "=", "partialRoute", "[", "0", "]", ";", "// remove the first point if the previous partial route had the same point as last", "if", "(", "leadPoint", "&&", "leadPoint", ".", "equals", "(", "tailPoint", ")", ")", "partialRoute", ".", "shift", "(", ")", ";", "// save tailPoint for next iteration", "tailPoint", "=", "partialRoute", "[", "partialRoute", ".", "length", "-", "1", "]", "||", "tailPoint", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "newVertices", ",", "partialRoute", ")", ";", "}", "return", "newVertices", ";", "}" ]
initialization of the route finding
[ "initialization", "of", "the", "route", "finding" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/plugins/routers/joint.routers.manhattan.js#L753-L822
7,754
clientIO/joint
dist/joint.nowrap.js
TypedArray
function TypedArray(arg1) { var result; if (typeof arg1 === 'number') { result = new Array(arg1); for (var i = 0; i < arg1; ++i) { result[i] = 0; } } else { result = arg1.slice(0); } result.subarray = subarray; result.buffer = result; result.byteLength = result.length; result.set = set_; if (typeof arg1 === 'object' && arg1.buffer) { result.buffer = arg1.buffer; } return result; }
javascript
function TypedArray(arg1) { var result; if (typeof arg1 === 'number') { result = new Array(arg1); for (var i = 0; i < arg1; ++i) { result[i] = 0; } } else { result = arg1.slice(0); } result.subarray = subarray; result.buffer = result; result.byteLength = result.length; result.set = set_; if (typeof arg1 === 'object' && arg1.buffer) { result.buffer = arg1.buffer; } return result; }
[ "function", "TypedArray", "(", "arg1", ")", "{", "var", "result", ";", "if", "(", "typeof", "arg1", "===", "'number'", ")", "{", "result", "=", "new", "Array", "(", "arg1", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arg1", ";", "++", "i", ")", "{", "result", "[", "i", "]", "=", "0", ";", "}", "}", "else", "{", "result", "=", "arg1", ".", "slice", "(", "0", ")", ";", "}", "result", ".", "subarray", "=", "subarray", ";", "result", ".", "buffer", "=", "result", ";", "result", ".", "byteLength", "=", "result", ".", "length", ";", "result", ".", "set", "=", "set_", ";", "if", "(", "typeof", "arg1", "===", "'object'", "&&", "arg1", ".", "buffer", ")", "{", "result", ".", "buffer", "=", "arg1", ".", "buffer", ";", "}", "return", "result", ";", "}" ]
we need typed arrays
[ "we", "need", "typed", "arrays" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L98-L118
7,755
clientIO/joint
dist/joint.nowrap.js
function(knots) { console.warn('deprecated'); var firstControlPoints = []; var secondControlPoints = []; var n = knots.length - 1; var i; // Special case: Bezier curve should be a straight line. if (n == 1) { // 3P1 = 2P0 + P3 firstControlPoints[0] = new Point( (2 * knots[0].x + knots[1].x) / 3, (2 * knots[0].y + knots[1].y) / 3 ); // P2 = 2P1 – P0 secondControlPoints[0] = new Point( 2 * firstControlPoints[0].x - knots[0].x, 2 * firstControlPoints[0].y - knots[0].y ); return [firstControlPoints, secondControlPoints]; } // Calculate first Bezier control points. // Right hand side vector. var rhs = []; // Set right hand side X values. for (i = 1; i < n - 1; i++) { rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x; } rhs[0] = knots[0].x + 2 * knots[1].x; rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0; // Get first control points X-values. var x = this.getFirstControlPoints(rhs); // Set right hand side Y values. for (i = 1; i < n - 1; ++i) { rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y; } rhs[0] = knots[0].y + 2 * knots[1].y; rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0; // Get first control points Y-values. var y = this.getFirstControlPoints(rhs); // Fill output arrays. for (i = 0; i < n; i++) { // First control point. firstControlPoints.push(new Point(x[i], y[i])); // Second control point. if (i < n - 1) { secondControlPoints.push(new Point( 2 * knots [i + 1].x - x[i + 1], 2 * knots[i + 1].y - y[i + 1] )); } else { secondControlPoints.push(new Point( (knots[n].x + x[n - 1]) / 2, (knots[n].y + y[n - 1]) / 2) ); } } return [firstControlPoints, secondControlPoints]; }
javascript
function(knots) { console.warn('deprecated'); var firstControlPoints = []; var secondControlPoints = []; var n = knots.length - 1; var i; // Special case: Bezier curve should be a straight line. if (n == 1) { // 3P1 = 2P0 + P3 firstControlPoints[0] = new Point( (2 * knots[0].x + knots[1].x) / 3, (2 * knots[0].y + knots[1].y) / 3 ); // P2 = 2P1 – P0 secondControlPoints[0] = new Point( 2 * firstControlPoints[0].x - knots[0].x, 2 * firstControlPoints[0].y - knots[0].y ); return [firstControlPoints, secondControlPoints]; } // Calculate first Bezier control points. // Right hand side vector. var rhs = []; // Set right hand side X values. for (i = 1; i < n - 1; i++) { rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x; } rhs[0] = knots[0].x + 2 * knots[1].x; rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0; // Get first control points X-values. var x = this.getFirstControlPoints(rhs); // Set right hand side Y values. for (i = 1; i < n - 1; ++i) { rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y; } rhs[0] = knots[0].y + 2 * knots[1].y; rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0; // Get first control points Y-values. var y = this.getFirstControlPoints(rhs); // Fill output arrays. for (i = 0; i < n; i++) { // First control point. firstControlPoints.push(new Point(x[i], y[i])); // Second control point. if (i < n - 1) { secondControlPoints.push(new Point( 2 * knots [i + 1].x - x[i + 1], 2 * knots[i + 1].y - y[i + 1] )); } else { secondControlPoints.push(new Point( (knots[n].x + x[n - 1]) / 2, (knots[n].y + y[n - 1]) / 2) ); } } return [firstControlPoints, secondControlPoints]; }
[ "function", "(", "knots", ")", "{", "console", ".", "warn", "(", "'deprecated'", ")", ";", "var", "firstControlPoints", "=", "[", "]", ";", "var", "secondControlPoints", "=", "[", "]", ";", "var", "n", "=", "knots", ".", "length", "-", "1", ";", "var", "i", ";", "// Special case: Bezier curve should be a straight line.", "if", "(", "n", "==", "1", ")", "{", "// 3P1 = 2P0 + P3", "firstControlPoints", "[", "0", "]", "=", "new", "Point", "(", "(", "2", "*", "knots", "[", "0", "]", ".", "x", "+", "knots", "[", "1", "]", ".", "x", ")", "/", "3", ",", "(", "2", "*", "knots", "[", "0", "]", ".", "y", "+", "knots", "[", "1", "]", ".", "y", ")", "/", "3", ")", ";", "// P2 = 2P1 – P0", "secondControlPoints", "[", "0", "]", "=", "new", "Point", "(", "2", "*", "firstControlPoints", "[", "0", "]", ".", "x", "-", "knots", "[", "0", "]", ".", "x", ",", "2", "*", "firstControlPoints", "[", "0", "]", ".", "y", "-", "knots", "[", "0", "]", ".", "y", ")", ";", "return", "[", "firstControlPoints", ",", "secondControlPoints", "]", ";", "}", "// Calculate first Bezier control points.", "// Right hand side vector.", "var", "rhs", "=", "[", "]", ";", "// Set right hand side X values.", "for", "(", "i", "=", "1", ";", "i", "<", "n", "-", "1", ";", "i", "++", ")", "{", "rhs", "[", "i", "]", "=", "4", "*", "knots", "[", "i", "]", ".", "x", "+", "2", "*", "knots", "[", "i", "+", "1", "]", ".", "x", ";", "}", "rhs", "[", "0", "]", "=", "knots", "[", "0", "]", ".", "x", "+", "2", "*", "knots", "[", "1", "]", ".", "x", ";", "rhs", "[", "n", "-", "1", "]", "=", "(", "8", "*", "knots", "[", "n", "-", "1", "]", ".", "x", "+", "knots", "[", "n", "]", ".", "x", ")", "/", "2.0", ";", "// Get first control points X-values.", "var", "x", "=", "this", ".", "getFirstControlPoints", "(", "rhs", ")", ";", "// Set right hand side Y values.", "for", "(", "i", "=", "1", ";", "i", "<", "n", "-", "1", ";", "++", "i", ")", "{", "rhs", "[", "i", "]", "=", "4", "*", "knots", "[", "i", "]", ".", "y", "+", "2", "*", "knots", "[", "i", "+", "1", "]", ".", "y", ";", "}", "rhs", "[", "0", "]", "=", "knots", "[", "0", "]", ".", "y", "+", "2", "*", "knots", "[", "1", "]", ".", "y", ";", "rhs", "[", "n", "-", "1", "]", "=", "(", "8", "*", "knots", "[", "n", "-", "1", "]", ".", "y", "+", "knots", "[", "n", "]", ".", "y", ")", "/", "2.0", ";", "// Get first control points Y-values.", "var", "y", "=", "this", ".", "getFirstControlPoints", "(", "rhs", ")", ";", "// Fill output arrays.", "for", "(", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "// First control point.", "firstControlPoints", ".", "push", "(", "new", "Point", "(", "x", "[", "i", "]", ",", "y", "[", "i", "]", ")", ")", ";", "// Second control point.", "if", "(", "i", "<", "n", "-", "1", ")", "{", "secondControlPoints", ".", "push", "(", "new", "Point", "(", "2", "*", "knots", "[", "i", "+", "1", "]", ".", "x", "-", "x", "[", "i", "+", "1", "]", ",", "2", "*", "knots", "[", "i", "+", "1", "]", ".", "y", "-", "y", "[", "i", "+", "1", "]", ")", ")", ";", "}", "else", "{", "secondControlPoints", ".", "push", "(", "new", "Point", "(", "(", "knots", "[", "n", "]", ".", "x", "+", "x", "[", "n", "-", "1", "]", ")", "/", "2", ",", "(", "knots", "[", "n", "]", ".", "y", "+", "y", "[", "n", "-", "1", "]", ")", "/", "2", ")", ")", ";", "}", "}", "return", "[", "firstControlPoints", ",", "secondControlPoints", "]", ";", "}" ]
Get open-ended Bezier Spline Control Points. @deprecated @param knots Input Knot Bezier spline points (At least two points!). @param firstControlPoints Output First Control points. Array of knots.length - 1 length. @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
[ "Get", "open", "-", "ended", "Bezier", "Spline", "Control", "Points", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L441-L514
7,756
clientIO/joint
dist/joint.nowrap.js
function(c) { return !!c && this.start.x === c.start.x && this.start.y === c.start.y && this.controlPoint1.x === c.controlPoint1.x && this.controlPoint1.y === c.controlPoint1.y && this.controlPoint2.x === c.controlPoint2.x && this.controlPoint2.y === c.controlPoint2.y && this.end.x === c.end.x && this.end.y === c.end.y; }
javascript
function(c) { return !!c && this.start.x === c.start.x && this.start.y === c.start.y && this.controlPoint1.x === c.controlPoint1.x && this.controlPoint1.y === c.controlPoint1.y && this.controlPoint2.x === c.controlPoint2.x && this.controlPoint2.y === c.controlPoint2.y && this.end.x === c.end.x && this.end.y === c.end.y; }
[ "function", "(", "c", ")", "{", "return", "!", "!", "c", "&&", "this", ".", "start", ".", "x", "===", "c", ".", "start", ".", "x", "&&", "this", ".", "start", ".", "y", "===", "c", ".", "start", ".", "y", "&&", "this", ".", "controlPoint1", ".", "x", "===", "c", ".", "controlPoint1", ".", "x", "&&", "this", ".", "controlPoint1", ".", "y", "===", "c", ".", "controlPoint1", ".", "y", "&&", "this", ".", "controlPoint2", ".", "x", "===", "c", ".", "controlPoint2", ".", "x", "&&", "this", ".", "controlPoint2", ".", "y", "===", "c", ".", "controlPoint2", ".", "y", "&&", "this", ".", "end", ".", "x", "===", "c", ".", "end", ".", "x", "&&", "this", ".", "end", ".", "y", "===", "c", ".", "end", ".", "y", ";", "}" ]
Checks whether two curves are exactly the same.
[ "Checks", "whether", "two", "curves", "are", "exactly", "the", "same", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1026-L1037
7,757
clientIO/joint
dist/joint.nowrap.js
function(t) { var start = this.start; var control1 = this.controlPoint1; var control2 = this.controlPoint2; var end = this.end; // shortcuts for `t` values that are out of range if (t <= 0) { return { startControlPoint1: start.clone(), startControlPoint2: start.clone(), divider: start.clone(), dividerControlPoint1: control1.clone(), dividerControlPoint2: control2.clone() }; } if (t >= 1) { return { startControlPoint1: control1.clone(), startControlPoint2: control2.clone(), divider: end.clone(), dividerControlPoint1: end.clone(), dividerControlPoint2: end.clone() }; } var midpoint1 = (new Line(start, control1)).pointAt(t); var midpoint2 = (new Line(control1, control2)).pointAt(t); var midpoint3 = (new Line(control2, end)).pointAt(t); var subControl1 = (new Line(midpoint1, midpoint2)).pointAt(t); var subControl2 = (new Line(midpoint2, midpoint3)).pointAt(t); var divider = (new Line(subControl1, subControl2)).pointAt(t); var output = { startControlPoint1: midpoint1, startControlPoint2: subControl1, divider: divider, dividerControlPoint1: subControl2, dividerControlPoint2: midpoint3 }; return output; }
javascript
function(t) { var start = this.start; var control1 = this.controlPoint1; var control2 = this.controlPoint2; var end = this.end; // shortcuts for `t` values that are out of range if (t <= 0) { return { startControlPoint1: start.clone(), startControlPoint2: start.clone(), divider: start.clone(), dividerControlPoint1: control1.clone(), dividerControlPoint2: control2.clone() }; } if (t >= 1) { return { startControlPoint1: control1.clone(), startControlPoint2: control2.clone(), divider: end.clone(), dividerControlPoint1: end.clone(), dividerControlPoint2: end.clone() }; } var midpoint1 = (new Line(start, control1)).pointAt(t); var midpoint2 = (new Line(control1, control2)).pointAt(t); var midpoint3 = (new Line(control2, end)).pointAt(t); var subControl1 = (new Line(midpoint1, midpoint2)).pointAt(t); var subControl2 = (new Line(midpoint2, midpoint3)).pointAt(t); var divider = (new Line(subControl1, subControl2)).pointAt(t); var output = { startControlPoint1: midpoint1, startControlPoint2: subControl1, divider: divider, dividerControlPoint1: subControl2, dividerControlPoint2: midpoint3 }; return output; }
[ "function", "(", "t", ")", "{", "var", "start", "=", "this", ".", "start", ";", "var", "control1", "=", "this", ".", "controlPoint1", ";", "var", "control2", "=", "this", ".", "controlPoint2", ";", "var", "end", "=", "this", ".", "end", ";", "// shortcuts for `t` values that are out of range", "if", "(", "t", "<=", "0", ")", "{", "return", "{", "startControlPoint1", ":", "start", ".", "clone", "(", ")", ",", "startControlPoint2", ":", "start", ".", "clone", "(", ")", ",", "divider", ":", "start", ".", "clone", "(", ")", ",", "dividerControlPoint1", ":", "control1", ".", "clone", "(", ")", ",", "dividerControlPoint2", ":", "control2", ".", "clone", "(", ")", "}", ";", "}", "if", "(", "t", ">=", "1", ")", "{", "return", "{", "startControlPoint1", ":", "control1", ".", "clone", "(", ")", ",", "startControlPoint2", ":", "control2", ".", "clone", "(", ")", ",", "divider", ":", "end", ".", "clone", "(", ")", ",", "dividerControlPoint1", ":", "end", ".", "clone", "(", ")", ",", "dividerControlPoint2", ":", "end", ".", "clone", "(", ")", "}", ";", "}", "var", "midpoint1", "=", "(", "new", "Line", "(", "start", ",", "control1", ")", ")", ".", "pointAt", "(", "t", ")", ";", "var", "midpoint2", "=", "(", "new", "Line", "(", "control1", ",", "control2", ")", ")", ".", "pointAt", "(", "t", ")", ";", "var", "midpoint3", "=", "(", "new", "Line", "(", "control2", ",", "end", ")", ")", ".", "pointAt", "(", "t", ")", ";", "var", "subControl1", "=", "(", "new", "Line", "(", "midpoint1", ",", "midpoint2", ")", ")", ".", "pointAt", "(", "t", ")", ";", "var", "subControl2", "=", "(", "new", "Line", "(", "midpoint2", ",", "midpoint3", ")", ")", ".", "pointAt", "(", "t", ")", ";", "var", "divider", "=", "(", "new", "Line", "(", "subControl1", ",", "subControl2", ")", ")", ".", "pointAt", "(", "t", ")", ";", "var", "output", "=", "{", "startControlPoint1", ":", "midpoint1", ",", "startControlPoint2", ":", "subControl1", ",", "divider", ":", "divider", ",", "dividerControlPoint1", ":", "subControl2", ",", "dividerControlPoint2", ":", "midpoint3", "}", ";", "return", "output", ";", "}" ]
Returns five helper points necessary for curve division.
[ "Returns", "five", "helper", "points", "necessary", "for", "curve", "division", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1040-L1086
7,758
clientIO/joint
dist/joint.nowrap.js
function(opt) { opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions; // not using localOpt var length = 0; var n = subdivisions.length; for (var i = 0; i < n; i++) { var currentSubdivision = subdivisions[i]; length += currentSubdivision.endpointDistance(); } return length; }
javascript
function(opt) { opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions; // not using localOpt var length = 0; var n = subdivisions.length; for (var i = 0; i < n; i++) { var currentSubdivision = subdivisions[i]; length += currentSubdivision.endpointDistance(); } return length; }
[ "function", "(", "opt", ")", "{", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "// opt.precision only used in getSubdivisions() call", "var", "subdivisions", "=", "(", "opt", ".", "subdivisions", "===", "undefined", ")", "?", "this", ".", "getSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ":", "opt", ".", "subdivisions", ";", "// not using localOpt", "var", "length", "=", "0", ";", "var", "n", "=", "subdivisions", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "currentSubdivision", "=", "subdivisions", "[", "i", "]", ";", "length", "+=", "currentSubdivision", ".", "endpointDistance", "(", ")", ";", "}", "return", "length", ";", "}" ]
Returns flattened length of the curve with precision better than `opt.precision`; or using `opt.subdivisions` provided.
[ "Returns", "flattened", "length", "of", "the", "curve", "with", "precision", "better", "than", "opt", ".", "precision", ";", "or", "using", "opt", ".", "subdivisions", "provided", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1165-L1181
7,759
clientIO/joint
dist/joint.nowrap.js
function(ratio, opt) { if (!this.isDifferentiable()) return null; if (ratio < 0) ratio = 0; else if (ratio > 1) ratio = 1; var t = this.tAt(ratio, opt); return this.tangentAtT(t); }
javascript
function(ratio, opt) { if (!this.isDifferentiable()) return null; if (ratio < 0) ratio = 0; else if (ratio > 1) ratio = 1; var t = this.tAt(ratio, opt); return this.tangentAtT(t); }
[ "function", "(", "ratio", ",", "opt", ")", "{", "if", "(", "!", "this", ".", "isDifferentiable", "(", ")", ")", "return", "null", ";", "if", "(", "ratio", "<", "0", ")", "ratio", "=", "0", ";", "else", "if", "(", "ratio", ">", "1", ")", "ratio", "=", "1", ";", "var", "t", "=", "this", ".", "tAt", "(", "ratio", ",", "opt", ")", ";", "return", "this", ".", "tangentAtT", "(", "t", ")", ";", "}" ]
Returns a tangent line at requested `ratio` with precision better than requested `opt.precision`; or using `opt.subdivisions` provided.
[ "Returns", "a", "tangent", "line", "at", "requested", "ratio", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "or", "using", "opt", ".", "subdivisions", "provided", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1245-L1255
7,760
clientIO/joint
dist/joint.nowrap.js
function(length, opt) { if (!this.isDifferentiable()) return null; var t = this.tAtLength(length, opt); return this.tangentAtT(t); }
javascript
function(length, opt) { if (!this.isDifferentiable()) return null; var t = this.tAtLength(length, opt); return this.tangentAtT(t); }
[ "function", "(", "length", ",", "opt", ")", "{", "if", "(", "!", "this", ".", "isDifferentiable", "(", ")", ")", "return", "null", ";", "var", "t", "=", "this", ".", "tAtLength", "(", "length", ",", "opt", ")", ";", "return", "this", ".", "tangentAtT", "(", "t", ")", ";", "}" ]
Returns a tangent line at requested `length` with precision better than requested `opt.precision`; or using `opt.subdivisions` provided.
[ "Returns", "a", "tangent", "line", "at", "requested", "length", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "or", "using", "opt", ".", "subdivisions", "provided", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1258-L1265
7,761
clientIO/joint
dist/joint.nowrap.js
function(t) { if (!this.isDifferentiable()) return null; if (t < 0) t = 0; else if (t > 1) t = 1; var skeletonPoints = this.getSkeletonPoints(t); var p1 = skeletonPoints.startControlPoint2; var p2 = skeletonPoints.dividerControlPoint1; var tangentStart = skeletonPoints.divider; var tangentLine = new Line(p1, p2); tangentLine.translate(tangentStart.x - p1.x, tangentStart.y - p1.y); // move so that tangent line starts at the point requested return tangentLine; }
javascript
function(t) { if (!this.isDifferentiable()) return null; if (t < 0) t = 0; else if (t > 1) t = 1; var skeletonPoints = this.getSkeletonPoints(t); var p1 = skeletonPoints.startControlPoint2; var p2 = skeletonPoints.dividerControlPoint1; var tangentStart = skeletonPoints.divider; var tangentLine = new Line(p1, p2); tangentLine.translate(tangentStart.x - p1.x, tangentStart.y - p1.y); // move so that tangent line starts at the point requested return tangentLine; }
[ "function", "(", "t", ")", "{", "if", "(", "!", "this", ".", "isDifferentiable", "(", ")", ")", "return", "null", ";", "if", "(", "t", "<", "0", ")", "t", "=", "0", ";", "else", "if", "(", "t", ">", "1", ")", "t", "=", "1", ";", "var", "skeletonPoints", "=", "this", ".", "getSkeletonPoints", "(", "t", ")", ";", "var", "p1", "=", "skeletonPoints", ".", "startControlPoint2", ";", "var", "p2", "=", "skeletonPoints", ".", "dividerControlPoint1", ";", "var", "tangentStart", "=", "skeletonPoints", ".", "divider", ";", "var", "tangentLine", "=", "new", "Line", "(", "p1", ",", "p2", ")", ";", "tangentLine", ".", "translate", "(", "tangentStart", ".", "x", "-", "p1", ".", "x", ",", "tangentStart", ".", "y", "-", "p1", ".", "y", ")", ";", "// move so that tangent line starts at the point requested", "return", "tangentLine", ";", "}" ]
Returns a tangent line at requested `t`.
[ "Returns", "a", "tangent", "line", "at", "requested", "t", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1268-L1286
7,762
clientIO/joint
dist/joint.nowrap.js
function(ratio, opt) { if (ratio <= 0) return 0; if (ratio >= 1) return 1; opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions; var localOpt = { precision: precision, subdivisions: subdivisions }; var curveLength = this.length(localOpt); var length = curveLength * ratio; return this.tAtLength(length, localOpt); }
javascript
function(ratio, opt) { if (ratio <= 0) return 0; if (ratio >= 1) return 1; opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions; var localOpt = { precision: precision, subdivisions: subdivisions }; var curveLength = this.length(localOpt); var length = curveLength * ratio; return this.tAtLength(length, localOpt); }
[ "function", "(", "ratio", ",", "opt", ")", "{", "if", "(", "ratio", "<=", "0", ")", "return", "0", ";", "if", "(", "ratio", ">=", "1", ")", "return", "1", ";", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "var", "subdivisions", "=", "(", "opt", ".", "subdivisions", "===", "undefined", ")", "?", "this", ".", "getSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ":", "opt", ".", "subdivisions", ";", "var", "localOpt", "=", "{", "precision", ":", "precision", ",", "subdivisions", ":", "subdivisions", "}", ";", "var", "curveLength", "=", "this", ".", "length", "(", "localOpt", ")", ";", "var", "length", "=", "curveLength", "*", "ratio", ";", "return", "this", ".", "tAtLength", "(", "length", ",", "localOpt", ")", ";", "}" ]
Returns `t` at requested `ratio` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
[ "Returns", "t", "at", "requested", "ratio", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "optionally", "using", "opt", ".", "subdivisions", "provided", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1289-L1303
7,763
clientIO/joint
dist/joint.nowrap.js
function(dx, dy) { if (dx === undefined) { dx = 0; } if (dy === undefined) { dy = dx; } this.a += 2 * dx; this.b += 2 * dy; return this; }
javascript
function(dx, dy) { if (dx === undefined) { dx = 0; } if (dy === undefined) { dy = dx; } this.a += 2 * dx; this.b += 2 * dy; return this; }
[ "function", "(", "dx", ",", "dy", ")", "{", "if", "(", "dx", "===", "undefined", ")", "{", "dx", "=", "0", ";", "}", "if", "(", "dy", "===", "undefined", ")", "{", "dy", "=", "dx", ";", "}", "this", ".", "a", "+=", "2", "*", "dx", ";", "this", ".", "b", "+=", "2", "*", "dy", ";", "return", "this", ";", "}" ]
inflate by dx and dy @param dx {delta_x} representing additional size to x @param dy {delta_y} representing additional size to y - dy param is not required -> in that case y is sized by dx
[ "inflate", "by", "dx", "and", "dy" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1519-L1532
7,764
clientIO/joint
dist/joint.nowrap.js
function(p) { var refPointDelta = 30; var x0 = p.x; var y0 = p.y; var a = this.a; var b = this.b; var center = this.bbox().center(); var m = center.x; var n = center.y; var q1 = x0 > center.x + a / 2; var q3 = x0 < center.x - a / 2; var y, x; if (q1 || q3) { y = x0 > center.x ? y0 - refPointDelta : y0 + refPointDelta; x = (a * a / (x0 - m)) - (a * a * (y0 - n) * (y - n)) / (b * b * (x0 - m)) + m; } else { x = y0 > center.y ? x0 + refPointDelta : x0 - refPointDelta; y = ( b * b / (y0 - n)) - (b * b * (x0 - m) * (x - m)) / (a * a * (y0 - n)) + n; } return (new Point(x, y)).theta(p); }
javascript
function(p) { var refPointDelta = 30; var x0 = p.x; var y0 = p.y; var a = this.a; var b = this.b; var center = this.bbox().center(); var m = center.x; var n = center.y; var q1 = x0 > center.x + a / 2; var q3 = x0 < center.x - a / 2; var y, x; if (q1 || q3) { y = x0 > center.x ? y0 - refPointDelta : y0 + refPointDelta; x = (a * a / (x0 - m)) - (a * a * (y0 - n) * (y - n)) / (b * b * (x0 - m)) + m; } else { x = y0 > center.y ? x0 + refPointDelta : x0 - refPointDelta; y = ( b * b / (y0 - n)) - (b * b * (x0 - m) * (x - m)) / (a * a * (y0 - n)) + n; } return (new Point(x, y)).theta(p); }
[ "function", "(", "p", ")", "{", "var", "refPointDelta", "=", "30", ";", "var", "x0", "=", "p", ".", "x", ";", "var", "y0", "=", "p", ".", "y", ";", "var", "a", "=", "this", ".", "a", ";", "var", "b", "=", "this", ".", "b", ";", "var", "center", "=", "this", ".", "bbox", "(", ")", ".", "center", "(", ")", ";", "var", "m", "=", "center", ".", "x", ";", "var", "n", "=", "center", ".", "y", ";", "var", "q1", "=", "x0", ">", "center", ".", "x", "+", "a", "/", "2", ";", "var", "q3", "=", "x0", "<", "center", ".", "x", "-", "a", "/", "2", ";", "var", "y", ",", "x", ";", "if", "(", "q1", "||", "q3", ")", "{", "y", "=", "x0", ">", "center", ".", "x", "?", "y0", "-", "refPointDelta", ":", "y0", "+", "refPointDelta", ";", "x", "=", "(", "a", "*", "a", "/", "(", "x0", "-", "m", ")", ")", "-", "(", "a", "*", "a", "*", "(", "y0", "-", "n", ")", "*", "(", "y", "-", "n", ")", ")", "/", "(", "b", "*", "b", "*", "(", "x0", "-", "m", ")", ")", "+", "m", ";", "}", "else", "{", "x", "=", "y0", ">", "center", ".", "y", "?", "x0", "+", "refPointDelta", ":", "x0", "-", "refPointDelta", ";", "y", "=", "(", "b", "*", "b", "/", "(", "y0", "-", "n", ")", ")", "-", "(", "b", "*", "b", "*", "(", "x0", "-", "m", ")", "*", "(", "x", "-", "m", ")", ")", "/", "(", "a", "*", "a", "*", "(", "y0", "-", "n", ")", ")", "+", "n", ";", "}", "return", "(", "new", "Point", "(", "x", ",", "y", ")", ")", ".", "theta", "(", "p", ")", ";", "}" ]
Compute angle between tangent and x axis @param {g.Point} p Point of tangency, it has to be on ellipse boundaries. @returns {number} angle between tangent and x axis
[ "Compute", "angle", "between", "tangent", "and", "x", "axis" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L1632-L1658
7,765
clientIO/joint
dist/joint.nowrap.js
function(arg) { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments var currentSegment; var previousSegment = ((numSegments !== 0) ? segments[numSegments - 1] : null); // if we are appending to an empty path, previousSegment is null var nextSegment = null; if (!Array.isArray(arg)) { // arg is a segment if (!arg || !arg.isSegment) throw new Error('Segment required.'); currentSegment = this.prepareSegment(arg, previousSegment, nextSegment); segments.push(currentSegment); } else { // arg is an array of segments if (!arg[0].isSegment) throw new Error('Segments required.'); var n = arg.length; for (var i = 0; i < n; i++) { var currentArg = arg[i]; currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment); segments.push(currentSegment); previousSegment = currentSegment; } } }
javascript
function(arg) { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments var currentSegment; var previousSegment = ((numSegments !== 0) ? segments[numSegments - 1] : null); // if we are appending to an empty path, previousSegment is null var nextSegment = null; if (!Array.isArray(arg)) { // arg is a segment if (!arg || !arg.isSegment) throw new Error('Segment required.'); currentSegment = this.prepareSegment(arg, previousSegment, nextSegment); segments.push(currentSegment); } else { // arg is an array of segments if (!arg[0].isSegment) throw new Error('Segments required.'); var n = arg.length; for (var i = 0; i < n; i++) { var currentArg = arg[i]; currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment); segments.push(currentSegment); previousSegment = currentSegment; } } }
[ "function", "(", "arg", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "// works even if path has no segments", "var", "currentSegment", ";", "var", "previousSegment", "=", "(", "(", "numSegments", "!==", "0", ")", "?", "segments", "[", "numSegments", "-", "1", "]", ":", "null", ")", ";", "// if we are appending to an empty path, previousSegment is null", "var", "nextSegment", "=", "null", ";", "if", "(", "!", "Array", ".", "isArray", "(", "arg", ")", ")", "{", "// arg is a segment", "if", "(", "!", "arg", "||", "!", "arg", ".", "isSegment", ")", "throw", "new", "Error", "(", "'Segment required.'", ")", ";", "currentSegment", "=", "this", ".", "prepareSegment", "(", "arg", ",", "previousSegment", ",", "nextSegment", ")", ";", "segments", ".", "push", "(", "currentSegment", ")", ";", "}", "else", "{", "// arg is an array of segments", "if", "(", "!", "arg", "[", "0", "]", ".", "isSegment", ")", "throw", "new", "Error", "(", "'Segments required.'", ")", ";", "var", "n", "=", "arg", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "currentArg", "=", "arg", "[", "i", "]", ";", "currentSegment", "=", "this", ".", "prepareSegment", "(", "currentArg", ",", "previousSegment", ",", "nextSegment", ")", ";", "segments", ".", "push", "(", "currentSegment", ")", ";", "previousSegment", "=", "currentSegment", ";", "}", "}", "}" ]
Accepts one segment or an array of segments as argument. Throws an error if argument is not a segment or an array of segments.
[ "Accepts", "one", "segment", "or", "an", "array", "of", "segments", "as", "argument", ".", "Throws", "an", "error", "if", "argument", "is", "not", "a", "segment", "or", "an", "array", "of", "segments", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2102-L2131
7,766
clientIO/joint
dist/joint.nowrap.js
function() { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array var bbox; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; if (segment.isVisible) { var segmentBBox = segment.bbox(); bbox = bbox ? bbox.union(segmentBBox) : segmentBBox; } } if (bbox) return bbox; // if the path has only invisible elements, return end point of last segment var lastSegment = segments[numSegments - 1]; return new Rect(lastSegment.end.x, lastSegment.end.y, 0, 0); }
javascript
function() { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array var bbox; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; if (segment.isVisible) { var segmentBBox = segment.bbox(); bbox = bbox ? bbox.union(segmentBBox) : segmentBBox; } } if (bbox) return bbox; // if the path has only invisible elements, return end point of last segment var lastSegment = segments[numSegments - 1]; return new Rect(lastSegment.end.x, lastSegment.end.y, 0, 0); }
[ "function", "(", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "return", "null", ";", "// if segments is an empty array", "var", "bbox", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numSegments", ";", "i", "++", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ";", "if", "(", "segment", ".", "isVisible", ")", "{", "var", "segmentBBox", "=", "segment", ".", "bbox", "(", ")", ";", "bbox", "=", "bbox", "?", "bbox", ".", "union", "(", "segmentBBox", ")", ":", "segmentBBox", ";", "}", "}", "if", "(", "bbox", ")", "return", "bbox", ";", "// if the path has only invisible elements, return end point of last segment", "var", "lastSegment", "=", "segments", "[", "numSegments", "-", "1", "]", ";", "return", "new", "Rect", "(", "lastSegment", ".", "end", ".", "x", ",", "lastSegment", ".", "end", ".", "y", ",", "0", ",", "0", ")", ";", "}" ]
Returns the bbox of the path. If path has no segments, returns null. If path has only invisible segments, returns bbox of the end point of last segment.
[ "Returns", "the", "bbox", "of", "the", "path", ".", "If", "path", "has", "no", "segments", "returns", "null", ".", "If", "path", "has", "only", "invisible", "segments", "returns", "bbox", "of", "the", "end", "point", "of", "last", "segment", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2136-L2157
7,767
clientIO/joint
dist/joint.nowrap.js
function() { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments var path = new Path(); for (var i = 0; i < numSegments; i++) { var segment = segments[i].clone(); path.appendSegment(segment); } return path; }
javascript
function() { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments var path = new Path(); for (var i = 0; i < numSegments; i++) { var segment = segments[i].clone(); path.appendSegment(segment); } return path; }
[ "function", "(", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "// works even if path has no segments", "var", "path", "=", "new", "Path", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numSegments", ";", "i", "++", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ".", "clone", "(", ")", ";", "path", ".", "appendSegment", "(", "segment", ")", ";", "}", "return", "path", ";", "}" ]
Returns a new path that is a clone of this path.
[ "Returns", "a", "new", "path", "that", "is", "a", "clone", "of", "this", "path", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2160-L2174
7,768
clientIO/joint
dist/joint.nowrap.js
function(p) { if (!p) return false; var segments = this.segments; var otherSegments = p.segments; var numSegments = segments.length; if (otherSegments.length !== numSegments) return false; // if the two paths have different number of segments, they cannot be equal for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var otherSegment = otherSegments[i]; // as soon as an inequality is found in segments, return false if ((segment.type !== otherSegment.type) || (!segment.equals(otherSegment))) return false; } // if no inequality found in segments, return true return true; }
javascript
function(p) { if (!p) return false; var segments = this.segments; var otherSegments = p.segments; var numSegments = segments.length; if (otherSegments.length !== numSegments) return false; // if the two paths have different number of segments, they cannot be equal for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var otherSegment = otherSegments[i]; // as soon as an inequality is found in segments, return false if ((segment.type !== otherSegment.type) || (!segment.equals(otherSegment))) return false; } // if no inequality found in segments, return true return true; }
[ "function", "(", "p", ")", "{", "if", "(", "!", "p", ")", "return", "false", ";", "var", "segments", "=", "this", ".", "segments", ";", "var", "otherSegments", "=", "p", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "otherSegments", ".", "length", "!==", "numSegments", ")", "return", "false", ";", "// if the two paths have different number of segments, they cannot be equal", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numSegments", ";", "i", "++", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ";", "var", "otherSegment", "=", "otherSegments", "[", "i", "]", ";", "// as soon as an inequality is found in segments, return false", "if", "(", "(", "segment", ".", "type", "!==", "otherSegment", ".", "type", ")", "||", "(", "!", "segment", ".", "equals", "(", "otherSegment", ")", ")", ")", "return", "false", ";", "}", "// if no inequality found in segments, return true", "return", "true", ";", "}" ]
Checks whether two paths are exactly the same. If `p` is undefined or null, returns false.
[ "Checks", "whether", "two", "paths", "are", "exactly", "the", "same", ".", "If", "p", "is", "undefined", "or", "null", "returns", "false", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2288-L2309
7,769
clientIO/joint
dist/joint.nowrap.js
function(index) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) throw new Error('Path has no segments.'); if (index < 0) index = numSegments + index; // convert negative indices to positive if (index >= numSegments || index < 0) throw new Error('Index out of range.'); return segments[index]; }
javascript
function(index) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) throw new Error('Path has no segments.'); if (index < 0) index = numSegments + index; // convert negative indices to positive if (index >= numSegments || index < 0) throw new Error('Index out of range.'); return segments[index]; }
[ "function", "(", "index", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "throw", "new", "Error", "(", "'Path has no segments.'", ")", ";", "if", "(", "index", "<", "0", ")", "index", "=", "numSegments", "+", "index", ";", "// convert negative indices to positive", "if", "(", "index", ">=", "numSegments", "||", "index", "<", "0", ")", "throw", "new", "Error", "(", "'Index out of range.'", ")", ";", "return", "segments", "[", "index", "]", ";", "}" ]
Accepts negative indices. Throws an error if path has no segments. Throws an error if index is out of range.
[ "Accepts", "negative", "indices", ".", "Throws", "an", "error", "if", "path", "has", "no", "segments", ".", "Throws", "an", "error", "if", "index", "is", "out", "of", "range", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2314-L2324
7,770
clientIO/joint
dist/joint.nowrap.js
function(opt) { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // not using opt.segmentSubdivisions // not using localOpt var segmentSubdivisions = []; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var subdivisions = segment.getSubdivisions({ precision: precision }); segmentSubdivisions.push(subdivisions); } return segmentSubdivisions; }
javascript
function(opt) { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // not using opt.segmentSubdivisions // not using localOpt var segmentSubdivisions = []; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var subdivisions = segment.getSubdivisions({ precision: precision }); segmentSubdivisions.push(subdivisions); } return segmentSubdivisions; }
[ "function", "(", "opt", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "// works even if path has no segments", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "// not using opt.segmentSubdivisions", "// not using localOpt", "var", "segmentSubdivisions", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numSegments", ";", "i", "++", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ";", "var", "subdivisions", "=", "segment", ".", "getSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ";", "segmentSubdivisions", ".", "push", "(", "subdivisions", ")", ";", "}", "return", "segmentSubdivisions", ";", "}" ]
Returns an array of segment subdivisions, with precision better than requested `opt.precision`.
[ "Returns", "an", "array", "of", "segment", "subdivisions", "with", "precision", "better", "than", "requested", "opt", ".", "precision", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2327-L2347
7,771
clientIO/joint
dist/joint.nowrap.js
function(opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return 0; // if segments is an empty array opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSegmentSubdivisions() call var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var length = 0; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; length += segment.length({ subdivisions: subdivisions }); } return length; }
javascript
function(opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return 0; // if segments is an empty array opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSegmentSubdivisions() call var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var length = 0; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; length += segment.length({ subdivisions: subdivisions }); } return length; }
[ "function", "(", "opt", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "return", "0", ";", "// if segments is an empty array", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "// opt.precision only used in getSegmentSubdivisions() call", "var", "segmentSubdivisions", "=", "(", "opt", ".", "segmentSubdivisions", "===", "undefined", ")", "?", "this", ".", "getSegmentSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ":", "opt", ".", "segmentSubdivisions", ";", "// not using localOpt", "var", "length", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numSegments", ";", "i", "++", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ";", "var", "subdivisions", "=", "segmentSubdivisions", "[", "i", "]", ";", "length", "+=", "segment", ".", "length", "(", "{", "subdivisions", ":", "subdivisions", "}", ")", ";", "}", "return", "length", ";", "}" ]
Returns length of the path, with precision better than requested `opt.precision`; or using `opt.segmentSubdivisions` provided. If path has no segments, returns 0.
[ "Returns", "length", "of", "the", "path", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "or", "using", "opt", ".", "segmentSubdivisions", "provided", ".", "If", "path", "has", "no", "segments", "returns", "0", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2451-L2471
7,772
clientIO/joint
dist/joint.nowrap.js
function(ratio, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array if (ratio <= 0) return this.start.clone(); if (ratio >= 1) return this.end.clone(); opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions }; var pathLength = this.length(localOpt); var length = pathLength * ratio; return this.pointAtLength(length, localOpt); }
javascript
function(ratio, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array if (ratio <= 0) return this.start.clone(); if (ratio >= 1) return this.end.clone(); opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions }; var pathLength = this.length(localOpt); var length = pathLength * ratio; return this.pointAtLength(length, localOpt); }
[ "function", "(", "ratio", ",", "opt", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "return", "null", ";", "// if segments is an empty array", "if", "(", "ratio", "<=", "0", ")", "return", "this", ".", "start", ".", "clone", "(", ")", ";", "if", "(", "ratio", ">=", "1", ")", "return", "this", ".", "end", ".", "clone", "(", ")", ";", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "var", "segmentSubdivisions", "=", "(", "opt", ".", "segmentSubdivisions", "===", "undefined", ")", "?", "this", ".", "getSegmentSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ":", "opt", ".", "segmentSubdivisions", ";", "var", "localOpt", "=", "{", "precision", ":", "precision", ",", "segmentSubdivisions", ":", "segmentSubdivisions", "}", ";", "var", "pathLength", "=", "this", ".", "length", "(", "localOpt", ")", ";", "var", "length", "=", "pathLength", "*", "ratio", ";", "return", "this", ".", "pointAtLength", "(", "length", ",", "localOpt", ")", ";", "}" ]
Returns point at requested `ratio` between 0 and 1, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
[ "Returns", "point", "at", "requested", "ratio", "between", "0", "and", "1", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "optionally", "using", "opt", ".", "segmentSubdivisions", "provided", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2513-L2531
7,773
clientIO/joint
dist/joint.nowrap.js
function(length, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array if (length === 0) return this.start.clone(); var fromStart = true; if (length < 0) { fromStart = false; // negative lengths mean start calculation from end point length = -length; // absolute value } opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var lastVisibleSegment; var l = 0; // length so far for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; var d = segment.length({ precision: precision, subdivisions: subdivisions }); if (segment.isVisible) { if (length <= (l + d)) { return segment.pointAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions }); } lastVisibleSegment = segment; } l += d; } // if length requested is higher than the length of the path, return last visible segment endpoint if (lastVisibleSegment) return (fromStart ? lastVisibleSegment.end : lastVisibleSegment.start); // if no visible segment, return last segment end point (no matter if fromStart or no) var lastSegment = segments[numSegments - 1]; return lastSegment.end.clone(); }
javascript
function(length, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array if (length === 0) return this.start.clone(); var fromStart = true; if (length < 0) { fromStart = false; // negative lengths mean start calculation from end point length = -length; // absolute value } opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var lastVisibleSegment; var l = 0; // length so far for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; var d = segment.length({ precision: precision, subdivisions: subdivisions }); if (segment.isVisible) { if (length <= (l + d)) { return segment.pointAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions }); } lastVisibleSegment = segment; } l += d; } // if length requested is higher than the length of the path, return last visible segment endpoint if (lastVisibleSegment) return (fromStart ? lastVisibleSegment.end : lastVisibleSegment.start); // if no visible segment, return last segment end point (no matter if fromStart or no) var lastSegment = segments[numSegments - 1]; return lastSegment.end.clone(); }
[ "function", "(", "length", ",", "opt", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "return", "null", ";", "// if segments is an empty array", "if", "(", "length", "===", "0", ")", "return", "this", ".", "start", ".", "clone", "(", ")", ";", "var", "fromStart", "=", "true", ";", "if", "(", "length", "<", "0", ")", "{", "fromStart", "=", "false", ";", "// negative lengths mean start calculation from end point", "length", "=", "-", "length", ";", "// absolute value", "}", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "var", "segmentSubdivisions", "=", "(", "opt", ".", "segmentSubdivisions", "===", "undefined", ")", "?", "this", ".", "getSegmentSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ":", "opt", ".", "segmentSubdivisions", ";", "// not using localOpt", "var", "lastVisibleSegment", ";", "var", "l", "=", "0", ";", "// length so far", "for", "(", "var", "i", "=", "(", "fromStart", "?", "0", ":", "(", "numSegments", "-", "1", ")", ")", ";", "(", "fromStart", "?", "(", "i", "<", "numSegments", ")", ":", "(", "i", ">=", "0", ")", ")", ";", "(", "fromStart", "?", "(", "i", "++", ")", ":", "(", "i", "--", ")", ")", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ";", "var", "subdivisions", "=", "segmentSubdivisions", "[", "i", "]", ";", "var", "d", "=", "segment", ".", "length", "(", "{", "precision", ":", "precision", ",", "subdivisions", ":", "subdivisions", "}", ")", ";", "if", "(", "segment", ".", "isVisible", ")", "{", "if", "(", "length", "<=", "(", "l", "+", "d", ")", ")", "{", "return", "segment", ".", "pointAtLength", "(", "(", "(", "fromStart", "?", "1", ":", "-", "1", ")", "*", "(", "length", "-", "l", ")", ")", ",", "{", "precision", ":", "precision", ",", "subdivisions", ":", "subdivisions", "}", ")", ";", "}", "lastVisibleSegment", "=", "segment", ";", "}", "l", "+=", "d", ";", "}", "// if length requested is higher than the length of the path, return last visible segment endpoint", "if", "(", "lastVisibleSegment", ")", "return", "(", "fromStart", "?", "lastVisibleSegment", ".", "end", ":", "lastVisibleSegment", ".", "start", ")", ";", "// if no visible segment, return last segment end point (no matter if fromStart or no)", "var", "lastSegment", "=", "segments", "[", "numSegments", "-", "1", "]", ";", "return", "lastSegment", ".", "end", ".", "clone", "(", ")", ";", "}" ]
Returns point at requested `length`, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided. Accepts negative length.
[ "Returns", "point", "at", "requested", "length", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "optionally", "using", "opt", ".", "segmentSubdivisions", "provided", ".", "Accepts", "negative", "length", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2535-L2579
7,774
clientIO/joint
dist/joint.nowrap.js
function(segment, previousSegment, nextSegment) { // insert after previous segment and before previous segment's next segment segment.previousSegment = previousSegment; segment.nextSegment = nextSegment; if (previousSegment) previousSegment.nextSegment = segment; if (nextSegment) nextSegment.previousSegment = segment; var updateSubpathStart = segment; if (segment.isSubpathStart) { segment.subpathStartSegment = segment; // assign self as subpath start segment updateSubpathStart = nextSegment; // start updating from next segment } // assign previous segment's subpath start (or self if it is a subpath start) to subsequent segments if (updateSubpathStart) this.updateSubpathStartSegment(updateSubpathStart); return segment; }
javascript
function(segment, previousSegment, nextSegment) { // insert after previous segment and before previous segment's next segment segment.previousSegment = previousSegment; segment.nextSegment = nextSegment; if (previousSegment) previousSegment.nextSegment = segment; if (nextSegment) nextSegment.previousSegment = segment; var updateSubpathStart = segment; if (segment.isSubpathStart) { segment.subpathStartSegment = segment; // assign self as subpath start segment updateSubpathStart = nextSegment; // start updating from next segment } // assign previous segment's subpath start (or self if it is a subpath start) to subsequent segments if (updateSubpathStart) this.updateSubpathStartSegment(updateSubpathStart); return segment; }
[ "function", "(", "segment", ",", "previousSegment", ",", "nextSegment", ")", "{", "// insert after previous segment and before previous segment's next segment", "segment", ".", "previousSegment", "=", "previousSegment", ";", "segment", ".", "nextSegment", "=", "nextSegment", ";", "if", "(", "previousSegment", ")", "previousSegment", ".", "nextSegment", "=", "segment", ";", "if", "(", "nextSegment", ")", "nextSegment", ".", "previousSegment", "=", "segment", ";", "var", "updateSubpathStart", "=", "segment", ";", "if", "(", "segment", ".", "isSubpathStart", ")", "{", "segment", ".", "subpathStartSegment", "=", "segment", ";", "// assign self as subpath start segment", "updateSubpathStart", "=", "nextSegment", ";", "// start updating from next segment", "}", "// assign previous segment's subpath start (or self if it is a subpath start) to subsequent segments", "if", "(", "updateSubpathStart", ")", "this", ".", "updateSubpathStartSegment", "(", "updateSubpathStart", ")", ";", "return", "segment", ";", "}" ]
Helper method for adding segments.
[ "Helper", "method", "for", "adding", "segments", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2603-L2621
7,775
clientIO/joint
dist/joint.nowrap.js
function(index) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) throw new Error('Path has no segments.'); if (index < 0) index = numSegments + index; // convert negative indices to positive if (index >= numSegments || index < 0) throw new Error('Index out of range.'); var removedSegment = segments.splice(index, 1)[0]; var previousSegment = removedSegment.previousSegment; var nextSegment = removedSegment.nextSegment; // link the previous and next segments together (if present) if (previousSegment) previousSegment.nextSegment = nextSegment; // may be null if (nextSegment) nextSegment.previousSegment = previousSegment; // may be null // if removed segment used to start a subpath, update all subsequent segments until another subpath start segment is reached if (removedSegment.isSubpathStart && nextSegment) this.updateSubpathStartSegment(nextSegment); }
javascript
function(index) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) throw new Error('Path has no segments.'); if (index < 0) index = numSegments + index; // convert negative indices to positive if (index >= numSegments || index < 0) throw new Error('Index out of range.'); var removedSegment = segments.splice(index, 1)[0]; var previousSegment = removedSegment.previousSegment; var nextSegment = removedSegment.nextSegment; // link the previous and next segments together (if present) if (previousSegment) previousSegment.nextSegment = nextSegment; // may be null if (nextSegment) nextSegment.previousSegment = previousSegment; // may be null // if removed segment used to start a subpath, update all subsequent segments until another subpath start segment is reached if (removedSegment.isSubpathStart && nextSegment) this.updateSubpathStartSegment(nextSegment); }
[ "function", "(", "index", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "throw", "new", "Error", "(", "'Path has no segments.'", ")", ";", "if", "(", "index", "<", "0", ")", "index", "=", "numSegments", "+", "index", ";", "// convert negative indices to positive", "if", "(", "index", ">=", "numSegments", "||", "index", "<", "0", ")", "throw", "new", "Error", "(", "'Index out of range.'", ")", ";", "var", "removedSegment", "=", "segments", ".", "splice", "(", "index", ",", "1", ")", "[", "0", "]", ";", "var", "previousSegment", "=", "removedSegment", ".", "previousSegment", ";", "var", "nextSegment", "=", "removedSegment", ".", "nextSegment", ";", "// link the previous and next segments together (if present)", "if", "(", "previousSegment", ")", "previousSegment", ".", "nextSegment", "=", "nextSegment", ";", "// may be null", "if", "(", "nextSegment", ")", "nextSegment", ".", "previousSegment", "=", "previousSegment", ";", "// may be null", "// if removed segment used to start a subpath, update all subsequent segments until another subpath start segment is reached", "if", "(", "removedSegment", ".", "isSubpathStart", "&&", "nextSegment", ")", "this", ".", "updateSubpathStartSegment", "(", "nextSegment", ")", ";", "}" ]
Remove the segment at `index`. Accepts negative indices, from `-1` to `-segments.length`. Throws an error if path has no segments. Throws an error if index is out of range.
[ "Remove", "the", "segment", "at", "index", ".", "Accepts", "negative", "indices", "from", "-", "1", "to", "-", "segments", ".", "length", ".", "Throws", "an", "error", "if", "path", "has", "no", "segments", ".", "Throws", "an", "error", "if", "index", "is", "out", "of", "range", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2627-L2646
7,776
clientIO/joint
dist/joint.nowrap.js
function(length, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array var fromStart = true; if (length < 0) { fromStart = false; // negative lengths mean start calculation from end point length = -length; // absolute value } opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var lastValidSegment; // visible AND differentiable (with a tangent) var l = 0; // length so far for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; var d = segment.length({ precision: precision, subdivisions: subdivisions }); if (segment.isDifferentiable()) { if (length <= (l + d)) { return segment.tangentAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions }); } lastValidSegment = segment; } l += d; } // if length requested is higher than the length of the path, return tangent of endpoint of last valid segment if (lastValidSegment) { var t = (fromStart ? 1 : 0); return lastValidSegment.tangentAtT(t); } // if no valid segment, return null return null; }
javascript
function(length, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array var fromStart = true; if (length < 0) { fromStart = false; // negative lengths mean start calculation from end point length = -length; // absolute value } opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var lastValidSegment; // visible AND differentiable (with a tangent) var l = 0; // length so far for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; var d = segment.length({ precision: precision, subdivisions: subdivisions }); if (segment.isDifferentiable()) { if (length <= (l + d)) { return segment.tangentAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions }); } lastValidSegment = segment; } l += d; } // if length requested is higher than the length of the path, return tangent of endpoint of last valid segment if (lastValidSegment) { var t = (fromStart ? 1 : 0); return lastValidSegment.tangentAtT(t); } // if no valid segment, return null return null; }
[ "function", "(", "length", ",", "opt", ")", "{", "var", "segments", "=", "this", ".", "segments", ";", "var", "numSegments", "=", "segments", ".", "length", ";", "if", "(", "numSegments", "===", "0", ")", "return", "null", ";", "// if segments is an empty array", "var", "fromStart", "=", "true", ";", "if", "(", "length", "<", "0", ")", "{", "fromStart", "=", "false", ";", "// negative lengths mean start calculation from end point", "length", "=", "-", "length", ";", "// absolute value", "}", "opt", "=", "opt", "||", "{", "}", ";", "var", "precision", "=", "(", "opt", ".", "precision", "===", "undefined", ")", "?", "this", ".", "PRECISION", ":", "opt", ".", "precision", ";", "var", "segmentSubdivisions", "=", "(", "opt", ".", "segmentSubdivisions", "===", "undefined", ")", "?", "this", ".", "getSegmentSubdivisions", "(", "{", "precision", ":", "precision", "}", ")", ":", "opt", ".", "segmentSubdivisions", ";", "// not using localOpt", "var", "lastValidSegment", ";", "// visible AND differentiable (with a tangent)", "var", "l", "=", "0", ";", "// length so far", "for", "(", "var", "i", "=", "(", "fromStart", "?", "0", ":", "(", "numSegments", "-", "1", ")", ")", ";", "(", "fromStart", "?", "(", "i", "<", "numSegments", ")", ":", "(", "i", ">=", "0", ")", ")", ";", "(", "fromStart", "?", "(", "i", "++", ")", ":", "(", "i", "--", ")", ")", ")", "{", "var", "segment", "=", "segments", "[", "i", "]", ";", "var", "subdivisions", "=", "segmentSubdivisions", "[", "i", "]", ";", "var", "d", "=", "segment", ".", "length", "(", "{", "precision", ":", "precision", ",", "subdivisions", ":", "subdivisions", "}", ")", ";", "if", "(", "segment", ".", "isDifferentiable", "(", ")", ")", "{", "if", "(", "length", "<=", "(", "l", "+", "d", ")", ")", "{", "return", "segment", ".", "tangentAtLength", "(", "(", "(", "fromStart", "?", "1", ":", "-", "1", ")", "*", "(", "length", "-", "l", ")", ")", ",", "{", "precision", ":", "precision", ",", "subdivisions", ":", "subdivisions", "}", ")", ";", "}", "lastValidSegment", "=", "segment", ";", "}", "l", "+=", "d", ";", "}", "// if length requested is higher than the length of the path, return tangent of endpoint of last valid segment", "if", "(", "lastValidSegment", ")", "{", "var", "t", "=", "(", "fromStart", "?", "1", ":", "0", ")", ";", "return", "lastValidSegment", ".", "tangentAtT", "(", "t", ")", ";", "}", "// if no valid segment, return null", "return", "null", ";", "}" ]
Returns tangent line at requested `length`, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided. Accepts negative length.
[ "Returns", "tangent", "line", "at", "requested", "length", "with", "precision", "better", "than", "requested", "opt", ".", "precision", ";", "optionally", "using", "opt", ".", "segmentSubdivisions", "provided", ".", "Accepts", "negative", "length", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2822-L2866
7,777
clientIO/joint
dist/joint.nowrap.js
function(segment) { var previousSegment = segment.previousSegment; // may be null while (segment && !segment.isSubpathStart) { // assign previous segment's subpath start segment to this segment if (previousSegment) segment.subpathStartSegment = previousSegment.subpathStartSegment; // may be null else segment.subpathStartSegment = null; // if segment had no previous segment, assign null - creates an invalid path! previousSegment = segment; segment = segment.nextSegment; // move on to the segment after etc. } }
javascript
function(segment) { var previousSegment = segment.previousSegment; // may be null while (segment && !segment.isSubpathStart) { // assign previous segment's subpath start segment to this segment if (previousSegment) segment.subpathStartSegment = previousSegment.subpathStartSegment; // may be null else segment.subpathStartSegment = null; // if segment had no previous segment, assign null - creates an invalid path! previousSegment = segment; segment = segment.nextSegment; // move on to the segment after etc. } }
[ "function", "(", "segment", ")", "{", "var", "previousSegment", "=", "segment", ".", "previousSegment", ";", "// may be null", "while", "(", "segment", "&&", "!", "segment", ".", "isSubpathStart", ")", "{", "// assign previous segment's subpath start segment to this segment", "if", "(", "previousSegment", ")", "segment", ".", "subpathStartSegment", "=", "previousSegment", ".", "subpathStartSegment", ";", "// may be null", "else", "segment", ".", "subpathStartSegment", "=", "null", ";", "// if segment had no previous segment, assign null - creates an invalid path!", "previousSegment", "=", "segment", ";", "segment", "=", "segment", ".", "nextSegment", ";", "// move on to the segment after etc.", "}", "}" ]
Helper method for updating subpath start of segments, starting with the one provided.
[ "Helper", "method", "for", "updating", "subpath", "start", "of", "segments", "starting", "with", "the", "one", "provided", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L2966-L2978
7,778
clientIO/joint
dist/joint.nowrap.js
function(ref, distance) { var theta = toRad((new Point(ref)).theta(this)); var offset = this.offset(cos(theta) * distance, -sin(theta) * distance); return offset; }
javascript
function(ref, distance) { var theta = toRad((new Point(ref)).theta(this)); var offset = this.offset(cos(theta) * distance, -sin(theta) * distance); return offset; }
[ "function", "(", "ref", ",", "distance", ")", "{", "var", "theta", "=", "toRad", "(", "(", "new", "Point", "(", "ref", ")", ")", ".", "theta", "(", "this", ")", ")", ";", "var", "offset", "=", "this", ".", "offset", "(", "cos", "(", "theta", ")", "*", "distance", ",", "-", "sin", "(", "theta", ")", "*", "distance", ")", ";", "return", "offset", ";", "}" ]
Move point on line starting from ref ending at me by distance distance.
[ "Move", "point", "on", "line", "starting", "from", "ref", "ending", "at", "me", "by", "distance", "distance", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L3204-L3209
7,779
clientIO/joint
dist/joint.nowrap.js
function(sx, sy, origin) { origin = (origin && new Point(origin)) || new Point(0, 0); this.x = origin.x + sx * (this.x - origin.x); this.y = origin.y + sy * (this.y - origin.y); return this; }
javascript
function(sx, sy, origin) { origin = (origin && new Point(origin)) || new Point(0, 0); this.x = origin.x + sx * (this.x - origin.x); this.y = origin.y + sy * (this.y - origin.y); return this; }
[ "function", "(", "sx", ",", "sy", ",", "origin", ")", "{", "origin", "=", "(", "origin", "&&", "new", "Point", "(", "origin", ")", ")", "||", "new", "Point", "(", "0", ",", "0", ")", ";", "this", ".", "x", "=", "origin", ".", "x", "+", "sx", "*", "(", "this", ".", "x", "-", "origin", ".", "x", ")", ";", "this", ".", "y", "=", "origin", ".", "y", "+", "sy", "*", "(", "this", ".", "y", "-", "origin", ".", "y", ")", ";", "return", "this", ";", "}" ]
Scale point with origin.
[ "Scale", "point", "with", "origin", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L3265-L3271
7,780
clientIO/joint
dist/joint.nowrap.js
function(o) { o = (o && new Point(o)) || new Point(0, 0); var x = this.x; var y = this.y; this.x = sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y)); // r this.y = toRad(o.theta(new Point(x, y))); return this; }
javascript
function(o) { o = (o && new Point(o)) || new Point(0, 0); var x = this.x; var y = this.y; this.x = sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y)); // r this.y = toRad(o.theta(new Point(x, y))); return this; }
[ "function", "(", "o", ")", "{", "o", "=", "(", "o", "&&", "new", "Point", "(", "o", ")", ")", "||", "new", "Point", "(", "0", ",", "0", ")", ";", "var", "x", "=", "this", ".", "x", ";", "var", "y", "=", "this", ".", "y", ";", "this", ".", "x", "=", "sqrt", "(", "(", "x", "-", "o", ".", "x", ")", "*", "(", "x", "-", "o", ".", "x", ")", "+", "(", "y", "-", "o", ".", "y", ")", "*", "(", "y", "-", "o", ".", "y", ")", ")", ";", "// r", "this", ".", "y", "=", "toRad", "(", "o", ".", "theta", "(", "new", "Point", "(", "x", ",", "y", ")", ")", ")", ";", "return", "this", ";", "}" ]
Converts rectangular to polar coordinates. An origin can be specified, otherwise it's 0@0.
[ "Converts", "rectangular", "to", "polar", "coordinates", ".", "An", "origin", "can", "be", "specified", "otherwise", "it", "s", "0" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L3312-L3320
7,781
clientIO/joint
dist/joint.nowrap.js
function(p) { if (!p) return false; var points = this.points; var otherPoints = p.points; var numPoints = points.length; if (otherPoints.length !== numPoints) return false; // if the two polylines have different number of points, they cannot be equal for (var i = 0; i < numPoints; i++) { var point = points[i]; var otherPoint = p.points[i]; // as soon as an inequality is found in points, return false if (!point.equals(otherPoint)) return false; } // if no inequality found in points, return true return true; }
javascript
function(p) { if (!p) return false; var points = this.points; var otherPoints = p.points; var numPoints = points.length; if (otherPoints.length !== numPoints) return false; // if the two polylines have different number of points, they cannot be equal for (var i = 0; i < numPoints; i++) { var point = points[i]; var otherPoint = p.points[i]; // as soon as an inequality is found in points, return false if (!point.equals(otherPoint)) return false; } // if no inequality found in points, return true return true; }
[ "function", "(", "p", ")", "{", "if", "(", "!", "p", ")", "return", "false", ";", "var", "points", "=", "this", ".", "points", ";", "var", "otherPoints", "=", "p", ".", "points", ";", "var", "numPoints", "=", "points", ".", "length", ";", "if", "(", "otherPoints", ".", "length", "!==", "numPoints", ")", "return", "false", ";", "// if the two polylines have different number of points, they cannot be equal", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "i", "++", ")", "{", "var", "point", "=", "points", "[", "i", "]", ";", "var", "otherPoint", "=", "p", ".", "points", "[", "i", "]", ";", "// as soon as an inequality is found in points, return false", "if", "(", "!", "point", ".", "equals", "(", "otherPoint", ")", ")", "return", "false", ";", "}", "// if no inequality found in points, return true", "return", "true", ";", "}" ]
Checks whether two polylines are exactly the same. If `p` is undefined or null, returns false.
[ "Checks", "whether", "two", "polylines", "are", "exactly", "the", "same", ".", "If", "p", "is", "undefined", "or", "null", "returns", "false", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L3686-L3707
7,782
clientIO/joint
dist/joint.nowrap.js
function() { var points = this.points; var numPoints = points.length; if (numPoints === 0) return ''; // if points array is empty var output = ''; for (var i = 0; i < numPoints; i++) { var point = points[i]; output += point.x + ',' + point.y + ' '; } return output.trim(); }
javascript
function() { var points = this.points; var numPoints = points.length; if (numPoints === 0) return ''; // if points array is empty var output = ''; for (var i = 0; i < numPoints; i++) { var point = points[i]; output += point.x + ',' + point.y + ' '; } return output.trim(); }
[ "function", "(", ")", "{", "var", "points", "=", "this", ".", "points", ";", "var", "numPoints", "=", "points", ".", "length", ";", "if", "(", "numPoints", "===", "0", ")", "return", "''", ";", "// if points array is empty", "var", "output", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "i", "++", ")", "{", "var", "point", "=", "points", "[", "i", "]", ";", "output", "+=", "point", ".", "x", "+", "','", "+", "point", ".", "y", "+", "' '", ";", "}", "return", "output", ".", "trim", "(", ")", ";", "}" ]
Return svgString that can be used to recreate this line.
[ "Return", "svgString", "that", "can", "be", "used", "to", "recreate", "this", "line", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L3901-L3915
7,783
clientIO/joint
dist/joint.nowrap.js
function(angle) { if (!angle) return this.clone(); var theta = toRad(angle); var st = abs(sin(theta)); var ct = abs(cos(theta)); var w = this.width * ct + this.height * st; var h = this.width * st + this.height * ct; return new Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h); }
javascript
function(angle) { if (!angle) return this.clone(); var theta = toRad(angle); var st = abs(sin(theta)); var ct = abs(cos(theta)); var w = this.width * ct + this.height * st; var h = this.width * st + this.height * ct; return new Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h); }
[ "function", "(", "angle", ")", "{", "if", "(", "!", "angle", ")", "return", "this", ".", "clone", "(", ")", ";", "var", "theta", "=", "toRad", "(", "angle", ")", ";", "var", "st", "=", "abs", "(", "sin", "(", "theta", ")", ")", ";", "var", "ct", "=", "abs", "(", "cos", "(", "theta", ")", ")", ";", "var", "w", "=", "this", ".", "width", "*", "ct", "+", "this", ".", "height", "*", "st", ";", "var", "h", "=", "this", ".", "width", "*", "st", "+", "this", ".", "height", "*", "ct", ";", "return", "new", "Rect", "(", "this", ".", "x", "+", "(", "this", ".", "width", "-", "w", ")", "/", "2", ",", "this", ".", "y", "+", "(", "this", ".", "height", "-", "h", ")", "/", "2", ",", "w", ",", "h", ")", ";", "}" ]
Find my bounding box when I'm rotated with the center of rotation in the center of me. @return r {rectangle} representing a bounding box
[ "Find", "my", "bounding", "box", "when", "I", "m", "rotated", "with", "the", "center", "of", "rotation", "in", "the", "center", "of", "me", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L3981-L3991
7,784
clientIO/joint
dist/joint.nowrap.js
function(p, angle) { p = new Point(p); var center = new Point(this.x + this.width / 2, this.y + this.height / 2); var result; if (angle) p.rotate(center, angle); // (clockwise, starting from the top side) var sides = [ this.topLine(), this.rightLine(), this.bottomLine(), this.leftLine() ]; var connector = new Line(center, p); for (var i = sides.length - 1; i >= 0; --i) { var intersection = sides[i].intersection(connector); if (intersection !== null) { result = intersection; break; } } if (result && angle) result.rotate(center, -angle); return result; }
javascript
function(p, angle) { p = new Point(p); var center = new Point(this.x + this.width / 2, this.y + this.height / 2); var result; if (angle) p.rotate(center, angle); // (clockwise, starting from the top side) var sides = [ this.topLine(), this.rightLine(), this.bottomLine(), this.leftLine() ]; var connector = new Line(center, p); for (var i = sides.length - 1; i >= 0; --i) { var intersection = sides[i].intersection(connector); if (intersection !== null) { result = intersection; break; } } if (result && angle) result.rotate(center, -angle); return result; }
[ "function", "(", "p", ",", "angle", ")", "{", "p", "=", "new", "Point", "(", "p", ")", ";", "var", "center", "=", "new", "Point", "(", "this", ".", "x", "+", "this", ".", "width", "/", "2", ",", "this", ".", "y", "+", "this", ".", "height", "/", "2", ")", ";", "var", "result", ";", "if", "(", "angle", ")", "p", ".", "rotate", "(", "center", ",", "angle", ")", ";", "// (clockwise, starting from the top side)", "var", "sides", "=", "[", "this", ".", "topLine", "(", ")", ",", "this", ".", "rightLine", "(", ")", ",", "this", ".", "bottomLine", "(", ")", ",", "this", ".", "leftLine", "(", ")", "]", ";", "var", "connector", "=", "new", "Line", "(", "center", ",", "p", ")", ";", "for", "(", "var", "i", "=", "sides", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "var", "intersection", "=", "sides", "[", "i", "]", ".", "intersection", "(", "connector", ")", ";", "if", "(", "intersection", "!==", "null", ")", "{", "result", "=", "intersection", ";", "break", ";", "}", "}", "if", "(", "result", "&&", "angle", ")", "result", ".", "rotate", "(", "center", ",", "-", "angle", ")", ";", "return", "result", ";", "}" ]
Find point on my boundary where line starting from my center ending in point p intersects me. @param {number} angle If angle is specified, intersection with rotated rectangle is computed.
[ "Find", "point", "on", "my", "boundary", "where", "line", "starting", "from", "my", "center", "ending", "in", "point", "p", "intersects", "me", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L4132-L4158
7,785
clientIO/joint
dist/joint.nowrap.js
function(sx, sy, origin) { origin = this.origin().scale(sx, sy, origin); this.x = origin.x; this.y = origin.y; this.width *= sx; this.height *= sy; return this; }
javascript
function(sx, sy, origin) { origin = this.origin().scale(sx, sy, origin); this.x = origin.x; this.y = origin.y; this.width *= sx; this.height *= sy; return this; }
[ "function", "(", "sx", ",", "sy", ",", "origin", ")", "{", "origin", "=", "this", ".", "origin", "(", ")", ".", "scale", "(", "sx", ",", "sy", ",", "origin", ")", ";", "this", ".", "x", "=", "origin", ".", "x", ";", "this", ".", "y", "=", "origin", ".", "y", ";", "this", ".", "width", "*=", "sx", ";", "this", ".", "height", "*=", "sy", ";", "return", "this", ";", "}" ]
Scale rectangle with origin.
[ "Scale", "rectangle", "with", "origin", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L4316-L4324
7,786
clientIO/joint
dist/joint.nowrap.js
function(domain, range, value) { var domainSpan = domain[1] - domain[0]; var rangeSpan = range[1] - range[0]; return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0; }
javascript
function(domain, range, value) { var domainSpan = domain[1] - domain[0]; var rangeSpan = range[1] - range[0]; return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0; }
[ "function", "(", "domain", ",", "range", ",", "value", ")", "{", "var", "domainSpan", "=", "domain", "[", "1", "]", "-", "domain", "[", "0", "]", ";", "var", "rangeSpan", "=", "range", "[", "1", "]", "-", "range", "[", "0", "]", ";", "return", "(", "(", "(", "value", "-", "domain", "[", "0", "]", ")", "/", "domainSpan", ")", "*", "rangeSpan", "+", "range", "[", "0", "]", ")", "||", "0", ";", "}" ]
Return the `value` from the `domain` interval scaled to the `range` interval.
[ "Return", "the", "value", "from", "the", "domain", "interval", "scaled", "to", "the", "range", "interval", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L4416-L4421
7,787
clientIO/joint
dist/joint.nowrap.js
function() { var args = []; var n = arguments.length; for (var i = 0; i < n; i++) { args.push(arguments[i]); } if (!(this instanceof Closepath)) { // switching context of `this` to Closepath when called without `new` return applyToNew(Closepath, args); } if (n > 0) { throw new Error('Closepath constructor expects no arguments.'); } return this; }
javascript
function() { var args = []; var n = arguments.length; for (var i = 0; i < n; i++) { args.push(arguments[i]); } if (!(this instanceof Closepath)) { // switching context of `this` to Closepath when called without `new` return applyToNew(Closepath, args); } if (n > 0) { throw new Error('Closepath constructor expects no arguments.'); } return this; }
[ "function", "(", ")", "{", "var", "args", "=", "[", "]", ";", "var", "n", "=", "arguments", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "args", ".", "push", "(", "arguments", "[", "i", "]", ")", ";", "}", "if", "(", "!", "(", "this", "instanceof", "Closepath", ")", ")", "{", "// switching context of `this` to Closepath when called without `new`", "return", "applyToNew", "(", "Closepath", ",", "args", ")", ";", "}", "if", "(", "n", ">", "0", ")", "{", "throw", "new", "Error", "(", "'Closepath constructor expects no arguments.'", ")", ";", "}", "return", "this", ";", "}" ]
does not inherit from any other geometry object
[ "does", "not", "inherit", "from", "any", "other", "geometry", "object" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L5179-L5196
7,788
clientIO/joint
dist/joint.nowrap.js
function(obj) { this.guid.id = this.guid.id || 1; obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id); return obj.id; }
javascript
function(obj) { this.guid.id = this.guid.id || 1; obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id); return obj.id; }
[ "function", "(", "obj", ")", "{", "this", ".", "guid", ".", "id", "=", "this", ".", "guid", ".", "id", "||", "1", ";", "obj", ".", "id", "=", "(", "obj", ".", "id", "===", "undefined", "?", "'j_'", "+", "this", ".", "guid", ".", "id", "++", ":", "obj", ".", "id", ")", ";", "return", "obj", ".", "id", ";", "}" ]
Generate global unique id for obj and store it as a property of the object.
[ "Generate", "global", "unique", "id", "for", "obj", "and", "store", "it", "as", "a", "property", "of", "the", "object", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L7980-L7985
7,789
clientIO/joint
dist/joint.nowrap.js
function(blob, fileName) { if (window.navigator.msSaveBlob) { // requires IE 10+ // pulls up a save dialog window.navigator.msSaveBlob(blob, fileName); } else { // other browsers // downloads directly in Chrome and Safari // presents a save/open dialog in Firefox // Firefox bug: `from` field in save dialog always shows `from:blob:` // https://bugzilla.mozilla.org/show_bug.cgi?id=1053327 var url = window.URL.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(url); // mark the url for garbage collection } }
javascript
function(blob, fileName) { if (window.navigator.msSaveBlob) { // requires IE 10+ // pulls up a save dialog window.navigator.msSaveBlob(blob, fileName); } else { // other browsers // downloads directly in Chrome and Safari // presents a save/open dialog in Firefox // Firefox bug: `from` field in save dialog always shows `from:blob:` // https://bugzilla.mozilla.org/show_bug.cgi?id=1053327 var url = window.URL.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(url); // mark the url for garbage collection } }
[ "function", "(", "blob", ",", "fileName", ")", "{", "if", "(", "window", ".", "navigator", ".", "msSaveBlob", ")", "{", "// requires IE 10+", "// pulls up a save dialog", "window", ".", "navigator", ".", "msSaveBlob", "(", "blob", ",", "fileName", ")", ";", "}", "else", "{", "// other browsers", "// downloads directly in Chrome and Safari", "// presents a save/open dialog in Firefox", "// Firefox bug: `from` field in save dialog always shows `from:blob:`", "// https://bugzilla.mozilla.org/show_bug.cgi?id=1053327", "var", "url", "=", "window", ".", "URL", ".", "createObjectURL", "(", "blob", ")", ";", "var", "link", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "link", ".", "href", "=", "url", ";", "link", ".", "download", "=", "fileName", ";", "document", ".", "body", ".", "appendChild", "(", "link", ")", ";", "link", ".", "click", "(", ")", ";", "document", ".", "body", ".", "removeChild", "(", "link", ")", ";", "window", ".", "URL", ".", "revokeObjectURL", "(", "url", ")", ";", "// mark the url for garbage collection", "}", "}" ]
Download `blob` as file with `fileName`. Does not work in IE9.
[ "Download", "blob", "as", "file", "with", "fileName", ".", "Does", "not", "work", "in", "IE9", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L8438-L8463
7,790
clientIO/joint
dist/joint.nowrap.js
function(dataUri, fileName) { var blob = joint.util.dataUriToBlob(dataUri); joint.util.downloadBlob(blob, fileName); }
javascript
function(dataUri, fileName) { var blob = joint.util.dataUriToBlob(dataUri); joint.util.downloadBlob(blob, fileName); }
[ "function", "(", "dataUri", ",", "fileName", ")", "{", "var", "blob", "=", "joint", ".", "util", ".", "dataUriToBlob", "(", "dataUri", ")", ";", "joint", ".", "util", ".", "downloadBlob", "(", "blob", ",", "fileName", ")", ";", "}" ]
Download `dataUri` as file with `fileName`. Does not work in IE9.
[ "Download", "dataUri", "as", "file", "with", "fileName", ".", "Does", "not", "work", "in", "IE9", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L8467-L8471
7,791
clientIO/joint
dist/joint.nowrap.js
function(url, callback) { if (!url || url.substr(0, 'data:'.length) === 'data:') { // No need to convert to data uri if it is already in data uri. // This not only convenient but desired. For example, // IE throws a security error if data:image/svg+xml is used to render // an image to the canvas and an attempt is made to read out data uri. // Now if our image is already in data uri, there is no need to render it to the canvas // and so we can bypass this error. // Keep the async nature of the function. return setTimeout(function() { callback(null, url); }, 0); } // chrome, IE10+ var modernHandler = function(xhr, callback) { if (xhr.status === 200) { var reader = new FileReader(); reader.onload = function(evt) { var dataUri = evt.target.result; callback(null, dataUri); }; reader.onerror = function() { callback(new Error('Failed to load image ' + url)); }; reader.readAsDataURL(xhr.response); } else { callback(new Error('Failed to load image ' + url)); } }; var legacyHandler = function(xhr, callback) { var Uint8ToString = function(u8a) { var CHUNK_SZ = 0x8000; var c = []; for (var i = 0; i < u8a.length; i += CHUNK_SZ) { c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ))); } return c.join(''); }; if (xhr.status === 200) { var bytes = new Uint8Array(xhr.response); var suffix = (url.split('.').pop()) || 'png'; var map = { 'svg': 'svg+xml' }; var meta = 'data:image/' + (map[suffix] || suffix) + ';base64,'; var b64encoded = meta + btoa(Uint8ToString(bytes)); callback(null, b64encoded); } else { callback(new Error('Failed to load image ' + url)); } }; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.addEventListener('error', function() { callback(new Error('Failed to load image ' + url)); }); xhr.responseType = window.FileReader ? 'blob' : 'arraybuffer'; xhr.addEventListener('load', function() { if (window.FileReader) { modernHandler(xhr, callback); } else { legacyHandler(xhr, callback); } }); xhr.send(); }
javascript
function(url, callback) { if (!url || url.substr(0, 'data:'.length) === 'data:') { // No need to convert to data uri if it is already in data uri. // This not only convenient but desired. For example, // IE throws a security error if data:image/svg+xml is used to render // an image to the canvas and an attempt is made to read out data uri. // Now if our image is already in data uri, there is no need to render it to the canvas // and so we can bypass this error. // Keep the async nature of the function. return setTimeout(function() { callback(null, url); }, 0); } // chrome, IE10+ var modernHandler = function(xhr, callback) { if (xhr.status === 200) { var reader = new FileReader(); reader.onload = function(evt) { var dataUri = evt.target.result; callback(null, dataUri); }; reader.onerror = function() { callback(new Error('Failed to load image ' + url)); }; reader.readAsDataURL(xhr.response); } else { callback(new Error('Failed to load image ' + url)); } }; var legacyHandler = function(xhr, callback) { var Uint8ToString = function(u8a) { var CHUNK_SZ = 0x8000; var c = []; for (var i = 0; i < u8a.length; i += CHUNK_SZ) { c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ))); } return c.join(''); }; if (xhr.status === 200) { var bytes = new Uint8Array(xhr.response); var suffix = (url.split('.').pop()) || 'png'; var map = { 'svg': 'svg+xml' }; var meta = 'data:image/' + (map[suffix] || suffix) + ';base64,'; var b64encoded = meta + btoa(Uint8ToString(bytes)); callback(null, b64encoded); } else { callback(new Error('Failed to load image ' + url)); } }; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.addEventListener('error', function() { callback(new Error('Failed to load image ' + url)); }); xhr.responseType = window.FileReader ? 'blob' : 'arraybuffer'; xhr.addEventListener('load', function() { if (window.FileReader) { modernHandler(xhr, callback); } else { legacyHandler(xhr, callback); } }); xhr.send(); }
[ "function", "(", "url", ",", "callback", ")", "{", "if", "(", "!", "url", "||", "url", ".", "substr", "(", "0", ",", "'data:'", ".", "length", ")", "===", "'data:'", ")", "{", "// No need to convert to data uri if it is already in data uri.", "// This not only convenient but desired. For example,", "// IE throws a security error if data:image/svg+xml is used to render", "// an image to the canvas and an attempt is made to read out data uri.", "// Now if our image is already in data uri, there is no need to render it to the canvas", "// and so we can bypass this error.", "// Keep the async nature of the function.", "return", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", "null", ",", "url", ")", ";", "}", ",", "0", ")", ";", "}", "// chrome, IE10+", "var", "modernHandler", "=", "function", "(", "xhr", ",", "callback", ")", "{", "if", "(", "xhr", ".", "status", "===", "200", ")", "{", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "reader", ".", "onload", "=", "function", "(", "evt", ")", "{", "var", "dataUri", "=", "evt", ".", "target", ".", "result", ";", "callback", "(", "null", ",", "dataUri", ")", ";", "}", ";", "reader", ".", "onerror", "=", "function", "(", ")", "{", "callback", "(", "new", "Error", "(", "'Failed to load image '", "+", "url", ")", ")", ";", "}", ";", "reader", ".", "readAsDataURL", "(", "xhr", ".", "response", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "'Failed to load image '", "+", "url", ")", ")", ";", "}", "}", ";", "var", "legacyHandler", "=", "function", "(", "xhr", ",", "callback", ")", "{", "var", "Uint8ToString", "=", "function", "(", "u8a", ")", "{", "var", "CHUNK_SZ", "=", "0x8000", ";", "var", "c", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "u8a", ".", "length", ";", "i", "+=", "CHUNK_SZ", ")", "{", "c", ".", "push", "(", "String", ".", "fromCharCode", ".", "apply", "(", "null", ",", "u8a", ".", "subarray", "(", "i", ",", "i", "+", "CHUNK_SZ", ")", ")", ")", ";", "}", "return", "c", ".", "join", "(", "''", ")", ";", "}", ";", "if", "(", "xhr", ".", "status", "===", "200", ")", "{", "var", "bytes", "=", "new", "Uint8Array", "(", "xhr", ".", "response", ")", ";", "var", "suffix", "=", "(", "url", ".", "split", "(", "'.'", ")", ".", "pop", "(", ")", ")", "||", "'png'", ";", "var", "map", "=", "{", "'svg'", ":", "'svg+xml'", "}", ";", "var", "meta", "=", "'data:image/'", "+", "(", "map", "[", "suffix", "]", "||", "suffix", ")", "+", "';base64,'", ";", "var", "b64encoded", "=", "meta", "+", "btoa", "(", "Uint8ToString", "(", "bytes", ")", ")", ";", "callback", "(", "null", ",", "b64encoded", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "'Failed to load image '", "+", "url", ")", ")", ";", "}", "}", ";", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "open", "(", "'GET'", ",", "url", ",", "true", ")", ";", "xhr", ".", "addEventListener", "(", "'error'", ",", "function", "(", ")", "{", "callback", "(", "new", "Error", "(", "'Failed to load image '", "+", "url", ")", ")", ";", "}", ")", ";", "xhr", ".", "responseType", "=", "window", ".", "FileReader", "?", "'blob'", ":", "'arraybuffer'", ";", "xhr", ".", "addEventListener", "(", "'load'", ",", "function", "(", ")", "{", "if", "(", "window", ".", "FileReader", ")", "{", "modernHandler", "(", "xhr", ",", "callback", ")", ";", "}", "else", "{", "legacyHandler", "(", "xhr", ",", "callback", ")", ";", "}", "}", ")", ";", "xhr", ".", "send", "(", ")", ";", "}" ]
Read an image at `url` and return it as base64-encoded data uri. The mime type of the image is inferred from the `url` file extension. If data uri is provided as `url`, it is returned back unchanged. `callback` is a method with `err` as first argument and `dataUri` as second argument. Works with IE9.
[ "Read", "an", "image", "at", "url", "and", "return", "it", "as", "base64", "-", "encoded", "data", "uri", ".", "The", "mime", "type", "of", "the", "image", "is", "inferred", "from", "the", "url", "file", "extension", ".", "If", "data", "uri", "is", "provided", "as", "url", "it", "is", "returned", "back", "unchanged", ".", "callback", "is", "a", "method", "with", "err", "as", "first", "argument", "and", "dataUri", "as", "second", "argument", ".", "Works", "with", "IE9", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L8507-L8591
7,792
clientIO/joint
dist/joint.nowrap.js
function(xhr, callback) { if (xhr.status === 200) { var reader = new FileReader(); reader.onload = function(evt) { var dataUri = evt.target.result; callback(null, dataUri); }; reader.onerror = function() { callback(new Error('Failed to load image ' + url)); }; reader.readAsDataURL(xhr.response); } else { callback(new Error('Failed to load image ' + url)); } }
javascript
function(xhr, callback) { if (xhr.status === 200) { var reader = new FileReader(); reader.onload = function(evt) { var dataUri = evt.target.result; callback(null, dataUri); }; reader.onerror = function() { callback(new Error('Failed to load image ' + url)); }; reader.readAsDataURL(xhr.response); } else { callback(new Error('Failed to load image ' + url)); } }
[ "function", "(", "xhr", ",", "callback", ")", "{", "if", "(", "xhr", ".", "status", "===", "200", ")", "{", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "reader", ".", "onload", "=", "function", "(", "evt", ")", "{", "var", "dataUri", "=", "evt", ".", "target", ".", "result", ";", "callback", "(", "null", ",", "dataUri", ")", ";", "}", ";", "reader", ".", "onerror", "=", "function", "(", ")", "{", "callback", "(", "new", "Error", "(", "'Failed to load image '", "+", "url", ")", ")", ";", "}", ";", "reader", ".", "readAsDataURL", "(", "xhr", ".", "response", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "'Failed to load image '", "+", "url", ")", ")", ";", "}", "}" ]
chrome, IE10+
[ "chrome", "IE10", "+" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L8525-L8544
7,793
clientIO/joint
dist/joint.nowrap.js
function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; if (this.svgElement) this.vel = V(this.el); }
javascript
function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; if (this.svgElement) this.vel = V(this.el); }
[ "function", "(", "el", ")", "{", "this", ".", "$el", "=", "el", "instanceof", "Backbone", ".", "$", "?", "el", ":", "Backbone", ".", "$", "(", "el", ")", ";", "this", ".", "el", "=", "this", ".", "$el", "[", "0", "]", ";", "if", "(", "this", ".", "svgElement", ")", "this", ".", "vel", "=", "V", "(", "this", ".", "el", ")", ";", "}" ]
Utilize an alternative DOM manipulation API by adding an element reference wrapped in Vectorizer.
[ "Utilize", "an", "alternative", "DOM", "manipulation", "API", "by", "adding", "an", "element", "reference", "wrapped", "in", "Vectorizer", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L9649-L9653
7,794
clientIO/joint
dist/joint.nowrap.js
function(cells, opt) { var preparedCells = joint.util.toArray(cells).map(function(cell) { return this._prepareCell(cell, opt); }, this); this.get('cells').reset(preparedCells, opt); return this; }
javascript
function(cells, opt) { var preparedCells = joint.util.toArray(cells).map(function(cell) { return this._prepareCell(cell, opt); }, this); this.get('cells').reset(preparedCells, opt); return this; }
[ "function", "(", "cells", ",", "opt", ")", "{", "var", "preparedCells", "=", "joint", ".", "util", ".", "toArray", "(", "cells", ")", ".", "map", "(", "function", "(", "cell", ")", "{", "return", "this", ".", "_prepareCell", "(", "cell", ",", "opt", ")", ";", "}", ",", "this", ")", ";", "this", ".", "get", "(", "'cells'", ")", ".", "reset", "(", "preparedCells", ",", "opt", ")", ";", "return", "this", ";", "}" ]
When adding a lot of cells, it is much more efficient to reset the entire cells collection in one go. Useful for bulk operations and optimizations.
[ "When", "adding", "a", "lot", "of", "cells", "it", "is", "much", "more", "efficient", "to", "reset", "the", "entire", "cells", "collection", "in", "one", "go", ".", "Useful", "for", "bulk", "operations", "and", "optimizations", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L10185-L10193
7,795
clientIO/joint
dist/joint.nowrap.js
function(elementA, elementB) { var isSuccessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isSuccessor = true; return false; } }, { outbound: true }); return isSuccessor; }
javascript
function(elementA, elementB) { var isSuccessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isSuccessor = true; return false; } }, { outbound: true }); return isSuccessor; }
[ "function", "(", "elementA", ",", "elementB", ")", "{", "var", "isSuccessor", "=", "false", ";", "this", ".", "search", "(", "elementA", ",", "function", "(", "element", ")", "{", "if", "(", "element", "===", "elementB", "&&", "element", "!==", "elementA", ")", "{", "isSuccessor", "=", "true", ";", "return", "false", ";", "}", "}", ",", "{", "outbound", ":", "true", "}", ")", ";", "return", "isSuccessor", ";", "}" ]
Return `true` is `elementB` is a successor of `elementA`. Return `false` otherwise.
[ "Return", "true", "is", "elementB", "is", "a", "successor", "of", "elementA", ".", "Return", "false", "otherwise", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L10723-L10733
7,796
clientIO/joint
dist/joint.nowrap.js
function(elementA, elementB) { var isPredecessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isPredecessor = true; return false; } }, { inbound: true }); return isPredecessor; }
javascript
function(elementA, elementB) { var isPredecessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isPredecessor = true; return false; } }, { inbound: true }); return isPredecessor; }
[ "function", "(", "elementA", ",", "elementB", ")", "{", "var", "isPredecessor", "=", "false", ";", "this", ".", "search", "(", "elementA", ",", "function", "(", "element", ")", "{", "if", "(", "element", "===", "elementB", "&&", "element", "!==", "elementA", ")", "{", "isPredecessor", "=", "true", ";", "return", "false", ";", "}", "}", ",", "{", "inbound", ":", "true", "}", ")", ";", "return", "isPredecessor", ";", "}" ]
Return `true` is `elementB` is a predecessor of `elementA`. Return `false` otherwise.
[ "Return", "true", "is", "elementB", "is", "a", "predecessor", "of", "elementA", ".", "Return", "false", "otherwise", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L10736-L10746
7,797
clientIO/joint
dist/joint.nowrap.js
function(model, opt) { this.getConnectedLinks(model).forEach(function(link) { link.set((link.source().id === model.id ? 'source' : 'target'), { x: 0, y: 0 }, opt); }); }
javascript
function(model, opt) { this.getConnectedLinks(model).forEach(function(link) { link.set((link.source().id === model.id ? 'source' : 'target'), { x: 0, y: 0 }, opt); }); }
[ "function", "(", "model", ",", "opt", ")", "{", "this", ".", "getConnectedLinks", "(", "model", ")", ".", "forEach", "(", "function", "(", "link", ")", "{", "link", ".", "set", "(", "(", "link", ".", "source", "(", ")", ".", "id", "===", "model", ".", "id", "?", "'source'", ":", "'target'", ")", ",", "{", "x", ":", "0", ",", "y", ":", "0", "}", ",", "opt", ")", ";", "}", ")", ";", "}" ]
Disconnect links connected to the cell `model`.
[ "Disconnect", "links", "connected", "to", "the", "cell", "model", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L10787-L10793
7,798
clientIO/joint
dist/joint.nowrap.js
function(rect, opt) { rect = g.rect(rect); opt = joint.util.defaults(opt || {}, { strict: false }); var method = opt.strict ? 'containsRect' : 'intersect'; return this.getElements().filter(function(el) { return rect[method](el.getBBox()); }); }
javascript
function(rect, opt) { rect = g.rect(rect); opt = joint.util.defaults(opt || {}, { strict: false }); var method = opt.strict ? 'containsRect' : 'intersect'; return this.getElements().filter(function(el) { return rect[method](el.getBBox()); }); }
[ "function", "(", "rect", ",", "opt", ")", "{", "rect", "=", "g", ".", "rect", "(", "rect", ")", ";", "opt", "=", "joint", ".", "util", ".", "defaults", "(", "opt", "||", "{", "}", ",", "{", "strict", ":", "false", "}", ")", ";", "var", "method", "=", "opt", ".", "strict", "?", "'containsRect'", ":", "'intersect'", ";", "return", "this", ".", "getElements", "(", ")", ".", "filter", "(", "function", "(", "el", ")", "{", "return", "rect", "[", "method", "]", "(", "el", ".", "getBBox", "(", ")", ")", ";", "}", ")", ";", "}" ]
Find all elements in given area
[ "Find", "all", "elements", "in", "given", "area" ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L10810-L10820
7,799
clientIO/joint
dist/joint.nowrap.js
function(element, opt) { opt = joint.util.defaults(opt || {}, { searchBy: 'bbox' }); var bbox = element.getBBox(); var elements = (opt.searchBy === 'bbox') ? this.findModelsInArea(bbox) : this.findModelsFromPoint(bbox[opt.searchBy]()); // don't account element itself or any of its descendents return elements.filter(function(el) { return element.id !== el.id && !el.isEmbeddedIn(element); }); }
javascript
function(element, opt) { opt = joint.util.defaults(opt || {}, { searchBy: 'bbox' }); var bbox = element.getBBox(); var elements = (opt.searchBy === 'bbox') ? this.findModelsInArea(bbox) : this.findModelsFromPoint(bbox[opt.searchBy]()); // don't account element itself or any of its descendents return elements.filter(function(el) { return element.id !== el.id && !el.isEmbeddedIn(element); }); }
[ "function", "(", "element", ",", "opt", ")", "{", "opt", "=", "joint", ".", "util", ".", "defaults", "(", "opt", "||", "{", "}", ",", "{", "searchBy", ":", "'bbox'", "}", ")", ";", "var", "bbox", "=", "element", ".", "getBBox", "(", ")", ";", "var", "elements", "=", "(", "opt", ".", "searchBy", "===", "'bbox'", ")", "?", "this", ".", "findModelsInArea", "(", "bbox", ")", ":", "this", ".", "findModelsFromPoint", "(", "bbox", "[", "opt", ".", "searchBy", "]", "(", ")", ")", ";", "// don't account element itself or any of its descendents", "return", "elements", ".", "filter", "(", "function", "(", "el", ")", "{", "return", "element", ".", "id", "!==", "el", ".", "id", "&&", "!", "el", ".", "isEmbeddedIn", "(", "element", ")", ";", "}", ")", ";", "}" ]
Find all elements under the given element.
[ "Find", "all", "elements", "under", "the", "given", "element", "." ]
99ba02fe6c64e407bdfff6ba595d2068422c3e76
https://github.com/clientIO/joint/blob/99ba02fe6c64e407bdfff6ba595d2068422c3e76/dist/joint.nowrap.js#L10823-L10836