<commit_before>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, $, brackets, window */

/**
 * Initializes the default brackets menu items.
 */
define(function (require, exports, module) {
    "use strict";

    var AppInit         = require("utils/AppInit"),
        Commands        = require("command/Commands"),
        EditorManager   = require("editor/EditorManager"),
        Menus           = require("command/Menus"),
        Strings         = require("strings");

    AppInit.htmlReady(function () {
        /*
         * File menu
         */
        var menu;
        menu = Menus.addMenu(Strings.FILE_MENU, Menus.AppMenuBar.FILE_MENU);
        menu.addMenuItem(Commands.FILE_NEW);
        menu.addMenuItem(Commands.FILE_NEW_FOLDER);
        menu.addMenuItem(Commands.FILE_OPEN);
        menu.addMenuItem(Commands.FILE_OPEN_FOLDER);
        menu.addMenuItem(Commands.FILE_CLOSE);
        menu.addMenuItem(Commands.FILE_CLOSE_ALL);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.FILE_SAVE);
        menu.addMenuItem(Commands.FILE_SAVE_ALL);
        menu.addMenuItem(Commands.FILE_SAVE_AS);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.FILE_LIVE_FILE_PREVIEW);
        menu.addMenuItem(Commands.FILE_LIVE_HIGHLIGHT);
        menu.addMenuItem(Commands.FILE_PROJECT_SETTINGS);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.FILE_EXTENSION_MANAGER);

        // supress redundant quit menu item on mac
        if (brackets.platform !== "mac" && !brackets.inBrowser) {
            menu.addMenuDivider();
            menu.addMenuItem(Commands.FILE_QUIT);
        }

        /*
         * Edit  menu
         */
        menu = Menus.addMenu(Strings.EDIT_MENU, Menus.AppMenuBar.EDIT_MENU);
        menu.addMenuItem(Commands.EDIT_UNDO);
        menu.addMenuItem(Commands.EDIT_REDO);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_CUT);
        menu.addMenuItem(Commands.EDIT_COPY);
        menu.addMenuItem(Commands.EDIT_PASTE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_SELECT_ALL);
        menu.addMenuItem(Commands.EDIT_SELECT_LINE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_FIND);
        menu.addMenuItem(Commands.EDIT_FIND_IN_FILES);
        menu.addMenuItem(Commands.EDIT_FIND_NEXT);

        menu.addMenuItem(Commands.EDIT_FIND_PREVIOUS);

        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_REPLACE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_INDENT);
        menu.addMenuItem(Commands.EDIT_UNINDENT);
        menu.addMenuItem(Commands.EDIT_DUPLICATE);
        menu.addMenuItem(Commands.EDIT_DELETE_LINES);
        menu.addMenuItem(Commands.EDIT_LINE_UP);
        menu.addMenuItem(Commands.EDIT_LINE_DOWN);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_LINE_COMMENT);
        menu.addMenuItem(Commands.EDIT_BLOCK_COMMENT);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.SHOW_CODE_HINTS);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_CLOSE_BRACKETS);

        /*
         * View menu
         */
        menu = Menus.addMenu(Strings.VIEW_MENU, Menus.AppMenuBar.VIEW_MENU);
        menu.addMenuItem(Commands.VIEW_HIDE_SIDEBAR);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.VIEW_INCREASE_FONT_SIZE);
        menu.addMenuItem(Commands.VIEW_DECREASE_FONT_SIZE);
        menu.addMenuItem(Commands.VIEW_RESTORE_FONT_SIZE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_ACTIVE_LINE);
        menu.addMenuItem(Commands.TOGGLE_LINE_NUMBERS);
        menu.addMenuItem(Commands.TOGGLE_WORD_WRAP);

        /*
         * Navigate menu
         */
        menu = Menus.addMenu(Strings.NAVIGATE_MENU, Menus.AppMenuBar.NAVIGATE_MENU);
        menu.addMenuItem(Commands.NAVIGATE_QUICK_OPEN);
        menu.addMenuItem(Commands.NAVIGATE_GOTO_LINE);
        menu.addMenuItem(Commands.NAVIGATE_GOTO_DEFINITION);
        menu.addMenuItem(Commands.NAVIGATE_JUMPTO_DEFINITION);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.NAVIGATE_NEXT_DOC);
        menu.addMenuItem(Commands.NAVIGATE_PREV_DOC);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.NAVIGATE_SHOW_IN_FILE_TREE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_QUICK_EDIT);
        menu.addMenuItem(Commands.QUICK_EDIT_PREV_MATCH);
        menu.addMenuItem(Commands.QUICK_EDIT_NEXT_MATCH);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_QUICK_DOCS);

        /*
         * Help menu
         */
        menu = Menus.addMenu(Strings.HELP_MENU, Menus.AppMenuBar.HELP_MENU);
        menu.addMenuItem(Commands.HELP_CHECK_FOR_UPDATE);

        menu.addMenuDivider();
        if (brackets.config.how_to_use_url) {
            menu.addMenuItem(Commands.HELP_HOW_TO_USE_BRACKETS);
        }
        if (brackets.config.forum_url) {
            menu.addMenuItem(Commands.HELP_FORUM);
        }
        if (brackets.config.release_notes_url) {
            menu.addMenuItem(Commands.HELP_RELEASE_NOTES);
        }
        if (brackets.config.report_issue_url) {
            menu.addMenuItem(Commands.HELP_REPORT_AN_ISSUE);
        }

        menu.addMenuDivider();
        menu.addMenuItem(Commands.HELP_SHOW_EXT_FOLDER);

        var hasAboutItem = (brackets.platform !== "mac" || brackets.inBrowser);

        // Add final divider only if we have a twitter URL or about item
        if (hasAboutItem || brackets.config.twitter_url) {
            menu.addMenuDivider();
        }

        if (brackets.config.twitter_url) {
            menu.addMenuItem(Commands.HELP_TWITTER);
        }
        // supress redundant about menu item in mac shell
        if (hasAboutItem) {
            menu.addMenuItem(Commands.HELP_ABOUT);
        }

        /*
         * Context Menus
         */
        var project_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.PROJECT_MENU);
        project_cmenu.addMenuItem(Commands.FILE_NEW);
        project_cmenu.addMenuItem(Commands.FILE_NEW_FOLDER);
        project_cmenu.addMenuItem(Commands.FILE_RENAME);
        project_cmenu.addMenuItem(Commands.FILE_SAVE_AS);
        project_cmenu.addMenuItem(Commands.FILE_DELETE);
        project_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_OS);
        project_cmenu.addMenuDivider();
        project_cmenu.addMenuItem(Commands.EDIT_FIND_IN_SUBTREE);
        project_cmenu.addMenuDivider();
        project_cmenu.addMenuItem(Commands.FILE_REFRESH);

        var working_set_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.WORKING_SET_MENU);
        working_set_cmenu.addMenuItem(Commands.FILE_CLOSE);
        working_set_cmenu.addMenuItem(Commands.FILE_SAVE);
        working_set_cmenu.addMenuItem(Commands.FILE_SAVE_AS);
        working_set_cmenu.addMenuItem(Commands.FILE_RENAME);
        working_set_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_FILE_TREE);
        working_set_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_OS);
        working_set_cmenu.addMenuDivider();
        working_set_cmenu.addMenuItem(Commands.EDIT_FIND_IN_SUBTREE);
        working_set_cmenu.addMenuDivider();
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_ADDED);
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_NAME);
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_TYPE);
        working_set_cmenu.addMenuDivider();
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_AUTO);

        var editor_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.EDITOR_MENU);
        // editor_cmenu.addMenuItem(Commands.NAVIGATE_JUMPTO_DEFINITION);
        editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_EDIT);
        editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_DOCS);
        editor_cmenu.addMenuItem(Commands.EDIT_SELECT_ALL);

        var inline_editor_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.INLINE_EDITOR_MENU);
        inline_editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_EDIT);
        inline_editor_cmenu.addMenuItem(Commands.EDIT_SELECT_ALL);
        inline_editor_cmenu.addMenuDivider();
        inline_editor_cmenu.addMenuItem(Commands.QUICK_EDIT_PREV_MATCH);
        inline_editor_cmenu.addMenuItem(Commands.QUICK_EDIT_NEXT_MATCH);

        /**
         * Context menu for code editors (both full-size and inline)
         * Auto selects the word the user clicks if the click does not occur over
         * an existing selection
         */
        $("#editor-holder").on("contextmenu", function (e) {
            if ($(e.target).parents(".CodeMirror-gutter").length !== 0) {
                return;
            }

            // Note: on mousedown before this event, CodeMirror automatically checks mouse pos, and
            // if not clicking on a selection moves the cursor to click location. When triggered
            // from keyboard, no pre-processing occurs and the cursor/selection is left as is.

            var editor = EditorManager.getFocusedEditor(),
                inlineWidget = EditorManager.getFocusedInlineWidget();

            if (editor) {
                // If there's just an insertion point select the word token at the cursor pos so
                // it's more clear what the context menu applies to.
                if (!editor.hasSelection()) {
                    editor.selectWordAt(editor.getCursorPos());

                    // Prevent menu from overlapping text by moving it down a little
                    // Temporarily backout this change for now to help mitigate issue #1111,
                    // which only happens if mouse is not over context menu. Better fix
                    // requires change to bootstrap, which is too risky for now.
                    //e.pageY += 6;
                }

                // Inline text editors have a different context menu (safe to assume it's not some other
                // type of inline widget since we already know an Editor has focus)
                if (inlineWidget) {
                    inline_editor_cmenu.open(e);
                } else {
                    editor_cmenu.open(e);
                }
            }
        });

        /**
         * Context menus for folder tree & working set list
         */
        $("#project-files-container").on("contextmenu", function (e) {
            project_cmenu.open(e);
        });

        $("#open-files-container").on("contextmenu", function (e) {
            working_set_cmenu.open(e);
        });

        // Prevent the browser context menu since Brackets creates a custom context menu
        $(window).contextmenu(function (e) {
            e.preventDefault();
        });

        /*
         * General menu event processing
         */
        // Prevent clicks on top level menus and menu items from taking focus
        $(window.document).on("mousedown", ".dropdown", function (e) {
            e.preventDefault();
        });

        // Switch menus when the mouse enters an adjacent menu
        // Only open the menu if another one has already been opened
        // by clicking
        $(window.document).on("mouseenter", "#titlebar .dropdown", function (e) {
            var open = $(this).siblings(".open");
            if (open.length > 0) {
                open.removeClass("open");
                $(this).addClass("open");
            }
        });
    });
});
<commit_msg>Moved live highlight From file menu to view menu.<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, $, brackets, window */

/**
 * Initializes the default brackets menu items.
 */
