<commit_before>import fs from 'fs';
import path from 'path';
import $ from 'jquery';
import jsTest from '@jenkins-cd/js-test';
import { mockBehaviorShim } from './mocks';

const htmlConfigTabbedContent = fs.readFileSync(
    path.resolve(__dirname, './freestyle-config-tabbed.html'),
    'utf8'
);

function getConfigTabbar() {
    // eslint-disable-next-line no-undef
    return require('../../../../main/js/config-tabbar');
}

function getConfigTabbarWidget() {
    // eslint-disable-next-line no-undef
    return require('../../../../main/js/widgets/config/tabbar');
}

describe("tabbar-spec tests", function () {
    // Need to mock the utils/page module because we will hijack the scroll events
    const mockPageUtils = jest.requireActual('../../../../main/js/util/page');

    beforeEach(() => {
        mockBehaviorShim();

        jest.mock('../../../../main/js/util/page', () => ({
            __esModule: true,
            ...mockPageUtils,
            default: {
                ...mockPageUtils.default,
                fireBottomStickerAdjustEvent: jest.fn(),
            }
        }));
    });

    afterEach(() => {
        jest.resetAllMocks()
    });

    afterAll(() => {
        // Should call resetModules on afterAll because the test "test section activation"
        // will break if resetModules is called on afterEach.
        jest.resetModules();
    });

    it("- test section count", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var tabbars = getConfigTabbar();
            var firstTableMetadata = tabbars.tabs[0];

            expect(firstTableMetadata.configTable.find('.section-header-row').length).toBe(4);
            expect(firstTableMetadata.sectionCount()).toBe(4);
            expect($('.tabBar .tab').size()).toBe(4);

            expect(firstTableMetadata.sectionIds()).toEqual([
                'config_general',
                'config__advanced_project_options',
                'config__build_triggers',
                'config__build'
            ])

            done();
        }, htmlConfigTabbedContent);
    });

    // This test may be deterministic, as it breaks if jest.resetModules is called on afterEach
    it("- test section activation", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var tabbars = getConfigTabbar();
            var firstTableMetadata = tabbars.tabs[0];

            // The first section ("General") should be active by default
            expect(firstTableMetadata.activeSection().id).toBe('config_general');
            expect(firstTableMetadata.activeSectionCount()).toBe(1);

            firstTableMetadata.onShowSection(function() {
                expect(this.id).toBe('config__build');

                expect(firstTableMetadata.activeSectionCount()).toBe(1);
                var activeSection = firstTableMetadata.activeSection();
                expect(activeSection.id).toBe('config__build');
                expect(activeSection.activeRowCount()).toBe(2);
                expect(firstTableMetadata.getTopRows().filter('.active').size()).toBe(1); // should be activeSection.activeRowCount() - 1

                done();
            });

            // Mimic the user clicking on one of the tabs. Should make that section active,
            // with all of the rows in that section having an "active" class.
            firstTableMetadata.activateSection('config__build');
            // above 'firstTableMetadata.onShowSection' handler should get called now

        }, htmlConfigTabbedContent);
    });

    it("- test row-group modeling", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBar = getConfigTabbarWidget();
            var firstTableMetadata = configTabBar.addTabsOnFirst();

            var generalSection = firstTableMetadata.activeSection();
            expect(generalSection.id).toBe('config_general');

            var sectionRowGroups = generalSection.rowGroups;

            expect(sectionRowGroups.length).toBe(1);
            expect(sectionRowGroups[0].getRowCount(false)).toBe(0); // zero because it does not have any non row-group rows nested immediately inside i.e. does not have any "normal" rows
            expect(sectionRowGroups[0].getRowCount(true)).toBe(4); // there are some nested down in the children. see below
            expect(sectionRowGroups[0].rowGroups.length).toBe(1);
            expect(sectionRowGroups[0].rowGroups[0].getRowCount(false)).toBe(4); // The inner grouping has rows
            expect(sectionRowGroups[0].rowGroups[0].getRowCount()).toBe(4); // Same as above ... just making sure they're direct child rows and not nested below
            expect(generalSection.getRowGroupLabels().toString()).toBe('Discard Old Builds');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test finder - via handler triggering", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            // All tabs should be visible...
            expect($('.tab', tabBar).size()).toBe(4);
            expect($('.tab.hidden', tabBar).size()).toBe(0);

            var finder = configTabBar.findInput;
            expect(finder.size()).toBe(1);

            // Find sections that have the text "trigger" in them...
            keydowns('trigger', finder);

            // Need to wait for the change to happen ... there's a 300ms delay.
            // We could just call configTabBar.showSections(), but ...
            setTimeout(function() {
                expect($('.tab.hidden', tabBar).size()).toBe(3);
                expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('General|#Advanced Project Options|#Build');

                var activeSection = configTabBar.activeSection();
                expect(textCleanup(activeSection.title)).toBe('#Build Triggers');

                expect($('.highlight-split .highlight').text()).toBe('Trigger');

                done();
            }, 600);
        }, htmlConfigTabbedContent);
    });

    it("- test finder - via showSections()", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            configTabBar.showSections('quiet period');
            expect($('.tab.hidden', tabBar).size()).toBe(3);
            expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('General|#Build Triggers|#Build');

            var activeSection = configTabBar.activeSection();
            expect(textCleanup(activeSection.title)).toBe('#Advanced Project Options');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test finder - via showSections() - in inner row-group", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            configTabBar.showSections('Strategy');
            expect($('.tab.hidden', tabBar).size()).toBe(3);
            expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('#Advanced Project Options|#Build Triggers|#Build');

            var activeSection = configTabBar.activeSection();
            expect(textCleanup(activeSection.title)).toBe('General');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test adopt sections ", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            // Move the advanced stuff into the general section
            var general = configTabBar.getSection('config_general');
            general.adoptSection('config__advanced_project_options');

            // Only 3 tabs should be visible
            // (used to be 4 before the merge/adopt)...
            expect($('.tab', tabBar).size()).toBe(3);
            expect(textCleanup($('.tab', tabBar).text())).toBe('General|#Build Triggers|#Build');

            // And if we try to use the finder now to find something
            // that was in the advanced section, it should now appear in the
            // General section ...
            configTabBar.showSections('quiet period');
            expect($('.tab.hidden', tabBar).size()).toBe(2);
            expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('#Build Triggers|#Build');

            var activeSection = configTabBar.activeSection();
            expect(textCleanup(activeSection.title)).toBe('General');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test getSibling ", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();

            // console.log('**** ' + configTabBar.sectionIds());
            // config_general,config__advanced_project_options,config__build_triggers,config__build

            var config_general = configTabBar.getSection('config_general');
            var config__advanced_project_options = configTabBar.getSection('config__advanced_project_options');
            var config__build_triggers = configTabBar.getSection('config__build_triggers');
            var config__build = configTabBar.getSection('config__build');

            expect(config_general.getSibling(-1)).toBeUndefined();
            expect(config_general.getSibling(0)).toBe(config_general);
            expect(config_general.getSibling(+1)).toBe(config__advanced_project_options);
            expect(config_general.getSibling(+2)).toBe(config__build_triggers);
            expect(config_general.getSibling(+3)).toBe(config__build);
            expect(config_general.getSibling(+4)).toBeUndefined();

            expect(config__advanced_project_options.getSibling(-2)).toBeUndefined();
            expect(config__advanced_project_options.getSibling(-1)).toBe(config_general);
            expect(config__advanced_project_options.getSibling(0)).toBe(config__advanced_project_options);
            expect(config__advanced_project_options.getSibling(+1)).toBe(config__build_triggers);
            expect(config__advanced_project_options.getSibling(+2)).toBe(config__build);
            expect(config__advanced_project_options.getSibling(+3)).toBeUndefined();

            done();
        }, htmlConfigTabbedContent);
    });

    function keydowns(text, onInput) {
        // hmmm, for some reason, the key events do not result in the text being
        // set in the input, so setting it manually.
        onInput.val(text);

        // Now fire a keydown event to trigger the handler
        var e = $.Event("keydown");
        e.which = 116;
        onInput.trigger(e);
    }

    function textCleanup(text) {
        return text.trim().replace(/(\r\n|\n|\r)/gm, "").replace(/  +/g, "|");
    }
});<commit_msg>Update war/src/test/js/widgets/config/tabbar.spec.js<commit_after>import fs from 'fs';
import path from 'path';
import $ from 'jquery';
import jsTest from '@jenkins-cd/js-test';
import { mockBehaviorShim } from './mocks';

const htmlConfigTabbedContent = fs.readFileSync(
    path.resolve(__dirname, './freestyle-config-tabbed.html'),
    'utf8'
);

function getConfigTabbar() {
    // eslint-disable-next-line no-undef
    return require('../../../../main/js/config-tabbar');
}

function getConfigTabbarWidget() {
    // eslint-disable-next-line no-undef
    return require('../../../../main/js/widgets/config/tabbar');
}

