<commit_before>//  Package imports
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';

//  Our imports
import LocalSettingsPageItem from './item';

//  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

const messages = defineMessages({
  layout_auto: {  id: 'layout.auto', defaultMessage: 'Auto' },
  layout_desktop: { id: 'layout.desktop', defaultMessage: 'Desktop' },
  layout_mobile: { id: 'layout.single', defaultMessage: 'Mobile' },
  side_arm_none: { id: 'settings.side_arm.none', defaultMessage: 'None' },
  side_arm_keep: { id: 'settings.side_arm_reply_mode.keep', defaultMessage: 'Keep secondary toot button to set privacy' },
  side_arm_copy: { id: 'settings.side_arm_reply_mode.copy', defaultMessage: 'Copy privacy setting of the toot being replied to' },
  side_arm_restrict: { id: 'settings.side_arm_reply_mode.restrict', defaultMessage: 'Restrict privacy setting to that of the toot being replied to' },
  regexp: { id: 'settings.content_warnings.regexp', defaultMessage: 'Regular expression' },
});

@injectIntl
export default class LocalSettingsPage extends React.PureComponent {

  static propTypes = {
    index    : PropTypes.number,
    intl     : PropTypes.object.isRequired,
    onChange : PropTypes.func.isRequired,
    settings : ImmutablePropTypes.map.isRequired,
  };

  pages = [
    ({ intl, onChange, settings }) => (

<FormattedMessage id='settings.general' defaultMessage='General' />

        <LocalSettingsPageItem
          settings={settings}
          item={['show_reply_count']}
          id='mastodon-settings--reply-count'
          onChange={onChange}
        >
          <FormattedMessage id='settings.show_reply_counter' defaultMessage='Display an estimate of the reply count' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['hicolor_privacy_icons']}
          id='mastodon-settings--hicolor_privacy_icons'
          onChange={onChange}
        >
          <FormattedMessage id='settings.hicolor_privacy_icons' defaultMessage='High color privacy icons' />
          <FormattedMessage id='settings.hicolor_privacy_icons.hint' defaultMessage="Display privacy icons in bright and easily distinguishable colors" />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['confirm_boost_missing_media_description']}
          id='mastodon-settings--confirm_boost_missing_media_description'
          onChange={onChange}
        >
          <FormattedMessage id='settings.confirm_boost_missing_media_description' defaultMessage='Show confirmation dialog before boosting toots lacking media descriptions' />
        </LocalSettingsPageItem>

<FormattedMessage id='settings.notifications_opts' defaultMessage='Notifications options' />

          <LocalSettingsPageItem
            settings={settings}
            item={['notifications', 'tab_badge']}
            id='mastodon-settings--notifications-tab_badge'
            onChange={onChange}
          >
            <FormattedMessage id='settings.notifications.tab_badge' defaultMessage="Unread notifications badge" />
            <FormattedMessage id='settings.notifications.tab_badge.hint' defaultMessage="Display a badge for unread notifications in the column icons when the notifications column isn't open" />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['notifications', 'favicon_badge']}
            id='mastodon-settings--notifications-favicon_badge'
            onChange={onChange}
          >
            <FormattedMessage id='settings.notifications.favicon_badge' defaultMessage='Unread notifications favicon badge' />
            <FormattedMessage id='settings.notifications.favicon_badge.hint' defaultMessage="Add a badge for unread notifications to the favicon" />
          </LocalSettingsPageItem>

<FormattedMessage id='settings.layout_opts' defaultMessage='Layout options' />

          <LocalSettingsPageItem
            settings={settings}
            item={['layout']}
            id='mastodon-settings--layout'
            options={[
              { value: 'auto', message: intl.formatMessage(messages.layout_auto) },
              { value: 'multiple', message: intl.formatMessage(messages.layout_desktop) },
              { value: 'single', message: intl.formatMessage(messages.layout_mobile) },
            ]}
            onChange={onChange}
          >
            <FormattedMessage id='settings.layout' defaultMessage='Layout:' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['stretch']}
            id='mastodon-settings--stretch'
            onChange={onChange}
          >
            <FormattedMessage id='settings.wide_view' defaultMessage='Wide view (Desktop mode only)' />
            <FormattedMessage id='settings.wide_view_hint' defaultMessage='Stretches columns to better fill the available space.' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['navbar_under']}
            id='mastodon-settings--navbar_under'
            onChange={onChange}
          >
            <FormattedMessage id='settings.navbar_under' defaultMessage='Navbar at the bottom (Mobile only)' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['swipe_to_change_columns']}
            id='mastodon-settings--swipe_to_change_columns'
            onChange={onChange}
          >
            <FormattedMessage id='settings.swipe_to_change_columns' defaultMessage='Allow swiping to change columns (Mobile only)' />
          </LocalSettingsPageItem>

    ),
    ({ intl, onChange, settings }) => (

<FormattedMessage id='settings.compose_box_opts' defaultMessage='Compose box' />

        <LocalSettingsPageItem
          settings={settings}
          item={['always_show_spoilers_field']}
          id='mastodon-settings--always_show_spoilers_field'
          onChange={onChange}
        >
          <FormattedMessage id='settings.always_show_spoilers_field' defaultMessage='Always enable the Content Warning field' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['preselect_on_reply']}
          id='mastodon-settings--preselect_on_reply'
          onChange={onChange}
        >
          <FormattedMessage id='settings.preselect_on_reply' defaultMessage='Pre-select usernames on reply' />
          <FormattedMessage id='settings.preselect_on_reply_hint' defaultMessage='When replying to a conversation with multiple participants, pre-select usernames past the first' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['confirm_missing_media_description']}
          id='mastodon-settings--confirm_missing_media_description'
          onChange={onChange}
        >
          <FormattedMessage id='settings.confirm_missing_media_description' defaultMessage='Show confirmation dialog before sending toots lacking media descriptions' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['confirm_before_clearing_draft']}
          id='mastodon-settings--confirm_before_clearing_draft'
          onChange={onChange}
        >
          <FormattedMessage id='settings.confirm_before_clearing_draft' defaultMessage='Show confirmation dialog before overwriting the message being composed' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['show_content_type_choice']}
          id='mastodon-settings--show_content_type_choice'
          onChange={onChange}
        >
          <FormattedMessage id='settings.show_content_type_choice' defaultMessage='Show content-type choice when authoring toots' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['side_arm']}
          id='mastodon-settings--side_arm'
          options={[
            { value: 'none', message: intl.formatMessage(messages.side_arm_none) },
            { value: 'direct', message: intl.formatMessage({ id: 'privacy.direct.short' }) },
            { value: 'private', message: intl.formatMessage({ id: 'privacy.private.short' }) },
            { value: 'unlisted', message: intl.formatMessage({ id: 'privacy.unlisted.short' }) },
            { value: 'public', message: intl.formatMessage({ id: 'privacy.public.short' }) },
          ]}
          onChange={onChange}
        >
          <FormattedMessage id='settings.side_arm' defaultMessage='Secondary toot button:' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['side_arm_reply_mode']}
          id='mastodon-settings--side_arm_reply_mode'
          options={[
            { value: 'keep', message: intl.formatMessage(messages.side_arm_keep) },
            { value: 'copy', message: intl.formatMessage(messages.side_arm_copy) },
            { value: 'restrict', message: intl.formatMessage(messages.side_arm_restrict) },
          ]}
          onChange={onChange}
        >
          <FormattedMessage id='settings.side_arm_reply_mode' defaultMessage='When replying to a toot:' />
        </LocalSettingsPageItem>

    ),
    ({ intl, onChange, settings }) => (

<FormattedMessage id='settings.content_warnings' defaultMessage='Content warnings' />

        <LocalSettingsPageItem
          settings={settings}
          item={['content_warnings', 'auto_unfold']}
          id='mastodon-settings--content_warnings-auto_unfold'
          onChange={onChange}
        >
          <FormattedMessage id='settings.enable_content_warnings_auto_unfold' defaultMessage='Automatically unfold content-warnings' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['content_warnings', 'filter']}
          id='mastodon-settings--content_warnings-auto_unfold'
          onChange={onChange}
          dependsOn={[['content_warnings', 'auto_unfold']]}
          placeholder={intl.formatMessage(messages.regexp)}
        >
          <FormattedMessage id='settings.content_warnings_filter' defaultMessage='Content warnings to not automatically unfold:' />
        </LocalSettingsPageItem>

    ),
    ({ onChange, settings }) => (

<FormattedMessage id='settings.collapsed_statuses' defaultMessage='Collapsed toots' />

        <LocalSettingsPageItem
          settings={settings}
          item={['collapsed', 'enabled']}
          id='mastodon-settings--collapsed-enabled'
          onChange={onChange}
        >
          <FormattedMessage id='settings.enable_collapsed' defaultMessage='Enable collapsed toots' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['collapsed', 'show_action_bar']}
          id='mastodon-settings--collapsed-show-action-bar'
          onChange={onChange}
          dependsOn={[['collapsed', 'enabled']]}
        >
          <FormattedMessage id='settings.show_action_bar' defaultMessage='Show action buttons in collapsed toots' />
        </LocalSettingsPageItem>