define(function (require, exports, module) {
    "use strict";

    var AppInit         = require("utils/AppInit"),
        Commands        = require("command/Commands"),
        EditorManager   = require("editor/EditorManager"),
        Menus           = require("command/Menus"),
        Strings         = require("strings");

    AppInit.htmlReady(function () {
        /*
         * File menu
         */
        var menu;
        menu = Menus.addMenu(Strings.FILE_MENU, Menus.AppMenuBar.FILE_MENU);
        menu.addMenuItem(Commands.FILE_NEW);
        menu.addMenuItem(Commands.FILE_NEW_FOLDER);
        menu.addMenuItem(Commands.FILE_OPEN);
        menu.addMenuItem(Commands.FILE_OPEN_FOLDER);
        menu.addMenuItem(Commands.FILE_CLOSE);
        menu.addMenuItem(Commands.FILE_CLOSE_ALL);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.FILE_SAVE);
        menu.addMenuItem(Commands.FILE_SAVE_ALL);
        menu.addMenuItem(Commands.FILE_SAVE_AS);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.FILE_LIVE_FILE_PREVIEW);
        menu.addMenuItem(Commands.FILE_PROJECT_SETTINGS);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.FILE_EXTENSION_MANAGER);

        // supress redundant quit menu item on mac
        if (brackets.platform !== "mac" && !brackets.inBrowser) {
            menu.addMenuDivider();
            menu.addMenuItem(Commands.FILE_QUIT);
        }

        /*
         * Edit  menu
         */
        menu = Menus.addMenu(Strings.EDIT_MENU, Menus.AppMenuBar.EDIT_MENU);
        menu.addMenuItem(Commands.EDIT_UNDO);
        menu.addMenuItem(Commands.EDIT_REDO);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_CUT);
        menu.addMenuItem(Commands.EDIT_COPY);
        menu.addMenuItem(Commands.EDIT_PASTE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_SELECT_ALL);
        menu.addMenuItem(Commands.EDIT_SELECT_LINE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_FIND);
        menu.addMenuItem(Commands.EDIT_FIND_IN_FILES);
        menu.addMenuItem(Commands.EDIT_FIND_NEXT);

        menu.addMenuItem(Commands.EDIT_FIND_PREVIOUS);

        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_REPLACE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_INDENT);
        menu.addMenuItem(Commands.EDIT_UNINDENT);
        menu.addMenuItem(Commands.EDIT_DUPLICATE);
        menu.addMenuItem(Commands.EDIT_DELETE_LINES);
        menu.addMenuItem(Commands.EDIT_LINE_UP);
        menu.addMenuItem(Commands.EDIT_LINE_DOWN);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.EDIT_LINE_COMMENT);
        menu.addMenuItem(Commands.EDIT_BLOCK_COMMENT);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.SHOW_CODE_HINTS);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_CLOSE_BRACKETS);

        /*
         * View menu
         */
        menu = Menus.addMenu(Strings.VIEW_MENU, Menus.AppMenuBar.VIEW_MENU);
        menu.addMenuItem(Commands.VIEW_HIDE_SIDEBAR);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.VIEW_INCREASE_FONT_SIZE);
        menu.addMenuItem(Commands.VIEW_DECREASE_FONT_SIZE);
        menu.addMenuItem(Commands.VIEW_RESTORE_FONT_SIZE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_ACTIVE_LINE);
        menu.addMenuItem(Commands.TOGGLE_LINE_NUMBERS);
        menu.addMenuItem(Commands.TOGGLE_WORD_WRAP);
        menu.addMenuItem(Commands.FILE_LIVE_HIGHLIGHT);

        /*
         * Navigate menu
         */
        menu = Menus.addMenu(Strings.NAVIGATE_MENU, Menus.AppMenuBar.NAVIGATE_MENU);
        menu.addMenuItem(Commands.NAVIGATE_QUICK_OPEN);
        menu.addMenuItem(Commands.NAVIGATE_GOTO_LINE);
        menu.addMenuItem(Commands.NAVIGATE_GOTO_DEFINITION);
        menu.addMenuItem(Commands.NAVIGATE_JUMPTO_DEFINITION);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.NAVIGATE_NEXT_DOC);
        menu.addMenuItem(Commands.NAVIGATE_PREV_DOC);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.NAVIGATE_SHOW_IN_FILE_TREE);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_QUICK_EDIT);
        menu.addMenuItem(Commands.QUICK_EDIT_PREV_MATCH);
        menu.addMenuItem(Commands.QUICK_EDIT_NEXT_MATCH);
        menu.addMenuDivider();
        menu.addMenuItem(Commands.TOGGLE_QUICK_DOCS);

        /*
         * Help menu
         */
        menu = Menus.addMenu(Strings.HELP_MENU, Menus.AppMenuBar.HELP_MENU);
        menu.addMenuItem(Commands.HELP_CHECK_FOR_UPDATE);

        menu.addMenuDivider();
        if (brackets.config.how_to_use_url) {
            menu.addMenuItem(Commands.HELP_HOW_TO_USE_BRACKETS);
        }
        if (brackets.config.forum_url) {
            menu.addMenuItem(Commands.HELP_FORUM);
        }
        if (brackets.config.release_notes_url) {
            menu.addMenuItem(Commands.HELP_RELEASE_NOTES);
        }
        if (brackets.config.report_issue_url) {
            menu.addMenuItem(Commands.HELP_REPORT_AN_ISSUE);
        }

        menu.addMenuDivider();
        menu.addMenuItem(Commands.HELP_SHOW_EXT_FOLDER);

        var hasAboutItem = (brackets.platform !== "mac" || brackets.inBrowser);

        // Add final divider only if we have a twitter URL or about item
        if (hasAboutItem || brackets.config.twitter_url) {
            menu.addMenuDivider();
        }

        if (brackets.config.twitter_url) {
            menu.addMenuItem(Commands.HELP_TWITTER);
        }
        // supress redundant about menu item in mac shell
        if (hasAboutItem) {
            menu.addMenuItem(Commands.HELP_ABOUT);
        }

        /*
         * Context Menus
         */
        var project_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.PROJECT_MENU);
        project_cmenu.addMenuItem(Commands.FILE_NEW);
        project_cmenu.addMenuItem(Commands.FILE_NEW_FOLDER);
        project_cmenu.addMenuItem(Commands.FILE_RENAME);
        project_cmenu.addMenuItem(Commands.FILE_SAVE_AS);
        project_cmenu.addMenuItem(Commands.FILE_DELETE);
        project_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_OS);
        project_cmenu.addMenuDivider();
        project_cmenu.addMenuItem(Commands.EDIT_FIND_IN_SUBTREE);
        project_cmenu.addMenuDivider();
        project_cmenu.addMenuItem(Commands.FILE_REFRESH);

        var working_set_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.WORKING_SET_MENU);
        working_set_cmenu.addMenuItem(Commands.FILE_CLOSE);
        working_set_cmenu.addMenuItem(Commands.FILE_SAVE);
        working_set_cmenu.addMenuItem(Commands.FILE_SAVE_AS);
        working_set_cmenu.addMenuItem(Commands.FILE_RENAME);
        working_set_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_FILE_TREE);
        working_set_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_OS);
        working_set_cmenu.addMenuDivider();
        working_set_cmenu.addMenuItem(Commands.EDIT_FIND_IN_SUBTREE);
        working_set_cmenu.addMenuDivider();
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_ADDED);
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_NAME);
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_TYPE);
        working_set_cmenu.addMenuDivider();
        working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_AUTO);

        var editor_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.EDITOR_MENU);
        // editor_cmenu.addMenuItem(Commands.NAVIGATE_JUMPTO_DEFINITION);
        editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_EDIT);
        editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_DOCS);
        editor_cmenu.addMenuItem(Commands.EDIT_SELECT_ALL);

        var inline_editor_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.INLINE_EDITOR_MENU);
        inline_editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_EDIT);
        inline_editor_cmenu.addMenuItem(Commands.EDIT_SELECT_ALL);
        inline_editor_cmenu.addMenuDivider();
        inline_editor_cmenu.addMenuItem(Commands.QUICK_EDIT_PREV_MATCH);
        inline_editor_cmenu.addMenuItem(Commands.QUICK_EDIT_NEXT_MATCH);

        /**
         * Context menu for code editors (both full-size and inline)
         * Auto selects the word the user clicks if the click does not occur over
         * an existing selection
         */
        $("#editor-holder").on("contextmenu", function (e) {
            if ($(e.target).parents(".CodeMirror-gutter").length !== 0) {
                return;
            }

            // Note: on mousedown before this event, CodeMirror automatically checks mouse pos, and
            // if not clicking on a selection moves the cursor to click location. When triggered
            // from keyboard, no pre-processing occurs and the cursor/selection is left as is.

            var editor = EditorManager.getFocusedEditor(),
                inlineWidget = EditorManager.getFocusedInlineWidget();

            if (editor) {
                // If there's just an insertion point select the word token at the cursor pos so
                // it's more clear what the context menu applies to.
                if (!editor.hasSelection()) {
                    editor.selectWordAt(editor.getCursorPos());

                    // Prevent menu from overlapping text by moving it down a little
                    // Temporarily backout this change for now to help mitigate issue #1111,
                    // which only happens if mouse is not over context menu. Better fix
                    // requires change to bootstrap, which is too risky for now.
                    //e.pageY += 6;
                }

                // Inline text editors have a different context menu (safe to assume it's not some other
                // type of inline widget since we already know an Editor has focus)
                if (inlineWidget) {
                    inline_editor_cmenu.open(e);
                } else {
                    editor_cmenu.open(e);
                }
            }
        });

        /**
         * Context menus for folder tree & working set list
         */
        $("#project-files-container").on("contextmenu", function (e) {
            project_cmenu.open(e);
        });

        $("#open-files-container").on("contextmenu", function (e) {
            working_set_cmenu.open(e);
        });

        // Prevent the browser context menu since Brackets creates a custom context menu
        $(window).contextmenu(function (e) {
            e.preventDefault();
        });

        /*
         * General menu event processing
         */
        // Prevent clicks on top level menus and menu items from taking focus
        $(window.document).on("mousedown", ".dropdown", function (e) {
            e.preventDefault();
        });

        // Switch menus when the mouse enters an adjacent menu
        // Only open the menu if another one has already been opened
        // by clicking
        $(window.document).on("mouseenter", "#titlebar .dropdown", function (e) {
            var open = $(this).siblings(".open");
            if (open.length > 0) {
                open.removeClass("open");
                $(this).addClass("open");
            }
        });
    });
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Link from 'next/link';
import remark from 'remark';
import github from 'remark-github';
import emoji from 'remark-emoji';
import reactRenderer from 'remark-react';
import { injectIntl, intlShape } from 'react-intl';
import { H1, H3 } from './heading';
import ReleaseWrap from './wrap';
import List from './list';
import ListItem from './item';

const Release = ({ version, notes, date, intl: { formatRelative } }) => (
  <ReleaseWrap>

      <Link href={`https://github.com/mcansh/blog/releases/${version}`}>
        Version {version}
      </Link>

{formatRelative(date)}

    {
      remark()
        .use(reactRenderer, {
          remarkReactComponents: {
            ul: List,
            h3: H3,
            li: ListItem,
          },
        })
        .use(github, {
          repository: 'mcansh/blog',
        })
        .use(emoji)
        .processSync(notes).contents
    }
  </ReleaseWrap>
);

Release.propTypes = {
  version: PropTypes.string.isRequired,
  notes: PropTypes.string.isRequired,
  date: PropTypes.string.isRequired,
  intl: intlShape.isRequired,
};

export default injectIntl(Release);
<commit_msg>swap formatRelative injectted API for component<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Link from 'next/link';
import remark from 'remark';
import github from 'remark-github';
import emoji from 'remark-emoji';
import reactRenderer from 'remark-react';
import { FormattedRelative } from 'react-intl';
import { H1, H3 } from './heading';
import ReleaseWrap from './wrap';
import List from './list';
import ListItem from './item';

