code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
appendBuffer(buffer) {
if (this.audioBuffer.updating || this.audioQueue.length > 0) {
this.audioQueue.push(buffer);
}
else {
this.audioBuffer.appendBuffer(buffer);
}
} | Appends or queue's audio data into the buffer.
@param {*} buffer | appendBuffer ( buffer ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/audio_player.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/audio_player.js | Apache-2.0 |
setupAudioProcessor() {
this.mediaSource.addEventListener('sourceopen', () => {
this.audioBuffer = this.mediaSource.addSourceBuffer('audio/mpeg');
this.audioBuffer.mode = 'sequence';
this.audioBuffer.addEventListener('update', () => {
if (
this.audioQueue.length > 0
&& this.audioBuffer
&& !this.audioBuffer.updating
) {
this.audioBuffer.appendBuffer(this.audioQueue.shift());
this.play();
}
});
this.audioBuffer.addEventListener('error', (e) => {
console.log('AudioBuffer Error: ', e);
});
this.emit('ready');
});
} | Set's up the audio processor required to process the mpeg receiving by Google. | setupAudioProcessor ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/audio_player.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/audio_player.js | Apache-2.0 |
play() {
this.audioPlayer.setSinkId(this.audioOutDeviceId);
if (this.audioPlayer.paused) {
this.audioPlayer
.play()
.then(() => {
console.log('Assistant Audio is playing...');
})
.catch((e) => {
console.log('something went wrong starting the player...', e);
});
}
} | Play's the Audio Player if nessesary. | play ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/audio_player.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/audio_player.js | Apache-2.0 |
stop() {
this.audioQueue = [];
this.audioPlayer.src = '';
this.reset();
} | Empties the audioQueue and resets the current player. | stop ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/audio_player.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/audio_player.js | Apache-2.0 |
setDeviceId(audioOutDeviceId) {
this.audioOutDeviceId = audioOutDeviceId;
this.audioPlayer.setSinkId(this.audioOutDeviceId);
} | Sets the `sinkId` of the audio element to the given
speaker's device ID.
@param {string} audioOutDeviceId
Device ID of desired speaker source | setDeviceId ( audioOutDeviceId ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/audio_player.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/audio_player.js | Apache-2.0 |
stop() {
if (!this.isActive) return;
this.stream.disconnect();
this.rawStream.getTracks().forEach((track) => track.stop());
this.audioProcessor.disconnect();
this.audioProcessor.onaudioprocess = null;
this.audioProcessor = null;
this.emit('mic-stopped');
} | Closes the Microphone stream for the browser. | stop ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/microphone.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/microphone.js | Apache-2.0 |
get isActive() {
return this.audioProcessor !== null;
} | Getter function for checking if the microphone is active. | isActive ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/microphone.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/microphone.js | Apache-2.0 |
setDeviceId(audioInDeviceId) {
this.audioInDeviceId = audioInDeviceId;
} | Sets the `audioInDeviceId` to provided Device ID.
@param {string} audioInDeviceId
Device ID of desired microphone source | setDeviceId ( audioInDeviceId ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/microphone.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/microphone.js | Apache-2.0 |
onAudioProcess(event) {
let data = event.inputBuffer.getChannelData(0);
data = this.downsampleBuffer(data);
// [TODO]: Implement piping?
this.emit('data', data);
} | Processes the audio to be ready for Google.
@param event event | onAudioProcess ( event ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/microphone.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/microphone.js | Apache-2.0 |
downsampleBuffer(buffer) {
if (this.audioContext.sampleRate === this.sampleRate) {
return buffer;
}
const sampleRateRatio = this.audioContext.sampleRate / this.sampleRate;
const newLength = Math.round(buffer.length / sampleRateRatio);
const result = new Int16Array(newLength);
let offsetResult = 0;
let offsetBuffer = 0;
while (offsetResult < result.length) {
const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
let accum = 0;
let count = 0;
for (
let i = offsetBuffer;
i < nextOffsetBuffer && i < buffer.length;
i += 1
) {
accum += buffer[i];
count += 1;
}
result[offsetResult] = Math.min(1, accum / count) * 0x7fff;
offsetResult += 1;
offsetBuffer = nextOffsetBuffer;
}
return result.buffer;
} | Downsamles the buffer if needed to right sampleRate & converts the data into an int16 buffer
@param buffer buffer | downsampleBuffer ( buffer ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/lib/microphone.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/microphone.js | Apache-2.0 |
async function isCommandAvailable(cmdName) {
return new Promise((resolve, _) => {
cp.exec(`which ${cmdName}`, (err, stdout, stderr) => {
if (err || stderr) {
resolve(false);
}
resolve(true);
});
});
} | Checks if a given command exists in the current system
@param {string} cmdName
Name of the command whose existance has to be checked
@returns {Promise<boolean>}
Boolean value based on command availibility | isCommandAvailable ( cmdName ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterUtils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterUtils.js | Apache-2.0 |
async function getSupportedLinuxPackageFormat() {
if (process.platform !== 'linux') return null;
const hasDpkg = await isCommandAvailable('dpkg');
const hasRpm = await isCommandAvailable('rpm');
if (hasDpkg) {
return 'deb';
}
if (hasRpm) {
return 'rpm';
}
return null;
} | Checks the preferred package format (deb or rpm) for
current linux system. If the host system is not linux,
`null` is returned. | getSupportedLinuxPackageFormat ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterUtils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterUtils.js | Apache-2.0 |
function getTagReleaseLink(version) {
return `${releasesUrl}/tag/${version}`;
} | Returns link for GitHub Release page for a given
version tag
@param {string} version
Tag name (i.e., version). The version should be
prefixed with a `v` | getTagReleaseLink ( version ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterUtils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterUtils.js | Apache-2.0 |
constructor(rendererWindow, app, shouldAutoDownload) {
this.rendererWindow = rendererWindow;
this.app = app;
this.shouldAutoDownload = shouldAutoDownload;
this.postUpdateDownloadInfo = null;
this._isDownloadCached = false;
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
} | Creates updater service object
@param {import('electron').BrowserWindow} rendererWindow
Renderer window to communicate update status.
@param {import('electron').App} app
App instance to quit before updating.
@param {boolean} shouldAutoDownload
Specify if any new update should be downloaded
automatically. | constructor ( rendererWindow , app , shouldAutoDownload ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
static shouldUseGenericUpdater() {
return isDebOrRpm() || isSnap() || process.env.DEV_MODE;
} | Checks if a generic updater should be used over electron
auto-updater based on platform, package format and environment. | shouldUseGenericUpdater ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
sendStatusToWindow(status, arg) {
if (status === undefined) return;
const currentStatus = status ?? this.currentStatus;
const currentInfo = arg ?? this.currentInfo;
this.currentStatus = currentStatus;
this.currentInfo = currentInfo;
if (this.rendererWindow.isDestroyed()) return;
this.rendererWindow.webContents.send(currentStatus, currentInfo);
} | Sends the updater status and args to renderer process.
Also updates the current status in the updater service.
@param {string?} status
@param {any?} arg | sendStatusToWindow ( status , arg ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
getChangelog() {
const releaseNotes = this.currentInfo?.releaseNotes;
return releaseNotes;
} | Returns changelog of either the current version or
the new version available as a string of HTML
@returns {string?} | getChangelog ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
installMacUpdate(onUpdateApplied) {
const { downloadedFile } = this.postUpdateDownloadInfo;
const cacheFolder = path.dirname(downloadedFile);
// Path to the `.app` folder
const appPath = path.resolve(this.app.getAppPath(), '../../..');
const appPathParent = path.dirname(appPath);
this.sendStatusToWindow(UpdaterStatus.InstallingUpdate, {
downloadedFile,
cacheFolder,
appPath,
appPathParent,
});
if (fs.existsSync(`${cacheFolder}/Google Assistant.app`)) {
cp.execSync(`rm -rf "${cacheFolder}/Google Assistant.app"`);
}
// Extract the downloaded archive
const appExtractionCmd = `ditto -x -k "${downloadedFile}" "${cacheFolder}"`;
cp.exec(appExtractionCmd, (err, stdout, stderr) => {
if (err) {
displayDialogMain({
type: 'error',
message: 'Error occurred while extracting archive',
detail: err.message,
});
return;
}
// Delete existing `.app` in application directory
// to avoid problems with moving the updated version
// to the destination.
const removeExistingApp = `rm -rf "${appPath}"`;
// Copy the extracted `.app` to the application directory
const moveUpdateToApplications = [
'mv',
`"${cacheFolder}/Google Assistant.app"`,
`"${appPathParent}"`,
].join(' ');
// Apply update (remove and move update)
cp.execSync(`${removeExistingApp} && ${moveUpdateToApplications}`);
this.sendStatusToWindow(UpdaterStatus.UpdateApplied, null);
onUpdateApplied();
});
} | Installs update on MacOS
@param {() => void} onUpdateApplied
Callback function called after update is installed | installMacUpdate ( onUpdateApplied ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
installUpdateAndRestart() {
// Prevent the app from applying the same update
// multiple times in a row
if (this.app.isUpdating) return;
this.app.isQuitting = true;
this.app.isUpdating = true;
if (process.platform !== 'darwin') {
autoUpdater.quitAndInstall(true, true);
}
else {
this.installMacUpdate(() => {
this.app.relaunch();
this.app.quit();
});
}
} | Restarts the application after applying update | installUpdateAndRestart ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
installUpdateAndQuit() {
// Prevent the app from applying the same update
// multiple times in a row
if (this.app.isUpdating) return;
this.app.isQuitting = true;
this.app.isUpdating = true;
if (process.platform !== 'darwin') {
autoUpdater.quitAndInstall(true);
}
else {
this.installMacUpdate(() => {
this.app.quit();
});
}
} | Quits the application after applying update | installUpdateAndQuit ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
static checkForUpdates() {
if (!UpdaterService.shouldUseGenericUpdater()) {
autoUpdater.checkForUpdates();
}
else {
updaterGeneric.checkForUpdates();
}
} | Checks for an update and notifies the user when available | checkForUpdates ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterMain.js | Apache-2.0 |
on(channel, listener) {
super.on(channel, listener);
} | @param {UpdaterGenericEvent} channel
@param {(...args: any[]) => void} listener
@override | on ( channel , listener ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/updater/updaterGeneric.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/updater/updaterGeneric.js | Apache-2.0 |
function isSnap() {
return (
process.platform === 'linux'
&& process.env.SNAP !== undefined
);
} | Returns `true` if the assistant is running as a
snap application (linux). | isSnap ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function isAppImage() {
return (
process.platform === 'linux'
&& process.env.APPIMAGE !== undefined
);
} | Returns `true` if the assistant is running as an
AppImage application (linux). | isAppImage ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function isDebOrRpm() {
return (
process.platform === 'linux'
&& process.env.APPIMAGE === undefined
&& process.env.SNAP === undefined
);
} | Checks if the currently installed package is a `.deb`
or `.rpm` package. | isDebOrRpm ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function isWaylandSession() {
if (process.platform !== 'linux') return false;
return (
process.env['WAYLAND_DISPLAY'] !== undefined
|| process.env['XDG_SESSION_TYPE'] !== 'x11'
);
} | Checks whether the current system session uses the Wayland
windowing system | isWaylandSession ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function displayDialog(options) {
return ipcRenderer.sendSync('display-dialog', options);
} | Displays a dialog box
@param {Electron.MessageBoxSyncOptions} options
Options for creating a dialog box
@returns {number}
Index of the button clicked | displayDialog ( options ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function displayAsyncDialog(options) {
return ipcRenderer.invoke('display-async-dialog', options);
} | Displays an async dialog box
@param {Electron.MessageBoxOptions} options
Options for creating a dialog box
@returns {Promise<Electron.MessageBoxReturnValue>}
The returned value (possibly number) as promise | displayAsyncDialog ( options ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function displayAsyncOpenDialog(options) {
return ipcRenderer.invoke('display-async-open-dialog', options);
} | Displays an async dialog box
@param {Electron.OpenDialogOptions} options
Options for creating a dialog box
@returns {Promise<Electron.OpenDialogReturnValue>}
The returned value as promise | displayAsyncOpenDialog ( options ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utils.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utils.js | Apache-2.0 |
function getMainWindow() {
return global.mainWindow;
} | Returns the browser window created by the
main process
@returns {Electron.BrowserWindow} | getMainWindow ( ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utilsMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utilsMain.js | Apache-2.0 |
function displayErrorBoxMain(title, content) {
// Prevent close on blur when the error box
// is in foreground. Not required on "linux"
// as the error message is printed in the console
// instead of showing a dialog.
if (process.platform !== 'linux') {
global.allowCloseOnBlur = false;
}
dialog.showErrorBox(title, content);
} | Displays a modal dialog that shows an error message.
Emits error message to the console (stderr) in Linux.
@param {string} title
@param {string} content | displayErrorBoxMain ( title , content ) | javascript | Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client | app/src/common/utilsMain.js | https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/common/utilsMain.js | Apache-2.0 |
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}()); | requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
@see: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
@see: http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
@license: MIT license | (anonymous) ( ) | javascript | itsron143/ParticleGround-Portfolio | js/jquery.particleground.js | https://github.com/itsron143/ParticleGround-Portfolio/blob/master/js/jquery.particleground.js | MIT |
humanize.naturalDay = function(timestamp, format) {
timestamp = (timestamp === undefined) ? humanize.time() : timestamp;
format = (format === undefined) ? 'Y-m-d' : format;
var oneDay = 86400;
var d = new Date();
var today = (new Date(d.getFullYear(), d.getMonth(), d.getDate())).getTime() / 1000;
if (timestamp < today && timestamp >= today - oneDay) {
return 'yesterday';
} else if (timestamp >= today && timestamp < today + oneDay) {
return 'today';
} else if (timestamp >= today + oneDay && timestamp < today + 2 * oneDay) {
return 'tomorrow';
}
return humanize.date(format, timestamp);
}; | For dates that are the current day or within one day, return 'today', 'tomorrow' or 'yesterday', as appropriate.
Otherwise, format the date using the passed in format string.
Examples (when 'today' is 17 Feb 2007):
16 Feb 2007 becomes yesterday.
17 Feb 2007 becomes today.
18 Feb 2007 becomes tomorrow.
Any other day is formatted according to given argument or the DATE_FORMAT setting if no argument is given. | humanize.naturalDay ( timestamp , format ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.ordinal = function(number) {
number = parseInt(number, 10);
number = isNaN(number) ? 0 : number;
var sign = number < 0 ? '-' : '';
number = Math.abs(number);
return sign + number + (number > 4 && number < 21 ? 'th' : {1: 'st', 2: 'nd', 3: 'rd'}[number % 10] || 'th');
}; | Converts an integer to its ordinal as a string.
1 becomes 1st
2 becomes 2nd
3 becomes 3rd etc | humanize.ordinal ( number ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.filesize = function(filesize, kilo, decimals, decPoint, thousandsSep) {
kilo = (kilo === undefined) ? 1024 : kilo;
decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
decPoint = (decPoint === undefined) ? '.' : decPoint;
thousandsSep = (thousandsSep === undefined) ? ',' : thousandsSep;
if (filesize <= 0) { return '0 bytes'; }
var thresholds = [1];
var units = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
if (filesize < kilo) { return humanize.numberFormat(filesize, 0) + ' ' + units[0]; }
for (var i = 1; i < units.length; i++) {
thresholds[i] = thresholds[i-1] * kilo;
if (filesize < thresholds[i]) {
return humanize.numberFormat(filesize / thresholds[i-1], decimals, decPoint, thousandsSep) + ' ' + units[i-1];
}
}
// use the last unit if we drop out to here
return humanize.numberFormat(filesize / thresholds[units.length - 1], decimals, decPoint, thousandsSep) + ' ' + units[units.length - 1];
}; | Formats the value like a 'human-readable' file size (i.e. '13 KB', '4.1 MB', '102 bytes', etc).
For example:
If value is 123456789, the output would be 117.7 MB. | humanize.filesize ( filesize , kilo , decimals , decPoint , thousandsSep ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.linebreaks = function(str) {
// remove beginning and ending newlines
str = str.replace(/^([\n|\r]*)/, '');
str = str.replace(/([\n|\r]*)$/, '');
// normalize all to \n
str = str.replace(/(\r\n|\n|\r)/g, "\n");
// any consecutive new lines more than 2 gets turned into p tags
str = str.replace(/(\n{2,})/g, '</p><p>');
// any that are singletons get turned into br
str = str.replace(/\n/g, '<br />');
return '<p>' + str + '</p>';
}; | Replaces line breaks in plain text with appropriate HTML
A single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).
For example:
If value is Joel\nis a\n\nslug, the output will be <p>Joel<br />is a</p><p>slug</p> | humanize.linebreaks ( str ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.nl2br = function(str) {
return str.replace(/(\r\n|\n|\r)/g, '<br />');
}; | Converts all newlines in a piece of plain text to HTML line breaks (<br />). | humanize.nl2br ( str ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.truncatechars = function(string, length) {
if (string.length <= length) { return string; }
return string.substr(0, length) + '…';
}; | Truncates a string if it is longer than the specified number of characters.
Truncated strings will end with a translatable ellipsis sequence ('…'). | humanize.truncatechars ( string , length ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.truncatewords = function(string, numWords) {
var words = string.split(' ');
if (words.length < numWords) { return string; }
return words.slice(0, numWords).join(' ') + '…';
}; | Truncates a string after a certain number of words.
Newlines within the string will be removed. | humanize.truncatewords ( string , numWords ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
humanize.relativeTime = function(timestamp) {
timestamp = (timestamp === undefined) ? humanize.time() : timestamp;
var currTime = humanize.time();
var timeDiff = currTime - timestamp;
// within 2 seconds
if (timeDiff < 2 && timeDiff > -2) {
return (timeDiff >= 0 ? 'just ' : '') + 'now';
}
// within a minute
if (timeDiff < 60 && timeDiff > -60) {
return (timeDiff >= 0 ? Math.floor(timeDiff) + ' seconds ago' : 'in ' + Math.floor(-timeDiff) + ' seconds');
}
// within 2 minutes
if (timeDiff < 120 && timeDiff > -120) {
return (timeDiff >= 0 ? 'about a minute ago' : 'in about a minute');
}
// within an hour
if (timeDiff < 3600 && timeDiff > -3600) {
return (timeDiff >= 0 ? Math.floor(timeDiff / 60) + ' minutes ago' : 'in ' + Math.floor(-timeDiff / 60) + ' minutes');
}
// within 2 hours
if (timeDiff < 7200 && timeDiff > -7200) {
return (timeDiff >= 0 ? 'about an hour ago' : 'in about an hour');
}
// within 24 hours
if (timeDiff < 86400 && timeDiff > -86400) {
return (timeDiff >= 0 ? Math.floor(timeDiff / 3600) + ' hours ago' : 'in ' + Math.floor(-timeDiff / 3600) + ' hours');
}
// within 2 days
var days2 = 2 * 86400;
if (timeDiff < days2 && timeDiff > -days2) {
return (timeDiff >= 0 ? '1 day ago' : 'in 1 day');
}
// within 29 days
var days29 = 29 * 86400;
if (timeDiff < days29 && timeDiff > -days29) {
return (timeDiff >= 0 ? Math.floor(timeDiff / 86400) + ' days ago' : 'in ' + Math.floor(-timeDiff / 86400) + ' days');
}
// within 60 days
var days60 = 60 * 86400;
if (timeDiff < days60 && timeDiff > -days60) {
return (timeDiff >= 0 ? 'about a month ago' : 'in about a month');
}
var currTimeYears = parseInt(humanize.date('Y', currTime), 10);
var timestampYears = parseInt(humanize.date('Y', timestamp), 10);
var currTimeMonths = currTimeYears * 12 + parseInt(humanize.date('n', currTime), 10);
var timestampMonths = timestampYears * 12 + parseInt(humanize.date('n', timestamp), 10);
// within a year
var monthDiff = currTimeMonths - timestampMonths;
if (monthDiff < 12 && monthDiff > -12) {
return (monthDiff >= 0 ? monthDiff + ' months ago' : 'in ' + (-monthDiff) + ' months');
}
var yearDiff = currTimeYears - timestampYears;
if (yearDiff < 2 && yearDiff > -2) {
return (yearDiff >= 0 ? 'a year ago' : 'in a year');
}
return (yearDiff >= 0 ? yearDiff + ' years ago' : 'in ' + (-yearDiff) + ' years');
};
/**
* Converts an integer to its ordinal as a string.
*
* 1 becomes 1st
* 2 becomes 2nd
* 3 becomes 3rd etc
*/
humanize.ordinal = function(number) {
number = parseInt(number, 10);
number = isNaN(number) ? 0 : number;
var sign = number < 0 ? '-' : '';
number = Math.abs(number);
return sign + number + (number > 4 && number < 21 ? 'th' : {1: 'st', 2: 'nd', 3: 'rd'}[number % 10] || 'th');
};
/**
* Formats the value like a 'human-readable' file size (i.e. '13 KB', '4.1 MB', '102 bytes', etc).
*
* For example:
* If value is 123456789, the output would be 117.7 MB.
*/
humanize.filesize = function(filesize, kilo, decimals, decPoint, thousandsSep) {
kilo = (kilo === undefined) ? 1024 : kilo;
decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
decPoint = (decPoint === undefined) ? '.' : decPoint;
thousandsSep = (thousandsSep === undefined) ? ',' : thousandsSep;
if (filesize <= 0) { return '0 bytes'; }
var thresholds = [1];
var units = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
if (filesize < kilo) { return humanize.numberFormat(filesize, 0) + ' ' + units[0]; }
for (var i = 1; i < units.length; i++) {
thresholds[i] = thresholds[i-1] * kilo;
if (filesize < thresholds[i]) {
return humanize.numberFormat(filesize / thresholds[i-1], decimals, decPoint, thousandsSep) + ' ' + units[i-1];
}
}
// use the last unit if we drop out to here
return humanize.numberFormat(filesize / thresholds[units.length - 1], decimals, decPoint, thousandsSep) + ' ' + units[units.length - 1];
};
/**
* Replaces line breaks in plain text with appropriate HTML
* A single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).
*
* For example:
* If value is Joel\nis a\n\nslug, the output will be <p>Joel<br />is a</p><p>slug</p>
*/
humanize.linebreaks = function(str) {
// remove beginning and ending newlines
str = str.replace(/^([\n|\r]*)/, '');
str = str.replace(/([\n|\r]*)$/, '');
// normalize all to \n
str = str.replace(/(\r\n|\n|\r)/g, "\n");
// any consecutive new lines more than 2 gets turned into p tags
str = str.replace(/(\n{2,})/g, '</p><p>');
// any that are singletons get turned into br
str = str.replace(/\n/g, '<br />');
return '<p>' + str + '</p>';
};
/**
* Converts all newlines in a piece of plain text to HTML line breaks (<br />).
*/
humanize.nl2br = function(str) {
return str.replace(/(\r\n|\n|\r)/g, '<br />');
};
/**
* Truncates a string if it is longer than the specified number of characters.
* Truncated strings will end with a translatable ellipsis sequence ('…').
*/
humanize.truncatechars = function(string, length) {
if (string.length <= length) { return string; }
return string.substr(0, length) + '…';
};
/**
* Truncates a string after a certain number of words.
* Newlines within the string will be removed.
*/
humanize.truncatewords = function(string, numWords) {
var words = string.split(' ');
if (words.length < numWords) { return string; }
return words.slice(0, numWords).join(' ') + '…';
};
}).call(this); | returns a string representing how many seconds, minutes or hours ago it was or will be in the future
Will always return a relative time, most granular of seconds to least granular of years. See unit tests for more details | humanize.relativeTime ( timestamp ) | javascript | yona-projects/yona | public/javascripts/lib/humanize.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/humanize.js | Apache-2.0 |
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(jQuery);
}
}(this, function ($) { | at.js - 1.5.3
Copyright (c) 2017 chord.luo <[email protected]>;
Homepage: http://ichord.github.com/At.js
License: MIT | (anonymous) ( root , factory ) | javascript | yona-projects/yona | public/javascripts/lib/atjs/jquery.atwho.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/atjs/jquery.atwho.js | Apache-2.0 |
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "결과 없음"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "너무 짧습니다. "+n+"글자 더 입력해주세요."; },
formatInputTooLong: function (input, max) { var n = input.length - max; return "너무 깁니다. "+n+"글자 지워주세요."; },
formatSelectionTooBig: function (limit) { return "최대 "+limit+"개까지만 선택하실 수 있습니다."; },
formatLoadMore: function (pageNumber) { return "불러오는 중…"; },
formatSearching: function () { return "검색 중…"; }
});
})(jQuery); | Select2 <Language> translation.
Author: Swen Mun <[email protected]> | (anonymous) ( $ ) | javascript | yona-projects/yona | public/javascripts/lib/select2/select2_locale_ko.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/select2/select2_locale_ko.js | Apache-2.0 |
renderDayName = function(opts, day, abbr)
{
day += opts.firstDay;
while (day >= 7) {
day -= 7;
}
return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];
}, | templating functions to abstract HTML rendering | renderDayName ( opts , day , abbr ) | javascript | yona-projects/yona | public/javascripts/lib/pikaday/pikaday.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/pikaday/pikaday.js | Apache-2.0 |
gotoMonth: function(month)
{
if (!isNaN(month)) {
this.calendars[0].month = parseInt(month, 10);
this.adjustCalendars();
}
}, | change view to a specific month (zero-index, e.g. 0: January) | gotoMonth ( month ) | javascript | yona-projects/yona | public/javascripts/lib/pikaday/pikaday.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/pikaday/pikaday.js | Apache-2.0 |
gotoYear: function(year)
{
if (!isNaN(year)) {
this.calendars[0].year = parseInt(year, 10);
this.adjustCalendars();
}
}, | change view to a specific full year (e.g. "2012") | gotoYear ( year ) | javascript | yona-projects/yona | public/javascripts/lib/pikaday/pikaday.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/pikaday/pikaday.js | Apache-2.0 |
function versionCompare(v1, v2) {
var v1parts = ("" + v1).split("."),
v2parts = ("" + v2).split("."),
minLength = Math.min(v1parts.length, v2parts.length),
p1, p2, i;
// Compare tuple pair-by-pair.
for(i = 0; i < minLength; i++) {
// Convert to integer if possible, because "8" > "10".
p1 = parseInt(v1parts[i], 10);
p2 = parseInt(v2parts[i], 10);
if (isNaN(p1)){ p1 = v1parts[i]; }
if (isNaN(p2)){ p2 = v2parts[i]; }
if (p1 == p2) {
continue;
}else if (p1 > p2) {
return 1;
}else if (p1 < p2) {
return -1;
}
// one operand is NaN
return NaN;
}
// The longer tuple is always considered 'greater'
if (v1parts.length === v2parts.length) {
return 0;
}
return (v1parts.length < v2parts.length) ? -1 : 1;
} | Compare two dotted version strings (like '10.2.3').
@returns {Integer} 0: v1 == v2, -1: v1 < v2, 1: v1 > v2 | versionCompare ( v1 , v2 ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.dynatree.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.dynatree.js | Apache-2.0 |
$.widget("ui.dynatree", {
/*
init: function() {
// ui.core 1.6 renamed init() to _init(): this stub assures backward compatibility
_log("warn", "ui.dynatree.init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher.");
return this._init();
},
*/
_init: function() {
// if( parseFloat($.ui.version) < 1.8 ) {
if(versionCompare($.ui.version, "1.8") < 0){
// jquery.ui.core 1.8 renamed _init() to _create(): this stub assures backward compatibility
if(this.options.debugLevel >= 0){
_log("warn", "ui.dynatree._init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher.");
}
return this._create();
}
// jquery.ui.core 1.8 still uses _init() to perform "default functionality"
if(this.options.debugLevel >= 2){
_log("debug", "ui.dynatree._init() was called; no current default functionality.");
}
}, | ***********************************************************************
Widget $(..).dynatree | $.widget ( "ui.dynatree" , { _init : function ( ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.dynatree.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.dynatree.js | Apache-2.0 |
function _initDragAndDrop(tree) {
var dnd = tree.options.dnd || null;
// Register 'connectToDynatree' option with ui.draggable
if(dnd && (dnd.onDragStart || dnd.onDrop)) {
_registerDnd();
}
// Attach ui.draggable to this Dynatree instance
if(dnd && dnd.onDragStart ) {
tree.$tree.draggable({
addClasses: false,
appendTo: "body",
containment: false,
delay: 0,
distance: 4,
revert: false,
scroll: true, // issue 244: enable scrolling (if ul.dynatree-container)
scrollSpeed: 7,
scrollSensitivity: 10,
// Delegate draggable.start, drag, and stop events to our handler
connectToDynatree: true,
// Let source tree create the helper element
helper: function(event) {
var sourceNode = $.ui.dynatree.getNode(event.target);
if(!sourceNode){ // issue 211
return "<div></div>";
}
return sourceNode.tree._onDragEvent("helper", sourceNode, null, event, null, null);
},
start: function(event, ui) {
// See issues 211, 268, 278
// var sourceNode = $.ui.dynatree.getNode(event.target);
var sourceNode = ui.helper.data("dtSourceNode");
return !!sourceNode; // Abort dragging if no Node could be found
},
_last: null
});
}
// Attach ui.droppable to this Dynatree instance
if(dnd && dnd.onDrop) {
tree.$tree.droppable({
addClasses: false,
tolerance: "intersect",
greedy: false,
_last: null
});
}
}
//--- Extend ui.draggable event handling --------------------------------------
var didRegisterDnd = false;
var _registerDnd = function() {
if(didRegisterDnd){
return;
}
// Register proxy-functions for draggable.start/drag/stop
$.ui.plugin.add("draggable", "connectToDynatree", {
start: function(event, ui) {
// issue 386
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("dtSourceNode") || null;
// logMsg("draggable-connectToDynatree.start, %s", sourceNode);
// logMsg(" this: %o", this);
// logMsg(" event: %o", event);
// logMsg(" draggable: %o", draggable);
// logMsg(" ui: %o", ui);
if(sourceNode) {
// Adjust helper offset, so cursor is slightly outside top/left corner
// draggable.offset.click.top -= event.target.offsetTop;
// draggable.offset.click.left -= event.target.offsetLeft;
draggable.offset.click.top = -2;
draggable.offset.click.left = + 16;
// logMsg(" draggable2: %o", draggable);
// logMsg(" draggable.offset.click FIXED: %s/%s", draggable.offset.click.left, draggable.offset.click.top);
// Trigger onDragStart event
// TODO: when called as connectTo..., the return value is ignored(?)
return sourceNode.tree._onDragEvent("start", sourceNode, null, event, ui, draggable);
}
},
drag: function(event, ui) {
// issue 386
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("dtSourceNode") || null,
prevTargetNode = ui.helper.data("dtTargetNode") || null,
targetNode = $.ui.dynatree.getNode(event.target);
// logMsg("$.ui.dynatree.getNode(%o): %s", event.target, targetNode);
// logMsg("connectToDynatree.drag: helper: %o", ui.helper[0]);
if(event.target && !targetNode){
// We got a drag event, but the targetNode could not be found
// at the event location. This may happen,
// 1. if the mouse jumped over the drag helper,
// 2. or if non-dynatree element is dragged
// We ignore it:
var isHelper = $(event.target).closest("div.dynatree-drag-helper,#dynatree-drop-marker").length > 0;
if(isHelper){
// logMsg("Drag event over helper: ignored.");
return;
}
}
// logMsg("draggable-connectToDynatree.drag: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode"));
ui.helper.data("dtTargetNode", targetNode);
// Leaving a tree node
if(prevTargetNode && prevTargetNode !== targetNode ) {
prevTargetNode.tree._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
}
if(targetNode){
if(!targetNode.tree.options.dnd.onDrop) {
// not enabled as drop target
// noop(); // Keep JSLint happy
} else if(targetNode === prevTargetNode) {
// Moving over same node
targetNode.tree._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
}else{
// Entering this node first time
targetNode.tree._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
}
}
// else go ahead with standard event handling
},
stop: function(event, ui) {
// issue 386
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("dtSourceNode") || null,
targetNode = ui.helper.data("dtTargetNode") || null,
mouseDownEvent = draggable._mouseDownEvent,
eventType = event.type,
dropped = (eventType == "mouseup" && event.which == 1);
logMsg("draggable-connectToDynatree.stop: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode"));
// logMsg("draggable-connectToDynatree.stop, %s", sourceNode);
// logMsg(" type: %o, downEvent: %o, upEvent: %o", eventType, mouseDownEvent, event);
// logMsg(" targetNode: %o", targetNode);
if(!dropped){
logMsg("Drag was cancelled");
}
if(targetNode) {
if(dropped){
targetNode.tree._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
}
targetNode.tree._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
}
if(sourceNode){
sourceNode.tree._onDragEvent("stop", sourceNode, null, event, ui, draggable);
}
}
});
didRegisterDnd = true;
};
// ---------------------------------------------------------------------------
}(jQuery)); | *****************************************************************************
Drag and drop support | _initDragAndDrop ( tree ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.dynatree.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.dynatree.js | Apache-2.0 |
$.ui.dynatree.getNode = function(el) {
if(el instanceof DynaTreeNode){
return el; // el already was a DynaTreeNode
}
if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}
// TODO: for some reason $el.parents("[dtnode]") does not work (jQuery 1.6.1)
// maybe, because dtnode is a property, not an attribute
while( el ) {
if(el.dtnode) {
return el.dtnode;
}
el = el.parentNode;
}
return null;
/*
var $el = el.selector === undefined ? $(el) : el,
// parent = $el.closest("[dtnode]"),
// parent = $el.parents("[dtnode]").first(),
useProp = (typeof $el.prop == "function"),
node;
$el.parents().each(function(){
node = useProp ? $(this).prop("dtnode") : $(this).attr("dtnode");
if(node){
return false;
}
});
return node;
*/
};
/**Return persistence information from cookies.*/
$.ui.dynatree.getPersistData = DynaTreeStatus._getTreePersistData;
/*******************************************************************************
* Plugin default options:
*/
$.ui.dynatree.prototype.options = {
title: "Dynatree", // Tree's name (only used for debug output)
minExpandLevel: 1, // 1: root node is not collapsible
imagePath: null, // Path to a folder containing icons. Defaults to 'skin/' subdirectory.
children: null, // Init tree structure from this object array.
initId: null, // Init tree structure from a <ul> element with this ID.
initAjax: null, // Ajax options used to initialize the tree strucuture.
autoFocus: true, // Set focus to first child, when expanding or lazy-loading.
keyboard: true, // Support keyboard navigation.
persist: false, // Persist expand-status to a cookie
autoCollapse: false, // Automatically collapse all siblings, when a node is expanded.
clickFolderMode: 3, // 1:activate, 2:expand, 3:activate and expand
activeVisible: true, // Make sure, active nodes are visible (expanded).
checkbox: false, // Show checkboxes.
selectMode: 2, // 1:single, 2:multi, 3:multi-hier
fx: null, // Animations, e.g. null or { height: "toggle", duration: 200 }
noLink: false, // Use <span> instead of <a> tags for all nodes
// Low level event handlers: onEvent(dtnode, event): return false, to stop default processing
onClick: null, // null: generate focus, expand, activate, select events.
onDblClick: null, // (No default actions.)
onKeydown: null, // null: generate keyboard navigation (focus, expand, activate).
onKeypress: null, // (No default actions.)
onFocus: null, // null: set focus to node.
onBlur: null, // null: remove focus from node.
// Pre-event handlers onQueryEvent(flag, dtnode): return false, to stop processing
onQueryActivate: null, // Callback(flag, dtnode) before a node is (de)activated.
onQuerySelect: null, // Callback(flag, dtnode) before a node is (de)selected.
onQueryExpand: null, // Callback(flag, dtnode) before a node is expanded/collpsed.
// High level event handlers
onPostInit: null, // Callback(isReloading, isError) when tree was (re)loaded.
onActivate: null, // Callback(dtnode) when a node is activated.
onDeactivate: null, // Callback(dtnode) when a node is deactivated.
onSelect: null, // Callback(flag, dtnode) when a node is (de)selected.
onExpand: null, // Callback(flag, dtnode) when a node is expanded/collapsed.
onLazyRead: null, // Callback(dtnode) when a lazy node is expanded for the first time.
onCustomRender: null, // Callback(dtnode) before a node is rendered. Return a HTML string to override.
onCreate: null, // Callback(dtnode, nodeSpan) after a node was rendered for the first time.
onRender: null, // Callback(dtnode, nodeSpan) after a node was rendered.
// postProcess is similar to the standard dataFilter hook,
// but it is also called for JSONP
postProcess: null, // Callback(data, dataType) before an Ajax result is passed to dynatree
// Drag'n'drop support
dnd: {
// Make tree nodes draggable:
onDragStart: null, // Callback(sourceNode), return true, to enable dnd
onDragStop: null, // Callback(sourceNode)
// helper: null,
// Make tree nodes accept draggables
autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
onDragEnter: null, // Callback(targetNode, sourceNode)
onDragOver: null, // Callback(targetNode, sourceNode, hitMode)
onDrop: null, // Callback(targetNode, sourceNode, hitMode)
onDragLeave: null // Callback(targetNode, sourceNode)
},
ajaxDefaults: { // Used by initAjax option
cache: false, // false: Append random '_' argument to the request url to prevent caching.
timeout: 0, // >0: Make sure we get an ajax error for invalid URLs
dataType: "json" // Expect json format and pass json object to callbacks.
},
strings: {
loading: "Loading…",
loadError: "Load error!"
},
generateIds: false, // Generate id attributes like <span id='dynatree-id-KEY'>
idPrefix: "dynatree-id-", // Used to generate node id's like <span id="dynatree-id-<key>">.
keyPathSeparator: "/", // Used by node.getKeyPath() and tree.loadKeyPath().
// cookieId: "dynatree-cookie", // Choose a more unique name, to allow multiple trees.
cookieId: "dynatree", // Choose a more unique name, to allow multiple trees.
cookie: {
expires: null //7, // Days or Date; null: session cookie
// path: "/", // Defaults to current page
// domain: "jquery.com",
// secure: true
},
// Class names used, when rendering the HTML markup.
// Note: if only single entries are passed for options.classNames, all other
// values are still set to default.
classNames: {
container: "dynatree-container",
node: "dynatree-node",
folder: "dynatree-folder",
// document: "dynatree-document",
empty: "dynatree-empty",
vline: "dynatree-vline",
expander: "dynatree-expander",
connector: "dynatree-connector",
checkbox: "dynatree-checkbox",
nodeIcon: "dynatree-icon",
title: "dynatree-title",
noConnector: "dynatree-no-connector",
nodeError: "dynatree-statusnode-error",
nodeWait: "dynatree-statusnode-wait",
hidden: "dynatree-hidden",
combinedExpanderPrefix: "dynatree-exp-",
combinedIconPrefix: "dynatree-ico-",
nodeLoading: "dynatree-loading",
// disabled: "dynatree-disabled",
hasChildren: "dynatree-has-children",
active: "dynatree-active",
selected: "dynatree-selected",
expanded: "dynatree-expanded",
lazy: "dynatree-lazy",
focused: "dynatree-focused",
partsel: "dynatree-partsel",
lastsib: "dynatree-lastsib"
},
debugLevel: 2, // 0:quiet, 1:normal, 2:debug $REPLACE: debugLevel: 1,
// ------------------------------------------------------------------------
lastentry: undefined
};
//
if(versionCompare($.ui.version, "1.8") < 0){
//if( parseFloat($.ui.version) < 1.8 ) {
$.ui.dynatree.defaults = $.ui.dynatree.prototype.options;
}
/*******************************************************************************
* Reserved data attributes for a tree node.
*/
$.ui.dynatree.nodedatadefaults = {
title: null, // (required) Displayed name of the node (html is allowed here)
key: null, // May be used with activate(), select(), find(), ...
isFolder: false, // Use a folder icon. Also the node is expandable but not selectable.
isLazy: false, // Call onLazyRead(), when the node is expanded for the first time to allow for delayed creation of children.
tooltip: null, // Show this popup text.
href: null, // Added to the generated <a> tag.
icon: null, // Use a custom image (filename relative to tree.options.imagePath). 'null' for default icon, 'false' for no icon.
addClass: null, // Class name added to the node's span tag.
noLink: false, // Use <span> instead of <a> tag for this node
activate: false, // Initial active status.
focus: false, // Initial focused status.
expand: false, // Initial expanded status.
select: false, // Initial selected status.
hideCheckbox: false, // Suppress checkbox display for this node.
unselectable: false, // Prevent selection.
// disabled: false,
// The following attributes are only valid if passed to some functions:
children: null, // Array of child nodes.
// NOTE: we can also add custom attributes here.
// This may then also be used in the onActivate(), onSelect() or onLazyTree() callbacks.
// ------------------------------------------------------------------------
lastentry: undefined
};
/*******************************************************************************
* Drag and drop support
*/
function _initDragAndDrop(tree) {
var dnd = tree.options.dnd || null;
// Register 'connectToDynatree' option with ui.draggable
if(dnd && (dnd.onDragStart || dnd.onDrop)) {
_registerDnd();
}
// Attach ui.draggable to this Dynatree instance
if(dnd && dnd.onDragStart ) {
tree.$tree.draggable({
addClasses: false,
appendTo: "body",
containment: false,
delay: 0,
distance: 4,
revert: false,
scroll: true, // issue 244: enable scrolling (if ul.dynatree-container)
scrollSpeed: 7,
scrollSensitivity: 10,
// Delegate draggable.start, drag, and stop events to our handler
connectToDynatree: true,
// Let source tree create the helper element
helper: function(event) {
var sourceNode = $.ui.dynatree.getNode(event.target);
if(!sourceNode){ // issue 211
return "<div></div>";
}
return sourceNode.tree._onDragEvent("helper", sourceNode, null, event, null, null);
},
start: function(event, ui) {
// See issues 211, 268, 278
// var sourceNode = $.ui.dynatree.getNode(event.target);
var sourceNode = ui.helper.data("dtSourceNode");
return !!sourceNode; // Abort dragging if no Node could be found
},
_last: null
});
}
// Attach ui.droppable to this Dynatree instance
if(dnd && dnd.onDrop) {
tree.$tree.droppable({
addClasses: false,
tolerance: "intersect",
greedy: false,
_last: null
});
}
}
//--- Extend ui.draggable event handling --------------------------------------
var didRegisterDnd = false;
var _registerDnd = function() {
if(didRegisterDnd){
return;
}
// Register proxy-functions for draggable.start/drag/stop
$.ui.plugin.add("draggable", "connectToDynatree", {
start: function(event, ui) {
// issue 386
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("dtSourceNode") || null;
// logMsg("draggable-connectToDynatree.start, %s", sourceNode);
// logMsg(" this: %o", this);
// logMsg(" event: %o", event);
// logMsg(" draggable: %o", draggable);
// logMsg(" ui: %o", ui);
if(sourceNode) {
// Adjust helper offset, so cursor is slightly outside top/left corner
// draggable.offset.click.top -= event.target.offsetTop;
// draggable.offset.click.left -= event.target.offsetLeft;
draggable.offset.click.top = -2;
draggable.offset.click.left = + 16;
// logMsg(" draggable2: %o", draggable);
// logMsg(" draggable.offset.click FIXED: %s/%s", draggable.offset.click.left, draggable.offset.click.top);
// Trigger onDragStart event
// TODO: when called as connectTo..., the return value is ignored(?)
return sourceNode.tree._onDragEvent("start", sourceNode, null, event, ui, draggable);
}
},
drag: function(event, ui) {
// issue 386
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("dtSourceNode") || null,
prevTargetNode = ui.helper.data("dtTargetNode") || null,
targetNode = $.ui.dynatree.getNode(event.target);
// logMsg("$.ui.dynatree.getNode(%o): %s", event.target, targetNode);
// logMsg("connectToDynatree.drag: helper: %o", ui.helper[0]);
if(event.target && !targetNode){
// We got a drag event, but the targetNode could not be found
// at the event location. This may happen,
// 1. if the mouse jumped over the drag helper,
// 2. or if non-dynatree element is dragged
// We ignore it:
var isHelper = $(event.target).closest("div.dynatree-drag-helper,#dynatree-drop-marker").length > 0;
if(isHelper){
// logMsg("Drag event over helper: ignored.");
return;
}
}
// logMsg("draggable-connectToDynatree.drag: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode"));
ui.helper.data("dtTargetNode", targetNode);
// Leaving a tree node
if(prevTargetNode && prevTargetNode !== targetNode ) {
prevTargetNode.tree._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
}
if(targetNode){
if(!targetNode.tree.options.dnd.onDrop) {
// not enabled as drop target
// noop(); // Keep JSLint happy
} else if(targetNode === prevTargetNode) {
// Moving over same node
targetNode.tree._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
}else{
// Entering this node first time
targetNode.tree._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
}
}
// else go ahead with standard event handling
},
stop: function(event, ui) {
// issue 386
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("dtSourceNode") || null,
targetNode = ui.helper.data("dtTargetNode") || null,
mouseDownEvent = draggable._mouseDownEvent,
eventType = event.type,
dropped = (eventType == "mouseup" && event.which == 1);
logMsg("draggable-connectToDynatree.stop: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode"));
// logMsg("draggable-connectToDynatree.stop, %s", sourceNode);
// logMsg(" type: %o, downEvent: %o, upEvent: %o", eventType, mouseDownEvent, event);
// logMsg(" targetNode: %o", targetNode);
if(!dropped){
logMsg("Drag was cancelled");
}
if(targetNode) {
if(dropped){
targetNode.tree._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
}
targetNode.tree._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
}
if(sourceNode){
sourceNode.tree._onDragEvent("stop", sourceNode, null, event, ui, draggable);
}
}
});
didRegisterDnd = true;
};
// ---------------------------------------------------------------------------
}(jQuery)); | Return a DynaTreeNode object for a given DOM element | $.ui.dynatree.getNode ( el ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.dynatree.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.dynatree.js | Apache-2.0 |
!function ($) {
"use strict"; // jshint ;_;
var Search = function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.search.defaults, options);
this.item = this.options.item || this.$element.data('items');
this.items = $('[data-item="'+this.item+'"]');
this.lookup();
this.searchTimer;
}
Search.prototype = {
constructor: Search
, lookup : function() {
this.$element.on('keyup', $.proxy(this.keyup, this));
this.$element.on('keydown', $.proxy(this.kedown, this));
}
, keyup : function() {
this.searchTimer = setTimeout(
$.proxy(this.search, this),
this.options.delay,
this.$element.val().toLowerCase()
);
}
, keydown : function() {
clearTimeout(this.searchTimer);
}
, search : function(filter) {
var $this = this;
if(!$.trim(filter)) {
this.items.show();
return ;
}
this.items.each(function(index, item) {
($this.matcher(filter, item)) ? $(item).show() : $(item).hide();
});
}
, matcher : function(filter, item) {
return ($(item).data('value').toLowerCase().indexOf(filter) !== -1);
}
}
$.fn.search = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('search')
, options = typeof option == 'object' && option
if (!data) $this.data('search', (data = new Search(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.search.defaults ={
items : "",
delay : 200
}
$(document).on('focus' , '[data-toggle="item-search"]', function(e) {
var $this = $(this);
if ($this.data('search')) return;
$this.search($this.data());
});
}(window.jQuery); | Yobi, Project Hosting SW
Copyright 2014 NAVER Corp.
http://yobi.io
@author Insanehong
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | (anonymous) ( $ ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.search.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.search.js | Apache-2.0 |
"init": function(elContainer, htOptions){
var welTarget = $(elContainer);
this._htData = this._getRequestOptions(welTarget, htOptions || {});
this._htHandlers = {};
// if target element is anchor and request method is GET
// plain HTML will works enough.
if(this._htData.sMethod === "get" && el.tagName.toLowerCase() === "a"){
return;
}
// legacy compatibility
if(typeof this._htData.fOnLoad === "function"){
this._attachCustomEvent("load", htOptions.fOnLoad);
}
if(typeof this._htData.fOnError === "function"){
this._attachCustomEvent("error", htOptions.fOnError);
}
// Set cursor style on target
welTarget.css("cursor", "pointer");
// Send request on click or keydown enterkey
welTarget.on("click keydown", $.proxy(this._onClickTarget, this));
// public interfaces
return {
"options": this._htData,
"on" : this._attachCustomEvent,
"off" : this._detachCustomEvent
};
}, | Attach event handler on available target elements | "init" ( elContainer , htOptions ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
"_onClickTarget": function(weEvt){
if((weEvt.type === "keydown" && weEvt.keyCode !== 13) || !this._htData){
return;
}
this._sendRequest(this._htData);
weEvt.preventDefault();
weEvt.stopPropagation();
return false;
}, | Event Handler on target element
@param {Wrapped Event} weEvt | "_onClickTarget" ( weEvt ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
"_onSuccessRequest": function(oRes, sStatus, oXHR){
// fire custom event "load"
// if any event handler returns explicitly false(Boolean),
// default action will be prevented.
var bCustomEventResult = this._fireEvent("load", {
"oRes" : oRes,
"oXHR" : oXHR,
"sStatus": sStatus
});
if(bCustomEventResult === false){
return;
}
// default action below:
var sLocation = oXHR.getResponseHeader("Location");
if(oXHR.status === 204 && sLocation){
document.location.href = sLocation;
} else {
document.location.reload();
}
}, | Default callback for handle request success event
redirects to URL if server responses JSON data
(e.g. {"url":"http://www.foobar.com/"})
or just reload current page
@param {Object} oRes
@param {String} sStatus
@param {Object} oXHR | "_onSuccessRequest" ( oRes , sStatus , oXHR ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
"_onErrorRequest": function(oXHR){
// fire custom event "load"
// if any event handler returns explicitly false(Boolean),
// default action will be prevented.
this._fireEvent("error", {
"oXHR": oXHR
});
// default action below:
switch(oXHR.status){
case 200:
// if server responses ok(200) but cannot determine redirect URL,
// reload current page.
document.location.reload();
break;
case 204:
// if server responses 204, it is client error.
// in this case, check AJAX dataType option on _sendRequest
document.location.href = oXHR.getResponseHeader("Location");
break;
}
// need to do something else?
}, | Default callback for handle request error event
@param {Object} oXHR | "_onErrorRequest" ( oXHR ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
"_attachCustomEvent": function(sEventName, fHandler){
if(typeof sEventName === "object"){
for(var sKey in sEventName){
this._htHandlers[sKey] = this._htHandlers[sKey] || [];
this._htHandlers[sKey].push(sEventName[sKey]);
}
} else {
this._htHandlers[sEventName] = this._htHandlers[sEventName] || [];
this._htHandlers[sEventName].push(fHandler);
}
}, | Attach custom event handler
@param {String} sEventName
@param {Function} fHandler
@param {String} sNamespace
@example
$("#button").data("requestAs").on("eventName", function(){});
// or
$("#button").data("requestAs").on({
"event1st": function(){},
"event2nd": function(){}
}); | "_attachCustomEvent" ( sEventName , fHandler ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
"_detachCustomEvent": function(sEventName, fHandler){
if(!fHandler){
this._htHandlers[sEventName] = [];
return;
}
var aHandlers = this._htHandlers[sEventName];
var nIndex = aHandlers ? aHandlers.indexOf(fHandler) : -1;
if(nIndex > -1){
this._htHandlers[sEventName].splice(nIndex, 1);
}
}, | Detach custom event handler
clears all handler of sEventName when fHandler is empty
@param {String} sEventName
@param {Function} fHandler | "_detachCustomEvent" ( sEventName , fHandler ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
"_fireEvent": function(sEventName, oData){
var aHandlers = this._htHandlers[sEventName];
if ((aHandlers instanceof Array) === false) {
return;
}
var bResult = undefined;
aHandlers.forEach(function(fHandler){
bResult = bResult || fHandler(oData);
});
return bResult;
} | Run specified custom event handlers
@param {String} sEventName
@param {Object} oData | "_fireEvent" ( sEventName , oData ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.requestAs.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.requestAs.js | Apache-2.0 |
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array)
$.merge(val, v);
else
val.push(v);
}
return val;
}; | Returns the value(s) of the element in the matched set. For example, consider the following form:
<form><fieldset>
<input name="A" type="text" />
<input name="A" type="text" />
<input name="B" type="checkbox" value="B1" />
<input name="B" type="checkbox" value="B2"/>
<input name="C" type="radio" value="C1" />
<input name="C" type="radio" value="C2" />
</fieldset></form>
var v = $(':text').fieldValue();
// if no values are entered into the text inputs
v == ['','']
// if values entered into the text inputs are 'foo' and 'bar'
v == ['foo','bar']
var v = $(':checkbox').fieldValue();
// if neither checkbox is checked
v === undefined
// if both checkboxes are checked
v == ['B1', 'B2']
var v = $(':radio').fieldValue();
// if neither radio is checked
v === undefined
// if first radio is checked
v == ['C1']
The successful argument controls whether or not the field element must be 'successful'
(per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
The default value of the successful argument is true. If this value is false the value(s)
for each element is returned.
Note: This method *always* returns an array. If no valid value can be determined the
array will be empty, otherwise it will contain one or more values. | $.fn.fieldValue ( successful ) | javascript | yona-projects/yona | public/javascripts/lib/jquery/jquery.form.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/lib/jquery/jquery.form.js | Apache-2.0 |
function _initDatePicker(){
if(typeof Pikaday != "function"){
console.log("[Yobi] Pikaday required (https://github.com/dbushell/Pikaday)");
return false;
}
// append Pikaday element to DatePicker
htVar.oPicker = new Pikaday({
"format" : htVar.sDateFormat,
"onSelect" : function(oDate) {
htElement.welInputDueDate.val(this.toString());
}
});
htElement.welDatePicker.append(htVar.oPicker.el);
// fill DatePicker date to InputDueDate if empty
// or set DatePicker date with InputDueDate
var sDueDate = htElement.welInputDueDate.val();
if(sDueDate.length > 0){
htVar.oPicker.setDate(sDueDate);
}
// set relative event between dueDate input and datePicker
htElement.welInputDueDate.blur(function() {
htVar.oPicker.setDate(this.value);
});
} | initialize DatePicker
@requires Pikaday | _initDatePicker ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.milestone.Write.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.milestone.Write.js | Apache-2.0 |
(function(ns){
var oNS = $yobi.createNamespace(ns);
oNS.container[oNS.name] = function(htOptions){
var htVar = {};
var htElement = {};
/**
* initialize
*/
function _init(htOptions){
var htOpt = htOptions || {};
_initVar(htOpt);
_initElement(htOpt);
_attachEvent();
}
/**
* initialize variables
*/
function _initVar(htOptions){
htVar.rxPrjName = /^[0-9A-Za-z-_\.가-힣]+$/;
htVar.aReservedWords = [".", "..", ".git"];
}
/**
* initialize element variables
*/
function _initElement(htOptions){
// 프로젝트 설정 관련
htElement.welForm = $("form#saveSetting");
htElement.welInputLogo = $("#logoPath");
htElement.welInputName = $("input#project-name");
htElement.welBtnSave = $("#save");
htElement.welReviewerCount = $("#welReviewerCount");
htElement.welMenuSettingCode = $("#menuSettingCode");
htElement.welMenuSettingPullRequest = $("#menuSettingPullRequest");
htElement.welReviewerCountDisable = $('#reviewerCountDisable')
htElement.welMenuSettingReview = $("#menuSettingReview");
htElement.welReviewerCountSettingPanel = $("#reviewerCountSettingPanel");
htElement.welDefaultBranceSettingPanel = $("#defaultBranceSettingPanel");
htElement.welSubMenuProjectChangeVCS = $("#subMenuProjectChangeVCS");
}
/**
* attach event handlers
*/
function _attachEvent(){
htElement.welInputLogo.change(_onChangeLogoPath);
htElement.welBtnSave.click(_onClickBtnSave);
htElement.welMenuSettingCode.on('click', _onClickMenuSettingCode);
htElement.welMenuSettingPullRequest.on('click', _onClickMenuSettingPullRequest);
htElement.welMenuSettingReview.on('click', _onClickMenuSettingReview);
if(htElement.welReviewerCount.data("value") === true) {
htElement.welReviewerCount.show();
}
$(".reviewer-count-wrap").on("click", '[data-toggle="reviewer-count"]', _toggleReviewerCount);
}
function _toggleReviewerCount(){
var sAction = $(this).data("action");
htElement.welReviewerCount[sAction]();
}
function _onChangeLogoPath(){
var welTarget = $(this);
if($yobi.isImageFile(welTarget) === false){
$yobi.showAlert(Messages("project.logo.alert"));
welTarget.val('');
return;
}
htElement.welForm.submit();
}
function _onClickBtnSave(){
var sPrjName = htElement.welInputName.val();
if(!htVar.rxPrjName.test(sPrjName)){
$yobi.showAlert(Messages("project.name.alert"));
return false;
}
if(htVar.aReservedWords.indexOf(sPrjName) >= 0){
$yobi.showAlert(Messages("project.name.reserved.alert"));
return false;
}
return true;
}
function _onClickMenuSettingCode() {
var isChecked = $(this).prop("checked");
if (!isChecked) {
htElement.welMenuSettingCode.prop("checked", false);
htElement.welMenuSettingPullRequest.prop("checked", false);
htElement.welMenuSettingReview.prop("checked", false);
htElement.welReviewerCountDisable.trigger('click');
htElement.welReviewerCountSettingPanel.hide();
htElement.welDefaultBranceSettingPanel.hide();
htElement.welSubMenuProjectChangeVCS.hide();
}
}
function _onClickMenuSettingPullRequest() {
var isChecked = $(this).prop("checked");
if(isChecked) {
htElement.welMenuSettingCode.prop("checked", true);
htElement.welReviewerCountSettingPanel.show();
} else {
htElement.welReviewerCountSettingPanel.hide();
htElement.welReviewerCountDisable.trigger('click');
}
}
function _onClickMenuSettingReview() {
var isChecked = $(this).prop("checked");
if(isChecked) {
htElement.welMenuSettingCode.prop("checked", true);
}
}
_init(htOptions);
};
})("yobi.project.Setting"); | Yobi, Project Hosting SW
Copyright 2013 NAVER Corp.
http://yobi.io
@author Jihan Kim
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | (anonymous) ( ns ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Setting.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Setting.js | Apache-2.0 |
function _init(htOptions){
_initElement(htOptions || {});
_initFileDownloader();
_attachEvent();
} | initialize
@param {Hash Table} htOptions | _init ( htOptions ) | javascript | yona-projects/yona | public/javascripts/service/yobi.milestone.View.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.milestone.View.js | Apache-2.0 |
(function(ns){
var oNS = $yobi.createNamespace(ns);
oNS.container[oNS.name] = function(htOptions){
var htVar = {};
var htElement = {};
/**
* initialize
*
* @param {Hash Table} htOptions
*/
function _init(htOptions){
_initElement(htOptions || {});
_initFileDownloader();
_attachEvent();
}
/**
* initialize elements
*/
function _initElement(htOptions){
htElement.welAttachments = $(".attachments")
htElement.waLabels = $("a.issue-label[data-color]")
htElement.sMilestoneId = htOptions.sMilestoneId;
htElement.sURLLabels = htOptions.sURLLabels;
}
/**
* attach event handlers
*/
function _attachEvent(){
htElement.waLabels.on("click", function(weEvt){
weEvt.preventDefault();
location.href = htElement.sURLLabels + "?milestoneId=" + htElement.sMilestoneId + "&labelIds=" + $(this).attr('data-labelId');
});
}
/**
* initialize fileDownloader
*/
function _initFileDownloader(){
htElement.welAttachments.each(function(i, elContainer){
if(!$(elContainer).data("isYobiAttachment")){
(new yobi.Attachments({"elContainer": elContainer}));
}
});
}
_init(htOptions || {});
};
})("yobi.milestone.View"); | Yobi, Project Hosting SW
Copyright 2013 NAVER Corp.
http://yobi.io
@author JiHan Kim
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | (anonymous) ( ns ) | javascript | yona-projects/yona | public/javascripts/service/yobi.milestone.View.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.milestone.View.js | Apache-2.0 |
function barPositionCSS(n, speed, ease) {
var barCSS;
if (Settings.positionUsing === 'translate3d') {
barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
} else if (Settings.positionUsing === 'translate') {
barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
} else {
barCSS = { 'margin-left': toBarPerc(n)+'%' };
}
barCSS.transition = 'all '+speed+'ms '+ease;
return barCSS;
}
/**
* (Internal) Queues a function to be executed.
*/
var queue = (function() {
var pending = [];
function next() {
var fn = pending.shift();
if (fn) {
fn(next);
}
}
return function(fn) {
pending.push(fn);
if (pending.length == 1) next();
};
})();
/**
* (Internal) Applies css properties to an element, similar to the jQuery
* css method.
*
* While this helper does assist with vendor prefixed property names, it
* does not perform any manipulation of values prior to setting styles.
*/
var css = (function() {
var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ],
cssProps = {};
function camelCase(string) {
return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) {
return letter.toUpperCase();
});
}
function getVendorProp(name) {
var style = document.body.style;
if (name in style) return name;
var i = cssPrefixes.length,
capName = name.charAt(0).toUpperCase() + name.slice(1),
vendorName;
while (i--) {
vendorName = cssPrefixes[i] + capName;
if (vendorName in style) return vendorName;
}
return name;
}
function getStyleProp(name) {
name = camelCase(name);
return cssProps[name] || (cssProps[name] = getVendorProp(name));
}
function applyCss(element, prop, value) {
prop = getStyleProp(prop);
element.style[prop] = value;
}
return function(element, properties) {
var args = arguments,
prop,
value;
if (args.length == 2) {
for (prop in properties) {
value = properties[prop];
if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
}
} else {
applyCss(element, args[1], args[2]);
}
}
})();
/**
* (Internal) Determines if an element or space separated list of class names contains a class name.
*/
function hasClass(element, name) {
var list = typeof element == 'string' ? element : classList(element);
return list.indexOf(' ' + name + ' ') >= 0;
}
/**
* (Internal) Adds a class to an element.
*/
function addClass(element, name) {
var oldList = classList(element),
newList = oldList + name;
if (hasClass(oldList, name)) return;
// Trim the opening space.
element.className = newList.substring(1);
}
/**
* (Internal) Removes a class from an element.
*/
function removeClass(element, name) {
var oldList = classList(element),
newList;
if (!hasClass(element, name)) return;
// Replace the class name.
newList = oldList.replace(' ' + name + ' ', ' ');
// Trim the opening and closing spaces.
element.className = newList.substring(1, newList.length - 1);
}
/**
* (Internal) Gets a space separated list of the class names on the element.
* The list is wrapped with a single space on each end to facilitate finding
* matches within the list.
*/
function classList(element) {
return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
}
/**
* (Internal) Removes an element from the DOM.
*/
function removeElement(element) {
element && element.parentNode && element.parentNode.removeChild(element);
}
return NProgress;
});
},{}]},{},[1]) | (Internal) returns the correct CSS for changing the bar's
position given an n percentage, and speed and ease from Settings | barPositionCSS ( n , speed , ease ) | javascript | yona-projects/yona | public/javascripts/service/yona.Migration.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yona.Migration.js | Apache-2.0 |
function _onClickLabelOnList(weEvt) {
weEvt.preventDefault();
var link = $(this);
var targetQuery = "[data-search=labelIds]";
var target = htElement.welForm.find(targetQuery);
var labelId = link.data("labelId");
var newValue;
if(target.prop("multiple")){
newValue = (target.val() || []);
newValue.push(labelId);
} else {
newValue = labelId;
}
target.data("select2").val(newValue, true); // triggerChange=true
console.log("labelId", labelId);
} | "click" event handler of labels on the list.
Add clicked label to search form condition.
@param event
@private | _onClickLabelOnList ( weEvt ) | javascript | yona-projects/yona | public/javascripts/service/yobi.board.List.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.board.List.js | Apache-2.0 |
function _onClickReviewCardLink(weEvt){
var sThreadId = _getHashFromLinkString($(weEvt.currentTarget).attr("href"));
if(!_isThreadExistOnCurrentPage(sThreadId)){
return;
}
var sPreviousHash = location.hash;
location.hash = sThreadId;
if(sPreviousHash === location.hash) {
$(window).trigger("hashchange");
}
weEvt.preventDefault();
return false;
} | @param weEvt
@returns {boolean}
@private | _onClickReviewCardLink ( weEvt ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _isThreadExistOnCurrentPage(sHash){
return ($("#" + sHash).length > 0);
} | @param sHash
@returns {boolean}
@private | _isThreadExistOnCurrentPage ( sHash ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _showReviewCardsTabByState(state){
if(["open", "closed"].indexOf(state) > -1) {
$("a[href=#reviewcards-" + state + "]").tab("show");
}
} | Show review-card list tab of {@code state}
@param state
@private | _showReviewCardsTabByState ( state ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _isFoldedThread(welTarget){
return welTarget.hasClass("fold") && (welTarget.find(".btn-thread-here").length > 0);
} | @param welTarget
@returns {boolean}
@private | _isFoldedThread ( welTarget ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _isTargetBelongs(elTarget, sQuery){
return ($(elTarget).parents(sQuery).length > 0);
} | @param elTarget
@param sQuery
@returns {boolean}
@private | _isTargetBelongs ( elTarget , sQuery ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _onClickBtnFoldThread(weEvt){
$(weEvt.currentTarget).closest(".comment-thread-wrap").toggleClass("fold");
_setAllBtnThreadHerePosition();
} | On Click fold/unfold thread toggle button
@param weEvt
@private | _onClickBtnFoldThread ( weEvt ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _setAllBtnThreadHerePosition(){
htElement.welDiffBody.find(".btn-thread-here").each(function(i, el){
_setBtnThreadHerePosition($(el));
});
} | Set positions of all .btn-thread-here button
@private | _setAllBtnThreadHerePosition ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _setBtnThreadHerePosition(welButton){
var welThread = welButton.closest(".comment-thread-wrap");
var nPadding = 10;
// set unfold button right
welButton.css("right", ((welThread.index() * welButton.width()) + nPadding) + "px");
// set unfold button top
// find target line with thread
var welEndLine = _getTargetLineByThread(welThread);
if(welEndLine.length > 0){
welButton.css("top", welEndLine.position().top - nPadding + "px");
}
} | Set position of .btn-thread-here , which marks folded thread
@param welButton
@private | _setBtnThreadHerePosition ( welButton ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _getTargetLineByThread(welThread){
var sEndLineQuery = 'tr[data-line="' + welThread.data("range-endline") + '"]' +
'[data-side="' + welThread.data("range-endside") + '"]';
var welEndLine = welThread.closest("tr").prev(sEndLineQuery);
return welEndLine;
} | Get last line element in target range of comment-thread
@param welThread
@returns {*}
@private | _getTargetLineByThread ( welThread ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _doesMouseButtonPressed(weEvt){
return (typeof weEvt.buttons !== "undefined") ? (weEvt.buttons !== 0) : (weEvt.which !== 0);
} | Returns whether any mouse button has been pressed.
@param weEvt
@returns {boolean}
@private | _doesMouseButtonPressed ( weEvt ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _onMouseLeaveCodeCommentThread(){
yobi.CodeCommentBlock.unblock();
if(yobi.CodeCommentBox.isVisible() && htVar.htBlockInfo){
yobi.CodeCommentBlock.block(htVar.htBlockInfo);
}
} | On MouseLeave event fired from CodeCommentThread
@private | _onMouseLeaveCodeCommentThread ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.code.Diff.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.code.Diff.js | Apache-2.0 |
function _source(sQuery, fProcess) {
if (sQuery.match(htVar.sLastQuery) && htVar.bIsLastRangeEntire) {
fProcess(htVar.htCachedUsers);
} else {
htVar.htData.query = sQuery;
$yobi.sendForm({
"sURL" : htVar.sActionURL,
"htOptForm" : {"method":"get"},
"htData" : htVar.htData,
"sDataType" : "json",
"fOnLoad" : function(oData, oStatus, oXHR){
var sContentRange = oXHR.getResponseHeader('Content-Range');
htVar.bIsLastRangeEntire = _isEntireRange(sContentRange);
htVar.sLastQuery = sQuery;
var userData = {};
var userInfos = [];
$.each(oData, function (i, user) {
userData[user.info] = user;
userInfos.push(user.info);
});
htVar.htUserData = userData;
htVar.htCachedUsers = userInfos;
fProcess(userInfos);
sContentRange = null;
}
});
}
} | For more information, See "source" option at
http://twitter.github.io/bootstrap/javascript.html#typeahead
@param {Function} fProcess | _source ( sQuery , fProcess ) | javascript | yona-projects/yona | public/javascripts/service/yobi.organization.Member.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.organization.Member.js | Apache-2.0 |
function _isEntireRange(sContentRange){
var aMatch = htVar.rxContentRange.exec(sContentRange || ""); // [1]=total, [2]=items
return (aMatch) ? !(parseInt(aMatch[1], 10) < parseInt(aMatch[2], 10)) : true;
} | Return whether the given content range is an entire range for items.
e.g) "items 10/10"
@param {String} sContentRange the value of Content-Range header from response
@return {Boolean} | _isEntireRange ( sContentRange ) | javascript | yona-projects/yona | public/javascripts/service/yobi.organization.Member.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.organization.Member.js | Apache-2.0 |
(function(ns){
var oNS = $yobi.createNamespace(ns);
oNS.container[oNS.name] = function(htOptions){
var htVar = {};
var htElement = {};
/**
* initialize
*/
function _init(htOptions){
_initVar(htOptions);
_initElement();
_attachEvent();
}
/**
* initialize variables
*/
function _initVar(){
htVar.sActionURL = htOptions.sActionURL;
htVar.htData = htOptions.htData || {};
htVar.rxContentRange = /items\s+([0-9]+)\/([0-9]+)/;
htVar.oTypeahead = new yobi.ui.Typeahead("#loginId", {
"htData" : {
"minLength" : 1,
"updater" : _updater,
"source" : _source,
"render" : _render
}
});
}
function _render(items) {
var that = this;
items = $(items).map(function(i, item) {
i = $(that.options.item).attr('data-value', item);
var _linkHtml = $('<div />');
_linkHtml.append(item);
i.find('a').html(_linkHtml.html());
return i[0];
});
items.first().addClass('active');
this.$menu.html(items);
return this;
}
function _updater(item) {
return htVar.htUserData[item].loginId;
}
/**
* For more information, See "source" option at
* http://twitter.github.io/bootstrap/javascript.html#typeahead
*
* @param {Function} fProcess
*/
function _source(sQuery, fProcess) {
if (sQuery.match(htVar.sLastQuery) && htVar.bIsLastRangeEntire) {
fProcess(htVar.htCachedUsers);
} else {
htVar.htData.query = sQuery;
$yobi.sendForm({
"sURL" : htVar.sActionURL,
"htOptForm" : {"method":"get"},
"htData" : htVar.htData,
"sDataType" : "json",
"fOnLoad" : function(oData, oStatus, oXHR){
var sContentRange = oXHR.getResponseHeader('Content-Range');
htVar.bIsLastRangeEntire = _isEntireRange(sContentRange);
htVar.sLastQuery = sQuery;
var userData = {};
var userInfos = [];
$.each(oData, function (i, user) {
userData[user.info] = user;
userInfos.push(user.info);
});
htVar.htUserData = userData;
htVar.htCachedUsers = userInfos;
fProcess(userInfos);
sContentRange = null;
}
});
}
}
/**
* Return whether the given content range is an entire range for items.
* e.g) "items 10/10"
*
* @param {String} sContentRange the value of Content-Range header from response
* @return {Boolean}
*/
function _isEntireRange(sContentRange){
var aMatch = htVar.rxContentRange.exec(sContentRange || ""); // [1]=total, [2]=items
return (aMatch) ? !(parseInt(aMatch[1], 10) < parseInt(aMatch[2], 10)) : true;
}
/**
* initialize element variables
*/
function _initElement(){
htElement.waBtns = $(".btns");
htElement.enrollAcceptBtns = $(".enrollAcceptBtn");
htElement.memberListWrap = $('.members');
htElement.welAlertDelete = $("#alertDeletion");
}
/**
* attach event handlers
*/
function _attachEvent(){
htElement.memberListWrap.on('click','[data-action="apply"]',_onClickApply);
htElement.memberListWrap.on('click','[data-action="delete"]',_onClickDelete);
htElement.enrollAcceptBtns.click(_onClickEnrollAcceptBtns);
$('#loginId').focus();
}
/**
* @param {Wrapped Event} weEvt
*/
function _onClickEnrollAcceptBtns(weEvt){
weEvt.preventDefault();
var loginId = $(this).attr('data-loginId');
$('#loginId').val(loginId);
$('#addNewMember').submit();
}
/**
* @param {Wrapped Element} weltArget
*/
function _onClickDelete(){
var sURL = $(this).attr("data-href");
// DELETE 메소드로 AJAX 호출
$("#deleteBtn").click(function(){
$.ajax(sURL, {
"method" : "delete",
"dataType": "html",
"success" : _onSuccessDeleteMember,
"error" : _onErrorDeleteMember
});
});
_showConfirmDeleteMember(sURL);
}
function _onSuccessDeleteMember(sResult){
var htData = $.parseJSON(sResult);
document.location.replace(htData.location);
}
/**
* @param {Object} oXHR
*/
function _onErrorDeleteMember(oXHR){
var sErrorMsg;
switch(oXHR.status){
case 403:
var sNeedle = Messages("project.member.ownerCannotLeave");
sErrorMsg = (oXHR.responseText.indexOf(sNeedle) > -1) ? sNeedle : Messages("error.forbidden");
break;
case 404:
sErrorMsg = Messages("organization.member.unknownOrganization");
break;
default:
sErrorMsg = Messages("error.badrequest");
break;
}
$yobi.alert(sErrorMsg);
htElement.welAlertDelete.modal("hide");
}
/**
* @param {String} sURL
*/
function _showConfirmDeleteMember(sURL){
htElement.welAlertDelete.modal();
}
/**
* @param {Wrapped Element} welTarget
*/
function _onClickApply(){
var sURL = $(this).attr("data-href");
var sLoginId = $(this).attr("data-loginId");
var sRoleId = $('input[name="roleof-' + sLoginId + '"]').val();
if(typeof sRoleId == "undefined"){
//console.log("cannot find Role Id");
return false;
}
// send request
$yobi.sendForm({
"sURL" : sURL,
"htData" : {"id": sRoleId},
"fOnLoad" : function(oData, oStatus, oXHR) {
console.log("oXHR.responseText:" + oXHR.responseText);
if (oXHR.responseText != "") {
var htData = $.parseJSON(oXHR.responseText);
document.location.replace(htData.location);
}
}
});
}
_init(htOptions);
};
})("yobi.organization.Member"); | Yobi, Project Hosting SW
Copyright 2013 NAVER Corp.
http://yobi.io
@author Changsung Kim
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | (anonymous) ( ns ) | javascript | yona-projects/yona | public/javascripts/service/yobi.organization.Member.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.organization.Member.js | Apache-2.0 |
function temporarySaveHandler($textarea, contentInitialized) {
var noticePanel = $(".editor-notice-label"); // 화면 어딘가 임시저장 상태 표시할 곳
if (!window.draftSavingTimeout) window.draftSavingTimeout = 0;
// this 대신 editor 컨테이너. this 에 붙여두면 화면 전환 시 handler가 메모리에 중첩됨
$textarea.on('keyup', function () {
if ($textarea.val() !== localStorage.getItem(location.pathname)) {
clearTimeout(window.draftSavingTimeout);
if ($textarea.val() === "") {
localStorage.removeItem(location.pathname);
return;
}
noticePanel.children().fadeOut();
window.draftSavingTimeout = setTimeout(function () {
if($textarea.data("editorMode") === "update-comment-body") {
// FIXME: There are bug when editing comment.
// NOW, just make it skipping to store at local storage
localStorage.setItem(location.pathname + '-last-comment-update-draft', $textarea.val());
return;
}
localStorage.setItem(location.pathname, $textarea.val());
noticePanel.html("<span class=\"saved\">Draft saved</span>");
}, 5000);
}
});
if (contentInitialized === undefined || contentInitialized === true) { // default: true
var lastTextAreaText = $("textarea.content[data-editor-mode='update-comment-body']").last().val();
var storedDraftText = localStorage.getItem(location.pathname);
if (storedDraftText && lastTextAreaText
&& storedDraftText.trim() === lastTextAreaText.trim()) {
removeCurrentPageTemprarySavedContent();
} else if (storedDraftText) {
$textarea.val(storedDraftText);
}
}
} | Yona, 21st Century Project Hosting SW
<p>
Copyright Yona & Yobi Authors & NAVER Corp. & NAVER LABS Corp.
https://yona.io
* | temporarySaveHandler ( $textarea , contentInitialized ) | javascript | yona-projects/yona | public/javascripts/service/yona.temporarySaveHandler.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yona.temporarySaveHandler.js | Apache-2.0 |
(function(ns){
var oNS = $yobi.createNamespace(ns);
oNS.container[oNS.name] = function(htOptions){
var htElement = {};
/**
* initialize
*/
function _init(htOptions){
_initElement(htOptions);
_attachEvent(htOptions);
}
/**
* initialize element variables
*/
function _initElement(htOptions){
htElement.welChkAccept = $("#accept");
htElement.welBtnTransferPop = $("#btnTransfer");
htElement.welBtnTransferPrj = $("#btnTransferExec");
}
/**
* attach event handlers
*/
function _attachEvent(htOptions){
htElement.welBtnTransferPop.click(_onClickBtnTransferPop);
htElement.welBtnTransferPrj.one("click", function(){
$.ajax(htOptions.sTransferURL + "?owner=" + $("#owner").val(), {
"method" : "put",
"success": function(oRes, sStatus, oXHR){
// default action below:
var sLocation = oXHR.getResponseHeader("Location");
if(oXHR.status === 204 && sLocation){
document.location.href = sLocation;
} else {
document.location.reload();
}
},
"error": function(){
$("#alertTransfer").modal("hide");
$yobi.alert(Messages("project.transfer.error"));
return false;
}
});
});
}
function _onClickBtnTransferPop(){
if(htElement.welChkAccept.is(":checked") === false){
$yobi.alert(Messages("project.transfer.alert"));
return false;
}
return true;
}
_init(htOptions || {});
};
})("yobi.project.Transfer"); | Yobi, Project Hosting SW
Copyright 2013 NAVER Corp.
http://yobi.io
@author Keesun Baik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | (anonymous) ( ns ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Transfer.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Transfer.js | Apache-2.0 |
function _onKeyPressNewLabel(oEvent) {
if (oEvent.keyCode == 13) {
_submitLabel();
return false;
}
} | When any key is pressed on input box in any Category line.
@param {Object} oEvent | _onKeyPressNewLabel ( oEvent ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _onKeyPressNewCategory(oEvent) {
if (oEvent.keyCode == 13) {
_onClickNewCategory();
return false;
}
} | When any key is pressed on input box in New Category line.
@param {Object} oEvent | _onKeyPressNewCategory ( oEvent ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _initLabels() {
$yobi.sendForm({
"sURL" : htVar.sURLProjectLabels,
"htOptForm": {"method":"get"},
"fOnLoad" : function(data) {
_appendLabels(data);
for (var i = 0; i < aRequired.length; i++) {
var sCategory = aRequired[i];
if (!htElement.htCategory.hasOwnProperty(sCategory)) {
__addCategory(sCategory);
}
}
_hideLabelEditor();
}
});
} | Get list of tags from the server and show them in #tags div. | _initLabels ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _createLabel(sInstanceId, sName) {
// If someone clicks a delete button, remove the tag which contains
// the button, and also hide its category in .project-info div if
// the category becomes to have no tag.
var fOnLoadAfterDeleteLabel = function() {
var welCategory = welLabel.parent().parent();
var sCategory = welCategory.data('category');
welLabel.remove();
if (welCategory.children('.label-list').children().length == 0
&& isRequired(sCategory)
&& htElement.welInputLabel.data('category') != sCategory) {
delete htElement.htCategory[sCategory];
welCategory.remove();
}
};
var fOnClickDelete = function() {
$yobi.sendForm({
"sURL" : htVar.sURLProjectLabels + '/' + sInstanceId,
"htData" : {"_method":"DELETE"},
"fOnLoad": fOnLoadAfterDeleteLabel
});
};
var welDeleteButton = $('#label-delete-button-template')
.tmpl()
.click(fOnClickDelete);
var welLabel = $('#label-template')
.tmpl({'name': sName})
.append(welDeleteButton);
welLabel.setRemovability = function(bFlag) {
if (bFlag === true) {
welLabel.addClass('label');
welDeleteButton.show();
} else {
welLabel.removeClass('label');
welDeleteButton.hide();
}
}
htElement.aLabel.push(welLabel);
return welLabel;
} | Make a tag element by given instance id and name.)
@param {String} sInstanceId
@param {String} sName | _createLabel ( sInstanceId , sName ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _appendLabels(htLabels) {
for(var sInstanceId in htLabels) {
var waCategory, welCategory;
var htLabel = htLabels[sInstanceId];
waCategory = htElement.welLabelBoard
.children("[data-category=" + htLabel.category + "]");
if (waCategory.length > 0) {
waCategory
.children(".label-list")
.append(_createLabel(sInstanceId, htLabel.name));
} else {
__addCategory(htLabel.category)
.children(".label-list")
.append(_createLabel(sInstanceId, htLabel.name));
}
}
} | Append the given tags on #tags div to show them.
@param {Object} htLabels | _appendLabels ( htLabels ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _createCategory(sCategory) {
var welBtnPlusLabel = htElement.welBtnPlusLabel
.clone()
.data('category', sCategory)
.click(_onClickPlusLabel);
var welCategory = $('#category-template')
.tmpl({'category': sCategory})
.append(welBtnPlusLabel);
welCategory.welBtnPlusLabel = welBtnPlusLabel;
htElement.aBtnPlusLabel.push(welBtnPlusLabel);
return welCategory;
} | Create a category consists with category name, labels belong
to this and plus button to add a label.
@param {String} sCategory
@return {Object} The created category | _createCategory ( sCategory ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _onClickNewCategory() {
var sCategory = htElement.welInputCategory.val();
var welCategory = htElement.htCategory[sCategory];
if (!welCategory) {
welCategory = __addCategory(sCategory);
}
htElement.welInputCategory.val("");
welCategory.welBtnPlusLabel.trigger('click');
if (!htElement.welInputCategory.is(":focus")) {
htElement.welInputCategory.trigger('focus');
}
} | Add a category just before `htElement.welNewCategory`. | _onClickNewCategory ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _onClickPlusCategory() {
htElement.welInputLabelBox.hide();
htElement.welInputCategoryBox.show();
$(this).before(htElement.welInputCategoryBox);
jQuery.map(htElement.aBtnPlusLabel, function(btn) { btn.show(); });
htElement.welBtnPlusCategory.hide();
if (!htElement.welInputCategory.is(":focus")) {
htElement.welInputCategory.trigger('focus');
}
} | When a plus button in the end of the Label Board is clicked.. | _onClickPlusCategory ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _setLabelsRemovability(bFlag) {
jQuery.map(htElement.aLabel,
function(label) { label.setRemovability(bFlag); });
} | Show all delete buttons for all labels if bFlag is true, and hide if
bFlag is false.
@param {Boolean} bFlag | _setLabelsRemovability ( bFlag ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _hideLabelEditor() {
_setLabelsRemovability(false);
jQuery.map(htElement.aBtnPlusLabel, function(btn) { btn.hide(); });
htElement.welBtnPlusCategory.hide();
htElement.welInputCategoryBox.hide();
htElement.welInputLabelBox.hide();
htElement.welLabelBoard
.css('height', htVar.nLabelBoardHeight);
htElement.welLabelBoard.parent()
.css('height', htVar.labelBoardParentHeight);
} | Make .project-info div editable.
@param {Boolean} bFlag | _hideLabelEditor ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _showLabelEditor() {
_setLabelsRemovability(true);
jQuery.map(htElement.aBtnPlusLabel, function(btn) { btn.show(); });
htElement.welBtnPlusCategory.show();
htVar.nLabelBoardHeight =
htElement.welLabelBoard.css('height');
htVar.nLabelBoardParentHeight =
htElement.welLabelBoard.parent().css('height');
htElement.welLabelBoard.css('height', 'auto');
htElement.welLabelBoard.parent().css('height', 'auto');
} | Make .project-info div uneditable.
@param {Boolean} bFlag | _showLabelEditor ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _onClickPlusLabel() {
var sCategory, welCategory, nLabel;
for (sCategory in htElement.htCategory) {
if ($(this).data('category') == sCategory) {
continue;
}
welCategory = htElement.htCategory[sCategory];
nLabel = welCategory.children('.label-list').children().length;
if (nLabel == 0 && isRequired(sCategory)) {
delete htElement.htCategory[sCategory];
welCategory.remove();
}
}
htElement.welInputLabel.data('category', $(this).data('category'));
new yobi.ui.Typeahead(htElement.welInputLabel, {
"sActionURL": htVar.sURLLabels,
"htData": {
"category": $(this).data('category'),
"project_id": htVar.nProjectId,
"limit": 8
}
});
htElement.welInputCategoryBox.hide();
htElement.welInputLabelBox.show();
$(this).after(htElement.welInputLabelBox);
jQuery.map(htElement.aBtnPlusLabel, function(btn) { btn.show(); });
$(this).hide();
if (!htElement.welInputLabel.is(":focus")) {
htElement.welInputLabel.trigger('focus');
}
}
/**
* Show all delete buttons for all labels if bFlag is true, and hide if
* bFlag is false.
*
* @param {Boolean} bFlag
*/
function _setLabelsRemovability(bFlag) {
jQuery.map(htElement.aLabel,
function(label) { label.setRemovability(bFlag); });
}
/**
* Make .project-info div editable.
*
* @param {Boolean} bFlag
*/
function _hideLabelEditor() {
_setLabelsRemovability(false);
jQuery.map(htElement.aBtnPlusLabel, function(btn) { btn.hide(); });
htElement.welBtnPlusCategory.hide();
htElement.welInputCategoryBox.hide();
htElement.welInputLabelBox.hide();
htElement.welLabelBoard
.css('height', htVar.nLabelBoardHeight);
htElement.welLabelBoard.parent()
.css('height', htVar.labelBoardParentHeight);
}
/**
* Make .project-info div uneditable.
*
* @param {Boolean} bFlag
*/
function _showLabelEditor() {
_setLabelsRemovability(true);
jQuery.map(htElement.aBtnPlusLabel, function(btn) { btn.show(); });
htElement.welBtnPlusCategory.show();
htVar.nLabelBoardHeight =
htElement.welLabelBoard.css('height');
htVar.nLabelBoardParentHeight =
htElement.welLabelBoard.parent().css('height');
htElement.welLabelBoard.css('height', 'auto');
htElement.welLabelBoard.parent().css('height', 'auto');
}
_init(htOptions || {});
};
})("yobi.project.Home"); | When a plus button in each category is clicked.. | _onClickPlusLabel ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.project.Home.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.project.Home.js | Apache-2.0 |
function _initElement(options){
elements.list = $(options.list);
elements.form = $(options.form);
elements.formInput = elements.form.find('input,button[type=submit]');
elements.inputCategory = elements.form.find('input[name="category"]');
elements.inputName = elements.form.find('input[name="name"]');
elements.inputColor = elements.form.find('input[name="color"]');
elements.colorsWrap = elements.form.find("div.label-preset-colors");
elements.editCategoryForm = $(options.editCategoryForm);
elements.editCategoryName = elements.editCategoryForm.find("[name=name]");
elements.editCategoryExclusive = elements.editCategoryForm.find("[name=isExclusive]");
elements.editLabelForm = $(options.editLabelForm);
elements.editLabelCategory = elements.editLabelForm.find('[name="category.id"]');
elements.editLabelName = elements.editLabelForm.find("[name=name]");
elements.editLabelColor = elements.editLabelForm.find("[name=color]");
elements.editLabelColorsWrap = elements.editLabelForm.find("div.label-preset-colors");
} | Initialize element variables
@param options
@private | _initElement ( options ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _initVar(options){
vars.listURL = options.listURL;
vars.actionURL = elements.form.prop("action");
vars.categories = [];
elements.inputCategory.typeahead();
elements.inputCategory.data("typeahead").source = vars.categories;
} | Initialize variables
@param options
@private | _initVar ( options ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _buildCategoryList(){
$("div[data-category-name]").each(function(i, item){
var categoryName = $(item).data("categoryName");
if(vars.categories.indexOf(categoryName) < 0){
vars.categories.push(categoryName);
}
});
} | Build category list array from HTML data.
for check is new category, and Typeahead source of inputCategory.
@private | _buildCategoryList ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _preventSubmitWhenEnterKeyPressed(evt){
if(_isEnterKeyPressed(evt)){
evt.preventDefault();
return false;
}
} | false when enter key pressed
@private | _preventSubmitWhenEnterKeyPressed ( evt ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _isEnterKeyPressed(evt){
return ((evt.keyCode || evt.which) === 13);
} | Returns whether the pressed key is ENTER
from given Event.
@param evt
@returns {boolean}
@private | _isEnterKeyPressed ( evt ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _isFormValid(){
if(elements.inputCategory.val().length === 0 ||
elements.inputName.val().length === 0 ||
elements.inputColor.val().length === 0){
$yobi.alert(Messages("label.failedTo", Messages("label.add")) + "\n" + Messages("label.error.empty"));
return false;
}
if(_getRefinedHexColor(elements.inputColor.val()) === false){
$yobi.alert(Messages("label.failedTo", Messages("label.add")) + "\n" + Messages("label.error.color", elements.inputColor.val()));
return false;
}
return true;
} | Returns whether is form valid
and shows error if invalid.
@returns {boolean}
@private | _isFormValid ( ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _isNewCategory(categoryName){
return (vars.categories.indexOf(categoryName) < 0);
} | Returns whether is specified {@code categoryName} exists
@param categoryName
@returns {boolean}
@private | _isNewCategory ( categoryName ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
function _requestAddLabel(requestData){
if(_isLabelExists(requestData.categoryName, requestData.labelName)){
$yobi.alert(Messages("label.error.duplicated"));
return false;
}
$.ajax(vars.actionURL, {
"method": "post",
"data" : requestData
})
.done(function(res){
if (res instanceof Object){
_addLabelIntoCategory(res);
elements.inputName.val("").focus();
return;
}
$yobi.alert(Messages("label.error.creationFailed"));
})
.fail(function(res){
_showError(res, "label.add");
});
} | Send request to add label with given data
called from _onSubmitForm.
@param requestData
@private | _requestAddLabel ( requestData ) | javascript | yona-projects/yona | public/javascripts/service/yobi.issue.LabelEditor.js | https://github.com/yona-projects/yona/blob/master/public/javascripts/service/yobi.issue.LabelEditor.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.