<FormattedMessage id='settings.auto_collapse' defaultMessage='Automatic collapsing' />

          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'all']}
            id='mastodon-settings--collapsed-auto-all'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
          >
            <FormattedMessage id='settings.auto_collapse_all' defaultMessage='Everything' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'notifications']}
            id='mastodon-settings--collapsed-auto-notifications'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_notifications' defaultMessage='Notifications' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'lengthy']}
            id='mastodon-settings--collapsed-auto-lengthy'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_lengthy' defaultMessage='Lengthy toots' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'reblogs']}
            id='mastodon-settings--collapsed-auto-reblogs'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_reblogs' defaultMessage='Boosts' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'replies']}
            id='mastodon-settings--collapsed-auto-replies'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_replies' defaultMessage='Replies' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'media']}
            id='mastodon-settings--collapsed-auto-media'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_media' defaultMessage='Toots with media' />
          </LocalSettingsPageItem>

<FormattedMessage id='settings.image_backgrounds' defaultMessage='Image backgrounds' />

          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'backgrounds', 'user_backgrounds']}
            id='mastodon-settings--collapsed-user-backgrouns'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
          >
            <FormattedMessage id='settings.image_backgrounds_users' defaultMessage='Give collapsed toots an image background' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'backgrounds', 'preview_images']}
            id='mastodon-settings--collapsed-preview-images'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
          >
            <FormattedMessage id='settings.image_backgrounds_media' defaultMessage='Preview collapsed toot media' />
          </LocalSettingsPageItem>

    ),
    ({ onChange, settings }) => (

<FormattedMessage id='settings.media' defaultMessage='Media' />

        <LocalSettingsPageItem
          settings={settings}
          item={['media', 'letterbox']}
          id='mastodon-settings--media-letterbox'
          onChange={onChange}
        >
          <FormattedMessage id='settings.media_letterbox' defaultMessage='Letterbox media' />
          <FormattedMessage id='settings.media_letterbox_hint' defaultMessage='Scale down and letterbox media to fill the image containers instead of stretching and cropping them' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['media', 'fullwidth']}
          id='mastodon-settings--media-fullwidth'
          onChange={onChange}
        >
          <FormattedMessage id='settings.media_fullwidth' defaultMessage='Full-width media previews' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['inline_preview_cards']}
          id='mastodon-settings--inline-preview-cards'
          onChange={onChange}
        >
          <FormattedMessage id='settings.inline_preview_cards' defaultMessage='Inline preview cards for external links' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['media', 'reveal_behind_cw']}
          id='mastodon-settings--reveal-behind-cw'
          onChange={onChange}
        >
          <FormattedMessage id='settings.media_reveal_behind_cw' defaultMessage='Reveal sensitive media behind a CW by default' />
        </LocalSettingsPageItem>

    ),
  ];

  render () {
    const { pages } = this;
    const { index, intl, onChange, settings } = this.props;
    const CurrentPage = pages[index] || pages[0];

    return <CurrentPage intl={intl} onChange={onChange} settings={settings} />;
  }

}
<commit_msg>Add hints to make local settings about layout more explicit<commit_after>//  Package imports
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';

//  Our imports
import LocalSettingsPageItem from './item';

//  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

const messages = defineMessages({
  layout_auto: {  id: 'layout.auto', defaultMessage: 'Auto' },
  layout_auto_hint: {  id: 'layout.hint.auto', defaultMessage: 'Automatically chose layout based on “Enable advanced web interface” setting and screen size.' },
  layout_desktop: { id: 'layout.desktop', defaultMessage: 'Desktop' },
  layout_desktop_hint: { id: 'layout.hint.desktop', defaultMessage: 'Use multiple-column layout regardless of the “Enable advanced web interface” setting or screen size.' },
  layout_mobile: { id: 'layout.single', defaultMessage: 'Mobile' },
  layout_mobile_hint: { id: 'layout.hint.single', defaultMessage: 'Use single-column layout regardless of the “Enable advanced web interface” setting or screen size.' },
  side_arm_none: { id: 'settings.side_arm.none', defaultMessage: 'None' },
  side_arm_keep: { id: 'settings.side_arm_reply_mode.keep', defaultMessage: 'Keep secondary toot button to set privacy' },
  side_arm_copy: { id: 'settings.side_arm_reply_mode.copy', defaultMessage: 'Copy privacy setting of the toot being replied to' },
  side_arm_restrict: { id: 'settings.side_arm_reply_mode.restrict', defaultMessage: 'Restrict privacy setting to that of the toot being replied to' },
  regexp: { id: 'settings.content_warnings.regexp', defaultMessage: 'Regular expression' },
});

@injectIntl
export default class LocalSettingsPage extends React.PureComponent {

  static propTypes = {
    index    : PropTypes.number,
    intl     : PropTypes.object.isRequired,
    onChange : PropTypes.func.isRequired,
    settings : ImmutablePropTypes.map.isRequired,
  };

  pages = [
    ({ intl, onChange, settings }) => (

<FormattedMessage id='settings.general' defaultMessage='General' />

        <LocalSettingsPageItem
          settings={settings}
          item={['show_reply_count']}
          id='mastodon-settings--reply-count'
          onChange={onChange}
        >
          <FormattedMessage id='settings.show_reply_counter' defaultMessage='Display an estimate of the reply count' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['hicolor_privacy_icons']}
          id='mastodon-settings--hicolor_privacy_icons'
          onChange={onChange}
        >
          <FormattedMessage id='settings.hicolor_privacy_icons' defaultMessage='High color privacy icons' />
          <FormattedMessage id='settings.hicolor_privacy_icons.hint' defaultMessage="Display privacy icons in bright and easily distinguishable colors" />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['confirm_boost_missing_media_description']}
          id='mastodon-settings--confirm_boost_missing_media_description'
          onChange={onChange}
        >
          <FormattedMessage id='settings.confirm_boost_missing_media_description' defaultMessage='Show confirmation dialog before boosting toots lacking media descriptions' />
        </LocalSettingsPageItem>

<FormattedMessage id='settings.notifications_opts' defaultMessage='Notifications options' />

          <LocalSettingsPageItem
            settings={settings}
            item={['notifications', 'tab_badge']}
            id='mastodon-settings--notifications-tab_badge'
            onChange={onChange}
          >
            <FormattedMessage id='settings.notifications.tab_badge' defaultMessage="Unread notifications badge" />
            <FormattedMessage id='settings.notifications.tab_badge.hint' defaultMessage="Display a badge for unread notifications in the column icons when the notifications column isn't open" />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['notifications', 'favicon_badge']}
            id='mastodon-settings--notifications-favicon_badge'
            onChange={onChange}
          >
            <FormattedMessage id='settings.notifications.favicon_badge' defaultMessage='Unread notifications favicon badge' />
            <FormattedMessage id='settings.notifications.favicon_badge.hint' defaultMessage="Add a badge for unread notifications to the favicon" />
          </LocalSettingsPageItem>