const Release = ({ version, notes, date }) => (
  <ReleaseWrap>

      <Link href={`https://github.com/mcansh/blog/releases/${version}`}>
        Version {version}
      </Link>

      <FormattedRelative value={date} />

    {
      remark()
        .use(reactRenderer, {
          remarkReactComponents: {
            ul: List,
            h3: H3,
            li: ListItem,
          },
        })
        .use(github, {
          repository: 'mcansh/blog',
        })
        .use(emoji)
        .processSync(notes).contents
    }
  </ReleaseWrap>
);

Release.propTypes = {
  version: PropTypes.string.isRequired,
  notes: PropTypes.string.isRequired,
  date: PropTypes.string.isRequired,
};

export default Release;
<|endoftext|>


<commit_before>import os from 'os';
import { HTTP } from 'meteor/http';
import { Settings } from '../../../models';
import { settings } from '../../../settings';
import { Info } from '../../../utils';
import { getWorkspaceAccessToken } from '../../../cloud/server';
import { MongoInternals } from 'meteor/mongo';

export default () => {
	try {
		const uniqueID = Settings.findOne('uniqueID');
		const { _oplogHandle } = MongoInternals.defaultRemoteCollectionDriver().mongo;
		const oplogEnabled = _oplogHandle && _oplogHandle.onOplogEntry && settings.get('Force_Disable_OpLog_For_Cache') !== true;

		const data = {
			uniqueId: uniqueID.value,
			installedAt: uniqueID.createdAt,
			version: Info.version,
			oplogEnabled,
			osType: os.type(),
			osPlatform: os.platform(),
			osArch: os.arch(),
			osRelease: os.release(),
			nodeVersion: process.version,
			deployMethod: process.env.DEPLOY_METHOD || 'tar',
			deployPlatform: process.env.DEPLOY_PLATFORM || 'selfinstall',
		};

		const headers = {};
		const token = getWorkspaceAccessToken();
		if (token) {
			headers.Authorization = `Bearer ${ token }`;
		}

		const result = HTTP.get('https://releases.rocket.chat/updates/check', {
			params: data,
			headers,
		});

		return result.data;
	} catch (error) {
		// There's no need to log this error
		// as it's pointless and the user
		// can't do anything about it anyways

		return {
			versions: [],
			alerts: [],
		};
	}
};
<commit_msg>Fix: Error when version check enpoint was returning invalid data (#14089)<commit_after>import os from 'os';
import { HTTP } from 'meteor/http';
import { check, Match } from 'meteor/check';
import { Settings } from '../../../models';
import { settings } from '../../../settings';
import { Info } from '../../../utils';
import { getWorkspaceAccessToken } from '../../../cloud/server';
import { MongoInternals } from 'meteor/mongo';

export default () => {
	try {
		const uniqueID = Settings.findOne('uniqueID');
		const { _oplogHandle } = MongoInternals.defaultRemoteCollectionDriver().mongo;
		const oplogEnabled = _oplogHandle && _oplogHandle.onOplogEntry && settings.get('Force_Disable_OpLog_For_Cache') !== true;

		const params = {
			uniqueId: uniqueID.value,
			installedAt: uniqueID.createdAt,
			version: Info.version,
			oplogEnabled,
			osType: os.type(),
			osPlatform: os.platform(),
			osArch: os.arch(),
			osRelease: os.release(),
			nodeVersion: process.version,
			deployMethod: process.env.DEPLOY_METHOD || 'tar',
			deployPlatform: process.env.DEPLOY_PLATFORM || 'selfinstall',
		};

		const headers = {};
		const token = getWorkspaceAccessToken();
		if (token) {
			headers.Authorization = `Bearer ${ token }`;
		}

		const { data } = HTTP.get('https://releases.rocket.chat/updates/check', {
			params,
			headers,
		});

		check(data, Match.ObjectIncluding({
			versions: [String],
			alerts: Match.Optional([Match.ObjectIncluding({
				id: Match.Optional(String),
				title: Match.Optional(String),
				text: Match.Optional(String),
				textArguments: Match.Optional([Match.Any]),
				modifiers: Match.Optional([String]),
				infoUrl: Match.Optional(String),
			})]),
		}));

		return data;
	} catch (error) {
		// There's no need to log this error
		// as it's pointless and the user
		// can't do anything about it anyways

		return {
			versions: [],
			alerts: [],
		};
	}
};
<|endoftext|>


<commit_before>var express = require('express'),
bodyParser  = require("body-parser"),
request = require('request'),
shim = require.once("../shim.js"),
app = null,
server = null,
platform = null,

sendMessage = function(message, thread) {
	var slackTeams = exports.config.slack_teams,
	thread_components = thread.split('~', 2),
	thread_id = thread_components[0],
	thread_team_id = thread_components[1],
	slack_token = slackTeams[thread_team_id].slack_token;

	if (slack_token != null) {
		var body = {
			"token": slack_token,
			"channel": thread_id,
			"username": exports.config.name,
			"link_names": 1,
			"text": message,
			"unfurl_links": true,
			"icon_url": exports.config.icon
		};

		request({
			"uri": 'https://slack.com/api/chat.postMessage',
			"method": 'GET',
			"qs": body
		},
		function (error, response, body) {
			if (response.statusCode != 200) {
				console.log('error: ' + response.statusCode);
			}
		});
	}
	else {
		console.log('No slack team found!!!');
	}
},

sendFile = function(type, file, description, thread) {
	var slackTeams = exports.config.slack_teams,
	thread_components = thread.split('~', 2),
	thread_id = thread_components[0],
	thread_team_id = thread_components[1],
	slack_token = slackTeams[thread_team_id].slack_token;

	if (slack_token != null) {
		var body = {
			"token": slack_token,
			"channel": thread_id,
			"file": file,
			"filetype": type,
			"title": description
		};

		request({
			"uri": 'https://slack.com/api/files.upload',
			"method": 'GET',
			"qs": body
		},
		function (error, response, body) {
			if (response.statusCode != 200) {
				console.log('error: ' + response.statusCode);
			}
		});
	}
	else {
		console.log('No slack team found!!!');
	}
},

renameChannel = function(title, thread) {
	var slackTeams = exports.config.slack_teams,
	thread_components = thread.split('~', 2),
	thread_id = thread_components[0],
	thread_team_id = thread_components[1],
	slack_token = slackTeams[thread_team_id].slack_token;

	if (slack_token != null) {
		var body = {
			"token": slack_token,
			"channel": thread_id,
			"name": title
		};

		request({
			"uri": 'https://slack.com/api/channels.rename',
			"method": 'GET',
			"qs": body
		},
		function (error, response, body) {
			if (response.statusCode != 200) {
				console.log('error: ' + response.statusCode);
			}
		});
	}
	else {
		console.log('No slack team found!!!');
	}
},

getUsers = function(slackTeam) {
	var body = {"token": slackTeam.slack_token},
	userMap = [];
	request({
		"uri": 'https://slack.com/api/users.list',
		"method": 'GET',
		"qs": body
	},
	function (error, response, body) {
		body = JSON.parse(body);
		if (response.statusCode != 200 || body.ok == false) {
			console.log('failed to get list of users');
		}
		else {
			for (var i = 0; i < body.members.length; i++) {
				userMap[body.members[i].id] = body.members[i].name
			}
			slackTeam.users = userMap;
		}
	});
},

lookUpUserAddToTeam = function(slackTeam, userId, match, message, callback) {
	var body = {"token": slackTeam.slack_token, "user": userId},
	userMap = [];
	request({
		"uri": 'https://slack.com/api/users.info',
		"method": 'GET',
		"qs": body
	},
	function (error, response, body) {
		body = JSON.parse(body);
		if (response.statusCode != 200) {
			console.log('error: ' + response.statusCode + '\n' + error);
			return message
		}
		else {
			slackTeam.users[body.user.id] = body.user.name;
			return callback(body.user.name, message, match);
		}
	});
},

replaceUserIdWithUserName = function(userName, message, match) {
	if (userName) {
		var index = message.indexOf(match);
		return message.substr(0, index) + userName + message.substr(index + match.length);
	}
};

exports.start = function (callback) {
	var slackTeams = exports.config.slack_teams,
	slack_token = null;
	app = express();
	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({ extended: true }));

	platform = shim.createPlatformModule({
		commandPrefix: exports.config.commandPrefix,
		sendMessage: sendMessage,
		sendFile: sendFile,
		setTitle: renameChannel
	});

	for (teamId in slackTeams) {
		getUsers(slackTeams[teamId]);
	}

	app.post('/', function (req, res) {
		var data = req.body,
		event = [],
		message = data.text.trim(),
		shimMessage = null;

		if (data.user_name != 'slackbot') {
			// Check that the message sent contains a identifier
			// TODO: need to check that regex is correct?
			var matches = message.match(/<?@[^:>]+>:?/g);
			if (matches != null) {
				var slackTeams = exports.config.slack_teams,
				userName,
				id,
				slackTeam = slackTeams[data.team_id];

				if (slackTeam) {

					for (var j = 0; j < matches.length; j++) {
						// replace identifier with empty string
						id = matches[j].replace(/[ :<>@]+/g, '');

						// find the user
						userName = slackTeam.users[id];
						if (!userName) {
							// query slack to see if the user is in the team, they may have been added recently
							message = lookUpUserAddToTeam(slackTeam, id, matches[j], message, replaceUserIdWithUserName);
						}
						else {
							message = replaceUserIdWithUserName(userName, message, matches[j]);
						}
					}
				}
				else {
					console.log('No slack team found matching: ' + data.team_id);
				}
			}

			event.body = message;
			event.threadID = data.channel_id + '~' + data.team_id;
			event.senderID = data.user_id;
			event.senderName = data.user_name;

			shimMessage = shim.createEvent(event.threadID, event.senderID, event.senderName, event.body);
			callback(platform, shimMessage);
		}
		res.sendStatus(200);
	});
	server = app.listen(this.config.port);
};

exports.stop = function() {
	var slackTeams = exports.config.slack_teams;

	server.close();
	server = null;
	app = null;
	platform = null;
};
<commit_msg>hotfix old slack integration in master<commit_after>var express = require('express'),
bodyParser  = require("body-parser"),
request = require('request'),
shim = require.once("../shim.js"),
app = null,
server = null,
platform = null,

sendMessage = function(message, thread) {
	var slackTeams = exports.config.slack_teams,
	thread_components = thread.split('~', 2),
	thread_id = thread_components[0],
	thread_team_id = thread_components[1],
	slack_token = slackTeams[thread_team_id].slack_token;

	if (slack_token != null) {
		var body = {
			"token": slack_token,
			"channel": thread_id,
			"username": exports.config.name,
			"link_names": 1,
			"text": message,
			"unfurl_links": true,
			"icon_url": exports.config.icon
		};

		request({
			"uri": 'https://slack.com/api/chat.postMessage',
			"method": 'GET',
			"qs": body
		},
		function (error, response, body) {
			if (response.statusCode != 200) {
				console.log('error: ' + response.statusCode);
			}
		});
	}
	else {
		console.log('No slack team found!!!');
	}
},