describe("tabbar-spec tests", function () {
    // Need to mock the utils/page module because we will hijack the scroll events
    const mockPageUtils = jest.requireActual('../../../../main/js/util/page');

    beforeEach(() => {
        mockBehaviorShim();

        jest.mock('../../../../main/js/util/page', () => ({
            __esModule: true,
            ...mockPageUtils,
            default: {
                ...mockPageUtils.default,
                fireBottomStickerAdjustEvent: jest.fn(),
            }
        }));
    });

    afterEach(() => {
        jest.resetAllMocks()
    });

    afterAll(() => {
        // Should call resetModules on afterAll because the test "test section activation"
        // will break if resetModules is called on afterEach.
        jest.resetModules();
    });

    it("- test section count", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var tabbars = getConfigTabbar();
            var firstTableMetadata = tabbars.tabs[0];

            expect(firstTableMetadata.configTable.find('.section-header-row').length).toBe(4);
            expect(firstTableMetadata.sectionCount()).toBe(4);
            expect($('.tabBar .tab').size()).toBe(4);

            expect(firstTableMetadata.sectionIds()).toEqual([
                'config_general',
                'config__advanced_project_options',
                'config__build_triggers',
                'config__build'
            ])

            done();
        }, htmlConfigTabbedContent);
    });

    // This test may not be deterministic, as it breaks if jest.resetModules is called on afterEach
    it("- test section activation", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var tabbars = getConfigTabbar();
            var firstTableMetadata = tabbars.tabs[0];

            // The first section ("General") should be active by default
            expect(firstTableMetadata.activeSection().id).toBe('config_general');
            expect(firstTableMetadata.activeSectionCount()).toBe(1);

            firstTableMetadata.onShowSection(function() {
                expect(this.id).toBe('config__build');

                expect(firstTableMetadata.activeSectionCount()).toBe(1);
                var activeSection = firstTableMetadata.activeSection();
                expect(activeSection.id).toBe('config__build');
                expect(activeSection.activeRowCount()).toBe(2);
                expect(firstTableMetadata.getTopRows().filter('.active').size()).toBe(1); // should be activeSection.activeRowCount() - 1

                done();
            });

            // Mimic the user clicking on one of the tabs. Should make that section active,
            // with all of the rows in that section having an "active" class.
            firstTableMetadata.activateSection('config__build');
            // above 'firstTableMetadata.onShowSection' handler should get called now

        }, htmlConfigTabbedContent);
    });

    it("- test row-group modeling", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBar = getConfigTabbarWidget();
            var firstTableMetadata = configTabBar.addTabsOnFirst();

            var generalSection = firstTableMetadata.activeSection();
            expect(generalSection.id).toBe('config_general');

            var sectionRowGroups = generalSection.rowGroups;

            expect(sectionRowGroups.length).toBe(1);
            expect(sectionRowGroups[0].getRowCount(false)).toBe(0); // zero because it does not have any non row-group rows nested immediately inside i.e. does not have any "normal" rows
            expect(sectionRowGroups[0].getRowCount(true)).toBe(4); // there are some nested down in the children. see below
            expect(sectionRowGroups[0].rowGroups.length).toBe(1);
            expect(sectionRowGroups[0].rowGroups[0].getRowCount(false)).toBe(4); // The inner grouping has rows
            expect(sectionRowGroups[0].rowGroups[0].getRowCount()).toBe(4); // Same as above ... just making sure they're direct child rows and not nested below
            expect(generalSection.getRowGroupLabels().toString()).toBe('Discard Old Builds');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test finder - via handler triggering", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            // All tabs should be visible...
            expect($('.tab', tabBar).size()).toBe(4);
            expect($('.tab.hidden', tabBar).size()).toBe(0);

            var finder = configTabBar.findInput;
            expect(finder.size()).toBe(1);

            // Find sections that have the text "trigger" in them...
            keydowns('trigger', finder);

            // Need to wait for the change to happen ... there's a 300ms delay.
            // We could just call configTabBar.showSections(), but ...
            setTimeout(function() {
                expect($('.tab.hidden', tabBar).size()).toBe(3);
                expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('General|#Advanced Project Options|#Build');

                var activeSection = configTabBar.activeSection();
                expect(textCleanup(activeSection.title)).toBe('#Build Triggers');

                expect($('.highlight-split .highlight').text()).toBe('Trigger');

                done();
            }, 600);
        }, htmlConfigTabbedContent);
    });

    it("- test finder - via showSections()", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            configTabBar.showSections('quiet period');
            expect($('.tab.hidden', tabBar).size()).toBe(3);
            expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('General|#Build Triggers|#Build');

            var activeSection = configTabBar.activeSection();
            expect(textCleanup(activeSection.title)).toBe('#Advanced Project Options');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test finder - via showSections() - in inner row-group", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            configTabBar.showSections('Strategy');
            expect($('.tab.hidden', tabBar).size()).toBe(3);
            expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('#Advanced Project Options|#Build Triggers|#Build');

            var activeSection = configTabBar.activeSection();
            expect(textCleanup(activeSection.title)).toBe('General');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test adopt sections ", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();
            var tabBar = $('.tabBar');

            // Move the advanced stuff into the general section
            var general = configTabBar.getSection('config_general');
            general.adoptSection('config__advanced_project_options');

            // Only 3 tabs should be visible
            // (used to be 4 before the merge/adopt)...
            expect($('.tab', tabBar).size()).toBe(3);
            expect(textCleanup($('.tab', tabBar).text())).toBe('General|#Build Triggers|#Build');

            // And if we try to use the finder now to find something
            // that was in the advanced section, it should now appear in the
            // General section ...
            configTabBar.showSections('quiet period');
            expect($('.tab.hidden', tabBar).size()).toBe(2);
            expect(textCleanup($('.tab.hidden', tabBar).text())).toBe('#Build Triggers|#Build');

            var activeSection = configTabBar.activeSection();
            expect(textCleanup(activeSection.title)).toBe('General');

            done();
        }, htmlConfigTabbedContent);
    });

    it("- test getSibling ", function (done) {
        jsTest.onPage(function() {
            document.documentElement.innerHTML = htmlConfigTabbedContent;

            var configTabBarWidget = getConfigTabbarWidget();
            var configTabBar = configTabBarWidget.addTabsOnFirst();

            // console.log('**** ' + configTabBar.sectionIds());
            // config_general,config__advanced_project_options,config__build_triggers,config__build

            var config_general = configTabBar.getSection('config_general');
            var config__advanced_project_options = configTabBar.getSection('config__advanced_project_options');
            var config__build_triggers = configTabBar.getSection('config__build_triggers');
            var config__build = configTabBar.getSection('config__build');

            expect(config_general.getSibling(-1)).toBeUndefined();
            expect(config_general.getSibling(0)).toBe(config_general);
            expect(config_general.getSibling(+1)).toBe(config__advanced_project_options);
            expect(config_general.getSibling(+2)).toBe(config__build_triggers);
            expect(config_general.getSibling(+3)).toBe(config__build);
            expect(config_general.getSibling(+4)).toBeUndefined();

            expect(config__advanced_project_options.getSibling(-2)).toBeUndefined();
            expect(config__advanced_project_options.getSibling(-1)).toBe(config_general);
            expect(config__advanced_project_options.getSibling(0)).toBe(config__advanced_project_options);
            expect(config__advanced_project_options.getSibling(+1)).toBe(config__build_triggers);
            expect(config__advanced_project_options.getSibling(+2)).toBe(config__build);
            expect(config__advanced_project_options.getSibling(+3)).toBeUndefined();

            done();
        }, htmlConfigTabbedContent);
    });

    function keydowns(text, onInput) {
        // hmmm, for some reason, the key events do not result in the text being
        // set in the input, so setting it manually.
        onInput.val(text);

        // Now fire a keydown event to trigger the handler
        var e = $.Event("keydown");
        e.which = 116;
        onInput.trigger(e);
    }

    function textCleanup(text) {
        return text.trim().replace(/(\r\n|\n|\r)/gm, "").replace(/  +/g, "|");
    }
});
<|endoftext|>


