<commit_before>import React from 'react';
import {shallow, mount} from 'enzyme';

import {cloneRepository, buildRepository} from '../helpers';
import Commit, {nullCommit} from '../../lib/models/commit';
import Branch, {nullBranch} from '../../lib/models/branch';
import UserStore from '../../lib/models/user-store';
import CommitView from '../../lib/views/commit-view';

describe('CommitView', function() {
  let atomEnv, commandRegistry, tooltips, config, lastCommit;
  let app;

  beforeEach(function() {
    atomEnv = global.buildAtomEnvironment();
    commandRegistry = atomEnv.commands;
    tooltips = atomEnv.tooltips;
    config = atomEnv.config;

    lastCommit = new Commit({sha: '1234abcd', message: 'commit message'});
    const noop = () => {};
    const returnTruthyPromise = () => Promise.resolve(true);
    const store = new UserStore({config});

    app = (
      <CommitView
        commandRegistry={commandRegistry}
        tooltips={tooltips}
        config={config}
        lastCommit={lastCommit}
        userStore={store}
        currentBranch={nullBranch}
        isMerging={false}
        stagedChangesExist={false}
        mergeConflictsExist={false}
        isCommitting={false}
        deactivateCommitBox={false}
        maximumCharacterLimit={72}
        message=""
        prepareToCommit={returnTruthyPromise}
        commit={noop}
        abortMerge={noop}
        onChangeMessage={noop}
        toggleExpandedCommitMessageEditor={noop}
      />
    );
  });

  afterEach(function() {
    atomEnv.destroy();
  });

  describe('when the repo is loading', function() {
    beforeEach(function() {
      app = React.cloneElement(app, {lastCommit: nullCommit});
    });

    it('disables the commit button', function() {
      app = React.cloneElement(app, {message: 'even with text'});
      const wrapper = shallow(app);

      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });
  });

  it('displays the remaining characters limit based on which line is being edited', function() {
    const wrapper = mount(app);
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '72');

    wrapper.setProps({message: 'abcde fghij'});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '61');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: '\nklmno'});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '∞');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: 'abcde\npqrst'});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '∞');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.find('atom-text-editor').getDOMNode().getModel().setCursorBufferPosition([0, 3]);
    wrapper.update();
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '67');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({stagedChangesExist: true, maximumCharacterLimit: 50});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '45');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: 'a'.repeat(41)}).update();
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '9');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isTrue(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: 'a'.repeat(58)}).update();
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '-8');
    assert.isTrue(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));
  });

  describe('the commit button', function() {
    let wrapper;

    beforeEach(async function() {
      const workdirPath = await cloneRepository('three-files');
      const repository = await buildRepository(workdirPath);

      app = React.cloneElement(app, {
        repository,
        stagedChangesExist: true,
        mergeConflictsExist: false,
        message: 'something',
      });
      wrapper = mount(app);
    });

    it('is disabled when no changes are staged', function() {
      wrapper.setProps({stagedChangesExist: false});
      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));

      wrapper.setProps({stagedChangesExist: true});
      assert.isFalse(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });

    it('is disabled when there are merge conflicts', function() {
      wrapper.setProps({mergeConflictsExist: true});
      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));

      wrapper.setProps({mergeConflictsExist: false});
      assert.isFalse(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });

    it('is disabled when the commit message is empty', function() {
      wrapper.setProps({message: ''}).update();
      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));

      wrapper.setProps({message: 'Not empty'}).update();
      assert.isFalse(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });

    it('displays the current branch name', function() {
      const currentBranch = new Branch('aw-do-the-stuff');
      wrapper.setProps({currentBranch});
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Commit to aw-do-the-stuff');
    });

    it('indicates when a commit will be detached', function() {
      const currentBranch = Branch.createDetached('master~3');
      wrapper.setProps({currentBranch});
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Create detached commit');
    });

    it('displays a progress message while committing', function() {
      wrapper.setState({showWorking: true});
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Working...');
    });

    it('falls back to "commit" with no current branch', function() {
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Commit');
    });
  });

  describe('committing', function() {
    let commit, prepareToCommitResolution;
    let wrapper, editorElement, editor, commitButton, workspaceElement;

    beforeEach(function() {
      const prepareToCommit = () => Promise.resolve(prepareToCommitResolution);

      commit = sinon.spy();
      app = React.cloneElement(app, {stagedChangesExist: true, prepareToCommit, commit, message: 'Something'});
      wrapper = mount(app);

      editorElement = wrapper.find('atom-text-editor').getDOMNode();
      sinon.spy(editorElement, 'focus');
      editor = editorElement.getModel();

      // Perform an extra render to ensure the editor text is reflected in the commit button enablement.
      // The controller accomplishes this by re-rendering on Repository update.
      wrapper.setProps({});

      commitButton = wrapper.find('.github-CommitView-commit');
      workspaceElement = atomEnv.views.getView(atomEnv.workspace);
    });

    describe('when props.prepareToCommit() resolves true', function() {
      beforeEach(function() {
        prepareToCommitResolution = true;
      });

      it('calls props.commit(message) when the commit button is clicked', async function() {
        wrapper.update();
        commitButton.simulate('click');

        await assert.async.isTrue(commit.calledWith('Something'));

        // undo history is cleared
        commandRegistry.dispatch(editorElement, 'core:undo');
        assert.equal(editor.getText(), '');
      });

      it('calls props.commit(message) when github:commit is dispatched', async function() {
        commandRegistry.dispatch(workspaceElement, 'github:commit');

        await assert.async.isTrue(commit.calledWith('Something'));
      });
    });

    describe('when props.prepareToCommit() resolves false', function() {
      beforeEach(function() {
        prepareToCommitResolution = false;
      });

      it('takes no further action when the commit button is clicked', async function() {
        commitButton.simulate('click');

        await assert.async.isTrue(editorElement.focus.called);
        assert.isFalse(commit.called);
      });

      it('takes no further action when github:commit is dispatched', async function() {
        commandRegistry.dispatch(workspaceElement, 'github:commit');

        await assert.async.isTrue(editorElement.focus.called);
        assert.isFalse(commit.called);
      });
    });
  });

  it('shows the "Abort Merge" button when props.isMerging is true', function() {
    app = React.cloneElement(app, {isMerging: true});
    const wrapper = shallow(app);
    assert.isTrue(wrapper.find('.github-CommitView-abortMerge').exists());

    wrapper.setProps({isMerging: false});
    assert.isFalse(wrapper.find('.github-CommitView-abortMerge').exists());
  });

  it('calls props.abortMerge() when the "Abort Merge" button is clicked', function() {
    const abortMerge = sinon.stub().resolves();
    app = React.cloneElement(app, {abortMerge, stagedChangesExist: true, isMerging: true});
    const wrapper = shallow(app);

    wrapper.find('.github-CommitView-abortMerge').simulate('click');
    assert.isTrue(abortMerge.calledOnce);
  });

  describe('restoring focus', function() {
    it('to the commit button', function() {
      const wrapper = mount(app);
      sinon.spy(wrapper.instance().refCommitButton.get(), 'focus');

      wrapper.instance().setFocus(CommitView.focus.COMMIT_BUTTON);
      assert.isTrue(wrapper.instance().refCommitButton.get().focus.called);
    });
  });
});
<commit_msg>add unit tests for co-author functionality in `CommitView`<commit_after>import React from 'react';
import {shallow, mount} from 'enzyme';

import Author from '../../lib/models/author'
import CoAuthorForm from '../../lib/views/co-author-form';
import {cloneRepository, buildRepository} from '../helpers';
import Commit, {nullCommit} from '../../lib/models/commit';
import Branch, {nullBranch} from '../../lib/models/branch';
import ObserveModel from '../../lib/views/observe-model';
import UserStore from '../../lib/models/user-store';
import CommitView from '../../lib/views/commit-view';

