<commit_before>const lost = require('lost')
const pxtorem = require('postcss-pxtorem')

module.exports = {
  siteMetadata: {
    url: 'https://lumen.netlify.com',
    title: 'Blog by John Doe',
    subtitle:
      'Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu.',
    copyright: '© All rights reserved.',
    disqusShortname: '',
    menu: [
      {
        label: 'Articles',
        path: '/',
      },
      {
        label: 'About me',
        path: '/about/',
      },
      {
        label: 'Contact me',
        path: '/contact/',
      },
    ],
    author: {
      name: 'John Doe',
      email: '#',
      telegram: '#',
      twitter: '#',
      github: '#',
      rss: '#',
      vk: '#',
    },
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-plugin-feed',
      options: {
        query: `
          {
            site {
              siteMetadata {
                site_url: url
                title
                description: subtitle
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) =>
              allMarkdownRemark.edges.map(edge =>
                Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.frontmatter.description,
                  date: edge.node.frontmatter.date,
                  url: site.siteMetadata.site_url + edge.node.fields.slug,
                  guid: site.siteMetadata.site_url + edge.node.fields.slug,
                  custom_elements: [{ 'content:encoded': edge.node.html }],
                })),
            query: `
              {
                allMarkdownRemark(
                  limit: 1000,
                  sort: { order: DESC, fields: [frontmatter___date] },
                  filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } }
                ) {
                  edges {
                    node {
                      html
                      fields {
                        slug
                      }
                      frontmatter {
                        title
                        date
                        layout
                        draft
                        description
                      }
                    }
                  }
                }
              }
            `,
            output: '/rss.xml',
          },
        ],
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 960,
            },
          },
          {
            resolve: 'gatsby-remark-responsive-iframe',
            options: { wrapperStyle: 'margin-bottom: 1.0725rem' },
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: { trackingId: 'UA-73379983-2' },
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: ['roboto:400,400i,500,700'],
      },
    },
    {
      resolve: 'gatsby-plugin-sitemap',
      options: {
        query: `
            {
              site {
                siteMetadata {
                  url
                }
              }
              allSitePage(
                filter: {
                  path: { regex: "/^(?!/404/|/404.html|/dev-404-page/)/" }
                }
              ) {
                edges {
                  node {
                    path
                  }
                }
              }
          }`,
        output: '/sitemap.xml',
        serialize: ({ site, allSitePage }) =>
          allSitePage.edges.map(edge => {
            return {
              url: site.siteMetadata.url + edge.node.path,
              changefreq: 'daily',
              priority: 0.7,
            }
          }),
      },
    },
    'gatsby-plugin-offline',
    'gatsby-plugin-catch-links',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        postCssPlugins: [
          lost(),
          pxtorem({
            rootValue: 16,
            unitPrecision: 5,
            propList: [
              'font',
              'font-size',
              'line-height',
              'letter-spacing',
              'margin',
              'margin-top',
              'margin-left',
              'margin-bottom',
              'margin-right',
              'padding',
              'padding-top',
              'padding-left',
              'padding-bottom',
              'padding-right',
              'border-radius',
              'width',
              'max-width',
            ],
            selectorBlackList: [],
            replace: true,
            mediaQuery: false,
            minPixelValue: 0,
          }),
        ],
        precision: 8,
      },
    },
  ],
}
<commit_msg>`yarn format`<commit_after>const lost = require('lost')
const pxtorem = require('postcss-pxtorem')

module.exports = {
  siteMetadata: {
    url: 'https://lumen.netlify.com',
    title: 'Blog by John Doe',
    subtitle:
      'Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu.',
    copyright: '© All rights reserved.',
    disqusShortname: '',
    menu: [
      {
        label: 'Articles',
        path: '/',
      },
      {
        label: 'About me',
        path: '/about/',
      },
      {
        label: 'Contact me',
        path: '/contact/',
      },
    ],
    author: {
      name: 'John Doe',
      email: '#',
      telegram: '#',
      twitter: '#',
      github: '#',
      rss: '#',
      vk: '#',
    },
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-plugin-feed',
      options: {
        query: `
          {
            site {
              siteMetadata {
                site_url: url
                title
                description: subtitle
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) =>
              allMarkdownRemark.edges.map(edge =>
                Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.frontmatter.description,
                  date: edge.node.frontmatter.date,
                  url: site.siteMetadata.site_url + edge.node.fields.slug,
                  guid: site.siteMetadata.site_url + edge.node.fields.slug,
                  custom_elements: [{ 'content:encoded': edge.node.html }],
                })
              ),
            query: `
              {
                allMarkdownRemark(
                  limit: 1000,
                  sort: { order: DESC, fields: [frontmatter___date] },
                  filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } }
                ) {
                  edges {
                    node {
                      html
                      fields {
                        slug
                      }
                      frontmatter {
                        title
                        date
                        layout
                        draft
                        description
                      }
                    }
                  }
                }
              }
            `,
            output: '/rss.xml',
          },
        ],
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 960,
            },
          },
          {
            resolve: 'gatsby-remark-responsive-iframe',
            options: { wrapperStyle: 'margin-bottom: 1.0725rem' },
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: { trackingId: 'UA-73379983-2' },
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: ['roboto:400,400i,500,700'],
      },
    },
    {
      resolve: 'gatsby-plugin-sitemap',
      options: {
        query: `
            {
              site {
                siteMetadata {
                  url
                }
              }
              allSitePage(
                filter: {
                  path: { regex: "/^(?!/404/|/404.html|/dev-404-page/)/" }
                }
              ) {
                edges {
                  node {
                    path
                  }
                }
              }
          }`,
        output: '/sitemap.xml',
        serialize: ({ site, allSitePage }) =>
          allSitePage.edges.map(edge => {
            return {
              url: site.siteMetadata.url + edge.node.path,
              changefreq: 'daily',
              priority: 0.7,
            }
          }),
      },
    },
    'gatsby-plugin-offline',
    'gatsby-plugin-catch-links',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        postCssPlugins: [
          lost(),
          pxtorem({
            rootValue: 16,
            unitPrecision: 5,
            propList: [
              'font',
              'font-size',
              'line-height',
              'letter-spacing',
              'margin',
              'margin-top',
              'margin-left',
              'margin-bottom',
              'margin-right',
              'padding',
              'padding-top',
              'padding-left',
              'padding-bottom',
              'padding-right',
              'border-radius',
              'width',
              'max-width',
            ],
            selectorBlackList: [],
            replace: true,
            mediaQuery: false,
            minPixelValue: 0,
          }),
        ],
        precision: 8,
      },
    },
  ],
}
<|endoftext|>


<commit_before>// `views` section processor
//

'use strict';

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var _       = require('lodash');
var async   = require('async');
var fstools = require('fs-tools');

// internal
var stopwatch     = require('../utils/stopwatch');
var expandTree    = require('../utils/expand_tree');
var engines       = require('./views/engines');

////////////////////////////////////////////////////////////////////////////////

//  buildClientTree(views[, namespace = 'this.views']) -> String
//  - views (Object): Views map generated by [[Views.collect]].
//  - namespace (String): Global object used as container for the tree.
//
//  Returns a browserified function that will create views tree and will
//  inject it into the `namespace`.
//
//
//  ##### Example
//
//      collect('/path/to/views', function (err, views) {
//        // ...
//        var output = buildClientTree(views, 'this.appViews');
//        fs.writeFile('/path/to/client.js', output);
//        // ...
//      });
//
function buildClientTree(viewsTree, namespace) {
  namespace = namespace || 'this.views';

  var body = [];

  //
  // generate tree population with functions
  //

  _.each(viewsTree, function (view, api) {
    body.push('this[' + JSON.stringify(api) + '] = ' + view.client);
  });

  //
  // Return tree populator
  //

  return '(function () {\n' +
         body.join('\n') +
         '\n}).call(' + namespace + ' || (' + namespace + ' = {}));';
}

//  writeClientTree(filename, views[, namespace], callback(err)) -> String
//  - filename (String): Filename where to write built views tree.
//  - views (Object): Views map generated by [[Views.collect]].
//  - namespace (String): Global object used as container for the tree.
//  - callback (Function): Executed once everything is done.
//
//  Build client-side `views` tree populator and writes it into the `filename`
//  creating parent directories if needed.
//
//
//  ##### Example
//
//      collect('/path/to/views', function (err, views) {
//        // ...
//        writeClientTree('/path/to/client.js', views, function (err) {
//          // ... syntax sugar is sweet ...
//        });
//      });
//
function writeClientTree(filename, tree, namespace, callback) {
  if (!callback) {
    callback  = namespace;
    namespace = null;
  }

  fstools.mkdir(path.dirname(filename), function (err) {
    var str;

    if (err) {
      callback(err);
      return;
    }

    try {
      str = buildClientTree(tree, namespace);
    } catch (err) {
      callback(err);
      return;
    }

    fs.writeFile(filename, str, 'utf8', callback);
  });
}

