text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
/* eslint-disable max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let ProxyManager const settings = require('@overleaf/settings') const logger = require('logger-sharelatex') const request = require('request') const URL = require('url') module.exports = ProxyManager = { apply(publicApiRouter) { return (() => { const result = [] for (var proxyUrl in settings.proxyUrls) { const target = settings.proxyUrls[proxyUrl] result.push( (function (target) { const method = (target.options != null ? target.options.method : undefined) || 'get' return publicApiRouter[method]( proxyUrl, ProxyManager.createProxy(target) ) })(target) ) } return result })() }, createProxy(target) { return function (req, res, next) { const targetUrl = makeTargetUrl(target, req) logger.log({ targetUrl, reqUrl: req.url }, 'proxying url') const options = { url: targetUrl } if (req.headers != null ? req.headers.cookie : undefined) { options.headers = { Cookie: req.headers.cookie } } if ((target != null ? target.options : undefined) != null) { Object.assign(options, target.options) } if (['post', 'put'].includes(options.method)) { options.form = req.body } const upstream = request(options) upstream.on('error', error => logger.error({ err: error }, 'error in ProxyManager') ) // TODO: better handling of status code // see https://github.com/overleaf/write_latex/wiki/Streams-and-pipes-in-Node.js return upstream.pipe(res) } }, } // make a URL from a proxy target. // if the query is specified, set/replace the target's query with the given query var makeTargetUrl = function (target, req) { const targetUrl = URL.parse(parseSettingUrl(target, req)) if (req.query != null && Object.keys(req.query).length > 0) { targetUrl.query = req.query targetUrl.search = null // clear `search` as it takes precedence over `query` } return targetUrl.format() } var parseSettingUrl = function (target, { params }) { let path if (typeof target === 'string') { return target } if (typeof target.path === 'function') { path = target.path(params) } else { ;({ path } = target) } return `${target.baseUrl}${path || ''}` }
overleaf/web/app/src/infrastructure/ProxyManager.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/ProxyManager.js", "repo_id": "overleaf", "token_count": 1052 }
493
const mongoose = require('../infrastructure/Mongoose') const { ProjectSchema } = require('./Project') const { Schema } = mongoose const { ObjectId } = Schema const DeleterDataSchema = new Schema({ deleterId: { type: ObjectId, ref: 'User' }, deleterIpAddress: { type: String }, deletedAt: { type: Date }, deletedProjectId: { type: ObjectId }, deletedProjectOwnerId: { type: ObjectId, ref: 'User' }, deletedProjectCollaboratorIds: [{ type: ObjectId, ref: 'User' }], deletedProjectReadOnlyIds: [{ type: ObjectId, ref: 'User' }], deletedProjectReadWriteTokenAccessIds: [{ type: ObjectId, ref: 'User' }], deletedProjectReadOnlyTokenAccessIds: [{ type: ObjectId, ref: 'User' }], deletedProjectReadWriteToken: { type: String }, deletedProjectReadOnlyToken: { type: String }, deletedProjectLastUpdatedAt: { type: Date }, deletedProjectOverleafId: { type: Number }, deletedProjectOverleafHistoryId: { type: Number }, }) const DeletedProjectSchema = new Schema( { deleterData: DeleterDataSchema, project: ProjectSchema, }, { collection: 'deletedProjects' } ) exports.DeletedProject = mongoose.model('DeletedProject', DeletedProjectSchema) exports.DeletedProjectSchema = DeletedProjectSchema
overleaf/web/app/src/models/DeletedProject.js/0
{ "file_path": "overleaf/web/app/src/models/DeletedProject.js", "repo_id": "overleaf", "token_count": 397 }
494
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const SamlLogSchema = new Schema( { createdAt: { type: Date, default: () => new Date() }, data: { type: Object }, jsonData: { type: String }, providerId: { type: String, default: '' }, sessionId: { type: String, default: '' }, }, { collection: 'samlLogs', } ) exports.SamlLog = mongoose.model('SamlLog', SamlLogSchema) exports.SamlLogSchema = SamlLogSchema
overleaf/web/app/src/models/SamlLog.js/0
{ "file_path": "overleaf/web/app/src/models/SamlLog.js", "repo_id": "overleaf", "token_count": 180 }
495
extends ../layout/layout-no-js block vars - metadata = { title: 'Unsupported browser', viewport: true } block body body.full-height main.content.content-alt.full-height#main-content .container.full-height .error-container.full-height .error-details h1.error-status Unsupported Browser p.error-description | Sorry, we don't support your browser anymore. Find out more about #[a(href="https://www.overleaf.com/learn/how-to/What_browsers_do_you_support") what browsers we support]. br | If you think you're seeing this message in error, please #[a(href="/contact") let us know]. if fromURL p | URL: | a(href=fromURL) #{fromURL}
overleaf/web/app/views/general/unsupported-browser.pug/0
{ "file_path": "overleaf/web/app/views/general/unsupported-browser.pug", "repo_id": "overleaf", "token_count": 290 }
496
div#history(ng-show="ui.view == 'history' && history.updates.length > 0") include ./history/entriesListV1 include ./history/entriesListV2 include ./history/diffPanelV1 include ./history/previewPanelV2 .full-size(ng-if="ui.view == 'history' && history.updates.length === 0 && !isHistoryLoading()") .no-history-available h3 | #{translate('no_history_available')} script(type="text/ng-template", id="historyRestoreDiffModalTemplate") .modal-header button.close( type="button" data-dismiss="modal" ng-click="cancel()" aria-label="Close" ) span(aria-hidden="true") × h3 #{translate("restore")} {{diff.doc.name}} .modal-body.modal-body-share p !{translate("sure_you_want_to_restore_before", {filename: "{{diff.doc.name}}", date:"{{diff.start_ts | formatDate}}"}, ['strong'])} .modal-footer button.btn.btn-default( ng-click="cancel()", ng-disabled="state.inflight" ) #{translate("cancel")} button.btn.btn-danger( ng-click="restore()", ng-disabled="state.inflight" ) span(ng-show="!state.inflight") #{translate("restore")} span(ng-show="state.inflight") #{translate("restoring")} … script(type="text/ng-template", id="historyLabelTpl") .history-label( ng-class="{\ 'history-label-own' : $ctrl.isOwnedByCurrentUser,\ 'history-label-pseudo-current-state': $ctrl.isPseudoCurrentStateLabel,\ }" ) span.history-label-comment( tooltip-append-to-body="true" tooltip-template="'historyLabelTooltipTpl'" tooltip-placement="left" tooltip-enable="$ctrl.showTooltip" ) i.fa.fa-tag |  {{ ::$ctrl.isPseudoCurrentStateLabel ? '#{translate("history_label_project_current_state")}' : $ctrl.labelText }} button.history-label-delete-btn( ng-if="$ctrl.isOwnedByCurrentUser && !$ctrl.isPseudoCurrentStateLabel" stop-propagation="click" ng-click="$ctrl.onLabelDelete()" aria-label=translate("delete") ) span(aria-hidden="true") × script(type="text/ng-template", id="historyLabelTooltipTpl") .history-label-tooltip p.history-label-tooltip-title i.fa.fa-tag |  {{ $ctrl.labelText }} p.history-label-tooltip-owner #{translate("history_label_created_by")} {{ $ctrl.labelOwnerName }} time.history-label-tooltip-datetime {{ $ctrl.labelCreationDateTime | formatDate }} script(type="text/ng-template", id="historyV2DeleteLabelModalTemplate") .modal-header h3 #{translate("history_delete_label")} .modal-body .alert.alert-danger(ng-show="state.error.message") {{ state.error.message}} .alert.alert-danger(ng-show="state.error && !state.error.message") #{translate("generic_something_went_wrong")} p(ng-if="labelDetails") | #{translate("history_are_you_sure_delete_label")} strong "{{ labelDetails.comment }}" | ? .modal-footer button.btn.btn-default( type="button" ng-disabled="state.inflight" ng-click="$dismiss()" ) #{translate("cancel")} button.btn.btn-primary( type="button" ng-click="deleteLabel()" ng-disabled="state.inflight" ) {{ state.inflight ? '#{translate("history_deleting_label")}' : '#{translate("history_delete_label")}' }}
overleaf/web/app/views/project/editor/history.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/history.pug", "repo_id": "overleaf", "token_count": 1254 }
497
extends ../../layout block content main.content.content-alt#main-content .container .row .col-md-8.col-md-offset-2 .card.project-invite-accept .page-header.text-centered h1(ng-non-bindable) #{translate("user_wants_you_to_see_project", {username:owner.first_name, projectname:""})} br em(ng-non-bindable) #{project.name} .row.text-center .col-md-12 p | #{translate("accepting_invite_as")}  em(ng-non-bindable) #{user.email} .row .col-md-12 form.form( name="acceptForm", method="POST", action="/project/"+invite.projectId+"/invite/token/"+invite.token+"/accept" ) input(name='_csrf', type='hidden', value=csrfToken) input(name='token', type='hidden', value=invite.token) .form-group.text-center button.btn.btn-lg.btn-primary(type="submit") | #{translate("join_project")} .form-group.text-center
overleaf/web/app/views/project/invite/show.pug/0
{ "file_path": "overleaf/web/app/views/project/invite/show.pug", "repo_id": "overleaf", "token_count": 514 }
498
extends ../layout block content main.content.content-alt#main-content .container .row .col-md-8.col-md-offset-2 .card(ng-cloak) .page-header h2 #{translate("subscription_canceled")} .alert.alert-info p #{translate("to_modify_your_subscription_go_to")} a(href="/user/subscription") #{translate("manage_subscription")}. p a.btn.btn-primary(href="/project") < #{translate("back_to_your_projects")}
overleaf/web/app/views/subscriptions/canceled_subscription.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/canceled_subscription.pug", "repo_id": "overleaf", "token_count": 219 }
499
extends ../layout block content main.content.content-alt#main-content .container .row .col-md-8.col-md-offset-2 .card(ng-cloak) .page-header h2 #{translate("thanks_for_subscribing")} .alert.alert-success if (personalSubscription.recurly.trial_ends_at) p !{translate("next_payment_of_x_collectected_on_y", {paymentAmmount: personalSubscription.recurly.price, collectionDate: personalSubscription.recurly.nextPaymentDueAt}, ['strong', 'strong'])} include ./_price_exceptions p #{translate("to_modify_your_subscription_go_to")} a(href="/user/subscription") #{translate("manage_subscription")}. p if (personalSubscription.groupPlan == true) a.btn.btn-success.btn-large(href=`/manage/groups/${personalSubscription._id}/members`) #{translate("add_your_first_group_member_now")} p.letter-from-founders p #{translate("thanks_for_subscribing_you_help_sl", {planName:personalSubscription.plan.name})} p #{translate("need_anything_contact_us_at")} a(href=`mailto:${settings.adminEmail}`, ng-non-bindable) #{settings.adminEmail} | . p #{translate("regards")}, br(ng-non-bindable) | The #{settings.appName} Team p a.btn.btn-primary(href="/project") < #{translate("back_to_your_projects")}
overleaf/web/app/views/subscriptions/successful_subscription.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/successful_subscription.pug", "repo_id": "overleaf", "token_count": 604 }
500
extends ../layout block append meta meta(name="ol-reconfirmationRemoveEmail", content=reconfirmationRemoveEmail) meta(name="ol-reconfirmedViaSAML", content=reconfirmedViaSAML) meta(name="ol-passwordStrengthOptions", data-type="json", content=settings.passwordStrengthOptions || {}) meta(name="ol-oauthProviders", data-type="json", content=oauthProviders) meta(name="ol-thirdPartyIds", data-type="json", content=thirdPartyIds) block content main.content.content-alt#main-content .container .row .col-md-12.col-lg-10.col-lg-offset-1 if ssoError .alert.alert-danger | #{translate('sso_link_error')}: #{translate(ssoError)} .card .page-header h1 #{translate("account_settings")} .account-settings(ng-controller="AccountSettingsController", ng-cloak) if hasFeature('affiliations') include settings/user-affiliations .row .col-md-5 h3 #{translate("update_account_info")} form(async-form="settings", name="settingsForm", method="POST", action="/user/settings", novalidate) input(type="hidden", name="_csrf", value=csrfToken) if !hasFeature('affiliations') if !externalAuthenticationSystemUsed() .form-group label(for='email') #{translate("email")} input.form-control( id="email" type='email', name='email', placeholder="email@example.com" required, ng-model="email", ng-model-options="{ updateOn: 'blur' }" ) span.small.text-danger(ng-show="settingsForm.email.$invalid && settingsForm.email.$dirty") | #{translate("must_be_email_address")} else // show the email, non-editable .form-group label.control-label #{translate("email")} div.form-control( readonly="true", ng-non-bindable ) #{user.email} if shouldAllowEditingDetails .form-group label(for='firstName').control-label #{translate("first_name")} input.form-control( id="firstName" type='text', name='first_name', value=user.first_name ng-non-bindable ) .form-group label(for='lastName').control-label #{translate("last_name")} input.form-control( id="lastName" type='text', name='last_name', value=user.last_name ng-non-bindable ) .form-group form-messages(aria-live="polite" for="settingsForm") .alert.alert-success(ng-show="settingsForm.response.success") | #{translate("thanks_settings_updated")} .actions button.btn.btn-primary( type='submit', ng-disabled="settingsForm.$invalid" ) #{translate("update")} else .form-group label.control-label #{translate("first_name")} div.form-control( readonly="true", ng-non-bindable ) #{user.first_name} .form-group label.control-label #{translate("last_name")} div.form-control( readonly="true", ng-non-bindable ) #{user.last_name} .col-md-5.col-md-offset-1 h3 #{translate("change_password")} if externalAuthenticationSystemUsed() && !settings.overleaf p Password settings are managed externally else if !hasPassword p | #[a(href="/user/password/reset", target='_blank') #{translate("no_existing_password")}] else - var submitAction - submitAction = '/user/password/update' form( async-form="changepassword" name="changePasswordForm" action=submitAction method="POST" novalidate ) input(type="hidden", name="_csrf", value=csrfToken) .form-group label(for='currentPassword') #{translate("current_password")} input.form-control( id="currentPassword" type='password', name='currentPassword', placeholder='*********', ng-model="currentPassword", required ) span.small.text-danger(ng-show="changePasswordForm.currentPassword.$invalid && changePasswordForm.currentPassword.$dirty" aria-live="polite") | #{translate("required")} .form-group label(for='passwordField') #{translate("new_password")} input.form-control( id='passwordField', type='password', name='newPassword1', placeholder='*********', ng-model="newPassword1", required, complex-password ) span.small.text-danger(ng-show="changePasswordForm.newPassword1.$error.complexPassword && changePasswordForm.newPassword1.$dirty", ng-bind-html="complexPasswordErrorMessage" aria-live="polite") .form-group label(for='newPassword2') #{translate("confirm_new_password")} input.form-control( id="newPassword2" type='password', name='newPassword2', placeholder='*********', ng-model="newPassword2", equals="passwordField" ) span.small.text-danger(ng-show="changePasswordForm.newPassword2.$error.areEqual && changePasswordForm.newPassword2.$dirty" aria-live="polite") | #{translate("doesnt_match")} span.small.text-danger(ng-show="!changePasswordForm.newPassword2.$error.areEqual && changePasswordForm.newPassword2.$invalid && changePasswordForm.newPassword2.$dirty" aria-live="polite") | #{translate("invalid_password")} .form-group form-messages(aria-live="polite" for="changePasswordForm") .actions button.btn.btn-primary( type='submit', ng-disabled="changePasswordForm.$invalid" ) #{translate("change")} | !{moduleIncludes("userSettings", locals)} hr h3 | #{translate("sharelatex_beta_program")} if (user.betaProgram) p.small | #{translate("beta_program_already_participating")} div a(id="beta-program-participate-link" href="/beta/participate") #{translate("manage_beta_program_membership")} hr h3 | #{translate("sessions")} div a(id="sessions-link", href="/user/sessions") #{translate("manage_sessions")} if hasFeature('oauth') hr include settings/user-oauth if hasFeature('saas') && (!externalAuthenticationSystemUsed() || (settings.createV1AccountOnLogin && settings.overleaf)) hr p.small | #{translate("newsletter_info_and_unsubscribe")} a( href, ng-click="unsubscribe()", ng-show="subscribed && !unsubscribing" ) #{translate("unsubscribe")} span( ng-show="unsubscribing" ) i.fa.fa-spin.fa-refresh(aria-hidden="true") | #{translate("unsubscribing")} span.text-success( ng-show="!subscribed" ) i.fa.fa-check(aria-hidden="true") | #{translate("unsubscribed")} if !settings.overleaf && user.overleaf p | Please note: If you have linked your account with Overleaf | v2, then deleting your ShareLaTeX account will also delete | account and all of it's associated projects and data. p #{translate("need_to_leave")} a(href, ng-click="deleteAccount()") #{translate("delete_your_account")} script(type='text/ng-template', id='deleteAccountModalTemplate') .modal-header h3 #{translate("delete_account")} div.modal-body#delete-account-modal p !{translate("delete_account_warning_message_3")} if settings.createV1AccountOnLogin && settings.overleaf p strong | Your Overleaf v2 projects will be deleted if you delete your account. | If you want to remove any remaining Overleaf v1 projects in your account, | please first make sure they are imported to Overleaf v2. if settings.overleaf && !hasPassword p b | #[a(href="/user/password/reset", target='_blank') #{translate("delete_acct_no_existing_pw")}]. else form(novalidate, name="deleteAccountForm") label #{translate('email')} input.form-control( type="text", autocomplete="off", placeholder="", ng-model="state.deleteText", focus-on="open", ng-keyup="checkValidation()" ) label #{translate('password')} input.form-control( type="password", autocomplete="off", placeholder="", ng-model="state.password", ng-keyup="checkValidation()" ) div.confirmation-checkbox-wrapper input( type="checkbox" ng-model="state.confirmSharelatexDelete" ng-change="checkValidation()" ).pull-left label(style="display: inline")  I understand this will delete all projects in my Overleaf account with email address #[em {{ userDefaultEmail }}] div(ng-if="state.error") div.alert.alert-danger(ng-switch="state.error.code") span(ng-switch-when="InvalidCredentialsError") | #{translate('email_or_password_wrong_try_again')} span(ng-switch-when="SubscriptionAdminDeletionError") | #{translate('subscription_admins_cannot_be_deleted')} span(ng-switch-when="UserDeletionError") | #{translate('user_deletion_error')} span(ng-switch-default) | #{translate('generic_something_went_wrong')} if settings.createV1AccountOnLogin && settings.overleaf div(ng-if="state.error && state.error.code == 'InvalidCredentialsError'") div.alert.alert-info | If you can't remember your password, or if you are using Single-Sign-On with another provider | to sign in (such as Twitter or Google), please | #[a(href="/user/password/reset", target='_blank') reset your password], | and try again. .modal-footer button.btn.btn-default( ng-click="cancel()" ) #{translate("cancel")} button.btn.btn-danger( ng-disabled="!state.isValid || state.inflight" ng-click="delete()" ) span(ng-hide="state.inflight") #{translate("delete")} span(ng-show="state.inflight") #{translate("deleting")}…
overleaf/web/app/views/user/settings.pug/0
{ "file_path": "overleaf/web/app/views/user/settings.pug", "repo_id": "overleaf", "token_count": 5189 }
501
import _ from 'lodash' /* global PassField */ /* eslint-disable max-len */ import App from '../base' import 'libs/passfield' App.directive('complexPassword', () => ({ require: ['^asyncForm', 'ngModel'], link(scope, element, attrs, ctrl) { PassField.Config.blackList = [] const defaultPasswordOpts = { pattern: '', length: { min: 6, max: 72, }, allowEmpty: false, allowAnyChars: false, isMasked: true, showToggle: false, showGenerate: false, showTip: false, showWarn: false, checkMode: PassField.CheckModes.STRICT, chars: { digits: '1234567890', letters: 'abcdefghijklmnopqrstuvwxyz', letters_up: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', symbols: '@#$%^&*()-_=+[]{};:<>/?!£€.,', }, } const opts = _.defaults( window.passwordStrengthOptions || {}, defaultPasswordOpts ) if (opts.length.min === 1) { // this allows basically anything to be a valid password opts.acceptRate = 0 } if (opts.length.max > 72) { // there is a hard limit of 71 characters in the password at the backend opts.length.max = 72 } if (opts.length.max > 0) { // PassField's notion of 'max' is non-inclusive opts.length.max += 1 } const passField = new PassField.Field('passwordField', opts) const [asyncFormCtrl, ngModelCtrl] = Array.from(ctrl) ngModelCtrl.$parsers.unshift(function (modelValue) { let isValid = passField.validatePass() const email = asyncFormCtrl.getEmail() || window.usersEmail if (!isValid) { scope.complexPasswordErrorMessage = passField.getPassValidationMessage() } else if (typeof email === 'string' && email !== '') { const startOfEmail = email.split('@')[0] if ( modelValue.indexOf(email) !== -1 || modelValue.indexOf(startOfEmail) !== -1 ) { isValid = false scope.complexPasswordErrorMessage = 'Password can not contain email address' } } if (opts.length.max != null && modelValue.length >= opts.length.max) { isValid = false scope.complexPasswordErrorMessage = `Maximum password length ${ opts.length.max - 1 } exceeded` } if (opts.length.min != null && modelValue.length < opts.length.min) { isValid = false scope.complexPasswordErrorMessage = `Password too short, minimum ${opts.length.min}` } ngModelCtrl.$setValidity('complexPassword', isValid) return modelValue }) }, }))
overleaf/web/frontend/js/directives/complexPassword.js/0
{ "file_path": "overleaf/web/frontend/js/directives/complexPassword.js", "repo_id": "overleaf", "token_count": 1130 }
502
import { useRef, useEffect, useLayoutEffect } from 'react' import PropTypes from 'prop-types' import _ from 'lodash' const SCROLL_END_OFFSET = 30 function InfiniteScroll({ atEnd, children, className = '', fetchData, itemCount, isLoading, }) { const root = useRef(null) // we keep the value in a Ref instead of state so it can be safely used in effects const scrollBottomRef = useRef(0) function setScrollBottom(value) { scrollBottomRef.current = value } function updateScrollPosition() { root.current.scrollTop = root.current.scrollHeight - root.current.clientHeight - scrollBottomRef.current } // Repositions the scroll after new items are loaded useLayoutEffect(updateScrollPosition, [itemCount]) // Repositions the scroll after a window resize useEffect(() => { const handleResize = _.debounce(updateScrollPosition, 400) window.addEventListener('resize', handleResize) return () => { window.removeEventListener('resize', handleResize) } }, []) function onScrollHandler(event) { setScrollBottom( root.current.scrollHeight - root.current.scrollTop - root.current.clientHeight ) if (event.target !== event.currentTarget) { // Ignore scroll events on nested divs // (this check won't be necessary in React 17: https://github.com/facebook/react/issues/15723 return } if (shouldFetchData()) { fetchData() } } function shouldFetchData() { const containerIsLargerThanContent = root.current.children[0].clientHeight < root.current.clientHeight if (atEnd || isLoading || containerIsLargerThanContent) { return false } else { return root.current.scrollTop < SCROLL_END_OFFSET } } return ( <div ref={root} onScroll={onScrollHandler} className={`infinite-scroll ${className}`} > {children} </div> ) } InfiniteScroll.propTypes = { atEnd: PropTypes.bool, children: PropTypes.element.isRequired, className: PropTypes.string, fetchData: PropTypes.func.isRequired, itemCount: PropTypes.number.isRequired, isLoading: PropTypes.bool, } export default InfiniteScroll
overleaf/web/frontend/js/features/chat/components/infinite-scroll.js/0
{ "file_path": "overleaf/web/frontend/js/features/chat/components/infinite-scroll.js", "repo_id": "overleaf", "token_count": 781 }
503
import PropTypes from 'prop-types' import classNames from 'classnames' import { useTranslation } from 'react-i18next' import Icon from '../../../shared/components/icon' function HistoryToggleButton({ historyIsOpen, onClick }) { const { t } = useTranslation() const classes = classNames('btn', 'btn-full-height', { active: historyIsOpen, }) return ( // eslint-disable-next-line jsx-a11y/anchor-is-valid <a role="button" className={classes} href="#" onClick={onClick}> <Icon type="fw" modifier="history" /> <p className="toolbar-label">{t('history')}</p> </a> ) } HistoryToggleButton.propTypes = { historyIsOpen: PropTypes.bool, onClick: PropTypes.func.isRequired, } export default HistoryToggleButton
overleaf/web/frontend/js/features/editor-navigation-toolbar/components/history-toggle-button.js/0
{ "file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/history-toggle-button.js", "repo_id": "overleaf", "token_count": 260 }
504
import classnames from 'classnames' import { Button } from 'react-bootstrap' import PropTypes from 'prop-types' import Icon from '../../../../shared/components/icon' import { useFileTreeActionable } from '../../contexts/file-tree-actionable' export default function FileTreeModalCreateFileMode({ mode, icon, label }) { const { newFileCreateMode, startCreatingFile } = useFileTreeActionable() const handleClick = () => { startCreatingFile(mode) } return ( <li className={classnames({ active: newFileCreateMode === mode })}> <Button bsStyle="link" block onClick={handleClick} className="modal-new-file-mode" > <Icon modifier="fw" type={icon} /> &nbsp; {label} </Button> </li> ) } FileTreeModalCreateFileMode.propTypes = { mode: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, label: PropTypes.string.isRequired, }
overleaf/web/frontend/js/features/file-tree/components/file-tree-create/file-tree-modal-create-file-mode.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/file-tree-modal-create-file-mode.js", "repo_id": "overleaf", "token_count": 346 }
505
import { useTranslation } from 'react-i18next' import Icon from '../../../shared/components/icon' import TooltipButton from '../../../shared/components/tooltip-button' import { useFileTreeMainContext } from '../contexts/file-tree-main' import { useFileTreeActionable } from '../contexts/file-tree-actionable' function FileTreeToolbar() { const { hasWritePermissions } = useFileTreeMainContext() if (!hasWritePermissions) return null return ( <div className="toolbar toolbar-filetree"> <FileTreeToolbarLeft /> <FileTreeToolbarRight /> </div> ) } function FileTreeToolbarLeft() { const { t } = useTranslation() const { canCreate, startCreatingFolder, startCreatingDocOrFile, startUploadingDocOrFile, } = useFileTreeActionable() if (!canCreate) return null return ( <div className="toolbar-left"> <TooltipButton id="new_file" description={t('new_file')} onClick={startCreatingDocOrFile} > <Icon type="file" modifier="fw" accessibilityLabel={t('new_file')} /> </TooltipButton> <TooltipButton id="new_folder" description={t('new_folder')} onClick={startCreatingFolder} > <Icon type="folder" modifier="fw" accessibilityLabel={t('new_folder')} /> </TooltipButton> <TooltipButton id="upload" description={t('upload')} onClick={startUploadingDocOrFile} > <Icon type="upload" modifier="fw" accessibilityLabel={t('upload')} /> </TooltipButton> </div> ) } function FileTreeToolbarRight() { const { t } = useTranslation() const { canRename, canDelete, startRenaming, startDeleting, } = useFileTreeActionable() if (!canRename && !canDelete) { return null } return ( <div className="toolbar-right"> {canRename ? ( <TooltipButton id="rename" description={t('rename')} onClick={startRenaming} > <Icon type="pencil" modifier="fw" accessibilityLabel={t('rename')} /> </TooltipButton> ) : null} {canDelete ? ( <TooltipButton id="delete" description={t('delete')} onClick={startDeleting} > <Icon type="trash-o" modifier="fw" accessibilityLabel={t('delete')} /> </TooltipButton> ) : null} </div> ) } export default FileTreeToolbar
overleaf/web/frontend/js/features/file-tree/components/file-tree-toolbar.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-toolbar.js", "repo_id": "overleaf", "token_count": 1042 }
506
import { useEffect, useState } from 'react' import { postJSON } from '../../../infrastructure/fetch-json' import { fileCollator } from '../util/file-collator' import useAbortController from '../../../shared/hooks/use-abort-controller' const alphabetical = (a, b) => fileCollator.compare(a.path, b.path) export function useProjectOutputFiles(projectId) { const [loading, setLoading] = useState(false) const [data, setData] = useState(null) const [error, setError] = useState(false) const { signal } = useAbortController() useEffect(() => { if (projectId) { setLoading(true) setError(false) setData(null) postJSON(`/project/${projectId}/compile`, { body: { check: 'silent', draft: false, incrementalCompilesEnabled: false, }, signal, }) .then(data => { if (data.status === 'success') { const filteredFiles = data.outputFiles.filter(file => file.path.match(/.*\.(pdf|png|jpeg|jpg|gif)/) ) setData(filteredFiles.sort(alphabetical)) } else { setError('linked-project-compile-error') } }) .catch(error => setError(error)) .finally(() => setLoading(false)) } }, [projectId, signal]) return { loading, data, error } }
overleaf/web/frontend/js/features/file-tree/hooks/use-project-output-files.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/hooks/use-project-output-files.js", "repo_id": "overleaf", "token_count": 579 }
507
import App from '../../../base' import { react2angular } from 'react2angular' import HotkeysModal from '../components/hotkeys-modal' App.component('hotkeysModal', react2angular(HotkeysModal, undefined)) export default App.controller('HotkeysModalController', function ($scope) { $scope.show = false $scope.isMac = /Mac/i.test(navigator.platform) $scope.handleHide = () => { $scope.$applyAsync(() => { $scope.show = false }) } $scope.openHotkeysModal = () => { $scope.$applyAsync(() => { $scope.trackChangesVisible = $scope.project && $scope.project.features.trackChangesVisible $scope.show = true }) } })
overleaf/web/frontend/js/features/hotkeys-modal/controllers/hotkeys-modal-controller.js/0
{ "file_path": "overleaf/web/frontend/js/features/hotkeys-modal/controllers/hotkeys-modal-controller.js", "repo_id": "overleaf", "token_count": 242 }
508
import PropTypes from 'prop-types' import { Dropdown, MenuItem, OverlayTrigger, Tooltip } from 'react-bootstrap' import { useTranslation } from 'react-i18next' import classNames from 'classnames' import Icon from '../../../shared/components/icon' import ControlledDropdown from '../../../shared/components/controlled-dropdown' function PreviewRecompileButton({ compilerState: { autoCompileHasChanges, autoCompileHasLintingError, isAutoCompileOn, isCompiling, isDraftModeOn, isSyntaxCheckOn, }, onRecompile, onRecompileFromScratch, onRunSyntaxCheckNow, onStopCompilation, onSetAutoCompile, onSetDraftMode, onSetSyntaxCheck, showText, }) { const { t } = useTranslation() function handleSelectAutoCompileOn() { onSetAutoCompile(true) } function handleSelectAutoCompileOff() { onSetAutoCompile(false) } function handleSelectDraftModeOn() { onSetDraftMode(true) } function handleSelectDraftModeOff() { onSetDraftMode(false) } function handleSelectSyntaxCheckOn() { onSetSyntaxCheck(true) } function handleSelectSyntaxCheckOff() { onSetSyntaxCheck(false) } let compilingProps = {} let recompileProps = {} function _hideText(keepAria) { return { 'aria-hidden': !keepAria, style: { position: 'absolute', right: '-100vw', }, } } if (!showText) { compilingProps = _hideText(isCompiling) recompileProps = _hideText(!isCompiling) } else if (isCompiling) { recompileProps = _hideText() } else { compilingProps = _hideText() } const recompileButtonGroupClasses = classNames( 'btn-recompile-group', 'toolbar-item', { 'btn-recompile-group-has-changes': autoCompileHasChanges && !autoCompileHasLintingError, } ) const buttonElement = ( <ControlledDropdown id="pdf-recompile-dropdown" className={recompileButtonGroupClasses} > <button className="btn btn-recompile" onClick={() => onRecompile()}> <Icon type="refresh" spin={isCompiling} /> <span id="text-compiling" className="toolbar-text" {...compilingProps}> {t('compiling')} &hellip; </span> <span id="text-recompile" className="toolbar-text" {...recompileProps}> {t('recompile')} </span> </button> <Dropdown.Toggle aria-label={t('toggle_compile_options_menu')} className="btn btn-recompile" bsStyle="success" /> <Dropdown.Menu> <MenuItem header>{t('auto_compile')}</MenuItem> <MenuItem onSelect={handleSelectAutoCompileOn}> <Icon type={isAutoCompileOn ? 'check' : ''} modifier="fw" /> {t('on')} </MenuItem> <MenuItem onSelect={handleSelectAutoCompileOff}> <Icon type={!isAutoCompileOn ? 'check' : ''} modifier="fw" /> {t('off')} </MenuItem> <MenuItem header>{t('compile_mode')}</MenuItem> <MenuItem onSelect={handleSelectDraftModeOff}> <Icon type={!isDraftModeOn ? 'check' : ''} modifier="fw" /> {t('normal')} </MenuItem> <MenuItem onSelect={handleSelectDraftModeOn}> <Icon type={isDraftModeOn ? 'check' : ''} modifier="fw" /> {t('fast')} <span className="subdued">[draft]</span> </MenuItem> <MenuItem header>Syntax Checks</MenuItem> <MenuItem onSelect={handleSelectSyntaxCheckOn}> <Icon type={isSyntaxCheckOn ? 'check' : ''} modifier="fw" /> {t('stop_on_validation_error')} </MenuItem> <MenuItem onSelect={handleSelectSyntaxCheckOff}> <Icon type={!isSyntaxCheckOn ? 'check' : ''} modifier="fw" /> {t('ignore_validation_errors')} </MenuItem> <MenuItem onSelect={onRunSyntaxCheckNow}> <Icon type="" modifier="fw" /> {t('run_syntax_check_now')} </MenuItem> <MenuItem className={!isCompiling ? 'hidden' : ''} divider /> <MenuItem onSelect={onStopCompilation} className={!isCompiling ? 'hidden' : ''} disabled={!isCompiling} aria-disabled={!isCompiling} > {t('stop_compile')} </MenuItem> <MenuItem divider /> <MenuItem onSelect={onRecompileFromScratch} disabled={isCompiling} aria-disabled={!!isCompiling} > {t('recompile_from_scratch')} </MenuItem> </Dropdown.Menu> </ControlledDropdown> ) return showText ? ( buttonElement ) : ( <OverlayTrigger placement="bottom" overlay={ <Tooltip id="tooltip-download-pdf"> {isCompiling ? t('compiling') : t('recompile')} </Tooltip> } > {buttonElement} </OverlayTrigger> ) } PreviewRecompileButton.propTypes = { compilerState: PropTypes.shape({ autoCompileHasChanges: PropTypes.bool.isRequired, autoCompileHasLintingError: PropTypes.bool, isAutoCompileOn: PropTypes.bool.isRequired, isCompiling: PropTypes.bool.isRequired, isDraftModeOn: PropTypes.bool.isRequired, isSyntaxCheckOn: PropTypes.bool.isRequired, logEntries: PropTypes.object.isRequired, }), onRecompile: PropTypes.func.isRequired, onRecompileFromScratch: PropTypes.func.isRequired, onRunSyntaxCheckNow: PropTypes.func.isRequired, onSetAutoCompile: PropTypes.func.isRequired, onSetDraftMode: PropTypes.func.isRequired, onSetSyntaxCheck: PropTypes.func.isRequired, onStopCompilation: PropTypes.func.isRequired, showText: PropTypes.bool.isRequired, } export default PreviewRecompileButton
overleaf/web/frontend/js/features/preview/components/preview-recompile-button.js/0
{ "file_path": "overleaf/web/frontend/js/features/preview/components/preview-recompile-button.js", "repo_id": "overleaf", "token_count": 2414 }
509
import { useState } from 'react' import { Modal, Button } from 'react-bootstrap' import { Trans } from 'react-i18next' import PropTypes from 'prop-types' import Icon from '../../../shared/components/icon' import { transferProjectOwnership } from '../utils/api' import AccessibleModal from '../../../shared/components/accessible-modal' import { reload } from '../utils/location' import { useProjectContext } from '../../../shared/context/project-context' export default function TransferOwnershipModal({ member, cancel }) { const [inflight, setInflight] = useState(false) const [error, setError] = useState(false) const project = useProjectContext() function confirm() { setError(false) setInflight(true) transferProjectOwnership(project, member) .then(() => { reload() }) .catch(() => { setError(true) setInflight(false) }) } return ( <AccessibleModal show onHide={cancel}> <Modal.Header closeButton> <Modal.Title> <Trans i18nKey="change_project_owner" /> </Modal.Title> </Modal.Header> <Modal.Body> <p> <Trans i18nKey="project_ownership_transfer_confirmation_1" values={{ user: member.email, project: project.name }} components={[<strong key="strong-1" />, <strong key="strong-2" />]} /> </p> <p> <Trans i18nKey="project_ownership_transfer_confirmation_2" /> </p> </Modal.Body> <Modal.Footer> <div className="modal-footer-left"> {inflight && <Icon type="refresh" spin />} {error && ( <span className="text-danger"> <Trans i18nKey="generic_something_went_wrong" /> </span> )} </div> <div className="modal-footer-right"> <Button type="button" bsStyle="default" onClick={cancel} disabled={inflight} > <Trans i18nKey="cancel" /> </Button> <Button type="button" bsStyle="success" onClick={confirm} disabled={inflight} > <Trans i18nKey="change_owner" /> </Button> </div> </Modal.Footer> </AccessibleModal> ) } TransferOwnershipModal.propTypes = { member: PropTypes.object.isRequired, cancel: PropTypes.func.isRequired, }
overleaf/web/frontend/js/features/share-project-modal/components/transfer-ownership-modal.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/transfer-ownership-modal.js", "repo_id": "overleaf", "token_count": 1130 }
510
[ { "category": "Greek", "command": "\\alpha", "codepoint": "U+1D6FC", "description": "Lowercase Greek letter alpha", "aliases": ["a", "α"], "notes": "" }, { "category": "Greek", "command": "\\beta", "codepoint": "U+1D6FD", "description": "Lowercase Greek letter beta", "aliases": ["b", "β"], "notes": "" }, { "category": "Greek", "command": "\\gamma", "codepoint": "U+1D6FE", "description": "Lowercase Greek letter gamma", "aliases": ["γ"], "notes": "" }, { "category": "Greek", "command": "\\delta", "codepoint": "U+1D6FF", "description": "Lowercase Greek letter delta", "aliases": ["δ"], "notes": "" }, { "category": "Greek", "command": "\\varepsilon", "codepoint": "U+1D700", "description": "Lowercase Greek letter epsilon, varepsilon", "aliases": ["ε"], "notes": "" }, { "category": "Greek", "command": "\\epsilon", "codepoint": "U+1D716", "description": "Lowercase Greek letter epsilon lunate", "aliases": ["ε"], "notes": "" }, { "category": "Greek", "command": "\\zeta", "codepoint": "U+1D701", "description": "Lowercase Greek letter zeta", "aliases": ["ζ"], "notes": "" }, { "category": "Greek", "command": "\\eta", "codepoint": "U+1D702", "description": "Lowercase Greek letter eta", "aliases": ["η"], "notes": "" }, { "category": "Greek", "command": "\\vartheta", "codepoint": "U+1D717", "description": "Lowercase Greek letter curly theta, vartheta", "aliases": ["θ"], "notes": "" }, { "category": "Greek", "command": "\\theta", "codepoint": "U+1D703", "description": "Lowercase Greek letter theta", "aliases": ["θ"], "notes": "" }, { "category": "Greek", "command": "\\iota", "codepoint": "U+1D704", "description": "Lowercase Greek letter iota", "aliases": ["ι"], "notes": "" }, { "category": "Greek", "command": "\\kappa", "codepoint": "U+1D705", "description": "Lowercase Greek letter kappa", "aliases": ["κ"], "notes": "" }, { "category": "Greek", "command": "\\lambda", "codepoint": "U+1D706", "description": "Lowercase Greek letter lambda", "aliases": ["λ"], "notes": "" }, { "category": "Greek", "command": "\\mu", "codepoint": "U+1D707", "description": "Lowercase Greek letter mu", "aliases": ["μ"], "notes": "" }, { "category": "Greek", "command": "\\nu", "codepoint": "U+1D708", "description": "Lowercase Greek letter nu", "aliases": ["ν"], "notes": "" }, { "category": "Greek", "command": "\\xi", "codepoint": "U+1D709", "description": "Lowercase Greek letter xi", "aliases": ["ξ"], "notes": "" }, { "category": "Greek", "command": "\\pi", "codepoint": "U+1D70B", "description": "Lowercase Greek letter pi", "aliases": ["π"], "notes": "" }, { "category": "Greek", "command": "\\varrho", "codepoint": "U+1D71A", "description": "Lowercase Greek letter rho, varrho", "aliases": ["ρ"], "notes": "" }, { "category": "Greek", "command": "\\rho", "codepoint": "U+1D70C", "description": "Lowercase Greek letter rho", "aliases": ["ρ"], "notes": "" }, { "category": "Greek", "command": "\\sigma", "codepoint": "U+1D70E", "description": "Lowercase Greek letter sigma", "aliases": ["σ"], "notes": "" }, { "category": "Greek", "command": "\\varsigma", "codepoint": "U+1D70D", "description": "Lowercase Greek letter final sigma, varsigma", "aliases": ["ς"], "notes": "" }, { "category": "Greek", "command": "\\tau", "codepoint": "U+1D70F", "description": "Lowercase Greek letter tau", "aliases": ["τ"], "notes": "" }, { "category": "Greek", "command": "\\upsilon", "codepoint": "U+1D710", "description": "Lowercase Greek letter upsilon", "aliases": ["υ"], "notes": "" }, { "category": "Greek", "command": "\\phi", "codepoint": "U+1D719", "description": "Lowercase Greek letter phi", "aliases": ["φ"], "notes": "" }, { "category": "Greek", "command": "\\varphi", "codepoint": "U+1D711", "description": "Lowercase Greek letter phi, varphi", "aliases": ["φ"], "notes": "" }, { "category": "Greek", "command": "\\chi", "codepoint": "U+1D712", "description": "Lowercase Greek letter chi", "aliases": ["χ"], "notes": "" }, { "category": "Greek", "command": "\\psi", "codepoint": "U+1D713", "description": "Lowercase Greek letter psi", "aliases": ["ψ"], "notes": "" }, { "category": "Greek", "command": "\\omega", "codepoint": "U+1D714", "description": "Lowercase Greek letter omega", "aliases": ["ω"], "notes": "" }, { "category": "Greek", "command": "\\Gamma", "codepoint": "U+00393", "description": "Uppercase Greek letter Gamma", "aliases": ["Γ"], "notes": "" }, { "category": "Greek", "command": "\\Delta", "codepoint": "U+00394", "description": "Uppercase Greek letter Delta", "aliases": ["Δ"], "notes": "" }, { "category": "Greek", "command": "\\Theta", "codepoint": "U+00398", "description": "Uppercase Greek letter Theta", "aliases": ["Θ"], "notes": "" }, { "category": "Greek", "command": "\\Lambda", "codepoint": "U+0039B", "description": "Uppercase Greek letter Lambda", "aliases": ["Λ"], "notes": "" }, { "category": "Greek", "command": "\\Xi", "codepoint": "U+0039E", "description": "Uppercase Greek letter Xi", "aliases": ["Ξ"], "notes": "" }, { "category": "Greek", "command": "\\Pi", "codepoint": "U+003A0", "description": "Uppercase Greek letter Pi", "aliases": ["Π"], "notes": "Use \\prod for the product." }, { "category": "Greek", "command": "\\Sigma", "codepoint": "U+003A3", "description": "Uppercase Greek letter Sigma", "aliases": ["Σ"], "notes": "Use \\sum for the sum." }, { "category": "Greek", "command": "\\Upsilon", "codepoint": "U+003A5", "description": "Uppercase Greek letter Upsilon", "aliases": ["Υ"], "notes": "" }, { "category": "Greek", "command": "\\Phi", "codepoint": "U+003A6", "description": "Uppercase Greek letter Phi", "aliases": ["Φ"], "notes": "" }, { "category": "Greek", "command": "\\Psi", "codepoint": "U+003A8", "description": "Uppercase Greek letter Psi", "aliases": ["Ψ"], "notes": "" }, { "category": "Greek", "command": "\\Omega", "codepoint": "U+003A9", "description": "Uppercase Greek letter Omega", "aliases": ["Ω"], "notes": "" }, { "category": "Relations", "command": "\\neq", "codepoint": "U+02260", "description": "Not equal", "aliases": ["!="], "notes": "" }, { "category": "Relations", "command": "\\leq", "codepoint": "U+02264", "description": "Less than or equal", "aliases": ["<="], "notes": "" }, { "category": "Relations", "command": "\\geq", "codepoint": "U+02265", "description": "Greater than or equal", "aliases": [">="], "notes": "" }, { "category": "Relations", "command": "\\ll", "codepoint": "U+0226A", "description": "Much less than", "aliases": ["<<"], "notes": "" }, { "category": "Relations", "command": "\\gg", "codepoint": "U+0226B", "description": "Much greater than", "aliases": [">>"], "notes": "" }, { "category": "Relations", "command": "\\prec", "codepoint": "U+0227A", "description": "Precedes", "notes": "" }, { "category": "Relations", "command": "\\succ", "codepoint": "U+0227B", "description": "Succeeds", "notes": "" }, { "category": "Relations", "command": "\\in", "codepoint": "U+02208", "description": "Set membership", "notes": "" }, { "category": "Relations", "command": "\\notin", "codepoint": "U+02209", "description": "Negated set membership", "notes": "" }, { "category": "Relations", "command": "\\ni", "codepoint": "U+0220B", "description": "Contains", "notes": "" }, { "category": "Relations", "command": "\\subset", "codepoint": "U+02282", "description": "Subset", "notes": "" }, { "category": "Relations", "command": "\\subseteq", "codepoint": "U+02286", "description": "Subset or equals", "notes": "" }, { "category": "Relations", "command": "\\supset", "codepoint": "U+02283", "description": "Superset", "notes": "" }, { "category": "Relations", "command": "\\simeq", "codepoint": "U+02243", "description": "Similar", "notes": "" }, { "category": "Relations", "command": "\\approx", "codepoint": "U+02248", "description": "Approximate", "notes": "" }, { "category": "Relations", "command": "\\equiv", "codepoint": "U+02261", "description": "Identical with", "notes": "" }, { "category": "Relations", "command": "\\cong", "codepoint": "U+02245", "description": "Congruent with", "notes": "" }, { "category": "Relations", "command": "\\mid", "codepoint": "U+02223", "description": "Mid, divides, vertical bar, modulus, absolute value", "notes": "Use \\lvert...\\rvert for the absolute value." }, { "category": "Relations", "command": "\\nmid", "codepoint": "U+02224", "description": "Negated mid, not divides", "notes": "Requires \\usepackage{amssymb}." }, { "category": "Relations", "command": "\\parallel", "codepoint": "U+02225", "description": "Parallel, double vertical bar, norm", "notes": "Use \\lVert...\\rVert for the norm." }, { "category": "Relations", "command": "\\perp", "codepoint": "U+027C2", "description": "Perpendicular", "notes": "" }, { "category": "Operators", "command": "\\times", "codepoint": "U+000D7", "description": "Cross product, multiplication", "aliases": ["x"], "notes": "" }, { "category": "Operators", "command": "\\div", "codepoint": "U+000F7", "description": "Division", "notes": "" }, { "category": "Operators", "command": "\\cap", "codepoint": "U+02229", "description": "Intersection", "notes": "" }, { "category": "Operators", "command": "\\cup", "codepoint": "U+0222A", "description": "Union", "notes": "" }, { "category": "Operators", "command": "\\cdot", "codepoint": "U+022C5", "description": "Dot product, multiplication", "notes": "" }, { "category": "Operators", "command": "\\cdots", "codepoint": "U+022EF", "description": "Centered dots", "notes": "" }, { "category": "Operators", "command": "\\bullet", "codepoint": "U+02219", "description": "Bullet", "notes": "" }, { "category": "Operators", "command": "\\circ", "codepoint": "U+025E6", "description": "Circle", "notes": "" }, { "category": "Operators", "command": "\\wedge", "codepoint": "U+02227", "description": "Wedge, logical and", "notes": "" }, { "category": "Operators", "command": "\\vee", "codepoint": "U+02228", "description": "Vee, logical or", "notes": "" }, { "category": "Operators", "command": "\\setminus", "codepoint": "U+0005C", "description": "Set minus, backslash", "notes": "Use \\backslash for a backslash." }, { "category": "Operators", "command": "\\oplus", "codepoint": "U+02295", "description": "Plus sign in circle", "notes": "" }, { "category": "Operators", "command": "\\otimes", "codepoint": "U+02297", "description": "Multiply sign in circle", "notes": "" }, { "category": "Operators", "command": "\\sum", "codepoint": "U+02211", "description": "Summation operator", "notes": "Use \\Sigma for the letter Sigma." }, { "category": "Operators", "command": "\\prod", "codepoint": "U+0220F", "description": "Product operator", "notes": "Use \\Pi for the letter Pi." }, { "category": "Operators", "command": "\\bigcap", "codepoint": "U+022C2", "description": "Intersection operator", "notes": "" }, { "category": "Operators", "command": "\\bigcup", "codepoint": "U+022C3", "description": "Union operator", "notes": "" }, { "category": "Operators", "command": "\\int", "codepoint": "U+0222B", "description": "Integral operator", "notes": "" }, { "category": "Operators", "command": "\\iint", "codepoint": "U+0222C", "description": "Double integral operator", "notes": "Requires \\usepackage{amsmath}." }, { "category": "Operators", "command": "\\iiint", "codepoint": "U+0222D", "description": "Triple integral operator", "notes": "Requires \\usepackage{amsmath}." }, { "category": "Arrows", "command": "\\leftarrow", "codepoint": "U+02190", "description": "Leftward arrow", "aliases": ["<-"], "notes": "" }, { "category": "Arrows", "command": "\\rightarrow", "codepoint": "U+02192", "description": "Rightward arrow", "aliases": ["->"], "notes": "" }, { "category": "Arrows", "command": "\\leftrightarrow", "codepoint": "U+02194", "description": "Left and right arrow", "aliases": ["<->"], "notes": "" }, { "category": "Arrows", "command": "\\uparrow", "codepoint": "U+02191", "description": "Upward arrow", "notes": "" }, { "category": "Arrows", "command": "\\downarrow", "codepoint": "U+02193", "description": "Downward arrow", "notes": "" }, { "category": "Arrows", "command": "\\Leftarrow", "codepoint": "U+021D0", "description": "Is implied by", "aliases": ["<="], "notes": "" }, { "category": "Arrows", "command": "\\Rightarrow", "codepoint": "U+021D2", "description": "Implies", "aliases": ["=>"], "notes": "" }, { "category": "Arrows", "command": "\\Leftrightarrow", "codepoint": "U+021D4", "description": "Left and right double arrow", "aliases": ["<=>"], "notes": "" }, { "category": "Arrows", "command": "\\mapsto", "codepoint": "U+021A6", "description": "Maps to, rightward", "notes": "" }, { "category": "Arrows", "command": "\\nearrow", "codepoint": "U+02197", "description": "NE pointing arrow", "notes": "" }, { "category": "Arrows", "command": "\\searrow", "codepoint": "U+02198", "description": "SE pointing arrow", "notes": "" }, { "category": "Arrows", "command": "\\rightleftharpoons", "codepoint": "U+021CC", "description": "Right harpoon over left", "notes": "" }, { "category": "Arrows", "command": "\\leftharpoonup", "codepoint": "U+021BC", "description": "Left harpoon up", "notes": "" }, { "category": "Arrows", "command": "\\rightharpoonup", "codepoint": "U+021C0", "description": "Right harpoon up", "notes": "" }, { "category": "Arrows", "command": "\\leftharpoondown", "codepoint": "U+021BD", "description": "Left harpoon down", "notes": "" }, { "category": "Arrows", "command": "\\rightharpoondown", "codepoint": "U+021C1", "description": "Right harpoon down", "notes": "" }, { "category": "Misc", "command": "\\infty", "codepoint": "U+0221E", "description": "Infinity", "notes": "" }, { "category": "Misc", "command": "\\partial", "codepoint": "U+1D715", "description": "Partial differential", "notes": "" }, { "category": "Misc", "command": "\\nabla", "codepoint": "U+02207", "description": "Nabla, del, hamilton operator", "notes": "" }, { "category": "Misc", "command": "\\varnothing", "codepoint": "U+02300", "description": "Empty set", "notes": "Requires \\usepackage{amssymb}." }, { "category": "Misc", "command": "\\forall", "codepoint": "U+02200", "description": "For all", "notes": "" }, { "category": "Misc", "command": "\\exists", "codepoint": "U+02203", "description": "There exists", "notes": "" }, { "category": "Misc", "command": "\\neg", "codepoint": "U+000AC", "description": "Not sign", "notes": "" }, { "category": "Misc", "command": "\\Re", "codepoint": "U+0211C", "description": "Real part", "notes": "" }, { "category": "Misc", "command": "\\Im", "codepoint": "U+02111", "description": "Imaginary part", "notes": "" }, { "category": "Misc", "command": "\\Box", "codepoint": "U+025A1", "description": "Square", "notes": "Requires \\usepackage{amssymb}." }, { "category": "Misc", "command": "\\triangle", "codepoint": "U+025B3", "description": "Triangle", "notes": "" }, { "category": "Misc", "command": "\\aleph", "codepoint": "U+02135", "description": "Hebrew letter aleph", "notes": "" }, { "category": "Misc", "command": "\\wp", "codepoint": "U+02118", "description": "Weierstrass letter p", "notes": "" }, { "category": "Misc", "command": "\\#", "codepoint": "U+00023", "description": "Number sign, hashtag", "notes": "" }, { "category": "Misc", "command": "\\$", "codepoint": "U+00024", "description": "Dollar sign", "notes": "" }, { "category": "Misc", "command": "\\%", "codepoint": "U+00025", "description": "Percent sign", "notes": "" }, { "category": "Misc", "command": "\\&", "codepoint": "U+00026", "description": "Et sign, and, ampersand", "notes": "" }, { "category": "Misc", "command": "\\{", "codepoint": "U+0007B", "description": "Left curly brace", "notes": "" }, { "category": "Misc", "command": "\\}", "codepoint": "U+0007D", "description": "Right curly brace", "notes": "" }, { "category": "Misc", "command": "\\langle", "codepoint": "U+027E8", "description": "Left angle bracket, bra", "notes": "" }, { "category": "Misc", "command": "\\rangle", "codepoint": "U+027E9", "description": "Right angle bracket, ket", "notes": "" } ]
overleaf/web/frontend/js/features/symbol-palette/data/symbols.json/0
{ "file_path": "overleaf/web/frontend/js/features/symbol-palette/data/symbols.json", "repo_id": "overleaf", "token_count": 8416 }
511
/* eslint-disable max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.component('spellMenu', { bindings: { open: '<', top: '<', left: '<', layoutFromBottom: '<', highlight: '<', replaceWord: '&', learnWord: '&', }, template: `\ <div class="dropdown context-menu spell-check-menu" ng-show="$ctrl.open" ng-style="{top: $ctrl.top, left: $ctrl.left}" ng-class="{open: $ctrl.open, 'spell-check-menu-from-bottom': $ctrl.layoutFromBottom}" > <ul class="dropdown-menu"> <li ng-repeat="suggestion in $ctrl.highlight.suggestions | limitTo:8"> <a href ng-click="$ctrl.replaceWord({ highlight: $ctrl.highlight, suggestion: suggestion })" > {{ suggestion }} </a> </li> <li class="divider"></li> <li> <a href ng-click="$ctrl.learnWord({ highlight: $ctrl.highlight })">Add to Dictionary</a> </li> </ul> </div>\ `, })
overleaf/web/frontend/js/ide/editor/components/spellMenu.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/components/spellMenu.js", "repo_id": "overleaf", "token_count": 452 }
512
import _ from 'lodash' /* eslint-disable camelcase, max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__ * DS205: Consider reworking code to avoid use of IIFEs * DS206: Consider reworking classes to avoid initClass * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import moment from 'moment' import ColorManager from '../colors/ColorManager' import displayNameForUser from './util/displayNameForUser' import HistoryViewModes from './util/HistoryViewModes' import './controllers/HistoryV2ListController' import './controllers/HistoryV2FileTreeController' import './controllers/HistoryV2ToolbarController' import './controllers/HistoryV2AddLabelModalController' import './controllers/HistoryV2DeleteLabelModalController' import './directives/infiniteScroll' import './directives/historyDraggableBoundary' import './directives/historyDroppableArea' import './components/historyEntriesList' import './components/historyEntry' import './components/historyLabelsList' import './components/historyLabel' import './components/historyFileTree' import './components/historyFileEntity' import { paywallPrompt } from '../../../../frontend/js/main/account-upgrade' let HistoryManager export default HistoryManager = (function () { HistoryManager = class HistoryManager { static initClass() { this.prototype.MAX_RECENT_UPDATES_TO_SELECT = 5 this.prototype.BATCH_SIZE = 10 } constructor(ide, $scope, localStorage) { this.labelCurrentVersion = this.labelCurrentVersion.bind(this) this.deleteLabel = this.deleteLabel.bind(this) this._addLabelLocally = this._addLabelLocally.bind(this) this.ide = ide this.$scope = $scope this.localStorage = localStorage this.$scope.HistoryViewModes = HistoryViewModes this._localStorageViewModeProjKey = `history.userPrefs.viewMode.${$scope.project_id}` this._localStorageShowOnlyLabelsProjKey = `history.userPrefs.showOnlyLabels.${$scope.project_id}` this._previouslySelectedPathname = null this._loadFileTreeRequestCanceller = null this.hardReset() this.$scope.toggleHistory = () => { if (this.$scope.ui.view === 'history') { this.hide() } else { this.show() this._handleHistoryUIStateChange() } this.ide.$timeout(() => { this.$scope.$broadcast('history:toggle') }, 0) } this.$scope.isHistoryLoading = () => { const selection = this.$scope.history.selection return ( this.$scope.history.loadingFileTree || (this.$scope.history.viewMode === HistoryViewModes.POINT_IN_TIME && selection.file && selection.file.loading) || (this.$scope.history.viewMode === HistoryViewModes.COMPARE && selection.diff && selection.diff.loading) ) } } show() { this.$scope.ui.view = 'history' this.hardReset() if (this.$scope.history.showOnlyLabels) { this.fetchNextBatchOfUpdates() } } hide() { this.$scope.ui.view = 'editor' } _getViewModeUserPref() { return ( this.localStorage(this._localStorageViewModeProjKey) || HistoryViewModes.POINT_IN_TIME ) } _getShowOnlyLabelsUserPref() { return this.localStorage(this._localStorageShowOnlyLabelsProjKey) || false } _setViewModeUserPref(viewModeUserPref) { if ( viewModeUserPref === HistoryViewModes.POINT_IN_TIME || viewModeUserPref === HistoryViewModes.COMPARE ) { this.localStorage(this._localStorageViewModeProjKey, viewModeUserPref) } } _setShowOnlyLabelsUserPref(showOnlyLabelsUserPref) { this.localStorage( this._localStorageShowOnlyLabelsProjKey, !!showOnlyLabelsUserPref ) } hardReset() { this.$scope.history = { isV2: true, updates: [], viewMode: this._getViewModeUserPref(), nextBeforeTimestamp: null, loading: false, atEnd: false, userHasFullFeature: undefined, freeHistoryLimitHit: false, selection: { docs: {}, pathname: null, range: { fromV: null, toV: null, }, hoveredRange: { fromV: null, toV: null, }, diff: null, files: [], file: null, }, error: null, showOnlyLabels: this._getShowOnlyLabelsUserPref(), labels: null, loadingFileTree: true, } const _deregisterFeatureWatcher = this.$scope.$watch( 'project.features.versioning', hasVersioning => { if (hasVersioning != null) { this.$scope.history.userHasFullFeature = hasVersioning if (this.$scope.user.isAdmin) { this.$scope.history.userHasFullFeature = true } _deregisterFeatureWatcher() } } ) } softReset() { this.$scope.history.viewMode = this._getViewModeUserPref() this.$scope.history.selection = { docs: {}, pathname: null, range: { fromV: null, toV: null, }, hoveredRange: { fromV: null, toV: null, }, diff: null, // When history.viewMode == HistoryViewModes.COMPARE files: [], // When history.viewMode == HistoryViewModes.COMPARE file: null, } this.$scope.history.error = null this.$scope.history.showOnlyLabels = this._getShowOnlyLabelsUserPref() } toggleHistoryViewMode() { if (this.$scope.history.viewMode === HistoryViewModes.COMPARE) { this.softReset() this.$scope.history.viewMode = HistoryViewModes.POINT_IN_TIME this._setViewModeUserPref(HistoryViewModes.POINT_IN_TIME) } else { this.softReset() this.$scope.history.viewMode = HistoryViewModes.COMPARE this._setViewModeUserPref(HistoryViewModes.COMPARE) } this._handleHistoryUIStateChange() this.ide.$timeout(() => { this.$scope.$broadcast('history:toggle') }, 0) } _handleHistoryUIStateChange() { if (this.$scope.history.viewMode === HistoryViewModes.COMPARE) { if (this.$scope.history.showOnlyLabels) { this.autoSelectLabelsForComparison() } else { this.autoSelectRecentUpdates() } } else { // Point-in-time mode if (this.$scope.history.showOnlyLabels) { this.autoSelectLabelForPointInTime() } else { this.autoSelectVersionForPointInTime() } } } setHoverFrom(fromV) { const selection = this.$scope.history.selection selection.hoveredRange.fromV = fromV selection.hoveredRange.toV = selection.range.toV this.$scope.history.hoveringOverListSelectors = true } setHoverTo(toV) { const selection = this.$scope.history.selection selection.hoveredRange.toV = toV selection.hoveredRange.fromV = selection.range.fromV this.$scope.history.hoveringOverListSelectors = true } resetHover() { const selection = this.$scope.history.selection selection.hoveredRange.toV = null selection.hoveredRange.fromV = null this.$scope.history.hoveringOverListSelectors = false } showAllUpdates() { if (this.$scope.history.showOnlyLabels) { this.$scope.history.showOnlyLabels = false this._setShowOnlyLabelsUserPref(false) this._handleHistoryUIStateChange() } } showOnlyLabels() { if (!this.$scope.history.showOnlyLabels) { this.$scope.history.showOnlyLabels = true this._setShowOnlyLabelsUserPref(true) this._handleHistoryUIStateChange() } } restoreFile(version, pathname) { const url = `/project/${this.$scope.project_id}/restore_file` return this.ide.$http.post(url, { version, pathname, _csrf: window.csrfToken, }) } loadFileTreeForVersion(version) { return this._loadFileTree(version, version) } loadFileTreeDiff(toV, fromV) { return this._loadFileTree(toV, fromV) } _loadFileTree(toV, fromV) { let url = `/project/${this.$scope.project_id}/filetree/diff` const selection = this.$scope.history.selection const query = [`from=${fromV}`, `to=${toV}`] url += `?${query.join('&')}` this.$scope.$applyAsync( () => (this.$scope.history.loadingFileTree = true) ) selection.file = null selection.pathname = null // If `this._loadFileTreeRequestCanceller` is not null, then we have a request inflight if (this._loadFileTreeRequestCanceller != null) { // Resolving it will cancel the inflight request (or, rather, ignore its result) this._loadFileTreeRequestCanceller.resolve() } this._loadFileTreeRequestCanceller = this.ide.$q.defer() return this.ide.$http .get(url, { timeout: this._loadFileTreeRequestCanceller.promise }) .then(response => { this.$scope.history.selection.files = response.data.diff for (const file of this.$scope.history.selection.files) { if (file.newPathname != null) { file.oldPathname = file.pathname file.pathname = file.newPathname delete file.newPathname } } this._loadFileTreeRequestCanceller = null this.$scope.history.loadingFileTree = false this.autoSelectFile() }) .catch(err => { if (err.status !== -1) { this._loadFileTreeRequestCanceller = null } else { this.$scope.history.loadingFileTree = false } }) } selectFile(file) { if (file != null && file.pathname != null) { this.$scope.history.selection.pathname = this._previouslySelectedPathname = file.pathname this.$scope.history.selection.file = file if (this.$scope.history.viewMode === HistoryViewModes.POINT_IN_TIME) { this.loadFileAtPointInTime() } else { this.reloadDiff() } } } autoSelectFile() { const selectedPathname = null const files = this.$scope.history.selection.files let fileToSelect = null let previouslySelectedFile = null let previouslySelectedFileHasOp = false const filesWithOps = this._getFilesWithOps() const orderedOpTypes = ['edited', 'added', 'renamed', 'removed'] if (this._previouslySelectedPathname != null) { previouslySelectedFile = _.find(files, { pathname: this._previouslySelectedPathname, }) previouslySelectedFileHasOp = _.some(filesWithOps, { pathname: this._previouslySelectedPathname, }) } if (previouslySelectedFile != null && previouslySelectedFileHasOp) { fileToSelect = previouslySelectedFile } else { for (const opType of orderedOpTypes) { const fileWithMatchingOpType = _.find(filesWithOps, { operation: opType, }) if (fileWithMatchingOpType != null) { fileToSelect = _.find(files, { pathname: fileWithMatchingOpType.pathname, }) break } } if (fileToSelect == null) { if (previouslySelectedFile != null) { fileToSelect = previouslySelectedFile } else { const mainFile = _.find(files, function (file) { return /main\.tex$/.test(file.pathname) }) if (mainFile != null) { fileToSelect = mainFile } else { const anyTeXFile = _.find(files, function (file) { return /\.tex$/.test(file.pathname) }) if (anyTeXFile != null) { fileToSelect = anyTeXFile } else { fileToSelect = files[0] } } } } } this.selectFile(fileToSelect) } _getFilesWithOps() { let filesWithOps if (this.$scope.history.viewMode === HistoryViewModes.POINT_IN_TIME) { const currentUpdate = this.getUpdateForVersion( this.$scope.history.selection.range.toV ) filesWithOps = [] if (currentUpdate != null) { for (const pathname of currentUpdate.pathnames) { filesWithOps.push({ pathname: pathname, operation: 'edited', }) } for (const op of currentUpdate.project_ops) { let fileWithOp if (op.add != null) { fileWithOp = { pathname: op.add.pathname, operation: 'added', } } else if (op.remove != null) { fileWithOp = { pathname: op.remove.pathname, operation: 'removed', } } else if (op.rename != null) { fileWithOp = { pathname: op.rename.newPathname, operation: 'renamed', } } if (fileWithOp != null) { filesWithOps.push(fileWithOp) } } } } else { filesWithOps = _.reduce( this.$scope.history.selection.files, (curFilesWithOps, file) => { if (file.operation) { curFilesWithOps.push({ pathname: file.pathname, operation: file.operation, }) } return curFilesWithOps }, [] ) } return filesWithOps } autoSelectRecentUpdates() { if (this.$scope.history.updates.length === 0) { return } const toV = this.$scope.history.updates[0].toV let fromV = null let indexOfLastUpdateNotByMe = 0 for (let i = 0; i < this.$scope.history.updates.length; i++) { const update = this.$scope.history.updates[i] if ( this._updateContainsUserId(update, this.$scope.user.id) || i > this.MAX_RECENT_UPDATES_TO_SELECT ) { break } indexOfLastUpdateNotByMe = i } fromV = this.$scope.history.updates[indexOfLastUpdateNotByMe].fromV this.selectVersionsForCompare(toV, fromV) } autoSelectVersionForPointInTime() { if (this.$scope.history.updates.length === 0) { return } let versionToSelect = this.$scope.history.updates[0].toV const range = this.$scope.history.selection.range if ( range.toV != null && range.fromV != null && range.toV === range.fromV ) { versionToSelect = range.toV } this.selectVersionForPointInTime(versionToSelect) } autoSelectLastLabel() { if ( this.$scope.history.labels == null || this.$scope.history.labels.length === 0 ) { return } return this.selectLabelForPointInTime(this.$scope.history.labels[0]) } expandSelectionToVersion(version) { if (version > this.$scope.history.selection.range.toV) { this.$scope.history.selection.range.toV = version } else if (version < this.$scope.history.selection.range.fromV) { this.$scope.history.selection.range.fromV = version } } selectVersionForPointInTime(version) { const selection = this.$scope.history.selection if ( selection.range.toV !== version && selection.range.fromV !== version ) { selection.range.toV = version selection.range.fromV = version this.loadFileTreeForVersion(version) } } selectVersionsForCompare(toV, fromV) { const range = this.$scope.history.selection.range if (range.toV !== toV || range.fromV !== fromV) { range.toV = toV range.fromV = fromV this.loadFileTreeDiff(toV, fromV) } } autoSelectLabelForPointInTime() { const selectedUpdate = this.getUpdateForVersion( this.$scope.history.selection.range.toV ) let nSelectedLabels = 0 if (selectedUpdate != null && selectedUpdate.labels != null) { nSelectedLabels = selectedUpdate.labels.length } // If the currently selected update has no labels, select the last one (version-wise) if (nSelectedLabels === 0) { this.autoSelectLastLabel() // If the update has one label, select it } else if (nSelectedLabels === 1) { this.selectLabelForPointInTime(selectedUpdate.labels[0]) // If there are multiple labels for the update, select the latest } else if (nSelectedLabels > 1) { const sortedLabels = this.ide.$filter('orderBy')( selectedUpdate.labels, '-created_at' ) const lastLabelFromUpdate = sortedLabels[0] this.selectLabelForPointInTime(lastLabelFromUpdate) } } selectLabelForPointInTime(labelToSelect) { let updateToSelect = null if (this._isLabelSelected(labelToSelect)) { // Label already selected return } for (const update of Array.from(this.$scope.history.updates)) { if (update.toV === labelToSelect.version) { updateToSelect = update break } } if (updateToSelect != null) { this.selectVersionForPointInTime(updateToSelect.toV) } else { const selection = this.$scope.history.selection selection.range.toV = labelToSelect.version selection.range.fromV = labelToSelect.version this.loadFileTreeForVersion(labelToSelect.version) } } getUpdateForVersion(version) { for (const update of this.$scope.history.updates) { if (update.toV === version) { return update } } } autoSelectLabelsForComparison() { const labels = this.$scope.history.labels let nLabels = 0 if (Array.isArray(labels)) { nLabels = labels.length } if (nLabels === 0) { // TODO better handling } else if (nLabels === 1) { this.selectVersionsForCompare(labels[0].version, labels[0].version) } else if (nLabels > 1) { this.selectVersionsForCompare(labels[0].version, labels[1].version) } } fetchNextBatchOfUpdates() { if (this.$scope.history.atEnd) { return } let updatesURL = `/project/${this.ide.project_id}/updates?min_count=${this.BATCH_SIZE}` if (this.$scope.history.nextBeforeTimestamp != null) { updatesURL += `&before=${this.$scope.history.nextBeforeTimestamp}` } const labelsURL = `/project/${this.ide.project_id}/labels` const requests = { updates: this.ide.$http.get(updatesURL) } if (this.$scope.history.labels == null) { requests.labels = this.ide.$http.get(labelsURL) } this.$scope.history.loading = true return this.ide.$q .all(requests) .then(response => { this.$scope.history.loading = false const updatesData = response.updates.data let lastUpdateToV = null if (updatesData.updates.length > 0) { lastUpdateToV = updatesData.updates[0].toV } if (response.labels != null) { this.$scope.history.labels = this._loadLabels( response.labels.data, lastUpdateToV ) } this._loadUpdates(updatesData.updates) this.$scope.history.nextBeforeTimestamp = updatesData.nextBeforeTimestamp if ( updatesData.nextBeforeTimestamp == null || this.$scope.history.freeHistoryLimitHit || this.$scope.history.updates.length === 0 ) { this.$scope.history.atEnd = true } if (this.$scope.history.updates.length === 0) { this.$scope.history.loadingFileTree = false } }) .catch(error => { this.$scope.history.loading = false const { status, statusText } = error this.$scope.history.error = { status, statusText } this.$scope.history.atEnd = true this.$scope.history.loadingFileTree = false }) } _loadLabels(labels, lastUpdateToV) { const sortedLabels = this._sortLabelsByVersionAndDate(labels) const labelsWithoutPseudoLabel = this._deletePseudoCurrentStateLabelIfExistent( sortedLabels ) const labelsWithPseudoLabelIfNeeded = this._addPseudoCurrentStateLabelIfNeeded( labelsWithoutPseudoLabel, lastUpdateToV ) return labelsWithPseudoLabelIfNeeded } _deletePseudoCurrentStateLabelIfExistent(labels) { if (labels.length && labels[0].isPseudoCurrentStateLabel) { labels.shift() } return labels } _addPseudoCurrentStateLabelIfNeeded(labels, mostRecentVersion) { if ( (labels.length && labels[0].version !== mostRecentVersion) || labels.length === 0 ) { const pseudoCurrentStateLabel = { id: '1', isPseudoCurrentStateLabel: true, version: mostRecentVersion, created_at: new Date().toISOString(), } labels.unshift(pseudoCurrentStateLabel) } return labels } _sortLabelsByVersionAndDate(labels) { return this.ide.$filter('orderBy')(labels, [ 'isPseudoCurrentStateLabel', '-version', '-created_at', ]) } loadFileAtPointInTime() { const toV = this.$scope.history.selection.range.toV const { pathname } = this.$scope.history.selection if (toV == null) { return } let url = `/project/${this.$scope.project_id}/diff` const query = [ `pathname=${encodeURIComponent(pathname)}`, `from=${toV}`, `to=${toV}`, ] url += `?${query.join('&')}` this.$scope.history.selection.file.loading = true return this.ide.$http .get(url) .then(response => { const { text, binary } = this._parseDiff(response.data.diff) this.$scope.history.selection.file.binary = binary this.$scope.history.selection.file.text = text this.$scope.history.selection.file.loading = false }) .catch(function () {}) } reloadDiff() { let { diff } = this.$scope.history.selection const { range, pathname } = this.$scope.history.selection const { fromV, toV } = range if (pathname == null) { this.$scope.history.selection.diff = null return } if ( diff != null && diff.pathname === pathname && diff.fromV === fromV && diff.toV === toV ) { return } this.$scope.history.selection.diff = diff = { fromV, toV, pathname, error: false, } diff.loading = true let url = `/project/${this.$scope.project_id}/diff` const query = [`pathname=${encodeURIComponent(pathname)}`] if (diff.fromV != null && diff.toV != null) { query.push(`from=${diff.fromV}`, `to=${diff.toV}`) } url += `?${query.join('&')}` return this.ide.$http .get(url) .then(response => { const { data } = response diff.loading = false const { text, highlights, binary } = this._parseDiff(data.diff) diff.binary = binary diff.text = text diff.highlights = highlights }) .catch(function () { diff.loading = false diff.error = true }) } labelCurrentVersion(labelComment) { return this._labelVersion( labelComment, this.$scope.history.selection.range.toV ) } deleteLabel(label) { const url = `/project/${this.$scope.project_id}/labels/${label.id}` return this.ide .$http({ url, method: 'DELETE', headers: { 'X-CSRF-Token': window.csrfToken, }, }) .then(response => { return this._deleteLabelLocally(label) }) } _deleteLabelLocally(labelToDelete) { for (let i = 0; i < this.$scope.history.updates.length; i++) { const update = this.$scope.history.updates[i] if (update.toV === labelToDelete.version) { update.labels = _.filter( update.labels, label => label.id !== labelToDelete.id ) break } } this.$scope.history.labels = this._loadLabels( _.filter( this.$scope.history.labels, label => label.id !== labelToDelete.id ), this.$scope.history.updates[0].toV ) this._handleHistoryUIStateChange() } _isLabelSelected(label) { if (label) { return ( label.version <= this.$scope.history.selection.range.toV && label.version >= this.$scope.history.selection.range.fromV ) } else { return false } } _parseDiff(diff) { if (diff.binary) { return { binary: true } } let row = 0 let column = 0 const highlights = [] let text = '' const iterable = diff || [] for (let i = 0; i < iterable.length; i++) { var endColumn, endRow const entry = iterable[i] let content = entry.u || entry.i || entry.d if (!content) { content = '' } text += content const lines = content.split('\n') const startRow = row const startColumn = column if (lines.length > 1) { endRow = startRow + lines.length - 1 endColumn = lines[lines.length - 1].length } else { endRow = startRow endColumn = startColumn + lines[0].length } row = endRow column = endColumn const range = { start: { row: startRow, column: startColumn, }, end: { row: endRow, column: endColumn, }, } if (entry.i != null || entry.d != null) { const user = entry.meta.users != null ? entry.meta.users[0] : undefined const name = displayNameForUser(user) const date = moment(entry.meta.end_ts).format('Do MMM YYYY, h:mm a') if (entry.i != null) { highlights.push({ label: `Added by ${name} on ${date}`, highlight: range, hue: ColorManager.getHueForUserId( user != null ? user.id : undefined ), }) } else if (entry.d != null) { highlights.push({ label: `Deleted by ${name} on ${date}`, strikeThrough: range, hue: ColorManager.getHueForUserId( user != null ? user.id : undefined ), }) } } } return { text, highlights } } _loadUpdates(updates) { if (updates == null) { updates = [] } let previousUpdate = this.$scope.history.updates[ this.$scope.history.updates.length - 1 ] const dateTimeNow = new Date() const timestamp24hoursAgo = dateTimeNow.setDate(dateTimeNow.getDate() - 1) let cutOffIndex = null const iterable = updates || [] for (let i = 0; i < iterable.length; i++) { const update = iterable[i] for (const user of Array.from(update.meta.users || [])) { if (user != null) { user.hue = ColorManager.getHueForUserId(user.id) } } if ( previousUpdate == null || !moment(previousUpdate.meta.end_ts).isSame(update.meta.end_ts, 'day') ) { update.meta.first_in_day = true } previousUpdate = update if ( !this.$scope.history.userHasFullFeature && update.meta.end_ts < timestamp24hoursAgo ) { cutOffIndex = i || 1 // Make sure that we show at least one entry (to allow labelling). this.$scope.history.freeHistoryLimitHit = true if (this.$scope.project.owner._id === this.$scope.user.id) { ga( 'send', 'event', 'subscription-funnel', 'editor-click-feature', 'history' ) paywallPrompt('history') } break } } const firstLoad = this.$scope.history.updates.length === 0 if (!this.$scope.history.userHasFullFeature && cutOffIndex != null) { updates = updates.slice(0, cutOffIndex) } this.$scope.history.updates = this.$scope.history.updates.concat(updates) if (firstLoad) { this._handleHistoryUIStateChange() } } _labelVersion(comment, version) { const url = `/project/${this.$scope.project_id}/labels` return this.ide.$http .post(url, { comment, version, _csrf: window.csrfToken, }) .then(response => { return this._addLabelLocally(response.data) }) } _addLabelLocally(label) { const localUpdate = _.find( this.$scope.history.updates, update => update.toV === label.version ) if (localUpdate != null) { localUpdate.labels = localUpdate.labels.concat(label) } this.$scope.history.labels = this._loadLabels( this.$scope.history.labels.concat(label), this.$scope.history.updates[0].toV ) this._handleHistoryUIStateChange() } _updateContainsUserId(update, user_id) { for (const user of Array.from(update.meta.users)) { if ((user != null ? user.id : undefined) === user_id) { return true } } return false } } HistoryManager.initClass() return HistoryManager })() function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/frontend/js/ide/history/HistoryV2Manager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/HistoryV2Manager.js", "repo_id": "overleaf", "token_count": 14090 }
513
/* eslint-disable max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.directive('infiniteScroll', () => ({ link(scope, element, attrs, ctrl) { const innerElement = element.find('.infinite-scroll-inner') element.css({ 'overflow-y': 'auto' }) const atEndOfListView = function () { if (attrs.infiniteScrollUpwards != null) { return atTopOfListView() } else { return atBottomOfListView() } } var atTopOfListView = () => element.scrollTop() < 30 var atBottomOfListView = () => element.scrollTop() + element.height() >= innerElement.height() - 30 const listShorterThanContainer = () => element.height() > innerElement.height() var loadUntilFull = function () { if ( (listShorterThanContainer() || atEndOfListView()) && !scope.$eval(attrs.infiniteScrollDisabled) ) { const promise = scope.$eval(attrs.infiniteScroll) return promise.then(() => setTimeout(() => loadUntilFull(), 0)) } } element.on('scroll', event => loadUntilFull()) return scope.$watch(attrs.infiniteScrollInitialize, function (value) { if (value) { return loadUntilFull() } }) }, }))
overleaf/web/frontend/js/ide/history/directives/infiniteScroll.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/directives/infiniteScroll.js", "repo_id": "overleaf", "token_count": 577 }
514
/* eslint-disable max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' import PDFJS from './pdfJsLoader' export default App.factory('pdfHighlights', function () { let pdfHighlights return (pdfHighlights = class pdfHighlights { constructor(options) { this.highlightsLayerDiv = options.highlights[0] this.highlightElements = [] } addHighlight(viewport, left, top, width, height) { let rect = viewport.convertToViewportRectangle([ left, top, left + width, top + height, ]) rect = PDFJS.Util.normalizeRect(rect) const element = document.createElement('div') element.style.left = Math.floor(rect[0]) + 'px' element.style.top = Math.floor(rect[1]) + 'px' element.style.width = Math.ceil(rect[2] - rect[0]) + 'px' element.style.height = Math.ceil(rect[3] - rect[1]) + 'px' this.highlightElements.push(element) this.highlightsLayerDiv.appendChild(element) return element } clearHighlights() { for (const h of Array.from(this.highlightElements)) { if (h != null) { h.parentNode.removeChild(h) } } return (this.highlightElements = []) } }) })
overleaf/web/frontend/js/ide/pdfng/directives/pdfHighlights.js/0
{ "file_path": "overleaf/web/frontend/js/ide/pdfng/directives/pdfHighlights.js", "repo_id": "overleaf", "token_count": 643 }
515
import _ from 'lodash' /* eslint-disable camelcase, max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' import isValidTeXFile from '../../../main/is-valid-tex-file' export default App.controller( 'SettingsController', function ($scope, settings, ide) { $scope.overallThemesList = window.overallThemes $scope.ui = { loadingStyleSheet: false } const _updateCSSFile = function (theme) { $scope.ui.loadingStyleSheet = true const docHeadEl = document.querySelector('head') const oldStyleSheetEl = document.getElementById('main-stylesheet') const newStyleSheetEl = document.createElement('link') newStyleSheetEl.addEventListener('load', e => { return $scope.$applyAsync(() => { $scope.ui.loadingStyleSheet = false return docHeadEl.removeChild(oldStyleSheetEl) }) }) newStyleSheetEl.setAttribute('rel', 'stylesheet') newStyleSheetEl.setAttribute('id', 'main-stylesheet') newStyleSheetEl.setAttribute('href', theme.path) return docHeadEl.appendChild(newStyleSheetEl) } if (!['default', 'vim', 'emacs'].includes($scope.settings.mode)) { $scope.settings.mode = 'default' } if (!['pdfjs', 'native'].includes($scope.settings.pdfViewer)) { $scope.settings.pdfViewer = 'pdfjs' } if ( $scope.settings.fontFamily != null && !['monaco', 'lucida'].includes($scope.settings.fontFamily) ) { delete $scope.settings.fontFamily } if ( $scope.settings.lineHeight != null && !['compact', 'normal', 'wide'].includes($scope.settings.lineHeight) ) { delete $scope.settings.lineHeight } $scope.fontSizeAsStr = function (newVal) { if (newVal != null) { $scope.settings.fontSize = newVal } return $scope.settings.fontSize.toString() } $scope.getValidMainDocs = () => { let filteredDocs = [] if ($scope.docs) { // Filter the existing docs (editable files) by accepted file extensions. // It's possible that an existing project has an invalid file selected as the main one. // To gracefully handle that case, make sure we also show the current main file (ignoring extension). filteredDocs = $scope.docs.filter( doc => isValidTeXFile(doc.doc.name) || $scope.project.rootDoc_id === doc.doc.id ) } return filteredDocs } $scope.$watch('settings.editorTheme', (editorTheme, oldEditorTheme) => { if (editorTheme !== oldEditorTheme) { return settings.saveSettings({ editorTheme }) } }) $scope.$watch('settings.overallTheme', (overallTheme, oldOverallTheme) => { if (overallTheme !== oldOverallTheme) { const chosenTheme = _.find( $scope.overallThemesList, theme => theme.val === overallTheme ) if (chosenTheme != null) { _updateCSSFile(chosenTheme) return settings.saveSettings({ overallTheme }) } } }) $scope.$watch('settings.fontSize', (fontSize, oldFontSize) => { if (fontSize !== oldFontSize) { return settings.saveSettings({ fontSize: parseInt(fontSize, 10) }) } }) $scope.$watch('settings.mode', (mode, oldMode) => { if (mode !== oldMode) { return settings.saveSettings({ mode }) } }) $scope.$watch('settings.autoComplete', (autoComplete, oldAutoComplete) => { if (autoComplete !== oldAutoComplete) { return settings.saveSettings({ autoComplete }) } }) $scope.$watch( 'settings.autoPairDelimiters', (autoPairDelimiters, oldAutoPairDelimiters) => { if (autoPairDelimiters !== oldAutoPairDelimiters) { return settings.saveSettings({ autoPairDelimiters }) } } ) $scope.$watch('settings.pdfViewer', (pdfViewer, oldPdfViewer) => { if (pdfViewer !== oldPdfViewer) { return settings.saveSettings({ pdfViewer }) } }) $scope.$watch( 'settings.syntaxValidation', (syntaxValidation, oldSyntaxValidation) => { if (syntaxValidation !== oldSyntaxValidation) { return settings.saveSettings({ syntaxValidation }) } } ) $scope.$watch('settings.fontFamily', (fontFamily, oldFontFamily) => { if (fontFamily !== oldFontFamily) { return settings.saveSettings({ fontFamily }) } }) $scope.$watch('settings.lineHeight', (lineHeight, oldLineHeight) => { if (lineHeight !== oldLineHeight) { return settings.saveSettings({ lineHeight }) } }) $scope.$watch('project.spellCheckLanguage', (language, oldLanguage) => { if (this.ignoreUpdates) { return } if (oldLanguage != null && language !== oldLanguage) { settings.saveProjectSettings({ spellCheckLanguage: language }) // Also set it as the default for the user return settings.saveSettings({ spellCheckLanguage: language }) } }) $scope.$watch('project.compiler', (compiler, oldCompiler) => { if (this.ignoreUpdates) { return } if (oldCompiler != null && compiler !== oldCompiler) { return settings.saveProjectSettings({ compiler }) } }) $scope.$watch('project.imageName', (imageName, oldImageName) => { if (this.ignoreUpdates) { return } if (oldImageName != null && imageName !== oldImageName) { return settings.saveProjectSettings({ imageName }) } }) $scope.$watch('project.rootDoc_id', (rootDoc_id, oldRootDoc_id) => { if (this.ignoreUpdates) { return } // don't save on initialisation, Angular passes oldRootDoc_id as // undefined in this case. if (typeof oldRootDoc_id === 'undefined') { return } if ($scope.permissionsLevel === 'readOnly') { // The user is unauthorized to persist rootDoc changes. // Use the new value for this very editor session only. return } // otherwise only save changes, null values are allowed if (rootDoc_id !== oldRootDoc_id) { settings.saveProjectSettings({ rootDocId: rootDoc_id }).catch(() => { $scope.project.rootDoc_id = oldRootDoc_id }) } }) ide.socket.on('compilerUpdated', compiler => { this.ignoreUpdates = true $scope.$apply(() => { return ($scope.project.compiler = compiler) }) return delete this.ignoreUpdates }) ide.socket.on('imageNameUpdated', imageName => { this.ignoreUpdates = true $scope.$apply(() => { return ($scope.project.imageName = imageName) }) return delete this.ignoreUpdates }) return ide.socket.on('spellCheckLanguageUpdated', languageCode => { this.ignoreUpdates = true $scope.$apply(() => { return ($scope.project.spellCheckLanguage = languageCode) }) return delete this.ignoreUpdates }) } )
overleaf/web/frontend/js/ide/settings/controllers/SettingsController.js/0
{ "file_path": "overleaf/web/frontend/js/ide/settings/controllers/SettingsController.js", "repo_id": "overleaf", "token_count": 2937 }
516
import * as eventTracking from '../infrastructure/event-tracking' function startFreeTrial(source, version, $scope) { const plan = 'collaborator_free_trial_7_days' const w = window.open() const go = function () { let url if (typeof ga === 'function') { ga('send', 'event', 'subscription-funnel', 'upgraded-free-trial', source) } eventTracking.sendMB(`${source}-paywall-click`) url = `/user/subscription/new?planCode=${plan}&ssp=true` url = `${url}&itm_campaign=${source}` if (version) { url = `${url}&itm_content=${version}` } if ($scope) { $scope.startedFreeTrial = true } w.location = url } go() } function upgradePlan(source, $scope) { const w = window.open() const go = function () { if (typeof ga === 'function') { ga('send', 'event', 'subscription-funnel', 'upgraded-plan', source) } const url = '/user/subscription' if ($scope) { $scope.startedFreeTrial = true } w.location = url } go() } function paywallPrompt(source) { eventTracking.sendMB(`${source}-paywall-prompt`) } export { startFreeTrial, upgradePlan, paywallPrompt }
overleaf/web/frontend/js/main/account-upgrade.js/0
{ "file_path": "overleaf/web/frontend/js/main/account-upgrade.js", "repo_id": "overleaf", "token_count": 462 }
517
/* eslint-disable camelcase, max-len */ import App from '../base' import getMeta from '../utils/meta' App.factory('MultiCurrencyPricing', function () { const currencyCode = getMeta('ol-recomendedCurrency') return { currencyCode, plans: { USD: { symbol: '$', student: { monthly: '$8', annual: '$80', }, personal: { monthly: '$10', annual: '$120', }, collaborator: { monthly: '$15', annual: '$180', }, professional: { monthly: '$30', annual: '$360', }, }, EUR: { symbol: '€', student: { monthly: '€7', annual: '€70', }, personal: { monthly: '€9', annual: '€108', }, collaborator: { monthly: '€14', annual: '€168', }, professional: { monthly: '€28', annual: '€336', }, }, GBP: { symbol: '£', student: { monthly: '£6', annual: '£60', }, personal: { monthly: '£8', annual: '£96', }, collaborator: { monthly: '£12', annual: '£144', }, professional: { monthly: '£24', annual: '£288', }, }, SEK: { symbol: 'kr', student: { monthly: '60 kr', annual: '600 kr', }, personal: { monthly: '73 kr', annual: '876 kr', }, collaborator: { monthly: '110 kr', annual: '1320 kr', }, professional: { monthly: '220 kr', annual: '2640 kr', }, }, CAD: { symbol: '$', student: { monthly: '$9', annual: '$90', }, personal: { monthly: '$11', annual: '$132', }, collaborator: { monthly: '$17', annual: '$204', }, professional: { monthly: '$34', annual: '$408', }, }, NOK: { symbol: 'kr', student: { monthly: '60 kr', annual: '600 kr', }, personal: { monthly: '73 kr', annual: '876 kr', }, collaborator: { monthly: '110 kr', annual: '1320 kr', }, professional: { monthly: '220 kr', annual: '2640 kr', }, }, DKK: { symbol: 'kr', student: { monthly: '50 kr', annual: '500 kr', }, personal: { monthly: '60 kr', annual: '720 kr', }, collaborator: { monthly: '90 kr', annual: '1080 kr', }, professional: { monthly: '180 kr', annual: '2160 kr', }, }, AUD: { symbol: '$', student: { monthly: '$10', annual: '$100', }, personal: { monthly: '$12', annual: '$144', }, collaborator: { monthly: '$18', annual: '$216', }, professional: { monthly: '$35', annual: '$420', }, }, NZD: { symbol: '$', student: { monthly: '$10', annual: '$100', }, personal: { monthly: '$12', annual: '$144', }, collaborator: { monthly: '$18', annual: '$216', }, professional: { monthly: '$35', annual: '$420', }, }, CHF: { symbol: 'Fr', student: { monthly: 'Fr 8', annual: 'Fr 80', }, personal: { monthly: 'Fr 10', annual: 'Fr 120', }, collaborator: { monthly: 'Fr 15', annual: 'Fr 180', }, professional: { monthly: 'Fr 30', annual: 'Fr 360', }, }, SGD: { symbol: '$', student: { monthly: '$12', annual: '$120', }, personal: { monthly: '$13', annual: '$156', }, collaborator: { monthly: '$20', annual: '$240', }, professional: { monthly: '$40', annual: '$480', }, }, }, } }) App.controller( 'PlansController', function ( $scope, $modal, eventTracking, MultiCurrencyPricing, $http, $filter, $location ) { $scope.plans = MultiCurrencyPricing.plans $scope.currencyCode = MultiCurrencyPricing.currencyCode $scope.trial_len = 7 $scope.planQueryString = '_free_trial_7_days' $scope.ui = { view: 'monthly' } $scope.changeCurreny = function (e, newCurrency) { e.preventDefault() $scope.currencyCode = newCurrency } // because ternary logic in angular bindings is hard $scope.getCollaboratorPlanCode = function () { const { view } = $scope.ui if (view === 'annual') { return 'collaborator-annual' } else { return `collaborator${$scope.planQueryString}` } } $scope.getPersonalPlanCode = function () { const { view } = $scope.ui if (view === 'annual') { return 'paid-personal-annual' } else { return `paid-personal${$scope.planQueryString}` } } $scope.signUpNowClicked = function (plan, location) { if ($scope.ui.view === 'annual') { plan = `${plan}_annual` } plan = eventLabel(plan, location) eventTracking.sendMB('plans-page-start-trial') eventTracking.send('subscription-funnel', 'sign_up_now_button', plan) } $scope.switchToMonthly = function (e, location) { const uiView = 'monthly' switchEvent(e, uiView + '-prices', location) $scope.ui.view = uiView } $scope.switchToStudent = function (e, location) { const uiView = 'student' switchEvent(e, uiView + '-prices', location) $scope.ui.view = uiView } $scope.switchToAnnual = function (e, location) { const uiView = 'annual' switchEvent(e, uiView + '-prices', location) $scope.ui.view = uiView } $scope.openGroupPlanModal = function () { const path = `${window.location.pathname}${window.location.search}` history.replaceState(null, document.title, path + '#groups') $modal .open({ templateUrl: 'groupPlanModalPurchaseTemplate', controller: 'GroupPlansModalPurchaseController', }) .result.finally(() => history.replaceState(null, document.title, window.location.pathname) ) eventTracking.send( 'subscription-funnel', 'plans-page', 'group-inquiry-potential' ) } if ($location.hash() === 'groups') { $scope.openGroupPlanModal() } var eventLabel = (label, location) => label function switchEvent(e, label, location) { e.preventDefault() const gaLabel = eventLabel(label, location) eventTracking.send('subscription-funnel', 'plans-page', gaLabel) } } ) App.controller( 'GroupPlansModalPurchaseController', function ($scope, $modal, $location, $httpParamSerializer) { $scope.options = { plan_codes: [ { display: 'Collaborator', code: 'collaborator', }, { display: 'Professional', code: 'professional', }, ], currencies: [ { display: 'USD ($)', code: 'USD', }, { display: 'GBP (£)', code: 'GBP', }, { display: 'EUR (€)', code: 'EUR', }, ], currencySymbols: { USD: '$', EUR: '€', GBP: '£', }, sizes: [2, 3, 4, 5, 10, 20, 50], usages: [ { display: 'Enterprise', code: 'enterprise', }, { display: 'Educational', code: 'educational', }, ], } $scope.prices = getMeta('ol-groupPlans') let currency = 'USD' const recomendedCurrency = getMeta('ol-recomendedCurrency') if (['USD', 'GBP', 'EUR'].includes(recomendedCurrency)) { currency = recomendedCurrency } // default selected $scope.selected = { plan_code: 'collaborator', currency, size: '10', usage: 'enterprise', } // selected via query if ($location.search()) { // usage if ($location.search().usage) { $scope.options.usages.forEach(usage => { if (usage.code === $location.search().usage) { $scope.selected.usage = usage.code } }) } // plan if ($location.search().plan) { $scope.options.plan_codes.forEach(plan => { if (plan.code === $location.search().plan) { $scope.selected.plan_code = plan.code } }) } // number if ($location.search().number) { // $location.search().number is a string, // but $scope.options.sizes are numbers // and $scope.selected.size is a string const groupCount = parseInt($location.search().number, 10) if ($scope.options.sizes.indexOf(groupCount) !== -1) { $scope.selected.size = $location.search().number } } // currency if ($location.search().currency) { $scope.options.currencies.forEach(currency => { if (currency.code === $location.search().currency) { $scope.selected.currency = currency.code } }) } } $scope.recalculatePrice = function () { const { usage, plan_code, currency, size } = $scope.selected const price = $scope.prices[usage][plan_code][currency][size] const currencySymbol = $scope.options.currencySymbols[currency] $scope.displayPrice = `${currencySymbol}${price}` } $scope.$watch('selected', $scope.recalculatePrice, true) $scope.recalculatePrice() $scope.purchase = function () { const { plan_code, size, usage, currency } = $scope.selected const queryParams = { planCode: `group_${plan_code}_${size}_${usage}`, currency, itm_campaign: 'groups', } if ($location.search().itm_content) { queryParams.itm_content = $location.search().itm_content } window.location = `/user/subscription/new?${$httpParamSerializer( queryParams )}` } } )
overleaf/web/frontend/js/main/plans.js/0
{ "file_path": "overleaf/web/frontend/js/main/plans.js", "repo_id": "overleaf", "token_count": 5565 }
518
import App from '../base' App.controller( 'TranslationsPopupController', function ($scope, ipCookie, localStorage) { function getStoredDismissal() { const localStore = localStorage('hide-i18n-notification') if (localStore === null) { // Not stored in localStorage, check cookie const cookieStore = ipCookie('hidei18nNotification') // If stored in cookie, set on localStorage for forwards compat if (cookieStore) { localStorage('hide-i18n-notification', cookieStore) ipCookie.remove('hidei18nNotification') } return cookieStore } return localStore } $scope.hidei18nNotification = getStoredDismissal() $scope.dismiss = function () { localStorage('hide-i18n-notification', true) $scope.hidei18nNotification = true } } )
overleaf/web/frontend/js/main/translations.js/0
{ "file_path": "overleaf/web/frontend/js/main/translations.js", "repo_id": "overleaf", "token_count": 334 }
519
import PropTypes from 'prop-types' import classNames from 'classnames' function Icon({ type, spin, modifier, classes = {}, accessibilityLabel, children, }) { const iconClassName = classNames( 'fa', `fa-${type}`, { 'fa-spin': spin, [`fa-${modifier}`]: modifier, }, classes.icon ) return ( <> <i className={iconClassName} aria-hidden="true"> {children} </i> {accessibilityLabel ? ( <span className="sr-only">{accessibilityLabel}</span> ) : null} </> ) } Icon.propTypes = { type: PropTypes.string.isRequired, spin: PropTypes.bool, modifier: PropTypes.string, classes: PropTypes.exact({ icon: PropTypes.string, }), accessibilityLabel: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), } export default Icon
overleaf/web/frontend/js/shared/components/icon.js/0
{ "file_path": "overleaf/web/frontend/js/shared/components/icon.js", "repo_id": "overleaf", "token_count": 362 }
520
import { useEffect, useState } from 'react' export default function useDebounce(value, delay = 0) { const [debouncedValue, setDebouncedValue] = useState(value) useEffect(() => { const timer = window.setTimeout(() => { setDebouncedValue(value) }, delay) return () => { window.clearTimeout(timer) } }, [value, delay]) return debouncedValue }
overleaf/web/frontend/js/shared/hooks/use-debounce.js/0
{ "file_path": "overleaf/web/frontend/js/shared/hooks/use-debounce.js", "repo_id": "overleaf", "token_count": 133 }
521
/*! jQuery UI - v1.11.4 - 2016-02-10 * http://jqueryui.com * Includes: core.js, widget.js, mouse.js, draggable.js, droppable.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ /*! * jQuery UI Core 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.4", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; return !!img && visible( img ); } return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Widget 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; (elem = elems[i]) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { // Allow multiple hashes to be passed on init if ( args.length ) { options = $.widget.extend.apply( null, [ options ].concat(args) ); } this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); var widget = $.widget; /*! * jQuery UI Mouse 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/mouse/ */ var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); var mouse = $.widget("ui.mouse", { version: "1.11.4", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown." + this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click." + this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("." + this.widgetName); if ( this._mouseMoveDelegate ) { this.document .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate) .unbind("mouseup." + this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if ( mouseHandled ) { return; } this._mouseMoved = false; // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; this.document .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .bind( "mouseup." + this.widgetName, this._mouseUpDelegate ); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // Only check for mouseups outside the document if you've moved inside the document // at least once. This prevents the firing of mouseup in the case of IE<9, which will // fire a mousemove event if content is placed under the cursor. See #7778 // Support: IE <9 if ( this._mouseMoved ) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); // Iframe mouseup check - mouseup occurred in another document } else if ( !event.which ) { return this._mouseUp( event ); } } if ( event.which || event.button ) { this._mouseMoved = true; } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { this.document .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate ); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } mouseHandled = false; return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); /*! * jQuery UI Draggable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/draggable/ */ $.widget("ui.draggable", $.ui.mouse, { version: "1.11.4", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if ( this.options.helper === "original" ) { this._setPositionRelative(); } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._removeHandleClassName(); this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; this._blurActiveElement( event ); // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix ); return true; }, _blockFrames: function( selector ) { this.iframeBlocks = this.document.find( selector ).map(function() { var iframe = $( this ); return $( "<div>" ) .css( "position", "absolute" ) .appendTo( iframe.parent() ) .outerWidth( iframe.outerWidth() ) .outerHeight( iframe.outerHeight() ) .offset( iframe.offset() )[ 0 ]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _blurActiveElement: function( event ) { var document = this.document[ 0 ]; // Only need to blur if the event occurred on the draggable itself, see #10527 if ( !this.handleElement.is( event.target ) ) { return; } // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent( true ); this.offsetParent = this.helper.offsetParent(); this.hasFixedAncestor = this.helper.parents().filter(function() { return $( this ).css( "position" ) === "fixed"; }).length > 0; //The element's absolute position on the page minus margins this.positionAbs = this.element.offset(); this._refreshOffsets( event ); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } // Reset helper's right/bottom css if they're set and set explicit width/height instead // as this prevents resizing of elements with right/bottom set (see #7772) this._normalizeRightBottom(); this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _refreshOffsets: function( event ) { this.offset = { top: this.positionAbs.top - this.margins.top, left: this.positionAbs.left - this.margins.left, scroll: false, parent: this._getParentOffset(), relative: this._getRelativeOffset() }; this.offset.click = { left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.hasFixedAncestor ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function( event ) { this._unblockFrames(); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // Only need to focus if the event occurred on the draggable itself, see #10527 if ( this.handleElement.is( event.target ) ) { // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); } return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this.handleElement = this.options.handle ? this.element.find( this.options.handle ) : this.element; this.handleElement.addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.handleElement.removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helperIsFunction = $.isFunction( o.helper ), helper = helperIsFunction ? $( o.helper.apply( this.element[ 0 ], [ event ] ) ) : ( o.helper === "clone" ? this.element.clone().removeAttr( "id" ) : this.element ); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } // http://bugs.jqueryui.com/ticket/9446 // a helper function can return the original element // which wouldn't have been set to relative in _create if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) { this._setPositionRelative(); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _setPositionRelative: function() { if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) { this.element[ 0 ].style.position = "relative"; } }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"), 10) || 0), top: (parseInt(this.element.css("marginTop"), 10) || 0), right: (parseInt(this.element.css("marginRight"), 10) || 0), bottom: (parseInt(this.element.css("marginBottom"), 10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var isUserScrollable, c, ce, o = this.options, document = this.document[ 0 ]; this.relativeContainer = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) ); this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relativeContainer = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relativeContainer ){ co = this.relativeContainer.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, _normalizeRightBottom: function() { if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) { this.helper.width( this.helper.width() ); this.helper.css( "right", "auto" ); } if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) { this.helper.height( this.helper.height() ); this.helper.css( "bottom", "auto" ); } }, // From now on bulk stuff - mainly helpers _trigger: function( type, event, ui ) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); // Absolute position and offset (see #6884 ) have to be recalculated after plugins if ( /^(drag|start|stop)/.test( type ) ) { this.positionAbs = this._convertPositionTo( "absolute" ); ui.offset = this.positionAbs; } return $.Widget.prototype._trigger.call( this, type, event, ui ); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add( "draggable", "connectToSortable", { start: function( event, ui, draggable ) { var uiSortable = $.extend( {}, ui, { item: draggable.element }); draggable.sortables = []; $( draggable.options.connectToSortable ).each(function() { var sortable = $( this ).sortable( "instance" ); if ( sortable && !sortable.options.disabled ) { draggable.sortables.push( sortable ); // refreshPositions is called at drag start to refresh the containerCache // which is used in drag. This ensures it's initialized and synchronized // with any changes that might have happened on the page since initialization. sortable.refreshPositions(); sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, draggable ) { var uiSortable = $.extend( {}, ui, { item: draggable.element }); draggable.cancelHelperRemoval = false; $.each( draggable.sortables, function() { var sortable = this; if ( sortable.isOver ) { sortable.isOver = 0; // Allow this sortable to handle removing the helper draggable.cancelHelperRemoval = true; sortable.cancelHelperRemoval = false; // Use _storedCSS To restore properties in the sortable, // as this also handles revert (#9675) since the draggable // may have modified them in unexpected ways (#8809) sortable._storedCSS = { position: sortable.placeholder.css( "position" ), top: sortable.placeholder.css( "top" ), left: sortable.placeholder.css( "left" ) }; sortable._mouseStop(event); // Once drag has ended, the sortable should return to using // its original helper, not the shared helper from draggable sortable.options.helper = sortable.options._helper; } else { // Prevent this Sortable from removing the helper. // However, don't set the draggable to remove the helper // either as another connected Sortable may yet handle the removal. sortable.cancelHelperRemoval = true; sortable._trigger( "deactivate", event, uiSortable ); } }); }, drag: function( event, ui, draggable ) { $.each( draggable.sortables, function() { var innermostIntersecting = false, sortable = this; // Copy over variables that sortable's _intersectsWith uses sortable.positionAbs = draggable.positionAbs; sortable.helperProportions = draggable.helperProportions; sortable.offset.click = draggable.offset.click; if ( sortable._intersectsWith( sortable.containerCache ) ) { innermostIntersecting = true; $.each( draggable.sortables, function() { // Copy over variables that sortable's _intersectsWith uses this.positionAbs = draggable.positionAbs; this.helperProportions = draggable.helperProportions; this.offset.click = draggable.offset.click; if ( this !== sortable && this._intersectsWith( this.containerCache ) && $.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if ( innermostIntersecting ) { // If it intersects, we use a little isOver variable and set it once, // so that the move-in stuff gets fired only once. if ( !sortable.isOver ) { sortable.isOver = 1; // Store draggable's parent in case we need to reappend to it later. draggable._parent = ui.helper.parent(); sortable.currentItem = ui.helper .appendTo( sortable.element ) .data( "ui-sortable-item", true ); // Store helper option to later restore it sortable.options._helper = sortable.options.helper; sortable.options.helper = function() { return ui.helper[ 0 ]; }; // Fire the start events of the sortable with our passed browser event, // and our own helper (so it doesn't create a new one) event.target = sortable.currentItem[ 0 ]; sortable._mouseCapture( event, true ); sortable._mouseStart( event, true, true ); // Because the browser event is way off the new appended portlet, // modify necessary variables to reflect the changes sortable.offset.click.top = draggable.offset.click.top; sortable.offset.click.left = draggable.offset.click.left; sortable.offset.parent.left -= draggable.offset.parent.left - sortable.offset.parent.left; sortable.offset.parent.top -= draggable.offset.parent.top - sortable.offset.parent.top; draggable._trigger( "toSortable", event ); // Inform draggable that the helper is in a valid drop zone, // used solely in the revert option to handle "valid/invalid". draggable.dropped = sortable.element; // Need to refreshPositions of all sortables in the case that // adding to one sortable changes the location of the other sortables (#9675) $.each( draggable.sortables, function() { this.refreshPositions(); }); // hack so receive/update callbacks work (mostly) draggable.currentItem = draggable.element; sortable.fromOutside = draggable; } if ( sortable.currentItem ) { sortable._mouseDrag( event ); // Copy the sortable's position because the draggable's can potentially reflect // a relative position, while sortable is always absolute, which the dragged // element has now become. (#8809) ui.position = sortable.position; } } else { // If it doesn't intersect with the sortable, and it intersected before, // we fake the drag stop of the sortable, but make sure it doesn't remove // the helper by using cancelHelperRemoval. if ( sortable.isOver ) { sortable.isOver = 0; sortable.cancelHelperRemoval = true; // Calling sortable's mouseStop would trigger a revert, // so revert must be temporarily false until after mouseStop is called. sortable.options._revert = sortable.options.revert; sortable.options.revert = false; sortable._trigger( "out", event, sortable._uiHash( sortable ) ); sortable._mouseStop( event, true ); // restore sortable behaviors that were modfied // when the draggable entered the sortable area (#9481) sortable.options.revert = sortable.options._revert; sortable.options.helper = sortable.options._helper; if ( sortable.placeholder ) { sortable.placeholder.remove(); } // Restore and recalculate the draggable's offset considering the sortable // may have modified them in unexpected ways. (#8809, #10669) ui.helper.appendTo( draggable._parent ); draggable._refreshOffsets( event ); ui.position = draggable._generatePosition( event, true ); draggable._trigger( "fromSortable", event ); // Inform draggable that the helper is no longer in a valid drop zone draggable.dropped = false; // Need to refreshPositions of all sortables just in case removing // from one sortable changes the location of other sortables (#9675) $.each( draggable.sortables, function() { this.refreshPositions(); }); } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( !i.scrollParentNotHidden ) { i.scrollParentNotHidden = i.helper.scrollParent( false ); } if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParentNotHidden.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, scrollParent = i.scrollParentNotHidden[ 0 ], document = i.document[ 0 ]; if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) { if ( !o.axis || o.axis !== "x" ) { if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) { scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed; } else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) { scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed; } } if ( !o.axis || o.axis !== "y" ) { if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) { scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed; } else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) { scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left - inst.margins.left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top - inst.margins.top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a, b) { return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); var draggable = $.ui.draggable; /*! * jQuery UI Droppable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/droppable/ */ $.widget( "ui.droppable", { version: "1.11.4", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction( accept ) ? accept : function( d ) { return d.is( accept ); }; this.proportions = function( /* valueToWrite */ ) { if ( arguments.length ) { // Store the droppable's proportions proportions = arguments[ 0 ]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[ 0 ].offsetWidth, height: this.element[ 0 ].offsetHeight }; } }; this._addToManager( o.scope ); o.addClasses && this.element.addClass( "ui-droppable" ); }, _addToManager: function( scope ) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || []; $.ui.ddmanager.droppables[ scope ].push( this ); }, _splice: function( drop ) { var i = 0; for ( ; i < drop.length; i++ ) { if ( drop[ i ] === this ) { drop.splice( i, 1 ); } } }, _destroy: function() { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this.element.removeClass( "ui-droppable ui-droppable-disabled" ); }, _setOption: function( key, value ) { if ( key === "accept" ) { this.accept = $.isFunction( value ) ? value : function( d ) { return d.is( value ); }; } else if ( key === "scope" ) { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this._addToManager( value ); } this._super( key, value ); }, _activate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.addClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "activate", event, this.ui( draggable ) ); } }, _deactivate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "deactivate", event, this.ui( draggable ) ); } }, _over: function( event ) { // console.log("_over", this.element[0]); var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.addClass( this.options.hoverClass ); } this._trigger( "over", event, this.ui( draggable ) ); } }, _out: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "out", event, this.ui( draggable ) ); } }, _drop: function( event, custom ) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return false; } this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() { var inst = $( this ).droppable( "instance" ); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) && $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event ) ) { childrenIntersection = true; return false; } }); if ( childrenIntersection ) { return false; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "drop", event, this.ui( draggable ) ); return this.element; } return false; }, ui: function( c ) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function() { function isOverAxis( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function( draggable, droppable, toleranceMode, event ) { if ( !droppable.offset ) { return false; } var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch ( toleranceMode ) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width ); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight }); } }, drop: function( draggable, event ) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() { if ( !this.options ) { return; } if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) { dropped = this._drop.call( this, event ) || dropped; } if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { this.isout = true; this.isover = false; this._deactivate.call( this, event ); } }); return dropped; }, dragStart: function( draggable, event ) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function( draggable, event ) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if ( draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } var droppables = $.ui.ddmanager.droppables[ draggable.options.scope ] || []; // Run through all droppables and check their positions based on specific tolerance options $.each( droppables, function() { if ( this.options.disabled || this.greedyChild || !this.visible ) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if ( !c ) { return; } if ( this.options.greedy ) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents( ":data(ui-droppable)" ).filter( function() { return $( this ).droppable( "instance" ).options.scope === scope; } ); if ( parent.length ) { parentInstance = $( parent[ 0 ] ).droppable( "instance" ); parentInstance.enteredGreedyChild = parentInstance.enteredGreedyChild || ( c === "isover" ); parentInstance.leftGreedyChild = parentInstance.leftGreedyChild || ( c === "isout" ); } } this[ c ] = true; this[ c === "isout" ? "isover" : "isout" ] = false; this.c = c; } ); $.each( droppables, function() { if ( this.enteredGreedyChild ) { this.greedyChild = true this.isover = false this.isout = true this.c = "isout" } // Only move into the parent if we haven't moved into another greedy child if ( this.leftGreedyChild && !this.enteredGreedyChild ) { this.greedyChild = false this.isover = true this.isout = false this.c = "isover" } if ( !this.c ) { return; } this[this.c === "isover" ? "_over" : "_out"].call( this, event ); this.leftGreedyChild = false; this.enteredGreedyChild = false; this.c = null; } ); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; var droppable = $.ui.droppable; /** * @preserve * jquery.layout 1.3.0 - Release Candidate 30.79 * $Date: 2013-01-12 08:00:00 (Sat, 12 Jan 2013) $ * $Rev: 303007 $ * * Copyright (c) 2013 Kevin Dalman (http://allpro.net) * Based on work by Fabrizio Balliano (http://www.fabrizioballiano.net) * * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. * * SEE: http://layout.jquery-dev.net/LICENSE.txt * * Changelog: http://layout.jquery-dev.net/changelog.cfm#1.3.0.rc30.79 * * Docs: http://layout.jquery-dev.net/documentation.html * Tips: http://layout.jquery-dev.net/tips.html * Help: http://groups.google.com/group/jquery-ui-layout */ /* JavaDoc Info: http://code.google.com/closure/compiler/docs/js-for-compiler.html * {!Object} non-nullable type (never NULL) * {?string} nullable type (sometimes NULL) - default for {Object} * {number=} optional parameter * {*} ALL types */ /* TODO for jQ 2.0 * change .andSelf() to .addBack() * $.fn.disableSelection won't work */ // NOTE: For best readability, view with a fixed-width font and tabs equal to 4-chars ;(function ($) { // alias Math methods - used a lot! var min = Math.min , max = Math.max , round = Math.floor , isStr = function (v) { return $.type(v) === "string"; } /** * @param {!Object} Instance * @param {Array.<string>} a_fn */ , runPluginCallbacks = function (Instance, a_fn) { if ($.isArray(a_fn)) for (var i=0, c=a_fn.length; i<c; i++) { var fn = a_fn[i]; try { if (isStr(fn)) // 'name' of a function fn = eval(fn); if ($.isFunction(fn)) g(fn)( Instance ); } catch (ex) {} } function g (f) { return f; }; // compiler hack } ; /* * GENERIC $.layout METHODS - used by all layouts */ $.layout = { version: "1.3.rc30.79" , revision: 0.033007 // 1.3.0 final = 1.0300 - major(n+).minor(nn)+patch(nn+) // $.layout.browser REPLACES $.browser , browser: {} // set below // *PREDEFINED* EFFECTS & DEFAULTS // MUST list effect here - OR MUST set an fxSettings option (can be an empty hash: {}) , effects: { // Pane Open/Close Animations slide: { all: { duration: "fast" } // eg: duration: 1000, easing: "easeOutBounce" , north: { direction: "up" } , south: { direction: "down" } , east: { direction: "right"} , west: { direction: "left" } } , drop: { all: { duration: "slow" } , north: { direction: "up" } , south: { direction: "down" } , east: { direction: "right"} , west: { direction: "left" } } , scale: { all: { duration: "fast" } } // these are not recommended, but can be used , blind: {} , clip: {} , explode: {} , fade: {} , fold: {} , puff: {} // Pane Resize Animations , size: { all: { easing: "swing" } } } // INTERNAL CONFIG DATA - DO NOT CHANGE THIS! , config: { optionRootKeys: "effects,panes,north,south,west,east,center".split(",") , allPanes: "north,south,west,east,center".split(",") , borderPanes: "north,south,west,east".split(",") , oppositeEdge: { north: "south" , south: "north" , east: "west" , west: "east" } // offscreen data , offscreenCSS: { left: "-99999px", right: "auto" } // used by hide/close if useOffscreenClose=true , offscreenReset: "offscreenReset" // key used for data // CSS used in multiple places , hidden: { visibility: "hidden" } , visible: { visibility: "visible" } // layout element settings , resizers: { cssReq: { position: "absolute" , padding: 0 , margin: 0 , fontSize: "1px" , textAlign: "left" // to counter-act "center" alignment! , overflow: "hidden" // prevent toggler-button from overflowing // SEE $.layout.defaults.zIndexes.resizer_normal } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true background: "#DDD" , border: "none" } } , togglers: { cssReq: { position: "absolute" , display: "block" , padding: 0 , margin: 0 , overflow: "hidden" , textAlign: "center" , fontSize: "1px" , cursor: "pointer" , zIndex: 1 } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true background: "#AAA" } } , content: { cssReq: { position: "relative" /* contain floated or positioned elements */ } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true overflow: "auto" , padding: "10px" } , cssDemoPane: { // DEMO CSS - REMOVE scrolling from 'pane' when it has a content-div overflow: "hidden" , padding: 0 } } , panes: { // defaults for ALL panes - overridden by 'per-pane settings' below cssReq: { position: "absolute" , margin: 0 // $.layout.defaults.zIndexes.pane_normal } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true padding: "10px" , background: "#FFF" , border: "1px solid #BBB" , overflow: "auto" } } , north: { side: "top" , sizeType: "Height" , dir: "horz" , cssReq: { top: 0 , bottom: "auto" , left: 0 , right: 0 , width: "auto" // height: DYNAMIC } } , south: { side: "bottom" , sizeType: "Height" , dir: "horz" , cssReq: { top: "auto" , bottom: 0 , left: 0 , right: 0 , width: "auto" // height: DYNAMIC } } , east: { side: "right" , sizeType: "Width" , dir: "vert" , cssReq: { left: "auto" , right: 0 , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" // width: DYNAMIC } } , west: { side: "left" , sizeType: "Width" , dir: "vert" , cssReq: { left: 0 , right: "auto" , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" // width: DYNAMIC } } , center: { dir: "center" , cssReq: { left: "auto" // DYNAMIC , right: "auto" // DYNAMIC , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" , width: "auto" } } } // CALLBACK FUNCTION NAMESPACE - used to store reusable callback functions , callbacks: {} , getParentPaneElem: function (el) { // must pass either a container or pane element var $el = $(el) , layout = $el.data("layout") || $el.data("parentLayout"); if (layout) { var $cont = layout.container; // see if this container is directly-nested inside an outer-pane if ($cont.data("layoutPane")) return $cont; var $pane = $cont.closest("."+ $.layout.defaults.panes.paneClass); // if a pane was found, return it if ($pane.data("layoutPane")) return $pane; } return null; } , getParentPaneInstance: function (el) { // must pass either a container or pane element var $pane = $.layout.getParentPaneElem(el); return $pane ? $pane.data("layoutPane") : null; } , getParentLayoutInstance: function (el) { // must pass either a container or pane element var $pane = $.layout.getParentPaneElem(el); return $pane ? $pane.data("parentLayout") : null; } , getEventObject: function (evt) { return typeof evt === "object" && evt.stopPropagation ? evt : null; } , parsePaneName: function (evt_or_pane) { var evt = $.layout.getEventObject( evt_or_pane ) , pane = evt_or_pane; if (evt) { // ALWAYS stop propagation of events triggered in Layout! evt.stopPropagation(); pane = $(this).data("layoutEdge"); } if (pane && !/^(west|east|north|south|center)$/.test(pane)) { $.layout.msg('LAYOUT ERROR - Invalid pane-name: "'+ pane +'"'); pane = "error"; } return pane; } // LAYOUT-PLUGIN REGISTRATION // more plugins can added beyond this default list , plugins: { draggable: !!$.fn.draggable // resizing , effects: { core: !!$.effects // animimations (specific effects tested by initOptions) , slide: $.effects && ($.effects.slide || ($.effects.effect && $.effects.effect.slide)) // default effect } } // arrays of plugin or other methods to be triggered for events in *each layout* - will be passed 'Instance' , onCreate: [] // runs when layout is just starting to be created - right after options are set , onLoad: [] // runs after layout container and global events init, but before initPanes is called , onReady: [] // runs after initialization *completes* - ie, after initPanes completes successfully , onDestroy: [] // runs after layout is destroyed , onUnload: [] // runs after layout is destroyed OR when page unloads , afterOpen: [] // runs after setAsOpen() completes , afterClose: [] // runs after setAsClosed() completes /* * GENERIC UTILITY METHODS */ // calculate and return the scrollbar width, as an integer , scrollbarWidth: function () { return window.scrollbarWidth || $.layout.getScrollbarSize('width'); } , scrollbarHeight: function () { return window.scrollbarHeight || $.layout.getScrollbarSize('height'); } , getScrollbarSize: function (dim) { var $c = $('<div style="position: absolute; top: -10000px; left: -10000px; width: 100px; height: 100px; overflow: scroll;"></div>').appendTo("body"); var d = { width: $c.css("width") - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight }; $c.remove(); window.scrollbarWidth = d.width; window.scrollbarHeight = d.height; return dim.match(/^(width|height)$/) ? d[dim] : d; } /** * Returns hash container 'display' and 'visibility' * * @see $.swap() - swaps CSS, runs callback, resets CSS * @param {!Object} $E jQuery element * @param {boolean=} [force=false] Run even if display != none * @return {!Object} Returns current style props, if applicable */ , showInvisibly: function ($E, force) { if ($E && $E.length && (force || $E.css("display") === "none")) { // only if not *already hidden* var s = $E[0].style // save ONLY the 'style' props because that is what we must restore , CSS = { display: s.display || '', visibility: s.visibility || '' }; // show element 'invisibly' so can be measured $E.css({ display: "block", visibility: "hidden" }); return CSS; } return {}; } /** * Returns data for setting size of an element (container or a pane). * * @see _create(), onWindowResize() for container, plus others for pane * @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc */ , getElementDimensions: function ($E, inset) { var // dimensions hash - start with current data IF passed d = { css: {}, inset: {} } , x = d.css // CSS hash , i = { bottom: 0 } // TEMP insets (bottom = complier hack) , N = $.layout.cssNum , off = $E.offset() , b, p, ei // TEMP border, padding ; d.offsetLeft = off.left; d.offsetTop = off.top; if (!inset) inset = {}; // simplify logic below $.each("Left,Right,Top,Bottom".split(","), function (idx, e) { // e = edge b = x["border" + e] = $.layout.borderWidth($E, e); p = x["padding"+ e] = $.layout.cssNum($E, "padding"+e); ei = e.toLowerCase(); d.inset[ei] = inset[ei] >= 0 ? inset[ei] : p; // any missing insetX value = paddingX i[ei] = d.inset[ei] + b; // total offset of content from outer side }); x.width = $E.width(); x.height = $E.height(); x.top = N($E,"top",true); x.bottom = N($E,"bottom",true); x.left = N($E,"left",true); x.right = N($E,"right",true); d.outerWidth = $E.outerWidth(); d.outerHeight = $E.outerHeight(); // calc the TRUE inner-dimensions, even in quirks-mode! d.innerWidth = max(0, d.outerWidth - i.left - i.right); d.innerHeight = max(0, d.outerHeight - i.top - i.bottom); // layoutWidth/Height is used in calcs for manual resizing // layoutW/H only differs from innerW/H when in quirks-mode - then is like outerW/H d.layoutWidth = $E.innerWidth(); d.layoutHeight = $E.innerHeight(); //if ($E.prop('tagName') === 'BODY') { debugData( d, $E.prop('tagName') ); } // DEBUG //d.visible = $E.is(":visible");// && x.width > 0 && x.height > 0; return d; } , getElementStyles: function ($E, list) { var CSS = {} , style = $E[0].style , props = list.split(",") , sides = "Top,Bottom,Left,Right".split(",") , attrs = "Color,Style,Width".split(",") , p, s, a, i, j, k ; for (i=0; i < props.length; i++) { p = props[i]; if (p.match(/(border|padding|margin)$/)) for (j=0; j < 4; j++) { s = sides[j]; if (p === "border") for (k=0; k < 3; k++) { a = attrs[k]; CSS[p+s+a] = style[p+s+a]; } else CSS[p+s] = style[p+s]; } else CSS[p] = style[p]; }; return CSS } /** * Return the innerWidth for the current browser/doctype * * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles() * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {number=} outerWidth (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerWidth of the elem by subtracting padding and borders */ , cssWidth: function ($E, outerWidth) { // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerWidth <= 0) return 0; var bs = !$.layout.browser.boxModel ? "border-box" : $.support.boxSizing ? $E.css("boxSizing") : "content-box" , b = $.layout.borderWidth , n = $.layout.cssNum , W = outerWidth ; // strip border and/or padding from outerWidth to get CSS Width if (bs !== "border-box") W -= (b($E, "Left") + b($E, "Right")); if (bs === "content-box") W -= (n($E, "paddingLeft") + n($E, "paddingRight")); return max(0,W); } /** * Return the innerHeight for the current browser/doctype * * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles() * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {number=} outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerHeight of the elem by subtracting padding and borders */ , cssHeight: function ($E, outerHeight) { // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerHeight <= 0) return 0; var bs = !$.layout.browser.boxModel ? "border-box" : $.support.boxSizing ? $E.css("boxSizing") : "content-box" , b = $.layout.borderWidth , n = $.layout.cssNum , H = outerHeight ; // strip border and/or padding from outerHeight to get CSS Height if (bs !== "border-box") H -= (b($E, "Top") + b($E, "Bottom")); if (bs === "content-box") H -= (n($E, "paddingTop") + n($E, "paddingBottom")); return max(0,H); } /** * Returns the 'current CSS numeric value' for a CSS property - 0 if property does not exist * * @see Called by many methods * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {string} prop The name of the CSS property, eg: top, width, etc. * @param {boolean=} [allowAuto=false] true = return 'auto' if that is value; false = return 0 * @return {(string|number)} Usually used to get an integer value for position (top, left) or size (height, width) */ , cssNum: function ($E, prop, allowAuto) { if (!$E.jquery) $E = $($E); var CSS = $.layout.showInvisibly($E) , p = $.css($E[0], prop, true) , v = allowAuto && p=="auto" ? p : Math.round(parseFloat(p) || 0); $E.css( CSS ); // RESET return v; } , borderWidth: function (el, side) { if (el.jquery) el = el[0]; var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left return $.css(el, b+"Style", true) === "none" ? 0 : Math.round(parseFloat($.css(el, b+"Width", true)) || 0); } /** * Mouse-tracking utility - FUTURE REFERENCE * * init: if (!window.mouse) { * window.mouse = { x: 0, y: 0 }; * $(document).mousemove( $.layout.trackMouse ); * } * * @param {Object} evt * , trackMouse: function (evt) { window.mouse = { x: evt.clientX, y: evt.clientY }; } */ /** * SUBROUTINE for preventPrematureSlideClose option * * @param {Object} evt * @param {Object=} el */ , isMouseOverElem: function (evt, el) { var $E = $(el || this) , d = $E.offset() , T = d.top , L = d.left , R = L + $E.outerWidth() , B = T + $E.outerHeight() , x = evt.pageX // evt.clientX ? , y = evt.pageY // evt.clientY ? ; // if X & Y are < 0, probably means is over an open SELECT return ($.layout.browser.msie && x < 0 && y < 0) || ((x >= L && x <= R) && (y >= T && y <= B)); } /** * Message/Logging Utility * * @example $.layout.msg("My message"); // log text * @example $.layout.msg("My message", true); // alert text * @example $.layout.msg({ foo: "bar" }, "Title"); // log hash-data, with custom title * @example $.layout.msg({ foo: "bar" }, true, "Title", { sort: false }); -OR- * @example $.layout.msg({ foo: "bar" }, "Title", { sort: false, display: true }); // alert hash-data * * @param {(Object|string)} info String message OR Hash/Array * @param {(Boolean|string|Object)=} [popup=false] True means alert-box - can be skipped * @param {(Object|string)=} [debugTitle=""] Title for Hash data - can be skipped * @param {Object=} [debugOpts] Extra options for debug output */ , msg: function (info, popup, debugTitle, debugOpts) { if ($.isPlainObject(info) && window.debugData) { if (typeof popup === "string") { debugOpts = debugTitle; debugTitle = popup; } else if (typeof debugTitle === "object") { debugOpts = debugTitle; debugTitle = null; } var t = debugTitle || "log( <object> )" , o = $.extend({ sort: false, returnHTML: false, display: false }, debugOpts); if (popup === true || o.display) debugData( info, t, o ); else if (window.console) console.log(debugData( info, t, o )); } else if (popup) alert(info); else if (window.console) console.log(info); else { var id = "#layoutLogger" , $l = $(id); if (!$l.length) $l = createLog(); $l.children("ul").append('<li style="padding: 4px 10px; margin: 0; border-top: 1px solid #CCC;">'+ info.replace(/\</g,"&lt;").replace(/\>/g,"&gt;") +'</li>'); } function createLog () { var pos = $.support.fixedPosition ? 'fixed' : 'absolute' , $e = $('<div id="layoutLogger" style="position: '+ pos +'; top: 5px; z-index: 999999; max-width: 25%; overflow: hidden; border: 1px solid #000; border-radius: 5px; background: #FBFBFB; box-shadow: 0 2px 10px rgba(0,0,0,0.3);">' + '<div style="font-size: 13px; font-weight: bold; padding: 5px 10px; background: #F6F6F6; border-radius: 5px 5px 0 0; cursor: move;">' + '<span style="float: right; padding-left: 7px; cursor: pointer;" title="Remove Console" onclick="$(this).closest(\'#layoutLogger\').remove()">X</span>Layout console.log</div>' + '<ul style="font-size: 13px; font-weight: none; list-style: none; margin: 0; padding: 0 0 2px;"></ul>' + '</div>' ).appendTo("body"); $e.css('left', $(window).width() - $e.outerWidth() - 5) if ($.ui.draggable) $e.draggable({ handle: ':first-child' }); return $e; }; } }; /* * $.layout.browser REPLACES removed $.browser, with extra data * Parsing code here adapted from jQuery 1.8 $.browse */ var u = navigator.userAgent.toLowerCase() , m = /(chrome)[ \/]([\w.]+)/.exec( u ) || /(webkit)[ \/]([\w.]+)/.exec( u ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( u ) || /(msie) ([\w.]+)/.exec( u ) || u.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( u ) || [] , b = m[1] || "" , v = m[2] || 0 , ie = b === "msie" ; $.layout.browser = { version: v , safari: b === "webkit" // webkit (NOT chrome) = safari , webkit: b === "chrome" // chrome = webkit , msie: ie , isIE6: ie && v == 6 // ONLY IE reverts to old box-model - update for older jQ onReady , boxModel: !ie || $.support.boxModel !== false }; if (b) $.layout.browser[b] = true; // set CURRENT browser /* OLD versions of jQuery only set $.support.boxModel after page is loaded * so if this is IE, use support.boxModel to test for quirks-mode (ONLY IE changes boxModel) */ if (ie) $(function(){ $.layout.browser.boxModel = $.support.boxModel; }); // DEFAULT OPTIONS $.layout.defaults = { /* * LAYOUT & LAYOUT-CONTAINER OPTIONS * - none of these options are applicable to individual panes */ name: "" // Not required, but useful for buttons and used for the state-cookie , containerClass: "ui-layout-container" // layout-container element , inset: null // custom container-inset values (override padding) , scrollToBookmarkOnLoad: true // after creating a layout, scroll to bookmark in URL (.../page.htm#myBookmark) , resizeWithWindow: true // bind thisLayout.resizeAll() to the window.resize event , resizeWithWindowDelay: 200 // delay calling resizeAll because makes window resizing very jerky , resizeWithWindowMaxDelay: 0 // 0 = none - force resize every XX ms while window is being resized , maskPanesEarly: false // true = create pane-masks on resizer.mouseDown instead of waiting for resizer.dragstart , onresizeall_start: null // CALLBACK when resizeAll() STARTS - NOT pane-specific , onresizeall_end: null // CALLBACK when resizeAll() ENDS - NOT pane-specific , onload_start: null // CALLBACK when Layout inits - after options initialized, but before elements , onload_end: null // CALLBACK when Layout inits - after EVERYTHING has been initialized , onunload_start: null // CALLBACK when Layout is destroyed OR onWindowUnload , onunload_end: null // CALLBACK when Layout is destroyed OR onWindowUnload , initPanes: true // false = DO NOT initialize the panes onLoad - will init later , showErrorMessages: true // enables fatal error messages to warn developers of common errors , showDebugMessages: false // display console-and-alert debug msgs - IF this Layout version _has_ debugging code! // Changing this zIndex value will cause other zIndex values to automatically change , zIndex: null // the PANE zIndex - resizers and masks will be +1 // DO NOT CHANGE the zIndex values below unless you clearly understand their relationships , zIndexes: { // set _default_ z-index values here... pane_normal: 0 // normal z-index for panes , content_mask: 1 // applied to overlays used to mask content INSIDE panes during resizing , resizer_normal: 2 // normal z-index for resizer-bars , pane_sliding: 100 // applied to *BOTH* the pane and its resizer when a pane is 'slid open' , pane_animate: 1000 // applied to the pane when being animated - not applied to the resizer , resizer_drag: 10000 // applied to the CLONED resizer-bar when being 'dragged' } , errors: { pane: "pane" // description of "layout pane element" - used only in error messages , selector: "selector" // description of "jQuery-selector" - used only in error messages , addButtonError: "Error Adding Button\nInvalid " , containerMissing: "UI Layout Initialization Error\nThe specified layout-container does not exist." , centerPaneMissing: "UI Layout Initialization Error\nThe center-pane element does not exist.\nThe center-pane is a required element." , noContainerHeight: "UI Layout Initialization Warning\nThe layout-container \"CONTAINER\" has no height.\nTherefore the layout is 0-height and hence 'invisible'!" , callbackError: "UI Layout Callback Error\nThe EVENT callback is not a valid function." } /* * PANE DEFAULT SETTINGS * - settings under the 'panes' key become the default settings for *all panes* * - ALL pane-options can also be set specifically for each panes, which will override these 'default values' */ , panes: { // default options for 'all panes' - will be overridden by 'per-pane settings' applyDemoStyles: false // NOTE: renamed from applyDefaultStyles for clarity , closable: true // pane can open & close , resizable: true // when open, pane can be resized , slidable: true // when closed, pane can 'slide open' over other panes - closes on mouse-out , initClosed: false // true = init pane as 'closed' , initHidden: false // true = init pane as 'hidden' - no resizer-bar/spacing // SELECTORS //, paneSelector: "" // MUST be pane-specific - jQuery selector for pane , contentSelector: ".ui-layout-content" // INNER div/element to auto-size so only it scrolls, not the entire pane! , contentIgnoreSelector: ".ui-layout-ignore" // element(s) to 'ignore' when measuring 'content' , findNestedContent: false // true = $P.find(contentSelector), false = $P.children(contentSelector) // GENERIC ROOT-CLASSES - for auto-generated classNames , paneClass: "ui-layout-pane" // Layout Pane , resizerClass: "ui-layout-resizer" // Resizer Bar , togglerClass: "ui-layout-toggler" // Toggler Button , buttonClass: "ui-layout-button" // CUSTOM Buttons - eg: '[ui-layout-button]-toggle/-open/-close/-pin' // ELEMENT SIZE & SPACING //, size: 100 // MUST be pane-specific -initial size of pane , minSize: 0 // when manually resizing a pane , maxSize: 0 // ditto, 0 = no limit , spacing_open: 6 // space between pane and adjacent panes - when pane is 'open' , spacing_closed: 6 // ditto - when pane is 'closed' , togglerLength_open: 50 // Length = WIDTH of toggler button on north/south sides - HEIGHT on east/west sides , togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden' , togglerAlign_open: "center" // top/left, bottom/right, center, OR... , togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right , togglerContent_open: "" // text or HTML to put INSIDE the toggler , togglerContent_closed: "" // ditto // RESIZING OPTIONS , resizerDblClickToggle: true // , autoResize: true // IF size is 'auto' or a percentage, then recalc 'pixel size' whenever the layout resizes , autoReopen: true // IF a pane was auto-closed due to noRoom, reopen it when there is room? False = leave it closed , resizerDragOpacity: 1 // option for ui.draggable //, resizerCursor: "" // MUST be pane-specific - cursor when over resizer-bar , maskContents: false // true = add DIV-mask over-or-inside this pane so can 'drag' over IFRAMES , maskObjects: false // true = add IFRAME-mask over-or-inside this pane to cover objects/applets - content-mask will overlay this mask , maskZindex: null // will override zIndexes.content_mask if specified - not applicable to iframe-panes , resizingGrid: false // grid size that the resizers will snap-to during resizing, eg: [20,20] , livePaneResizing: false // true = LIVE Resizing as resizer is dragged , liveContentResizing: false // true = re-measure header/footer heights as resizer is dragged , liveResizingTolerance: 1 // how many px change before pane resizes, to control performance // SLIDING OPTIONS , sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding' , slideTrigger_open: "click" // click, dblclick, mouseenter , slideTrigger_close: "mouseleave"// click, mouseleave , slideDelay_open: 300 // applies only for mouseenter event - 0 = instant open , slideDelay_close: 300 // applies only for mouseleave event (300ms is the minimum!) , hideTogglerOnSlide: false // when pane is slid-open, should the toggler show? , preventQuickSlideClose: $.layout.browser.webkit // Chrome triggers slideClosed as it is opening , preventPrematureSlideClose: false // handle incorrect mouseleave trigger, like when over a SELECT-list in IE // PANE-SPECIFIC TIPS & MESSAGES , tips: { Open: "Open" // eg: "Open Pane" , Close: "Close" , Resize: "Resize" , Slide: "Slide Open" , Pin: "Pin" , Unpin: "Un-Pin" , noRoomToOpen: "Not enough room to show this panel." // alert if user tries to open a pane that cannot , minSizeWarning: "Panel has reached its minimum size" // displays in browser statusbar , maxSizeWarning: "Panel has reached its maximum size" // ditto } // HOT-KEYS & MISC , showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver , enableCursorHotkey: true // enabled 'cursor' hotkeys //, customHotkey: "" // MUST be pane-specific - EITHER a charCode OR a character , customHotkeyModifier: "SHIFT" // either 'SHIFT', 'CTRL' or 'CTRL+SHIFT' - NOT 'ALT' // PANE ANIMATION // NOTE: fxSss_open, fxSss_close & fxSss_size options (eg: fxName_open) are auto-generated if not passed , fxName: "slide" // ('none' or blank), slide, drop, scale -- only relevant to 'open' & 'close', NOT 'size' , fxSpeed: null // slow, normal, fast, 200, nnn - if passed, will OVERRIDE fxSettings.duration , fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 } , fxOpacityFix: true // tries to fix opacity in IE to restore anti-aliasing after animation , animatePaneSizing: false // true = animate resizing after dragging resizer-bar OR sizePane() is called /* NOTE: Action-specific FX options are auto-generated from the options above if not specifically set: fxName_open: "slide" // 'Open' pane animation fnName_close: "slide" // 'Close' pane animation fxName_size: "slide" // 'Size' pane animation - when animatePaneSizing = true fxSpeed_open: null fxSpeed_close: null fxSpeed_size: null fxSettings_open: {} fxSettings_close: {} fxSettings_size: {} */ // CHILD/NESTED LAYOUTS , children: null // Layout-options for nested/child layout - even {} is valid as options , containerSelector: '' // if child is NOT 'directly nested', a selector to find it/them (can have more than one child layout!) , initChildren: true // true = child layout will be created as soon as _this_ layout completes initialization , destroyChildren: true // true = destroy child-layout if this pane is destroyed , resizeChildren: true // true = trigger child-layout.resizeAll() when this pane is resized // EVENT TRIGGERING , triggerEventsOnLoad: false // true = trigger onopen OR onclose callbacks when layout initializes , triggerEventsDuringLiveResize: true // true = trigger onresize callback REPEATEDLY if livePaneResizing==true // PANE CALLBACKS , onshow_start: null // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start , onshow_end: null // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end , onhide_start: null // CALLBACK when pane STARTS to Close - BEFORE onclose_start , onhide_end: null // CALLBACK when pane ENDS being Closed - AFTER onclose_end , onopen_start: null // CALLBACK when pane STARTS to Open , onopen_end: null // CALLBACK when pane ENDS being Opened , onclose_start: null // CALLBACK when pane STARTS to Close , onclose_end: null // CALLBACK when pane ENDS being Closed , onresize_start: null // CALLBACK when pane STARTS being Resized ***FOR ANY REASON*** , onresize_end: null // CALLBACK when pane ENDS being Resized ***FOR ANY REASON*** , onsizecontent_start: null // CALLBACK when sizing of content-element STARTS , onsizecontent_end: null // CALLBACK when sizing of content-element ENDS , onswap_start: null // CALLBACK when pane STARTS to Swap , onswap_end: null // CALLBACK when pane ENDS being Swapped , ondrag_start: null // CALLBACK when pane STARTS being ***MANUALLY*** Resized , ondrag_end: null // CALLBACK when pane ENDS being ***MANUALLY*** Resized } /* * PANE-SPECIFIC SETTINGS * - options listed below MUST be specified per-pane - they CANNOT be set under 'panes' * - all options under the 'panes' key can also be set specifically for any pane * - most options under the 'panes' key apply only to 'border-panes' - NOT the the center-pane */ , north: { paneSelector: ".ui-layout-north" , size: "auto" // eg: "auto", "30%", .30, 200 , resizerCursor: "n-resize" // custom = url(myCursor.cur) , customHotkey: "" // EITHER a charCode (43) OR a character ("o") } , south: { paneSelector: ".ui-layout-south" , size: "auto" , resizerCursor: "s-resize" , customHotkey: "" } , east: { paneSelector: ".ui-layout-east" , size: 200 , resizerCursor: "e-resize" , customHotkey: "" } , west: { paneSelector: ".ui-layout-west" , size: 200 , resizerCursor: "w-resize" , customHotkey: "" } , center: { paneSelector: ".ui-layout-center" , minWidth: 0 , minHeight: 0 } }; $.layout.optionsMap = { // layout/global options - NOT pane-options layout: ("name,instanceKey,stateManagement,effects,inset,zIndexes,errors," + "zIndex,scrollToBookmarkOnLoad,showErrorMessages,maskPanesEarly," + "outset,resizeWithWindow,resizeWithWindowDelay,resizeWithWindowMaxDelay," + "onresizeall,onresizeall_start,onresizeall_end,onload,onload_start,onload_end,onunload,onunload_start,onunload_end").split(",") // borderPanes: [ ALL options that are NOT specified as 'layout' ] // default.panes options that apply to the center-pane (most options apply _only_ to border-panes) , center: ("paneClass,contentSelector,contentIgnoreSelector,findNestedContent,applyDemoStyles,triggerEventsOnLoad," + "showOverflowOnHover,maskContents,maskObjects,liveContentResizing," + "containerSelector,children,initChildren,resizeChildren,destroyChildren," + "onresize,onresize_start,onresize_end,onsizecontent,onsizecontent_start,onsizecontent_end").split(",") // options that MUST be specifically set 'per-pane' - CANNOT set in the panes (defaults) key , noDefault: ("paneSelector,resizerCursor,customHotkey").split(",") }; /** * Processes options passed in converts flat-format data into subkey (JSON) format * In flat-format, subkeys are _currently_ separated with 2 underscores, like north__optName * Plugins may also call this method so they can transform their own data * * @param {!Object} hash Data/options passed by user - may be a single level or nested levels * @param {boolean=} [addKeys=false] Should the primary layout.options keys be added if they do not exist? * @return {Object} Returns hash of minWidth & minHeight */ $.layout.transformData = function (hash, addKeys) { var json = addKeys ? { panes: {}, center: {} } : {} // init return object , branch, optKey, keys, key, val, i, c; if (typeof hash !== "object") return json; // no options passed // convert all 'flat-keys' to 'sub-key' format for (optKey in hash) { branch = json; val = hash[ optKey ]; keys = optKey.split("__"); // eg: west__size or north__fxSettings__duration c = keys.length - 1; // convert underscore-delimited to subkeys for (i=0; i <= c; i++) { key = keys[i]; if (i === c) { // last key = value if ($.isPlainObject( val )) branch[key] = $.layout.transformData( val ); // RECURSE else branch[key] = val; } else { if (!branch[key]) branch[key] = {}; // create the subkey // recurse to sub-key for next loop - if not done branch = branch[key]; } } } return json; }; // INTERNAL CONFIG DATA - DO NOT CHANGE THIS! $.layout.backwardCompatibility = { // data used by renameOldOptions() map: { // OLD Option Name: NEW Option Name applyDefaultStyles: "applyDemoStyles" // CHILD/NESTED LAYOUTS , childOptions: "children" , initChildLayout: "initChildren" , destroyChildLayout: "destroyChildren" , resizeChildLayout: "resizeChildren" , resizeNestedLayout: "resizeChildren" // MISC Options , resizeWhileDragging: "livePaneResizing" , resizeContentWhileDragging: "liveContentResizing" , triggerEventsWhileDragging: "triggerEventsDuringLiveResize" , maskIframesOnResize: "maskContents" // STATE MANAGEMENT , useStateCookie: "stateManagement.enabled" , "cookie.autoLoad": "stateManagement.autoLoad" , "cookie.autoSave": "stateManagement.autoSave" , "cookie.keys": "stateManagement.stateKeys" , "cookie.name": "stateManagement.cookie.name" , "cookie.domain": "stateManagement.cookie.domain" , "cookie.path": "stateManagement.cookie.path" , "cookie.expires": "stateManagement.cookie.expires" , "cookie.secure": "stateManagement.cookie.secure" // OLD Language options , noRoomToOpenTip: "tips.noRoomToOpen" , togglerTip_open: "tips.Close" // open = Close , togglerTip_closed: "tips.Open" // closed = Open , resizerTip: "tips.Resize" , sliderTip: "tips.Slide" } /** * @param {Object} opts */ , renameOptions: function (opts) { var map = $.layout.backwardCompatibility.map , oldData, newData, value ; for (var itemPath in map) { oldData = getBranch( itemPath ); value = oldData.branch[ oldData.key ]; if (value !== undefined) { newData = getBranch( map[itemPath], true ); newData.branch[ newData.key ] = value; delete oldData.branch[ oldData.key ]; } } /** * @param {string} path * @param {boolean=} [create=false] Create path if does not exist */ function getBranch (path, create) { var a = path.split(".") // split keys into array , c = a.length - 1 , D = { branch: opts, key: a[c] } // init branch at top & set key (last item) , i = 0, k, undef; for (; i<c; i++) { // skip the last key (data) k = a[i]; if (D.branch[ k ] == undefined) { // child-key does not exist if (create) { D.branch = D.branch[ k ] = {}; // create child-branch } else // can't go any farther D.branch = {}; // branch is undefined } else D.branch = D.branch[ k ]; // get child-branch } return D; }; } /** * @param {Object} opts */ , renameAllOptions: function (opts) { var ren = $.layout.backwardCompatibility.renameOptions; // rename root (layout) options ren( opts ); // rename 'defaults' to 'panes' if (opts.defaults) { if (typeof opts.panes !== "object") opts.panes = {}; $.extend(true, opts.panes, opts.defaults); delete opts.defaults; } // rename options in the the options.panes key if (opts.panes) ren( opts.panes ); // rename options inside *each pane key*, eg: options.west $.each($.layout.config.allPanes, function (i, pane) { if (opts[pane]) ren( opts[pane] ); }); return opts; } }; /* ============================================================ * BEGIN WIDGET: $( selector ).layout( {options} ); * ============================================================ */ $.fn.layout = function (opts) { var // local aliases to global data browser = $.layout.browser , _c = $.layout.config // local aliases to utlity methods , cssW = $.layout.cssWidth , cssH = $.layout.cssHeight , elDims = $.layout.getElementDimensions , styles = $.layout.getElementStyles , evtObj = $.layout.getEventObject , evtPane = $.layout.parsePaneName /** * options - populated by initOptions() */ , options = $.extend(true, {}, $.layout.defaults) , effects = options.effects = $.extend(true, {}, $.layout.effects) /** * layout-state object */ , state = { // generate unique ID to use for event.namespace so can unbind only events added by 'this layout' id: "layout"+ $.now() // code uses alias: sID , initialized: false , paneResizing: false , panesSliding: {} , container: { // list all keys referenced in code to avoid compiler error msgs innerWidth: 0 , innerHeight: 0 , outerWidth: 0 , outerHeight: 0 , layoutWidth: 0 , layoutHeight: 0 } , north: { childIdx: 0 } , south: { childIdx: 0 } , east: { childIdx: 0 } , west: { childIdx: 0 } , center: { childIdx: 0 } } /** * parent/child-layout pointers */ //, hasParentLayout = false - exists ONLY inside Instance so can be set externally , children = { north: null , south: null , east: null , west: null , center: null } /* * ########################### * INTERNAL HELPER FUNCTIONS * ########################### */ /** * Manages all internal timers */ , timer = { data: {} , set: function (s, fn, ms) { timer.clear(s); timer.data[s] = setTimeout(fn, ms); } , clear: function (s) { var t=timer.data; if (t[s]) {clearTimeout(t[s]); delete t[s];} } } /** * Alert or console.log a message - IF option is enabled. * * @param {(string|!Object)} msg Message (or debug-data) to display * @param {boolean=} [popup=false] True by default, means 'alert', false means use console.log * @param {boolean=} [debug=false] True means is a widget debugging message */ , _log = function (msg, popup, debug) { var o = options; if ((o.showErrorMessages && !debug) || (debug && o.showDebugMessages)) $.layout.msg( o.name +' / '+ msg, (popup !== false) ); return false; } /** * Executes a Callback function after a trigger event, like resize, open or close * * @param {string} evtName Name of the layout callback, eg "onresize_start" * @param {(string|boolean)=} [pane=""] This is passed only so we can pass the 'pane object' to the callback * @param {(string|boolean)=} [skipBoundEvents=false] True = do not run events bound to the elements - only the callbacks set in options */ , _runCallbacks = function (evtName, pane, skipBoundEvents) { var hasPane = pane && isStr(pane) , s = hasPane ? state[pane] : state , o = hasPane ? options[pane] : options , lName = options.name // names like onopen and onopen_end separate are interchangeable in options... , lng = evtName + (evtName.match(/_/) ? "" : "_end") , shrt = lng.match(/_end$/) ? lng.substr(0, lng.length - 4) : "" , fn = o[lng] || o[shrt] , retVal = "NC" // NC = No Callback , args = [] , $P ; if ( !hasPane && $.type(pane) === 'boolean' ) { skipBoundEvents = pane; // allow pane param to be skipped for Layout callback pane = ""; } // first trigger the callback set in the options if (fn) { // convert function name (string) to function object if (isStr( fn )) { if (fn.match(/,/)) { // function name cannot contain a comma, // so must be a function name AND a parameter to pass args = fn.split(",") , fn = eval(args[0]); } else // just the name of an external function? fn = eval(fn); } // execute the callback, if exists if ($.isFunction( fn )) { if (args.length) retVal = g(fn)(args[1]); // pass the argument parsed from 'list' else if ( hasPane ) // pass data: pane-name, pane-element, pane-state, pane-options, and layout-name retVal = g(fn)( pane, $Ps[pane], s, o, lName ); else // must be a layout/container callback - pass suitable info retVal = g(fn)( Instance, s, o, lName ); } // _log( options.errors.callbackError.replace(/EVENT/, $.trim((pane || "") +" "+ lng)), false ); // if ($.type(ex) === 'string' && string.length) // _log('Exception: '+ ex, false ); } // trigger additional events bound directly to the pane if (!skipBoundEvents && retVal !== false) { if ( hasPane ) { // PANE events can be bound to each pane-elements $P = $Ps[pane]; o = options[pane]; s = state[pane]; $P.triggerHandler('layoutpane'+ lng, [ pane, $P, s, o, lName ]); if (shrt) $P.triggerHandler('layoutpane'+ shrt, [ pane, $P, s, o, lName ]); } else { // LAYOUT events can be bound to the container-element $N.triggerHandler('layout'+ lng, [ Instance, s, o, lName ]); if (shrt) $N.triggerHandler('layout'+ shrt, [ Instance, s, o, lName ]); } } // ALWAYS resizeChildren after an onresize_end event - even during initialization // IGNORE onsizecontent_end event because causes child-layouts to resize TWICE if (hasPane && evtName === "onresize_end") // BAD: || evtName === "onsizecontent_end" resizeChildren(pane+"", true); // compiler hack -force string return retVal; function g (f) { return f; }; // compiler hack } /** * cure iframe display issues in IE & other browsers */ , _fixIframe = function (pane) { if (browser.mozilla) return; // skip FireFox - it auto-refreshes iframes onShow var $P = $Ps[pane]; // if the 'pane' is an iframe, do it if (state[pane].tagName === "IFRAME") $P.css(_c.hidden).css(_c.visible); else // ditto for any iframes INSIDE the pane $P.find('IFRAME').css(_c.hidden).css(_c.visible); } /** * @param {string} pane Can accept ONLY a 'pane' (east, west, etc) * @param {number=} outerSize (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerHeight/Width of el by subtracting padding and borders */ , cssSize = function (pane, outerSize) { var fn = _c[pane].dir=="horz" ? cssH : cssW; return fn($Ps[pane], outerSize); } /** * @param {string} pane Can accept ONLY a 'pane' (east, west, etc) * @return {Object} Returns hash of minWidth & minHeight */ , cssMinDims = function (pane) { // minWidth/Height means CSS width/height = 1px var $P = $Ps[pane] , dir = _c[pane].dir , d = { minWidth: 1001 - cssW($P, 1000) , minHeight: 1001 - cssH($P, 1000) } ; if (dir === "horz") d.minSize = d.minHeight; if (dir === "vert") d.minSize = d.minWidth; return d; } // TODO: see if these methods can be made more useful... // TODO: *maybe* return cssW/H from these so caller can use this info /** * @param {(string|!Object)} el * @param {number=} outerWidth * @param {boolean=} [autoHide=false] */ , setOuterWidth = function (el, outerWidth, autoHide) { var $E = el, w; if (isStr(el)) $E = $Ps[el]; // west else if (!el.jquery) $E = $(el); w = cssW($E, outerWidth); $E.css({ width: w }); if (w > 0) { if (autoHide && $E.data('autoHidden') && $E.innerHeight() > 0) { $E.show().data('autoHidden', false); if (!browser.mozilla) // FireFox refreshes iframes - IE does not // make hidden, then visible to 'refresh' display after animation $E.css(_c.hidden).css(_c.visible); } } else if (autoHide && !$E.data('autoHidden')) $E.hide().data('autoHidden', true); } /** * @param {(string|!Object)} el * @param {number=} outerHeight * @param {boolean=} [autoHide=false] */ , setOuterHeight = function (el, outerHeight, autoHide) { var $E = el, h; if (isStr(el)) $E = $Ps[el]; // west else if (!el.jquery) $E = $(el); h = cssH($E, outerHeight); $E.css({ height: h, visibility: "visible" }); // may have been 'hidden' by sizeContent if (h > 0 && $E.innerWidth() > 0) { if (autoHide && $E.data('autoHidden')) { $E.show().data('autoHidden', false); if (!browser.mozilla) // FireFox refreshes iframes - IE does not $E.css(_c.hidden).css(_c.visible); } } else if (autoHide && !$E.data('autoHidden')) $E.hide().data('autoHidden', true); } /** * Converts any 'size' params to a pixel/integer size, if not already * If 'auto' or a decimal/percentage is passed as 'size', a pixel-size is calculated * /** * @param {string} pane * @param {(string|number)=} size * @param {string=} [dir] * @return {number} */ , _parseSize = function (pane, size, dir) { if (!dir) dir = _c[pane].dir; if (isStr(size) && size.match(/%/)) size = (size === '100%') ? -1 : parseInt(size, 10) / 100; // convert % to decimal if (size === 0) return 0; else if (size >= 1) return parseInt(size, 10); var o = options, avail = 0; if (dir=="horz") // north or south or center.minHeight avail = sC.innerHeight - ($Ps.north ? o.north.spacing_open : 0) - ($Ps.south ? o.south.spacing_open : 0); else if (dir=="vert") // east or west or center.minWidth avail = sC.innerWidth - ($Ps.west ? o.west.spacing_open : 0) - ($Ps.east ? o.east.spacing_open : 0); if (size === -1) // -1 == 100% return avail; else if (size > 0) // percentage, eg: .25 return round(avail * size); else if (pane=="center") return 0; else { // size < 0 || size=='auto' || size==Missing || size==Invalid // auto-size the pane var dim = (dir === "horz" ? "height" : "width") , $P = $Ps[pane] , $C = dim === 'height' ? $Cs[pane] : false , vis = $.layout.showInvisibly($P) // show pane invisibly if hidden , szP = $P.css(dim) // SAVE current pane size , szC = $C ? $C.css(dim) : 0 // SAVE current content size ; $P.css(dim, "auto"); if ($C) $C.css(dim, "auto"); size = (dim === "height") ? $P.outerHeight() : $P.outerWidth(); // MEASURE $P.css(dim, szP).css(vis); // RESET size & visibility if ($C) $C.css(dim, szC); return size; } } /** * Calculates current 'size' (outer-width or outer-height) of a border-pane - optionally with 'pane-spacing' added * * @param {(string|!Object)} pane * @param {boolean=} [inclSpace=false] * @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes */ , getPaneSize = function (pane, inclSpace) { var $P = $Ps[pane] , o = options[pane] , s = state[pane] , oSp = (inclSpace ? o.spacing_open : 0) , cSp = (inclSpace ? o.spacing_closed : 0) ; if (!$P || s.isHidden) return 0; else if (s.isClosed || (s.isSliding && inclSpace)) return cSp; else if (_c[pane].dir === "horz") return $P.outerHeight() + oSp; else // dir === "vert" return $P.outerWidth() + oSp; } /** * Calculate min/max pane dimensions and limits for resizing * * @param {string} pane * @param {boolean=} [slide=false] */ , setSizeLimits = function (pane, slide) { if (!isInitialized()) return; var o = options[pane] , s = state[pane] , c = _c[pane] , dir = c.dir , type = c.sizeType.toLowerCase() , isSliding = (slide != undefined ? slide : s.isSliding) // only open() passes 'slide' param , $P = $Ps[pane] , paneSpacing = o.spacing_open // measure the pane on the *opposite side* from this pane , altPane = _c.oppositeEdge[pane] , altS = state[altPane] , $altP = $Ps[altPane] , altPaneSize = (!$altP || altS.isVisible===false || altS.isSliding ? 0 : (dir=="horz" ? $altP.outerHeight() : $altP.outerWidth())) , altPaneSpacing = ((!$altP || altS.isHidden ? 0 : options[altPane][ altS.isClosed !== false ? "spacing_closed" : "spacing_open" ]) || 0) // limitSize prevents this pane from 'overlapping' opposite pane , containerSize = (dir=="horz" ? sC.innerHeight : sC.innerWidth) , minCenterDims = cssMinDims("center") , minCenterSize = dir=="horz" ? max(options.center.minHeight, minCenterDims.minHeight) : max(options.center.minWidth, minCenterDims.minWidth) // if pane is 'sliding', then ignore center and alt-pane sizes - because 'overlays' them , limitSize = (containerSize - paneSpacing - (isSliding ? 0 : (_parseSize("center", minCenterSize, dir) + altPaneSize + altPaneSpacing))) , minSize = s.minSize = max( _parseSize(pane, o.minSize), cssMinDims(pane).minSize ) , maxSize = s.maxSize = min( (o.maxSize ? _parseSize(pane, o.maxSize) : 100000), limitSize ) , r = s.resizerPosition = {} // used to set resizing limits , top = sC.inset.top , left = sC.inset.left , W = sC.innerWidth , H = sC.innerHeight , rW = o.spacing_open // subtract resizer-width to get top/left position for south/east ; switch (pane) { case "north": r.min = top + minSize; r.max = top + maxSize; break; case "west": r.min = left + minSize; r.max = left + maxSize; break; case "south": r.min = top + H - maxSize - rW; r.max = top + H - minSize - rW; break; case "east": r.min = left + W - maxSize - rW; r.max = left + W - minSize - rW; break; }; } /** * Returns data for setting the size/position of center pane. Also used to set Height for east/west panes * * @return JSON Returns a hash of all dimensions: top, bottom, left, right, (outer) width and (outer) height */ , calcNewCenterPaneDims = function () { var d = { top: getPaneSize("north", true) // true = include 'spacing' value for pane , bottom: getPaneSize("south", true) , left: getPaneSize("west", true) , right: getPaneSize("east", true) , width: 0 , height: 0 }; // NOTE: sC = state.container // calc center-pane outer dimensions d.width = sC.innerWidth - d.left - d.right; // outerWidth d.height = sC.innerHeight - d.bottom - d.top; // outerHeight // add the 'container border/padding' to get final positions relative to the container d.top += sC.inset.top; d.bottom += sC.inset.bottom; d.left += sC.inset.left; d.right += sC.inset.right; return d; } /** * @param {!Object} el * @param {boolean=} [allStates=false] */ , getHoverClasses = function (el, allStates) { var $El = $(el) , type = $El.data("layoutRole") , pane = $El.data("layoutEdge") , o = options[pane] , root = o[type +"Class"] , _pane = "-"+ pane // eg: "-west" , _open = "-open" , _closed = "-closed" , _slide = "-sliding" , _hover = "-hover " // NOTE the trailing space , _state = $El.hasClass(root+_closed) ? _closed : _open , _alt = _state === _closed ? _open : _closed , classes = (root+_hover) + (root+_pane+_hover) + (root+_state+_hover) + (root+_pane+_state+_hover) ; if (allStates) // when 'removing' classes, also remove alternate-state classes classes += (root+_alt+_hover) + (root+_pane+_alt+_hover); if (type=="resizer" && $El.hasClass(root+_slide)) classes += (root+_slide+_hover) + (root+_pane+_slide+_hover); return $.trim(classes); } , addHover = function (evt, el) { var $E = $(el || this); if (evt && $E.data("layoutRole") === "toggler") evt.stopPropagation(); // prevent triggering 'slide' on Resizer-bar $E.addClass( getHoverClasses($E) ); } , removeHover = function (evt, el) { var $E = $(el || this); $E.removeClass( getHoverClasses($E, true) ); } , onResizerEnter = function (evt) { // ALSO called by toggler.mouseenter var pane = $(this).data("layoutEdge") , s = state[pane] ; // ignore closed-panes and mouse moving back & forth over resizer! // also ignore if ANY pane is currently resizing if ( s.isClosed || s.isResizing || state.paneResizing ) return; if ($.fn.disableSelection) $("body").disableSelection(); if (options.maskPanesEarly) showMasks( pane, { resizing: true }); } , onResizerLeave = function (evt, el) { var e = el || this // el is only passed when called by the timer , pane = $(e).data("layoutEdge") , name = pane +"ResizerLeave" ; timer.clear(pane+"_openSlider"); // cancel slideOpen timer, if set timer.clear(name); // cancel enableSelection timer - may re/set below // this method calls itself on a timer because it needs to allow // enough time for dragging to kick-in and set the isResizing flag // dragging has a 100ms delay set, so this delay must be >100 if (!el) // 1st call - mouseleave event timer.set(name, function(){ onResizerLeave(evt, e); }, 200); // if user is resizing, then dragStop will enableSelection(), so can skip it here else if ( !state.paneResizing ) { // 2nd call - by timer if ($.fn.enableSelection) $("body").enableSelection(); if (options.maskPanesEarly) hideMasks(); } } /* * ########################### * INITIALIZATION METHODS * ########################### */ /** * Initialize the layout - called automatically whenever an instance of layout is created * * @see none - triggered onInit * @return mixed true = fully initialized | false = panes not initialized (yet) | 'cancel' = abort */ , _create = function () { // initialize config/options initOptions(); var o = options , s = state; // TEMP state so isInitialized returns true during init process s.creatingLayout = true; // init plugins for this layout, if there are any (eg: stateManagement) runPluginCallbacks( Instance, $.layout.onCreate ); // options & state have been initialized, so now run beforeLoad callback // onload will CANCEL layout creation if it returns false if (false === _runCallbacks("onload_start")) return 'cancel'; // initialize the container element _initContainer(); // bind hotkey function - keyDown - if required initHotkeys(); // bind window.onunload $(window).bind("unload."+ sID, unload); // init plugins for this layout, if there are any (eg: customButtons) runPluginCallbacks( Instance, $.layout.onLoad ); // if layout elements are hidden, then layout WILL NOT complete initialization! // initLayoutElements will set initialized=true and run the onload callback IF successful if (o.initPanes) _initLayoutElements(); delete s.creatingLayout; return state.initialized; } /** * Initialize the layout IF not already * * @see All methods in Instance run this test * @return boolean true = layoutElements have been initialized | false = panes are not initialized (yet) */ , isInitialized = function () { if (state.initialized || state.creatingLayout) return true; // already initialized else return _initLayoutElements(); // try to init panes NOW } /** * Initialize the layout - called automatically whenever an instance of layout is created * * @see _create() & isInitialized * @param {boolean=} [retry=false] // indicates this is a 2nd try * @return An object pointer to the instance created */ , _initLayoutElements = function (retry) { // initialize config/options var o = options; // CANNOT init panes inside a hidden container! if (!$N.is(":visible")) { // handle Chrome bug where popup window 'has no height' // if layout is BODY element, try again in 50ms // SEE: http://layout.jquery-dev.net/samples/test_popup_window.html if ( !retry && browser.webkit && $N[0].tagName === "BODY" ) setTimeout(function(){ _initLayoutElements(true); }, 50); return false; } // a center pane is required, so make sure it exists if (!getPane("center").length) { return _log( o.errors.centerPaneMissing ); } // TEMP state so isInitialized returns true during init process state.creatingLayout = true; // update Container dims $.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT include insetX values // initialize all layout elements initPanes(); // size & position panes - calls initHandles() - which calls initResizable() if (o.scrollToBookmarkOnLoad) { var l = self.location; if (l.hash) l.replace( l.hash ); // scrollTo Bookmark } // check to see if this layout 'nested' inside a pane if (Instance.hasParentLayout) o.resizeWithWindow = false; // bind resizeAll() for 'this layout instance' to window.resize event else if (o.resizeWithWindow) $(window).bind("resize."+ sID, windowResize); delete state.creatingLayout; state.initialized = true; // init plugins for this layout, if there are any runPluginCallbacks( Instance, $.layout.onReady ); // now run the onload callback, if exists _runCallbacks("onload_end"); return true; // elements initialized successfully } /** * Initialize nested layouts for a specific pane - can optionally pass layout-options * * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west * @param {Object=} [opts] Layout-options - if passed, will OVERRRIDE options[pane].children * @return An object pointer to the layout instance created - or null */ , createChildren = function (evt_or_pane, opts) { var pane = evtPane.call(this, evt_or_pane) , $P = $Ps[pane] ; if (!$P) return; var $C = $Cs[pane] , s = state[pane] , o = options[pane] , sm = options.stateManagement || {} , cos = opts ? (o.children = opts) : o.children ; if ( $.isPlainObject( cos ) ) cos = [ cos ]; // convert a hash to a 1-elem array else if (!cos || !$.isArray( cos )) return; $.each( cos, function (idx, co) { if ( !$.isPlainObject( co ) ) return; // determine which element is supposed to be the 'child container' // if pane has a 'containerSelector' OR a 'content-div', use those instead of the pane var $containers = co.containerSelector ? $P.find( co.containerSelector ) : ($C || $P); $containers.each(function(){ var $cont = $(this) , child = $cont.data("layout") // see if a child-layout ALREADY exists on this element ; // if no layout exists, but children are set, try to create the layout now if (!child) { // TODO: see about moving this to the stateManagement plugin, as a method // set a unique child-instance key for this layout, if not already set setInstanceKey({ container: $cont, options: co }, s ); // If THIS layout has a hash in stateManagement.autoLoad, // then see if it also contains state-data for this child-layout // If so, copy the stateData to child.options.stateManagement.autoLoad if ( sm.includeChildren && state.stateData[pane] ) { // THIS layout's state was cached when its state was loaded var paneChildren = state.stateData[pane].children || {} , childState = paneChildren[ co.instanceKey ] , co_sm = co.stateManagement || (co.stateManagement = { autoLoad: true }) ; // COPY the stateData into the autoLoad key if ( co_sm.autoLoad === true && childState ) { co_sm.autoSave = false; // disable autoSave because saving handled by parent-layout co_sm.includeChildren = true; // cascade option - FOR NOW co_sm.autoLoad = $.extend(true, {}, childState); // COPY the state-hash } } // create the layout child = $cont.layout( co ); // if successful, update data if (child) { // add the child and update all layout-pointers // MAY have already been done by child-layout calling parent.refreshChildren() refreshChildren( pane, child ); } } }); }); } , setInstanceKey = function (child, parentPaneState) { // create a named key for use in state and instance branches var $c = child.container , o = child.options , sm = o.stateManagement , key = o.instanceKey || $c.data("layoutInstanceKey") ; if (!key) key = (sm && sm.cookie ? sm.cookie.name : '') || o.name; // look for a name/key if (!key) key = "layout"+ (++parentPaneState.childIdx); // if no name/key found, generate one else key = key.replace(/[^\w-]/gi, '_').replace(/_{2,}/g, '_'); // ensure is valid as a hash key o.instanceKey = key; $c.data("layoutInstanceKey", key); // useful if layout is destroyed and then recreated return key; } /** * @param {string} pane The pane being opened, ie: north, south, east, or west * @param {Object=} newChild New child-layout Instance to add to this pane */ , refreshChildren = function (pane, newChild) { var $P = $Ps[pane] , pC = children[pane] , s = state[pane] , o ; // check for destroy()ed layouts and update the child pointers & arrays if ($.isPlainObject( pC )) { $.each( pC, function (key, child) { if (child.destroyed) delete pC[key] }); // if no more children, remove the children hash if ($.isEmptyObject( pC )) pC = children[pane] = null; // clear children hash } // see if there is a directly-nested layout inside this pane // if there is, then there can be only ONE child-layout, so check that... if (!newChild && !pC) { newChild = $P.data("layout"); } // if a newChild instance was passed, add it to children[pane] if (newChild) { // update child.state newChild.hasParentLayout = true; // set parent-flag in child // instanceKey is a key-name used in both state and children o = newChild.options; // set a unique child-instance key for this layout, if not already set setInstanceKey( newChild, s ); // add pointer to pane.children hash if (!pC) pC = children[pane] = {}; // create an empty children hash pC[ o.instanceKey ] = newChild.container.data("layout"); // add childLayout instance } // ALWAYS refresh the pane.children alias, even if null Instance[pane].children = children[pane]; // if newChild was NOT passed - see if there is a child layout NOW if (!newChild) { createChildren(pane); // MAY create a child and re-call this method } } , windowResize = function () { var o = options , delay = Number(o.resizeWithWindowDelay); if (delay < 10) delay = 100; // MUST have a delay! // resizing uses a delay-loop because the resize event fires repeatly - except in FF, but delay anyway timer.clear("winResize"); // if already running timer.set("winResize", function(){ timer.clear("winResize"); timer.clear("winResizeRepeater"); var dims = elDims( $N, o.inset ); // only trigger resizeAll() if container has changed size if (dims.innerWidth !== sC.innerWidth || dims.innerHeight !== sC.innerHeight) resizeAll(); }, delay); // ALSO set fixed-delay timer, if not already running if (!timer.data["winResizeRepeater"]) setWindowResizeRepeater(); } , setWindowResizeRepeater = function () { var delay = Number(options.resizeWithWindowMaxDelay); if (delay > 0) timer.set("winResizeRepeater", function(){ setWindowResizeRepeater(); resizeAll(); }, delay); } , unload = function () { var o = options; _runCallbacks("onunload_start"); // trigger plugin callabacks for this layout (eg: stateManagement) runPluginCallbacks( Instance, $.layout.onUnload ); _runCallbacks("onunload_end"); } /** * Validate and initialize container CSS and events * * @see _create() */ , _initContainer = function () { var N = $N[0] , $H = $("html") , tag = sC.tagName = N.tagName , id = sC.id = N.id , cls = sC.className = N.className , o = options , name = o.name , props = "position,margin,padding,border" , css = "layoutCSS" , CSS = {} , hid = "hidden" // used A LOT! // see if this container is a 'pane' inside an outer-layout , parent = $N.data("parentLayout") // parent-layout Instance , pane = $N.data("layoutEdge") // pane-name in parent-layout , isChild = parent && pane , num = $.layout.cssNum , $parent, n ; // sC = state.container sC.selector = $N.selector.split(".slice")[0]; sC.ref = (o.name ? o.name +' layout / ' : '') + tag + (id ? "#"+id : cls ? '.['+cls+']' : ''); // used in messages sC.isBody = (tag === "BODY"); // try to find a parent-layout if (!isChild && !sC.isBody) { $parent = $N.closest("."+ $.layout.defaults.panes.paneClass); parent = $parent.data("parentLayout"); pane = $parent.data("layoutEdge"); isChild = parent && pane; } $N .data({ layout: Instance , layoutContainer: sID // FLAG to indicate this is a layout-container - contains unique internal ID }) .addClass(o.containerClass) ; var layoutMethods = { destroy: '' , initPanes: '' , resizeAll: 'resizeAll' , resize: 'resizeAll' }; // loop hash and bind all methods - include layoutID namespacing for (name in layoutMethods) { $N.bind("layout"+ name.toLowerCase() +"."+ sID, Instance[ layoutMethods[name] || name ]); } // if this container is another layout's 'pane', then set child/parent pointers if (isChild) { // update parent flag Instance.hasParentLayout = true; // set pointers to THIS child-layout (Instance) in parent-layout parent.refreshChildren( pane, Instance ); } // SAVE original container CSS for use in destroy() if (!$N.data(css)) { // handle props like overflow different for BODY & HTML - has 'system default' values if (sC.isBody) { // SAVE <BODY> CSS $N.data(css, $.extend( styles($N, props), { height: $N.css("height") , overflow: $N.css("overflow") , overflowX: $N.css("overflowX") , overflowY: $N.css("overflowY") })); // ALSO SAVE <HTML> CSS $H.data(css, $.extend( styles($H, 'padding'), { height: "auto" // FF would return a fixed px-size! , overflow: $H.css("overflow") , overflowX: $H.css("overflowX") , overflowY: $H.css("overflowY") })); } else // handle props normally for non-body elements $N.data(css, styles($N, props+",top,bottom,left,right,width,height,overflow,overflowX,overflowY") ); } try { // common container CSS CSS = { overflow: hid , overflowX: hid , overflowY: hid }; $N.css( CSS ); if (o.inset && !$.isPlainObject(o.inset)) { // can specify a single number for equal outset all-around n = parseInt(o.inset, 10) || 0 o.inset = { top: n , bottom: n , left: n , right: n }; } // format html & body if this is a full page layout if (sC.isBody) { // if HTML has padding, use this as an outer-spacing around BODY if (!o.outset) { // use padding from parent-elem (HTML) as outset o.outset = { top: num($H, "paddingTop") , bottom: num($H, "paddingBottom") , left: num($H, "paddingLeft") , right: num($H, "paddingRight") }; } else if (!$.isPlainObject(o.outset)) { // can specify a single number for equal outset all-around n = parseInt(o.outset, 10) || 0 o.outset = { top: n , bottom: n , left: n , right: n }; } // HTML $H.css( CSS ).css({ height: "100%" , border: "none" // no border or padding allowed when using height = 100% , padding: 0 // ditto , margin: 0 }); // BODY if (browser.isIE6) { // IE6 CANNOT use the trick of setting absolute positioning on all 4 sides - must have 'height' $N.css({ width: "100%" , height: "100%" , border: "none" // no border or padding allowed when using height = 100% , padding: 0 // ditto , margin: 0 , position: "relative" }); // convert body padding to an inset option - the border cannot be measured in IE6! if (!o.inset) o.inset = elDims( $N ).inset; } else { // use absolute positioning for BODY to allow borders & padding without overflow $N.css({ width: "auto" , height: "auto" , margin: 0 , position: "absolute" // allows for border and padding on BODY }); // apply edge-positioning created above $N.css( o.outset ); } // set current layout-container dimensions $.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT include insetX values } else { // container MUST have 'position' var p = $N.css("position"); if (!p || !p.match(/(fixed|absolute|relative)/)) $N.css("position","relative"); // set current layout-container dimensions if ( $N.is(":visible") ) { $.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT change insetX (padding) values if (sC.innerHeight < 1) // container has no 'height' - warn developer _log( o.errors.noContainerHeight.replace(/CONTAINER/, sC.ref) ); } } // if container has min-width/height, then enable scrollbar(s) if ( num($N, "minWidth") ) $N.parent().css("overflowX","auto"); if ( num($N, "minHeight") ) $N.parent().css("overflowY","auto"); } catch (ex) {} } /** * Bind layout hotkeys - if options enabled * * @see _create() and addPane() * @param {string=} [panes=""] The edge(s) to process */ , initHotkeys = function (panes) { panes = panes ? panes.split(",") : _c.borderPanes; // bind keyDown to capture hotkeys, if option enabled for ANY pane $.each(panes, function (i, pane) { var o = options[pane]; if (o.enableCursorHotkey || o.customHotkey) { $(document).bind("keydown."+ sID, keyDown); // only need to bind this ONCE return false; // BREAK - binding was done } }); } /** * Build final OPTIONS data * * @see _create() */ , initOptions = function () { var data, d, pane, key, val, i, c, o; // reprocess user's layout-options to have correct options sub-key structure opts = $.layout.transformData( opts, true ); // panes = default subkey // auto-rename old options for backward compatibility opts = $.layout.backwardCompatibility.renameAllOptions( opts ); // if user-options has 'panes' key (pane-defaults), clean it... if (!$.isEmptyObject(opts.panes)) { // REMOVE any pane-defaults that MUST be set per-pane data = $.layout.optionsMap.noDefault; for (i=0, c=data.length; i<c; i++) { key = data[i]; delete opts.panes[key]; // OK if does not exist } // REMOVE any layout-options specified under opts.panes data = $.layout.optionsMap.layout; for (i=0, c=data.length; i<c; i++) { key = data[i]; delete opts.panes[key]; // OK if does not exist } } // MOVE any NON-layout-options from opts-root to opts.panes data = $.layout.optionsMap.layout; var rootKeys = $.layout.config.optionRootKeys; for (key in opts) { val = opts[key]; if ($.inArray(key, rootKeys) < 0 && $.inArray(key, data) < 0) { if (!opts.panes[key]) opts.panes[key] = $.isPlainObject(val) ? $.extend(true, {}, val) : val; delete opts[key] } } // START by updating ALL options from opts $.extend(true, options, opts); // CREATE final options (and config) for EACH pane $.each(_c.allPanes, function (i, pane) { // apply 'pane-defaults' to CONFIG.[PANE] _c[pane] = $.extend(true, {}, _c.panes, _c[pane]); d = options.panes; o = options[pane]; // center-pane uses SOME keys in defaults.panes branch if (pane === 'center') { // ONLY copy keys from opts.panes listed in: $.layout.optionsMap.center data = $.layout.optionsMap.center; // list of 'center-pane keys' for (i=0, c=data.length; i<c; i++) { // loop the list... key = data[i]; // only need to use pane-default if pane-specific value not set if (!opts.center[key] && (opts.panes[key] || !o[key])) o[key] = d[key]; // pane-default } } else { // border-panes use ALL keys in defaults.panes branch o = options[pane] = $.extend(true, {}, d, o); // re-apply pane-specific opts AFTER pane-defaults createFxOptions( pane ); // ensure all border-pane-specific base-classes exist if (!o.resizerClass) o.resizerClass = "ui-layout-resizer"; if (!o.togglerClass) o.togglerClass = "ui-layout-toggler"; } // ensure we have base pane-class (ALL panes) if (!o.paneClass) o.paneClass = "ui-layout-pane"; }); // update options.zIndexes if a zIndex-option specified var zo = opts.zIndex , z = options.zIndexes; if (zo > 0) { z.pane_normal = zo; z.content_mask = max(zo+1, z.content_mask); // MIN = +1 z.resizer_normal = max(zo+2, z.resizer_normal); // MIN = +2 } // DELETE 'panes' key now that we are done - values were copied to EACH pane delete options.panes; function createFxOptions ( pane ) { var o = options[pane] , d = options.panes; // ensure fxSettings key to avoid errors if (!o.fxSettings) o.fxSettings = {}; if (!d.fxSettings) d.fxSettings = {}; $.each(["_open","_close","_size"], function (i,n) { var sName = "fxName"+ n , sSpeed = "fxSpeed"+ n , sSettings = "fxSettings"+ n // recalculate fxName according to specificity rules , fxName = o[sName] = o[sName] // options.west.fxName_open || d[sName] // options.panes.fxName_open || o.fxName // options.west.fxName || d.fxName // options.panes.fxName || "none" // MEANS $.layout.defaults.panes.fxName == "" || false || null || 0 , fxExists = $.effects && ($.effects[fxName] || ($.effects.effect && $.effects.effect[fxName])) ; // validate fxName to ensure is valid effect - MUST have effect-config data in options.effects if (fxName === "none" || !options.effects[fxName] || !fxExists) fxName = o[sName] = "none"; // effect not loaded OR unrecognized fxName // set vars for effects subkeys to simplify logic var fx = options.effects[fxName] || {} // effects.slide , fx_all = fx.all || null // effects.slide.all , fx_pane = fx[pane] || null // effects.slide.west ; // create fxSpeed[_open|_close|_size] o[sSpeed] = o[sSpeed] // options.west.fxSpeed_open || d[sSpeed] // options.west.fxSpeed_open || o.fxSpeed // options.west.fxSpeed || d.fxSpeed // options.panes.fxSpeed || null // DEFAULT - let fxSetting.duration control speed ; // create fxSettings[_open|_close|_size] o[sSettings] = $.extend( true , {} , fx_all // effects.slide.all , fx_pane // effects.slide.west , d.fxSettings // options.panes.fxSettings , o.fxSettings // options.west.fxSettings , d[sSettings] // options.panes.fxSettings_open , o[sSettings] // options.west.fxSettings_open ); }); // DONE creating action-specific-settings for this pane, // so DELETE generic options - are no longer meaningful delete o.fxName; delete o.fxSpeed; delete o.fxSettings; } } /** * Initialize module objects, styling, size and position for all panes * * @see _initElements() * @param {string} pane The pane to process */ , getPane = function (pane) { var sel = options[pane].paneSelector if (sel.substr(0,1)==="#") // ID selector // NOTE: elements selected 'by ID' DO NOT have to be 'children' return $N.find(sel).eq(0); else { // class or other selector var $P = $N.children(sel).eq(0); // look for the pane nested inside a 'form' element return $P.length ? $P : $N.children("form:first").children(sel).eq(0); } } /** * @param {Object=} evt */ , initPanes = function (evt) { // stopPropagation if called by trigger("layoutinitpanes") - use evtPane utility evtPane(evt); // NOTE: do north & south FIRST so we can measure their height - do center LAST $.each(_c.allPanes, function (idx, pane) { addPane( pane, true ); }); // init the pane-handles NOW in case we have to hide or close the pane below initHandles(); // now that all panes have been initialized and initially-sized, // make sure there is really enough space available for each pane $.each(_c.borderPanes, function (i, pane) { if ($Ps[pane] && state[pane].isVisible) { // pane is OPEN setSizeLimits(pane); makePaneFit(pane); // pane may be Closed, Hidden or Resized by makePaneFit() } }); // size center-pane AGAIN in case we 'closed' a border-pane in loop above sizeMidPanes("center"); // Chrome/Webkit sometimes fires callbacks BEFORE it completes resizing! // Before RC30.3, there was a 10ms delay here, but that caused layout // to load asynchrously, which is BAD, so try skipping delay for now // process pane contents and callbacks, and init/resize child-layout if exists $.each(_c.allPanes, function (idx, pane) { afterInitPane(pane); }); } /** * Add a pane to the layout - subroutine of initPanes() * * @see initPanes() * @param {string} pane The pane to process * @param {boolean=} [force=false] Size content after init */ , addPane = function (pane, force) { if (!force && !isInitialized()) return; var o = options[pane] , s = state[pane] , c = _c[pane] , dir = c.dir , fx = s.fx , spacing = o.spacing_open || 0 , isCenter = (pane === "center") , CSS = {} , $P = $Ps[pane] , size, minSize, maxSize, child ; // if pane-pointer already exists, remove the old one first if ($P) removePane( pane, false, true, false ); else $Cs[pane] = false; // init $P = $Ps[pane] = getPane(pane); if (!$P.length) { $Ps[pane] = false; // logic return; } // SAVE original Pane CSS if (!$P.data("layoutCSS")) { var props = "position,top,left,bottom,right,width,height,overflow,zIndex,display,backgroundColor,padding,margin,border"; $P.data("layoutCSS", styles($P, props)); } // create alias for pane data in Instance - initHandles will add more Instance[pane] = { name: pane , pane: $Ps[pane] , content: $Cs[pane] , options: options[pane] , state: state[pane] , children: children[pane] }; // add classes, attributes & events $P .data({ parentLayout: Instance // pointer to Layout Instance , layoutPane: Instance[pane] // NEW pointer to pane-alias-object , layoutEdge: pane , layoutRole: "pane" }) .css(c.cssReq).css("zIndex", options.zIndexes.pane_normal) .css(o.applyDemoStyles ? c.cssDemo : {}) // demo styles .addClass( o.paneClass +" "+ o.paneClass+"-"+pane ) // default = "ui-layout-pane ui-layout-pane-west" - may be a dupe of 'paneSelector' .bind("mouseenter."+ sID, addHover ) .bind("mouseleave."+ sID, removeHover ) ; var paneMethods = { hide: '' , show: '' , toggle: '' , close: '' , open: '' , slideOpen: '' , slideClose: '' , slideToggle: '' , size: 'sizePane' , sizePane: 'sizePane' , sizeContent: '' , sizeHandles: '' , enableClosable: '' , disableClosable: '' , enableSlideable: '' , disableSlideable: '' , enableResizable: '' , disableResizable: '' , swapPanes: 'swapPanes' , swap: 'swapPanes' , move: 'swapPanes' , removePane: 'removePane' , remove: 'removePane' , createChildren: '' , resizeChildren: '' , resizeAll: 'resizeAll' , resizeLayout: 'resizeAll' } , name; // loop hash and bind all methods - include layoutID namespacing for (name in paneMethods) { $P.bind("layoutpane"+ name.toLowerCase() +"."+ sID, Instance[ paneMethods[name] || name ]); } // see if this pane has a 'scrolling-content element' initContent(pane, false); // false = do NOT sizeContent() - called later if (!isCenter) { // call _parseSize AFTER applying pane classes & styles - but before making visible (if hidden) // if o.size is auto or not valid, then MEASURE the pane and use that as its 'size' size = s.size = _parseSize(pane, o.size); minSize = _parseSize(pane,o.minSize) || 1; maxSize = _parseSize(pane,o.maxSize) || 100000; if (size > 0) size = max(min(size, maxSize), minSize); s.autoResize = o.autoResize; // used with percentage sizes // state for border-panes s.isClosed = false; // true = pane is closed s.isSliding = false; // true = pane is currently open by 'sliding' over adjacent panes s.isResizing= false; // true = pane is in process of being resized s.isHidden = false; // true = pane is hidden - no spacing, resizer or toggler is visible! // array for 'pin buttons' whose classNames are auto-updated on pane-open/-close if (!s.pins) s.pins = []; } // states common to ALL panes s.tagName = $P[0].tagName; s.edge = pane; // useful if pane is (or about to be) 'swapped' - easy find out where it is (or is going) s.noRoom = false; // true = pane 'automatically' hidden due to insufficient room - will unhide automatically s.isVisible = true; // false = pane is invisible - closed OR hidden - simplify logic // init pane positioning setPanePosition( pane ); // if pane is not visible, if (dir === "horz") // north or south pane CSS.height = cssH($P, size); else if (dir === "vert") // east or west pane CSS.width = cssW($P, size); //else if (isCenter) {} $P.css(CSS); // apply size -- top, bottom & height will be set by sizeMidPanes if (dir != "horz") sizeMidPanes(pane, true); // true = skipCallback // if manually adding a pane AFTER layout initialization, then... if (state.initialized) { initHandles( pane ); initHotkeys( pane ); } // close or hide the pane if specified in settings if (o.initClosed && o.closable && !o.initHidden) close(pane, true, true); // true, true = force, noAnimation else if (o.initHidden || o.initClosed) hide(pane); // will be completely invisible - no resizer or spacing else if (!s.noRoom) // make the pane visible - in case was initially hidden $P.css("display","block"); // ELSE setAsOpen() - called later by initHandles() // RESET visibility now - pane will appear IF display:block $P.css("visibility","visible"); // check option for auto-handling of pop-ups & drop-downs if (o.showOverflowOnHover) $P.hover( allowOverflow, resetOverflow ); // if manually adding a pane AFTER layout initialization, then... if (state.initialized) { afterInitPane( pane ); } } , afterInitPane = function (pane) { var $P = $Ps[pane] , s = state[pane] , o = options[pane] ; if (!$P) return; // see if there is a directly-nested layout inside this pane if ($P.data("layout")) refreshChildren( pane, $P.data("layout") ); // process pane contents and callbacks, and init/resize child-layout if exists if (s.isVisible) { // pane is OPEN if (state.initialized) // this pane was added AFTER layout was created resizeAll(); // will also sizeContent else sizeContent(pane); if (o.triggerEventsOnLoad) _runCallbacks("onresize_end", pane); else // automatic if onresize called, otherwise call it specifically // resize child - IF inner-layout already exists (created before this layout) resizeChildren(pane, true); // a previously existing childLayout } // init childLayouts - even if pane is not visible if (o.initChildren && o.children) createChildren(pane); } /** * @param {string=} panes The pane(s) to process */ , setPanePosition = function (panes) { panes = panes ? panes.split(",") : _c.borderPanes; // create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV $.each(panes, function (i, pane) { var $P = $Ps[pane] , $R = $Rs[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side , CSS = {} ; if (!$P) return; // pane does not exist - skip // set css-position to account for container borders & padding switch (pane) { case "north": CSS.top = sC.inset.top; CSS.left = sC.inset.left; CSS.right = sC.inset.right; break; case "south": CSS.bottom = sC.inset.bottom; CSS.left = sC.inset.left; CSS.right = sC.inset.right; break; case "west": CSS.left = sC.inset.left; // top, bottom & height set by sizeMidPanes() break; case "east": CSS.right = sC.inset.right; // ditto break; case "center": // top, left, width & height set by sizeMidPanes() } // apply position $P.css(CSS); // update resizer position if ($R && s.isClosed) $R.css(side, sC.inset[side]); else if ($R && !s.isHidden) $R.css(side, sC.inset[side] + getPaneSize(pane)); }); } /** * Initialize module objects, styling, size and position for all resize bars and toggler buttons * * @see _create() * @param {string=} [panes=""] The edge(s) to process */ , initHandles = function (panes) { panes = panes ? panes.split(",") : _c.borderPanes; // create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV $.each(panes, function (i, pane) { var $P = $Ps[pane]; $Rs[pane] = false; // INIT $Ts[pane] = false; if (!$P) return; // pane does not exist - skip var o = options[pane] , s = state[pane] , c = _c[pane] , paneId = o.paneSelector.substr(0,1) === "#" ? o.paneSelector.substr(1) : "" , rClass = o.resizerClass , tClass = o.togglerClass , spacing = (s.isVisible ? o.spacing_open : o.spacing_closed) , _pane = "-"+ pane // used for classNames , _state = (s.isVisible ? "-open" : "-closed") // used for classNames , I = Instance[pane] // INIT RESIZER BAR , $R = I.resizer = $Rs[pane] = $("<div></div>") // INIT TOGGLER BUTTON , $T = I.toggler = (o.closable ? $Ts[pane] = $("<div></div>") : false) ; //if (s.isVisible && o.resizable) ... handled by initResizable if (!s.isVisible && o.slidable) $R.attr("title", o.tips.Slide).css("cursor", o.sliderCursor); $R // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer" .attr("id", paneId ? paneId +"-resizer" : "" ) .data({ parentLayout: Instance , layoutPane: Instance[pane] // NEW pointer to pane-alias-object , layoutEdge: pane , layoutRole: "resizer" }) .css(_c.resizers.cssReq).css("zIndex", options.zIndexes.resizer_normal) .css(o.applyDemoStyles ? _c.resizers.cssDemo : {}) // add demo styles .addClass(rClass +" "+ rClass+_pane) .hover(addHover, removeHover) // ALWAYS add hover-classes, even if resizing is not enabled - handle with CSS instead .hover(onResizerEnter, onResizerLeave) // ALWAYS NEED resizer.mouseleave to balance toggler.mouseenter .appendTo($N) // append DIV to container ; if (o.resizerDblClickToggle) $R.bind("dblclick."+ sID, toggle ); if ($T) { $T // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "#paneLeft-toggler" .attr("id", paneId ? paneId +"-toggler" : "" ) .data({ parentLayout: Instance , layoutPane: Instance[pane] // NEW pointer to pane-alias-object , layoutEdge: pane , layoutRole: "toggler" }) .css(_c.togglers.cssReq) // add base/required styles .css(o.applyDemoStyles ? _c.togglers.cssDemo : {}) // add demo styles .addClass(tClass +" "+ tClass+_pane) .hover(addHover, removeHover) // ALWAYS add hover-classes, even if toggling is not enabled - handle with CSS instead .bind("mouseenter", onResizerEnter) // NEED toggler.mouseenter because mouseenter MAY NOT fire on resizer .appendTo($R) // append SPAN to resizer DIV ; // ADD INNER-SPANS TO TOGGLER if (o.togglerContent_open) // ui-layout-open $("<span>"+ o.togglerContent_open +"</span>") .data({ layoutEdge: pane , layoutRole: "togglerContent" }) .data("layoutRole", "togglerContent") .data("layoutEdge", pane) .addClass("content content-open") .css("display","none") .appendTo( $T ) //.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-open instead! ; if (o.togglerContent_closed) // ui-layout-closed $("<span>"+ o.togglerContent_closed +"</span>") .data({ layoutEdge: pane , layoutRole: "togglerContent" }) .addClass("content content-closed") .css("display","none") .appendTo( $T ) //.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-closed instead! ; // ADD TOGGLER.click/.hover enableClosable(pane); } // add Draggable events initResizable(pane); // ADD CLASSNAMES & SLIDE-BINDINGS - eg: class="resizer resizer-west resizer-open" if (s.isVisible) setAsOpen(pane); // onOpen will be called, but NOT onResize else { setAsClosed(pane); // onClose will be called bindStartSlidingEvents(pane, true); // will enable events IF option is set } }); // SET ALL HANDLE DIMENSIONS sizeHandles(); } /** * Initialize scrolling ui-layout-content div - if exists * * @see initPane() - or externally after an Ajax injection * @param {string} pane The pane to process * @param {boolean=} [resize=true] Size content after init */ , initContent = function (pane, resize) { if (!isInitialized()) return; var o = options[pane] , sel = o.contentSelector , I = Instance[pane] , $P = $Ps[pane] , $C ; if (sel) $C = I.content = $Cs[pane] = (o.findNestedContent) ? $P.find(sel).eq(0) // match 1-element only : $P.children(sel).eq(0) ; if ($C && $C.length) { $C.data("layoutRole", "content"); // SAVE original Content CSS if (!$C.data("layoutCSS")) $C.data("layoutCSS", styles($C, "height")); $C.css( _c.content.cssReq ); if (o.applyDemoStyles) { $C.css( _c.content.cssDemo ); // add padding & overflow: auto to content-div $P.css( _c.content.cssDemoPane ); // REMOVE padding/scrolling from pane } // ensure no vertical scrollbar on pane - will mess up measurements if ($P.css("overflowX").match(/(scroll|auto)/)) { $P.css("overflow", "hidden"); } state[pane].content = {}; // init content state if (resize !== false) sizeContent(pane); // sizeContent() is called AFTER init of all elements } else I.content = $Cs[pane] = false; } /** * Add resize-bars to all panes that specify it in options * -dependancy: $.fn.resizable - will skip if not found * * @see _create() * @param {string=} [panes=""] The edge(s) to process */ , initResizable = function (panes) { var draggingAvailable = $.layout.plugins.draggable , side // set in start() ; panes = panes ? panes.split(",") : _c.borderPanes; $.each(panes, function (idx, pane) { var o = options[pane]; if (!draggingAvailable || !$Ps[pane] || !o.resizable) { o.resizable = false; return true; // skip to next } var s = state[pane] , z = options.zIndexes , c = _c[pane] , side = c.dir=="horz" ? "top" : "left" , $P = $Ps[pane] , $R = $Rs[pane] , base = o.resizerClass , lastPos = 0 // used when live-resizing , r, live // set in start because may change // 'drag' classes are applied to the ORIGINAL resizer-bar while dragging is in process , resizerClass = base+"-drag" // resizer-drag , resizerPaneClass = base+"-"+pane+"-drag" // resizer-north-drag // 'helper' class is applied to the CLONED resizer-bar while it is being dragged , helperClass = base+"-dragging" // resizer-dragging , helperPaneClass = base+"-"+pane+"-dragging" // resizer-north-dragging , helperLimitClass = base+"-dragging-limit" // resizer-drag , helperPaneLimitClass = base+"-"+pane+"-dragging-limit" // resizer-north-drag , helperClassesSet = false // logic var ; if (!s.isClosed) $R.attr("title", o.tips.Resize) .css("cursor", o.resizerCursor); // n-resize, s-resize, etc $R.draggable({ containment: $N[0] // limit resizing to layout container , axis: (c.dir=="horz" ? "y" : "x") // limit resizing to horz or vert axis , delay: 0 , distance: 1 , grid: o.resizingGrid // basic format for helper - style it using class: .ui-draggable-dragging , helper: "clone" , opacity: o.resizerDragOpacity , addClasses: false // avoid ui-state-disabled class when disabled //, iframeFix: o.draggableIframeFix // TODO: consider using when bug is fixed , zIndex: z.resizer_drag , start: function (e, ui) { // REFRESH options & state pointers in case we used swapPanes o = options[pane]; s = state[pane]; // re-read options live = o.livePaneResizing; // ondrag_start callback - will CANCEL hide if returns false // TODO: dragging CANNOT be cancelled like this, so see if there is a way? if (false === _runCallbacks("ondrag_start", pane)) return false; s.isResizing = true; // prevent pane from closing while resizing state.paneResizing = pane; // easy to see if ANY pane is resizing timer.clear(pane+"_closeSlider"); // just in case already triggered // SET RESIZER LIMITS - used in drag() setSizeLimits(pane); // update pane/resizer state r = s.resizerPosition; lastPos = ui.position[ side ] $R.addClass( resizerClass +" "+ resizerPaneClass ); // add drag classes helperClassesSet = false; // reset logic var - see drag() // DISABLE TEXT SELECTION (probably already done by resizer.mouseOver) $('body').disableSelection(); // MASK PANES CONTAINING IFRAMES, APPLETS OR OTHER TROUBLESOME ELEMENTS showMasks( pane, { resizing: true }); } , drag: function (e, ui) { if (!helperClassesSet) { // can only add classes after clone has been added to the DOM //$(".ui-draggable-dragging") ui.helper .addClass( helperClass +" "+ helperPaneClass ) // add helper classes .css({ right: "auto", bottom: "auto" }) // fix dir="rtl" issue .children().css("visibility","hidden") // hide toggler inside dragged resizer-bar ; helperClassesSet = true; // draggable bug!? RE-SET zIndex to prevent E/W resize-bar showing through N/S pane! if (s.isSliding) $Ps[pane].css("zIndex", z.pane_sliding); } // CONTAIN RESIZER-BAR TO RESIZING LIMITS var limit = 0; if (ui.position[side] < r.min) { ui.position[side] = r.min; limit = -1; } else if (ui.position[side] > r.max) { ui.position[side] = r.max; limit = 1; } // ADD/REMOVE dragging-limit CLASS if (limit) { ui.helper.addClass( helperLimitClass +" "+ helperPaneLimitClass ); // at dragging-limit window.defaultStatus = (limit>0 && pane.match(/(north|west)/)) || (limit<0 && pane.match(/(south|east)/)) ? o.tips.maxSizeWarning : o.tips.minSizeWarning; } else { ui.helper.removeClass( helperLimitClass +" "+ helperPaneLimitClass ); // not at dragging-limit window.defaultStatus = ""; } // DYNAMICALLY RESIZE PANES IF OPTION ENABLED // won't trigger unless resizer has actually moved! if (live && Math.abs(ui.position[side] - lastPos) >= o.liveResizingTolerance) { lastPos = ui.position[side]; resizePanes(e, ui, pane) } } , stop: function (e, ui) { $('body').enableSelection(); // RE-ENABLE TEXT SELECTION window.defaultStatus = ""; // clear 'resizing limit' message from statusbar $R.removeClass( resizerClass +" "+ resizerPaneClass ); // remove drag classes from Resizer s.isResizing = false; state.paneResizing = false; // easy to see if ANY pane is resizing resizePanes(e, ui, pane, true); // true = resizingDone } }); }); /** * resizePanes * * Sub-routine called from stop() - and drag() if livePaneResizing * * @param {!Object} evt * @param {!Object} ui * @param {string} pane * @param {boolean=} [resizingDone=false] */ var resizePanes = function (evt, ui, pane, resizingDone) { var dragPos = ui.position , c = _c[pane] , o = options[pane] , s = state[pane] , resizerPos ; switch (pane) { case "north": resizerPos = dragPos.top; break; case "west": resizerPos = dragPos.left; break; case "south": resizerPos = sC.layoutHeight - dragPos.top - o.spacing_open; break; case "east": resizerPos = sC.layoutWidth - dragPos.left - o.spacing_open; break; }; // remove container margin from resizer position to get the pane size var newSize = resizerPos - sC.inset[c.side]; // Disable OR Resize Mask(s) created in drag.start if (!resizingDone) { // ensure we meet liveResizingTolerance criteria if (Math.abs(newSize - s.size) < o.liveResizingTolerance) return; // SKIP resize this time // resize the pane manualSizePane(pane, newSize, false, true); // true = noAnimation sizeMasks(); // resize all visible masks } else { // resizingDone // ondrag_end callback if (false !== _runCallbacks("ondrag_end", pane)) manualSizePane(pane, newSize, false, true); // true = noAnimation hideMasks(true); // true = force hiding all masks even if one is 'sliding' if (s.isSliding) // RE-SHOW 'object-masks' so objects won't show through sliding pane showMasks( pane, { resizing: true }); } }; } /** * sizeMask * * Needed to overlay a DIV over an IFRAME-pane because mask CANNOT be *inside* the pane * Called when mask created, and during livePaneResizing */ , sizeMask = function () { var $M = $(this) , pane = $M.data("layoutMask") // eg: "west" , s = state[pane] ; // only masks over an IFRAME-pane need manual resizing if (s.tagName == "IFRAME" && s.isVisible) // no need to mask closed/hidden panes $M.css({ top: s.offsetTop , left: s.offsetLeft , width: s.outerWidth , height: s.outerHeight }); /* ALT Method... var $P = $Ps[pane]; $M.css( $P.position() ).css({ width: $P[0].offsetWidth, height: $P[0].offsetHeight }); */ } , sizeMasks = function () { $Ms.each( sizeMask ); // resize all 'visible' masks } /** * @param {string} pane The pane being resized, animated or isSliding * @param {Object=} [args] (optional) Options: which masks to apply, and to which panes */ , showMasks = function (pane, args) { var c = _c[pane] , panes = ["center"] , z = options.zIndexes , a = $.extend({ objectsOnly: false , animation: false , resizing: true , sliding: state[pane].isSliding }, args ) , o, s ; if (a.resizing) panes.push( pane ); if (a.sliding) panes.push( _c.oppositeEdge[pane] ); // ADD the oppositeEdge-pane if (c.dir === "horz") { panes.push("west"); panes.push("east"); } $.each(panes, function(i,p){ s = state[p]; o = options[p]; if (s.isVisible && ( o.maskObjects || (!a.objectsOnly && o.maskContents) )) { getMasks(p).each(function(){ sizeMask.call(this); this.style.zIndex = s.isSliding ? z.pane_sliding+1 : z.pane_normal+1 this.style.display = "block"; }); } }); } /** * @param {boolean=} force Hide masks even if a pane is sliding */ , hideMasks = function (force) { // ensure no pane is resizing - could be a timing issue if (force || !state.paneResizing) { $Ms.hide(); // hide ALL masks } // if ANY pane is sliding, then DO NOT remove masks from panes with maskObjects enabled else if (!force && !$.isEmptyObject( state.panesSliding )) { var i = $Ms.length - 1 , p, $M; for (; i >= 0; i--) { $M = $Ms.eq(i); p = $M.data("layoutMask"); if (!options[p].maskObjects) { $M.hide(); } } } } /** * @param {string} pane */ , getMasks = function (pane) { var $Masks = $([]) , $M, i = 0, c = $Ms.length ; for (; i<c; i++) { $M = $Ms.eq(i); if ($M.data("layoutMask") === pane) $Masks = $Masks.add( $M ); } if ($Masks.length) return $Masks; else return createMasks(pane); } /** * createMasks * * Generates both DIV (ALWAYS used) and IFRAME (optional) elements as masks * An IFRAME mask is created *under* the DIV when maskObjects=true, because a DIV cannot mask an applet * * @param {string} pane */ , createMasks = function (pane) { var $P = $Ps[pane] , s = state[pane] , o = options[pane] , z = options.zIndexes //, objMask = o.maskObjects && s.tagName != "IFRAME" // check for option , $Masks = $([]) , isIframe, el, $M, css, i ; if (!o.maskContents && !o.maskObjects) return $Masks; // if o.maskObjects=true, then loop TWICE to create BOTH kinds of mask, else only create a DIV for (i=0; i < (o.maskObjects ? 2 : 1); i++) { isIframe = o.maskObjects && i==0; el = document.createElement( isIframe ? "iframe" : "div" ); $M = $(el).data("layoutMask", pane); // add data to relate mask to pane el.className = "ui-layout-mask ui-layout-mask-"+ pane; // for user styling css = el.style; // styles common to both DIVs and IFRAMES css.display = "block"; css.position = "absolute"; css.background = "#FFF"; if (isIframe) { // IFRAME-only props el.frameborder = 0; el.src = "about:blank"; //el.allowTransparency = true; - for IE, but breaks masking ability! css.opacity = 0; css.filter = "Alpha(Opacity='0')"; css.border = 0; } // if pane is an IFRAME, then must mask the pane itself if (s.tagName == "IFRAME") { // NOTE sizing done by a subroutine so can be called during live-resizing css.zIndex = z.pane_normal+1; // 1-higher than pane $N.append( el ); // append to LAYOUT CONTAINER } // otherwise put masks *inside the pane* to mask its contents else { $M.addClass("ui-layout-mask-inside-pane"); css.zIndex = o.maskZindex || z.content_mask; // usually 1, but customizable css.top = 0; css.left = 0; css.width = "100%"; css.height = "100%"; $P.append( el ); // append INSIDE pane element } // add to return object $Masks = $Masks.add( el ); // add Mask to cached array so can be resized & reused $Ms = $Ms.add( el ); } return $Masks; } /** * Destroy this layout and reset all elements * * @param {boolean=} [destroyChildren=false] Destory Child-Layouts first? */ , destroy = function (evt_or_destroyChildren, destroyChildren) { // UNBIND layout events and remove global object $(window).unbind("."+ sID); // resize & unload $(document).unbind("."+ sID); // keyDown (hotkeys) if (typeof evt_or_destroyChildren === "object") // stopPropagation if called by trigger("layoutdestroy") - use evtPane utility evtPane(evt_or_destroyChildren); else // no event, so transfer 1st param to destroyChildren param destroyChildren = evt_or_destroyChildren; // need to look for parent layout BEFORE we remove the container data, else skips a level //var parentPane = Instance.hasParentLayout ? $.layout.getParentPaneInstance( $N ) : null; // reset layout-container $N .clearQueue() .removeData("layout") .removeData("layoutContainer") .removeClass(options.containerClass) .unbind("."+ sID) // remove ALL Layout events ; // remove all mask elements that have been created $Ms.remove(); // loop all panes to remove layout classes, attributes and bindings $.each(_c.allPanes, function (i, pane) { removePane( pane, false, true, destroyChildren ); // true = skipResize }); // do NOT reset container CSS if is a 'pane' (or 'content') in an outer-layout - ie, THIS layout is 'nested' var css = "layoutCSS"; if ($N.data(css) && !$N.data("layoutRole")) // RESET CSS $N.css( $N.data(css) ).removeData(css); // for full-page layouts, also reset the <HTML> CSS if (sC.tagName === "BODY" && ($N = $("html")).data(css)) // RESET <HTML> CSS $N.css( $N.data(css) ).removeData(css); // trigger plugins for this layout, if there are any runPluginCallbacks( Instance, $.layout.onDestroy ); // trigger state-management and onunload callback unload(); // clear the Instance of everything except for container & options (so could recreate) // RE-CREATE: myLayout = myLayout.container.layout( myLayout.options ); for (var n in Instance) if (!n.match(/^(container|options)$/)) delete Instance[ n ]; // add a 'destroyed' flag to make it easy to check Instance.destroyed = true; // if this is a child layout, CLEAR the child-pointer in the parent /* for now the pointer REMAINS, but with only container, options and destroyed keys if (parentPane) { var layout = parentPane.pane.data("parentLayout") , key = layout.options.instanceKey || 'error'; // THIS SYNTAX MAY BE WRONG! parentPane.children[key] = layout.children[ parentPane.name ].children[key] = null; } */ return Instance; // for coding convenience } /** * Remove a pane from the layout - subroutine of destroy() * * @see destroy() * @param {(string|Object)} evt_or_pane The pane to process * @param {boolean=} [remove=false] Remove the DOM element? * @param {boolean=} [skipResize=false] Skip calling resizeAll()? * @param {boolean=} [destroyChild=true] Destroy Child-layouts? If not passed, obeys options setting */ , removePane = function (evt_or_pane, remove, skipResize, destroyChild) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $P = $Ps[pane] , $C = $Cs[pane] , $R = $Rs[pane] , $T = $Ts[pane] ; // NOTE: elements can still exist even after remove() // so check for missing data(), which is cleared by removed() if ($P && $.isEmptyObject( $P.data() )) $P = false; if ($C && $.isEmptyObject( $C.data() )) $C = false; if ($R && $.isEmptyObject( $R.data() )) $R = false; if ($T && $.isEmptyObject( $T.data() )) $T = false; if ($P) $P.stop(true, true); var o = options[pane] , s = state[pane] , d = "layout" , css = "layoutCSS" , pC = children[pane] , hasChildren = $.isPlainObject( pC ) && !$.isEmptyObject( pC ) , destroy = destroyChild !== undefined ? destroyChild : o.destroyChildren ; // FIRST destroy the child-layout(s) if (hasChildren && destroy) { $.each( pC, function (key, child) { if (!child.destroyed) child.destroy(true);// tell child-layout to destroy ALL its child-layouts too if (child.destroyed) // destroy was successful delete pC[key]; }); // if no more children, remove the children hash if ($.isEmptyObject( pC )) { pC = children[pane] = null; // clear children hash hasChildren = false; } } // Note: can't 'remove' a pane element with non-destroyed children if ($P && remove && !hasChildren) $P.remove(); // remove the pane-element and everything inside it else if ($P && $P[0]) { // create list of ALL pane-classes that need to be removed var root = o.paneClass // default="ui-layout-pane" , pRoot = root +"-"+ pane // eg: "ui-layout-pane-west" , _open = "-open" , _sliding= "-sliding" , _closed = "-closed" , classes = [ root, root+_open, root+_closed, root+_sliding, // generic classes pRoot, pRoot+_open, pRoot+_closed, pRoot+_sliding ] // pane-specific classes ; $.merge(classes, getHoverClasses($P, true)); // ADD hover-classes // remove all Layout classes from pane-element $P .removeClass( classes.join(" ") ) // remove ALL pane-classes .removeData("parentLayout") .removeData("layoutPane") .removeData("layoutRole") .removeData("layoutEdge") .removeData("autoHidden") // in case set .unbind("."+ sID) // remove ALL Layout events // TODO: remove these extra unbind commands when jQuery is fixed //.unbind("mouseenter"+ sID) //.unbind("mouseleave"+ sID) ; // do NOT reset CSS if this pane/content is STILL the container of a nested layout! // the nested layout will reset its 'container' CSS when/if it is destroyed if (hasChildren && $C) { // a content-div may not have a specific width, so give it one to contain the Layout $C.width( $C.width() ); $.each( pC, function (key, child) { child.resizeAll(); // resize the Layout }); } else if ($C) $C.css( $C.data(css) ).removeData(css).removeData("layoutRole"); // remove pane AFTER content in case there was a nested layout if (!$P.data(d)) $P.css( $P.data(css) ).removeData(css); } // REMOVE pane resizer and toggler elements if ($T) $T.remove(); if ($R) $R.remove(); // CLEAR all pointers and state data Instance[pane] = $Ps[pane] = $Cs[pane] = $Rs[pane] = $Ts[pane] = false; s = { removed: true }; if (!skipResize) resizeAll(); } /* * ########################### * ACTION METHODS * ########################### */ /** * @param {string} pane */ , _hidePane = function (pane) { var $P = $Ps[pane] , o = options[pane] , s = $P[0].style ; if (o.useOffscreenClose) { if (!$P.data(_c.offscreenReset)) $P.data(_c.offscreenReset, { left: s.left, right: s.right }); $P.css( _c.offscreenCSS ); } else $P.hide().removeData(_c.offscreenReset); } /** * @param {string} pane */ , _showPane = function (pane) { var $P = $Ps[pane] , o = options[pane] , off = _c.offscreenCSS , old = $P.data(_c.offscreenReset) , s = $P[0].style ; $P .show() // ALWAYS show, just in case .removeData(_c.offscreenReset); if (o.useOffscreenClose && old) { if (s.left == off.left) s.left = old.left; if (s.right == off.right) s.right = old.right; } } /** * Completely 'hides' a pane, including its spacing - as if it does not exist * The pane is not actually 'removed' from the source, so can use 'show' to un-hide it * * @param {(string|Object)} evt_or_pane The pane being hidden, ie: north, south, east, or west * @param {boolean=} [noAnimation=false] */ , hide = function (evt_or_pane, noAnimation) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] ; if (!$P || s.isHidden) return; // pane does not exist OR is already hidden // onhide_start callback - will CANCEL hide if returns false if (state.initialized && false === _runCallbacks("onhide_start", pane)) return; s.isSliding = false; // just in case delete state.panesSliding[pane]; // now hide the elements if ($R) $R.hide(); // hide resizer-bar if (!state.initialized || s.isClosed) { s.isClosed = true; // to trigger open-animation on show() s.isHidden = true; s.isVisible = false; if (!state.initialized) _hidePane(pane); // no animation when loading page sizeMidPanes(_c[pane].dir === "horz" ? "" : "center"); if (state.initialized || o.triggerEventsOnLoad) _runCallbacks("onhide_end", pane); } else { s.isHiding = true; // used by onclose close(pane, false, noAnimation); // adjust all panes to fit } } /** * Show a hidden pane - show as 'closed' by default unless openPane = true * * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west * @param {boolean=} [openPane=false] * @param {boolean=} [noAnimation=false] * @param {boolean=} [noAlert=false] */ , show = function (evt_or_pane, openPane, noAnimation, noAlert) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] ; if (!$P || !s.isHidden) return; // pane does not exist OR is not hidden // onshow_start callback - will CANCEL show if returns false if (false === _runCallbacks("onshow_start", pane)) return; s.isShowing = true; // used by onopen/onclose //s.isHidden = false; - will be set by open/close - if not cancelled s.isSliding = false; // just in case delete state.panesSliding[pane]; // now show the elements //if ($R) $R.show(); - will be shown by open/close if (openPane === false) close(pane, true); // true = force else open(pane, false, noAnimation, noAlert); // adjust all panes to fit } /** * Toggles a pane open/closed by calling either open or close * * @param {(string|Object)} evt_or_pane The pane being toggled, ie: north, south, east, or west * @param {boolean=} [slide=false] */ , toggle = function (evt_or_pane, slide) { if (!isInitialized()) return; var evt = evtObj(evt_or_pane) , pane = evtPane.call(this, evt_or_pane) , s = state[pane] ; if (evt) // called from to $R.dblclick OR triggerPaneEvent evt.stopImmediatePropagation(); if (s.isHidden) show(pane); // will call 'open' after unhiding it else if (s.isClosed) open(pane, !!slide); else close(pane); } /** * Utility method used during init or other auto-processes * * @param {string} pane The pane being closed * @param {boolean=} [setHandles=false] */ , _closePane = function (pane, setHandles) { var $P = $Ps[pane] , s = state[pane] ; _hidePane(pane); s.isClosed = true; s.isVisible = false; if (setHandles) setAsClosed(pane); } /** * Close the specified pane (animation optional), and resize all other panes as needed * * @param {(string|Object)} evt_or_pane The pane being closed, ie: north, south, east, or west * @param {boolean=} [force=false] * @param {boolean=} [noAnimation=false] * @param {boolean=} [skipCallback=false] */ , close = function (evt_or_pane, force, noAnimation, skipCallback) { var pane = evtPane.call(this, evt_or_pane); // if pane has been initialized, but NOT the complete layout, close pane instantly if (!state.initialized && $Ps[pane]) { _closePane(pane, true); // INIT pane as closed return; } if (!isInitialized()) return; var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , c = _c[pane] , doFX, isShowing, isHiding, wasSliding; // QUEUE in case another action/animation is in progress $N.queue(function( queueNext ){ if ( !$P || (!o.closable && !s.isShowing && !s.isHiding) // invalid request // (!o.resizable && !o.closable) ??? || (!force && s.isClosed && !s.isShowing) // already closed ) return queueNext(); // onclose_start callback - will CANCEL hide if returns false // SKIP if just 'showing' a hidden pane as 'closed' var abort = !s.isShowing && false === _runCallbacks("onclose_start", pane); // transfer logic vars to temp vars isShowing = s.isShowing; isHiding = s.isHiding; wasSliding = s.isSliding; // now clear the logic vars (REQUIRED before aborting) delete s.isShowing; delete s.isHiding; if (abort) return queueNext(); doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none"); s.isMoving = true; s.isClosed = true; s.isVisible = false; // update isHidden BEFORE sizing panes if (isHiding) s.isHidden = true; else if (isShowing) s.isHidden = false; if (s.isSliding) // pane is being closed, so UNBIND trigger events bindStopSlidingEvents(pane, false); // will set isSliding=false else // resize panes adjacent to this one sizeMidPanes(_c[pane].dir === "horz" ? "" : "center", false); // false = NOT skipCallback // if this pane has a resizer bar, move it NOW - before animation setAsClosed(pane); // CLOSE THE PANE if (doFX) { // animate the close lockPaneForFX(pane, true); // need to set left/top so animation will work $P.hide( o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () { lockPaneForFX(pane, false); // undo if (s.isClosed) close_2(); queueNext(); }); } else { // hide the pane without animation _hidePane(pane); close_2(); queueNext(); }; }); // SUBROUTINE function close_2 () { s.isMoving = false; bindStartSlidingEvents(pane, true); // will enable if o.slidable = true // if opposite-pane was autoClosed, see if it can be autoOpened now var altPane = _c.oppositeEdge[pane]; if (state[ altPane ].noRoom) { setSizeLimits( altPane ); makePaneFit( altPane ); } if (!skipCallback && (state.initialized || o.triggerEventsOnLoad)) { // onclose callback - UNLESS just 'showing' a hidden pane as 'closed' if (!isShowing) _runCallbacks("onclose_end", pane); // onhide OR onshow callback if (isShowing) _runCallbacks("onshow_end", pane); if (isHiding) _runCallbacks("onhide_end", pane); } } } /** * @param {string} pane The pane just closed, ie: north, south, east, or west */ , setAsClosed = function (pane) { if (!$Rs[pane]) return; // handles not initialized yet! var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side , rClass = o.resizerClass , tClass = o.togglerClass , _pane = "-"+ pane // used for classNames , _open = "-open" , _sliding= "-sliding" , _closed = "-closed" ; $R .css(side, sC.inset[side]) // move the resizer .removeClass( rClass+_open +" "+ rClass+_pane+_open ) .removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) .addClass( rClass+_closed +" "+ rClass+_pane+_closed ) ; // DISABLE 'resizing' when closed - do this BEFORE bindStartSlidingEvents? if (o.resizable && $.layout.plugins.draggable) $R .draggable("disable") .removeClass("ui-state-disabled") // do NOT apply disabled styling - not suitable here .css("cursor", "default") .attr("title","") ; // if pane has a toggler button, adjust that too if ($T) { $T .removeClass( tClass+_open +" "+ tClass+_pane+_open ) .addClass( tClass+_closed +" "+ tClass+_pane+_closed ) .attr("title", o.tips.Open) // may be blank ; // toggler-content - if exists $T.children(".content-open").hide(); $T.children(".content-closed").css("display","block"); } // sync any 'pin buttons' syncPinBtns(pane, false); if (state.initialized) { // resize 'length' and position togglers for adjacent panes sizeHandles(); } } /** * Open the specified pane (animation optional), and resize all other panes as needed * * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west * @param {boolean=} [slide=false] * @param {boolean=} [noAnimation=false] * @param {boolean=} [noAlert=false] */ , open = function (evt_or_pane, slide, noAnimation, noAlert) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , c = _c[pane] , doFX, isShowing ; // QUEUE in case another action/animation is in progress $N.queue(function( queueNext ){ if ( !$P || (!o.resizable && !o.closable && !s.isShowing) // invalid request || (s.isVisible && !s.isSliding) // already open ) return queueNext(); // pane can ALSO be unhidden by just calling show(), so handle this scenario if (s.isHidden && !s.isShowing) { queueNext(); // call before show() because it needs the queue free show(pane, true); return; } if (s.autoResize && s.size != o.size) // resize pane to original size set in options sizePane(pane, o.size, true, true, true); // true=skipCallback/noAnimation/forceResize else // make sure there is enough space available to open the pane setSizeLimits(pane, slide); // onopen_start callback - will CANCEL open if returns false var cbReturn = _runCallbacks("onopen_start", pane); if (cbReturn === "abort") return queueNext(); // update pane-state again in case options were changed in onopen_start if (cbReturn !== "NC") // NC = "No Callback" setSizeLimits(pane, slide); if (s.minSize > s.maxSize) { // INSUFFICIENT ROOM FOR PANE TO OPEN! syncPinBtns(pane, false); // make sure pin-buttons are reset if (!noAlert && o.tips.noRoomToOpen) alert(o.tips.noRoomToOpen); return queueNext(); // ABORT } if (slide) // START Sliding - will set isSliding=true bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane else if (s.isSliding) // PIN PANE (stop sliding) - open pane 'normally' instead bindStopSlidingEvents(pane, false); // UNBIND trigger events - will set isSliding=false else if (o.slidable) bindStartSlidingEvents(pane, false); // UNBIND trigger events s.noRoom = false; // will be reset by makePaneFit if 'noRoom' makePaneFit(pane); // transfer logic var to temp var isShowing = s.isShowing; // now clear the logic var delete s.isShowing; doFX = !noAnimation && s.isClosed && (o.fxName_open != "none"); s.isMoving = true; s.isVisible = true; s.isClosed = false; // update isHidden BEFORE sizing panes - WHY??? Old? if (isShowing) s.isHidden = false; if (doFX) { // ANIMATE // mask adjacent panes with objects lockPaneForFX(pane, true); // need to set left/top so animation will work $P.show( o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function() { lockPaneForFX(pane, false); // undo if (s.isVisible) open_2(); // continue queueNext(); }); } else { // no animation _showPane(pane);// just show pane and... open_2(); // continue queueNext(); }; }); // SUBROUTINE function open_2 () { s.isMoving = false; // cure iframe display issues _fixIframe(pane); // NOTE: if isSliding, then other panes are NOT 'resized' if (!s.isSliding) { // resize all panes adjacent to this one sizeMidPanes(_c[pane].dir=="vert" ? "center" : "", false); // false = NOT skipCallback } // set classes, position handles and execute callbacks... setAsOpen(pane); }; } /** * @param {string} pane The pane just opened, ie: north, south, east, or west * @param {boolean=} [skipCallback=false] */ , setAsOpen = function (pane, skipCallback) { var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side , rClass = o.resizerClass , tClass = o.togglerClass , _pane = "-"+ pane // used for classNames , _open = "-open" , _closed = "-closed" , _sliding= "-sliding" ; $R .css(side, sC.inset[side] + getPaneSize(pane)) // move the resizer .removeClass( rClass+_closed +" "+ rClass+_pane+_closed ) .addClass( rClass+_open +" "+ rClass+_pane+_open ) ; if (s.isSliding) $R.addClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) else // in case 'was sliding' $R.removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) removeHover( 0, $R ); // remove hover classes if (o.resizable && $.layout.plugins.draggable) $R .draggable("enable") .css("cursor", o.resizerCursor) .attr("title", o.tips.Resize); else if (!s.isSliding) $R.css("cursor", "default"); // n-resize, s-resize, etc // if pane also has a toggler button, adjust that too if ($T) { $T .removeClass( tClass+_closed +" "+ tClass+_pane+_closed ) .addClass( tClass+_open +" "+ tClass+_pane+_open ) .attr("title", o.tips.Close); // may be blank removeHover( 0, $T ); // remove hover classes // toggler-content - if exists $T.children(".content-closed").hide(); $T.children(".content-open").css("display","block"); } // sync any 'pin buttons' syncPinBtns(pane, !s.isSliding); // update pane-state dimensions - BEFORE resizing content $.extend(s, elDims($P)); if (state.initialized) { // resize resizer & toggler sizes for all panes sizeHandles(); // resize content every time pane opens - to be sure sizeContent(pane, true); // true = remeasure headers/footers, even if 'pane.isMoving' } if (!skipCallback && (state.initialized || o.triggerEventsOnLoad) && $P.is(":visible")) { // onopen callback _runCallbacks("onopen_end", pane); // onshow callback - TODO: should this be here? if (s.isShowing) _runCallbacks("onshow_end", pane); // ALSO call onresize because layout-size *may* have changed while pane was closed if (state.initialized) _runCallbacks("onresize_end", pane); } // TODO: Somehow sizePane("north") is being called after this point??? } /** * slideOpen / slideClose / slideToggle * * Pass-though methods for sliding */ , slideOpen = function (evt_or_pane) { if (!isInitialized()) return; var evt = evtObj(evt_or_pane) , pane = evtPane.call(this, evt_or_pane) , s = state[pane] , delay = options[pane].slideDelay_open ; // prevent event from triggering on NEW resizer binding created below if (evt) evt.stopImmediatePropagation(); if (s.isClosed && evt && evt.type === "mouseenter" && delay > 0) // trigger = mouseenter - use a delay timer.set(pane+"_openSlider", open_NOW, delay); else open_NOW(); // will unbind events if is already open /** * SUBROUTINE for timed open */ function open_NOW () { if (!s.isClosed) // skip if no longer closed! bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane else if (!s.isMoving) open(pane, true); // true = slide - open() will handle binding }; } , slideClose = function (evt_or_pane) { if (!isInitialized()) return; var evt = evtObj(evt_or_pane) , pane = evtPane.call(this, evt_or_pane) , o = options[pane] , s = state[pane] , delay = s.isMoving ? 1000 : 300 // MINIMUM delay - option may override ; if (s.isClosed || s.isResizing) return; // skip if already closed OR in process of resizing else if (o.slideTrigger_close === "click") close_NOW(); // close immediately onClick else if (o.preventQuickSlideClose && s.isMoving) return; // handle Chrome quick-close on slide-open else if (o.preventPrematureSlideClose && evt && $.layout.isMouseOverElem(evt, $Ps[pane])) return; // handle incorrect mouseleave trigger, like when over a SELECT-list in IE else if (evt) // trigger = mouseleave - use a delay // 1 sec delay if 'opening', else .3 sec timer.set(pane+"_closeSlider", close_NOW, max(o.slideDelay_close, delay)); else // called programically close_NOW(); /** * SUBROUTINE for timed close */ function close_NOW () { if (s.isClosed) // skip 'close' if already closed! bindStopSlidingEvents(pane, false); // UNBIND trigger events - TODO: is this needed here? else if (!s.isMoving) close(pane); // close will handle unbinding }; } /** * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west */ , slideToggle = function (evt_or_pane) { var pane = evtPane.call(this, evt_or_pane); toggle(pane, true); } /** * Must set left/top on East/South panes so animation will work properly * * @param {string} pane The pane to lock, 'east' or 'south' - any other is ignored! * @param {boolean} doLock true = set left/top, false = remove */ , lockPaneForFX = function (pane, doLock) { var $P = $Ps[pane] , s = state[pane] , o = options[pane] , z = options.zIndexes ; if (doLock) { showMasks( pane, { animation: true, objectsOnly: true }); $P.css({ zIndex: z.pane_animate }); // overlay all elements during animation if (pane=="south") $P.css({ top: sC.inset.top + sC.innerHeight - $P.outerHeight() }); else if (pane=="east") $P.css({ left: sC.inset.left + sC.innerWidth - $P.outerWidth() }); } else { // animation DONE - RESET CSS hideMasks(); $P.css({ zIndex: (s.isSliding ? z.pane_sliding : z.pane_normal) }); if (pane=="south") $P.css({ top: "auto" }); // if pane is positioned 'off-screen', then DO NOT screw with it! else if (pane=="east" && !$P.css("left").match(/\-99999/)) $P.css({ left: "auto" }); // fix anti-aliasing in IE - only needed for animations that change opacity if (browser.msie && o.fxOpacityFix && o.fxName_open != "slide" && $P.css("filter") && $P.css("opacity") == 1) $P[0].style.removeAttribute('filter'); } } /** * Toggle sliding functionality of a specific pane on/off by adding removing 'slide open' trigger * * @see open(), close() * @param {string} pane The pane to enable/disable, 'north', 'south', etc. * @param {boolean} enable Enable or Disable sliding? */ , bindStartSlidingEvents = function (pane, enable) { var o = options[pane] , $P = $Ps[pane] , $R = $Rs[pane] , evtName = o.slideTrigger_open.toLowerCase() ; if (!$R || (enable && !o.slidable)) return; // make sure we have a valid event if (evtName.match(/mouseover/)) evtName = o.slideTrigger_open = "mouseenter"; else if (!evtName.match(/(click|dblclick|mouseenter)/)) evtName = o.slideTrigger_open = "click"; // must remove double-click-toggle when using dblclick-slide if (o.resizerDblClickToggle && evtName.match(/click/)) { $R[enable ? "unbind" : "bind"]('dblclick.'+ sID, toggle) } $R // add or remove event [enable ? "bind" : "unbind"](evtName +'.'+ sID, slideOpen) // set the appropriate cursor & title/tip .css("cursor", enable ? o.sliderCursor : "default") .attr("title", enable ? o.tips.Slide : "") ; } /** * Add or remove 'mouseleave' events to 'slide close' when pane is 'sliding' open or closed * Also increases zIndex when pane is sliding open * See bindStartSlidingEvents for code to control 'slide open' * * @see slideOpen(), slideClose() * @param {string} pane The pane to process, 'north', 'south', etc. * @param {boolean} enable Enable or Disable events? */ , bindStopSlidingEvents = function (pane, enable) { var o = options[pane] , s = state[pane] , c = _c[pane] , z = options.zIndexes , evtName = o.slideTrigger_close.toLowerCase() , action = (enable ? "bind" : "unbind") , $P = $Ps[pane] , $R = $Rs[pane] ; timer.clear(pane+"_closeSlider"); // just in case if (enable) { s.isSliding = true; state.panesSliding[pane] = true; // remove 'slideOpen' event from resizer // ALSO will raise the zIndex of the pane & resizer bindStartSlidingEvents(pane, false); } else { s.isSliding = false; delete state.panesSliding[pane]; } // RE/SET zIndex - increases when pane is sliding-open, resets to normal when not $P.css("zIndex", enable ? z.pane_sliding : z.pane_normal); $R.css("zIndex", enable ? z.pane_sliding+2 : z.resizer_normal); // NOTE: mask = pane_sliding+1 // make sure we have a valid event if (!evtName.match(/(click|mouseleave)/)) evtName = o.slideTrigger_close = "mouseleave"; // also catches 'mouseout' // add/remove slide triggers $R[action](evtName, slideClose); // base event on resize // need extra events for mouseleave if (evtName === "mouseleave") { // also close on pane.mouseleave $P[action]("mouseleave."+ sID, slideClose); // cancel timer when mouse moves between 'pane' and 'resizer' $R[action]("mouseenter."+ sID, cancelMouseOut); $P[action]("mouseenter."+ sID, cancelMouseOut); } if (!enable) timer.clear(pane+"_closeSlider"); else if (evtName === "click" && !o.resizable) { // IF pane is not resizable (which already has a cursor and tip) // then set the a cursor & title/tip on resizer when sliding $R.css("cursor", enable ? o.sliderCursor : "default"); $R.attr("title", enable ? o.tips.Close : ""); // use Toggler-tip, eg: "Close Pane" } // SUBROUTINE for mouseleave timer clearing function cancelMouseOut (evt) { timer.clear(pane+"_closeSlider"); evt.stopPropagation(); } } /** * Hides/closes a pane if there is insufficient room - reverses this when there is room again * MUST have already called setSizeLimits() before calling this method * * @param {string} pane The pane being resized * @param {boolean=} [isOpening=false] Called from onOpen? * @param {boolean=} [skipCallback=false] Should the onresize callback be run? * @param {boolean=} [force=false] */ , makePaneFit = function (pane, isOpening, skipCallback, force) { var o = options[pane] , s = state[pane] , c = _c[pane] , $P = $Ps[pane] , $R = $Rs[pane] , isSidePane = c.dir==="vert" , hasRoom = false ; // special handling for center & east/west panes if (pane === "center" || (isSidePane && s.noVerticalRoom)) { // see if there is enough room to display the pane // ERROR: hasRoom = s.minHeight <= s.maxHeight && (isSidePane || s.minWidth <= s.maxWidth); hasRoom = (s.maxHeight >= 0); if (hasRoom && s.noRoom) { // previously hidden due to noRoom, so show now _showPane(pane); if ($R) $R.show(); s.isVisible = true; s.noRoom = false; if (isSidePane) s.noVerticalRoom = false; _fixIframe(pane); } else if (!hasRoom && !s.noRoom) { // not currently hidden, so hide now _hidePane(pane); if ($R) $R.hide(); s.isVisible = false; s.noRoom = true; } } // see if there is enough room to fit the border-pane if (pane === "center") { // ignore center in this block } else if (s.minSize <= s.maxSize) { // pane CAN fit hasRoom = true; if (s.size > s.maxSize) // pane is too big - shrink it sizePane(pane, s.maxSize, skipCallback, true, force); // true = noAnimation else if (s.size < s.minSize) // pane is too small - enlarge it sizePane(pane, s.minSize, skipCallback, true, force); // true = noAnimation // need s.isVisible because new pseudoClose method keeps pane visible, but off-screen else if ($R && s.isVisible && $P.is(":visible")) { // make sure resizer-bar is positioned correctly // handles situation where nested layout was 'hidden' when initialized var pos = s.size + sC.inset[c.side]; if ($.layout.cssNum( $R, c.side ) != pos) $R.css( c.side, pos ); } // if was previously hidden due to noRoom, then RESET because NOW there is room if (s.noRoom) { // s.noRoom state will be set by open or show if (s.wasOpen && o.closable) { if (o.autoReopen) open(pane, false, true, true); // true = noAnimation, true = noAlert else // leave the pane closed, so just update state s.noRoom = false; } else show(pane, s.wasOpen, true, true); // true = noAnimation, true = noAlert } } else { // !hasRoom - pane CANNOT fit if (!s.noRoom) { // pane not set as noRoom yet, so hide or close it now... s.noRoom = true; // update state s.wasOpen = !s.isClosed && !s.isSliding; if (s.isClosed){} // SKIP else if (o.closable) // 'close' if possible close(pane, true, true); // true = force, true = noAnimation else // 'hide' pane if cannot just be closed hide(pane, true); // true = noAnimation } } } /** * manualSizePane is an exposed flow-through method allowing extra code when pane is 'manually resized' * * @param {(string|Object)} evt_or_pane The pane being resized * @param {number} size The *desired* new size for this pane - will be validated * @param {boolean=} [skipCallback=false] Should the onresize callback be run? * @param {boolean=} [noAnimation=false] * @param {boolean=} [force=false] Force resizing even if does not seem necessary */ , manualSizePane = function (evt_or_pane, size, skipCallback, noAnimation, force) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , o = options[pane] , s = state[pane] // if resizing callbacks have been delayed and resizing is now DONE, force resizing to complete... , forceResize = force || (o.livePaneResizing && !s.isResizing) ; // ANY call to manualSizePane disables autoResize - ie, percentage sizing s.autoResize = false; // flow-through... sizePane(pane, size, skipCallback, noAnimation, forceResize); // will animate resize if option enabled } /** * sizePane is called only by internal methods whenever a pane needs to be resized * * @param {(string|Object)} evt_or_pane The pane being resized * @param {number} size The *desired* new size for this pane - will be validated * @param {boolean=} [skipCallback=false] Should the onresize callback be run? * @param {boolean=} [noAnimation=false] * @param {boolean=} [force=false] Force resizing even if does not seem necessary */ , sizePane = function (evt_or_pane, size, skipCallback, noAnimation, force) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) // probably NEVER called from event? , o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , side = _c[pane].side , dimName = _c[pane].sizeType.toLowerCase() , skipResizeWhileDragging = s.isResizing && !o.triggerEventsDuringLiveResize , doFX = noAnimation !== true && o.animatePaneSizing , oldSize, newSize ; // QUEUE in case another action/animation is in progress $N.queue(function( queueNext ){ // calculate 'current' min/max sizes setSizeLimits(pane); // update pane-state oldSize = s.size; size = _parseSize(pane, size); // handle percentages & auto size = max(size, _parseSize(pane, o.minSize)); size = min(size, s.maxSize); if (size < s.minSize) { // not enough room for pane! queueNext(); // call before makePaneFit() because it needs the queue free makePaneFit(pane, false, skipCallback); // will hide or close pane return; } // IF newSize is same as oldSize, then nothing to do - abort if (!force && size === oldSize) return queueNext(); s.newSize = size; // onresize_start callback CANNOT cancel resizing because this would break the layout! if (!skipCallback && state.initialized && s.isVisible) _runCallbacks("onresize_start", pane); // resize the pane, and make sure its visible newSize = cssSize(pane, size); if (doFX && $P.is(":visible")) { // ANIMATE var fx = $.layout.effects.size[pane] || $.layout.effects.size.all , easing = o.fxSettings_size.easing || fx.easing , z = options.zIndexes , props = {}; props[ dimName ] = newSize +'px'; s.isMoving = true; // overlay all elements during animation $P.css({ zIndex: z.pane_animate }) .show().animate( props, o.fxSpeed_size, easing, function(){ // reset zIndex after animation $P.css({ zIndex: (s.isSliding ? z.pane_sliding : z.pane_normal) }); s.isMoving = false; delete s.newSize; sizePane_2(); // continue queueNext(); }); } else { // no animation $P.css( dimName, newSize ); // resize pane delete s.newSize; // if pane is visible, then if ($P.is(":visible")) sizePane_2(); // continue else { // pane is NOT VISIBLE, so just update state data... // when pane is *next opened*, it will have the new size s.size = size; // update state.size $.extend(s, elDims($P)); // update state dimensions } queueNext(); }; }); // SUBROUTINE function sizePane_2 () { /* Panes are sometimes not sized precisely in some browsers!? * This code will resize the pane up to 3 times to nudge the pane to the correct size */ var actual = dimName==='width' ? $P.outerWidth() : $P.outerHeight() , tries = [{ pane: pane , count: 1 , target: size , actual: actual , correct: (size === actual) , attempt: size , cssSize: newSize }] , lastTry = tries[0] , thisTry = {} , msg = 'Inaccurate size after resizing the '+ pane +'-pane.' ; while ( !lastTry.correct ) { thisTry = { pane: pane, count: lastTry.count+1, target: size }; if (lastTry.actual > size) thisTry.attempt = max(0, lastTry.attempt - (lastTry.actual - size)); else // lastTry.actual < size thisTry.attempt = max(0, lastTry.attempt + (size - lastTry.actual)); thisTry.cssSize = cssSize(pane, thisTry.attempt); $P.css( dimName, thisTry.cssSize ); thisTry.actual = dimName=='width' ? $P.outerWidth() : $P.outerHeight(); thisTry.correct = (size === thisTry.actual); // log attempts and alert the user of this *non-fatal error* (if showDebugMessages) if ( tries.length === 1) { _log(msg, false, true); _log(lastTry, false, true); } _log(thisTry, false, true); // after 4 tries, is as close as its gonna get! if (tries.length > 3) break; tries.push( thisTry ); lastTry = tries[ tries.length - 1 ]; } // END TESTING CODE // update pane-state dimensions s.size = size; $.extend(s, elDims($P)); if (s.isVisible && $P.is(":visible")) { // reposition the resizer-bar if ($R) $R.css( side, size + sC.inset[side] ); // resize the content-div sizeContent(pane); } if (!skipCallback && !skipResizeWhileDragging && state.initialized && s.isVisible) _runCallbacks("onresize_end", pane); // resize all the adjacent panes, and adjust their toggler buttons // when skipCallback passed, it means the controlling method will handle 'other panes' if (!skipCallback) { // also no callback if live-resize is in progress and NOT triggerEventsDuringLiveResize if (!s.isSliding) sizeMidPanes(_c[pane].dir=="horz" ? "" : "center", skipResizeWhileDragging, force); sizeHandles(); } // if opposite-pane was autoClosed, see if it can be autoOpened now var altPane = _c.oppositeEdge[pane]; if (size < oldSize && state[ altPane ].noRoom) { setSizeLimits( altPane ); makePaneFit( altPane, false, skipCallback ); } // DEBUG - ALERT user/developer so they know there was a sizing problem if (tries.length > 1) _log(msg +'\nSee the Error Console for details.', true, true); } } /** * @see initPanes(), sizePane(), resizeAll(), open(), close(), hide() * @param {(Array.<string>|string)} panes The pane(s) being resized, comma-delmited string * @param {boolean=} [skipCallback=false] Should the onresize callback be run? * @param {boolean=} [force=false] */ , sizeMidPanes = function (panes, skipCallback, force) { panes = (panes ? panes : "east,west,center").split(","); $.each(panes, function (i, pane) { if (!$Ps[pane]) return; // NO PANE - skip var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , isCenter= (pane=="center") , hasRoom = true , CSS = {} // if pane is not visible, show it invisibly NOW rather than for *each call* in this script , visCSS = $.layout.showInvisibly($P) , newCenter = calcNewCenterPaneDims() ; // update pane-state dimensions $.extend(s, elDims($P)); if (pane === "center") { if (!force && s.isVisible && newCenter.width === s.outerWidth && newCenter.height === s.outerHeight) { $P.css(visCSS); return true; // SKIP - pane already the correct size } // set state for makePaneFit() logic $.extend(s, cssMinDims(pane), { maxWidth: newCenter.width , maxHeight: newCenter.height }); CSS = newCenter; s.newWidth = CSS.width; s.newHeight = CSS.height; // convert OUTER width/height to CSS width/height CSS.width = cssW($P, CSS.width); // NEW - allow pane to extend 'below' visible area rather than hide it CSS.height = cssH($P, CSS.height); hasRoom = CSS.width >= 0 && CSS.height >= 0; // height >= 0 = ALWAYS TRUE NOW // during layout init, try to shrink east/west panes to make room for center if (!state.initialized && o.minWidth > newCenter.width) { var reqPx = o.minWidth - s.outerWidth , minE = options.east.minSize || 0 , minW = options.west.minSize || 0 , sizeE = state.east.size , sizeW = state.west.size , newE = sizeE , newW = sizeW ; if (reqPx > 0 && state.east.isVisible && sizeE > minE) { newE = max( sizeE-minE, sizeE-reqPx ); reqPx -= sizeE-newE; } if (reqPx > 0 && state.west.isVisible && sizeW > minW) { newW = max( sizeW-minW, sizeW-reqPx ); reqPx -= sizeW-newW; } // IF we found enough extra space, then resize the border panes as calculated if (reqPx === 0) { if (sizeE && sizeE != minE) sizePane('east', newE, true, true, force); // true = skipCallback/noAnimation - initPanes will handle when done if (sizeW && sizeW != minW) sizePane('west', newW, true, true, force); // true = skipCallback/noAnimation // now start over! sizeMidPanes('center', skipCallback, force); $P.css(visCSS); return; // abort this loop } } } else { // for east and west, set only the height, which is same as center height // set state.min/maxWidth/Height for makePaneFit() logic if (s.isVisible && !s.noVerticalRoom) $.extend(s, elDims($P), cssMinDims(pane)) if (!force && !s.noVerticalRoom && newCenter.height === s.outerHeight) { $P.css(visCSS); return true; // SKIP - pane already the correct size } // east/west have same top, bottom & height as center CSS.top = newCenter.top; CSS.bottom = newCenter.bottom; s.newSize = newCenter.height // NEW - allow pane to extend 'below' visible area rather than hide it CSS.height = cssH($P, newCenter.height); s.maxHeight = CSS.height; hasRoom = (s.maxHeight >= 0); // ALWAYS TRUE NOW if (!hasRoom) s.noVerticalRoom = true; // makePaneFit() logic } if (hasRoom) { // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized if (!skipCallback && state.initialized) _runCallbacks("onresize_start", pane); $P.css(CSS); // apply the CSS to pane if (pane !== "center") sizeHandles(pane); // also update resizer length if (s.noRoom && !s.isClosed && !s.isHidden) makePaneFit(pane); // will re-open/show auto-closed/hidden pane if (s.isVisible) { $.extend(s, elDims($P)); // update pane dimensions if (state.initialized) sizeContent(pane); // also resize the contents, if exists } } else if (!s.noRoom && s.isVisible) // no room for pane makePaneFit(pane); // will hide or close pane // reset visibility, if necessary $P.css(visCSS); delete s.newSize; delete s.newWidth; delete s.newHeight; if (!s.isVisible) return true; // DONE - next pane /* * Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes * Normally these panes have only 'left' & 'right' positions so pane auto-sizes * ALSO required when pane is an IFRAME because will NOT default to 'full width' * TODO: Can I use width:100% for a north/south iframe? * TODO: Sounds like a job for $P.outerWidth( sC.innerWidth ) SETTER METHOD */ if (pane === "center") { // finished processing midPanes var fix = browser.isIE6 || !browser.boxModel; if ($Ps.north && (fix || state.north.tagName=="IFRAME")) $Ps.north.css("width", cssW($Ps.north, sC.innerWidth)); if ($Ps.south && (fix || state.south.tagName=="IFRAME")) $Ps.south.css("width", cssW($Ps.south, sC.innerWidth)); } // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized if (!skipCallback && state.initialized) _runCallbacks("onresize_end", pane); }); } /** * @see window.onresize(), callbacks or custom code * @param {(Object|boolean)=} evt_or_refresh If 'true', then also reset pane-positioning */ , resizeAll = function (evt_or_refresh) { var oldW = sC.innerWidth , oldH = sC.innerHeight ; // stopPropagation if called by trigger("layoutdestroy") - use evtPane utility evtPane(evt_or_refresh); // cannot size layout when 'container' is hidden or collapsed if (!$N.is(":visible")) return; if (!state.initialized) { _initLayoutElements(); return; // no need to resize since we just initialized! } if (evt_or_refresh === true && $.isPlainObject(options.outset)) { // update container CSS in case outset option has changed $N.css( options.outset ); } // UPDATE container dimensions $.extend(sC, elDims( $N, options.inset )); if (!sC.outerHeight) return; // if 'true' passed, refresh pane & handle positioning too if (evt_or_refresh === true) { setPanePosition(); } // onresizeall_start will CANCEL resizing if returns false // state.container has already been set, so user can access this info for calcuations if (false === _runCallbacks("onresizeall_start")) return false; var // see if container is now 'smaller' than before shrunkH = (sC.innerHeight < oldH) , shrunkW = (sC.innerWidth < oldW) , $P, o, s ; // NOTE special order for sizing: S-N-E-W $.each(["south","north","east","west"], function (i, pane) { if (!$Ps[pane]) return; // no pane - SKIP o = options[pane]; s = state[pane]; if (s.autoResize && s.size != o.size) // resize pane to original size set in options sizePane(pane, o.size, true, true, true); // true=skipCallback/noAnimation/forceResize else { setSizeLimits(pane); makePaneFit(pane, false, true, true); // true=skipCallback/forceResize } }); sizeMidPanes("", true, true); // true=skipCallback/forceResize sizeHandles(); // reposition the toggler elements // trigger all individual pane callbacks AFTER layout has finished resizing $.each(_c.allPanes, function (i, pane) { $P = $Ps[pane]; if (!$P) return; // SKIP if (state[pane].isVisible) // undefined for non-existent panes _runCallbacks("onresize_end", pane); // callback - if exists }); _runCallbacks("onresizeall_end"); //_triggerLayoutEvent(pane, 'resizeall'); } /** * Whenever a pane resizes or opens that has a nested layout, trigger resizeAll * * @param {(string|Object)} evt_or_pane The pane just resized or opened */ , resizeChildren = function (evt_or_pane, skipRefresh) { var pane = evtPane.call(this, evt_or_pane); if (!options[pane].resizeChildren) return; // ensure the pane-children are up-to-date if (!skipRefresh) refreshChildren( pane ); var pC = children[pane]; if ($.isPlainObject( pC )) { // resize one or more children $.each( pC, function (key, child) { if (!child.destroyed) child.resizeAll(); }); } } /** * IF pane has a content-div, then resize all elements inside pane to fit pane-height * * @param {(string|Object)} evt_or_panes The pane(s) being resized * @param {boolean=} [remeasure=false] Should the content (header/footer) be remeasured? */ , sizeContent = function (evt_or_panes, remeasure) { if (!isInitialized()) return; var panes = evtPane.call(this, evt_or_panes); panes = panes ? panes.split(",") : _c.allPanes; $.each(panes, function (idx, pane) { var $P = $Ps[pane] , $C = $Cs[pane] , o = options[pane] , s = state[pane] , m = s.content // m = measurements ; if (!$P || !$C || !$P.is(":visible")) return true; // NOT VISIBLE - skip // if content-element was REMOVED, update OR remove the pointer if (!$C.length) { initContent(pane, false); // false = do NOT sizeContent() - already there! if (!$C) return; // no replacement element found - pointer have been removed } // onsizecontent_start will CANCEL resizing if returns false if (false === _runCallbacks("onsizecontent_start", pane)) return; // skip re-measuring offsets if live-resizing if ((!s.isMoving && !s.isResizing) || o.liveContentResizing || remeasure || m.top == undefined) { _measure(); // if any footers are below pane-bottom, they may not measure correctly, // so allow pane overflow and re-measure if (m.hiddenFooters > 0 && $P.css("overflow") === "hidden") { $P.css("overflow", "visible"); _measure(); // remeasure while overflowing $P.css("overflow", "hidden"); } } // NOTE: spaceAbove/Below *includes* the pane paddingTop/Bottom, but not pane.borders var newH = s.innerHeight - (m.spaceAbove - s.css.paddingTop) - (m.spaceBelow - s.css.paddingBottom); if (!$C.is(":visible") || m.height != newH) { // size the Content element to fit new pane-size - will autoHide if not enough room setOuterHeight($C, newH, true); // true=autoHide m.height = newH; // save new height }; if (state.initialized) _runCallbacks("onsizecontent_end", pane); function _below ($E) { return max(s.css.paddingBottom, (parseInt($E.css("marginBottom"), 10) || 0)); }; function _measure () { var ignore = options[pane].contentIgnoreSelector , $Fs = $C.nextAll().not(".ui-layout-mask").not(ignore || ":lt(0)") // not :lt(0) = ALL , $Fs_vis = $Fs.filter(':visible') , $F = $Fs_vis.filter(':last') ; m = { top: $C[0].offsetTop , height: $C.outerHeight() , numFooters: $Fs.length , hiddenFooters: $Fs.length - $Fs_vis.length , spaceBelow: 0 // correct if no content footer ($E) } m.spaceAbove = m.top; // just for state - not used in calc m.bottom = m.top + m.height; if ($F.length) //spaceBelow = (LastFooter.top + LastFooter.height) [footerBottom] - Content.bottom + max(LastFooter.marginBottom, pane.paddingBotom) m.spaceBelow = ($F[0].offsetTop + $F.outerHeight()) - m.bottom + _below($F); else // no footer - check marginBottom on Content element itself m.spaceBelow = _below($C); }; }); } /** * Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary * * @see initHandles(), open(), close(), resizeAll() * @param {(string|Object)=} evt_or_panes The pane(s) being resized */ , sizeHandles = function (evt_or_panes) { var panes = evtPane.call(this, evt_or_panes) panes = panes ? panes.split(",") : _c.borderPanes; $.each(panes, function (i, pane) { var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , $TC ; if (!$P || !$R) return; var dir = _c[pane].dir , _state = (s.isClosed ? "_closed" : "_open") , spacing = o["spacing"+ _state] , togAlign = o["togglerAlign"+ _state] , togLen = o["togglerLength"+ _state] , paneLen , left , offset , CSS = {} ; if (spacing === 0) { $R.hide(); return; } else if (!s.noRoom && !s.isHidden) // skip if resizer was hidden for any reason $R.show(); // in case was previously hidden // Resizer Bar is ALWAYS same width/height of pane it is attached to if (dir === "horz") { // north/south //paneLen = $P.outerWidth(); // s.outerWidth || paneLen = sC.innerWidth; // handle offscreen-panes s.resizerLength = paneLen; left = $.layout.cssNum($P, "left") $R.css({ width: cssW($R, paneLen) // account for borders & padding , height: cssH($R, spacing) // ditto , left: left > -9999 ? left : sC.inset.left // handle offscreen-panes }); } else { // east/west paneLen = $P.outerHeight(); // s.outerHeight || s.resizerLength = paneLen; $R.css({ height: cssH($R, paneLen) // account for borders & padding , width: cssW($R, spacing) // ditto , top: sC.inset.top + getPaneSize("north", true) // TODO: what if no North pane? //, top: $.layout.cssNum($Ps["center"], "top") }); } // remove hover classes removeHover( o, $R ); if ($T) { if (togLen === 0 || (s.isSliding && o.hideTogglerOnSlide)) { $T.hide(); // always HIDE the toggler when 'sliding' return; } else $T.show(); // in case was previously hidden if (!(togLen > 0) || togLen === "100%" || togLen > paneLen) { togLen = paneLen; offset = 0; } else { // calculate 'offset' based on options.PANE.togglerAlign_open/closed if (isStr(togAlign)) { switch (togAlign) { case "top": case "left": offset = 0; break; case "bottom": case "right": offset = paneLen - togLen; break; case "middle": case "center": default: offset = round((paneLen - togLen) / 2); // 'default' catches typos } } else { // togAlign = number var x = parseInt(togAlign, 10); // if (togAlign >= 0) offset = x; else offset = paneLen - togLen + x; // NOTE: x is negative! } } if (dir === "horz") { // north/south var width = cssW($T, togLen); $T.css({ width: width // account for borders & padding , height: cssH($T, spacing) // ditto , left: offset // TODO: VERIFY that toggler positions correctly for ALL values , top: 0 }); // CENTER the toggler content SPAN $T.children(".content").each(function(){ $TC = $(this); $TC.css("marginLeft", round((width-$TC.outerWidth())/2)); // could be negative }); } else { // east/west var height = cssH($T, togLen); $T.css({ height: height // account for borders & padding , width: cssW($T, spacing) // ditto , top: offset // POSITION the toggler , left: 0 }); // CENTER the toggler content SPAN $T.children(".content").each(function(){ $TC = $(this); $TC.css("marginTop", round((height-$TC.outerHeight())/2)); // could be negative }); } // remove ALL hover classes removeHover( 0, $T ); } // DONE measuring and sizing this resizer/toggler, so can be 'hidden' now if (!state.initialized && (o.initHidden || s.isHidden)) { $R.hide(); if ($T) $T.hide(); } }); } /** * @param {(string|Object)} evt_or_pane */ , enableClosable = function (evt_or_pane) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $T = $Ts[pane] , o = options[pane] ; if (!$T) return; o.closable = true; $T .bind("click."+ sID, function(evt){ evt.stopPropagation(); toggle(pane); }) .css("visibility", "visible") .css("cursor", "pointer") .attr("title", state[pane].isClosed ? o.tips.Open : o.tips.Close) // may be blank .show(); } /** * @param {(string|Object)} evt_or_pane * @param {boolean=} [hide=false] */ , disableClosable = function (evt_or_pane, hide) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $T = $Ts[pane] ; if (!$T) return; options[pane].closable = false; // is closable is disable, then pane MUST be open! if (state[pane].isClosed) open(pane, false, true); $T .unbind("."+ sID) .css("visibility", hide ? "hidden" : "visible") // instead of hide(), which creates logic issues .css("cursor", "default") .attr("title", ""); } /** * @param {(string|Object)} evt_or_pane */ , enableSlidable = function (evt_or_pane) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $R = $Rs[pane] ; if (!$R || !$R.data('draggable')) return; options[pane].slidable = true; if (state[pane].isClosed) bindStartSlidingEvents(pane, true); } /** * @param {(string|Object)} evt_or_pane */ , disableSlidable = function (evt_or_pane) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $R = $Rs[pane] ; if (!$R) return; options[pane].slidable = false; if (state[pane].isSliding) close(pane, false, true); else { bindStartSlidingEvents(pane, false); $R .css("cursor", "default") .attr("title", ""); removeHover(null, $R[0]); // in case currently hovered } } /** * @param {(string|Object)} evt_or_pane */ , enableResizable = function (evt_or_pane) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $R = $Rs[pane] , o = options[pane] ; if (!$R || !$R.data('draggable')) return; o.resizable = true; $R.draggable("enable"); if (!state[pane].isClosed) $R .css("cursor", o.resizerCursor) .attr("title", o.tips.Resize); } /** * @param {(string|Object)} evt_or_pane */ , disableResizable = function (evt_or_pane) { if (!isInitialized()) return; var pane = evtPane.call(this, evt_or_pane) , $R = $Rs[pane] ; if (!$R || !$R.data('draggable')) return; options[pane].resizable = false; $R .draggable("disable") .css("cursor", "default") .attr("title", ""); removeHover(null, $R[0]); // in case currently hovered } /** * Move a pane from source-side (eg, west) to target-side (eg, east) * If pane exists on target-side, move that to source-side, ie, 'swap' the panes * * @param {(string|Object)} evt_or_pane1 The pane/edge being swapped * @param {string} pane2 ditto */ , swapPanes = function (evt_or_pane1, pane2) { if (!isInitialized()) return; var pane1 = evtPane.call(this, evt_or_pane1); // change state.edge NOW so callbacks can know where pane is headed... state[pane1].edge = pane2; state[pane2].edge = pane1; // run these even if NOT state.initialized if (false === _runCallbacks("onswap_start", pane1) || false === _runCallbacks("onswap_start", pane2) ) { state[pane1].edge = pane1; // reset state[pane2].edge = pane2; return; } var oPane1 = copy( pane1 ) , oPane2 = copy( pane2 ) , sizes = {} ; sizes[pane1] = oPane1 ? oPane1.state.size : 0; sizes[pane2] = oPane2 ? oPane2.state.size : 0; // clear pointers & state $Ps[pane1] = false; $Ps[pane2] = false; state[pane1] = {}; state[pane2] = {}; // ALWAYS remove the resizer & toggler elements if ($Ts[pane1]) $Ts[pane1].remove(); if ($Ts[pane2]) $Ts[pane2].remove(); if ($Rs[pane1]) $Rs[pane1].remove(); if ($Rs[pane2]) $Rs[pane2].remove(); $Rs[pane1] = $Rs[pane2] = $Ts[pane1] = $Ts[pane2] = false; // transfer element pointers and data to NEW Layout keys move( oPane1, pane2 ); move( oPane2, pane1 ); // cleanup objects oPane1 = oPane2 = sizes = null; // make panes 'visible' again if ($Ps[pane1]) $Ps[pane1].css(_c.visible); if ($Ps[pane2]) $Ps[pane2].css(_c.visible); // fix any size discrepancies caused by swap resizeAll(); // run these even if NOT state.initialized _runCallbacks("onswap_end", pane1); _runCallbacks("onswap_end", pane2); return; function copy (n) { // n = pane var $P = $Ps[n] , $C = $Cs[n] ; return !$P ? false : { pane: n , P: $P ? $P[0] : false , C: $C ? $C[0] : false , state: $.extend(true, {}, state[n]) , options: $.extend(true, {}, options[n]) } }; function move (oPane, pane) { if (!oPane) return; var P = oPane.P , C = oPane.C , oldPane = oPane.pane , c = _c[pane] // save pane-options that should be retained , s = $.extend(true, {}, state[pane]) , o = options[pane] // RETAIN side-specific FX Settings - more below , fx = { resizerCursor: o.resizerCursor } , re, size, pos ; $.each("fxName,fxSpeed,fxSettings".split(","), function (i, k) { fx[k +"_open"] = o[k +"_open"]; fx[k +"_close"] = o[k +"_close"]; fx[k +"_size"] = o[k +"_size"]; }); // update object pointers and attributes $Ps[pane] = $(P) .data({ layoutPane: Instance[pane] // NEW pointer to pane-alias-object , layoutEdge: pane }) .css(_c.hidden) .css(c.cssReq) ; $Cs[pane] = C ? $(C) : false; // set options and state options[pane] = $.extend(true, {}, oPane.options, fx); state[pane] = $.extend(true, {}, oPane.state); // change classNames on the pane, eg: ui-layout-pane-east ==> ui-layout-pane-west re = new RegExp(o.paneClass +"-"+ oldPane, "g"); P.className = P.className.replace(re, o.paneClass +"-"+ pane); // ALWAYS regenerate the resizer & toggler elements initHandles(pane); // create the required resizer & toggler // if moving to different orientation, then keep 'target' pane size if (c.dir != _c[oldPane].dir) { size = sizes[pane] || 0; setSizeLimits(pane); // update pane-state size = max(size, state[pane].minSize); // use manualSizePane to disable autoResize - not useful after panes are swapped manualSizePane(pane, size, true, true); // true/true = skipCallback/noAnimation } else // move the resizer here $Rs[pane].css(c.side, sC.inset[c.side] + (state[pane].isVisible ? getPaneSize(pane) : 0)); // ADD CLASSNAMES & SLIDE-BINDINGS if (oPane.state.isVisible && !s.isVisible) setAsOpen(pane, true); // true = skipCallback else { setAsClosed(pane); bindStartSlidingEvents(pane, true); // will enable events IF option is set } // DESTROY the object oPane = null; }; } /** * INTERNAL method to sync pin-buttons when pane is opened or closed * Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes * * @see open(), setAsOpen(), setAsClosed() * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin True means set the pin 'down', False means 'up' */ , syncPinBtns = function (pane, doPin) { if ($.layout.plugins.buttons) $.each(state[pane].pins, function (i, selector) { $.layout.buttons.setPinState(Instance, $(selector), pane, doPin); }); } ; // END var DECLARATIONS /** * Capture keys when enableCursorHotkey - toggle pane if hotkey pressed * * @see document.keydown() */ function keyDown (evt) { if (!evt) return true; var code = evt.keyCode; if (code < 33) return true; // ignore special keys: ENTER, TAB, etc var PANE = { 38: "north" // Up Cursor - $.ui.keyCode.UP , 40: "south" // Down Cursor - $.ui.keyCode.DOWN , 37: "west" // Left Cursor - $.ui.keyCode.LEFT , 39: "east" // Right Cursor - $.ui.keyCode.RIGHT } , ALT = evt.altKey // no worky! , SHIFT = evt.shiftKey , CTRL = evt.ctrlKey , CURSOR = (CTRL && code >= 37 && code <= 40) , o, k, m, pane ; if (CURSOR && options[PANE[code]].enableCursorHotkey) // valid cursor-hotkey pane = PANE[code]; else if (CTRL || SHIFT) // check to see if this matches a custom-hotkey $.each(_c.borderPanes, function (i, p) { // loop each pane to check its hotkey o = options[p]; k = o.customHotkey; m = o.customHotkeyModifier; // if missing or invalid, treated as "CTRL+SHIFT" if ((SHIFT && m=="SHIFT") || (CTRL && m=="CTRL") || (CTRL && SHIFT)) { // Modifier matches if (k && code === (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) { // Key matches pane = p; return false; // BREAK } } }); // validate pane if (!pane || !$Ps[pane] || !options[pane].closable || state[pane].isHidden) return true; toggle(pane); evt.stopPropagation(); evt.returnValue = false; // CANCEL key return false; }; /* * ###################################### * UTILITY METHODS * called externally or by initButtons * ###################################### */ /** * Change/reset a pane overflow setting & zIndex to allow popups/drop-downs to work * * @param {Object=} [el] (optional) Can also be 'bound' to a click, mouseOver, or other event */ function allowOverflow (el) { if (!isInitialized()) return; if (this && this.tagName) el = this; // BOUND to element var $P; if (isStr(el)) $P = $Ps[el]; else if ($(el).data("layoutRole")) $P = $(el); else $(el).parents().each(function(){ if ($(this).data("layoutRole")) { $P = $(this); return false; // BREAK } }); if (!$P || !$P.length) return; // INVALID var pane = $P.data("layoutEdge") , s = state[pane] ; // if pane is already raised, then reset it before doing it again! // this would happen if allowOverflow is attached to BOTH the pane and an element if (s.cssSaved) resetOverflow(pane); // reset previous CSS before continuing // if pane is raised by sliding or resizing, or its closed, then abort if (s.isSliding || s.isResizing || s.isClosed) { s.cssSaved = false; return; } var newCSS = { zIndex: (options.zIndexes.resizer_normal + 1) } , curCSS = {} , of = $P.css("overflow") , ofX = $P.css("overflowX") , ofY = $P.css("overflowY") ; // determine which, if any, overflow settings need to be changed if (of != "visible") { curCSS.overflow = of; newCSS.overflow = "visible"; } if (ofX && !ofX.match(/(visible|auto)/)) { curCSS.overflowX = ofX; newCSS.overflowX = "visible"; } if (ofY && !ofY.match(/(visible|auto)/)) { curCSS.overflowY = ofX; newCSS.overflowY = "visible"; } // save the current overflow settings - even if blank! s.cssSaved = curCSS; // apply new CSS to raise zIndex and, if necessary, make overflow 'visible' $P.css( newCSS ); // make sure the zIndex of all other panes is normal $.each(_c.allPanes, function(i, p) { if (p != pane) resetOverflow(p); }); }; /** * @param {Object=} [el] (optional) Can also be 'bound' to a click, mouseOver, or other event */ function resetOverflow (el) { if (!isInitialized()) return; if (this && this.tagName) el = this; // BOUND to element var $P; if (isStr(el)) $P = $Ps[el]; else if ($(el).data("layoutRole")) $P = $(el); else $(el).parents().each(function(){ if ($(this).data("layoutRole")) { $P = $(this); return false; // BREAK } }); if (!$P || !$P.length) return; // INVALID var pane = $P.data("layoutEdge") , s = state[pane] , CSS = s.cssSaved || {} ; // reset the zIndex if (!s.isSliding && !s.isResizing) $P.css("zIndex", options.zIndexes.pane_normal); // reset Overflow - if necessary $P.css( CSS ); // clear var s.cssSaved = false; }; /* * ##################### * CREATE/RETURN LAYOUT * ##################### */ try { // validate that container exists var $N = $(this).eq(0); // FIRST matching Container element if (!$N.length) { return _log( options.errors.containerMissing ); }; // Users retrieve Instance of a layout with: $N.layout() OR $N.data("layout") // return the Instance-pointer if layout has already been initialized if ($N.data("layoutContainer") && $N.data("layout")) return $N.data("layout"); // cached pointer } catch(e){ console.log("eeeee",e) } // init global vars var $Ps = {} // Panes x5 - set in initPanes() , $Cs = {} // Content x5 - set in initPanes() , $Rs = {} // Resizers x4 - set in initHandles() , $Ts = {} // Togglers x4 - set in initHandles() , $Ms = $([]) // Masks - up to 2 masks per pane (IFRAME + DIV) // aliases for code brevity , sC = state.container // alias for easy access to 'container dimensions' , sID = state.id // alias for unique layout ID/namespace - eg: "layout435" ; // create Instance object to expose data & option Properties, and primary action Methods var Instance = { // layout data options: options // property - options hash , state: state // property - dimensions hash // object pointers , container: $N // property - object pointers for layout container , panes: $Ps // property - object pointers for ALL Panes: panes.north, panes.center , contents: $Cs // property - object pointers for ALL Content: contents.north, contents.center , resizers: $Rs // property - object pointers for ALL Resizers, eg: resizers.north , togglers: $Ts // property - object pointers for ALL Togglers, eg: togglers.north // border-pane open/close , hide: hide // method - ditto , show: show // method - ditto , toggle: toggle // method - pass a 'pane' ("north", "west", etc) , open: open // method - ditto , close: close // method - ditto , slideOpen: slideOpen // method - ditto , slideClose: slideClose // method - ditto , slideToggle: slideToggle // method - ditto // pane actions , setSizeLimits: setSizeLimits // method - pass a 'pane' - update state min/max data , _sizePane: sizePane // method -intended for user by plugins only! , sizePane: manualSizePane // method - pass a 'pane' AND an 'outer-size' in pixels or percent, or 'auto' , sizeContent: sizeContent // method - pass a 'pane' , swapPanes: swapPanes // method - pass TWO 'panes' - will swap them , showMasks: showMasks // method - pass a 'pane' OR list of panes - default = all panes with mask option set , hideMasks: hideMasks // method - ditto' // pane element methods , initContent: initContent // method - ditto , addPane: addPane // method - pass a 'pane' , removePane: removePane // method - pass a 'pane' to remove from layout, add 'true' to delete the pane-elem , createChildren: createChildren // method - pass a 'pane' and (optional) layout-options (OVERRIDES options[pane].children , refreshChildren: refreshChildren // method - pass a 'pane' and a layout-instance // special pane option setting , enableClosable: enableClosable // method - pass a 'pane' , disableClosable: disableClosable // method - ditto , enableSlidable: enableSlidable // method - ditto , disableSlidable: disableSlidable // method - ditto , enableResizable: enableResizable // method - ditto , disableResizable: disableResizable// method - ditto // utility methods for panes , allowOverflow: allowOverflow // utility - pass calling element (this) , resetOverflow: resetOverflow // utility - ditto // layout control , destroy: destroy // method - no parameters , initPanes: isInitialized // method - no parameters , resizeAll: resizeAll // method - no parameters // callback triggering , runCallbacks: _runCallbacks // method - pass evtName & pane (if a pane-event), eg: trigger("onopen", "west") // alias collections of options, state and children - created in addPane and extended elsewhere , hasParentLayout: false // set by initContainer() , children: children // pointers to child-layouts, eg: Instance.children.west.layoutName , north: false // alias group: { name: pane, pane: $Ps[pane], options: options[pane], state: state[pane], children: children[pane] } , south: false // ditto , west: false // ditto , east: false // ditto , center: false // ditto }; // create the border layout NOW if (_create() === 'cancel') // onload_start callback returned false to CANCEL layout creation return null; else // true OR false -- if layout-elements did NOT init (hidden or do not exist), can auto-init later return Instance; // return the Instance object } })( jQuery ); // END Layout - keep internal vars internal! // START Plugins - shared wrapper, no global vars (function ($) { /** * jquery.layout.state 1.0 * $Date: 2011-07-16 08:00:00 (Sat, 16 July 2011) $ * * Copyright (c) 2012 * Kevin Dalman (http://allpro.net) * * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. * * @requires: UI Layout 1.3.0.rc30.1 or higher * @requires: $.ui.cookie (above) * * @see: http://groups.google.com/group/jquery-ui-layout */ /* * State-management options stored in options.stateManagement, which includes a .cookie hash * Default options saves ALL KEYS for ALL PANES, ie: pane.size, pane.isClosed, pane.isHidden * * // STATE/COOKIE OPTIONS * @example $(el).layout({ stateManagement: { enabled: true , stateKeys: "east.size,west.size,east.isClosed,west.isClosed" , cookie: { name: "appLayout", path: "/" } } }) * @example $(el).layout({ stateManagement__enabled: true }) // enable auto-state-management using cookies * @example $(el).layout({ stateManagement__cookie: { name: "appLayout", path: "/" } }) * @example $(el).layout({ stateManagement__cookie__name: "appLayout", stateManagement__cookie__path: "/" }) * * // STATE/COOKIE METHODS * @example myLayout.saveCookie( "west.isClosed,north.size,south.isHidden", {expires: 7} ); * @example myLayout.loadCookie(); * @example myLayout.deleteCookie(); * @example var JSON = myLayout.readState(); // CURRENT Layout State * @example var JSON = myLayout.readCookie(); // SAVED Layout State (from cookie) * @example var JSON = myLayout.state.stateData; // LAST LOADED Layout State (cookie saved in layout.state hash) * * CUSTOM STATE-MANAGEMENT (eg, saved in a database) * @example var JSON = myLayout.readState( "west.isClosed,north.size,south.isHidden" ); * @example myLayout.loadState( JSON ); */ /** * UI COOKIE UTILITY * * A $.cookie OR $.ui.cookie namespace *should be standard*, but until then... * This creates $.ui.cookie so Layout does not need the cookie.jquery.js plugin * NOTE: This utility is REQUIRED by the layout.state plugin * * Cookie methods in Layout are created as part of State Management */ if (!$.ui) $.ui = {}; $.ui.cookie = { // cookieEnabled is not in DOM specs, but DOES works in all browsers,including IE6 acceptsCookies: !!navigator.cookieEnabled , read: function (name) { var c = document.cookie , cs = c ? c.split(';') : [] , pair // loop var ; for (var i=0, n=cs.length; i < n; i++) { pair = $.trim(cs[i]).split('='); // name=value pair if (pair[0] == name) // found the layout cookie return decodeURIComponent(pair[1]); } return null; } , write: function (name, val, cookieOpts) { var params = "" , date = "" , clear = false , o = cookieOpts || {} , x = o.expires || null , t = $.type(x) ; if (t === "date") date = x; else if (t === "string" && x > 0) { x = parseInt(x,10); t = "number"; } if (t === "number") { date = new Date(); if (x > 0) date.setDate(date.getDate() + x); else { date.setFullYear(1970); clear = true; } } if (date) params += ";expires="+ date.toUTCString(); if (o.path) params += ";path="+ o.path; if (o.domain) params += ";domain="+ o.domain; if (o.secure) params += ";secure"; document.cookie = name +"="+ (clear ? "" : encodeURIComponent( val )) + params; // write or clear cookie } , clear: function (name) { $.ui.cookie.write(name, "", {expires: -1}); } }; // if cookie.jquery.js is not loaded, create an alias to replicate it // this may be useful to other plugins or code dependent on that plugin if (!$.cookie) $.cookie = function (k, v, o) { var C = $.ui.cookie; if (v === null) C.clear(k); else if (v === undefined) return C.read(k); else C.write(k, v, o); }; // tell Layout that the state plugin is available $.layout.plugins.stateManagement = true; // Add State-Management options to layout.defaults $.layout.config.optionRootKeys.push("stateManagement"); $.layout.defaults.stateManagement = { enabled: false // true = enable state-management, even if not using cookies , autoSave: true // Save a state-cookie when page exits? , autoLoad: true // Load the state-cookie when Layout inits? , animateLoad: true // animate panes when loading state into an active layout , includeChildren: true // recurse into child layouts to include their state as well // List state-data to save - must be pane-specific , stateKeys: "north.size,south.size,east.size,west.size,"+ "north.isClosed,south.isClosed,east.isClosed,west.isClosed,"+ "north.isHidden,south.isHidden,east.isHidden,west.isHidden" , cookie: { name: "" // If not specified, will use Layout.name, else just "Layout" , domain: "" // blank = current domain , path: "" // blank = current page, "/" = entire website , expires: "" // 'days' to keep cookie - leave blank for 'session cookie' , secure: false } }; // Set stateManagement as a layout-option, NOT a pane-option $.layout.optionsMap.layout.push("stateManagement"); /* * State Management methods */ $.layout.state = { /** * Get the current layout state and save it to a cookie * * myLayout.saveCookie( keys, cookieOpts ) * * @param {Object} inst * @param {(string|Array)=} keys * @param {Object=} cookieOpts */ saveCookie: function (inst, keys, cookieOpts) { var o = inst.options , sm = o.stateManagement , oC = $.extend(true, {}, sm.cookie, cookieOpts || null) , data = inst.state.stateData = inst.readState( keys || sm.stateKeys ) // read current panes-state ; $.ui.cookie.write( oC.name || o.name || "Layout", $.layout.state.encodeJSON(data), oC ); return $.extend(true, {}, data); // return COPY of state.stateData data } /** * Remove the state cookie * * @param {Object} inst */ , deleteCookie: function (inst) { var o = inst.options; $.ui.cookie.clear( o.stateManagement.cookie.name || o.name || "Layout" ); } /** * Read & return data from the cookie - as JSON * * @param {Object} inst */ , readCookie: function (inst) { var o = inst.options; var c = $.ui.cookie.read( o.stateManagement.cookie.name || o.name || "Layout" ); // convert cookie string back to a hash and return it return c ? $.layout.state.decodeJSON(c) : {}; } /** * Get data from the cookie and USE IT to loadState * * @param {Object} inst */ , loadCookie: function (inst) { var c = $.layout.state.readCookie(inst); // READ the cookie if (c) { inst.state.stateData = $.extend(true, {}, c); // SET state.stateData inst.loadState(c); // LOAD the retrieved state } return c; } /** * Update layout options from the cookie, if one exists * * @param {Object} inst * @param {Object=} stateData * @param {boolean=} animate */ , loadState: function (inst, data, opts) { if (!$.isPlainObject( data ) || $.isEmptyObject( data )) return; // normalize data & cache in the state object data = inst.state.stateData = $.layout.transformData( data ); // panes = default subkey // add missing/default state-restore options var smo = inst.options.stateManagement; opts = $.extend({ animateLoad: false //smo.animateLoad , includeChildren: smo.includeChildren }, opts ); if (!inst.state.initialized) { /* * layout NOT initialized, so just update its options */ // MUST remove pane.children keys before applying to options // use a copy so we don't remove keys from original data var o = $.extend(true, {}, data); //delete o.center; // center has no state-data - only children $.each($.layout.config.allPanes, function (idx, pane) { if (o[pane]) delete o[pane].children; }); // update CURRENT layout-options with saved state data $.extend(true, inst.options, o); } else { /* * layout already initialized, so modify layout's configuration */ var noAnimate = !opts.animateLoad , o, c, h, state, open ; $.each($.layout.config.borderPanes, function (idx, pane) { o = data[ pane ]; if (!$.isPlainObject( o )) return; // no key, skip pane s = o.size; c = o.initClosed; h = o.initHidden; ar = o.autoResize state = inst.state[pane]; open = state.isVisible; // reset autoResize if (ar) state.autoResize = ar; // resize BEFORE opening if (!open) inst._sizePane(pane, s, false, false, false); // false=skipCallback/noAnimation/forceResize // open/close as necessary - DO NOT CHANGE THIS ORDER! if (h === true) inst.hide(pane, noAnimate); else if (c === true) inst.close(pane, false, noAnimate); else if (c === false) inst.open (pane, false, noAnimate); else if (h === false) inst.show (pane, false, noAnimate); // resize AFTER any other actions if (open) inst._sizePane(pane, s, false, false, noAnimate); // animate resize if option passed }); /* * RECURSE INTO CHILD-LAYOUTS */ if (opts.includeChildren) { var paneStateChildren, childState; $.each(inst.children, function (pane, paneChildren) { paneStateChildren = data[pane] ? data[pane].children : 0; if (paneStateChildren && paneChildren) { $.each(paneChildren, function (stateKey, child) { childState = paneStateChildren[stateKey]; if (child && childState) child.loadState( childState ); }); } }); } } } /** * Get the *current layout state* and return it as a hash * * @param {Object=} inst // Layout instance to get state for * @param {object=} [opts] // State-Managements override options */ , readState: function (inst, opts) { // backward compatility if ($.type(opts) === 'string') opts = { keys: opts }; if (!opts) opts = {}; var sm = inst.options.stateManagement , ic = opts.includeChildren , recurse = ic !== undefined ? ic : sm.includeChildren , keys = opts.stateKeys || sm.stateKeys , alt = { isClosed: 'initClosed', isHidden: 'initHidden' } , state = inst.state , panes = $.layout.config.allPanes , data = {} , pair, pane, key, val , ps, pC, child, array, count, branch ; if ($.isArray(keys)) keys = keys.join(","); // convert keys to an array and change delimiters from '__' to '.' keys = keys.replace(/__/g, ".").split(','); // loop keys and create a data hash for (var i=0, n=keys.length; i < n; i++) { pair = keys[i].split("."); pane = pair[0]; key = pair[1]; if ($.inArray(pane, panes) < 0) continue; // bad pane! val = state[ pane ][ key ]; if (val == undefined) continue; if (key=="isClosed" && state[pane]["isSliding"]) val = true; // if sliding, then *really* isClosed ( data[pane] || (data[pane]={}) )[ alt[key] ? alt[key] : key ] = val; } // recurse into the child-layouts for each pane if (recurse) { $.each(panes, function (idx, pane) { pC = inst.children[pane]; ps = state.stateData[pane]; if ($.isPlainObject( pC ) && !$.isEmptyObject( pC )) { // ensure a key exists for this 'pane', eg: branch = data.center branch = data[pane] || (data[pane] = {}); if (!branch.children) branch.children = {}; $.each( pC, function (key, child) { // ONLY read state from an initialize layout if ( child.state.initialized ) branch.children[ key ] = $.layout.state.readState( child ); // if we have PREVIOUS (onLoad) state for this child-layout, KEEP IT! else if ( ps && ps.children && ps.children[ key ] ) { branch.children[ key ] = $.extend(true, {}, ps.children[ key ] ); } }); } }); } return data; } /** * Stringify a JSON hash so can save in a cookie or db-field */ , encodeJSON: function (JSON) { return parse(JSON); function parse (h) { var D=[], i=0, k, v, t // k = key, v = value , a = $.isArray(h) ; for (k in h) { v = h[k]; t = typeof v; if (t == 'string') // STRING - add quotes v = '"'+ v +'"'; else if (t == 'object') // SUB-KEY - recurse into it v = parse(v); D[i++] = (!a ? '"'+ k +'":' : '') + v; } return (a ? '[' : '{') + D.join(',') + (a ? ']' : '}'); }; } /** * Convert stringified JSON back to a hash object * @see $.parseJSON(), adding in jQuery 1.4.1 */ , decodeJSON: function (str) { try { return $.parseJSON ? $.parseJSON(str) : window["eval"]("("+ str +")") || {}; } catch (e) { return {}; } } , _create: function (inst) { var _ = $.layout.state , o = inst.options , sm = o.stateManagement ; // ADD State-Management plugin methods to inst $.extend( inst, { // readCookie - update options from cookie - returns hash of cookie data readCookie: function () { return _.readCookie(inst); } // deleteCookie , deleteCookie: function () { _.deleteCookie(inst); } // saveCookie - optionally pass keys-list and cookie-options (hash) , saveCookie: function (keys, cookieOpts) { return _.saveCookie(inst, keys, cookieOpts); } // loadCookie - readCookie and use to loadState() - returns hash of cookie data , loadCookie: function () { return _.loadCookie(inst); } // loadState - pass a hash of state to use to update options , loadState: function (stateData, opts) { _.loadState(inst, stateData, opts); } // readState - returns hash of current layout-state , readState: function (keys) { return _.readState(inst, keys); } // add JSON utility methods too... , encodeJSON: _.encodeJSON , decodeJSON: _.decodeJSON }); // init state.stateData key, even if plugin is initially disabled inst.state.stateData = {}; // autoLoad MUST BE one of: data-array, data-hash, callback-function, or TRUE if ( !sm.autoLoad ) return; // When state-data exists in the autoLoad key USE IT, // even if stateManagement.enabled == false if ($.isPlainObject( sm.autoLoad )) { if (!$.isEmptyObject( sm.autoLoad )) { inst.loadState( sm.autoLoad ); } } else if ( sm.enabled ) { // update the options from cookie or callback // if options is a function, call it to get stateData if ($.isFunction( sm.autoLoad )) { var d = {}; try { d = sm.autoLoad( inst, inst.state, inst.options, inst.options.name || '' ); // try to get data from fn } catch (e) {} if (d && $.isPlainObject( d ) && !$.isEmptyObject( d )) inst.loadState(d); } else // any other truthy value will trigger loadCookie inst.loadCookie(); } } , _unload: function (inst) { var sm = inst.options.stateManagement; if (sm.enabled && sm.autoSave) { // if options is a function, call it to save the stateData if ($.isFunction( sm.autoSave )) { try { sm.autoSave( inst, inst.state, inst.options, inst.options.name || '' ); // try to get data from fn } catch (e) {} } else // any truthy value will trigger saveCookie inst.saveCookie(); } } }; // add state initialization method to Layout's onCreate array of functions $.layout.onCreate.push( $.layout.state._create ); $.layout.onUnload.push( $.layout.state._unload ); /** * jquery.layout.buttons 1.0 * $Date: 2011-07-16 08:00:00 (Sat, 16 July 2011) $ * * Copyright (c) 2012 * Kevin Dalman (http://allpro.net) * * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. * * @requires: UI Layout 1.3.0.rc30.1 or higher * * @see: http://groups.google.com/group/jquery-ui-layout * * Docs: [ to come ] * Tips: [ to come ] */ // tell Layout that the state plugin is available $.layout.plugins.buttons = true; // Add buttons options to layout.defaults $.layout.defaults.autoBindCustomButtons = false; // Specify autoBindCustomButtons as a layout-option, NOT a pane-option $.layout.optionsMap.layout.push("autoBindCustomButtons"); /* * Button methods */ $.layout.buttons = { /** * Searches for .ui-layout-button-xxx elements and auto-binds them as layout-buttons * * @see _create() * * @param {Object} inst Layout Instance object */ init: function (inst) { var pre = "ui-layout-button-" , layout = inst.options.name || "" , name; $.each("toggle,open,close,pin,toggle-slide,open-slide".split(","), function (i, action) { $.each($.layout.config.borderPanes, function (ii, pane) { $("."+pre+action+"-"+pane).each(function(){ // if button was previously 'bound', data.layoutName was set, but is blank if layout has no 'name' name = $(this).data("layoutName") || $(this).attr("layoutName"); if (name == undefined || name === layout) inst.bindButton(this, action, pane); }); }); }); } /** * Helper function to validate params received by addButton utilities * * Two classes are added to the element, based on the buttonClass... * The type of button is appended to create the 2nd className: * - ui-layout-button-pin // action btnClass * - ui-layout-button-pin-west // action btnClass + pane * - ui-layout-button-toggle * - ui-layout-button-open * - ui-layout-button-close * * @param {Object} inst Layout Instance object * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * * @return {Array.<Object>} If both params valid, the element matching 'selector' in a jQuery wrapper - otherwise returns null */ , get: function (inst, selector, pane, action) { var $E = $(selector) , o = inst.options , err = o.errors.addButtonError ; if (!$E.length) { // element not found $.layout.msg(err +" "+ o.errors.selector +": "+ selector, true); } else if ($.inArray(pane, $.layout.config.borderPanes) < 0) { // invalid 'pane' sepecified $.layout.msg(err +" "+ o.errors.pane +": "+ pane, true); $E = $(""); // NO BUTTON } else { // VALID var btn = o[pane].buttonClass +"-"+ action; $E .addClass( btn +" "+ btn +"-"+ pane ) .data("layoutName", o.name); // add layout identifier - even if blank! } return $E; } /** * NEW syntax for binding layout-buttons - will eventually replace addToggle, addOpen, etc. * * @param {Object} inst Layout Instance object * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} action * @param {string} pane */ , bind: function (inst, selector, action, pane) { var _ = $.layout.buttons; switch (action.toLowerCase()) { case "toggle": _.addToggle (inst, selector, pane); break; case "open": _.addOpen (inst, selector, pane); break; case "close": _.addClose (inst, selector, pane); break; case "pin": _.addPin (inst, selector, pane); break; case "toggle-slide": _.addToggle (inst, selector, pane, true); break; case "open-slide": _.addOpen (inst, selector, pane, true); break; } return inst; } /** * Add a custom Toggler button for a pane * * @param {Object} inst Layout Instance object * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @param {boolean=} slide true = slide-open, false = pin-open */ , addToggle: function (inst, selector, pane, slide) { $.layout.buttons.get(inst, selector, pane, "toggle") .click(function(evt){ inst.toggle(pane, !!slide); evt.stopPropagation(); }); return inst; } /** * Add a custom Open button for a pane * * @param {Object} inst Layout Instance object * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @param {boolean=} slide true = slide-open, false = pin-open */ , addOpen: function (inst, selector, pane, slide) { $.layout.buttons.get(inst, selector, pane, "open") .attr("title", inst.options[pane].tips.Open) .click(function (evt) { inst.open(pane, !!slide); evt.stopPropagation(); }); return inst; } /** * Add a custom Close button for a pane * * @param {Object} inst Layout Instance object * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. */ , addClose: function (inst, selector, pane) { $.layout.buttons.get(inst, selector, pane, "close") .attr("title", inst.options[pane].tips.Close) .click(function (evt) { inst.close(pane); evt.stopPropagation(); }); return inst; } /** * Add a custom Pin button for a pane * * Four classes are added to the element, based on the paneClass for the associated pane... * Assuming the default paneClass and the pin is 'up', these classes are added for a west-pane pin: * - ui-layout-pane-pin * - ui-layout-pane-west-pin * - ui-layout-pane-pin-up * - ui-layout-pane-west-pin-up * * @param {Object} inst Layout Instance object * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the pin is for: 'north', 'south', etc. */ , addPin: function (inst, selector, pane) { var _ = $.layout.buttons , $E = _.get(inst, selector, pane, "pin"); if ($E.length) { var s = inst.state[pane]; $E.click(function (evt) { _.setPinState(inst, $(this), pane, (s.isSliding || s.isClosed)); if (s.isSliding || s.isClosed) inst.open( pane ); // change from sliding to open else inst.close( pane ); // slide-closed evt.stopPropagation(); }); // add up/down pin attributes and classes _.setPinState(inst, $E, pane, (!s.isClosed && !s.isSliding)); // add this pin to the pane data so we can 'sync it' automatically // PANE.pins key is an array so we can store multiple pins for each pane s.pins.push( selector ); // just save the selector string } return inst; } /** * Change the class of the pin button to make it look 'up' or 'down' * * @see addPin(), syncPins() * * @param {Object} inst Layout Instance object * @param {Array.<Object>} $Pin The pin-span element in a jQuery wrapper * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin true = set the pin 'down', false = set it 'up' */ , setPinState: function (inst, $Pin, pane, doPin) { var updown = $Pin.attr("pin"); if (updown && doPin === (updown=="down")) return; // already in correct state var o = inst.options[pane] , pin = o.buttonClass +"-pin" , side = pin +"-"+ pane , UP = pin +"-up "+ side +"-up" , DN = pin +"-down "+side +"-down" ; $Pin .attr("pin", doPin ? "down" : "up") // logic .attr("title", doPin ? o.tips.Unpin : o.tips.Pin) .removeClass( doPin ? UP : DN ) .addClass( doPin ? DN : UP ) ; } /** * INTERNAL function to sync 'pin buttons' when pane is opened or closed * Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes * * @see open(), close() * * @param {Object} inst Layout Instance object * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin True means set the pin 'down', False means 'up' */ , syncPinBtns: function (inst, pane, doPin) { // REAL METHOD IS _INSIDE_ LAYOUT - THIS IS HERE JUST FOR REFERENCE $.each(inst.state[pane].pins, function (i, selector) { $.layout.buttons.setPinState(inst, $(selector), pane, doPin); }); } , _load: function (inst) { var _ = $.layout.buttons; // ADD Button methods to Layout Instance // Note: sel = jQuery Selector string $.extend( inst, { bindButton: function (sel, action, pane) { return _.bind(inst, sel, action, pane); } // DEPRECATED METHODS , addToggleBtn: function (sel, pane, slide) { return _.addToggle(inst, sel, pane, slide); } , addOpenBtn: function (sel, pane, slide) { return _.addOpen(inst, sel, pane, slide); } , addCloseBtn: function (sel, pane) { return _.addClose(inst, sel, pane); } , addPinBtn: function (sel, pane) { return _.addPin(inst, sel, pane); } }); // init state array to hold pin-buttons for (var i=0; i<4; i++) { var pane = $.layout.config.borderPanes[i]; inst.state[pane].pins = []; } // auto-init buttons onLoad if option is enabled if ( inst.options.autoBindCustomButtons ) _.init(inst); } , _unload: function (inst) { // TODO: unbind all buttons??? } }; // add initialization method to Layout's onLoad array of functions $.layout.onLoad.push( $.layout.buttons._load ); //$.layout.onUnload.push( $.layout.buttons._unload ); /** * jquery.layout.browserZoom 1.0 * $Date: 2011-12-29 08:00:00 (Thu, 29 Dec 2011) $ * * Copyright (c) 2012 * Kevin Dalman (http://allpro.net) * * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. * * @requires: UI Layout 1.3.0.rc30.1 or higher * * @see: http://groups.google.com/group/jquery-ui-layout * * TODO: Extend logic to handle other problematic zooming in browsers * TODO: Add hotkey/mousewheel bindings to _instantly_ respond to these zoom event */ // tell Layout that the plugin is available $.layout.plugins.browserZoom = true; $.layout.defaults.browserZoomCheckInterval = 1000; $.layout.optionsMap.layout.push("browserZoomCheckInterval"); /* * browserZoom methods */ $.layout.browserZoom = { _init: function (inst) { // abort if browser does not need this check if ($.layout.browserZoom.ratio() !== false) $.layout.browserZoom._setTimer(inst); } , _setTimer: function (inst) { // abort if layout destroyed or browser does not need this check if (inst.destroyed) return; var o = inst.options , s = inst.state // don't need check if inst has parentLayout, but check occassionally in case parent destroyed! // MINIMUM 100ms interval, for performance , ms = inst.hasParentLayout ? 5000 : Math.max( o.browserZoomCheckInterval, 100 ) ; // set the timer setTimeout(function(){ if (inst.destroyed || !o.resizeWithWindow) return; var d = $.layout.browserZoom.ratio(); if (d !== s.browserZoom) { s.browserZoom = d; inst.resizeAll(); } // set a NEW timeout $.layout.browserZoom._setTimer(inst); } , ms ); } , ratio: function () { var w = window , s = screen , d = document , dE = d.documentElement || d.body , b = $.layout.browser , v = b.version , r, sW, cW ; // we can ignore all browsers that fire window.resize event onZoom if ((b.msie && v > 8) || !b.msie ) return false; // don't need to track zoom if (s.deviceXDPI && s.systemXDPI) // syntax compiler hack return calc(s.deviceXDPI, s.systemXDPI); // everything below is just for future reference! if (b.webkit && (r = d.body.getBoundingClientRect)) return calc((r.left - r.right), d.body.offsetWidth); if (b.webkit && (sW = w.outerWidth)) return calc(sW, w.innerWidth); if ((sW = s.width) && (cW = dE.clientWidth)) return calc(sW, cW); return false; // no match, so cannot - or don't need to - track zoom function calc (x,y) { return (parseInt(x,10) / parseInt(y,10) * 100).toFixed(); } } }; // add initialization method to Layout's onLoad array of functions $.layout.onReady.push( $.layout.browserZoom._init ); })( jQuery );
overleaf/web/frontend/js/vendor/libs/jquery-layout.js/0
{ "file_path": "overleaf/web/frontend/js/vendor/libs/jquery-layout.js", "repo_id": "overleaf", "token_count": 111095 }
522
const FILE_PER_FOLDER = 2 const DOC_PER_FOLDER = 3 const FOLDER_PER_FOLDER = 2 const MAX_DEPTH = 7 function fakeId() { return Math.random().toString(16).replace(/0\./, 'random-test-id-') } function makeFileRefs(path) { const fileRefs = [] for (let index = 0; index < FILE_PER_FOLDER; index++) { fileRefs.push({ _id: fakeId(), name: `${path}-file-${index}.jpg` }) } return fileRefs } function makeDocs(path) { const docs = [] for (let index = 0; index < DOC_PER_FOLDER; index++) { docs.push({ _id: fakeId(), name: `${path}-doc-${index}.tex` }) } return docs } function makeFolders(path, depth = 0) { const folders = [] for (let index = 0; index < FOLDER_PER_FOLDER; index++) { const folderPath = `${path}-folder-${index}` folders.push({ _id: fakeId(), name: folderPath, folders: depth < MAX_DEPTH ? makeFolders(folderPath, depth + 1) : [], fileRefs: makeFileRefs(folderPath), docs: makeDocs(folderPath), }) } return folders } export const rootFolderLimit = [ { _id: fakeId(), name: 'rootFolder', folders: makeFolders('root'), fileRefs: makeFileRefs('root'), docs: makeDocs('root'), }, ]
overleaf/web/frontend/stories/fixtures/file-tree-limit.js/0
{ "file_path": "overleaf/web/frontend/stories/fixtures/file-tree-limit.js", "repo_id": "overleaf", "token_count": 486 }
523
import { useEffect } from 'react' import ShareProjectModal from '../js/features/share-project-modal/components/share-project-modal' import useFetchMock from './hooks/use-fetch-mock' import { withContextRoot } from './utils/with-context-root' export const LinkSharingOff = args => { useFetchMock(setupFetchMock) const project = { ...args.project, publicAccesLevel: 'private', } return withContextRoot(<ShareProjectModal {...args} />, { project }) } export const LinkSharingOn = args => { useFetchMock(setupFetchMock) const project = { ...args.project, publicAccesLevel: 'tokenBased', } return withContextRoot(<ShareProjectModal {...args} />, { project }) } export const LinkSharingLoading = args => { useFetchMock(setupFetchMock) const project = { ...args.project, publicAccesLevel: 'tokenBased', tokens: undefined, } return withContextRoot(<ShareProjectModal {...args} />, { project }) } export const NonAdminLinkSharingOff = args => { const project = { ...args.project, publicAccesLevel: 'private', } return withContextRoot(<ShareProjectModal {...args} isAdmin={false} />, { project, }) } export const NonAdminLinkSharingOn = args => { const project = { ...args.project, publicAccesLevel: 'tokenBased', } return withContextRoot(<ShareProjectModal {...args} isAdmin={false} />, { project, }) } export const RestrictedTokenMember = args => { // Override isRestrictedTokenMember to be true, then revert it back to the // original value on unmount // Currently this is necessary because the context value is set from window, // however in the future we should change this to set via props const originalIsRestrictedTokenMember = window.isRestrictedTokenMember window.isRestrictedTokenMember = true useEffect(() => { return () => { window.isRestrictedTokenMember = originalIsRestrictedTokenMember } }) const project = { ...args.project, publicAccesLevel: 'tokenBased', } return withContextRoot(<ShareProjectModal {...args} />, { project }) } export const LegacyLinkSharingReadAndWrite = args => { useFetchMock(setupFetchMock) const project = { ...args.project, publicAccesLevel: 'readAndWrite', } return withContextRoot(<ShareProjectModal {...args} />, { project }) } export const LegacyLinkSharingReadOnly = args => { useFetchMock(setupFetchMock) const project = { ...args.project, publicAccesLevel: 'readOnly', } return withContextRoot(<ShareProjectModal {...args} />, { project }) } export const LimitedCollaborators = args => { useFetchMock(setupFetchMock) const project = { ...args.project, features: { ...args.project.features, collaborators: 3, }, } return withContextRoot(<ShareProjectModal {...args} />, { project }) } const project = { _id: 'a-project', name: 'A Project', features: { collaborators: -1, // unlimited }, publicAccesLevel: 'private', tokens: { readOnly: 'ro-token', readAndWrite: 'rw-token', }, owner: { email: 'stories@overleaf.com', }, members: [ { _id: 'viewer-member', type: 'user', privileges: 'readOnly', name: 'Viewer User', email: 'viewer@example.com', }, { _id: 'author-member', type: 'user', privileges: 'readAndWrite', name: 'Author User', email: 'author@example.com', }, ], invites: [ { _id: 'test-invite-1', privileges: 'readOnly', name: 'Invited Viewer', email: 'invited-viewer@example.com', }, { _id: 'test-invite-2', privileges: 'readAndWrite', name: 'Invited Author', email: 'invited-author@example.com', }, ], } export default { title: 'Modals / Share Project', component: ShareProjectModal, args: { show: true, animation: false, isAdmin: true, user: {}, project, }, argTypes: { handleHide: { action: 'hide' }, }, } const contacts = [ // user with edited name { type: 'user', email: 'test-user@example.com', first_name: 'Test', last_name: 'User', name: 'Test User', }, // user with default name (email prefix) { type: 'user', email: 'test@example.com', first_name: 'test', }, // no last name { type: 'user', first_name: 'Eratosthenes', email: 'eratosthenes@example.com', }, // more users { type: 'user', first_name: 'Claudius', last_name: 'Ptolemy', email: 'ptolemy@example.com', }, { type: 'user', first_name: 'Abd al-Rahman', last_name: 'Al-Sufi', email: 'al-sufi@example.com', }, { type: 'user', first_name: 'Nicolaus', last_name: 'Copernicus', email: 'copernicus@example.com', }, ] function setupFetchMock(fetchMock) { const delay = 1000 fetchMock // list contacts .get('express:/user/contacts', { contacts }, { delay }) // change privacy setting .post('express:/project/:projectId/settings/admin', 200, { delay }) // update project member (e.g. set privilege level) .put('express:/project/:projectId/users/:userId', 200, { delay }) // remove project member .delete('express:/project/:projectId/users/:userId', 200, { delay }) // transfer ownership .post('express:/project/:projectId/transfer-ownership', 200, { delay, }) // send invite .post('express:/project/:projectId/invite', 200, { delay }) // delete invite .delete('express:/project/:projectId/invite/:inviteId', 204, { delay, }) // resend invite .post('express:/project/:projectId/invite/:inviteId/resend', 200, { delay, }) // send analytics event .post('express:/event/:key', 200) }
overleaf/web/frontend/stories/share-project-modal.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/share-project-modal.stories.js", "repo_id": "overleaf", "token_count": 2185 }
524
.author_details { font-size: 0.8em; color: @gray; } .post { img { border-radius: 3px; -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); max-width: 100%; height: auto; } } .blog { iframe { width: 100%; } > .page-header { h1 { margin: 0; } padding: 0; margin: 0; border: none; } .post { .page-header { h2 { margin-top: 0; } } } .page-header { h1 { a { color: @text-color; } .small { color: @gray-dark; font-size: 16px; display: inline-block; float: right; margin-top: 22px; } } } .blurb { ul { li { margin-bottom: @line-height-computed / 4; } } } }
overleaf/web/frontend/stylesheets/app/blog.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/blog.less", "repo_id": "overleaf", "token_count": 452 }
525
@stripe-width: 20px; @keyframes pdf-toolbar-stripes { from { background-position: 0 0; } to { background-position: @stripe-width 0; } } .pdf .toolbar.toolbar-pdf { .toolbar-small-mixin; .toolbar-alt-mixin; padding-right: 5px; &.changes-to-autocompile { // prettier-ignore #gradient > .striped(@color: rgba(255, 255, 255, 0.1), @angle: -45deg); background-size: @stripe-width @stripe-width; .animation(pdf-toolbar-stripes 2s linear infinite); } .auto-compile-status { color: white; margin-right: (@line-height-computed / 2); i { color: @brand-danger; } } .auto-compile-status when (@is-overleaf-light = true) { color: @ol-blue-gray-3; } } .pdf .toolbar.toolbar-pdf when (@is-overleaf-light = false) { border-bottom: 0; } .toolbar-pdf-left, .toolbar-pdf-right { display: flex; align-items: center; align-self: stretch; flex: 1 1 100%; } .toolbar-pdf-right { flex: 1 0 auto; } .btn-toggle-logs { &:focus, &:active:focus { outline: none; } } .btn-toggle-logs-label { padding-left: @line-height-computed / 4; } .pdf { background-color: @pdf-bg; } .pdf-viewer, .pdf-logs, .pdf-errors, .pdf-uncompiled { .full-size; top: @pdf-top-offset; } .pdf-logs, .pdf-errors, .pdf-uncompiled, .pdf-validation-problems { padding: @line-height-computed / 2; } .pdf-uncompiled { .fa { color: @blue; } } .btn-recompile-group { align-self: stretch; margin-right: 6px; border-radius: 0 @btn-border-radius-base @btn-border-radius-base 0; background-color: @btn-primary-bg; &.btn-recompile-group-has-changes { // prettier-ignore #gradient > .striped(@color: rgba(255, 255, 255, 0.2), @angle: -45deg); background-size: @stripe-width @stripe-width; .animation(pdf-toolbar-stripes 2s linear infinite); } } .btn-recompile { height: 100%; // .btn-primary; color: #fff; background-color: transparent; padding-top: 3px; padding-bottom: 3px; &:first-child { border-top-left-radius: 0; border-bottom-left-radius: 0; } &[disabled] { background-color: mix(@btn-primary-bg, @toolbar-alt-bg-color, 65%); .opacity(1); } } .btn-recompile-label { margin-left: @line-height-computed / 4; } .toolbar-text { padding-left: @padding-xs; } .pdf-viewer { iframe { width: 100%; height: 100%; border: none; } .pdfjs-viewer { .full-size; background-color: @pdfjs-bg; overflow: scroll; canvas, div.pdf-canvas { background: white; box-shadow: @pdf-page-shadow-color 0px 0px 10px; } div.pdf-canvas.pdfng-empty { background-color: white; } div.pdf-canvas.pdfng-loading { background-color: white; } .page-container { margin: 10px auto; padding: 0 10px; box-sizing: content-box; user-select: none; } } .progress-thin { position: absolute; top: -2px; height: 3px; left: 0; right: 0; .progress-bar { height: 100%; background-color: @link-color; } } .pdfjs-controls { position: absolute; padding: @line-height-computed / 2; top: 0; left: 0; display: inline-block; .btn-group { transition: opacity 0.5s ease, visibility 0 linear 0.5s; visibility: hidden; opacity: 0; } &:hover, &.flash { .btn-group { transition: none; visibility: visible; opacity: 1; } } i.fa-arrows-h { border-right: 2px solid white; border-left: 2px solid white; } i.fa-arrows-v { border-top: 2px solid white; border-bottom: 2px solid white; } } } .pdf-logs { overflow: auto; .alert { font-size: 0.9rem; margin-bottom: @line-height-computed / 2; cursor: pointer; .line-no { float: right; color: @log-line-no-color; font-weight: 700; .fa { opacity: 0; } } .entry-message { font-weight: 700; //font-family: @font-family-monospace; } .entry-content { white-space: pre-wrap; font-size: 0.8rem; //font-family: @font-family-monospace; } &:hover .line-no { color: inherit; .fa { opacity: 1; } } &.alert-danger { background-color: tint(@alert-danger-bg, 15%); &:hover { background-color: @alert-danger-bg; } } &.alert-warning { background-color: tint(@alert-warning-bg, 15%); &:hover { background-color: @alert-warning-bg; } } &.alert-info { background-color: tint(@alert-info-bg, 15%); &:hover { background-color: @alert-info-bg; } } } pre { font-size: 12px; } .dropdown { position: relative; } .force-recompile { margin-top: 10px; text-align: right; } } .synctex-controls { margin-right: -8px; position: absolute; z-index: @synctex-controls-z-index; padding: @synctex-controls-padding; top: 68px; } .synctex-control { @ol-synctex-control-size: 24px; align-items: center; display: flex; justify-content: center; font-size: 1em; margin-bottom: @ol-synctex-control-size / 2; width: @ol-synctex-control-size; height: @ol-synctex-control-size; border-radius: @ol-synctex-control-size / 2; padding: 0 0 2px; background-color: fade(@btn-default-bg, 80%); transition: background 0.15s ease; &[disabled] { opacity: 1; background-color: fade(@btn-default-bg, 60%); } > .synctex-control-icon { display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } > .synctex-spin-icon { margin-top: 2px; } } .synctex-control-goto-pdf > .synctex-control-icon { text-indent: 1px; // "Optical" adjustment. &::before { content: '\f061'; } } .synctex-control-goto-code > .synctex-control-icon { text-indent: -1px; // "Optical" adjustment. &::before { content: '\f060'; } } .editor-dark { .pdf-logs { background-color: lighten(@editor-dark-background-color, 10%); } .pdfjs-viewer { background-color: lighten(@editor-dark-background-color, 10%); } .pdf .toolbar { .toolbar-right a { i { border-color: @gray; } &:hover { i { border-color: @gray-light; } } } } } .keyboard-tooltip { .tooltip-inner { max-width: none; } } .keyboard-shortcut { white-space: nowrap; } @keyframes expand-feedback-area { from { max-height: 0; } to { max-height: 500px; } } .card-hint:extend(.card-thin) { margin-top: 10px; padding-bottom: 7px; cursor: default; &-icon-container { background: currentColor; width: 2.5rem; height: 2.5rem; font-size: 1.5rem; text-align: center; border-radius: 50%; float: left; margin-right: 10px; .fa { color: #fff; } .alert-danger & { color: @state-danger-border; } .alert-warning & { color: @state-warning-border; } .alert-info & { color: @state-info-border; } } &-text, &-feedback-label { color: @log-hints-color; font-size: 0.9rem; margin-bottom: 20px; } &-text { min-height: 35px; } &-feedback-label { font-size: inherit; margin-right: 0.5em; margin-bottom: 0; font-weight: normal; } &-ext-link, &-feedback { display: inline-block; font-size: 0.8rem; } &-footer a, &-text a { .alert-danger & { color: @state-danger-text; } .alert-warning & { color: @state-warning-text; } .alert-info & { color: @state-info-text; } } &-feedback { color: @log-hints-color; float: right; } &-extra-feedback { color: @log-hints-color; font-size: 0.8rem; margin-top: 10px; padding-bottom: 5px; animation: 0.5s ease-out expand-feedback-area; overflow: hidden; &-label { margin: 5px 0 10px; padding-top: 5px; border-top: solid 1px @gray-lighter; } .radio { margin: 5px; } textarea { font-size: 0.8rem; margin-bottom: 10px; padding: 5px; } input[type='radio'] { margin-top: 2px; } } & + p { margin-top: 20px; } } .files-dropdown-container { .pull-right(); position: relative; } .files-dropdown { display: inline-block; } .plv-text-layer { display: none; user-select: text; .pdf-page-container:hover &, .pdfjs-viewer-show-text & { display: block; } } @editor-and-logs-pane-toolbars-height: @toolbar-small-height + @toolbar-height; @btn-small-height: (@padding-small-vertical * 2)+ (@font-size-small * @line-height-small); #download-dropdown-list, #dropdown-files-logs-pane-list { overflow-y: auto; .dropdown-header { white-space: nowrap; } } #download-dropdown-list { max-height: calc( ~'100vh - ' @editor-and-logs-pane-toolbars-height ~' - ' @margin-md ); } #dropdown-files-logs-pane-list { max-height: calc( ~'100vh - ' @editor-and-logs-pane-toolbars-height ~' - ' @btn-small-height ~' - ' @margin-md ); } .toolbar-pdf-expand-btn { .btn-inline-link; margin-left: @margin-xs; color: @toolbar-icon-btn-color; border-radius: @border-radius-small; &:hover { color: @toolbar-icon-btn-hover-color; } &:active { background-color: @link-color; color: #fff; } &:focus { outline: 0; color: #fff; } }
overleaf/web/frontend/stylesheets/app/editor/pdf.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/editor/pdf.less", "repo_id": "overleaf", "token_count": 4388 }
526
.v1-import-title { text-align: center; margin-top: @line-height-computed / 2; } .v1-import-row { display: flex; align-items: center; } .v1-import-col { padding-left: 15px; padding-right: 15px; } .v1-import-col ul { margin-bottom: 0; } .v1-import-col--left { flex-shrink: 1.1; } .v1-import-img { width: 100%; margin-top: 30px; } .v1-import-cta { margin-top: 20px; margin-left: auto; margin-right: auto; width: 90%; text-align: center; } .v1-import-warning { color: #4b7fd1; font-size: 10em; line-height: 1em; } .v1-import-footer { display: flex; justify-content: space-evenly; text-align: left; } .v1-import-btn { width: 20rem; }
overleaf/web/frontend/stylesheets/app/list/v1-import-modal.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/list/v1-import-modal.less", "repo_id": "overleaf", "token_count": 314 }
527
.form-helper { display: inline-block; width: 1.3em; height: 1.3em; line-height: 1.3; vertical-align: initial; background-color: @gray; color: #fff; font-weight: bolder; border-radius: 50%; &:hover, &:focus { color: #fff; text-decoration: none; } } .price-breakdown { text-align: center; margin-bottom: -10px; } .input-feedback-message { display: none; font-size: 0.8em; .has-error & { display: inline-block; } } .payment-submit { padding-top: (@line-height-computed / 2); } .payment-method-toggle { margin-bottom: (@line-height-computed / 2); &-switch { display: inline-block; width: 50%; text-align: center; border: solid 1px @gray-lighter; border-radius: @border-radius-large 0 0 @border-radius-large; padding: (@line-height-computed / 2); color: @btn-switch-color; &:hover, &:focus { color: @btn-switch-color; text-decoration: none; } &:hover { color: @btn-switch-hover-color; } & + & { border-left-width: 0; border-radius: 0 @border-radius-large @border-radius-large 0; } &-selected { color: @link-active-color; box-shadow: inset 0 -2px 0 0; &:hover, &:focus { color: @link-active-color; } } } } .team-invite .message { margin: 3em 0; } .capitalised { text-transform: capitalize; } .three-d-secure-container { > .three-d-secure-recurly-container { height: 400px; > div[data-recurly='three-d-secure-container'] { height: 100%; } } }
overleaf/web/frontend/stylesheets/app/subscription.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/subscription.less", "repo_id": "overleaf", "token_count": 691 }
528
// // A stylesheet for use with Bootstrap 3.x // @author: Dan Grossman http://www.dangrossman.info/ // @copyright: Copyright (c) 2012-2015 Dan Grossman. All rights reserved. // @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php // @website: https://www.improvely.com/ // // // VARIABLES // // // Settings // The class name to contain everything within. @arrow-size: 7px; // // Colors @daterangepicker-color: @brand-primary; @daterangepicker-bg-color: #fff; @daterangepicker-cell-color: @daterangepicker-color; @daterangepicker-cell-border-color: transparent; @daterangepicker-cell-bg-color: @daterangepicker-bg-color; @daterangepicker-cell-hover-color: @daterangepicker-color; @daterangepicker-cell-hover-border-color: @daterangepicker-cell-border-color; @daterangepicker-cell-hover-bg-color: #eee; @daterangepicker-in-range-color: #000; @daterangepicker-in-range-border-color: transparent; @daterangepicker-in-range-bg-color: #ebf4f8; @daterangepicker-active-color: #fff; @daterangepicker-active-bg-color: #138a07; @daterangepicker-active-border-color: transparent; @daterangepicker-unselected-color: #999; @daterangepicker-unselected-border-color: transparent; @daterangepicker-unselected-bg-color: #fff; // // daterangepicker @daterangepicker-width: 278px; @daterangepicker-padding: 4px; @daterangepicker-z-index: 3000; @daterangepicker-border-size: 1px; @daterangepicker-border-color: #ccc; @daterangepicker-border-radius: 4px; // // Calendar @daterangepicker-calendar-margin: @daterangepicker-padding; @daterangepicker-calendar-bg-color: @daterangepicker-bg-color; @daterangepicker-calendar-border-size: 1px; @daterangepicker-calendar-border-color: @daterangepicker-bg-color; @daterangepicker-calendar-border-radius: @daterangepicker-border-radius; // // Calendar Cells @daterangepicker-cell-size: 20px; @daterangepicker-cell-width: @daterangepicker-cell-size; @daterangepicker-cell-height: @daterangepicker-cell-size; @daterangepicker-cell-border-radius: @daterangepicker-calendar-border-radius; @daterangepicker-cell-border-size: 1px; // // Dropdowns @daterangepicker-dropdown-z-index: @daterangepicker-z-index + 1; // // Controls @daterangepicker-control-height: 30px; @daterangepicker-control-line-height: @daterangepicker-control-height; @daterangepicker-control-color: #555; @daterangepicker-control-border-size: 1px; @daterangepicker-control-border-color: #ccc; @daterangepicker-control-border-radius: 4px; @daterangepicker-control-active-border-size: 1px; @daterangepicker-control-active-border-color: @brand-primary; @daterangepicker-control-active-border-radius: @daterangepicker-control-border-radius; @daterangepicker-control-disabled-color: #ccc; // // Ranges @daterangepicker-ranges-color: @brand-primary; @daterangepicker-ranges-bg-color: daterangepicker-ranges-color; @daterangepicker-ranges-border-size: 1px; @daterangepicker-ranges-border-color: @daterangepicker-ranges-bg-color; @daterangepicker-ranges-border-radius: @daterangepicker-border-radius; @daterangepicker-ranges-hover-color: #fff; @daterangepicker-ranges-hover-bg-color: @daterangepicker-ranges-color; @daterangepicker-ranges-hover-border-size: @daterangepicker-ranges-border-size; @daterangepicker-ranges-hover-border-color: @daterangepicker-ranges-hover-bg-color; @daterangepicker-ranges-hover-border-radius: @daterangepicker-border-radius; @daterangepicker-ranges-active-border-size: @daterangepicker-ranges-border-size; @daterangepicker-ranges-active-border-color: @daterangepicker-ranges-bg-color; @daterangepicker-ranges-active-border-radius: @daterangepicker-border-radius; // // STYLESHEETS // .daterangepicker { position: absolute; color: @daterangepicker-color; background-color: @daterangepicker-bg-color; border-radius: @daterangepicker-border-radius; width: @daterangepicker-width; padding: @daterangepicker-padding; margin-top: @daterangepicker-border-size; // TODO: Should these be parameterized?? // top: 100px; // left: 20px; @arrow-prefix-size: @arrow-size; @arrow-suffix-size: (@arrow-size - @daterangepicker-border-size); &:before, &:after { position: absolute; display: inline-block; border-bottom-color: rgba(0, 0, 0, 0.2); content: ''; } &:before { top: -@arrow-prefix-size; border-right: @arrow-prefix-size solid transparent; border-left: @arrow-prefix-size solid transparent; border-bottom: @arrow-prefix-size solid @daterangepicker-border-color; } &:after { top: -@arrow-suffix-size; border-right: @arrow-suffix-size solid transparent; border-bottom: @arrow-suffix-size solid @daterangepicker-bg-color; border-left: @arrow-suffix-size solid transparent; } &.opensleft { &:before { // TODO: Make this relative to prefix size. right: @arrow-prefix-size + 2px; } &:after { // TODO: Make this relative to suffix size. right: @arrow-suffix-size + 4px; } } &.openscenter { &:before { left: 0; right: 0; width: 0; margin-left: auto; margin-right: auto; } &:after { left: 0; right: 0; width: 0; margin-left: auto; margin-right: auto; } } &.opensright { &:before { // TODO: Make this relative to prefix size. left: @arrow-prefix-size + 2px; } &:after { // TODO: Make this relative to suffix size. left: @arrow-suffix-size + 4px; } } &.dropup { margin-top: -5px; // NOTE: Note sure why these are special-cased. &:before { top: initial; bottom: -@arrow-prefix-size; border-bottom: initial; border-top: @arrow-prefix-size solid @daterangepicker-border-color; } &:after { top: initial; bottom: -@arrow-suffix-size; border-bottom: initial; border-top: @arrow-suffix-size solid @daterangepicker-bg-color; } } &.dropdown-menu { max-width: none; z-index: @daterangepicker-dropdown-z-index; } &.single { .ranges, .calendar { float: none; } } /* Calendars */ &.show-calendar { .calendar { display: block; } } .calendar { display: none; max-width: @daterangepicker-width - (@daterangepicker-calendar-margin * 2); margin: @daterangepicker-calendar-margin; &.single { .calendar-table { border: none; } } th, td { white-space: nowrap; text-align: center; // TODO: Should this actually be hard-coded? min-width: 32px; } } .calendar-table { border: @daterangepicker-calendar-border-size solid @daterangepicker-calendar-border-color; padding: @daterangepicker-calendar-margin; border-radius: @daterangepicker-calendar-border-radius; background-color: @daterangepicker-calendar-bg-color; } table { width: 100%; margin: 0; } td, th { text-align: center; width: @daterangepicker-cell-width; height: @daterangepicker-cell-height; border-radius: @daterangepicker-cell-border-radius; border: @daterangepicker-cell-border-size solid @daterangepicker-cell-border-color; white-space: nowrap; cursor: pointer; &.available { &:hover { background-color: @daterangepicker-cell-hover-bg-color; border-color: @daterangepicker-cell-hover-border-color; color: @daterangepicker-cell-hover-color; } } &.week { font-size: 80%; color: #ccc; } } td { &.off { &, &.in-range, &.start-date, &.end-date { background-color: @daterangepicker-unselected-bg-color; border-color: @daterangepicker-unselected-border-color; color: @daterangepicker-unselected-color; } } // // Date Range &.in-range { background-color: @daterangepicker-in-range-bg-color; border-color: @daterangepicker-in-range-border-color; color: @daterangepicker-in-range-color; // TODO: Should this be static or should it be parameterized? border-radius: 0; } &.start-date { border-radius: @daterangepicker-cell-border-radius 0 0 @daterangepicker-cell-border-radius; } &.end-date { border-radius: 0 @daterangepicker-cell-border-radius @daterangepicker-cell-border-radius 0; } &.start-date.end-date { border-radius: @daterangepicker-cell-border-radius; } &.active { &, &:hover { background-color: @daterangepicker-active-bg-color; border-color: @daterangepicker-active-border-color; color: @daterangepicker-active-color; } } } th { &.month { width: auto; } } // // Disabled Controls // td, option { &.disabled { color: #999; cursor: not-allowed; text-decoration: line-through; } } select { &.monthselect, &.yearselect { font-size: 12px; padding: 1px; height: auto; margin: 0; cursor: default; } &.monthselect { margin-right: 2%; width: 56%; } &.yearselect { width: 40%; } &.hourselect, &.minuteselect, &.secondselect, &.ampmselect { width: 50px; margin-bottom: 0; } } // // Text Input Controls (above calendar) // .input-mini { border: @daterangepicker-control-border-size solid @daterangepicker-control-border-color; border-radius: @daterangepicker-control-border-radius; color: @daterangepicker-control-color; height: @daterangepicker-control-line-height; line-height: @daterangepicker-control-height; display: block; vertical-align: middle; // TODO: Should these all be static, too?? margin: 0 0 5px 0; padding: 0 6px 0 28px; width: 100%; &.active { border: @daterangepicker-control-active-border-size solid @daterangepicker-control-active-border-color; border-radius: @daterangepicker-control-active-border-radius; } } .daterangepicker_input { position: relative; padding-left: 0; i { position: absolute; // NOTE: These appear to be eyeballed to me... left: 8px; top: 10px; } } &.rtl { .input-mini { padding-right: 28px; padding-left: 6px; } .daterangepicker_input i { left: auto; right: 8px; } } // // Time Picker // .calendar-time { text-align: center; margin: 5px auto; line-height: @daterangepicker-control-line-height; position: relative; padding-left: 28px; select { &.disabled { color: @daterangepicker-control-disabled-color; cursor: not-allowed; } } } } // // Predefined Ranges // .ranges { font-size: 11px; float: none; margin: 4px; text-align: left; ul { list-style: none; margin: 0 auto; padding: 0; width: 100%; } li { font-size: 13px; background-color: @daterangepicker-ranges-bg-color; border: @daterangepicker-ranges-border-size solid @daterangepicker-ranges-border-color; border-radius: @daterangepicker-ranges-border-radius; color: @daterangepicker-ranges-color; padding: 3px 12px; margin-bottom: 8px; cursor: pointer; &:hover { background-color: @daterangepicker-ranges-hover-bg-color; color: @daterangepicker-ranges-hover-color; } &.active { background-color: @daterangepicker-ranges-hover-bg-color; border: @daterangepicker-ranges-hover-border-size solid @daterangepicker-ranges-hover-border-color; color: @daterangepicker-ranges-hover-color; } } } /* Larger Screen Styling */ @media (min-width: 564px) { .daterangepicker { .glyphicon { font-family: FontAwesome; } .glyphicon-chevron-left:before { content: '\f053'; } .glyphicon-chevron-right:before { content: '\f054'; } .glyphicon-calendar:before { content: '\f073'; } width: auto; .ranges { ul { width: 160px; } } &.single { .ranges { ul { width: 100%; } } .calendar.left { clear: none; } &.ltr { .ranges, .calendar { float: left; } } &.rtl { .ranges, .calendar { float: right; } } } &.ltr { direction: ltr; text-align: left; .calendar { &.left { clear: left; margin-right: 0; .calendar-table { border-right: none; border-top-right-radius: 0; border-bottom-right-radius: 0; } } &.right { margin-left: 0; .calendar-table { border-left: none; border-top-left-radius: 0; border-bottom-left-radius: 0; } } } .left .daterangepicker_input { padding-right: 12px; } .calendar.left .calendar-table { padding-right: 12px; } .ranges, .calendar { float: left; } } &.rtl { direction: rtl; text-align: right; .calendar { &.left { clear: right; margin-left: 0; .calendar-table { border-left: none; border-top-left-radius: 0; border-bottom-left-radius: 0; } } &.right { margin-right: 0; .calendar-table { border-right: none; border-top-right-radius: 0; border-bottom-right-radius: 0; } } } .left .daterangepicker_input { padding-left: 12px; } .calendar.left .calendar-table { padding-left: 12px; } .ranges, .calendar { text-align: right; float: right; } } } } @media (min-width: 730px) { /* force the calendar to display on one row */ &.show-calendar { min-width: 658px; /* width of all contained elements, IE/Edge fallback */ width: -moz-max-content; width: -webkit-max-content; width: max-content; } .daterangepicker { .ranges { width: auto; } &.ltr { .ranges { float: left; clear: none !important; } } &.rtl { .ranges { float: right; } } .calendar { clear: none !important; } } }
overleaf/web/frontend/stylesheets/components/daterange-picker.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/daterange-picker.less", "repo_id": "overleaf", "token_count": 6585 }
529
.list-like-table { border: 1px solid @hr-border; border-radius: @border-radius-base; list-style: none; margin: 0; padding: 0 @padding-sm; li { border-top: 1px solid @hr-border; div { display: table-cell; float: none; vertical-align: middle; } .row { display: table; margin: 0; width: 100%; } &:first-child { border-top: 0; } } }
overleaf/web/frontend/stylesheets/components/lists.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/lists.less", "repo_id": "overleaf", "token_count": 196 }
530
.ol-tabs { // Overrides for nav.less .nav-tabs { border: 0 !important; margin-bottom: 0; margin-top: -@line-height-computed; //- adjusted for portal-name padding: @padding-lg 0 @padding-md; text-align: center; } .nav-tabs > li { display: inline-block; float: none; a { border: 0; color: @link-color-alt; &:focus, &:hover { background-color: transparent !important; border: 0; color: @link-hover-color-alt; } } } li.active > a { background-color: transparent !important; border: 0 !important; border-bottom: 1px solid @accent-color-secondary!important; color: @accent-color-secondary!important; &:hover { border-bottom: 1px solid @accent-color-secondary!important; color: @accent-color-secondary!important; } } .tab-content:extend(.container) { background-color: transparent !important; border: none !important; } }
overleaf/web/frontend/stylesheets/components/tabs.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/tabs.less", "repo_id": "overleaf", "token_count": 405 }
531
// // Scaffolding // -------------------------------------------------- // Reset the box-sizing // // Heads up! This reset may cause conflicts with some third-party widgets. // For recommendations on resolving such conflicts, see // http://getbootstrap.com/getting-started/#third-box-sizing * { .box-sizing(border-box); } *:before, *:after { .box-sizing(border-box); } // Body reset html { //font-size: 62.5%; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); height: 100%; } body { font-family: @font-family-base; font-size: @font-size-base; line-height: @line-height-base; color: @text-color; background-color: @body-bg; min-height: 100%; position: relative; padding-bottom: @footer-height; & > .content { min-height: calc(~'100vh -' @footer-height); padding-top: @header-height + @content-margin-vertical; } } // Reset fonts for relevant elements input, button, select, textarea { font-family: inherit; font-size: inherit; line-height: inherit; } // Links a { color: @link-color; text-decoration: none; &:hover, &:focus { color: @link-hover-color; text-decoration: underline; } &:focus { .tab-focus(); } } // Figures // // We reset this here because previously Normalize had no `figure` margins. This // ensures we don't break anyone's use of the element. figure { margin: 0; } // Images img { vertical-align: middle; } // Responsive images (ensure images don't scale beyond their parents) .img-responsive { .img-responsive(); } // Rounded corners .img-rounded { border-radius: @border-radius-large; } // Image thumbnails // // Heads up! This is mixin-ed into thumbnails.less for `.thumbnail`. .img-thumbnail { padding: @thumbnail-padding; line-height: @line-height-base; background-color: @thumbnail-bg; border: 1px solid @thumbnail-border; border-radius: @thumbnail-border-radius; .transition(all 0.2s ease-in-out); // Keep them at most 100% wide .img-responsive(inline-block); } // Perfect circle .img-circle { border-radius: 50%; // set radius in percents } // Horizontal rules hr { margin-top: @line-height-computed; margin-bottom: @line-height-computed; border: 0; border-top: 1px solid @hr-border; &.thin { margin-top: @line-height-computed / 2; margin-bottom: @line-height-computed / 2; } } // Only display content to screen readers // // See: http://a11yproject.com/posts/how-to-hide-content/ .sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } .content { padding-top: @content-margin-vertical; padding-bottom: @content-margin-vertical; } .content-alt { background-color: @content-alt-bg-color; } .row-spaced { margin-top: @line-height-computed; } .row-spaced-small { margin-top: @line-height-computed / 2; } .row-spaced-large { margin-top: @line-height-computed * 2; }
overleaf/web/frontend/stylesheets/core/scaffolding.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/core/scaffolding.less", "repo_id": "overleaf", "token_count": 1079 }
532
#!/bin/bash SHARELATEX_CONFIG=/app/config/settings.webpack.js npm run webpack:production & WEBPACK=$! wait $WEBPACK && echo "Webpack complete" || exit 1
overleaf/web/install_deps.sh/0
{ "file_path": "overleaf/web/install_deps.sh", "repo_id": "overleaf", "token_count": 56 }
533
{ "linked_accounts": "contas ligadas", "unable_to_extract_the_supplied_zip_file": "Abrir este conteúdo no Overleaf falhou porque o arquivo zip não pôde ser extraído. Por favor, certifique-se de que é um arquivo zip válido. Se isso continuar acontecendo para links em um site específico, informe isso a eles.", "the_file_supplied_is_of_an_unsupported_type ": "O link para abrir este conteúdo no Overleaf apontou para o tipo errado de arquivo. Tipos de arquivos válidos são arquivos .tex e .zip. Se isso continuar acontecendo para links em um site específico, informe isso a eles.", "the_requested_publisher_was_not_found": "The link to open this content on Overleaf specified a publisher that could not be found. If this keeps happening for links on a particular site, please report this to them.", "the_supplied_uri_is_invalid": "O link para abrir este conteúdo no Overleaf incluiu um URI inválido. Se isso continuar acontecendo nos links de um site específico, informe isso a eles.", "the_requested_conversion_job_was_not_found": "O link para abrir este conteúdo no Overleaf especificou um trabalho de conversão que não pôde ser encontrado. É possível que o trabalho tenha expirado e precise ser executado novamente. Se isso continuar acontecendo nos links de um site específico, informe isso a eles.", "not_found_error_from_the_supplied_url": "O link para abrir este conteúdo no Overleaf apontou para um arquivo que não foi encontrado. Se isso continuar acontecendo nos links de um site específico, informe isso a eles.", "too_many_requests": "Muitas solicitações foram recebidas em um curto espaço de tempo. Por favor, aguarde alguns instantes e tente novamente.", "password_change_passwords_do_not_match": "Senhas não coincidem", "github_for_link_shared_projects": "Este projeto foi acessado por meio do compartilhamento de links e não será sincronizado com o seu Github, a menos que você seja convidado por e-mail pelo proprietário do projeto.", "browsing_project_latest_for_pseudo_label": "Navegando no estado atual do seu projeto", "history_label_project_current_state": "Estado atual", "download_project_at_this_version": "Download do projeto nesta versão", "submit": "enviar", "help_articles_matching": "Artigos de ajuda que correspondem ao seu assunto", "dropbox_for_link_share_projs": "Este projeto foi acessado via compartilhamento de links e não será sincronizado com o seu Dropbox, a menos que você seja convidado por e-mail pelo proprietário do projeto", "clear_search": "limpar pesquisa", "email_registered_try_alternative": "Desculpe, não temos uma conta que confere com essas credenciais. Talvez você tenha se inscrito com um provedor diferente.", "access_your_projects_with_git": "Acesse seus projetos com o Git", "ask_proj_owner_to_upgrade_for_git_bridge": "Solicite ao proprietário do projeto para atualizar sua conta para usar o git", "export_csv": "Exportar CSV", "add_comma_separated_emails_help": "Separa múltiplos endereços de emails utilizando vírgula (,).", "members_management": "Gerenciamento de membros", "managers_management": "Gerenciamento de gerentes", "institution_account": "Conta Institucional", "git": "Git", "clone_with_git": "Clonar com o Git", "git_bridge_modal_description": "Você pode usar <code>git clone</code> no seu projeto usando o link abaixo.", "managers_cannot_remove_admin": "Administradores não podem ser removidos", "managers_cannot_remove_self": "Gerentes não podem remover a si mesmos", "user_not_found": "Usuário não encontrado", "user_already_added": "Usuário já foi adicionado", "bonus_twitter_share_text": "Estou usando o __appName__, o editor gratuito online e colaborativo de LaTeX - é muito bom e fácil de usar!", "bonus_email_share_header": "Editor Online de LaTeX que você deve gostar", "bonus_email_share_body": "Oi, eu estou usando o editor online de LaTeX __appName__ e acredito que você vai ter interesse ver dar uma olhada.", "bonus_share_link_text": "Editor Online de LaTeX __appName__", "bonus_facebook_name": "__appName__ - Editor Online de LaTeX", "bonus_facebook_caption": "Projetos e Compilação ilimitados e gratuitos", "bonus_facebook_description": "__appName__ é um editor online e gratuito de LaTeX. Colaboração em tempo real como o Google Docs, com Dropbox, histórico e auto-completar", "remove_manager": "Remover gerente", "invalid_element_name": "Não pode copiar o seu projeto porque os arquivos contém caracteres inválidos (como asterisco, barras ou caracteres de controle). Por favor, renomeie os arquivos e tente novamente.", "password_change_failed_attempt": "Alteração da senha falhou", "password_change_successful": "Senha alterada", "not_registered": "Não registrado", "featured_latex_templates": "Templates LaTeX Destacados", "no_featured_templates": "Sem templates destacados", "try_again": "Por favor, tente novamente", "email_required": "Email obrigatório", "registration_error": "Erro de Registro", "newsletter-accept": "Gostaria de receber e-mails sobre ofertas de produtos, notícias e eventos da empresa.", "resending_confirmation_email": "Reenviando email de confirmação", "please_confirm_email": "Por favor, confirme seu e-mail __emailAddress__ clicando no link no e-mail de confirmação", "register_using_service": "Registre-se usando __service__", "login_to_overleaf": "Faça o login no Overleaf", "login_with_email": "Entre com seu email", "login_with_service": "Logar com __service__", "first_time_sl_user": "Primeira vez aqui como usuário do ShareLaTeX", "migrate_from_sl": "Migrar do ShareLaTeX", "dont_have_account": "Não tem uma conta?", "sl_extra_info_tooltip": "Por favor, faça o login no ShareLaTeX para mover sua conta para o Overleaf. Levará apenas alguns segundos. Se você tiver uma assinatura do ShareLaTeX, ela será automaticamente transferida para o Overleaf.", "register_using_email": "Registre-se usando seu email", "login_register_or": "ou", "to_add_more_collaborators": "Para adicionar mais colaboradores ou ativar o compartilhamento de links, pergunte ao proprietário do projeto", "by": "por", "emails": "E-mails", "editor_theme": "Tema do editor", "overall_theme": "Tema Geral", "faq_how_does_free_trial_works_answer": "Você obtém acesso total ao plano __appName__ escolhido durante a avaliação gratuita de __len __ dias. Não há obrigação de continuar além da versão de avaliação. Seu cartão será cobrado no final da avaliação de __len__ dias, a menos que você cancele antes disso. Você pode cancelar via suas configurações de assinatura.", "thousands_templates": "Milhares de templates", "get_instant_access_to": "Tenha acesso instantâneo a", "ask_proj_owner_to_upgrade_for_full_history": "Por favor, peça ao dono do projeto para atualizar para acessar o recurso de Histórico Completo.", "currently_seeing_only_24_hrs_history": "Você está vendo as alterações das últimas 24 horas neste projeto.", "archive_projects": "Projetos Arquivados", "archive_and_leave_projects": "Projetos Arquivados e Deixados", "about_to_archive_projects": "Você está prestes a arquivar os seguintes projetos:", "please_confirm_your_email_before_making_it_default": "Por favor, confirme o seu email antes de tornar ele padrão.", "back_to_editor": "Voltar ao editor", "generic_history_error": "Algo deu errado ao tentar buscar o histórico do seu projeto. Se o erro persistir, entre em contato conosco via:", "unconfirmed": "Não confirmado", "please_check_your_inbox": "Por favor, verifique sua caixa de entrada", "resend_confirmation_email": "Reenviar e-mail de confirmação", "history_label_created_by": "Criado por", "history_label_this_version": "Etiquetar esta versão", "history_add_label": "Adicionar etiqueta", "history_adding_label": "Adicionando marcador", "history_new_label_name": "Novo nome do marcador", "history_new_label_added_at": "Um novo marcador será adicionado a partir de", "history_delete_label": "Excluir marcador", "history_deleting_label": "Excluindo marcador", "history_are_you_sure_delete_label": "Tem certeza de que deseja excluir o seguinte marcador", "browsing_project_labelled": "Procurando versão do projeto com marcador", "history_view_all": "Todo o histórico", "history_view_labels": "Marcadores", "history_view_a11y_description": "Mostrar todo o histórico do projeto ou apenas versões com marcadores.", "add_another_email": "Adicionar outro e-mail", "start_by_adding_your_email": "Comece adicionando o seu e-mail.", "is_email_affiliated": "O seu e-mail está afiliado a uma instituição? ", "let_us_know": "Conte para nós", "add_new_email": "Adicionar novo e-mail", "error_performing_request": "Um erro ocorreu enquanto sua solicitação era processada.", "reload_emails_and_affiliations": "Recarregar e-mails e afiliações", "emails_and_affiliations_title": "E-mails e Afiliações", "emails_and_affiliations_explanation": "Adicionar outros e-mails à sua conta para acessar qualquer melhoria que a sua universidade ou instituição tem, para facilitar para colaboradores encontrarem vocês e para ter certeza que você consiga recuperar a sua conta.", "institution_and_role": "Instituição e papel", "add_role_and_department": "Adicionar perfil e departamento", "save_or_cancel-save": "Salvar", "save_or_cancel-or": "ou", "save_or_cancel-cancel": "Cancelar", "make_default": "Tornar padrão", "remove": "remover", "confirm_email": "Confirme o Email", "invited_to_join_team": "Você foi convidado para participar de uma equipe", "join_team": "Junte-se à equipe", "accepted_invite": "Convite aceito", "invited_to_group": "__inviterName__ lhe convidou para entrar no time no __appName__", "join_team_explanation": "Por favor, clique no botão abaixo para entrar no time e aproveitar os benefícios de uma conta paga no __appName__.", "accept_invitation": "Aceitar convite", "joined_team": "Você entrou no time gerenciado por __inviterName__", "compare_to_another_version": "Compare com outra versão", "file_action_edited": "Editado", "file_action_renamed": "Renomeado", "file_action_created": "Criado", "file_action_deleted": "Deletado", "browsing_project_as_of": "Navegando projecto como", "view_single_version": "Ver versão simples", "font_family": "Família da Fonte", "line_height": "Altura da Linha", "compact": "Compacto", "wide": "Largo", "default": "Padrão", "leave": "Sair", "archived_projects": "Projetos Arquivados", "archive": "Arquivar", "student_disclaimer": "O desconto educacional se aplica à todos os estudantes de instituições secundárias e pós-secundárias (escolas e universidades). Nos poderemos entrar em contato com você para confirmar se você é elegível para o desconto.", "billed_after_x_days": "Você não será cobrado até que os __len__ dias da experimentação expirar.", "looking_multiple_licenses": "Procurando por lincenças múltiplas?", "reduce_costs_group_licenses": "Você pode diminuir seu trabalho e reduzir os custos com nosso desconto para licenças para grupo.", "find_out_more": "Descubra Mais", "compare_plan_features": "Compare os Recursos dos Planos", "in_good_company": "Você esta em Boa Companhia", "unlimited": "Ilimitado", "priority_support": "Suporte prioritário", "dropbox_integration_lowercase": "Integração com Dropbox", "github_integration_lowercase": "Integração com GitHub", "discounted_group_accounts": "disconto para contas de grupo", "referring_your_friends": "referenciando seus amigos", "still_have_questions": "Ainda tem dúvidas?", "quote_erdogmus": "A habilidade natural para acompanhar mudanças e colaboração em tempo real é o que diferencia o ShareLaTeX.", "quote_henderson": "ShareLaTeX se mostrou a ferramenta mais poderosa e robusta para colaboração que é amplamente utilizada em nossa Escola.", "best_value": "Melhor valor", "faq_how_free_trial_works_question": "Como foi o uso da versão de experimentação?", "faq_change_plans_question": "Eu posso alterar o plano depois?", "faq_do_collab_need_premium_question": "Todos os meus colaboradores precisam ter uma conta premium?", "faq_need_more_collab_question": "E se eu precisar de mais colaboradores?", "faq_purchase_more_licenses_question": "Eu posso comprar licenças adicionais para os meus colegas?", "faq_monthly_or_annual_question": "Eu devo escolher o pagamento mensal ou anual?", "faq_how_to_pay_question": "Eu posso pagar online com meu cartão de débito, crédito ou Paypal?", "faq_pay_by_invoice_question": "Eu posso pagar com boleto ou ordem de pedido?", "reference_search": "Busca avançada de referências", "reference_search_info": "Você sempre pode buscar pela chave da citação e a busca avançada por referências também permite que você busque por autor, título, ano e publicação.", "reference_sync": "Gerenciador de sincronia de referências", "reference_sync_info": "Gerencie sua biblioteca de referências no Mendeley e vincule ele diretamente com o seu arquivo .bib no Overleaf, assim você pode citar facilmente qualquer referência na biblioiteca do seu Mendeley.", "faq_how_free_trial_works_answer": "Você escolheu ter acesso à versão de experimentação do __appName__ por __len__ dias. Não há nenhuma obrigação para você continuar além da emperimentação. Seu cartão será cobrado apenas depois do __len__º dia, a não ser que você cancele antes. Você pode cancelar nas configurações da sua inscrição.", "faq_change_plans_answer": "Sim, você pode trocar de plano em qualquer momento pelas configurações da sua inscrição. Isso inclue opções para trocar para um plano diferente, trocar a cobrança mensal e anual, ou cancelar e migrar para o plano gratuíto.", "faq_do_collab_need_premium_answer": "Recursos Premium, como acompanhar alterações estarão disponíveis para os seus colaboradores nos projetos que você criar, mesmo que o seu colaborador tenha conta grátis.", "faq_need_more_collab_answer": "Você pode migrar para um dos nossos planos pagos, com suporte para mais colaboradores. Você também pode adicionar colaboradores nas nossas contas gratuítas referenciando os seus amigos pelo link __referFriendsLink__.", "faq_purchase_more_licenses_answer": "Sim, nós oferecemos __groupLink__, que são mais fácil de administrar, ajudando a economizar no seu trabalho, ajudando a reduzir custos na compra de várias licenças.", "faq_monthly_or_annual_answer": "Cobrança anual é um meio de reduzir seu trabalho de gerenciar sua conta. Se você preferir gerenciar apenas uma conta por ano ao invés de doze, o pagamento anual é pra você.", "faq_how_to_pay_answer": "Sim, você pode. A maioria dos cartões de créditos, débitos e Paypal são aceitos. Selecione o seu plano e você terá a opção de pagar com cartão ou através do Paypal quando for a hora de fazer o pagamento.", "powerful_latex_editor": "Editor Poderoso de LaTeX", "realtime_track_changes": "Acompanhe alterações em tempo real.", "realtime_track_changes_info": "Agora você não precisa escolher entre acompanhar as alterações e as configurações no LaTeX. Deixe comentários, acompanhe sua lista de tarefas, e aceite ou rejeite as alterações dos outros.", "full_doc_history_info": "Volte no tempo e veja qualquer versão e quem fez as alterações. Não importa o que aconteça, nós te damos cobertura.", "dropbox_integration_info": "Trabalhe online ou offline perfeitamente com a sincronia do Dropbox. As suas alterações locais serão enviadas automaticamente para a sua versão do Overleaf e vice-e-versa.", "github_integration_info": "Enviar e baixe suas alterações do GitHub, assim você e seus colaboradores podem trabalhar offline com o git e online com o Overleaf.", "latex_editor_info": "Tudo que você precisa num editar moderno de LaTeX - correção ortográfica, auto-completar inteligente, realce de sintaxe, diversas cores de temas, atalhos de vim e emacs, ajuda com mensagens de aviso e erros do LaTeX e muito mais.", "change_plans_any_time": "Você pode mudar seu plano ou mudar sua conta em qualquer momento. ", "number_collab": "Número de colaboradores", "unlimited_private_info": "Todos os seus projetos serão privador por padrão. Convide colaboradores para ler ou editar por endereço de email ou envia um link secreto para eles.", "unlimited_private": "Projetos privados ilimitados", "realtime_collab": "Colaboração em tempo real", "realtime_collab_info": "Quando você trabalha em conjunto, você pode ver o cursor dos seus colaboradores e as alterações em tempo real, assim todos sempre tem a última versão.", "hundreds_templates": "Centenas de modelos", "hundreds_templates_info": "Faça documentos lindos começando com modelos LaTeX da nossa galeria: revistas, conferências, teses, relatórios, currículos e muito mais.", "instant_access": "Tenha acesso instantâneo ao __appName__", "tagline_personal": "Ideal para trabalhar individualmente", "tagline_collaborator": "Incrível para trabalhos em grupo", "tagline_professional": "Para aqueles que trabalhos com vários", "tagline_student_annual": "Economize ainda mais", "tagline_student_monthly": "Incrível para um único mandato", "all_premium_features": "Todos os recursos premium", "sync_dropbox_github": "Sincronize com Dropbox e GitHub", "track_changes": "Acompanhe as mudanças", "tooltip_hide_pdf": "Clique para esconder o PDF", "tooltip_show_pdf": "Clique para mostrar o PDF", "tooltip_hide_filetree": "Clique para esconder a árvore de arquivos", "tooltip_show_filetree": "Clique para mostrar a árvore de arquivos", "cannot_verify_user_not_robot": "Desculpe, não conseguimos verificar se você não é um robô. Por favor, verifique se o Google reCAPTCHA não está sendo bloqueado por algum firewall ou bloqueador de anúncios.", "uncompiled_changes": "Mudanças não Compiladas", "code_check_failed": "Verificação do código falhou", "code_check_failed_explanation": "Seu código contém erros que precisam ser corrigidos antes de rodar a auto-compilação", "tags_slash_folders": "Rótulos/Pastas", "file_already_exists": "Já existe um arquivo ou pasta com esse nome", "import_project_to_v2": "Importar projeto para V2", "open_in_v1": "Abrir em V1", "import_to_v2": "Importar para V2", "never_mind_open_in_v1": "Não importa, abra em V1", "yes_im_sure": "Sim, eu tenho certeza", "drop_files_here_to_upload": "Largar arquivos aqui para enviar", "drag_here": "arraste aqui", "creating_project": "Criando projeto", "select_a_zip_file": "Selecione um arquivo .zip", "drag_a_zip_file": "arraste um arquivo .zip", "v1_badge": "Emblema V1", "v1_projects": "Projetos V1", "open_your_billing_details_page": "Abrir a Página de Detalhes da Cobrança", "try_out_link_sharing": "Experimente o novo recurso de compartilhamento de links!", "try_link_sharing": "Experimente o Compartilhar Link", "try_link_sharing_description": "Dê acesso ao seu projeto simplesmente compartilhando um link.", "learn_more_about_link_sharing": "Saiba mais sobre Compartilhamento de Link", "link_sharing": "Compartilhamento de link", "tc_switch_everyone_tip": "Alternar acompanhar-alterações para todos", "tc_switch_user_tip": "Alternar acompanhar-alterações para esse usuário", "tc_switch_guests_tip": "Alternar acompanhar-alterações para todos os convidados por links compartilhado", "tc_guests": "Convidados", "select_all_projects": "Selecionar todos", "select_project": "Selecionar", "main_file_not_found": "Arquivo principal desconhecido.", "please_set_main_file": "Por favor, selecione o arquivo principal para esse projeto no menu do projeto. ", "link_sharing_is_off": "Compartilhamento de Link está desligado, somente usuários convidados podem ver esse projeto.", "turn_on_link_sharing": "Ligar compartilhamento de Link.", "link_sharing_is_on": "Compartilhamento de Link está ligado", "turn_off_link_sharing": "Desligar compartilhamento de Link", "anyone_with_link_can_edit": "Qualquer um com esse link pode editar esse projeto", "anyone_with_link_can_view": "Qualquer um com esse link pode ver esse projeto", "turn_on_link_sharing_consequences": "Quando o compartilhamento de Link estiver habilitado, qualquer um com o link poderá acessar e editar o projeto", "turn_off_link_sharing_consequences": "Quando o compartilhamento de Link estiver desabilitado, apenas pessoas convidadas para o projeto poderão ter acesso", "autocompile_disabled": "Autocompilação desativada", "autocompile_disabled_reason": "Devido à alta carga do servidor, a recompilação de fundo foi desativada temporariamente. Recompile clicando no botão acima.", "auto_compile_onboarding_description": "Quando habilitado, seu projeto irá compilar enquanto você digita.", "try_out_auto_compile_setting": "Experimente a nova configuração de compilação automática", "got_it": "Entendi", "pdf_compile_in_progress_error": "Compilador já está executando em outra janela", "pdf_compile_try_again": "Aguarde até que sua outra compilação termine antes de tentar novamente.", "invalid_email": "Algum email está inválido", "auto_compile": "Compilar Automaticamente", "on": "Ligado", "tc_everyone": "Todos", "per_user_tc_title": "Acompanhar Alterações por Usuário", "you_can_use_per_user_tc": "Agora você pode acompanhar as alterações por usuário", "turn_tc_on_individuals": "Ligar Acompanhar Alterações individualmente por usuário", "keep_tc_on_like_before": "Ou continue verificando todas, como antes", "auto_close_brackets": "Fechamento Automático de Delimitadores", "auto_pair_delimiters": "Delimitadores de Pareamento Automático", "successfull_dropbox_link": "Dropbox vinculado com sucesso, Redirecionando para página de configurações.", "show_link": "Mostrar Link", "hide_link": "Esconder Link", "aggregate_changed": "Alterado", "aggregate_to": "para", "confirm_password_to_continue": "Confirme sua senha para continuar", "confirm_password_footer": "Não pediremos sua senha de novo por um tempo.", "accept_all": "Aceitar todos", "reject_all": "Rejeitar todos", "bulk_accept_confirm": "Vocês tem certeza que deseja aceitar as __nChanges__ alterações selecionadas?", "bulk_reject_confirm": "Vocês tem certeza que deseja rejeitar as __nChanges__ alterações selecionadas?", "uncategorized": "Sem Categoria", "pdf_compile_rate_limit_hit": "Limite de taxa de compilação atingido", "project_flagged_too_many_compiles": "Este projeto foi marcado por compilar com muita frequência. O limite vai ser restabelecido logo.", "reauthorize_github_account": "Reautorize sua conta GitHub", "github_credentials_expired": "Suas credenciais de autorização do GitHub expiraram", "hit_enter_to_reply": "Pressione Enter para responder", "add_your_comment_here": "Adicione seu comentário aqui", "resolved_comments": "Comentários resolvidos", "try_it_for_free": "Experimente gratuitamente", "please_ask_the_project_owner_to_upgrade_to_track_changes": "Solicite ao proprietário do projeto que atualize para utilizar o controle de alterações", "mark_as_resolved": "Marcar como resolvido", "reopen": "Reabrir", "add_comment": "Adicionar comentário", "no_resolved_threads": "Não existem comentários resolvidos.", "upgrade_to_track_changes": "Atualizar para acompanhar alterações", "see_changes_in_your_documents_live": "Ver alterações nos seus documentos, ao vivo", "track_any_change_in_real_time": "Acompanhar qualquer alteração, em tempo real", "review_your_peers_work": "Revisar o trabalho de seus colegas", "accept_or_reject_each_changes_individually": "Aceitar ou rejeitar cada alteração individualmente", "accept": "Aceitar", "reject": "Rejeitar", "no_comments": "Sem comentários", "edit": "Editar", "are_you_sure": "Você tem certeza?", "resolve": "Resolver", "reply": "Responder", "quoted_text_in": "Texto citado em", "review": "Revisar", "track_changes_is_on": "Controle de alterações está ligado", "track_changes_is_off": "Controle de alterações está <strong>desligado</strong>", "current_file": "Arquivo atual", "overview": "Visão geral", "tracked_change_added": "Adicionado", "tracked_change_deleted": "Deletado", "show_all": "mostrar tudo", "show_less": "mostrar menos", "dropbox_sync_error": "Erro de sincronização do Dropbox", "send": "Enviar", "sending": "Enviando", "invalid_password": "Senha inválida", "error": "Erro", "other_actions": "Outras Ações", "send_test_email": "Enviar email de teste", "email_sent": "Email Enviado", "create_first_admin_account": "Criar o primeira conta de Administrador", "ldap": "LDAP", "ldap_create_admin_instructions": "Escolha um endereço de e-mail para a primeira conta de administrador do __appName__. Isso deve corresponder a uma conta no sistema LDAP. Você será solicitado a fazer login com esta conta.", "saml": "SAML", "saml_create_admin_instructions": "Escolha um email para ser a conta de administrador do __appName__. Isso deve corresponder a uma conta no sistema SAML. Você deverá entrar com essa conta.", "admin_user_created_message": "Criar um usuário admin, <a href=\"__link__\">Entrar aqui</a> para continuar", "status_checks": "Verificações de Status", "editor_resources": "Editor de Recursos", "checking": "Verificando", "cannot_invite_self": "Não pode enviar convite para você mesmo", "cannot_invite_non_user": "Não foi possível enviar o convite. O destinatário deve ter uma conta no __appName__", "log_in_with": "Entrar com __provider__", "return_to_login_page": "Retornar à página de Login", "login_failed": "Login falhou", "delete_account_warning_message_3": "Você está prestes <strong>a excluir todos os dados de sua conta permanentemente, incluindo seus projetos e configurações. Digite o endereço de e-mail e sua senha da conta nas caixas abaixo para continuar.</strong>", "delete_account_warning_message_2": "Você está prestes da <strong>deletar todos os dados de sua conta</strong> permanentemente, incluindo seus projetos e configurações. Por favor, digite o endereço de email da sua conta nas caixas de texto abaixo para prosseguir.", "your_sessions": "Suas Sessões", "clear_sessions_description": "Essa é a lista de outras sessões (logins) que estão ativas na sua conta, sem incluir sua sessão corrente. Clique no botão \"Limpar Sessões\" para desconectar elas.", "no_other_sessions": "Nenhuma outra sessão ativa.", "ip_address": "Endereço de IP", "session_created_at": "Sessão Criada Em", "clear_sessions": "Limpar Sessões", "clear_sessions_success": "Sessões Limpas", "sessions": "Sessões", "manage_sessions": "Administrar suas sessões", "syntax_validation": "Checar código", "history": "Histórico", "joining": "Participando", "open_project": "Abrir Projeto", "files_cannot_include_invalid_characters": "Arquivos não podem ter os caracteres '*' ou '/'", "invalid_file_name": "Nome de Arquivo Inválido", "autocomplete_references": "Referência Autocompletar (dentro do bloco <code>\\cite{}</code>)", "autocomplete": "Autocompletar", "failed_compile_check": "Parece que o seu projeto tem erros fatais de sintaxe que você pode corrigir antes de compilar", "failed_compile_check_try": "Tentar compilar mesmo assim", "failed_compile_option_or": "ou", "failed_compile_check_ignore": "desligar verificação de sintaxe", "compile_time_checks": "Verificação de Sintaxe", "stop_on_validation_error": "Verificar sintaxe antes de compilar", "ignore_validation_errors": "Não verificar sintaxe", "run_syntax_check_now": "Verificar sintaxe agora", "your_billing_details_were_saved": "Os detalhes da sua cobrança foram salvos", "security_code": "Código de segurança", "paypal_upgrade": "Para aprimorar sua conta, clique no botão abaixo e entre no PayPal usando seu email e senha.", "upgrade_cc_btn": "Aprimorar agora, pague depois de 7 dias", "upgrade_paypal_btn": "Continuar", "notification_project_invite": "<b>__userName__</b> você gostaria de entrar em <b>__projectName__</b> <a class=\"btn btn-sm btn-info pull-right\" href=\"/project/__projectId__/invite/token/__token__\">Entrar no Projeto</a>", "file_restored": "Seu arquivo (__filename__) foi recuperado.", "file_restored_back_to_editor": "Você pode voltar para o editor e trabalhar novamente.", "file_restored_back_to_editor_btn": "Voltar para o editor", "view_project": "Ver Projeto", "join_project": "Entrar no Projeto", "invite_not_accepted": "Convite ainda não aceito", "resend": "Reenviar", "syntax_check": "Sintaxe verificada", "revoke_invite": "Revogar Convite", "pending": "Pendente", "invite_not_valid": "Esse não é um convite válido do projeto", "invite_not_valid_description": "Talvez o convite tenha expirado. Por favor, entre em contato com o dono do projeto.", "accepting_invite_as": "Você está aceitando esse convite como", "accept_invite": "Aceitar convite", "log_hint_ask_extra_feedback": "Você pode nos ajudar a entender porque essa dica não é útil?", "log_hint_extra_feedback_didnt_understand": "Eu não entendi a dica", "log_hint_extra_feedback_not_applicable": "Eu não posso aplicar essa solução no meu documento", "log_hint_extra_feedback_incorrect": "Isso não corrige o erro", "log_hint_extra_feedback_other": "Outra:", "log_hint_extra_feedback_submit": "Enviar", "if_you_are_registered": "Se você já está registrado", "stop_compile": "Parar compilação", "terminated": "Compilação cancelada", "compile_terminated_by_user": "O compilador foi cancelado usando o botão \"Parar Compilação\". Você pode olhar os logs e ver onde a compilação parou.", "site_description": "Um editor de LaTeX online fácil de usar. Sem instalação, colaboração em tempo real, controle de versões, centenas de templates LaTeX e mais.", "knowledge_base": "base de conhecimento", "contact_message_label": "Mensagem", "kb_suggestions_enquiry": "Você já viu nossa <0>__kbLink__</0>?", "answer_yes": "Sim", "answer_no": "Não", "log_hint_extra_info": "Saiba mais", "log_hint_feedback_label": "Essa dica foi útil?", "log_hint_feedback_gratitude": "Obrigado por seu comentário!", "recompile_pdf": "Recompilar o PDF", "about_paulo_reis": "é desenvolvedor de software front-end e pesquisador de experiência de usuário residente em Aveiro, Portugal. Paulo tem PhD em experiência de usuário e é apaixonado por criar tecnologia adequada às necessidades do usuário — tanto em conceito ou validação/teste, quanto em idealização ou implementação.", "login_or_password_wrong_try_again": "Seu usário ou senha estão incorretos. Tente novamente.", "manage_beta_program_membership": "Gerenciar a participação no Programa Beta", "beta_program_opt_out_action": "Descadastrar do Programa Beta", "disable_beta": "Desabilitar Beta", "beta_program_badge_description": "Enquanto usa o __appName__, você verá os recursos beta marcados com este emblema:", "beta_program_current_beta_features_description": "Nós estamos testando os seguintes recursos beta:", "enable_beta": "Habilitar Beta", "user_in_beta_program": "Usuário está participando do Programa Beta", "beta_program_already_participating": "Você está inscrito no Programa Beta.", "sharelatex_beta_program": "Programa Beta __appName__", "beta_program_benefits": "Nós estamos sempre melhorando o __appName__. Ingressando em nosso Programa Beta você pode ter acesso aos novos recursos e nos ajudar a entender melhor suas necessidades.", "beta_program_opt_in_action": "Cadastrar no Programa Beta", "conflicting_paths_found": "Conflito de Caminhos Encontrado", "following_paths_conflict": "Os arquivos e diretórios a seguir conflitam com o mesmo caminho", "open_a_file_on_the_left": "Abra em arquivo à esquerda", "reference_error_relink_hint": "Se os problemas persistirem, tente revincular sua conta aqui:", "pdf_rendering_error": "Erro ao renderizar PDF", "something_went_wrong_rendering_pdf": "Alguma coisa deu errado ao renderizar o PDF.", "mendeley_reference_loading_error_expired": "O token do Mendeley expirou, por favor, revincule sua conta", "zotero_reference_loading_error_expired": "O token do Zotero expirou, por favor, revincule sua conta", "mendeley_reference_loading_error_forbidden": "Não foi possível carregar as referências do Mendeley, por favor, revincule sua conta e tente novamente", "zotero_reference_loading_error_forbidden": "Não foi possível carregar as referências do Zotero, por favor, revincule sua conta e tente novamente", "mendeley_integration": "Integração Mendeley", "mendeley_sync_description": "A integração com Mendeley permite importar suas referências do mendeley para seus projetos no __appName__", "mendeley_is_premium": "A integração com Mendeley é um recurso premium", "link_to_mendeley": "Vincular ao Mendeley", "unlink_to_mendeley": "Desvincular ao Mendeley", "mendeley_reference_loading": "Carregando referências do Mendeley", "mendeley_reference_loading_success": "Carregado referências do Mendeley", "mendeley_reference_loading_error": "Erro, não foi possível carregar as referências do Mendeley", "zotero_integration": "Integração Zotero.", "zotero_sync_description": "A integração Zotero permite você importar as referências do zotero para seus projetos no __appName__.", "zotero_is_premium": "A integração Zotero é um recurso premium", "link_to_zotero": "Vincular ao Zotero", "unlink_to_zotero": "Desvincular ao Zotero", "zotero_reference_loading": "Carregando referências do Zotero", "zotero_reference_loading_success": "Carregado referência do Zotero", "zotero_reference_loading_error": "Erro, não foi possível carregar as referências do Zotero", "reference_import_button": "Importar Referências para", "unlink_reference": "Desvincular Provedor de Referências", "unlink_warning_reference": "Cuidado: Quando você desvincular sua conta desse provedor você não poderá mais importar as referências para os seus projetos.", "mendeley": "Mendeley", "zotero": "Zotero", "suggest_new_doc": "Sugerir novo documento", "request_sent_thank_you": "Requisição Enviada, Obrigado.", "suggestion": "Sugestões", "project_url": "URL do projeto afetada", "subject": "Assunto", "confirm": "Confirmar", "cancel_personal_subscription_first": "Você já tem uma inscrição pessoal, você gostaria que cancelássemos a primeira antes de se juntar à licença de grupo?", "delete_projects": "Deletar Projetos", "leave_projects": "Deixar Projetos", "delete_and_leave_projects": "Deletar e Deixar Projetos", "too_recently_compiled": "Esse projeto foi compilado recentemente, então a compilação foi pulada.", "clsi_maintenance": "O servidor de compilação está fora do ar para manutenção, logo estará de volta.", "references_search_hint": "Pressione CTRL-Espaço para Buscar", "ask_proj_owner_to_upgrade_for_references_search": "Peça ao proprietário do projeto para atualizar para usar o recurso de Pesquisa de Referências.\n", "ask_proj_owner_to_upgrade_for_faster_compiles": "Por favor, peça ao dono do projeto para aprimorar para compilação mais rápida e aumentar o limite de tempo.", "search_bib_files": "Busque por autor, título ou ano", "leave_group": "Sair do grupo", "leave_now": "Sair agora", "sure_you_want_to_leave_group": "Você tem certeza que deseja sair do grupo?", "notification_group_invite": "Você foi convidado para entrar no __groupName__, <a href=\"/user/subscription/__subscription_id__/group/invited\">Entre Aqui</a>.", "search_references": "Buscar os arquivos .bib no projeto", "no_search_results": "Sem resultados", "email_already_registered": "Este email já está registrado", "compile_mode": "Modo de Compilação", "normal": "Normal", "fast": "Rápido", "rename_folder": "Renomear Pasta", "delete_folder": "Excluir Pasta", "about_to_delete_folder": "Você está prestes a excluir as seguintes pastas (qualquer projeto dentro não serão excluídos):", "to_modify_your_subscription_go_to": "Para modificar sua inscrição, vá para", "manage_subscription": "Administrar Inscrição", "activate_account": "Ative sua conta", "yes_please": "Sim, por favor!", "nearly_activated": "Você está a um passo de ativar sua conta no __appName__!", "please_set_a_password": "Por favor, insira sua senha", "activation_token_expired": "Seu token de ativação expirou, você precisa que outro seja enviado para você.", "activate": "Ativar", "activating": "Ativando", "ill_take_it": "Eu fico com isso!", "cancel_your_subscription": "Parar Sua Inscrição", "no_thanks_cancel_now": "Não, obrigado - Ainda quero Cancelar Agora", "cancel_my_account": "Cancelar minha inscrição", "sure_you_want_to_cancel": "Você tem certeza que deseja cancelar?", "i_want_to_stay": "Quero ficar", "have_more_days_to_try": "Ganhe mais <strong>__days__ dias</strong> na sua Experimentação!", "interested_in_cheaper_plan": "Você estaria interessado em um plano de estudante com <strong>__price__</strong> mais barato?", "session_expired_redirecting_to_login": "Sessão Expirada. Redirecionando para a página de login em __seconds__ segundos", "maximum_files_uploaded_together": "Máximo de __max__ arquivos enviados juntos", "too_many_files_uploaded_throttled_short_period": "Excesso de arquivos enviados, seus envios foram suprimidos por um curto tempo.", "compile_larger_projects": "Compile projetos maiores", "upgrade_to_get_feature": "Aprimore para ter __feature__, mais:", "new_group": "Novo Grupo", "about_to_delete_groups": "Você está prestes a deletar os seguintes grupos:", "removing": "Removendo", "adding": "Adicionando", "groups": "Grupos", "rename_group": "Renomear Grupo", "renaming": "Renomeando", "create_group": "Criar Grupo", "delete_group": "Deletar Grupo", "delete_groups": "Deletar Grupos", "your_groups": "Seus Grupos", "group_name": "Nome do Grupo", "no_groups": "Sem Grupos", "Subscription": "Inscrição", "Documentation": "Documentação", "Universities": "Universidades", "Account Settings": "Configurações da Conta", "Projects": "Projetos", "Account": "Conta", "global": "global", "Terms": "Termos", "Security": "Segurança", "About": "Sobre", "editor_disconected_click_to_reconnect": "Editor desconectado, clique em qualquer lugar para reconectar.", "word_count": "Contagem de Palavras", "please_compile_pdf_before_word_count": "Por favor, compile seu projeto antes de executar a contagem de palavras", "total_words": "Total de Palavras", "headers": "Cabeçalhos", "math_inline": "Matemática em Linha", "math_display": "Exibição Matemática", "connected_users": "Usuários Conectados", "projects": "Projetos", "upload_project": "Carregar Projeto", "all_projects": "Todos Projetos", "your_projects": "Seus Projetos", "shared_with_you": "Compartilhado com você", "deleted_projects": "Projetos Excluídos", "templates": "Modelos", "new_folder": "Nova Pasta", "create_your_first_project": "Crie seu primeiro projeto", "complete": "Completo", "on_free_sl": "Você está usando a versão gratuíta do __appName__", "upgrade": "Atualizar", "or_unlock_features_bonus": "ou desbloqueie alguns recursos grátis por", "sharing_sl": "compartilhando __appName__", "add_to_folder": "Adicionar à pasta", "create_new_folder": "Criar Nova Pasta", "more": "Mais", "rename": "Renomear", "make_copy": "Fazer uma cópia", "restore": "Restaurar", "title": "Título", "last_modified": "Última Modificação", "no_projects": "Sem projetos", "welcome_to_sl": "Bem-vindo ao __appName__!", "new_to_latex_look_at": "Novo no LaTeX? Comece dando uma olhada nos nossos ", "or": "ou", "or_create_project_left": "ou crie seu primeiro projeto na esquerda", "thanks_settings_updated": "Obrigado, suas configurações foram salvas.", "update_account_info": "Atualizar Informações da Conta", "must_be_email_address": "Deve ser um endereço de email", "first_name": "Primeiro Nome", "last_name": "Sobrenome", "update": "Atualizar", "change_password": "Mudar Senha", "current_password": "Senha Atual", "new_password": "Nova Senha", "confirm_new_password": "Confirmar Nova Senha", "required": "Obrigatório", "doesnt_match": "Não corresponde", "dropbox_integration": "Integração com Dropbox", "learn_more": "Aprenda mais", "dropbox_is_premium": "Sincronização com o Dropbox é um recurso premium", "account_is_linked": "Conta está vinculada", "unlink_dropbox": "Desvincular Dropbox", "link_to_dropbox": "Vincular ao Dropbox", "newsletter_info_and_unsubscribe": "Enviamos notícias de tempos em tempos resumindo os novos recursos disponíveis. Se você preferir não receber esses e-mails, poderá cancelar a inscrição a qualquer momento:", "unsubscribed": "Não inscrito", "unsubscribing": "Cancelando Inscrição", "unsubscribe": "Cancelar Inscrição", "need_to_leave": "Precisa sair?", "delete_your_account": "Exclua sua conta", "delete_account": "Excluir Conta", "delete_account_warning_message": "Você está prestes a <strong>excluir todos os dados da sua conta</strong> permanentemente, inclusive seus projetos e configurações. Por favor escreva seu endereço de email dentro da caixa de texto abaixo para prosseguir.", "deleting": "Excluindo", "delete": "Excluir", "sl_benefits_plans": "__appName__ é o editor LaTeX mais fácil de usar do mundo. Mantenha-se atualizado com seus colaboradores, veja todas as alterações no seu trabalho e use seu ambiente LaTeX em qualquer lugar do mundo.", "monthly": "Mensalmente", "personal": "Pessoal", "free": "Grátis", "one_collaborator": "Um colaborador apenas", "collaborator": "Colaborador", "collabs_per_proj": "__collabcount__ colaboradores por projeto", "full_doc_history": "Histórico de todo o documento", "sync_to_dropbox": "Sincronize com Dropbox", "start_free_trial": "Comece o Teste Grátis!", "professional": "Profissional", "unlimited_collabs": "Colaboradores Ilimitados", "name": "Nome", "student": "Estudante", "university": "Universidade", "position": "Posição", "choose_plan_works_for_you": "Escolha o plano que funciona para você em nosso teste de __len__ dias grátis. Cancele a qualquer momento.", "interested_in_group_licence": "Interessado em usar o __appName__ no seu grupo, equipe ou departamento com uma conta ampla?", "get_in_touch_for_details": "Entre em contato para saber mais detalhes!", "group_plan_enquiry": "Consulta de Plano de Grupos", "enjoy_these_features": "Aproveite todas nossos incríveis recursos", "create_unlimited_projects": "Crie quantos projetos quiser.", "never_loose_work": "Não perca nada, nós lhe damos cobertura.", "access_projects_anywhere": "Acesse seus projetos de qualquer lugar.", "log_in": "Entrar", "login": "Entrar", "logging_in": "Entrando", "forgot_your_password": "Esqueceu sua senha", "password_reset": "Reiniciar Senha", "password_reset_email_sent": "Você receberá um email para terminar de reiniciar sua senha.", "please_enter_email": "Por favor, insira seu endereço de email", "request_password_reset": "Solicitar redefinição de senha", "reset_your_password": "Redefinir sua senha", "password_has_been_reset": "Sua senha foi redefinida", "login_here": "Entre aqui", "set_new_password": "Adicionar nova senha", "user_wants_you_to_see_project": "__username__ gostaria que você participasse de __projectname__", "join_sl_to_view_project": "Entre no __appName__ para ver esse projeto", "register_to_edit_template": "Por favor, registre-se para editar o modelo __templateName__", "already_have_sl_account": "Já possui uma conta no __appName__?", "register": "Registrar", "password": "Senha", "registering": "Registrando", "planned_maintenance": "Manutenção Planejada", "no_planned_maintenance": "Não há nenhuma manutenção planejada", "cant_find_page": "Desculpe, não conseguimos achar a página que você está procurando.", "take_me_home": "Ir para o início!", "no_preview_available": "Desculpe, não há pré-visualização disponível.", "no_messages": "Sem mensagens", "send_first_message": "Envie sua primeira mensagem", "account_not_linked_to_dropbox": "Sua conta não está vinculada ao Dropbox", "update_dropbox_settings": "Atualizar configurações do Dropbox", "refresh_page_after_starting_free_trial": "Por favor atualize essa página depois de iniciar seu teste grátis.", "checking_dropbox_status": "verificando estado do Dropbox", "dismiss": "Ignorar", "deleted_files": "Arquivos Excluídos", "new_file": "Novo Arquivo", "upload_file": "Atualizar Arquivo", "create": "Criar", "creating": "Criando", "upload_files": "Enviar Arquivo(s)", "sure_you_want_to_delete": "Você tem certeza que deseja excluir permanentemente os seguintes arquivos?", "common": "Comum", "navigation": "Navegação", "editing": "Editando", "ok": "OK", "source": "Fonte", "actions": "Ações", "copy_project": "Copiar Projeto", "publish_as_template": "Publicar Modelo", "sync": "Sincronia", "settings": "Configurações", "main_document": "Documento principal", "off": "Desligar", "auto_complete": "Auto-completar", "theme": "Tema", "font_size": "Tamanho da Fonte", "pdf_viewer": "Visualizador PDF", "built_in": "Embutido", "native": "Nativo", "show_hotkeys": "Mostrar Atalhos", "new_name": "Novo Nome", "copying": "Copiando", "copy": "Copiar", "compiling": "Compilando", "click_here_to_preview_pdf": "Clique aqui para pré-visualizar seu trabalho como PDF", "server_error": "Erro no Servidor", "somthing_went_wrong_compiling": "Desculpe, alguma coisa saiu errado e seu projeto não pode ser compilado. Por favor, tente mais tarde.", "timedout": "Tempo Expirado", "proj_timed_out_reason": "Desculpe, sua compilação demorou muito e o tempo expirou. Isso pode ter acontecido devido a muitas imagens em alta qualidade ou muitos diagramas complicados.", "no_errors_good_job": "Sem erros, bom trabalho!", "compile_error": "Erro de Compilação", "generic_failed_compile_message": "Desculpe, seu código LaTeX não pode ser compilado por algum motivo. Por favor, verifique os erros abaixo para mais detalhes, ou veja o log original.", "other_logs_and_files": "Outros Logs &amp; Arquivos", "view_raw_logs": "Ver Logs Originais", "hide_raw_logs": "Esconder Logs Originais", "clear_cache": "Limpar cache", "clear_cache_explanation": "Isso irá limpar todos os arquivos LaTex (.aux, .bbl, etc) ocultos do seu servidor de compilação. Você geralmente não precisa fazer isso a menos que tenha problemas nas referências.", "clear_cache_is_safe": "Seus arquivos de projeto não serão excluídos ou modificados.", "clearing": "Limpando", "template_description": "Descrição do Modelo", "project_last_published_at": "Seu projeto foi publicado pela última vez em", "problem_talking_to_publishing_service": "Há um problema com nosso serviço de publicação, por favor tente mais tarde", "unpublishing": "Despublicando", "republish": "Replublicar", "publishing": "Publicando", "share_project": "Compartilhar Projeto", "this_project_is_private": "Este projeto é privado e só pode ser acessível pelas pessoas abaixo.", "make_public": "Tornar Público", "this_project_is_public": "Esse projeto é publico e pode ser editado por qualquer pessoa com a URL.", "make_private": "Tornar Privado", "can_edit": "Pode Editar", "share_with_your_collabs": "Compartilhar com os colaboradores", "share": "Compartilhar", "need_to_upgrade_for_more_collabs": "Você precisa aprimorar sua conta para adicionar mais colaboradores.", "make_project_public": "Tornar projeto público", "make_project_public_consequences": "Se você tornar seu probjeto público, qualquer um com a URL podera ter acesso a ele.", "allow_public_editing": "Permitir edição pública", "allow_public_read_only": "Permitir ao público acesso somente à leitura", "make_project_private": "Desabilitar compartilhamento de link", "make_project_private_consequences": "Se você tornar seu projeto privado então somente as pessoas compartilhadas terão acesso.", "need_to_upgrade_for_history": "Você precisa aprimorar sua conta para ter o recurso de Histórico.", "ask_proj_owner_to_upgrade_for_history": "Por favor, peça ao dono do projeto para aprimorar para usar o recurso de Histórico.", "anonymous": "Anônimo", "generic_something_went_wrong": "Desculpe, algo saiu errado", "restoring": "Restaurando", "restore_to_before_these_changes": "Restaurar para antes dessas alterações", "profile_complete_percentage": "Seu perfil está __percentval__% completo", "file_has_been_deleted": "__filename__ foi excluído", "sure_you_want_to_restore_before": "Você tem certeza que deseja restaurar __filenname__ para antes das alterações em __date__?", "rename_project": "Renomear Projeto", "about_to_delete_projects": "Você está prestes a excluir os seguintes projetos:", "about_to_leave_projects": "Você está prestes à deixar de seguir os projetos:", "upload_zipped_project": "Subir Projeto Zipado", "upload_a_zipped_project": "Subir um projeto zipado", "your_profile": "Seu Perfil", "institution": "Instituição", "role": "Papel", "folders": "Pastas", "disconnected": "Desconectado", "please_refresh": "Por favor, atualize a página para continuar.", "lost_connection": "Conexão perdida", "reconnecting_in_x_secs": "Reconectando em __seconds__ segs", "try_now": "Tente Agora", "reconnecting": "Reconectando", "saving_notification_with_seconds": "Salvando __docname__... (__seconds__ segundos de alterações não salvas)", "help_us_spread_word": "Ajude-nos a divulgar o __appName__", "share_sl_to_get_rewards": "Compartilhe o __appName__ com seus amigos e colegas e desbloqueie as recompensas abaixo", "post_on_facebook": "Publicar no Facebook", "share_us_on_googleplus": "Compartilhe-nos no Google+", "email_us_to_your_friends": "Envie um email sobre nós para seus amigos", "link_to_us": "Nos link em seu website", "direct_link": "Link Direto", "sl_gives_you_free_stuff_see_progress_below": "Quando alguém começar a usar __appName__ depois de você recomendar, nós iremos lhe dar <strong>recursos grátis</strong> para lhe agradecer! Veja seu progresso abaixo.", "spread_the_word_and_fill_bar": "Nos divulgue e preencha essa barra", "one_free_collab": "Um colaborador grátis", "three_free_collab": "Três colaboradores grátis", "free_dropbox_and_history": "Dropbox e Histórico Grátis", "you_not_introed_anyone_to_sl": "Você não adicionou ninguém ao __appName__ ainda. Comece a compartilhar!", "you_introed_small_number": " Você introduziu <0>__numberOfPeople__</0> pessoas no __appName__. Parabéns, mas você pode trazer mais?", "you_introed_high_number": " Você adicionou <0>__numberOfPeople__</0> pessoas ao __appName__. Bom trabalho!", "link_to_sl": "Link ao __appName__", "can_link_to_sl_with_html": "Você pode vincular o __appName__ com o HTML a seguir:", "year": "ano", "month": "mês", "subscribe_to_this_plan": "Inscreva-se neste plano", "your_plan": "Seu plano", "your_subscription": "Sua Inscrição", "on_free_trial_expiring_at": "Você está atualmente usando o teste grátis que irá expirar em __expirasAt__.", "choose_a_plan_below": "Escolha um plano abaixo para se inscrever.", "currently_subscribed_to_plan": "Você está atualmente inscrito no plano <0>__planName__</0>", "change_plan": "Mudar plano", "next_payment_of_x_collectected_on_y": "O próximo pagamento de <0>__paymentAmmount__</0> será coletado em <1>__collectionDate__</1>", "update_your_billing_details": "Atualize Seus Detalhes de Pagamento", "subscription_canceled_and_terminate_on_x": "Sua inscrição foi cancelada e irá terminar em <0>__terminateDate__</0>. Nenhum pagamento futuro será cobrado.", "your_subscription_has_expired": "Sua inscrição expirou.", "create_new_subscription": "Crie Nova Inscrição", "problem_with_subscription_contact_us": "Houve um problema na sua inscrição. Por favor, entre em contato conosco para mais informações.", "manage_group": "Gerenciar grupo", "loading_billing_form": "Carregando formulário de detalhes de cobrança", "you_have_added_x_of_group_size_y": "Você adicionou __addedUserSize__ de <1>__groupSize__</1> membros disponíveis.", "remove_from_group": "Remover do grupo", "group_account": "Conta do grupo", "registered": "Registrado", "no_members": "Sem membros", "add_more_members": "Adicionar mais membros", "add": "Adicionar", "thanks_for_subscribing": "Obrigado por se inscrever!", "your_card_will_be_charged_soon": "Seu cartão será cobrado em breve.", "if_you_dont_want_to_be_charged": "Se você não queiser ser cobrado novamente ", "add_your_first_group_member_now": "Adicione seu primeiro membro no grupo agora", "thanks_for_subscribing_you_help_sl": "Obrigado por se inscriver ao plano __planName__. É a ajuda de pessoas como você que permitem ao __appName__ continuar a crescer e melhorar.", "back_to_your_projects": "Voltar ao seus projetos", "goes_straight_to_our_inboxes": "Isso vai direto para ambas as nossas caixas de entrada", "need_anything_contact_us_at": "Se houver qualquer coisa que você precisar, sinta-se à vontade para entrar em contato conosco por", "regards": "Saudações", "about": "Sobre", "comment": "Comentário", "restricted_no_permission": "Restrito, desculpe você não tem permissão para carregar essa página.", "online_latex_editor": "Editor LaTeX Online", "meet_team_behind_latex_editor": "Conheça o time por trás do seu editor LaTeX favorito.", "follow_me_on_twitter": "Siga-me no Twitter", "motivation": "Motivação", "evolved": "Evoluído", "the_easy_online_collab_latex_editor": "O editor LaTeX fácil de usar, online e colaborativo", "get_started_now": "Comece agora", "sl_used_over_x_people_at": "__appName__ é usado por mais de __numberOfUsers__ estudantes e acadêmicos de:", "collaboration": "Colaboração", "work_on_single_version": "Trabalhe junto em uma única versão", "view_collab_edits": "Veja a edição dos colaboradores", "ease_of_use": " Facilidade de Uso", "no_complicated_latex_install": "Sem instalação complicada do LaTeX", "all_packages_and_templates": "Todos os pacotes e <0>__templatesLink__</0> que você precisa", "document_history": "Histórico do documento", "see_what_has_been": "Veja o que foi ", "added": "adicionado", "and": "e", "removed": "removido", "restore_to_any_older_version": "Restaurar para qualquer versão antiga", "work_from_anywhere": "Trabalhe de qualquer lugar", "acces_work_from_anywhere": "Acesse seu trabalho de qualquer lugar do mundo", "work_offline_and_sync_with_dropbox": "Trabalhe offline e sincronize seus arquivos via Dropbox e GitHub", "over": "mais de", "view_templates": "Ver modelos", "nothing_to_install_ready_to_go": "Não há nada complicado ou difícil para instalar, e você pode <0>__start_now__</0>, mesmo que nunca tenha visto isso antes. __appName__ vem com um completo, ambiente LaTex pronto para usar que roda em nossos servidores.", "start_using_latex_now": "começar a usar LaTeX agora mesmo", "get_same_latex_setup": "Com __appName__ você tem o mesmo aplicativo onde quer que vá. Trabalhando com seus colegas e estudantes no __appName__, você sabe que não terá problema de inconsistência ou conflito de pacotes.", "support_lots_of_features": "Nós temos suporte para todos os recursos LaTeX, incluindo inserção de imagens, bibliografias, equações e muito mais! Leia sobre todos os recursos interessantes que você pode usar no __appName__ em nosso <0>__help_guides_link__</0>", "latex_guides": "Guias LaTeX", "reset_password": "Trocar Senha", "set_password": "Inserir Senha", "updating_site": "Atualizando Site", "bonus_please_recommend_us": "Bônus - Por favor nos recomende", "admin": "admin", "subscribe": "Inscrever", "update_billing_details": "Atualizar Detalhes de Cobrança", "group_admin": "Administrador do Grupo", "all_templates": "Todos os Modelos", "your_settings": "Suas Configurações", "maintenance": "Manutenção", "to_many_login_requests_2_mins": "Essa conta teve muitas solicitações de entrada. Por favor, aguarde 2 minutos antes de tentar novamente.", "email_or_password_wrong_try_again": "Seu email ou senha estão incorretos. Tente novamente.", "rate_limit_hit_wait": "Frequência de tentativas atingida. Por favor, aguarde um pouco antes de tentar novamente.", "problem_changing_email_address": "Houve um problema ao alterar seu endereço de email. Por favor, tente novamente em alguns minutos. Se o problema persistir, por favor, entre em contato conosco.", "single_version_easy_collab_blurb": "__appName__ garante que você sempre esteja atualizado com seus colaboradores e o que eles estão fazendo. Existe apenas uma versão principal de cada documento que todos têm acesso. Conflitos de alteração são impossíveis e você não precisa esperar seus colegas lhe enviarem as últimas alterações antes de continuar o trabalho.", "can_see_collabs_type_blurb": "Se várias pessoas querem trabalhar em um documento ao mesmo tempo, não tem problema. Você pode ver onde seus colegas estão digitando diretamente no editor e as alterações irão aparecer na sua tela imediatamente.", "work_directly_with_collabs": "Trabalhe diretamente com seus colaboradores", "work_with_word_users": "Trabalhe com usuários do Word", "work_with_word_users_blurb": "__appName__ é tão fácil de se familiarizar que você poderá convidar seus colegas que não usam LaTeX para editar seus documentos LaTeX. Eles irão começar a produzir a partir do primeiro dia e serão capazes de aprender LaTeX aos poucos.", "view_which_changes": "Veja quais alterações foram feitas", "sl_included_history_of_changes_blurb": "__appName__ incluí o histórico de todas as alterações para você ver exatamente quem alterou o quê e quando. Torna-se extremamente fácil se manter atualizado acerca do progresso dos seus colaboradores e você pode revisar os trabalhos recentes.", "can_revert_back_blurb": "Em modo colaborativo ou sozinho, alguns enganos são feitos. Reverter para versões anteriore é simples e remove o risco de perder trabalho ou se arrepender de uma alteração.", "start_using_sl_now": "Comece a usar __appName__ agora", "over_x_templates_easy_getting_started": "Existem milhares de __templates__ em nossa galeria de modelos, assim é fácil começar, mesmo que você esteja escrevendo um artigo de revista, tese, currículo ou outra coisa.", "done": "Pronto", "change": "Modificado", "page_not_found": "Página Não Encontrada", "please_see_help_for_more_info": "Por favor veja em nosso guia de ajuda para mais informações", "this_project_will_appear_in_your_dropbox_folder_at": "Esse projeto irá aparecer em sua pasta Dropbox em ", "member_of_group_subscription": "Você é membro de um grupo inscrito administrado por __admin_email__. Por favor, entre em contato com ele para administrar sua inscrição.\n", "about_henry_oswald": "é um engenheiro de software que mora em Londres. Ele construiu o protótipo original do __appName__ e é o responsável por construir uma plataforma estável e escalável. Henry é um forte defensor do Desenvolvimento Orientado à Testes e garante que mantemos o código do __appName__ limpo e fácil de manter.", "about_james_allen": "tem Doutorado em física teórica e é apaixonado por LaTeX. Ele criou um dos primeiros editores online de LaTeX, ScribTeX, e tem um importante papel no desenvolvimento das tecnologias que fazem o __appName__ possível.", "two_strong_principles_behind_sl": "Existem dois fortes princípios que conduzem o nosso trabalho por trás do __appName__:", "want_to_improve_workflow_of_as_many_people_as_possible": "Nós queremos melhorar o fluxo de trabalho do maior número de pessoas possível.", "detail_on_improve_peoples_workflow": "LaTeX é conhecido por ser difícil de usar, e a colaboração é sempre difícil de coordenar. Nós acreditamos que desenvolvemos uma solução incrível para ajudar as pessoas que enfrentam esses problemas, e nós queremos garantir que o __appName__ seja acessível pelo máximo de pessoas possível. Nós tentamos manter nosso preço justo, e liberamos o máximo do __appName__ como código-aberto para que qualquer pessoal possa hospedar por si própria.", "want_to_create_sustainable_lasting_legacy": "Queremos criar um legado permanente e sustentável.", "details_on_legacy": "Desenvolver e manter um produto como o __appName__ requer muito tempo e trabalho, assim é importante que encontremos um modelo de negócio que suporte ambos os requisitos, e a longo prazo. Nós não queremos que o __appName__ dependa de fundos externos ou desapareça devido à falha do modelo de negócio. Eu me orgulho em dizer que atualmente nós podemos rodar o __appName__ lucrativo e sustentável, e esperamos fazer isso a longo prazo.", "get_in_touch": "Entre em contato", "want_to_hear_from_you_email_us_at": "Nós adoramos ouvir de todos que estão usando __appName__, ou querem conversar sobre o que estamos fazendo. Você pode entrar em contato conosco em ", "cant_find_email": "Esse email não está registrado, desculpe.", "plans_amper_pricing": "Planos &amp; Preços", "documentation": "Documentação", "account": "Conta", "subscription": "Inscrição", "log_out": "Sair", "en": "Inglês", "pt": "Português", "es": "Espanhol", "fr": "Francês", "de": "Alemão", "it": "Italiano", "da": "Dinamarquês", "sv": "Suéco", "no": "Noroeguês", "nl": "Holandês", "pl": "Polonês", "ru": "Russo", "uk": "Ucraniano", "ro": "Romeno", "click_here_to_view_sl_in_lng": "Clique aqui e veja a página __appName__ em <0>__lngName__</0>", "language": "Idioma", "upload": "Carregar", "menu": "Menu", "full_screen": "Tela cheia", "logs_and_output_files": "Logs e arquivos de saída", "download_pdf": "Baixar PDF", "split_screen": "Dividir a tela", "clear_cached_files": "Limpar arquivos em cache", "go_to_code_location_in_pdf": "Vá para a localização do código no PDF", "please_compile_pdf_before_download": "Por favor, compile seu projeto antes de baixar o PDF", "remove_collaborator": "Remover colaborador", "add_to_folders": "Adicionar à pasta", "download_zip_file": "Baixar arquivo .zip", "price": "Preço", "close": "Fechar", "keybindings": "Atalhos", "restricted": "Restrito", "start_x_day_trial": "Comece seus __len__ Dias de Teste Grátis Hoje!", "buy_now": "Comprar agora!", "cs": "Tcheco", "view_all": "Ver Todos", "terms": "Termos", "privacy": "Privacidade", "contact": "Contato", "change_to_this_plan": "Alterar para esse plano", "processing": "processando", "sure_you_want_to_change_plan": "Você tem certeza que deseja alterar o plano para <0>__planName__</0>?", "move_to_annual_billing": "Migrar para Plano Anual", "annual_billing_enabled": "Plano anual habilitado", "move_to_annual_billing_now": "Migrar para plano anual agora", "change_to_annual_billing_and_save": "Ganhe <0>__percentage__</0> de desconto no plano anual. Se você migrar agora você irá economizar __yearSaving__ por ano.", "missing_template_question": "Falta algum modelo?", "tell_us_about_the_template": "Se estiver faltando um modelo, por favor: Nos envie uma cópia do modelo, o URL do __appName__ para o modelo ou nos avise onde podemos encontrá-lo. Também, por favor, nos conte sobre o modelo para colocarmos na descrição.", "email_us": "Nos envie email", "this_project_is_public_read_only": "Esse projeto é público e pode ser visualizado, mas não editado, por qualquer pessoa com a URL", "tr": "Turco", "select_files": "Selecionar arquivo(s)", "drag_files": "arraste arquivo(s)", "upload_failed_sorry": "Envio falhou. Desculpe :(", "inserting_files": "Inserindo arquivo...", "password_reset_token_expired": "Sua ficha de reinicialização de senha expirou.Por favor, solicite um novo email de reinicialização de senha e clique no link contido nele.", "merge_project_with_github": "Mesclar Projeto com GitHub", "pull_github_changes_into_sharelatex": "Puxar mudanças do GitHub no __appName__", "push_sharelatex_changes_to_github": "Empurrar mudanças do __appName__ no GitHub", "features": "Recursos", "commit": "Commitar", "commiting": "Submetendo", "importing_and_merging_changes_in_github": "Importar e mesclar mudanças no GitHub", "upgrade_for_faster_compiles": "Aprimore sua conta para ter compilações mais rápidas e com limite de tempo maior.", "free_accounts_have_timeout_upgrade_to_increase": "Contas gratuítas tem um minuto no limite de tempo de compilação. Aprimore sua conta para aumentar seu limite.", "learn_how_to_make_documents_compile_quickly": "Aprenda como fazer seu documento compilar mais rápido", "zh-CN": "Chinês", "cn": "Chinês (Simplificado)", "sync_to_github": "Sincronizar com GitHub", "sync_to_dropbox_and_github": "Sincronizar com Dropbox e GitHub", "project_too_large": "Projeto muito grande", "project_too_large_please_reduce": "Esse projeto tem muitos textos editáveis, por favor tente e reduza. Os maiores arquivos são:", "please_ask_the_project_owner_to_link_to_github": "Por favor, peça ao dono do projeto que vincule o projeto a um repositório no GitHub.", "go_to_pdf_location_in_code": "Ir para a localização do PDF no código", "ko": "Coreano", "ja": "Japonês", "about_brian_gough": "é um desenvolvedor de software e ex-físico teórico de energia da Fermilab e Los alamos. Por muitos anos ele publicou manuais grátis de softwares comerciais usando TeX e LaTeX e também mantém a Biblioteca Científica da GNU.", "first_few_days_free": "Primeiros __trialLen__ dias grátis", "every": "por", "credit_card": "Cartão de Crédito", "credit_card_number": "Número do Cartão de Crédito", "invalid": "Inválido", "expiry": "Data de Validade", "january": "Janeiro", "february": "Fevereiro", "march": "Março", "april": "Abril", "may": "maio", "june": "Junho", "july": "Julho", "august": "Agosto", "september": "Setembro", "october": "Outubro", "november": "Novembro", "december": "Dezembro", "zip_post_code": "CEP / Código Postal", "city": "Cidade", "address": "Endereço", "coupon_code": "Código de cupom", "country": "País", "billing_address": "Endereço de Cobrança", "upgrade_now": "Aprimorar Agora", "state": "Estado", "vat_number": "Número IVA", "you_have_joined": "Você entrou no __groupName__", "claim_premium_account": "Você solicitou a sua conta premium fornecida por __groupName__.", "you_are_invited_to_group": "Você foi convidado para entrar no __groupName__", "you_can_claim_premium_account": "Você pode reivindicar sua conta premium fornecida pelo __groupName__ verificando seu email", "not_now": "Não agora", "verify_email_join_group": "Verifique seu email e entre no Grupo", "check_email_to_complete_group": "Por favor, verifique seu email para completar sua entrada no grupo", "verify_email_address": "Email de Verificação", "group_provides_you_with_premium_account": "__groupName__ forneceu para você uma conta premium. Verifique o seu email para aprimorar sua conta.", "check_email_to_complete_the_upgrade": "Por favor, verifique seu email para completar a aprimoração da sua conta.", "email_link_expired": "Link do email expirou, por favor, solicite um link novo.", "services": "Serviços", "about_shane_kilkelly": "é um desenvolvedor de software que mora em Edinburgh. Shane é um forte defensor de Programação Funcional, Desenvolvimento Orientado a Teste e se orgulha em construir softwares de qualidade.", "this_is_your_template": "Este é seu modelo de seu projeto", "links": "Links", "account_settings": "Configurações da Conta", "search_projects": "Buscar projetos", "clone_project": "Clonar Projeto", "delete_project": "Deletar Projeto", "download_zip": "Baixar Zip", "new_project": "Novo Projeto", "blank_project": "Projeto Em Branco", "example_project": "Projeto Exemplo", "from_template": "De um Modelo", "cv_or_resume": "Currículo", "cover_letter": "Capa de Apresentação", "journal_article": "Artigo de Revista", "presentation": "Apresentação", "thesis": "Tese", "bibliographies": "Bibliografia", "terms_of_service": "Termos de Serviço", "privacy_policy": "Política de Privacidade", "plans_and_pricing": "Planos e Preços", "university_licences": "Licenças de Universidade", "security": "Segurança", "contact_us": "Entre em Contato", "thanks": "Obrigado", "blog": "Blog", "latex_editor": "Editor LaTeX", "get_free_stuff": "Obter material grátis", "chat": "Bate-papo", "your_message": "Sua Mensagem", "loading": "Carregando", "connecting": "Conectando", "recompile": "Recompilar", "download": "Baixar", "email": "Email", "owner": "Dono", "read_and_write": "Ler e Escrever", "read_only": "Somente Ler", "publish": "Publicar", "view_in_template_gallery": "Ver isso na galeria de modelos", "description": "Descrição", "unpublish": "Despublicar", "hotkeys": "Atalhos", "saving": "Salvando", "cancel": "Cancelar", "project_name": "Nome do Projeto", "root_document": "Diretório Raiz", "spell_check": "Verificar ortografia", "compiler": "Compilador", "private": "Privado", "public": "Público", "delete_forever": "Deletar Permanentemente", "support_and_feedback": "Suporte e comentários", "help": "Ajuda", "latex_templates": "Modelos LaTeX", "info": "Info", "latex_help_guide": "Guia de ajuda LaTeX", "choose_your_plan": "Escolha seu plano", "indvidual_plans": "Planos individuais", "free_forever": "Grátis para sempre", "low_priority_compile": "Baixa prioridade de compilação", "unlimited_projects": "Projetos ilimitados", "unlimited_compiles": "Compilação ilimitada", "full_history_of_changes": "Histórico total de mudanças", "highest_priority_compiling": "Alta prioridade de compilação", "dropbox_sync": "Sincronização Dropbox", "beta": "Beta", "sign_up_now": "Inscreva-se agora", "annual": "Anual", "half_price_student": "Metade do Preço em Planos para Estudantes", "about_us": "Sobre Nós", "loading_recent_github_commits": "Carregando commits recentes", "no_new_commits_in_github": "Nenhum novo commit no GitHub desde a última mesclagem.", "dropbox_sync_description": "Mantenha seus projetos __appName__ sincronizados com o Dropbox. Mudanças no __appName__ serão enviadas automaticamente para o Dropbox, e o inverso também.", "github_sync_description": "Com a Sincronização GitHub você pode vincular seus projetos __appName__ com os repositórios do GitHub. Crie novos commits no __appName__ e mescle com commits feitos fora ou no GitHub.", "github_import_description": "Com a Sincronização GitHub você pode importar seus projetos __appName__ com os repositórios do GitHub. Crie novos commits no __appName__ e mescle com commits feitos fora ou no GitHub.", "link_to_github_description": "Você precisa autorizar o __appName__ para acessar sua conta no GitHub para permitir a sincronização dos projetos.", "unlink": "Desvincular", "unlink_github_warning": "Qualquer projeto que você tenha sincronizado com o GitHub será desconectado e não poderão mais ser sincronizados com o GitHub. Você tem certeza que deseja desvincular sua conta do GitHub.", "github_account_successfully_linked": "Conta do GitHub foi vinculada com sucesso!", "github_successfully_linked_description": "Obrigado, nós vinculamos com sucesso sua conta do GitHub com o __appName__. Agora você pode exportar seus projetos do __appName__ para o GitHub e importar seus projetos de repositórios do GitHub.", "import_from_github": "Importar do GitHub", "github_sync_error": "Desculpe, houve um erro ao se comunicar com nosso serviço do GitHub. Por favor, tente novamente mais tarde.", "loading_github_repositories": "Carregando seu repositório do GitHub", "select_github_repository": "Selecione um repositório no GitHub para importar para o __appName__.", "import_to_sharelatex": "Importar para o __appName__", "importing": "Importando", "github_sync": "Sincronizar com GitHub", "checking_project_github_status": "Verificando estado do projeto no GitHub", "account_not_linked_to_github": "Sua conta não está vinculada ao GitHub", "project_not_linked_to_github": "Esse projeto não está vinculado a um repositório no GitHub. Você pode criar um repositório para ele no GitHub.", "create_project_in_github": "Criar um repositório no GitHub", "project_synced_with_git_repo_at": "Esse projeto foi sincronizado com um repositório no GitHub em", "recent_commits_in_github": "Commits recentes no GitHub", "sync_project_to_github": "Sincronizar projeto com GitHub", "sync_project_to_github_explanation": "Qualquer mudança feita no __appName__ será commitada e mesclada com qualquer atualização no GitHub.", "github_merge_failed": "Suas mudanças no __appName__ e GitHub não puderam ser mescladas automaticamente. Por favor, mescle (merge) manualmente o branch <0>__sharelatex_branch__</0> no branch <1>__master_branch__</1> no git. Clique abaixo para continuar, depois de você ter mesclado manualmente.", "continue_github_merge": "Mesclei manualmente. Continuar", "export_project_to_github": "Exportar Projeto para o GitHub", "github_validation_check": "Por favor, verifique se o nome do projeto é válido e que você tem permissão para criar o repositório.", "repository_name": "Nome do Repositório", "optional": "Opcional", "github_public_description": "Qualquer um pode ver esse repositório.", "github_commit_message_placeholder": "Mensagem de commit para as alterações feitas no __appName__...", "merge": "Mesclar", "merging": "Mesclando", "github_account_is_linked": "Sua conta do GitHub foi vinculada com sucesso.", "unlink_github": "Desvincular conta do GitHub", "link_to_github": "Vincule à sua conta do GitHub", "github_integration": "Integração com o GitHub", "github_is_premium": "Sincronizar com GitHub é um recurso premium", "thank_you": "Obrigado" }
overleaf/web/locales/pt.json/0
{ "file_path": "overleaf/web/locales/pt.json", "repo_id": "overleaf", "token_count": 28378 }
534
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['saas'] const indexes = [ { key: { project_id: 1, }, name: 'project_id_1', }, { key: { owner_id: 1, }, name: 'owner_id_1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.githubSyncProjectStates, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.githubSyncProjectStates, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145010_create_githubSyncProjectStates_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145010_create_githubSyncProjectStates_indexes.js", "repo_id": "overleaf", "token_count": 257 }
535
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const indexes = [ { key: { project_id: 1, }, name: 'project_id', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.rooms, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.rooms, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145026_create_rooms_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145026_create_rooms_indexes.js", "repo_id": "overleaf", "token_count": 216 }
536
const Helpers = require('./lib/helpers') exports.tags = ['saas'] exports.migrate = async client => { const { db } = client await Helpers.dropCollection(db, 'projectImportBatchRecords') } exports.rollback = async client => { // can't really do anything here }
overleaf/web/migrations/20200522145741_dropProjectImportBatchRecords.js/0
{ "file_path": "overleaf/web/migrations/20200522145741_dropProjectImportBatchRecords.js", "repo_id": "overleaf", "token_count": 89 }
537
/* eslint-disable node/handle-callback-err, max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let LaunchpadController const OError = require('@overleaf/o-error') const Settings = require('@overleaf/settings') const Path = require('path') const Url = require('url') const logger = require('logger-sharelatex') const metrics = require('@overleaf/metrics') const UserRegistrationHandler = require('../../../../app/src/Features/User/UserRegistrationHandler') const EmailHandler = require('../../../../app/src/Features/Email/EmailHandler') const _ = require('underscore') const UserGetter = require('../../../../app/src/Features/User/UserGetter') const { User } = require('../../../../app/src/models/User') const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController') const SessionManager = require('../../../../app/src/Features/Authentication/SessionManager') module.exports = LaunchpadController = { _getAuthMethod() { if (Settings.ldap) { return 'ldap' } else if (Settings.saml) { return 'saml' } else { return 'local' } }, launchpadPage(req, res, next) { // TODO: check if we're using external auth? // * how does all this work with ldap and saml? const sessionUser = SessionManager.getSessionUser(req.session) const authMethod = LaunchpadController._getAuthMethod() return LaunchpadController._atLeastOneAdminExists(function ( err, adminUserExists ) { if (err != null) { return next(err) } if (!sessionUser) { if (!adminUserExists) { return res.render(Path.resolve(__dirname, '../views/launchpad'), { adminUserExists, authMethod, }) } else { AuthenticationController.setRedirectInSession(req) return res.redirect('/login') } } else { return UserGetter.getUser( sessionUser._id, { isAdmin: 1 }, function (err, user) { if (err != null) { return next(err) } if (user && user.isAdmin) { return res.render(Path.resolve(__dirname, '../views/launchpad'), { wsUrl: Settings.wsUrl, adminUserExists, authMethod, }) } else { return res.redirect('/restricted') } } ) } }) }, _atLeastOneAdminExists(callback) { if (callback == null) { callback = function (err, exists) {} } return UserGetter.getUser( { isAdmin: true }, { _id: 1, isAdmin: 1 }, function (err, user) { if (err != null) { return callback(err) } return callback(null, user != null) } ) }, sendTestEmail(req, res, next) { const { email } = req.body if (!email) { logger.log({}, 'no email address supplied') return res.sendStatus(400) } logger.log({ email }, 'sending test email') const emailOptions = { to: email } return EmailHandler.sendEmail('testEmail', emailOptions, function (err) { if (err != null) { OError.tag(err, 'error sending test email', { email, }) return next(err) } logger.log({ email }, 'sent test email') return res.sendStatus(201) }) }, registerExternalAuthAdmin(authMethod) { return function (req, res, next) { if (LaunchpadController._getAuthMethod() !== authMethod) { logger.log( { authMethod }, 'trying to register external admin, but that auth service is not enabled, disallow' ) return res.sendStatus(403) } const { email } = req.body if (!email) { logger.log({ authMethod }, 'no email supplied, disallow') return res.sendStatus(400) } logger.log({ email }, 'attempted register first admin user') return LaunchpadController._atLeastOneAdminExists(function (err, exists) { if (err != null) { return next(err) } if (exists) { logger.log( { email }, 'already have at least one admin user, disallow' ) return res.sendStatus(403) } const body = { email, password: 'password_here', first_name: email, last_name: '', } logger.log( { body, authMethod }, 'creating admin account for specified external-auth user' ) return UserRegistrationHandler.registerNewUser( body, function (err, user) { if (err != null) { OError.tag(err, 'error with registerNewUser', { email, authMethod, }) return next(err) } return User.updateOne( { _id: user._id }, { $set: { isAdmin: true }, emails: [{ email }], }, function (err) { if (err != null) { OError.tag(err, 'error setting user to admin', { user_id: user._id, }) return next(err) } AuthenticationController.setRedirectInSession(req, '/launchpad') logger.log( { email, user_id: user._id, authMethod }, 'created first admin account' ) return res.json({ redir: '/launchpad', email }) } ) } ) }) } }, registerAdmin(req, res, next) { const { email } = req.body const { password } = req.body if (!email || !password) { logger.log({}, 'must supply both email and password, disallow') return res.sendStatus(400) } logger.log({ email }, 'attempted register first admin user') return LaunchpadController._atLeastOneAdminExists(function (err, exists) { if (err != null) { return next(err) } if (exists) { logger.log( { email: req.body.email }, 'already have at least one admin user, disallow' ) return res.sendStatus(403) } const body = { email, password } return UserRegistrationHandler.registerNewUser( body, function (err, user) { if (err != null) { return next(err) } logger.log({ user_id: user._id }, 'making user an admin') User.updateOne( { _id: user._id }, { $set: { isAdmin: true, emails: [{ email }], }, }, function (err) { if (err != null) { OError.tag(err, 'error setting user to admin', { user_id: user._id, }) return next(err) } AuthenticationController.setRedirectInSession(req, '/launchpad') logger.log( { email, user_id: user._id }, 'created first admin account' ) return res.json({ redir: '', id: user._id.toString(), first_name: user.first_name, last_name: user.last_name, email: user.email, created: Date.now(), }) } ) } ) }) }, }
overleaf/web/modules/launchpad/app/src/LaunchpadController.js/0
{ "file_path": "overleaf/web/modules/launchpad/app/src/LaunchpadController.js", "repo_id": "overleaf", "token_count": 3753 }
538
const { waitForDb } = require('../../../app/src/infrastructure/mongodb') const UserGetter = require('../../../app/src/Features/User/UserGetter') const UserDeleter = require('../../../app/src/Features/User/UserDeleter') async function main() { await waitForDb() const email = (process.argv.slice(2).pop() || '').replace(/^--email=/, '') if (!email) { console.error(`Usage: node ${__filename} --email=joe@example.com`) process.exit(1) } await new Promise((resolve, reject) => { UserGetter.getUser({ email }, function (error, user) { if (error) { return reject(error) } if (!user) { console.log( `user ${email} not in database, potentially already deleted` ) return resolve() } UserDeleter.deleteUser(user._id, function (err) { if (err) { return reject(err) } resolve() }) }) }) } main() .then(() => { console.error('Done.') process.exit(0) }) .catch(err => { console.error(err) process.exit(1) })
overleaf/web/modules/server-ce-scripts/scripts/delete-user.js/0
{ "file_path": "overleaf/web/modules/server-ce-scripts/scripts/delete-user.js", "repo_id": "overleaf", "token_count": 455 }
539
google-site-verification: google4f15e48c48709a75.html
overleaf/web/public/google4f15e48c48709a75.html/0
{ "file_path": "overleaf/web/public/google4f15e48c48709a75.html", "repo_id": "overleaf", "token_count": 20 }
540
const fs = require('fs') const { ObjectId, waitForDb } = require('../app/src/infrastructure/mongodb') const async = require('async') const UserUpdater = require('../app/src/Features/User/UserUpdater') const UserSessionsManager = require('../app/src/Features/User/UserSessionsManager') const ASYNC_LIMIT = 10 const processLogger = { failedClear: [], failedSet: [], success: [], printSummary: () => { console.log( { success: processLogger.success, failedClear: processLogger.failedClear, failedSet: processLogger.failedSet, }, `\nDONE. ${processLogger.success.length} successful. ${processLogger.failedClear.length} failed to clear sessions. ${processLogger.failedSet.length} failed to set must_reconfirm.` ) }, } function _validateUserIdList(userIds) { if (!Array.isArray(userIds)) throw new Error('users is not an array') userIds.forEach(userId => { if (!ObjectId.isValid(userId)) throw new Error('user ID not valid') }) } function _handleUser(userId, callback) { UserUpdater.updateUser(userId, { $set: { must_reconfirm: true } }, error => { if (error) { console.log(`Failed to set must_reconfirm ${userId}`, error) processLogger.failedSet.push(userId) return callback() } else { UserSessionsManager.revokeAllUserSessions({ _id: userId }, [], error => { if (error) { console.log(`Failed to clear sessions for ${userId}`, error) processLogger.failedClear.push(userId) } else { processLogger.success.push(userId) } return callback() }) } }) } async function _loopUsers(userIds) { await new Promise((resolve, reject) => { async.eachLimit(userIds, ASYNC_LIMIT, _handleUser, error => { if (error) return reject(error) resolve() }) }) } const fileName = process.argv[2] if (!fileName) throw new Error('missing filename') const usersFile = fs.readFileSync(fileName, 'utf8') const userIds = usersFile .trim() .split('\n') .map(id => id.trim()) async function processUsers(userIds) { console.log('---Starting set_must_reconfirm script---') await waitForDb() _validateUserIdList(userIds) console.log(`---Starting to process ${userIds.length} users---`) await _loopUsers(userIds) processLogger.printSummary() process.exit() } processUsers(userIds)
overleaf/web/scripts/clear_sessions_set_must_reconfirm.js/0
{ "file_path": "overleaf/web/scripts/clear_sessions_set_must_reconfirm.js", "repo_id": "overleaf", "token_count": 908 }
541
const { db, ObjectId, waitForDb } = require('../app/src/infrastructure/mongodb') const minimist = require('minimist') const argv = minimist(process.argv.slice(2)) const commit = argv.commit !== undefined const projectIds = argv._.map(x => { return ObjectId(x) }) if (!commit) { console.log('Doing dry run without --commit') } console.log('checking', projectIds.length, 'projects') waitForDb().then(async () => { const affectedProjects = await db.projects .find( { _id: { $in: projectIds } }, { projection: { _id: 1, owner_ref: 1, tokenAccessReadOnly_refs: 1, tokenAccessReadAndWrite_refs: 1, }, } ) .toArray() console.log('Found ' + affectedProjects.length + ' affected projects') affectedProjects.forEach(project => { console.log(JSON.stringify(project)) }) if (!commit) { console.log('dry run, not updating') process.exit(0) } else { try { const result = await db.projects.updateMany( { _id: { $in: affectedProjects.map(project => project._id) } }, { $set: { publicAccesLevel: 'private', // note the spelling in the db is publicAccesLevel (with one 's') tokenAccessReadOnly_refs: [], tokenAccessReadAndWrite_refs: [], }, } ) console.log('result', JSON.stringify(result)) process.exit(0) } catch (err) { console.error('err', err) process.exit(1) } } })
overleaf/web/scripts/invalidate_tokens.js/0
{ "file_path": "overleaf/web/scripts/invalidate_tokens.js", "repo_id": "overleaf", "token_count": 646 }
542
const Settings = require('@overleaf/settings') const { ObjectId } = require('mongodb') const { Project } = require('../app/src/models/Project') async function main() { const { image, projectIds } = parseArgs() await updateImage(image, projectIds) } function parseArgs() { if (process.argv.length < 4) { printUsage() process.exit(1) } const image = parseImage(process.argv[2]) const projectIds = parseProjectIds(process.argv.slice(3)) return { image, projectIds } } function printUsage() { console.error('Usage: node set_tex_live_image.js <image> <projectId> ...') } function parseImage(image) { const allowedImageNames = Settings.allowedImageNames.map(x => x.imageName) if (!allowedImageNames.includes(image)) { console.error(`Unknown image: ${image}`) console.error('Please use one of:') for (const allowedImage of allowedImageNames) { console.error(` - ${allowedImage}`) } process.exit(1) } return image } function parseProjectIds(projectIds) { const oids = [] for (const projectId of projectIds) { let oid try { oid = ObjectId(projectId) } catch (err) { console.error(`Invalid project id: ${projectId}`) process.exit(1) } oids.push(oid) } return oids } async function updateImage(image, projectIds) { const res = await Project.updateMany( { _id: { $in: projectIds.map(ObjectId) } }, { $set: { imageName: `quay.io/sharelatex/${image}` } } ).exec() console.log(`Found ${res.n} out of ${projectIds.length} projects`) console.log(`Modified ${res.nModified} projects`) } main() .then(() => { process.exit() }) .catch(err => { console.error(err) process.exit(1) })
overleaf/web/scripts/set_tex_live_image.js/0
{ "file_path": "overleaf/web/scripts/set_tex_live_image.js", "repo_id": "overleaf", "token_count": 650 }
543
{ "devDependencies": { "@fidm/x509": "^1.2.1" } }
overleaf/web/scripts/ukamf/package.json/0
{ "file_path": "overleaf/web/scripts/ukamf/package.json", "repo_id": "overleaf", "token_count": 36 }
544
Test
overleaf/web/test/acceptance/files/test.tex/0
{ "file_path": "overleaf/web/test/acceptance/files/test.tex", "repo_id": "overleaf", "token_count": 1 }
545
const { exec } = require('child_process') const { promisify } = require('util') const { expect } = require('chai') const logger = require('logger-sharelatex') const { filterOutput } = require('./helpers/settings') const { db, ObjectId } = require('../../../app/src/infrastructure/mongodb') const DUMMY_NAME = 'unknown.tex' const DUMMY_TIME = new Date('2021-04-12T00:00:00.000Z') const ONE_DAY_IN_S = 60 * 60 * 24 const BATCH_SIZE = 3 function getSecondsFromObjectId(id) { return id.getTimestamp().getTime() / 1000 } function getObjectIdFromDate(date) { const seconds = new Date(date).getTime() / 1000 return ObjectId.createFromTime(seconds) } describe('BackFillDummyDocMeta', function () { let docIds let projectIds let stopAtSeconds beforeEach('create docs', async function () { docIds = [] docIds[0] = getObjectIdFromDate('2021-04-01T00:00:00.000Z') docIds[1] = getObjectIdFromDate('2021-04-02T00:00:00.000Z') docIds[2] = getObjectIdFromDate('2021-04-11T00:00:00.000Z') docIds[3] = getObjectIdFromDate('2021-04-12T00:00:00.000Z') docIds[4] = getObjectIdFromDate('2021-04-13T00:00:00.000Z') docIds[5] = getObjectIdFromDate('2021-04-14T00:00:00.000Z') docIds[6] = getObjectIdFromDate('2021-04-15T00:00:00.000Z') docIds[7] = getObjectIdFromDate('2021-04-16T00:01:00.000Z') docIds[8] = getObjectIdFromDate('2021-04-16T00:02:00.000Z') docIds[9] = getObjectIdFromDate('2021-04-16T00:03:00.000Z') docIds[10] = getObjectIdFromDate('2021-04-16T00:04:00.000Z') docIds[11] = getObjectIdFromDate('2021-04-16T00:05:00.000Z') projectIds = [] projectIds[0] = getObjectIdFromDate('2021-04-01T00:00:00.000Z') projectIds[1] = getObjectIdFromDate('2021-04-02T00:00:00.000Z') projectIds[2] = getObjectIdFromDate('2021-04-11T00:00:00.000Z') projectIds[3] = getObjectIdFromDate('2021-04-12T00:00:00.000Z') projectIds[4] = getObjectIdFromDate('2021-04-13T00:00:00.000Z') projectIds[5] = getObjectIdFromDate('2021-04-14T00:00:00.000Z') projectIds[6] = getObjectIdFromDate('2021-04-15T00:00:00.000Z') projectIds[7] = getObjectIdFromDate('2021-04-16T00:01:00.000Z') projectIds[8] = getObjectIdFromDate('2021-04-16T00:02:00.000Z') projectIds[9] = getObjectIdFromDate('2021-04-16T00:03:00.000Z') // two docs in the same project projectIds[10] = projectIds[9] projectIds[11] = projectIds[4] stopAtSeconds = new Date('2021-04-17T00:00:00.000Z').getTime() / 1000 }) const now = new Date() beforeEach('insert doc stubs into docs collection', async function () { await db.docs.insertMany([ // incomplete, without deletedDocs context { _id: docIds[0], project_id: projectIds[0], deleted: true }, { _id: docIds[1], project_id: projectIds[1], deleted: true }, { _id: docIds[2], project_id: projectIds[2], deleted: true }, { _id: docIds[3], project_id: projectIds[3], deleted: true }, // incomplete, with deletedDocs context { _id: docIds[4], project_id: projectIds[4], deleted: true }, // complete { _id: docIds[5], project_id: projectIds[5], deleted: true, name: 'foo.tex', deletedAt: now, }, // not deleted { _id: docIds[6], project_id: projectIds[6] }, // multiple in a single batch { _id: docIds[7], project_id: projectIds[7], deleted: true }, { _id: docIds[8], project_id: projectIds[8], deleted: true }, { _id: docIds[9], project_id: projectIds[9], deleted: true }, // two docs in one project { _id: docIds[10], project_id: projectIds[10], deleted: true }, { _id: docIds[11], project_id: projectIds[11], deleted: true }, ]) }) beforeEach('insert deleted project context', async function () { await db.deletedProjects.insertMany([ // projectIds[0] and projectIds[1] have no entry // hard-deleted { deleterData: { deletedProjectId: projectIds[2] } }, // soft-deleted, no entry for doc { deleterData: { deletedProjectId: projectIds[3] }, project: { deletedDocs: [] }, }, // soft-deleted, has entry for doc { deleterData: { deletedProjectId: projectIds[4] }, project: { deletedDocs: [ { _id: docIds[4], name: 'main.tex', deletedAt: now }, { _id: docIds[11], name: 'main.tex', deletedAt: now }, ], }, }, ]) }) let options async function runScript(dryRun) { options = { BATCH_SIZE, CACHE_SIZE: 100, DRY_RUN: dryRun, FIRST_PROJECT_ID: projectIds[0].toString(), INCREMENT_BY_S: ONE_DAY_IN_S, STOP_AT_S: stopAtSeconds, // start right away LET_USER_DOUBLE_CHECK_INPUTS_FOR: 1, } let result try { result = await promisify(exec)( Object.entries(options) .map(([key, value]) => `${key}=${value}`) .concat(['node', 'scripts/back_fill_dummy_doc_meta.js']) .join(' ') ) } catch (error) { // dump details like exit code, stdErr and stdOut logger.error({ error }, 'script failed') throw error } let { stderr: stdErr, stdout: stdOut } = result stdErr = stdErr.split('\n') stdOut = stdOut.split('\n').filter(filterOutput) const oneDayFromProjectId9InSeconds = getSecondsFromObjectId(projectIds[9]) + ONE_DAY_IN_S const oneDayFromProjectId9AsObjectId = getObjectIdFromDate( 1000 * oneDayFromProjectId9InSeconds ) let overlappingPartStdOut let overlappingPartStdErr if (dryRun) { // In dry-run, the previous id will get processed again as the name has not been updated. overlappingPartStdOut = [ `Back filling dummy meta data for ["${docIds[9]}","${docIds[10]}"]`, `Orphaned deleted doc ${docIds[9]} (no deletedProjects entry)`, `Orphaned deleted doc ${docIds[10]} (no deletedProjects entry)`, ] overlappingPartStdErr = [ `Processed 11 until ${oneDayFromProjectId9AsObjectId}`, ] } else { // Outside dry-run, the previous id will not match again as the `name` has been back-filled. overlappingPartStdOut = [ `Back filling dummy meta data for ["${docIds[10]}"]`, `Orphaned deleted doc ${docIds[10]} (no deletedProjects entry)`, ] overlappingPartStdErr = [ `Processed 10 until ${oneDayFromProjectId9AsObjectId}`, ] } expect(stdOut.filter(filterOutput)).to.deep.equal([ `Back filling dummy meta data for ["${docIds[0]}"]`, `Orphaned deleted doc ${docIds[0]} (no deletedProjects entry)`, `Back filling dummy meta data for ["${docIds[1]}"]`, `Orphaned deleted doc ${docIds[1]} (no deletedProjects entry)`, `Back filling dummy meta data for ["${docIds[2]}"]`, `Orphaned deleted doc ${docIds[2]} (failed hard deletion)`, `Back filling dummy meta data for ["${docIds[3]}"]`, `Missing deletedDoc for ${docIds[3]}`, // two docs in the same project `Back filling dummy meta data for ["${docIds[4]}","${docIds[11]}"]`, `Found deletedDoc for ${docIds[4]}`, `Found deletedDoc for ${docIds[11]}`, // 7,8,9 are on the same day, but exceed the batch size of 2 `Back filling dummy meta data for ["${docIds[7]}","${docIds[8]}","${docIds[9]}"]`, `Orphaned deleted doc ${docIds[7]} (no deletedProjects entry)`, `Orphaned deleted doc ${docIds[8]} (no deletedProjects entry)`, `Orphaned deleted doc ${docIds[9]} (no deletedProjects entry)`, // Potential double processing ...overlappingPartStdOut, '', ]) expect(stdErr.filter(filterOutput)).to.deep.equal([ `Options: {`, ` "dryRun": ${options.DRY_RUN},`, ` "cacheSize": ${options.CACHE_SIZE},`, ` "firstProjectId": "${options.FIRST_PROJECT_ID}",`, ` "incrementByS": ${options.INCREMENT_BY_S},`, ` "batchSize": ${options.BATCH_SIZE},`, ` "stopAtS": ${options.STOP_AT_S},`, ` "letUserDoubleCheckInputsFor": ${options.LET_USER_DOUBLE_CHECK_INPUTS_FOR}`, '}', 'Waiting for you to double check inputs for 1 ms', `Processed 1 until ${getObjectIdFromDate('2021-04-02T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-03T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-04T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-05T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-06T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-07T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-08T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-09T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-10T00:00:00.000Z')}`, `Processed 2 until ${getObjectIdFromDate('2021-04-11T00:00:00.000Z')}`, `Processed 3 until ${getObjectIdFromDate('2021-04-12T00:00:00.000Z')}`, `Processed 4 until ${getObjectIdFromDate('2021-04-13T00:00:00.000Z')}`, `Processed 6 until ${getObjectIdFromDate('2021-04-14T00:00:00.000Z')}`, `Processed 6 until ${getObjectIdFromDate('2021-04-15T00:00:00.000Z')}`, `Processed 6 until ${getObjectIdFromDate('2021-04-16T00:00:00.000Z')}`, // 7,8,9,10 are on the same day, but exceed the batch size of 3 `Processed 9 until ${projectIds[9]}`, ...overlappingPartStdErr, 'Done.', '', ]) } describe('DRY_RUN=true', function () { beforeEach('run script', async function () { await runScript(true) }) it('should leave docs as is', async function () { const docs = await db.docs.find({}).toArray() expect(docs).to.deep.equal([ { _id: docIds[0], project_id: projectIds[0], deleted: true }, { _id: docIds[1], project_id: projectIds[1], deleted: true }, { _id: docIds[2], project_id: projectIds[2], deleted: true }, { _id: docIds[3], project_id: projectIds[3], deleted: true }, { _id: docIds[4], project_id: projectIds[4], deleted: true }, { _id: docIds[5], project_id: projectIds[5], deleted: true, name: 'foo.tex', deletedAt: now, }, { _id: docIds[6], project_id: projectIds[6] }, { _id: docIds[7], project_id: projectIds[7], deleted: true }, { _id: docIds[8], project_id: projectIds[8], deleted: true }, { _id: docIds[9], project_id: projectIds[9], deleted: true }, { _id: docIds[10], project_id: projectIds[10], deleted: true }, { _id: docIds[11], project_id: projectIds[11], deleted: true }, ]) }) }) describe('DRY_RUN=false', function () { beforeEach('run script', async function () { await runScript(false) }) it('should back fill name and deletedAt dates into broken docs', async function () { const docs = await db.docs.find({}).toArray() expect(docs).to.deep.equal([ { _id: docIds[0], project_id: projectIds[0], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[1], project_id: projectIds[1], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[2], project_id: projectIds[2], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[3], project_id: projectIds[3], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[4], project_id: projectIds[4], deleted: true, name: 'main.tex', deletedAt: now, }, { _id: docIds[5], project_id: projectIds[5], deleted: true, name: 'foo.tex', deletedAt: now, }, { _id: docIds[6], project_id: projectIds[6] }, { _id: docIds[7], project_id: projectIds[7], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[8], project_id: projectIds[8], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[9], project_id: projectIds[9], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[10], project_id: projectIds[10], deleted: true, name: DUMMY_NAME, deletedAt: DUMMY_TIME, }, { _id: docIds[11], project_id: projectIds[11], deleted: true, name: 'main.tex', deletedAt: now, }, ]) }) }) })
overleaf/web/test/acceptance/src/BackFillDummyDocMetaTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/BackFillDummyDocMetaTests.js", "repo_id": "overleaf", "token_count": 6058 }
546
const { expect } = require('chai') const User = require('./helpers/User').promises const { Project } = require('../../../app/src/models/Project') const { ObjectId } = require('mongodb') const cheerio = require('cheerio') describe('Project CRUD', function () { beforeEach(async function () { this.user = new User() await this.user.login() this.projectId = await this.user.createProject('example-project') }) describe('project page', function () { it('should cast refProviders to booleans', async function () { await this.user.mongoUpdate({ $set: { refProviders: { mendeley: { encrypted: 'aaa' }, zotero: { encrypted: 'bbb' }, }, }, }) const { response, body } = await this.user.doRequest( 'GET', `/project/${this.projectId}` ) expect(response.statusCode).to.equal(200) const dom = cheerio.load(body) const metaOlUser = dom('meta[name="ol-user"]')[0] const userData = JSON.parse(metaOlUser.attribs.content) expect(userData.refProviders.mendeley).to.equal(true) expect(userData.refProviders.zotero).to.equal(true) }) }) describe("when project doesn't exist", function () { it('should return 404', async function () { const { response } = await this.user.doRequest( 'GET', '/project/aaaaaaaaaaaaaaaaaaaaaaaa' ) expect(response.statusCode).to.equal(404) }) }) describe('when project has malformed id', function () { it('should return 404', async function () { const { response } = await this.user.doRequest('GET', '/project/blah') expect(response.statusCode).to.equal(404) }) }) describe('when trashing a project', function () { it('should mark the project as trashed for the user', async function () { const { response } = await this.user.doRequest( 'POST', `/project/${this.projectId}/trash` ) expect(response.statusCode).to.equal(200) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.trashed, [this.user._id]) }) it('does nothing if the user has already trashed the project', async function () { // Mark as trashed the first time await this.user.doRequest('POST', `/project/${this.projectId}/trash`) // And then a second time await this.user.doRequest('POST', `/project/${this.projectId}/trash`) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.trashed, [this.user._id]) }) describe('with an array archived state', function () { it('should mark the project as not archived for the user', async function () { await Project.updateOne( { _id: this.projectId }, { $set: { archived: [ObjectId(this.user._id)] } } ).exec() const { response } = await this.user.doRequest( 'POST', `/project/${this.projectId}/trash` ) expect(response.statusCode).to.equal(200) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.archived, []) }) }) describe('with a legacy boolean state', function () { it('should mark the project as not archived for the user', async function () { await Project.updateOne( { _id: this.projectId }, { $set: { archived: true } } ).exec() const { response } = await this.user.doRequest( 'POST', `/project/${this.projectId}/trash` ) expect(response.statusCode).to.equal(200) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.archived, []) }) }) }) describe('when untrashing a project', function () { it('should mark the project as untrashed for the user', async function () { await Project.updateOne( { _id: this.projectId }, { trashed: [ObjectId(this.user._id)] } ).exec() const { response } = await this.user.doRequest( 'DELETE', `/project/${this.projectId}/trash` ) expect(response.statusCode).to.equal(200) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.trashed, []) }) it('does nothing if the user has already untrashed the project', async function () { await Project.updateOne( { _id: this.projectId }, { trashed: [ObjectId(this.user._id)] } ).exec() // Mark as untrashed the first time await this.user.doRequest('DELETE', `/project/${this.projectId}/trash`) // And then a second time await this.user.doRequest('DELETE', `/project/${this.projectId}/trash`) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.trashed, []) }) it('sets trashed to an empty array if not set', async function () { await this.user.doRequest('DELETE', `/project/${this.projectId}/trash`) const trashedProject = await Project.findById(this.projectId).exec() expectObjectIdArrayEqual(trashedProject.trashed, []) }) }) }) function expectObjectIdArrayEqual(objectIdArray, stringArray) { const stringifiedArray = objectIdArray.map(id => id.toString()) expect(stringifiedArray).to.deep.equal(stringArray) }
overleaf/web/test/acceptance/src/ProjectCRUDTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/ProjectCRUDTests.js", "repo_id": "overleaf", "token_count": 2147 }
547
const { expect } = require('chai') const async = require('async') const User = require('./helpers/User') const request = require('./helpers/request') const settings = require('@overleaf/settings') const { db } = require('../../../app/src/infrastructure/mongodb') const expectErrorResponse = require('./helpers/expectErrorResponse') const tryEditorAccess = (user, projectId, test, callback) => async.series( [ cb => user.request.get(`/project/${projectId}`, (error, response, body) => { if (error != null) { return cb(error) } test(response, body) cb() }), cb => user.request.get( `/project/${projectId}/download/zip`, (error, response, body) => { if (error != null) { return cb(error) } test(response, body) cb() } ), ], callback ) const tryReadOnlyTokenAccess = ( user, token, testPageLoad, testFormPost, callback ) => { _doTryTokenAccess( `/read/${token}`, user, token, testPageLoad, testFormPost, callback ) } const tryReadAndWriteTokenAccess = ( user, token, testPageLoad, testFormPost, callback ) => { _doTryTokenAccess( `/${token}`, user, token, testPageLoad, testFormPost, callback ) } const _doTryTokenAccess = ( url, user, token, testPageLoad, testFormPost, callback ) => { user.request.get(url, (err, response, body) => { if (err) { return callback(err) } testPageLoad(response, body) if (!testFormPost) { return callback() } user.request.post( `${url}/grant`, { json: { token } }, (err, response, body) => { if (err) { return callback(err) } testFormPost(response, body) callback() } ) }) } const tryContentAccess = (user, projcetId, test, callback) => { // The real-time service calls this end point to determine the user's // permissions. let userId if (user.id != null) { userId = user.id } else { userId = 'anonymous-user' } request.post( { url: `/project/${projcetId}/join`, qs: { user_id: userId }, auth: { user: settings.apis.web.user, pass: settings.apis.web.pass, sendImmediately: true, }, json: true, jar: false, }, (error, response, body) => { if (error != null) { return callback(error) } test(response, body) callback() } ) } const tryAnonContentAccess = (user, projectId, token, test, callback) => { // The real-time service calls this end point to determine the user's // permissions. let userId if (user.id != null) { userId = user.id } else { userId = 'anonymous-user' } request.post( { url: `/project/${projectId}/join`, qs: { user_id: userId }, auth: { user: settings.apis.web.user, pass: settings.apis.web.pass, sendImmediately: true, }, headers: { 'x-sl-anonymous-access-token': token, }, json: true, jar: false, }, (error, response, body) => { if (error != null) { return callback(error) } test(response, body) callback() } ) } describe('TokenAccess', function () { beforeEach(function (done) { this.timeout(90000) this.owner = new User() this.other1 = new User() this.other2 = new User() this.anon = new User() this.siteAdmin = new User({ email: 'admin@example.com' }) async.parallel( [ cb => this.siteAdmin.login(err => { if (err) { return cb(err) } this.siteAdmin.ensureAdmin(cb) }), cb => this.owner.login(cb), cb => this.other1.login(cb), cb => this.other2.login(cb), cb => this.anon.getCsrfToken(cb), ], done ) }) describe('no token-access', function () { beforeEach(function (done) { this.owner.createProject( `token-ro-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId // Note, never made token-based, // thus no tokens done() } ) }) it('should deny access ', function (done) { async.series( [ cb => { tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ) }, cb => { tryContentAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ) }, ], done ) }) }) describe('read-only token', function () { beforeEach(function (done) { this.owner.createProject( `token-ro-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('allow the user read-only access to the project', function (done) { async.series( [ cb => { // deny access before token is used tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ) }, cb => { // use token tryReadOnlyTokenAccess( this.other1, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) expect(body.tokenAccessGranted).to.equal('readOnly') }, cb ) }, cb => { // allow content access read-only tryContentAccess( this.other1, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('readOnly') expect(body.isRestrictedUser).to.equal(true) expect(body.project.owner).to.have.keys('_id') expect(body.project.owner).to.not.have.any.keys( 'email', 'first_name', 'last_name' ) }, cb ) }, cb => { tryEditorAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ) }, ], done ) }) it('should redirect the admin to the project (with rw access)', function (done) { async.series( [ cb => { // use token tryReadOnlyTokenAccess( this.siteAdmin, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) }, cb ) }, cb => { // allow content access read-and-write tryContentAccess( this.siteAdmin, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('owner') expect(body.isRestrictedUser).to.equal(false) }, cb ) }, ], done ) }) describe('made private again', function () { beforeEach(function (done) { this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000)) }) it('should not allow the user to access the project', function (done) { async.series( [ // no access before token is used cb => tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ), // token goes nowhere cb => tryReadOnlyTokenAccess( this.other1, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(404) }, cb ), // still no access cb => tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryContentAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ), ], done ) }) }) }) describe('anonymous read-only token', function () { beforeEach(function (done) { this.owner.createProject( `token-anon-ro-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('should allow the user to access project via read-only token url', function (done) { async.series( [ cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryReadOnlyTokenAccess( this.anon, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) expect(body.grantAnonymousAccess).to.equal('readOnly') }, cb ), cb => tryEditorAccess( this.anon, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ), cb => tryAnonContentAccess( this.anon, this.projectId, this.tokens.readOnly, (response, body) => { expect(body.privilegeLevel).to.equal('readOnly') expect(body.isRestrictedUser).to.equal(true) expect(body.project.owner).to.have.keys('_id') expect(body.project.owner).to.not.have.any.keys( 'email', 'first_name', 'last_name' ) }, cb ), ], done ) }) describe('made private again', function () { beforeEach(function (done) { this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000)) }) it('should deny access to project', function (done) { async.series( [ cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), // should not allow the user to access read-only token cb => tryReadOnlyTokenAccess( this.anon, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(404) }, cb ), // still no access cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), // should not allow the user to join the project cb => tryAnonContentAccess( this.anon, this.projectId, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ), ], done ) }) }) }) describe('read-and-write token', function () { beforeEach(function (done) { this.owner.createProject( `token-rw-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('should allow the user to access project via read-and-write token url', function (done) { async.series( [ // deny access before the token is used cb => tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryReadAndWriteTokenAccess( this.other1, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) expect(body.tokenAccessGranted).to.equal('readAndWrite') }, cb ), cb => tryEditorAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ), cb => tryContentAccess( this.other1, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('readAndWrite') expect(body.isRestrictedUser).to.equal(false) expect(body.project.owner).to.have.all.keys( '_id', 'email', 'first_name', 'last_name', 'privileges', 'signUpDate' ) }, cb ), ], done ) }) describe('upgrading from a read-only token', function () { beforeEach(function (done) { this.owner.createProject( `token-rw-upgrade-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('should allow user to access project via read-only, then upgrade to read-write', function (done) { async.series( [ // deny access before the token is used cb => tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ), cb => { // use read-only token tryReadOnlyTokenAccess( this.other1, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) expect(body.tokenAccessGranted).to.equal('readOnly') }, cb ) }, cb => { tryEditorAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ) }, cb => { // allow content access read-only tryContentAccess( this.other1, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('readOnly') expect(body.isRestrictedUser).to.equal(true) expect(body.project.owner).to.have.keys('_id') expect(body.project.owner).to.not.have.any.keys( 'email', 'first_name', 'last_name' ) }, cb ) }, // // Then switch to read-write token // cb => tryReadAndWriteTokenAccess( this.other1, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) expect(body.tokenAccessGranted).to.equal('readAndWrite') }, cb ), cb => tryEditorAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ), cb => tryContentAccess( this.other1, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('readAndWrite') expect(body.isRestrictedUser).to.equal(false) expect(body.project.owner).to.have.all.keys( '_id', 'email', 'first_name', 'last_name', 'privileges', 'signUpDate' ) }, cb ), ], done ) }) }) describe('made private again', function () { beforeEach(function (done) { this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000)) }) it('should deny access to project', function (done) { async.series( [ cb => { tryEditorAccess( this.other1, this.projectId, (response, body) => {}, cb ) }, cb => { tryReadAndWriteTokenAccess( this.other1, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(404) }, cb ) }, cb => { tryEditorAccess( this.other1, this.projectId, expectErrorResponse.restricted.html, cb ) }, cb => { tryContentAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ) }, ], done ) }) }) }) if (!settings.allowAnonymousReadAndWriteSharing) { describe('anonymous read-and-write token, disabled', function () { beforeEach(function (done) { this.owner.createProject( `token-anon-rw-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('should not allow the user to access read-and-write token', function (done) { async.series( [ cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryReadAndWriteTokenAccess( this.anon, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body).to.deep.equal({ redirect: '/restricted', anonWriteAccessDenied: true, }) }, cb ), cb => tryAnonContentAccess( this.anon, this.projectId, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ), cb => this.anon.login((err, response, body) => { expect(err).to.not.exist expect(response.statusCode).to.equal(200) expect(body.redir).to.equal(`/${this.tokens.readAndWrite}`) cb() }), ], done ) }) }) } else { describe('anonymous read-and-write token, enabled', function () { beforeEach(function (done) { this.owner.createProject( `token-anon-rw-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('should allow the user to access project via read-and-write token url', function (done) { async.series( [ cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryReadAndWriteTokenAccess( this.anon, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(body.redirect).to.equal(`/project/${this.projectId}`) expect(body.grantAnonymousAccess).to.equal('readAndWrite') }, cb ), cb => tryEditorAccess( this.anon, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ), cb => tryAnonContentAccess( this.anon, this.projectId, this.tokens.readAndWrite, (response, body) => { expect(body.privilegeLevel).to.equal('readAndWrite') }, cb ), ], done ) }) describe('made private again', function () { beforeEach(function (done) { this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000)) }) it('should not allow the user to access read-and-write token', function (done) { async.series( [ cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryReadAndWriteTokenAccess( this.anon, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(404) }, cb ), cb => tryEditorAccess( this.anon, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryAnonContentAccess( this.anon, this.projectId, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ), ], done ) }) }) }) } describe('private overleaf project', function () { beforeEach(function (done) { this.owner.createProject('overleaf-import', (err, projectId) => { expect(err).not.to.exist this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { expect(err).not.to.exist this.owner.getProject(this.projectId, (err, project) => { expect(err).not.to.exist this.tokens = project.tokens this.owner.makePrivate(this.projectId, () => { db.projects.updateOne( { _id: project._id }, { $set: { overleaf: { id: 1234 }, }, }, err => { expect(err).not.to.exist done() } ) }) }) }) }) }) it('should only allow the owner access to the project', function (done) { async.series( [ // should redirect to canonical path, when owner uses read-write token cb => tryReadAndWriteTokenAccess( this.owner, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(response.body.redirect).to.equal( `/project/${this.projectId}` ) expect(response.body.higherAccess).to.equal(true) }, cb ), cb => tryEditorAccess( this.owner, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ), cb => tryContentAccess( this.owner, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('owner') }, cb ), // non-owner should be denied access cb => tryContentAccess( this.other2, this.projectId, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ), ], done ) }) }) describe('private project, with higher access', function () { beforeEach(function (done) { this.owner.createProject( `higher-access-test-${Math.random()}`, (err, projectId) => { expect(err).not.to.exist this.projectId = projectId this.owner.addUserToProject( this.projectId, this.other1, 'readAndWrite', err => { expect(err).not.to.exist this.owner.makeTokenBased(this.projectId, err => { expect(err).not.to.exist this.owner.getProject(this.projectId, (err, project) => { expect(err).not.to.exist this.tokens = project.tokens this.owner.makePrivate(this.projectId, () => { setTimeout(done, 1000) }) }) }) } ) } ) }) it('should allow the user access to the project', function (done) { async.series( [ // should redirect to canonical path, when user uses read-write token cb => tryReadAndWriteTokenAccess( this.other1, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(response.body.redirect).to.equal( `/project/${this.projectId}` ) expect(response.body.higherAccess).to.equal(true) }, cb ), // should redirect to canonical path, when user uses read-only token cb => tryReadOnlyTokenAccess( this.other1, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(200) expect(response.body.redirect).to.equal( `/project/${this.projectId}` ) expect(response.body.higherAccess).to.equal(true) }, cb ), // should allow the user access to the project cb => tryEditorAccess( this.other1, this.projectId, (response, body) => { expect(response.statusCode).to.equal(200) }, cb ), // should allow user to join the project cb => tryContentAccess( this.other1, this.projectId, (response, body) => { expect(body.privilegeLevel).to.equal('readAndWrite') }, cb ), // should not allow a different user to join the project cb => tryEditorAccess( this.other2, this.projectId, expectErrorResponse.restricted.html, cb ), cb => tryContentAccess( this.other2, this.projectId, (response, body) => { expect(response.statusCode).to.equal(403) expect(body).to.equal('Forbidden') }, cb ), ], done ) }) }) describe('deleted project', function () { beforeEach(function (done) { this.owner.createProject( `delete-test${Math.random()}`, (err, projectId) => { if (err != null) { return done(err) } this.projectId = projectId this.owner.makeTokenBased(this.projectId, err => { if (err != null) { return done(err) } this.owner.getProject(this.projectId, (err, project) => { if (err != null) { return done(err) } this.tokens = project.tokens done() }) }) } ) }) it('should 404', function (done) { async.series( [ // delete project cb => { this.owner.deleteProject(this.projectId, cb) }, cb => { // use read-only token tryReadOnlyTokenAccess( this.other1, this.tokens.readOnly, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(404) }, cb ) }, cb => { // use read-write token tryReadAndWriteTokenAccess( this.other1, this.tokens.readAndWrite, (response, body) => { expect(response.statusCode).to.equal(200) }, (response, body) => { expect(response.statusCode).to.equal(404) }, cb ) }, ], done ) }) }) })
overleaf/web/test/acceptance/src/TokenAccessTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/TokenAccessTests.js", "repo_id": "overleaf", "token_count": 21269 }
548
const { expect } = require('chai') module.exports = { requireLogin: { json(response, body) { expect(response.statusCode).to.equal(401) expect(body).to.equal('Unauthorized') expect(response.headers['www-authenticate']).to.equal('OverleafLogin') }, }, restricted: { html(response, body) { expect(response.statusCode).to.equal(403) expect(body).to.match(/<head><title>Restricted/) }, json(response, body) { expect(response.statusCode).to.equal(403) expect(body).to.deep.equal({ message: 'restricted' }) }, }, }
overleaf/web/test/acceptance/src/helpers/expectErrorResponse.js/0
{ "file_path": "overleaf/web/test/acceptance/src/helpers/expectErrorResponse.js", "repo_id": "overleaf", "token_count": 233 }
549
const AbstractMockApi = require('./AbstractMockApi') const sinon = require('sinon') class MockV1Api extends AbstractMockApi { reset() { this.affiliations = [] this.allInstitutionDomains = new Set() this.blocklistedDomains = [] this.brand_variations = {} this.brands = {} this.doc_exported = {} this.docInfo = {} this.existingEmails = [] this.exportId = null this.exportParams = null this.institutionDomains = {} this.institutionId = 1000 this.institutions = {} this.syncUserFeatures = sinon.stub() this.templates = {} this.updateEmail = sinon.stub() this.users = {} this.v1Id = 1000 this.validation_clients = {} } nextInstitutionId() { return this.institutionId++ } nextV1Id() { return this.v1Id++ } setUser(id, user) { this.users[id] = user } getDocInfo(token) { return this.docInfo[token] || null } setDocInfo(token, info) { this.docInfo[token] = info } setExportId(id) { this.exportId = id } getLastExportParams() { return this.exportParams } clearExportParams() { this.exportParams = null } createInstitution(options = {}) { const id = options.university_id || this.nextInstitutionId() options.id = id // include ID so that it is included in APIs this.institutions[id] = { ...options } if (options && options.hostname) { this.addInstitutionDomain(id, options.hostname, { confirmed: options.confirmed, }) } return id } addInstitutionDomain(institutionId, domain, options = {}) { if (this.allInstitutionDomains.has(domain)) return if (!this.institutionDomains[institutionId]) { this.institutionDomains[institutionId] = {} } this.institutionDomains[institutionId][domain] = options this.allInstitutionDomains.add(domain) } updateInstitution(id, options) { Object.assign(this.institutions[id], options) } updateInstitutionDomain(id, domain, options = {}) { if (!this.institutionDomains[id] || !this.institutionDomains[id][domain]) return this.institutionDomains[id][domain] = Object.assign( {}, this.institutionDomains[id][domain], options ) } addAffiliation(userId, email) { const institution = {} if (!email) return if (!this.affiliations[userId]) this.affiliations[userId] = [] if ( this.affiliations[userId].find(affiliationData => { return affiliationData.email === email }) ) return const domain = email.split('@').pop() if (this.blocklistedDomains.indexOf(domain.replace('.com', '')) !== -1) { return } if (this.allInstitutionDomains.has(domain)) { for (const [institutionId, domainData] of Object.entries( this.institutionDomains )) { if (domainData[domain]) { institution.id = institutionId } } } if (institution.id) { this.affiliations[userId].push({ email, institution }) } } setDocExported(token, info) { this.doc_exported[token] = info } setTemplates(templates) { this.templates = templates } applyRoutes() { this.app.get( '/api/v1/sharelatex/users/:v1_user_id/plan_code', (req, res) => { const user = this.users[req.params.v1_user_id] if (user) { res.json(user) } else { res.sendStatus(404) } } ) this.app.get( '/api/v1/sharelatex/users/:v1_user_id/subscriptions', (req, res) => { const user = this.users[req.params.v1_user_id] if (user && user.subscription) { res.json(user.subscription) } else { res.sendStatus(404) } } ) this.app.get( '/api/v1/sharelatex/users/:v1_user_id/subscription_status', (req, res) => { const user = this.users[req.params.v1_user_id] if (user && user.subscription_status) { res.json(user.subscription_status) } else { res.sendStatus(404) } } ) this.app.delete( '/api/v1/sharelatex/users/:v1_user_id/subscription', (req, res) => { const user = this.users[req.params.v1_user_id] if (user) { user.canceled = true res.sendStatus(200) } else { res.sendStatus(404) } } ) this.app.post('/api/v1/sharelatex/users/:v1_user_id/sync', (req, res) => { this.syncUserFeatures(req.params.v1_user_id) res.sendStatus(200) }) this.app.post('/api/v1/sharelatex/exports', (req, res) => { this.exportParams = Object.assign({}, req.body) res.json({ exportId: this.exportId }) }) this.app.get('/api/v2/users/:userId/affiliations', (req, res) => { if (!this.affiliations[req.params.userId]) return res.json([]) const affiliations = this.affiliations[req.params.userId].map( affiliation => { const institutionId = affiliation.institution.id const domain = affiliation.email.split('@').pop() const domainData = this.institutionDomains[institutionId][domain] || {} const institutionData = this.institutions[institutionId] || {} affiliation.institution = { id: institutionId, name: institutionData.name, commonsAccount: institutionData.commonsAccount, isUniversity: !institutionData.institution, ssoBeta: institutionData.sso_beta || false, ssoEnabled: institutionData.sso_enabled || false, maxConfirmationMonths: institutionData.maxConfirmationMonths || null, } affiliation.institution.confirmed = !!domainData.confirmed affiliation.licence = 'free' if ( institutionData.commonsAccount && (!institutionData.sso_enabled || (institutionData.sso_enabled && affiliation.cached_entitlement === true)) ) { affiliation.licence = 'pro_plus' } return affiliation } ) res.json(affiliations) }) this.app.post('/api/v2/users/:userId/affiliations', (req, res) => { this.addAffiliation(req.params.userId, req.body.email) res.sendStatus(201) }) this.app.delete('/api/v2/users/:userId/affiliations', (req, res) => { res.sendStatus(201) }) this.app.delete('/api/v2/users/:userId/affiliations/:email', (req, res) => { res.sendStatus(204) }) this.app.post( '/api/v2/institutions/reconfirmation_lapsed_processed', (req, res) => { res.sendStatus(200) } ) this.app.get( '/api/v2/institutions/need_reconfirmation_lapsed_processed', (req, res) => { const usersWithAffiliations = [] Object.keys(this.affiliations).forEach(userId => { if (this.affiliations[userId].length > 0) { usersWithAffiliations.push(userId) } }) res.json({ data: { users: usersWithAffiliations } }) } ) this.app.get('/api/v2/brands/:slug', (req, res) => { let brand if ((brand = this.brands[req.params.slug])) { res.json(brand) } else { res.sendStatus(404) } }) this.app.get('/universities/list', (req, res) => res.json([])) this.app.get('/universities/list/:id', (req, res) => res.json({ id: parseInt(req.params.id), name: `Institution ${req.params.id}`, }) ) this.app.get('/university/domains', (req, res) => res.json([])) this.app.put('/api/v1/sharelatex/users/:id/email', (req, res) => { const { email } = req.body && req.body.user if (this.existingEmails.includes(email)) { res.sendStatus(409) } else { this.updateEmail(parseInt(req.params.id), email) res.sendStatus(200) } }) this.app.post('/api/v1/sharelatex/login', (req, res) => { for (const id in this.users) { const user = this.users[id] if ( user && user.email === req.body.email && user.password === req.body.password ) { return res.json({ email: user.email, valid: true, user_profile: user.profile, }) } } res.status(403).json({ email: req.body.email, valid: false, }) }) this.app.get('/api/v2/partners/:partner/conversions/:id', (req, res) => { const partner = this.validation_clients[req.params.partner] const conversion = partner && partner.conversions && partner.conversions[req.params.id] if (conversion) { res.status(200).json({ input_file_uri: conversion, brand_variation_id: partner.brand_variation_id, }) } else { res.status(404).json({}) } }) this.app.get('/api/v2/brand_variations/:id', (req, res) => { const variation = this.brand_variations[req.params.id] if (variation) { res.status(200).json(variation) } else { res.status(404).json({}) } }) this.app.get('/api/v1/sharelatex/docs/:token/is_published', (req, res) => { return res.json({ allow: true }) }) this.app.get( '/api/v1/sharelatex/users/:user_id/docs/:token/info', (req, res) => { const info = this.getDocInfo(req.params.token) || { exists: false, exported: false, } res.json(info) } ) this.app.get('/api/v1/sharelatex/docs/:token/info', (req, res) => { const info = this.getDocInfo(req.params.token) || { exists: false, exported: false, } res.json(info) }) this.app.get( '/api/v1/sharelatex/docs/read_token/:token/exists', (req, res) => { res.json({ exists: false }) } ) this.app.get('/api/v2/templates/:templateId', (req, res) => { const template = this.templates[req.params.templateId] if (!template) { return res.sendStatus(404) } res.json(template) }) } } module.exports = MockV1Api // type hint for the inherited `instance` method /** * @function instance * @memberOf MockV1Api * @static * @returns {MockV1Api} */
overleaf/web/test/acceptance/src/mocks/MockV1Api.js/0
{ "file_path": "overleaf/web/test/acceptance/src/mocks/MockV1Api.js", "repo_id": "overleaf", "token_count": 4748 }
550
import { expect } from 'chai' import { screen, render, waitFor, cleanup } from '@testing-library/react' import sinon from 'sinon' import { contextProps } from './context-props' import FileTreeCreateNameInput from '../../../../../../frontend/js/features/file-tree/components/file-tree-create/file-tree-create-name-input' import FileTreeContext from '../../../../../../frontend/js/features/file-tree/components/file-tree-context' import FileTreeCreateNameProvider from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-create-name' describe('<FileTreeCreateNameInput/>', function () { const sandbox = sinon.createSandbox() beforeEach(function () { sandbox.spy(window, 'requestAnimationFrame') }) afterEach(function () { sandbox.restore() cleanup() }) it('renders an empty input', async function () { render( <FileTreeContext {...contextProps}> <FileTreeCreateNameProvider> <FileTreeCreateNameInput /> </FileTreeCreateNameProvider> </FileTreeContext> ) await screen.getByLabelText('File Name') await screen.getByPlaceholderText('File Name') }) it('renders a custom label and placeholder', async function () { render( <FileTreeContext {...contextProps}> <FileTreeCreateNameProvider> <FileTreeCreateNameInput label="File name in this project" placeholder="Enter a file name…" /> </FileTreeCreateNameProvider> </FileTreeContext> ) await screen.getByLabelText('File name in this project') await screen.getByPlaceholderText('Enter a file name…') }) it('uses an initial name', async function () { render( <FileTreeContext {...contextProps}> <FileTreeCreateNameProvider initialName="test.tex"> <FileTreeCreateNameInput /> </FileTreeCreateNameProvider> </FileTreeContext> ) const input = await screen.getByLabelText('File Name') expect(input.value).to.equal('test.tex') }) it('focuses the name', async function () { render( <FileTreeContext {...contextProps}> <FileTreeCreateNameProvider initialName="test.tex"> <FileTreeCreateNameInput focusName /> </FileTreeCreateNameProvider> </FileTreeContext> ) const input = await screen.getByLabelText('File Name') expect(input.value).to.equal('test.tex') await waitFor( () => expect(window.requestAnimationFrame).to.have.been.calledOnce ) // https://github.com/jsdom/jsdom/issues/2995 // "window.getSelection doesn't work with selection of <input> element" // const selection = window.getSelection().toString() // expect(selection).to.equal('test') // wait for the selection to update await new Promise(resolve => window.setTimeout(resolve, 100)) expect(input.selectionStart).to.equal(0) expect(input.selectionEnd).to.equal(4) }) })
overleaf/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-create-name-input.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-create-name-input.test.js", "repo_id": "overleaf", "token_count": 1049 }
551
import { screen, fireEvent, waitForElementToBeRemoved, } from '@testing-library/react' import { expect } from 'chai' import fetchMock from 'fetch-mock' import sinon from 'sinon' import { renderWithEditorContext } from '../../../helpers/render-with-context' import FileViewHeader from '../../../../../frontend/js/features/file-view/components/file-view-header.js' describe('<FileViewHeader/>', function () { const urlFile = { name: 'example.tex', linkedFileData: { url: 'https://overleaf.com', provider: 'url', }, created: new Date(2021, 1, 17, 3, 24).toISOString(), } const projectFile = { name: 'example.tex', linkedFileData: { v1_source_doc_id: 'v1-source-id', source_project_id: 'source-project-id', source_entity_path: '/source-entity-path.ext', provider: 'project_file', }, created: new Date(2021, 1, 17, 3, 24).toISOString(), } const projectOutputFile = { name: 'example.pdf', linkedFileData: { v1_source_doc_id: 'v1-source-id', source_output_file_path: '/source-entity-path.ext', provider: 'project_output_file', }, created: new Date(2021, 1, 17, 3, 24).toISOString(), } const thirdPartyReferenceFile = { name: 'example.tex', linkedFileData: { provider: 'zotero', }, created: new Date(2021, 1, 17, 3, 24).toISOString(), } beforeEach(function () { fetchMock.reset() }) describe('header text', function () { it('Renders the correct text for a file with the url provider', function () { renderWithEditorContext( <FileViewHeader file={urlFile} storeReferencesKeys={() => {}} /> ) screen.getByText('Imported from', { exact: false }) screen.getByText('at 3:24 am Wed, 17th Feb 21', { exact: false, }) }) it('Renders the correct text for a file with the project_file provider', function () { renderWithEditorContext( <FileViewHeader file={projectFile} storeReferencesKeys={() => {}} /> ) screen.getByText('Imported from', { exact: false }) screen.getByText('Another project', { exact: false }) screen.getByText('/source-entity-path.ext, at 3:24 am Wed, 17th Feb 21', { exact: false, }) }) it('Renders the correct text for a file with the project_output_file provider', function () { renderWithEditorContext( <FileViewHeader file={projectOutputFile} storeReferencesKeys={() => {}} /> ) screen.getByText('Imported from the output of', { exact: false }) screen.getByText('Another project', { exact: false }) screen.getByText('/source-entity-path.ext, at 3:24 am Wed, 17th Feb 21', { exact: false, }) }) }) describe('The refresh button', async function () { it('Changes text when the file is refreshing', async function () { fetchMock.post( 'express:/project/:project_id/linked_file/:file_id/refresh', { new_file_id: '5ff7418157b4e144321df5c4', } ) renderWithEditorContext( <FileViewHeader file={projectFile} storeReferencesKeys={() => {}} /> ) fireEvent.click(screen.getByRole('button', { name: 'Refresh' })) await waitForElementToBeRemoved(() => screen.getByText('Refreshing', { exact: false }) ) await screen.findByText('Refresh') }) it('Reindexes references after refreshing a file from a third-party provider', async function () { fetchMock.post( 'express:/project/:project_id/linked_file/:file_id/refresh', { new_file_id: '5ff7418157b4e144321df5c4', } ) const reindexResponse = { projectId: '123abc', keys: ['reference1', 'reference2', 'reference3', 'reference4'], } fetchMock.post( 'express:/project/:project_id/references/indexAll', reindexResponse ) const storeReferencesKeys = sinon.stub() renderWithEditorContext( <FileViewHeader file={thirdPartyReferenceFile} storeReferencesKeys={storeReferencesKeys} /> ) fireEvent.click(screen.getByRole('button', { name: 'Refresh' })) await waitForElementToBeRemoved(() => screen.getByText('Refreshing', { exact: false }) ) expect(fetchMock.done()).to.be.true expect(storeReferencesKeys).to.be.calledWith(reindexResponse.keys) }) }) describe('The download button', function () { it('exists', function () { renderWithEditorContext( <FileViewHeader file={urlFile} storeReferencesKeys={() => {}} /> ) screen.getByText('Download', { exact: false }) }) }) })
overleaf/web/test/frontend/features/file-view/components/file-view-header.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/file-view/components/file-view-header.test.js", "repo_id": "overleaf", "token_count": 1913 }
552
import sinon from 'sinon' import { screen, render, fireEvent } from '@testing-library/react' import PreviewRecompileButton from '../../../../../frontend/js/features/preview/components/preview-recompile-button' const { expect } = require('chai') describe('<PreviewRecompileButton />', function () { let onRecompile, onRecompileFromScratch, onStopCompilation beforeEach(function () { onRecompile = sinon.stub().resolves() onRecompileFromScratch = sinon.stub().resolves() onStopCompilation = sinon.stub().resolves() }) it('renders all items', function () { renderPreviewRecompileButton() const menuItems = screen.getAllByRole('menuitem') expect(menuItems.length).to.equal(9) expect(menuItems.map(item => item.textContent)).to.deep.equal([ 'On', 'Off', 'Normal', 'Fast [draft]', 'Check syntax before compile', "Don't check syntax", 'Run syntax check now', 'Stop compilation', 'Recompile from scratch', ]) const menuHeadingItems = screen.getAllByRole('heading') expect(menuHeadingItems.length).to.equal(3) expect(menuHeadingItems.map(item => item.textContent)).to.deep.equal([ 'Auto Compile', 'Compile Mode', 'Syntax Checks', ]) }) describe('Recompile from scratch', function () { describe('click', function () { it('should call onRecompileFromScratch', async function () { renderPreviewRecompileButton() const button = screen.getByRole('menuitem', { name: 'Recompile from scratch', }) await fireEvent.click(button) expect(onRecompileFromScratch).to.have.been.calledOnce }) }) describe('processing', function () { it('shows processing view and disable menuItem when recompiling', function () { renderPreviewRecompileButton({ isCompiling: true }) screen.getByRole('button', { name: 'Compiling…' }) expect( screen .getByRole('menuitem', { name: 'Recompile from scratch', }) .getAttribute('aria-disabled') ).to.equal('true') expect( screen .getByRole('menuitem', { name: 'Recompile from scratch', }) .closest('li') .getAttribute('class') ).to.equal('disabled') }) }) }) it('should show the button text when prop showText=true', function () { const showText = true renderPreviewRecompileButton({}, showText) expect(screen.getByText('Recompile').getAttribute('style')).to.be.null }) it('should not show the button text when prop showText=false', function () { const showText = false renderPreviewRecompileButton({}, showText) expect(screen.getByText('Recompile').getAttribute('style')).to.equal( 'position: absolute; right: -100vw;' ) }) describe('Autocompile feedback', function () { it('shows animated visual feedback via CSS class when there are uncompiled changes', function () { const { container } = renderPreviewRecompileButton({ autoCompileHasChanges: true, autoCompileHasLintingError: false, }) const recompileBtnGroupEl = container.querySelector( '.btn-recompile-group' ) expect( recompileBtnGroupEl.classList.contains( 'btn-recompile-group-has-changes' ) ).to.be.true }) it('does not show animated visual feedback via CSS class when there are no uncompiled changes', function () { const { container } = renderPreviewRecompileButton({ autoCompileHasChanges: false, autoCompileHasLintingError: false, }) const recompileBtnGroupEl = container.querySelector( '.btn-recompile-group' ) expect( recompileBtnGroupEl.classList.contains( 'btn-recompile-group-has-changes' ) ).to.be.false }) }) function renderPreviewRecompileButton(compilerState = {}, showText) { if (!compilerState.logEntries) { compilerState.logEntries = {} } if (showText === undefined) showText = true return render( <PreviewRecompileButton compilerState={{ autoCompileHasChanges: false, isAutoCompileOn: true, isClearingCache: false, isCompiling: false, isDraftModeOn: false, isSyntaxCheckOn: false, ...compilerState, }} onRecompile={onRecompile} onRunSyntaxCheckNow={() => {}} onSetAutoCompile={() => {}} onSetDraftMode={() => {}} onSetSyntaxCheck={() => {}} onRecompileFromScratch={onRecompileFromScratch} onStopCompilation={onStopCompilation} showText={showText} /> ) } })
overleaf/web/test/frontend/features/preview/components/preview-recompile-button.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/preview/components/preview-recompile-button.test.js", "repo_id": "overleaf", "token_count": 1964 }
553
/* eslint-disable max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { expect } from 'chai' import sinon from 'sinon' import EventEmitter from '../../../frontend/js/utils/EventEmitter' export default describe('EventEmitter', function () { beforeEach(function () { return (this.eventEmitter = new EventEmitter()) }) it('calls listeners', function () { const cb1 = sinon.stub() const cb2 = sinon.stub() this.eventEmitter.on('foo', cb1) this.eventEmitter.on('bar', cb2) this.eventEmitter.trigger('foo') expect(cb1).to.have.been.called return expect(cb2).to.not.have.been.called }) it('calls multiple listeners', function () { const cb1 = sinon.stub() const cb2 = sinon.stub() this.eventEmitter.on('foo', cb1) this.eventEmitter.on('foo', cb2) this.eventEmitter.trigger('foo') expect(cb1).to.have.been.called return expect(cb2).to.have.been.called }) it('calls listeners with namespace', function () { const cb1 = sinon.stub() const cb2 = sinon.stub() this.eventEmitter.on('foo', cb1) this.eventEmitter.on('foo.bar', cb2) this.eventEmitter.trigger('foo') expect(cb1).to.have.been.called return expect(cb2).to.have.been.called }) it('removes listeners', function () { const cb = sinon.stub() this.eventEmitter.on('foo', cb) this.eventEmitter.off('foo') this.eventEmitter.trigger('foo') return expect(cb).to.not.have.been.called }) it('removes namespaced listeners', function () { const cb = sinon.stub() this.eventEmitter.on('foo.bar', cb) this.eventEmitter.off('foo.bar') this.eventEmitter.trigger('foo') return expect(cb).to.not.have.been.called }) it('does not remove unnamespaced listeners if off called with namespace', function () { const cb1 = sinon.stub() const cb2 = sinon.stub() this.eventEmitter.on('foo', cb1) this.eventEmitter.on('foo.bar', cb2) this.eventEmitter.off('foo.bar') this.eventEmitter.trigger('foo') expect(cb1).to.have.been.called return expect(cb2).to.not.have.been.called }) })
overleaf/web/test/frontend/utils/EventEmitterTests.js/0
{ "file_path": "overleaf/web/test/frontend/utils/EventEmitterTests.js", "repo_id": "overleaf", "token_count": 927 }
554
const Path = require('path') const chai = require('chai') const sinon = require('sinon') /* * Chai configuration */ // add chai.should() chai.should() // Load sinon-chai assertions so expect(stubFn).to.have.been.calledWith('abc') // has a nicer failure messages chai.use(require('sinon-chai')) // Load promise support for chai chai.use(require('chai-as-promised')) // Do not truncate assertion errors chai.config.truncateThreshold = 0 // add support for mongoose in sinon require('sinon-mongoose') /* * Global stubs */ const globalStubsSandbox = sinon.createSandbox() const globalStubs = { logger: { debug: globalStubsSandbox.stub(), info: globalStubsSandbox.stub(), log: globalStubsSandbox.stub(), warn: globalStubsSandbox.stub(), err: globalStubsSandbox.stub(), error: globalStubsSandbox.stub(), fatal: globalStubsSandbox.stub(), }, } /* * Sandboxed module configuration */ const SandboxedModule = require('sandboxed-module') SandboxedModule.configure({ requires: getSandboxedModuleRequires(), globals: { Buffer, Promise, console, process }, }) function getSandboxedModuleRequires() { const requires = { 'logger-sharelatex': globalStubs.logger, } const internalModules = [ '../../app/src/util/promises', '../../app/src/Features/Errors/Errors', '../../app/src/Features/Helpers/Mongo', ] const externalLibs = [ 'async', 'json2csv', 'lodash', 'marked', 'moment', '@overleaf/o-error', 'sanitize-html', 'sshpk', 'underscore', 'xml2js', ] for (const modulePath of internalModules) { requires[Path.resolve(__dirname, modulePath)] = require(modulePath) } for (const lib of externalLibs) { requires[lib] = require(lib) } return requires } /* * Mocha hooks */ // sandboxed-module somehow registers every fake module it creates in this // module's children array, which uses quite a big amount of memory. We'll take // a copy of the module children array and restore it after each test so that // the garbage collector has a chance to reclaim the fake modules. let initialModuleChildren exports.mochaHooks = { beforeAll() { // Record initial module children initialModuleChildren = module.children.slice() }, beforeEach() { // Install logger stub this.logger = globalStubs.logger }, afterEach() { // Delete leaking sandboxed modules module.children = initialModuleChildren.slice() // Reset global stubs globalStubsSandbox.reset() // Restore other stubs sinon.restore() }, }
overleaf/web/test/unit/bootstrap.js/0
{ "file_path": "overleaf/web/test/unit/bootstrap.js", "repo_id": "overleaf", "token_count": 897 }
555
/* eslint-disable node/handle-callback-err, max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const sinon = require('sinon') const { expect } = require('chai') const modulePath = '../../../../app/src/Features/Collaborators/CollaboratorsInviteController.js' const SandboxedModule = require('sandboxed-module') const events = require('events') const MockRequest = require('../helpers/MockRequest') const MockResponse = require('../helpers/MockResponse') const { ObjectId } = require('mongodb') describe('CollaboratorsInviteController', function () { beforeEach(function () { this.user = { _id: 'id' } this.AnalyticsManger = { recordEvent: sinon.stub() } this.sendingUser = null this.AuthenticationController = { getSessionUser: req => { this.sendingUser = req.session.user return this.sendingUser }, } this.RateLimiter = { addCount: sinon.stub } this.LimitationsManager = {} this.UserGetter = { getUserByAnyEmail: sinon.stub(), getUser: sinon.stub(), } this.CollaboratorsInviteController = SandboxedModule.require(modulePath, { requires: { '../Project/ProjectGetter': (this.ProjectGetter = {}), '../Subscription/LimitationsManager': this.LimitationsManager, '../User/UserGetter': this.UserGetter, './CollaboratorsGetter': (this.CollaboratorsGetter = {}), './CollaboratorsInviteHandler': (this.CollaboratorsInviteHandler = {}), '../Editor/EditorRealTimeController': (this.EditorRealTimeController = { emitToRoom: sinon.stub(), }), '../Analytics/AnalyticsManager': this.AnalyticsManger, '../Authentication/AuthenticationController': this .AuthenticationController, '@overleaf/settings': (this.settings = {}), '../../infrastructure/RateLimiter': this.RateLimiter, }, }) this.res = new MockResponse() this.req = new MockRequest() this.project_id = 'project-id-123' return (this.callback = sinon.stub()) }) describe('getAllInvites', function () { beforeEach(function () { this.fakeInvites = [ { _id: ObjectId(), one: 1 }, { _id: ObjectId(), two: 2 }, ] this.req.params = { Project_id: this.project_id } this.res.json = sinon.stub() return (this.next = sinon.stub()) }) describe('when all goes well', function () { beforeEach(function () { this.CollaboratorsInviteHandler.getAllInvites = sinon .stub() .callsArgWith(1, null, this.fakeInvites) return this.CollaboratorsInviteController.getAllInvites( this.req, this.res, this.next ) }) it('should not produce an error', function () { return this.next.callCount.should.equal(0) }) it('should produce a list of invite objects', function () { this.res.json.callCount.should.equal(1) return this.res.json .calledWith({ invites: this.fakeInvites }) .should.equal(true) }) it('should have called CollaboratorsInviteHandler.getAllInvites', function () { this.CollaboratorsInviteHandler.getAllInvites.callCount.should.equal(1) return this.CollaboratorsInviteHandler.getAllInvites .calledWith(this.project_id) .should.equal(true) }) }) describe('when CollaboratorsInviteHandler.getAllInvites produces an error', function () { beforeEach(function () { this.CollaboratorsInviteHandler.getAllInvites = sinon .stub() .callsArgWith(1, new Error('woops')) return this.CollaboratorsInviteController.getAllInvites( this.req, this.res, this.next ) }) it('should produce an error', function () { this.next.callCount.should.equal(1) return this.next.firstCall.args[0].should.be.instanceof(Error) }) }) }) describe('inviteToProject', function () { beforeEach(function () { this.targetEmail = 'user@example.com' this.req.params = { Project_id: this.project_id } this.current_user = { _id: (this.current_user_id = 'current-user-id') } this.req.session = { user: this.current_user } this.req.body = { email: this.targetEmail, privileges: (this.privileges = 'readAndWrite'), } this.res.json = sinon.stub() this.res.sendStatus = sinon.stub() this.invite = { _id: ObjectId(), token: 'htnseuthaouse', sendingUserId: this.current_user_id, projectId: this.targetEmail, targetEmail: 'user@example.com', createdAt: new Date(), } this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, true) this.CollaboratorsInviteHandler.inviteToProject = sinon .stub() .callsArgWith(4, null, this.invite) this.callback = sinon.stub() return (this.next = sinon.stub()) }) describe('when all goes well', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, true) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, true) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should produce json response', function () { this.res.json.callCount.should.equal(1) return { invite: this.invite }.should.deep.equal( this.res.json.firstCall.args[0] ) }) it('should have called canAddXCollaborators', function () { this.LimitationsManager.canAddXCollaborators.callCount.should.equal(1) return this.LimitationsManager.canAddXCollaborators .calledWith(this.project_id) .should.equal(true) }) it('should have called _checkShouldInviteEmail', function () { this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 1 ) return this.CollaboratorsInviteController._checkShouldInviteEmail .calledWith(this.targetEmail) .should.equal(true) }) it('should have called inviteToProject', function () { this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 1 ) return this.CollaboratorsInviteHandler.inviteToProject .calledWith( this.project_id, this.current_user, this.targetEmail, this.privileges ) .should.equal(true) }) it('should have called emitToRoom', function () { this.EditorRealTimeController.emitToRoom.callCount.should.equal(1) return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:membership:changed') .should.equal(true) }) }) describe('when the user is not allowed to add more collaborators', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, true) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, false) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should produce json response without an invite', function () { this.res.json.callCount.should.equal(1) return { invite: null }.should.deep.equal( this.res.json.firstCall.args[0] ) }) it('should not have called _checkShouldInviteEmail', function () { this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 0 ) return this.CollaboratorsInviteController._checkShouldInviteEmail .calledWith(this.sendingUser, this.targetEmail) .should.equal(false) }) it('should not have called inviteToProject', function () { return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 0 ) }) }) describe('when canAddXCollaborators produces an error', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, true) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, new Error('woops')) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should call next with an error', function () { this.next.callCount.should.equal(1) return this.next .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) it('should not have called _checkShouldInviteEmail', function () { this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 0 ) return this.CollaboratorsInviteController._checkShouldInviteEmail .calledWith(this.sendingUser, this.targetEmail) .should.equal(false) }) it('should not have called inviteToProject', function () { return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 0 ) }) }) describe('when inviteToProject produces an error', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, true) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.CollaboratorsInviteHandler.inviteToProject = sinon .stub() .callsArgWith(4, new Error('woops')) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should call next with an error', function () { this.next.callCount.should.equal(1) expect(this.next).to.have.been.calledWith(sinon.match.instanceOf(Error)) }) it('should have called canAddXCollaborators', function () { this.LimitationsManager.canAddXCollaborators.callCount.should.equal(1) return this.LimitationsManager.canAddXCollaborators .calledWith(this.project_id) .should.equal(true) }) it('should have called _checkShouldInviteEmail', function () { this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 1 ) return this.CollaboratorsInviteController._checkShouldInviteEmail .calledWith(this.targetEmail) .should.equal(true) }) it('should have called inviteToProject', function () { this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 1 ) return this.CollaboratorsInviteHandler.inviteToProject .calledWith( this.project_id, this.current_user, this.targetEmail, this.privileges ) .should.equal(true) }) }) describe('when _checkShouldInviteEmail disallows the invite', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, false) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, true) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should produce json response with no invite, and an error property', function () { this.res.json.callCount.should.equal(1) return { invite: null, error: 'cannot_invite_non_user', }.should.deep.equal(this.res.json.firstCall.args[0]) }) it('should have called _checkShouldInviteEmail', function () { this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 1 ) return this.CollaboratorsInviteController._checkShouldInviteEmail .calledWith(this.targetEmail) .should.equal(true) }) it('should not have called inviteToProject', function () { return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 0 ) }) }) describe('when _checkShouldInviteEmail produces an error', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, new Error('woops')) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, true) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should call next with an error', function () { this.next.callCount.should.equal(1) return this.next .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) it('should have called _checkShouldInviteEmail', function () { this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 1 ) return this.CollaboratorsInviteController._checkShouldInviteEmail .calledWith(this.targetEmail) .should.equal(true) }) it('should not have called inviteToProject', function () { return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 0 ) }) }) describe('when the user invites themselves to the project', function () { beforeEach(function () { this.req.session.user = { _id: 'abc', email: 'me@example.com' } this.req.body.email = 'me@example.com' this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, true) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, true) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should reject action, return json response with error code', function () { this.res.json.callCount.should.equal(1) return { invite: null, error: 'cannot_invite_self' }.should.deep.equal( this.res.json.firstCall.args[0] ) }) it('should not have called canAddXCollaborators', function () { return this.LimitationsManager.canAddXCollaborators.callCount.should.equal( 0 ) }) it('should not have called _checkShouldInviteEmail', function () { return this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal( 0 ) }) it('should not have called inviteToProject', function () { return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal( 0 ) }) it('should not have called emitToRoom', function () { return this.EditorRealTimeController.emitToRoom.callCount.should.equal( 0 ) }) }) describe('when _checkRateLimit returns false', function () { beforeEach(function () { this.CollaboratorsInviteController._checkShouldInviteEmail = sinon .stub() .callsArgWith(1, null, true) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, false) this.LimitationsManager.canAddXCollaborators = sinon .stub() .callsArgWith(2, null, true) return this.CollaboratorsInviteController.inviteToProject( this.req, this.res, this.next ) }) it('should send a 429 response', function () { return this.res.sendStatus.calledWith(429).should.equal(true) }) it('should not call inviteToProject', function () { return this.CollaboratorsInviteHandler.inviteToProject.called.should.equal( false ) }) it('should not call emitToRoom', function () { return this.EditorRealTimeController.emitToRoom.called.should.equal( false ) }) }) }) describe('viewInvite', function () { beforeEach(function () { this.token = 'some-opaque-token' this.req.params = { Project_id: this.project_id, token: this.token, } this.req.session = { user: { _id: (this.current_user_id = 'current-user-id') }, } this.res.render = sinon.stub() this.res.redirect = sinon.stub() this.res.sendStatus = sinon.stub() this.invite = { _id: ObjectId(), token: this.token, sendingUserId: ObjectId(), projectId: this.project_id, targetEmail: 'user@example.com', createdAt: new Date(), } this.fakeProject = { _id: this.project_id, name: 'some project', owner_ref: this.invite.sendingUserId, collaberator_refs: [], readOnly_refs: [], } this.owner = { _id: this.fakeProject.owner_ref, first_name: 'John', last_name: 'Doe', email: 'john@example.com', } this.CollaboratorsGetter.isUserInvitedMemberOfProject = sinon .stub() .callsArgWith(2, null, false) this.CollaboratorsInviteHandler.getInviteByToken = sinon .stub() .callsArgWith(2, null, this.invite) this.ProjectGetter.getProject = sinon .stub() .callsArgWith(2, null, this.fakeProject) this.UserGetter.getUser.callsArgWith(2, null, this.owner) this.callback = sinon.stub() return (this.next = sinon.stub()) }) describe('when the token is valid', function () { beforeEach(function () { return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should render the view template', function () { this.res.render.callCount.should.equal(1) return this.res.render .calledWith('project/invite/show') .should.equal(true) }) it('should not call next', function () { return this.next.callCount.should.equal(0) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) return this.CollaboratorsInviteHandler.getInviteByToken .calledWith(this.fakeProject._id, this.invite.token) .should.equal(true) }) it('should call User.getUser', function () { this.UserGetter.getUser.callCount.should.equal(1) return this.UserGetter.getUser .calledWith({ _id: this.fakeProject.owner_ref }) .should.equal(true) }) it('should call ProjectGetter.getProject', function () { this.ProjectGetter.getProject.callCount.should.equal(1) return this.ProjectGetter.getProject .calledWith(this.project_id) .should.equal(true) }) }) describe('when user is already a member of the project', function () { beforeEach(function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject = sinon .stub() .callsArgWith(2, null, true) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should redirect to the project page', function () { this.res.redirect.callCount.should.equal(1) return this.res.redirect .calledWith(`/project/${this.project_id}`) .should.equal(true) }) it('should not call next with an error', function () { return this.next.callCount.should.equal(0) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should not call getInviteByToken', function () { return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 0 ) }) it('should not call User.getUser', function () { return this.UserGetter.getUser.callCount.should.equal(0) }) it('should not call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(0) }) }) describe('when isUserInvitedMemberOfProject produces an error', function () { beforeEach(function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject = sinon .stub() .callsArgWith(2, new Error('woops')) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should call next with an error', function () { this.next.callCount.should.equal(1) return expect(this.next.firstCall.args[0]).to.be.instanceof(Error) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should not call getInviteByToken', function () { return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 0 ) }) it('should not call User.getUser', function () { return this.UserGetter.getUser.callCount.should.equal(0) }) it('should not call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(0) }) }) describe('when the getInviteByToken produces an error', function () { beforeEach(function () { this.CollaboratorsInviteHandler.getInviteByToken.callsArgWith( 2, new Error('woops') ) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should call next with the error', function () { this.next.callCount.should.equal(1) return this.next .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should not call User.getUser', function () { return this.UserGetter.getUser.callCount.should.equal(0) }) it('should not call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(0) }) }) describe('when the getInviteByToken does not produce an invite', function () { beforeEach(function () { this.CollaboratorsInviteHandler.getInviteByToken.callsArgWith( 2, null, null ) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should render the not-valid view template', function () { this.res.render.callCount.should.equal(1) return this.res.render .calledWith('project/invite/not-valid') .should.equal(true) }) it('should not call next', function () { return this.next.callCount.should.equal(0) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should not call User.getUser', function () { return this.UserGetter.getUser.callCount.should.equal(0) }) it('should not call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(0) }) }) describe('when User.getUser produces an error', function () { beforeEach(function () { this.UserGetter.getUser.callsArgWith(2, new Error('woops')) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should produce an error', function () { this.next.callCount.should.equal(1) return expect(this.next.firstCall.args[0]).to.be.instanceof(Error) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) }) it('should call User.getUser', function () { this.UserGetter.getUser.callCount.should.equal(1) return this.UserGetter.getUser .calledWith({ _id: this.fakeProject.owner_ref }) .should.equal(true) }) it('should not call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(0) }) }) describe('when User.getUser does not find a user', function () { beforeEach(function () { this.UserGetter.getUser.callsArgWith(2, null, null) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should render the not-valid view template', function () { this.res.render.callCount.should.equal(1) return this.res.render .calledWith('project/invite/not-valid') .should.equal(true) }) it('should not call next', function () { return this.next.callCount.should.equal(0) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) }) it('should call User.getUser', function () { this.UserGetter.getUser.callCount.should.equal(1) return this.UserGetter.getUser .calledWith({ _id: this.fakeProject.owner_ref }) .should.equal(true) }) it('should not call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(0) }) }) describe('when getProject produces an error', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, new Error('woops')) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should produce an error', function () { this.next.callCount.should.equal(1) return expect(this.next.firstCall.args[0]).to.be.instanceof(Error) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) }) it('should call User.getUser', function () { this.UserGetter.getUser.callCount.should.equal(1) return this.UserGetter.getUser .calledWith({ _id: this.fakeProject.owner_ref }) .should.equal(true) }) it('should call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(1) }) }) describe('when Project.getUser does not find a user', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, null) return this.CollaboratorsInviteController.viewInvite( this.req, this.res, this.next ) }) it('should render the not-valid view template', function () { this.res.render.callCount.should.equal(1) return this.res.render .calledWith('project/invite/not-valid') .should.equal(true) }) it('should not call next', function () { return this.next.callCount.should.equal(0) }) it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () { this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal( 1 ) return this.CollaboratorsGetter.isUserInvitedMemberOfProject .calledWith(this.current_user_id, this.project_id) .should.equal(true) }) it('should call getInviteByToken', function () { return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal( 1 ) }) it('should call getUser', function () { this.UserGetter.getUser.callCount.should.equal(1) return this.UserGetter.getUser .calledWith({ _id: this.fakeProject.owner_ref }) .should.equal(true) }) it('should call ProjectGetter.getProject', function () { return this.ProjectGetter.getProject.callCount.should.equal(1) }) }) }) describe('resendInvite', function () { beforeEach(function () { this.req.params = { Project_id: this.project_id, invite_id: (this.invite_id = 'thuseoautoh'), } this.req.session = { user: { _id: (this.current_user_id = 'current-user-id') }, } this.res.render = sinon.stub() this.res.sendStatus = sinon.stub() this.CollaboratorsInviteHandler.resendInvite = sinon .stub() .callsArgWith(3, null) this.CollaboratorsInviteController._checkRateLimit = sinon .stub() .yields(null, true) this.callback = sinon.stub() return (this.next = sinon.stub()) }) describe('when resendInvite does not produce an error', function () { beforeEach(function () { return this.CollaboratorsInviteController.resendInvite( this.req, this.res, this.next ) }) it('should produce a 201 response', function () { this.res.sendStatus.callCount.should.equal(1) return this.res.sendStatus.calledWith(201).should.equal(true) }) it('should have called resendInvite', function () { return this.CollaboratorsInviteHandler.resendInvite.callCount.should.equal( 1 ) }) it('should check the rate limit', function () { return this.CollaboratorsInviteController._checkRateLimit.callCount.should.equal( 1 ) }) }) describe('when resendInvite produces an error', function () { beforeEach(function () { this.CollaboratorsInviteHandler.resendInvite = sinon .stub() .callsArgWith(3, new Error('woops')) return this.CollaboratorsInviteController.resendInvite( this.req, this.res, this.next ) }) it('should not produce a 201 response', function () { return this.res.sendStatus.callCount.should.equal(0) }) it('should call next with the error', function () { this.next.callCount.should.equal(1) return this.next .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) it('should have called resendInvite', function () { return this.CollaboratorsInviteHandler.resendInvite.callCount.should.equal( 1 ) }) }) }) describe('revokeInvite', function () { beforeEach(function () { this.req.params = { Project_id: this.project_id, invite_id: (this.invite_id = 'thuseoautoh'), } this.current_user = { _id: (this.current_user_id = 'current-user-id') } this.req.session = { user: this.current_user } this.res.render = sinon.stub() this.res.sendStatus = sinon.stub() this.CollaboratorsInviteHandler.revokeInvite = sinon .stub() .callsArgWith(2, null) this.callback = sinon.stub() return (this.next = sinon.stub()) }) describe('when revokeInvite does not produce an error', function () { beforeEach(function () { return this.CollaboratorsInviteController.revokeInvite( this.req, this.res, this.next ) }) it('should produce a 201 response', function () { this.res.sendStatus.callCount.should.equal(1) return this.res.sendStatus.calledWith(201).should.equal(true) }) it('should have called revokeInvite', function () { return this.CollaboratorsInviteHandler.revokeInvite.callCount.should.equal( 1 ) }) it('should have called emitToRoom', function () { this.EditorRealTimeController.emitToRoom.callCount.should.equal(1) return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:membership:changed') .should.equal(true) }) }) describe('when revokeInvite produces an error', function () { beforeEach(function () { this.CollaboratorsInviteHandler.revokeInvite = sinon .stub() .callsArgWith(2, new Error('woops')) return this.CollaboratorsInviteController.revokeInvite( this.req, this.res, this.next ) }) it('should not produce a 201 response', function () { return this.res.sendStatus.callCount.should.equal(0) }) it('should call next with the error', function () { this.next.callCount.should.equal(1) return this.next .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) it('should have called revokeInvite', function () { return this.CollaboratorsInviteHandler.revokeInvite.callCount.should.equal( 1 ) }) }) }) describe('acceptInvite', function () { beforeEach(function () { this.req.params = { Project_id: this.project_id, token: (this.token = 'mock-token'), } this.req.session = { user: { _id: (this.current_user_id = 'current-user-id') }, } this.res.render = sinon.stub() this.res.redirect = sinon.stub() this.CollaboratorsInviteHandler.acceptInvite = sinon .stub() .callsArgWith(3, null) this.callback = sinon.stub() return (this.next = sinon.stub()) }) describe('when acceptInvite does not produce an error', function () { beforeEach(function () { return this.CollaboratorsInviteController.acceptInvite( this.req, this.res, this.next ) }) it('should redirect to project page', function () { this.res.redirect.callCount.should.equal(1) return this.res.redirect .calledWith(`/project/${this.project_id}`) .should.equal(true) }) it('should have called acceptInvite', function () { return this.CollaboratorsInviteHandler.acceptInvite .calledWith(this.project_id, this.token) .should.equal(true) }) it('should have called emitToRoom', function () { this.EditorRealTimeController.emitToRoom.callCount.should.equal(1) return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:membership:changed') .should.equal(true) }) }) describe('when revokeInvite produces an error', function () { beforeEach(function () { this.CollaboratorsInviteHandler.acceptInvite = sinon .stub() .callsArgWith(3, new Error('woops')) return this.CollaboratorsInviteController.acceptInvite( this.req, this.res, this.next ) }) it('should not redirect to project page', function () { return this.res.redirect.callCount.should.equal(0) }) it('should call next with the error', function () { this.next.callCount.should.equal(1) return this.next .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) it('should have called acceptInvite', function () { return this.CollaboratorsInviteHandler.acceptInvite.callCount.should.equal( 1 ) }) }) }) describe('_checkShouldInviteEmail', function () { beforeEach(function () { return (this.email = 'user@example.com') }) describe('when we should be restricting to existing accounts', function () { beforeEach(function () { this.settings.restrictInvitesToExistingAccounts = true return (this.call = callback => { return this.CollaboratorsInviteController._checkShouldInviteEmail( this.email, callback ) }) }) describe('when user account is present', function () { beforeEach(function () { this.user = { _id: ObjectId().toString() } return (this.UserGetter.getUserByAnyEmail = sinon .stub() .callsArgWith(2, null, this.user)) }) it('should callback with `true`', function (done) { return this.call((err, shouldAllow) => { expect(err).to.equal(null) expect(shouldAllow).to.equal(true) return done() }) }) }) describe('when user account is absent', function () { beforeEach(function () { this.user = null return (this.UserGetter.getUserByAnyEmail = sinon .stub() .callsArgWith(2, null, this.user)) }) it('should callback with `false`', function (done) { return this.call((err, shouldAllow) => { expect(err).to.equal(null) expect(shouldAllow).to.equal(false) return done() }) }) it('should have called getUser', function (done) { return this.call((err, shouldAllow) => { this.UserGetter.getUserByAnyEmail.callCount.should.equal(1) this.UserGetter.getUserByAnyEmail .calledWith(this.email, { _id: 1 }) .should.equal(true) return done() }) }) }) describe('when getUser produces an error', function () { beforeEach(function () { this.user = null return (this.UserGetter.getUserByAnyEmail = sinon .stub() .callsArgWith(2, new Error('woops'))) }) it('should callback with an error', function (done) { return this.call((err, shouldAllow) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(shouldAllow).to.equal(undefined) return done() }) }) }) }) }) describe('_checkRateLimit', function () { beforeEach(function () { this.settings.restrictInvitesToExistingAccounts = false this.sendingUserId = '32312313' this.LimitationsManager.allowedNumberOfCollaboratorsForUser = sinon.stub() return this.LimitationsManager.allowedNumberOfCollaboratorsForUser .withArgs(this.sendingUserId) .yields(null, 17) }) it('should callback with `true` when rate limit under', function (done) { this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) return this.CollaboratorsInviteController._checkRateLimit( this.sendingUserId, (err, result) => { this.RateLimiter.addCount.called.should.equal(true) result.should.equal(true) return done() } ) }) it('should callback with `false` when rate limit hit', function (done) { this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, false) return this.CollaboratorsInviteController._checkRateLimit( this.sendingUserId, (err, result) => { this.RateLimiter.addCount.called.should.equal(true) result.should.equal(false) return done() } ) }) it('should call rate limiter with 10x the collaborators', function (done) { this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) return this.CollaboratorsInviteController._checkRateLimit( this.sendingUserId, (err, result) => { this.RateLimiter.addCount.args[0][0].throttle.should.equal(170) return done() } ) }) it('should call rate limiter with 200 when collaborators is -1', function (done) { this.LimitationsManager.allowedNumberOfCollaboratorsForUser .withArgs(this.sendingUserId) .yields(null, -1) this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) return this.CollaboratorsInviteController._checkRateLimit( this.sendingUserId, (err, result) => { this.RateLimiter.addCount.args[0][0].throttle.should.equal(200) return done() } ) }) it('should call rate limiter with 10 when user has no collaborators set', function (done) { this.LimitationsManager.allowedNumberOfCollaboratorsForUser .withArgs(this.sendingUserId) .yields(null) this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) return this.CollaboratorsInviteController._checkRateLimit( this.sendingUserId, (err, result) => { this.RateLimiter.addCount.args[0][0].throttle.should.equal(10) return done() } ) }) }) })
overleaf/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js", "repo_id": "overleaf", "token_count": 20096 }
556
/* eslint-disable max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const sinon = require('sinon') const { expect } = require('chai') const modulePath = '../../../../app/src/Features/Documents/DocumentHelper.js' const SandboxedModule = require('sandboxed-module') describe('DocumentHelper', function () { beforeEach(function () { return (this.DocumentHelper = SandboxedModule.require(modulePath)) }) describe('getTitleFromTexContent', function () { it('should return the title', function () { const document = '\\begin{document}\n\\title{foo}\n\\end{document}' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('foo') }) it('should return the title if surrounded by space', function () { const document = '\\begin{document}\n \\title{foo} \n\\end{document}' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('foo') }) it('should return null if there is no title', function () { const document = '\\begin{document}\n\\end{document}' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.eql(null) }) it('should accept an array', function () { const document = ['\\begin{document}', '\\title{foo}', '\\end{document}'] return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('foo') }) it('should parse out formatting elements from the title', function () { const document = '\\title{\\textbf{\\large{Second Year LaTeX Exercise}}}' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('Second Year LaTeX Exercise') }) it('should ignore junk after the title', function () { const document = '\\title{wombat} potato' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('wombat') }) it('should ignore junk before the title', function () { const document = '% this is something that v1 relied on, even though it seems odd \\title{wombat}' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('wombat') }) // NICETOHAVE: Current implementation doesn't do this // it "should keep content that surrounds formatting elements", -> // document = "\\title{Second Year \\large{LaTeX} Exercise}" // expect(@DocumentHelper.getTitleFromTexContent(document)).to.equal "Second Year LaTeX Exercise" it('should collapse whitespace', function () { const document = '\\title{Second Year LaTeX Exercise}' return expect( this.DocumentHelper.getTitleFromTexContent(document) ).to.equal('Second Year LaTeX Exercise') }) }) describe('detex', function () { // note, there are a number of tests for getTitleFromTexContent that also test cases here it('leaves a non-TeX string unchanged', function () { expect(this.DocumentHelper.detex('')).to.equal('') expect(this.DocumentHelper.detex('a')).to.equal('a') return expect(this.DocumentHelper.detex('a a')).to.equal('a a') }) it('collapses spaces', function () { expect(this.DocumentHelper.detex('a a')).to.equal('a a') return expect(this.DocumentHelper.detex('a \n a')).to.equal('a \n a') }) it('replaces named commands', function () { expect(this.DocumentHelper.detex('\\LaTeX')).to.equal('LaTeX') expect(this.DocumentHelper.detex('\\TikZ')).to.equal('TikZ') expect(this.DocumentHelper.detex('\\TeX')).to.equal('TeX') return expect(this.DocumentHelper.detex('\\BibTeX')).to.equal('BibTeX') }) it('removes general commands', function () { expect(this.DocumentHelper.detex('\\foo')).to.equal('') expect(this.DocumentHelper.detex('\\foo{}')).to.equal('') expect(this.DocumentHelper.detex('\\foo~Test')).to.equal('Test') expect(this.DocumentHelper.detex('\\"e')).to.equal('e') return expect(this.DocumentHelper.detex('\\textit{e}')).to.equal('e') }) it('leaves basic math', function () { return expect(this.DocumentHelper.detex('$\\cal{O}(n^2)$')).to.equal( 'O(n^2)' ) }) it('removes line spacing commands', function () { return expect(this.DocumentHelper.detex('a \\\\[1.50cm] b')).to.equal( 'a b' ) }) }) describe('contentHasDocumentclass', function () { it('should return true if the content has a documentclass', function () { const document = ['% line', '% line', '% line', '\\documentclass'] return expect( this.DocumentHelper.contentHasDocumentclass(document) ).to.equal(true) }) it('should allow whitespace before the documentclass', function () { const document = ['% line', '% line', '% line', ' \\documentclass'] return expect( this.DocumentHelper.contentHasDocumentclass(document) ).to.equal(true) }) it('should not allow non-whitespace before the documentclass', function () { const document = [ '% line', '% line', '% line', ' asdf \\documentclass', ] return expect( this.DocumentHelper.contentHasDocumentclass(document) ).to.equal(false) }) it('should return false when there is no documentclass', function () { const document = ['% line', '% line', '% line'] return expect( this.DocumentHelper.contentHasDocumentclass(document) ).to.equal(false) }) }) })
overleaf/web/test/unit/src/Documents/DocumentHelperTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Documents/DocumentHelperTests.js", "repo_id": "overleaf", "token_count": 2168 }
557
const SandboxedModule = require('sandboxed-module') const { expect } = require('chai') const modulePath = '../../../../app/src/Features/Helpers/AuthorizationHelper' describe('AuthorizationHelper', function () { beforeEach(function () { this.AuthorizationHelper = SandboxedModule.require(modulePath, { requires: { '../../models/User': { UserSchema: { obj: { staffAccess: { publisherMetrics: {}, publisherManagement: {}, institutionMetrics: {}, institutionManagement: {}, groupMetrics: {}, groupManagement: {}, adminMetrics: {}, }, }, }, }, }, }) }) describe('hasAnyStaffAccess', function () { it('with empty user', function () { const user = {} expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.false }) it('with no access user', function () { const user = { isAdmin: false, staffAccess: { adminMetrics: false } } expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.false }) it('with admin user', function () { const user = { isAdmin: true } expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.true }) it('with staff user', function () { const user = { staffAccess: { adminMetrics: true, somethingElse: false } } expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.true }) it('with non-staff user with extra attributes', function () { // make sure that staffAccess attributes not declared on the model don't // give user access const user = { staffAccess: { adminMetrics: false, somethingElse: true } } expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.false }) }) })
overleaf/web/test/unit/src/HelperFiles/AuthorizationHelperTests.js/0
{ "file_path": "overleaf/web/test/unit/src/HelperFiles/AuthorizationHelperTests.js", "repo_id": "overleaf", "token_count": 753 }
558
/* eslint-disable node/handle-callback-err, max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const { expect } = require('chai') const sinon = require('sinon') const modulePath = '../../../../app/src/Features/Metadata/MetaHandler' const SandboxedModule = require('sandboxed-module') describe('MetaHandler', function () { beforeEach(function () { this.projectId = 'someprojectid' this.docId = 'somedocid' this.ProjectEntityHandler = { getAllDocs: sinon.stub(), getDoc: sinon.stub(), } this.DocumentUpdaterHandler = { flushDocToMongo: sinon.stub(), } this.packageMapping = { foo: [ { caption: '\\bar', snippet: '\\bar', meta: 'foo-cmd', score: 12, }, { caption: '\\bat[]{}', snippet: '\\bar[$1]{$2}', meta: 'foo-cmd', score: 10, }, ], baz: [ { caption: '\\longercommandtest{}', snippet: '\\longercommandtest{$1}', meta: 'baz-cmd', score: 50, }, ], } return (this.MetaHandler = SandboxedModule.require(modulePath, { requires: { '../Project/ProjectEntityHandler': this.ProjectEntityHandler, '../DocumentUpdater/DocumentUpdaterHandler': this .DocumentUpdaterHandler, './packageMapping': this.packageMapping, }, })) }) describe('extractMetaFromDoc', function () { beforeEach(function () { return (this.lines = [ '\\usepackage{foo}', '\\usepackage{amsmath, booktabs}', 'one', 'two', 'three \\label{aaa}', 'four five', '\\label{bbb}', 'six seven', ]) }) it('should extract all the labels and packages', function () { const docMeta = this.MetaHandler.extractMetaFromDoc(this.lines) return expect(docMeta).to.deep.equal({ labels: ['aaa', 'bbb'], packages: { foo: [ { caption: '\\bar', snippet: '\\bar', meta: 'foo-cmd', score: 12, }, { caption: '\\bat[]{}', snippet: '\\bar[$1]{$2}', meta: 'foo-cmd', score: 10, }, ], }, }) }) }) describe('extractMetaFromProjectDocs', function () { beforeEach(function () { return (this.docs = { doc_one: { _id: 'id_one', lines: ['one', '\\label{aaa} two', 'three'], }, doc_two: { _id: 'id_two', lines: ['four'], }, doc_three: { _id: 'id_three', lines: ['\\label{bbb}', 'five six', 'seven eight \\label{ccc} nine'], }, doc_four: { _id: 'id_four', lines: [ '\\usepackage[width=\\textwidth]{baz}', '\\usepackage{amsmath}', ], }, doc_five: { _id: 'id_five', lines: [ '\\usepackage{foo,baz}', '\\usepackage[options=foo]{hello}', 'some text', '\\section{this}\\label{sec:intro}', 'In Section \\ref{sec:intro} we saw', 'nothing', ], }, }) }) it('should extract all metadata', function () { const projectMeta = this.MetaHandler.extractMetaFromProjectDocs(this.docs) return expect(projectMeta).to.deep.equal({ id_one: { labels: ['aaa'], packages: {} }, id_two: { labels: [], packages: {} }, id_three: { labels: ['bbb', 'ccc'], packages: {} }, id_four: { labels: [], packages: { baz: [ { caption: '\\longercommandtest{}', snippet: '\\longercommandtest{$1}', meta: 'baz-cmd', score: 50, }, ], }, }, id_five: { labels: ['sec:intro'], packages: { foo: [ { caption: '\\bar', snippet: '\\bar', meta: 'foo-cmd', score: 12, }, { caption: '\\bat[]{}', snippet: '\\bar[$1]{$2}', meta: 'foo-cmd', score: 10, }, ], baz: [ { caption: '\\longercommandtest{}', snippet: '\\longercommandtest{$1}', meta: 'baz-cmd', score: 50, }, ], }, }, }) }) }) describe('getMetaForDoc', function () { beforeEach(function () { this.fakeLines = ['\\usepackage{abc}', 'one', '\\label{aaa}', 'two'] this.fakeMeta = { labels: ['aaa'], packages: ['abc'] } this.DocumentUpdaterHandler.flushDocToMongo = sinon .stub() .callsArgWith(2, null) this.ProjectEntityHandler.getDoc = sinon .stub() .callsArgWith(2, null, this.fakeLines) this.MetaHandler.extractMetaFromDoc = sinon.stub().returns(this.fakeMeta) return (this.call = callback => { return this.MetaHandler.getMetaForDoc( this.projectId, this.docId, callback ) }) }) it('should not produce an error', function (done) { return this.call((err, docMeta) => { expect(err).to.equal(null) return done() }) }) it('should produce docMeta', function (done) { return this.call((err, docMeta) => { expect(docMeta).to.equal(this.fakeMeta) return done() }) }) it('should call flushDocToMongo', function (done) { return this.call((err, docMeta) => { this.DocumentUpdaterHandler.flushDocToMongo.callCount.should.equal(1) this.DocumentUpdaterHandler.flushDocToMongo .calledWith(this.projectId, this.docId) .should.equal(true) return done() }) }) it('should call getDoc', function (done) { return this.call((err, docMeta) => { this.ProjectEntityHandler.getDoc.callCount.should.equal(1) this.ProjectEntityHandler.getDoc .calledWith(this.projectId, this.docId) .should.equal(true) return done() }) }) it('should call extractMetaFromDoc', function (done) { return this.call((err, docMeta) => { this.MetaHandler.extractMetaFromDoc.callCount.should.equal(1) this.MetaHandler.extractMetaFromDoc .calledWith(this.fakeLines) .should.equal(true) return done() }) }) }) describe('getAllMetaForProject', function () { beforeEach(function () { this.fakeDocs = { doc_one: { lines: ['\\usepackage[some-options,more=foo]{foo}', '\\label{aaa}'], }, } this.fakeMeta = { labels: ['aaa'], packages: { foo: [ { caption: '\\bar', snippet: '\\bar', meta: 'foo-cmd', score: 12, }, { caption: '\\bat[]{}', snippet: '\\bar[$1]{$2}', meta: 'foo-cmd', score: 10, }, ], }, } this.DocumentUpdaterHandler.flushProjectToMongo = sinon .stub() .callsArgWith(1, null) this.ProjectEntityHandler.getAllDocs = sinon .stub() .callsArgWith(1, null, this.fakeDocs) this.MetaHandler.extractMetaFromProjectDocs = sinon .stub() .returns(this.fakeMeta) return (this.call = callback => { return this.MetaHandler.getAllMetaForProject(this.projectId, callback) }) }) it('should not produce an error', function (done) { return this.call((err, projectMeta) => { expect(err).to.equal(null) return done() }) }) it('should produce projectMeta', function (done) { return this.call((err, projectMeta) => { expect(projectMeta).to.equal(this.fakeMeta) return done() }) }) it('should call getAllDocs', function (done) { return this.call((err, projectMeta) => { this.ProjectEntityHandler.getAllDocs.callCount.should.equal(1) this.ProjectEntityHandler.getAllDocs .calledWith(this.projectId) .should.equal(true) return done() }) }) it('should call extractMetaFromDoc', function (done) { return this.call((err, docMeta) => { this.MetaHandler.extractMetaFromProjectDocs.callCount.should.equal(1) this.MetaHandler.extractMetaFromProjectDocs .calledWith(this.fakeDocs) .should.equal(true) return done() }) }) }) })
overleaf/web/test/unit/src/Metadata/MetaHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Metadata/MetaHandlerTests.js", "repo_id": "overleaf", "token_count": 4660 }
559
/* eslint-disable max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const { expect } = require('chai') const modulePath = '../../../../app/src/Features/Project/ProjectEditorHandler' const SandboxedModule = require('sandboxed-module') describe('ProjectEditorHandler', function () { beforeEach(function () { this.project = { _id: 'project-id', name: 'Project Name', rootDoc_id: 'file-id', publicAccesLevel: 'private', deletedByExternalDataSource: false, rootFolder: [ { _id: 'root-folder-id', name: '', docs: [], fileRefs: [], folders: [ { _id: 'sub-folder-id', name: 'folder', docs: [ { _id: 'doc-id', name: 'main.tex', lines: (this.lines = ['line 1', 'line 2', 'line 3']), }, ], fileRefs: [ { _id: 'file-id', name: 'image.png', created: (this.created = new Date()), size: 1234, }, ], folders: [], }, ], }, ], deletedDocs: [ { _id: 'deleted-doc-id', name: 'main.tex', deletedAt: (this.deletedAt = new Date('2017-01-01')), }, ], } this.members = [ { user: (this.owner = { _id: 'owner-id', first_name: 'Owner', last_name: 'ShareLaTeX', email: 'owner@sharelatex.com', }), privilegeLevel: 'owner', }, { user: { _id: 'read-only-id', first_name: 'Read', last_name: 'Only', email: 'read-only@sharelatex.com', }, privilegeLevel: 'readOnly', }, { user: { _id: 'read-write-id', first_name: 'Read', last_name: 'Write', email: 'read-write@sharelatex.com', }, privilegeLevel: 'readAndWrite', }, ] this.invites = [ { _id: 'invite_one', email: 'user-one@example.com', privileges: 'readOnly', projectId: this.project._id, token: 'my-secret-token1', }, { _id: 'invite_two', email: 'user-two@example.com', privileges: 'readOnly', projectId: this.project._id, token: 'my-secret-token2', }, ] this.deletedDocsFromDocstore = [ { _id: 'deleted-doc-id-from-docstore', name: 'docstore.tex' }, ] return (this.handler = SandboxedModule.require(modulePath)) }) describe('buildProjectModelView', function () { describe('with owner, members and invites included', function () { beforeEach(function () { return (this.result = this.handler.buildProjectModelView( this.project, this.members, this.invites, this.deletedDocsFromDocstore )) }) it('should include the id', function () { expect(this.result._id).to.exist return this.result._id.should.equal('project-id') }) it('should include the name', function () { expect(this.result.name).to.exist return this.result.name.should.equal('Project Name') }) it('should include the root doc id', function () { expect(this.result.rootDoc_id).to.exist return this.result.rootDoc_id.should.equal('file-id') }) it('should include the public access level', function () { expect(this.result.publicAccesLevel).to.exist return this.result.publicAccesLevel.should.equal('private') }) it('should include the owner', function () { expect(this.result.owner).to.exist this.result.owner._id.should.equal('owner-id') this.result.owner.email.should.equal('owner@sharelatex.com') this.result.owner.first_name.should.equal('Owner') this.result.owner.last_name.should.equal('ShareLaTeX') return this.result.owner.privileges.should.equal('owner') }) it('should include the deletedDocs', function () { expect(this.result.deletedDocs).to.exist this.result.deletedDocs.should.deep.equal([ { // omit deletedAt field _id: this.project.deletedDocs[0]._id, name: this.project.deletedDocs[0].name, }, this.deletedDocsFromDocstore[0], ]) }) it('invites should not include the token', function () { expect(this.result.invites[0].token).not.to.exist expect(this.result.invites[1].token).not.to.exist }) it('should gather readOnly_refs and collaberators_refs into a list of members', function () { const findMember = id => { for (const member of Array.from(this.result.members)) { if (member._id === id) { return member } } return null } this.result.members.length.should.equal(2) expect(findMember('read-only-id')).to.exist findMember('read-only-id').privileges.should.equal('readOnly') findMember('read-only-id').first_name.should.equal('Read') findMember('read-only-id').last_name.should.equal('Only') findMember('read-only-id').email.should.equal( 'read-only@sharelatex.com' ) expect(findMember('read-write-id')).to.exist findMember('read-write-id').privileges.should.equal('readAndWrite') findMember('read-write-id').first_name.should.equal('Read') findMember('read-write-id').last_name.should.equal('Write') return findMember('read-write-id').email.should.equal( 'read-write@sharelatex.com' ) }) it('should include folders in the project', function () { this.result.rootFolder[0]._id.should.equal('root-folder-id') this.result.rootFolder[0].name.should.equal('') this.result.rootFolder[0].folders[0]._id.should.equal('sub-folder-id') return this.result.rootFolder[0].folders[0].name.should.equal('folder') }) it('should not duplicate folder contents', function () { this.result.rootFolder[0].docs.length.should.equal(0) return this.result.rootFolder[0].fileRefs.length.should.equal(0) }) it('should include files in the project', function () { this.result.rootFolder[0].folders[0].fileRefs[0]._id.should.equal( 'file-id' ) this.result.rootFolder[0].folders[0].fileRefs[0].name.should.equal( 'image.png' ) this.result.rootFolder[0].folders[0].fileRefs[0].created.should.equal( this.created ) return expect(this.result.rootFolder[0].folders[0].fileRefs[0].size).not .to.exist }) it('should include docs in the project but not the lines', function () { this.result.rootFolder[0].folders[0].docs[0]._id.should.equal('doc-id') this.result.rootFolder[0].folders[0].docs[0].name.should.equal( 'main.tex' ) return expect(this.result.rootFolder[0].folders[0].docs[0].lines).not.to .exist }) it('should include invites', function () { expect(this.result.invites).to.exist return this.result.invites.should.deep.equal(this.invites) }) }) describe('when docstore sends a deleted doc that is also present in the project', function () { beforeEach(function () { this.deletedDocsFromDocstore.push(this.project.deletedDocs[0]) this.result = this.handler.buildProjectModelView( this.project, this.members, this.invites, this.deletedDocsFromDocstore ) }) it('should not send any duplicate', function () { expect(this.result.deletedDocs).to.exist this.result.deletedDocs.should.deep.equal([ this.project.deletedDocs[0], this.deletedDocsFromDocstore[0], ]) }) }) describe('deletedByExternalDataSource', function () { it('should set the deletedByExternalDataSource flag to false when it is not there', function () { delete this.project.deletedByExternalDataSource const result = this.handler.buildProjectModelView( this.project, this.members, [], [] ) return result.deletedByExternalDataSource.should.equal(false) }) it('should set the deletedByExternalDataSource flag to false when it is false', function () { const result = this.handler.buildProjectModelView( this.project, this.members, [], [] ) return result.deletedByExternalDataSource.should.equal(false) }) it('should set the deletedByExternalDataSource flag to true when it is true', function () { this.project.deletedByExternalDataSource = true const result = this.handler.buildProjectModelView( this.project, this.members, [], [] ) return result.deletedByExternalDataSource.should.equal(true) }) }) describe('features', function () { beforeEach(function () { this.owner.features = { versioning: true, collaborators: 3, compileGroup: 'priority', compileTimeout: 96, } return (this.result = this.handler.buildProjectModelView( this.project, this.members, [], [] )) }) it('should copy the owner features to the project', function () { this.result.features.versioning.should.equal( this.owner.features.versioning ) this.result.features.collaborators.should.equal( this.owner.features.collaborators ) this.result.features.compileGroup.should.equal( this.owner.features.compileGroup ) return this.result.features.compileTimeout.should.equal( this.owner.features.compileTimeout ) }) }) describe('trackChangesState', function () { describe('when the owner does not have the trackChanges feature', function () { beforeEach(function () { this.owner.features = { trackChanges: false, } this.result = this.handler.buildProjectModelView( this.project, this.members, [], [] ) }) it('should not emit trackChangesState', function () { expect(this.result.trackChangesState).to.not.exist }) }) describe('when the owner has got the trackChanges feature', function () { beforeEach(function () { this.owner.features = { trackChanges: true, } }) function genCase([dbEntry, expected]) { describe(`when track_changes is ${JSON.stringify( dbEntry )}`, function () { beforeEach(function () { this.project.track_changes = dbEntry this.result = this.handler.buildProjectModelView( this.project, this.members, [], [] ) }) it(`should set trackChangesState=${expected}`, function () { expect(this.result.trackChangesState).to.deep.equal(expected) }) }) } const CASES = [ [null, false], [false, false], [true, true], [{ someId: true }, { someId: true }], ] CASES.map(genCase) }) }) }) describe('buildOwnerAndMembersViews', function () { beforeEach(function () { this.owner.features = { versioning: true, collaborators: 3, compileGroup: 'priority', compileTimeout: 22, } return (this.result = this.handler.buildOwnerAndMembersViews( this.members )) }) it('should produce an object with the right keys', function () { return expect(this.result).to.have.all.keys([ 'owner', 'ownerFeatures', 'members', ]) }) it('should separate the owner from the members', function () { this.result.members.length.should.equal(this.members.length - 1) expect(this.result.owner._id).to.equal(this.owner._id) expect(this.result.owner.email).to.equal(this.owner.email) return expect( this.result.members.filter(m => m._id === this.owner._id).length ).to.equal(0) }) it('should extract the ownerFeatures from the owner object', function () { return expect(this.result.ownerFeatures).to.deep.equal( this.owner.features ) }) describe('when there is no owner', function () { beforeEach(function () { // remove the owner from members list this.membersWithoutOwner = this.members.filter( m => m.user._id !== this.owner._id ) return (this.result = this.handler.buildOwnerAndMembersViews( this.membersWithoutOwner )) }) it('should produce an object with the right keys', function () { return expect(this.result).to.have.all.keys([ 'owner', 'ownerFeatures', 'members', ]) }) it('should not separate out an owner', function () { this.result.members.length.should.equal(this.membersWithoutOwner.length) return expect(this.result.owner).to.equal(null) }) it('should not extract the ownerFeatures from the owner object', function () { return expect(this.result.ownerFeatures).to.equal(null) }) }) }) })
overleaf/web/test/unit/src/Project/ProjectEditorHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Project/ProjectEditorHandlerTests.js", "repo_id": "overleaf", "token_count": 6507 }
560
const SandboxedModule = require('sandboxed-module') const sinon = require('sinon') const modulePath = require('path').join( __dirname, '../../../../app/src/Features/Referal/ReferalFeatures.js' ) describe('ReferalFeatures', function () { beforeEach(function () { this.ReferalFeatures = SandboxedModule.require(modulePath, { requires: { '../../models/User': { User: (this.User = {}), }, '@overleaf/settings': (this.Settings = {}), }, }) this.callback = sinon.stub() this.referal_id = 'referal-id-123' this.referal_medium = 'twitter' this.user_id = 'user-id-123' this.new_user_id = 'new-user-id-123' }) describe('getBonusFeatures', function () { beforeEach(function () { this.refered_user_count = 3 this.Settings.bonus_features = { 3: { collaborators: 3, dropbox: false, versioning: false, }, } const stubbedUser = { refered_user_count: this.refered_user_count, features: { collaborators: 1, dropbox: false, versioning: false }, } this.User.findOne = sinon.stub().callsArgWith(2, null, stubbedUser) this.ReferalFeatures.getBonusFeatures(this.user_id, this.callback) }) it('should get the users number of refered user', function () { this.User.findOne.calledWith({ _id: this.user_id }).should.equal(true) }) it('should call the callback with the features', function () { this.callback .calledWith(null, this.Settings.bonus_features[3]) .should.equal(true) }) }) describe('when the user is not at a bonus level', function () { beforeEach(function () { this.refered_user_count = 0 this.Settings.bonus_features = { 1: { collaborators: 3, dropbox: false, versioning: false, }, } this.User.findOne = sinon .stub() .callsArgWith(2, null, { refered_user_count: this.refered_user_count }) this.ReferalFeatures.getBonusFeatures(this.user_id, this.callback) }) it('should get the users number of refered user', function () { this.User.findOne.calledWith({ _id: this.user_id }).should.equal(true) }) it('should call the callback with no features', function () { this.callback.calledWith(null, {}).should.equal(true) }) }) })
overleaf/web/test/unit/src/Referal/ReferalFeaturesTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Referal/ReferalFeaturesTests.js", "repo_id": "overleaf", "token_count": 996 }
561
const sinon = require('sinon') const sinonChai = require('sinon-chai') const chai = require('chai') const chaiAsPromised = require('chai-as-promised') chai.use(sinonChai) chai.use(chaiAsPromised) const { expect } = chai const recurly = require('recurly') const modulePath = '../../../../app/src/Features/Subscription/RecurlyClient' const SandboxedModule = require('sandboxed-module') describe('RecurlyClient', function () { beforeEach(function () { this.settings = { apis: { recurly: { apiKey: 'nonsense', privateKey: 'private_nonsense', }, }, } this.user = { _id: '123456', email: 'joe@example.com', first_name: 'Joe' } this.subscription = { id: 'subscription-123', uuid: 'subscription-uuid-123', } this.subscriptionChange = { id: 'subscription-change-123' } this.recurlyAccount = new recurly.Account() Object.assign(this.recurlyAccount, { code: this.user._id }) this.recurlySubscription = new recurly.Subscription() Object.assign(this.recurlySubscription, this.subscription) this.recurlySubscriptionChange = new recurly.SubscriptionChange() Object.assign(this.recurlySubscriptionChange, this.subscriptionChange) this.UserGetter = { promises: { getUser: sinon.stub().callsFake(userId => { if (userId === this.user._id) { return this.user } }), }, } let client this.client = client = { getAccount: sinon.stub(), } this.recurly = { errors: recurly.errors, Client: function () { return client }, } return (this.RecurlyClient = SandboxedModule.require(modulePath, { globals: { console: console, }, requires: { '@overleaf/settings': this.settings, recurly: this.recurly, 'logger-sharelatex': { err: sinon.stub(), error: sinon.stub(), warn: sinon.stub(), log: sinon.stub(), debug: sinon.stub(), }, '../User/UserGetter': this.UserGetter, }, })) }) describe('initalizing recurly client with undefined API key parameter', function () { it('should create a client without error', function () { let testClient expect(() => { testClient = new recurly.Client(undefined) }).to.not.throw() expect(testClient).to.be.instanceOf(recurly.Client) }) }) describe('getAccountForUserId', function () { it('should return an Account if one exists', async function () { this.client.getAccount = sinon.stub().resolves(this.recurlyAccount) await expect( this.RecurlyClient.promises.getAccountForUserId(this.user._id) ) .to.eventually.be.an.instanceOf(recurly.Account) .that.has.property('code', this.user._id) }) it('should return nothing if no account found', async function () { this.client.getAccount = sinon .stub() .throws(new recurly.errors.NotFoundError()) expect( this.RecurlyClient.promises.getAccountForUserId('nonsense') ).to.eventually.equal(undefined) }) it('should re-throw caught errors', async function () { this.client.getAccount = sinon.stub().throws() await expect( this.RecurlyClient.promises.getAccountForUserId(this.user._id) ).to.eventually.be.rejectedWith(Error) }) }) describe('createAccountForUserId', function () { it('should return the Account as created by recurly', async function () { this.client.createAccount = sinon.stub().resolves(this.recurlyAccount) await expect( this.RecurlyClient.promises.createAccountForUserId(this.user._id) ) .to.eventually.be.an.instanceOf(recurly.Account) .that.has.property('code', this.user._id) }) it('should throw any API errors', async function () { this.client.createAccount = sinon.stub().throws() await expect( this.RecurlyClient.promises.createAccountForUserId(this.user._id) ).to.eventually.be.rejectedWith(Error) }) }) describe('getSubscription', function () { it('should return the subscription found by recurly', async function () { this.client.getSubscription = sinon .stub() .resolves(this.recurlySubscription) await expect( this.RecurlyClient.promises.getSubscription(this.subscription.id) ) .to.eventually.be.an.instanceOf(recurly.Subscription) .that.has.property('id', this.subscription.id) }) it('should throw any API errors', async function () { this.client.getSubscription = sinon.stub().throws() await expect( this.RecurlyClient.promises.getSubscription(this.user._id) ).to.eventually.be.rejectedWith(Error) }) }) describe('changeSubscription', function () { beforeEach(function () { this.client.createSubscriptionChange = sinon .stub() .resolves(this.recurlySubscriptionChange) }) it('should attempt to create a subscription change', async function () { this.RecurlyClient.promises.changeSubscription(this.subscription.id, {}) expect(this.client.createSubscriptionChange).to.be.calledWith( this.subscription.id ) }) it('should return the subscription change event', async function () { await expect( this.RecurlyClient.promises.changeSubscription( this.subscriptionChange.id, {} ) ) .to.eventually.be.an.instanceOf(recurly.SubscriptionChange) .that.has.property('id', this.subscriptionChange.id) }) it('should throw any API errors', async function () { this.client.createSubscriptionChange = sinon.stub().throws() await expect( this.RecurlyClient.promises.changeSubscription(this.subscription.id, {}) ).to.eventually.be.rejectedWith(Error) }) describe('changeSubscriptionByUuid', function () { it('should attempt to create a subscription change', async function () { this.RecurlyClient.promises.changeSubscriptionByUuid( this.subscription.uuid, {} ) expect(this.client.createSubscriptionChange).to.be.calledWith( 'uuid-' + this.subscription.uuid ) }) it('should return the subscription change event', async function () { await expect( this.RecurlyClient.promises.changeSubscriptionByUuid( this.subscriptionChange.id, {} ) ) .to.eventually.be.an.instanceOf(recurly.SubscriptionChange) .that.has.property('id', this.subscriptionChange.id) }) it('should throw any API errors', async function () { this.client.createSubscriptionChange = sinon.stub().throws() await expect( this.RecurlyClient.promises.changeSubscriptionByUuid( this.subscription.id, {} ) ).to.eventually.be.rejectedWith(Error) }) }) }) describe('removeSubscriptionChange', function () { beforeEach(function () { this.client.removeSubscriptionChange = sinon.stub().resolves() }) it('should attempt to remove a pending subscription change', async function () { this.RecurlyClient.promises.removeSubscriptionChange( this.subscription.id, {} ) expect(this.client.removeSubscriptionChange).to.be.calledWith( this.subscription.id ) }) it('should throw any API errors', async function () { this.client.removeSubscriptionChange = sinon.stub().throws() await expect( this.RecurlyClient.promises.removeSubscriptionChange( this.subscription.id, {} ) ).to.eventually.be.rejectedWith(Error) }) describe('removeSubscriptionChangeByUuid', function () { it('should attempt to remove a pending subscription change', async function () { this.RecurlyClient.promises.removeSubscriptionChangeByUuid( this.subscription.uuid, {} ) expect(this.client.removeSubscriptionChange).to.be.calledWith( 'uuid-' + this.subscription.uuid ) }) it('should throw any API errors', async function () { this.client.removeSubscriptionChange = sinon.stub().throws() await expect( this.RecurlyClient.promises.removeSubscriptionChangeByUuid( this.subscription.id, {} ) ).to.eventually.be.rejectedWith(Error) }) }) }) describe('reactivateSubscriptionByUuid', function () { it('should attempt to reactivate the subscription', async function () { this.client.reactivateSubscription = sinon .stub() .resolves(this.recurlySubscription) await expect( this.RecurlyClient.promises.reactivateSubscriptionByUuid( this.subscription.uuid ) ).to.eventually.be.an.instanceOf(recurly.Subscription) expect(this.client.reactivateSubscription).to.be.calledWith( 'uuid-' + this.subscription.uuid ) }) }) describe('cancelSubscriptionByUuid', function () { it('should attempt to cancel the subscription', async function () { this.client.cancelSubscription = sinon .stub() .resolves(this.recurlySubscription) await expect( this.RecurlyClient.promises.cancelSubscriptionByUuid( this.subscription.uuid ) ).to.eventually.be.an.instanceOf(recurly.Subscription) expect(this.client.cancelSubscription).to.be.calledWith( 'uuid-' + this.subscription.uuid ) }) }) })
overleaf/web/test/unit/src/Subscription/RecurlyClientTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Subscription/RecurlyClientTests.js", "repo_id": "overleaf", "token_count": 4035 }
562
/* eslint-disable max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const SandboxedModule = require('sandboxed-module') const assert = require('assert') const { expect } = require('chai') const sinon = require('sinon') const ProjectHelper = require('../../../../app/src/Features/Project/ProjectHelper') const modulePath = '../../../../app/src/Features/Templates/TemplatesController' describe('TemplatesController', function () { beforeEach(function () { this.user_id = 'user-id' this.TemplatesController = SandboxedModule.require(modulePath, { requires: { '../Project/ProjectHelper': ProjectHelper, '../Authentication/AuthenticationController': (this.AuthenticationController = { getLoggedInUserId: sinon.stub().returns(this.user_id), }), './TemplatesManager': (this.TemplatesManager = { createProjectFromV1Template: sinon.stub(), }), }, }) this.next = sinon.stub() this.req = { body: { brandVariationId: 'brand-variation-id', compiler: 'compiler', mainFile: 'main-file', templateId: 'template-id', templateName: 'template-name', templateVersionId: 'template-version-id', }, session: { templateData: 'template-data', user: { _id: this.user_id, }, }, } return (this.res = { redirect: sinon.stub() }) }) describe('createProjectFromV1Template', function () { describe('on success', function () { beforeEach(function () { this.project = { _id: 'project-id' } this.TemplatesManager.createProjectFromV1Template.yields( null, this.project ) return this.TemplatesController.createProjectFromV1Template( this.req, this.res, this.next ) }) it('should call TemplatesManager', function () { return this.TemplatesManager.createProjectFromV1Template.should.have.been.calledWithMatch( 'brand-variation-id', 'compiler', 'main-file', 'template-id', 'template-name', 'template-version-id', 'user-id' ) }) it('should redirect to project', function () { return this.res.redirect.should.have.been.calledWith( '/project/project-id' ) }) it('should delete session', function () { return expect(this.req.session.templateData).to.be.undefined }) }) describe('on error', function () { beforeEach(function () { this.TemplatesManager.createProjectFromV1Template.yields('error') return this.TemplatesController.createProjectFromV1Template( this.req, this.res, this.next ) }) it('should call next with error', function () { return this.next.should.have.been.calledWith('error') }) it('should not redirect', function () { return this.res.redirect.called.should.equal(false) }) }) }) })
overleaf/web/test/unit/src/Templates/TemplatesControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Templates/TemplatesControllerTests.js", "repo_id": "overleaf", "token_count": 1403 }
563
const sinon = require('sinon') const { expect } = require('chai') const modulePath = '../../../../app/src/Features/User/UserController.js' const SandboxedModule = require('sandboxed-module') const OError = require('@overleaf/o-error') const Errors = require('../../../../app/src/Features/Errors/Errors') describe('UserController', function () { beforeEach(function () { this.user_id = '323123' this.user = { _id: this.user_id, email: 'email@overleaf.com', save: sinon.stub().callsArgWith(0), ace: {}, } this.req = { user: {}, session: { destroy() {}, user: { _id: this.user_id, email: 'old@something.com', }, }, sessionID: '123', body: {}, i18n: { translate: text => text, }, ip: '0:0:0:0', query: {}, } this.UserDeleter = { deleteUser: sinon.stub().yields() } this.UserGetter = { getUser: sinon.stub().callsArgWith(1, null, this.user), promises: { getUser: sinon.stub().resolves(this.user) }, } this.User = { findById: sinon.stub().callsArgWith(1, null, this.user) } this.NewsLetterManager = { unsubscribe: sinon.stub().callsArgWith(1) } this.UserRegistrationHandler = { registerNewUser: sinon.stub() } this.AuthenticationController = { establishUserSession: sinon.stub().callsArg(2), } this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user._id), getSessionUser: sinon.stub().returns(this.req.session.user), setInSessionUser: sinon.stub(), } this.AuthenticationManager = { authenticate: sinon.stub(), validatePassword: sinon.stub(), promises: { authenticate: sinon.stub(), setUserPassword: sinon.stub(), }, } this.UserUpdater = { changeEmailAddress: sinon.stub(), promises: { confirmEmail: sinon.stub().resolves(), addAffiliationForNewUser: sinon.stub().resolves(), }, } this.settings = { siteUrl: 'sharelatex.example.com' } this.UserHandler = { populateTeamInvites: sinon.stub().callsArgWith(1) } this.UserSessionsManager = { trackSession: sinon.stub(), untrackSession: sinon.stub(), revokeAllUserSessions: sinon.stub().callsArgWith(2, null), promises: { getAllUserSessions: sinon.stub().resolves(), revokeAllUserSessions: sinon.stub().resolves(), }, } this.HttpErrorHandler = { badRequest: sinon.stub(), conflict: sinon.stub(), unprocessableEntity: sinon.stub(), legacyInternal: sinon.stub(), } this.UrlHelper = { getSafeRedirectPath: sinon.stub(), } this.UrlHelper.getSafeRedirectPath .withArgs('https://evil.com') .returns(undefined) this.UrlHelper.getSafeRedirectPath.returnsArg(0) this.UserController = SandboxedModule.require(modulePath, { requires: { '../Helpers/UrlHelper': this.UrlHelper, './UserGetter': this.UserGetter, './UserDeleter': this.UserDeleter, './UserUpdater': this.UserUpdater, '../../models/User': { User: this.User, }, '../Newsletter/NewsletterManager': this.NewsLetterManager, './UserRegistrationHandler': this.UserRegistrationHandler, '../Authentication/AuthenticationController': this .AuthenticationController, '../Authentication/SessionManager': this.SessionManager, '../Authentication/AuthenticationManager': this.AuthenticationManager, '../../infrastructure/Features': (this.Features = { hasFeature: sinon.stub(), }), './UserAuditLogHandler': (this.UserAuditLogHandler = { promises: { addEntry: sinon.stub().resolves(), }, }), './UserHandler': this.UserHandler, './UserSessionsManager': this.UserSessionsManager, '../Errors/HttpErrorHandler': this.HttpErrorHandler, '@overleaf/settings': this.settings, '@overleaf/metrics': { inc() {}, }, '@overleaf/o-error': OError, '../Email/EmailHandler': (this.EmailHandler = { sendEmail: sinon.stub(), promises: { sendEmail: sinon.stub().resolves() }, }), }, }) this.res = { send: sinon.stub(), status: sinon.stub(), sendStatus: sinon.stub(), json: sinon.stub(), } this.res.status.returns(this.res) this.next = sinon.stub() this.callback = sinon.stub() }) describe('tryDeleteUser', function () { beforeEach(function () { this.req.body.password = 'wat' this.req.logout = sinon.stub() this.req.session.destroy = sinon.stub().callsArgWith(0, null) this.SessionManager.getLoggedInUserId = sinon .stub() .returns(this.user._id) this.AuthenticationManager.authenticate = sinon .stub() .callsArgWith(2, null, this.user) }) it('should send 200', function (done) { this.res.sendStatus = code => { code.should.equal(200) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) it('should try to authenticate user', function (done) { this.res.sendStatus = code => { this.AuthenticationManager.authenticate.callCount.should.equal(1) this.AuthenticationManager.authenticate .calledWith({ _id: this.user._id }, this.req.body.password) .should.equal(true) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) it('should delete the user', function (done) { this.res.sendStatus = code => { this.UserDeleter.deleteUser.callCount.should.equal(1) this.UserDeleter.deleteUser.calledWith(this.user._id).should.equal(true) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) describe('when no password is supplied', function () { beforeEach(function () { this.req.body.password = '' }) it('should return 403', function (done) { this.res.sendStatus = code => { code.should.equal(403) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) }) describe('when authenticate produces an error', function () { beforeEach(function () { this.AuthenticationManager.authenticate = sinon .stub() .callsArgWith(2, new Error('woops')) }) it('should call next with an error', function (done) { this.next = err => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) }) describe('when authenticate does not produce a user', function () { beforeEach(function () { this.AuthenticationManager.authenticate = sinon .stub() .callsArgWith(2, null, null) }) it('should return 403', function (done) { this.res.sendStatus = code => { code.should.equal(403) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) }) describe('when deleteUser produces an error', function () { beforeEach(function () { this.UserDeleter.deleteUser = sinon.stub().yields(new Error('woops')) }) it('should call next with an error', function (done) { this.next = err => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) }) describe('when deleteUser produces a known error', function () { beforeEach(function () { this.UserDeleter.deleteUser = sinon .stub() .yields(new Errors.SubscriptionAdminDeletionError()) }) it('should return a HTTP Unprocessable Entity error', function (done) { this.HttpErrorHandler.unprocessableEntity = sinon.spy( (req, res, message, info) => { expect(req).to.exist expect(res).to.exist expect(message).to.equal('error while deleting user account') expect(info).to.deep.equal({ error: 'SubscriptionAdminDeletionError', }) done() } ) this.UserController.tryDeleteUser(this.req, this.res) }) }) describe('when session.destroy produces an error', function () { beforeEach(function () { this.req.session.destroy = sinon .stub() .callsArgWith(0, new Error('woops')) }) it('should call next with an error', function (done) { this.next = err => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) done() } this.UserController.tryDeleteUser(this.req, this.res, this.next) }) }) }) describe('unsubscribe', function () { it('should send the user to unsubscribe', function (done) { this.res.sendStatus = () => { this.NewsLetterManager.unsubscribe .calledWith(this.user) .should.equal(true) done() } this.UserController.unsubscribe(this.req, this.res) }) }) describe('updateUserSettings', function () { beforeEach(function () { this.auditLog = { initiatorId: this.user_id, ipAddress: this.req.ip } this.newEmail = 'hello@world.com' this.req.externalAuthenticationSystemUsed = sinon.stub().returns(false) }) it('should call save', function (done) { this.req.body = {} this.res.sendStatus = code => { this.user.save.called.should.equal(true) done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should set the first name', function (done) { this.req.body = { first_name: 'bobby ' } this.res.sendStatus = code => { this.user.first_name.should.equal('bobby') done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should set the role', function (done) { this.req.body = { role: 'student' } this.res.sendStatus = code => { this.user.role.should.equal('student') done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should set the institution', function (done) { this.req.body = { institution: 'MIT' } this.res.sendStatus = code => { this.user.institution.should.equal('MIT') done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should set some props on ace', function (done) { this.req.body = { editorTheme: 'something' } this.res.sendStatus = code => { this.user.ace.theme.should.equal('something') done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should set the overall theme', function (done) { this.req.body = { overallTheme: 'green-ish' } this.res.sendStatus = code => { this.user.ace.overallTheme.should.equal('green-ish') done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should send an error if the email is 0 len', function (done) { this.req.body.email = '' this.res.sendStatus = function (code) { code.should.equal(400) done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should send an error if the email does not contain an @', function (done) { this.req.body.email = 'bob at something dot com' this.res.sendStatus = function (code) { code.should.equal(400) done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should call the user updater with the new email and user _id', function (done) { this.req.body.email = this.newEmail.toUpperCase() this.UserUpdater.changeEmailAddress.callsArgWith(3) this.res.sendStatus = code => { code.should.equal(200) this.UserUpdater.changeEmailAddress .calledWith(this.user_id, this.newEmail, this.auditLog) .should.equal(true) done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should update the email on the session', function (done) { this.req.body.email = this.newEmail.toUpperCase() this.UserUpdater.changeEmailAddress.callsArgWith(3) let callcount = 0 this.User.findById = (id, cb) => { if (++callcount === 2) { this.user.email = this.newEmail } cb(null, this.user) } this.res.sendStatus = code => { code.should.equal(200) this.SessionManager.setInSessionUser .calledWith(this.req.session, { email: this.newEmail, first_name: undefined, last_name: undefined, }) .should.equal(true) done() } this.UserController.updateUserSettings(this.req, this.res) }) it('should call populateTeamInvites', function (done) { this.req.body.email = this.newEmail.toUpperCase() this.UserUpdater.changeEmailAddress.callsArgWith(3) this.res.sendStatus = code => { code.should.equal(200) this.UserHandler.populateTeamInvites .calledWith(this.user) .should.equal(true) done() } this.UserController.updateUserSettings(this.req, this.res) }) describe('when changeEmailAddress yields an error', function () { it('should pass on an error and not send a success status', function (done) { this.req.body.email = this.newEmail.toUpperCase() this.UserUpdater.changeEmailAddress.callsArgWith(3, new OError()) this.HttpErrorHandler.legacyInternal = sinon.spy( (req, res, message, error) => { expect(req).to.exist expect(req).to.exist message.should.equal('problem_changing_email_address') expect(error).to.be.instanceof(OError) done() } ) this.UserController.updateUserSettings(this.req, this.res, this.next) }) it('should call the HTTP conflict error handler when the email already exists', function (done) { this.HttpErrorHandler.conflict = sinon.spy((req, res, message) => { expect(req).to.exist expect(req).to.exist message.should.equal('email_already_registered') done() }) this.req.body.email = this.newEmail.toUpperCase() this.UserUpdater.changeEmailAddress.callsArgWith( 3, new Errors.EmailExistsError() ) this.UserController.updateUserSettings(this.req, this.res) }) }) describe('when using an external auth source', function () { beforeEach(function () { this.UserUpdater.changeEmailAddress.callsArgWith(2) this.newEmail = 'someone23@example.com' this.req.externalAuthenticationSystemUsed = sinon.stub().returns(true) }) it('should not set a new email', function (done) { this.req.body.email = this.newEmail this.res.sendStatus = code => { code.should.equal(200) this.UserUpdater.changeEmailAddress .calledWith(this.user_id, this.newEmail) .should.equal(false) done() } this.UserController.updateUserSettings(this.req, this.res) }) }) }) describe('logout', function () { it('should destroy the session', function (done) { this.req.session.destroy = sinon.stub().callsArgWith(0) this.res.redirect = url => { url.should.equal('/login') this.req.session.destroy.called.should.equal(true) done() } this.UserController.logout(this.req, this.res) }) it('should untrack session', function (done) { this.req.session.destroy = sinon.stub().callsArgWith(0) this.res.redirect = url => { url.should.equal('/login') this.UserSessionsManager.untrackSession.callCount.should.equal(1) this.UserSessionsManager.untrackSession .calledWith(sinon.match(this.req.user), this.req.sessionID) .should.equal(true) done() } this.UserController.logout(this.req, this.res) }) it('should redirect after logout', function (done) { this.req.body.redirect = '/institutional-login' this.req.session.destroy = sinon.stub().callsArgWith(0) this.res.redirect = url => { url.should.equal(this.req.body.redirect) done() } this.UserController.logout(this.req, this.res) }) it('should redirect after logout, but not to evil.com', function (done) { this.req.body.redirect = 'https://evil.com' this.req.session.destroy = sinon.stub().callsArgWith(0) this.res.redirect = url => { url.should.equal('/login') done() } this.UserController.logout(this.req, this.res) }) it('should redirect to login after logout when no redirect set', function (done) { this.req.session.destroy = sinon.stub().callsArgWith(0) this.res.redirect = url => { url.should.equal('/login') done() } this.UserController.logout(this.req, this.res) }) }) describe('register', function () { beforeEach(function () { this.UserRegistrationHandler.registerNewUserAndSendActivationEmail = sinon .stub() .callsArgWith(1, null, this.user, (this.url = 'mock/url')) this.req.body.email = this.user.email = this.email = 'email@example.com' this.UserController.register(this.req, this.res) }) it('should register the user and send them an email', function () { this.UserRegistrationHandler.registerNewUserAndSendActivationEmail .calledWith(this.email) .should.equal(true) }) it('should return the user and activation url', function () { this.res.json .calledWith({ email: this.email, setNewPasswordUrl: this.url, }) .should.equal(true) }) }) describe('clearSessions', function () { describe('success', function () { it('should call revokeAllUserSessions', function (done) { this.res.sendStatus.callsFake(() => { this.UserSessionsManager.promises.revokeAllUserSessions.callCount.should.equal( 1 ) done() }) this.UserController.clearSessions(this.req, this.res) }) it('send a 201 response', function (done) { this.res.sendStatus.callsFake(status => { status.should.equal(201) done() }) this.UserController.clearSessions(this.req, this.res) }) it('sends a security alert email', function (done) { this.res.sendStatus.callsFake(status => { this.EmailHandler.promises.sendEmail.callCount.should.equal(1) const expectedArg = { to: this.user.email, actionDescribed: `active sessions were cleared on your account ${this.user.email}`, action: 'active sessions cleared', } const emailCall = this.EmailHandler.promises.sendEmail.lastCall expect(emailCall.args[0]).to.equal('securityAlert') expect(emailCall.args[1]).to.deep.equal(expectedArg) done() }) this.UserController.clearSessions(this.req, this.res) }) }) describe('errors', function () { describe('when getAllUserSessions produces an error', function () { it('should return an error', function (done) { this.UserSessionsManager.promises.getAllUserSessions.rejects( new Error('woops') ) this.UserController.clearSessions(this.req, this.res, error => { expect(error).to.be.instanceof(Error) done() }) }) }) describe('when audit log addEntry produces an error', function () { it('should call next with an error', function (done) { this.UserAuditLogHandler.promises.addEntry.rejects(new Error('woops')) this.UserController.clearSessions(this.req, this.res, error => { expect(error).to.be.instanceof(Error) done() }) }) }) describe('when revokeAllUserSessions produces an error', function () { it('should call next with an error', function (done) { this.UserSessionsManager.promises.revokeAllUserSessions.rejects( new Error('woops') ) this.UserController.clearSessions(this.req, this.res, error => { expect(error).to.be.instanceof(Error) done() }) }) }) describe('when EmailHandler produces an error', function () { const anError = new Error('oops') it('send a 201 response but log error', function (done) { this.EmailHandler.promises.sendEmail.rejects(anError) this.res.sendStatus.callsFake(status => { status.should.equal(201) this.logger.error.callCount.should.equal(1) const loggerCall = this.logger.error.getCall(0) expect(loggerCall.args[0]).to.deep.equal({ error: anError, userId: this.user_id, }) expect(loggerCall.args[1]).to.contain( 'could not send security alert email when sessions cleared' ) done() }) this.UserController.clearSessions(this.req, this.res) }) }) }) }) describe('changePassword', function () { describe('success', function () { beforeEach(function () { this.AuthenticationManager.promises.authenticate.resolves(this.user) this.AuthenticationManager.promises.setUserPassword.resolves() this.req.body = { newPassword1: 'newpass', newPassword2: 'newpass', } }) it('should set the new password if they do match', function (done) { this.res.json.callsFake(() => { this.AuthenticationManager.promises.setUserPassword.should.have.been.calledWith( this.user, 'newpass' ) done() }) this.UserController.changePassword(this.req, this.res) }) it('should log the update', function (done) { this.res.json.callsFake(() => { this.UserAuditLogHandler.promises.addEntry.should.have.been.calledWith( this.user._id, 'update-password', this.user._id, this.req.ip ) this.AuthenticationManager.promises.setUserPassword.callCount.should.equal( 1 ) done() }) this.UserController.changePassword(this.req, this.res) }) it('should send security alert email', function (done) { this.res.json.callsFake(() => { const expectedArg = { to: this.user.email, actionDescribed: `your password has been changed on your account ${this.user.email}`, action: 'password changed', } const emailCall = this.EmailHandler.sendEmail.lastCall expect(emailCall.args[0]).to.equal('securityAlert') expect(emailCall.args[1]).to.deep.equal(expectedArg) done() }) this.UserController.changePassword(this.req, this.res) }) }) describe('errors', function () { it('should check the old password is the current one at the moment', function (done) { this.AuthenticationManager.promises.authenticate.resolves() this.req.body = { currentPassword: 'oldpasshere' } this.HttpErrorHandler.badRequest.callsFake(() => { expect(this.HttpErrorHandler.badRequest).to.have.been.calledWith( this.req, this.res, 'Your old password is wrong' ) this.AuthenticationManager.promises.authenticate.should.have.been.calledWith( { _id: this.user._id }, 'oldpasshere' ) this.AuthenticationManager.promises.setUserPassword.callCount.should.equal( 0 ) done() }) this.UserController.changePassword(this.req, this.res) }) it('it should not set the new password if they do not match', function (done) { this.AuthenticationManager.promises.authenticate.resolves({}) this.req.body = { newPassword1: '1', newPassword2: '2', } this.HttpErrorHandler.badRequest.callsFake(() => { expect(this.HttpErrorHandler.badRequest).to.have.been.calledWith( this.req, this.res, 'password_change_passwords_do_not_match' ) this.AuthenticationManager.promises.setUserPassword.callCount.should.equal( 0 ) done() }) this.UserController.changePassword(this.req, this.res) }) it('it should not set the new password if it is invalid', function (done) { // this.AuthenticationManager.validatePassword = sinon // .stub() // .returns({ message: 'validation-error' }) const err = new Error('bad') err.name = 'InvalidPasswordError' this.AuthenticationManager.promises.setUserPassword.rejects(err) this.AuthenticationManager.promises.authenticate.resolves({}) this.req.body = { newPassword1: 'newpass', newPassword2: 'newpass', } this.HttpErrorHandler.badRequest.callsFake(() => { expect(this.HttpErrorHandler.badRequest).to.have.been.calledWith( this.req, this.res, err.message ) this.AuthenticationManager.promises.setUserPassword.callCount.should.equal( 1 ) done() }) this.UserController.changePassword(this.req, this.res) }) describe('UserAuditLogHandler error', function () { it('should return error and not update password', function (done) { this.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops')) this.AuthenticationManager.promises.authenticate.resolves(this.user) this.AuthenticationManager.promises.setUserPassword.resolves() this.req.body = { newPassword1: 'newpass', newPassword2: 'newpass', } this.UserController.changePassword(this.req, this.res, error => { expect(error).to.be.instanceof(Error) this.AuthenticationManager.promises.setUserPassword.callCount.should.equal( 1 ) done() }) }) }) describe('EmailHandler error', function () { const anError = new Error('oops') beforeEach(function () { this.AuthenticationManager.promises.authenticate.resolves(this.user) this.AuthenticationManager.promises.setUserPassword.resolves() this.req.body = { newPassword1: 'newpass', newPassword2: 'newpass', } this.EmailHandler.sendEmail.yields(anError) }) it('should not return error but should log it', function (done) { this.res.json.callsFake(result => { expect(result.message.type).to.equal('success') this.logger.error.callCount.should.equal(1) expect(this.logger.error).to.have.been.calledWithExactly( { error: anError, userId: this.user_id, }, 'could not send security alert email when password changed' ) done() }) this.UserController.changePassword(this.req, this.res) }) }) }) }) describe('ensureAffiliationMiddleware', function () { describe('without affiliations feature', function () { beforeEach(async function () { await this.UserController.promises.ensureAffiliationMiddleware( this.req, this.res, this.next ) }) it('should not run affiliation check', function () { expect(this.UserGetter.promises.getUser).to.not.have.been.called expect(this.UserUpdater.promises.confirmEmail).to.not.have.been.called expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have .been.called }) it('should not return an error', function () { expect(this.next).to.be.calledWith() }) }) describe('without ensureAffiliation query parameter', function () { beforeEach(async function () { this.Features.hasFeature.withArgs('affiliations').returns(true) await this.UserController.promises.ensureAffiliationMiddleware( this.req, this.res, this.next ) }) it('should not run middleware', function () { expect(this.UserGetter.promises.getUser).to.not.have.been.called expect(this.UserUpdater.promises.confirmEmail).to.not.have.been.called expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have .been.called }) it('should not return an error', function () { expect(this.next).to.be.calledWith() }) }) describe('no flagged email', function () { beforeEach(async function () { const email = 'unit-test@overleaf.com' this.user.email = email this.user.emails = [ { email, }, ] this.Features.hasFeature.withArgs('affiliations').returns(true) this.req.query.ensureAffiliation = true await this.UserController.promises.ensureAffiliationMiddleware( this.req, this.res, this.next ) }) it('should get the user', function () { expect(this.UserGetter.promises.getUser).to.have.been.calledWith( this.user._id ) }) it('should not try to add affiliation or update user', function () { expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have .been.called }) it('should not return an error', function () { expect(this.next).to.be.calledWith() }) }) describe('flagged non-SSO email', function () { let emailFlagged beforeEach(async function () { emailFlagged = 'flagged@overleaf.com' this.user.email = emailFlagged this.user.emails = [ { email: emailFlagged, affiliationUnchecked: true, }, ] this.Features.hasFeature.withArgs('affiliations').returns(true) this.req.query.ensureAffiliation = true await this.UserController.promises.ensureAffiliationMiddleware( this.req, this.res, this.next ) }) it('should unflag the emails but not confirm', function () { expect( this.UserUpdater.promises.addAffiliationForNewUser ).to.have.been.calledWith(this.user._id, emailFlagged) expect( this.UserUpdater.promises.confirmEmail ).to.not.have.been.calledWith(this.user._id, emailFlagged) }) it('should not return an error', function () { expect(this.next).to.be.calledWith() }) }) describe('flagged SSO email', function () { let emailFlagged beforeEach(async function () { emailFlagged = 'flagged@overleaf.com' this.user.email = emailFlagged this.user.emails = [ { email: emailFlagged, affiliationUnchecked: true, samlProviderId: '123', }, ] this.Features.hasFeature.withArgs('affiliations').returns(true) this.req.query.ensureAffiliation = true await this.UserController.promises.ensureAffiliationMiddleware( this.req, this.res, this.next ) }) it('should add affiliation to v1, unflag and confirm on v2', function () { expect(this.UserUpdater.promises.addAffiliationForNewUser).to.have.not .been.called expect(this.UserUpdater.promises.confirmEmail).to.have.been.calledWith( this.user._id, emailFlagged ) }) it('should not return an error', function () { expect(this.next).to.be.calledWith() }) }) describe('when v1 returns an error', function () { let emailFlagged beforeEach(async function () { this.UserUpdater.promises.addAffiliationForNewUser.rejects() emailFlagged = 'flagged@overleaf.com' this.user.email = emailFlagged this.user.emails = [ { email: emailFlagged, affiliationUnchecked: true, }, ] this.Features.hasFeature.withArgs('affiliations').returns(true) this.req.query.ensureAffiliation = true await this.UserController.promises.ensureAffiliationMiddleware( this.req, this.res, this.next ) }) it('should return the error', function () { expect(this.next).to.be.calledWith(sinon.match.instanceOf(Error)) }) }) }) })
overleaf/web/test/unit/src/User/UserControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/User/UserControllerTests.js", "repo_id": "overleaf", "token_count": 14968 }
564
/* eslint-disable node/handle-callback-err, max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const { expect } = require('chai') const sinon = require('sinon') const assertCalledWith = sinon.assert.calledWith const assertNotCalled = sinon.assert.notCalled const { ObjectId } = require('mongodb') const modulePath = '../../../../app/src/Features/UserMembership/UserMembershipViewModel' const SandboxedModule = require('sandboxed-module') const { isObjectIdInstance, normalizeQuery, } = require('../../../../app/src/Features/Helpers/Mongo') describe('UserMembershipViewModel', function () { beforeEach(function () { this.UserGetter = { getUser: sinon.stub() } this.UserMembershipViewModel = SandboxedModule.require(modulePath, { requires: { mongodb: { ObjectId }, '../Helpers/Mongo': { isObjectIdInstance, normalizeQuery }, '../User/UserGetter': this.UserGetter, }, }) this.email = 'mock-email@bar.com' this.user = { _id: 'mock-user-id', email: 'mock-email@baz.com', first_name: 'Name', lastLoggedIn: '2020-05-20T10:41:11.407Z', } }) describe('build', function () { it('build email', function () { const viewModel = this.UserMembershipViewModel.build(this.email) return expect(viewModel).to.deep.equal({ email: this.email, invite: true, last_logged_in_at: null, first_name: null, last_name: null, _id: null, }) }) it('build user', function () { const viewModel = this.UserMembershipViewModel.build(this.user) expect(viewModel._id).to.equal(this.user._id) expect(viewModel.email).to.equal(this.user.email) expect(viewModel.last_logged_in_at).to.equal(this.user.lastLoggedIn) return expect(viewModel.invite).to.equal(false) }) }) describe('build async', function () { beforeEach(function () { return (this.UserMembershipViewModel.build = sinon.stub()) }) it('build email', function (done) { return this.UserMembershipViewModel.buildAsync( this.email, (error, viewModel) => { assertCalledWith(this.UserMembershipViewModel.build, this.email) return done() } ) }) it('build user', function (done) { return this.UserMembershipViewModel.buildAsync( this.user, (error, viewModel) => { assertCalledWith(this.UserMembershipViewModel.build, this.user) return done() } ) }) it('build user id', function (done) { this.UserGetter.getUser.yields(null, this.user) return this.UserMembershipViewModel.buildAsync( ObjectId(), (error, viewModel) => { expect(error).not.to.exist assertNotCalled(this.UserMembershipViewModel.build) expect(viewModel._id).to.equal(this.user._id) expect(viewModel.email).to.equal(this.user.email) expect(viewModel.first_name).to.equal(this.user.first_name) expect(viewModel.invite).to.equal(false) expect(viewModel.email).to.exist return done() } ) }) it('build user id with error', function (done) { this.UserGetter.getUser.yields(new Error('nope')) const userId = ObjectId() return this.UserMembershipViewModel.buildAsync( userId, (error, viewModel) => { expect(error).not.to.exist assertNotCalled(this.UserMembershipViewModel.build) expect(viewModel._id).to.equal(userId.toString()) expect(viewModel.email).not.to.exist return done() } ) }) }) })
overleaf/web/test/unit/src/UserMembership/UserMembershipViewModelTests.js/0
{ "file_path": "overleaf/web/test/unit/src/UserMembership/UserMembershipViewModelTests.js", "repo_id": "overleaf", "token_count": 1654 }
565
const { expect } = require('chai') const modulePath = '../../../../app/src/infrastructure/Features.js' const SandboxedModule = require('sandboxed-module') describe('Features', function () { beforeEach(function () { this.Features = SandboxedModule.require(modulePath, { requires: { '@overleaf/settings': (this.settings = { moduleImportSequence: [], enabledLinkedFileTypes: [], }), }, }) }) describe('externalAuthenticationSystemUsed', function () { describe('without any settings', function () { it('should return false', function () { expect(this.Features.externalAuthenticationSystemUsed()).to.be.false }) }) describe('with ldap setting', function () { beforeEach(function () { this.settings.ldap = { enable: true } }) it('should return true', function () { expect(this.Features.externalAuthenticationSystemUsed()).to.be.true }) }) describe('with saml setting', function () { beforeEach(function () { this.settings.saml = { enable: true } }) it('should return true', function () { expect(this.Features.externalAuthenticationSystemUsed()).to.be.true }) }) describe('with oauth setting', function () { beforeEach(function () { this.settings.overleaf = { oauth: true } }) it('should return true', function () { expect(this.Features.externalAuthenticationSystemUsed()).to.be.true }) }) }) describe('hasFeature', function () { describe('without any settings', function () { it('should return true', function () { expect(this.Features.hasFeature('registration-page')).to.be.true expect(this.Features.hasFeature('templates-server-pro')).to.be.true }) it('should return false', function () { expect(this.Features.hasFeature('registration')).to.be.false expect(this.Features.hasFeature('affiliations')).to.be.false expect(this.Features.hasFeature('analytics')).to.be.false expect(this.Features.hasFeature('custom-togglers')).to.be.false expect(this.Features.hasFeature('git-bridge')).to.be.false expect(this.Features.hasFeature('github-sync')).to.be.false expect(this.Features.hasFeature('homepage')).to.be.false expect(this.Features.hasFeature('link-url')).to.be.false expect(this.Features.hasFeature('oauth')).to.be.false expect(this.Features.hasFeature('overleaf-integration')).to.be.false expect(this.Features.hasFeature('references')).to.be.false expect(this.Features.hasFeature('saml')).to.be.false }) }) describe('with settings', function () { describe('empty overleaf object', function () { beforeEach(function () { this.settings.overleaf = {} this.settings.apis = {} }) it('should return true', function () { expect(this.Features.hasFeature('custom-togglers')).to.be.true expect(this.Features.hasFeature('overleaf-integration')).to.be.true expect(this.Features.hasFeature('registration')).to.be.true }) it('should return false', function () { expect(this.Features.hasFeature('affiliations')).to.be.false expect(this.Features.hasFeature('analytics')).to.be.false expect(this.Features.hasFeature('git-bridge')).to.be.false expect(this.Features.hasFeature('github-sync')).to.be.false expect(this.Features.hasFeature('homepage')).to.be.false expect(this.Features.hasFeature('link-url')).to.be.false expect(this.Features.hasFeature('oauth')).to.be.false expect(this.Features.hasFeature('references')).to.be.false expect(this.Features.hasFeature('saml')).to.be.false expect(this.Features.hasFeature('templates-server-pro')).to.be.false }) describe('with APIs', function () { beforeEach(function () { this.settings.apis = { linkedUrlProxy: { url: 'https://www.overleaf.com', }, references: { url: 'https://www.overleaf.com', }, v1: { url: 'https://www.overleaf.com', }, } }) it('should return true', function () { expect(this.Features.hasFeature('affiliations')).to.be.true expect(this.Features.hasFeature('analytics')).to.be.true expect(this.Features.hasFeature('custom-togglers')).to.be.true expect(this.Features.hasFeature('overleaf-integration')).to.be.true expect(this.Features.hasFeature('references')).to.be.true expect(this.Features.hasFeature('registration')).to.be.true }) it('should return false', function () { expect(this.Features.hasFeature('link-url')).to.be.false expect(this.Features.hasFeature('git-bridge')).to.be.false expect(this.Features.hasFeature('github-sync')).to.be.false expect(this.Features.hasFeature('homepage')).to.be.false expect(this.Features.hasFeature('oauth')).to.be.false expect(this.Features.hasFeature('saml')).to.be.false expect(this.Features.hasFeature('templates-server-pro')).to.be.false }) describe('with all other settings flags', function () { beforeEach(function () { this.settings.enableHomepage = true this.settings.enableGitBridge = true this.settings.enableGithubSync = true this.settings.enableSaml = true this.settings.oauth = true this.settings.enabledLinkedFileTypes = ['url', 'project_file'] }) it('should return true or return value', function () { expect(this.Features.hasFeature('link-url')).to.be.true expect(this.Features.hasFeature('affiliations')).to.be.true expect(this.Features.hasFeature('analytics')).to.be.true expect(this.Features.hasFeature('custom-togglers')).to.be.true expect(this.Features.hasFeature('github-sync')).to.be.true expect(this.Features.hasFeature('git-bridge')).to.be.true expect(this.Features.hasFeature('homepage')).to.be.true expect(this.Features.hasFeature('link-url')).to.be.true expect(this.Features.hasFeature('oauth')).to.be.true expect(this.Features.hasFeature('overleaf-integration')).to.be .true expect(this.Features.hasFeature('references')).to.be.true expect(this.Features.hasFeature('registration')).to.be.true expect(this.Features.hasFeature('saml')).to.be.true }) it('should return false', function () { expect(this.Features.hasFeature('templates-server-pro')).to.be .false }) }) }) }) }) }) })
overleaf/web/test/unit/src/infrastructure/FeaturesTests.js/0
{ "file_path": "overleaf/web/test/unit/src/infrastructure/FeaturesTests.js", "repo_id": "overleaf", "token_count": 3071 }
566
{ "ignores": [ "core-js", "requirejs", "@babel/register" ] }
owncloud/web/.depcheckrc/0
{ "file_path": "owncloud/web/.depcheckrc", "repo_id": "owncloud", "token_count": 41 }
567
NAME := web DIST := ${CURDIR}/dist HUGO := ${CURDIR}/hugo RELEASE := ${CURDIR}/release NODE_MODULES := ${CURDIR}/node_modules node_modules: package.json pnpm-lock.yaml [ -n "${NO_INSTALL}" ] || pnpm install touch ${NODE_MODULES} .PHONY: clean clean: rm -rf ${DIST} ${HUGO} ${RELEASE} ${NODE_MODULES} .PHONY: release release: clean make -f Makefile.release # # Release # make this app compatible with the ownCloud # default build tools # .PHONY: dist dist: make -f Makefile.release .PHONY: docs docs: docs-copy docs-build .PHONY: docs-copy docs-copy: mkdir -p $(HUGO); \ mkdir -p $(HUGO)/content/extensions; \ cd $(HUGO); \ git init; \ git remote rm origin; \ git remote add origin https://github.com/owncloud/owncloud.github.io; \ git fetch; \ git checkout origin/main -f; \ make -C $(HUGO) theme; \ rsync --delete -ax ../docs/ content/$(NAME) .PHONY: docs-build docs-build: cd $(HUGO); hugo .PHONY: l10n-push l10n-push: make -C packages/web-runtime/l10n push .PHONY: l10n-pull l10n-pull: make -C packages/web-runtime/l10n pull .PHONY: l10n-clean l10n-clean: make -C packages/web-runtime/l10n clean .PHONY: l10n-read l10n-read: node_modules make -C packages/web-runtime/l10n extract .PHONY: l10n-write l10n-write: node_modules make -C packages/web-runtime/l10n translations
owncloud/web/Makefile/0
{ "file_path": "owncloud/web/Makefile", "repo_id": "owncloud", "token_count": 547 }
568
Bugfix: Fix empty settings values We've updated owncloud-sdk to version 1.0.0-638 which makes sure that an empty array gets returned whenever there are no settings values for the authenticated user. Previously having no settings values broke our detection of whether settings values finished loading. https://github.com/owncloud/web/pull/3602 https://github.com/owncloud/ocis-settings/issues/24
owncloud/web/changelog/0.11.0_2020-06-26/fix-empty-settings/0
{ "file_path": "owncloud/web/changelog/0.11.0_2020-06-26/fix-empty-settings", "repo_id": "owncloud", "token_count": 101 }
569
Bugfix: Remove anchor on last breadcrumb segment The last segment of the breadcrumb was clickable, while it's expected that nothing happens (as it is the current path). We fixed that, the last breadcrumb element is not clickable anymore. https://github.com/owncloud/web/issues/3722 https://github.com/owncloud/web/issues/2965 https://github.com/owncloud/web/pull/3723 https://github.com/owncloud/web/issues/1883
owncloud/web/changelog/0.11.2_2020-07-03/fix-breadcrumb/0
{ "file_path": "owncloud/web/changelog/0.11.2_2020-07-03/fix-breadcrumb", "repo_id": "owncloud", "token_count": 124 }
570
Enhancement: Enable playing videos in media viewer We've added a capability to the media viewer extension to play videos. https://github.com/owncloud/web/pull/3803 https://github.com/owncloud/web/pull/3833 https://github.com/owncloud/web/pull/3844 https://github.com/owncloud/web/pull/3848
owncloud/web/changelog/0.14.0_2020-08-17/media-viewer-video-playback/0
{ "file_path": "owncloud/web/changelog/0.14.0_2020-08-17/media-viewer-video-playback", "repo_id": "owncloud", "token_count": 92 }
571
Enhancement: Remember public link password on page refresh When refreshing the page in the file list of a public link share, the user doesn't need to enter the password again. This only applies for the current page and the password is forgotten by the browser again upon closing or switching to another site. https://github.com/owncloud/web/pull/4083 https://github.com/owncloud/product/issues/231
owncloud/web/changelog/0.17.0_2020-09-25/public-link-remember-password-on-refresh/0
{ "file_path": "owncloud/web/changelog/0.17.0_2020-09-25/public-link-remember-password-on-refresh", "repo_id": "owncloud", "token_count": 97 }
572
Change: Set icon for unknown file types to "file" We've changed the icon for unknown file types to "file". https://owncloud.design/#/Design%20Tokens/Icon https://github.com/owncloud/web/pull/4237
owncloud/web/changelog/0.22.0_2020-10-26/default-icon/0
{ "file_path": "owncloud/web/changelog/0.22.0_2020-10-26/default-icon", "repo_id": "owncloud", "token_count": 59 }
573
Change: Configurable default extension We introduced a config option in the config.json file which allows to configure the default extension for ownCloud Web. Any of the configured extension ids can be chosen as default extension. If none is provided, we fall back to the files extension. https://github.com/owncloud/web/pull/4382
owncloud/web/changelog/0.27.0_2020-11-24/default-extension/0
{ "file_path": "owncloud/web/changelog/0.27.0_2020-11-24/default-extension", "repo_id": "owncloud", "token_count": 77 }
574
Change: Join users and groups into a single list in collaborators sidebar Users and groups were shown as two separate lists (users, then groups) in the collaborators sidebar. This separation is now removed, i.e. there is only one list with all collaborators, sorted by display name (lower case, ascending). On equal names groups are shown first. https://github.com/owncloud/web/issues/2900
owncloud/web/changelog/0.3.0_2020-01-31/2900/0
{ "file_path": "owncloud/web/changelog/0.3.0_2020-01-31/2900", "repo_id": "owncloud", "token_count": 92 }
575
Enhancement: Improved collaborators column in shared file lists Fixed issue with the collaborators column where only one was being displayed in the "shared with you" file list. This is done by properly aggregating all share entries under each file entry for the list, which now also includes group shares and link shares. Improved the look of the collaborators by adding avatars and icons there for the shares in the collaborators and owner columns. https://github.com/owncloud/web/issues/2924 https://github.com/owncloud/web/pull/3049
owncloud/web/changelog/0.5.0_2020-03-02/2924/0
{ "file_path": "owncloud/web/changelog/0.5.0_2020-03-02/2924", "repo_id": "owncloud", "token_count": 124 }
576
Bugfix: Sorted collaborators column, deduplicate public entry The collaborators column that appears in the "shared with others" section are now sorted: first by share type (user, group, link, remote) and then by display name using natural sort. Additionally, if there is more than one public link for the resource, the text "Public" only appears once in the collaborators column. https://github.com/owncloud/web/issues/3137 https://github.com/owncloud/web/pull/3171
owncloud/web/changelog/0.6.0_2020-03-16/3137/0
{ "file_path": "owncloud/web/changelog/0.6.0_2020-03-16/3137", "repo_id": "owncloud", "token_count": 120 }
577
Enhancement: add state to app urls Currently opened file can be added to app routes so reloading the page can be made to work For now it's only implemented in mediaviewer https://github.com/owncloud/web/pull/3294
owncloud/web/changelog/0.8.0_2020-04-14/3294/0
{ "file_path": "owncloud/web/changelog/0.8.0_2020-04-14/3294", "repo_id": "owncloud", "token_count": 60 }
578
Bugfix: Fix role selection for public links The dropdown for the role selection in public links was not working anymore - the model didn't react to selections. Fixed it by bringing back a field that was accidentally removed. https://github.com/owncloud/web/pull/4504
owncloud/web/changelog/1.0.0_2020-12-16/fix-link-role-selection/0
{ "file_path": "owncloud/web/changelog/1.0.0_2020-12-16/fix-link-role-selection", "repo_id": "owncloud", "token_count": 64 }
579
Bugfix: Allow search in additional share info We fixed that searching for a potential sharee didn't look at the additional share info. https://github.com/owncloud/ocis/issues/1656 https://github.com/owncloud/web/pull/4753
owncloud/web/changelog/2.0.1_2021-02-18/search-in-additional-info/0
{ "file_path": "owncloud/web/changelog/2.0.1_2021-02-18/search-in-additional-info", "repo_id": "owncloud", "token_count": 64 }
580
Enhancement: Add web-pkg package We added web-pkg as a new package. It is supposed to be the central location for reuse of generic functionality. https://github.com/owncloud/web/pull/4907
owncloud/web/changelog/3.0.0_2021-04-21/enhancement-introduce-web-pkg/0
{ "file_path": "owncloud/web/changelog/3.0.0_2021-04-21/enhancement-introduce-web-pkg", "repo_id": "owncloud", "token_count": 54 }
581
Enhancement: Lazy file avatar loading We've changed the way how large file lists get rendered. In some cases where we had a long list of files, the loading of avatars could lead to long waiting times till the first paint happens. Now we first render the list of files, load the associated avatars in the background and then update the ui. https://github.com/owncloud/web/pull/5073 https://github.com/owncloud/web/issues/4973
owncloud/web/changelog/3.1.0_2021-05-12/enhancement-lazy-file-avatar-loading/0
{ "file_path": "owncloud/web/changelog/3.1.0_2021-05-12/enhancement-lazy-file-avatar-loading", "repo_id": "owncloud", "token_count": 113 }
582
Bugfix: Make skip to main content link visible We've fixed the z-index of the skip to main content link so that it is not hidden under different content anymore and is again visible on focus, with a visible focus border. https://github.com/owncloud/web/pull/5118 https://github.com/owncloud/web/pull/5167
owncloud/web/changelog/3.3.0_2021-06-23/bugfix-make-skip-to-visible/0
{ "file_path": "owncloud/web/changelog/3.3.0_2021-06-23/bugfix-make-skip-to-visible", "repo_id": "owncloud", "token_count": 87 }
583
Enhancement: Asynchronous loading of images Thumbnail and avatar images now get loaded in the background and don't block the main rendering of the user interface. https://github.com/owncloud/web/issues/4973 https://github.com/owncloud/web/pull/5194
owncloud/web/changelog/3.3.0_2021-06-23/enhancement-async-image-loading/0
{ "file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-async-image-loading", "repo_id": "owncloud", "token_count": 69 }
584
Enhancement: Send focus to "Add people" btn after closing Add/Edit panels We've started sending the focus to "Add people" button after the `Add` panel in the people accordion has been closed. Also, when editing a share the focus jumps back to the "Edit" button in the respective share after cancelling or confirming the action. https://github.com/owncloud/web/pull/5129 https://github.com/owncloud/web/pull/5146
owncloud/web/changelog/3.3.0_2021-06-23/enhancement-people-focus/0
{ "file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-people-focus", "repo_id": "owncloud", "token_count": 114 }
585
Enhancement: Details in Sharing Sidebar We're now displaying more information about the highlighted file in the sharing sidebar, including a preview (if applicable) as well as sharing and version information in one place. https://github.com/owncloud/web/issues/5161 https://github.com/owncloud/web/pull/5284 https://github.com/owncloud/web/pull/5483
owncloud/web/changelog/3.4.0_2021-07-09/enhancement-details-in-sharing-sidebar/0
{ "file_path": "owncloud/web/changelog/3.4.0_2021-07-09/enhancement-details-in-sharing-sidebar", "repo_id": "owncloud", "token_count": 102 }
586
Enhancement: Refactor recipient autocomplete in people panel We've refactored the recipient autocomplete in people panel so that selected recipients are displayed directly in the autocomplete instead of the list below it. https://github.com/owncloud/web/pull/5554
owncloud/web/changelog/4.0.0_2021-08-04/enhancement-invite/0
{ "file_path": "owncloud/web/changelog/4.0.0_2021-08-04/enhancement-invite", "repo_id": "owncloud", "token_count": 64 }
587
Bugfix: Pagination on Locationpicker Pagination on copying/moving files as well as page reloads when copying/moving files were broken. When changing the Vue router encoding, we fixed both issues. https://github.com/owncloud/web/pull/5715
owncloud/web/changelog/4.2.0_2021-09-14/bugfix-pagination-move-pagereload/0
{ "file_path": "owncloud/web/changelog/4.2.0_2021-09-14/bugfix-pagination-move-pagereload", "repo_id": "owncloud", "token_count": 65 }
588
Enhancement: Multiple shared with me tables We have separated the single table on the shared with me page into up to three different tables: - pending shares - accepted shares - declined shares By default we show pending and accepted shares. There is navigation in place to switch over from the accepted to the declined shares and the other way around. Pending shares stay visible all the time since it's expected that users take immediate action on pending shares anyway. https://github.com/owncloud/web/pull/5814 https://github.com/owncloud/web/pull/5177
owncloud/web/changelog/4.3.0_2021-10-07/enhancement-shared-with-me-split/0
{ "file_path": "owncloud/web/changelog/4.3.0_2021-10-07/enhancement-shared-with-me-split", "repo_id": "owncloud", "token_count": 129 }
589
Enhancement: Use default info from app provider The app provider returns information about the default application per mime type. This information is now respected when triggering the default action for a file. https://github.com/owncloud/web/issues/5962 https://github.com/owncloud/web/pull/5970
owncloud/web/changelog/4.5.0_2021-11-16/enhancement-app-provider-defaults/0
{ "file_path": "owncloud/web/changelog/4.5.0_2021-11-16/enhancement-app-provider-defaults", "repo_id": "owncloud", "token_count": 74 }
590
Bugfix: File renaming We fixed the displayed file name not being properly updated in files list and sidebar after renaming. https://github.com/owncloud/web/issues/4893 https://github.com/owncloud/web/pull/6114
owncloud/web/changelog/4.7.0_2021-12-16/bugfix-file-rename/0
{ "file_path": "owncloud/web/changelog/4.7.0_2021-12-16/bugfix-file-rename", "repo_id": "owncloud", "token_count": 61 }
591
Bugfix: Editor default handling Editor apps that don't provide the information about whether or not they are a default editor were not recognized as default editors when left-clicking a file in the file list. We've changed the default behaviour so that editors are capable of being the default editor unless explicitly disabled. https://github.com/owncloud/web/pull/6186
owncloud/web/changelog/4.8.0_2021-12-22/bugfix-app-defaults/0
{ "file_path": "owncloud/web/changelog/4.8.0_2021-12-22/bugfix-app-defaults", "repo_id": "owncloud", "token_count": 81 }
592