sendFile = function(type, file, description, thread) {
	var slackTeams = exports.config.slack_teams,
	thread_components = thread.split('~', 2),
	thread_id = thread_components[0],
	thread_team_id = thread_components[1],
	slack_token = slackTeams[thread_team_id].slack_token;

	if (slack_token != null) {
		var body = {
			"token": slack_token,
			"channel": thread_id,
			"file": file,
			"filetype": type,
			"title": description
		};

		request({
			"uri": 'https://slack.com/api/files.upload',
			"method": 'GET',
			"qs": body
		},
		function (error, response, body) {
			if (response.statusCode != 200) {
				console.log('error: ' + response.statusCode);
			}
		});
	}
	else {
		console.log('No slack team found!!!');
	}
},

renameChannel = function(title, thread) {
	var slackTeams = exports.config.slack_teams,
	thread_components = thread.split('~', 2),
	thread_id = thread_components[0],
	thread_team_id = thread_components[1],
	slack_token = slackTeams[thread_team_id].slack_token;

	if (slack_token != null) {
		var body = {
			"token": slack_token,
			"channel": thread_id,
			"name": title
		};

		request({
			"uri": 'https://slack.com/api/channels.rename',
			"method": 'GET',
			"qs": body
		},
		function (error, response, body) {
			if (response.statusCode != 200) {
				console.log('error: ' + response.statusCode);
			}
		});
	}
	else {
		console.log('No slack team found!!!');
	}
},

getUsers = function(slackTeam) {
	var body = {"token": slackTeam.slack_token},
	userMap = [];
	request({
		"uri": 'https://slack.com/api/users.list',
		"method": 'GET',
		"qs": body
	},
	function (error, response, body) {
		body = JSON.parse(body);
		if (response.statusCode != 200 || body.ok == false) {
			console.log('failed to get list of users');
		}
		else {
			for (var i = 0; i < body.members.length; i++) {
				userMap[body.members[i].id] = body.members[i].name
			}
			slackTeam.users = userMap;
		}
	});
},

lookUpUserAddToTeam = function(slackTeam, userId, match, message, callback) {
	var body = {"token": slackTeam.slack_token, "user": userId},
	userMap = [];
	request({
		"uri": 'https://slack.com/api/users.info',
		"method": 'GET',
		"qs": body
	},
	function (error, response, body) {
		body = JSON.parse(body);
		if (response.statusCode != 200) {
			console.log('error: ' + response.statusCode + '\n' + error);
			return message
		}
		else {
			slackTeam.users[body.user.id] = body.user.name;
			return callback(body.user.name, message, match);
		}
	});
},

replaceUserIdWithUserName = function(userName, message, match) {
	if (userName) {
		var index = message.indexOf(match);
		return message.substr(0, index) + userName + message.substr(index + match.length);
	}
};

exports.start = function (callback) {
	var slackTeams = exports.config.slack_teams,
	slack_token = null;
	app = express();
	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({ extended: true }));

	platform = shim.createPlatformModule({
		commandPrefix: exports.config.commandPrefix,
		sendMessage: sendMessage,
		sendFile: sendFile,
		setTitle: renameChannel
	});

	for (var i = 0; i < slackTeams.length; i++) {
		getUsers(slackTeams[i]);
	}

	app.post('/', function (req, res) {
		var data = JSON.parse(req.body),
		event = [],
		message = data.text.trim(),
		shimMessage = null;

		if (data.user_name != 'slackbot') {
			// Check that the message sent contains a identifier
			// TODO: need to check that regex is correct?
			var matches = message.match(/<?@[^:>]+>:?/g);
			if (matches != null) {
				var slackTeams = exports.config.slack_teams,
				userName,
				id,
				slackTeam = slackTeams[data.team_id];

				if (slackTeam) {

					for (var j = 0; j < matches.length; j++) {
						// replace identifier with empty string
						id = matches[j].replace(/[ :<>@]+/g, '');

						// find the user
						userName = slackTeam.users[id];
						if (!userName) {
							// query slack to see if the user is in the team, they may have been added recently
							message = lookUpUserAddToTeam(slackTeam, id, matches[j], message, replaceUserIdWithUserName);
						}
						else {
							message = replaceUserIdWithUserName(userName, message, matches[j]);
						}
					}
				}
				else {
					console.log('No slack team found matching: ' + data.team_id);
				}
			}

			event.body = message;
			event.threadID = data.channel_id + '~' + data.team_id;
			event.senderID = data.user_id;
			event.senderName = data.user_name;

			shimMessage = shim.createEvent(event.threadID, event.senderID, event.senderName, event.body);
			callback(platform, shimMessage);
		}
		res.sendStatus(200);
	});
	server = app.listen(this.config.port);
};

exports.stop = function() {
	var slackTeams = exports.config.slack_teams;

	server.close();
	server = null;
	app = null;
	platform = null;
};
<|endoftext|>


<commit_before>grunt.initConfig({
	meta: {
		banner: "/*! Tetra.js v<%= pkg.version %> | (MIT Licence) (c) Viadeo/APVO Corp */"
	},
	build: {
		'dist/tetra.js': [
			"lib/tetra.js",
			"lib/deps/require.js",
			"lib/mod/require/client.js",
			"lib/mod/tmpl/client-micro-tmpl.js",
			"lib/tetra-view.js",
			"lib/tetra-controller.js",
			"lib/tetra-model.js",
			"lib/conf/default.js"
		],
		'dist/tetra-viadeo.js': [
			"lib/tetra.js",
			"lib/deps/sizzle.js",
			"lib/deps/mod/libAbstracted/jquery-connector.js",
			"lib/deps/mod/libAbstracted/prototype-connector.js",
			"lib/deps/mod/libAbstracted/builder.js",
			"lib/deps/require.js",
			"lib/mod/require/client.js",
			"lib/mod/tmpl/client-micro-tmpl.js",
			"lib/tetra-view.js",
			"lib/tetra-controller.js",
			"lib/tetra-model.js",
			"lib/conf/viadeo-webapp.js"
		]
	},
	min: {
		'dist/tetra.min.js': ['<banner>', 'dist/tetra.js'],
		'dist/tetra-viadeo.min.js': ['<banner>', 'dist/tetra-viadeo.js']
	},
	watch: {
		files: ["lib/*.js"],
		tasks: 'default'
	}
});

// Default task.
grunt.registerTask('default', 'concat min watch');<commit_msg>Add module.exports to grunt.js<commit_after>module.exports = function( grunt ) {
	grunt.initConfig({
		meta: {
			banner: "/*! Tetra.js v<%= pkg.version %> | (MIT Licence) (c) Viadeo/APVO Corp */"
		},
		build: {
			'dist/tetra.js': [
				"lib/tetra.js",
				"lib/deps/require.js",
				"lib/mod/require/client.js",
				"lib/mod/tmpl/client-micro-tmpl.js",
				"lib/tetra-view.js",
				"lib/tetra-controller.js",
				"lib/tetra-model.js",
				"lib/conf/default.js"
			],
			'dist/tetra-viadeo.js': [
				"lib/tetra.js",
				"lib/deps/sizzle.js",
				"lib/deps/mod/libAbstracted/jquery-connector.js",
				"lib/deps/mod/libAbstracted/prototype-connector.js",
				"lib/deps/mod/libAbstracted/builder.js",
				"lib/deps/require.js",
				"lib/mod/require/client.js",
				"lib/mod/tmpl/client-micro-tmpl.js",
				"lib/tetra-view.js",
				"lib/tetra-controller.js",
				"lib/tetra-model.js",
				"lib/conf/viadeo-webapp.js"
			]
		},
		min: {
			'dist/tetra.min.js': ['<banner>', 'dist/tetra.js'],
			'dist/tetra-viadeo.min.js': ['<banner>', 'dist/tetra-viadeo.js']
		},
		watch: {
			files: ["lib/*.js"],
			tasks: 'default'
		}
	});

	// Default task.
	grunt.registerTask('default', 'concat min watch');
};<|endoftext|>


<commit_before>import React, { useState } from 'react';
import { t } from 'ttag';
import gql from 'graphql-tag';
import { useMutation } from '@apollo/react-hooks';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import {
  Tabs,
  Tab,
  Box,
  Popover,
  Typography,
  SvgIcon,
} from '@material-ui/core';
import Snackbar from '@material-ui/core/Snackbar';
import CloseIcon from '@material-ui/icons/Close';
import Avatar from 'components/AppLayout/Widgets/Avatar';
import useCurrentUser from 'lib/useCurrentUser';
import cx from 'clsx';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
  },
  vote: {
    display: 'flex',
    alignItems: 'center',
    borderRadius: 45,
    padding: '1px 8px',
    marginRight: 3,
    outline: 'none',
    cursor: 'pointer',
    border: `1px solid ${theme.palette.secondary[100]}`,
    color: theme.palette.secondary[100],
    background: theme.palette.common.white,
    [theme.breakpoints.up('md')]: {
      padding: '4px 18px',
      marginRight: 10,
    },
  },
  voted: {
    border: `1px solid ${theme.palette.primary[500]}`,
    color: theme.palette.primary[500],
  },
  buttonGroup: {
    display: 'flex',
    alignItems: 'center',
    whiteSpace: 'nowrap',
    '& $vote': {
      marginRight: 0,
      display: 'inline-flex',
      color: theme.palette.secondary[200],
      background: theme.palette.secondary[50],
      '& img': {
        paddingLeft: 6,
      },
      '&:first-child': {
        borderTopRightRadius: 0,
        borderBottomRightRadius: 0,
        borderRight: 0,
        paddingRight: 0,
      },
      '&:last-child': {
        borderTopLeftRadius: 0,
        borderBottomLeftRadius: 0,
      },
      '&:not(:first-child):not(:last-child)': {
        borderRadius: 0,
        borderLeft: 0,
        borderRight: 0,
      },
    },
  },
  popover: {
    position: 'relative',
    width: 420,
    maxWidth: '90vw',
    padding: 32,
  },
  closeButton: {
    background: theme.palette.common.white,
    cursor: 'pointer',
    position: 'absolute',
    right: 6,
    top: 10,
    border: 'none',
    outline: 'none',
    color: theme.palette.secondary[100],
  },
  feedbacks: {
    marginTop: 16,
    maxHeight: 300,
    overflow: 'auto',
  },
  popupTitle: {
    fontSize: 18,
    marginBottom: 24,
  },
  textarea: {
    padding: 15,
    width: '100%',
    borderRadius: 8,
    border: `1px solid ${theme.palette.secondary[100]}`,
    outline: 'none',
    '&:focus': {
      border: `1px solid ${theme.palette.primary[500]}`,
    },
  },
  textCenter: { textAlign: 'center' },
  sendButton: {
    outline: 'none',
    border: 'none',
    marginTop: 10,
    padding: '10px 25px',
    background: theme.palette.primary[500],
    color: theme.palette.common.white,
    cursor: 'pointer',
    borderRadius: 30,
    '&:disabled': {
      opacity: 0.7,
      cursor: 'not-allowed',
    },
  },
}));