describe('CommitView', function() {
  let atomEnv, commandRegistry, tooltips, config, lastCommit;
  let app;

  beforeEach(function() {
    atomEnv = global.buildAtomEnvironment();
    commandRegistry = atomEnv.commands;
    tooltips = atomEnv.tooltips;
    config = atomEnv.config;

    lastCommit = new Commit({sha: '1234abcd', message: 'commit message'});
    const noop = () => {};
    const returnTruthyPromise = () => Promise.resolve(true);
    const store = new UserStore({config});

    app = (
      <CommitView
        commandRegistry={commandRegistry}
        tooltips={tooltips}
        config={config}
        lastCommit={lastCommit}
        userStore={store}
        currentBranch={nullBranch}
        isMerging={false}
        stagedChangesExist={false}
        mergeConflictsExist={false}
        isCommitting={false}
        deactivateCommitBox={false}
        maximumCharacterLimit={72}
        message=""
        prepareToCommit={returnTruthyPromise}
        commit={noop}
        abortMerge={noop}
        onChangeMessage={noop}
        toggleExpandedCommitMessageEditor={noop}
        updateSelectedCoAuthors={noop}
      />
    );
  });

  afterEach(function() {
    atomEnv.destroy();
  });

  describe('coauthor stuff', function() {
    let wrapper;
    beforeEach(function() {
      wrapper = shallow(app);
    })
    it('on initial load, renders co-author toggle but not input or form', function() {
      const coAuthorButton = wrapper.find('.github-CommitView-coAuthorToggle');
      assert.deepEqual(coAuthorButton.length, 1);
      assert.isFalse(coAuthorButton.hasClass('focused'));

      const coAuthorInput = wrapper.find('github-CommitView-coAuthorEditor');
      assert.deepEqual(coAuthorInput.length, 0);

      const coAuthorForm = wrapper.find(CoAuthorForm);
      assert.deepEqual(coAuthorForm.length, 0);
    });
    it('renders co-author input when toggle is clicked', function() {
      const coAuthorButton = wrapper.find('.github-CommitView-coAuthorToggle');
      coAuthorButton.simulate('click');

      const coAuthorInput = wrapper.find(ObserveModel);
      assert.deepEqual(coAuthorInput.length, 1);
    });
    it('renders co-author form when a new co-author is added', function() {
      const coAuthorButton = wrapper.find('.github-CommitView-coAuthorToggle');
      coAuthorButton.simulate('click');

      const newAuthor = Author.createNew('pizza@unicorn.party', 'Pizza Unicorn');
      wrapper.instance().onSelectedCoAuthorsChanged([newAuthor]);
      wrapper.update();

      const coAuthorForm = wrapper.find(CoAuthorForm);
      assert.deepEqual(coAuthorForm.length, 1);
    });

  });

  describe('when the repo is loading', function() {
    beforeEach(function() {
      app = React.cloneElement(app, {lastCommit: nullCommit});
    });

    it('disables the commit button', function() {
      app = React.cloneElement(app, {message: 'even with text'});
      const wrapper = shallow(app);

      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });
  });

  it('displays the remaining characters limit based on which line is being edited', function() {
    const wrapper = mount(app);
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '72');

    wrapper.setProps({message: 'abcde fghij'});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '61');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: '\nklmno'});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '∞');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: 'abcde\npqrst'});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '∞');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.find('atom-text-editor').getDOMNode().getModel().setCursorBufferPosition([0, 3]);
    wrapper.update();
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '67');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({stagedChangesExist: true, maximumCharacterLimit: 50});
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '45');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: 'a'.repeat(41)}).update();
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '9');
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isTrue(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));

    wrapper.setProps({message: 'a'.repeat(58)}).update();
    assert.strictEqual(wrapper.find('.github-CommitView-remaining-characters').text(), '-8');
    assert.isTrue(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-error'));
    assert.isFalse(wrapper.find('.github-CommitView-remaining-characters').hasClass('is-warning'));
  });

  describe('the commit button', function() {
    let wrapper;

    beforeEach(async function() {
      const workdirPath = await cloneRepository('three-files');
      const repository = await buildRepository(workdirPath);

      app = React.cloneElement(app, {
        repository,
        stagedChangesExist: true,
        mergeConflictsExist: false,
        message: 'something',
      });
      wrapper = mount(app);
    });

    it('is disabled when no changes are staged', function() {
      wrapper.setProps({stagedChangesExist: false});
      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));

      wrapper.setProps({stagedChangesExist: true});
      assert.isFalse(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });

    it('is disabled when there are merge conflicts', function() {
      wrapper.setProps({mergeConflictsExist: true});
      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));

      wrapper.setProps({mergeConflictsExist: false});
      assert.isFalse(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });

    it('is disabled when the commit message is empty', function() {
      wrapper.setProps({message: ''}).update();
      assert.isTrue(wrapper.find('.github-CommitView-commit').prop('disabled'));

      wrapper.setProps({message: 'Not empty'}).update();
      assert.isFalse(wrapper.find('.github-CommitView-commit').prop('disabled'));
    });

    it('displays the current branch name', function() {
      const currentBranch = new Branch('aw-do-the-stuff');
      wrapper.setProps({currentBranch});
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Commit to aw-do-the-stuff');
    });

    it('indicates when a commit will be detached', function() {
      const currentBranch = Branch.createDetached('master~3');
      wrapper.setProps({currentBranch});
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Create detached commit');
    });

    it('displays a progress message while committing', function() {
      wrapper.setState({showWorking: true});
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Working...');
    });

    it('falls back to "commit" with no current branch', function() {
      assert.strictEqual(wrapper.find('.github-CommitView-commit').text(), 'Commit');
    });
  });

  describe('committing', function() {
    let commit, prepareToCommitResolution;
    let wrapper, editorElement, editor, commitButton, workspaceElement;

    beforeEach(function() {
      const prepareToCommit = () => Promise.resolve(prepareToCommitResolution);

      commit = sinon.spy();
      app = React.cloneElement(app, {stagedChangesExist: true, prepareToCommit, commit, message: 'Something'});
      wrapper = mount(app);

      editorElement = wrapper.find('atom-text-editor').getDOMNode();
      sinon.spy(editorElement, 'focus');
      editor = editorElement.getModel();

      // Perform an extra render to ensure the editor text is reflected in the commit button enablement.
      // The controller accomplishes this by re-rendering on Repository update.
      wrapper.setProps({});

      commitButton = wrapper.find('.github-CommitView-commit');
      workspaceElement = atomEnv.views.getView(atomEnv.workspace);
    });

    describe('when props.prepareToCommit() resolves true', function() {
      beforeEach(function() {
        prepareToCommitResolution = true;
      });

      it('calls props.commit(message) when the commit button is clicked', async function() {
        wrapper.update();
        commitButton.simulate('click');

        await assert.async.isTrue(commit.calledWith('Something'));

        // undo history is cleared
        commandRegistry.dispatch(editorElement, 'core:undo');
        assert.equal(editor.getText(), '');
      });

      it('calls props.commit(message) when github:commit is dispatched', async function() {
        commandRegistry.dispatch(workspaceElement, 'github:commit');

        await assert.async.isTrue(commit.calledWith('Something'));
      });
    });

    describe('when props.prepareToCommit() resolves false', function() {
      beforeEach(function() {
        prepareToCommitResolution = false;
      });

      it('takes no further action when the commit button is clicked', async function() {
        commitButton.simulate('click');

        await assert.async.isTrue(editorElement.focus.called);
        assert.isFalse(commit.called);
      });

      it('takes no further action when github:commit is dispatched', async function() {
        commandRegistry.dispatch(workspaceElement, 'github:commit');

        await assert.async.isTrue(editorElement.focus.called);
        assert.isFalse(commit.called);
      });
    });
  });

  it('shows the "Abort Merge" button when props.isMerging is true', function() {
    app = React.cloneElement(app, {isMerging: true});
    const wrapper = shallow(app);
    assert.isTrue(wrapper.find('.github-CommitView-abortMerge').exists());

    wrapper.setProps({isMerging: false});
    assert.isFalse(wrapper.find('.github-CommitView-abortMerge').exists());
  });

  it('calls props.abortMerge() when the "Abort Merge" button is clicked', function() {
    const abortMerge = sinon.stub().resolves();
    app = React.cloneElement(app, {abortMerge, stagedChangesExist: true, isMerging: true});
    const wrapper = shallow(app);

    wrapper.find('.github-CommitView-abortMerge').simulate('click');
    assert.isTrue(abortMerge.calledOnce);
  });

  describe('restoring focus', function() {
    it('to the commit button', function() {
      const wrapper = mount(app);
      sinon.spy(wrapper.instance().refCommitButton.get(), 'focus');

      wrapper.instance().setFocus(CommitView.focus.COMMIT_BUTTON);
      assert.isTrue(wrapper.instance().refCommitButton.get().focus.called);
    });
  });
});
<|endoftext|>