<commit_before>(function () {

  var iorad = require('iorad.js');

  return {

    categoriesList: [],

    lastSectionsList: [],

    timeout: 0,

    lastCategoryId: 0,

    lastSectionId: 0,

    myDefaultLocale: '',

    SOLUTION_APP_LOCATION: 'nav_bar',

    TICKETING_APP_LOCATION_PATTERN: /ticket_sidebar$/,

    currentPluginType: '',

    addToHelpCenter: false,

    addToHelpCenterAsDraft: false,

    pluginTypes: {
      SOLUTION: 'zendeskapp_solutions', // this is a nav bar app that creates tutorials.
      TICKETING: 'zendeskapp_ticketing' // this is a ticket sidebar app that creates tutorials for existing and new tickets.
    },

    TICKET_COMMENT_MARKDOWN_FORMAT: '[%@](https:%@)',

    events: {
      'app.activated'                       : 'init',
      'pane.activated'                      : 'runSolutionApp',
      'fetchCategories.done'                : 'onFetchCategories',
      'fetchSections.done'                  : 'onFetchSections',
      'createArticle.done'                  : 'onCreateArticle',
      'createArticle.fail'                  : 'onCreateArticleFailed',
      'fetchLocales.done'                   : 'onLocaleLoaded',
      'click .btn-iorad-widget'             : 'submitNewTutorial',
      'click #addToHelpCenterToggle'        : 'onAddToHelpCenterToggleClicked',
      'click #addToHelpCenterAsDraftToggle' : 'onAddToHelpCenterAsDraftToggleClicked',
      'change .categoryOptions'             : 'updateSectionOptions',
      'iframe.editor.close'                 : 'onIoradClose',
      'hidden #mySuccessModal'              : 'onModalHidden',
      'hidden #myErrorModal'                : 'onModalHidden',
      'hidden #mylinkCreatedModal'          : 'onModalHidden'
    },

    requests: require('requests.js'),

    init: function () {
      // apply app settings
      this.addToHelpCenterAsDraft = this.settings['addToHelpCenterAsDraft'];

      this.ajax('fetchLocales');
      this.runTicketingApp();
    },

    // conditionally run app based on app current location
    runSolutionApp: function () {
      if (this.currentLocation() === this.SOLUTION_APP_LOCATION) {

        // load post to solutions app.
        this.currentPluginType = this.pluginTypes.SOLUTION;
        this.startFetchCategories();
      }
    },

    runTicketingApp: function () {
      if (this.TICKETING_APP_LOCATION_PATTERN.test(this.currentLocation())) {

        // load ticketing app.
        this.currentPluginType = this.pluginTypes.TICKETING;
        this.showTicketingView();
      }
    },

    startFetchCategories: function () {
      this.ajax('fetchCategories');
    },

    onLocaleLoaded: function (data) {
      this.myDefaultLocale = data.default_locale;
    },

    onModalHidden: function () {
      if (this.currentPluginType === this.pluginTypes.SOLUTION) {
        this.initializeSolutionAppControl();
      } else {
        this.showTicketingView();
      }
    },

    onIoradClose: function (data) {
      if (this.currentPluginType === this.pluginTypes.SOLUTION || this.addToHelpCenter) {
        this.createArticle(data);
      } else if (this.currentPluginType === this.pluginTypes.TICKETING) {
        this.addIoradPlayerUrlToNewTicketComment(data);
      }
    },

    onFetchCategories: function (data) {
      this.categoriesList = data.categories;
      _.each(this.categoriesList, function (category) {
        category.selected = false;
      });

      this.categoriesList[0].selected = true;

      if (this.currentPluginType === this.pluginTypes.SOLUTION) {
        this.initializeSolutionAppControl();
      } else {
        this.initializeTicketingAppControl();
      }
    },

    onFetchSections: function (data) {
      this.lastSectionsList = data.sections;
      if (this.currentPluginType === this.pluginTypes.SOLUTION) {
        this.switchTo('ioradWidgetControl',
          {
            categories: this.categoriesList,
            sections: this.lastSectionsList,
            settings: this.settings
          });
      } else {
        this.showTicketingView();
      }
    },

    onCreateArticle: function (data) {
      if (this.addToHelpCenter && this.currentPluginType === this.pluginTypes.TICKETING) {
        this.addSolutionUrlToNewTicketComment({ title: data.article.title, url: data.article.html_url });
      } else {
        this.switchTo('tutorialCreatedModal', { msg: data.article.title, url: data.article.html_url });
        this.$("#mySuccessModal").modal({
          backdrop: true,
          keyboard: false
        });
      }
    },

    onCreateArticleFailed: function (data) {
      this.switchTo('errorModal');
      this.$("#myErrorModal").modal({
        backdrop: true,
        keyboard: false
      });
    },

    onAddToHelpCenterToggleClicked: function (event) {
      this.addToHelpCenter = event.target.checked;
      if (this.addToHelpCenter) {
        this.$(".loading").removeClass("hide");
        this.startFetchCategories();
      } else {
        this.showTicketingView();
      }
    },

    onAddToHelpCenterAsDraftToggleClicked: function (event) {
      this.addToHelpCenterAsDraft = event.target.checked;
    },

    submitNewTutorial: function (event) {
      event.preventDefault();
      this.lastCategoryId = parseInt(this.$(".categoryOptions").val(), 10);
      this.lastSectionId = parseInt(this.$(".sectionOptions").val(), 10);
      this.switchTo('ioradWidgetTutorialBuilder');
      var $ioradEditorIframe = this.$(".iorad-editor-wrapper iframe");
      $ioradEditorIframe.addClass("iorad-editor");
      var zendeskAppsParams = $ioradEditorIframe.attr("src").replace("?", "&");
      $ioradEditorIframe.attr("src", iorad.newTutorialEditorUrl(event.view.location.href, this.currentPluginType) + zendeskAppsParams);
    },

    updateSectionOptions: function (event) {
      event.preventDefault();
      var $selection        = this.$(event.originalEvent.srcElement),
        selectedCategoryId  = parseInt($selection.val(), 10),
        selectedCategory    = _.find(this.categoriesList, function (category) {
          return category.id === selectedCategoryId;
        });
      _.each(this.categoriesList, function (category) {
        category.selected = false;
      });
      selectedCategory.selected = true;
      this.ajax('fetchSections', selectedCategoryId);
    },

    initializeSolutionAppControl: function () {
      this.switchTo('ioradWidgetControl',
        {
          categories: this.categoriesList,
          settings: this.settings
        });
      var selectedCategoryId = parseInt(this.$('.categoryOptions').val(), 10);
      this.ajax('fetchSections', selectedCategoryId);
    },

    initializeTicketingAppControl: function () {
      this.ajax('fetchSections', this.categoriesList[0].id);
    },

    createArticle: function (data) {
      var iframeHTML = iorad.getEmbeddedPlayerUrl(
        data.uid,
        data.tutorialId,
        data.tutorialTitle
      ),
        articleBody = helpers.fmt("
%@
", iframeHTML);

      _.each(data.steps, function (step) {
        articleBody += helpers.fmt("
%@
", helpers.safeString(step.description).string);
      });

      var articleJson = JSON.stringify({
        article: {
          "title": data.tutorialTitle,
          "locale": this.myDefaultLocale,
          "body": articleBody,
          "draft": this.addToHelpCenterAsDraft
        }
      });

      // this could be replaced with a loading marque.
      this.$('.iorad-editor-wrapper').html();
      this.ajax('createArticle', this.lastSectionId, articleJson);
    },

    addIoradPlayerUrlToNewTicketComment: function (data) {
      var url = iorad.getPlayerUrl(data.uid, data.tutorialId, data.tutorialTitle),
        comment = helpers.fmt(this.TICKET_COMMENT_MARKDOWN_FORMAT, data.tutorialTitle, url);

      this.comment().text(this.comment().text() + comment);
      this.showLinkCreatedModal();
    },

    addSolutionUrlToNewTicketComment: function (article) {
      var comment = helpers.fmt(this.TICKET_COMMENT_MARKDOWN_FORMAT, article.title, article.url);
      this.comment().text(this.comment().text() + comment);
      this.showLinkCreatedModal();
    },

    showLinkCreatedModal: function () {
      this.switchTo('linkCreatedModal', { addToHelpCenter: this.addToHelpCenter });
      this.$("#mylinkCreatedModal").modal({
        backdrop: true,
        keyboard: false
      });
    },

    showTicketingView: function () {
      if (this.addToHelpCenter) {
        this.switchTo('ticketingTemplate', { categories: this.categoriesList, sections: this.lastSectionsList, addToHelpCenter: this.addToHelpCenter });
      } else {
        this.switchTo('ticketingTemplate');
      }
    }
  };
}());
<commit_msg>avoid save as draft setting being applied to ticketing view app.<commit_after>(function () {

  var iorad = require('iorad.js');

  return {

    categoriesList: [],

    lastSectionsList: [],

    timeout: 0,

    lastCategoryId: 0,

    lastSectionId: 0,

    myDefaultLocale: '',

    SOLUTION_APP_LOCATION: 'nav_bar',

    TICKETING_APP_LOCATION_PATTERN: /ticket_sidebar$/,

    currentPluginType: '',

    addToHelpCenter: false,

    addToHelpCenterAsDraft: false,

    pluginTypes: {
      SOLUTION: 'zendeskapp_solutions', // this is a nav bar app that creates tutorials.
      TICKETING: 'zendeskapp_ticketing' // this is a ticket sidebar app that creates tutorials for existing and new tickets.
    },

    TICKET_COMMENT_MARKDOWN_FORMAT: '[%@](https:%@)',

    events: {
      'app.activated'                       : 'init',
      'pane.activated'                      : 'runSolutionApp',
      'fetchCategories.done'                : 'onFetchCategories',
      'fetchSections.done'                  : 'onFetchSections',
      'createArticle.done'                  : 'onCreateArticle',
      'createArticle.fail'                  : 'onCreateArticleFailed',
      'fetchLocales.done'                   : 'onLocaleLoaded',
      'click .btn-iorad-widget'             : 'submitNewTutorial',
      'click #addToHelpCenterToggle'        : 'onAddToHelpCenterToggleClicked',
      'click #addToHelpCenterAsDraftToggle' : 'onAddToHelpCenterAsDraftToggleClicked',
      'change .categoryOptions'             : 'updateSectionOptions',
      'iframe.editor.close'                 : 'onIoradClose',
      'hidden #mySuccessModal'              : 'onModalHidden',
      'hidden #myErrorModal'                : 'onModalHidden',
      'hidden #mylinkCreatedModal'          : 'onModalHidden'
    },

    requests: require('requests.js'),

    init: function () {
      // apply app settings
      this.addToHelpCenterAsDraft = this.settings['addToHelpCenterAsDraft'];

      this.ajax('fetchLocales');
      this.runTicketingApp();
    },

    // conditionally run app based on app current location
    runSolutionApp: function () {
      if (this.currentLocation() === this.SOLUTION_APP_LOCATION) {

        // load post to solutions app.
        this.currentPluginType = this.pluginTypes.SOLUTION;
        this.startFetchCategories();
      }
    },

    runTicketingApp: function () {
      if (this.TICKETING_APP_LOCATION_PATTERN.test(this.currentLocation())) {

        // load ticketing app.
        this.currentPluginType = this.pluginTypes.TICKETING;
        this.showTicketingView();
      }
    },

    startFetchCategories: function () {
      this.ajax('fetchCategories');
    },

    onLocaleLoaded: function (data) {
      this.myDefaultLocale = data.default_locale;
    },

    onModalHidden: function () {
      if (this.currentPluginType === this.pluginTypes.SOLUTION) {
        this.initializeSolutionAppControl();
      } else {
        this.showTicketingView();
      }
    },

    onIoradClose: function (data) {
      if (this.currentPluginType === this.pluginTypes.SOLUTION || this.addToHelpCenter) {
        this.createArticle(data);
      } else if (this.currentPluginType === this.pluginTypes.TICKETING) {
        this.addIoradPlayerUrlToNewTicketComment(data);
      }
    },

    onFetchCategories: function (data) {
      this.categoriesList = data.categories;
      _.each(this.categoriesList, function (category) {
        category.selected = false;
      });

      this.categoriesList[0].selected = true;

      if (this.currentPluginType === this.pluginTypes.SOLUTION) {
        this.initializeSolutionAppControl();
      } else {
        this.initializeTicketingAppControl();
      }
    },

    onFetchSections: function (data) {
      this.lastSectionsList = data.sections;
      if (this.currentPluginType === this.pluginTypes.SOLUTION) {
        this.switchTo('ioradWidgetControl',
          {
            categories: this.categoriesList,
            sections: this.lastSectionsList,
            settings: this.settings
          });
      } else {
        this.showTicketingView();
      }
    },

    onCreateArticle: function (data) {
      if (this.addToHelpCenter && this.currentPluginType === this.pluginTypes.TICKETING) {
        this.addSolutionUrlToNewTicketComment({ title: data.article.title, url: data.article.html_url });
      } else {
        this.switchTo('tutorialCreatedModal', { msg: data.article.title, url: data.article.html_url });
        this.$("#mySuccessModal").modal({
          backdrop: true,
          keyboard: false
        });
      }
    },

    onCreateArticleFailed: function (data) {
      this.switchTo('errorModal');
      this.$("#myErrorModal").modal({
        backdrop: true,
        keyboard: false
      });
    },

    onAddToHelpCenterToggleClicked: function (event) {
      this.addToHelpCenter = event.target.checked;
      if (this.addToHelpCenter) {
        this.$(".loading").removeClass("hide");
        this.startFetchCategories();
      } else {
        this.showTicketingView();
      }
    },

    onAddToHelpCenterAsDraftToggleClicked: function (event) {
      this.addToHelpCenterAsDraft = event.target.checked;
    },

    submitNewTutorial: function (event) {
      event.preventDefault();
      this.lastCategoryId = parseInt(this.$(".categoryOptions").val(), 10);
      this.lastSectionId = parseInt(this.$(".sectionOptions").val(), 10);
      this.switchTo('ioradWidgetTutorialBuilder');
      var $ioradEditorIframe = this.$(".iorad-editor-wrapper iframe");
      $ioradEditorIframe.addClass("iorad-editor");
      var zendeskAppsParams = $ioradEditorIframe.attr("src").replace("?", "&");
      $ioradEditorIframe.attr("src", iorad.newTutorialEditorUrl(event.view.location.href, this.currentPluginType) + zendeskAppsParams);
    },

    updateSectionOptions: function (event) {
      event.preventDefault();
      var $selection        = this.$(event.originalEvent.srcElement),
        selectedCategoryId  = parseInt($selection.val(), 10),
        selectedCategory    = _.find(this.categoriesList, function (category) {
          return category.id === selectedCategoryId;
        });
      _.each(this.categoriesList, function (category) {
        category.selected = false;
      });
      selectedCategory.selected = true;
      this.ajax('fetchSections', selectedCategoryId);
    },

    initializeSolutionAppControl: function () {
      this.switchTo('ioradWidgetControl',
        {
          categories: this.categoriesList,
          settings: this.settings
        });
      var selectedCategoryId = parseInt(this.$('.categoryOptions').val(), 10);
      this.ajax('fetchSections', selectedCategoryId);
    },

    initializeTicketingAppControl: function () {
      this.ajax('fetchSections', this.categoriesList[0].id);
    },

    createArticle: function (data) {
      var iframeHTML = iorad.getEmbeddedPlayerUrl(
          data.uid,
          data.tutorialId,
          data.tutorialTitle
        ),
        articleBody = helpers.fmt("
%@
", iframeHTML),
        saveAsDraft = this.currentPluginType === this.pluginTypes.SOLUTION ?
                          this.addToHelpCenterAsDraft
                          : false;

      _.each(data.steps, function (step) {
        articleBody += helpers.fmt("
%@
", helpers.safeString(step.description).string);
      });

      var articleJson = JSON.stringify({
        article: {
          "title": data.tutorialTitle,
          "locale": this.myDefaultLocale,
          "body": articleBody,
          "draft": saveAsDraft
        }
      });

      // this could be replaced with a loading marque.
      this.$('.iorad-editor-wrapper').html();
      this.ajax('createArticle', this.lastSectionId, articleJson);
    },

    addIoradPlayerUrlToNewTicketComment: function (data) {
      var url = iorad.getPlayerUrl(data.uid, data.tutorialId, data.tutorialTitle),
        comment = helpers.fmt(this.TICKET_COMMENT_MARKDOWN_FORMAT, data.tutorialTitle, url);

      this.comment().text(this.comment().text() + comment);
      this.showLinkCreatedModal();
    },

    addSolutionUrlToNewTicketComment: function (article) {
      var comment = helpers.fmt(this.TICKET_COMMENT_MARKDOWN_FORMAT, article.title, article.url);
      this.comment().text(this.comment().text() + comment);
      this.showLinkCreatedModal();
    },

    showLinkCreatedModal: function () {
      this.switchTo('linkCreatedModal', { addToHelpCenter: this.addToHelpCenter });
      this.$("#mylinkCreatedModal").modal({
        backdrop: true,
        keyboard: false
      });
    },

    showTicketingView: function () {
      if (this.addToHelpCenter) {
        this.switchTo('ticketingTemplate', { categories: this.categoriesList, sections: this.lastSectionsList, addToHelpCenter: this.addToHelpCenter });
      } else {
        this.switchTo('ticketingTemplate');
      }
    }
  };
}());
<|endoftext|>


<commit_before>/**
 * ResizeBars.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class handles table cell selection by faking it using a css class that gets applied
 * to cells when dragging the mouse from one cell to another.
 *
 * @class tinymce.tableplugin.ResizeBars
 * @private
 */
define("tinymce/tableplugin/ResizeBars", [
	"tinymce/util/Tools"
], function(Tools) {
	return function(editor) {
		var RESIZE_BAR_CLASS = 'mce-resize-bar',
			RESIZE_BAR_ROW_CLASS = 'mce-resize-bar-row',
			RESIZE_BAR_ROW_CURSOR_CLASS = 'row-resize',
			RESIZE_BAR_COL_CLASS = 'mce-resize-bar-col',
			RESIZE_BAR_COL_CURSOR_CLASS = 'col-resize',
			RESIZE_BAR_THICKNESS = 4;

		function getTopEdge(index, row) {
			return {
				index: index,
				y: editor.dom.getPos(row).y
			};
		}

		function getBottomEdge(index, row) {
			return {
				index: index,
				y: editor.dom.getPos(row).y + row.offsetHeight
			};
		}

		function getLeftEdge(index, cell) {
			return {
				index: index,
				x: editor.dom.getPos(cell).x
			};
		}

		function getRightEdge(index, cell) {
			return {
				index: index,
				x: editor.dom.getPos(cell).x + cell.offsetWidth
			};
		}

		function findPositions(getInnerEdge, getOuterEdge, thingsToMeasure) {
			var tablePositions = [];

			//Skip the first item in the array = no left (LTR), right (RTL) or top bars
			for (var i = 1; i < thingsToMeasure.length; i++) {
				//Get the element from the details
				var item = thingsToMeasure[i].element;
				//We need to zero index this again
				tablePositions.push(getInnerEdge(i - 1, item));
			}

			var lastTableLineToMake = thingsToMeasure[thingsToMeasure.length - 1];
			tablePositions.push(getOuterEdge(thingsToMeasure.length - 1, lastTableLineToMake.element));

			return tablePositions;
		}

		function clearBars() {
			var bars = editor.dom.select('.' + RESIZE_BAR_CLASS);
			Tools.each(bars, function(bar) {
				editor.dom.remove(bar);
			});
		}

		function generateBar(classToAdd, cursor, left, top, height, width, indexAttr, index) {
			var bar = {
				'data-mce-bogus': 'all',
				'class': RESIZE_BAR_CLASS + ' ' + classToAdd,
				unselectable: true,
				style: 'cursor: ' + cursor + '; ' +
					'margin: 0; ' +
					'padding: 0; ' +
					'position: absolute; ' +
					'left: ' + left + 'px; ' +
					'top: ' + top + 'px; ' +
					'height: ' + height + 'px; ' +
					'width: ' + width + 'px; ' +
					'background-color: blue; ' +
					'opacity: 0.5'
			};

			bar[indexAttr] = index;

			return bar;
		}

		function drawRows(rowPositions, tableWidth, tablePosition) {
			Tools.each(rowPositions, function(rowPosition) {
				var left = tablePosition.x,
					top = rowPosition.y - RESIZE_BAR_THICKNESS / 2,
					height = RESIZE_BAR_THICKNESS,
					width = tableWidth;

				editor.dom.add(editor.getBody(), 'div',
					generateBar(RESIZE_BAR_ROW_CLASS, RESIZE_BAR_ROW_CURSOR_CLASS,
						left, top, height, width, 'data-row', rowPosition.index));
			});
		}

		function drawCols(cellPositions, tableHeight, tablePosition) {
			Tools.each(cellPositions, function(cellPosition) {
				var left = cellPosition.x - RESIZE_BAR_THICKNESS / 2,
					top = tablePosition.y,
					height = tableHeight,
					width = RESIZE_BAR_THICKNESS;

				editor.dom.add(editor.getBody(), 'div',
					generateBar(RESIZE_BAR_COL_CLASS, RESIZE_BAR_COL_CURSOR_CLASS,
						left, top, height, width, 'data-col', cellPosition.index));
			});
		}

		function getTableDetails(table) {
			return Tools.map(table.rows, function(row) {

				var cells = Tools.map(row.cells, function(cell) {

					var rowspan = cell.hasAttribute('rowspan') ? parseInt(cell.getAttribute('rowspan'), 10) : 1;
					var colspan = cell.hasAttribute('colspan') ? parseInt(cell.getAttribute('colspan'), 10) : 1;

					return {
						element: cell,
						rowspan: rowspan,
						colspan: colspan
					};
				});

				return {
					element: row,
					cells: cells
				};

			});

		}

		function getJengaGrid(tableDetails) {
			function key(rowIndex, colIndex) {
				return rowIndex + ',' + colIndex;
			}

			function getAt(rowIndex, colIndex) {
				return access[key(rowIndex, colIndex)];
			}

			var access = {};
			var cells = [];

			var maxRows = 0;
			var maxCols = 0;

			Tools.each(tableDetails, function(row, rowIndex) {
				var currentRow = [];

				Tools.each(row.cells, function(cell) {

					var start = 0;

					while (access[key(rowIndex, start)] !== undefined) {
						start++;
					}

					var current = {
						element: cell.element,
						colspan: cell.colspan,
						rowspan: cell.rowspan,
						rowIndex: rowIndex,
						colIndex: start
					};

					for (var i = 0; i < cell.colspan; i++) {
						for (var j = 0; j < cell.rowspan; j++) {
							var cr = rowIndex + j;
							var cc = start + i;
							access[key(cr, cc)] = current;
							maxRows = Math.max(maxRows, cr + 1);
							maxCols = Math.max(maxCols, cc + 1);
						}
					}

					currentRow.push(current);
				});

				cells.push({
					element: row.element,
					row: currentRow
				});
			});

			return {
				grid: {
					maxRows: maxRows,
					maxCols: maxCols
				},
				getAt: getAt
			};
		}

		function getStructuralBlocks(jenga) {
			function range(start, end) {
				var r = [];

				for (var i = start; i < end; i++) {
					r.push(i);
				}

				return r;
			}

			function decide(getBlock, isSingle, getFallback) {
				var inBlock = getBlock();
				var singleInBlock;

				for (var i = 0; i < inBlock.length; i++) {
					if (isSingle(inBlock[i])) {
						singleInBlock = inBlock[i];
					}
				}
				//Is this necessary?  inblock[0] and getfallback should be the same thing?
				singleInBlock = singleInBlock ? singleInBlock : inBlock[0];
				return singleInBlock ? singleInBlock : getFallback();
			}

			function getCols(jenga) {
				var cols = range(0, jenga.grid.maxCols);
				var rows = range(0, jenga.grid.maxRows);

				return Tools.map(cols, function(col) {

					function getBlock() {
						for (var i = 0; i < rows.length; i++) {
							var detail = jenga.getAt(i, col);
							if (detail.colIndex === col) {
								return [detail];
							}
						}
					}

					function isSingle(detail) {
						return detail.colspan === 1;
					}

					function getFallback() {
						return jenga.getAt(0, col);
					}

					return decide(getBlock, isSingle, getFallback);

				});
			}

			function getRows(jenga) {

				var cols = range(0, jenga.grid.maxCols);
				var rows = range(0, jenga.grid.maxRows);

				return Tools.map(rows, function(row) {

					function getBlock() {
						for (var i = 0; i < cols.length; i++) {
							var detail = jenga.getAt(row, i);
							if (detail.rowIndex === row) {
								return [detail];
							}
						}
					}

					function isSingle(detail) {
						return detail.rowspan === 1;
					}

					function getFallback() {
						jenga.getAt(row, 0);
					}

					return decide(getBlock, isSingle, getFallback);
				});
			}
			return {
				rows: getRows(jenga),
				cols: getCols(jenga)
			};
		}

		function drawBars(table) {
			var tableDetails = getTableDetails(table);
			var jenga = getJengaGrid(tableDetails);
			var blocks = getStructuralBlocks(jenga);

			var tablePosition = editor.dom.getPos(table);
			var rowPositions = blocks.rows.length > 0 ? findPositions(getTopEdge, getBottomEdge, blocks.rows) : [];
			//The below needs to be LTR/RTL
			//TODO: Fix this since it doesn't work
			var getInner = editor.rtl ? getRightEdge : getLeftEdge;
			var getOuter = editor.rtl ? getLeftEdge : getRightEdge;
			var colPositions = blocks.cols.length > 0 ? findPositions(getInner, getOuter, blocks.cols) : [];

			drawRows(rowPositions, table.offsetWidth, tablePosition);
			drawCols(colPositions, table.offsetHeight, tablePosition);
		}

		/*editor.on('MouseDown', function(e) {
			window.console.log('mousedown', e);
		});*/

		editor.on('mouseover', function(e) {
			var tableElement = editor.dom.getParent(e.target, 'table');

			if (e.target.nodeName === 'table' || tableElement) {
				clearBars();
				drawBars(tableElement);
			}
		});

		/*editor.on('mouseout', function(e) {
			var tableElement = editor.dom.getParent(e.target, 'table');

			if (e.target.nodeName === 'table' || tableElement) {
				window.console.log('out table');
			}
		});*/

		return {
			clear: clearBars
		};
	};
});<commit_msg>working copy<commit_after>/**
 * ResizeBars.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class handles table cell selection by faking it using a css class that gets applied
 * to cells when dragging the mouse from one cell to another.
 *
 * @class tinymce.tableplugin.ResizeBars
 * @private
 */
define("tinymce/tableplugin/ResizeBars", [
	"tinymce/util/Tools"
], function(Tools) {
	return function(editor) {
		var RESIZE_BAR_CLASS = 'mce-resize-bar',
			RESIZE_BAR_ROW_CLASS = 'mce-resize-bar-row',
			RESIZE_BAR_ROW_CURSOR_CLASS = 'row-resize',
			RESIZE_BAR_COL_CLASS = 'mce-resize-bar-col',
			RESIZE_BAR_COL_CURSOR_CLASS = 'col-resize',
			RESIZE_BAR_THICKNESS = 4,
			RESIZE_MINIMUM_WIDTH = 10;

		function getTopEdge(index, row) {
			return {
				index: index,
				y: editor.dom.getPos(row).y
			};
		}

		function getBottomEdge(index, row) {
			return {
				index: index,
				y: editor.dom.getPos(row).y + row.offsetHeight
			};
		}

		function getLeftEdge(index, cell) {
			return {
				index: index,
				x: editor.dom.getPos(cell).x
			};
		}

		function getRightEdge(index, cell) {
			return {
				index: index,
				x: editor.dom.getPos(cell).x + cell.offsetWidth
			};
		}

		function findPositions(getInnerEdge, getOuterEdge, thingsToMeasure) {
			var tablePositions = [];

			//Skip the first item in the array = no left (LTR), right (RTL) or top bars
			for (var i = 1; i < thingsToMeasure.length; i++) {
				//Get the element from the details
				var item = thingsToMeasure[i].element;
				//We need to zero index this again
				tablePositions.push(getInnerEdge(i - 1, item));
			}

			var lastTableLineToMake = thingsToMeasure[thingsToMeasure.length - 1];
			tablePositions.push(getOuterEdge(thingsToMeasure.length - 1, lastTableLineToMake.element));

			return tablePositions;
		}

		function clearBars() {
			var bars = editor.dom.select('.' + RESIZE_BAR_CLASS);
			Tools.each(bars, function(bar) {
				editor.dom.remove(bar);
			});
		}

		function generateBar(classToAdd, cursor, left, top, height, width, indexAttr, index) {
			var bar = {
				'data-mce-bogus': 'all',
				'class': RESIZE_BAR_CLASS + ' ' + classToAdd,
				unselectable: true,
				style: 'cursor: ' + cursor + '; ' +
					'margin: 0; ' +
					'padding: 0; ' +
					'position: absolute; ' +
					'left: ' + left + 'px; ' +
					'top: ' + top + 'px; ' +
					'height: ' + height + 'px; ' +
					'width: ' + width + 'px; ' +
					'background-color: blue; ' +
					'opacity: 0.5'
			};

			bar[indexAttr] = index;

			return bar;
		}

		function drawRows(rowPositions, tableWidth, tablePosition) {
			Tools.each(rowPositions, function(rowPosition) {
				var left = tablePosition.x,
					top = rowPosition.y - RESIZE_BAR_THICKNESS / 2,
					height = RESIZE_BAR_THICKNESS,
					width = tableWidth;

				editor.dom.add(editor.getBody(), 'div',
					generateBar(RESIZE_BAR_ROW_CLASS, RESIZE_BAR_ROW_CURSOR_CLASS,
						left, top, height, width, 'data-row', rowPosition.index));
			});
		}

		function drawCols(cellPositions, tableHeight, tablePosition) {
			Tools.each(cellPositions, function(cellPosition) {
				var left = cellPosition.x - RESIZE_BAR_THICKNESS / 2,
					top = tablePosition.y,
					height = tableHeight,
					width = RESIZE_BAR_THICKNESS;

				editor.dom.add(editor.getBody(), 'div',
					generateBar(RESIZE_BAR_COL_CLASS, RESIZE_BAR_COL_CURSOR_CLASS,
						left, top, height, width, 'data-col', cellPosition.index));
			});
		}

		function getTableDetails(table) {
			return Tools.map(table.rows, function(row) {

				var cells = Tools.map(row.cells, function(cell) {

					var rowspan = cell.hasAttribute('rowspan') ? parseInt(cell.getAttribute('rowspan'), 10) : 1;
					var colspan = cell.hasAttribute('colspan') ? parseInt(cell.getAttribute('colspan'), 10) : 1;

					return {
						element: cell,
						rowspan: rowspan,
						colspan: colspan
					};
				});

				return {
					element: row,
					cells: cells
				};

			});

		}

		function getJengaGrid(tableDetails) {
			function key(rowIndex, colIndex) {
				return rowIndex + ',' + colIndex;
			}

			function getAt(rowIndex, colIndex) {
				return access[key(rowIndex, colIndex)];
			}

			var access = {};
			var cells = [];

			var maxRows = 0;
			var maxCols = 0;

			Tools.each(tableDetails, function(row, rowIndex) {
				var currentRow = [];

				Tools.each(row.cells, function(cell) {

					var start = 0;

					while (access[key(rowIndex, start)] !== undefined) {
						start++;
					}

					var current = {
						element: cell.element,
						colspan: cell.colspan,
						rowspan: cell.rowspan,
						rowIndex: rowIndex,
						colIndex: start
					};

					for (var i = 0; i < cell.colspan; i++) {
						for (var j = 0; j < cell.rowspan; j++) {
							var cr = rowIndex + j;
							var cc = start + i;
							access[key(cr, cc)] = current;
							maxRows = Math.max(maxRows, cr + 1);
							maxCols = Math.max(maxCols, cc + 1);
						}
					}

					currentRow.push(current);
				});

				cells.push({
					element: row.element,
					row: currentRow
				});
			});

			return {
				grid: {
					maxRows: maxRows,
					maxCols: maxCols
				},
				getAt: getAt
			};
		}

		function range(start, end) {
			var r = [];

			for (var i = start; i < end; i++) {
				r.push(i);
			}

			return r;
		}

		function decide(getBlock, isSingle, getFallback) {
			var inBlock = getBlock();
			var singleInBlock;

			for (var i = 0; i < inBlock.length; i++) {
				if (isSingle(inBlock[i])) {
					singleInBlock = inBlock[i];
				}
			}
			//Is this necessary?  inblock[0] and getfallback should be the same thing?
			singleInBlock = singleInBlock ? singleInBlock : inBlock[0];
			return singleInBlock ? singleInBlock : getFallback();
		}

		function getColumnBlocks(jenga) {
			var cols = range(0, jenga.grid.maxCols);
			var rows = range(0, jenga.grid.maxRows);

			return Tools.map(cols, function(col) {

				function getBlock() {
					for (var i = 0; i < rows.length; i++) {
						var detail = jenga.getAt(i, col);
						if (detail.colIndex === col) {
							return [detail];
						}
					}
				}

				function isSingle(detail) {
					return detail.colspan === 1;
				}

				function getFallback() {
					return jenga.getAt(0, col);
				}

				return decide(getBlock, isSingle, getFallback);

			});
		}

		function getRowBlocks(jenga) {

			var cols = range(0, jenga.grid.maxCols);
			var rows = range(0, jenga.grid.maxRows);

			return Tools.map(rows, function(row) {

				function getBlock() {
					for (var i = 0; i < cols.length; i++) {
						var detail = jenga.getAt(row, i);
						if (detail.rowIndex === row) {
							return [detail];
						}
					}
				}

				function isSingle(detail) {
					return detail.rowspan === 1;
				}

				function getFallback() {
					jenga.getAt(row, 0);
				}

				return decide(getBlock, isSingle, getFallback);
			});
		}

		function drawBars(table) {
			var tableDetails = getTableDetails(table);
			var jenga = getJengaGrid(tableDetails);
			var rows = getRowBlocks(jenga);
			var cols = getColumnBlocks(jenga);

			var tablePosition = editor.dom.getPos(table);
			var rowPositions = rows.length > 0 ? findPositions(getTopEdge, getBottomEdge, rows) : [];
			//The below needs to be LTR/RTL
			//TODO: Fix this since it doesn't work
			var getInner = editor.rtl ? getRightEdge : getLeftEdge;
			var getOuter = editor.rtl ? getLeftEdge : getRightEdge;
			var colPositions = cols.length > 0 ? findPositions(getInner, getOuter, cols) : [];

			drawRows(rowPositions, table.offsetWidth, tablePosition);
			drawCols(colPositions, table.offsetHeight, tablePosition);
		}

		function deduceSize(deducables, index) {
			if (index < 0 || index >= deducables.length - 1) {
				return "";
			}

			var current = deducables[index];

			if (current) {
				current = {
					value: current,
					delta: 0
				};
			} else {
				var reversedUpToIndex = deducables.slice(0, index).reverse();
				for (var i = 0; i < reversedUpToIndex.length; i++) {
					if (reversedUpToIndex[i]) {
						current = {
							value: reversedUpToIndex[i],
							delta: i + 1
						};
					}
				}
			}

			var next = deducables[index + 1];

			if (next) {
				next = {
					value: next,
					delta: 1
				};
			} else {
				var rest = deducables.slice(index + 1);
				for (var j = 0; j < rest.length; j++) {
					if (rest[j]) {
						next = {
							value: rest[j],
							delta: j + 1
						};
					}
				}
			}

			var extras = next.delta - current.delta;
			return Math.abs(next.value - current.value) / extras;
		}

		function getPixelWidths(jenga) {
			var cols = getColumnBlocks(jenga);

			var backups = Tools.map(cols, function(col) {
				//TODO LTR RTL
				return editor.rtl ? getRightEdge(col.colIndex, col.element).x : getLeftEdge(col.colIndex, col.element).x;
			});

			var widths = [];

			for (var i = 0; i < cols.length; i++) {
				var span = cols[i].element.hasAttribute('colspan') ? parseInt(cols[i].element.getAttribute('colspan'), 10) : 1;
				//Deduce if the column has colspan of more than 1
				var width = span > 1 ? deduceSize(backups, i) : cols[i].element.offsetWidth;
				//If everything's failed and we still don't have a width
				width = width ? width : RESIZE_MINIMUM_WIDTH;
				widths.push(width);
			}

			return widths;
		}

		//function adjustWidth(table, delta, index) {
		function adjustWidth(table) {
			var tableDetails = getTableDetails(table);
			var jenga = getJengaGrid(tableDetails);

			var widths = getPixelWidths(jenga);
			window.console.log(widths);
			//var deltas =
		}

		editor.on('MouseDown', function(e) {
			var tableElement = editor.dom.getParent(e.target, 'table');

			if (e.target.nodeName === 'table' || tableElement) {
				adjustWidth(tableElement);
			}
		});

		editor.on('mouseover', function(e) {
			var tableElement = editor.dom.getParent(e.target, 'table');

			if (e.target.nodeName === 'table' || tableElement) {
				clearBars();
				drawBars(tableElement);
			}
		});

		/*editor.on('mouseout', function(e) {
			var tableElement = editor.dom.getParent(e.target, 'table');

			if (e.target.nodeName === 'table' || tableElement) {
				window.console.log('out table');
			}
		});*/

		return {
			clear: clearBars
		};
	};
});<|endoftext|>


<commit_before>import Reflux from 'reflux';
import {hashHistory} from 'react-router';
import searchBoxStore from '../header/searchBoxStore';
import assetUtils from 'js/assetUtils';
import {actions} from 'js/actions';
import {ASSETS_TABLE_COLUMNS} from './assetsTable';

const myLibraryStore = Reflux.createStore({
  /**
   * A method for aborting current XHR fetch request.
   * It doesn't need to be defined upfront, but I'm adding it here for clarity.
   */
  abortFetchData: undefined,
  PAGE_SIZE: 100,
  DEFAULT_COLUMN: ASSETS_TABLE_COLUMNS.get('last-modified'),

  init() {
    this.data = {
      isFetchingData: false,
      sortColumn: this.DEFAULT_COLUMN,
      isOrderAsc: this.DEFAULT_COLUMN.defaultIsOrderAsc,
      currentPage: 0,
      totalPages: null,
      totalUserAssets: null,
      totalSearchAssets: null,
      assets: []
    };
    this.previousPath = null;

    hashHistory.listen(this.onRouteChange.bind(this));
    searchBoxStore.listen(this.searchBoxStoreChanged);
    actions.library.moveToCollection.completed.listen(this.onMoveToCollectionCompleted);
    actions.library.searchMyLibraryAssets.started.listen(this.onSearchStarted);
    actions.library.searchMyLibraryAssets.completed.listen(this.onSearchCompleted);
    actions.library.searchMyLibraryAssets.failed.listen(this.onSearchFailed);
    actions.resources.loadAsset.completed.listen(this.onAssetChanged);
    actions.resources.updateAsset.completed.listen(this.onAssetChanged);
    actions.resources.cloneAsset.completed.listen(this.onAssetCreated);
    actions.resources.createResource.completed.listen(this.onAssetCreated);
    actions.resources.deleteAsset.completed.listen(this.onDeleteAssetCompleted);

    this.fetchData();
  },

  onRouteChange(data) {
    // refresh data when navigating into library from other place
    if (
      this.previousPath !== null &&
      this.previousPath.split('/')[1] !== 'library' &&
      data.pathname.split('/')[1] === 'library'
    ) {
      this.fetchData();
    }
    this.previousPath = data.pathname;
  },

  // methods for handling search parameters

  searchBoxStoreChanged() {
    // reset to first page when search changes
    this.data.currentPage = 0;
    this.data.totalPages = null;
    this.data.totalSearchAssets = null;
    this.fetchData();
  },

  // methods for reacting to assets changes

  onMoveToCollectionCompleted(asset) {
    if (assetUtils.isLibraryAsset(asset.asset_type)) {
      // update total root assets after moving asset into/out of collection
      if (asset.parent === null) {
        this.data.totalUserAssets++;
      } else {
        this.data.totalUserAssets--;
      }
      this.fetchData();
    }
  },

  onAssetChanged(asset) {
    if (
      assetUtils.isLibraryAsset(asset.asset_type) &&
      this.data.assets.length !== 0
    ) {
      let wasUpdated = false;
      for (let i = 0; i < this.data.assets.length; i++) {
        if (this.data.assets[i].uid === asset.uid) {
          this.data.assets[i] = asset;
          wasUpdated = true;
          break;
        }
      }
      if (wasUpdated) {
        this.trigger(this.data);
      }
    }
  },

  onDeleteAssetCompleted({uid, assetType}) {
    if (assetUtils.isLibraryAsset(assetType)) {
      const found = this.data.assets.find((asset) => {return asset.uid === uid;});
      if (found) {
        this.data.totalUserAssets--;
        this.fetchData();
      }
      // if not found it is possible it is on other page of results, but it is
      // not important enough to do a data fetch
    }
  },

  onAssetCreated(asset) {
    if (
      assetUtils.isLibraryAsset(asset.asset_type) &&
      asset.parent === null
    ) {
      this.data.totalUserAssets++;
      this.fetchData();
    }
  },

  // methods for handling data fetch

  onSearchStarted(abort) {
    this.abortFetchData = abort;
    this.data.isFetchingData = true;
    this.trigger(this.data);
  },

  onSearchCompleted(response) {
    delete this.abortFetchData;

    this.data.hasNextPage = response.next !== null;
    this.data.hasPreviousPage = response.previous !== null;

    this.data.totalPages = Math.ceil(response.count / this.PAGE_SIZE);

    this.data.assets = response.results;
    this.data.totalSearchAssets = response.count;

    // update total count for the first time and the ones that will get a full count
    if (
      this.data.totalUserAssets === null ||
      searchBoxStore.getSearchPhrase() === ''
    ) {
      this.data.totalUserAssets = this.data.totalSearchAssets;
    }
    this.data.isFetchingData = false;
    this.trigger(this.data);
  },

  onSearchFailed() {
    delete this.abortFetchData;
    this.data.isFetchingData = false;
    this.trigger(this.data);
  },

  // public methods

  setCurrentPage(newCurrentPage) {
    this.data.currentPage = newCurrentPage;
    this.fetchData();
  },

  setOrder(sortColumn, isOrderAsc) {
    if (
      this.data.sortColumn.id !== sortColumn.id ||
      this.data.isOrderAsc !== isOrderAsc
    ) {
      this.data.sortColumn = sortColumn;
      this.data.isOrderAsc = isOrderAsc;
      this.fetchData();
    }
  },

  // the method for fetching new data

  fetchData() {
    if (this.abortFetchData) {
      this.abortFetchData();
    }

    actions.library.searchMyLibraryAssets({
      searchPhrase: searchBoxStore.getSearchPhrase(),
      pageSize: this.PAGE_SIZE,
      page: this.data.currentPage,
      sort: this.data.sortColumn.backendProp,
      order: this.data.isOrderAsc ? -1 : 1
    });
  },
});

export default myLibraryStore;
<commit_msg>publicCollectionsStore updating<commit_after>import Reflux from 'reflux';
import {hashHistory} from 'react-router';
import searchBoxStore from '../header/searchBoxStore';
import assetUtils from 'js/assetUtils';
import {actions} from 'js/actions';
import {ASSETS_TABLE_COLUMNS} from './assetsTable';

const myLibraryStore = Reflux.createStore({
  /**
   * A method for aborting current XHR fetch request.
   * It doesn't need to be defined upfront, but I'm adding it here for clarity.
   */
  abortFetchData: undefined,
  previousPath: null,
  PAGE_SIZE: 100,
  DEFAULT_COLUMN: ASSETS_TABLE_COLUMNS.get('last-modified'),

  init() {
    this.data = {
      isFetchingData: false,
      sortColumn: this.DEFAULT_COLUMN,
      isOrderAsc: this.DEFAULT_COLUMN.defaultIsOrderAsc,
      currentPage: 0,
      totalPages: null,
      totalUserAssets: null,
      totalSearchAssets: null,
      assets: []
    };

    hashHistory.listen(this.onRouteChange.bind(this));
    searchBoxStore.listen(this.searchBoxStoreChanged);
    actions.library.moveToCollection.completed.listen(this.onMoveToCollectionCompleted);
    actions.library.searchMyLibraryAssets.started.listen(this.onSearchStarted);
    actions.library.searchMyLibraryAssets.completed.listen(this.onSearchCompleted);
    actions.library.searchMyLibraryAssets.failed.listen(this.onSearchFailed);
    actions.resources.loadAsset.completed.listen(this.onAssetChanged);
    actions.resources.updateAsset.completed.listen(this.onAssetChanged);
    actions.resources.cloneAsset.completed.listen(this.onAssetCreated);
    actions.resources.createResource.completed.listen(this.onAssetCreated);
    actions.resources.deleteAsset.completed.listen(this.onDeleteAssetCompleted);

    this.fetchData();
  },

  // methods for handling search and data fetch

  fetchData() {
    if (this.abortFetchData) {
      this.abortFetchData();
    }

    actions.library.searchMyLibraryAssets({
      searchPhrase: searchBoxStore.getSearchPhrase(),
      pageSize: this.PAGE_SIZE,
      page: this.data.currentPage,
      sort: this.data.sortColumn.backendProp,
      order: this.data.isOrderAsc ? -1 : 1
    });
  },

  onRouteChange(data) {
    // refresh data when navigating into library from other place
    if (
      this.previousPath !== null &&
      this.previousPath.split('/')[1] !== 'library' &&
      data.pathname.split('/')[1] === 'library'
    ) {
      this.fetchData();
    }
    this.previousPath = data.pathname;
  },

  searchBoxStoreChanged() {
    // reset to first page when search changes
    this.data.currentPage = 0;
    this.data.totalPages = null;
    this.data.totalSearchAssets = null;
    this.fetchData();
  },

  onSearchStarted(abort) {
    this.abortFetchData = abort;
    this.data.isFetchingData = true;
    this.trigger(this.data);
  },

  onSearchCompleted(response) {
    delete this.abortFetchData;

    this.data.hasNextPage = response.next !== null;
    this.data.hasPreviousPage = response.previous !== null;

    this.data.totalPages = Math.ceil(response.count / this.PAGE_SIZE);

    this.data.assets = response.results;
    this.data.totalSearchAssets = response.count;

    // update total count for the first time and the ones that will get a full count
    if (
      this.data.totalUserAssets === null ||
      searchBoxStore.getSearchPhrase() === ''
    ) {
      this.data.totalUserAssets = this.data.totalSearchAssets;
    }
    this.data.isFetchingData = false;
    this.trigger(this.data);
  },

  onSearchFailed() {
    delete this.abortFetchData;
    this.data.isFetchingData = false;
    this.trigger(this.data);
  },

  // methods for handling actions that update assets

  onMoveToCollectionCompleted(asset) {
    if (assetUtils.isLibraryAsset(asset.asset_type)) {
      // update total root assets after moving asset into/out of collection
      if (asset.parent === null) {
        this.data.totalUserAssets++;
      } else {
        this.data.totalUserAssets--;
      }
      this.fetchData();
    }
  },

  onAssetChanged(asset) {
    if (
      assetUtils.isLibraryAsset(asset.asset_type) &&
      this.data.assets.length !== 0
    ) {
      let wasUpdated = false;
      for (let i = 0; i < this.data.assets.length; i++) {
        if (this.data.assets[i].uid === asset.uid) {
          this.data.assets[i] = asset;
          wasUpdated = true;
          break;
        }
      }
      if (wasUpdated) {
        this.trigger(this.data);
      }
    }
  },

  onDeleteAssetCompleted({uid, assetType}) {
    if (assetUtils.isLibraryAsset(assetType)) {
      const found = this.data.assets.find((asset) => {return asset.uid === uid;});
      if (found) {
        this.data.totalUserAssets--;
        this.fetchData();
      }
      // if not found it is possible it is on other page of results, but it is
      // not important enough to do a data fetch
    }
  },

  onAssetCreated(asset) {
    if (
      assetUtils.isLibraryAsset(asset.asset_type) &&
      asset.parent === null
    ) {
      this.data.totalUserAssets++;
      this.fetchData();
    }
  },

  // public methods

  setCurrentPage(newCurrentPage) {
    this.data.currentPage = newCurrentPage;
    this.fetchData();
  },

  setOrder(sortColumn, isOrderAsc) {
    if (
      this.data.sortColumn.id !== sortColumn.id ||
      this.data.isOrderAsc !== isOrderAsc
    ) {
      this.data.sortColumn = sortColumn;
      this.data.isOrderAsc = isOrderAsc;
      this.fetchData();
    }
  }
});

export default myLibraryStore;
<|endoftext|>


<commit_before>if (typeof SPARQL == 'undefined') {
    SPARQL = {};
}

SPARQL = {
    prefix : {
        rdf : "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n",
        rdfs : "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> \n",
        owl : "PREFIX owl:<http://www.w3.org/2002/07/owl#> \n",
        all : function(){
            result = "";
            result += SPARQL.prefix.rdf;
            result += SPARQL.prefix.rdfs;
            result += SPARQL.prefix.owl;
            return result;
        }
    },
    result : {
        columns : function(data){
            return data.head.vars;
        },
        rows : function(data){
            return data.results.bindings;
        },
        time_taken : function(data){
            return data.results.time_taken;
        },
        print : function(){
           Utils.alert("The PRINT feature has not been implemented yet.");
        }
    },
    get_query: function() {
        if (editor) {
            return editor.getSession().getValue();
        } else {
            return $("#txt_sparql_query").val();
        }
    },
    textbox : {
        is_valid : function(){
            var query = SPARQL.get_query();
            if(query == undefined || query.trim() == ''){
                Utils.alert("No SPARQL query inputted in the text box.")
                return false;
            }
            return true;
        }
    },
    download : {
        rdb : function(){
            var query = SPARQL.get_query();
            if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                $("#btn_show_checked_properties_no").click();
                query = SPARQL.get_query();
                $("#btn_show_checked_properties_yes").click();
            }
            var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"rdb-converter.sql?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
            var selected_class = QueryBuilder.classes.get_selected_class();
            if(selected_class != undefined && selected_class != ''){
               download_url += "&for_class="+selected_class;
               download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
            }
            window.open(download_url);
        },
        csv : function(){
            var query = SPARQL.get_query();
            if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                $("#btn_show_checked_properties_no").click();
                query = $("#txt_sparql_query").val();
                $("#btn_show_checked_properties_yes").click();
            }
            var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"csv-converter.csv?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
            var selected_class = QueryBuilder.classes.get_selected_class();
            if(selected_class != undefined && selected_class != ''){
               download_url += "&for_class="+selected_class;
               download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
            }
            window.open(download_url);
        },
        pdf : function(){
            Utils.alert("The PDF download feature has not been implemented yet.");
        },
        json :{
            sesame : function(){
                var query = SPARQL.get_query();
                if(QueryBuilder.properties.will_show_properties_in_preview() == false){
                    $("#btn_show_checked_properties_yes").click();
                    $("#btn_show_checked_properties_no").click();
                }
                var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"json?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query)+"&json_output_format=sesame";
                window.open(download_url);
            },
            virtuoso : function(){
                var query = SPARQL.get_query();
                if(QueryBuilder.properties.will_show_properties_in_preview() == false){
                    $("#btn_show_checked_properties_yes").click();
                    $("#btn_show_checked_properties_no").click();
                }
                var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"json?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
                window.open(download_url);
            },
            for_class : function(){
                var query = SPARQL.get_query();
                if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                    $("#btn_show_checked_properties_no").click();
                    $("#btn_show_checked_properties_yes").click();
                }
                var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"json?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query)+"&for_class="+QueryBuilder.classes.get_selected_class();
                download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
                window.open(download_url);
            }

        },
        configured : function(){
            var query = SPARQL.get_query();
            if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                $("#btn_show_checked_properties_no").click();
                query = $("#txt_sparql_query").val();
                $("#btn_show_checked_properties_yes").click();
            }
            var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"configured-converter?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
            download_url += "&for_class="+QueryBuilder.classes.get_selected_class();
            download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
            var str_variable_dictionary = "";
            for(i=0;i<configured_convert.variable_dictionary.length;i++){
                if (i>0)
                    str_variable_dictionary += ",";
                str_variable_dictionary += configured_convert.variable_dictionary[i].variable + "::" + configured_convert.variable_dictionary[i].value;

            }
            download_url += "&variable_dictionary="+encodeURIComponent(str_variable_dictionary);
            download_url += "&header="+encodeURIComponent(configured_convert.header);
            download_url += "&body="+encodeURIComponent(configured_convert.body);
            download_url += "&footer="+encodeURIComponent(configured_convert.footer);
            window.open(download_url);
        }

    },

    flash_error : function(msg){
        $.gritter.add({title: "ERROR in SPARQL query execution",text: msg, sticky:true});
    }

};<commit_msg>Bug fix in integrating new SPARQL editor with QueryBuilder<commit_after>if (typeof SPARQL == 'undefined') {
    SPARQL = {};
}