const ThumbUpIcon = props => (
  <SvgIcon {...props} viewBox="0 0 17 15">
    <path d="M1 13.8672H3.65455V6.51612H1V13.8672ZM15.6 7.1287C15.6 6.45486 15.0027 5.90353 14.2727 5.90353H10.0852L10.7156 3.10401L10.7355 2.90798C10.7355 2.65682 10.6227 2.42403 10.4435 2.25863L9.74009 1.61542L5.37336 5.65237C5.12782 5.8729 4.98182 6.17919 4.98182 6.51612V12.642C4.98182 13.3158 5.57909 13.8672 6.30909 13.8672H12.2818C12.8326 13.8672 13.3038 13.5609 13.5029 13.1198L15.5071 8.80107C15.5668 8.66017 15.6 8.51315 15.6 8.35388V7.1287Z" />
  </SvgIcon>
);

const ThumbDownIcon = props => (
  <SvgIcon {...props} viewBox="0 0 17 15">
    <path d="M10.2909 1.46155H4.31818C3.76736 1.46155 3.29618 1.76784 3.09709 2.2089L1.09291 6.52765C1.03318 6.66854 1 6.81556 1 6.97483V8.20001C1 8.87386 1.59727 9.42518 2.32727 9.42518H6.51482L5.88436 12.2247L5.86445 12.4207C5.86445 12.6719 5.97727 12.9047 6.15646 13.0701L6.85991 13.7133L11.2333 9.67635C11.4722 9.45581 11.6182 9.14952 11.6182 8.8126V2.68672C11.6182 2.01288 11.0209 1.46155 10.2909 1.46155ZM12.9455 1.46155V8.8126H15.6V1.46155H12.9455Z" />
  </SvgIcon>
);
const CustomTab = withStyles({
  root: {
    position: 'relative',
    minHeight: 0,
  },
  wrapper: {
    '& > svg': {
      position: 'absolute',
      left: 0,
    },
  },
})(Tab);

const Feedback = withStyles(theme => ({
  root: {
    marginTop: 16,
    display: 'flex',
    borderBottom: `1px solid ${theme.palette.secondary[100]}`,
    alignItems: ({ comment }) => (comment ? 'flex-start' : 'center'),
    paddingBottom: 10,
  },
  name: {
    color: ({ comment }) =>
      comment ? theme.palette.primary[500] : theme.palette.secondary[300],
  },
}))(({ comment, user, classes }) => (

    <Avatar user={user} size={48} />
    <Box px={2}>

{user.name}

{comment}

    </Box>

));

// Subset of fields that needs to be updated after login
//
const ArticleReplyFeedbackForUser = gql`
  fragment ArticleReplyFeedbackForUser on ArticleReply {
    articleId
    replyId
    ownVote
  }
`;

const ArticleReplyFeedbackData = gql`
  fragment ArticleReplyFeedbackData on ArticleReply {
    ...ArticleReplyFeedbackForUser
    positiveFeedbackCount
    negativeFeedbackCount
    ownVote
    feedbacks {
      id
      user {
        id
        name
        avatarUrl
      }
      comment
    }
  }
  ${ArticleReplyFeedbackForUser}
`;

const CREATE_REPLY_FEEDBACK = gql`
  mutation CreateOrUpdateArticleReplyFeedback(
    $articleId: String!
    $replyId: String!
    $vote: FeedbackVote!
    $comment: String
  ) {
    CreateOrUpdateArticleReplyFeedback(
      articleId: $articleId
      replyId: $replyId
      vote: $vote
      comment: $comment
    ) {
      ...ArticleReplyFeedbackData
    }
  }
  ${ArticleReplyFeedbackData}
`;

function ReplyFeedback({
  articleId,
  replyId,
  positiveFeedbackCount,
  negativeFeedbackCount,
  ownVote,
  feedbacks = [],
  reply = {},
  className,
}) {
  const { user, text } = reply;

  const [vote, setVote] = useState(null);
  const [reason, setReason] = useState('');
  const [reasonsPopoverAnchorEl, setReasonsPopoverAnchorEl] = useState(null);
  const [votePopoverAnchorEl, setVotePopoverAnchorEl] = useState(null);
  const [tab, setTab] = useState(0);
  const [showReorderSnack, setReorderSnackShow] = useState(false);
  const currentUser = useCurrentUser();
  const [createReplyFeedback, { loading: updatingReplyFeedback }] = useMutation(
    CREATE_REPLY_FEEDBACK,
    {
      refetchQueries: ['LoadArticlePage'], // Update article reply order
      awaitRefetchQueries: true,
      onCompleted() {
        closeVotePopover();
        setReason('');
        setReorderSnackShow(true);
      },
    }
  );

  const openReasonsPopover = event => {
    setReasonsPopoverAnchorEl(event.currentTarget);
  };

  const closeReasonsPopover = () => {
    setReasonsPopoverAnchorEl(null);
  };

  const openVotePopover = (event, value) => {
    setVotePopoverAnchorEl(event.currentTarget);
    setVote(value);
  };

  const closeVotePopover = () => {
    setVotePopoverAnchorEl(null);
    setVote(null);
  };

  const classes = useStyles();

  // Note that currentUser and user may be undefined or null (when appId mismatch)
  // Both case should not consider as ownArticleReply
  //
  const isOwnArticleReply = currentUser && user && currentUser.id === user.id;

  return (

      <button
        className={cx(classes.vote, ownVote === 'UPVOTE' && classes.voted)}
        type="button"
        onClick={e => openVotePopover(e, 'UPVOTE')}
      >
        <ThumbUpIcon />
      </button>
      <button
        className={cx(classes.vote, ownVote === 'DOWNVOTE' && classes.voted)}
        type="button"
        onClick={e => openVotePopover(e, 'DOWNVOTE')}
      >
        <ThumbDownIcon />
      </button>

        <button className={classes.vote} type="button">
          {positiveFeedbackCount}
          <ThumbUpIcon style={{ fontSize: 16, margin: '0 2px' }} />
        </button>
        <button className={classes.vote} type="button">
          {negativeFeedbackCount}
          <ThumbDownIcon style={{ fontSize: 16, margin: '0 2px' }} />
        </button>
        <button
          className={classes.vote}
          type="button"
          onClick={openReasonsPopover}
        >
          {t`See Reasons`}
        </button>

      <Popover
        id={`reply-reasons-${reply.id}`}
        open={!!reasonsPopoverAnchorEl}
        anchorEl={reasonsPopoverAnchorEl}
        onClose={closeReasonsPopover}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        classes={{ paper: classes.popover }}
      >
        <button
          type="button"
          className={classes.closeButton}
          onClick={closeReasonsPopover}
        >
          <CloseIcon />
        </button>
        {text}
        <Tabs
          value={tab}
          onChange={(e, value) => setTab(value)}
          indicatorColor="primary"
          textColor="primary"
          variant="fullWidth"
        >
          <CustomTab
            icon={<ThumbUpIcon />}
            label={t`Helpful ${positiveFeedbackCount}`}
          />
          <CustomTab
            icon={<ThumbDownIcon />}
            label={t`Not Helpful ${negativeFeedbackCount}`}
          />
        </Tabs>
        <Box
          display={tab === 0 ? 'block' : 'none'}
          className={classes.feedbacks}
        >
          {feedbacks
            .filter(({ vote, user }) => vote === 'UPVOTE' && user)
            .map(feedback => (
              <Feedback key={feedback.id} {...feedback} />
            ))}
        </Box>
        <Box
          display={tab === 1 ? 'block' : 'none'}
          className={classes.feedbacks}
        >
          {feedbacks
            .filter(({ vote, user }) => vote === 'DOWNVOTE' && user)
            .map(feedback => (
              <Feedback key={feedback.id} {...feedback} />
            ))}
        </Box>
      </Popover>
      <Popover
        id={`feedback-reasons-${reply.id}`}
        open={!!votePopoverAnchorEl}
        anchorEl={votePopoverAnchorEl}
        onClose={closeVotePopover}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        classes={{ paper: classes.popover }}
      >
        <button
          type="button"
          className={classes.closeButton}
          onClick={closeVotePopover}
        >
          <CloseIcon />
        </button>
        <Typography
          className={classes.popupTitle}
        >{t`The reason why you upvote/downvote:`}</Typography>
        <textarea
          className={classes.textarea}
          value={reason}
          onChange={e => setReason(e.target.value)}
          rows={10}
        />

          <button
            type="button"
            className={classes.sendButton}
            disabled={isOwnArticleReply || updatingReplyFeedback}
            onClick={() => {
              createReplyFeedback({
                variables: { articleId, replyId, vote, comment: reason },
              });
            }}
          >{t`Send`}</button>

      </Popover>
      <Snackbar
        open={showReorderSnack}
        onClose={() => setReorderSnackShow(false)}
        message={t`Thank you for the feedback.`}
      ></Snackbar>

  );
}

ReplyFeedback.fragments = {
  ArticleReplyFeedbackData,
  ArticleReplyFeedbackForUser,
};

export default ReplyFeedback;
<commit_msg>Add missing field in gql query<commit_after>import React, { useState } from 'react';
import { t } from 'ttag';
import gql from 'graphql-tag';
import { useMutation } from '@apollo/react-hooks';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import {
  Tabs,
  Tab,
  Box,
  Popover,
  Typography,
  SvgIcon,
} from '@material-ui/core';
import Snackbar from '@material-ui/core/Snackbar';
import CloseIcon from '@material-ui/icons/Close';
import Avatar from 'components/AppLayout/Widgets/Avatar';
import useCurrentUser from 'lib/useCurrentUser';
import cx from 'clsx';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
  },
  vote: {
    display: 'flex',
    alignItems: 'center',
    borderRadius: 45,
    padding: '1px 8px',
    marginRight: 3,
    outline: 'none',
    cursor: 'pointer',
    border: `1px solid ${theme.palette.secondary[100]}`,
    color: theme.palette.secondary[100],
    background: theme.palette.common.white,
    [theme.breakpoints.up('md')]: {
      padding: '4px 18px',
      marginRight: 10,
    },
  },
  voted: {
    border: `1px solid ${theme.palette.primary[500]}`,
    color: theme.palette.primary[500],
  },
  buttonGroup: {
    display: 'flex',
    alignItems: 'center',
    whiteSpace: 'nowrap',
    '& $vote': {
      marginRight: 0,
      display: 'inline-flex',
      color: theme.palette.secondary[200],
      background: theme.palette.secondary[50],
      '& img': {
        paddingLeft: 6,
      },
      '&:first-child': {
        borderTopRightRadius: 0,
        borderBottomRightRadius: 0,
        borderRight: 0,
        paddingRight: 0,
      },
      '&:last-child': {
        borderTopLeftRadius: 0,
        borderBottomLeftRadius: 0,
      },
      '&:not(:first-child):not(:last-child)': {
        borderRadius: 0,
        borderLeft: 0,
        borderRight: 0,
      },
    },
  },
  popover: {
    position: 'relative',
    width: 420,
    maxWidth: '90vw',
    padding: 32,
  },
  closeButton: {
    background: theme.palette.common.white,
    cursor: 'pointer',
    position: 'absolute',
    right: 6,
    top: 10,
    border: 'none',
    outline: 'none',
    color: theme.palette.secondary[100],
  },
  feedbacks: {
    marginTop: 16,
    maxHeight: 300,
    overflow: 'auto',
  },
  popupTitle: {
    fontSize: 18,
    marginBottom: 24,
  },
  textarea: {
    padding: 15,
    width: '100%',
    borderRadius: 8,
    border: `1px solid ${theme.palette.secondary[100]}`,
    outline: 'none',
    '&:focus': {
      border: `1px solid ${theme.palette.primary[500]}`,
    },
  },
  textCenter: { textAlign: 'center' },
  sendButton: {
    outline: 'none',
    border: 'none',
    marginTop: 10,
    padding: '10px 25px',
    background: theme.palette.primary[500],
    color: theme.palette.common.white,
    cursor: 'pointer',
    borderRadius: 30,
    '&:disabled': {
      opacity: 0.7,
      cursor: 'not-allowed',
    },
  },
}));