<commit_before>var tpl = {

    // Hash of preloaded templates for the app
    templates:{},

    // Recursively pre-load all the templates for the app.
    // This implementation should be changed in a production environment. All the template files should be
    // concatenated in a single file.
    loadTemplates:function (names, callback) {

        var that = this;

        var loadTemplate = function (index) {
            var name = names[index];
            FMS.printDebug('Loading template: ' + name + ', index: ' + index);
            $.get('templates/' + CONFIG.LANGUAGE + '/' + name + '.html', function (data) {
                that.templates[name] = data;
                index++;
                if (index < names.length) {
                    loadTemplate(index);
                } else {
                    callback();
                }
            });
        };

        loadTemplate(0);
    },

    // Get template by name from hash of preloaded templates
    get:function (name) {
        return this.templates[name];
    }

};

(function (FMS, Backbone, _, $) {
    _.extend(FMS, {
        templates: [
            'home', 'help', 'initial_help', 'around', 'offline', 'save_offline', 'reports', 'login', 'address_search', 'existing', 'photo', 'details', 'details_extra', 'submit', 'submit_email', 'submit_name', 'submit_set_password', 'submit_password', 'submit_confirm', 'sent'
        ],

        usedBefore: 0,
        isLoggedIn: 0,
        isOffline: 0,
        initialized: 0,
        users: new FMS.Users(),
        currentUser: null,
        currentPosition: null,
        isAndroid: false,
        iPhoneModel: 0,
        uploadTimeout: CONFIG.UPLOAD_TIMEOUT || 120000,
        testing: 0,

        currentDraft: new FMS.Draft(),
        allDrafts: new FMS.Drafts(),

        reportToView: null,

        online: function() {
            FMS.isOffline = 0;
        },

        offline: function() {
            FMS.isOffline = 1;
        },

        printDebug: function(msg) {
            if ( CONFIG.DEBUG ) {
                console.log(msg);
            }
        },

        checkOnlineStatus: function() {
            if ( navigator && navigator.connection && ( navigator.connection.type == Connection.NONE ||
                    navigator.connection.type == Connection.UNKNOWN ) ) {
                FMS.offline();
            } else {
                FMS.online();
            }
        },

        checkLoggedInStatus: function() {
            if ( FMS.isOffline ) {
            } else {
                $.ajax( {
                    url: CONFIG.FMS_URL + '/auth/ajax/check_auth',
                    type: 'GET',
                    dataType: 'json',
                    timeout: 30000,
                    success: function( data, status ) {
                        FMS.isLoggedIn = 1;
                    },
                    error: function() {
                        FMS.isLoggedIn = 0;
                    }
                } );
            }
        },

        saveCurrentDraft: function(force) {
            FMS.router.pause();
            if ( force || FMS.currentDraft.isPartial() ) {
                FMS.allDrafts.add( FMS.currentDraft );
                FMS.currentDraft.save();
                localStorage.currentDraftID = FMS.currentDraft.id;
            }
        },

        loadCurrentDraft: function() {
            if ( localStorage.currentDraftID && localStorage.currentDraftID != 'null' ) {
                var r = FMS.allDrafts.get( localStorage.currentDraftID );
                if ( r ) {
                    FMS.currentDraft = r;
                }
            }
            localStorage.currentDraftID = null;
        },

        removeDraft: function(draftID, removePhoto) {
            var draft = FMS.allDrafts.get(draftID);
            var uri = draft.get('file');
            FMS.allDrafts.remove(draft);
            draft.destroy();

            if ( removePhoto && uri ) {
                return FMS.files.deleteURI( uri );
            }
            var p = $.Deferred();
            p.resolve();
            return p;
        },

        setCurrentDraft: function(draft) {
            FMS.currentDraft = draft;
            localStorage.currentDraftID = draft.id;
        },

        clearCurrentDraft: function() {
            FMS.currentDraft = new FMS.Draft();
            localStorage.currentDraftID = null;
        },

        openExternal: function(e) {
            e.preventDefault();
            var href = $(e.srcElement).attr('href');
            FMS.openExternalURL(href);
            return false;
        },

        openExternalURL: function(url) {
            window.cordova.InAppBrowser.open(url, '_system');
        },

        setHelpHeight: function() {
            var helpContent = $('#helpContent'),
            viewHeight = $(window).height();

            helpContent.height(viewHeight - 60);
        },

        setupHelp: function() {
            var help = $('#help'),
            helpContent = $('#helpContent'),
            viewWidth = $(window).width();

            var template;
            if ( !FMS.usedBefore ) {
                template = _.template( tpl.get('initial_help') );
            } else {
                template = _.template( tpl.get('help') );
            }
            helpContent.html(template());

            if ( !help.hasClass('android2') ) {
                if ( FMS.usedBefore ) {
                    FMS.setHelpHeight();
                }
                help.show();
            }
            help.css('left', viewWidth);
        },

        helpShow: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help');
            $('#display-help').hide();
            var onShow = function() {
                $('#help').show();
                $('#dismiss').show();
            };
            help.animate({left: 0}, onShow );
        },

        helpHide: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help'),
            viewWidth = $(window).width();

            $('#dismiss').hide();
            if ( help.hasClass('android2') ) {
                $('body').scrollTop(0);
            }
            var onHide = function() {
                $('#display-help').show();
                $('#helpContent').scrollTop(0);
                if ( $('#help').hasClass('android2') ) {
                    $('#help').hide();
                }
                if ( !FMS.usedBefore ) {
                    var template = _.template( tpl.get('help') );
                    $('#helpContent').html(template());
                    FMS.usedBefore = 1;
                    localStorage.usedBefore = 1;
                    if ( !$('#help').hasClass('android2') ) {
                        FMS.setHelpHeight();
                    }
                }
            };
            help.animate({left: viewWidth}, 400, 'swing', onHide );
        },

        initialize: function () {
            if ( this.initialized == 1 ) {
                return this;
            }
            $('#load-screen').height( $(window).height() );
            FMS.initialized = 1;
            if ( navigator && navigator.splashscreen ) {
                navigator.splashscreen.hide();
            }
            tpl.loadTemplates( FMS.templates, function() {

                if ( typeof device !== 'undefined' && device.platform === 'Android' ) {
                    $.mobile.defaultPageTransition = 'none';
                    FMS.isAndroid = true;
                    if ( parseInt(device.version) < 3 ) {
                        $('#help').addClass('android2');
                    }
                }

                if ( typeof device !== 'undefined' && device.platform === 'iOS' ) {
                    var model = parseInt(device.model.replace('iPhone',''), 10);
                    FMS.iPhoneModel = model;

                    // fix overlap of status bar in ios7
                    if (parseFloat(window.device.version) >= 7.0) {
                        $('body').addClass('ios7');
                    }
                }

                _.extend(FMS, {
                    router: new FMS.appRouter(),
                    locator: new FMS.Locate()
                });
                _.extend( FMS.locator, Backbone.Events );

                // we only ever have the details of one user
                FMS.users.fetch();
                if ( FMS.users.length > 0 ) {
                    FMS.currentUser = FMS.users.get(1);
                }
                if ( FMS.currentUser === null ) {
                    FMS.currentUser = new FMS.User({id: 1});
                }

                FMS.windowHeight = $(window).height();
                if ( $('body').hasClass('ios7') ) {
                    FMS.windowHeight -= 20;
                }

                if ( localStorage.usedBefore ) {
                    FMS.usedBefore = 1;
                }

                if ( CONFIG.TESTING ) {
                    FMS.testing = 1;
                }

                document.addEventListener('pause', function() { FMS.locator.stopTracking(); FMS.saveCurrentDraft(); }, false);
                document.addEventListener('resume', onResume, false);
                document.addEventListener('backbutton', function(e) { FMS.router.back(e); }, true);
                document.addEventListener('offline', function() { FMS.offline(); }, true);
                document.addEventListener('online', function() { FMS.online(); }, true);

                $(document).on('ajaxStart', function() { $.mobile.loading('show'); } );
                $(document).on('ajaxStop', function() { $.mobile.loading('hide'); } );

                $('#display-help').on('vclick', function(e) { FMS.helpShow(e); } );
                $('#dismiss').on('vclick', function(e) { FMS.helpHide(e); } );

                FMS.allDrafts.comparator = function(a,b) { var a_date = a.get('created'), b_date = b.get('created'); return a_date === b_date ? 0 : a_date < b_date ? 1 : -1; };
                FMS.allDrafts.fetch();
                FMS.checkOnlineStatus();
                FMS.loadCurrentDraft();
                FMS.checkLoggedInStatus();
                FMS.setupHelp();

                Backbone.history.start();
                navigator.splashscreen.hide();
                $('#display-help').show();
            });
        }
    });

    function onResume() {
        FMS.checkOnlineStatus();
        FMS.loadCurrentDraft();
        if ( ( FMS.router.currentView.id == 'front-page' || FMS.router.currentView.id == 'around-page' ) && FMS.currentPosition !== null ) {
            FMS.locator.trackPosition();
        }
    }
})(FMS, Backbone, _, $);