SPARQL = {
    prefix : {
        rdf : "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n",
        rdfs : "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> \n",
        owl : "PREFIX owl:<http://www.w3.org/2002/07/owl#> \n",
        all : function(){
            result = "";
            result += SPARQL.prefix.rdf;
            result += SPARQL.prefix.rdfs;
            result += SPARQL.prefix.owl;
            return result;
        }
    },
    result : {
        columns : function(data){
            return data.head.vars;
        },
        rows : function(data){
            return data.results.bindings;
        },
        time_taken : function(data){
            return data.results.time_taken;
        },
        print : function(){
           Utils.alert("The PRINT feature has not been implemented yet.");
        }
    },
    get_query: function() {
        if (editor) {
            return editor.getSession().getValue();
        } else {
            return $("#txt_sparql_query").val();
        }
    },
    textbox : {
        is_valid : function(){
            var query = SPARQL.get_query();
            if(query == undefined || query.trim() == ''){
                Utils.alert("No SPARQL query inputted in the text box.")
                return false;
            }
            return true;
        }
    },
    download : {
        rdb : function(){
            var query = SPARQL.get_query();
            if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                $("#btn_show_checked_properties_no").click();
                query = SPARQL.get_query();
                $("#btn_show_checked_properties_yes").click();
            }
            var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"rdb-converter.sql?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
            var selected_class = QueryBuilder.classes.get_selected_class();
            if(selected_class != undefined && selected_class != ''){
               download_url += "&for_class="+selected_class;
               download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
            }
            window.open(download_url);
        },
        csv : function(){
            var query = SPARQL.get_query();
            if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                $("#btn_show_checked_properties_no").click();
                query = SPARQL.get_query();
                $("#btn_show_checked_properties_yes").click();
            }
            var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"csv-converter.csv?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
            var selected_class = QueryBuilder.classes.get_selected_class();
            if(selected_class != undefined && selected_class != ''){
               download_url += "&for_class="+selected_class;
               download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
            }
            window.open(download_url);
        },
        pdf : function(){
            Utils.alert("The PDF download feature has not been implemented yet.");
        },
        json :{
            sesame : function(){
                var query = SPARQL.get_query();
                if(QueryBuilder.properties.will_show_properties_in_preview() == false){
                    $("#btn_show_checked_properties_yes").click();
                    $("#btn_show_checked_properties_no").click();
                }
                var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"json?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query)+"&json_output_format=sesame";
                window.open(download_url);
            },
            virtuoso : function(){
                var query = SPARQL.get_query();
                if(QueryBuilder.properties.will_show_properties_in_preview() == false){
                    $("#btn_show_checked_properties_yes").click();
                    $("#btn_show_checked_properties_no").click();
                }
                var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"json?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
                window.open(download_url);
            },
            for_class : function(){
                var query = SPARQL.get_query();
                if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                    $("#btn_show_checked_properties_no").click();
                    $("#btn_show_checked_properties_yes").click();
                }
                var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"json?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query)+"&for_class="+QueryBuilder.classes.get_selected_class();
                download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
                window.open(download_url);
            }

        },
        configured : function(){
            var query = SPARQL.get_query();
            if(QueryBuilder.properties.will_show_properties_in_preview() == true){
                $("#btn_show_checked_properties_no").click();
                query = SPARQL.get_query();;
                $("#btn_show_checked_properties_yes").click();
            }
            var download_url = Utils.rdf2any.server+Utils.rdf2any.actions.convert+"configured-converter?dataset="+QueryBuilder.datasets.get_selected()+"&query="+encodeURIComponent(query);
            download_url += "&for_class="+QueryBuilder.classes.get_selected_class();
            download_url += "&properties="+encodeURIComponent(QueryBuilder.properties.get_checked_properties());
            var str_variable_dictionary = "";
            for(i=0;i<configured_convert.variable_dictionary.length;i++){
                if (i>0)
                    str_variable_dictionary += ",";
                str_variable_dictionary += configured_convert.variable_dictionary[i].variable + "::" + configured_convert.variable_dictionary[i].value;

            }
            download_url += "&variable_dictionary="+encodeURIComponent(str_variable_dictionary);
            download_url += "&header="+encodeURIComponent(configured_convert.header);
            download_url += "&body="+encodeURIComponent(configured_convert.body);
            download_url += "&footer="+encodeURIComponent(configured_convert.footer);
            window.open(download_url);
        }

    },

    flash_error : function(msg){
        $.gritter.add({title: "ERROR in SPARQL query execution",text: msg, sticky:true});
    }

};<|endoftext|>