<FormattedMessage id='settings.layout_opts' defaultMessage='Layout options' />

          <LocalSettingsPageItem
            settings={settings}
            item={['layout']}
            id='mastodon-settings--layout'
            options={[
              { value: 'auto', message: intl.formatMessage(messages.layout_auto), hint: intl.formatMessage(messages.layout_auto_hint) },
              { value: 'multiple', message: intl.formatMessage(messages.layout_desktop), hint: intl.formatMessage(messages.layout_desktop_hint) },
              { value: 'single', message: intl.formatMessage(messages.layout_mobile), hint: intl.formatMessage(messages.layout_mobile_hint) },
            ]}
            onChange={onChange}
          >
            <FormattedMessage id='settings.layout' defaultMessage='Layout:' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['stretch']}
            id='mastodon-settings--stretch'
            onChange={onChange}
          >
            <FormattedMessage id='settings.wide_view' defaultMessage='Wide view (Desktop mode only)' />
            <FormattedMessage id='settings.wide_view_hint' defaultMessage='Stretches columns to better fill the available space.' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['navbar_under']}
            id='mastodon-settings--navbar_under'
            onChange={onChange}
          >
            <FormattedMessage id='settings.navbar_under' defaultMessage='Navbar at the bottom (Mobile only)' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['swipe_to_change_columns']}
            id='mastodon-settings--swipe_to_change_columns'
            onChange={onChange}
          >
            <FormattedMessage id='settings.swipe_to_change_columns' defaultMessage='Allow swiping to change columns (Mobile only)' />
          </LocalSettingsPageItem>

    ),
    ({ intl, onChange, settings }) => (

<FormattedMessage id='settings.compose_box_opts' defaultMessage='Compose box' />

        <LocalSettingsPageItem
          settings={settings}
          item={['always_show_spoilers_field']}
          id='mastodon-settings--always_show_spoilers_field'
          onChange={onChange}
        >
          <FormattedMessage id='settings.always_show_spoilers_field' defaultMessage='Always enable the Content Warning field' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['preselect_on_reply']}
          id='mastodon-settings--preselect_on_reply'
          onChange={onChange}
        >
          <FormattedMessage id='settings.preselect_on_reply' defaultMessage='Pre-select usernames on reply' />
          <FormattedMessage id='settings.preselect_on_reply_hint' defaultMessage='When replying to a conversation with multiple participants, pre-select usernames past the first' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['confirm_missing_media_description']}
          id='mastodon-settings--confirm_missing_media_description'
          onChange={onChange}
        >
          <FormattedMessage id='settings.confirm_missing_media_description' defaultMessage='Show confirmation dialog before sending toots lacking media descriptions' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['confirm_before_clearing_draft']}
          id='mastodon-settings--confirm_before_clearing_draft'
          onChange={onChange}
        >
          <FormattedMessage id='settings.confirm_before_clearing_draft' defaultMessage='Show confirmation dialog before overwriting the message being composed' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['show_content_type_choice']}
          id='mastodon-settings--show_content_type_choice'
          onChange={onChange}
        >
          <FormattedMessage id='settings.show_content_type_choice' defaultMessage='Show content-type choice when authoring toots' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['side_arm']}
          id='mastodon-settings--side_arm'
          options={[
            { value: 'none', message: intl.formatMessage(messages.side_arm_none) },
            { value: 'direct', message: intl.formatMessage({ id: 'privacy.direct.short' }) },
            { value: 'private', message: intl.formatMessage({ id: 'privacy.private.short' }) },
            { value: 'unlisted', message: intl.formatMessage({ id: 'privacy.unlisted.short' }) },
            { value: 'public', message: intl.formatMessage({ id: 'privacy.public.short' }) },
          ]}
          onChange={onChange}
        >
          <FormattedMessage id='settings.side_arm' defaultMessage='Secondary toot button:' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['side_arm_reply_mode']}
          id='mastodon-settings--side_arm_reply_mode'
          options={[
            { value: 'keep', message: intl.formatMessage(messages.side_arm_keep) },
            { value: 'copy', message: intl.formatMessage(messages.side_arm_copy) },
            { value: 'restrict', message: intl.formatMessage(messages.side_arm_restrict) },
          ]}
          onChange={onChange}
        >
          <FormattedMessage id='settings.side_arm_reply_mode' defaultMessage='When replying to a toot:' />
        </LocalSettingsPageItem>

    ),
    ({ intl, onChange, settings }) => (

<FormattedMessage id='settings.content_warnings' defaultMessage='Content warnings' />

        <LocalSettingsPageItem
          settings={settings}
          item={['content_warnings', 'auto_unfold']}
          id='mastodon-settings--content_warnings-auto_unfold'
          onChange={onChange}
        >
          <FormattedMessage id='settings.enable_content_warnings_auto_unfold' defaultMessage='Automatically unfold content-warnings' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['content_warnings', 'filter']}
          id='mastodon-settings--content_warnings-auto_unfold'
          onChange={onChange}
          dependsOn={[['content_warnings', 'auto_unfold']]}
          placeholder={intl.formatMessage(messages.regexp)}
        >
          <FormattedMessage id='settings.content_warnings_filter' defaultMessage='Content warnings to not automatically unfold:' />
        </LocalSettingsPageItem>

    ),
    ({ onChange, settings }) => (

<FormattedMessage id='settings.collapsed_statuses' defaultMessage='Collapsed toots' />

        <LocalSettingsPageItem
          settings={settings}
          item={['collapsed', 'enabled']}
          id='mastodon-settings--collapsed-enabled'
          onChange={onChange}
        >
          <FormattedMessage id='settings.enable_collapsed' defaultMessage='Enable collapsed toots' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['collapsed', 'show_action_bar']}
          id='mastodon-settings--collapsed-show-action-bar'
          onChange={onChange}
          dependsOn={[['collapsed', 'enabled']]}
        >
          <FormattedMessage id='settings.show_action_bar' defaultMessage='Show action buttons in collapsed toots' />
        </LocalSettingsPageItem>

<FormattedMessage id='settings.auto_collapse' defaultMessage='Automatic collapsing' />

          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'all']}
            id='mastodon-settings--collapsed-auto-all'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
          >
            <FormattedMessage id='settings.auto_collapse_all' defaultMessage='Everything' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'notifications']}
            id='mastodon-settings--collapsed-auto-notifications'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_notifications' defaultMessage='Notifications' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'lengthy']}
            id='mastodon-settings--collapsed-auto-lengthy'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_lengthy' defaultMessage='Lengthy toots' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'reblogs']}
            id='mastodon-settings--collapsed-auto-reblogs'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_reblogs' defaultMessage='Boosts' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'replies']}
            id='mastodon-settings--collapsed-auto-replies'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_replies' defaultMessage='Replies' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'auto', 'media']}
            id='mastodon-settings--collapsed-auto-media'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
            dependsOnNot={[['collapsed', 'auto', 'all']]}
          >
            <FormattedMessage id='settings.auto_collapse_media' defaultMessage='Toots with media' />
          </LocalSettingsPageItem>

<FormattedMessage id='settings.image_backgrounds' defaultMessage='Image backgrounds' />

          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'backgrounds', 'user_backgrounds']}
            id='mastodon-settings--collapsed-user-backgrouns'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
          >
            <FormattedMessage id='settings.image_backgrounds_users' defaultMessage='Give collapsed toots an image background' />
          </LocalSettingsPageItem>
          <LocalSettingsPageItem
            settings={settings}
            item={['collapsed', 'backgrounds', 'preview_images']}
            id='mastodon-settings--collapsed-preview-images'
            onChange={onChange}
            dependsOn={[['collapsed', 'enabled']]}
          >
            <FormattedMessage id='settings.image_backgrounds_media' defaultMessage='Preview collapsed toot media' />
          </LocalSettingsPageItem>

    ),
    ({ onChange, settings }) => (

<FormattedMessage id='settings.media' defaultMessage='Media' />

        <LocalSettingsPageItem
          settings={settings}
          item={['media', 'letterbox']}
          id='mastodon-settings--media-letterbox'
          onChange={onChange}
        >
          <FormattedMessage id='settings.media_letterbox' defaultMessage='Letterbox media' />
          <FormattedMessage id='settings.media_letterbox_hint' defaultMessage='Scale down and letterbox media to fill the image containers instead of stretching and cropping them' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['media', 'fullwidth']}
          id='mastodon-settings--media-fullwidth'
          onChange={onChange}
        >
          <FormattedMessage id='settings.media_fullwidth' defaultMessage='Full-width media previews' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['inline_preview_cards']}
          id='mastodon-settings--inline-preview-cards'
          onChange={onChange}
        >
          <FormattedMessage id='settings.inline_preview_cards' defaultMessage='Inline preview cards for external links' />
        </LocalSettingsPageItem>
        <LocalSettingsPageItem
          settings={settings}
          item={['media', 'reveal_behind_cw']}
          id='mastodon-settings--reveal-behind-cw'
          onChange={onChange}
        >
          <FormattedMessage id='settings.media_reveal_behind_cw' defaultMessage='Reveal sensitive media behind a CW by default' />
        </LocalSettingsPageItem>

    ),
  ];

  render () {
    const { pages } = this;
    const { index, intl, onChange, settings } = this.props;
    const CurrentPage = pages[index] || pages[0];

    return <CurrentPage intl={intl} onChange={onChange} settings={settings} />;
  }

}
<|endoftext|>


<commit_before>'use strict';