var androidStartUp = function() {
    // deviceready does not fire on some android versions very reliably so
    // we do this instead

    if (FMS.initialized === 1) {
        return;
    }

    if ( typeof device != 'undefined' ) {
        if ( device.platform == 'Android' ) {
            FMS.initialize();
        }
    } else {
        window.setTimeout( androidStartUp, 1000 );
    }
};

function onload() {
    document.addEventListener('deviceready', FMS.initialize, false);
    window.setTimeout( androidStartUp, 2000 );
}
<commit_msg>Allow cobrands to override templates<commit_after>var tpl = {

    // Hash of preloaded templates for the app
    templates:{},

    // Recursively pre-load all the templates for the app.
    // This implementation should be changed in a production environment. All the template files should be
    // concatenated in a single file.
    loadTemplates:function (names, callback) {

        var that = this;

        var loadTemplate = function (index) {
            var name = names[index];
            FMS.printDebug('Loading template: ' + name + ', index: ' + index);
            // Build a list of possible paths to the template, which will be tried in order.
            var template_paths = [
                'templates/' + CONFIG.LANGUAGE + '/' + name + '.html'
            ];
            // cobrands can override the base templates by creating the appropriate file in
            // /www/cobrands/<cobrand name>/templates/<language>, so put the cobranded template
            // path first in the list if we're using a cobrand.
            if (CONFIG.COBRAND) {
                template_paths.unshift('cobrands/' + CONFIG.COBRAND + '/templates/' + CONFIG.LANGUAGE + '/' + name + '.html');
            }
            // Fetch a template by loading it over AJAX.
            // Returns a jqXHR object so failures can be handed elsewhere
            var getTemplate = function(template_path) {
                FMS.printDebug("Fetching template: " + template_path);
                return $.get(template_path, function (data) {
                    FMS.printDebug("success!")
                    that.templates[name] = data;
                    index++;
                    if (index < names.length) {
                        loadTemplate(index);
                    } else {
                        callback();
                    }
                });
            };

            // Try to get the first template in template_paths, working down the list
            // in case of failure.
            var tryToGetTemplate = function() {
                getTemplate(template_paths[0])
                    .fail(function() {
                        template_paths.shift();
                        if (template_paths.length) {
                            tryToGetTemplate();
                        }
                    });
            }

            // Kick-off template loading for this template.
            tryToGetTemplate();
        };

        loadTemplate(0);
    },

    // Get template by name from hash of preloaded templates
    get:function (name) {
        return this.templates[name];
    }

};

(function (FMS, Backbone, _, $) {
    _.extend(FMS, {
        templates: [
            'home', 'help', 'initial_help', 'around', 'offline', 'save_offline', 'reports', 'login', 'address_search', 'existing', 'photo', 'details', 'details_extra', 'submit', 'submit_email', 'submit_name', 'submit_set_password', 'submit_password', 'submit_confirm', 'sent'
        ],

        usedBefore: 0,
        isLoggedIn: 0,
        isOffline: 0,
        initialized: 0,
        users: new FMS.Users(),
        currentUser: null,
        currentPosition: null,
        isAndroid: false,
        iPhoneModel: 0,
        uploadTimeout: CONFIG.UPLOAD_TIMEOUT || 120000,
        testing: 0,

        currentDraft: new FMS.Draft(),
        allDrafts: new FMS.Drafts(),

        reportToView: null,

        online: function() {
            FMS.isOffline = 0;
        },

        offline: function() {
            FMS.isOffline = 1;
        },

        printDebug: function(msg) {
            if ( CONFIG.DEBUG ) {
                console.log(msg);
            }
        },

        checkOnlineStatus: function() {
            if ( navigator && navigator.connection && ( navigator.connection.type == Connection.NONE ||
                    navigator.connection.type == Connection.UNKNOWN ) ) {
                FMS.offline();
            } else {
                FMS.online();
            }
        },

        checkLoggedInStatus: function() {
            if ( FMS.isOffline ) {
            } else {
                $.ajax( {
                    url: CONFIG.FMS_URL + '/auth/ajax/check_auth',
                    type: 'GET',
                    dataType: 'json',
                    timeout: 30000,
                    success: function( data, status ) {
                        FMS.isLoggedIn = 1;
                    },
                    error: function() {
                        FMS.isLoggedIn = 0;
                    }
                } );
            }
        },

        saveCurrentDraft: function(force) {
            FMS.router.pause();
            if ( force || FMS.currentDraft.isPartial() ) {
                FMS.allDrafts.add( FMS.currentDraft );
                FMS.currentDraft.save();
                localStorage.currentDraftID = FMS.currentDraft.id;
            }
        },

        loadCurrentDraft: function() {
            if ( localStorage.currentDraftID && localStorage.currentDraftID != 'null' ) {
                var r = FMS.allDrafts.get( localStorage.currentDraftID );
                if ( r ) {
                    FMS.currentDraft = r;
                }
            }
            localStorage.currentDraftID = null;
        },

        removeDraft: function(draftID, removePhoto) {
            var draft = FMS.allDrafts.get(draftID);
            var uri = draft.get('file');
            FMS.allDrafts.remove(draft);
            draft.destroy();

            if ( removePhoto && uri ) {
                return FMS.files.deleteURI( uri );
            }
            var p = $.Deferred();
            p.resolve();
            return p;
        },

        setCurrentDraft: function(draft) {
            FMS.currentDraft = draft;
            localStorage.currentDraftID = draft.id;
        },

        clearCurrentDraft: function() {
            FMS.currentDraft = new FMS.Draft();
            localStorage.currentDraftID = null;
        },

        openExternal: function(e) {
            e.preventDefault();
            var href = $(e.srcElement).attr('href');
            FMS.openExternalURL(href);
            return false;
        },

        openExternalURL: function(url) {
            window.cordova.InAppBrowser.open(url, '_system');
        },

        setHelpHeight: function() {
            var helpContent = $('#helpContent'),
            viewHeight = $(window).height();

            helpContent.height(viewHeight - 60);
        },

        setupHelp: function() {
            var help = $('#help'),
            helpContent = $('#helpContent'),
            viewWidth = $(window).width();

            var template;
            if ( !FMS.usedBefore ) {
                template = _.template( tpl.get('initial_help') );
            } else {
                template = _.template( tpl.get('help') );
            }
            helpContent.html(template());

            if ( !help.hasClass('android2') ) {
                if ( FMS.usedBefore ) {
                    FMS.setHelpHeight();
                }
                help.show();
            }
            help.css('left', viewWidth);
        },

        helpShow: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help');
            $('#display-help').hide();
            var onShow = function() {
                $('#help').show();
                $('#dismiss').show();
            };
            help.animate({left: 0}, onShow );
        },

        helpHide: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help'),
            viewWidth = $(window).width();

            $('#dismiss').hide();
            if ( help.hasClass('android2') ) {
                $('body').scrollTop(0);
            }
            var onHide = function() {
                $('#display-help').show();
                $('#helpContent').scrollTop(0);
                if ( $('#help').hasClass('android2') ) {
                    $('#help').hide();
                }
                if ( !FMS.usedBefore ) {
                    var template = _.template( tpl.get('help') );
                    $('#helpContent').html(template());
                    FMS.usedBefore = 1;
                    localStorage.usedBefore = 1;
                    if ( !$('#help').hasClass('android2') ) {
                        FMS.setHelpHeight();
                    }
                }
            };
            help.animate({left: viewWidth}, 400, 'swing', onHide );
        },

        initialize: function () {
            if ( this.initialized == 1 ) {
                return this;
            }
            $('#load-screen').height( $(window).height() );
            FMS.initialized = 1;
            if ( navigator && navigator.splashscreen ) {
                navigator.splashscreen.hide();
            }
            tpl.loadTemplates( FMS.templates, function() {

                if ( typeof device !== 'undefined' && device.platform === 'Android' ) {
                    $.mobile.defaultPageTransition = 'none';
                    FMS.isAndroid = true;
                    if ( parseInt(device.version) < 3 ) {
                        $('#help').addClass('android2');
                    }
                }

                if ( typeof device !== 'undefined' && device.platform === 'iOS' ) {
                    var model = parseInt(device.model.replace('iPhone',''), 10);
                    FMS.iPhoneModel = model;

                    // fix overlap of status bar in ios7
                    if (parseFloat(window.device.version) >= 7.0) {
                        $('body').addClass('ios7');
                    }
                }

                _.extend(FMS, {
                    router: new FMS.appRouter(),
                    locator: new FMS.Locate()
                });
                _.extend( FMS.locator, Backbone.Events );

                // we only ever have the details of one user
                FMS.users.fetch();
                if ( FMS.users.length > 0 ) {
                    FMS.currentUser = FMS.users.get(1);
                }
                if ( FMS.currentUser === null ) {
                    FMS.currentUser = new FMS.User({id: 1});
                }

                FMS.windowHeight = $(window).height();
                if ( $('body').hasClass('ios7') ) {
                    FMS.windowHeight -= 20;
                }

                if ( localStorage.usedBefore ) {
                    FMS.usedBefore = 1;
                }

                if ( CONFIG.TESTING ) {
                    FMS.testing = 1;
                }

                document.addEventListener('pause', function() { FMS.locator.stopTracking(); FMS.saveCurrentDraft(); }, false);
                document.addEventListener('resume', onResume, false);
                document.addEventListener('backbutton', function(e) { FMS.router.back(e); }, true);
                document.addEventListener('offline', function() { FMS.offline(); }, true);
                document.addEventListener('online', function() { FMS.online(); }, true);

                $(document).on('ajaxStart', function() { $.mobile.loading('show'); } );
                $(document).on('ajaxStop', function() { $.mobile.loading('hide'); } );

                $('#display-help').on('vclick', function(e) { FMS.helpShow(e); } );
                $('#dismiss').on('vclick', function(e) { FMS.helpHide(e); } );

                FMS.allDrafts.comparator = function(a,b) { var a_date = a.get('created'), b_date = b.get('created'); return a_date === b_date ? 0 : a_date < b_date ? 1 : -1; };
                FMS.allDrafts.fetch();
                FMS.checkOnlineStatus();
                FMS.loadCurrentDraft();
                FMS.checkLoggedInStatus();
                FMS.setupHelp();

                Backbone.history.start();
                navigator.splashscreen.hide();
                $('#display-help').show();
            });
        }
    });

    function onResume() {
        FMS.checkOnlineStatus();
        FMS.loadCurrentDraft();
        if ( ( FMS.router.currentView.id == 'front-page' || FMS.router.currentView.id == 'around-page' ) && FMS.currentPosition !== null ) {
            FMS.locator.trackPosition();
        }
    }
})(FMS, Backbone, _, $);