<commit_before>const request = require('request-promise-native');
const bot = require('./../bot');
const md = require('to-markdown');
const RichEmbed = require('discord.js').RichEmbed;
const did_from_uname = async function (uname) {
    let res = await request('http://localhost/v0/discord/did_from_uname/' + encodeURIComponent(uname));
    console.log(res);
    res = JSON.parse(res);
    return res.id;
}
module.exports = {
    'ping': function (body) {
        console.log("Recieved a ping event\n" + body);
    },
    'post': async function (body) {
        console.log("Recieved a post event for post no: " + body.post.post_number);
        let embed = new RichEmbed();
        embed.setAuthor(body.post.username, body.post.avatar_template.replace('{size}', "100")).setDescription(md(body.post.cooked))
        if (body.post.reply_to_user && body.post.reply_to_user.username) {
            let id = await did_from_uname(body.post.reply_to_user.username);
            if (id)
                bot.users.get(id).send('You recieved a reply from ' + body.post.username + ' for post ' + body.base_url + '/t/' + body.post.topic_slug + '/' + body.post.topic_id + '/' + body.post.post_number, { embed: embed })
        }
    },
    'user': async function (body) {
        console.log("Recieved user event");
    }
}
<commit_msg>fix icon_url<commit_after>const request = require('request-promise-native');
const bot = require('./../bot');
const md = require('to-markdown');
const RichEmbed = require('discord.js').RichEmbed;
const did_from_uname = async function (uname) {
    let res = await request('http://localhost/v0/discord/did_from_uname/' + encodeURIComponent(uname));
    console.log(res);
    res = JSON.parse(res);
    return res.id;
}
module.exports = {
    'ping': function (body) {
        console.log("Recieved a ping event\n" + body);
    },
    'post': async function (body) {
        console.log("Recieved a post event for post no: " + body.post.post_number);
        let embed = new RichEmbed();
        embed.setAuthor(body.post.username, body.base_url + body.post.avatar_template.replace('{size}', "100")).setDescription(md(body.post.cooked))
        if (body.post.reply_to_user && body.post.reply_to_user.username) {
            let id = await did_from_uname(body.post.reply_to_user.username);
            if (id)
                bot.users.get(id).send('You recieved a reply from ' + body.post.username + ' for post ' + body.base_url + '/t/' + body.post.topic_slug + '/' + body.post.topic_id + '/' + body.post.post_number, { embed: embed })
        }
    },
    'user': async function (body) {
        console.log("Recieved user event");
    }
}
<|endoftext|>