function processViews(N, outfile, config, callback) {
  var viewsTree = {};

  async.forEachSeries(config.files, function (pathname, next) {
    var str;

    try {
      str = pathname.readSync();
    } catch (err) {
      next(err);
      return;
    }

    async.parallel([
      function (next) {
        // compile server-side views (functions)
        engines[pathname.extname].server(str, {
          filename: String(pathname)
        }, next);
      },
      function (next) {
        // compile client-side views (string sources of functions)
        engines[pathname.extname].client(str, {
          filename: String(pathname)
        }, next);
      }
    ], function (err, results) {
      // expose compiled data into the tree
      results = results || [];

      viewsTree[pathname.apiPath] = {
        server: results[0],
        client: results[1]
      };

      next(err);
    });
  }, function (err) {
    if (err) {
      callback(err);
      return;
    }

    // Inject server tree
    _.each(viewsTree, function (render, api) {
      N.views[api] = render.server;
    });

    expandTree(N.views);

    // write client-side views tree
    writeClientTree(outfile, viewsTree, 'this.N.views', callback);
  });
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function (sandbox, callback) {
  var N = sandbox.N
    , tmpdir = sandbox.tmpdir
    , config  = sandbox.config
    , timer   = stopwatch()
    , outdir  = path.join(tmpdir, 'views');

  N.views = {};

  try {
    fstools.mkdirSync(outdir);
  } catch (err) {
    callback(err);
    return;
  }

  async.forEachSeries(_.keys(config.packages), function (pkgName, next) {
    var
    viewsConfig   = config.packages[pkgName].views,
    viewsOutfile  = path.join(outdir, pkgName + '.js');

    if (!viewsConfig) {
      next();
      return;
    }

    processViews(N, viewsOutfile, viewsConfig, next);
  }, function (err) {
    N.logger.info('Processed views section %s', timer.elapsed);
    callback(err);
  });
};
<commit_msg>Refactor lib/system/init/bundle/views.js<commit_after>// `views` section processor
//

'use strict';

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var _       = require('lodash');
var async   = require('async');
var fstools = require('fs-tools');

// internal
var stopwatch     = require('../utils/stopwatch');
var engines       = require('./views/engines');

////////////////////////////////////////////////////////////////////////////////

//  writeClientViews(filename, views[, namespace], callback(err)) -> String
//  - filename (String): Filename where to write built views tree.
//  - views (Object): Views map generated by [[Views.collect]].
//  - namespace (String): Global object used as container for the tree.
//  - callback (Function): Executed once everything is done.
//
//  Build client-side `views` tree populator and writes it into the `filename`
//  creating parent directories if needed.
//
//
//  ##### Example
//
//      collect('/path/to/views', function (err, views) {
//        // ...
//        writeClientTree('/path/to/client.js', views, function (err) {
//          // ... syntax sugar is sweet ...
//        });
//      });
//
function writeClientViews(filename, views, namespace, callback) {
  if (!callback) {
    callback  = namespace;
    namespace = null;
  }

  if (!namespace) {
    namespace = 'this.views';
  }

  fstools.mkdir(path.dirname(filename), function (err) {
    var result = '';

    if (err) {
      callback(err);
      return;
    }

    result += '(function () {\n';

    _.forEach(views, function (code, apiPath) {
      result += '  this[' + JSON.stringify(apiPath) + '] = (' + code + ');\n';
    });

    result += '}).call(' + namespace + ' || (' + namespace + ' = {}))';

    // Done.
    fs.writeFile(filename, result, 'utf8', callback);
  });
}

function processViews(N, outfile, config, callback) {
  var serverViews = {}
    , clientViews = {};

  async.forEachSeries(config.files, function (pathname, next) {
    var str;

    try {
      str = pathname.readSync();
    } catch (err) {
      next(err);
      return;
    }

    async.parallel([
      function (next) {
        // compile server-side views (functions)
        engines[pathname.extname].server(str, {
          filename: String(pathname)
        }, next);
      },
      function (next) {
        // compile client-side views (string sources of functions)
        engines[pathname.extname].client(str, {
          filename: String(pathname)
        }, next);
      }
    ], function (err, results) {
      if (results) {
        serverViews[pathname.apiPath] = results[0];
        clientViews[pathname.apiPath] = results[1];
      }

      next(err);
    });
  }, function (err) {
    if (err) {
      callback(err);
      return;
    }

    // Inject server views table.
    _.extend(N.views, serverViews);

    // Write client-side views table.
    writeClientViews(outfile, clientViews, 'this.N.views', callback);
  });
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function (sandbox, callback) {
  var N = sandbox.N
    , tmpdir = sandbox.tmpdir
    , config  = sandbox.config
    , timer   = stopwatch()
    , outdir  = path.join(tmpdir, 'views');

  N.views = {};

  try {
    fstools.mkdirSync(outdir);
  } catch (err) {
    callback(err);
    return;
  }

  async.forEachSeries(_.keys(config.packages), function (pkgName, next) {
    var
    viewsConfig   = config.packages[pkgName].views,
    viewsOutfile  = path.join(outdir, pkgName + '.js');

    if (!viewsConfig) {
      next();
      return;
    }

    processViews(N, viewsOutfile, viewsConfig, next);
  }, function (err) {
    N.logger.info('Processed views section %s', timer.elapsed);
    callback(err);
  });
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import { take, all, fork, put, select, call } from 'redux-saga/effects';
import { notesApi } from '../../api';
import {
    ADD_NOTE_REQUEST,
    addNoteSuccess,
    addNoteFailure,
    UPDATE_NOTE_REQUEST,
    updateNoteSuccess,
    updateNoteFailure,
    DELETE_NOTE_REQUEST,
    deleteNoteSuccess,
    deleteNoteFailure,
    GET_ALL_NOTES_REQUEST,
    getAllNotesSuccess,
    getAllNotesFailure,
    CHANGE_NOTE_ORDER_REQUEST,
    changeNoteOrderSuccess,
    changeNoteOrderFailure
} from './notes.actions';

function* watchAddNote() {
    while (true) {
        try {
            const { payload } = yield take(ADD_NOTE_REQUEST);
            const { title, description, files } = payload;

            const newNote = yield call(() =>
                notesApi.create({
                    title,
                    description,
                    files
                })
            );

            yield put(
                addNoteSuccess({
                    id: newNote.id,
                    title: newNote.title,
                    description: newNote.description,
                    files: newNote.files
                })
            );
        } catch (error) {
            yield put(addNoteFailure());
        }
    }
}

function* watchUpdateNote() {
    while (true) {
        const { payload } = yield take(UPDATE_NOTE_REQUEST);
        const { id, title, description } = payload;

        try {
            yield call(() => notesApi.update({ id, title, description }));
            yield put(
                updateNoteSuccess({
                    id,
                    title,
                    description
                })
            );
        } catch (error) {
            yield put(updateNoteFailure(id));
        }
    }
}

function* watchDeleteNote() {
    while (true) {
        const { payload } = yield take(DELETE_NOTE_REQUEST);
        const { id } = payload;

        try {
            yield call(() => notesApi.remove(id));

            yield put(deleteNoteSuccess(id));
        } catch (error) {
            yield put(deleteNoteFailure(id));
        }
    }
}

function* watchGetAllNotes() {
    while (true) {
        yield take(GET_ALL_NOTES_REQUEST);

        try {
            const notes = yield call(notesApi.getAll);

            yield put(getAllNotesSuccess(notes));
        } catch (error) {
            yield put(getAllNotesFailure());
        }
    }
}

function* watchChangeNoteOrder() {
    while (true) {
        const { payload } = yield take(CHANGE_NOTE_ORDER_REQUEST);
        const { id, commitChanges } = payload;

        if (!commitChanges) {
            continue; // eslint-disable-line no-continue
        }

        try {
            const notes = yield select(state => state.notes);
            const reorderedNoteIndex = _.findIndex(
                notes,
                note => note.id === id
            );

            if (reorderedNoteIndex > 0) {
                const { id: anchorNoteId } = notes[reorderedNoteIndex - 1];

                yield call(() =>
                    notesApi.insertBefore({ noteId: id, anchorNoteId })
                );
            } else {
                const { id: anchorNoteId } = notes[reorderedNoteIndex + 1];

                yield call(() =>
                    notesApi.insertAfter({ noteId: id, anchorNoteId })
                );
            }

            yield put(changeNoteOrderSuccess(id));
        } catch (error) {
            yield put(changeNoteOrderFailure(id));
        }
    }
}

export default function* watchNotes() {
    yield all([
        fork(watchAddNote),
        fork(watchUpdateNote),
        fork(watchDeleteNote),
        fork(watchGetAllNotes),
        fork(watchChangeNoteOrder)
    ]);
}
<commit_msg>Added queued updates for notes reordering<commit_after>import _ from 'lodash';
import {
    take,
    all,
    fork,
    put,
    select,
    call,
    actionChannel
} from 'redux-saga/effects';
import { notesApi } from '../../api';
import {
    ADD_NOTE_REQUEST,
    addNoteSuccess,
    addNoteFailure,
    UPDATE_NOTE_REQUEST,
    updateNoteSuccess,
    updateNoteFailure,
    DELETE_NOTE_REQUEST,
    deleteNoteSuccess,
    deleteNoteFailure,
    GET_ALL_NOTES_REQUEST,
    getAllNotesSuccess,
    getAllNotesFailure,
    CHANGE_NOTE_ORDER_REQUEST,
    changeNoteOrderSuccess,
    changeNoteOrderFailure
} from './notes.actions';

function* watchAddNote() {
    while (true) {
        try {
            const { payload } = yield take(ADD_NOTE_REQUEST);
            const { title, description, files } = payload;

            const newNote = yield call(() =>
                notesApi.create({
                    title,
                    description,
                    files
                })
            );

            yield put(
                addNoteSuccess({
                    id: newNote.id,
                    title: newNote.title,
                    description: newNote.description,
                    files: newNote.files
                })
            );
        } catch (error) {
            yield put(addNoteFailure());
        }
    }
}

function* watchUpdateNote() {
    while (true) {
        const { payload } = yield take(UPDATE_NOTE_REQUEST);
        const { id, title, description } = payload;

        try {
            yield call(() => notesApi.update({ id, title, description }));
            yield put(
                updateNoteSuccess({
                    id,
                    title,
                    description
                })
            );
        } catch (error) {
            yield put(updateNoteFailure(id));
        }
    }
}

function* watchDeleteNote() {
    while (true) {
        const { payload } = yield take(DELETE_NOTE_REQUEST);
        const { id } = payload;

        try {
            yield call(() => notesApi.remove(id));

            yield put(deleteNoteSuccess(id));
        } catch (error) {
            yield put(deleteNoteFailure(id));
        }
    }
}

function* watchGetAllNotes() {
    while (true) {
        yield take(GET_ALL_NOTES_REQUEST);

        try {
            const notes = yield call(notesApi.getAll);

            yield put(getAllNotesSuccess(notes));
        } catch (error) {
            yield put(getAllNotesFailure());
        }
    }
}

function* watchChangeNoteOrder() {
    const reorderingActionsQueue = yield actionChannel(
        CHANGE_NOTE_ORDER_REQUEST
    );

    while (true) {
        const { payload } = yield take(reorderingActionsQueue);
        const { id, commitChanges } = payload;

        if (!commitChanges) {
            continue; // eslint-disable-line no-continue
        }

        try {
            const notes = yield select(state => state.notes);
            const reorderedNoteIndex = _.findIndex(
                notes,
                note => note.id === id
            );

            if (reorderedNoteIndex > 0) {
                const { id: anchorNoteId } = notes[reorderedNoteIndex - 1];

                yield call(() =>
                    notesApi.insertBefore({ noteId: id, anchorNoteId })
                );
            } else {
                const { id: anchorNoteId } = notes[reorderedNoteIndex + 1];

                yield call(() =>
                    notesApi.insertAfter({ noteId: id, anchorNoteId })
                );
            }

            yield put(changeNoteOrderSuccess(id));
        } catch (error) {
            yield put(changeNoteOrderFailure(id));
        }
    }
}

export default function* watchNotes() {
    yield all([
        fork(watchAddNote),
        fork(watchUpdateNote),
        fork(watchDeleteNote),
        fork(watchGetAllNotes),
        fork(watchChangeNoteOrder)
    ]);
}
<|endoftext|>


<commit_before>'use strict'

const gulp = require('gulp')
const exec = require('child_process').exec

const MASTER_BRANCH = 'master'
const CHANGELOG_MD = 'CHANGELOG.md'
const README_MD = 'README.md'

function runCommand (cmd) {
  return new Promise((resolve, reject) => {
    if (!cmd) {
      reject(new Error('No command specified.'))
    }

    exec(cmd, function (err, stdout, stderr) {
      if (err) {
        reject(err)
      } else if (stderr) {
        reject(stderr)
      } else {
        resolve(stdout)
      }
    })
  })
}

function getCurrentBranch () {
  return runCommand('git rev-parse --abbrev-ref HEAD')
}

function getGitDiffs () {
  return runCommand(`git diff --name-only ${MASTER_BRANCH}`)
}

function isWhitelistBranch (branch) {
  return (branch.trim() === MASTER_BRANCH)
}

function filterFiles(files) {
  return files.filter(file => !file.includes(README_MD))
}

function verifyGitDiffs (diffs) {
  diffs = diffs || ''

  let files = diffs.trim().split('\n')
  let filteredFiles = filterFiles(files)

  return new Promise((resolve, reject) => {
    if (filteredFiles.length === 0) {
      resolve(true)
    } else if (filteredFiles.indexOf(CHANGELOG_MD) !== -1) {
      resolve(true)
    } else {
      reject(new Error('CHANGELOG.md was not updated'))
    }
  })
}

gulp.task('changelog', () => {
  return getCurrentBranch()
    .then(branch => {
      return isWhitelistBranch(branch)
        ? true
        : getGitDiffs().then(verifyGitDiffs)
    })
})

module.exports = {
  runCommand: runCommand,
  getCurrentBranch: getCurrentBranch,
  getGitDiffs: getGitDiffs,
  isWhitelistBranch: isWhitelistBranch,
  filterFiles: filterFiles,
  verifyGitDiffs: verifyGitDiffs
}
<commit_msg>fix linting error<commit_after>'use strict'

const gulp = require('gulp')
const exec = require('child_process').exec

const MASTER_BRANCH = 'master'
const CHANGELOG_MD = 'CHANGELOG.md'
const README_MD = 'README.md'

function runCommand (cmd) {
  return new Promise((resolve, reject) => {
    if (!cmd) {
      reject(new Error('No command specified.'))
    }

    exec(cmd, function (err, stdout, stderr) {
      if (err) {
        reject(err)
      } else if (stderr) {
        reject(stderr)
      } else {
        resolve(stdout)
      }
    })
  })
}

function getCurrentBranch () {
  return runCommand('git rev-parse --abbrev-ref HEAD')
}

function getGitDiffs () {
  return runCommand(`git diff --name-only ${MASTER_BRANCH}`)
}

function isWhitelistBranch (branch) {
  return (branch.trim() === MASTER_BRANCH)
}

function filterFiles (files) {
  return files.filter(file => !file.includes(README_MD))
}

function verifyGitDiffs (diffs) {
  diffs = diffs || ''

  let files = diffs.trim().split('\n')
  let filteredFiles = filterFiles(files)

  return new Promise((resolve, reject) => {
    if (filteredFiles.length === 0) {
      resolve(true)
    } else if (filteredFiles.indexOf(CHANGELOG_MD) !== -1) {
      resolve(true)
    } else {
      reject(new Error('CHANGELOG.md was not updated'))
    }
  })
}

gulp.task('changelog', () => {
  return getCurrentBranch()
    .then(branch => {
      return isWhitelistBranch(branch)
        ? true
        : getGitDiffs().then(verifyGitDiffs)
    })
})

module.exports = {
  runCommand: runCommand,
  getCurrentBranch: getCurrentBranch,
  getGitDiffs: getGitDiffs,
  isWhitelistBranch: isWhitelistBranch,
  filterFiles: filterFiles,
  verifyGitDiffs: verifyGitDiffs
}
<|endoftext|>


<commit_before>'use strict';

self.addEventListener('activate', function (event) {
	event.waitUntil(clients.claim());
});

self.addEventListener('push', function (event) {
	let data = JSON.parse(event.data.text());
	console.log('[Service Worker] Push received');
	if (data.update) {
		// force service worker to update via push
		self.registration.update().then(() => console.log('[Service Worker] Updated'));
		return;
	}
	if (options.requireInteraction === undefined) {
		options.requireInteraction = false;
	}
	sendMessageToAllClients({
		Q: {
			notification: {
				received: data
			}
		}
	});
	if (data.collapseId) {
		options.tag = data.collapseId;
	}
	event.waitUntil(self.registration.showNotification(data.title, data));
});

self.addEventListener('notificationclick', function (event) {
	let data = event.notification.data;
	console.log('[Service Worker] Notification click Received.');
	event.notification.close();
	if (data.url) {
		event.waitUntil(clients.openWindow(data.url));
	}
	var payload = Object.assign({}, event.notification.data, {
		action: event.action
	});
	sendMessageToAllClients({
		Q: {
			notification: {
				clicked: payload
			}
		}
	});
});

function sendMessageToAllClients(msg) {
	self.clients.matchAll({includeUncontrolled: true, type: 'window'})
	.then(function(all) {
		all.forEach(function(client) {
			client.postMessage(msg);
		});
	});
}<commit_msg>Fixed bug.<commit_after>'use strict';

self.addEventListener('activate', function (event) {
	event.waitUntil(clients.claim());
});

self.addEventListener('push', function (event) {
	let data = JSON.parse(event.data.text());
	console.log('[Service Worker] Push received');
	if (data.update) {
		// force service worker to update via push
		self.registration.update().then(() => console.log('[Service Worker] Updated'));
		return;
	}
	if (data.requireInteraction === undefined) {
		data.requireInteraction = false;
	}
	sendMessageToAllClients({
		Q: {
			notification: {
				received: data
			}
		}
	});
	if (data.collapseId) {
		data.tag = data.collapseId;
	}
	event.waitUntil(self.registration.showNotification(data.title, data));
});

self.addEventListener('notificationclick', function (event) {
	let data = event.notification.data;
	console.log('[Service Worker] Notification click Received.');
	event.notification.close();
	if (data.url) {
		event.waitUntil(clients.openWindow(data.url));
	}
	var payload = Object.assign({}, event.notification.data, {
		action: event.action
	});
	sendMessageToAllClients({
		Q: {
			notification: {
				clicked: payload
			}
		}
	});
});

function sendMessageToAllClients(msg) {
	self.clients.matchAll({includeUncontrolled: true, type: 'window'})
	.then(function(all) {
		all.forEach(function(client) {
			client.postMessage(msg);
		});
	});
}<|endoftext|>


<commit_before>import m from 'mithril';
import prop from 'mithril/stream';
import _ from 'underscore';
import moment from 'moment';
import h from '../h';
import { commonPayment } from '../api';
import models from '../models';

const I18nScope = _.partial(h.i18nScope, 'projects.subscription_fields');

const subscriptionStatusIcon = {
    oninit: function(vnode) {
        const statusClass = {
                active: 'fa-circle.text-success',
                started: 'fa-circle.text-waiting',
                inactive: 'fa-circle.text-error',
                canceled: 'fa-times-circle.text-error',
                canceling: 'fa-times-circle-o.text-error',
                deleted: 'fa-circle.text-error',
                error: 'fa-circle.text-error',
            },
            subscriptionTransition = prop(null);

        // get last subscription status transition from '/subscription_status_transitions' from this subscription
        if (vnode.attrs.subscription.id) {
            vnode.attrs.subscription.transition_date = vnode.attrs.subscription.created_at;

            const filterRowVM = commonPayment
                .filtersVM({
                    subscription_id: 'eq',
                    project_id: 'eq',
                })
                .order({
                    created_at: 'desc',
                })
                .subscription_id(vnode.attrs.subscription.id)
                .project_id(vnode.attrs.subscription.project_id);

            const lRew = commonPayment.loaderWithToken(models.subscriptionTransition.getRowOptions(filterRowVM.parameters()));
            lRew.load().then(data => {
                vnode.attrs.subscription.transition_date =
                    data && data.length > 0 && _.first(data).created_at ? _.first(data).created_at : vnode.attrs.subscription.created_at;
                h.redraw();
            });
        }

        vnode.state = {
            statusClass,
        };
    },
    view: function({ state, attrs }) {
        const subscription = attrs.subscription,
            statusClass = state.statusClass,
            statusToShowTransitionDate = ['started', 'canceling', 'canceled', 'inactive'],
            shouldShowTransitionDate = statusToShowTransitionDate.indexOf(subscription.status) >= 0;

        return m('span', [
            m('span.fontsize-smaller', [
                m(`span.fa.${statusClass[subscription.status] || 'Erro'}`, ' '),
                window.I18n.t(`status.${subscription.status}`, I18nScope()),
            ]),
            shouldShowTransitionDate
                ? m(
                      '.fontcolor-secondary.fontsize-mini.fontweight-semibold.lineheight-tightest',
                      `em ${moment(subscription.transition_date).format('DD/MM/YYYY')}`
                  )
                : '',
        ]);
    },
};

export default subscriptionStatusIcon;
<commit_msg>locale pt to subscription status icon date [finishes #166725854]<commit_after>import m from 'mithril';
import prop from 'mithril/stream';
import _ from 'underscore';
import moment from 'moment';
import h from '../h';
import { commonPayment } from '../api';
import models from '../models';

const I18nScope = _.partial(h.i18nScope, 'projects.subscription_fields');

const subscriptionStatusIcon = {
    oninit: function(vnode) {
        const statusClass = {
                active: 'fa-circle.text-success',
                started: 'fa-circle.text-waiting',
                inactive: 'fa-circle.text-error',
                canceled: 'fa-times-circle.text-error',
                canceling: 'fa-times-circle-o.text-error',
                deleted: 'fa-circle.text-error',
                error: 'fa-circle.text-error',
            },
            subscriptionTransition = prop(null);

        // get last subscription status transition from '/subscription_status_transitions' from this subscription
        if (vnode.attrs.subscription.id) {
            vnode.attrs.subscription.transition_date = vnode.attrs.subscription.created_at;

            const filterRowVM = commonPayment
                .filtersVM({
                    subscription_id: 'eq',
                    project_id: 'eq',
                })
                .order({
                    created_at: 'desc',
                })
                .subscription_id(vnode.attrs.subscription.id)
                .project_id(vnode.attrs.subscription.project_id);

            const lRew = commonPayment.loaderWithToken(models.subscriptionTransition.getRowOptions(filterRowVM.parameters()));
            lRew.load().then(data => {
                vnode.attrs.subscription.transition_date =
                    data && data.length > 0 && _.first(data).created_at ? _.first(data).created_at : vnode.attrs.subscription.created_at;
                h.redraw();
            });
        }

        vnode.state = {
            statusClass,
        };
    },
    view: function({ state, attrs }) {
        const subscription = attrs.subscription,
            statusClass = state.statusClass,
            statusToShowTransitionDate = ['started', 'canceling', 'canceled', 'inactive'],
            shouldShowTransitionDate = statusToShowTransitionDate.indexOf(subscription.status) >= 0;

        return m('span', [
            m('span.fontsize-smaller', [
                m(`span.fa.${statusClass[subscription.status] || 'Erro'}`, ' '),
                window.I18n.t(`status.${subscription.status}`, I18nScope()),
            ]),
            shouldShowTransitionDate
                ? m(
                      '.fontcolor-secondary.fontsize-mini.fontweight-semibold.lineheight-tightest',
                      `em ${h.momentify(subscription.transition_date, 'DD/MM/YYYY')}`
                  )
                : '',
        ]);
    },
};

export default subscriptionStatusIcon;
<|endoftext|>


<commit_before>
/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module requirements.
 */

var HTTPPolling = require('./http-polling');
var jsonpolling_re = /^\d+$/;

/**
 * Export the constructor.
 */

exports = module.exports = JSONPPolling;

/**
 * JSON-P polling transport.
 *
 * @api public
 */

function JSONPPolling (mng, data, req) {
  HTTPPolling.call(this, mng, data, req);

  this.head = 'io.j[0](';
  this.foot = ');';

  if (data.query.i && jsonpolling_re.test(data.query.i)) {
    this.head = 'io.j[' + data.query.i + '](';
  }
};

/**
 * Inherits from Transport.
 */

JSONPPolling.prototype.__proto__ = HTTPPolling.prototype;

/**
 * Transport name
 *
 * @api public
 */

JSONPPolling.prototype.name = 'jsonppolling';

/**
 * Make sure POST are decoded.
 */

JSONPPolling.prototype.postEncoded = true;

/**
 * Handles incoming data.
 * Due to a bug in \n handling by browsers, we expect a JSONified string.
 *
 * @api private
 */

JSONPPolling.prototype.onData = function (data) {
  try {
    data = JSON.parse(data);
  } catch (e) {
    this.error('parse', 'reconnect');
    return;
  }

  HTTPPolling.prototype.onData.call(this, data);
};

/**
 * Performs the write.
 *
 * @api private
 */

JSONPPolling.prototype.doWrite = function (data) {
  HTTPPolling.prototype.doWrite.call(this);

  var data = data === undefined
    ? ''
    : this.head + JSON.stringify(data) + this.foot;

  this.response.writeHead(200, {
      'Content-Type': 'text/javascript; charset=UTF-8'
    , 'Content-Length': Buffer.byteLength(data)
    , 'X-XSS-Protection': '0'
  });

  this.response.write(data);
  this.log.debug(this.name + ' writing', data);
};
<commit_msg>changed jsonp pooling headers<commit_after>
/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module requirements.
 */

var HTTPPolling = require('./http-polling');
var jsonpolling_re = /^\d+$/;

/**
 * Export the constructor.
 */

exports = module.exports = JSONPPolling;

/**
 * JSON-P polling transport.
 *
 * @api public
 */

function JSONPPolling (mng, data, req) {
  HTTPPolling.call(this, mng, data, req);

  this.head = 'io.j[0](';
  this.foot = ');';

  if (data.query.i && jsonpolling_re.test(data.query.i)) {
    this.head = 'io.j[' + data.query.i + '](';
  }
};

/**
 * Inherits from Transport.
 */

JSONPPolling.prototype.__proto__ = HTTPPolling.prototype;

/**
 * Transport name
 *
 * @api public
 */

JSONPPolling.prototype.name = 'jsonppolling';

/**
 * Make sure POST are decoded.
 */

JSONPPolling.prototype.postEncoded = true;

/**
 * Handles incoming data.
 * Due to a bug in \n handling by browsers, we expect a JSONified string.
 *
 * @api private
 */

JSONPPolling.prototype.onData = function (data) {
  try {
    data = JSON.parse(data);
  } catch (e) {
    this.error('parse', 'reconnect');
    return;
  }

  HTTPPolling.prototype.onData.call(this, data);
};

/**
 * Performs the write.
 *
 * @api private
 */

JSONPPolling.prototype.doWrite = function (data) {
  HTTPPolling.prototype.doWrite.call(this);

  var data = data === undefined
    ? ''
    : this.head + JSON.stringify(data) + this.foot;

  this.response.writeHead(200, {
      'Content-Type': 'text/plain; charset=UTF-8'
    , 'Content-Length': Buffer.byteLength(data)
    , 'X-XSS-Protection': '0'
  });

  this.response.write(data);
  this.log.debug(this.name + ' writing', data);
};
<|endoftext|>


<commit_before>import UniqueId from 'kaku-core/modules/UniqueId';
import Youtube from '../wrapper/Youtube';
import PlaylistManager from '../../modules/PlaylistManager';
import YoutubeTrack from 'kaku-core/models/track/YoutubeTrack';

class YoutubeImporter {
  costructor() {
    // TODO
    // we need to add more protect here
    this._regex = /[&?]list=([a-z0-9_-]+)/i;
  }

  _getPlaylistTitle(id) {
    let promise = new Promise((resolve, reject) => {
      Youtube.getPlayListsById(id, (error, result) => {
        if (error) {
          reject(error);
        }
        else {
          let title =
            result.items &&
            result.items[0] &&
            result.items[0].snippet &&
            result.items[0].snippet.title ||
            'playlist - ' + UniqueId(6);
          resolve(title);
        }
      });
    });
    return promise;
  }

  import(url) {
    let id = this._parsePlaylistId(url);
    if (!id) {
      return Promise.reject();
    }

    return this._getPlaylistTitle(id).then((title) => {
      return PlaylistManager.addYoutubePlaylist(title, id);
    }).then((playlist) => {
      let promise = new Promise((resolve, reject) => {
        // TODO
        // support paging to make sure we can fetch all items back
        Youtube.getPlayListsItemsById(id, 50, (error, result) => {
          if (error) {
            reject(error);
          }
          else {
            let rawTracks = result.items || [];
            // change from rawData into YoutubeTrack
            let tracks = rawTracks.map((rawTrack) => {
              let youtubeTrack = new YoutubeTrack();
              youtubeTrack.initYoutubeResult(rawTrack);
              return youtubeTrack;
            });
            // add all tracks in one operation
            playlist.addTracks(tracks).then(() => {
              resolve(playlist);
            });
          }
        });
      });
      return promise;
    });
  }

  _parsePlaylistId(url) {
    url = url || '';
    let result;
    let matches = url.match(this._regex);

    if (matches && matches.length > 0) {
      return matches[1];
    }
  }
}

module.exports = new YoutubeImporter();
<commit_msg>Revert "rewrite src/modules/importer/YoutubeImporter.js with ES6 syntax (#413)"<commit_after>import UniqueId from 'kaku-core/modules/UniqueId';
import Youtube from '../wrapper/Youtube';
import PlaylistManager from '../../modules/PlaylistManager';
import YoutubeTrack from 'kaku-core/models/track/YoutubeTrack';

function YoutubeImporter() {
  // TODO
  // we need to add more protect here
  this._regex = /[&?]list=([a-z0-9_-]+)/i;
}

YoutubeImporter.prototype._getPlaylistTitle = function(id) {
  let promise = new Promise((resolve, reject) => {
    Youtube.getPlayListsById(id, function(error, result) {
      if (error) {
        reject(error);
      }
      else {
        let title =
          result.items &&
          result.items[0] &&
          result.items[0].snippet &&
          result.items[0].snippet.title ||
          'playlist - ' + UniqueId(6);
        resolve(title);
      }
    });
  });
  return promise;
};

YoutubeImporter.prototype.import = function(url) {
  let id = this._parsePlaylistId(url);
  if (!id) {
    return Promise.reject();
  }

  return this._getPlaylistTitle(id).then((title) => {
    return PlaylistManager.addYoutubePlaylist(title, id);
  }).then((playlist) => {
    let promise = new Promise((resolve, reject) => {
      // TODO
      // support paging to make sure we can fetch all items back
      Youtube.getPlayListsItemsById(id, 50, function(error, result) {
        if (error) {
          reject(error);
        }
        else {
          let rawTracks = result.items || [];
          // change from rawData into YoutubeTrack
          let tracks = rawTracks.map((rawTrack) => {
            let youtubeTrack = new YoutubeTrack();
            youtubeTrack.initYoutubeResult(rawTrack);
            return youtubeTrack;
          });
          // add all tracks in one operation
          playlist.addTracks(tracks).then(() => {
            resolve(playlist);
          });
        }
      });
    });
    return promise;
  });
};

YoutubeImporter.prototype._parsePlaylistId = function(url) {
  url = url || '';
  let result;
  let matches = url.match(this._regex);
  if (matches && matches.length > 0) {
    return matches[1];
  }
};

module.exports = new YoutubeImporter();
<|endoftext|>


<commit_before>/**
 * Package: svgedit.contextmenu
 *
 * Licensed under the Apache License, Version 2
 *
 * Author: Adam Bender
 */
// Dependencies:
// 1) jQuery (for dom injection of context menus)
var svgedit = svgedit || {};
(function() {
	var self = this;
	if (!svgedit.contextmenu) {
		svgedit.contextmenu = {};
	}
	self.contextMenuExtensions = {}
	var addContextMenuItem = function(menuItem) {
		// menuItem: {id, label, shortcut, action}
		if (!menuItemIsValid(menuItem)) {
			console
					.error("Menu items must be defined and have at least properties: id, label, action, where action must be a function");
			return;
		}
		if (menuItem.id in self.contextMenuExtensions) {
			console.error('Cannot add extension "' + menuItem.id
					+ '", an extension by that name already exists"');
			return;
		}
		// Register menuItem action, see below for deferred menu dom injection
		console.log("Registed contextmenu item: {id:"+ menuItem.id+", label:"+menuItem.label+"}");
		self.contextMenuExtensions[menuItem.id] = menuItem;
		//TODO: Need to consider how to handle custom enable/disable behavior
	}
	var hasCustomHandler = function(handlerKey) {
		return self.contextMenuExtensions[handlerKey] && true;
	}
	var getCustomHandler = function(handlerKey) {
		return self.contextMenuExtensions[handlerKey].action;
	}
	var injectExtendedContextMenuItemIntoDom = function(menuItem) {
		if (Object.keys(self.contextMenuExtensions).length == 0) {
			// all menuItems appear at the bottom of the menu in their own container.
			// if this is the first extension menu we need to add the separator.
			$("#cmenu_canvas").append("
");
		}
		var shortcut = menuItem.shortcut || "";
		$("#cmenu_canvas").append("
"
									+ menuItem.label + ""
									+ shortcut + "
");
	}

	var menuItemIsValid = function(menuItem) {
		return menuItem && menuItem.id && menuItem.label && menuItem.action && typeof menuItem.action == 'function';
	}

	// Defer injection to wait out initial menu processing. This probably goes away once all context
	// menu behavior is brought here.
	svgEditor.ready(function() {
		for (menuItem in contextMenuExtensions) {
			injectExtendedContextMenuItemIntoDom(contextMenuExtensions[menuItem]);
		}
	});
	svgedit.contextmenu.resetCustomMenus = function(){self.contextMenuExtensions = {}}
	svgedit.contextmenu.add = addContextMenuItem;
	svgedit.contextmenu.hasCustomHandler = hasCustomHandler;
	svgedit.contextmenu.getCustomHandler = getCustomHandler;
})();
<commit_msg>added missing semicolons. Need to investigate contextMenuExtensions potential leaking<commit_after>/**
 * Package: svgedit.contextmenu
 *
 * Licensed under the Apache License, Version 2
 *
 * Author: Adam Bender
 */
// Dependencies:
// 1) jQuery (for dom injection of context menus)
var svgedit = svgedit || {};
(function() {
	var self = this;
	if (!svgedit.contextmenu) {
		svgedit.contextmenu = {};
	}
	self.contextMenuExtensions = {};
	var menuItemIsValid = function(menuItem) {
		return menuItem && menuItem.id && menuItem.label && menuItem.action && typeof menuItem.action == 'function';
	};
	var addContextMenuItem = function(menuItem) {
		// menuItem: {id, label, shortcut, action}
		if (!menuItemIsValid(menuItem)) {
			console.error("Menu items must be defined and have at least properties: id, label, action, where action must be a function");
			return;
		}
		if (menuItem.id in self.contextMenuExtensions) {
			console.error('Cannot add extension "' + menuItem.id + '", an extension by that name already exists"');
			return;
		}
		// Register menuItem action, see below for deferred menu dom injection
		console.log("Registed contextmenu item: {id:"+ menuItem.id+", label:"+menuItem.label+"}");
		self.contextMenuExtensions[menuItem.id] = menuItem;
		//TODO: Need to consider how to handle custom enable/disable behavior
	};
	var hasCustomHandler = function(handlerKey) {
		return self.contextMenuExtensions[handlerKey] && true;
	};
	var getCustomHandler = function(handlerKey) {
		return self.contextMenuExtensions[handlerKey].action;
	};
	var injectExtendedContextMenuItemIntoDom = function(menuItem) {
		if (Object.keys(self.contextMenuExtensions).length === 0) {
			// all menuItems appear at the bottom of the menu in their own container.
			// if this is the first extension menu we need to add the separator.
			$("#cmenu_canvas").append("
");
		}
		var shortcut = menuItem.shortcut || "";
		$("#cmenu_canvas").append("
"
									+ menuItem.label + ""
									+ shortcut + "
");
	};
	// Defer injection to wait out initial menu processing. This probably goes away once all context
	// menu behavior is brought here.
	svgEditor.ready(function() {
		for (var menuItem in contextMenuExtensions) {
			injectExtendedContextMenuItemIntoDom(contextMenuExtensions[menuItem]);
		}
	});
	svgedit.contextmenu.resetCustomMenus = function(){self.contextMenuExtensions = {};};
	svgedit.contextmenu.add = addContextMenuItem;
	svgedit.contextmenu.hasCustomHandler = hasCustomHandler;
	svgedit.contextmenu.getCustomHandler = getCustomHandler;
})();
<|endoftext|>


<commit_before>var Timeline = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();

	var panel = new UI.Panel();
	panel.setPosition( 'absolute' );
	panel.setWidth( '300px' );
	panel.setHeight( '100%' );
	panel.dom.style.background = '#555';
	container.add( panel );

	// controls

	var controls = new UI.Panel();
	controls.setPosition( 'absolute' );
	controls.setWidth( '100%' );
	controls.setPadding( '5px 0px' );
	controls.setBackground( '#666' );
	panel.add( controls );

	var button = new UI.Button();
	button.setLabel( '►' );
	button.setMarginLeft( '5px' );
	button.setPaddingRight( '4px' );
	button.onClick( function () { signals.play.dispatch() } );
	controls.add( button );

	var timeText = new UI.Text();
	timeText.setColor( '#bbb' );
	timeText.setMarginLeft( '5px' );
	timeText.setValue( '0:00.00' );
	controls.add( timeText );

	var playbackRateText = new UI.Text();
	playbackRateText.setColor( '#999' );
	playbackRateText.setMarginLeft( '5px' );
	playbackRateText.setValue( '1.0x' );
	controls.add( playbackRateText );

	var button = new UI.Button();
	button.setLabel( 'MODULES' );
	button.setMarginLeft( '60px' );
	button.onClick( function () {

		scroller.style.background = 'url(' + ( function () {

			var canvas = document.createElement( 'canvas' );
			canvas.width = 1;
			canvas.height = 32;

			var context = canvas.getContext( '2d' );
			context.fillStyle = '#444';
			context.fillRect( 0, 0, 1, 1 );
			return canvas.toDataURL();

		}() ) + ')';

		modules.setDisplay( '' );
		curves.setDisplay( 'none' );

	 } );
	controls.add( button );

	var button = new UI.Button();
	button.setLabel( 'CURVES' );
	button.onClick( function () {

		scroller.style.background = '';

		modules.setDisplay( 'none' );
		curves.setDisplay( '' );

	} );
	controls.add( button );

	// timeline

	var keysDown = {};
	document.addEventListener( 'keydown', function ( event ) { keysDown[ event.keyCode ] = true; } );
	document.addEventListener( 'keyup',   function ( event ) { keysDown[ event.keyCode ] = false; } );

	var time = 0;
	var scale = 32;

	var timeline = new UI.Panel();
	timeline.setPosition( 'absolute' );
	timeline.setLeft( '300px' );
	timeline.setRight( '0px');
	timeline.setTop( '0px' );
	timeline.setBottom( '0px' );
	timeline.setOverflow( 'hidden' );
	timeline.dom.addEventListener( 'mousewheel', function ( event ) {

		// check if [shift] is pressed

		if ( keysDown[ 16 ] === true ) {

			event.preventDefault();

			scale = Math.max( 1, scale + ( event.wheelDeltaY / 10 ) );

			signals.timelineScaled.dispatch( scale );

		}

	} );
	container.add( timeline );

	var marks = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
	marks.style.position = 'absolute';
	marks.setAttribute( 'width', '100%' );
	marks.setAttribute( 'height', '32px' );
	timeline.dom.appendChild( marks );

	var marksPath = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
	marksPath.setAttribute( 'style', 'stroke: #888; stroke-width: 1px; fill: none;' );
	marks.appendChild( marksPath );

	marks.addEventListener( 'mousedown', function ( event ) {

		var onMouseMove = function ( event ) {

			signals.setTime.dispatch( ( event.offsetX + scroller.scrollLeft ) / scale );

		};

		var onMouseUp = function ( event ) {

			onMouseMove( event );

			marks.removeEventListener( 'mousemove', onMouseMove );
			document.removeEventListener( 'mouseup', onMouseUp );

		};

		marks.addEventListener( 'mousemove', onMouseMove, false );
		document.addEventListener( 'mouseup', onMouseUp, false );

	}, false );
	timeline.dom.appendChild( marks );

	var updateMarks = function ( force ) {

		var drawing = '';
		var scale4 = scale / 4;
		var offset = - scroller.scrollLeft % scale;
		var width = marks.getBoundingClientRect().width || 1024;

		for ( var i = offset, l = width; i <= l; i += scale ) {

			drawing += 'M ' + i + ' 8 L' + i + ' 24';
			drawing += 'M ' + ( i + ( scale4 * 1 ) ) + ' 12 L' + ( i + ( scale4 * 1 ) ) + ' 20';
			drawing += 'M ' + ( i + ( scale4 * 2 ) ) + ' 12 L' + ( i + ( scale4 * 2 ) ) + ' 20';
			drawing += 'M ' + ( i + ( scale4 * 3 ) ) + ' 12 L' + ( i + ( scale4 * 3 ) ) + ' 20';

		}

		marksPath.setAttribute( 'd', drawing );

	};

	var scroller = document.createElement( 'div' );
	scroller.style.position = 'absolute';
	scroller.style.top = '32px';
	scroller.style.bottom = '0px'
	scroller.style.width = '100%';
	scroller.style.overflow = 'auto';
	scroller.addEventListener( 'scroll', function ( event ) {

		updateMarks();
		updateTimeMark();

	}, false );
	timeline.dom.appendChild( scroller );

	var modules = new Timeline.Modules( editor );
	scroller.appendChild( modules.dom );

	var curves = new Timeline.Curves( editor );
	curves.setDisplay( 'none' );
	scroller.appendChild( curves.dom );

	//

	var timeMark = document.createElement( 'div' );
	timeMark.style.position = 'absolute';
	timeMark.style.top = '0px';
	timeMark.style.left = '-8px';
	timeMark.style.width = '16px';
	timeMark.style.height = '100%';
	timeMark.style.background = 'url(' + ( function () {

		var canvas = document.createElement( 'canvas' );
		canvas.width = 16;
		canvas.height = 1;

		var context = canvas.getContext( '2d' );
		context.fillStyle = '#f00';
		context.fillRect( 8, 0, 1, 1 );

		return canvas.toDataURL();

	}() ) + ')';
	timeMark.style.pointerEvents = 'none';
	timeline.dom.appendChild( timeMark );

	var updateTimeMark = function () {

		timeMark.style.left = ( time * scale ) - scroller.scrollLeft - 8 + 'px';

	};

	updateMarks( true );

	// signals

	signals.setPlaybackRate.add( function ( value ) {

		playbackRateText.setValue( value.toFixed( 1 ) + 'x' );

	} );

	signals.timeChanged.add( function ( value ) {

		time = value;

		var minutes = Math.floor( value / 60 );
		var seconds = value % 60;
		var padding = seconds < 10 ? '0' : '';

		timeText.setValue( minutes + ':' + padding + seconds.toFixed( 2 ) );

		updateTimeMark();

	} );

	var prevScale = scale;

	signals.timelineScaled.add( function ( value ) {

		scroller.scrollLeft = ( scroller.scrollLeft * value ) / prevScale;

		updateMarks();
		updateTimeMark();

		prevScale = value;

	} );

	return container;

}
<commit_msg>Removed force from Timeline updateMarks()<commit_after>var Timeline = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();

	var panel = new UI.Panel();
	panel.setPosition( 'absolute' );
	panel.setWidth( '300px' );
	panel.setHeight( '100%' );
	panel.dom.style.background = '#555';
	container.add( panel );

	// controls

	var controls = new UI.Panel();
	controls.setPosition( 'absolute' );
	controls.setWidth( '100%' );
	controls.setPadding( '5px 0px' );
	controls.setBackground( '#666' );
	panel.add( controls );

	var button = new UI.Button();
	button.setLabel( '►' );
	button.setMarginLeft( '5px' );
	button.setPaddingRight( '4px' );
	button.onClick( function () { signals.play.dispatch() } );
	controls.add( button );

	var timeText = new UI.Text();
	timeText.setColor( '#bbb' );
	timeText.setMarginLeft( '5px' );
	timeText.setValue( '0:00.00' );
	controls.add( timeText );

	var playbackRateText = new UI.Text();
	playbackRateText.setColor( '#999' );
	playbackRateText.setMarginLeft( '5px' );
	playbackRateText.setValue( '1.0x' );
	controls.add( playbackRateText );

	var button = new UI.Button();
	button.setLabel( 'MODULES' );
	button.setMarginLeft( '60px' );
	button.onClick( function () {

		scroller.style.background = 'url(' + ( function () {

			var canvas = document.createElement( 'canvas' );
			canvas.width = 1;
			canvas.height = 32;

			var context = canvas.getContext( '2d' );
			context.fillStyle = '#444';
			context.fillRect( 0, 0, 1, 1 );
			return canvas.toDataURL();

		}() ) + ')';

		modules.setDisplay( '' );
		curves.setDisplay( 'none' );

	 } );
	controls.add( button );

	var button = new UI.Button();
	button.setLabel( 'CURVES' );
	button.onClick( function () {

		scroller.style.background = '';

		modules.setDisplay( 'none' );
		curves.setDisplay( '' );

	} );
	controls.add( button );

	// timeline

	var keysDown = {};
	document.addEventListener( 'keydown', function ( event ) { keysDown[ event.keyCode ] = true; } );
	document.addEventListener( 'keyup',   function ( event ) { keysDown[ event.keyCode ] = false; } );

	var time = 0;
	var scale = 32;

	var timeline = new UI.Panel();
	timeline.setPosition( 'absolute' );
	timeline.setLeft( '300px' );
	timeline.setRight( '0px');
	timeline.setTop( '0px' );
	timeline.setBottom( '0px' );
	timeline.setOverflow( 'hidden' );
	timeline.dom.addEventListener( 'mousewheel', function ( event ) {

		// check if [shift] is pressed

		if ( keysDown[ 16 ] === true ) {

			event.preventDefault();

			scale = Math.max( 1, scale + ( event.wheelDeltaY / 10 ) );

			signals.timelineScaled.dispatch( scale );

		}

	} );
	container.add( timeline );

	var marks = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
	marks.style.position = 'absolute';
	marks.setAttribute( 'width', '100%' );
	marks.setAttribute( 'height', '32px' );
	timeline.dom.appendChild( marks );

	var marksPath = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
	marksPath.setAttribute( 'style', 'stroke: #888; stroke-width: 1px; fill: none;' );
	marks.appendChild( marksPath );

	marks.addEventListener( 'mousedown', function ( event ) {

		var onMouseMove = function ( event ) {

			signals.setTime.dispatch( ( event.offsetX + scroller.scrollLeft ) / scale );

		};

		var onMouseUp = function ( event ) {

			onMouseMove( event );

			marks.removeEventListener( 'mousemove', onMouseMove );
			document.removeEventListener( 'mouseup', onMouseUp );

		};

		marks.addEventListener( 'mousemove', onMouseMove, false );
		document.addEventListener( 'mouseup', onMouseUp, false );

	}, false );
	timeline.dom.appendChild( marks );

	var updateMarks = function () {

		var drawing = '';
		var scale4 = scale / 4;
		var offset = - scroller.scrollLeft % scale;
		var width = marks.getBoundingClientRect().width || 1024;

		for ( var i = offset, l = width; i <= l; i += scale ) {

			drawing += 'M ' + i + ' 8 L' + i + ' 24';
			drawing += 'M ' + ( i + ( scale4 * 1 ) ) + ' 12 L' + ( i + ( scale4 * 1 ) ) + ' 20';
			drawing += 'M ' + ( i + ( scale4 * 2 ) ) + ' 12 L' + ( i + ( scale4 * 2 ) ) + ' 20';
			drawing += 'M ' + ( i + ( scale4 * 3 ) ) + ' 12 L' + ( i + ( scale4 * 3 ) ) + ' 20';

		}

		marksPath.setAttribute( 'd', drawing );

	};

	var scroller = document.createElement( 'div' );
	scroller.style.position = 'absolute';
	scroller.style.top = '32px';
	scroller.style.bottom = '0px'
	scroller.style.width = '100%';
	scroller.style.overflow = 'auto';
	scroller.addEventListener( 'scroll', function ( event ) {

		updateMarks();
		updateTimeMark();

	}, false );
	timeline.dom.appendChild( scroller );

	var modules = new Timeline.Modules( editor );
	scroller.appendChild( modules.dom );

	var curves = new Timeline.Curves( editor );
	curves.setDisplay( 'none' );
	scroller.appendChild( curves.dom );

	//

	var timeMark = document.createElement( 'div' );
	timeMark.style.position = 'absolute';
	timeMark.style.top = '0px';
	timeMark.style.left = '-8px';
	timeMark.style.width = '16px';
	timeMark.style.height = '100%';
	timeMark.style.background = 'url(' + ( function () {

		var canvas = document.createElement( 'canvas' );
		canvas.width = 16;
		canvas.height = 1;

		var context = canvas.getContext( '2d' );
		context.fillStyle = '#f00';
		context.fillRect( 8, 0, 1, 1 );

		return canvas.toDataURL();

	}() ) + ')';
	timeMark.style.pointerEvents = 'none';
	timeline.dom.appendChild( timeMark );

	var updateTimeMark = function () {

		timeMark.style.left = ( time * scale ) - scroller.scrollLeft - 8 + 'px';

	};

	updateMarks();

	// signals

	signals.setPlaybackRate.add( function ( value ) {

		playbackRateText.setValue( value.toFixed( 1 ) + 'x' );

	} );

	signals.timeChanged.add( function ( value ) {

		time = value;

		var minutes = Math.floor( value / 60 );
		var seconds = value % 60;
		var padding = seconds < 10 ? '0' : '';

		timeText.setValue( minutes + ':' + padding + seconds.toFixed( 2 ) );

		updateTimeMark();

	} );

	var prevScale = scale;

	signals.timelineScaled.add( function ( value ) {

		scroller.scrollLeft = ( scroller.scrollLeft * value ) / prevScale;

		updateMarks();
		updateTimeMark();

		prevScale = value;

	} );

	return container;

}
<|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Metadata;

(function()
{
    var parameterCounter = 0;

    Metadata =
    {
        metaObject: {},
        getNewDefaultMetaObject: getNewDefaultMetaObject,
        parameterCounter: parameterCounter,
        parameterDialog: parameterDialog,
        atLeastOneParameter: atLeastOneParameter,
        metadataDialog: metadataDialog,
        timePId : null,
        addTimeParameter: addTimeParameter
    };

    $(document).ready(function()
    {
        // Event handlers.
        $("#editMetadata").on('click', metadataDialog);
        $("#editParameters").on('click', parameterDialog);

        var metaScreenHTML = Parts.getMetaScreenHTML();
        $("#metaScreen").html(metaScreenHTML);
        $("#metaForm").on('submit', function()
        {
            saveMetaObject();
            return false;
        });

        var parameterScreenHTML = Parts.getParameterScreenHTML();
        $("#parameterScreen").html(parameterScreenHTML);

        $("#params").on("focus", ".parameterDescription", function()
        {
            $(this).animate({ height: "10em" }, 500);
        });
        $("#params").on("focusout", ".parameterDescription", function()
        {
            $(this).animate({height:"1em"}, 500);
        });

        $("#params").on('click', '.deleteParent', function()
        {
            var tr = $(this).closest('tr');
            tr.addClass("toBeRemoved");
            // console.log("removed parameter with id:\t"+tr[0].id);
            if(tr[0].id === "t" && tr.not(".toBeRemoved"))
            {
                // for time parameter: make visible when Time-parameter has been removed
                $("#addTimeParameter").removeClass("hidden");
            }
            if ($("#params").children().not(".toBeRemoved").length === 0)
                $("#paramsTableHead").addClass("hidden");
        });
    });

    /*
     ** Public Functions
     */

    // Creates and returns a new default meta object containing sensible defaults.
    // If needed, change the defaults here.
    function getNewDefaultMetaObject()
    {
        parameterCounter = 0;

        var pObj = {};

        Metadata.metaObject = {
            name: "",
            difficulty: "medium",
            character: "", //character is defined in properties by free form input text
            description: "",
            parameterObject: pObj,
            scriptVersion: 3,
            defaultChangeType: LanguageManager.sLang("edt_parts_delta"),
        };
    }

    //Create the dialog to change the script description.
    function metadataDialog()
    {
        var tabs = $("#metaTabs");
        tabs.tabs();

        Main.selectNode(null);

        $("#metaScreen").dialog(
        {
            title: LanguageManager.sLang("edt_metadata_title"),
            height: ParameterValues.heightMetaScreen,
            width: ParameterValues.widthMetaScreen,
            modal: true,
            buttons: [
            {
                text: LanguageManager.sLang("edt_common_confirm"),
                click: function()
                {
                    saveMetaObject();
                }
            },
            {
                text: LanguageManager.sLang("edt_common_cancel"),
                click: function()
                {
                    $("#metaScreen").dialog('close');
                }
            }],
            close: function()
            {
                $("#main").focus();
            }
        });

        // Show the stored values for the metadata.
        $("#scriptName").val(Metadata.metaObject.name);
        $("#scriptDifficulty").val(Metadata.metaObject.difficulty);
        $("#scriptDescription").val(Metadata.metaObject.description);
        $("#character").val(Metadata.metaObject.character);
        $("#defaultChangeTypeSelect").val(Metadata.metaObject.defaultChangeType);
    }

    function parameterDialog()
    {
        Main.selectNode(null);

        //console.log('timePId:\t'+Metadata.timePId);
        if (Metadata.timePId !== null )
        {
            $("#addTimeParameter").addClass("hidden");
        }

        $("#parameterScreen").dialog(
        {
            title: LanguageManager.sLang("edt_metadata_parameters_title"),
            height: ParameterValues.heightParameterScreen,
            width: ParameterValues.widthParameterScreen,
            modal: true,
            buttons: [
            {
                text: LanguageManager.sLang("edt_metadata_parameters_to_feedback"),
                click: function()
                {
                    saveParameters();
                    $(this).dialog('close');
                    FeedbackForm.feedbackFormDialog();
                }
            },
            {
                text: LanguageManager.sLang("edt_common_confirm"),
                click: function()
                {
                    saveParameters();
                    $(this).dialog('close');
                }
            },
            {
                text: LanguageManager.sLang("edt_common_cancel"),
                click: function()
                {
                    $(this).dialog('close');
                }
            }],
            close: function()
            {
                $(".toBeRemoved").removeClass("toBeRemoved");
                $(".newParameter").remove();
                //Ugly test to determine if there are parameters. If there are, the table headers need to be visible in the metascreen the next time.
                if (atLeastOneParameter())
                {
                    $("#paramsTableHead").removeClass("hidden");
                }
            }
        });

        $("#params").empty();
        $("#paramsTableHead").addClass("hidden");

        for (var parameterName in Metadata.metaObject.parameterObject)
        {
            var parameter = Metadata.metaObject.parameterObject[parameterName];
            var addedDiv = $("#params").append(HtmlGenerator.parameterHTML).children().last();
            addedDiv.removeClass("newParameter").addClass("existingParameter");

            addedDiv.prop('id', parameterName);
            if(parameterName === "t")
                addedDiv.addClass("isT");
            addedDiv.find(".name").val(parameter.name);
            addedDiv.find(".initialValue").val(parameter.initialValue);
            addedDiv.find(".weightForFinalScore").val(parameter.weightForFinalScore);
            addedDiv.find(".minimumScore").val(parameter.minimumScore);
            addedDiv.find(".maximumScore").val(parameter.maximumScore);
            addedDiv.find(".parameterDescription").val(parameter.parameterDescription);
        }
        if ($("#params").children().length > 0)
            $("#paramsTableHead").removeClass("hidden");

        $("#scriptDescription").val(Metadata.metaObject.description);
        $("#defaultChangeTypeSelect").val(Metadata.metaObject.defaultChangeType);
    }

    function atLeastOneParameter(type)
    {
        var pObj = Metadata.metaObject.parameterObject;
        return (!$.isEmptyObject(pObj));
    }

    function addTimeParameter(div)
    {
        var newParamObject = ObjectGenerator.parameterObject(div);

        if (newParamObject === null) return;

        var id = 't';
        $(div).prop('id', id);
        Metadata.metaObject.parameterObject[id] = newParamObject;

        Metadata.timePId = id;

        $(div).removeClass("newParameter").addClass("existingParameter").addClass('isT');

        var timeObject =
        {
            parameterid : id,
            changeType: "delta",
            value: 1
        };

        for (var nodeId in Main.nodes)
        {
            var node = Main.nodes[nodeId];
            if (node.type === Main.playerType)
            {
                if (node.parameters !== undefined && node.parameters !== null)
                    node.parameters.push(timeObject);
                else
                    node.parameters = [timeObject];
            }
        }
    }

    /*
     ** Private Functions
     */

    function saveParameters()
    {
        Main.unsavedChanges = true;

        $(".toBeRemoved").each(function()
        {
            var id = $(this).prop('id');

            // Remove the preconditions and effects for every node with this parameter.
            for (var nodeID in Main.nodes)
            {
                var node = Main.nodes[nodeID];
                for (var i = 0; i < node.parameters.length; i++)
                    if (node.parameters[i].parameterid == id)
                        node.parameters.splice(i, 1);
                removeAllPreconditionsWithParam(id, node.preconditions);
            }

            delete FeedbackForm.conditions[id];

            if (id === Metadata.timePId && Metadata.timePId !== null)
                Metadata.timePId = null;

            // Remove the parameter from the html and the object.
            $(this).remove();

            delete Metadata.metaObject.parameterObject[id];
        });

        $(".existingParameter").each(function()
        {
            var id = $(this).prop('id');
            var newParamObject = ObjectGenerator.parameterObject($(this));

            Metadata.metaObject.parameterObject[id] = newParamObject;
        });

        // All new parameters.
        $(".newParameter").each(function()
        {
            var newParamObject = ObjectGenerator.parameterObject($(this));

            if (newParamObject === null) return;

            var id = 'p' + (Metadata.parameterCounter += 1).toString();

            $(this).prop('id', id);
            Metadata.metaObject.parameterObject[id] = newParamObject;

            $(this).removeClass("newParameter").addClass("existingParameter");
        });

        //console.log(Metadata.metaObject.parameterObject);
    }

    // Save all changes to the metaObject.
    function saveMetaObject()
    {
        Main.unsavedChanges = true;

        // All parameters that should be removed.
        var previouslySelectedNode = Main.selectedElement;
        Main.selectNode(null);

        Metadata.metaObject.character = $("#character").val();

        Metadata.metaObject.defaultChangeType = $("#defaultChangeTypeSelect").val();

        // Save all values in the dialog to the metaObject.
        Metadata.metaObject.name = $("#scriptName").val();
        Metadata.metaObject.difficulty = $("#scriptDifficulty").val();
        Metadata.metaObject.description = $("#scriptDescription").val();

        var truncatedName;
        if (Metadata.metaObject.name.length > 20)
        {
            truncatedName = Metadata.metaObject.name.substring(0, 17) + "...";
        }
        else
        {
            truncatedName = Metadata.metaObject.name;
        }
        $('#scriptNameTab .scriptName').text(truncatedName);

        $("#metaScreen").dialog('close');
        Main.selectNode(previouslySelectedNode);
    }

    function removeAllPreconditionsWithParam(paramIdToRemove, precondition)
    {
        for (var i = 0; i < precondition.preconditions.length; i++)
        {
            var currentPrecondition = precondition.preconditions[i];
            if ("type" in currentPrecondition)
            {
                removeAllPreconditionsWithParam(paramIdToRemove,
                    currentPrecondition);
                if (currentPrecondition.preconditions.length === 0)
                {
                    precondition.preconditions.splice(i, 1);
                    i--;
                }
            }
            else
            {
                if (currentPrecondition.parameterid == paramIdToRemove)
                {
                    precondition.preconditions.splice(i, 1);
                    i--;
                }
            }
        }
    }

})();
<commit_msg>Fixed inconsistency in script name format, updating the main script name<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Metadata;

(function()
{
    var parameterCounter = 0;

    Metadata =
    {
        metaObject: {},
        getNewDefaultMetaObject: getNewDefaultMetaObject,
        parameterCounter: parameterCounter,
        parameterDialog: parameterDialog,
        atLeastOneParameter: atLeastOneParameter,
        metadataDialog: metadataDialog,
        timePId : null,
        addTimeParameter: addTimeParameter
    };

    $(document).ready(function()
    {
        // Event handlers.
        $("#editMetadata").on('click', metadataDialog);
        $("#editParameters").on('click', parameterDialog);

        var metaScreenHTML = Parts.getMetaScreenHTML();
        $("#metaScreen").html(metaScreenHTML);
        $("#metaForm").on('submit', function()
        {
            saveMetaObject();
            return false;
        });

        var parameterScreenHTML = Parts.getParameterScreenHTML();
        $("#parameterScreen").html(parameterScreenHTML);

        $("#params").on("focus", ".parameterDescription", function()
        {
            $(this).animate({ height: "10em" }, 500);
        });
        $("#params").on("focusout", ".parameterDescription", function()
        {
            $(this).animate({height:"1em"}, 500);
        });

        $("#params").on('click', '.deleteParent', function()
        {
            var tr = $(this).closest('tr');
            tr.addClass("toBeRemoved");
            // console.log("removed parameter with id:\t"+tr[0].id);
            if(tr[0].id === "t" && tr.not(".toBeRemoved"))
            {
                // for time parameter: make visible when Time-parameter has been removed
                $("#addTimeParameter").removeClass("hidden");
            }
            if ($("#params").children().not(".toBeRemoved").length === 0)
                $("#paramsTableHead").addClass("hidden");
        });
    });

    /*
     ** Public Functions
     */

    // Creates and returns a new default meta object containing sensible defaults.
    // If needed, change the defaults here.
    function getNewDefaultMetaObject()
    {
        parameterCounter = 0;

        var pObj = {};

        Metadata.metaObject = {
            name: "",
            difficulty: "medium",
            character: "", //character is defined in properties by free form input text
            description: "",
            parameterObject: pObj,
            scriptVersion: 3,
            defaultChangeType: LanguageManager.sLang("edt_parts_delta"),
        };
    }

    //Create the dialog to change the script description.
    function metadataDialog()
    {
        var tabs = $("#metaTabs");
        tabs.tabs();

        Main.selectNode(null);

        $("#metaScreen").dialog(
        {
            title: LanguageManager.sLang("edt_metadata_title"),
            height: ParameterValues.heightMetaScreen,
            width: ParameterValues.widthMetaScreen,
            modal: true,
            buttons: [
            {
                text: LanguageManager.sLang("edt_common_confirm"),
                click: function()
                {
                    saveMetaObject();
                }
            },
            {
                text: LanguageManager.sLang("edt_common_cancel"),
                click: function()
                {
                    $("#metaScreen").dialog('close');
                }
            }],
            close: function()
            {
                $("#main").focus();
            }
        });

        // Show the stored values for the metadata.
        $("#scriptName").val(Metadata.metaObject.name);
        $("#scriptDifficulty").val(Metadata.metaObject.difficulty);
        $("#scriptDescription").val(Metadata.metaObject.description);
        $("#character").val(Metadata.metaObject.character);
        $("#defaultChangeTypeSelect").val(Metadata.metaObject.defaultChangeType);
    }

    function parameterDialog()
    {
        Main.selectNode(null);

        //console.log('timePId:\t'+Metadata.timePId);
        if (Metadata.timePId !== null )
        {
            $("#addTimeParameter").addClass("hidden");
        }

        $("#parameterScreen").dialog(
        {
            title: LanguageManager.sLang("edt_metadata_parameters_title"),
            height: ParameterValues.heightParameterScreen,
            width: ParameterValues.widthParameterScreen,
            modal: true,
            buttons: [
            {
                text: LanguageManager.sLang("edt_metadata_parameters_to_feedback"),
                click: function()
                {
                    saveParameters();
                    $(this).dialog('close');
                    FeedbackForm.feedbackFormDialog();
                }
            },
            {
                text: LanguageManager.sLang("edt_common_confirm"),
                click: function()
                {
                    saveParameters();
                    $(this).dialog('close');
                }
            },
            {
                text: LanguageManager.sLang("edt_common_cancel"),
                click: function()
                {
                    $(this).dialog('close');
                }
            }],
            close: function()
            {
                $(".toBeRemoved").removeClass("toBeRemoved");
                $(".newParameter").remove();
                //Ugly test to determine if there are parameters. If there are, the table headers need to be visible in the metascreen the next time.
                if (atLeastOneParameter())
                {
                    $("#paramsTableHead").removeClass("hidden");
                }
            }
        });

        $("#params").empty();
        $("#paramsTableHead").addClass("hidden");

        for (var parameterName in Metadata.metaObject.parameterObject)
        {
            var parameter = Metadata.metaObject.parameterObject[parameterName];
            var addedDiv = $("#params").append(HtmlGenerator.parameterHTML).children().last();
            addedDiv.removeClass("newParameter").addClass("existingParameter");

            addedDiv.prop('id', parameterName);
            if(parameterName === "t")
                addedDiv.addClass("isT");
            addedDiv.find(".name").val(parameter.name);
            addedDiv.find(".initialValue").val(parameter.initialValue);
            addedDiv.find(".weightForFinalScore").val(parameter.weightForFinalScore);
            addedDiv.find(".minimumScore").val(parameter.minimumScore);
            addedDiv.find(".maximumScore").val(parameter.maximumScore);
            addedDiv.find(".parameterDescription").val(parameter.parameterDescription);
        }
        if ($("#params").children().length > 0)
            $("#paramsTableHead").removeClass("hidden");

        $("#scriptDescription").val(Metadata.metaObject.description);
        $("#defaultChangeTypeSelect").val(Metadata.metaObject.defaultChangeType);
    }

    function atLeastOneParameter(type)
    {
        var pObj = Metadata.metaObject.parameterObject;
        return (!$.isEmptyObject(pObj));
    }

    function addTimeParameter(div)
    {
        var newParamObject = ObjectGenerator.parameterObject(div);

        if (newParamObject === null) return;

        var id = 't';
        $(div).prop('id', id);
        Metadata.metaObject.parameterObject[id] = newParamObject;

        Metadata.timePId = id;

        $(div).removeClass("newParameter").addClass("existingParameter").addClass('isT');

        var timeObject =
        {
            parameterid : id,
            changeType: "delta",
            value: 1
        };

        for (var nodeId in Main.nodes)
        {
            var node = Main.nodes[nodeId];
            if (node.type === Main.playerType)
            {
                if (node.parameters !== undefined && node.parameters !== null)
                    node.parameters.push(timeObject);
                else
                    node.parameters = [timeObject];
            }
        }
    }

    /*
     ** Private Functions
     */

    function saveParameters()
    {
        Main.unsavedChanges = true;

        $(".toBeRemoved").each(function()
        {
            var id = $(this).prop('id');

            // Remove the preconditions and effects for every node with this parameter.
            for (var nodeID in Main.nodes)
            {
                var node = Main.nodes[nodeID];
                for (var i = 0; i < node.parameters.length; i++)
                    if (node.parameters[i].parameterid == id)
                        node.parameters.splice(i, 1);
                removeAllPreconditionsWithParam(id, node.preconditions);
            }

            delete FeedbackForm.conditions[id];

            if (id === Metadata.timePId && Metadata.timePId !== null)
                Metadata.timePId = null;

            // Remove the parameter from the html and the object.
            $(this).remove();

            delete Metadata.metaObject.parameterObject[id];
        });

        $(".existingParameter").each(function()
        {
            var id = $(this).prop('id');
            var newParamObject = ObjectGenerator.parameterObject($(this));

            Metadata.metaObject.parameterObject[id] = newParamObject;
        });

        // All new parameters.
        $(".newParameter").each(function()
        {
            var newParamObject = ObjectGenerator.parameterObject($(this));

            if (newParamObject === null) return;

            var id = 'p' + (Metadata.parameterCounter += 1).toString();

            $(this).prop('id', id);
            Metadata.metaObject.parameterObject[id] = newParamObject;

            $(this).removeClass("newParameter").addClass("existingParameter");
        });

        //console.log(Metadata.metaObject.parameterObject);
    }

    // Save all changes to the metaObject.
    function saveMetaObject()
    {
        Main.unsavedChanges = true;

        // All parameters that should be removed.
        var previouslySelectedNode = Main.selectedElement;
        Main.selectNode(null);

        Metadata.metaObject.character = $("#character").val();

        Metadata.metaObject.defaultChangeType = $("#defaultChangeTypeSelect").val();

        // Save all values in the dialog to the metaObject
        Metadata.metaObject.name = formatScriptName($("#scriptName").val());
        $('#scriptNameTab .scriptName').text(Metadata.metaObject.name);

        Metadata.metaObject.difficulty = $("#scriptDifficulty").val();
        Metadata.metaObject.description = $("#scriptDescription").val();

        $("#metaScreen").dialog('close');
        Main.selectNode(previouslySelectedNode);
    }

    function removeAllPreconditionsWithParam(paramIdToRemove, precondition)
    {
        for (var i = 0; i < precondition.preconditions.length; i++)
        {
            var currentPrecondition = precondition.preconditions[i];
            if ("type" in currentPrecondition)
            {
                removeAllPreconditionsWithParam(paramIdToRemove,
                    currentPrecondition);
                if (currentPrecondition.preconditions.length === 0)
                {
                    precondition.preconditions.splice(i, 1);
                    i--;
                }
            }
            else
            {
                if (currentPrecondition.parameterid == paramIdToRemove)
                {
                    precondition.preconditions.splice(i, 1);
                    i--;
                }
            }
        }
    }

    function formatScriptName(scriptName)
    {
        scriptName = scriptName.trim().replace(/[^a-z0-9_,\.\s\|\!\&\\\/\'\"\[\]\{\+\=\(\)\}]/gi, '');
        if (scriptName !== "" && scriptName.length <= 35)
        {
            return scriptName;
        }
        else
        {
            return Metadata.metaObject.name;
        }
    }
})();
<|endoftext|>


<commit_before>var tree;
function loadNodeData(node, fnLoadComplete)  {

            var messages = [];
            //prepare URL for XHR request:

			var compoIdParameter ="";
			if(node.data.componentId != "undefined"){
				compoIdParameter="&compoId="+node.data.componentId
			}

            var sUrl = context+"/TreeMenuAjaxServlet?mtype="+menuType+"&ntype="+node.data.nodeType+"&key="+node.data.id+"&leaf="+node.data.isLeaf+compoIdParameter;
            //prepare our callback object
            var callback = {

                success: function(oResponse) {
                    YAHOO.log("XHR transaction was successful.", "info", "example");
					try {
						messages = YAHOO.lang.JSON.parse(oResponse.responseText);
                    }
					catch (x) {
						alert("JSON Parse failed!"+x);
						return;
					}

					for (var i = 0, len = messages.length; i < len; ++i) {
						var m = messages[i];
						var	tempNode = new YAHOO.widget.TextNode(m, node, false);
							tempNode.labelElId = m.id;
						if(m.isLeaf!="undefined"){
							tempNode.isLeaf=m.isLeaf;
						}
						if(m.labelStyle!="undefined"){
							tempNode.labelStyle = m.labelStyle;
						}
						if (m.nbObjects != -1){
							tempNode.label = m.label + " ("+m.nbObjects+")";
						}
						else {
							tempNode.label = m.label;
						}
					}

                    oResponse.argument.fnLoadComplete();
                },

                failure: function(oResponse) {
                    YAHOO.log("Failed to process XHR transaction.", "info", "example");
                    oResponse.argument.fnLoadComplete();
                },

                argument: {
                    "node": node,
                    "fnLoadComplete": fnLoadComplete,
                },

                //timeout -- if more than 7 seconds go by, we'll abort
                //the transaction and assume there are no children:
                timeout: 70000
            };

            YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
        }

(function() {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

  	//Add an onDOMReady handler to build the tree and the resize bar when the document is ready
    Event.onDOMReady(function() {

        //build the tree
    	return buildTree();

    });
})();
<commit_msg>related to feature #228, treeview didn't appears with Internet Explorer.<commit_after>var tree;
function loadNodeData(node, fnLoadComplete)  {

            var messages = [];
            //prepare URL for XHR request:

			var compoIdParameter ="";
			if(node.data.componentId != "undefined"){
				compoIdParameter="&compoId="+node.data.componentId
			}

            var sUrl = context+"/TreeMenuAjaxServlet?mtype="+menuType+"&ntype="+node.data.nodeType+"&key="+node.data.id+"&leaf="+node.data.isLeaf+compoIdParameter;
            //prepare our callback object
            var callback = {

                success: function(oResponse) {
                    YAHOO.log("XHR transaction was successful.", "info", "example");
					try {
						messages = YAHOO.lang.JSON.parse(oResponse.responseText);
                    }
					catch (x) {
						alert("JSON Parse failed!"+x);
						return;
					}

					for (var i = 0, len = messages.length; i < len; ++i) {
						var m = messages[i];
						var	tempNode = new YAHOO.widget.TextNode(m, node, false);
							tempNode.labelElId = m.id;
						if(m.isLeaf!="undefined"){
							tempNode.isLeaf=m.isLeaf;
						}
						if(m.labelStyle!="undefined"){
							tempNode.labelStyle = m.labelStyle;
						}
						if (m.nbObjects != -1){
							tempNode.label = m.label + " ("+m.nbObjects+")";
						}
						else {
							tempNode.label = m.label;
						}
					}

                    oResponse.argument.fnLoadComplete();
                },

                failure: function(oResponse) {
                    YAHOO.log("Failed to process XHR transaction.", "info", "example");
                    oResponse.argument.fnLoadComplete();
                },

                argument: {
                    "node": node,
                    "fnLoadComplete": fnLoadComplete
                },

                //timeout -- if more than 7 seconds go by, we'll abort
                //the transaction and assume there are no children:
                timeout: 70000
            };

            YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
        }

(function() {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

  	//Add an onDOMReady handler to build the tree and the resize bar when the document is ready
    Event.onDOMReady(function() {

        //build the tree
    	return buildTree();

    });
})();
<|endoftext|>