const ThumbUpIcon = props => (
  <SvgIcon {...props} viewBox="0 0 17 15">
    <path d="M1 13.8672H3.65455V6.51612H1V13.8672ZM15.6 7.1287C15.6 6.45486 15.0027 5.90353 14.2727 5.90353H10.0852L10.7156 3.10401L10.7355 2.90798C10.7355 2.65682 10.6227 2.42403 10.4435 2.25863L9.74009 1.61542L5.37336 5.65237C5.12782 5.8729 4.98182 6.17919 4.98182 6.51612V12.642C4.98182 13.3158 5.57909 13.8672 6.30909 13.8672H12.2818C12.8326 13.8672 13.3038 13.5609 13.5029 13.1198L15.5071 8.80107C15.5668 8.66017 15.6 8.51315 15.6 8.35388V7.1287Z" />
  </SvgIcon>
);

const ThumbDownIcon = props => (
  <SvgIcon {...props} viewBox="0 0 17 15">
    <path d="M10.2909 1.46155H4.31818C3.76736 1.46155 3.29618 1.76784 3.09709 2.2089L1.09291 6.52765C1.03318 6.66854 1 6.81556 1 6.97483V8.20001C1 8.87386 1.59727 9.42518 2.32727 9.42518H6.51482L5.88436 12.2247L5.86445 12.4207C5.86445 12.6719 5.97727 12.9047 6.15646 13.0701L6.85991 13.7133L11.2333 9.67635C11.4722 9.45581 11.6182 9.14952 11.6182 8.8126V2.68672C11.6182 2.01288 11.0209 1.46155 10.2909 1.46155ZM12.9455 1.46155V8.8126H15.6V1.46155H12.9455Z" />
  </SvgIcon>
);
const CustomTab = withStyles({
  root: {
    position: 'relative',
    minHeight: 0,
  },
  wrapper: {
    '& > svg': {
      position: 'absolute',
      left: 0,
    },
  },
})(Tab);

const Feedback = withStyles(theme => ({
  root: {
    marginTop: 16,
    display: 'flex',
    borderBottom: `1px solid ${theme.palette.secondary[100]}`,
    alignItems: ({ comment }) => (comment ? 'flex-start' : 'center'),
    paddingBottom: 10,
  },
  name: {
    color: ({ comment }) =>
      comment ? theme.palette.primary[500] : theme.palette.secondary[300],
  },
}))(({ comment, user, classes }) => (

    <Avatar user={user} size={48} />
    <Box px={2}>

{user.name}

{comment}

    </Box>

));

// Subset of fields that needs to be updated after login
//
const ArticleReplyFeedbackForUser = gql`
  fragment ArticleReplyFeedbackForUser on ArticleReply {
    articleId
    replyId
    ownVote
  }
`;

const ArticleReplyFeedbackData = gql`
  fragment ArticleReplyFeedbackData on ArticleReply {
    ...ArticleReplyFeedbackForUser
    positiveFeedbackCount
    negativeFeedbackCount
    ownVote
    feedbacks {
      id
      comment
      vote
      user {
        id
        name
        avatarUrl
      }
    }
  }
  ${ArticleReplyFeedbackForUser}
`;

const CREATE_REPLY_FEEDBACK = gql`
  mutation CreateOrUpdateArticleReplyFeedback(
    $articleId: String!
    $replyId: String!
    $vote: FeedbackVote!
    $comment: String
  ) {
    CreateOrUpdateArticleReplyFeedback(
      articleId: $articleId
      replyId: $replyId
      vote: $vote
      comment: $comment
    ) {
      ...ArticleReplyFeedbackData
    }
  }
  ${ArticleReplyFeedbackData}
`;

function ReplyFeedback({
  articleId,
  replyId,
  positiveFeedbackCount,
  negativeFeedbackCount,
  ownVote,
  feedbacks = [],
  reply = {},
  className,
}) {
  const { user, text } = reply;

  const [vote, setVote] = useState(null);
  const [reason, setReason] = useState('');
  const [reasonsPopoverAnchorEl, setReasonsPopoverAnchorEl] = useState(null);
  const [votePopoverAnchorEl, setVotePopoverAnchorEl] = useState(null);
  const [tab, setTab] = useState(0);
  const [showReorderSnack, setReorderSnackShow] = useState(false);
  const currentUser = useCurrentUser();
  const [createReplyFeedback, { loading: updatingReplyFeedback }] = useMutation(
    CREATE_REPLY_FEEDBACK,
    {
      refetchQueries: ['LoadArticlePage'], // Update article reply order
      awaitRefetchQueries: true,
      onCompleted() {
        closeVotePopover();
        setReason('');
        setReorderSnackShow(true);
      },
    }
  );

  const openReasonsPopover = event => {
    setReasonsPopoverAnchorEl(event.currentTarget);
  };

  const closeReasonsPopover = () => {
    setReasonsPopoverAnchorEl(null);
  };

  const openVotePopover = (event, value) => {
    setVotePopoverAnchorEl(event.currentTarget);
    setVote(value);
  };

  const closeVotePopover = () => {
    setVotePopoverAnchorEl(null);
    setVote(null);
  };

  const classes = useStyles();

  // Note that currentUser and user may be undefined or null (when appId mismatch)
  // Both case should not consider as ownArticleReply
  //
  const isOwnArticleReply = currentUser && user && currentUser.id === user.id;

  return (

      <button
        className={cx(classes.vote, ownVote === 'UPVOTE' && classes.voted)}
        type="button"
        onClick={e => openVotePopover(e, 'UPVOTE')}
      >
        <ThumbUpIcon />
      </button>
      <button
        className={cx(classes.vote, ownVote === 'DOWNVOTE' && classes.voted)}
        type="button"
        onClick={e => openVotePopover(e, 'DOWNVOTE')}
      >
        <ThumbDownIcon />
      </button>

        <button className={classes.vote} type="button">
          {positiveFeedbackCount}
          <ThumbUpIcon style={{ fontSize: 16, margin: '0 2px' }} />
        </button>
        <button className={classes.vote} type="button">
          {negativeFeedbackCount}
          <ThumbDownIcon style={{ fontSize: 16, margin: '0 2px' }} />
        </button>
        <button
          className={classes.vote}
          type="button"
          onClick={openReasonsPopover}
        >
          {t`See Reasons`}
        </button>

      <Popover
        id={`reply-reasons-${reply.id}`}
        open={!!reasonsPopoverAnchorEl}
        anchorEl={reasonsPopoverAnchorEl}
        onClose={closeReasonsPopover}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        classes={{ paper: classes.popover }}
      >
        <button
          type="button"
          className={classes.closeButton}
          onClick={closeReasonsPopover}
        >
          <CloseIcon />
        </button>
        {text}
        <Tabs
          value={tab}
          onChange={(e, value) => setTab(value)}
          indicatorColor="primary"
          textColor="primary"
          variant="fullWidth"
        >
          <CustomTab
            icon={<ThumbUpIcon />}
            label={t`Helpful ${positiveFeedbackCount}`}
          />
          <CustomTab
            icon={<ThumbDownIcon />}
            label={t`Not Helpful ${negativeFeedbackCount}`}
          />
        </Tabs>
        <Box
          display={tab === 0 ? 'block' : 'none'}
          className={classes.feedbacks}
        >
          {feedbacks
            .filter(({ vote, user }) => vote === 'UPVOTE' && user)
            .map(feedback => (
              <Feedback key={feedback.id} {...feedback} />
            ))}
        </Box>
        <Box
          display={tab === 1 ? 'block' : 'none'}
          className={classes.feedbacks}
        >
          {feedbacks
            .filter(({ vote, user }) => vote === 'DOWNVOTE' && user)
            .map(feedback => (
              <Feedback key={feedback.id} {...feedback} />
            ))}
        </Box>
      </Popover>
      <Popover
        id={`feedback-reasons-${reply.id}`}
        open={!!votePopoverAnchorEl}
        anchorEl={votePopoverAnchorEl}
        onClose={closeVotePopover}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        classes={{ paper: classes.popover }}
      >
        <button
          type="button"
          className={classes.closeButton}
          onClick={closeVotePopover}
        >
          <CloseIcon />
        </button>
        <Typography
          className={classes.popupTitle}
        >{t`The reason why you upvote/downvote:`}</Typography>
        <textarea
          className={classes.textarea}
          value={reason}
          onChange={e => setReason(e.target.value)}
          rows={10}
        />

          <button
            type="button"
            className={classes.sendButton}
            disabled={isOwnArticleReply || updatingReplyFeedback}
            onClick={() => {
              createReplyFeedback({
                variables: { articleId, replyId, vote, comment: reason },
              });
            }}
          >{t`Send`}</button>

      </Popover>
      <Snackbar
        open={showReorderSnack}
        onClose={() => setReorderSnackShow(false)}
        message={t`Thank you for the feedback.`}
      ></Snackbar>

  );
}

ReplyFeedback.fragments = {
  ArticleReplyFeedbackData,
  ArticleReplyFeedbackForUser,
};

export default ReplyFeedback;
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------------------------
// all about main circle
// ---------------------------------------------------------------------------------------