var androidStartUp = function() {
    // deviceready does not fire on some android versions very reliably so
    // we do this instead

    if (FMS.initialized === 1) {
        return;
    }

    if ( typeof device != 'undefined' ) {
        if ( device.platform == 'Android' ) {
            FMS.initialize();
        }
    } else {
        window.setTimeout( androidStartUp, 1000 );
    }
};

function onload() {
    document.addEventListener('deviceready', FMS.initialize, false);
    window.setTimeout( androidStartUp, 2000 );
}
<|endoftext|>


<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#{1}/gm, regex: /\#{1}.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(.*?)\*{2}/gm},
    'italic': {pattern: /\*{1}/gm, regex: /\*{1}(.*?)\*{1}/gm},
    'underline': {pattern: /\.\.{1,}/gm, regex: /\.\.{1,}(.*?)\.\.{1,}/gm},
    'strike': {pattern: /\~{1,}/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\={1,}/gm, regex: /\={1,}(?!\")(.*?)\={1,}/gm},
    'superscript': {pattern: /\^{2}/gm, regex: /\^{2}(.*?)\^{2}/gm},
    'subscript': {pattern: /\^{1}/gm, regex: /\^{1}(.*?)\^{1}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /^\-{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /^\.{4,}/gm}
  };
  var block = {
    'pre-extra': {pattern: /[]/gm, regex: /^\[(.*?)\|(.*?)\]\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote-extra': {pattern: /[]/gm, regex: /^\[(.*?)\]\`{2}([\s\S]*?)\`{2}/gm},
    'pre': {pattern: /\`{3,}/gm, regex: /^\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote': {pattern: /\`{2}/gm, regex: /^\`{2}([\s\S]*?)\`{2}/gm},
    'code': {pattern: /\`{1}/gm, regex: /\`{1}(.*?)\`{1}/gm}
  };
  var list = {
    'unordered': {pattern: /\-{1}/gm, regex: /(^\-{1}(?!\-{3,}).+\n){1,}/gm},
    'ordered': {pattern: /\d{1,}\./gm, regex: /(^\d{1,}\..+\n){1,}/gm},
    'checklist': {pattern: /[]/gm, regex: /(^\[[Xx]?\].+\n){1,}/gm}
  };
  var link = {
    'url-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)/gm},
    'url': {pattern: /[]/gm, regex: /\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/
  function FixPre(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  }

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Block=============================
  ============================================================*/
  exports.Block = function(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        if (key == 'pre-extra') {
          var extra = exports.Prepare(match).split(']```'),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split('```')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = 'language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = 'data-language="' + language + '"';
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          exports.service = service;
          return '
' + second + '
';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']``'),
            credit = extra[0].split('[')[1],
            quote = extra[1].split('``')[0];
          return '' + exports.Trim(quote) + '' + exports.Trim(credit) + '';
        } else {
          var temp = exports.Prepare(match).replace(block[key].pattern, ''),
            classes = 'nohighlight language-none';
          if (key == 'pre') {
            return '
' + temp + '
';
          } else if (key == 'quote') {
            return '' + exports.Trim(temp) + '';
          } else {
            return '' + exports.Trim(temp) + '';
          }
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'unordered' || key == 'ordered') {
          var tag = key == 'unordered' ? 'ul' : 'ol';
          return '<' + tag + ' class="' + prefix + key + '">' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '</' + tag + '>';
        } else {
          return '' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[\]/gm, ''),
              tag = (new RegExp('\[\]', 'gm')).test(line) ? 'unchecked' : 'checked' ;
            return '' + exports.Trim(temp) + '';
          }) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url-extra') {
          var extra = exports.Prepare(match).split(']('),
            title = extra[0].split('[')[1],
            url = extra[1].split(']')[0];
          return '' + exports.Trim(title) + '';
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    switch (exports.service) {
      case 'prism':
        break;
      case 'highlight':
        break;
      case 'shjs':
        break;
      case 'rainbow':
        break;
      case 'prettify':
        prettyPrint();
        break;
      default:
        break;
    }
    FixPre(elements);
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<commit_msg>Update extension.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#{1}/gm, regex: /\#{1}.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(.*?)\*{2}/gm},
    'italic': {pattern: /\*{1}/gm, regex: /\*{1}(.*?)\*{1}/gm},
    'underline': {pattern: /\.\.{1,}/gm, regex: /\.\.{1,}(.*?)\.\.{1,}/gm},
    'strike': {pattern: /\~{1,}/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\={1,}/gm, regex: /\={1,}(?!\")(.*?)\={1,}/gm},
    'superscript': {pattern: /\^{2}/gm, regex: /\^{2}(.*?)\^{2}/gm},
    'subscript': {pattern: /\^{1}/gm, regex: /\^{1}(.*?)\^{1}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /^\-{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /^\.{4,}/gm}
  };
  var block = {
    'pre-extra': {pattern: /[]/gm, regex: /^\[(.*?)\|(.*?)\]\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote-extra': {pattern: /[]/gm, regex: /^\[(.*?)\]\`{2}([\s\S]*?)\`{2}/gm},
    'pre': {pattern: /\`{3,}/gm, regex: /^\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote': {pattern: /\`{2}/gm, regex: /^\`{2}([\s\S]*?)\`{2}/gm},
    'code': {pattern: /\`{1}/gm, regex: /\`{1}(.*?)\`{1}/gm}
  };
  var list = {
    'unordered': {pattern: /\-{1}/gm, regex: /(^\-{1}(?!\-{3,}).+\n){1,}/gm},
    'ordered': {pattern: /\d{1,}\./gm, regex: /(^\d{1,}\..+\n){1,}/gm},
    'checklist': {pattern: /[]/gm, regex: /(^\[[Xx]?\].+\n){1,}/gm}
  };
  var link = {
    'url-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)/gm},
    'url': {pattern: /[]/gm, regex: /\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/
  function FixPre(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  }

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Block=============================
  ============================================================*/
  exports.Block = function(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        if (key == 'pre-extra') {
          var extra = exports.Prepare(match).split(']```'),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split('```')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = 'language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = 'data-language="' + language + '"';
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          exports.service = service;
          return '
' + second + '
';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']``'),
            credit = extra[0].split('[')[1],
            quote = extra[1].split('``')[0];
          return '' + exports.Trim(quote) + '' + exports.Trim(credit) + '';
        } else {
          var temp = exports.Prepare(match).replace(block[key].pattern, ''),
            classes = 'nohighlight language-none';
          if (key == 'pre') {
            return '
' + temp + '
';
          } else if (key == 'quote') {
            return '' + exports.Trim(temp) + '';
          } else {
            return '' + exports.Trim(temp) + '';
          }
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'unordered' || key == 'ordered') {
          var tag = key == 'unordered' ? 'ul' : 'ol';
          return '<' + tag + ' class="' + prefix + key + '">' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '</' + tag + '>';
        } else {
          return '' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx]?\]/gm, ''),
              tag = (new RegExp('\[\]', 'gm')).test(line) ? 'unchecked' : 'checked' ;
            return '' + exports.Trim(temp) + '';
          }) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url-extra') {
          var extra = exports.Prepare(match).split(']('),
            title = extra[0].split('[')[1],
            url = extra[1].split(']')[0];
          return '' + exports.Trim(title) + '';
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };
  exports.FixNewLine = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        content = element.innerHTML,
        fixed = content.replace(/\
/gm, '');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    switch (exports.service) {
      case 'prism':
        break;
      case 'highlight':
        hljs.initHighlighting();
        break;
      case 'shjs':
        sh_highlightDocument();
        break;
      case 'rainbow':
        Rainbow.color();
        break;
      case 'prettify':
        prettyPrint();
        break;
      default:
        break;
    }
    FixPre(elements);
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<|endoftext|>


<commit_before>"use strict";

angular.module('myApp', ['ionic','ngCordova','myApp.controllers'])

.run(function($ionicPlatform) {
//  $ionicPlatform.ready(function() {
//    if(window.cordova && window.cordova.plugins.Keyboard) {
//      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
//    }
//    if(window.StatusBar) {
//      StatusBar.styleDefault();
//    }
//  });
})
;

<commit_msg>Update app.js<commit_after>"use strict";

angular.module('myApp', ['ionic','ngCordova','myApp.controllers'])

.run(function($ionicPlatform) {
   $cordovaStatusbar.overlaysWebView(true);
//  $ionicPlatform.ready(function() {
//    if(window.cordova && window.cordova.plugins.Keyboard) {
//      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
//    }
//    if(window.StatusBar) {
//      StatusBar.styleDefault();
//    }
//  });
})
;

<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below

var VsCode = require('vscode');
var Window = VsCode.window;
var commands = VsCode.commands;
var workspace = VsCode.workspace;
var Position = VsCode.Position;

var path = require('path');
var fs = require('fs');
var git = require('parse-git-config');
var open = require('open');
var copy = require('copy-paste').copy;
var gitRev = require('git-rev-2');
var findParentDir = require('find-parent-dir');

const gitProvider = require('./gitProvider');
const requireSelectionForLines = workspace.getConfiguration('openInGitHub').get('requireSelectionForLines');

function getGitProviderLink(cb, fileFsPath, lines, pr) {
    var cwd = workspace.rootPath;
    var repoDir = findParentDir.sync(workspace.rootPath, '.git') || cwd;

    git({
        cwd: repoDir
    }, function (err, config) {
        const rawUri = config['remote \"origin\"'].url;
        var provider = null;

        try {
            provider = gitProvider(rawUri);
        } catch (e) {
            let errmsg = e.toString();
            Window.showWarningMessage(`Unknown Git provider. ${errmsg}`);
            return;
        }

        gitRev.branch(cwd, function (branchErr, branch) {
            if (branchErr || !branch)
                branch = 'master';

            let subdir = fileFsPath ? fileFsPath.substring(workspace.rootPath.length).replace(/\"/g, "") : undefined;

            if (repoDir !== cwd) {
                // The workspace directory is a subdirectory of the git repo folder so we need to prepend the the nested path
                var repoRelativePath = cwd.replace(repoDir, "/");
                subdir = repoRelativePath + subdir;
            }

            if (pr){
                try {
                    cb(provider.prUrl(branch));
                }catch (e){
                    Window.showWarningMessage(e.toString());
                    return;
                }
            }
            else {
                if (lines) {
                    if (lines[0] == lines[1]) {
                        cb(provider.webUrl(branch, subdir, lines[0]));
                    }
                    else {
                        cb(provider.webUrl(branch, subdir, lines[0], lines[1]));
                    }
                }
                else {
                    cb(provider.webUrl(branch, subdir));
                }
            }
        });
    });
}

function getGitProviderLinkForFile(fileFsPath, cb) {
    getGitProviderLink(cb, fileFsPath);
}

function getGitProviderLinkForCurrentEditorLines(cb) {
    var editor = Window.activeTextEditor;
    if (editor) {
        var fileFsPath = editor.document.uri.fsPath;

        if (includeLines(editor)) {
            getGitProviderLink(cb, fileFsPath, getSelectedLines(editor));
        }
        else {
            getGitProviderLinkForFile(fileFsPath, cb);
        }
    }
}

function includeLines(editor) {
    return !requireSelectionForLines || !editor.selection.isEmpty;
}

function getSelectedLines(editor) {
    var anchorLineIndex = editor.selection.anchor.line + 1;
    var activeLineIndex = editor.selection.active.line + 1;

    return [anchorLineIndex, activeLineIndex].sort();
}

function getGitProviderLinkForRepo(cb) {
    getGitProviderLink(cb);
}

function getGitProviderPullRequest(cb) {
    getGitProviderLink(cb, undefined, undefined, true);
}

function branchOnCallingContext(args, cb, pr) {
    if (pr) {
        getGitProviderPullRequest(cb);
    }
    else if (args && args.fsPath) {
        getGitProviderLinkForFile(args.fsPath, cb);
    }
    else if (Window.activeTextEditor) {
        getGitProviderLinkForCurrentEditorLines(cb);
    }
    else {
        getGitProviderLinkForRepo(cb);
    }
}

function openInGitProvider(args) {
    branchOnCallingContext(args, open);
}

function copyGitProviderLinkToClipboard(args) {
    branchOnCallingContext(args, copy);
}

function openPrGitProvider(args) {
    branchOnCallingContext(args, open, true);
}

//TODO: rename openInGitHub to openInGitProvider
function activate(context) {
    context.subscriptions.push(commands.registerCommand('extension.openInGitHub', openInGitProvider));
    context.subscriptions.push(commands.registerCommand('extension.copyGitHubLinkToClipboard', copyGitProviderLinkToClipboard));
    context.subscriptions.push(commands.registerCommand('extension.openPrGitProvider', openPrGitProvider));
}

exports.activate = activate;
<commit_msg>Adds dynamic remote selection based on branch #64 (#66)<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below

var VsCode = require('vscode');
var Window = VsCode.window;
var commands = VsCode.commands;
var workspace = VsCode.workspace;
var Position = VsCode.Position;

var path = require('path');
var fs = require('fs');
var git = require('parse-git-config');
var open = require('open');
var copy = require('copy-paste').copy;
var gitRev = require('git-rev-2');
var findParentDir = require('find-parent-dir');

const gitProvider = require('./gitProvider');
const requireSelectionForLines = workspace.getConfiguration('openInGitHub').get('requireSelectionForLines');

function getGitProviderLink(cb, fileFsPath, lines, pr) {
    var cwd = workspace.rootPath;
    var repoDir = findParentDir.sync(workspace.rootPath, '.git') || cwd;

    git({
        cwd: repoDir
    }, function (err, config) {

        gitRev.branch(cwd, function(branchErr, branch) {
            var rawUri,
                configuredBranch,
                provider = null,
                remoteName;

            if (branchErr || !branch) branch = 'master';

            // Check to see if the branch has a configured remote
            configuredBranch = config[`branch "${branch}"`];

            if (!configuredBranch) {
                Window.showWarningMessage(`No remote found on branch.`);
                return;
            }

            // Use the current branch's configured remote
            remoteName = configuredBranch.remote;
            rawUri = config[`remote "${remoteName}"`].url;

            try {
                provider = gitProvider(rawUri);
            } catch (e) {
                let errmsg = e.toString();
                Window.showWarningMessage(`Unknown Git provider. ${errmsg}`);
                return;
            }

            let subdir = fileFsPath ? fileFsPath.substring(workspace.rootPath.length).replace(/\"/g, "") : undefined;

            if (repoDir !== cwd) {
                // The workspace directory is a subdirectory of the git repo folder so we need to prepend the the nested path
                var repoRelativePath = cwd.replace(repoDir, "/");
                subdir = repoRelativePath + subdir;
            }

            if (pr){
                try {
                    cb(provider.prUrl(branch));
                }catch (e){
                    Window.showWarningMessage(e.toString());
                    return;
                }
            }
            else {
                if (lines) {
                    if (lines[0] == lines[1]) {
                        cb(provider.webUrl(branch, subdir, lines[0]));
                    }
                    else {
                        cb(provider.webUrl(branch, subdir, lines[0], lines[1]));
                    }
                }
                else {
                    cb(provider.webUrl(branch, subdir));
                }
            }
        });
    });
}

function getGitProviderLinkForFile(fileFsPath, cb) {
    getGitProviderLink(cb, fileFsPath);
}

function getGitProviderLinkForCurrentEditorLines(cb) {
    var editor = Window.activeTextEditor;
    if (editor) {
        var fileFsPath = editor.document.uri.fsPath;

        if (includeLines(editor)) {
            getGitProviderLink(cb, fileFsPath, getSelectedLines(editor));
        }
        else {
            getGitProviderLinkForFile(fileFsPath, cb);
        }
    }
}

function includeLines(editor) {
    return !requireSelectionForLines || !editor.selection.isEmpty;
}

function getSelectedLines(editor) {
    var anchorLineIndex = editor.selection.anchor.line + 1;
    var activeLineIndex = editor.selection.active.line + 1;

    return [anchorLineIndex, activeLineIndex].sort();
}

function getGitProviderLinkForRepo(cb) {
    getGitProviderLink(cb);
}

function getGitProviderPullRequest(cb) {
    getGitProviderLink(cb, undefined, undefined, true);
}

function branchOnCallingContext(args, cb, pr) {
    if (pr) {
        getGitProviderPullRequest(cb);
    }
    else if (args && args.fsPath) {
        getGitProviderLinkForFile(args.fsPath, cb);
    }
    else if (Window.activeTextEditor) {
        getGitProviderLinkForCurrentEditorLines(cb);
    }
    else {
        getGitProviderLinkForRepo(cb);
    }
}

function openInGitProvider(args) {
    branchOnCallingContext(args, open);
}

function copyGitProviderLinkToClipboard(args) {
    branchOnCallingContext(args, copy);
}

function openPrGitProvider(args) {
    branchOnCallingContext(args, open, true);
}

//TODO: rename openInGitHub to openInGitProvider
function activate(context) {
    context.subscriptions.push(commands.registerCommand('extension.openInGitHub', openInGitProvider));
    context.subscriptions.push(commands.registerCommand('extension.copyGitHubLinkToClipboard', copyGitProviderLinkToClipboard));
    context.subscriptions.push(commands.registerCommand('extension.openPrGitProvider', openPrGitProvider));
}

exports.activate = activate;
<|endoftext|>


<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#/gm, regex: /\#.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(?!\*{2,})(.*?)\*{2}/gm},
    'italic': {pattern: /\*/gm, regex: /\*(?!\*{3,})(.*?)\*/gm},
    'underline': {pattern: /\_/gm, regex: /\_{2}(?!\_{2,})(.*?)\_{2}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{2}(?!\~{2,})(.*?)\~{2}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={2}(?!\={2,})(.*?)\={2}/gm},
    'superscript': {pattern: /\+/gm, regex: /\+{2}(?!\+{2,})(.*?)\+{2}/gm},
    'subscript': {pattern: /\-/gm, regex: /\-{2}(?!\-{2,})(.*?)\-{2}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /\_{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /\-{4,}/gm},
    'rule-dotted': {pattern: /[]/gm, regex: /\.{4,}/gm},
    'rule-double': {pattern: /[]/gm, regex: /\={4,}/gm},
    'rule-thick': {pattern: /[]/gm, regex: /\+{4,}/gm}
  };
  var quote = {
    'quote-code': {pattern: /\`/gm, regex: /\`(.*?)\`/gm},
    'quote-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\[([\s\S]*?)\]\}/gm},
    'quote-plain': {pattern: /(\{\[|\]\})/gm, regex: /\{\[([\s\S]*?)\]\}/gm}
  };
  var code = {
    'code-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\(([\s\S]*?)\)\}/gm},
    'code-plain': {pattern: /(\{\(|\)\})/gm, regex: /\{\(([\s\S]*?)\)\}/gm}
  };
  var list = {
    'list-disc': {pattern: /(\-)/gm, regex: /(^\-(?!\-{3,}).+\n){1,}/gm},
    'list-circle': {pattern: /(\*)/gm, regex: /(^\*(?!\*{3,}).+\n){1,}/gm},
    'list-square': {pattern: /(\@)/gm, regex: /(^\@(?!\@{3,}).+\n){1,}/gm},
    'list-decimal': {pattern: /(\o\.)/gm, regex: /(^\o\..+\n){1,}/igm},
    'list-roman': {pattern: /(\i\.)/gm, regex: /(^\i\..+\n){1,}/igm},
    'list-alpha': {pattern: /(\a\.)/gm, regex: /(^\a\..+\n){1,}/igm},
    'checklist': {pattern: /\[[Xx\s]?\]/gm, regex: /(^\[[Xx\s]?\].+\n){1,}/gm}
  };
  var link = {
    'url': {pattern: /[]/gm, regex: /(\!\[(.*?)\]\((.*?)\)|\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)|\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b)/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };
  var image = {
    'image': {pattern: /[]/gm, regex: /\!\[(.*?)\]\((.*?)\)/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        if (key == 'header1' || key == 'header2') {
          return '' + exports.Trim(temp) + '
';
        } else {
          return '' + exports.Trim(temp) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Quote=============================
  ============================================================*/
  exports.Quote = function(doc) {
    for (key in quote) {
      doc = doc.replace(quote[key].regex, function(match) {
        if (key == 'quote-code') {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key + ' nohighlight language-none';
          return '' + exports.Trim(temp) + '';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']{['),
            credit = extra[0].split('[')[1],
            content = extra[1].split(']}')[0],
            classes = prefix + key;
          return '
"' + exports.Trim(content) + '"
' + exports.Trim(credit) + '
';
        } else {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key;
          return '
"' + exports.Trim(temp) + '"
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Code==============================
  ============================================================*/
  exports.Code = function(doc) {
    for (key in code) {
      doc = doc.replace(code[key].regex, function(match) {
        if (key == 'code-extra') {
          var extra = exports.Prepare(match).split(']{('),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split(')}')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = prefix + key + ' language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = language;
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + second + '
';
        } else {
          var temp = exports.Prepare(match).replace(code[key].pattern, ''),
            classes = 'nohighlight language-none';
          return '
' + temp + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'list-disc' || key == 'list-circle' || key == 'list-square') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else if (key == 'list-decimal' || key == 'list-roman' || key == 'list-alpha') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx\s]?\]/gm, ''),
              tag = (new RegExp(/\[\s?\]/gm)).test(line) ? 'unchecked' : 'checked';
            return '' + exports.Trim(temp) + '
';
          }) + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url') {
          if ((new RegExp(/^\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)$/gm)).test(match)) {
            var extra = exports.Prepare(match).split(']('),
              title = extra[0].split('[')[1],
              url = extra[1].split(']')[0];
            return '' + exports.Trim(title) + '';
          } else if ((new RegExp(/^\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b$/gm)).test(match)) {
            return '' + exports.Trim(match) + '';
          }
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Image=============================
  ============================================================*/
  exports.Image = function(doc) {
    for (key in image) {
      doc = doc.replace(image[key].regex, function(match) {
        console.log(match);
        var extra = exports.Prepare(match).split(']('),
          alt = exports.Trim(extra[0].split('![')[1]).toLowerCase(),
          url = exports.Trim(extra[1].split(')')[0]).toLowerCase();
          console.log(extra);
          console.log(alt);
          console.log(url);
        return '';
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<commit_msg>Update extension.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#/gm, regex: /\#.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(?!\*{2,})(.*?)\*{2}/gm},
    'italic': {pattern: /\*/gm, regex: /\*(?!\*{3,})(.*?)\*/gm},
    'underline': {pattern: /\_/gm, regex: /\_{2}(?!\_{2,})(.*?)\_{2}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{2}(?!\~{2,})(.*?)\~{2}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={2}(?!\={2,})(.*?)\={2}/gm},
    'superscript': {pattern: /\+/gm, regex: /\+{2}(?!\+{2,})(.*?)\+{2}/gm},
    'subscript': {pattern: /\-/gm, regex: /\-{2}(?!\-{2,})(.*?)\-{2}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /\_{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /\-{4,}/gm},
    'rule-dotted': {pattern: /[]/gm, regex: /\.{4,}/gm},
    'rule-double': {pattern: /[]/gm, regex: /\={4,}/gm},
    'rule-thick': {pattern: /[]/gm, regex: /\+{4,}/gm}
  };
  var quote = {
    'quote-code': {pattern: /\`/gm, regex: /\`(.*?)\`/gm},
    'quote-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\[([\s\S]*?)\]\}/gm},
    'quote-plain': {pattern: /(\{\[|\]\})/gm, regex: /\{\[([\s\S]*?)\]\}/gm}
  };
  var code = {
    'code-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\(([\s\S]*?)\)\}/gm},
    'code-plain': {pattern: /(\{\(|\)\})/gm, regex: /\{\(([\s\S]*?)\)\}/gm}
  };
  var list = {
    'list-disc': {pattern: /(\-)/gm, regex: /(^\-(?!\-{3,}).+\n){1,}/gm},
    'list-circle': {pattern: /(\*)/gm, regex: /(^\*(?!\*{3,}).+\n){1,}/gm},
    'list-square': {pattern: /(\@)/gm, regex: /(^\@(?!\@{3,}).+\n){1,}/gm},
    'list-decimal': {pattern: /(\o\.)/gm, regex: /(^\o\..+\n){1,}/igm},
    'list-roman': {pattern: /(\i\.)/gm, regex: /(^\i\..+\n){1,}/igm},
    'list-alpha': {pattern: /(\a\.)/gm, regex: /(^\a\..+\n){1,}/igm},
    'checklist': {pattern: /\[[Xx\s]?\]/gm, regex: /(^\[[Xx\s]?\].+\n){1,}/gm}
  };
  var link = {
    'url': {pattern: /[]/gm, regex: /(\!\[(.*?)\]\((.*?)\)|\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)|\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b)/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };
  var image = {
    'image': {pattern: /[]/gm, regex: /\!\[(.*?)\]\((.*?)\)/gm}
  };
  var table = {
    'table': {pattern: /\>/gm, regex: /\{\|([\s\S]*?)\|\}/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        if (key == 'header1' || key == 'header2') {
          return '' + exports.Trim(temp) + '
';
        } else {
          return '' + exports.Trim(temp) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Quote=============================
  ============================================================*/
  exports.Quote = function(doc) {
    for (key in quote) {
      doc = doc.replace(quote[key].regex, function(match) {
        if (key == 'quote-code') {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key + ' nohighlight language-none';
          return '' + exports.Trim(temp) + '';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']{['),
            credit = extra[0].split('[')[1],
            content = extra[1].split(']}')[0],
            classes = prefix + key;
          return '
"' + exports.Trim(content) + '"
' + exports.Trim(credit) + '
';
        } else {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key;
          return '
"' + exports.Trim(temp) + '"
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Code==============================
  ============================================================*/
  exports.Code = function(doc) {
    for (key in code) {
      doc = doc.replace(code[key].regex, function(match) {
        if (key == 'code-extra') {
          var extra = exports.Prepare(match).split(']{('),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split(')}')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = prefix + key + ' language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = language;
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + second + '
';
        } else {
          var temp = exports.Prepare(match).replace(code[key].pattern, ''),
            classes = 'nohighlight language-none';
          return '
' + temp + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'list-disc' || key == 'list-circle' || key == 'list-square') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else if (key == 'list-decimal' || key == 'list-roman' || key == 'list-alpha') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx\s]?\]/gm, ''),
              tag = (new RegExp(/\[\s?\]/gm)).test(line) ? 'unchecked' : 'checked';
            return '' + exports.Trim(temp) + '
';
          }) + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url') {
          if ((new RegExp(/^\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)$/gm)).test(match)) {
            var extra = exports.Prepare(match).split(']('),
              title = extra[0].split('[')[1],
              url = extra[1].split(']')[0];
            return '' + exports.Trim(title) + '';
          } else if ((new RegExp(/^\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b$/gm)).test(match)) {
            return '' + exports.Trim(match) + '';
          }
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Image=============================
  ============================================================*/
  exports.Image = function(doc) {
    for (key in image) {
      doc = doc.replace(image[key].regex, function(match) {
        var extra = exports.Prepare(match).split(']('),
          alt = exports.Trim(extra[0].split('![')[1]).toLowerCase(),
          url = exports.Trim(extra[1].split(')')[0]).toLowerCase();
        return '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Table=============================
  ============================================================*/
  exports.Table = function(doc) {
    for (key in table) {
      doc = '

' + doc.replace(table[key].regex, function(match) {
        var extra = exports.Prepare(match).split('{|')[1].split('|}')[0],
          tBody = extra.split('||');
        for (var a = 0; a
\>/gm)).test(tRow)) {
            return '
' + tRow.replace(/.+\n/gm, function(row) {
              var temp = row.replace(table[key].pattern, '');
              return '' + exports.Trim(temp) + '	';
            }) + '
';
          } else {
            return '
' + tRow.replace(/.+\n/gm, function(row) {
              var temp = row.replace(table[key].pattern, '');
              return '' + exports.Trim(temp) + '	';
            }) + '
';
          }
        }
      }) + '

';
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<|endoftext|>