angular.module('ehelseEditor').factory('Document', ['$rootScope', 'DocumentField', 'Topic', function($rootScope, DocumentField, Topic) {

    function newDocument() {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "1",
            standardId: null,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        };
    }

    function newProfile(standardId) {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "2",
            standardId: standardId,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        }
    }

    var current_document = newDocument();
    var topic_documents = [];
    var link_category_list = [];
    var documents = [];
    var documents_dict = {};
    var topics_documents_dict = {};

    function extendCurrentDocumentTargetGroupsByTargetGroupIds(target_groups_ids) {
        for (var i = 0; i < target_groups_ids.length; i++) {
            current_document.targetGroups.push({
                targetGroupId: target_groups_ids[i],
                description: "",
                actionId: null,
                deadline: "",
                mandatoryId: null
            });
        }
    }

    function extendCurrentDocumentFieldsByFieldIds(field_ids) {
        for (var i = 0; i < field_ids.length; i++) {
            current_document.fields.push({fieldId: field_ids[i], value: ""});
        }
    }

    function removeTargetGroup(group) {

        var index = current_document.targetGroups.indexOf(group);
        if (index > -1) {
            current_document.targetGroups.splice(index, 1);
        }
    }

    function removeField(field) {

        var index = current_document.fields.indexOf(field);
        if (index > -1) {
            current_document.fields.splice(index, 1);
        }
    }

    function removeCurrentDocumentLink(link) {

        var index = current_document.links.indexOf(link);
        if (index > -1) {
            current_document.links.splice(index, 1);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function submitCurrentDocument() {
        current_document.populatedProfiles.length = 0;
        if (current_document.id) {

            $rootScope.put(
                'documents/' + current_document.id,
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    setCurrentDocument(current_document);
                    updateDocumentInDocumentsList(data);
                    $rootScope.notifySuccess("Dokumentet ble oppdatert", 3000);
                }
                ,
                function (data) {
                    var error = getErrorMessage(data);
                    setCurrentDocument(current_document);
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes: " + error, 6000);
                }
            );
        }
        else {
            $rootScope.post(
                'documents/',
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    //push profile id to standard
                    if(data.standardId){
                        documents_dict[data.standardId].profiles.push({id:data.id});
                        console.log(documents_dict[data.standardId].profiles);
                    }
                    if( data.previousDocumentId){
                        documents_dict[data.previousDocumentId].nextDocumentId = data.id;
                    }
                    documents.push(data);
                    generateDocumentDict(documents);
                    generateTopicsDocumentsDict(documents);
                    setCurrentDocument(data);
                    $rootScope.notifySuccess("Ny standard ble opprettet", 3000);
                    $rootScope.buttonState = 'editDocument';
                }
                ,
                function (data) {
                    var error = getErrorMessage(data);
                    setCurrentDocument(current_document);
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes: " + error, 6000);
                }
            );
        }
    }

    function getErrorMessage(error){
        var error_message = "";
        var message = error.message;
        var INTERNAL_ID = "Internal id";
        var HIS = "HIS";

        if(message.indexOf(INTERNAL_ID) > -1){
            error_message = "Intern ID må være unik";
        }
        else if (message.indexOf(HIS) > -1){
            error_message = "HIS nummer må være unik";
        }
        return error_message;
    }

    function deleteCurrentDocument() {
        $rootScope.delete(
            'documents/' + current_document.id,
            function(){
                deleteCurrentDocumentFromDocumentsList();
                $rootScope.notifySuccess("Dokumentet ble slettet", 3000);
                $rootScope.changeContentView('');
            },
            function(){
                console.log("Document could not be deleted");
                $rootScope.notifyError("Dokument kunne ikke bli slettet", 6000);
            }
        )
    }

    function getCurrentDocument() {
        return current_document;
    }

    function getTargetGroupsIdsHelper(targetGroups) {
        var ids = [];
        for (var i = 0; i < targetGroups.length; i++) {
            ids.push(targetGroups[i].targetGroupId);
        }
        return ids;
    }

    function getTargetGroupsIds() {
        return getTargetGroupsIdsHelper(current_document.targetGroups);
    }

    function updateDocumentInDocumentsList(document) {
        setDocument(documents_dict[document.id], document);
        generateTopicsDocumentsDict(documents);
    }

    function deleteCurrentDocumentFromDocumentsList() {
        if(documents_dict[current_document.nextDocumentId]){
            documents_dict[current_document.nextDocumentId].previousDocumentId = null;
        }
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == current_document.id) {
                documents.splice(i,1);
                break;
            }
        }
        generateTopicsDocumentsDict(documents);
    }

    function getDocumentFieldIdsHelper(documentFields) {
        var ids = [];
        for (var i = 0; i < documentFields.length; i++) {
            ids.push(documentFields[i].fieldId);
        }
        return ids;
    }

    function getCurrentDocumentFieldIds() {
        return getDocumentFieldIdsHelper(current_document.fields);
    }

    function setDocument(a, b) {
        a.id = b.id;
        a.topicId = b.topicId;
        a.title = b.title;
        a.documentTypeId = b.documentTypeId;
        a.statusId = b.statusId;
        a.internalId = b.internalId;
        a.hisNumber = b.hisNumber;
        a.nextDocumentId = b.nextDocumentId;
        a.previousDocumentId = b.previousDocumentId;
        a.description = b.description;
        a.sequence = b.sequence;
        a.comment = b.comment;
        a.targetGroups = b.targetGroups;
        a.fields = b.fields;
        a.links = b.links;
        a.standardId = b.standardId;
        a.populatedProfiles = b.populatedProfiles || [];
    }

    function clone(document){
        var d = {};
        setDocument(d, document);
        return d;
    }

    function setCurrentDocument(document) {
        if (!document) {
            document = newDocument();
            setDocument(current_document, document);
            setCurrentDocumentFieldsByDocumentDocumentTypeId();
        }
        else {
            setDocument(current_document, document);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();

        if(document.standardId){
            getRelatedProfiles(document);
        }else{
            getProfiles(document)
        }
    }

    function getDocumentsByTopicId(id) {
        return topics_documents_dict[id];
    }

    function setCurrentDocumentFieldsByDocumentDocumentTypeId() {
        current_document.fields.length = 0;
        extendCurrentDocumentFieldsByFieldIds(DocumentField.getRequiredDocumentFieldIdsByDocumentTypeId(current_document.documentTypeId))
    }

    function generateCurrentDocumentLinksAsLinkCategoryList() {

        var link_category_dict = {};
        for (var i = 0; i < current_document.links.length; i++) {
            var link = current_document.links[i];
            if (!link_category_dict[link.linkCategoryId]) {
                link_category_dict[link.linkCategoryId] = {id: link.linkCategoryId, links: []};
            }
            link_category_dict[link.linkCategoryId].links.push(link);
        }
        link_category_list.length = 0;

        for (var prop in link_category_dict) {
            // skip loop if the property is from prototype
            if (!link_category_dict.hasOwnProperty(prop)) continue;

            link_category_list.push(link_category_dict[prop]);
        }
    }

    function getCurrentDocumentLinksAsLinkCategoryList() {
        return link_category_list;
    }

    function getCurrentDocumentLinkCategoriesIds() {
        var link_category_ids = [];
        for (var i = 0; i < current_document.links.length; i++) {
            link_category_ids.push(current_document.links[i].linkCategoryId);
        }
        return link_category_ids;
    }

    function extendCurrentDocumentLinkCategoriesByLinkCategoriesIds(ids) {
        for (var i = 0; i < ids.length; i++) {
            addLinkToCurrentDocumentByLinkCategoryId(ids[i]);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function addLinkToCurrentDocumentByLinkCategoryId(id) {
        current_document.links.push({linkCategoryId: id, text: "", url: ""});
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function removeCurrentDocumentLinksByCategoryId(linkCategoryId) {
        var tmp_list = [];
        for (var i = 0; i < current_document.links.length; i++) {
            if (current_document.links[i].linkCategoryId != linkCategoryId) {
                tmp_list.push(current_document.links[i]);
            }
        }
        current_document.links.length = 0;
        Array.prototype.push.apply(current_document.links, tmp_list);
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getNewProfile(standardId) {
        return newProfile(standardId);
    }

    function getAllDocuments() {
        $rootScope.get(
            'documents/',
            function (data) {
                documents.length = 0;

                for(var i = 0; i < data.documents.length; i++){
                    var document = data.documents[i];
                    document.populatedProfiles = [];
                    documents.push(document);
                }

                generateDocumentDict(documents);
                generateTopicsDocumentsDict(documents);
            },
            function () {
                console.log("Could not load documents");
            }
        );
    }

    function newVersion(document){
        var new_version = clone(document);
        new_version.previousDocumentId = new_version.id;
        new_version.id = null;
        return new_version;
    }

    function generateDocumentDict(documents){
        for(var i = 0; i < documents.length; i++){
            documents_dict[documents[i].id] = documents[i];
        }
    }

    function generateTopicsDocumentsDict(documents){
        var topics = Topic.getAllAsDict();

        for(var id in topics) {
            if(Array.isArray(topics_documents_dict[id])){
                topics_documents_dict[id].length = 0;
            }
            else{
                topics_documents_dict[id] = [];
            }
        }

        var document;
        for(var i = 0; i < documents.length; i++){
            document = documents[i];
            if(!topics_documents_dict[document.topicId]){
                topics_documents_dict[document.topicId] = [];
            }
            topics_documents_dict[document.topicId].push(document);
        }
    }

    function getAll(){
        return documents;
    }

    function getProfiles(document) {

        var profiles = null;
        if(documents_dict[document.id]) {
            profiles = documents_dict[document.id].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    function getRelatedProfiles(document) {

        var profiles = null;
        if(documents_dict[document.standardId]) {
            profiles = documents_dict[document.standardId].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    getAllDocuments();

    function getAllAsDict(){
        return documents_dict;
    }

    function getById(id){
        return documents_dict[id];
    }

    return {
        getCurrentDocumentTargetGroupsIds: getTargetGroupsIds,
        getCurrentDocument: getCurrentDocument,
        extendCurrentDocumentTargetGroupsByTargetGroupIds: extendCurrentDocumentTargetGroupsByTargetGroupIds,
        removeCurrentDocumentTargetGroup: removeTargetGroup,
        submitCurrentDocument: submitCurrentDocument,
        setCurrentDocument: setCurrentDocument,
        getNewProfile: getNewProfile,
        newVersion: newVersion,
        getAll: getAll,
        getAllAsDict: getAllAsDict,
        getById: getById,
        deleteCurrentDocument: deleteCurrentDocument,
        getCurrentDocumentFieldIds: getCurrentDocumentFieldIds,
        extendCurrentDocumentFieldsByFieldIds: extendCurrentDocumentFieldsByFieldIds,
        removeCurrentDocumentField: removeField,
        getDocumentsByTopicId: getDocumentsByTopicId,
        setCurrentDocumentFieldsByDocumentDocumentTypeId: setCurrentDocumentFieldsByDocumentDocumentTypeId,
        getCurrentDocumentLinksAsLinkCategoryList: getCurrentDocumentLinksAsLinkCategoryList,
        getCurrentDocumentLinkCategoriesIds: getCurrentDocumentLinkCategoriesIds,
        extendCurrentDocumentLinkCategoriesByLinkCategoriesIds: extendCurrentDocumentLinkCategoriesByLinkCategoriesIds,
        addLinkToCurrentDocumentByLinkCategoryId: addLinkToCurrentDocumentByLinkCategoryId,
        removeCurrentDocumentLink: removeCurrentDocumentLink,
        removeCurrentDocumentLinksByCategoryId: removeCurrentDocumentLinksByCategoryId
    };
}]);
<commit_msg>Fixed document bug<commit_after>'use strict';

angular.module('ehelseEditor').factory('Document', ['$rootScope', 'DocumentField', 'Topic', function($rootScope, DocumentField, Topic) {

    function newDocument() {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "1",
            standardId: null,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        };
    }

    function newProfile(standardId) {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "2",
            standardId: standardId,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        }
    }

    var current_document = newDocument();
    var topic_documents = [];
    var link_category_list = [];
    var documents = [];
    var documents_dict = {};
    var topics_documents_dict = {};

    function extendCurrentDocumentTargetGroupsByTargetGroupIds(target_groups_ids) {
        for (var i = 0; i < target_groups_ids.length; i++) {
            current_document.targetGroups.push({
                targetGroupId: target_groups_ids[i],
                description: "",
                actionId: null,
                deadline: "",
                mandatoryId: null
            });
        }
    }

    function extendCurrentDocumentFieldsByFieldIds(field_ids) {
        for (var i = 0; i < field_ids.length; i++) {
            current_document.fields.push({fieldId: field_ids[i], value: ""});
        }
    }

    function removeTargetGroup(group) {

        var index = current_document.targetGroups.indexOf(group);
        if (index > -1) {
            current_document.targetGroups.splice(index, 1);
        }
    }

    function removeField(field) {

        var index = current_document.fields.indexOf(field);
        if (index > -1) {
            current_document.fields.splice(index, 1);
        }
    }

    function removeCurrentDocumentLink(link) {

        var index = current_document.links.indexOf(link);
        if (index > -1) {
            current_document.links.splice(index, 1);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function submitCurrentDocument() {
        current_document.populatedProfiles.length = 0;
        if (current_document.id) {

            $rootScope.put(
                'documents/' + current_document.id,
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    setCurrentDocument(current_document);
                    updateDocumentInDocumentsList(data);
                    $rootScope.notifySuccess("Dokumentet ble oppdatert", 3000);
                }
                ,
                function (data) {
                    var error = getErrorMessage(data);
                    setCurrentDocument(current_document);
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes: " + error, 6000);
                }
            );
        }
        else {
            $rootScope.post(
                'documents/',
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    //push profile id to standard
                    if(data.standardId){
                        documents_dict[data.standardId].profiles.push({id:data.id});
                        console.log(documents_dict[data.standardId].profiles);
                    }
                    if( data.previousDocumentId){
                        documents_dict[data.previousDocumentId].nextDocumentId = data.id;
                    }
                    documents.push(data);
                    generateDocumentDict(documents);
                    generateTopicsDocumentsDict(documents);
                    setCurrentDocument(data);
                    $rootScope.notifySuccess("Ny standard ble opprettet", 3000);
                    $rootScope.buttonState = 'editDocument';
                }
                ,
                function (data) {
                    var error = getErrorMessage(data);
                    setCurrentDocument(current_document);
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes: " + error, 6000);
                }
            );
        }
    }

    function getErrorMessage(error){
        var error_message = "";
        var message = error.message;
        var INTERNAL_ID = "Internal id";
        var HIS = "HIS";

        if(message.indexOf(INTERNAL_ID) > -1){
            error_message = "Intern ID må være unik";
        }
        else if (message.indexOf(HIS) > -1){
            error_message = "HIS nummer må være unik";
        }
        return error_message;
    }

    function deleteCurrentDocument() {
        $rootScope.delete(
            'documents/' + current_document.id,
            function(){
                deleteCurrentDocumentFromDocumentsList();
                $rootScope.notifySuccess("Dokumentet ble slettet", 3000);
                $rootScope.changeContentView('');
            },
            function(){
                console.log("Document could not be deleted");
                $rootScope.notifyError("Dokument kunne ikke bli slettet", 6000);
            }
        )
    }

    function getCurrentDocument() {
        return current_document;
    }

    function getTargetGroupsIdsHelper(targetGroups) {
        var ids = [];
        for (var i = 0; i < targetGroups.length; i++) {
            ids.push(targetGroups[i].targetGroupId);
        }
        return ids;
    }

    function getTargetGroupsIds() {
        return getTargetGroupsIdsHelper(current_document.targetGroups);
    }

    function updateDocumentInDocumentsList(document) {
        setDocument(documents_dict[document.id], document);
        generateTopicsDocumentsDict(documents);
    }

    function deleteCurrentDocumentFromDocumentsList() {
        if(documents_dict[current_document.nextDocumentId]){
            documents_dict[current_document.nextDocumentId].previousDocumentId = null;
        }
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == current_document.id) {
                documents.splice(i,1);
                break;
            }
        }
        generateTopicsDocumentsDict(documents);
    }

    function getDocumentFieldIdsHelper(documentFields) {
        var ids = [];
        for (var i = 0; i < documentFields.length; i++) {
            ids.push(documentFields[i].fieldId);
        }
        return ids;
    }

    function getCurrentDocumentFieldIds() {
        return getDocumentFieldIdsHelper(current_document.fields);
    }

    function setDocument(a, b) {
        a.id = b.id;
        a.topicId = b.topicId;
        a.title = b.title;
        a.documentTypeId = b.documentTypeId;
        a.statusId = b.statusId;
        a.internalId = b.internalId;
        a.hisNumber = b.hisNumber;
        a.nextDocumentId = b.nextDocumentId;
        a.previousDocumentId = b.previousDocumentId;
        a.description = b.description;
        a.sequence = b.sequence;
        a.comment = b.comment;
        a.targetGroups = b.targetGroups;
        a.fields = b.fields;
        a.links = b.links;
        a.standardId = b.standardId;
        a.populatedProfiles = b.populatedProfiles || [];
    }

    function clone(document){
        var d = {};
        setDocument(d, document);
        return d;
    }

    function setCurrentDocument(document) {
        if (!document) {
            document = newDocument();
            setDocument(current_document, document);
            setCurrentDocumentFieldsByDocumentDocumentTypeId();
        }
        else {
            setDocument(current_document, document);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();

        if(document.standardId){
            getRelatedProfiles(document);
        }else{
            getProfiles(document)
        }
    }

    function getDocumentsByTopicId(id) {
        if(!Array.isArray(topics_documents_dict[id])){
            topics_documents_dict[id] = [];
        }
        return topics_documents_dict[id];
    }

    function setCurrentDocumentFieldsByDocumentDocumentTypeId() {
        current_document.fields.length = 0;
        extendCurrentDocumentFieldsByFieldIds(DocumentField.getRequiredDocumentFieldIdsByDocumentTypeId(current_document.documentTypeId))
    }

    function generateCurrentDocumentLinksAsLinkCategoryList() {

        var link_category_dict = {};
        for (var i = 0; i < current_document.links.length; i++) {
            var link = current_document.links[i];
            if (!link_category_dict[link.linkCategoryId]) {
                link_category_dict[link.linkCategoryId] = {id: link.linkCategoryId, links: []};
            }
            link_category_dict[link.linkCategoryId].links.push(link);
        }
        link_category_list.length = 0;

        for (var prop in link_category_dict) {
            // skip loop if the property is from prototype
            if (!link_category_dict.hasOwnProperty(prop)) continue;

            link_category_list.push(link_category_dict[prop]);
        }
    }

    function getCurrentDocumentLinksAsLinkCategoryList() {
        return link_category_list;
    }

    function getCurrentDocumentLinkCategoriesIds() {
        var link_category_ids = [];
        for (var i = 0; i < current_document.links.length; i++) {
            link_category_ids.push(current_document.links[i].linkCategoryId);
        }
        return link_category_ids;
    }

    function extendCurrentDocumentLinkCategoriesByLinkCategoriesIds(ids) {
        for (var i = 0; i < ids.length; i++) {
            addLinkToCurrentDocumentByLinkCategoryId(ids[i]);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function addLinkToCurrentDocumentByLinkCategoryId(id) {
        current_document.links.push({linkCategoryId: id, text: "", url: ""});
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function removeCurrentDocumentLinksByCategoryId(linkCategoryId) {
        var tmp_list = [];
        for (var i = 0; i < current_document.links.length; i++) {
            if (current_document.links[i].linkCategoryId != linkCategoryId) {
                tmp_list.push(current_document.links[i]);
            }
        }
        current_document.links.length = 0;
        Array.prototype.push.apply(current_document.links, tmp_list);
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getNewProfile(standardId) {
        return newProfile(standardId);
    }

    function getAllDocuments() {
        $rootScope.get(
            'documents/',
            function (data) {
                documents.length = 0;

                for(var i = 0; i < data.documents.length; i++){
                    var document = data.documents[i];
                    document.populatedProfiles = [];
                    documents.push(document);
                }

                generateDocumentDict(documents);
                generateTopicsDocumentsDict(documents);
            },
            function () {
                console.log("Could not load documents");
            }
        );
    }

    function newVersion(document){
        var new_version = clone(document);
        new_version.previousDocumentId = new_version.id;
        new_version.id = null;
        return new_version;
    }

    function generateDocumentDict(documents){
        for(var i = 0; i < documents.length; i++){
            documents_dict[documents[i].id] = documents[i];
        }
    }

    function generateTopicsDocumentsDict(documents){
        var topics = Topic.getAllAsDict();

        for(var id in topics) {
            if(Array.isArray(topics_documents_dict[id])){
                topics_documents_dict[id].length = 0;
            }
            else{
                topics_documents_dict[id] = [];
            }
        }

        var document;
        for(var i = 0; i < documents.length; i++){
            document = documents[i];
            if(!Array.isArray(topics_documents_dict[document.topicId])){
                topics_documents_dict[document.topicId] = [];
            }
            topics_documents_dict[document.topicId].push(document);
        }
    }

    function getAll(){
        return documents;
    }

    function getProfiles(document) {

        var profiles = null;
        if(documents_dict[document.id]) {
            profiles = documents_dict[document.id].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    function getRelatedProfiles(document) {

        var profiles = null;
        if(documents_dict[document.standardId]) {
            profiles = documents_dict[document.standardId].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    getAllDocuments();

    function getAllAsDict(){
        return documents_dict;
    }

    function getById(id){
        return documents_dict[id];
    }

    return {
        getCurrentDocumentTargetGroupsIds: getTargetGroupsIds,
        getCurrentDocument: getCurrentDocument,
        extendCurrentDocumentTargetGroupsByTargetGroupIds: extendCurrentDocumentTargetGroupsByTargetGroupIds,
        removeCurrentDocumentTargetGroup: removeTargetGroup,
        submitCurrentDocument: submitCurrentDocument,
        setCurrentDocument: setCurrentDocument,
        getNewProfile: getNewProfile,
        newVersion: newVersion,
        getAll: getAll,
        getAllAsDict: getAllAsDict,
        getById: getById,
        deleteCurrentDocument: deleteCurrentDocument,
        getCurrentDocumentFieldIds: getCurrentDocumentFieldIds,
        extendCurrentDocumentFieldsByFieldIds: extendCurrentDocumentFieldsByFieldIds,
        removeCurrentDocumentField: removeField,
        getDocumentsByTopicId: getDocumentsByTopicId,
        setCurrentDocumentFieldsByDocumentDocumentTypeId: setCurrentDocumentFieldsByDocumentDocumentTypeId,
        getCurrentDocumentLinksAsLinkCategoryList: getCurrentDocumentLinksAsLinkCategoryList,
        getCurrentDocumentLinkCategoriesIds: getCurrentDocumentLinkCategoriesIds,
        extendCurrentDocumentLinkCategoriesByLinkCategoriesIds: extendCurrentDocumentLinkCategoriesByLinkCategoriesIds,
        addLinkToCurrentDocumentByLinkCategoryId: addLinkToCurrentDocumentByLinkCategoryId,
        removeCurrentDocumentLink: removeCurrentDocumentLink,
        removeCurrentDocumentLinksByCategoryId: removeCurrentDocumentLinksByCategoryId
    };
}]);
<|endoftext|>


<commit_before>var util = require('util')
var fs = require('fs')

var escapeMessage = function (message) {
  if (message === null || message === undefined) {
    return ''
  }

  return message.toString()
    .replace(/\|/g, '||')
    .replace(/\'/g, "|'")
    .replace(/\n/g, '|n')
    .replace(/\r/g, '|r')
    .replace(/\u0085/g, '|x')
    .replace(/\u2028/g, '|l')
    .replace(/\u2029/g, '|p')
    .replace(/\[/g, '|[')
    .replace(/\]/g, '|]')
}

var formatMessage = function () {
  var args = Array.prototype.slice.call(arguments)

  for (var i = args.length - 1; i > 0; i--) {
    args[i] = escapeMessage(args[i])
  }
  return util.format.apply(null, args) + '\n'
}

var TeamcityReporter = function (baseReporterDecorator) {
  baseReporterDecorator(this)
  var self = this

  this.adapters = [fs.writeSync.bind(fs.writeSync, 1)]

  this.TEST_IGNORED = "##teamcity[testIgnored name='%s']"
  this.SUITE_START = "##teamcity[testSuiteStarted name='%s']"
  this.SUITE_END = "##teamcity[testSuiteFinished name='%s']"
  this.TEST_START = "##teamcity[testStarted name='%s']"
  this.TEST_FAILED = "##teamcity[testFailed name='%s' message='FAILED' details='%s']"
  this.TEST_END = "##teamcity[testFinished name='%s' duration='%s']"
  this.BLOCK_OPENED = "##teamcity[blockOpened name='%s']"
  this.BLOCK_CLOSED = "##teamcity[blockClosed name='%s']"

  var reporter = this
  var initializeBrowser = function (browser) {
    reporter.browserResults[browser.id] = {
      name: browser.name,
      log: [],
      lastSuite: null
    }
  }

  this.onRunStart = function (browsers) {
    this.write(formatMessage(this.BLOCK_OPENED, 'JavaScript Unit Tests'))

    this.browserResults = {}
    // Support Karma 0.10 (TODO: remove)
    browsers.forEach(initializeBrowser)
  }

  this.onBrowserStart = function (browser) {
    initializeBrowser(browser)
  }

  this.specSuccess = function (browser, result) {
    var log = this.getLog(browser, result)
    var testName = result.description

    log.push(formatMessage(this.TEST_START, testName))
    log.push(formatMessage(this.TEST_END, testName, result.time))
  }

  this.specFailure = function (browser, result) {
    var log = this.getLog(browser, result)
    var testName = result.description

    log.push(formatMessage(this.TEST_START, testName))
    log.push(formatMessage(this.TEST_FAILED, testName, result.log.join('\n\n')))
    log.push(formatMessage(this.TEST_END, testName, result.time))
  }

  this.specSkipped = function (browser, result) {
    var log = this.getLog(browser, result)
    var testName = result.description

    log.push(formatMessage(this.TEST_IGNORED, testName))
  }

  this.onRunComplete = function () {
    Object.keys(this.browserResults).forEach(function (browserId) {
      var browserResult = self.browserResults[browserId]
      self.flushLogs(browserResult)
    })
    self.write(formatMessage(self.BLOCK_CLOSED, 'JavaScript Unit Tests'))
  }

  this.getLog = function (browser, result) {
    var browserResult = this.browserResults[browser.id]
    return browserResult.log
  }

  this.flushLogs = function (browserResult) {
    self.write(browserResult.log.join(''))
    while (browserResult.log.length > 0) {
      browserResult.log.shift()
    }
  }
}

TeamcityReporter.$inject = ['baseReporterDecorator']

module.exports = {
  'reporter:teamcity': ['type', TeamcityReporter]
}
<commit_msg>use suite name and test description<commit_after>var util = require('util')
var fs = require('fs')

var escapeMessage = function (message) {
  if (message === null || message === undefined) {
    return ''
  }

  return message.toString()
    .replace(/\|/g, '||')
    .replace(/\'/g, "|'")
    .replace(/\n/g, '|n')
    .replace(/\r/g, '|r')
    .replace(/\u0085/g, '|x')
    .replace(/\u2028/g, '|l')
    .replace(/\u2029/g, '|p')
    .replace(/\[/g, '|[')
    .replace(/\]/g, '|]')
}

var formatMessage = function () {
  var args = Array.prototype.slice.call(arguments)

  for (var i = args.length - 1; i > 0; i--) {
    args[i] = escapeMessage(args[i])
  }
  return util.format.apply(null, args) + '\n'
}

var fullTestName = function (result) {
  return result.suite.join(' ') + ' ' + result.description
}

var TeamcityReporter = function (baseReporterDecorator) {
  baseReporterDecorator(this)
  var self = this

  this.adapters = [fs.writeSync.bind(fs.writeSync, 1)]

  this.TEST_IGNORED = "##teamcity[testIgnored name='%s']"
  this.SUITE_START = "##teamcity[testSuiteStarted name='%s']"
  this.SUITE_END = "##teamcity[testSuiteFinished name='%s']"
  this.TEST_START = "##teamcity[testStarted name='%s']"
  this.TEST_FAILED = "##teamcity[testFailed name='%s' message='FAILED' details='%s']"
  this.TEST_END = "##teamcity[testFinished name='%s' duration='%s']"
  this.BLOCK_OPENED = "##teamcity[blockOpened name='%s']"
  this.BLOCK_CLOSED = "##teamcity[blockClosed name='%s']"

  var reporter = this
  var initializeBrowser = function (browser) {
    reporter.browserResults[browser.id] = {
      name: browser.name,
      log: [],
      lastSuite: null
    }
  }

  this.onRunStart = function (browsers) {
    this.write(formatMessage(this.BLOCK_OPENED, 'JavaScript Unit Tests'))

    this.browserResults = {}
    // Support Karma 0.10 (TODO: remove)
    browsers.forEach(initializeBrowser)
  }

  this.onBrowserStart = function (browser) {
    initializeBrowser(browser)
  }

  this.specSuccess = function (browser, result) {
    var log = this.getLog(browser, result)
    var testName = fullTestName(result)

    log.push(formatMessage(this.TEST_START, testName))
    log.push(formatMessage(this.TEST_END, testName, result.time))
  }

  this.specFailure = function (browser, result) {
    var log = this.getLog(browser, result)
    var testName = fullTestName(result)

    log.push(formatMessage(this.TEST_START, testName))
    log.push(formatMessage(this.TEST_FAILED, testName, result.log.join('\n\n')))
    log.push(formatMessage(this.TEST_END, testName, result.time))
  }

  this.specSkipped = function (browser, result) {
    var log = this.getLog(browser, result)
    var testName = fullTestName(result)

    log.push(formatMessage(this.TEST_IGNORED, testName))
  }

  this.onRunComplete = function () {
    Object.keys(this.browserResults).forEach(function (browserId) {
      var browserResult = self.browserResults[browserId]
      self.flushLogs(browserResult)
    })
    self.write(formatMessage(self.BLOCK_CLOSED, 'JavaScript Unit Tests'))
  }

  this.getLog = function (browser, result) {
    var browserResult = this.browserResults[browser.id]
    return browserResult.log
  }

  this.flushLogs = function (browserResult) {
    self.write(browserResult.log.join(''))
    while (browserResult.log.length > 0) {
      browserResult.log.shift()
    }
  }
}

TeamcityReporter.$inject = ['baseReporterDecorator']

module.exports = {
  'reporter:teamcity': ['type', TeamcityReporter]
}
<|endoftext|>


<commit_before>import React from 'react';
import IconButton from '../../../components/icon_button';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';

const messages = defineMessages({
  upload: { id: 'upload_button.label', defaultMessage: 'Add media ({formats})' },
});

const SUPPORTED_FORMATS = 'JPEG, PNG, GIF, WebM, MP4, MOV, OGG, WAV, MP3, FLAC';

const makeMapStateToProps = () => {
  const mapStateToProps = state => ({
    acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']),
  });

  return mapStateToProps;
};

const iconStyle = {
  height: null,
  lineHeight: '27px',
};

export default @connect(makeMapStateToProps)
@injectIntl
class UploadButton extends ImmutablePureComponent {

  static propTypes = {
    disabled: PropTypes.bool,
    unavailable: PropTypes.bool,
    onSelectFile: PropTypes.func.isRequired,
    style: PropTypes.object,
    resetFileKey: PropTypes.number,
    acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired,
    intl: PropTypes.object.isRequired,
  };

  handleChange = (e) => {
    if (e.target.files.length > 0) {
      this.props.onSelectFile(e.target.files);
    }
  }

  handleClick = () => {
    this.fileElement.click();
  }

  setRef = (c) => {
    this.fileElement = c;
  }

  render () {
    const { intl, resetFileKey, unavailable, disabled, acceptContentTypes } = this.props;

    if (unavailable) {
      return null;
    }

    return (

        <IconButton icon='camera' title={intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} />

          {intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })}
          <input
            key={resetFileKey}
            ref={this.setRef}
            type='file'
            multiple
            accept={acceptContentTypes.toArray().join(',')}
            onChange={this.handleChange}
            disabled={disabled}
            style={{ display: 'none' }}
          />

    );
  }

}
<commit_msg>Change camera icon to paperclip icon in upload form (#11149)<commit_after>import React from 'react';
import IconButton from '../../../components/icon_button';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';

const messages = defineMessages({
  upload: { id: 'upload_button.label', defaultMessage: 'Add media ({formats})' },
});

const SUPPORTED_FORMATS = 'JPEG, PNG, GIF, WebM, MP4, MOV, OGG, WAV, MP3, FLAC';

const makeMapStateToProps = () => {
  const mapStateToProps = state => ({
    acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']),
  });

  return mapStateToProps;
};

const iconStyle = {
  height: null,
  lineHeight: '27px',
};

export default @connect(makeMapStateToProps)
@injectIntl
class UploadButton extends ImmutablePureComponent {

  static propTypes = {
    disabled: PropTypes.bool,
    unavailable: PropTypes.bool,
    onSelectFile: PropTypes.func.isRequired,
    style: PropTypes.object,
    resetFileKey: PropTypes.number,
    acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired,
    intl: PropTypes.object.isRequired,
  };

  handleChange = (e) => {
    if (e.target.files.length > 0) {
      this.props.onSelectFile(e.target.files);
    }
  }

  handleClick = () => {
    this.fileElement.click();
  }

  setRef = (c) => {
    this.fileElement = c;
  }

  render () {
    const { intl, resetFileKey, unavailable, disabled, acceptContentTypes } = this.props;

    if (unavailable) {
      return null;
    }

    return (

        <IconButton icon='paperclip' title={intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} />

          {intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })}
          <input
            key={resetFileKey}
            ref={this.setRef}
            type='file'
            multiple
            accept={acceptContentTypes.toArray().join(',')}
            onChange={this.handleChange}
            disabled={disabled}
            style={{ display: 'none' }}
          />

    );
  }

}
<|endoftext|>


<commit_before>/**
 * Created by pmcneil on 17/09/14.
 * Javascript mainly to do with the apniFormat displays
 * todo maybe re-name to format.js and split out the apninFormat specific bits
 */
$(function () {
    if (typeof internetExplorer !== 'undefined') {
        $.ajaxSetup({cache: false});
    }
    var lazyLoad = function () {
        var delay = 0;
        $('div.results > div > div.unfetched.name').each(function () {
                var el = $(this);
                var getName = function () {
                    var id = el.attr('id');
                    var format = el.data('format');
                    var product = el.data('product');
                    if (format != 'noneFormat') {
                        var url = format + "/name/" + id + "?product=" + product;
                        window.console && console.log("found a name, getting " + url);
                        $.get(url, function (data, status, request) {
                            window.console && console.log('status ' + status + ', request ' + request);
                            if (data !== undefined) {
                                var parentDiv = el.parent('div');
                                el.replaceWith(data);
                                $('.toggleNext').unbind('click').click(function () {
                                    toggleNext(this);
                                });
                                parentDiv.find("protologue-pdf").each(function () {
                                    checkProtologue(this);
                                });
                                parentDiv.find('branch').click(function(event){
                                    console.log('in branch');

                                    if($(event.target).is("a")) {
                                        // default behaviour on a hyperlink click
                                    }
                                    else {
                                        $(this).children('ul').toggle();
                                        event.preventDefault();
                                    }
                                });

                            }
                        });
                    }
                };
                window.setTimeout(getName, delay);
                delay = delay + 200;
            }
        )
        ;
    };
    window.setTimeout(lazyLoad, 100);

    $('.toggleNext').unbind('click').click(function () {
        toggleNext(this);
    });

    var toggleNext = function (el) {
        $(el).find('i').toggle();
        $(el).next('div').toggle(200);
    };

    $(".closeForm").click(function () {
        $('.openForm').show();
        $('.closeForm').hide();
        $('.panel-body > form.closable').toggle();
    });

    $(".openForm").click(function () {
        $('.openForm').hide();
        $('.closeForm').show();
        $('.panel-body > form.closable').toggle();
    });

    $(".hideSearch").each(function () {
        $('.closeForm').addClass('highlight').focus();

        window.setTimeout(function () {
            $('.openForm').show();
            $('.closeForm').hide();
            $('.closeForm').removeClass('highlight');
            $('.panel-body > form.closable').toggle(200);
        }, 1000);
    });

    $("#expandAll").click(function () {
        $('.instances').show();
        $('.fa-caret-down.toggleNext').hide();
        $('.fa-caret-up.toggleNext').show();
    });

    $("#collapseAll").click(function () {
        $('.instances').hide();
        $('.fa-caret-down.toggleNext').show();
        $('.fa-caret-up.toggleNext').hide();
    });

    $(".loadFormat").click(function () {
        var url = $(this).attr('href');
        var parent = $(this).parent('div');
        $.get(url, function (data, status, request) {
            window.console && console.log('status ' + status + ', request ' + request);
            if (data != undefined) {
                parent.html(data);
            }
            $('.toggleNext').unbind('click').click(function () {
                toggleNext(this);
            });
        });
        return false;
    });

    $(".suggest").each(function () {
        var action = $(this).data('subject');
        var context = $(this).data('context');
        var quoted = $(this).data('quoted');
        var actionurl = baseContextPath + '/suggest/' + action;
        if(context != undefined) {
            var contextElement = $("#"+context);
            var contextValue = contextElement.val();
            actionurl += '?context=' + encodeURIComponent(contextValue);
        }
        $(this).autocomplete({
            minLength: 1,
            source: actionurl,
            select: function (event, ui) {
                var qry = ui.item.value;
                if (quoted) {
                    qry = '"' + ui.item.value + '"';
                }
                $(this).val(qry);
                event.cancel();
            }
        });
    });

    $(".checkbig").submit(function () {
        var data = $(this).serialize();
        if (data.length > 4096) {
            $(this).attr('method', 'POST');
        }
    });

    $("foa").each(function () {
        var url = $(this).data('id');
        window.console && console.log("found foa, getting " + url);
        $.get(url, function (data, status, request) {
            window.console && console.log('status ' + status + ', request ' + request);
            if (data != undefined) {
                var html = $.parseHTML(data);
                var content = $(html).find('div.foa-content');
                var footer = $(html).find('div.foa-footer');
                $("foa").append(content);
                $("div.foa-content").append(footer);
            }
        });
    });

    var checkProtologue = function (el) {
        var thisEl = el;
        var url = $(el).data('id');
        var link = '';
        window.console && console.log("found protologue pdf, trying " + url);
        $.ajax({
            type: "HEAD",
            async: true,
            url: url,
            success: function () {
                window.console && console.log("protologue pdf exists");
                $(thisEl).append(link);
            }
        });
    };

    $("protologue-pdf").each(function () {
        checkProtologue(this);
    });

    $("#fontToggle").click(function (event) {
        var results = $('.results');
        var font = results.css("font-family");
        if (font.startsWith("\"Book")) {
            results.css("font-family", "\"Lucida Grande\", \"Helvetica Nueue\", Arial, sans-serif");
            $.cookie('resultFont', 'sans', {expires: 365});
        } else {
            results.css("font-family", "\"Bookman\", Georgia, \"Times New Roman\", serif");
            $.cookie('resultFont', 'serif', {expires: 365});
        }
        event.preventDefault();
    });

    $("#inRank")
        .each(function () {
            var el = $(this);
            if (el.val()) {
                $('#rankName').prop('disabled', false);
            } else {
                $('#rankName').val('').prop('disabled', true);
            }
        })
        .change(function (even) {
            var el = $(this);
            if (el.val()) {
                $('#rankName').prop('disabled', false).focus();
            } else {
                $('#rankName').val('').prop('disabled', true);
            }
        });

//check user preference for sans serif fonts on results
    var prefFont = $.cookie('resultFont');
    if (prefFont) {
        if (prefFont == 'sans') {
            $('.results').css("font-family", "\"Lucida Grande\", \"Helvetica Nueue\", Arial, sans-serif");
        }
    }

})
;

<commit_msg>NSL-1412 add context sensitive search on in rank autocomplete search<commit_after>/**
 * Created by pmcneil on 17/09/14.
 * Javascript mainly to do with the apniFormat displays
 * todo maybe re-name to format.js and split out the apninFormat specific bits
 */
$(function () {
    if (typeof internetExplorer !== 'undefined') {
        $.ajaxSetup({cache: false});
    }
    var lazyLoad = function () {
        var delay = 0;
        $('div.results > div > div.unfetched.name').each(function () {
                var el = $(this);
                var getName = function () {
                    var id = el.attr('id');
                    var format = el.data('format');
                    var product = el.data('product');
                    if (format != 'noneFormat') {
                        var url = format + "/name/" + id + "?product=" + product;
                        window.console && console.log("found a name, getting " + url);
                        $.get(url, function (data, status, request) {
                            window.console && console.log('status ' + status + ', request ' + request);
                            if (data !== undefined) {
                                var parentDiv = el.parent('div');
                                el.replaceWith(data);
                                $('.toggleNext').unbind('click').click(function () {
                                    toggleNext(this);
                                });
                                parentDiv.find("protologue-pdf").each(function () {
                                    checkProtologue(this);
                                });
                                parentDiv.find('branch').click(function (event) {
                                    console.log('in branch');

                                    if ($(event.target).is("a")) {
                                        // default behaviour on a hyperlink click
                                    }
                                    else {
                                        $(this).children('ul').toggle();
                                        event.preventDefault();
                                    }
                                });

                            }
                        });
                    }
                };
                window.setTimeout(getName, delay);
                delay = delay + 200;
            }
        )
        ;
    };
    window.setTimeout(lazyLoad, 100);

    $('.toggleNext').unbind('click').click(function () {
        toggleNext(this);
    });

    var toggleNext = function (el) {
        $(el).find('i').toggle();
        $(el).next('div').toggle(200);
    };

    $(".closeForm").click(function () {
        $('.openForm').show();
        $('.closeForm').hide();
        $('.panel-body > form.closable').toggle();
    });

    $(".openForm").click(function () {
        $('.openForm').hide();
        $('.closeForm').show();
        $('.panel-body > form.closable').toggle();
    });

    $(".hideSearch").each(function () {
        $('.closeForm').addClass('highlight').focus();

        window.setTimeout(function () {
            $('.openForm').show();
            $('.closeForm').hide();
            $('.closeForm').removeClass('highlight');
            $('.panel-body > form.closable').toggle(200);
        }, 1000);
    });

    $("#expandAll").click(function () {
        $('.instances').show();
        $('.fa-caret-down.toggleNext').hide();
        $('.fa-caret-up.toggleNext').show();
    });

    $("#collapseAll").click(function () {
        $('.instances').hide();
        $('.fa-caret-down.toggleNext').show();
        $('.fa-caret-up.toggleNext').hide();
    });

    $(".loadFormat").click(function () {
        var url = $(this).attr('href');
        var parent = $(this).parent('div');
        $.get(url, function (data, status, request) {
            window.console && console.log('status ' + status + ', request ' + request);
            if (data != undefined) {
                parent.html(data);
            }
            $('.toggleNext').unbind('click').click(function () {
                toggleNext(this);
            });
        });
        return false;
    });

    $(".suggest").each(function () {
        var action = $(this).data('subject');
        var context = $(this).data('context');
        var quoted = $(this).data('quoted');
        var actionurl = function (request, response) {
            var url = baseContextPath + '/suggest/' + action + '?term=' + encodeURIComponent(request.term);
            if (context != undefined) {
                var contextElement = $("#" + context);
                var contextValue = contextElement.val();
                url += '&context=' + encodeURIComponent(contextValue);
            }
            $.get(url, function (data, status, request) {
                response(data);
            });
        };
        $(this).autocomplete({
            minLength: 1,
            source: actionurl,
            select: function (event, ui) {
                var qry = ui.item.value;
                if (quoted) {
                    qry = '"' + ui.item.value + '"';
                }
                $(this).val(qry);
                event.cancel();
            }
        });
    });

    $(".checkbig").submit(function () {
        var data = $(this).serialize();
        if (data.length > 4096) {
            $(this).attr('method', 'POST');
        }
    });

    $("foa").each(function () {
        var url = $(this).data('id');
        window.console && console.log("found foa, getting " + url);
        $.get(url, function (data, status, request) {
            window.console && console.log('status ' + status + ', request ' + request);
            if (data != undefined) {
                var html = $.parseHTML(data);
                var content = $(html).find('div.foa-content');
                var footer = $(html).find('div.foa-footer');
                $("foa").append(content);
                $("div.foa-content").append(footer);
            }
        });
    });

    var checkProtologue = function (el) {
        var thisEl = el;
        var url = $(el).data('id');
        var link = '';
        window.console && console.log("found protologue pdf, trying " + url);
        $.ajax({
            type: "HEAD",
            async: true,
            url: url,
            success: function () {
                window.console && console.log("protologue pdf exists");
                $(thisEl).append(link);
            }
        });
    };

    $("protologue-pdf").each(function () {
        checkProtologue(this);
    });

    $("#fontToggle").click(function (event) {
        var results = $('.results');
        var font = results.css("font-family");
        if (font.startsWith("\"Book")) {
            results.css("font-family", "\"Lucida Grande\", \"Helvetica Nueue\", Arial, sans-serif");
            $.cookie('resultFont', 'sans', {expires: 365});
        } else {
            results.css("font-family", "\"Bookman\", Georgia, \"Times New Roman\", serif");
            $.cookie('resultFont', 'serif', {expires: 365});
        }
        event.preventDefault();
    });

    $("#inRank")
        .each(function () {
            var el = $(this);
            if (el.val()) {
                $('#rankName').prop('disabled', false);
            } else {
                $('#rankName').val('').prop('disabled', true);
            }
        })
        .change(function (even) {
            var el = $(this);
            if (el.val()) {
                $('#rankName').prop('disabled', false).focus();
            } else {
                $('#rankName').val('').prop('disabled', true);
            }
        });

//check user preference for sans serif fonts on results
    var prefFont = $.cookie('resultFont');
    if (prefFont) {
        if (prefFont == 'sans') {
            $('.results').css("font-family", "\"Lucida Grande\", \"Helvetica Nueue\", Arial, sans-serif");
        }
    }

})
;

<|endoftext|>


<commit_before>"use strict";
var querystring     = require("querystring");
var request         = require("request");
var async           = require("async");

var regex = "href=\"/watch([^\"]*)\"";
var youTubeUrl = "https://www.youtube.com";

var searchArray = ["", ""];

var searchInYouTube = function (searchString, cb) {
    var youTubeSearchUrl = youTubeUrl + "/results?" + querystring.stringify({"search_query": searchString});

    request(youTubeSearchUrl, function (err, response, body) {
        if (err) { return cb(err); }

        var regexResults = body.match(regex),
            path = regexResults[0], //href="/watch?v=T-sxSd1uwoU"
            url;

        url = path.replace("href=\"", youTubeUrl).replace("\"", "");
        return cb(null, url);
    });
};

async.map(searchArray, searchInYouTube, function (err, results) {
    if (err) { throw err; }
    console.log(results);
});

<commit_msg>Added file download<commit_after>"use strict";
var querystring     = require("querystring");
var request         = require("request");
var async           = require("async");
var http            = require('http');
var fs              = require('fs');

var regex = "href=\"/watch([^\"]*)\"";
var youTubeUrl = "http://www.youtube.com";
var youTubeToMp3URL = "http://youtubeinmp3.com/fetch/?video=";

var searchArray = [];

var searchInYouTube = function (searchString, cb) {
    var youTubeSearchUrl = youTubeUrl + "/results?" + querystring.stringify({"search_query": searchString});

    request(youTubeSearchUrl, function (err, response, body) {
        if (err) { return cb(err); }

        var regexResults = body.match(regex),
            path = regexResults[0], //href="/watch?v=T-sxSd1uwoU"
            url;

        url = path.replace("href=\"", youTubeUrl).replace("\"", "");
        return cb(null, {searchString: searchString, url: url});
    });
};

var downloadMp3 = function (result, cb) {
    var file = fs.createWriteStream(result.searchString + ".mp3");

    request(youTubeToMp3URL + result.url, function (err, response, fileUrl) {
        if (err) { return cb(err); }

        http.get(fileUrl, function (res) {
            console.log("Downloading MP3 for: " + result.searchString);
            res.pipe(file);

            res.on('end', function () {
                cb();
            });
        });
    });
};

async.map(searchArray, searchInYouTube, function (err, results) {
    if (err) { throw err; }

    async.each(results, downloadMp3, function (err) {
        if (err) { throw err; }

        console.log("All files downloaded");
    });
});

<|endoftext|>