function CircleLib( elementID)
{
	this.element = null;
	this.clickCallback = null;

	try {
		this.element = document.getElementById(elementID);

		var circle = this;
		window.addEventListener('resize', function(){
			circle.OnResize();
		}, true);
		this.element.onclick = function() {
			if( null != circle.clickCallback) {
				circle.clickCallback();
			}
		};

		this.init();
	} catch(e) {
		console.log('Circle not ready');
	}
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.init = function()
{
	this.OnResize();

	this.element.style.position = 'absolute';
	this.element.style.background = 'rgba(0,0,0,.3)';
	this.element.style.zIndex = '10';
	this.element.style.textAlign = 'center';
	this.element.style.webkitTouchCallout = 'none';
	this.element.style.webkitUserSelect = 'none';
	this.element.style.MozUserSelect = 'none';
	this.element.style.msUserSelect = 'none';
	this.element.style.userSelect = 'none';
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.rotate = function(degree)
{
	this.element.style.webkitTransform = 'rotate('+degree+'deg)';
	this.element.style.MozTransform = 'rotate('+degree+'deg)';
	this.element.style.transform = 'rotate('+degree+'deg)';
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.text = function(str,fontSize)
{
	var elementHeight = parseInt(this.element.style.height);
	var lineHeight = parseInt(elementHeight/10*fontSize);

	this.element.innerHTML = str;
	this.element.style.fontSize = lineHeight+'px';
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.click = function(callback)
{
	this.clickCallback = callback;
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.OnResize = function()
{
	var body = document.getElementsByTagName('body')[0];
	var x = window.innerWidth  || document.documentElement.clientWidth  || body.clientWidth;
	var y = window.innerHeight || document.documentElement.clientHeight || body.clientHeight;
	var min = x > y ? y : x;

	this.element.style.top = ((y-min)/2)+'px';
	this.element.style.left = ((x-min)/2)+'px';
	this.element.style.width = min+'px';
	this.element.style.height = min+'px';
	this.element.style.lineHeight = min+'px';
	this.element.style.webkitBorderRadius = min+'px';
	this.element.style.MozBorderRadius = min+'px';
	this.element.style.borderRadius = min+'px';
}

// ---------------------------------------------------------------------------------------
// eof
<commit_msg>added a button shape<commit_after>// ---------------------------------------------------------------------------------------
// all about main circle
// ---------------------------------------------------------------------------------------

function CircleLib( elementID)
{
	this.element = null;
	this.clickCallback = null;
	this.fontSize = 1;

	try {
		this.element = document.getElementById(elementID);

		var circle = this;
		window.addEventListener('resize', function(){
			circle.OnResize();
		}, true);
		this.element.onclick = function() {
			if( null != circle.clickCallback) {
				circle.clickCallback();
			}
		};

		this.init();
	} catch(e) {
		console.log('Circle not ready');
	}
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.init = function()
{
	this.OnResize();

	this.element.style.position = 'absolute';
//	this.element.style.background = 'rgba(0,0,0,.3)';
	this.element.style.color = '#ffffff';
	this.element.style.zIndex = '10';
	this.element.style.textAlign = 'center';
	this.element.style.webkitTouchCallout = 'none';
	this.element.style.webkitUserSelect = 'none';
	this.element.style.MozUserSelect = 'none';
	this.element.style.msUserSelect = 'none';
	this.element.style.userSelect = 'none';
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.rotate = function(degree)
{
	this.element.style.webkitTransform = 'rotate('+degree+'deg)';
	this.element.style.MozTransform = 'rotate('+degree+'deg)';
	this.element.style.transform = 'rotate('+degree+'deg)';
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.text = function(str,fontSize)
{
	this.fontSize = fontSize;

	var elementHeight = parseInt(this.element.style.height);
	var fontSizeHeight = parseInt(elementHeight/10*this.fontSize);

	this.element.innerHTML = str;
	this.element.style.fontSize = fontSizeHeight+'px';
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.click = function(callback)
{
	this.clickCallback = callback;
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.OnResize = function()
{
	var body = document.getElementsByTagName('body')[0];
	var x = window.innerWidth  || document.documentElement.clientWidth  || body.clientWidth;
	var y = window.innerHeight || document.documentElement.clientHeight || body.clientHeight;
	var min = x > y ? y : x;
	min *= .85;

	var fontSizeHeight = parseInt(min/10*this.fontSize);

	this.element.style.top = ((y-min)/2)+'px';
	this.element.style.left = ((x-min)/2)+'px';
	this.element.style.width = min+'px';
	this.element.style.height = min+'px';
	this.element.style.lineHeight = min+'px';
	this.element.style.webkitBorderRadius = min+'px';
	this.element.style.MozBorderRadius = min+'px';
	this.element.style.borderRadius = min+'px';
	this.element.style.fontSize = fontSizeHeight+'px';

	this.setGradient();
}

// ---------------------------------------------------------------------------------------

CircleLib.prototype.setGradient = function()
{
	var innerColor = 'rgba(0,0,0,0)';
	var borderColor = 'rgba(0,0,0,.2)';
	var outerColor = 'rgba(0,0,0,.05)';
	var frameColor = 'rgba(255,255,255,.1)';
	var innerPos = '54.5%';
	var borderPos = '55%';
	var outerPos = '61%';
	var frame1Pos = '65.5%';
	var frame2Pos = '66%';

	// old browsers
	this.element.style.background = innerColor;

	// firefox 3.6+
	this.element.style.background = '-moz-radial-gradient(center, ellipse cover,'+innerColor+' 0%,'+innerColor+' '+innerPos+','+borderColor+' '+borderPos+','+outerColor+' '+outerPos+','+outerColor+' '+frame1Pos+','+frameColor+' '+frame2Pos+','+frameColor+' 100%)';

	// chrome10+ and safari5.1+
	this.element.style.background = '-webkit-radial-gradient(center, ellipse cover,'+innerColor+' 0%,'+innerColor+' '+innerPos+','+borderColor+' '+borderPos+','+outerColor+' '+outerPos+','+outerColor+' '+frame1Pos+','+frameColor+' '+frame2Pos+','+frameColor+' 100%)';

	// opera 12+
	this.element.style.background = '-o-radial-gradient(center, ellipse cover,'+innerColor+' 0%,'+innerColor+' '+innerPos+','+borderColor+' '+borderPos+','+outerColor+' '+outerPos+','+outerColor+' '+frame1Pos+','+frameColor+' '+frame2Pos+','+frameColor+' 100%)';

	// ie10+
	this.element.style.background = '-ms-radial-gradient(center, ellipse cover,'+innerColor+' 0%,'+innerColor+' '+innerPos+','+borderColor+' '+borderPos+','+outerColor+' '+outerPos+','+outerColor+' '+frame1Pos+','+frameColor+' '+frame2Pos+','+frameColor+' 100%)';

	// modern css
	this.element.style.background = 'radial-gradient(ellipse at center,'+innerColor+' 0%,'+innerColor+' '+innerPos+','+borderColor+' '+borderPos+','+outerColor+' '+outerPos+','+outerColor+' '+frame1Pos+','+frameColor+' '+frame2Pos+','+frameColor+' 100%)';
}

// ---------------------------------------------------------------------------------------
// eof
<|endoftext|>


<commit_before>Meteor.methods({
  updateCategories: function () {
    // TODO: see if this method is still necessary
    if(isAdmin(Meteor.user())){
      Posts.find().forEach(function(post){
        if(post.categories){
          console.log('Found categories for post "'+post.headline+'"');
          Posts.update(post._id,{$set:{userId:post.user_id}}, function(error){
            console.log(error);
          });
        }
      });
    }
  },
  giveInvites: function () {
    if(isAdmin(Meteor.user()))
      Meteor.users.update({}, {$inc:{inviteCount: 1}}, {multi:true});
  },
  updateCategoryInPosts: function (categoryId) {
    check(categoryId, String);

    if (!isAdmin(Meteor.user()))
      throw new Meteor.Error(403, "Not an admin");

    var category = Categories.findOne(categoryId);
    if (!category)
      throw new Meteor.Error(404, "No such category");

    // Such update is server-only, because Minimongo does not support $ yet
    Posts.update(
      {'categories._id': categoryId}
    , {$set: {'categories.$': category}}
    , {multi: true}
    );
  }
})<commit_msg>#194: now updateCategoryInPosts correctly process deleted categories<commit_after>Meteor.methods({
  updateCategories: function () {
    // TODO: see if this method is still necessary
    if(isAdmin(Meteor.user())){
      Posts.find().forEach(function(post){
        if(post.categories){
          console.log('Found categories for post "'+post.headline+'"');
          Posts.update(post._id,{$set:{userId:post.user_id}}, function(error){
            console.log(error);
          });
        }
      });
    }
  },
  giveInvites: function () {
    if(isAdmin(Meteor.user()))
      Meteor.users.update({}, {$inc:{inviteCount: 1}}, {multi:true});
  },
  updateCategoryInPosts: function (categoryId) {
    check(categoryId, String);

    if (!isAdmin(Meteor.user()))
      throw new Meteor.Error(403, "Not an admin");

    var category = Categories.findOne(categoryId);
    if (!category) {
      Posts.update(
        {}
      , {$pull: {categories: {_id: categoryId}}}
      , {multi: true}
      );
    } else {
      // Such update is server-only, because Minimongo does not support $ yet
      Posts.update(
        {'categories._id': categoryId}
      , {$set: {'categories.$': category}}
      , {multi: true}
      );
    }
  }
})<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib');
  grunt.loadNpmTasks('grunt-coverjs');

  grunt.registerTask('intro', 'Introduction to build', function() {
    grunt.log.write('We are going to build a jQTouch release!');
  });

  grunt.registerMultiTask('compass', '', function() {
    /* roll our own, because I couldn't find -l options to the `contrib` version */

    var cb = this.async(); // Tell grunt the task is async
    var options = this.data['options'] || {};
    var params = grunt.template.process(this.data['params']);

    var exec = require('child_process').exec;
    console.log('compass ' + params + '');
    var child = exec('compass ' + params + '', options, function(error, stdout, stderr) {
      if (!!stdout) {
        console.log('stdout: ' + stdout);
      }
      if (error !== null) {
        console.log('error: ' + error);
        console.log('stderr: ' + stdout);
      }
      cb(); // Execute the callback when the async task is done
    });
  });

  grunt.registerMultiTask('rake', 'Compile a Ruby Package with Rake', function() {
    var cb = this.async(); // Tell grunt the task is async

    var options = this.data['options'];
    var params = grunt.template.process(this.data['params']);

    var exec = require('child_process').exec;
    var child = exec('rake ' + params + '', options, function(error, stdout, stderr) {
      if (!!stdout) {
        console.log('stdout: ' + stdout);
      }
      if (error !== null) {
        console.log('error: ' + error);
        console.log('stderr: ' + stdout);
      }
      cb(); // Execute the callback when the async task is done
    });
  });

  grunt.registerMultiTask('gitmodule', 'Update git submodules', function() {
    var cb = this.async(); // Tell grunt the task is async

    var target = this.target || '';
    var path = this.data['path'] || ('submodules/' + this.target);

    var exec = require('child_process').exec;
    var child = exec('git submodule update --init --recursive ' + path,
      function(error, stdout, stderr) {
        if (!!stdout) {
          console.log('stdout: ' + stdout);
        }
        if (error !== null) {
          console.log('error: ' + error);
          console.log('stderr: ' + stdout);
        }
        cb(); // Execute the callback when the async task is done
      }
    );
  });

  // Project configuration.
  grunt
      .initConfig({
        pkg: '<json:package.json>',
        meta: {
          version: '<%= pkg.version %>-<%= pkg.version %>',
          banner: '/*\n'
              + '          _/    _/_/    _/_/_/_/_/                              _/                		\n'
              + '             _/    _/      _/      _/_/    _/    _/    _/_/_/  _/_/_/ 					\n'
              + '        _/  _/  _/_/      _/    _/    _/  _/    _/  _/        _/    _/					\n'
              + '       _/  _/    _/      _/    _/    _/  _/    _/  _/        _/    _/ 					\n'
              + '      _/    _/_/  _/    _/      _/_/      _/_/_/    _/_/_/  _/    _/  					\n'
              + '     _/																 				\n'
              + '  _/																	 				\n'
              + '  Created by David Kaneda <http://www.davidkaneda.com>				 					\n'
              + '  Maintained by Thomas Yip <http://beedesk.com/>						 				\n'
              + '  Sponsored by Sencha Labs <http://www.sencha.com/>					 				\n'
              + '  Special thanks to Jonathan Stark <http://www.jonathanstark.com/>    					\n'
              + '																		 				\n'
              + '  Documentation and issue tracking on GitHub <http://github.com/senchalabs/jQTouch/>	\n'
              + '																						\n'
              + '  (c) 2009-<%= grunt.template.today("yyyy") %> Sencha Labs								\n'
              + '																						\n'
              + '  Version: <%= meta.version %> - <%= grunt.template.today("yyyy-mm-dd") %>				\n'
              + '																						\n'
              + '  jQTouch may be freely distributed under the MIT license.								\n'
              + '*/'
        },
        dirs: {
          src: 'src',
          dest: 'jqtouch-<%= pkg.version %>-<%= pkg.versionId %>'
        },
        clean: {
          zepto: ['zepto/lib'],
          dist: ['<%= dirs.dest %>']
        },
        copy: {
          prepare: {
            files: {
              '<%= dirs.dest %>/': ['dist/**', 'src/**', 'lib/**', 'themes/**',
                  'extensions/**', 'demos/**', 'versions/**', '*']
            },
            options: {
              cwd: '',
              excludeEmpty: false,

            }
          },
          zepto: {
            files: {
              'lib/zepto/': ['submodules/zepto/dist/**'],
              'lib/zepto/touch.js': ['submodules/zepto/src/touch.js'],
            },
            options: {
              cwd: '',
              excludeEmpty: false,

            }
          },
          checkin: { /* replace checkin version to updated css */
            files: {
              'themes/css/': ['<%= dirs.dest %>/themes/css/**']
            },
            options: {
              cwd: '',
              excludeEmpty: false,

            }
          }
        },
        gitmodule: {
          zepto: {
          },
          recipes: {
            path: 'submodules/compass-recipes'
          }
        },
        rake: {
          zepto: {
            params: 'concat[fx:ajax:data:detect:event:form:polyfill:touch] dist',
            options: {
              cwd: 'submodules/zepto'
            }
          }
        },
        compass: {
          all: {
            params: 'compile -l <%= dirs.dest %>/themes/compass-recipes/ --sass-dir <%= dirs.dest %>/themes/scss --css-dir <%= dirs.dest %>/themes/css --output-style compressed --environment production -q'
          }
        },
        lint: {
          files: ['src/jqtouch.js']
        },
        qunit: {
          files: ['test/unit/*.html']
        },
        concat: {
          dist: {
            src: ['<banner>', '<file_strip_banner:src/jqtouch.js>'],
            dest: '<%= dirs.dest %>/src/jqtouch.js'
          }
        },
        min: {
          jqtouch: {
            src: ['<%= dirs.dest %>/src/jqtouch.js'],
            dest: '<%= dirs.dest %>/src/jqtouch.min.js'
          },
          'jquery-bridge': {
            src: ['<%= dirs.dest %>/src/jqtouch-jquery.js'],
            dest: '<%= dirs.dest %>/src/jqtouch-jquery.min.js'
          },
          'jquery-bridge2': {
            src: ['<%= dirs.dest %>/src/jqtouch-jquery2.js'],
            dest: '<%= dirs.dest %>/src/jqtouch-jquery2.min.js'
          }
        },
        cover: {
          compile: {
            files: {
              'test/instrumented/jqtouch.js': ['src/jqtouch.js']
            }
          }
        },
        watch: {
          files: '<%= dirs.dest %>/themes/css',
          tasks: 'compass'
        },
        jshint: {
          options: {
            curly: true,
            eqeqeq: true,
            immed: true,
            latedef: true,
            newcap: true,
            noarg: true,
            sub: true,
            undef: true,
            boss: true,
            eqnull: true,
            browser: true
          },
          globals: {
            jQuery: true
          }
        },
        uglify: {}
      });

  // Tasks
  grunt.registerTask('zepto', 'clean:zepto rake:zepto copy:zepto');

  grunt.registerTask('css', 'clean:dist copy:prepare gitmodule:recipes compass');

  grunt.registerTask('light', 'intro copy:prepare css concat min');

  grunt.registerTask('default', 'intro qunit cover light');

  grunt.registerTask('full', 'intro lint zepto default copy:checkin');

};
<commit_msg>minor. Added task comment.<commit_after>/*global module:false*/
module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib');
  grunt.loadNpmTasks('grunt-coverjs');

  grunt.registerTask('intro', 'Introduction to build', function() {
    grunt.log.write('We are going to build a jQTouch release!');
  });

  grunt.registerMultiTask('compass', 'Compile sass with compass', function() {
    /* roll our own, because I couldn't find -l options to the `contrib` version */

    var cb = this.async(); // Tell grunt the task is async
    var options = this.data['options'] || {};
    var params = grunt.template.process(this.data['params']);

    var exec = require('child_process').exec;
    console.log('compass ' + params + '');
    var child = exec('compass ' + params + '', options, function(error, stdout, stderr) {
      if (!!stdout) {
        console.log('stdout: ' + stdout);
      }
      if (error !== null) {
        console.log('error: ' + error);
        console.log('stderr: ' + stdout);
      }
      cb(); // Execute the callback when the async task is done
    });
  });

  grunt.registerMultiTask('rake', 'Compile a Ruby Package with Rake', function() {
    var cb = this.async(); // Tell grunt the task is async

    var options = this.data['options'];
    var params = grunt.template.process(this.data['params']);

    var exec = require('child_process').exec;
    var child = exec('rake ' + params + '', options, function(error, stdout, stderr) {
      if (!!stdout) {
        console.log('stdout: ' + stdout);
      }
      if (error !== null) {
        console.log('error: ' + error);
        console.log('stderr: ' + stdout);
      }
      cb(); // Execute the callback when the async task is done
    });
  });

  grunt.registerMultiTask('gitmodule', 'Update git submodules', function() {
    var cb = this.async(); // Tell grunt the task is async

    var target = this.target || '';
    var path = this.data['path'] || ('submodules/' + this.target);

    var exec = require('child_process').exec;
    var child = exec('git submodule update --init --recursive ' + path,
      function(error, stdout, stderr) {
        if (!!stdout) {
          console.log('stdout: ' + stdout);
        }
        if (error !== null) {
          console.log('error: ' + error);
          console.log('stderr: ' + stdout);
        }
        cb(); // Execute the callback when the async task is done
      }
    );
  });

  // Project configuration.
  grunt
      .initConfig({
        pkg: '<json:package.json>',
        meta: {
          version: '<%= pkg.version %>-<%= pkg.version %>',
          banner: '/*\n'
              + '          _/    _/_/    _/_/_/_/_/                              _/                		\n'
              + '             _/    _/      _/      _/_/    _/    _/    _/_/_/  _/_/_/ 					\n'
              + '        _/  _/  _/_/      _/    _/    _/  _/    _/  _/        _/    _/					\n'
              + '       _/  _/    _/      _/    _/    _/  _/    _/  _/        _/    _/ 					\n'
              + '      _/    _/_/  _/    _/      _/_/      _/_/_/    _/_/_/  _/    _/  					\n'
              + '     _/																 				\n'
              + '  _/																	 				\n'
              + '  Created by David Kaneda <http://www.davidkaneda.com>				 					\n'
              + '  Maintained by Thomas Yip <http://beedesk.com/>						 				\n'
              + '  Sponsored by Sencha Labs <http://www.sencha.com/>					 				\n'
              + '  Special thanks to Jonathan Stark <http://www.jonathanstark.com/>    					\n'
              + '																		 				\n'
              + '  Documentation and issue tracking on GitHub <http://github.com/senchalabs/jQTouch/>	\n'
              + '																						\n'
              + '  (c) 2009-<%= grunt.template.today("yyyy") %> Sencha Labs								\n'
              + '																						\n'
              + '  Version: <%= meta.version %> - <%= grunt.template.today("yyyy-mm-dd") %>				\n'
              + '																						\n'
              + '  jQTouch may be freely distributed under the MIT license.								\n'
              + '*/'
        },
        dirs: {
          src: 'src',
          dest: 'jqtouch-<%= pkg.version %>-<%= pkg.versionId %>'
        },
        clean: {
          zepto: ['zepto/lib'],
          dist: ['<%= dirs.dest %>']
        },
        copy: {
          prepare: {
            files: {
              '<%= dirs.dest %>/': ['dist/**', 'src/**', 'lib/**', 'themes/**',
                  'extensions/**', 'demos/**', 'versions/**', '*']
            },
            options: {
              cwd: '',
              excludeEmpty: false,

            }
          },
          zepto: {
            files: {
              'lib/zepto/': ['submodules/zepto/dist/**'],
              'lib/zepto/touch.js': ['submodules/zepto/src/touch.js'],
            },
            options: {
              cwd: '',
              excludeEmpty: false,

            }
          },
          checkin: { /* replace checkin version to updated css */
            files: {
              'themes/css/': ['<%= dirs.dest %>/themes/css/**']
            },
            options: {
              cwd: '',
              excludeEmpty: false,

            }
          }
        },
        gitmodule: {
          zepto: {
          },
          recipes: {
            path: 'submodules/compass-recipes'
          }
        },
        rake: {
          zepto: {
            params: 'concat[fx:ajax:data:detect:event:form:polyfill:touch] dist',
            options: {
              cwd: 'submodules/zepto'
            }
          }
        },
        compass: {
          all: {
            params: 'compile -l <%= dirs.dest %>/themes/compass-recipes/ --sass-dir <%= dirs.dest %>/themes/scss --css-dir <%= dirs.dest %>/themes/css --output-style compressed --environment production -q'
          }
        },
        lint: {
          files: ['src/jqtouch.js']
        },
        qunit: {
          files: ['test/unit/*.html']
        },
        concat: {
          dist: {
            src: ['<banner>', '<file_strip_banner:src/jqtouch.js>'],
            dest: '<%= dirs.dest %>/src/jqtouch.js'
          }
        },
        min: {
          jqtouch: {
            src: ['<%= dirs.dest %>/src/jqtouch.js'],
            dest: '<%= dirs.dest %>/src/jqtouch.min.js'
          },
          'jquery-bridge': {
            src: ['<%= dirs.dest %>/src/jqtouch-jquery.js'],
            dest: '<%= dirs.dest %>/src/jqtouch-jquery.min.js'
          },
          'jquery-bridge2': {
            src: ['<%= dirs.dest %>/src/jqtouch-jquery2.js'],
            dest: '<%= dirs.dest %>/src/jqtouch-jquery2.min.js'
          }
        },
        cover: {
          compile: {
            files: {
              'test/instrumented/jqtouch.js': ['src/jqtouch.js']
            }
          }
        },
        watch: {
          files: '<%= dirs.dest %>/themes/css',
          tasks: 'compass'
        },
        jshint: {
          options: {
            curly: true,
            eqeqeq: true,
            immed: true,
            latedef: true,
            newcap: true,
            noarg: true,
            sub: true,
            undef: true,
            boss: true,
            eqnull: true,
            browser: true
          },
          globals: {
            jQuery: true
          }
        },
        uglify: {}
      });

  // Tasks
  grunt.registerTask('zepto', 'clean:zepto rake:zepto copy:zepto');

  grunt.registerTask('css', 'clean:dist copy:prepare gitmodule:recipes compass');

  grunt.registerTask('light', 'intro copy:prepare css concat min');

  grunt.registerTask('default', 'intro qunit cover light');

  grunt.registerTask('full', 'intro lint zepto default copy:checkin');

};
<|endoftext|>