text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
const AuthenticationController = require('../Authentication/AuthenticationController') const TemplatesController = require('./TemplatesController') const TemplatesMiddleware = require('./TemplatesMiddleware') const RateLimiterMiddleware = require('../Security/RateLimiterMiddleware') const AnalyticsRegistrationSourceMiddleware = require('../Analytics/AnalyticsRegistrationSourceMiddleware') module.exports = { apply(app) { app.get( '/project/new/template/:Template_version_id', TemplatesMiddleware.saveTemplateDataInSession, AuthenticationController.requireLogin(), TemplatesController.getV1Template ) app.post( '/project/new/template', AnalyticsRegistrationSourceMiddleware.setSource('template'), AuthenticationController.requireLogin(), RateLimiterMiddleware.rateLimit({ endpointName: 'create-project-from-template', maxRequests: 20, timeInterval: 60, }), TemplatesController.createProjectFromV1Template, AnalyticsRegistrationSourceMiddleware.clearSource() ) }, }
overleaf/web/app/src/Features/Templates/TemplatesRouter.js/0
{ "file_path": "overleaf/web/app/src/Features/Templates/TemplatesRouter.js", "repo_id": "overleaf", "token_count": 339 }
489
const AuthorizationMiddleware = require('../Authorization/AuthorizationMiddleware') const AuthenticationController = require('../Authentication/AuthenticationController') const ProjectUploadController = require('./ProjectUploadController') const RateLimiterMiddleware = require('../Security/RateLimiterMiddleware') const Settings = require('@overleaf/settings') module.exports = { apply(webRouter, apiRouter) { webRouter.post( '/project/new/upload', AuthenticationController.requireLogin(), RateLimiterMiddleware.rateLimit({ endpointName: 'project-upload', maxRequests: 20, timeInterval: 60, }), ProjectUploadController.multerMiddleware, ProjectUploadController.uploadProject ) const fileUploadEndpoint = '/Project/:Project_id/upload' const fileUploadRateLimit = RateLimiterMiddleware.rateLimit({ endpointName: 'file-upload', params: ['Project_id'], maxRequests: 200, timeInterval: 60 * 15, }) if (Settings.allowAnonymousReadAndWriteSharing) { webRouter.post( fileUploadEndpoint, fileUploadRateLimit, AuthorizationMiddleware.ensureUserCanWriteProjectContent, ProjectUploadController.multerMiddleware, ProjectUploadController.uploadFile ) } else { webRouter.post( fileUploadEndpoint, fileUploadRateLimit, AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanWriteProjectContent, ProjectUploadController.multerMiddleware, ProjectUploadController.uploadFile ) } }, }
overleaf/web/app/src/Features/Uploads/UploadsRouter.js/0
{ "file_path": "overleaf/web/app/src/Features/Uploads/UploadsRouter.js", "repo_id": "overleaf", "token_count": 573 }
490
const { User } = require('../../models/User') const UserCreator = require('./UserCreator') const UserGetter = require('./UserGetter') const AuthenticationManager = require('../Authentication/AuthenticationManager') const NewsletterManager = require('../Newsletter/NewsletterManager') const async = require('async') const logger = require('logger-sharelatex') const crypto = require('crypto') const EmailHandler = require('../Email/EmailHandler') const OneTimeTokenHandler = require('../Security/OneTimeTokenHandler') const Analytics = require('../Analytics/AnalyticsManager') const settings = require('@overleaf/settings') const EmailHelper = require('../Helpers/EmailHelper') const UserRegistrationHandler = { _registrationRequestIsValid(body) { const invalidEmail = AuthenticationManager.validateEmail(body.email || '') const invalidPassword = AuthenticationManager.validatePassword( body.password || '', body.email ) return !(invalidEmail || invalidPassword) }, _createNewUserIfRequired(user, userDetails, callback) { if (!user) { userDetails.holdingAccount = false UserCreator.createNewUser( { holdingAccount: false, email: userDetails.email, first_name: userDetails.first_name, last_name: userDetails.last_name, }, {}, callback ) } else { callback(null, user) } }, registerNewUser(userDetails, callback) { const self = this const requestIsValid = this._registrationRequestIsValid(userDetails) if (!requestIsValid) { return callback(new Error('request is not valid')) } userDetails.email = EmailHelper.parseEmail(userDetails.email) UserGetter.getUserByAnyEmail(userDetails.email, (error, user) => { if (error) { return callback(error) } if (user && user.holdingAccount === false) { return callback(new Error('EmailAlreadyRegistered'), user) } self._createNewUserIfRequired(user, userDetails, (error, user) => { if (error) { return callback(error) } async.series( [ callback => User.updateOne( { _id: user._id }, { $set: { holdingAccount: false } }, callback ), callback => AuthenticationManager.setUserPassword( user, userDetails.password, callback ), callback => { if (userDetails.subscribeToNewsletter === 'true') { NewsletterManager.subscribe(user, error => { if (error) { logger.warn( { err: error, user }, 'Failed to subscribe user to newsletter' ) } }) } callback() }, // this can be slow, just fire it off ], error => { Analytics.recordEvent(user._id, 'user-registered') callback(error, user) } ) }) }) }, registerNewUserAndSendActivationEmail(email, callback) { UserRegistrationHandler.registerNewUser( { email, password: crypto.randomBytes(32).toString('hex'), }, (error, user) => { if (error && error.message !== 'EmailAlreadyRegistered') { return callback(error) } if (error && error.message === 'EmailAlreadyRegistered') { logger.log({ email }, 'user already exists, resending welcome email') } const ONE_WEEK = 7 * 24 * 60 * 60 // seconds OneTimeTokenHandler.getNewToken( 'password', { user_id: user._id.toString(), email: user.email }, { expiresIn: ONE_WEEK }, (error, token) => { if (error) { return callback(error) } const setNewPasswordUrl = `${settings.siteUrl}/user/activate?token=${token}&user_id=${user._id}` EmailHandler.sendEmail( 'registered', { to: user.email, setNewPasswordUrl, }, error => { if (error) { logger.warn({ err: error }, 'failed to send activation email') } } ) callback(null, user, setNewPasswordUrl) } ) } ) }, } module.exports = UserRegistrationHandler
overleaf/web/app/src/Features/User/UserRegistrationHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/User/UserRegistrationHandler.js", "repo_id": "overleaf", "token_count": 2060 }
491
/* 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const csurf = require('csurf') const csrf = csurf() const { promisify } = require('util') // Wrapper for `csurf` middleware that provides a list of routes that can be excluded from csrf checks. // // Include with `Csrf = require('./Csrf')` // // Add the middleware to the router with: // myRouter.csrf = new Csrf() // myRouter.use webRouter.csrf.middleware // When building routes, specify a route to exclude from csrf checks with: // myRouter.csrf.disableDefaultCsrfProtection "/path" "METHOD" // // To validate the csrf token in a request to ensure that it's valid, you can use `validateRequest`, which takes a // request object and calls a callback with an error if invalid. class Csrf { constructor() { this.middleware = this.middleware.bind(this) this.excluded_routes = {} } disableDefaultCsrfProtection(route, method) { if (!this.excluded_routes[route]) { this.excluded_routes[route] = {} } return (this.excluded_routes[route][method] = 1) } middleware(req, res, next) { // We want to call the middleware for all routes, even if excluded, because csurf sets up a csrfToken() method on // the request, to get a new csrf token for any rendered forms. For excluded routes we'll then ignore a 'bad csrf // token' error from csurf and continue on... // check whether the request method is excluded for the specified route if ( (this.excluded_routes[req.path] != null ? this.excluded_routes[req.path][req.method] : undefined) === 1 ) { // ignore the error if it's due to a bad csrf token, and continue return csrf(req, res, err => { if (err && err.code !== 'EBADCSRFTOKEN') { return next(err) } else { return next() } }) } else { return csrf(req, res, next) } } static validateRequest(req, cb) { // run a dummy csrf check to see if it returns an error if (cb == null) { cb = function (valid) {} } return csrf(req, null, err => cb(err)) } static validateToken(token, session, cb) { if (token == null) { return cb(new Error('missing token')) } // run a dummy csrf check to see if it returns an error // use this to simulate a csrf check regardless of req method, headers &c. const req = { body: { _csrf: token, }, headers: {}, method: 'POST', session, } return Csrf.validateRequest(req, cb) } } Csrf.promises = { validateRequest: promisify(Csrf.validateRequest), } module.exports = Csrf
overleaf/web/app/src/infrastructure/Csrf.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/Csrf.js", "repo_id": "overleaf", "token_count": 1130 }
492
const settings = require('@overleaf/settings') const Metrics = require('@overleaf/metrics') const RedisWrapper = require('./RedisWrapper') const rclient = RedisWrapper.client('ratelimiter') const { RedisRateLimiter } = require('rolling-rate-limiter') const { callbackify } = require('util') async function addCount(opts) { if (settings.disableRateLimits) { return true } const namespace = `RateLimit:${opts.endpointName}:` const k = `{${opts.subjectName}}` const limiter = new RedisRateLimiter({ client: rclient, namespace, interval: opts.timeInterval * 1000, maxInInterval: opts.throttle, }) const rateLimited = await limiter.limit(k) if (rateLimited) { Metrics.inc('rate-limit-hit', 1, { path: opts.endpointName, }) } return !rateLimited } async function clearRateLimit(endpointName, subject) { // same as the key which will be built by RollingRateLimiter (namespace+k) const keyName = `RateLimit:${endpointName}:{${subject}}` await rclient.del(keyName) } module.exports = { addCount: callbackify(addCount), clearRateLimit: callbackify(clearRateLimit), promises: { addCount, clearRateLimit, }, }
overleaf/web/app/src/infrastructure/RateLimiter.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/RateLimiter.js", "repo_id": "overleaf", "token_count": 414 }
493
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const DocSchema = new Schema({ name: { type: String, default: 'new doc' }, }) exports.Doc = mongoose.model('Doc', DocSchema) exports.DocSchema = DocSchema
overleaf/web/app/src/models/Doc.js/0
{ "file_path": "overleaf/web/app/src/models/Doc.js", "repo_id": "overleaf", "token_count": 87 }
494
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const SystemMessageSchema = new Schema({ content: { type: String, default: '' }, }) exports.SystemMessage = mongoose.model('SystemMessage', SystemMessageSchema)
overleaf/web/app/src/models/SystemMessage.js/0
{ "file_path": "overleaf/web/app/src/models/SystemMessage.js", "repo_id": "overleaf", "token_count": 76 }
495
mixin linkAdvisors(linkText, linkClass, track) //- To Do: verify path - var gaCategory = track && track.category ? track.category : 'All' - var gaAction = track && track.action ? track.action : null - var gaLabel = track && track.label ? track.label : null - var mb = track && track.mb ? 'true' : null - var mbSegmentation = track && track.segmentation ? track.segmentation : null - var trigger = track && track.trigger ? track.trigger : null a(href="/advisors" class=linkClass ? linkClass : '' event-tracking-ga=gaCategory event-tracking=gaAction event-tracking-label=gaLabel event-tracking-trigger=trigger event-tracking-mb=mb event-segmentation=mbSegmentation ) span(ng-non-bindable) #{linkText ? linkText : 'advisor programme'} mixin linkBenefits(linkText, linkClass) a(href=(settings.siteUrl ? settings.siteUrl : '') + "/for/authors" class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'benefits'} mixin linkBlog(linkText, linkClass, slug) if slug a(href=(settings.siteUrl ? settings.siteUrl : '') + "/blog/" + slug class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'blog'} mixin linkContact(linkText, linkClass) a(href=(settings.siteUrl ? settings.siteUrl : '') + "/contact" class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'contact'} mixin linkDash(linkText, linkClass) a(href="/project" class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'project dashboard'} mixin linkEducation(linkText, linkClass) a(href=(settings.siteUrl ? settings.siteUrl : '') + "/for/edu" class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'teaching toolkit'} mixin linkInvite(linkText, linkClass, track) - var gaCategory = track && track.category ? track.category : 'All' - var gaAction = track && track.action ? track.action : null - var gaLabel = track && track.label ? track.label : null - var mb = track && track.mb ? 'true' : null - var mbSegmentation = track && track.segmentation ? track.segmentation : null - var trigger = track && track.trigger ? track.trigger : null a(href="/user/bonus" class=linkClass ? linkClass : '' event-tracking-ga=gaCategory event-tracking=gaAction event-tracking-label=gaLabel event-tracking-trigger=trigger event-tracking-mb=mb event-segmentation=mbSegmentation ) span(ng-non-bindable) #{linkText ? linkText : 'invite your friends'} mixin linkPlansAndPricing(linkText, linkClass) a(href="/user/subscription/plans" class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'plans and pricing'} mixin linkPrintNewTab(linkText, linkClass, icon, track) - var gaCategory = track && track.category ? track.category : null - var gaAction = track && track.action ? track.action : null - var gaLabel = track && track.label ? track.label : null - var mb = track && track.mb ? 'true' : null - var mbSegmentation = track && track.segmentation ? track.segmentation : null - var trigger = track && track.trigger ? track.trigger : null a(href='?media=print' class=linkClass ? linkClass : '' event-tracking-ga=gaCategory event-tracking=gaAction event-tracking-label=gaLabel event-tracking-trigger=trigger event-tracking-mb=mb event-segmentation=mbSegmentation target="_BLANK", rel="noopener noreferrer" ) if icon i(class="fa fa-print") |   span(ng-non-bindable) #{linkText ? linkText : 'print'} mixin linkSignIn(linkText, linkClass, redirect) a(href=`/login${redirect ? '?redir=' + redirect : ''}` class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'sign in'} mixin linkSignUp(linkText, linkClass, redirect) a(href=`/register${redirect ? '?redir=' + redirect : ''}` class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'sign up'} mixin linkTweet(linkText, linkClass, tweetText, track) //- twitter-share-button is required by twitter - var gaCategory = track && track.category ? track.category : 'All' - var gaAction = track && track.action ? track.action : null - var gaLabel = track && track.label ? track.label : null - var mb = track && track.mb ? 'true' : null - var mbSegmentation = track && track.segmentation ? track.segmentation : null - var trigger = track && track.trigger ? track.trigger : null a(class="twitter-share-button " + linkClass event-tracking-ga=gaCategory event-tracking=gaAction event-tracking-label=gaLabel event-tracking-trigger=trigger event-tracking-mb=mb event-segmentation=mbSegmentation href="https://twitter.com/intent/tweet?text=" + tweetText target="_BLANK", rel="noopener noreferrer" ) #{linkText ? linkText : 'tweet'} mixin linkUniversities(linkText, linkClass) a(href=(settings.siteUrl ? settings.siteUrl : '') + "/for/universities" class=linkClass ? linkClass : '', ng-non-bindable) | #{linkText ? linkText : 'universities'}
overleaf/web/app/views/_mixins/links.pug/0
{ "file_path": "overleaf/web/app/views/_mixins/links.pug", "repo_id": "overleaf", "token_count": 1717 }
496
doctype html html(lang="en") - metadata = metadata || {} block vars head if (metadata && metadata.title) title= metadata.title if metadata && metadata.viewport meta(name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes") link(rel="icon", href="/favicon.ico") if buildCssPath link(rel="stylesheet", href=buildCssPath()) block body
overleaf/web/app/views/layout/layout-no-js.pug/0
{ "file_path": "overleaf/web/app/views/layout/layout-no-js.pug", "repo_id": "overleaf", "token_count": 140 }
497
aside.change-list( ng-if="history.isV2" ng-controller="HistoryV2ListController" ) history-entries-list( ng-if="!history.showOnlyLabels && !history.error" entries="history.updates" range-selection-enabled="history.viewMode === HistoryViewModes.COMPARE" selected-history-version="history.selection.range.toV" selected-history-range="history.selection.range" current-user="user" current-user-is-owner="project.owner._id === user.id" users="projectUsers" load-entries="loadMore()" load-disabled="history.loading || history.atEnd" load-initialize="ui.view == 'history'" is-loading="history.loading" free-history-limit-hit="history.freeHistoryLimitHit" on-version-select="handleVersionSelect(version)" on-range-select="handleRangeSelect(selectedToV, selectedFromV)" on-label-delete="handleLabelDelete(label)" ) history-labels-list( ng-if="history.showOnlyLabels && !history.error" labels="history.labels" range-selection-enabled="history.viewMode === HistoryViewModes.COMPARE" selected-history-version="history.selection.range.toV" selected-history-range="history.selection.range" current-user="user" users="projectUsers" is-loading="history.loading" on-version-select="handleVersionSelect(version)" on-range-select="handleRangeSelect(selectedToV, selectedFromV)" on-label-delete="handleLabelDelete(label)" ) script(type="text/ng-template", id="historyEntriesListTpl") .history-entries( infinite-scroll="$ctrl.loadEntries()" infinite-scroll-disabled="$ctrl.loadDisabled" infinite-scroll-initialize="$ctrl.loadInitialize" ) .infinite-scroll-inner history-entry( ng-repeat="entry in $ctrl.entries" range-selection-enabled="$ctrl.rangeSelectionEnabled" is-dragging="$ctrl.isDragging" selected-history-version="$ctrl.selectedHistoryVersion" selected-history-range="$ctrl.selectedHistoryRange" hovered-history-range="$ctrl.hoveredHistoryRange" entry="entry" current-user="$ctrl.currentUser" users="$ctrl.users" on-select="$ctrl.handleEntrySelect(selectedEntry)" on-label-delete="$ctrl.onLabelDelete({ label: label })" ) .loading(ng-show="$ctrl.isLoading") i.fa.fa-spin.fa-refresh |    #{translate("loading")}… .history-entries-list-upgrade-prompt( ng-if="$ctrl.freeHistoryLimitHit && $ctrl.currentUserIsOwner" ng-controller="FreeTrialModalController" ) p #{translate("currently_seeing_only_24_hrs_history")} p: strong #{translate("upgrade_to_get_feature", {feature:"full Project History"})} ul.list-unstyled li i.fa.fa-check   | #{translate("unlimited_projects")} li i.fa.fa-check   | #{translate("collabs_per_proj", {collabcount:'Multiple'})} li i.fa.fa-check   | #{translate("full_doc_history")} li i.fa.fa-check   | #{translate("sync_to_dropbox")} li i.fa.fa-check   | #{translate("sync_to_github")} li i.fa.fa-check   |#{translate("compile_larger_projects")} p.text-center a.btn.btn-success( href ng-class="buttonClass" ng-click="startFreeTrial('history')" ) #{translate("start_free_trial")} p.small(ng-show="startedFreeTrial") #{translate("refresh_page_after_starting_free_trial")} .history-entries-list-upgrade-prompt( ng-if="$ctrl.freeHistoryLimitHit && !$ctrl.currentUserIsOwner" ) p #{translate("currently_seeing_only_24_hrs_history")} strong #{translate("ask_proj_owner_to_upgrade_for_full_history")} script(type="text/ng-template", id="historyEntryTpl") time.history-entry-day(ng-if="::$ctrl.entry.meta.first_in_day") {{ ::$ctrl.entry.meta.end_ts | relativeDate }} .history-entry( ng-class="{\ 'history-entry-first-in-day': $ctrl.entry.meta.first_in_day,\ 'history-entry-selected': !$ctrl.isDragging && $ctrl.isEntrySelected(),\ 'history-entry-selected-to': $ctrl.rangeSelectionEnabled && !$ctrl.isDragging && $ctrl.selectedHistoryRange.toV === $ctrl.entry.toV,\ 'history-entry-selected-from': $ctrl.rangeSelectionEnabled && !$ctrl.isDragging && $ctrl.selectedHistoryRange.fromV === $ctrl.entry.fromV,\ 'history-entry-hover-selected': $ctrl.rangeSelectionEnabled && $ctrl.isDragging && $ctrl.isEntryHoverSelected(),\ 'history-entry-hover-selected-to': $ctrl.rangeSelectionEnabled && $ctrl.isDragging && $ctrl.hoveredHistoryRange.toV === $ctrl.entry.toV,\ 'history-entry-hover-selected-from': $ctrl.rangeSelectionEnabled && $ctrl.isDragging && $ctrl.hoveredHistoryRange.fromV === $ctrl.entry.fromV,\ }" history-droppable-area history-droppable-area-on-drop="$ctrl.onDrop(boundary)" history-droppable-area-on-over="$ctrl.onOver(boundary)" ) .history-entry-details( ng-click="$ctrl.onSelect({ selectedEntry: $ctrl.entry })" ) .history-entry-toV-handle( ng-show="$ctrl.rangeSelectionEnabled && $ctrl.selectedHistoryRange && ((!$ctrl.isDragging && $ctrl.selectedHistoryRange.toV === $ctrl.entry.toV) || ($ctrl.isDragging && $ctrl.hoveredHistoryRange.toV === $ctrl.entry.toV))" history-draggable-boundary="toV" history-draggable-boundary-on-drag-start="$ctrl.onDraggingStart()" history-draggable-boundary-on-drag-stop="$ctrl.onDraggingStop(isValidDrop, boundary)" ) history-label( ng-repeat="label in $ctrl.entry.labels | orderBy : '-created_at'" ng-init="user = $ctrl.buildUserView(label)" label-text="label.comment" label-owner-name="$ctrl.displayNameById(label.user_id) || 'Anonymous'" label-creation-date-time="label.created_at" is-owned-by-current-user="label.user_id === $ctrl.currentUser.id" on-label-delete="$ctrl.onLabelDelete({ label: label })" ) ol.history-entry-changes li.history-entry-change( ng-repeat="pathname in ::$ctrl.entry.pathnames" ) span.history-entry-change-action #{translate("file_action_edited")} span.history-entry-change-doc {{ ::pathname }} li.history-entry-change( ng-repeat="project_op in ::$ctrl.entry.project_ops" ) span.history-entry-change-action( ng-if="::project_op.rename" ) #{translate("file_action_renamed")} span.history-entry-change-action( ng-if="::project_op.add" ) #{translate("file_action_created")} span.history-entry-change-action( ng-if="::project_op.remove" ) #{translate("file_action_deleted")} span.history-entry-change-doc {{ ::$ctrl.getProjectOpDoc(project_op) }} .history-entry-metadata time.history-entry-metadata-time {{ ::$ctrl.entry.meta.end_ts | formatDate:'h:mm a' }} span | | • | ol.history-entry-metadata-users li.history-entry-metadata-user(ng-repeat="update_user in ::$ctrl.entry.meta.users") span.name( ng-if="::update_user && update_user.id != $ctrl.currentUser.id" ng-style="$ctrl.getUserCSSStyle(update_user);" ) {{ ::$ctrl.displayName(update_user) }} span.name( ng-if="::update_user && update_user.id == $ctrl.currentUser.id" ng-style="$ctrl.getUserCSSStyle(update_user);" ) You span.name( ng-if="::update_user == null" ng-style="$ctrl.getUserCSSStyle(update_user);" ) #{translate("anonymous")} li.history-entry-metadata-user(ng-if="::$ctrl.entry.meta.users.length == 0") span.name( ng-style="$ctrl.getUserCSSStyle();" ) #{translate("anonymous")} .history-entry-fromV-handle( ng-show="$ctrl.rangeSelectionEnabled && $ctrl.selectedHistoryRange && ((!$ctrl.isDragging && $ctrl.selectedHistoryRange.fromV === $ctrl.entry.fromV) || ($ctrl.isDragging && $ctrl.hoveredHistoryRange.fromV === $ctrl.entry.fromV))" history-draggable-boundary="fromV" history-draggable-boundary-on-drag-start="$ctrl.onDraggingStart()" history-draggable-boundary-on-drag-stop="$ctrl.onDraggingStop(isValidDrop, boundary)" ) script(type="text/ng-template", id="historyLabelsListTpl") .history-labels-list .history-version-with-label( ng-repeat="versionWithLabel in $ctrl.versionsWithLabels | orderBy:'-version' track by versionWithLabel.version" ng-class="{\ 'history-version-with-label-selected': !$ctrl.isDragging && $ctrl.isVersionSelected(versionWithLabel.version),\ 'history-version-with-label-selected-to': !$ctrl.isDragging && $ctrl.selectedHistoryRange.toV === versionWithLabel.version,\ 'history-version-with-label-selected-from': !$ctrl.isDragging && $ctrl.selectedHistoryRange.fromV === versionWithLabel.version,\ 'history-version-with-label-hover-selected': $ctrl.isDragging && $ctrl.isVersionHoverSelected(versionWithLabel.version),\ 'history-version-with-label-hover-selected-to': $ctrl.isDragging && $ctrl.hoveredHistoryRange.toV === versionWithLabel.version,\ 'history-version-with-label-hover-selected-from': $ctrl.isDragging && $ctrl.hoveredHistoryRange.fromV === versionWithLabel.version,\ }" ng-click="$ctrl.handleVersionSelect(versionWithLabel)" history-droppable-area history-droppable-area-on-drop="$ctrl.onDrop(boundary, versionWithLabel)" history-droppable-area-on-over="$ctrl.onOver(boundary, versionWithLabel)" ) .history-entry-toV-handle( ng-show="$ctrl.rangeSelectionEnabled && $ctrl.selectedHistoryRange && ((!$ctrl.isDragging && $ctrl.selectedHistoryRange.toV === versionWithLabel.version) || ($ctrl.isDragging && $ctrl.hoveredHistoryRange.toV === versionWithLabel.version))" history-draggable-boundary="toV" history-draggable-boundary-on-drag-start="$ctrl.onDraggingStart()" history-draggable-boundary-on-drag-stop="$ctrl.onDraggingStop(isValidDrop, boundary)" ) div( ng-repeat="label in versionWithLabel.labels track by label.id" ) history-label( show-tooltip="false" label-text="label.comment" is-owned-by-current-user="label.user_id === $ctrl.currentUser.id" on-label-delete="$ctrl.onLabelDelete({ label: label })" is-pseudo-current-state-label="label.isPseudoCurrentStateLabel" ) .history-entry-label-metadata .history-entry-label-metadata-user( ng-if="!label.isPseudoCurrentStateLabel" ng-init="user = $ctrl.buildUserView(label)" ) | Saved by span.name( ng-if="user && user._id !== $ctrl.currentUser.id" ng-style="$ctrl.getUserCSSStyle(user, versionWithLabel);" ) {{ ::user.displayName }} span.name( ng-if="user && user._id == $ctrl.currentUser.id" ng-style="$ctrl.getUserCSSStyle(user, versionWithLabel);" ) You span.name( ng-if="user == null" ng-style="$ctrl.getUserCSSStyle(user, versionWithLabel);" ) #{translate("anonymous")} time.history-entry-label-metadata-time {{ ::label.created_at | formatDate }} .history-entry-fromV-handle( ng-show="$ctrl.rangeSelectionEnabled && $ctrl.selectedHistoryRange && ((!$ctrl.isDragging && $ctrl.selectedHistoryRange.fromV === versionWithLabel.version) || ($ctrl.isDragging && $ctrl.hoveredHistoryRange.fromV === versionWithLabel.version))" history-draggable-boundary="fromV" history-draggable-boundary-on-drag-start="$ctrl.onDraggingStart()" history-draggable-boundary-on-drag-stop="$ctrl.onDraggingStop(isValidDrop, boundary)" ) .loading(ng-show="$ctrl.isLoading") i.fa.fa-spin.fa-refresh |    #{translate("loading")}…
overleaf/web/app/views/project/editor/history/entriesListV2.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/history/entriesListV2.pug", "repo_id": "overleaf", "token_count": 4635 }
498
td.project-list-table-name-cell .project-list-table-name-container input.project-list-table-select-item( select-individual, type="checkbox", ng-model="project.selected" stop-propagation="click" aria-label=translate('select_project') + " '{{ project.name }}'" ) span.project-list-table-name a.project-list-table-name-link( ng-href="{{projectLink(project)}}" stop-propagation="click" ) {{project.name}} span( ng-controller="TagListController" ) .tag-label( ng-repeat='tag in project.tags' stop-propagation="click" ) button.label.label-default.tag-label-name( ng-click="selectTag(tag)" aria-label="Select tag {{ tag.name }}" ) i.fa.fa-circle( aria-hidden="true" ng-style="{ 'color': 'hsl({{ getHueForTagId(tag._id) }}, 70%, 45%)' }" ) | {{tag.name}} button.label.label-default.tag-label-remove( ng-click="removeProjectFromTag(project, tag)" aria-label="Remove tag {{ tag.name }}" ) span(aria-hidden="true") × td.project-list-table-owner-cell span.owner(ng-if='project.owner') {{getOwnerName(project)}} |   i.fa.fa-question-circle.small( ng-if="hasGenericOwnerName()" tooltip="This project is owned by a user who hasn’t yet migrated their account to Overleaf v2" tooltip-append-to-body="true" aria-hidden="true" ) span(ng-if="isLinkSharingProject(project)") |   i.fa.fa-link.small( tooltip=translate("link_sharing") tooltip-placement="right" tooltip-append-to-body="true" aria-label=translate("link_sharing") ) td.project-list-table-lastupdated-cell span.last-modified(tooltip="{{project.lastUpdated | formatDate}}") | {{project.lastUpdated | fromNowDate}} span(ng-show='project.lastUpdatedBy') | | #{translate('by')} | {{getUserName(project.lastUpdatedBy)}} td.project-list-table-actions-cell div button.btn.btn-link.action-btn( ng-if="!(project.archived || project.trashed)" aria-label=translate('copy'), tooltip=translate('copy'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="openCloneProjectModal(project)" ) i.icon.fa.fa-files-o(aria-hidden="true") button.btn.btn-link.action-btn( aria-label=translate('download'), tooltip=translate('download'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="download($event)" ) i.icon.fa.fa-cloud-download(aria-hidden="true") button.btn.btn-link.action-btn( ng-if="!project.archived" aria-label=translate('archive'), tooltip=translate('archive'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="archive($event)" ) i.icon.fa.fa-inbox(aria-hidden="true") button.btn.btn-link.action-btn( ng-if="!project.trashed" aria-label=translate('trash'), tooltip=translate('trash'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="trash($event)" ) i.icon.fa.fa-trash(aria-hidden="true") button.btn.btn-link.action-btn( ng-if="project.archived && !project.trashed" aria-label=translate('unarchive'), tooltip=translate('unarchive'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="unarchive($event)" ) i.icon.fa.fa-reply(aria-hidden="true") button.btn.btn-link.action-btn( ng-if="project.trashed && !project.archived" aria-label=translate('untrash'), tooltip=translate('untrash'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="untrash($event)" ) i.icon.fa.fa-reply(aria-hidden="true") button.btn.btn-link.action-btn( ng-if="project.trashed && !project.archived && !isOwner()" aria-label=translate('leave'), tooltip=translate('leave'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="leave($event)" ) i.icon.fa.fa-sign-out(aria-hidden="true") button.btn.btn-link.action-btn( ng-if="project.trashed && !project.archived && isOwner()" aria-label=translate('delete'), tooltip=translate('delete'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="delete($event)" ) i.icon.fa.fa-ban(aria-hidden="true")
overleaf/web/app/views/project/list/item.pug/0
{ "file_path": "overleaf/web/app/views/project/list/item.pug", "repo_id": "overleaf", "token_count": 1804 }
499
div(ng-controller="GroupMembershipController") each groupSubscription in memberGroupSubscriptions if (user._id+'' != groupSubscription.admin_id._id+'') div p | You are a member of | +teamName(groupSubscription) if (groupSubscription.teamNotice && groupSubscription.teamNotice != '') p //- Team notice is sanitized in SubscriptionViewModelBuilder em(ng-non-bindable) !{groupSubscription.teamNotice} span button.btn.btn-danger.text-capitalise(ng-click="removeSelfFromGroup('"+groupSubscription._id+"')") #{translate("leave_group")} hr script(type='text/ng-template', id='LeaveGroupModalTemplate') .modal-header h3 #{translate("leave_group")} .modal-body p #{translate("sure_you_want_to_leave_group")} .modal-footer button.btn.btn-default( ng-disabled="inflight" ng-click="cancel()" ) #{translate("cancel")} button.btn.btn-danger( ng-disabled="state.inflight" ng-click="confirmLeaveGroup()" ) span(ng-hide="inflight") #{translate("leave_now")} span(ng-show="inflight") #{translate("processing")}…
overleaf/web/app/views/subscriptions/dashboard/_group_memberships.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/dashboard/_group_memberships.pug", "repo_id": "overleaf", "token_count": 440 }
500
if (typeof(suggestedLanguageSubdomainConfig) != "undefined") span(ng-controller="TranslationsPopupController", ng-cloak) .translations-message(ng-hide="hidei18nNotification") a(href=suggestedLanguageSubdomainConfig.url+currentUrl) !{translate("click_here_to_view_sl_in_lng", {lngName: translate(suggestedLanguageSubdomainConfig.lngCode)}, ['strong'])} img(src=buildImgPath("flags/24/" + suggestedLanguageSubdomainConfig.lngCode + ".png")) button(ng-click="dismiss()").close.pull-right span(aria-hidden="true") × span.sr-only #{translate("close")}
overleaf/web/app/views/translations/translation_message.pug/0
{ "file_path": "overleaf/web/app/views/translations/translation_message.pug", "repo_id": "overleaf", "token_count": 207 }
501
extends ../layout block append meta meta(name="ol-users", data-type="json", content=users) meta(name="ol-paths", data-type="json", content=paths) meta(name="ol-groupSize", data-type="json", content=groupSize) block content main.content.content-alt#main-content .container .row .col-md-10.col-md-offset-1 h1(ng-non-bindable) #{name || translate(translations.title)} .card(ng-controller="UserMembershipController") .page-header .pull-right(ng-cloak) small(ng-show="groupSize && selectedUsers.length == 0") !{translate("you_have_added_x_of_group_size_y", {addedUsersSize:'{{ users.length }}', groupSize: '{{ groupSize }}'}, ['strong', 'strong'])} a.btn.btn-danger( href, ng-show="selectedUsers.length > 0" ng-click="removeMembers()" ) #{translate(translations.remove)} h3 #{translate(translations.subtitle)} .row-spaced-small div(ng-if="inputs.removeMembers.error", ng-cloak) div.alert.alert-danger(ng-if="inputs.removeMembers.errorMessage") | #{translate('error')}: | {{ inputs.removeMembers.errorMessage }} div.alert.alert-danger(ng-if="!inputs.removeMembers.errorMessage") | #{translate('generic_something_went_wrong')} ul.list-unstyled.structured-list( select-all-list, ng-cloak ) li.container-fluid .row .col-md-4 input.select-all( select-all, type="checkbox" ) span.header #{translate("email")} .col-md-4 span.header #{translate("name")} .col-md-2 span.header #{translate("last_login")} .col-md-2 span.header #{translate("accepted_invite")} li.container-fluid( ng-repeat="user in users | orderBy:'email':true", ng-controller="UserMembershipListItemController" ) .row .col-md-4 input.select-item( select-individual, type="checkbox", ng-model="user.selected" ) span.email {{ user.email }} .col-md-4 span.name {{ user.first_name }} {{ user.last_name }} .col-md-2 span.lastLogin {{ user.last_logged_in_at | formatDate:'Do MMM YYYY' }} .col-md-2 span.registered i.fa.fa-check.text-success(ng-show="!user.invite" aria-hidden="true") span.sr-only(ng-show="!user.invite") #{translate('accepted_invite')} i.fa.fa-times(ng-show="user.invite" aria-hidden="true") span.sr-only(ng-show="user.invite") #{translate('invite_not_accepted')} li( ng-if="users.length == 0", ng-cloak ) .row .col-md-12.text-centered small #{translate("no_members")} hr div(ng-if="!groupSize || users.length < groupSize", ng-cloak) p.small #{translate("add_more_members")} div(ng-if="inputs.addMembers.error", ng-cloak) div.alert.alert-danger(ng-if="inputs.addMembers.errorMessage") | #{translate('error')}: | {{ inputs.addMembers.errorMessage }} div.alert.alert-danger(ng-if="!inputs.addMembers.errorMessage") | #{translate('generic_something_went_wrong')} form.form .row .col-xs-6 input.form-control( name="email", type="text", placeholder="jane@example.com, joe@example.com", ng-model="inputs.addMembers.content", on-enter="addMembers()" aria-describedby="add-members-description" ) .col-xs-4 button.btn.btn-primary(ng-click="addMembers()", ng-disabled="inputs.addMembers.inflightCount > 0") span(ng-show="inputs.addMembers.inflightCount === 0") #{translate("add")} span(ng-show="inputs.addMembers.inflightCount > 0") #{translate("adding")}… .col-xs-2(ng-if="paths.exportMembers", ng-cloak) a(href=paths.exportMembers) #{translate('export_csv')} .row .col-xs-8 span.help-block #{translate('add_comma_separated_emails_help')} div(ng-if="groupSize && users.length >= groupSize && users.length > 0", ng-cloak) .row .col-xs-2.col-xs-offset-10(ng-if="paths.exportMembers", ng-cloak) a(href=paths.exportMembers) #{translate('export_csv')}
overleaf/web/app/views/user_membership/index.pug/0
{ "file_path": "overleaf/web/app/views/user_membership/index.pug", "repo_id": "overleaf", "token_count": 2259 }
502
// 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.directive('expandableTextArea', () => ({ restrict: 'A', link(scope, el) { const resetHeight = function () { const curHeight = el.outerHeight() const fitHeight = el.prop('scrollHeight') // clear height if text area is empty if (el.val() === '') { el.css('height', 'unset') } // otherwise expand to fit text else if (fitHeight > curHeight) { scope.$emit('expandable-text-area:resize') el.css('height', fitHeight) } } return scope.$watch(() => el.val(), resetHeight) }, }))
overleaf/web/frontend/js/directives/expandableTextArea.js/0
{ "file_path": "overleaf/web/frontend/js/directives/expandableTextArea.js", "repo_id": "overleaf", "token_count": 328 }
503
import PropTypes from 'prop-types' import moment from 'moment' import Message from './message' const FIVE_MINUTES = 5 * 60 * 1000 function formatTimestamp(date) { if (!date) { return 'N/A' } else { return `${moment(date).format('h:mm a')} ${moment(date).calendar()}` } } function MessageList({ messages, resetUnreadMessages, userId }) { function shouldRenderDate(messageIndex) { if (messageIndex === 0) { return true } else { const message = messages[messageIndex] const previousMessage = messages[messageIndex - 1] return message.timestamp - previousMessage.timestamp > FIVE_MINUTES } } return ( // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions <ul className="list-unstyled" onClick={resetUnreadMessages} onKeyDown={resetUnreadMessages} > {messages.map((message, index) => ( // new messages are added to the beginning of the list, so we use a reversed index <li key={message.id} className="message"> {shouldRenderDate(index) && ( <div className="date"> <time dateTime={ message.timestamp ? moment(message.timestamp).format() : undefined } > {formatTimestamp(message.timestamp)} </time> </div> )} <Message message={message} userId={userId} /> </li> ))} </ul> ) } MessageList.propTypes = { messages: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, timestamp: PropTypes.number, }) ).isRequired, resetUnreadMessages: PropTypes.func.isRequired, userId: PropTypes.string.isRequired, } export default MessageList
overleaf/web/frontend/js/features/chat/components/message-list.js/0
{ "file_path": "overleaf/web/frontend/js/features/chat/components/message-list.js", "repo_id": "overleaf", "token_count": 793 }
504
import PropTypes from 'prop-types' import { OverlayTrigger, Tooltip } from 'react-bootstrap' import classNames from 'classnames' import Icon from '../../../shared/components/icon' function PdfToggleButton({ onClick, pdfViewIsOpen }) { const classes = classNames( 'btn', 'btn-full-height', 'btn-full-height-no-border', { active: pdfViewIsOpen, } ) return ( <OverlayTrigger placement="bottom" trigger={['hover', 'focus']} overlay={<Tooltip id="tooltip-online-user">PDF</Tooltip>} > {/* eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/interactive-supports-focus */} <a role="button" className={classes} onClick={onClick}> <Icon type="file-pdf-o" modifier="fw" accessibilityLabel="PDF" /> </a> </OverlayTrigger> ) } PdfToggleButton.propTypes = { onClick: PropTypes.func.isRequired, pdfViewIsOpen: PropTypes.bool, } export default PdfToggleButton
overleaf/web/frontend/js/features/editor-navigation-toolbar/components/pdf-toggle-button.js/0
{ "file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/pdf-toggle-button.js", "repo_id": "overleaf", "token_count": 391 }
505
import { ControlLabel, FormControl, FormGroup } from 'react-bootstrap' import { useCallback, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import FileTreeCreateNameInput from '../file-tree-create-name-input' import { useFileTreeActionable } from '../../../contexts/file-tree-actionable' import { useFileTreeCreateName } from '../../../contexts/file-tree-create-name' import { useFileTreeCreateForm } from '../../../contexts/file-tree-create-form' import ErrorMessage from '../error-message' export default function FileTreeImportFromUrl() { const { t } = useTranslation() const { name, setName, validName } = useFileTreeCreateName() const { setValid } = useFileTreeCreateForm() const { finishCreatingLinkedFile, error } = useFileTreeActionable() const [url, setUrl] = useState('') const handleChange = useCallback(event => { setUrl(event.target.value) }, []) // set the name when the URL changes useEffect(() => { if (url) { const matches = url.match(/^\s*https?:\/\/.+\/([^/]+\.(\w+))\s*$/) setName(matches ? matches[1] : '') } }, [setName, url]) // form validation: URL is set and name is valid useEffect(() => { setValid(validName && !!url) }, [setValid, validName, url]) // form submission: create a linked file with this name, from this URL const handleSubmit = event => { event.preventDefault() finishCreatingLinkedFile({ name, provider: 'url', data: { url: url.trim() }, }) } return ( <form className="form-controls" id="create-file" noValidate onSubmit={handleSubmit} > <FormGroup controlId="import-from-url"> <ControlLabel>{t('url_to_fetch_the_file_from')}</ControlLabel> <FormControl type="url" placeholder="https://example.com/my-file.png" required value={url} onChange={handleChange} /> </FormGroup> <FileTreeCreateNameInput label={t('file_name_in_this_project')} placeholder="my_file" error={error} /> {error && <ErrorMessage error={error} />} </form> ) }
overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-url.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-url.js", "repo_id": "overleaf", "token_count": 830 }
506
import { Button, Modal } from 'react-bootstrap' import { useTranslation } from 'react-i18next' import AccessibleModal from '../../../../shared/components/accessible-modal' import { useFileTreeActionable } from '../../contexts/file-tree-actionable' function FileTreeModalDelete() { const { t } = useTranslation() const { isDeleting, inFlight, finishDeleting, actionedEntities, cancel, error, } = useFileTreeActionable() if (!isDeleting) return null // the modal will not be rendered; return early function handleHide() { cancel() } function handleDelete() { finishDeleting() } return ( <AccessibleModal show onHide={handleHide}> <Modal.Header> <Modal.Title>{t('delete')}</Modal.Title> </Modal.Header> <Modal.Body> <p>{t('sure_you_want_to_delete')}</p> <ul> {actionedEntities.map(entity => ( <li key={entity._id}>{entity.name}</li> ))} </ul> {error && ( <div className="alert alert-danger file-tree-modal-alert"> {t('generic_something_went_wrong')} </div> )} </Modal.Body> <Modal.Footer> {inFlight ? ( <Button bsStyle="danger" disabled> {t('deleting')}… </Button> ) : ( <> <Button onClick={handleHide}>{t('cancel')}</Button> <Button bsStyle="danger" onClick={handleDelete}> {t('delete')} </Button> </> )} </Modal.Footer> </AccessibleModal> ) } export default FileTreeModalDelete
overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-delete.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-delete.js", "repo_id": "overleaf", "token_count": 762 }
507
// The collator used to sort files docs and folders in the tree. // Uses English as base language for consistency. // Options used: // numeric: true so 10 comes after 2 // sensitivity: 'variant' so case and accent are not equal // caseFirst: 'upper' so upper-case letters come first export const fileCollator = new Intl.Collator('en', { numeric: true, sensitivity: 'variant', caseFirst: 'upper', })
overleaf/web/frontend/js/features/file-tree/util/file-collator.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/util/file-collator.js", "repo_id": "overleaf", "token_count": 112 }
508
import React, { useState, useEffect } from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import { useTranslation } from 'react-i18next' import OutlineRoot from './outline-root' import Icon from '../../../shared/components/icon' import localStorage from '../../../infrastructure/local-storage' import withErrorBoundary from '../../../infrastructure/error-boundary' import { useProjectContext } from '../../../shared/context/project-context' const OutlinePane = React.memo(function OutlinePane({ isTexFile, outline, jumpToLine, onToggle, eventTracking, highlightedLine, }) { const { t } = useTranslation() const { _id: projectId } = useProjectContext({ _id: PropTypes.string.isRequired, }) const storageKey = `file_outline.expanded.${projectId}` const [expanded, setExpanded] = useState(() => { const storedExpandedState = localStorage.getItem(storageKey) !== false return storedExpandedState }) const isOpen = isTexFile && expanded useEffect(() => { onToggle(isOpen) }, [isOpen, onToggle]) const headerClasses = classNames('outline-pane', { 'outline-pane-disabled': !isTexFile, }) function handleExpandCollapseClick() { if (isTexFile) { localStorage.setItem(storageKey, !expanded) eventTracking.sendMB(expanded ? 'outline-collapse' : 'outline-expand') setExpanded(!expanded) } } return ( <div className={headerClasses}> <header className="outline-header"> <button className="outline-header-expand-collapse-btn" disabled={!isTexFile} onClick={handleExpandCollapseClick} aria-label={expanded ? t('hide_outline') : t('show_outline')} > <Icon type={isOpen ? 'angle-down' : 'angle-right'} classes={{ icon: 'outline-caret-icon' }} /> <h4 className="outline-header-name">{t('file_outline')}</h4> </button> </header> {expanded && isTexFile ? ( <div className="outline-body"> <OutlineRoot outline={outline} jumpToLine={jumpToLine} highlightedLine={highlightedLine} /> </div> ) : null} </div> ) }) OutlinePane.propTypes = { isTexFile: PropTypes.bool.isRequired, outline: PropTypes.array.isRequired, jumpToLine: PropTypes.func.isRequired, onToggle: PropTypes.func.isRequired, eventTracking: PropTypes.object.isRequired, highlightedLine: PropTypes.number, } export default withErrorBoundary(OutlinePane)
overleaf/web/frontend/js/features/outline/components/outline-pane.js/0
{ "file_path": "overleaf/web/frontend/js/features/outline/components/outline-pane.js", "repo_id": "overleaf", "token_count": 1013 }
509
import { useState } from 'react' import { Trans, useTranslation } from 'react-i18next' import { Button } from 'react-bootstrap' import PropTypes from 'prop-types' import { useUserContext } from '../../../shared/context/user-context' import Icon from '../../../shared/components/icon' import { upgradePlan } from '../../../main/account-upgrade' import StartFreeTrialButton from '../../../shared/components/start-free-trial-button' export default function AddCollaboratorsUpgrade() { const { t } = useTranslation() const user = useUserContext({ allowedFreeTrial: PropTypes.bool, }) const [startedFreeTrial, setStartedFreeTrial] = useState(false) return ( <div className="add-collaborators-upgrade"> <p className="text-center"> <Trans i18nKey="need_to_upgrade_for_more_collabs" />. {t('also')}: </p> <ul className="list-unstyled"> <li> <Icon type="check" /> &nbsp; <Trans i18nKey="unlimited_projects" /> </li> <li> <Icon type="check" /> &nbsp; <Trans i18nKey="collabs_per_proj" values={{ collabcount: 'Multiple' }} /> </li> <li> <Icon type="check" /> &nbsp; <Trans i18nKey="full_doc_history" /> </li> <li> <Icon type="check" /> &nbsp; <Trans i18nKey="sync_to_dropbox" /> </li> <li> <Icon type="check" /> &nbsp; <Trans i18nKey="sync_to_github" /> </li> <li> <Icon type="check" /> &nbsp; <Trans i18nKey="compile_larger_projects" /> </li> </ul> <p className="text-center row-spaced-thin"> {user.allowedFreeTrial ? ( <StartFreeTrialButton buttonStyle="success" setStartedFreeTrial={setStartedFreeTrial} source="project-sharing" /> ) : ( <Button bsStyle="success" onClick={() => { upgradePlan('project-sharing') setStartedFreeTrial(true) }} > <Trans i18nKey="upgrade" /> </Button> )} </p> {startedFreeTrial && ( <p className="small"> <Trans i18nKey="refresh_page_after_starting_free_trial" /> </p> )} </div> ) }
overleaf/web/frontend/js/features/share-project-modal/components/add-collaborators-upgrade.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/add-collaborators-upgrade.js", "repo_id": "overleaf", "token_count": 1216 }
510
import { useEffect, useState } from 'react' import { getJSON } from '../../../infrastructure/fetch-json' import useAbortController from '../../../shared/hooks/use-abort-controller' const contactCollator = new Intl.Collator('en') const alphabetical = (a, b) => contactCollator.compare(a.name, b.name) || contactCollator.compare(a.email, b.email) export function useUserContacts() { const [loading, setLoading] = useState(true) const [data, setData] = useState(null) const [error, setError] = useState(false) const { signal } = useAbortController() useEffect(() => { getJSON('/user/contacts', { signal }) .then(data => { setData(data.contacts.map(buildContact).sort(alphabetical)) }) .catch(error => setError(error)) .finally(() => setLoading(false)) }, [signal]) return { loading, data, error } } function buildContact(contact) { const [emailPrefix] = contact.email.split('@') // the name is not just the default "email prefix as first name" const hasName = contact.last_name || contact.first_name !== emailPrefix const name = hasName ? [contact.first_name, contact.last_name].filter(Boolean).join(' ') : '' return { ...contact, name, display: name ? `${name} <${contact.email}>` : contact.email, } }
overleaf/web/frontend/js/features/share-project-modal/hooks/use-user-contacts.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/hooks/use-user-contacts.js", "repo_id": "overleaf", "token_count": 459 }
511
import { Row, Col, Modal, Grid, Alert, Button } from 'react-bootstrap' import PropTypes from 'prop-types' import { useTranslation } from 'react-i18next' import Icon from '../../../shared/components/icon' import AccessibleModal from '../../../shared/components/accessible-modal' export default function WordCountModalContent({ animation = true, show, data, error, handleHide, loading, }) { const { t } = useTranslation() return ( <AccessibleModal animation={animation} show={show} onHide={handleHide} id="clone-project-modal" > <Modal.Header closeButton> <Modal.Title>{t('word_count')}</Modal.Title> </Modal.Header> <Modal.Body> {loading && !error && ( <div className="loading"> <Icon type="refresh" spin modifier="fw" /> &nbsp; {t('loading')}… </div> )} {error && ( <Alert bsStyle="danger">{t('generic_something_went_wrong')}</Alert> )} {data && ( <Grid fluid> {data.messages && ( <Row> <Col xs={12}> <Alert bsStyle="danger"> <p style={{ whiteSpace: 'pre-wrap' }}>{data.messages}</p> </Alert> </Col> </Row> )} <Row> <Col xs={4}> <div className="pull-right">{t('total_words')}:</div> </Col> <Col xs={6}>{data.textWords}</Col> </Row> <Row> <Col xs={4}> <div className="pull-right">{t('headers')}:</div> </Col> <Col xs={6}>{data.headers}</Col> </Row> <Row> <Col xs={4}> <div className="pull-right">{t('math_inline')}:</div> </Col> <Col xs={6}>{data.mathInline}</Col> </Row> <Row> <Col xs={4}> <div className="pull-right">{t('math_display')}:</div> </Col> <Col xs={6}>{data.mathDisplay}</Col> </Row> </Grid> )} </Modal.Body> <Modal.Footer> <Button onClick={handleHide}>{t('done')}</Button> </Modal.Footer> </AccessibleModal> ) } WordCountModalContent.propTypes = { animation: PropTypes.bool, show: PropTypes.bool.isRequired, handleHide: PropTypes.func.isRequired, loading: PropTypes.bool.isRequired, error: PropTypes.bool, data: PropTypes.shape({ messages: PropTypes.string, headers: PropTypes.number, mathDisplay: PropTypes.number, mathInline: PropTypes.number, textWords: PropTypes.number, }), }
overleaf/web/frontend/js/features/word-count-modal/components/word-count-modal-content.js/0
{ "file_path": "overleaf/web/frontend/js/features/word-count-modal/components/word-count-modal-content.js", "repo_id": "overleaf", "token_count": 1424 }
512
/* 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' const _cobrandingData = window.brandVariation export default App.factory('CobrandingDataService', function () { const isProjectCobranded = () => _cobrandingData != null const getLogoImgUrl = () => _cobrandingData != null ? _cobrandingData.logo_url : undefined const getSubmitBtnHtml = () => _cobrandingData != null ? _cobrandingData.submit_button_html : undefined const getBrandVariationName = () => _cobrandingData != null ? _cobrandingData.name : undefined const getBrandVariationHomeUrl = () => _cobrandingData != null ? _cobrandingData.home_url : undefined const getPublishGuideHtml = () => _cobrandingData != null ? _cobrandingData.publish_guide_html : undefined const getPartner = () => _cobrandingData != null ? _cobrandingData.partner : undefined const hasBrandedMenu = () => _cobrandingData != null ? _cobrandingData.branded_menu : undefined const getBrandId = () => _cobrandingData != null ? _cobrandingData.brand_id : undefined const getBrandVariationId = () => _cobrandingData != null ? _cobrandingData.id : undefined return { isProjectCobranded, getLogoImgUrl, getSubmitBtnHtml, getBrandVariationName, getBrandVariationHomeUrl, getPublishGuideHtml, getPartner, hasBrandedMenu, getBrandId, getBrandVariationId, } })
overleaf/web/frontend/js/ide/cobranding/CobrandingDataService.js/0
{ "file_path": "overleaf/web/frontend/js/ide/cobranding/CobrandingDataService.js", "repo_id": "overleaf", "token_count": 624 }
513
import _ from 'lodash' import CommandManager from './CommandManager' import EnvironmentManager from './EnvironmentManager' import PackageManager from './PackageManager' import Helpers from './Helpers' import 'ace/ace' import 'ace/ext-language_tools' const { Range } = ace.require('ace/range') const aceSnippetManager = ace.require('ace/snippets').snippetManager class AutoCompleteManager { constructor( $scope, editor, element, metadataManager, graphics, preamble, files ) { this.$scope = $scope this.editor = editor this.element = element this.metadataManager = metadataManager this.graphics = graphics this.preamble = preamble this.files = files this.monkeyPatchAutocomplete() this.$scope.$watch('autoComplete', autocomplete => { if (autocomplete) { this.enable() } else { this.disable() } }) const onChange = change => { this.onChange(change) } this.editor.on('changeSession', e => { e.oldSession.off('change', onChange) e.session.on('change', onChange) }) } enable() { this.editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: false, }) const CommandCompleter = new CommandManager(this.metadataManager) const SnippetCompleter = new EnvironmentManager() const PackageCompleter = new PackageManager(this.metadataManager, Helpers) const Graphics = this.graphics const Preamble = this.preamble const Files = this.files const GraphicsCompleter = { getCompletions(editor, session, pos, prefix, callback) { const { commandFragment } = Helpers.getContext(editor, pos) if (commandFragment) { const match = commandFragment.match( /^~?\\(includegraphics(?:\[.*])?){([^}]*, *)?(\w*)/ ) if (match) { // eslint-disable-next-line no-unused-vars const commandName = match[1] const graphicsPaths = Preamble.getGraphicsPaths() const result = [] for (const graphic of Graphics.getGraphicsFiles()) { let { path } = graphic for (const graphicsPath of graphicsPaths) { if (path.indexOf(graphicsPath) === 0) { path = path.slice(graphicsPath.length) break } } result.push({ caption: `\\${commandName}{${path}}`, value: `\\${commandName}{${path}}`, meta: 'graphic', score: 50, }) } callback(null, result) } } }, } const { metadataManager } = this const FilesCompleter = { getCompletions: (editor, session, pos, prefix, callback) => { const { commandFragment } = Helpers.getContext(editor, pos) if (commandFragment) { const match = commandFragment.match(/^\\(input|include){(\w*)/) if (match) { // eslint-disable-next-line no-unused-vars const commandName = match[1] const result = [] for (const file of Files.getTeXFiles()) { if (file.id !== this.$scope.docId && !file.deleted && file.path) { const { path } = file const cleanPath = path.replace(/(.+)\.tex$/i, '$1') result.push({ caption: `\\${commandName}{${path}}`, value: `\\${commandName}{${cleanPath}}`, meta: 'file', score: 50, }) } } callback(null, result) } } }, } const LabelsCompleter = { getCompletions(editor, session, pos, prefix, callback) { const { commandFragment } = Helpers.getContext(editor, pos) if (commandFragment) { const refMatch = commandFragment.match( /^~?\\([a-zA-Z]*ref){([^}]*, *)?(\w*)/ ) if (refMatch) { // eslint-disable-next-line no-unused-vars const commandName = refMatch[1] const result = [] if (commandName !== 'ref') { // ref is in top 100 commands result.push({ caption: `\\${commandName}{}`, snippet: `\\${commandName}{}`, meta: 'cross-reference', score: 60, }) } for (const label of metadataManager.getAllLabels()) { result.push({ caption: `\\${commandName}{${label}}`, value: `\\${commandName}{${label}}`, meta: 'cross-reference', score: 50, }) } callback(null, result) } } }, } const references = this.$scope.$root._references const ReferencesCompleter = { getCompletions(editor, session, pos, prefix, callback) { const { commandFragment } = Helpers.getContext(editor, pos) if (commandFragment) { const citeMatch = commandFragment.match( /^~?\\([a-z]*cite[a-z]*(?:\[.*])?){([^}]*, *)?(\w*)/ ) if (citeMatch) { // eslint-disable-next-line no-unused-vars let [_ignore, commandName, previousArgs] = citeMatch if (previousArgs == null) { previousArgs = '' } const previousArgsCaption = previousArgs.length > 8 ? '…,' : previousArgs const result = [] result.push({ caption: `\\${commandName}{}`, snippet: `\\${commandName}{}`, meta: 'reference', score: 60, }) if (references.keys && references.keys.length > 0) { references.keys.forEach(function (key) { if (key != null) { result.push({ caption: `\\${commandName}{${previousArgsCaption}${key}}`, value: `\\${commandName}{${previousArgs}${key}}`, meta: 'reference', score: 50, }) } }) callback(null, result) } else { callback(null, result) } } } }, } this.editor.completers = [ CommandCompleter, SnippetCompleter, PackageCompleter, ReferencesCompleter, LabelsCompleter, GraphicsCompleter, FilesCompleter, ] } disable() { return this.editor.setOptions({ enableBasicAutocompletion: false, enableSnippets: false, }) } onChange(change) { let i const cursorPosition = this.editor.getCursorPosition() const { end } = change const { lineUpToCursor, commandFragment } = Helpers.getContext( this.editor, end ) if ( (i = lineUpToCursor.indexOf('%')) > -1 && lineUpToCursor[i - 1] !== '\\' ) { return } const lastCharIsBackslash = lineUpToCursor.slice(-1) === '\\' const lastTwoChars = lineUpToCursor.slice(-2) // Don't offer autocomplete on double-backslash, backslash-colon, etc if (/^\\[^a-zA-Z]$/.test(lastTwoChars)) { if (this.editor.completer) { this.editor.completer.detach() } return } // Check that this change was made by us, not a collaborator // (Cursor is still one place behind) // NOTE: this is also the case when a user backspaces over a highlighted // region if ( change.origin !== 'remote' && change.action === 'insert' && end.row === cursorPosition.row && end.column === cursorPosition.column + 1 ) { if ( (commandFragment != null ? commandFragment.length : undefined) > 2 || lastCharIsBackslash ) { setTimeout(() => { this.editor.execCommand('startAutocomplete') }, 0) } } const match = change.lines[0].match(/\\(\w+){}/) if ( change.action === 'insert' && match && match[1] && // eslint-disable-next-line max-len /(begin|end|[a-zA-Z]*ref|usepackage|[a-z]*cite[a-z]*|input|include)/.test( match[1] ) ) { return setTimeout(() => { this.editor.execCommand('startAutocomplete') }, 0) } } monkeyPatchAutocomplete() { const { Autocomplete } = ace.require('ace/autocomplete') const Util = ace.require('ace/autocomplete/util') if (Autocomplete.prototype._insertMatch == null) { // Only override this once since it's global but we may create multiple // autocomplete handlers Autocomplete.prototype._insertMatch = Autocomplete.prototype.insertMatch Autocomplete.prototype.insertMatch = function (data) { const { editor } = this const pos = editor.getCursorPosition() let range = new Range(pos.row, pos.column, pos.row, pos.column + 1) const nextChar = editor.session.getTextRange(range) // If we are in \begin{it|}, then we need to remove the trailing } // since it will be adding in with the autocomplete of \begin{item}... if ( /^\\\w+(\[[\w\\,=. ]*\])?{/.test(this.completions.filterText) && nextChar === '}' ) { editor.session.remove(range) } // Provide our own `insertMatch` implementation. // See the `insertMatch` method of Autocomplete in // `ext-language_tools.js`. // We need this to account for editing existing commands, particularly // when adding a prefix. // We fix this by detecting when the cursor is in the middle of an // existing command, and adjusting the insertions/deletions // accordingly. // Example: // when changing `\ref{}` to `\href{}`, ace default behaviour // is likely to end up with `\href{}ref{}` if (data == null) { const { completions } = this const { popup } = this data = popup.getData(popup.getRow()) data.completer = { insertMatch(editor, matchData) { for (range of editor.selection.getAllRanges()) { const leftRange = _.clone(range) const rightRange = _.clone(range) // trim to left of cursor const lineUpToCursor = editor .getSession() .getTextRange( new Range( range.start.row, 0, range.start.row, range.start.column ) ) // Delete back to command start, as appropriate const commandStartIndex = Helpers.getLastCommandFragmentIndex( lineUpToCursor ) if (commandStartIndex !== -1) { leftRange.start.column = commandStartIndex } else { leftRange.start.column -= completions.filterText.length } editor.session.remove(leftRange) // look at text after cursor const lineBeyondCursor = editor .getSession() .getTextRange( new Range( rightRange.start.row, rightRange.start.column, rightRange.end.row, 99999 ) ) if (lineBeyondCursor) { const partialCommandMatch = lineBeyondCursor.match( /^([a-zA-Z0-9]+)\{/ ) if (partialCommandMatch) { // We've got a partial command after the cursor const commandTail = partialCommandMatch[1] // remove rest of the partial command, right of cursor rightRange.end.column += commandTail.length - completions.filterText.length editor.session.remove(rightRange) // trim the completion text to just the command, without // braces or brackets // example: '\cite{}' -> '\cite' if (matchData.snippet != null) { matchData.snippet = matchData.snippet.replace( /[{[].*[}\]]/, '' ) } if (matchData.caption != null) { matchData.caption = matchData.caption.replace( /[{[].*[}\]]/, '' ) } if (matchData.value != null) { matchData.value = matchData.value.replace( /[{[].*[}\]]/, '' ) } } const inArgument = lineBeyondCursor.match(/^([\w._-]+)\}(.*)/) if (inArgument) { const argumentRightOfCursor = inArgument[1] const afterArgument = inArgument[2] if (afterArgument) { rightRange.end.column = rightRange.start.column + argumentRightOfCursor.length + 1 } editor.session.remove(rightRange) } } } // finally, insert the match if (matchData.snippet) { aceSnippetManager.insertSnippet(editor, matchData.snippet) } else { editor.execCommand('insertstring', matchData.value || matchData) } }, } } Autocomplete.prototype._insertMatch.call(this, data) } // Overwrite this to set autoInsert = false and set font size Autocomplete.startCommand = { name: 'startAutocomplete', exec: editor => { if (!editor.completer) { editor.completer = new Autocomplete() } editor.completer.autoInsert = false editor.completer.autoSelect = true editor.completer.showPopup(editor) editor.completer.cancelContextMenu() const container = $( editor.completer.popup != null ? editor.completer.popup.container : undefined ) container.css({ 'font-size': this.$scope.fontSize + 'px' }) // Dynamically set width of autocomplete popup const filtered = editor.completer.completions && editor.completer.completions.filtered if (filtered) { const longestCaption = _.max(filtered.map(c => c.caption.length)) const longestMeta = _.max(filtered.map(c => c.meta.length)) const charWidth = editor.renderer.characterWidth // between 280 and 700 px const width = Math.max( Math.min( Math.round( longestCaption * charWidth + longestMeta * charWidth + 5 * charWidth ), 700 ), 280 ) container.css({ width: `${width}px` }) } if (filtered.length === 0) { editor.completer.detach() } }, bindKey: 'Ctrl-Space|Ctrl-Shift-Space|Alt-Space', } } Util.retrievePrecedingIdentifier = function (text, pos, regex) { let currentLineOffset = 0 for (let i = pos - 1; i <= 0; i++) { if (text[i] === '\n') { currentLineOffset = i + 1 break } } const currentLine = text.slice(currentLineOffset, pos) const fragment = Helpers.getLastCommandFragment(currentLine) || '' return fragment } } } export default AutoCompleteManager
overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager.js", "repo_id": "overleaf", "token_count": 8252 }
514
import 'ace/ace' const BuiltInUndoManager = ace.require('ace/undomanager').UndoManager class UndoManager { constructor(editor) { this.editor = editor this.onChangeSession = this.onChangeSession.bind(this) this.onChange = this.onChange.bind(this) } onChangeSession(session) { session.setUndoManager(new BuiltInUndoManager()) } onChange(change) { if (change.origin !== 'remote') return // HACK: remote changes in Ace are added by the ShareJS/Ace adapter // asynchronously via a timeout (see attach_ace function). This makes it // impossible to clear to undo stack when remote changes are received. // To hack around this we queue the undo stack clear so that it applies // after the change is applied setTimeout(() => { this.editor.getSession().getUndoManager().reset() }) } } export default UndoManager
overleaf/web/frontend/js/ide/editor/directives/aceEditor/undo/UndoManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/undo/UndoManager.js", "repo_id": "overleaf", "token_count": 281 }
515
/* 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 App from '../../../base' import iconTypeFromName from '../../file-tree/util/iconTypeFromName' import fileOperationI18nNames from '../../file-tree/util/fileOperationI18nNames' const historyFileEntityController = function ($scope, $element, $attrs) { const ctrl = this ctrl.hasOperation = false ctrl.getRenameTooltip = i18nRenamedStr => { const [simplifiedOldPathname, simplifiedPathname] = _getSimplifiedPaths( ctrl.fileEntity.oldPathname, ctrl.fileEntity.pathname ) return `${fileOperationI18nNames.renamed} <strong>${simplifiedOldPathname}</strong> &rarr; <strong>${simplifiedPathname}</strong>` } ctrl.getFileOperationName = () => { if (ctrl.fileEntity.operation === 'edited') { return fileOperationI18nNames.edited } else if (ctrl.fileEntity.operation === 'renamed') { return fileOperationI18nNames.renamed } else if (ctrl.fileEntity.operation === 'added') { return fileOperationI18nNames.created } else if (ctrl.fileEntity.operation === 'removed') { return fileOperationI18nNames.deleted } else { return '' } } const _getSimplifiedPaths = (path1, path2) => { const path1Parts = path1.split('/') const path2Parts = path2.split('/') const maxIterations = Math.min(path1Parts.length, path2Parts.length) - 1 for ( var commonPartIndex = 0; commonPartIndex < maxIterations; commonPartIndex++ ) { if (path1Parts[commonPartIndex] !== path2Parts[commonPartIndex]) { break } } path1Parts.splice(0, commonPartIndex) path2Parts.splice(0, commonPartIndex) return [path1Parts.join('/'), path2Parts.join('/')] } const _handleFolderClick = function () { ctrl.isOpen = !ctrl.isOpen ctrl.entityTypeIconClass = _getFolderIcon() } const _handleFileClick = () => ctrl.historyFileTreeController.handleEntityClick(ctrl.fileEntity) var _getFolderIcon = function () { if (ctrl.isOpen) { return 'fa-folder-open' } else { return 'fa-folder' } } ctrl.$onInit = function () { if (ctrl.fileEntity.type === 'folder') { ctrl.isOpen = true ctrl.entityTypeIconClass = _getFolderIcon() ctrl.handleClick = _handleFolderClick } else { if (ctrl.fileEntity.operation) { ctrl.hasOperation = true } ctrl.entityTypeIconClass = `fa-${iconTypeFromName(ctrl.fileEntity.name)}` ctrl.entityOpTextClass = ctrl.fileEntity.operation ? `history-file-entity-name-${ctrl.fileEntity.operation}` : null ctrl.handleClick = _handleFileClick $scope.$watch( () => ctrl.historyFileTreeController.selectedPathname, selectedPathname => (ctrl.isSelected = ctrl.fileEntity.pathname === selectedPathname) ) } } } export default App.component('historyFileEntity', { require: { historyFileTreeController: '^historyFileTree', }, bindings: { fileEntity: '<', }, controller: historyFileEntityController, templateUrl: 'historyFileEntityTpl', })
overleaf/web/frontend/js/ide/history/components/historyFileEntity.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/components/historyFileEntity.js", "repo_id": "overleaf", "token_count": 1280 }
516
/* 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 */ const rx = /INPUT|SELECT|TEXTAREA/i export default $(document).bind('keydown keypress', function (e) { if (e.which === 8) { // 8 == backspace if (!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly) { return e.preventDefault() } } })
overleaf/web/frontend/js/ide/hotkeys/BackspaceHighjack.js/0
{ "file_path": "overleaf/web/frontend/js/ide/hotkeys/BackspaceHighjack.js", "repo_id": "overleaf", "token_count": 210 }
517
/* eslint-disable max-len, new-cap, 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 * 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 */ import App from '../../../base' export default App.directive( 'pdfPage', ($timeout, pdfHighlights, pdfSpinner) => ({ require: '^pdfViewer', template: `\ <div class="plv-page-view page-view"> <div class="pdf-canvas pdfng-empty"></div> <div class="plv-text-layer text-layer"></div> <div class="plv-annotations-layer annotations-layer"></div> <div class="plv-highlights-layer highlights-layer"></div> </div>\ `, link(scope, element, attrs, ctrl) { const canvasElement = $(element).find('.pdf-canvas') const textElement = $(element).find('.text-layer') const annotationsElement = $(element).find('.annotations-layer') const highlightsElement = $(element).find('.highlights-layer') const updatePageSize = function (size) { const h = Math.floor(size[0]) const w = Math.floor(size[1]) element.height(h) element.width(w) canvasElement.height(h) canvasElement.width(w) return (scope.page.sized = true) } // keep track of our page element, so we can access it in the // parent with scope.pages[i].element, and the contained // elements for each part scope.page.element = element scope.page.elementChildren = { canvas: canvasElement, text: textElement, annotations: annotationsElement, highlights: highlightsElement, container: element, } if (!scope.page.sized) { if (scope.defaultPageSize != null) { updatePageSize(scope.defaultPageSize) } else { // shouldn't get here - the default page size should now // always be set before redraw is called var handler = scope.$watch( 'defaultPageSize', function (defaultPageSize) { if (defaultPageSize == null) { return } updatePageSize(defaultPageSize) return handler() } ) } } if (scope.page.current) { // console.log 'we must scroll to this page', scope.page.pageNum, 'at position', scope.page.position // this is the current page, we want to scroll it into view // and render it immediately scope.document.renderPage(scope.page) ctrl.setPdfPosition(scope.page, scope.page.position) } element.on('dblclick', function (e) { const offset = $(element).find('.pdf-canvas').offset() const dx = e.pageX - offset.left const dy = e.pageY - offset.top return scope.document .getPdfViewport(scope.page.pageNum) .then(function (viewport) { const pdfPoint = viewport.convertToPdfPoint(dx, dy) const event = { page: scope.page.pageNum, x: pdfPoint[0], y: viewport.viewBox[3] - pdfPoint[1], } return scope.$emit('pdfDoubleClick', event) }) }) const highlightsLayer = new pdfHighlights({ highlights: highlightsElement, }) scope.$on('pdf:highlights', function (event, highlights) { let h if (highlights == null) { return } if (!(highlights.length > 0)) { return } if (scope.timeoutHandler) { $timeout.cancel(scope.timeoutHandler) highlightsLayer.clearHighlights() scope.timeoutHandler = null } // console.log 'got highlight watch in pdfPage', scope.page const pageHighlights = (() => { const result = [] for (h of Array.from(highlights)) { if (h.page === scope.page.pageNum) { result.push(h) } } return result })() if (!pageHighlights.length) { return } scope.document.getPdfViewport(scope.page.pageNum).then(viewport => (() => { const result1 = [] for (const hl of Array.from(pageHighlights)) { // console.log 'adding highlight', h, viewport const top = viewport.viewBox[3] - hl.v result1.push( highlightsLayer.addHighlight( viewport, hl.h, top, hl.width, hl.height ) ) } return result1 })() ) return (scope.timeoutHandler = $timeout(function () { highlightsLayer.clearHighlights() return (scope.timeoutHandler = null) }, 1000)) }) return scope.$on('$destroy', function () { if (scope.timeoutHandler != null) { $timeout.cancel(scope.timeoutHandler) return highlightsLayer.clearHighlights() } }) }, }) )
overleaf/web/frontend/js/ide/pdfng/directives/pdfPage.js/0
{ "file_path": "overleaf/web/frontend/js/ide/pdfng/directives/pdfPage.js", "repo_id": "overleaf", "token_count": 2419 }
518
import '../../features/word-count-modal/controllers/word-count-modal-controller'
overleaf/web/frontend/js/ide/wordcount/index.js/0
{ "file_path": "overleaf/web/frontend/js/ide/wordcount/index.js", "repo_id": "overleaf", "token_count": 26 }
519
import _ from 'lodash' /* eslint-disable max-len, no-return-assign, no-useless-escape, */ import App from '../../../base' import getMeta from '../../../utils/meta' export default App.controller( 'UserAffiliationsController', function ($scope, $rootScope, UserAffiliationsDataService, $q, $window) { $scope.userEmails = [] $scope.linkedInstitutionIds = [] $scope.hideInstitutionNotifications = {} $scope.closeInstitutionNotification = type => { $scope.hideInstitutionNotifications[type] = true } $scope.samlBetaSession = ExposedSettings.hasSamlBeta $scope.samlInitPath = ExposedSettings.samlInitPath $scope.reconfirmationRemoveEmail = getMeta('ol-reconfirmationRemoveEmail') $scope.reconfirmedViaSAML = getMeta('ol-reconfirmedViaSAML') const LOCAL_AND_DOMAIN_REGEX = /([^@]+)@(.+)/ const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ const _matchLocalAndDomain = function (userEmailInput) { const match = userEmailInput ? userEmailInput.match(LOCAL_AND_DOMAIN_REGEX) : undefined if (match) { return { local: match[1], domain: match[2] } } else { return { local: null, domain: null } } } const _ssoAvailableForAffiliation = affiliation => { if (!affiliation) return false const institution = affiliation.institution if (!_ssoAvailableForInstitution(institution)) return false if (!institution.confirmed) return false // domain is confirmed, not the email return true } const _ssoAvailableForDomain = domain => { if (!domain) return false if (!domain.confirmed) return false // domain is confirmed, not the email const institution = domain.university if (!_ssoAvailableForInstitution(institution)) return false return true } const _ssoAvailableForInstitution = institution => { if (!ExposedSettings.hasSamlFeature) return false if (!institution) return false if (institution.ssoEnabled) return true if ($scope.samlBetaSession && institution.ssoBeta) return true return false } $scope.getEmailSuggestion = function (userInput) { const userInputLocalAndDomain = _matchLocalAndDomain(userInput) $scope.ui.isValidEmail = EMAIL_REGEX.test(userInput) $scope.ui.isBlacklistedEmail = false $scope.ui.showManualUniversitySelectionUI = false if (userInputLocalAndDomain.domain) { $scope.ui.isBlacklistedEmail = UserAffiliationsDataService.isDomainBlacklisted( userInputLocalAndDomain.domain ) return UserAffiliationsDataService.getUniversityDomainFromPartialDomainInput( userInputLocalAndDomain.domain ) .then(function (universityDomain) { const currentUserInputLocalAndDomain = _matchLocalAndDomain( $scope.newAffiliation.email ) if ( currentUserInputLocalAndDomain.domain === universityDomain.hostname ) { $scope.newAffiliation.university = universityDomain.university $scope.newAffiliation.department = universityDomain.department $scope.newAffiliation.ssoAvailable = _ssoAvailableForDomain( universityDomain ) } else { _resetAffiliationSuggestion() } return $q.resolve( `${userInputLocalAndDomain.local}@${universityDomain.hostname}` ) }) .catch(function () { _resetAffiliationSuggestion() return $q.reject(null) }) } else { _resetAffiliationSuggestion() return $q.reject(null) } } $scope.linkInstitutionAcct = function (email, institutionId) { _resetMakingRequestType() $scope.ui.isMakingRequest = true $scope.ui.isProcessing = true $window.location.href = `${$scope.samlInitPath}?university_id=${institutionId}&auto=/user/settings&email=${email}` } $scope.selectUniversityManually = function () { _resetAffiliationSuggestion() $scope.ui.showManualUniversitySelectionUI = true } $scope.changeAffiliation = function (userEmail) { if (_.get(userEmail, ['affiliation', 'institution', 'id'])) { UserAffiliationsDataService.getUniversityDetails( userEmail.affiliation.institution.id ).then( universityDetails => ($scope.affiliationToChange.university = universityDetails) ) } $scope.affiliationToChange.email = userEmail.email $scope.affiliationToChange.role = userEmail.affiliation.role $scope.affiliationToChange.department = userEmail.affiliation.department } $scope.saveAffiliationChange = function (userEmail) { userEmail.affiliation.role = $scope.affiliationToChange.role userEmail.affiliation.department = $scope.affiliationToChange.department _resetAffiliationToChange() return _monitorRequest( UserAffiliationsDataService.addRoleAndDepartment( userEmail.email, userEmail.affiliation.role, userEmail.affiliation.department ) ).then(() => setTimeout(() => _getUserEmails())) } $scope.cancelAffiliationChange = email => _resetAffiliationToChange() $scope.isChangingAffiliation = email => $scope.affiliationToChange.email === email $scope.showAddEmailForm = () => ($scope.ui.showAddEmailUI = true) $scope.addNewEmail = function () { let addEmailPromise if (!$scope.newAffiliation.university) { addEmailPromise = UserAffiliationsDataService.addUserEmail( $scope.newAffiliation.email ) } else { if ($scope.newAffiliation.university.isUserSuggested) { addEmailPromise = UserAffiliationsDataService.addUserAffiliationWithUnknownUniversity( $scope.newAffiliation.email, $scope.newAffiliation.university.name, $scope.newAffiliation.country.code, $scope.newAffiliation.role, $scope.newAffiliation.department ) } else { addEmailPromise = UserAffiliationsDataService.addUserAffiliation( $scope.newAffiliation.email, $scope.newAffiliation.university.id, $scope.newAffiliation.role, $scope.newAffiliation.department ) } } $scope.ui.isAddingNewEmail = true $scope.ui.showAddEmailUI = false return _monitorRequest(addEmailPromise) .then(function () { _resetNewAffiliation() _resetAddingEmail() setTimeout(() => _getUserEmails()) }) .finally(() => ($scope.ui.isAddingNewEmail = false)) } $scope.setDefaultUserEmail = userEmail => _monitorRequest( UserAffiliationsDataService.setDefaultUserEmail(userEmail.email) ).then(function () { for (const email of $scope.userEmails || []) { email.default = false } userEmail.default = true window.usersEmail = userEmail.email $rootScope.usersEmail = userEmail.email }) $scope.removeUserEmail = function (userEmail) { $scope.userEmails = $scope.userEmails.filter(ue => ue !== userEmail) return _monitorRequest( UserAffiliationsDataService.removeUserEmail(userEmail.email) ) } $scope.resendConfirmationEmail = function (userEmail) { _resetMakingRequestType() $scope.ui.isResendingConfirmation = true return _monitorRequest( UserAffiliationsDataService.resendConfirmationEmail(userEmail.email) ).finally(() => ($scope.ui.isResendingConfirmation = false)) } $scope.acknowledgeError = function () { _reset() return _getUserEmails() } var _resetAffiliationToChange = () => ($scope.affiliationToChange = { email: '', university: null, role: null, department: null, }) var _resetNewAffiliation = () => ($scope.newAffiliation = { email: '', country: null, university: null, role: null, department: null, }) var _resetAddingEmail = function () { $scope.ui.showAddEmailUI = false $scope.ui.isValidEmail = false $scope.ui.isBlacklistedEmail = false $scope.ui.showManualUniversitySelectionUI = false } var _resetAffiliationSuggestion = () => { $scope.newAffiliation = { email: $scope.newAffiliation.email, } } var _resetMakingRequestType = function () { $scope.ui.isLoadingEmails = false $scope.ui.isProcessing = false $scope.ui.isResendingConfirmation = false } var _reset = function () { $scope.ui = { hasError: false, errorMessage: '', showChangeAffiliationUI: false, isMakingRequest: false, isLoadingEmails: false, isAddingNewEmail: false, } _resetAffiliationToChange() _resetNewAffiliation() return _resetAddingEmail() } _reset() var _monitorRequest = function (promise) { $scope.ui.hasError = false $scope.ui.isMakingRequest = true promise .catch(function (response) { $scope.ui.hasError = true $scope.ui.errorMessage = _.get(response, ['data', 'message']) }) .finally(() => ($scope.ui.isMakingRequest = false)) return promise } $scope.inReconfirmNotificationPeriod = function (emailData) { return _.get(emailData, ['affiliation', 'inReconfirmNotificationPeriod']) } $scope.institutionAlreadyLinked = function (emailData) { const institutionId = emailData.affiliation && emailData.affiliation.institution && emailData.affiliation.institution && emailData.affiliation.institution.id ? emailData.affiliation.institution.id.toString() : undefined return $scope.linkedInstitutionIds.indexOf(institutionId) !== -1 } // Populates the emails table var _getUserEmails = function () { _resetMakingRequestType() $scope.ui.isLoadingEmails = true _monitorRequest( UserAffiliationsDataService.getUserEmailsEnsureAffiliation() ) .then(emails => { $scope.userEmails = emails.map(email => { email.ssoAvailable = _ssoAvailableForAffiliation(email.affiliation) return email }) $scope.linkedInstitutionIds = emails .filter(email => { return !!email.samlProviderId }) .map(email => email.samlProviderId) }) .finally(() => ($scope.ui.isLoadingEmails = false)) } _getUserEmails() } )
overleaf/web/frontend/js/main/affiliations/controllers/UserAffiliationsController.js/0
{ "file_path": "overleaf/web/frontend/js/main/affiliations/controllers/UserAffiliationsController.js", "repo_id": "overleaf", "token_count": 4589 }
520
import App from '../../base' export default App.controller( 'LeftHandMenuPromoController', function ($scope, UserAffiliationsDataService, eventTracking) { $scope.hasProjects = window.data.projects.length > 0 $scope.userHasNoSubscription = window.userHasNoSubscription $scope.upgradeSubscription = function () { eventTracking.send('subscription-funnel', 'project-page', 'upgrade') } $scope.share = function () { eventTracking.send('subscription-funnel', 'project-page', 'sharing') } const _userHasNoAffiliation = function () { $scope.withAffiliations = window.data.userAffiliations.length > 0 $scope.userOnPayingUniversity = window.data.userAffiliations.some( affiliation => affiliation.licence && affiliation.licence !== 'free' ) } _userHasNoAffiliation() } )
overleaf/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js/0
{ "file_path": "overleaf/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js", "repo_id": "overleaf", "token_count": 294 }
521
angular.module('localStorage', []).value('localStorage', localStorage) /* localStorage can throw browser exceptions, for example if it is full We don't use localStorage for anything critical, on in that case just fail gracefully. */ function localStorage(...args) { try { return $.localStorage(...args) } catch (e) { console.error('localStorage exception', e) return null } } export default localStorage
overleaf/web/frontend/js/modules/localStorage.js/0
{ "file_path": "overleaf/web/frontend/js/modules/localStorage.js", "repo_id": "overleaf", "token_count": 126 }
522
import { useCallback, useEffect } from 'react' import { useTranslation } from 'react-i18next' import { Button } from 'react-bootstrap' import PropTypes from 'prop-types' import * as eventTracking from '../../infrastructure/event-tracking' export default function StartFreeTrialButton({ buttonStyle = 'info', children, classes = {}, setStartedFreeTrial, source, }) { const { t } = useTranslation() useEffect(() => { eventTracking.sendMB(`${source}-paywall-prompt`) }, [source]) const handleClick = useCallback( event => { event.preventDefault() eventTracking.send('subscription-funnel', 'upgraded-free-trial', source) eventTracking.sendMB(`${source}-paywall-click`) if (setStartedFreeTrial) { setStartedFreeTrial(true) } const params = new URLSearchParams({ planCode: 'collaborator_free_trial_7_days', ssp: 'true', itm_campaign: source, }) window.open(`/user/subscription/new?${params}`) }, [setStartedFreeTrial, source] ) return ( <Button bsStyle={buttonStyle} onClick={handleClick} className={classes.button} > {children || t('start_free_trial')} </Button> ) } StartFreeTrialButton.propTypes = { buttonStyle: PropTypes.string, children: PropTypes.any, classes: PropTypes.shape({ button: PropTypes.string.isRequired, }), setStartedFreeTrial: PropTypes.func, source: PropTypes.string.isRequired, }
overleaf/web/frontend/js/shared/components/start-free-trial-button.js/0
{ "file_path": "overleaf/web/frontend/js/shared/components/start-free-trial-button.js", "repo_id": "overleaf", "token_count": 569 }
523
import { useEffect, useRef } from 'react' export default function useIsMounted() { const isMounted = useRef(true) useEffect(() => { return () => { isMounted.current = false } }, [isMounted]) return isMounted }
overleaf/web/frontend/js/shared/hooks/use-is-mounted.js/0
{ "file_path": "overleaf/web/frontend/js/shared/hooks/use-is-mounted.js", "repo_id": "overleaf", "token_count": 86 }
524
// Generated by CoffeeScript 1.10.0 define(function() { var HBOX_WARNING_REGEX, LATEX_WARNING_REGEX, LINES_REGEX, LOG_WRAP_LIMIT, LatexParser, LogText, PACKAGE_REGEX, PACKAGE_WARNING_REGEX, state; LOG_WRAP_LIMIT = 79; LATEX_WARNING_REGEX = /^LaTeX Warning: (.*)$/; HBOX_WARNING_REGEX = /^(Over|Under)full \\(v|h)box/; PACKAGE_WARNING_REGEX = /^(Package \b.+\b Warning:.*)$/; LINES_REGEX = /lines? ([0-9]+)/; PACKAGE_REGEX = /^Package (\b.+\b) Warning/; LogText = function(text) { var i, wrappedLines; this.text = text.replace(/(\r\n)|\r/g, '\n'); wrappedLines = this.text.split('\n'); this.lines = [wrappedLines[0]]; i = 1; while (i < wrappedLines.length) { if (wrappedLines[i - 1].length === LOG_WRAP_LIMIT && wrappedLines[i - 1].slice(-3) !== '...') { this.lines[this.lines.length - 1] += wrappedLines[i]; } else { this.lines.push(wrappedLines[i]); } i++; } this.row = 0; }; (function() { this.nextLine = function() { this.row++; if (this.row >= this.lines.length) { return false; } else { return this.lines[this.row]; } }; this.rewindLine = function() { this.row--; }; this.linesUpToNextWhitespaceLine = function() { return this.linesUpToNextMatchingLine(/^ *$/); }; this.linesUpToNextMatchingLine = function(match) { var lines, nextLine; lines = []; nextLine = this.nextLine(); if (nextLine !== false) { lines.push(nextLine); } while (nextLine !== false && !nextLine.match(match) && nextLine !== false) { nextLine = this.nextLine(); if (nextLine !== false) { lines.push(nextLine); } } return lines; }; }).call(LogText.prototype); state = { NORMAL: 0, ERROR: 1 }; LatexParser = function(text, options) { this.log = new LogText(text); this.state = state.NORMAL; options = options || {}; this.fileBaseNames = options.fileBaseNames || [/compiles/, /\/usr\/local/]; this.ignoreDuplicates = options.ignoreDuplicates; this.data = []; this.fileStack = []; this.currentFileList = this.rootFileList = []; this.openParens = 0; }; (function() { this.parse = function() { var lineNo; while ((this.currentLine = this.log.nextLine()) !== false) { if (this.state === state.NORMAL) { if (this.currentLineIsError()) { this.state = state.ERROR; this.currentError = { line: null, file: this.currentFilePath, level: 'error', message: this.currentLine.slice(2), content: '', raw: this.currentLine + '\n' }; } else if (this.currentLineIsRunawayArgument()) { this.parseRunawayArgumentError(); } else if (this.currentLineIsWarning()) { this.parseSingleWarningLine(LATEX_WARNING_REGEX); } else if (this.currentLineIsHboxWarning()) { this.parseHboxLine(); } else if (this.currentLineIsPackageWarning()) { this.parseMultipleWarningLine(); } else { this.parseParensForFilenames(); } } if (this.state === state.ERROR) { this.currentError.content += this.log.linesUpToNextMatchingLine(/^l\.[0-9]+/).join('\n'); this.currentError.content += '\n'; this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n'); this.currentError.content += '\n'; this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n'); this.currentError.raw += this.currentError.content; lineNo = this.currentError.raw.match(/l\.([0-9]+)/); if (lineNo) { this.currentError.line = parseInt(lineNo[1], 10); } this.data.push(this.currentError); this.state = state.NORMAL; } } return this.postProcess(this.data); }; this.currentLineIsError = function() { return this.currentLine[0] === '!'; }; this.currentLineIsRunawayArgument = function() { return this.currentLine.match(/^Runaway argument/); }; this.currentLineIsWarning = function() { return !!this.currentLine.match(LATEX_WARNING_REGEX); }; this.currentLineIsPackageWarning = function() { return !!this.currentLine.match(PACKAGE_WARNING_REGEX); }; this.currentLineIsHboxWarning = function() { return !!this.currentLine.match(HBOX_WARNING_REGEX); }; this.parseRunawayArgumentError = function() { var lineNo; this.currentError = { line: null, file: this.currentFilePath, level: 'error', message: this.currentLine, content: '', raw: this.currentLine + '\n' }; this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n'); this.currentError.content += '\n'; this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n'); this.currentError.raw += this.currentError.content; lineNo = this.currentError.raw.match(/l\.([0-9]+)/); if (lineNo) { this.currentError.line = parseInt(lineNo[1], 10); } return this.data.push(this.currentError); }; this.parseSingleWarningLine = function(prefix_regex) { var line, lineMatch, warning, warningMatch; warningMatch = this.currentLine.match(prefix_regex); if (!warningMatch) { return; } warning = warningMatch[1]; lineMatch = warning.match(LINES_REGEX); line = lineMatch ? parseInt(lineMatch[1], 10) : null; this.data.push({ line: line, file: this.currentFilePath, level: 'warning', message: warning, raw: warning }); }; this.parseMultipleWarningLine = function() { var line, lineMatch, packageMatch, packageName, prefixRegex, raw_message, warningMatch, warning_lines; warningMatch = this.currentLine.match(PACKAGE_WARNING_REGEX); if (!warningMatch) { return; } warning_lines = [warningMatch[1]]; lineMatch = this.currentLine.match(LINES_REGEX); line = lineMatch ? parseInt(lineMatch[1], 10) : null; packageMatch = this.currentLine.match(PACKAGE_REGEX); packageName = packageMatch[1]; prefixRegex = new RegExp('(?:\\(' + packageName + '\\))*[\\s]*(.*)', 'i'); while (!!(this.currentLine = this.log.nextLine())) { lineMatch = this.currentLine.match(LINES_REGEX); line = lineMatch ? parseInt(lineMatch[1], 10) : line; warningMatch = this.currentLine.match(prefixRegex); warning_lines.push(warningMatch[1]); } raw_message = warning_lines.join(' '); this.data.push({ line: line, file: this.currentFilePath, level: 'warning', message: raw_message, raw: raw_message }); }; this.parseHboxLine = function() { var line, lineMatch; lineMatch = this.currentLine.match(LINES_REGEX); line = lineMatch ? parseInt(lineMatch[1], 10) : null; this.data.push({ line: line, file: this.currentFilePath, level: 'typesetting', message: this.currentLine, raw: this.currentLine }); }; this.parseParensForFilenames = function() { var filePath, newFile, pos, previousFile, token; pos = this.currentLine.search(/\(|\)/); if (pos !== -1) { token = this.currentLine[pos]; this.currentLine = this.currentLine.slice(pos + 1); if (token === '(') { filePath = this.consumeFilePath(); if (filePath) { this.currentFilePath = filePath; newFile = { path: filePath, files: [] }; this.fileStack.push(newFile); this.currentFileList.push(newFile); this.currentFileList = newFile.files; } else { this.openParens++; } } else if (token === ')') { if (this.openParens > 0) { this.openParens--; } else { if (this.fileStack.length > 1) { this.fileStack.pop(); previousFile = this.fileStack[this.fileStack.length - 1]; this.currentFilePath = previousFile.path; this.currentFileList = previousFile.files; } } } this.parseParensForFilenames(); } }; this.consumeFilePath = function() { var endOfFilePath, path; if (!this.currentLine.match(/^\/?([^ \)]+\/)+/)) { return false; } endOfFilePath = this.currentLine.search(RegExp(' |\\)')); path = void 0; if (endOfFilePath === -1) { path = this.currentLine; this.currentLine = ''; } else { path = this.currentLine.slice(0, endOfFilePath); this.currentLine = this.currentLine.slice(endOfFilePath); } return path; }; return this.postProcess = function(data) { var all, errors, hashEntry, hashes, i, typesetting, warnings; all = []; errors = []; warnings = []; typesetting = []; hashes = []; hashEntry = function(entry) { return entry.raw; }; i = 0; while (i < data.length) { if (this.ignoreDuplicates && hashes.indexOf(hashEntry(data[i])) > -1) { i++; continue; } if (data[i].level === 'error') { errors.push(data[i]); } else if (data[i].level === 'typesetting') { typesetting.push(data[i]); } else if (data[i].level === 'warning') { warnings.push(data[i]); } all.push(data[i]); hashes.push(hashEntry(data[i])); i++; } return { errors: errors, warnings: warnings, typesetting: typesetting, all: all, files: this.rootFileList }; }; }).call(LatexParser.prototype); LatexParser.parse = function(text, options) { return new LatexParser(text, options).parse(); }; return LatexParser; });
overleaf/web/frontend/js/vendor/libs/latex-log-parser.js/0
{ "file_path": "overleaf/web/frontend/js/vendor/libs/latex-log-parser.js", "repo_id": "overleaf", "token_count": 4679 }
525
import HotkeysModal from '../js/features/hotkeys-modal/components/hotkeys-modal' export const ReviewEnabled = args => { return <HotkeysModal {...args} /> } export const ReviewDisabled = args => { return <HotkeysModal {...args} trackChangesVisible={false} /> } export const MacModifier = args => { return <HotkeysModal {...args} isMac /> } export default { title: 'Modals / Hotkeys', component: HotkeysModal, args: { animation: false, show: true, isMac: false, trackChangesVisible: true, }, argTypes: { handleHide: { action: 'handleHide' }, }, }
overleaf/web/frontend/stories/hotkeys-modal.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/hotkeys-modal.stories.js", "repo_id": "overleaf", "token_count": 209 }
526
import PropTypes from 'prop-types' import useExpandCollapse from '../js/shared/hooks/use-expand-collapse' function TestUI({ children, expandableProps, toggleProps }) { return ( <> <div {...expandableProps}>{children}</div> <button {...toggleProps}>Expand/collapse</button> </> ) } function VerticalTestUI(props) { return <TestUI {...props}>{verticalContents}</TestUI> } function HorizontalTestUI(props) { return <TestUI {...props}>{horizontalContents}</TestUI> } VerticalTestUI.propTypes = { expandableProps: PropTypes.object, toggleProps: PropTypes.object, } HorizontalTestUI.propTypes = VerticalTestUI.propTypes TestUI.propTypes = { ...VerticalTestUI.propTypes, children: PropTypes.node, } export const Vertical = args => { const { expandableProps, toggleProps } = useExpandCollapse(args) return ( <VerticalTestUI expandableProps={expandableProps} toggleProps={toggleProps} /> ) } export const VerticalInitiallyExpanded = args => { const { expandableProps, toggleProps } = useExpandCollapse(args) return ( <VerticalTestUI expandableProps={expandableProps} toggleProps={toggleProps} /> ) } VerticalInitiallyExpanded.args = { initiallyExpanded: true, } export const VerticalWithMinSize = args => { const { expandableProps, toggleProps } = useExpandCollapse(args) return ( <VerticalTestUI expandableProps={expandableProps} toggleProps={toggleProps} /> ) } VerticalWithMinSize.args = { collapsedSize: 200, } export const Horizontal = args => { const { expandableProps, toggleProps } = useExpandCollapse(args) return ( <HorizontalTestUI expandableProps={expandableProps} toggleProps={toggleProps} /> ) } Horizontal.args = { dimension: 'width', } export const HorizontalInitiallyExpanded = args => { const { expandableProps, toggleProps } = useExpandCollapse(args) return ( <HorizontalTestUI expandableProps={expandableProps} toggleProps={toggleProps} /> ) } HorizontalInitiallyExpanded.args = { initiallyExpanded: true, } export const HorizontalWithMinSize = args => { const { expandableProps, toggleProps } = useExpandCollapse(args) return ( <HorizontalTestUI expandableProps={expandableProps} toggleProps={toggleProps} /> ) } HorizontalWithMinSize.args = { dimension: 'width', collapsedSize: 200, } const defaultContentStyles = { display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '2em', backgroundImage: 'linear-gradient(to bottom, red, blue)', width: '500px', height: '500px', color: '#FFF', } const verticalContents = <div style={defaultContentStyles}>Vertical</div> const horizontalContents = ( <div style={{ ...defaultContentStyles, backgroundImage: 'linear-gradient(to right, red, blue)', }} > Horizontal </div> ) export default { title: 'useExpandCollapse', }
overleaf/web/frontend/stories/use-expand-collapse.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/use-expand-collapse.stories.js", "repo_id": "overleaf", "token_count": 1096 }
527
.contact-us-modal { textarea { height: 120px; } } .contact-suggestions { margin: 0 -20px 10px; padding: 10px 0; color: @gray-dark; background-color: @gray-lightest; border-top: solid 1px @gray-lighter; border-bottom: solid 1px @gray-lighter; font-size: 0.9rem; } .contact-suggestion-label { margin-bottom: 10px; padding: 0 20px; } .contact-suggestion-list { .list-unstyled(); background-color: #fff; border-top: solid 1px @gray-lighter; border-bottom: solid 1px @gray-lighter; margin: 0; li:last-child .contact-suggestion-list-item { border-bottom: none; } } .contact-suggestion-list-item { display: table; width: 100%; color: @dropdown-link-color; padding: 10px 20px; border-bottom: solid 1px lighten(@gray-lighter, 10%); cursor: pointer; &:hover, &:focus { text-decoration: none; color: @dropdown-link-hover-color!important; background-color: @dropdown-link-hover-bg; .fa { color: inherit; } } .fa { display: table-cell; text-align: right; color: @gray-lighter; } }
overleaf/web/frontend/stylesheets/app/contact-us.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/contact-us.less", "repo_id": "overleaf", "token_count": 441 }
528
@rp-base-font-size: 12px; @rp-small-font-size: 10px; @rp-icon-large-size: 18px; @rp-bg-blue: #dadfed; @rp-bg-dim-blue: #fafafa; @rp-highlight-blue: #8a96b5; @rp-border-grey: #d9d9d9; @rp-green: #2c8e30; @rp-green-on-dark: rgba(37, 107, 41, 0.5); @rp-red: #c5060b; @rp-yellow: #f3b111; @rp-yellow-on-dark: rgba(194, 93, 11, 0.5); @rp-grey: #aaaaaa; @rp-type-blue: #6b7797; @rp-type-darkgrey: #3f3f3f; @rp-entry-ribbon-width: 4px; @rp-entry-arrow-width: 6px; @rp-semibold-weight: 600; @review-panel-width: 230px; @review-off-width: 22px; @rp-toolbar-height: 32px; @rp-entry-animation-speed: 0.3s; .rp-button() { display: block; // IE doesn't do flex with inline items. background-color: @rp-highlight-blue; color: #fff; text-align: center; line-height: 1.3; user-select: none; border: 0; &:hover, &:focus { outline: 0; background-color: darken(@rp-highlight-blue, 5%); text-decoration: none; color: #fff; } &[disabled] { background-color: tint(@rp-highlight-blue, 50%); &:hover, &:focus { background-color: tint(@rp-highlight-blue, 50%); } } } .rp-collapse-arrow() { display: inline-block; transform: rotateZ(0deg); transition: transform 0.15s ease; &-on { transform: rotateZ(-90deg); } } #review-panel { display: block; .rp-size-expanded & { display: flex; flex-direction: column; width: @review-panel-width; overflow: visible; border-left-width: 1px; } .rp-size-mini & { width: @review-off-width; z-index: 6; border-left-width: 1px; } position: absolute; top: 32px; bottom: 0px; right: 0px; background-color: @rp-bg-blue; border-left: solid 0px @rp-border-grey; font-size: @rp-base-font-size; color: @rp-type-blue; z-index: 6; } .loading-panel { .rp-size-expanded & { right: @review-panel-width; } } .review-panel-toolbar { display: none; .rp-size-expanded & { display: flex; align-items: center; justify-content: space-between; padding: 0 5px; } .rp-unsupported & { display: none; } position: relative; border-bottom: 1px solid @rp-border-grey; background-color: @rp-bg-dim-blue; text-align: center; z-index: 3; flex-basis: 32px; flex-shrink: 0; } .review-panel-toolbar-label { cursor: pointer; text-align: right; flex-grow: 1; } .review-panel-toolbar-icon-on { margin-right: 5px; color: @red; } .review-panel-toolbar-label-disabled { cursor: auto; margin-right: 5px; } .review-panel-toolbar-spinner { margin-left: 5px; } .rp-tc-state { position: absolute; top: 100%; left: 0; right: 0; overflow: hidden; list-style: none; padding: 0 5px; margin: 0; border-bottom: 1px solid @rp-border-grey; background-color: @rp-bg-dim-blue; text-align: left; } .rp-tc-state-collapse { .rp-collapse-arrow; margin-left: 5px; } .rp-tc-state-item { display: flex; align-items: center; padding: 3px 0; &:last-of-type { padding-bottom: 5px; } } .rp-tc-state-separator { border-bottom: 1px solid @rp-border-grey; } .rp-tc-state-item-everyone { border-bottom: 1px solid @rp-border-grey; color: @red; } .rp-tc-state-item-name { flex-grow: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: @rp-semibold-weight; } .rp-tc-state-item-name-disabled { opacity: 0.35; } .rp-tc-state-item-guests { color: @blue; } .rp-entry-list { display: none; width: 100%; .rp-size-expanded &, .rp-size-mini & { display: block; } .rp-unsupported & { display: none; } .rp-state-current-file & { position: absolute; top: 0; bottom: 0; padding-bottom: 52px; } .rp-state-overview & { flex-grow: 2; overflow-y: auto; } } .rp-entry-list-inner { position: relative; } .rp-entry-indicator { display: none; .rp-size-mini & { display: block; } .rp-size-mini &-add-comment { display: none; } position: absolute; left: 2px; right: 2px; text-align: center; background-color: @rp-highlight-blue; border-radius: 3px; color: #fff; cursor: pointer; transition: top @rp-entry-animation-speed, left 0.1s, right 0.1s; .no-animate & { transition: none; } &-focused { left: 0px; right: 4px; z-index: 1; } } .rp-entry-wrapper { &:hover .rp-entry-insert, &:hover .rp-entry-delete, &:hover .rp-entry-aggregate, &:hover .rp-entry-comment { display: block; } } .rp-entry { .rp-state-current-file & { position: absolute; width: @review-panel-width; } .rp-state-current-file-mini & { display: none; left: @review-off-width + @rp-entry-arrow-width; box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.2); z-index: 1; &::before { content: ''; position: absolute; top: -(@review-off-width + @rp-entry-arrow-width); right: -(@review-off-width + @rp-entry-arrow-width); bottom: -(@review-off-width + @rp-entry-arrow-width); left: -(2 * @rp-entry-arrow-width + 2); z-index: -1; } &::after { .triangle( left, @rp-entry-arrow-width, @rp-entry-arrow-width * 1.5, inherit ); top: (@review-off-width / 2) - @rp-entry-arrow-width; left: -(@rp-entry-ribbon-width + @rp-entry-arrow-width); content: ''; } } .rp-state-current-file-mini.rp-layout-left & { left: auto; right: @review-off-width + @rp-entry-arrow-width; border-left-width: 0; border-right-width: @rp-entry-ribbon-width; border-right-style: solid; &::before { left: -(@review-off-width + @rp-entry-arrow-width); right: -(2 * @rp-entry-arrow-width + 2); } &::after { .triangle( right, @rp-entry-arrow-width, @rp-entry-arrow-width * 1.5, inherit ); right: -(@rp-entry-ribbon-width + @rp-entry-arrow-width); left: auto; } } .rp-state-current-file-expanded & { visibility: hidden; left: 5px; right: 5px; width: auto; &-focused { left: -2px; right: 12px; z-index: 1; } &-add-comment { right: auto; &.rp-entry-adding-comment { right: 5px; } } &-bulk-actions { right: auto; } } .rp-state-overview & { border-radius: 0; border-bottom: solid 1px @rp-border-grey; cursor: pointer; } .resolved-comments-dropdown & { position: static; margin-bottom: 5px; } border-left: solid @rp-entry-ribbon-width transparent; border-radius: 3px; background-color: #fff; transition: top @rp-entry-animation-speed, left 0.1s, right 0.1s; .no-animate & { transition: none; } &-insert, &-aggregate { border-color: @rp-green; } &-delete { border-color: @rp-red; } &-comment { border-color: @rp-yellow; } &-comment-resolving { top: 4px; left: 6px; opacity: 0; z-index: 3; transform: scale(0.1); transform-origin: 0 0; transition: top 0.35s ease-out, left 0.35s ease-out, transform 0.35s ease-out, opacity 0.35s ease-out 0.2s; } &-comment-resolved { border-color: @rp-grey; background-color: #efefef; } &-add-comment { background-color: transparent; right: auto; border-left-width: 0; &.rp-entry-adding-comment { background-color: #fff; right: 5px; border-left-width: 3px; border-left-color: @rp-yellow; } } &-bulk-actions { background-color: transparent; right: auto; border-left-width: 0; } } .rp-entry-body { display: flex; align-items: center; padding: 4px 5px; } .rp-entry-action-icon { font-size: @rp-icon-large-size; padding: 0 3px; line-height: 0; .rp-state-overview & { display: none; } } .rp-entry-details { line-height: 1.4; margin-left: 5px; // We need to set any low-enough flex base size (0px), making it growable (1) and non-shrinkable (0). // This is needed to ensure that IE makes the element fill the available space. flex: 1 0 1px; overflow-x: auto; .rp-state-overview & { margin-left: 0; } } .rp-entry-metadata { font-size: @rp-small-font-size; } .rp-entry-user { font-weight: @rp-semibold-weight; font-style: normal; } .rp-comment-actions { a { color: @rp-type-blue; } } .rp-content-highlight { color: @rp-type-darkgrey; font-weight: @rp-semibold-weight; text-decoration: none; del& { text-decoration: line-through; } } .rp-entry-actions { display: flex; .rp-state-overview .rp-entry-list & { display: none; } } .rp-entry-button { .rp-button(); flex: 1 1 50%; border-right: solid 1px #fff; padding: 2px 0; &:last-child { border-bottom-right-radius: 3px; border-right-width: 0; } .rp-state-current-file-mini.rp-layout-left & { &:first-child { border-bottom-left-radius: 3px; } &:last-child { border-bottom-right-radius: 0; } } } .rp-comment { margin: 2px 5px; padding-bottom: 3px; line-height: 1.4; border-bottom: solid 1px @rp-border-grey; &:last-child { margin-bottom: 2px; border-bottom-width: 0; } .rp-state-overview .rp-entry-list & { margin: 4px 5px; &:first-child { margin-top: 0; padding-top: 4px; } } } .rp-comment-content { margin: 0; color: @rp-type-darkgrey; overflow-x: auto; // Long words, like links can overflow without this. white-space: pre-wrap; } .rp-comment-resolver { color: @rp-type-blue; } .rp-comment-resolver-content { font-style: italic; margin: 0; } .rp-comment-reply { padding: 0 5px; } .rp-add-comment-btn, .rp-bulk-actions-btn { .rp-button(); display: inline-block; padding: 5px 10px; border-radius: 3px; .rp-in-editor-widgets & { display: block; white-space: nowrap; border-radius: 0; &:last-child { border-bottom-left-radius: 3px; } } } .rp-bulk-actions-btn { border-radius: 0; &:first-child { border-top-left-radius: 3px; border-bottom-left-radius: 3px; } &:last-child { border-top-right-radius: 3px; border-bottom-right-radius: 3px; margin-left: 1px; } } .rp-new-comment { padding: 5px; } .rp-comment-input { width: 100%; font-size: @rp-base-font-size; padding: 2px 5px; border-radius: 3px; border: solid 1px @rp-border-grey; resize: vertical; color: @rp-type-darkgrey; background-color: #fff; margin-top: 3px; overflow-x: hidden; min-height: 3em; max-height: 400px; } .rp-icon-delete { display: inline-block; line-height: 1; font-style: normal; font-size: 0.8em; text-decoration: line-through; font-weight: @rp-semibold-weight; &::before { content: 'Ab'; } } .rp-resolved-comment { border-left: solid @rp-entry-ribbon-width @rp-yellow; border-radius: 3px; background-color: #fff; margin-bottom: 5px; } .rp-resolved-comment-context { background-color: lighten(@rp-yellow, 35%); padding: 4px 5px; } .rp-resolved-comment-context-file { font-weight: @rp-semibold-weight; } .rp-resolved-comment-context-quote { color: #000; font-family: @font-family-monospace; margin: 0; } .rp-entry-callout { transition: top @rp-entry-animation-speed, height @rp-entry-animation-speed; .rp-state-current-file & { position: absolute; border-top: 1px solid grey; border-right: 1px dashed grey; &::after { content: ''; position: absolute; top: -1px; left: 3px; bottom: 0; border-bottom: 1px solid grey; } } .rp-state-current-file-expanded & { width: 3px; &::after { width: 3px; } } .rp-state-current-file-mini & { width: 1px; &::after { width: 1px; } } .rp-state-overview & { display: none; } .rp-state-current-file &-inverted { border-top: none; border-bottom: 1px solid grey; &::after { top: 0px; bottom: -1px; border-top: 1px solid grey; border-bottom: none; } } .rp-state-current-file &-insert { border-color: @rp-green; &::after { border-color: @rp-green; } } .rp-state-current-file &-delete { border-color: @rp-red; &::after { border-color: @rp-red; } } .rp-state-current-file &-comment { border-color: @rp-yellow; &::after { border-color: @rp-yellow; } } .rp-size-mini &-add-comment { display: none; } } .rp-overview-file-header { padding: 2px 5px; border-top: solid 1px @rp-border-grey; border-bottom: solid 1px @rp-border-grey; background-color: @rp-bg-dim-blue; margin-top: 10px; font-weight: @rp-semibold-weight; text-align: center; cursor: pointer; } .rp-overview-file-num-entries { font-weight: normal; font-size: 0.9em; } .rp-overview-file-header-collapse { .rp-collapse-arrow; float: left; } .rp-overview-file-entries { overflow: hidden; } .rp-comment-wrapper { transition: 0.35s opacity ease-out 0.2s; &-resolving { opacity: 0; } } .rp-loading, .rp-empty { text-align: center; padding: 5px; } .rp-nav { display: none; flex-shrink: 0; .rp-size-expanded & { display: flex; } .rp-unsupported & { display: none; } .rp-state-current-file & { position: absolute; bottom: 0; } width: 100%; font-size: @rp-icon-large-size; text-align: center; background-color: @rp-bg-dim-blue; border-top: solid 1px @rp-border-grey; z-index: 2; } .rp-nav-item { display: block; color: lighten(@rp-type-blue, 25%); flex: 0 0 50%; border-top: solid 3px transparent; padding-bottom: 2px; &:hover, &:focus { text-decoration: none; color: @rp-type-blue; } &-active { color: @rp-type-blue; border-top: solid 3px @rp-highlight-blue; } } .rp-nav-label { display: block; font-size: @rp-base-font-size; } #editor { .rp-size-mini & { right: @review-off-width; .ace-editor-body { overflow: visible; .ace_scrollbar-v { right: -@review-off-width; } } } .rp-size-expanded & { right: @review-panel-width; left: 0px; width: auto; } .rp-state-current-file-expanded & { .ace-editor-body { overflow: visible; .ace_scrollbar-v { right: -@review-panel-width; } } } } #editor-rich-text { .rp-size-expanded & { right: @review-panel-width; } } .rp-toggle { display: inline-block; vertical-align: middle; padding-left: 5px; } .rp-toggle-hidden-input { display: none; + .rp-toggle-btn { display: block; width: 3.5em; height: 1.75em; position: relative; outline: 0; margin: 0; font-weight: normal; cursor: pointer; user-select: none; padding: 1px; background-color: @rp-highlight-blue; border: 1px solid #fff; border-radius: 0.875em; transition: background 0.15s ease, border-color 0.15s ease; &::before { content: ''; display: block; width: 50%; height: 100%; position: relative; left: 0; background-color: #fff; border-radius: 0.875em; transition: background-color 0.15s ease, color 0.15s ease, left 0.15s ease; } } &:checked + .rp-toggle-btn { background-color: @red; border-color: #fff; &::before { left: 50%; background-color: #fff; } } &:disabled + .rp-toggle-btn { cursor: default; opacity: 0.35; } } .rp-unsupported-msg-wrapper { display: none; .rp-size-expanded.rp-unsupported & { display: block; } height: 100%; .rp-unsupported-msg { display: flex; width: @review-panel-width - 40px; height: 100%; flex-direction: column; justify-content: center; align-items: center; margin: 0 auto; text-align: center; .rp-unsupported-msg-title { font-size: 1.3em; margin-top: 13px; } } } .ace-editor-wrapper { .track-changes-marker-callout { border-radius: 0; position: absolute; .rp-state-overview &, .rp-loading-threads & { display: none; } } .track-changes-added-marker-callout { border-bottom: 1px dashed @rp-green; z-index: 1; } .track-changes-comment-marker-callout { border-bottom: 1px dashed @rp-yellow; } .track-changes-deleted-marker-callout { border-bottom: 1px dashed @rp-red; } .track-changes-marker { border-radius: 0; position: absolute; .rp-loading-threads & { display: none; } z-index: 6; // Appear above text selection } .track-changes-comment-marker { background-color: @rp-yellow; opacity: 0.3; } .track-changes-added-marker { background-color: @rp-green; opacity: 0.3; } .track-changes-deleted-marker { border-left: 2px dotted @rp-red; margin-left: -1px; } .ace_dark { .track-changes-comment-marker { background-color: @rp-yellow-on-dark; } .track-changes-added-marker { background-color: @rp-green-on-dark; } } } .cm-editor-wrapper { @rp-yellow-for-cm: fade( @rp-yellow, 40% ); // Get the RGBA colour with transparency @rp-green-for-cm: fade( @rp-green, 40% ); // Get the RGBA colour with transparency .track-changes-marker { border-radius: 0; } .track-changes-added-marker { // Uses rgba so not to affect the opacity of the text - doesn't layer like ace background-color: @rp-green-for-cm; color: black; } .track-changes-deleted-marker { border-left: 2px dotted #c5060b; // Commented out styles for callout to be reimplemented later // border-bottom: 1px dashed #c5060b; // width: 100%; } .track-changes-comment-marker { // Uses rgba so not to affect the opacity of the text - doesn't layer like ace background-color: @rp-yellow-for-cm; color: black; } .track-changes-added-marker.track-changes-comment-marker { background-color: mix(@rp-yellow-for-cm, @rp-green-for-cm); } } .review-icon { display: inline-block; background: url('/img/ol-icons/review-icon-dark-theme.svg') top/30px no-repeat; width: 30px; &::before { content: '\00a0'; // Non-breakable space. A non-breakable character here makes this icon work like font-awesome. } } a when (@is-overleaf-light = true) { .review-icon { background: url('/img/ol-icons/review-icon-light-theme.svg') top/30px no-repeat; } &.active, &:active { .review-icon { background: url('/img/ol-icons/review-icon-dark-theme.svg') top/30px no-repeat; } } } .resolved-comments-toggle { font-size: 14px; color: lighten(@rp-type-blue, 25%); border: solid 1px @rp-border-grey; border-radius: 3px; padding: 0 4px; display: block; height: 22px; width: 22px; line-height: 1.4; &:hover, &:focus { text-decoration: none; color: @rp-type-blue; } } .resolved-comments-backdrop { display: none; position: fixed; top: 0; right: 0; bottom: 0; left: 0; &-visible { display: block; } } .resolved-comments-dropdown { display: none; position: absolute; width: 300px; left: -150px; max-height: ~'calc(100vh - 100px)'; margin-top: @rp-entry-arrow-width * 1.5; margin-left: 1em; background-color: @rp-bg-blue; text-align: left; align-items: stretch; justify-content: center; border-radius: 3px; box-shadow: 0 0 20px 10px rgba(0, 0, 0, 0.3); z-index: 1; &::before { content: ''; .triangle( top, @rp-entry-arrow-width * 3, @rp-entry-arrow-width * 1.5, @rp-bg-blue ); top: -@rp-entry-ribbon-width * 2; left: 50%; margin-left: -@rp-entry-arrow-width * 0.75; } &-open { display: flex; } } .resolved-comments-scroller { flex: 0 0 auto; // Can't use 100% in the flex-basis key here, IE won't account for padding. width: 100%; // We need to set the width explicitly, as flex-basis won't work. max-height: ~'calc(100vh - 100px)'; // We also need to explicitly set the max-height, IE won't compute the flex-determined height. padding: 5px; overflow-y: auto; } .rp-collapse-toggle { color: @rp-type-blue; font-weight: @rp-semibold-weight; &:hover, &:focus { color: darken(@rp-type-blue, 5%); text-decoration: none; } } .rp-in-editor-widgets { position: absolute; top: 0; right: 0; font-size: 11px; z-index: 2; .rp-size-mini & { right: @review-off-width; } .rp-size-expanded &, .rp-unsupported & { display: none; } } .rp-track-changes-indicator { display: block; padding: 5px 10px; background-color: rgba(240, 240, 240, 0.9); color: @rp-type-blue; text-align: center; border-bottom-left-radius: 3px; white-space: nowrap; &.rp-track-changes-indicator-on-dark { background-color: rgba(88, 88, 88, 0.8); color: #fff; &:hover, &:focus { background-color: rgba(88, 88, 88, 1); color: #fff; } } &:hover, &:focus { outline: 0; text-decoration: none; background-color: rgba(240, 240, 240, 1); color: @rp-type-blue; } } .review-panel-toggler { display: none; position: absolute; top: 0; bottom: 0; width: 10px; opacity: 0.5; color: @rp-highlight-blue; z-index: 1; background-color: transparent; transition: background 0.1s; .rp-size-mini &, .rp-size-expanded & { display: block; } .rp-unsupported & { display: none; } .rp-size-expanded & { &::after { content: '\f105'; } } &:hover, &:focus { color: @rp-highlight-blue; background-color: #fff; } &::after { content: '\f104'; font-family: FontAwesome; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-size: 16px; display: block; position: absolute; top: 50%; width: 100%; text-align: center; margin-top: -0.5em; } } // Helper class for elements which aren't treated as flex-items by IE10, e.g: // * inline items; // * unknown elements (elements which aren't standard DOM elements, such as custom element directives) .rp-flex-block { display: block; }
overleaf/web/frontend/stylesheets/app/editor/review-panel.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/editor/review-panel.less", "repo_id": "overleaf", "token_count": 9946 }
529
// Styles for Chat panel in Overleaf v2 .chat .message-wrapper .message .message-content a { color: inherit; text-decoration: underline; }
overleaf/web/frontend/stylesheets/app/ol-chat.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/ol-chat.less", "repo_id": "overleaf", "token_count": 45 }
530
.translations-message { .system-message; text-align: center; img { vertical-align: text-bottom; margin-bottom: -1px; } .close { color: #fff; opacity: 1; text-shadow: none; } a { color: #fff; &:hover, &:focus { color: #fff; } } }
overleaf/web/frontend/stylesheets/app/translations.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/translations.less", "repo_id": "overleaf", "token_count": 138 }
531
.expand-collapse-container { overflow: hidden; transition: height 0.15s ease-in-out, width 0.15s ease-in-out; }
overleaf/web/frontend/stylesheets/components/expand-collapse.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/expand-collapse.less", "repo_id": "overleaf", "token_count": 44 }
532
// // Navbars // -------------------------------------------------- // Wrapper and base class // // Provide a static navbar from which we expand to create full-width, fixed, and // other navbar variations. .navbar { position: relative; min-height: @navbar-height; // Ensure a navbar always shows (e.g., without a .navbar-brand in collapsed mode) margin-bottom: @navbar-margin-bottom; border-bottom: 1px solid transparent; // Prevent floats from breaking the navbar &:extend(.clearfix all); @media (min-width: @grid-float-breakpoint) { border-radius: @navbar-border-radius; } } // Navbar heading // // Groups `.navbar-brand` and `.navbar-toggle` into a single component for easy // styling of responsive aspects. .navbar-header { &:extend(.clearfix all); @media (min-width: @grid-float-breakpoint) { float: left; } } // Navbar collapse (body) // // Group your navbar content into this for easy collapsing and expanding across // various device sizes. By default, this content is collapsed when <768px, but // will expand past that for a horizontal display. // // To start (on mobile devices) the navbar links, forms, and buttons are stacked // vertically and include a `max-height` to overflow in case you have too much // content for the user's viewport. .navbar-collapse { max-height: @navbar-collapse-max-height; overflow-x: visible; padding-right: @navbar-padding-horizontal; padding-left: @navbar-padding-horizontal; &:extend(.clearfix all); -webkit-overflow-scrolling: touch; &.in { overflow-y: auto; } @media (min-width: @grid-float-breakpoint) { width: auto; border-top: 0; box-shadow: none; &.collapse { display: block !important; height: auto !important; padding-bottom: 0; // Override default setting overflow: visible !important; } &.in { overflow-y: visible; } // Undo the collapse side padding for navbars with containers to ensure // alignment of right-aligned contents. .navbar-fixed-top &, .navbar-static-top &, .navbar-fixed-bottom & { padding-left: 0; padding-right: 0; } } } .navbar-main { z-index: 1; .container-fluid > .navbar-collapse { // High specificity needed to override Bootstrap's default. margin: 10px 0 0; @media (min-width: @grid-float-breakpoint) { margin: 0; } } .navbar-collapse { // Use absolute positioning to build the hamburger menu. position: absolute; left: 0; width: 100%; margin: 0; background-color: @navbar-default-bg; border-bottom: solid 1px @navbar-default-border; padding: 0; @media (min-width: @grid-float-breakpoint) { // Get back to regular layout mode as soon as the menu items are // expanded (i.e. not contained within the hamburguer menu). position: static; background-color: transparent; border-bottom: 0; padding-right: @navbar-padding-horizontal; padding-left: @navbar-padding-horizontal; } } } // Both navbar header and collapse // // When a container is present, change the behavior of the header and collapse. .container, .container-fluid { > .navbar-header, > .navbar-collapse { margin-right: -@navbar-padding-horizontal; margin-left: -@navbar-padding-horizontal; @media (min-width: @grid-float-breakpoint) { margin-right: 0; margin-left: 0; } } } // // Navbar alignment options // // Display the navbar across the entirety of the page or fixed it to the top or // bottom of the page. // Static top (unfixed, but 100% wide) navbar .navbar-static-top { z-index: @zindex-navbar; border-width: 0 0 1px; @media (min-width: @grid-float-breakpoint) { border-radius: 0; } } // Fix the top/bottom navbars when screen real estate supports it .navbar-fixed-top, .navbar-fixed-bottom { position: fixed; right: 0; left: 0; z-index: @zindex-navbar-fixed; // Undo the rounded corners @media (min-width: @grid-float-breakpoint) { border-radius: 0; } } .navbar-fixed-top { top: 0; border-width: 0 0 1px; } .navbar-fixed-bottom { bottom: 0; margin-bottom: 0; // override .navbar defaults border-width: 1px 0 0; } // Brand/project name .navbar-brand { float: left; //padding: @navbar-padding-vertical @navbar-padding-horizontal; //font-size: @font-size-large; line-height: @line-height-computed; //height: @navbar-height; &:hover, &:focus { text-decoration: none; } // @media (min-width: @grid-float-breakpoint) { // .navbar > .container &, // .navbar > .container-fluid & { // margin-left: -@navbar-padding-horizontal; // } // } } .navbar-title { font-size: 20px; display: inline-block; margin-top: 2px; color: @navbar-title-color; &:hover, &:active, &:focus { color: @navbar-title-color-hover; text-decoration: none; } } // Navbar toggle // // Custom button for toggling the `.navbar-collapse`, powered by the collapse // JavaScript plugin. .navbar-toggle { position: relative; float: right; background-color: transparent; background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214 border: 2px solid @navbar-default-link-color; border-radius: @border-radius-base; // We remove the `outline` here, but later compensate by attaching `:hover` // styles to `:focus`. &:focus { outline: none; } @media (min-width: @grid-float-breakpoint) { display: none; } } // Navbar nav links // // Builds on top of the `.nav` components with its own modifier class to make // the nav the full height of the horizontal nav (above 768px). .navbar-nav { margin: (@navbar-padding-vertical / 2) -@navbar-padding-horizontal; > li > a { padding-top: 10px; padding-bottom: 10px; line-height: @line-height-computed; } @media (max-width: @grid-float-breakpoint-max) { margin: (@navbar-padding-vertical / 2) 0; // Dropdowns get custom display when collapsed .open .dropdown-menu { position: static; float: none; width: auto; margin-top: 0; background-color: transparent; border: 0; box-shadow: none; > li > a, > li > div.subdued, > li > form > button, .dropdown-header { padding: 5px 15px 5px 25px; } > li > a, > li > form > button { line-height: @line-height-computed; &:hover, &:focus { background-image: none; } } > li > div.subdued { line-height: @line-height-computed; } } } // Uncollapse the nav @media (min-width: @grid-float-breakpoint) { float: left; margin: 0; > li { float: left; > a { padding-top: @navbar-padding-vertical; padding-bottom: @navbar-padding-vertical; } } &.navbar-right:last-child { margin-right: -@navbar-padding-horizontal; } } } // Component alignment // // Repurpose the pull utilities as their own navbar utilities to avoid specificity // issues with parents and chaining. Only do this when the navbar is uncollapsed // though so that navbar contents properly stack and align in mobile. @media (min-width: @grid-float-breakpoint) { .navbar-left { .pull-left(); } .navbar-right { .pull-right(); } } // Navbar form // // Extension of the `.form-inline` with some extra flavor for optimum display in // our navbars. .navbar-form { margin-left: -@navbar-padding-horizontal; margin-right: -@navbar-padding-horizontal; padding: 10px @navbar-padding-horizontal; border-top: 1px solid transparent; border-bottom: 1px solid transparent; @shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); .box-shadow(@shadow); // Mixin behavior for optimum display .form-inline(); .form-group { @media (max-width: @grid-float-breakpoint-max) { margin-bottom: 5px; } } // Vertically center in expanded, horizontal navbar .navbar-vertical-align(@input-height-base); // Undo 100% width for pull classes @media (min-width: @grid-float-breakpoint) { width: auto; border: 0; margin-left: 0; margin-right: 0; padding-top: 0; padding-bottom: 0; .box-shadow(none); // Outdent the form if last child to line up with content down the page &.navbar-right:last-child { margin-right: -@navbar-padding-horizontal; } } } // Dropdown menus // Menu position and menu carets .navbar-nav > li > .dropdown-menu { margin-top: 0; .border-top-radius(0); } // Menu position and menu caret support for dropups via extra dropup class .navbar-fixed-bottom .navbar-nav > li > .dropdown-menu { .border-bottom-radius(0); } // Buttons in navbars // // Vertically center a button within a navbar (when *not* in a form). .navbar-btn { .navbar-vertical-align(@input-height-base); &.btn-sm { .navbar-vertical-align(@input-height-small); } &.btn-xs { .navbar-vertical-align(22); } } // Text in navbars // // Add a class to make any element properly align itself vertically within the navbars. .navbar-text { .navbar-vertical-align(@line-height-computed); @media (min-width: @grid-float-breakpoint) { float: left; margin-left: @navbar-padding-horizontal; margin-right: @navbar-padding-horizontal; // Outdent the form if last child to line up with content down the page &.navbar-right:last-child { margin-right: 0; } } } // Alternate navbars // -------------------------------------------------- // Default navbar .navbar-default { background-color: @navbar-default-bg; border-color: @navbar-default-border; padding: @navbar-default-padding; position: absolute; top: 0; width: 100%; height: @header-height; .navbar-brand { position: absolute; top: 5px; bottom: 5px; width: @navbar-brand-width; padding: 0; background-image: @navbar-brand-image-url; background-size: contain; background-repeat: no-repeat; background-position: left center; } .navbar-text { color: @navbar-default-color; } .navbar-nav { > li > a { color: @navbar-default-link-color; border: 2px solid transparent; font-size: @navbar-btn-font-size; font-weight: @navbar-btn-font-weight; line-height: @navbar-btn-line-height; background-color: @navbar-default-link-bg; @media (min-width: @grid-float-breakpoint) { border-radius: @navbar-btn-border-radius; padding: @navbar-btn-padding; } &:hover, &:focus { color: #fff; background-color: @navbar-default-link-hover-bg; border: 2px solid @navbar-default-link-hover-color; } } > .active > a { &, &:hover, &:focus { color: @navbar-default-link-active-color; background-color: @navbar-default-link-active-bg; } } > .disabled > a { &, &:hover, &:focus { color: @navbar-default-link-disabled-color; background-color: @navbar-default-link-disabled-bg; } } > li.subdued > a { border: 0; color: @navbar-subdued-color; margin-left: 0; background-color: transparent; &:hover, &:focus { color: @navbar-subdued-hover-color; background-color: @navbar-subdued-hover-bg; } &:focus { .tab-focus(); } @media (min-width: @grid-float-breakpoint) { padding: @navbar-subdued-padding; } } @media (min-width: @grid-float-breakpoint) { > li > a { border-color: @navbar-default-link-border-color; margin-left: 1rem; } } } .navbar-toggle { border-color: @navbar-default-toggle-border-color; color: @navbar-default-link-color; &:hover, &.active { background-color: @navbar-default-toggle-hover-bg; border-color: @navbar-default-toggle-hover-bg; color: #fff; } } .navbar-collapse, .navbar-form { border-color: @navbar-default-border; } .navbar-collapse.in { box-shadow: 0 10px 15px rgba(0, 0, 0, 0.25); } // Dropdown menu items .navbar-nav { // Remove background color from open dropdown > .open > a { &, &:hover, &:focus { background-color: @navbar-default-link-active-bg; color: @navbar-default-link-active-color; } } > .open.subdued > a { &, &:hover, &:focus { color: @navbar-subdued-hover-color; background-color: @navbar-subdued-hover-bg; } } @media (max-width: @grid-float-breakpoint-max) { // Dropdowns get custom display when collapsed .open .dropdown-menu { background-color: lighten(@navbar-default-bg, 10%); > li > div.subdued { color: mix(@navbar-default-link-color, @navbar-default-bg); } > li > a, > li > form > button { // padding: 12px 12px 13px 30px; color: @navbar-default-link-color; &:hover, &:focus { color: #fff; background-color: @navbar-default-link-hover-bg; } } > .active > a, > .active > form > button { &, &:hover, &:focus { color: @navbar-default-link-active-color; background-color: @navbar-default-link-active-bg; } } > .disabled > a, > .disabled > form > button { &, &:hover, &:focus { color: @navbar-default-link-disabled-color; background-color: @navbar-default-link-disabled-bg; } } } } } // Links in navbars // // Add a class to ensure links outside the navbar nav are colored correctly. .navbar-link { color: @navbar-default-link-color; &:hover { color: @navbar-default-link-hover-color; } } @media (min-width: @grid-float-breakpoint) { padding: @navbar-default-padding-v 0; } } // Accessibility .skip-to-content { color: @navbar-default-link-color; background-color: @navbar-default-link-bg; border: 2px solid transparent; border-radius: @navbar-btn-border-radius; font-size: @navbar-btn-font-size; font-weight: @navbar-btn-font-weight; left: @navbar-brand-width + @padding-lg; line-height: @navbar-btn-line-height; padding: @navbar-btn-padding; position: absolute; top: -200px; z-index: @zindex-navbar + 1; &:focus { background-color: @navbar-default-link-hover-bg; border: 2px solid @navbar-default-link-hover-color; color: @white; text-decoration: none; top: @navbar-default-padding-v; } }
overleaf/web/frontend/stylesheets/components/navbar.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/navbar.less", "repo_id": "overleaf", "token_count": 6024 }
533
// // Thumbnails // -------------------------------------------------- // Mixin and adjust the regular image class .thumbnail { display: block; padding: @thumbnail-padding; margin-bottom: @line-height-computed; 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); > img, a > img { &:extend(.img-responsive); margin-left: auto; margin-right: auto; } // Add a hover state for linked versions only a&:hover, a&:focus, a&.active { border-color: @link-color; } // Image captions .caption { padding: @thumbnail-caption-padding; color: @thumbnail-caption-color; } }
overleaf/web/frontend/stylesheets/components/thumbnails.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/thumbnails.less", "repo_id": "overleaf", "token_count": 268 }
534
// // Variables // -------------------------------------------------- @gray-darker: #252525; @gray-dark: #505050; @gray: #7a7a7a; @gray-light: #a4a4a4; @gray-lighter: #cfcfcf; @gray-lightest: #f0f0f0; @white: #ffffff; // Styleguide colors @ol-blue-gray-0: #f4f5f8; @ol-blue-gray-1: #e4e8ee; @ol-blue-gray-2: #9da7b7; @ol-blue-gray-3: #5d6879; @ol-blue-gray-4: #455265; @ol-blue-gray-5: #2c3645; @ol-blue-gray-6: #1e2530; @ol-green: #138a07; @ol-type-green: #107206; @ol-dark-green: #004a0e; @ol-blue: #3e70bb; @ol-dark-blue: #2857a1; @ol-red: #c9453e; @ol-dark-red: #a6312b; @blue: #405ebf; @blueDark: #040d2d; @green: #46a546; @red: #a93529; @yellow: #a1a729; @orange: #f89406; @orange-dark: #9e5e04; @pink: #c3325f; @purple: #7a43b6; @brand-primary: @ol-green; @brand-secondary: @ol-dark-green; @brand-success: @green; @brand-info: @ol-blue; @brand-warning: @orange; @brand-danger: @ol-red; @ol-type-color: @ol-blue-gray-3; @accent-color-primary: @ol-green; @accent-color-secondary: @ol-dark-green; @editor-header-logo-background: url(/img/ol-brand/overleaf-o-white.svg) center / contain no-repeat; @editor-loading-logo-padding-top: 115.44%; @editor-loading-logo-background-url: url(/img/ol-brand/overleaf-o-grey.svg); @editor-loading-logo-foreground-url: url(/img/ol-brand/overleaf-o.svg); @editor-search-count-color: @ol-blue-gray-4; //== Scaffolding // // ## Settings for some of the most global styles. //** Background color for `<body>`. @body-bg: #fff; //** Global text color on `<body>`. @text-color: @ol-type-color; //** Global textual link color. @link-color: @ol-blue; @link-active-color: @ol-dark-green; //** Link hover color set via `darken()` function. @link-hover-color: @ol-dark-blue; @link-color-alt: @ol-type-green; @link-hover-color-alt: @ol-dark-green; @hr-border-alt: @gray-lighter; //== Typography // //## Font, line-height, and color for body text, headings, and more. @font-family-sans-serif: 'Lato', sans-serif; @font-family-serif: 'Merriweather', serif; //** Default monospace fonts for `<code>`, `<kbd>`, and `<pre>`. @font-family-monospace: Menlo, Monaco, Consolas, 'Courier New', monospace; @font-family-base: @font-family-sans-serif; @font-size-base: 16px; @font-size-large: ceil((@font-size-base * 1.25)); // ~18px @font-size-small: ceil((@font-size-base * 0.85)); // ~14px @font-size-extra-small: ceil((@font-size-base * 0.7)); // ~12px @font-size-h1: floor((@font-size-base * 2)); // ~36px @font-size-h2: floor((@font-size-base * 1.6)); // ~30px @font-size-h3: ceil((@font-size-base * 1.25)); // ~24px @font-size-h4: ceil((@font-size-base * 1.1)); // ~18px @font-size-h5: @font-size-base; @font-size-h6: ceil((@font-size-base * 0.85)); // ~12px //** Unit-less `line-height` for use in components like buttons. @line-height-base: 1.5625; // 20/14 //** Computed "line-height" (`font-size` * `line-height`) for use with `margin`, `padding`, etc. @line-height-computed: floor((@font-size-base * @line-height-base)); // ~20px //** By default, this inherits from the `<body>`. @headings-font-family: @font-family-serif; @headings-font-weight: 500; @headings-line-height: 1.35; @headings-color: @gray-dark; //-- Iconography // //## Specify custom locations of the include Glyphicons icon font. Useful for those including Bootstrap via Bower. @icon-font-path: '../fonts/'; @icon-font-name: 'glyphicons-halflings-regular'; @icon-font-svg-id: 'glyphicons_halflingsregular'; //== Components // //## Define common padding and border radius sizes and more. Values based on 14px text and 1.428 line-height (~20px to start). @margin-xs: 5px; @margin-sm: 10px; @margin-md: 20px; @margin-lg: 30px; @margin-xl: 40px; @margin-xxl: 50px; @padding-base-vertical: 5px; @padding-base-horizontal: 16px; @padding-large-vertical: 10px; @padding-large-horizontal: 16px; @padding-small-vertical: 5px; @padding-small-horizontal: 10px; @padding-xs-vertical: 1px; @padding-xs-horizontal: 8px; @padding-xs: 5px; @padding-sm: 10px; @padding-md: 20px; @padding-lg: 30px; @padding-xl: 40px; @line-height-large: 1.33; @line-height-small: 1.5; @border-radius-base: 3px; @border-radius-large: 5px; @border-radius-small: 2px; @border-width-base: 3px; @border-color-base: @ol-blue-gray-2; @btn-switch-color: @ol-blue-gray-4; @btn-switch-hover-color: darken(@ol-blue-gray-4, 8%); //** Global color for active items (e.g., navs or dropdowns). @component-active-color: #fff; //** Global background color for active items (e.g., navs or dropdowns). @component-active-bg: @brand-primary; //** Width of the `border` for generating carets that indicator dropdowns. @caret-width-base: 4px; //** Carets increase slightly in size for larger components. @caret-width-large: 5px; //== Tables // //## Customizes the `.table` component with basic values, each used across all table variations. //** Padding for `<th>`s and `<td>`s. @table-cell-padding: 8px; //** Padding for cells in `.table-condensed`. @table-condensed-cell-padding: 5px; //** Default background color used for all tables. @table-bg: transparent; //** Background color used for `.table-striped`. @table-bg-accent: #f9f9f9; //** Background color used for `.table-hover`. @table-bg-hover: #f5f5f5; @table-bg-active: @table-bg-hover; //** Border color for table and cell borders. @table-border-color: #ddd; //== Buttons // //## For each of Bootstrap's buttons, define text, background and border color. @btn-font-weight: 700; @btn-default-color: #fff; @btn-default-bg: @ol-blue-gray-4; @btn-default-border: transparent; @btn-primary-color: #fff; @btn-primary-bg: @ol-green; @btn-primary-border: transparent; @btn-success-color: #fff; @btn-success-bg: @ol-green; @btn-success-border: transparent; @btn-info-color: #fff; @btn-info-bg: @ol-blue; @btn-info-border: transparent; @btn-warning-color: #fff; @btn-warning-bg: @orange; @btn-warning-border: transparent; @btn-danger-color: #fff; @btn-danger-bg: @ol-red; @btn-danger-border: transparent; @btn-link-disabled-color: @gray-light; //== Forms // //## //** `<input>` background color @input-bg: #fff; //** `<input disabled>` background color @input-bg-disabled: @gray-lighter; //** Text color for `<input>`s @input-color: @ol-blue-gray-3; //** `<input>` border color @input-border: #ccc; //** `<input>` border radius @input-border-radius: unit(@line-height-base, em); //** Border color for inputs on focus @input-border-focus: #66afe9; //** Placeholder text color @input-color-placeholder: @gray-light; //** Default `.form-control` height @input-height-base: @line-height-computed + (@padding-base-vertical * 2) - 1; //** Large `.form-control` height @input-height-large: ( ceil(@font-size-large * @line-height-large) + (@padding-large-vertical * 2) + 2 ); //** Small `.form-control` height @input-height-small: ( floor(@font-size-small * @line-height-small) + (@padding-small-vertical * 2) + 2 ); @legend-color: @gray-dark; @legend-border-color: #e5e5e5; //** Background color for textual input addons @input-group-addon-bg: @gray-lighter; //** Border color for textual input addons @input-group-addon-border-color: @input-border; //== Dropdowns // //## Dropdown menu container and contents. //** Background for the dropdown menu. @dropdown-bg: #fff; //** Dropdown menu `border-color`. @dropdown-border: rgba(0, 0, 0, 0.15); //** Dropdown menu `border-color` **for IE8**. @dropdown-fallback-border: #ccc; //** Divider color for between dropdown items. @dropdown-divider-bg: #e5e5e5; //** Dropdown link text color. @dropdown-link-color: @gray-dark; //** Hover color for dropdown links. @dropdown-link-hover-color: #fff; //** Hover background for dropdown links. @dropdown-link-hover-bg: @brand-primary; //** Active dropdown menu item text color. @dropdown-link-active-color: @component-active-color; //** Active dropdown menu item background color. @dropdown-link-active-bg: @component-active-bg; //** Disabled dropdown menu item background color. @dropdown-link-disabled-color: @gray-light; //** Text color for headers within dropdown menus. @dropdown-header-color: @gray-light; // Note: Deprecated @dropdown-caret-color as of v3.1.0 @dropdown-caret-color: #000; //-- Z-index master list // // Warning: Avoid customizing these values. They're used for a bird's eye view // of components dependent on the z-axis and are designed to all work together. // // Note: These variables are not generated into the Customizer. @zindex-navbar: 1000; @zindex-dropdown: 1000; @zindex-navbar-fixed: 1030; @zindex-modal-background: 1040; @zindex-modal: 1050; @zindex-popover: 1060; @zindex-tooltip: 1070; //== Media queries breakpoints // //## Define the breakpoints at which your layout will change, adapting to different screen sizes. // Extra small screen / phone // Note: Deprecated @screen-xs and @screen-phone as of v3.0.1 @screen-xs: 480px; @screen-xs-min: @screen-xs; @screen-phone: @screen-xs-min; // Small screen / tablet // Note: Deprecated @screen-sm and @screen-tablet as of v3.0.1 @screen-sm: 768px; @screen-sm-min: @screen-sm; @screen-tablet: @screen-sm-min; // Medium screen / desktop // Note: Deprecated @screen-md and @screen-desktop as of v3.0.1 @screen-md: 992px; @screen-md-min: @screen-md; @screen-desktop: @screen-md-min; // Large screen / wide desktop // Note: Deprecated @screen-lg and @screen-lg-desktop as of v3.0.1 @screen-lg: 1200px; @screen-lg-min: @screen-lg; @screen-lg-desktop: @screen-lg-min; // So media queries don't overlap when required, provide a maximum @screen-xs-max: (@screen-sm-min - 1); @screen-sm-max: (@screen-md-min - 1); @screen-md-max: (@screen-lg-min - 1); @screen-size-sm-max: 767px; //== Grid system // //## Define your custom responsive grid. //** Number of columns in the grid. @grid-columns: 12; //** Padding between columns. Gets divided in half for the left and right. @grid-gutter-width: 30px; // Navbar collapse //** Point at which the navbar becomes uncollapsed. @grid-float-breakpoint: @screen-md-min; //** Point at which the navbar begins collapsing. @grid-float-breakpoint-max: (@grid-float-breakpoint - 1); //== Container sizes // //## Define the maximum width of `.container` for different screen sizes. // Small screen / tablet @container-tablet: ((720px + @grid-gutter-width)); //** For `@screen-sm-min` and up. @container-sm: @container-tablet; // Medium screen / desktop @container-desktop: ((940px + @grid-gutter-width)); //** For `@screen-md-min` and up. @container-md: @container-desktop; // Large screen / wide desktop @container-large-desktop: ((1140px + @grid-gutter-width)); //** For `@screen-lg-min` and up. @container-lg: @container-large-desktop; //== Navbar // //## // Basics of a navbar @navbar-height: 60px; @navbar-margin-bottom: 0; @navbar-border-radius: 0; @navbar-padding-horizontal: floor((@grid-gutter-width / 2)); @navbar-padding-vertical: ((@navbar-height - @line-height-computed) / 2); @navbar-collapse-max-height: 380px; @navbar-default-color: #fff; @navbar-default-bg: @ol-blue-gray-6; @navbar-default-border: transparent; // Navbar links @navbar-default-link-color: #fff; @navbar-default-link-border-color: @navbar-default-link-color; @navbar-default-link-hover-color: @ol-green; @navbar-default-link-hover-bg: @ol-green; @navbar-default-link-active-color: #fff; @navbar-default-link-active-bg: @ol-green; @navbar-default-link-disabled-color: #ccc; @navbar-default-link-disabled-bg: transparent; // Navbar brand label @navbar-default-brand-color: @navbar-default-link-color; @navbar-default-brand-hover-color: darken(@navbar-default-brand-color, 10%); @navbar-default-brand-hover-bg: transparent; // Navbar toggle @navbar-default-toggle-hover-bg: @link-hover-color; @navbar-default-toggle-border-color: @link-color; //== Navs // //## //=== Shared nav styles @nav-link-padding: 10px 15px; @nav-link-hover-bg: @link-color; @nav-disabled-link-color: @gray-light; @nav-disabled-link-hover-color: @gray-light; @nav-open-link-hover-color: #fff; //== Tabs @nav-tabs-border-color: #ddd; @nav-tabs-link-hover-border-color: @link-color; @nav-tabs-active-link-hover-bg: @body-bg; @nav-tabs-active-link-hover-color: @gray; @nav-tabs-active-link-hover-border-color: #ddd; @nav-tabs-justified-link-border-color: #ddd; @nav-tabs-justified-active-link-border-color: @body-bg; //== Pills @nav-pills-link-color: @btn-default-bg; @nav-pills-link-hover-color: @nav-link-hover-bg; @nav-pills-link-hover-bg: darken( @ol-blue-gray-4, 8% ); // match button-variant mixin @nav-pills-border-radius: @border-radius-base; @nav-pills-active-link-hover-bg: @ol-dark-green; @nav-pills-active-link-hover-color: @component-active-color; //== Pagination // //## @pagination-color: @ol-dark-green; @pagination-bg: #fff; @pagination-border: @gray-lighter; @pagination-hover-color: @ol-dark-green; @pagination-hover-bg: @gray-lightest; @pagination-hover-border: @gray-lighter; @pagination-active-color: #fff; @pagination-active-bg: @ol-dark-green; @pagination-active-border: @gray-lighter; @pagination-disabled-color: @gray-dark; @pagination-disabled-bg: @gray-lightest; @pagination-disabled-border: @gray-lighter; //== Pager // //## @pager-bg: @pagination-bg; @pager-border: @pagination-border; @pager-border-radius: 15px; @pager-hover-bg: @pagination-hover-bg; @pager-active-bg: @pagination-active-bg; @pager-active-color: @pagination-active-color; @pager-disabled-color: @pagination-disabled-color; // Plans @table-hover-bg: @ol-blue-gray-0; @plans-non-highlighted: white; //== Jumbotron // //## @jumbotron-padding: 30px; @jumbotron-color: inherit; @jumbotron-bg: @gray-lighter; @jumbotron-heading-color: inherit; @jumbotron-font-size: ceil((@font-size-base * 1.5)); //== Form states and alerts // //## Define colors for form feedback states and, by default, alerts. @state-success-text: darken(@brand-success, 20%); @state-success-bg: lighten(@brand-success, 50%); @state-success-border: darken(@brand-success, 5%); @state-info-text: darken(@brand-info, 20%); @state-info-bg: lighten(@brand-info, 47%); @state-info-border: darken(@brand-info, 7%); @state-warning-text: darken(@brand-warning, 10%); @state-warning-bg: lighten(@brand-warning, 45%); @state-warning-border: @brand-warning; @state-danger-text: darken(@brand-danger, 10%); @state-danger-bg: lighten(@brand-danger, 50%); @state-danger-border: darken(@brand-danger, 5%); //== Tooltips // //## //** Tooltip max width @tooltip-max-width: 200px; //** Tooltip text color @tooltip-color: #fff; //** Tooltip background color @tooltip-bg: #000; @tooltip-opacity: 0.9; //** Tooltip arrow width @tooltip-arrow-width: 5px; //** Tooltip arrow color @tooltip-arrow-color: @tooltip-bg; //== Popovers // //## //** Popover body background color @popover-bg: #fff; //** Popover maximum width @popover-max-width: 276px; //** Popover border color @popover-border-color: rgba(0, 0, 0, 0.2); //** Popover fallback border color @popover-fallback-border-color: #ccc; //** Popover title background color @popover-title-bg: darken(@popover-bg, 3%); //** Popover arrow width @popover-arrow-width: 10px; //** Popover arrow color @popover-arrow-color: #fff; //** Popover outer arrow width @popover-arrow-outer-width: (@popover-arrow-width + 1); //** Popover outer arrow color @popover-arrow-outer-color: fadein(@popover-border-color, 5%); //** Popover outer arrow fallback color @popover-arrow-outer-fallback-color: darken( @popover-fallback-border-color, 20% ); //== Labels // //## //** Default label background color @label-default-bg: @gray-light; //** Primary label background color @label-primary-bg: @brand-primary; //** Success label background color @label-success-bg: @brand-success; //** Info label background color @label-info-bg: @brand-info; //** Warning label background color @label-warning-bg: @brand-warning; //** Danger label background color @label-danger-bg: @brand-danger; //** Default label text color @label-color: #fff; //** Default text color of a linked label @label-link-hover-color: #fff; //== Modals // //## //** Padding applied to the modal body @modal-inner-padding: 20px; //** Padding applied to the modal title @modal-title-padding: 15px; //** Modal title line-height @modal-title-line-height: @line-height-base; //** Background color of modal content area @modal-content-bg: #fff; //** Modal content border color @modal-content-border-color: rgba(0, 0, 0, 0.2); //** Modal content border color **for IE8** @modal-content-fallback-border-color: #999; //** Modal backdrop background color @modal-backdrop-bg: #000; //** Modal backdrop opacity @modal-backdrop-opacity: 0.5; //** Modal header border color @modal-header-border-color: #e5e5e5; //** Modal footer border color @modal-footer-border-color: @modal-header-border-color; @modal-footer-background-color: @gray-lightest; @modal-lg: 900px; @modal-md: 600px; @modal-sm: 300px; //== Alerts // //## Define alert colors, border radius, and padding. @alert-padding: 15px; @alert-border-radius: @border-radius-base; @alert-link-font-weight: bold; @alert-success-bg: @brand-success; @alert-success-text: #fff; @alert-success-border: transparent; @alert-info-bg: @brand-info; @alert-info-text: #fff; @alert-info-border: transparent; @alert-warning-bg: @brand-warning; @alert-warning-text: #fff; @alert-warning-border: transparent; @alert-danger-bg: @brand-danger; @alert-danger-text: #fff; @alert-danger-border: transparent; @alert-alt-bg: @ol-blue-gray-1; @alert-alt-text: @ol-type-color; @alert-alt-border: transparent; //== Progress bars // //## //** Background color of the whole progress component @progress-bg: white; @progress-border-color: @gray-lighter; //** Progress bar text color @progress-bar-color: #fff; //** Default progress bar color @progress-bar-bg: @ol-blue-gray-4; //** Success progress bar color @progress-bar-success-bg: @ol-green; //** Warning progress bar color @progress-bar-warning-bg: @brand-warning; //** Danger progress bar color @progress-bar-danger-bg: @ol-red; //** Info progress bar color @progress-bar-info-bg: @ol-blue; //== List group // //## //** Background color on `.list-group-item` @list-group-bg: #fff; //** `.list-group-item` border color @list-group-border: #ddd; //** List group border radius @list-group-border-radius: @border-radius-base; //** Background color of single list elements on hover @list-group-hover-bg: #f5f5f5; //** Text color of active list elements @list-group-active-color: @component-active-color; //** Background color of active list elements @list-group-active-bg: @component-active-bg; //** Border color of active list elements @list-group-active-border: @list-group-active-bg; @list-group-active-text-color: lighten(@list-group-active-bg, 40%); @list-group-link-color: #555; @list-group-link-heading-color: #333; //== Panels // //## @panel-bg: #fff; @panel-body-padding: 15px; @panel-border-radius: @border-radius-base; //** Border color for elements within panels @panel-inner-border: #ddd; @panel-footer-bg: #f5f5f5; @panel-default-text: @gray-dark; @panel-default-border: #ddd; @panel-default-heading-bg: #f5f5f5; @panel-primary-text: #fff; @panel-primary-border: @brand-primary; @panel-primary-heading-bg: @brand-primary; @panel-success-text: @state-success-text; @panel-success-border: @state-success-border; @panel-success-heading-bg: @state-success-bg; @panel-info-text: @state-info-text; @panel-info-border: @state-info-border; @panel-info-heading-bg: @state-info-bg; @panel-warning-text: @state-warning-text; @panel-warning-border: @state-warning-border; @panel-warning-heading-bg: @state-warning-bg; @panel-danger-text: @state-danger-text; @panel-danger-border: @state-danger-border; @panel-danger-heading-bg: @state-danger-bg; //== Thumbnails // //## //** Padding around the thumbnail image @thumbnail-padding: 4px; //** Thumbnail background color @thumbnail-bg: @body-bg; //** Thumbnail border color @thumbnail-border: #ddd; //** Thumbnail border radius @thumbnail-border-radius: @border-radius-base; //** Custom text color for thumbnail captions @thumbnail-caption-color: @text-color; //** Padding around the thumbnail caption @thumbnail-caption-padding: 9px; //== Wells // //## @well-bg: #f5f5f5; @well-border: darken(@well-bg, 7%); //== Badges // //## @badge-color: #fff; //** Linked badge text color on hover @badge-link-hover-color: #fff; @badge-bg: @gray-light; //** Badge text color in active nav link @badge-active-color: @link-color; //** Badge background color in active nav link @badge-active-bg: #fff; @badge-font-weight: bold; @badge-line-height: 1; @badge-border-radius: 10px; //== Breadcrumbs // //## @breadcrumb-padding-vertical: 8px; @breadcrumb-padding-horizontal: 15px; //** Breadcrumb background color @breadcrumb-bg: #f5f5f5; //** Breadcrumb text color @breadcrumb-color: #ccc; //** Text color of current page in the breadcrumb @breadcrumb-active-color: @gray-light; //** Textual separator for between breadcrumb elements @breadcrumb-separator: '/'; //== Carousel // //## @carousel-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6); @carousel-control-color: #fff; @carousel-control-width: 15%; @carousel-control-opacity: 0.5; @carousel-control-font-size: 20px; @carousel-indicator-active-bg: #fff; @carousel-indicator-border-color: #fff; @carousel-caption-color: #fff; //== Close // //## @close-font-weight: bold; @close-color: #000; @close-text-shadow: 0 1px 0 #fff; //== Code // //## @code-color: #c7254e; @code-bg: #f9f2f4; @kbd-color: #fff; @kbd-bg: #333; @pre-bg: #f5f5f5; @pre-color: @gray-dark; @pre-border-color: #ccc; @pre-scrollable-max-height: 340px; //== Type // //## //** Text muted color @text-muted: @gray-light; //** Abbreviations and acronyms border color @abbr-border-color: @gray-light; //** Headings small color @headings-small-color: @gray-light; //** Blockquote small color @blockquote-small-color: @ol-blue-gray-3; //** Blockquote font size @blockquote-font-size: (@font-size-base * 1.125); //** Blockquote border color @blockquote-border-color: @gray-lighter; //** Page header border color @page-header-border-color: @gray-lighter; //== Miscellaneous @editor-search-count-color: @ol-blue-gray-4; //## //** Horizontal line color. @hr-border: @ol-blue-gray-1; //** Horizontal offset for forms and lists. @component-offset-horizontal: 180px; @content-margin-vertical: @line-height-computed; @left-menu-width: 260px; @left-menu-animation-duration: 0.35s; @toolbar-border-color: @ol-blue-gray-5; @toolbar-header-btn-border-color: @toolbar-border-color; @common-border-color: @gray-lighter; @editor-border-color: @ol-blue-gray-5; @editor-dark-background-color: #333; @editor-dark-toolbar-border-color: #222; @editor-dark-highlight-color: #ffa03a; // Custom @header-height: 68px; @footer-height: 50px; // Backgrounds @content-alt-bg-color: @ol-blue-gray-0; // Typography @text-small-color: @ol-type-color; // Navbar @navbar-title-color: @ol-blue-gray-1; @navbar-title-color-hover: @ol-blue-gray-2; @navbar-default-padding-v: (@grid-gutter-width / 2); @navbar-default-padding-h: 10px; @navbar-default-padding: @navbar-default-padding-v @navbar-default-padding-h; @navbar-brand-width: 130px; @navbar-btn-font-size: @font-size-base; @navbar-btn-border-radius: @btn-border-radius-base; @navbar-btn-font-weight: 400; @navbar-btn-padding: (@padding-base-vertical - 1) @padding-base-horizontal @padding-base-vertical; @navbar-btn-line-height: @line-height-base; @navbar-subdued-padding: (@padding-base-vertical + 1) (@padding-base-horizontal + 1) (@padding-base-vertical + 2); @navbar-subdued-color: #fff; @navbar-subdued-hover-bg: #fff; @navbar-subdued-hover-color: @ol-green; @navbar-brand-image-url: url(/img/ol-brand/overleaf-white.svg); @dropdown-divider-margin: 6px; @dropdown-item-padding: 4px 20px; @navbar-default-link-bg: transparent; // Button colors and sizing @btn-border-radius-large: 9999px; @btn-border-radius-base: 9999px; @btn-border-radius-small: 9999px; @btn-border-width: 0; @btn-border-bottom-width: 0; // Cards @card-box-shadow: none; // Project table @structured-list-link-color: @ol-blue; @structured-header-border-color: shade(@ol-blue-gray-1, 5%); @structured-list-border-color: @ol-blue-gray-1; @structured-list-hover-color: lighten(@ol-blue-gray-1, 5%); @structured-list-line-height: 2.5; // Sidebar @sidebar-bg: @ol-blue-gray-5; @sidebar-color: @ol-blue-gray-2; @sidebar-link-color: #fff; @sidebar-active-border-radius: 0; @sidebar-active-bg: @ol-blue-gray-6; @sidebar-active-color: #fff; @sidebar-active-font-weight: 700; @sidebar-hover-bg: @ol-blue-gray-4; @sidebar-hover-text-decoration: none; @v2-dash-pane-bg: @ol-blue-gray-4; @v2-dash-pane-link-color: #fff; @v2-dash-pane-color: #fff; @v2-dash-pane-toggle-color: #fff; @v2-dash-pane-btn-bg: @ol-blue-gray-5; @v2-dash-pane-btn-hover-bg: @ol-blue-gray-6; @folders-menu-margin: 0 - (@grid-gutter-width / 2); @folders-menu-line-height: @structured-list-line-height; @folders-menu-item-v-padding: (@line-height-computed / 4); @folders-menu-item-h-padding: (@grid-gutter-width / 2); @folders-title-padding: @folders-menu-item-v-padding 0; @folders-title-margin-top: 0; @folders-title-margin-bottom: 0; @folders-title-font-size: @font-size-small; @folders-title-font-weight: normal; @folders-title-line-height: @headings-line-height; @folders-title-color: @ol-blue-gray-2; @folders-title-text-transform: uppercase; @folders-tag-padding: @folders-menu-item-v-padding 20px @folders-menu-item-v-padding @folders-menu-item-h-padding; @folders-tag-line-height: 1.4; @folders-tag-display: block; @folders-tag-menu-color: #fff; @folders-tag-hover: @sidebar-hover-bg; @folders-tag-border-color: @folders-tag-menu-color; @folders-tag-menu-active-hover: rgba(0, 0, 0, 0.1); @folders-tag-menu-hover: rgba(0, 0, 0, 0.1); @info-badge-bg: @ol-blue; // Progress bars @progress-border-radius: @line-height-computed; @progress-border-width: 0; @progress-bar-shadow: none; // Footer @footer-link-color: @link-color-alt; @footer-link-hover-color: @link-hover-color-alt; @footer-bg-color: #fff; @footer-padding: 2em 0; // Editor header @ide-body-top-offset: 40px; @toolbar-header-bg-color: @ol-blue-gray-6; @toolbar-header-shadow: none; @toolbar-header-branded-btn-bg-color: transparent; @toolbar-btn-color: #fff; @toolbar-btn-hover-color: #fff; @toolbar-btn-hover-bg-color: @ol-blue-gray-5; @toolbar-btn-hover-text-shadow: none; @toolbar-btn-active-color: #fff; @toolbar-btn-active-bg-color: @ol-green; @toolbar-btn-active-shadow: none; @toolbar-font-size: 13px; @toolbar-alt-bg-color: @ol-blue-gray-5; @toolbar-icon-btn-color: #fff; @toolbar-icon-btn-hover-color: #fff; @toolbar-icon-btn-hover-shadow: none; @toolbar-icon-btn-hover-boxshadow: none; @toolbar-border-bottom: 1px solid @toolbar-border-color; @toolbar-small-height: 32px; @toolbar-tall-height: 58px; @project-name-color: @ol-blue-gray-2; @project-rename-link-color: @ol-blue-gray-2; @project-rename-link-color-hover: @ol-blue-gray-1; @global-alerts-padding: 7px; // Editor file-tree @file-tree-bg: @ol-blue-gray-4; @file-tree-line-height: 2.05; @file-tree-item-color: #fff; @file-tree-item-focus-color: @file-tree-item-color; @file-tree-item-selected-color: @file-tree-item-color; @file-tree-item-toggle-color: @ol-blue-gray-2; @file-tree-item-icon-color: @ol-blue-gray-2; @file-tree-item-input-color: @ol-blue-gray-5; @file-tree-item-folder-color: @ol-blue-gray-2; @file-tree-item-hover-bg: @ol-blue-gray-5; @file-tree-item-selected-bg: @ol-green; @file-tree-multiselect-bg: @ol-blue; @file-tree-multiselect-hover-bg: @ol-dark-blue; @file-tree-droppable-bg-color: @ol-blue-gray-2; @file-tree-error-color: @ol-blue-gray-1; // File outline @outline-v-rhythm: 24px; @outline-h-rhythm: 24px; @outline-item-h-padding: @outline-h-rhythm * 0.25; @outline-line-guide-color: @ol-blue-gray-3; @outline-expand-collapse-color: @ol-blue-gray-2; @outline-no-items-color: @file-tree-item-color; @outline-header-hover-bg: @ol-blue-gray-6; @outline-highlight-bg: tint(@file-tree-bg, 15%); @vertical-resizable-resizer-bg: @ol-blue-gray-5; @vertical-resizable-resizer-hover-bg: @ol-blue-gray-6; // Editor resizers @editor-resizer-bg-color: @ol-blue-gray-5; @editor-resizer-bg-color-dragging: @ol-blue-gray-5; @editor-toggler-bg-color: darken(@ol-blue-gray-2, 15%); @editor-toggler-hover-bg-color: @ol-green; @synctex-controls-z-index: 6; @synctex-controls-padding: 0; // Editor toolbar @editor-toolbar-height: 32px; @editor-toolbar-bg: @ol-blue-gray-5; // Toggle switch @toggle-switch-bg: @ol-blue-gray-1; @toggle-switch-highlight-color: @ol-green; // Formatting buttons @formatting-btn-color: #fff; @formatting-btn-bg: @ol-blue-gray-5; @formatting-btn-border: @ol-blue-gray-4; @formatting-menu-bg: @ol-blue-gray-5; // Chat @chat-bg: @ol-blue-gray-5; @chat-instructions-color: @ol-blue-gray-1; @chat-message-color: #fff; @chat-message-date-color: @ol-blue-gray-2; @chat-message-name-color: #fff; @chat-message-box-shadow: none; @chat-message-border-radius: @border-radius-large; @chat-message-padding: 5px 10px; @chat-message-weight: bold; @chat-new-message-bg: @ol-blue-gray-4; @chat-new-message-textarea-bg: @ol-blue-gray-1; @chat-new-message-textarea-color: @ol-blue-gray-6; @chat-new-message-border-color: @editor-border-color; // PDF and logs @pdf-top-offset: @toolbar-small-height; @pdf-bg: @ol-blue-gray-1; @pdfjs-bg: transparent; @pdf-page-shadow-color: rgba(0, 0, 0, 0.5); @logs-pane-bg: @ol-blue-gray-5; @log-line-no-color: #fff; @log-hints-color: @ol-blue-gray-4; // Tags @tag-border-radius: 9999px; @tag-color: @ol-blue-gray-4; @tag-bg-color: @ol-blue-gray-1; @tag-bg-hover-color: darken(@ol-blue-gray-1, 5%); @tag-max-width: 150px; @tag-top-adjustment: 2px; @labels-font-size: 85%; // System messages @sys-msg-background: @ol-blue; @sys-msg-color: #fff; @sys-msg-border: solid 1px lighten(@ol-blue, 10%); // Portals @black-alpha-strong: rgba(0, 0, 0, 0.8); @btn-portal-width: 200px; // v2 History @history-base-font-size: @font-size-small; @history-base-bg: @ol-blue-gray-1; @history-entry-label-bg-color: @ol-blue; @history-entry-pseudo-label-bg-color: @ol-green; @history-entry-label-color: #fff; @history-entry-selected-label-bg-color: #fff; @history-entry-selected-label-color: @ol-blue; @history-entry-selected-pseudo-label-color: @ol-green; @history-entry-day-bg: @ol-blue-gray-1; @history-entry-day-color: @ol-blue-gray-3; @history-entry-selected-bg: @ol-green; @history-entry-handle-bg: darken(@ol-green, 10%); @history-entry-handle-height: 8px; @history-base-color: @ol-blue-gray-3; @history-highlight-color: @ol-type-color; @history-toolbar-bg-color: @editor-toolbar-bg; @history-toolbar-color: #fff; @history-file-badge-bg: rgba(255, 255, 255, 0.25); @history-file-badge-color: @file-tree-item-color; // Input suggestions @input-suggestion-v-offset: 4px; // Symbol Palette @symbol-palette-bg: @ol-blue-gray-4; @symbol-palette-color: #fff; @symbol-palette-header-background: @ol-blue-gray-5; @symbol-palette-item-bg: @ol-blue-gray-5; @symbol-palette-item-color: #fff; @symbol-palette-selected-tab-bg: @ol-blue-gray-4; @symbol-palette-selected-tab-color: #fff;
overleaf/web/frontend/stylesheets/core/variables.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/core/variables.less", "repo_id": "overleaf", "token_count": 12222 }
535
{ "unlink_github_repository": "Odlinkovat Github repozitář", "unlinking": "Odlinkovávám", "github_no_master_branch_error": "Tento repozitář nemůže být importován, protože nemá master branch. Prosím zajistěte, aby projekt měl master branch.", "confirmation_token_invalid": "Omlováme se, ale Váš potvrzovací kód je neplatný nebo vypršel. Prosím požádejte o nový potrvzovací e-mail.", "confirmation_link_broken": "Omlouváme se, ale něco není v pořádku s Vaším potvrzovacím kódem. Prosíme zkuste zkopírovat odkaz z konce Vašeho potvrzovacího e-mailu.", "duplicate_file": "Zduplikovat soubor", "file_already_exists_in_this_location": "Soubor <0>__fileName__</0> již v daném umístění existuje. Pokud chcete tento soubor přesunout, nejprve přejmenujte nebo odstraňte ten existující.", "group_full": "Tato skupina je již naplněna.", "no_selection_select_file": "Nevybrali jste žádný soubor.", "no_selection_create_new_file": "Ve Vašem projektu nejsou žádné soubory. Prosíme vytvořte nový soubor.", "files_selected": "souborů označeno.", "home": "Domů", "this_action_cannot_be_undone": "Tuto akci nepůjde vrátit zpět!", "token_access_success": "Přístup umožněn", "token_access_failure": "Přístup odepřen; kontaktujte prosím majitele projektu", "trashed_projects": "Koš", "trash": "Vyhodit do koše", "untrash": "Obnovit", "delete_and_leave": "Odstranit / Opustit", "trash_projects": "Vyhodit projekty do koše", "about_to_trash_projects": "Chystáte se vyhodit do koše následující projekty:", "archived_projects_info_note": "Archiv projektů je teď samostatný pro každého uživatele. Pokud archivujete nějaký projekt, bude archivovaný pouze pro Vás, ale už ne pro Vaše spolupracovníky.", "trashed_projects_info_note": "__appName__ zavedl Koš pro projekty, které chcete vyhodit. Pokud vyhodíte projekt do koše, neprojeví se to u vašich spolupracovníků.", "project_ownership_transfer_confirmation_1": "Opravdu chcete změnit majitele projektu <1>__project__</1> na uživatele <0>__user__</0>?", "project_ownership_transfer_confirmation_2": "Tuto akci nebudete moci vrátit. Nový majitel bude o změně informován, a bude moci změnit přístupová práva, včetně možnosti zamezit Vám v přístupu.", "change_owner": "Změnit majitele", "change_project_owner": "Změnit majitele projektu", "faq_pay_by_invoice_answer": "Pokud chcete pořídit skupinový účet nebo síťovou licenci a rádi byste platbu fakturou\nnebo potřebujete služby na základě objednávkového listi, prosíme <0>dejte nám vědět</0>.\nIndividuální účty a skupiny s měsíční fakturací je možné objednat jedině online a platit pouze pomocí platební karty nebo PayPalu.", "password_too_long_please_reset": "Překročili jste maximální délku hesla. Prosíme změňte si heslo.", "projects": "Projekty", "upload_project": "Nahrát projekt", "all_projects": "Všechny projekty", "your_projects": "Vaše projekty", "shared_with_you": "Sdílené s Vámi", "deleted_projects": "Smazané projekty", "templates": "Šablony", "new_folder": "Nová složka", "create_your_first_project": "Vytvořte svůj první projekt!", "complete": "Hotovo", "on_free_sl": "Používáte bezplatnou verzi __appName__", "upgrade": "Upgrade", "or_unlock_features_bonus": "Odemkněte některé bonusové funkce", "sharing_sl": "sdílením __appName__", "add_to_folder": "Přidat do složky", "create_new_folder": "Vytvořit novou složku", "more": "Více", "rename": "Přejmenovat", "make_copy": "Zkopírovat", "restore": "Obnovit", "title": "Název", "last_modified": "Naposledy změněno", "no_projects": "Žádné projekty", "welcome_to_sl": "Vítejte v __appName__!", "new_to_latex_look_at": "Začínáte s LaTeXem? Podívejte se na naše", "or": "nebo", "or_create_project_left": "nebo nalevo vytvořit váš prví projekt.", "thanks_settings_updated": "Děkujeme, vaše nastavení bylo aktualizováno.", "update_account_info": "Aktualizovat informace o účtu", "must_be_email_address": "Musíte zadat emailovou adresu", "first_name": "Jméno", "last_name": "Příjmení", "update": "Aktualizovat", "change_password": "Změnit heslo", "current_password": "Aktuální heslo", "new_password": "Nové heslo", "confirm_new_password": "Potvrdit nové heslo", "required": "Povinná položka", "doesnt_match": "Nesouhlasí", "dropbox_integration": "Integrace s Dropboxem", "learn_more": "Zjistit více", "dropbox_is_premium": "Synchronizace s Dropboxem je prémiová funkce.", "account_is_linked": "Účet je spojen", "unlink_dropbox": "Odpojit Dropbox", "link_to_dropbox": "Připojit k Dropboxu", "newsletter_info_and_unsubscribe": "Každých pár měsíců posíláme newsletter shrnující všechny nové funkce. Pokud o něj nestojíte, můžete odběr kdykoliv zrušit:", "unsubscribed": "Odběr zrušen", "unsubscribing": "Ruším odběr", "unsubscribe": "Zrušit odběr", "need_to_leave": "Potřebujete odejít?", "delete_your_account": "Smazat váš účet", "delete_account": "Smazat účet", "delete_account_warning_message": "Chystáte se nenávratně <strong>vymazat všechna svá data</strong>, včetně projektů a nastaveni. Pro pokračování zadejte svou e-mailovou adresu.", "deleting": "Smazávám", "delete": "Smazat", "sl_benefits_plans": "__appName__ je nejsnáze použitelný LaTeX editor na světě. Spolupracujte rychle a online, sledujte všechny změny ve vaší práci a používejte LaTeX odkudkoli ze světa.", "monthly": "Měsíční", "personal": "Personal", "free": "Zdarma", "one_collaborator": "Jen jeden spolupracovník", "collaborator": "Collaborator", "collabs_per_proj": "__collabcount__ spolupracovníků na projektu", "full_doc_history": "Celá historie dokumentu", "sync_to_dropbox": "Synchronizujte s Dropboxem", "start_free_trial": "Začněte s trial verzí zdarma!", "professional": "Professional", "unlimited_collabs": "Neomezený počet spolupracovníků", "name": "Jméno", "student": "Student", "university": "Univerzita", "position": "Pozice", "choose_plan_works_for_you": "Vyberte tarif, který vám vyhovuje s naší bezplatnou __len__denní zkušební. Můžete ho kdykoliv zrušit.", "interested_in_group_licence": "Rádi byste využili jeden učet __appName__ pro skupiny, týmy nebo oddělení?", "get_in_touch_for_details": "Napište nám o detaily!", "group_plan_enquiry": "Poptávka skupinového tarifu", "enjoy_these_features": "Užijte si všechny tyto úžasné funkce", "create_unlimited_projects": "Vytvořte tolik projektů kolik potřebujete.", "never_loose_work": "Nemějte obavy, kryjeme vám záda.", "access_projects_anywhere": "Přistupujte ke svým projektům odkudkoliv.", "log_in": "Přihlásit se", "login": "Přihlášení", "logging_in": "Přihlašuji", "forgot_your_password": "Zapomenuté heslo", "password_reset": "Resetovat heslo", "password_reset_email_sent": "Byl vám zaslán email pro dokončení resetu vašeho hesla.", "please_enter_email": "Zadejte prosím svou emailovou adresu", "request_password_reset": "Požádat o resetování hesla", "reset_your_password": "Resetovat heslo", "password_has_been_reset": "Vaše heslo bylo resetováno", "login_here": "Přihlašte se zde", "set_new_password": "Nastavit nové heslo", "user_wants_you_to_see_project": "Uživatel __username__ by se rád přidal k projektu __projectname__", "join_sl_to_view_project": "Pro zobrazení tohoto projektu se přihlašte do __appName__.", "register_to_edit_template": "Pro úpravu šablony __templateName__ se prosím přihlašte", "already_have_sl_account": "Máte už účet v __appName__?", "register": "Registrovat", "password": "Heslo", "registering": "Registruji", "planned_maintenance": "Plánovaná odstávka", "no_planned_maintenance": "V současnosti není plánovaná žádná odstávka", "cant_find_page": "Je nám líto, ale nemůžeme najít stránku, kterou hledáte.", "take_me_home": "Vezmi mě zpět!", "no_preview_available": "Je nám líto, ale náhled není k dispozici.", "no_messages": "Žádné zprávy", "send_first_message": "Pošlete svou první zprávu spolupracovníkům", "account_not_linked_to_dropbox": "Váš účet není spojen s Dropboxem", "update_dropbox_settings": "Aktualizovat nastavení Dropboxu", "refresh_page_after_starting_free_trial": "Obnovte prosím stránku poté co začnete používat svou bezplatnou trial verzi.", "checking_dropbox_status": "kontroluji stav Dropboxu", "dismiss": "Zamítnout", "deleted_files": "Smazané soubory", "new_file": "Nový soubor", "upload_file": "Nahrát soubor", "create": "Vytvořit", "creating": "Vytvářím", "upload_files": "Nahrát soubor(y)", "sure_you_want_to_delete": "Opravdu chcete nenávratně smazat následující soubory?", "common": "Běžné", "navigation": "Pro navigaci", "editing": "Pro úpravy", "ok": "OK", "source": "Zdroj", "actions": "Akce", "copy_project": "Kopírovat projekt", "publish_as_template": "Publikovat jako šablonu", "sync": "Synchronizace", "settings": "Nastavení", "main_document": "Hlavní dokument", "off": "Vypnuto", "auto_complete": "Automatické dokončování", "theme": "Vzhled", "font_size": "Velikost písma", "pdf_viewer": "Prohlížeč PDF", "built_in": "Vestavěný", "native": "Výchozí", "show_hotkeys": "Zobrazit zkratky", "new_name": "Nové jméno", "copying": "Kopíruji", "copy": "Kopírovat", "compiling": "Kompiluji", "click_here_to_preview_pdf": "Klikněte zde pro náhled vaší práce v PDF.", "server_error": "Chyba serveru", "somthing_went_wrong_compiling": "Omlouváme se, ale něco se pokazilo a váš projekt nemůže být zkompilován. Zkuste to prosím znovu za pár okamžiků.", "timedout": "Vypršel čas", "proj_timed_out_reason": "Omlouváme se, ale kompilate trvala příliš dlouho a. Tato situace může být způsobena velkým množstvím obrázků ve vysokém rozlišení, nebo spoustou složitých diagramů.", "no_errors_good_job": "Bez chyby, dobrá práce!", "compile_error": "Chyba kompilace", "generic_failed_compile_message": "Je nám líto, ale váš LaTeX kód nemůže být z nějakého důvodu zkompilován. Pro detaily zkontrolujte chybová hlášení níže, nebo zobrazte log.", "other_logs_and_files": "Ostatní logy a soubory", "view_raw_logs": "Zobrazit logy", "hide_raw_logs": "Skrýt logy", "clear_cache": "Vymazat cache", "clear_cache_explanation": "Tímto odstraníte veškeré skryté soubory LaTeXu (.aux, .bbl, atd) z našeho serveru. Nemusíte to dělat pokud nemáte problémy s odkazy.", "clear_cache_is_safe": "Váš projekt nebude smazán nebo změněn.", "clearing": "Odstraňuji", "template_description": "Popis šablony", "project_last_published_at": "Váš projekt byl naposledy publikován", "problem_talking_to_publishing_service": "Vyskytl se problém s naší publikační službou, zkuste to prosím znovu za pár minut", "unpublishing": "Ruším publikování", "republish": "Publikovat znovu", "publishing": "Publikuji", "share_project": "Sdílet projekt", "this_project_is_private": "Tento projekt je soukromý a přístupný pouze lidem níže.", "make_public": "Nastavit jako veřejný", "this_project_is_public": "Tento projekt je veřejný a editovatelný kýmkoliv s URL.", "make_private": "Nastavit jako soukromý", "can_edit": "Může upravovat", "share_with_your_collabs": "Sdílet s vašimi spolupracovníky", "share": "Sdílet", "need_to_upgrade_for_more_collabs": "Pro přidání více spolupracovníků musíte upgradovat svůj účet.", "make_project_public": "Nastavit projekt jako veřejný.", "make_project_public_consequences": "Pokud váš projekt uděláte veřejným bude k němu moct přistoupit každý s URL.", "allow_public_editing": "Povolit veřejné editování", "allow_public_read_only": "Povolte veřejný přístup pouze pro čtení", "make_project_private": "Vypnout sdílení odkazem.", "make_project_private_consequences": "Pokud svůj projekt označíte jako soukromý, budou mít k němu přístup jen lidé, které určíte.", "need_to_upgrade_for_history": "Pro použití funkce Historie musíte upgradovat svůj účet.", "ask_proj_owner_to_upgrade_for_history": "Požádejte prosím vlastníka projektu o upgrade ať můžete používat funkci Historie.", "anonymous": "Anonymní", "generic_something_went_wrong": "Omlouváme se, ale něco je špatně.", "restoring": "Obnovuji", "restore_to_before_these_changes": "Obnovit stav před těmito změnami", "profile_complete_percentage": "Váš profil je hotový z __percentval__ %", "file_has_been_deleted": "__filename__ byl vymazán", "sure_you_want_to_restore_before": "Opravdu chcete obnovit <0>__filename__</0> do stavu před změnami k __date__?", "rename_project": "Přejmenovat projekt", "about_to_delete_projects": "Chcete smazat následující projekty:", "about_to_leave_projects": "Chystáte se ponechat následující projekty:", "upload_zipped_project": "Nahrát zazipovaný projekt", "upload_a_zipped_project": "Nahrát zazipovaný projekt", "your_profile": "Váš profil", "institution": "Instituce", "role": "Úloha", "folders": "Složky", "disconnected": "Odpojeno", "please_refresh": "Pro pokračování prosím obnovte stránku.", "lost_connection": "Připojení ztraceno", "reconnecting_in_x_secs": "Obnovuji připojení za __seconds__ sek", "try_now": "Vyzkoušejte teď", "reconnecting": "Obnovuji připojení", "saving_notification_with_seconds": "Ukládám __docname__... (__seconds__ sek neuložených změn)", "help_us_spread_word": "Pomozte nám šířit povědomí o __appName__", "share_sl_to_get_rewards": "Sdílejte __appName__ s vašimi přáteli a kolegy a získejte odměny níže", "post_on_facebook": "Publikovat na Facebooku", "share_us_on_googleplus": "Sdílejte nás na Google+", "email_us_to_your_friends": "Pošlete o nás email svým přátelům", "link_to_us": "Odkazujte na nás ze svého webu", "direct_link": "Přímý odkaz", "sl_gives_you_free_stuff_see_progress_below": "Když začne někdo používat __appName__ na základě vašeho doporučení, dáme vám <strong>něco zdarma</strong> jako poděkování! Níže můžete sledovat váš postup.", "spread_the_word_and_fill_bar": "Řekněte o nás někomu a vyplňte tento pruh", "one_free_collab": "Jeden spolupracovník zdarma", "three_free_collab": "Tři spolupracovníci zdarma", "free_dropbox_and_history": "Zdarma Dropbox a Historie", "you_not_introed_anyone_to_sl": "Zatím jste __appName__ nikomu nedoporučili. Začněte sdílet!", "you_introed_small_number": " Představili jste __appName__ <0>__numberOfPeople__</0> lidem. Dobrá práce, ale zvládnete víc?", "you_introed_high_number": " Představili jste __appName__ <0>__numberOfPeople__</0> lidem. Dobrá práce!", "link_to_sl": "Odkaz na __appName__", "can_link_to_sl_with_html": "Můžete odkázat na __appName__ pomocí následujícího HTML kódu:", "year": "rok", "month": "měsíc", "subscribe_to_this_plan": "Předplaťte si tento tarif", "your_plan": "Váš tarif", "your_subscription": "Vaše předplatné", "on_free_trial_expiring_at": "Používáte bezplatnou trial verzi, která vyprší __expiresAt__.", "choose_a_plan_below": "Pro předplatné vyberte z tarifů níže.", "currently_subscribed_to_plan": "Máte předplacen tarif <0>__planName__</0>.", "change_plan": "Změnit tarif", "next_payment_of_x_collectected_on_y": "Další platba <0>__paymentAmmount__</0> bude stržena <1>__collectionDate__</1>", "update_your_billing_details": "Aktualizujte své fakturační údaje", "subscription_canceled_and_terminate_on_x": " Vaše předplatné bylo zrušeno a bude ukončeno k <0>__terminateDate__</0>. Žádná další platba nebude stržena.", "your_subscription_has_expired": "Vaše předplatné vypršelo.", "create_new_subscription": "Vytvořit nové předplatné.", "problem_with_subscription_contact_us": "Vyskytly se problémy s vaším předplatným. Kontaktujte nás prosím pro více informací.", "manage_group": "Spravovat skupinu", "loading_billing_form": "Načítám formulář s fakturačními údaji", "you_have_added_x_of_group_size_y": "Přidal jste <0>__addedUsersSize__</0> z <1>__groupSize__</1> možných členů", "remove_from_group": "Odstranit ze skupiny", "group_account": "Účet skupiny", "registered": "Registrováno", "no_members": "Žádní členové", "add_more_members": "Přidat více členů", "add": "Přidat", "thanks_for_subscribing": "Děkujeme za odběr!", "your_card_will_be_charged_soon": "Z vaší karty bude brzy stržena platba.", "if_you_dont_want_to_be_charged": "Pokud nechcete aby vám byla stržena další platba ", "add_your_first_group_member_now": "Přidejte do vaší skupiny prvního člena", "thanks_for_subscribing_you_help_sl": "Děkujeme za předplacení tarifu __planName__. Podpora od lidí jako jste vy je to, co umožňuje, aby __appName__ rostl a zlepšoval se.", "back_to_your_projects": "Zpět k vašim projektům", "goes_straight_to_our_inboxes": "Přijde to přímo do obou našich schránek", "need_anything_contact_us_at": "Pokud vám můžeme s čímkoliv pomoci, nebojte se na nás obrátit na", "regards": "S pozdravem", "about": "O nás", "comment": "Komentář", "restricted_no_permission": "Důvěrné; omlouváme se, ale nemáte dostatečná práva k zobrazení této stránky.", "online_latex_editor": "Online LaTeX editor", "meet_team_behind_latex_editor": "Poznejte tým, který stojí za vašim oblíbením online LaTeX editorem:", "follow_me_on_twitter": "Sledujte mě na Twitteru", "motivation": "Motivace", "evolved": "pro budoucnost", "the_easy_online_collab_latex_editor": "Online LaTeX editor snadný k použití s možností spolupráce více autorů", "get_started_now": "Začněte hned", "sl_used_over_x_people_at": "__appName__ používá více než __numberOfUsers__ studentů a akademiků z:", "collaboration": "Spolupráce", "work_on_single_version": "Pracujte společně na jedné verzi", "view_collab_edits": "Sledujte úpravy spolupracovníků ", "ease_of_use": " Snadné použití", "no_complicated_latex_install": "Nemusíte instalovat LaTeX", "all_packages_and_templates": "Máme všechny balíčky a <0>__templatesLink__</0> které potřebujete", "document_history": "Historie dokumentu", "see_what_has_been": "Podívejte se, co bylo ", "added": "přidáno", "and": "a", "removed": "odstraněno", "restore_to_any_older_version": "Obnovujte ze starší verze", "work_from_anywhere": "Pracujte odkudkoliv", "acces_work_from_anywhere": "Mějte přístup ke své práci kdekoliv na světě", "work_offline_and_sync_with_dropbox": "Pracujte offline a synchronizujte svá data přes Dropbox a GitHub", "over": "více než", "view_templates": "Zobrazit šablony", "nothing_to_install_ready_to_go": "Není tady nic komplikovaného ani obtížného k instalaci, můžete <0>__start_now__</0>, i když jste ho nikdy předtím neviděli. __appName__ má zabudováno kompletní LaTeX prostředí běžící na našich serverech.", "start_using_latex_now": "začít používat LaTeX právě teď", "get_same_latex_setup": "S __appName__ máte stále to stejné nastavení LaTeXu, ať jste kdekoliv. Můžete se spolehnout, že při spolupráci s vašimi kolegy a studenty v __appName__ nenarazíte na problémy s různými verzemi nebo balíčky.", "support_lots_of_features": "Podporujeme téměř všechny funkce LaTeXu, včetně vkládání obrázků, bibliografie, rovnic a mnohem více! Přečtěte si o všech těch úžasných věcech, které můžete v __appName__ dělat, v našem <0>__help_guides_link__</0>", "latex_guides": "Průvodci LaTeXem", "reset_password": "Resetovat heslo", "set_password": "Nastavit heslo", "updating_site": "Upravuji stránku", "bonus_please_recommend_us": "Bonus - Doporučte nás prosím", "admin": "administrátor", "subscribe": "Odebírat novinky", "update_billing_details": "Aktualizovat fakturační údaje", "group_admin": "Administrátor skupiny", "all_templates": "Všechny šablony", "your_settings": "Vaše nastavení", "maintenance": "Údržba", "to_many_login_requests_2_mins": "Tento účet má příliš mnoho žádostí o přihlášení. Počkejte prosím 2 minuty před dalším pokusem.", "email_or_password_wrong_try_again": "Váš email, nebo heslo není správně.", "rate_limit_hit_wait": "Byla dosažena mezní hodnota. Počkejte prosím před dalším pokusem.", "problem_changing_email_address": "Nastal problém při změně vaší emailové adresy.Prosíme zkuste to za okamžik znovu. Pokud problémy přetrvají, kontaktujte nás.", "single_version_easy_collab_blurb": "__appName__ garantuje, že budete vždy synchronizovaní se svými spolupracovníky a s tím, co dělají. Existuje pouze jedna hlavní verze každého dokumentu, ke které má každý přístup. Je nemožné způsobit konflikt a vy tak nemusíte čekat, až ostatní dokončí svou práci a pošlou vám poslední verzi.", "can_see_collabs_type_blurb": "Pokud chce více lidí spolupracovat na jednom dokumentu, klidně můžou. Uvidíte, kde přesně vaši kolegové píšou, a to přímo v editoru. Jejich změny se vám ukážou okamžitě.", "work_directly_with_collabs": "Pracujte přímo se svými spolupracovníky", "work_with_word_users": "Pracujte s uživateli Wordu", "work_with_word_users_blurb": "Je tak jednoduché začít v __appName__. Můžete pozvat ke spolupráci vaše kolegy, kteří LaTeX neumí použít. Budou produktivní od prvního dne a budou postupně vstřebávat LaTeX krok za krokem.", "view_which_changes": "Zobrazit, co bylo", "sl_included_history_of_changes_blurb": "__appName__ uchovává historii všech vašich změn, takže můžete vidět, kdo změnil co a kdy. Díky tomu můžete velmi snadno držet krok s vašimi spolupracovníky a kontrolovat průběh práce.", "can_revert_back_blurb": "Při samostatné i skupinové práci můžou vzniknout chyby. Vrátit se k předchozí verzi je snadné a vy se tak nemusíte obávat ztráty dat nebo nechtěných změn.", "start_using_sl_now": "Začněte v __appName__ právě teď", "over_x_templates_easy_getting_started": "V naší galerii naleznete tísíce __templates__, takže he opravdu jednoduché začít, ať už chcete psát článek do časopisu, závěrečnou práci, CV, nebo něco jiného.", "done": "Hotovo", "change": "Změnit", "page_not_found": "Stránka nenalezena", "please_see_help_for_more_info": "Pro více informací prosím navštivte našeho průvodce nápovědou", "this_project_will_appear_in_your_dropbox_folder_at": "Tento projekt se objeví ve vaší Dropbox složce jako ", "member_of_group_subscription": "Jste členem skupiny předplatitelů spravované __admin_email__. Kontaktujte ho prosím pro správu svého předplatného.\n", "about_henry_oswald": "je softwarový vývojář žijící v Londýně. Vytvořil původní prototyp __appName__ a byl zodpovědný za tvorbu stabilní, rostoucí platformy. Henry je velkým zastáncem programování řízeného testy (TDD) a pravidelně se ujišťuje, že kód ShareLaTeXu zůstává čistý a snadný na údržbu.", "about_james_allen": "má Ph.D. v teoretické fyzice a zbožňuje LaTeX. Vytvořil jeden z prvních online LaTeX editorů, ScribTeX, a sehrál důležitou úlohu ve vývoji technologií, díky kterým __appName__ funguje.", "two_strong_principles_behind_sl": "Za naší prací na __appName__ jsou dvě silné hnací zásady:", "want_to_improve_workflow_of_as_many_people_as_possible": "Chceme vylepšit pracovní postup u tolika lidí, u kolika to jen bude možné.", "detail_on_improve_peoples_workflow": "LaTeX je často velmi náročný k používání a spolupráce s více autory obtížně koordinovatelná. Věříme, že jsme vyvinuli skvělé řešení, které dokáže pomoct lidem čelícím takovým problémům, a chceme si být jisti, že je jim __appName__ co nejvíce přístupný. Snažíme se držet naše ceny férové a navíc jsme většinu kódu __appName__ uvolnili jako otevřený software, takže si může každý hostovat svůj.", "want_to_create_sustainable_lasting_legacy": "Chceme vytvořit udržitelné a trvalé dědictví.", "details_on_legacy": "Vývoj a údržba takového produktu, jakým je __appName__, stojí spoustu úsilí a času, takže je nutné najít takový business model, který ho bude v dané situaci schopen dlouhodobě podporovat. Nechceme, aby byl __appName__ závislý na externím financování, nebo aby skončil kvůli chybně vybranému business modelu. Jsem velmi rád, že v současnosti zvládáme provozovat__appName__ ziskově a udržitelně s vidinou do daleké budoucnosti.", "get_in_touch": "Buďte v kontaktu", "want_to_hear_from_you_email_us_at": "Rádi uslyšíme kohokoliv, kdo používá __appName__, nebo si chce popovídat o tom, co děláme. Můžete být s námi v kontaktu na ", "cant_find_email": "Je nám líto, ale tato emailová adresa není registrována.", "plans_amper_pricing": "Tarify a ceny", "documentation": "Dokumentace", "account": "Účet", "subscription": "Předplatné", "log_out": "Odhlásit se", "en": "Angličtina", "pt": "Portugalština", "es": "Španělština", "fr": "Francouzština", "de": "Němčina", "it": "Italština", "da": "Dánština", "sv": "Švédština", "no": "Norština", "nl": "Holandština", "pl": "Polština", "ru": "Ruština", "uk": "Ukrajinština", "ro": "Rumunština", "click_here_to_view_sl_in_lng": "Pro použití __appName__ v <0>__lngName__</0> klikněte zde", "language": "Jazyk", "upload": "Nahrát", "menu": "Menu", "full_screen": "Celá obrazovka", "logs_and_output_files": "Logy a výstupní soubory", "download_pdf": "Stáhnout PDF", "split_screen": "Rozdělená obrazovka", "clear_cached_files": "Vymazat cache", "go_to_code_location_in_pdf": "Přejít od místa v kódu k PDF", "please_compile_pdf_before_download": "Před stažením PDF prosím zkompilujte svůj projekt", "remove_collaborator": "Odstranit spolupracovníka", "add_to_folders": "Přidat do složek", "download_zip_file": "Stáhnout soubor .zip", "price": "Cena", "close": "Zavřít", "keybindings": "Klávesové zkratky", "restricted": "Důvěrné", "start_x_day_trial": "Spusťte vaši bezplatnou __len__-ti denní trial verzi ještě dnes!", "buy_now": "Kupte teď!", "cs": "Čeština", "view_all": "Zobrazit vše", "terms": "Podmínky", "privacy": "Soukromí", "contact": "Kontakt", "change_to_this_plan": "Změnit na tento tarif", "processing": "zpracovávám", "sure_you_want_to_change_plan": "Opravdu chcete změnit tarif na <0>__planName__</0>?", "move_to_annual_billing": "Přesun k ročnímu vyúčtování", "annual_billing_enabled": "Roční vyúčtování povoleno", "move_to_annual_billing_now": "Přejděte k ročnímu vyúčtování právě teď", "change_to_annual_billing_and_save": "Získejte <0>__percentage__</0> z ročního vyúčtování. Pokud provedete změnu hned, ušetříte <1>__yearlySaving__</1> za rok.", "missing_template_question": "Chybí nám šablona?", "tell_us_about_the_template": "Pokud nám chybí nějaká šablona: pošlete nám prosím její kopii včetně url adresy v __appName__, nebo nám dejte vědět, kde ji můžeme najít. Zároveň nám též pošlete pár vět, které můžeme použít k jejímu popisu.", "email_us": "Napište nám", "this_project_is_public_read_only": "Tento projekt je veřejný a může být zobrazen, ale ne editován, kýmkoliv kdo má URL", "tr": "Turečtina", "select_files": "Vybrat soubor(y)", "drag_files": "přesuňte soubor(y)", "upload_failed_sorry": "Nahrání nevyšlo, je nám líto :(", "inserting_files": "Vkládám soubor...", "password_reset_token_expired": "Váš token pro reset hesla vypršel. Nechejte si prosím zaslat nový email a pokračujte odkazem v něm uvedeným.", "pull_github_changes_into_sharelatex": "Vložit změny z GitHubu do __appName__u.", "push_sharelatex_changes_to_github": "Vložit změny z __appName__u do GitHubu", "features": "Vlastnosti", "commit": "Commitovat", "commiting": "Commituji", "importing_and_merging_changes_in_github": "Importuji a merguji změny v GitHubu", "upgrade_for_faster_compiles": "Upgradujte pro rychlejší kompilaci a zvyšení limitu pro timeout.", "free_accounts_have_timeout_upgrade_to_increase": "Účty zdarma mají čas kompilace omezen na jednu minutu. Prémiové účty mají 4 minuty.", "learn_how_to_make_documents_compile_quickly": "Naučte se jak vyřešit problémy s časem kompilace.", "account_settings": "Nastavení účtu", "search_projects": "Vyhledat projekty", "clone_project": "Klonovat projekt", "delete_project": "Smazat projekt", "download_zip": "Stáhnout Zip", "new_project": "Nový projekt", "blank_project": "Prázdný projekt", "example_project": "Vzorový projekt", "from_template": "Ze šablony", "cv_or_resume": "CV nebo stručný životopis", "cover_letter": "Průvodní dopis", "journal_article": "Článek v časopise", "presentation": "Prezentace", "thesis": "Závěrečná práce", "bibliographies": "Bibliografie", "terms_of_service": "Podmínky používání služby", "privacy_policy": "Ochrana osobních údajů", "plans_and_pricing": "Tarify a ceny", "university_licences": "Univerzitní licence", "security": "Zabezpečení", "contact_us": "Kontaktujte nás", "thanks": "Děkujeme", "blog": "Blog", "latex_editor": "LaTeX editor", "get_free_stuff": "Získejte funkce zdarma", "chat": "Chat", "your_message": "Vaše zpráva", "loading": "Načítám", "connecting": "Připojuji", "recompile": "Překompilovat", "download": "Stáhnout", "email": "Email", "owner": "Vlastník", "read_and_write": "Číst a psát", "read_only": "Jen pro čtení", "publish": "Publikovat", "view_in_template_gallery": "Zobrazit v galerii šablon", "unpublish": "Zrušit publikování", "hotkeys": "Klávesové zkratky", "saving": "Ukládám", "cancel": "Zrušit", "project_name": "Jméno projektu", "root_document": "Hlavní dokument", "spell_check": "Kontrola pravopisu", "compiler": "Kompilátor", "private": "Soukromé", "public": "Veřejné", "delete_forever": "Smazat navždy", "support_and_feedback": "Podpora a zpětná vazba", "help": "Nápověda", "latex_templates": "Šablony pro LaTeX", "info": "Informace", "latex_help_guide": "Průvodce LaTeX nápovědou", "choose_your_plan": "Zvolte si svůj tarif", "indvidual_plans": "Individuální tarify", "free_forever": "Navždy zdarma", "low_priority_compile": "Kompilace s nízkou prioritou", "unlimited_projects": "Neomezený počet projektů", "unlimited_compiles": "Neomezený počet kompilací", "full_history_of_changes": "Kompletní historie změn", "highest_priority_compiling": "Kompilace s nejvyšší prioritou", "dropbox_sync": "Synchronizace s Dropboxem", "beta": "Beta", "sign_up_now": "Registrujte se", "annual": "Roční", "half_price_student": "Studentské tarify za poloviční cenu", "about_us": "O nás", "loading_recent_github_commits": "Načítám poslední commity", "no_new_commits_in_github": "Od posledního merge nejsou žádné nové commity.", "dropbox_sync_description": "Udržujte své projekty v __appName__u synchronizované s vašim Dropboxem. Změny v __appName__u budou automaticky poslány do Dropboxu a obráceně.", "github_sync_description": "Můžete spojit vaše projekty v __appName__u s GitHub repozitářem. Můžete vytvářet nové commity z __appName__u a mergovat s commity vytvořenými offline, nebo na GitHubu.", "github_import_description": "S GitHub synchronizací můžete importovat vaše GitHub repozitáře do __appName__u. Můžete vytvářet nové commity z __appName__u a mergovat s commity vytvořenými offline nebo v GitHubu.", "link_to_github_description": "Musíte autorizovat __appName__ k přístupu do vaše GitHub účtu abychom mohli synchronizovat vaše projekty.", "unlink": "Odpojit", "unlink_github_warning": "Všechny projekty synchronizované s GitHubem budou odpojeny a déle nesynchronizovány. Opravdu chcete váš GitHub účet odpojit?", "github_account_successfully_linked": "GitHub účet byl úspěšně připojen!", "github_successfully_linked_description": "Děkujeme, úspěšně jsem připojili váš GitHub účet k __appName__u. Nyní můžete exportovat své projekty v __appName__u do GitHubu, nebo importovat projekty z GitHub repozitáře.", "import_from_github": "Importovat z GitHubu", "github_sync_error": "Omlouváme se, ale při komunikaci s naší GitHub službou nastala chyba. Zkuste to za moment znovu.", "loading_github_repositories": "Načítám vaše repozitáře z GitHubu", "select_github_repository": "Vybrat GitHub repozitář k importování do __appName__u.", "import_to_sharelatex": "Importovat do __appName__u", "importing": "Importuji", "github_sync": "Synchronizace s GitHubem", "checking_project_github_status": "Kontroluji stav projektu na GitHubu", "account_not_linked_to_github": "Váš účet není spojen s GitHubem", "project_not_linked_to_github": "Tento projekt není spojen s GitHub repozitářem. Můžete pro něj GitHub repozitář vytvořit:", "create_project_in_github": "Vytvořit GitHub repozitář.", "project_synced_with_git_repo_at": "Tento projekt je synchronizován s GitHub repozitářem v", "recent_commits_in_github": "Poslední commity do GitHubu", "sync_project_to_github": "Synchronizovat projekt do GitHubu", "sync_project_to_github_explanation": "Každá změna, kterou uděláte v __appName__u, bude commitována a mergována z každou změnou v GitHubu.", "github_merge_failed": "Vaše změny v __appName__u a GitHubu nemohou být automaticky mergovány. Prosím mergujte manuálně <0>__sharelatex_branch__</0> branch do <1>__master_branch__</1> branche v gitu. Po dokončení manuálního merge klikněte níže pro pokračování.", "continue_github_merge": "Provedl jsem manuální merge. Pokračovat", "export_project_to_github": "Exportovat projekt do GitHubu", "github_validation_check": "Zkontrolujte prosím, jestli máte správné jméno repozitáře a jestli máte práva k jeho vytvoření.", "repository_name": "Jméno repozitáře", "optional": "Dobrovolný", "github_public_description": "Tento repozitář může vidět kdokoliv. Vy určíte kdo do něj může commitovat,", "github_commit_message_placeholder": "Commit zprávy pro změny udělané v __appName__u...", "merge": "Mergovat", "merging": "Merguji", "github_account_is_linked": "Váš GitHub účet byl úspěšně spojen.", "unlink_github": "Odpojit váš GitHub účet", "link_to_github": "Spojit s vašim GitHub účtem", "github_integration": "Integrace s GitHubem", "github_is_premium": "Synchronizace s GitHubem je prémiová funkce", "thank_you": "Děkujeme" }
overleaf/web/locales/cs.json/0
{ "file_path": "overleaf/web/locales/cs.json", "repo_id": "overleaf", "token_count": 16271 }
536
{ "to_modify_your_subscription_go_to": "Aboneliğinizi değiştirmek için:", "manage_subscription": "Abonelik", "activate_account": "Hesap etkinleştir", "yes_please": "Evet Lütfen!", "nearly_activated": "__appName__ isimli hesabınızı etkinleştirmenize bir adım kaldı!", "please_set_a_password": "Lütfen bir şifre belirleyin", "activation_token_expired": "Aktivasyon kodunuzun süresi geçmiş, size tekrar yollayacağımız kodu kullanın.", "activate": "Aktifleştir", "activating": "Aktifleştiriliyor", "ill_take_it": "Alıyorum!", "cancel_your_subscription": "Hesabınızı iptal edin", "no_thanks_cancel_now": "Hayır teşekkürler, hesabı iptal etmek istiyorum", "cancel_my_account": "Hesabımı iptal et", "sure_you_want_to_cancel": "İptal etmek istediğinizden emin misiniz?", "i_want_to_stay": "Kalmak istiyorum", "have_more_days_to_try": "Deneme sürenize <strong>__days__ gün</strong> daha ekleyin!", "interested_in_cheaper_plan": "Öğrenci planı ile daha ucuz, <strong>__price__</strong>, bir teklifle ilgilenir misiniz?", "new_group": "Yeni Grup", "about_to_delete_groups": "Şu projeleri silmek üzeresiniz:", "removing": "Kaldırılıyor", "adding": "Ekleniyor", "groups": "Gruplar", "rename_group": "Grubu Yeniden Adlandır", "renaming": "Değiştiriliyor", "create_group": "Grup Oluştur", "delete_group": "Grup Sil", "delete_groups": "Grupları Sil", "your_groups": "Gruplarınız", "group_name": "Grup Adı", "no_groups": "Grup Yok", "Subscription": "Abonelik", "Documentation": "Dökümantasyon", "Universities": "Üniversiteler", "Account Settings": "Hesap Ayarları", "Projects": "Projeler", "Account": "Hesap", "global": "global", "Terms": "Şartlar", "Security": "Güvenlik", "About": "Hakkında", "editor_disconected_click_to_reconnect": "Editör bağlantısı koptu, yeniden bağlanmak için herhangi bir yere tıklayın.", "word_count": "Kelime Sayısı", "please_compile_pdf_before_word_count": "Kelime sayısını hesaplamadan önce lütfen projenizi derleyin", "total_words": "Toplam Kelime", "headers": "Başlıklar", "math_inline": "Matematik İçerikleri", "math_display": "Matematik Görselleri", "connected_users": "Bağlı Kullanıcılar", "projects": "Projeler", "upload_project": "Proje Yükleyin", "all_projects": "Tüm Projeler", "your_projects": "Sizin Projeleriniz", "shared_with_you": "Sizinle Paylaşılanlar", "deleted_projects": "Silinen Projeler", "templates": "Şablonlar", "new_folder": "Yeni Klasör", "create_your_first_project": "İlk projenizi oluşturun!", "complete": "Tamamla", "on_free_sl": "__appName__'in ücretsiz sürümünü kullanmaktasınız", "upgrade": "Yükselt", "or_unlock_features_bonus": "ya da ücretsiz olarak bazı özelliklere erişmenin bir yolu da", "sharing_sl": "__appName__'i paylaşmaktır", "add_to_folder": "Klasöre ekle", "create_new_folder": "Yeni Klasör Oluştur", "more": "Daha fazla", "rename": "Adlandır", "make_copy": "Kopyasını oluştur", "restore": "Geri taşı", "title": "Başlık", "last_modified": "Son Değişiklik", "no_projects": "Proje bulunmamakta", "welcome_to_sl": "__appName__'e hoş geldiniz!", "new_to_latex_look_at": "LaTeX'te yeni misiniz? İsterseniz başlangıç olarak", "or": " ya da", "or_create_project_left": "ya da ilk projenizi sol taraftan oluşturabilirsiniz.", "thanks_settings_updated": "Teşekkürler, ayarlarınız güncellendi.", "update_account_info": "Hesap Bilgilerini Güncelle", "must_be_email_address": "E-posta adresi olmak zorundadır", "first_name": "Ad", "last_name": "Soyad", "update": "Güncelle", "change_password": "Şifre Değiştir", "current_password": "Mevcut Şifreniz", "new_password": "Yeni Şifre", "confirm_new_password": "Yeni Şifreyi Doğrula", "required": "gerekli", "doesnt_match": "Uyuşmuyor", "dropbox_integration": "Dropbox entegrasyonu", "learn_more": "Daha fazla bilgi", "dropbox_is_premium": "Dropbox senkronizasyonu premium bir özelliktir", "account_is_linked": "Hesap bağlandı", "unlink_dropbox": "Dropbox ile bağlantıyı kopar", "link_to_dropbox": "Dropbox'a bağla", "newsletter_info_and_unsubscribe": "Yeni özelliklerimizi tanıtmak için çoğu ay tanıtım bültenleri gönderiyoruz. Eğer bu e-postaları almak istemezseniz, dilediğiniz zaman abonelikten ayrılabilirsiniz:", "unsubscribed": "Abonelik sonlandırıldı", "unsubscribing": "Abonelik sonlandırılıyor", "unsubscribe": "Aboneliği sonlandır", "need_to_leave": "Bizden ayrılıyor musunuz?", "delete_your_account": "Hesabınızı silin", "delete_account": "Hesabı Sil", "delete_account_warning_message": "Hesabınızı kalıcı olarak silmek üzeresiniz, <strong>hesabınızdaki tüm veriler</strong>, projeleriniz ve ayarlarınız da dahil olmak üzere kalıcı olarak silinecektir. Eğer silme işlemine devam etmek istiyorsanız, lütfen aşağıdaki kutuya DELETE yazınız.", "deleting": "Siliniyor", "delete": "Sil", "sl_benefits_plans": "__appName__, dünyanın en kolay kullanımına sahip LaTeX editörüdür. İş arkadaşlarınızla olan çalışmalarınızı en güncel hali ile görebilir, tüm değişikliklerin kayıtlarını tutabilir ve sunduğumuz LaTeX ortamına da dünyanın her yerinden erişebilirsiniz.", "monthly": "Aylık", "personal": "Kişisel", "free": "Ücretsiz", "one_collaborator": "Yalnızca bir iş ortağı", "collaborator": "İş ortağı", "collabs_per_proj": "her bir proje için __collabcount__ iş ortağı", "full_doc_history": "Tüm değişiklikler geçmişi", "sync_to_dropbox": "Dropbox senkronizasyonu", "start_free_trial": "Hemen Ücretsiz Deneyin!", "professional": "Profesyonel", "unlimited_collabs": "Sınırsız iş ortağı", "name": "İsim", "student": "Öğrenci", "university": "Üniversite", "position": "Pozisyon", "choose_plan_works_for_you": "Lütfen size uygun __len__-günlük ücretsiz deneme planını seçin. Dilediğiniz zaman iptal edebilirsiniz.", "interested_in_group_licence": "__appName__'i bir grup, takım ya da bölüm ile beraber kullanmayı düşünür müsünüz?", "get_in_touch_for_details": "Ayrıntılı bilgi için iletişime geçin!", "group_plan_enquiry": "Grup Planı Sorgulama", "enjoy_these_features": "Tüm bu güzel özelliklerin keyfini çıkarın", "create_unlimited_projects": "İstediğiniz kadar proje oluşturun.", "never_loose_work": "Asla geride kalmayın, her zaman arkanızdayız.", "access_projects_anywhere": "Projelerinize her yerden erişin.", "log_in": "Giriş yap", "login": "Giriş yap", "logging_in": "Giriş yapılıyor", "forgot_your_password": "Şifrenizi mi unuttunuz", "password_reset": "Yeniden Şifre Tanımlama", "password_reset_email_sent": "Şifrenizi yeniden tanımlamanız için size bir e-posta gönderildi.", "please_enter_email": "Lütfen e-posta adresinizi giriniz", "request_password_reset": "Yeniden şifre tanımla", "reset_your_password": "Şifrenizi yeniden tanımlayın", "password_has_been_reset": "Şifreniz yeniden tanımlandı", "login_here": "Buradan giriş yapın", "set_new_password": "Yeni şifre tanımla", "user_wants_you_to_see_project": "__username__ adlı kullanıcı __projectname__ isimli projeyi görmenizi istiyor", "join_sl_to_view_project": "Bu projeyi görmek için __appName__'e katılın", "register_to_edit_template": "__templateName__ şablonunu düzenlemek için lütfen kayıt olunuz", "already_have_sl_account": "Zaten bir __appName__ hesabınız mı var?", "register": "Kayıt ol", "password": "Şifre", "registering": "Kayıt olunuyor", "planned_maintenance": "Planlanmış Bakım", "no_planned_maintenance": "Şu anda herhangi bir planlanmış bakım bulunmamaktadır", "cant_find_page": "Özür dileriz, aradığınız sayfayı bulamıyoruz", "take_me_home": "Çıkar beni buradan!", "no_preview_available": "Özür dileriz, herhangi bir önizleme bulunmamaktadır.", "no_messages": "Herhangi bir mesaj yok", "send_first_message": "İlk mesajınızı gönderin", "account_not_linked_to_dropbox": "Hesabınız, Dropbox'a bağlı değildir", "update_dropbox_settings": "Dropbox ayarlarını güncelle", "refresh_page_after_starting_free_trial": "Ücretsiz denemenize başladıktan sonra lütfen sayfayı yenileyin", "checking_dropbox_status": "Dropbox'un durumu kontrol ediliyor", "dismiss": "Reddet", "new_file": "Yeni Dosya", "upload_file": "Dosya Yükle", "create": "Oluştur", "creating": "Oluşturuluyor", "upload_files": "Dosya(lar) Yükle", "sure_you_want_to_delete": "<strong>&#123;&#123; entity.name &#125;&#125;</strong> kalıcı olarak silinecektir. Silmek istediğinizden emin misiniz?", "common": "Belirli", "navigation": "Yol gösterici", "editing": "Düzenleme", "ok": "Tamam", "source": "Kaynak", "actions": "İşlemler", "copy_project": "Projeyi Kopyala", "publish_as_template": "Şablon Olarak Yayınla", "sync": "Senkronizasyon", "settings": "Ayarlar", "main_document": "Ana döküman", "off": "Kapalı", "auto_complete": "Otomatik-Tamamlama", "theme": "Tema", "font_size": "Yazı Boyutu", "pdf_viewer": "PDF Görüntüleyici", "built_in": "Yerleşik", "native": "yerel", "show_hotkeys": "Kısayolları Göster", "new_name": "Yeni Ad", "copying": "kopyalama", "copy": "Kopyala", "compiling": "Derleniyor", "click_here_to_preview_pdf": "PDF olarak önizlemek için buraya tıklayın.", "server_error": "Sunucu Hatası", "somthing_went_wrong_compiling": "Özür dileriz, bir şeyler ters gitti ve projeniz derlenemiyor. Lütfen bir kaç dakika sonra tekrar deneyin.", "timedout": "Zaman aşımı", "proj_timed_out_reason": "Özür dileriz, derleme işleminiz çok uzun sürdü ve süre aşımına uğradı. Bu sorun, yüksek çözünürlüklü görüntülerin ya da aşırı karmaşık diyagramlardan fazlalığından kaynaklanıyor olabilir.", "no_errors_good_job": "Hiç bir hata bulunmamakta, tebrikler!", "compile_error": "Derleme Hatası", "generic_failed_compile_message": "Özür dileriz, LaTeX kodunuz bazı sorunlardan dolayı derlenememektedir. Daha ayrıntılı bilgi için aşağıdaki hataları kontrol edebilir ya da sonuç dökümüne bakabilirsiniz.", "other_logs_and_files": "Diğer sonuç dökümleri &amp; dosyalar", "view_raw_logs": "Sonuç Dökümünü Gör", "hide_raw_logs": "Sonuç Dökümünü Gizle", "clear_cache": "Önbelleği temizle", "clear_cache_explanation": "Bu, bütün gizli LaTeX dosyalarını (.aux, .bbl, etc) derleyici sunucumuzdan temizleyecektir. Referanslar ile ilgili sorun yaşamadığınız sürece genellikle bunu yapmanıza gerek yoktur.", "clear_cache_is_safe": "Proje dosyalarınız değiştirilmeyecek ya da silinmeyecektir.", "clearing": "Temizleniyor", "template_description": "Şablon Bilgisi", "project_last_published_at": "Projenizin en son yayınlandığı tarih", "problem_talking_to_publishing_service": "Yayın hizmetimizde bir sorun oluştu, lütfen bir kaç dakika sonra tekrar deneyin", "unpublishing": "Yayından kaldırılıyor", "republish": "Yeniden yayınla", "publishing": "Yayınlanıyor", "share_project": "Projeyi Paylaş", "this_project_is_private": "Bu, özel erişimli bir projedir ve yalnızca aşağıdaki kişiler tarafından erişilebilir.", "make_public": "Halka Açık Hale Getir", "this_project_is_public": "Bu, halka açık bir projedir ve URL sayesinde herkes tarafından düzenlenebilir.", "make_private": "Özel Erişimli Hale Getir", "can_edit": "Değişiklik Yapabilir", "share_with_your_collabs": "İş ortaklarınızla paylaşın", "share": "Paylaş", "need_to_upgrade_for_more_collabs": "Daha fazla iş ortağı ekleyebilmeniz için hesabınızı yükseltmeniz gerekmektedir", "make_project_public": "Projeyi halka açık hale getir", "make_project_public_consequences": "Eğer projeyi halka açık hale getirirseniz, herkes projeye URL adresi sayesinde erişebilecektir.", "allow_public_editing": "Düzenlemeyi halka açık hale getir", "allow_public_read_only": "Sadece okuma hakkını halka açık hale getir", "make_project_private": "Projeyi özel erişimli hale getir", "make_project_private_consequences": "Eğer bu projeyi özel erişimli olarak tanımlarsanız sadece sizin belirlediğiniz kişiler tarafından erişilebilecektir.", "need_to_upgrade_for_history": "Geçmiş kaydetme özelliğini kullanabilmeniz için hesabınızı yükseltmeniz gerekmektedir.", "ask_proj_owner_to_upgrade_for_history": "Geçmiş kaydetme özelliğini kullanmak için lütfen proje sahibini bilgilendiriniz.", "anonymous": "Anonim", "generic_something_went_wrong": "Özür dileriz, bir şeyler ters gitti :(", "restoring": "Onarma", "restore_to_before_these_changes": "Değişikliklerden önceki haline geri çevir", "profile_complete_percentage": "Profilinizin tamamlanan kısmı: %__percentval__", "file_has_been_deleted": "__filename__ silindi", "sure_you_want_to_restore_before": "<0>__filename__</0> adlı dosyanın __date__ tarihinden önceki haline geri çevirmek istediğinizden emin misiniz?", "rename_project": "Projeyi Yeniden Adlandır", "about_to_delete_projects": "Şu projeleri silmek üzeresiniz:", "about_to_leave_projects": "Şu projeleri terk etmek üzeresiniz:", "upload_zipped_project": "Sıkıştırılmış Proje Yükle", "upload_a_zipped_project": "Sıkıştırılmış bir proje yükle", "your_profile": "Profiliniz", "institution": "Enstitü", "role": "Pozisyon", "folders": "Klasörler", "disconnected": "Bağlantı koptu", "please_refresh": "Devam etmek için lütfen sayfayı yenileyin", "lost_connection": "Bağlantı Yok", "reconnecting_in_x_secs": "__seconds__ saniye içinde tekrar bağlanılmaya çalışılacak", "try_now": "Şimdi Dene", "reconnecting": "Yeniden bağlanıyor", "saving_notification_with_seconds": "__docname__ kaydediliyor... (Değişikliklerin kaydedilmemesinin üzerinden __seconds__ geçti)", "help_us_spread_word": "__appName__'i etrafa duyurmamıza yardım edin", "share_sl_to_get_rewards": "__appName__'i iş arkadaşlarınız ve dostlarınız ile paylaşarak aşağıdaki özellikleri ödül olarak kazabilirsiniz", "post_on_facebook": "Facebook'ta duyur", "share_us_on_googleplus": "Google+ aracılığı ile paylaş", "email_us_to_your_friends": "Dostlarınıza bizi e-posta yolu ile tanıt", "link_to_us": "İnternet sayfanızda bizim bağlantımızı paylaş", "direct_link": "Direk bağlantı adresi", "sl_gives_you_free_stuff_see_progress_below": "Eğer herhangi bir kişi sizin tavsiyeniz doğrultusunda __appName__'i kullanmaya başlarsa, size teşekkür etmek için birkaç özelliği <strong>ücretsiz olarak</strong> hediye edeceğiz! Bu süreci aşağıdan takip edebilirsiniz.", "spread_the_word_and_fill_bar": "Bizi başkalarına da tanıtarak bu çubuğu doldurabilirsiniz", "one_free_collab": "Fazladan bir iş ortağı", "three_free_collab": "Fazladan üç iş ortağı", "free_dropbox_and_history": "Ücretsiz Dropbox ve Geçmiş", "you_not_introed_anyone_to_sl": "Şuana kadar __appName__'i kimseye tanıtmadınız. Bizi paylaşın!", "you_introed_small_number": " Şuana kadar __appName__'i <0>__numberOfPeople__</0> kişiye tanıttınız. Tebrikler, acaba daha fazlası olacak mı?", "you_introed_high_number": " Şuana kadar __appName__'i <0>__numberOfPeople__</0> kişiye tanıttınız. Tebrikler!", "link_to_sl": "__appName__ için bağlantı adresi", "can_link_to_sl_with_html": "__appName__ bağlantısını, HTML ile, şu şekilde paylaşabilirsiniz", "year": "yıl", "month": "ay", "subscribe_to_this_plan": "Bu plana kaydol", "your_plan": "Planınız", "your_subscription": "Aboneliğiniz", "on_free_trial_expiring_at": "__expiresAt__ tarihinde bitecek olan deneme sürümünü kullanmaktasınız.", "choose_a_plan_below": "Abone olmak istediğiniz planı seçin.", "currently_subscribed_to_plan": "Şuan için<0>__planName__</0> planına aboneliğiniz devam etmektedir.", "change_plan": "Plan değiştir", "next_payment_of_x_collectected_on_y": "Bir sonraki <0>__paymentAmmount__</0> olan ödemeniz <1>__collectionDate__</1> tarihinde alınacaktır", "update_your_billing_details": "Ödeme Bilgilerini Güncelle", "subscription_canceled_and_terminate_on_x": " Aboneliğiniz iptal edildi ve <0>__terminateDate__</0> tarihinde sonlandırılacaktır. Başka herhangi bir ücret alınmayacaktır.", "your_subscription_has_expired": "Aboneliğinizin süresi doldu.", "create_new_subscription": "Yeni Abonelik Oluştur", "problem_with_subscription_contact_us": "Aboneliğiniz ile ilgili bir sorun bulunmaktadır. Lütfen ayrıntılı bilgi için bizimle iletişime geçin.", "manage_group": "Grupları Yönet", "loading_billing_form": "Ödeme bilgileri formu yükleniyor", "you_have_added_x_of_group_size_y": "<1>__groupSize__</1> kişilik grup kontenjanınıza, <0>__addedUsersSize__</0> kişi eklediniz", "remove_from_group": "Gruptan çıkar", "group_account": "Grup Hesabı", "registered": "Kayıtlı", "no_members": "Üye bulunmamaktadır", "add_more_members": "Daha fazla üye ekleyin", "add": "Ekle", "thanks_for_subscribing": "Aboneliğiniz için teşekkürler!", "your_card_will_be_charged_soon": "Kartınızdan yakında ücret tahsil edilecektir.", "if_you_dont_want_to_be_charged": "Eğer bir daha ücret tahsil edilmesini istemiyorsanız ", "add_your_first_group_member_now": "Grubunuza ilk üyeleri ekleyin", "thanks_for_subscribing_you_help_sl": "__planName__ planına abone olduğunuz için teşekkürler. Sizlerin bu destekleri sayesinde __appName__ büyümeye ve gelişmeye devam etmektedir.", "back_to_your_projects": "Projelerinize geri dönün", "goes_straight_to_our_inboxes": "Hem bizim hem de sizin gelen kutunuza yollanır", "need_anything_contact_us_at": "Eğer herhangi bir konuda bize ihtiyacınız olursa ve bize ulaşmak isterseniz e-posta adresimiz", "regards": "Saygılarımızla", "about": "Hakkında", "comment": "Yorumlar", "restricted_no_permission": "Üzgünüz, bu sayfaya erişmek için gerekli izniniz bulunmamaktadır.", "online_latex_editor": "Çevrimiçi LaTeX Editörü", "meet_team_behind_latex_editor": "En sevdiğiniz çevrimiçi LaTeX editörünün arkasındaki kişiler.", "follow_me_on_twitter": "Beni Twitter'da takip edin", "motivation": "Motivasyon", "evolved": "Evrim geçirdi", "the_easy_online_collab_latex_editor": "Kullanımı kolay, çevrimiçi, ortak çalışmaya uygun LaTeX editörü", "get_started_now": "Hemen kullanmaya başla", "sl_used_over_x_people_at": "__appName__'in __numberOfUsers__ kişiyi aşkın öğrenci ve akademisyen tarafından kullanıldığı yerlerden bazıları:", "collaboration": "İş birliği", "work_on_single_version": "Tek bir versiyon üzerinde ortaklaşa çalışın", "view_collab_edits": "Değişiklikleri anlık olarak görün: ", "ease_of_use": " Kullanım kolaylığı", "no_complicated_latex_install": "Karmaşık bir LaTeX kurulumuna gerek yok", "all_packages_and_templates": "İhtiyacınız olan tüm Paketler ve <0>__templatesLink__</0> kullanıma hazır", "document_history": "Döküman geçmişi", "see_what_has_been": "Tüm değişiklikleri görün, ne ", "added": "eklenmiş", "and": "ya da ne", "removed": "silinmiş", "restore_to_any_older_version": "Eski bir versiyona geri çevirin", "work_from_anywhere": "Her yerden çalışma imkanı", "acces_work_from_anywhere": "İşlerinize dünyanın her yerinden erişin", "work_offline_and_sync_with_dropbox": "Çevrimdışı çalışma imkanı ve dosyalarınızı Dropbox ve GitHub ile senkronize edebilme", "over": "fazla", "view_templates": "Şablonları görüntüleyin", "nothing_to_install_ready_to_go": "Hiçbir karmaşık ve zor bir kuruluma ihtiyacınız yok, daha önce hiç kullanmamış olsanız bile, <0>__start_now__</0>. __appName__, sunucularımızda bütün bir sistem olarak çalışır ve kullanıma her an hazır olacak bir şekilde hizmet vermektedir.", "start_using_latex_now": "hemen LaTeX'i kullanmaya başlayın", "get_same_latex_setup": "__appName__ sayesinde LaTeX kurulumunuzu gittiğiniz her yere taşımız olacaksınız. İş arkadaşlarınız ve öğrencileriniz ile __appName__ üzerinden çalışarak, paket çakışmaları yaşamayacak ve versiyon uyumsuzluklarıyla karşılaşmayacaksınız.", "support_lots_of_features": "Neredeyse tüm LaTeX özelliklerini destekliyoruz, görüntü ekleme, kaynakçalar, denklemler ve çok daha fazlası! __appName__ kullanarak yapabileceğiniz ilginç şeyler hakkında daha fazla bilgi almak için: <0>__help_guides_link__</0>", "latex_guides": "LaTeX kılavuzları", "reset_password": "Şifre Sıfırla", "set_password": "Şifre Belirle", "updating_site": "Sayfa Güncelleme", "bonus_please_recommend_us": "Ekstra özellik - Bizi tavsiye edin", "admin": "yönetici", "subscribe": "Abone Ol", "update_billing_details": "Ödeme Bilgilerini Güncelle", "group_admin": "Grup Yöneticisi", "all_templates": "Tüm Şablonlar", "your_settings": "Ayarlarınız", "maintenance": "Bakım", "to_many_login_requests_2_mins": "Bu hesap çok fazla giriş talebinde bulundu. Lütfen tekrar giriş yapabilmek için 2 dakika bekleyin.", "email_or_password_wrong_try_again": "E-posta adresiniz ya da şifreniz yanlış. Lütfen tekrar deneyin", "rate_limit_hit_wait": "Limiti aşıldı. Lütfen bir süre bekledikten sonra tekrar deneyin", "problem_changing_email_address": "E-posta adresinizi değiştirirken bir hata ile karşılaşıldı. Lütfen bir kaç dakika sonra tekrar deneyin. Eğer bu problem devam ederse bizimle iletişime geçebilirsiniz.", "single_version_easy_collab_blurb": "__appName__, sizi iş ortaklarınız ile sürekli güncel tutar. Bu sayede onların neler yaptıklarını takip edebilirsiniz. Her dökümanın sadece bir güncel versiyonu vardır ve herkes buna erişir. Çakışma yaşamanız imkansızdır, ve çalışmalarınıza devam etmeniz için iş arkadaşlarınızın yaptığı değişiklikleri taslak olarak göndermelerini beklemenize de gerek kalmadı.", "can_see_collabs_type_blurb": "Tek bir dökümanda birden fazla kişinin aynı anda çalışması sorun değildir. İş arkadaşlarınız neler yazdığı anlık olarak görebilir ve editörden takip edebilirsiniz.", "work_directly_with_collabs": "İş arkadaşlarınızla beraber çalışın", "work_with_word_users": "Word kullanıcıları ile beraber çalışın", "work_with_word_users_blurb": "__appName__, LaTeX kullanıcısı olmayan iş arkadaşlarınızın da dökümana katkıda bulunmalarını kolaylaştırır. İlk günden katkıda bulunabilirler ve çok az LaTeX bilgisi ile devam edebilirler.", "view_which_changes": "Hangi değişiklikler yapılmış görün", "sl_included_history_of_changes_blurb": "__appName__, yapılan tüm değişikliklerin kimin tarafından ve ne zaman yapıldığının kaydını tutar. Bu sayede süreç ile ilgili kolay değerlendirmeler yapabilir ve iş ortaklarınızın yaptığı çalışmaları takip edebilirsiniz.", "can_revert_back_blurb": "İş arkadaşlarınız ile yaptığınız çalışmalarda ya da kendi çalışmalarınızda bazen hatalar yapabilirsiniz. Projenin eski versiyonlarını geri getirmek oldukça basittir bu sayede yapılan değişiklikler için pişmanlık duymazsınız ve işin bozulma riski ortadan kalkmış olur.", "start_using_sl_now": "Hemen __appName__'i kullanmaya başlayın", "over_x_templates_easy_getting_started": "Şablon galerimizde sayısı 400'den __over__ olan __templates__ işe başlamanızı kolaylaştırabilir. Şablonlar arasında dergi makalesi, tez, CV ve daha fazlası bulunmaktadır.", "done": "Tamam", "change": "Değiştir", "page_not_found": "Sayfa Bulunamadı", "please_see_help_for_more_info": "Lütfen daha fazla bilgi için yardım rehberimize göz atın", "this_project_will_appear_in_your_dropbox_folder_at": "Bu projenin gözükeceği Dropbox klasörü: ", "member_of_group_subscription": "__admin_email__ tarafından yönetilen grubun bir üyesisiniz. Lütfen aboneliğinizi yönetmek için onlarla iletişime geçin.\n", "about_henry_oswald": "Londra'da yaşayan bir yazılım mühendisidir. __appName__'in prototipini yapmıştır ve bu platformun ölçeklenebilirliğinden ve devamlılığından sorumludur. Henry, geliştirme sürecinin sürekli olarak test edilerek yenilenmesini ve __appName__kodlarının okunabilir ve kolay onarılabilir bir halde tutabilmemizi sağlar.", "about_james_allen": "teorik fizik alanında doktora yapmaktadır ve bir LaTeX tutkunudur. İlk çevrimiçi editör olan ScribTex'i yaratmış ve __appName__'in büyümesinde büyük rol oynamıştır.", "two_strong_principles_behind_sl": "__appName__ üzerinde yaptığımız çalışmaların arkasında iki temel prensip vardır:", "want_to_improve_workflow_of_as_many_people_as_possible": "İş akışını daha fazla kişiye uygun hale getirecek şekilde geliştirmek istiyoruz.", "detail_on_improve_peoples_workflow": "LaTeX, bilindiği üzere kullanımı zor ve başkalarıyla ortak çalışması güç olan bir ortamdır. Bu sorunlara çözüm getmeyi ve __appName__'in daha fazla kişi tarafından kullanılabilmesini amaçladık. Fiyatlandırmamızı her zaman makul seviyelerde tutmaya çalıştık ve __appName__'in çoğu kısmını açık kaynak kodlu bir yazılım olarak sunduk. Bu sayede herkesin, __appName__'i, kendi sunucularına da kurabilmelerine olanak sağladık.", "want_to_create_sustainable_lasting_legacy": "Sürdürülebilir ve kalıcı bir miras haline getirmek istiyoruz.", "details_on_legacy": "__appName__gibi ürünlerin geliştirilmesi ve bakımları çok büyük iş yükü ve zaman almaktadır, bu yüzden bunu uzun süre destekleyecek bir iş modeli bulmamız bizim için çok önemli. __appName__'in harici bir yatırıma bağlı kalmasını ve bundan kaynaklı sebeplerden de sonlanmasını istemeyiz. Bu yüzden şuan __appName__'in hem kârlı hem de sürdürülebilir bir durumda olduğunu söylemekten mutluluk duyuyoruz, ve bu şekilde de uzun süre devam etmesini ümit ediyoruz.", "get_in_touch": "İrtibata geçin", "want_to_hear_from_you_email_us_at": "__appName__'i kullananların her zaman fikirlerini duymak isteriz, ayrıca yaptıklarımız hakkında bilgi almak ve bizimle iletişime geçmek için: ", "cant_find_email": "Üzgünüz ama bu kayıtlı bir e-posta adresi değildir.", "plans_amper_pricing": "Planlar ve Fiyatlandırma", "documentation": "Dökümantasyon", "account": "Hesap", "subscription": "Abonelik", "log_out": "Çıkış Yap", "en": "İngilizce", "pt": "Portekizce", "es": "İspanyolca", "fr": "Fransızca", "de": "Almanca", "it": "İtalyanca", "da": "Danca", "sv": "İsveççe", "no": "Norveççe", "nl": "Flemenkçe", "pl": "Lehçe", "ru": "Rusça", "uk": "Ukraynaca", "ro": "Romence", "click_here_to_view_sl_in_lng": "__appName__'i <0>__lngName__</0> dilinde kullanmak için", "language": "Dil", "upload": "Yükle", "menu": "Menü", "full_screen": "Tam ekran", "logs_and_output_files": "Sonuç dökümleri ve çıktılar", "download_pdf": "PDF halini indir", "split_screen": "Ekranı ayır", "clear_cached_files": "Önbellek dosyalarını temizle", "go_to_code_location_in_pdf": "PDF'deki yerin koddaki karşılığına git", "please_compile_pdf_before_download": "Dökümanınızın PDF halini indirmeden önce lütfen derleyin", "remove_collaborator": "İş ortağını çıkar", "add_to_folders": "Klasörlere ekle", "download_zip_file": "Zip Dosyasını İndir", "price": "Fiyat", "close": "Kapat", "keybindings": "Tuş Yönlendirmeleri", "restricted": "Yasaklı", "start_x_day_trial": "__len__-günlük deneme sürümüne bugün başlayın!", "buy_now": "Şimdi satın al!", "cs": "Çekçe", "view_all": "Hepsini Gör", "terms": "Şartlar", "privacy": "Gizlilik", "contact": "İletişim", "change_to_this_plan": "Bu plana geç", "processing": "işlem yapılıyor", "sure_you_want_to_change_plan": "Planınızı <0>__planName__</0> olarak değiştirmek istediğinizden emin misiniz?", "move_to_annual_billing": "Yıllık ödemeye geç", "annual_billing_enabled": "Yıllık ödeme aktif", "move_to_annual_billing_now": "Şimdi yıllık ödemeye geç", "change_to_annual_billing_and_save": "Yıllık ödeme planın geçerek <0>__percentage__</0> oranında bir kazanç sağlayabilirsiniz. Eğer şimdi bu plana geçerseniz yılda <1>__yearlySaving__</1> kâr edeceksiniz.", "missing_template_question": "Eksik şablon mu var?", "tell_us_about_the_template": "Eğer şablon eksiğimiz olduğunu düşünüyorsanız: Şablonun bir kopyasını, şablonun __appName__ URL adresini ya da o şablonu nereden bulacağımız ile ilgili bizi bilgilendirebilirsiniz. Ayrıca lütfen, şablon hakkında ufak bir açıklama da yazınız.", "email_us": "E-Posta atın", "this_project_is_public_read_only": "Bu, halka açık bir projedir ve URL sayesinde herkes tarafından görülebilir ancak değiştirilemez.", "tr": "Türkçe", "select_files": "Dosya(ları) seçin", "drag_files": "dosya(ları) sürükleyin", "upload_failed_sorry": "Yükleme başarısız, özür dileriz :(", "inserting_files": "Dosya yükleniyor...", "password_reset_token_expired": "Şifrenizi yeniden tanımlamanız için sağlanan iznin süresi geçti. Lütfen tekrar şifre sıfırlama talep edin ve e-posta ile gelen bağlantıdan şifrenizi yeniden tanımlayın.", "merge_project_with_github": "Projeleri GitHub ile birleştir", "pull_github_changes_into_sharelatex": "GitHub'daki değişiklikleri __appName__'e aktar", "push_sharelatex_changes_to_github": "__appName__'deki değişiklikleri GitHub'a aktar", "features": "Özellikler", "commit": "İşle", "commiting": "İşleniyor", "importing_and_merging_changes_in_github": "Değişiklikler GitHub'a aktarılıyor", "upgrade_for_faster_compiles": "Daha hızlı derlemek ve derlemedeki süre aşımı limitini arttırmak için hesabınızı yükseltin", "free_accounts_have_timeout_upgrade_to_increase": "Ücretsiz hesaplar sadece bir dakikalık süre aşımı limitine sahiptir. Bunu arttırmak için hesabınızı yükseltin.", "learn_how_to_make_documents_compile_quickly": "Dökümanınızın nasıl daha hızlı derlenebileceği hakkında bilgi edinin", "zh-CN": "Çince", "cn": "Çince (Basitleştirilmiş)", "sync_to_github": "GitHub ile senkronize et", "sync_to_dropbox_and_github": "Dropbox ve GitHub ile senkronize et", "project_too_large": "Proje aşırı büyük", "project_too_large_please_reduce": "Projede çok fazla yazı bulunmaktadır, lütfen azaltmayı deneyin.", "please_ask_the_project_owner_to_link_to_github": "Bu projenin GitHub deposu ile bağlanması için proje sahibi ile iletişime geçin", "go_to_pdf_location_in_code": "Koddaki yerin PDF'deki karşılığına git", "ko": "Korece", "ja": "Japonca", "about_brian_gough": "bir yazılım geliştiricisi ve Fermilab ve Los Alamos'ta çalışan eski bir teorik yüksek enerji fizikçisidir. Uzun yıllar boyunca TeX ve LaTeX üzerine ücretsiz yazılım dökümanları yayınlamış ve ayrıca GNU Bilimsel Kütüphanenin bakımında görev almıştır.", "first_few_days_free": "İlk__trialLen__ gün bedava", "every": "her", "credit_card": "Kredi Kartı", "credit_card_number": "Kredi Kartı numarası", "invalid": "Hatalı", "expiry": "Son kullanma tarihi", "january": "Ocak", "february": "Şubat", "march": "Mart", "april": "Nisan", "may": "Mayıs", "june": "Haziran", "july": "Temmuz", "august": "Ağustos", "september": "Eylül", "october": "Ekim", "november": "Kasım", "december": "Aralık", "zip_post_code": "Posta Kodu", "city": "Şehir", "address": "Adres", "coupon_code": "kupon kodu", "country": "Ülke", "billing_address": "Fatura Adresi", "upgrade_now": "Şimdi Yükselt", "state": "Eyalet", "vat_number": "KDV (VAT) Numarası", "you_have_joined": "__groupName__ grubuna katıldınız.", "claim_premium_account": "__groupName__ grubundan premium hesap hakkı kazandınız.", "you_are_invited_to_group": " __groupName__ grubuna davet edildiniz", "account_settings": "Hesap Ayarları", "search_projects": "Projelerde Ara", "clone_project": "Projenin Kopyasını Oluştur", "delete_project": "Projeyi Sil", "download_zip": "Zip Dosyasını İndir", "new_project": "Yeni Proje", "blank_project": "Boş Proje", "example_project": "Örnek Proje", "from_template": "Şablondan", "cv_or_resume": "CV ya da Özgeçmiş", "cover_letter": "Ön Yazı", "journal_article": "Dergi Makalesi", "presentation": "Sunum", "thesis": "Tez", "bibliographies": "Kaynakça", "terms_of_service": "Hizmet Şartları", "privacy_policy": "Gizlilik Politikası", "plans_and_pricing": "Planlar ve Fiyatlandırma", "university_licences": "Üniversite Lisansları", "security": "Güvenlik", "contact_us": "İletişime geçin", "thanks": "Teşekkürler", "blog": "Blog", "latex_editor": "LaTeX Editörü", "get_free_stuff": "Ücretsiz özellikler edinin", "chat": "Sohbet", "your_message": "Mesajınız", "loading": "Yükleniyor", "connecting": "Bağlanıyor", "recompile": "Tekrar Derle", "download": "İndir", "email": "E-posta", "owner": "Sahibi", "read_and_write": "Okuma ve Yazma", "read_only": "Yalnızca Görüntüleyebilir", "publish": "Yayınla", "view_in_template_gallery": "Şablon galerisinde görüntüle", "unpublish": "Yayından Kaldır", "hotkeys": "Kısayollar", "saving": "Kaydediliyor", "cancel": "İptal", "project_name": "Proje Adı", "root_document": "Kök Döküman", "spell_check": "İmla Denetimi", "compiler": "Derleyici", "private": "Özel", "public": "Halka Açık", "delete_forever": "Kalıcı Olarak Sil", "support_and_feedback": "Destek ve Geribildirim", "help": "Yardım", "latex_templates": "LaTeX Şablonları", "info": "Bilgi", "latex_help_guide": "LaTeX yardım kılavuzu", "choose_your_plan": "Planınızı seçin", "indvidual_plans": "Kişisel Planlar", "free_forever": "Her zaman ücretsiz", "low_priority_compile": "Düşük öncelikli derleme", "unlimited_projects": "Sınırsız Proje Sayısı", "unlimited_compiles": "Sınırsız Derleme", "full_history_of_changes": "Tüm yapılan değişikliklerin geçmişi", "highest_priority_compiling": "Yüksek öncelikli derleme", "dropbox_sync": "Dropbox Senkronizasyonu", "beta": "Beta", "sign_up_now": "Hemen Kaydolun", "annual": "Yıllık", "half_price_student": "Yarı Ücretli Öğrenci Planları", "about_us": "Hakkımızda", "loading_recent_github_commits": "Yapılan son işlemler yükleniyor", "no_new_commits_in_github": "En sonki birleşmeden itibaren GitHub'da yapılmış herhangi yeni bir işlem bulunmuyor.", "dropbox_sync_description": "__appName__ projelerinizi, Dropbox ile senkronize edin. Bu sayede __appName__ üzerinden yaptığınız değişiklikler otomatik olarak Dropbox üzerinde ve Dropbox üzerinde yapılan değişiklikler de __appName__ üzerinde işlenecektir.", "github_sync_description": "GitHub senkronizasyonu sayesinde __appName__ projeleriniz ile GitHub depolarınız arasında bağlantı kurabilirsiniz. Bu sayede __appName__ üzerinden çevrimdışı olarak işlem yapabilir ya da bu işlemleri GitHub üzerine işleyebilirsiniz.", "github_import_description": "GitHub senkronizasyonu sayesinde GitHub depolarınızı __appName__'e yükleyebilirsiniz. Bu sayede __appName__ üzerinden çevrimdışı olarak işlem yapabilir ya da bu işlemleri GitHub üzerine işleyebilirsiniz.", "link_to_github_description": "GitHub'daki hesabınız ile projelerinizin senkronize olabilmesi için __appName__'e yetki vermeniz gerekmektedir.", "unlink": "Bağlantıyı kopar", "unlink_github_warning": "GitHub ile senkronize etmiş olduğunuz tüm projeler arasındaki bağlantı koparılacaktır ve senkronizasyon iptal edilecektir. GitHub ile olan bu bağlantıyı koparmak istediğinizden emin misiniz?", "github_account_successfully_linked": "GitHub hesabınız ile bağlantı, başarıyla oluşturuldu.", "github_successfully_linked_description": "Teşekkürler, GitHub hesabınız ile __appName__ arasındaki bağlantı, başarıyla oluşturuldu. Artık __appName__ projelerinizi GitHub üzerine yükleyebilir ya da GitHub depolarınızı __appName__'e yükleyebilirsiniz.", "import_from_github": "GitHub'dan yükle", "github_sync_error": "Üzgünüz, GitHub servisine bağlanırken bir sorunla karşılaştık. Lütfen, birkaç dakika sonra tekrar deneyin.", "loading_github_repositories": "GitHub depolarınız yükleniyor", "select_github_repository": "__appName__'e yüklemek istediğiniz GitHub deponuzu seçiniz", "import_to_sharelatex": "__appName__'e yükle", "importing": "Yükleniyor", "github_sync": "GitHub Senkronizasyonu", "checking_project_github_status": "Projenin GitHub'daki durumu kontrol ediliyor", "account_not_linked_to_github": "Hesabınız ile GitHub arasında bir bağlantı oluşturulmamış", "project_not_linked_to_github": "Bu projenin herhangi bir GitHub deposu ile bağlantısı bulunmamaktadır. GitHub'da bunun için bir depo oluşturabilirsiniz:", "create_project_in_github": "GitHub deposu oluştur", "project_synced_with_git_repo_at": "Bu projenin senkronizasyon halinde olduğu GitHub deposu", "recent_commits_in_github": "GitHub'da yapılan güncel işlemler", "sync_project_to_github": "Projeyi GitHub ile senkronize et", "sync_project_to_github_explanation": "__appName__ üzerinden yaptığınız tüm değişiklikler GitHub üzerine işlenecek ve birleştirilecektir.", "github_merge_failed": "__appName__ üzerinden yaptığınız değişiklikler otomatik olarak GitHub üzerinde birleştirilemedi. Lütfen, <0>__sharelatex_branch__</0> dalının <1>__master_branch__</1> dalı ile olan birleşimini kendiniz yapınız. Birleşimi tamamladıktan sonra devam etmek için aşağıya tıklayın.", "continue_github_merge": "Kendim birleştirdim. Devam et", "export_project_to_github": "Projeyi GitHub'a yükle", "github_validation_check": "Lütfen, depo adının doğru yazıldığından ve yeni bir depo oluşturma yetkinizin olduğundan emin olunuz.", "repository_name": "Depo Adı", "optional": "İsteğe bağlı", "github_public_description": "Herkes bu depoyu görüntüleyebilir. Kimlerin işlem yapabileceğini siz seçersiniz.", "github_commit_message_placeholder": "__appName__ üzerinden yaptığınız değişiklikler için yorum giriniz...", "merge": "Birleştir", "merging": "Birleştiriliyor", "github_account_is_linked": "GitHub hesabınız ile bağlantı, başarıyla oluşturuldu.", "unlink_github": "GitHub hesabınız ile bağlantıyı koparın", "link_to_github": "GitHub hesabınız ile bağlantı oluşturun", "github_integration": "GitHub Entegrasyonu", "github_is_premium": "GitHub senkronizasyonu premium bir özelliktir", "thank_you": "Teşekkürler" }
overleaf/web/locales/tr.json/0
{ "file_path": "overleaf/web/locales/tr.json", "repo_id": "overleaf", "token_count": 17479 }
537
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const indexes = [ { key: { room_id: 1, timestamp: -1, }, name: 'room_id_1_timestamp_-1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.messages, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.messages, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145013_create_messages_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145013_create_messages_indexes.js", "repo_id": "overleaf", "token_count": 236 }
538
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const indexes = [ { key: { user_id: 1, }, name: 'user_id_1', }, { unique: true, key: { user_id: 1, name: 1, }, name: 'user_id_1_name_1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.tags, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.tags, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145029_create_tags_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145029_create_tags_indexes.js", "repo_id": "overleaf", "token_count": 283 }
539
const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const index = { key: { _id: 1, lastOpened: 1, active: 1 }, name: '_id_1_lastOpened_1_active_1', partialFilterExpression: { active: true, }, } exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.projects, [index]) } exports.rollback = async client => { const { db } = client await Helpers.dropIndexesFromCollection(db.projects, [index]) }
overleaf/web/migrations/20201106094956_active-projects-index-with-id.js/0
{ "file_path": "overleaf/web/migrations/20201106094956_active-projects-index-with-id.js", "repo_id": "overleaf", "token_count": 184 }
540
/* global io */ /* 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../../../../frontend/js/base' export default App.controller( 'LaunchpadController', function ($scope, $http, $timeout) { $scope.adminUserExists = window.data.adminUserExists $scope.ideJsPath = window.data.ideJsPath $scope.authMethod = window.data.authMethod $scope.createAdminSuccess = null $scope.createAdminError = null $scope.statusChecks = { ideJs: { status: 'inflight', error: null }, websocket: { status: 'inflight', error: null }, healthCheck: { status: 'inflight', error: null }, } $scope.testEmail = { emailAddress: '', inflight: false, status: null, // | 'ok' | 'success' } $scope.shouldShowAdminForm = () => !$scope.adminUserExists $scope.onCreateAdminSuccess = function (response) { const { status } = response if (status >= 200 && status < 300) { return ($scope.createAdminSuccess = true) } } $scope.onCreateAdminError = () => ($scope.createAdminError = true) $scope.sendTestEmail = function () { $scope.testEmail.inflight = true $scope.testEmail.status = null return $http .post('/launchpad/send_test_email', { email: $scope.testEmail.emailAddress, _csrf: window.csrfToken, }) .then(function (response) { const { status } = response $scope.testEmail.inflight = false if (status >= 200 && status < 300) { return ($scope.testEmail.status = 'ok') } }) .catch(function () { $scope.testEmail.inflight = false return ($scope.testEmail.status = 'error') }) } $scope.tryFetchIdeJs = function () { $scope.statusChecks.ideJs.status = 'inflight' return $timeout( () => $http .get($scope.ideJsPath) .then(function (response) { const { status } = response if (status >= 200 && status < 300) { return ($scope.statusChecks.ideJs.status = 'ok') } }) .catch(function (response) { const { status } = response $scope.statusChecks.ideJs.status = 'error' return ($scope.statusChecks.ideJs.error = new Error( `Http status: ${status}` )) }), 1000 ) } $scope.tryOpenWebSocket = function () { $scope.statusChecks.websocket.status = 'inflight' return $timeout(function () { if (typeof io === 'undefined' || io === null) { $scope.statusChecks.websocket.status = 'error' $scope.statusChecks.websocket.error = 'socket.io not loaded' return } const socket = io.connect(null, { reconnect: false, 'connect timeout': 30 * 1000, 'force new connection': true, }) socket.on('connectionAccepted', function () { $scope.statusChecks.websocket.status = 'ok' return $scope.$apply(function () {}) }) socket.on('connectionRejected', function (err) { $scope.statusChecks.websocket.status = 'error' $scope.statusChecks.websocket.error = err return $scope.$apply(function () {}) }) return socket.on('connect_failed', function (err) { $scope.statusChecks.websocket.status = 'error' $scope.statusChecks.websocket.error = err return $scope.$apply(function () {}) }) }, 1000) } $scope.tryHealthCheck = function () { $scope.statusChecks.healthCheck.status = 'inflight' return $http .get('/health_check') .then(function (response) { const { status } = response if (status >= 200 && status < 300) { return ($scope.statusChecks.healthCheck.status = 'ok') } }) .catch(function (response) { const { status } = response $scope.statusChecks.healthCheck.status = 'error' return ($scope.statusChecks.healthCheck.error = new Error( `Http status: ${status}` )) }) } $scope.runStatusChecks = function () { $timeout(() => $scope.tryFetchIdeJs(), 1000) return $timeout(() => $scope.tryOpenWebSocket(), 2000) } // kick off the status checks on load if ($scope.adminUserExists) { return $scope.runStatusChecks() } } )
overleaf/web/modules/launchpad/frontend/js/main/controllers/LaunchpadController.js/0
{ "file_path": "overleaf/web/modules/launchpad/frontend/js/main/controllers/LaunchpadController.js", "repo_id": "overleaf", "token_count": 2130 }
541
const { execSync } = require('child_process') const { expect } = require('chai') const { db } = require('../../../../../app/src/infrastructure/mongodb') const User = require('../../../../../test/acceptance/src/helpers/User').promises /** * @param {string} cmd * @return {string} */ function run(cmd) { // https://nodejs.org/docs/latest-v12.x/api/child_process.html#child_process_child_process_execsync_command_options // > stderr by default will be output to the parent process' stderr // > unless stdio is specified. // https://nodejs.org/docs/latest-v12.x/api/child_process.html#child_process_options_stdio // Pipe stdin from /dev/null, store stdout, pipe stderr to /dev/null. return execSync(cmd, { stdio: ['ignore', 'pipe', 'ignore'], cwd: 'modules/server-ce-scripts/scripts', }).toString() } async function getUser(email) { return db.users.findOne({ email }, { projection: { _id: 0, isAdmin: 1 } }) } describe('ServerCEScripts', function () { describe('check-mongodb', function () { it('should exit with code 0 on success', function () { run('node check-mongodb') }) it('should exit with code 1 on error', function () { try { run( 'MONGO_SERVER_SELECTION_TIMEOUT=1' + 'MONGO_CONNECTION_STRING=mongodb://localhost:4242 ' + 'node check-mongodb' ) } catch (e) { expect(e.status).to.equal(1) return } expect.fail('command should have failed') }) }) describe('check-redis', function () { it('should exit with code 0 on success', function () { run('node check-redis') }) it('should exit with code 1 on error', function () { try { run('REDIS_HOST=localhost node check-redis') } catch (e) { expect(e.status).to.equal(1) return } expect.fail('command should have failed') }) }) describe('create-user', function () { it('should exit with code 0 on success', function () { const out = run('node create-user --email=foo@bar.com') expect(out).to.include('/user/activate?token=') }) it('should create a regular user by default', async function () { run('node create-user --email=foo@bar.com') expect(await getUser('foo@bar.com')).to.deep.equal({ isAdmin: false }) }) it('should create an admin user with --admin flag', async function () { run('node create-user --admin --email=foo@bar.com') expect(await getUser('foo@bar.com')).to.deep.equal({ isAdmin: true }) }) it('should exit with code 1 on missing email', function () { try { run('node create-user') } catch (e) { expect(e.status).to.equal(1) return } expect.fail('command should have failed') }) }) describe('delete-user', function () { let user beforeEach(async function () { user = new User() await user.login() }) it('should log missing user', function () { const email = 'does-not-exist@example.com' const out = run('node delete-user --email=' + email) expect(out).to.include('not in database, potentially already deleted') }) it('should exit with code 0 on success', function () { const email = user.email run('node delete-user --email=' + email) }) it('should have deleted the user on success', async function () { const email = user.email run('node delete-user --email=' + email) const dbEntry = await user.get() expect(dbEntry).to.not.exist }) it('should exit with code 1 on missing email', function () { try { run('node delete-user') } catch (e) { expect(e.status).to.equal(1) return } expect.fail('command should have failed') }) }) })
overleaf/web/modules/server-ce-scripts/test/acceptance/src/ServerCEScriptsTests.js/0
{ "file_path": "overleaf/web/modules/server-ce-scripts/test/acceptance/src/ServerCEScriptsTests.js", "repo_id": "overleaf", "token_count": 1483 }
542
const readline = require('readline') const { waitForDb } = require('../app/src/infrastructure/mongodb') const ProjectEntityHandler = require('../app/src/Features/Project/ProjectEntityHandler') const ProjectGetter = require('../app/src/Features/Project/ProjectGetter') const Errors = require('../app/src/Features/Errors/Errors') /* eslint-disable no-console */ async function countFiles() { const rl = readline.createInterface({ input: process.stdin, }) for await (const projectId of rl) { try { const project = await ProjectGetter.promises.getProject(projectId) if (!project) { throw new Errors.NotFoundError('project not found') } const { files, docs, } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project) console.error( projectId, files.length, (project.deletedFiles && project.deletedFiles.length) || 0, docs.length, (project.deletedDocs && project.deletedDocs.length) || 0 ) } catch (err) { if (err instanceof Errors.NotFoundError) { console.error(projectId, 'NOTFOUND') } else { console.log(projectId, 'ERROR', err.name, err.message) } } } } waitForDb() .then(countFiles) .then(() => { process.exit(0) }) .catch(err => { console.log('Aiee, something went wrong!', err) process.exit(1) })
overleaf/web/scripts/count_files_in_projects.js/0
{ "file_path": "overleaf/web/scripts/count_files_in_projects.js", "repo_id": "overleaf", "token_count": 553 }
543
const { checkSanitizeOptions } = require('./checkSanitizeOptions') const { getAllPagesAndCache, scrapeAndCachePage } = require('./scrape') async function main() { const BASE_URL = process.argv.pop() if (!BASE_URL.startsWith('http')) { throw new Error( 'Usage: node scripts/learn/checkSanitize https://LEARN_WIKI' ) } const pages = await getAllPagesAndCache(BASE_URL) for (const page of pages) { try { const parsed = await scrapeAndCachePage(BASE_URL, page) const title = parsed.title const text = parsed.text ? parsed.text['*'] : '' checkSanitizeOptions(page, title, text) } catch (e) { console.error('---') console.error(page, e) throw e } } } if (require.main === module) { main().catch(err => { console.error(err) process.exit(1) }) }
overleaf/web/scripts/learn/checkSanitize/index.js/0
{ "file_path": "overleaf/web/scripts/learn/checkSanitize/index.js", "repo_id": "overleaf", "token_count": 330 }
544
const { getNextBatch } = require('./helpers/batchedUpdate') const { db, waitForDb } = require('../app/src/infrastructure/mongodb') const MODEL_NAME = process.argv.pop() const Model = require(`../app/src/models/${MODEL_NAME}`)[MODEL_NAME] function processBatch(batch) { for (const doc of batch) { const error = new Model(doc).validateSync() if (error) { const { errors } = error console.log(JSON.stringify({ _id: doc._id, errors })) } } } async function main() { await waitForDb() const collection = db[Model.collection.name] const query = {} const projection = {} let nextBatch let processed = 0 let maxId while ( (nextBatch = await getNextBatch(collection, query, maxId, projection)) .length ) { processBatch(nextBatch) maxId = nextBatch[nextBatch.length - 1]._id processed += nextBatch.length console.error(maxId, processed) } console.error('done') } main() .then(() => { process.exit(0) }) .catch(error => { console.error({ error }) process.exit(1) })
overleaf/web/scripts/validate-data-of-model.js/0
{ "file_path": "overleaf/web/scripts/validate-data-of-model.js", "repo_id": "overleaf", "token_count": 401 }
545
/* eslint-disable node/handle-callback-err, 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 Settings = require('@overleaf/settings') const request = require('./helpers/request') describe('siteIsOpen', function () { describe('when siteIsOpen is default (true)', function () { it('should get page', function (done) { return request.get('/login', (error, response, body) => { response.statusCode.should.equal(200) return done() }) }) }) describe('when siteIsOpen is false', function () { beforeEach(function () { return (Settings.siteIsOpen = false) }) afterEach(function () { return (Settings.siteIsOpen = true) }) it('should return maintenance page', function (done) { request.get('/login', (error, response, body) => { response.statusCode.should.equal(503) body.should.match(/is currently down for maintenance/) done() }) }) it('should return a plain text message for a json request', function (done) { request.get('/some/route', { json: true }, (error, response, body) => { response.statusCode.should.equal(503) body.message.should.match(/maintenance/) body.message.should.match(/status.example.com/) done() }) }) it('should return a 200 on / for load balancer health checks', function (done) { request.get('/', (error, response, body) => { response.statusCode.should.equal(200) done() }) }) it('should return a 200 on /status for readiness checks', function (done) { request.get('/status', (error, response, body) => { response.statusCode.should.equal(200) done() }) }) }) })
overleaf/web/test/acceptance/src/CloseSiteTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/CloseSiteTests.js", "repo_id": "overleaf", "token_count": 751 }
546
const { expect } = require('chai') const Async = require('async') const User = require('./helpers/User') const settings = require('@overleaf/settings') const CollaboratorsEmailHandler = require('../../../app/src/Features/Collaborators/CollaboratorsEmailHandler') const Features = require('../../../app/src/infrastructure/Features') const createInvite = (sendingUser, projectId, email, callback) => { sendingUser.getCsrfToken(err => { if (err) { return callback(err) } sendingUser.request.post( { uri: `/project/${projectId}/invite`, json: { email, privileges: 'readAndWrite', }, }, (err, response, body) => { if (err) { return callback(err) } expect(response.statusCode).to.equal(200) callback(null, body.invite) } ) }) } const createProject = (owner, projectName, callback) => { owner.createProject(projectName, (err, projectId) => { if (err) { throw err } const fakeProject = { _id: projectId, name: projectName, owner_ref: owner, } callback(err, projectId, fakeProject) }) } const createProjectAndInvite = (owner, projectName, email, callback) => { createProject(owner, projectName, (err, projectId, project) => { if (err) { return callback(err) } createInvite(owner, projectId, email, (err, invite) => { if (err) { return callback(err) } const link = CollaboratorsEmailHandler._buildInviteUrl(project, invite) callback(null, project, invite, link) }) }) } const revokeInvite = (sendingUser, projectId, inviteId, callback) => { sendingUser.getCsrfToken(err => { if (err) { return callback(err) } sendingUser.request.delete( { uri: `/project/${projectId}/invite/${inviteId}`, }, err => { if (err) { return callback(err) } callback() } ) }) } // Actions const tryFollowInviteLink = (user, link, callback) => { user.request.get( { uri: link, baseUrl: null, }, callback ) } const tryAcceptInvite = (user, invite, callback) => { user.getCsrfToken(err => { if (err) { return callback(err) } user.request.post( { uri: `/project/${invite.projectId}/invite/token/${invite.token}/accept`, json: { token: invite.token, }, }, callback ) }) } const tryRegisterUser = (user, email, callback) => { user.getCsrfToken(error => { if (error != null) { return callback(error) } user.request.post( { url: '/register', json: { email, password: 'some_weird_password', }, }, callback ) }) } const tryFollowLoginLink = (user, loginLink, callback) => { user.getCsrfToken(error => { if (error != null) { return callback(error) } user.request.get(loginLink, callback) }) } const tryLoginUser = (user, callback) => { user.getCsrfToken(error => { if (error != null) { return callback(error) } user.request.post( { url: '/login', json: { email: user.email, password: user.password, }, }, callback ) }) } const tryGetInviteList = (user, projectId, callback) => { user.getCsrfToken(error => { if (error != null) { return callback(error) } user.request.get( { url: `/project/${projectId}/invites`, json: true, }, callback ) }) } const tryJoinProject = (user, projectId, callback) => { return user.getCsrfToken(error => { if (error != null) { return callback(error) } user.request.post( { url: `/project/${projectId}/join`, qs: { user_id: user._id }, auth: { user: settings.apis.web.user, pass: settings.apis.web.pass, sendImmediately: true, }, json: true, jar: false, }, callback ) }) } // Expectations const expectProjectAccess = (user, projectId, callback) => { // should have access to project user.openProject(projectId, err => { expect(err).not.to.exist callback() }) } const expectNoProjectAccess = (user, projectId, callback) => { // should not have access to project page user.openProject(projectId, err => { expect(err).to.be.instanceof(Error) callback() }) } const expectInvitePage = (user, link, callback) => { // view invite tryFollowInviteLink(user, link, (err, response, body) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) expect(body).to.match(/<title>Project Invite - .*<\/title>/) callback() }) } const expectInvalidInvitePage = (user, link, callback) => { // view invalid invite tryFollowInviteLink(user, link, (err, response, body) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) expect(body).to.match(/<title>Invalid Invite - .*<\/title>/) callback() }) } const expectInviteRedirectToRegister = (user, link, callback) => { // view invite, redirect to `/register` tryFollowInviteLink(user, link, (err, response) => { expect(err).not.to.exist expect(response.statusCode).to.equal(302) expect(response.headers.location).to.match(/^\/register.*$/) callback() }) } const expectLoginPage = (user, callback) => { tryFollowLoginLink(user, '/login', (err, response, body) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) expect(body).to.match(/<title>Login - .*<\/title>/) callback() }) } const expectLoginRedirectToInvite = (user, link, callback) => { tryLoginUser(user, (err, response) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) callback() }) } const expectRegistrationRedirectToInvite = (user, email, link, callback) => { tryRegisterUser(user, email, (err, response) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) callback() }) } const expectInviteRedirectToProject = (user, link, invite, callback) => { // view invite, redirect straight to project tryFollowInviteLink(user, link, (err, response) => { expect(err).not.to.exist expect(response.statusCode).to.equal(302) expect(response.headers.location).to.equal(`/project/${invite.projectId}`) callback() }) } const expectAcceptInviteAndRedirect = (user, invite, callback) => { // should accept the invite and redirect to project tryAcceptInvite(user, invite, (err, response) => { expect(err).not.to.exist expect(response.statusCode).to.equal(302) expect(response.headers.location).to.equal(`/project/${invite.projectId}`) callback() }) } const expectInviteListCount = (user, projectId, count, callback) => { tryGetInviteList(user, projectId, (err, response, body) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) expect(body).to.have.all.keys(['invites']) expect(body.invites.length).to.equal(count) callback() }) } const expectInvitesInJoinProjectCount = (user, projectId, count, callback) => { tryJoinProject(user, projectId, (err, response, body) => { expect(err).not.to.exist expect(response.statusCode).to.equal(200) expect(body.project).to.contain.keys(['invites']) expect(body.project.invites.length).to.equal(count) callback() }) } describe('ProjectInviteTests', function () { beforeEach(function (done) { this.sendingUser = new User() this.user = new User() this.site_admin = new User({ email: 'admin@example.com' }) this.email = 'smoketestuser@example.com' this.projectName = 'sharing test' Async.series( [ cb => this.user.ensureUserExists(cb), cb => this.sendingUser.login(cb), cb => this.sendingUser.setFeatures({ collaborators: 10 }, cb), ], done ) }) describe('creating invites', function () { beforeEach(function () { this.projectName = 'wat' }) describe('creating two invites', function () { beforeEach(function (done) { createProject( this.sendingUser, this.projectName, (err, projectId, project) => { expect(err).not.to.exist this.projectId = projectId this.fakeProject = project done() } ) }) it('should allow the project owner to create and remove invites', function (done) { Async.series( [ cb => expectProjectAccess(this.sendingUser, this.projectId, cb), cb => expectInviteListCount(this.sendingUser, this.projectId, 0, cb), // create invite, check invite list count cb => { createInvite( this.sendingUser, this.projectId, this.email, (err, invite) => { if (err) { return cb(err) } this.invite = invite cb() } ) }, cb => expectInviteListCount(this.sendingUser, this.projectId, 1, cb), cb => revokeInvite( this.sendingUser, this.projectId, this.invite._id, cb ), cb => expectInviteListCount(this.sendingUser, this.projectId, 0, cb), // and a second time cb => { createInvite( this.sendingUser, this.projectId, this.email, (err, invite) => { if (err) { return cb(err) } this.invite = invite cb() } ) }, cb => expectInviteListCount(this.sendingUser, this.projectId, 1, cb), // check the joinProject view cb => expectInvitesInJoinProjectCount( this.sendingUser, this.projectId, 1, cb ), // revoke invite cb => revokeInvite( this.sendingUser, this.projectId, this.invite._id, cb ), cb => expectInviteListCount(this.sendingUser, this.projectId, 0, cb), cb => expectInvitesInJoinProjectCount( this.sendingUser, this.projectId, 0, cb ), ], done ) }) it('should allow the project owner to create many invites at once', function (done) { Async.series( [ cb => expectProjectAccess(this.sendingUser, this.projectId, cb), cb => expectInviteListCount(this.sendingUser, this.projectId, 0, cb), // create first invite cb => { createInvite( this.sendingUser, this.projectId, this.email, (err, invite) => { if (err) { return cb(err) } this.inviteOne = invite cb() } ) }, cb => expectInviteListCount(this.sendingUser, this.projectId, 1, cb), // and a second cb => { createInvite( this.sendingUser, this.projectId, this.email, (err, invite) => { if (err) { return cb(err) } this.inviteTwo = invite cb() } ) }, // should have two cb => expectInviteListCount(this.sendingUser, this.projectId, 2, cb), cb => expectInvitesInJoinProjectCount( this.sendingUser, this.projectId, 2, cb ), // revoke first cb => revokeInvite( this.sendingUser, this.projectId, this.inviteOne._id, cb ), cb => expectInviteListCount(this.sendingUser, this.projectId, 1, cb), // revoke second cb => revokeInvite( this.sendingUser, this.projectId, this.inviteTwo._id, cb ), cb => expectInviteListCount(this.sendingUser, this.projectId, 0, cb), ], done ) }) }) }) describe('clicking the invite link', function () { beforeEach(function (done) { createProjectAndInvite( this.sendingUser, this.projectName, this.email, (err, project, invite, link) => { expect(err).not.to.exist this.projectId = project._id this.fakeProject = project this.invite = invite this.link = link done() } ) }) describe('user is logged in already', function () { beforeEach(function (done) { this.user.login(done) }) describe('user is already a member of the project', function () { beforeEach(function (done) { Async.series( [ cb => expectInvitePage(this.user, this.link, cb), cb => expectAcceptInviteAndRedirect(this.user, this.invite, cb), cb => expectProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) describe('when user clicks on the invite a second time', function () { it('should just redirect to the project page', function (done) { Async.series( [ cb => expectProjectAccess(this.user, this.invite.projectId, cb), cb => expectInviteRedirectToProject( this.user, this.link, this.invite, cb ), cb => expectProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) describe('when the user recieves another invite to the same project', function () { it('should redirect to the project page', function (done) { Async.series( [ cb => { createInvite( this.sendingUser, this.projectId, this.email, (err, invite) => { if (err) { throw err } this.secondInvite = invite this.secondLink = CollaboratorsEmailHandler._buildInviteUrl( this.fakeProject, invite ) cb() } ) }, cb => expectInviteRedirectToProject( this.user, this.secondLink, this.secondInvite, cb ), cb => expectProjectAccess(this.user, this.invite.projectId, cb), cb => revokeInvite( this.sendingUser, this.projectId, this.secondInvite._id, cb ), ], done ) }) }) }) }) describe('user is not a member of the project', function () { it('should not grant access if the user does not accept the invite', function (done) { Async.series( [ cb => expectInvitePage(this.user, this.link, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) it('should render the invalid-invite page if the token is invalid', function (done) { Async.series( [ cb => { const link = this.link.replace( this.invite.token, 'not_a_real_token' ) expectInvalidInvitePage(this.user, link, cb) }, cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) it('should allow the user to accept the invite and access the project', function (done) { Async.series( [ cb => expectInvitePage(this.user, this.link, cb), cb => expectAcceptInviteAndRedirect(this.user, this.invite, cb), cb => expectProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) }) }) describe('user is not logged in initially', function () { describe('registration prompt workflow with valid token', function () { before(function () { if (!Features.hasFeature('registration')) { this.skip() } }) it('should redirect to the register page', function (done) { expectInviteRedirectToRegister(this.user, this.link, done) }) it('should allow user to accept the invite if the user registers a new account', function (done) { Async.series( [ cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectRegistrationRedirectToInvite( this.user, 'some_email@example.com', this.link, cb ), cb => expectInvitePage(this.user, this.link, cb), cb => expectAcceptInviteAndRedirect(this.user, this.invite, cb), cb => expectProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) }) describe('registration prompt workflow with non-valid token', function () { before(function () { if (!Features.hasFeature('registration')) { this.skip() } }) it('should redirect to the register page', function (done) { Async.series( [ cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) it('should display invalid-invite if the user registers a new account', function (done) { const badLink = this.link.replace( this.invite.token, 'not_a_real_token' ) Async.series( [ cb => expectInviteRedirectToRegister(this.user, badLink, cb), cb => expectRegistrationRedirectToInvite( this.user, 'some_email@example.com', badLink, cb ), cb => expectInvalidInvitePage(this.user, badLink, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) }) describe('login workflow with valid token', function () { it('should redirect to the register page', function (done) { Async.series( [ cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) it('should allow the user to login to view the invite', function (done) { Async.series( [ cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectLoginPage(this.user, cb), cb => expectLoginRedirectToInvite(this.user, this.link, cb), cb => expectInvitePage(this.user, this.link, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) it('should allow user to accept the invite if the user logs in', function (done) { Async.series( [ cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectLoginPage(this.user, cb), cb => expectLoginRedirectToInvite(this.user, this.link, cb), cb => expectInvitePage(this.user, this.link, cb), cb => expectAcceptInviteAndRedirect(this.user, this.invite, cb), cb => expectProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) }) describe('login workflow with non-valid token', function () { it('should redirect to the register page', function (done) { Async.series( [ cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) it('should show the invalid-invite page once the user has logged in', function (done) { const badLink = this.link.replace( this.invite.token, 'not_a_real_token' ) Async.series( [ cb => { return expectInviteRedirectToRegister(this.user, badLink, cb) }, cb => { return expectLoginPage(this.user, cb) }, cb => expectLoginRedirectToInvite(this.user, badLink, cb), cb => expectInvalidInvitePage(this.user, badLink, cb), cb => expectNoProjectAccess(this.user, this.invite.projectId, cb), ], done ) }) }) }) }) })
overleaf/web/test/acceptance/src/ProjectInviteTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/ProjectInviteTests.js", "repo_id": "overleaf", "token_count": 11769 }
547
const AuthenticationManager = require('../../../app/src/Features/Authentication/AuthenticationManager') const UserHelper = require('./helpers/UserHelper') const Features = require('../../../app/src/infrastructure/Features') const { expect } = require('chai') describe('UserHelper', function () { // Disable all tests unless the registration feature is enabled beforeEach(function () { if (!Features.hasFeature('registration')) { this.skip() } }) describe('UserHelper.createUser', function () { describe('with no args', function () { it('should create new user with default username and password', async function () { const userHelper = await UserHelper.createUser() userHelper.user.email.should.equal(userHelper.getDefaultEmail()) const authedUser = await AuthenticationManager.promises.authenticate( { _id: userHelper.user._id }, userHelper.getDefaultPassword() ) expect(authedUser).to.not.be.null }) }) describe('with email', function () { it('should create new user with provided email and default password', async function () { const userHelper = await UserHelper.createUser({ email: 'foo@test.com', }) userHelper.user.email.should.equal('foo@test.com') const authedUser = await AuthenticationManager.promises.authenticate( { _id: userHelper.user._id }, userHelper.getDefaultPassword() ) expect(authedUser).to.not.be.null }) }) describe('with password', function () { it('should create new user with provided password and default email', async function () { const userHelper = await UserHelper.createUser({ password: 'foofoofoo', }) userHelper.user.email.should.equal(userHelper.getDefaultEmail()) const authedUser = await AuthenticationManager.promises.authenticate( { _id: userHelper.user._id }, 'foofoofoo' ) expect(authedUser).to.not.be.null }) }) }) describe('UserHelper.getUser', function () { let user beforeEach(async function () { user = (await UserHelper.createUser()).user }) describe('with string id', function () { it('should fetch user', async function () { const userHelper = await UserHelper.getUser(user._id.toString()) userHelper.user.email.should.equal(user.email) }) }) describe('with _id', function () { it('should fetch user', async function () { const userHelper = await UserHelper.getUser({ _id: user._id }) userHelper.user.email.should.equal(user.email) }) }) }) describe('UserHelper.loginUser', function () { let userHelper beforeEach(async function () { userHelper = await UserHelper.createUser() }) describe('with email and password', function () { it('should login user', async function () { const newUserHelper = await UserHelper.loginUser({ email: userHelper.getDefaultEmail(), password: userHelper.getDefaultPassword(), }) newUserHelper.user.email.should.equal(userHelper.user.email) }) }) describe('without email', function () { it('should throw error', async function () { await UserHelper.loginUser({ password: userHelper.getDefaultPassword(), }).should.be.rejectedWith('email and password required') }) }) describe('without password', function () { it('should throw error', async function () { await UserHelper.loginUser({ email: userHelper.getDefaultEmail(), }).should.be.rejectedWith('email and password required') }) }) describe('without email and password', function () { it('should throw error', async function () { await UserHelper.loginUser().should.be.rejectedWith( 'email and password required' ) }) }) }) describe('UserHelper.registerUser', function () { describe('with no args', function () { it('should create new user with default username and password', async function () { const userHelper = await UserHelper.registerUser() userHelper.user.email.should.equal(userHelper.getDefaultEmail()) const authedUser = await AuthenticationManager.promises.authenticate( { _id: userHelper.user._id }, userHelper.getDefaultPassword() ) expect(authedUser).to.not.be.null }) }) describe('with email', function () { it('should create new user with provided email and default password', async function () { const userHelper = await UserHelper.registerUser({ email: 'foo2@test.com', }) userHelper.user.email.should.equal('foo2@test.com') const authedUser = await AuthenticationManager.promises.authenticate( { _id: userHelper.user._id }, userHelper.getDefaultPassword() ) expect(authedUser).to.not.be.null }) }) describe('with password', function () { it('should create new user with provided password and default email', async function () { const userHelper = await UserHelper.registerUser({ password: 'foofoofoo', }) userHelper.user.email.should.equal(userHelper.getDefaultEmail()) const authedUser = await AuthenticationManager.promises.authenticate( { _id: userHelper.user._id }, 'foofoofoo' ) expect(authedUser).to.not.be.null }) }) }) describe('getCsrfToken', function () { it('should fetch csrfToken', async function () { const userHelper = new UserHelper() await userHelper.getCsrfToken() expect(userHelper.csrfToken).to.be.a.string }) }) describe('after logout', function () { let userHelper, oldCsrfToken beforeEach(async function () { userHelper = await UserHelper.registerUser() oldCsrfToken = userHelper.csrfToken }) it('refreshes csrf token after logout', async function () { await userHelper.logout() expect(userHelper._csrfToken).to.equal('') await userHelper.getCsrfToken() expect(userHelper._csrfToken).to.not.equal('') expect(userHelper._csrfToken).to.not.equal(oldCsrfToken) }) }) })
overleaf/web/test/acceptance/src/UserHelperTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/UserHelperTests.js", "repo_id": "overleaf", "token_count": 2380 }
548
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. const BASE_URL = `http://${process.env.HTTP_TEST_HOST || 'localhost'}:3000` const request = require('request').defaults({ baseUrl: BASE_URL, followRedirect: false, }) module.exports = request module.exports.promises = { request: function (options) { return new Promise((resolve, reject) => { request(options, (err, response) => { if (err) { reject(err) } else { resolve(response) } }) }) }, }
overleaf/web/test/acceptance/src/helpers/request.js/0
{ "file_path": "overleaf/web/test/acceptance/src/helpers/request.js", "repo_id": "overleaf", "token_count": 225 }
549
import { expect } from 'chai' import { fireEvent, screen, waitForElementToBeRemoved, } from '@testing-library/react' import fetchMock from 'fetch-mock' import ChatPane from '../../../../../frontend/js/features/chat/components/chat-pane' import { renderWithChatContext, cleanUpContext, } from '../../../helpers/render-with-context' import { stubMathJax, tearDownMathJaxStubs } from './stubs' describe('<ChatPane />', function () { const user = { id: 'fake_user', first_name: 'fake_user_first_name', email: 'fake@example.com', } const testMessages = [ { id: 'msg_1', content: 'a message', user, timestamp: new Date().getTime(), }, { id: 'msg_2', content: 'another message', user, timestamp: new Date().getTime(), }, ] beforeEach(function () { fetchMock.reset() cleanUpContext() stubMathJax() }) afterEach(function () { tearDownMathJaxStubs() }) it('renders multiple messages', async function () { fetchMock.get(/messages/, testMessages) renderWithChatContext(<ChatPane />, { user }) await screen.findByText('a message') await screen.findByText('another message') }) it('provides error message with reload button on FetchError', async function () { fetchMock.get(/messages/, 500) renderWithChatContext(<ChatPane />, { user }) // should have hit a FetchError and will prompt user to reconnect await screen.findByText('Try again') // bring chat back up fetchMock.reset() fetchMock.get(/messages/, []) const reconnectButton = screen.getByRole('button', { name: 'Try again', }) expect(reconnectButton).to.exist // should now reconnect with placeholder message fireEvent.click(reconnectButton) await screen.findByText('Send your first message to your collaborators') }) it('a loading spinner is rendered while the messages are loading, then disappears', async function () { fetchMock.get(/messages/, []) renderWithChatContext(<ChatPane />, { user }) await waitForElementToBeRemoved(() => screen.getByText('Loading…')) }) describe('"send your first message" placeholder', function () { it('is rendered when there are no messages ', async function () { fetchMock.get(/messages/, []) renderWithChatContext(<ChatPane />, { user }) await screen.findByText('Send your first message to your collaborators') }) it('is not rendered when messages are displayed', function () { fetchMock.get(/messages/, testMessages) renderWithChatContext(<ChatPane />, { user }) expect( screen.queryByText('Send your first message to your collaborators') ).to.not.exist }) }) })
overleaf/web/test/frontend/features/chat/components/chat-pane.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/chat/components/chat-pane.test.js", "repo_id": "overleaf", "token_count": 973 }
550
import { expect } from 'chai' import { screen, fireEvent } from '@testing-library/react' import renderWithContext from '../helpers/render-with-context' import FileTreeFolderList from '../../../../../frontend/js/features/file-tree/components/file-tree-folder-list' describe('<FileTreeFolderList/>', function () { it('renders empty', function () { renderWithContext(<FileTreeFolderList folders={[]} docs={[]} files={[]} />) screen.queryByRole('tree') expect(screen.queryByRole('treeitem')).to.not.exist }) it('renders docs, files and folders', function () { const aFolder = { _id: '456def', name: 'A Folder', folders: [], docs: [], fileRefs: [], } const aDoc = { _id: '789ghi', name: 'doc.tex', linkedFileData: {} } const aFile = { _id: '987jkl', name: 'file.bib', linkedFileData: {} } renderWithContext( <FileTreeFolderList folders={[aFolder]} docs={[aDoc]} files={[aFile]} /> ) screen.queryByRole('tree') screen.queryByRole('treeitem', { name: 'A Folder' }) screen.queryByRole('treeitem', { name: 'doc.tex' }) screen.queryByRole('treeitem', { name: 'file.bib' }) }) describe('selection and multi-selection', function () { it('without write permissions', function () { const docs = [ { _id: '1', name: '1.tex' }, { _id: '2', name: '2.tex' }, ] renderWithContext( <FileTreeFolderList folders={[]} docs={docs} files={[]} />, { contextProps: { hasWritePermissions: false, rootFolder: [ { docs: [{ _id: '1' }, { _id: '2' }], fileRefs: [], folders: [], }, ], }, } ) const treeitem1 = screen.getByRole('treeitem', { name: '1.tex' }) const treeitem2 = screen.getByRole('treeitem', { name: '2.tex' }) // click on item 1: it gets selected fireEvent.click(treeitem1) screen.getByRole('treeitem', { name: '1.tex', selected: true }) screen.getByRole('treeitem', { name: '2.tex', selected: false }) // meta-click on item 2: no changes fireEvent.click(treeitem2, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: true }) screen.getByRole('treeitem', { name: '2.tex', selected: false }) }) it('with write permissions', function () { const docs = [ { _id: '1', name: '1.tex' }, { _id: '2', name: '2.tex' }, { _id: '3', name: '3.tex' }, ] renderWithContext( <FileTreeFolderList folders={[]} docs={docs} files={[]} />, { contextProps: { rootFolder: [ { docs: [{ _id: '1' }, { _id: '2' }, { _id: '3' }], fileRefs: [], folders: [], }, ], }, } ) const treeitem1 = screen.getByRole('treeitem', { name: '1.tex' }) const treeitem2 = screen.getByRole('treeitem', { name: '2.tex' }) const treeitem3 = screen.getByRole('treeitem', { name: '3.tex' }) // click item 1: it gets selected fireEvent.click(treeitem1) screen.getByRole('treeitem', { name: '1.tex', selected: true }) screen.getByRole('treeitem', { name: '2.tex', selected: false }) screen.getByRole('treeitem', { name: '3.tex', selected: false }) // click on item 2: it gets selected and item 1 is not selected anymore fireEvent.click(treeitem2) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: false }) // meta-click on item 3: it gets selected and item 2 as well fireEvent.click(treeitem3, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: true }) // meta-click on item 1: add to selection fireEvent.click(treeitem1, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: true }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: true }) // meta-click on item 1: remove from selection fireEvent.click(treeitem1, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: true }) // meta-click on item 3: remove from selection fireEvent.click(treeitem3, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: false }) // meta-click on item 2: cannot unselect fireEvent.click(treeitem2, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: false }) // meta-click on item 3: add back to selection fireEvent.click(treeitem3, { ctrlKey: true }) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: true }) screen.getByRole('treeitem', { name: '3.tex', selected: true }) // click on item 3: unselect other items fireEvent.click(treeitem3) screen.getByRole('treeitem', { name: '1.tex', selected: false }) screen.getByRole('treeitem', { name: '2.tex', selected: false }) screen.getByRole('treeitem', { name: '3.tex', selected: true }) }) }) })
overleaf/web/test/frontend/features/file-tree/components/file-tree-folder-list.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/file-tree/components/file-tree-folder-list.test.js", "repo_id": "overleaf", "token_count": 2507 }
551
import { screen, waitForElementToBeRemoved, fireEvent, } from '@testing-library/react' import fetchMock from 'fetch-mock' import { renderWithEditorContext } from '../../../helpers/render-with-context' import FileView from '../../../../../frontend/js/features/file-view/components/file-view.js' describe('<FileView/>', function () { const textFile = { 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 imageFile = { id: '60097ca20454610027c442a8', name: 'file.jpg', linkedFileData: { source_entity_path: '/source-entity-path', provider: 'project_file', }, } beforeEach(function () { fetchMock.reset() }) describe('for a text file', function () { it('shows a loading indicator while the file is loading', async function () { renderWithEditorContext( <FileView file={textFile} storeReferencesKeys={() => {}} /> ) await waitForElementToBeRemoved(() => screen.getByText('Loading', { exact: false }) ) }) it('shows messaging if the text view could not be loaded', async function () { renderWithEditorContext( <FileView file={textFile} storeReferencesKeys={() => {}} /> ) await screen.findByText('Sorry, no preview is available', { exact: false, }) }) }) describe('for an image file', function () { it('shows a loading indicator while the file is loading', async function () { renderWithEditorContext( <FileView file={imageFile} storeReferencesKeys={() => {}} /> ) screen.getByText('Loading', { exact: false }) }) it('shows messaging if the image could not be loaded', async function () { renderWithEditorContext( <FileView file={imageFile} storeReferencesKeys={() => {}} /> ) // Fake the image request failing as the request is handled by the browser fireEvent.error(screen.getByRole('img')) await screen.findByText('Sorry, no preview is available', { exact: false, }) }) }) })
overleaf/web/test/frontend/features/file-view/components/file-view.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/file-view/components/file-view.test.js", "repo_id": "overleaf", "token_count": 843 }
552
import { expect } from 'chai' import sinon from 'sinon' import { screen, render, fireEvent, waitFor } from '@testing-library/react' import SymbolPalette from '../../../../../frontend/js/features/symbol-palette/components/symbol-palette' describe('symbol palette', function () { let clock before(function () { clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'], }) }) after(function () { clock.runAll() clock.restore() }) it('handles keyboard interaction', async function () { this.timeout(10000) const handleSelect = sinon.stub() const { container } = render( <SymbolPalette show handleSelect={handleSelect} /> ) // check the number of tabs const tabs = await screen.findAllByRole('tab') expect(tabs).to.have.length(5) let selectedTab let symbols // the first tab should be selected selectedTab = await screen.getByRole('tab', { selected: true }) expect(selectedTab.textContent).to.equal('Greek') symbols = await screen.findAllByRole('option') expect(symbols).to.have.length(39) // click to select the third tab tabs[2].click() selectedTab = await screen.getByRole('tab', { selected: true }) expect(selectedTab.textContent).to.equal('Operators') symbols = await screen.findAllByRole('option') expect(symbols).to.have.length(20) // press the left arrow to select the second tab fireEvent.keyDown(selectedTab, { key: 'ArrowLeft' }) selectedTab = await screen.getByRole('tab', { selected: true }) expect(selectedTab.textContent).to.equal('Arrows') symbols = await screen.findAllByRole('option') expect(symbols).to.have.length(16) // select the search input const input = await screen.getByRole('searchbox') input.click() // type in the search input fireEvent.change(input, { target: { value: 'pi' } }) // make sure all scheduled microtasks have executed clock.runAll() // wait for the symbols to be filtered await waitFor(async () => { symbols = await screen.findAllByRole('option') expect(symbols).to.have.length(2) }) // check the search hint is displayed screen.getByText('Showing search results for "pi"') // press Tab to select the symbols fireEvent.keyDown(container, { key: 'Tab' }) // get the selected symbol let selectedSymbol selectedSymbol = await screen.getByRole('option', { selected: true }) expect(selectedSymbol.textContent).to.equal('𝜋') // move to the next symbol fireEvent.keyDown(selectedSymbol, { key: 'ArrowRight' }) // wait for the symbol to be selected selectedSymbol = await screen.getByRole('option', { selected: true }) expect(selectedSymbol.textContent).to.equal('Π') // click on the selected symbol selectedSymbol.click() expect(handleSelect).to.have.been.calledWith({ aliases: ['Π'], category: 'Greek', character: 'Π', codepoint: 'U+003A0', command: '\\Pi', description: 'Uppercase Greek letter Pi', notes: 'Use \\prod for the product.', }) }) })
overleaf/web/test/frontend/features/symbol-palette/components/symbol-palette.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/symbol-palette/components/symbol-palette.test.js", "repo_id": "overleaf", "token_count": 1105 }
553
/* global chai */ // Allow for mocking of Angular import 'angular' import 'angular-mocks' /** * Add chai assertion for comparing CodeMirror Pos objects. * A deep comparison will fail because CodeMirror inserts additional properties * that we want to ignore. */ chai.Assertion.addMethod('equalPos', function (expectedPos) { const { line: actualLine, ch: actualCh } = this._obj const { line: expectedLine, ch: expectedCh } = expectedPos this.assert( actualLine === expectedLine && actualCh === expectedCh, `expected #{exp} to equal #{act}`, `expected #{exp} to not equal #{act}`, `Pos({ line: ${expectedLine}, ch: ${expectedCh} })`, `Pos({ line: ${actualLine}, ch: ${actualCh} })` ) }) // Mock ExposedSettings window.ExposedSettings = {} /* * Bundle all test files together into a single bundle, and run tests against * this single bundle. * We are using karma-webpack to bundle our tests and the 'default' strategy is * to create a bundle for each test file. This isolates the tests better, but * causes a problem with Angular. The issue with Angular tests is because we * load a single global copy of Angular (see karma.conf.js) but * frontend/js/base.js is included in each bundle, meaning the Angular app is * initialised for each bundle when it is loaded onto the page when Karma * starts. This means that only the last bundle will have controllers/directives * registered against it, ultimately meaning that all other bundles will fail * because Angular cannot find the controller/directive under test. */ // Import from the top-level any JS files within a test/karma // directory const context = require.context('../../', true, /test\/karma\/.*\.js$/) context.keys().forEach(context)
overleaf/web/test/karma/import_tests.js/0
{ "file_path": "overleaf/web/test/karma/import_tests.js", "repo_id": "overleaf", "token_count": 479 }
554
const sinon = require('sinon') const { expect } = require('chai') const modulePath = '../../../../app/src/Features/Authentication/AuthenticationController.js' const SandboxedModule = require('sandboxed-module') const tk = require('timekeeper') const MockRequest = require('../helpers/MockRequest') const MockResponse = require('../helpers/MockResponse') const { ObjectId } = require('mongodb') describe('AuthenticationController', function () { beforeEach(function () { tk.freeze(Date.now()) this.UserModel = { findOne: sinon.stub() } this.httpAuthUsers = { 'valid-test-user': Math.random().toString(16).slice(2), } this.user = { _id: ObjectId(), email: (this.email = 'USER@example.com'), first_name: 'bob', last_name: 'brown', referal_id: 1234, isAdmin: false, } this.password = 'banana' this.req = new MockRequest() this.res = new MockResponse() this.callback = sinon.stub() this.next = sinon.stub() this.AuthenticationController = SandboxedModule.require(modulePath, { requires: { '../User/UserAuditLogHandler': (this.UserAuditLogHandler = { addEntry: sinon.stub().yields(null), }), '../Helpers/AsyncFormHelper': (this.AsyncFormHelper = { redirect: sinon.stub(), }), '../../infrastructure/RequestContentTypeDetection': { acceptsJson: (this.acceptsJson = sinon.stub().returns(false)), }, './AuthenticationManager': (this.AuthenticationManager = {}), '../User/UserUpdater': (this.UserUpdater = { updateUser: sinon.stub(), }), '@overleaf/metrics': (this.Metrics = { inc: sinon.stub() }), '../Security/LoginRateLimiter': (this.LoginRateLimiter = { processLoginRequest: sinon.stub(), recordSuccessfulLogin: sinon.stub(), }), '../User/UserHandler': (this.UserHandler = { setupLoginData: sinon.stub(), }), '../Analytics/AnalyticsManager': (this.AnalyticsManager = { recordEvent: sinon.stub(), identifyUser: sinon.stub(), }), '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = {}), '@overleaf/settings': (this.Settings = { siteUrl: 'http://www.foo.bar', httpAuthUsers: this.httpAuthUsers, }), passport: (this.passport = { authenticate: sinon.stub().returns(sinon.stub()), }), '../User/UserSessionsManager': (this.UserSessionsManager = { trackSession: sinon.stub(), untrackSession: sinon.stub(), revokeAllUserSessions: sinon.stub().callsArgWith(1, null), }), '../../infrastructure/Modules': (this.Modules = { hooks: { fire: sinon.stub().yields(null, []) }, }), '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = { ipMatcherAffiliation: sinon.stub().returns({ create: sinon.stub() }), }), '../../models/User': { User: this.UserModel }, '../../../../modules/oauth2-server/app/src/Oauth2Server': (this.Oauth2Server = { Request: sinon.stub(), Response: sinon.stub(), server: { authenticate: sinon.stub(), }, }), '../Helpers/UrlHelper': (this.UrlHelper = { getSafeRedirectPath: sinon.stub(), }), './SessionManager': (this.SessionManager = { isUserLoggedIn: sinon.stub().returns(true), getSessionUser: sinon.stub().returns(this.user), }), }, }) this.UrlHelper.getSafeRedirectPath .withArgs('https://evil.com') .returns(undefined) this.UrlHelper.getSafeRedirectPath.returnsArg(0) }) afterEach(function () { tk.reset() }) describe('validateAdmin', function () { beforeEach(function () { this.Settings.adminDomains = ['good.example.com'] this.goodAdmin = { email: 'alice@good.example.com', isAdmin: true, } this.badAdmin = { email: 'beatrice@bad.example.com', isAdmin: true, } this.normalUser = { email: 'claire@whatever.example.com', isAdmin: false, } }) it('should skip when adminDomains are not configured', function (done) { this.Settings.adminDomains = [] this.SessionManager.getSessionUser = sinon.stub().returns(this.normalUser) this.AuthenticationController.validateAdmin(this.req, this.res, err => { this.SessionManager.getSessionUser.called.should.equal(false) expect(err).to.not.exist done() }) }) it('should skip non-admin user', function (done) { this.SessionManager.getSessionUser = sinon.stub().returns(this.normalUser) this.AuthenticationController.validateAdmin(this.req, this.res, err => { this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.not.exist done() }) }) it('should permit an admin with the right doman', function (done) { this.SessionManager.getSessionUser = sinon.stub().returns(this.goodAdmin) this.AuthenticationController.validateAdmin(this.req, this.res, err => { this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.not.exist done() }) }) it('should block an admin with a missing email', function (done) { this.SessionManager.getSessionUser = sinon .stub() .returns({ isAdmin: true }) this.AuthenticationController.validateAdmin(this.req, this.res, err => { this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.exist done() }) }) it('should block an admin with a bad domain', function (done) { this.SessionManager.getSessionUser = sinon.stub().returns(this.badAdmin) this.AuthenticationController.validateAdmin(this.req, this.res, err => { this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.exist done() }) }) }) describe('passportLogin', function () { beforeEach(function () { this.info = null this.req.login = sinon.stub().callsArgWith(1, null) this.res.json = sinon.stub() this.req.session = { passport: { user: this.user }, postLoginRedirect: '/path/to/redir/to', } this.req.session.destroy = sinon.stub().callsArgWith(0, null) this.req.session.save = sinon.stub().callsArgWith(0, null) this.req.sessionStore = { generate: sinon.stub() } this.AuthenticationController.finishLogin = sinon.stub() this.passport.authenticate.callsArgWith(1, null, this.user, this.info) this.err = new Error('woops') }) it('should call passport.authenticate', function () { this.AuthenticationController.passportLogin(this.req, this.res, this.next) this.passport.authenticate.callCount.should.equal(1) }) describe('when authenticate produces an error', function () { beforeEach(function () { this.passport.authenticate.callsArgWith(1, this.err) }) it('should return next with an error', function () { this.AuthenticationController.passportLogin( this.req, this.res, this.next ) this.next.calledWith(this.err).should.equal(true) }) }) describe('when authenticate produces a user', function () { beforeEach(function () { this.req.session.postLoginRedirect = 'some_redirect' this.passport.authenticate.callsArgWith(1, null, this.user, this.info) }) afterEach(function () { delete this.req.session.postLoginRedirect }) it('should call finishLogin', function () { this.AuthenticationController.passportLogin( this.req, this.res, this.next ) this.AuthenticationController.finishLogin.callCount.should.equal(1) this.AuthenticationController.finishLogin .calledWith(this.user) .should.equal(true) }) }) describe('when authenticate does not produce a user', function () { beforeEach(function () { this.info = { text: 'a', type: 'b' } this.passport.authenticate.callsArgWith(1, null, false, this.info) }) it('should not call finishLogin', function () { this.AuthenticationController.passportLogin( this.req, this.res, this.next ) this.AuthenticationController.finishLogin.callCount.should.equal(0) }) it('should not send a json response with redirect', function () { this.AuthenticationController.passportLogin( this.req, this.res, this.next ) this.res.json.callCount.should.equal(1) this.res.json.calledWith({ message: this.info }).should.equal(true) expect(this.res.json.lastCall.args[0].redir != null).to.equal(false) }) }) }) describe('doPassportLogin', function () { beforeEach(function () { this.AuthenticationController._recordFailedLogin = sinon.stub() this.AuthenticationController._recordSuccessfulLogin = sinon.stub() this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, []) // @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) this.req.body = { email: this.email, password: this.password, session: { postLoginRedirect: '/path/to/redir/to', }, } this.cb = sinon.stub() }) describe('when the preDoPassportLogin hooks produce an info object', function () { beforeEach(function () { this.Modules.hooks.fire = sinon .stub() .callsArgWith(3, null, [null, { redir: '/somewhere' }, null]) }) it('should stop early and call done with this info object', function (done) { this.AuthenticationController.doPassportLogin( this.req, this.req.body.email, this.req.body.password, this.cb ) this.cb.callCount.should.equal(1) this.cb .calledWith(null, false, { redir: '/somewhere' }) .should.equal(true) this.LoginRateLimiter.processLoginRequest.callCount.should.equal(0) done() }) }) describe('when the users rate limit', function () { beforeEach(function () { this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) }) it('should block the request if the limit has been exceeded', function (done) { this.AuthenticationController.doPassportLogin( this.req, this.req.body.email, this.req.body.password, this.cb ) this.cb.callCount.should.equal(1) this.cb.calledWith(null, null).should.equal(true) done() }) }) describe('when the user is authenticated', function () { beforeEach(function () { this.cb = sinon.stub() this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) this.AuthenticationManager.authenticate = sinon .stub() .callsArgWith(2, null, this.user) this.req.sessionID = Math.random() this.AuthenticationController.doPassportLogin( this.req, this.req.body.email, this.req.body.password, this.cb ) }) it('should attempt to authorise the user', function () { this.AuthenticationManager.authenticate .calledWith({ email: this.email.toLowerCase() }, this.password) .should.equal(true) }) it("should establish the user's session", function () { this.cb.calledWith(null, this.user).should.equal(true) }) }) describe('when the user is not authenticated', function () { beforeEach(function () { this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) this.AuthenticationManager.authenticate = sinon .stub() .callsArgWith(2, null, null) this.cb = sinon.stub() this.AuthenticationController.doPassportLogin( this.req, this.req.body.email, this.req.body.password, this.cb ) }) it('should not establish the login', function () { this.cb.callCount.should.equal(1) this.cb.calledWith(null, false) // @res.body.should.exist expect(this.cb.lastCall.args[2]).to.contain.all.keys(['text', 'type']) }) // message: // text: 'Your email or password were incorrect. Please try again', // type: 'error' it('should not setup the user data in the background', function () { this.UserHandler.setupLoginData.called.should.equal(false) }) it('should record a failed login', function () { this.AuthenticationController._recordFailedLogin.called.should.equal( true ) }) it('should log the failed login', function () { this.logger.log .calledWith({ email: this.email.toLowerCase() }, 'failed log in') .should.equal(true) }) }) }) describe('requireLogin', function () { beforeEach(function () { this.user = { _id: 'user-id-123', email: 'user@sharelatex.com', } this.middleware = this.AuthenticationController.requireLogin() }) describe('when the user is logged in', function () { beforeEach(function () { this.req.session = { user: (this.user = { _id: 'user-id-123', email: 'user@sharelatex.com', }), } this.middleware(this.req, this.res, this.next) }) it('should call the next method in the chain', function () { this.next.called.should.equal(true) }) }) describe('when the user is not logged in', function () { beforeEach(function () { this.req.session = {} this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() this.req.query = {} this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) it('should redirect to the register or login page', function () { this.AuthenticationController._redirectToLoginOrRegisterPage .calledWith(this.req, this.res) .should.equal(true) }) }) }) describe('validateUserSession', function () { beforeEach(function () { this.user = { _id: 'user-id-123', email: 'user@sharelatex.com', } this.middleware = this.AuthenticationController.validateUserSession() }) describe('when the user has a session token', function () { beforeEach(function () { this.req.user = this.user this.SessionStoreManager.hasValidationToken = sinon.stub().returns(true) this.middleware(this.req, this.res, this.next) }) it('should call the next method in the chain', function () { this.next.called.should.equal(true) }) }) describe('when the user does not have a session token', function () { beforeEach(function () { this.req.session = { user: this.user, regenerate: sinon.stub().yields(), } this.req.user = this.user this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() this.req.query = {} this.SessionStoreManager.hasValidationToken = sinon .stub() .returns(false) this.middleware(this.req, this.res, this.next) }) it('should destroy the current session', function () { this.req.session.regenerate.called.should.equal(true) }) it('should redirect to the register or login page', function () { this.AuthenticationController._redirectToLoginOrRegisterPage .calledWith(this.req, this.res) .should.equal(true) }) }) }) describe('requireOauth', function () { beforeEach(function () { this.res.send = sinon.stub() this.res.status = sinon.stub().returns(this.res) this.res.sendStatus = sinon.stub() this.middleware = this.AuthenticationController.requireOauth() }) describe('when Oauth2Server authenticates', function () { beforeEach(function () { this.token = { accessToken: 'token', user: 'user', } this.Oauth2Server.server.authenticate.yields(null, this.token) this.middleware(this.req, this.res, this.next) }) it('should set oauth_token on request', function () { this.req.oauth_token.should.equal(this.token) }) it('should set oauth on request', function () { this.req.oauth.access_token.should.equal(this.token.accessToken) }) it('should set oauth_user on request', function () { this.req.oauth_user.should.equal('user') }) it('should call next', function () { this.next.should.have.been.calledOnce }) }) describe('when Oauth2Server returns 401 error', function () { beforeEach(function () { this.Oauth2Server.server.authenticate.yields({ code: 401 }) this.middleware(this.req, this.res, this.next) }) it('should return 401 error', function () { this.res.status.should.have.been.calledWith(401) }) it('should not call next', function () { this.next.should.have.not.been.calledOnce }) }) }) describe('requireGlobalLogin', function () { beforeEach(function () { this.req.headers = {} this.middleware = sinon.stub() this.AuthenticationController.requirePrivateApiAuth = sinon .stub() .returns(this.middleware) this.setRedirect = sinon.spy( this.AuthenticationController, 'setRedirectInSession' ) }) afterEach(function () { this.setRedirect.restore() }) describe('with white listed url', function () { beforeEach(function () { this.AuthenticationController.addEndpointToLoginWhitelist('/login') this.req._parsedUrl.pathname = '/login' this.AuthenticationController.requireGlobalLogin( this.req, this.res, this.next ) }) it('should call next() directly', function () { this.next.called.should.equal(true) }) }) describe('with white listed url and a query string', function () { beforeEach(function () { this.AuthenticationController.addEndpointToLoginWhitelist('/login') this.req._parsedUrl.pathname = '/login' this.req.url = '/login?query=something' this.AuthenticationController.requireGlobalLogin( this.req, this.res, this.next ) }) it('should call next() directly', function () { this.next.called.should.equal(true) }) }) describe('with http auth', function () { beforeEach(function () { this.req.headers.authorization = 'Mock Basic Auth' this.AuthenticationController.requireGlobalLogin( this.req, this.res, this.next ) }) it('should pass the request onto requirePrivateApiAuth middleware', function () { this.middleware .calledWith(this.req, this.res, this.next) .should.equal(true) }) }) describe('with a user session', function () { beforeEach(function () { this.req.session = { user: { mock: 'user', _id: 'some_id' } } this.AuthenticationController.requireGlobalLogin( this.req, this.res, this.next ) }) it('should call next() directly', function () { this.next.called.should.equal(true) }) }) describe('with no login credentials', function () { beforeEach(function () { this.req.session = {} this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.AuthenticationController.requireGlobalLogin( this.req, this.res, this.next ) }) it('should have called setRedirectInSession', function () { this.setRedirect.callCount.should.equal(1) }) it('should redirect to the /login page', function () { this.res.redirectedTo.should.equal('/login') }) }) }) describe('requireBasicAuth', function () { beforeEach(function () { this.basicAuthUsers = { 'basic-auth-user': 'basic-auth-password', } this.middleware = this.AuthenticationController.requireBasicAuth( this.basicAuthUsers ) }) describe('with http auth', function () { it('should error with incorrect user', function (done) { this.req.headers = { authorization: `Basic ${Buffer.from('user:nope').toString('base64')}`, } this.req.end = status => { expect(status).to.equal('Unauthorized') done() } this.middleware(this.req, this.req) }) it('should error with incorrect password', function (done) { this.req.headers = { authorization: `Basic ${Buffer.from('basic-auth-user:nope').toString( 'base64' )}`, } this.req.end = status => { expect(status).to.equal('Unauthorized') done() } this.middleware(this.req, this.req) }) it('should fail with empty pass', function (done) { this.req.headers = { authorization: `Basic ${Buffer.from(`basic-auth-user:`).toString( 'base64' )}`, } this.req.end = status => { expect(status).to.equal('Unauthorized') done() } this.middleware(this.req, this.req) }) it('should succeed with correct user/pass', function (done) { this.req.headers = { authorization: `Basic ${Buffer.from( `basic-auth-user:${this.basicAuthUsers['basic-auth-user']}` ).toString('base64')}`, } this.middleware(this.req, this.res, done) }) }) }) describe('requirePrivateApiAuth', function () { beforeEach(function () { this.AuthenticationController.requireBasicAuth = sinon.stub() }) it('should call requireBasicAuth with the private API user details', function () { this.AuthenticationController.requirePrivateApiAuth() this.AuthenticationController.requireBasicAuth .calledWith(this.httpAuthUsers) .should.equal(true) }) }) describe('_redirectToLoginOrRegisterPage', function () { beforeEach(function () { this.middleware = this.AuthenticationController.requireLogin( (this.options = { load_from_db: false }) ) this.req.session = {} this.AuthenticationController._redirectToRegisterPage = sinon.stub() this.AuthenticationController._redirectToLoginPage = sinon.stub() this.req.query = {} }) describe('they have come directly to the url', function () { beforeEach(function () { this.req.query = {} this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) it('should redirect to the login page', function () { this.AuthenticationController._redirectToRegisterPage .calledWith(this.req, this.res) .should.equal(false) this.AuthenticationController._redirectToLoginPage .calledWith(this.req, this.res) .should.equal(true) }) }) describe('they have come via a templates link', function () { beforeEach(function () { this.req.query.zipUrl = 'something' this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) it('should redirect to the register page', function () { this.AuthenticationController._redirectToRegisterPage .calledWith(this.req, this.res) .should.equal(true) this.AuthenticationController._redirectToLoginPage .calledWith(this.req, this.res) .should.equal(false) }) }) describe('they have been invited to a project', function () { beforeEach(function () { this.req.query.project_name = 'something' this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) it('should redirect to the register page', function () { this.AuthenticationController._redirectToRegisterPage .calledWith(this.req, this.res) .should.equal(true) this.AuthenticationController._redirectToLoginPage .calledWith(this.req, this.res) .should.equal(false) }) }) }) describe('_redirectToRegisterPage', function () { beforeEach(function () { this.req.path = '/target/url' this.req.query = { extra_query: 'foo' } this.AuthenticationController._redirectToRegisterPage(this.req, this.res) }) it('should redirect to the register page with a query string attached', function () { this.req.session.postLoginRedirect.should.equal( '/target/url?extra_query=foo' ) this.res.redirectedTo.should.equal('/register?extra_query=foo') }) it('should log out a message', function () { this.logger.log .calledWith( { url: this.url }, 'user not logged in so redirecting to register page' ) .should.equal(true) }) }) describe('_redirectToLoginPage', function () { beforeEach(function () { this.req.path = '/target/url' this.req.query = { extra_query: 'foo' } this.AuthenticationController._redirectToLoginPage(this.req, this.res) }) it('should redirect to the register page with a query string attached', function () { this.req.session.postLoginRedirect.should.equal( '/target/url?extra_query=foo' ) this.res.redirectedTo.should.equal('/login?extra_query=foo') }) }) describe('_recordSuccessfulLogin', function () { beforeEach(function () { this.UserUpdater.updateUser = sinon.stub().callsArg(2) this.AuthenticationController._recordSuccessfulLogin( this.user._id, this.callback ) }) it('should increment the user.login.success metric', function () { this.Metrics.inc.calledWith('user.login.success').should.equal(true) }) it("should update the user's login count and last logged in date", function () { this.UserUpdater.updateUser.args[0][1].$set.lastLoggedIn.should.not.equal( undefined ) this.UserUpdater.updateUser.args[0][1].$inc.loginCount.should.equal(1) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('_recordFailedLogin', function () { beforeEach(function () { this.AuthenticationController._recordFailedLogin(this.callback) }) it('should increment the user.login.failed metric', function () { this.Metrics.inc.calledWith('user.login.failed').should.equal(true) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('setRedirectInSession', function () { beforeEach(function () { this.req = { session: {} } this.req.path = '/somewhere' this.req.query = { one: '1' } }) it('should set redirect property on session', function () { this.AuthenticationController.setRedirectInSession(this.req) expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1') }) it('should set the supplied value', function () { this.AuthenticationController.setRedirectInSession( this.req, '/somewhere/specific' ) expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific') }) it('should not allow open redirects', function () { this.AuthenticationController.setRedirectInSession( this.req, 'https://evil.com' ) expect(this.req.session.postLoginRedirect).to.be.undefined }) describe('with a png', function () { beforeEach(function () { this.req = { session: {} } }) it('should not set the redirect', function () { this.AuthenticationController.setRedirectInSession( this.req, '/something.png' ) expect(this.req.session.postLoginRedirect).to.equal(undefined) }) }) describe('with a js path', function () { beforeEach(function () { this.req = { session: {} } }) it('should not set the redirect', function () { this.AuthenticationController.setRedirectInSession( this.req, '/js/something.js' ) expect(this.req.session.postLoginRedirect).to.equal(undefined) }) }) }) describe('_getRedirectFromSession', function () { it('should get redirect property from session', function () { this.req = { session: { postLoginRedirect: '/a?b=c' } } expect( this.AuthenticationController._getRedirectFromSession(this.req) ).to.equal('/a?b=c') }) it('should not allow open redirects', function () { this.req = { session: { postLoginRedirect: 'https://evil.com' } } expect(this.AuthenticationController._getRedirectFromSession(this.req)).to .be.null }) it('handle null values', function () { this.req = { session: {} } expect(this.AuthenticationController._getRedirectFromSession(this.req)).to .be.null }) }) describe('_clearRedirectFromSession', function () { beforeEach(function () { this.req = { session: { postLoginRedirect: '/a?b=c' } } }) it('should remove the redirect property from session', function () { this.AuthenticationController._clearRedirectFromSession(this.req) expect(this.req.session.postLoginRedirect).to.equal(undefined) }) }) describe('finishLogin', function () { // - get redirect // - async handlers // - afterLoginSessionSetup // - clear redirect // - issue redir, two ways beforeEach(function () { this.AuthenticationController._getRedirectFromSession = sinon .stub() .returns('/some/page') this.req.sessionID = 'thisisacryptographicallysecurerandomid' this.req.session = { passport: { user: { _id: 'one' } }, } this.req.session.destroy = sinon.stub().callsArgWith(0, null) this.req.session.save = sinon.stub().callsArgWith(0, null) this.req.sessionStore = { generate: sinon.stub() } this.req.login = sinon.stub().yields(null) this.AuthenticationController._clearRedirectFromSession = sinon.stub() this.AuthenticationController._redirectToReconfirmPage = sinon.stub() this.UserSessionsManager.trackSession = sinon.stub() this.UserHandler.setupLoginData = sinon.stub() this.LoginRateLimiter.recordSuccessfulLogin = sinon.stub() this.AuthenticationController._recordSuccessfulLogin = sinon.stub() this.AnalyticsManager.recordEvent = sinon.stub() this.AnalyticsManager.identifyUser = sinon.stub() this.acceptsJson.returns(true) this.res.json = sinon.stub() this.res.redirect = sinon.stub() }) it('should extract the redirect from the session', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect( this.AuthenticationController._getRedirectFromSession.callCount ).to.equal(1) expect( this.AuthenticationController._getRedirectFromSession.calledWith( this.req ) ).to.equal(true) }) it('should clear redirect from session', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect( this.AuthenticationController._clearRedirectFromSession.callCount ).to.equal(1) expect( this.AuthenticationController._clearRedirectFromSession.calledWith( this.req ) ).to.equal(true) }) it('should issue a json response with a redirect', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect( this.AsyncFormHelper.redirect.calledWith( this.req, this.res, '/some/page' ) ).to.equal(true) }) describe('with a non-json request', function () { beforeEach(function () { this.acceptsJson.returns(false) this.res.json = sinon.stub() this.res.redirect = sinon.stub() }) it('should issue a plain redirect', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect( this.AsyncFormHelper.redirect.calledWith( this.req, this.res, '/some/page' ) ).to.equal(true) }) }) describe('when user is flagged to reconfirm', function () { beforeEach(function () { this.req.session = {} this.user.must_reconfirm = true }) it('should redirect to reconfirm page', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect( this.AuthenticationController._redirectToReconfirmPage.calledWith( this.req ) ).to.equal(true) }) }) describe('preFinishLogin hook', function () { it('call hook and proceed', function () { this.Modules.hooks.fire = sinon.stub().yields(null, []) this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) sinon.assert.calledWith( this.Modules.hooks.fire, 'preFinishLogin', this.req, this.res, this.user ) expect(this.AsyncFormHelper.redirect.called).to.equal(true) }) it('stop if hook has redirected', function (done) { this.Modules.hooks.fire = sinon .stub() .yields(null, [{ doNotFinish: true }]) this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect(this.next.callCount).to.equal(0) expect(this.res.json.callCount).to.equal(0) done() }) it('call next with hook errors', function (done) { this.Modules.hooks.fire = sinon.stub().yields(new Error()) this.AuthenticationController.finishLogin( this.user, this.req, this.res, error => { expect(error).to.exist expect(this.res.json.callCount).to.equal(0) done() } ) }) }) describe('UserAuditLog', function () { it('should add an audit log entry', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect(this.UserAuditLogHandler.addEntry).to.have.been.calledWith( this.user._id, 'login', this.user._id, '42.42.42.42' ) }) it('should add an audit log entry before logging the user in', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect(this.UserAuditLogHandler.addEntry).to.have.been.calledBefore( this.req.login ) }) it('should not log the user in without an audit log entry', function () { const theError = new Error() this.UserAuditLogHandler.addEntry.yields(theError) this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect(this.next).to.have.been.calledWith(theError) expect(this.req.login).to.not.have.been.called }) }) describe('_afterLoginSessionSetup', function () { beforeEach(function () {}) it('should call req.login', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) this.req.login.callCount.should.equal(1) }) it('should erase the CSRF secret', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) expect(this.req.session.csrfSecret).to.not.exist }) it('should call req.session.save', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) this.req.session.save.callCount.should.equal(1) }) it('should call UserSessionsManager.trackSession', function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) this.UserSessionsManager.trackSession.callCount.should.equal(1) }) describe('when req.session.save produces an error', function () { beforeEach(function () { this.req.session.save = sinon .stub() .callsArgWith(0, new Error('woops')) }) it('should produce an error', function (done) { this.AuthenticationController.finishLogin( this.user, this.req, this.res, err => { expect(err).to.not.be.oneOf([null, undefined]) expect(err).to.be.instanceof(Error) done() } ) }) it('should not call UserSessionsManager.trackSession', function (done) { this.AuthenticationController.finishLogin( this.user, this.req, this.res, err => { expect(err).to.exist this.UserSessionsManager.trackSession.callCount.should.equal(0) done() } ) }) }) }) describe('_loginAsyncHandlers', function () { beforeEach(function () { this.AuthenticationController.finishLogin( this.user, this.req, this.res, this.next ) }) it('should call identifyUser', function () { this.AnalyticsManager.identifyUser .calledWith(this.user._id, this.req.sessionID) .should.equal(true) }) it('should setup the user data in the background', function () { this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true) }) it('should set res.session.justLoggedIn', function () { this.req.session.justLoggedIn.should.equal(true) }) it('should record the successful login', function () { this.AuthenticationController._recordSuccessfulLogin .calledWith(this.user._id) .should.equal(true) }) it('should tell the rate limiter that there was a success for that email', function () { this.LoginRateLimiter.recordSuccessfulLogin .calledWith(this.user.email) .should.equal(true) }) it('should log the successful login', function () { this.logger.log .calledWith( { email: this.user.email, user_id: this.user._id.toString() }, 'successful log in' ) .should.equal(true) }) it('should track the login event', function () { this.AnalyticsManager.recordEvent .calledWith(this.user._id, 'user-logged-in') .should.equal(true) }) }) }) })
overleaf/web/test/unit/src/Authentication/AuthenticationControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Authentication/AuthenticationControllerTests.js", "repo_id": "overleaf", "token_count": 17584 }
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 { assert, expect } = require('chai') const modulePath = '../../../../app/src/Features/Compile/ClsiCookieManager.js' const SandboxedModule = require('sandboxed-module') const realRequst = require('request') describe('ClsiCookieManager', function () { beforeEach(function () { const self = this this.redis = { auth() {}, get: sinon.stub(), setex: sinon.stub().callsArg(3), } this.project_id = '123423431321' this.request = { post: sinon.stub(), cookie: realRequst.cookie, jar: realRequst.jar, defaults: () => { return this.request }, } this.settings = { redis: { web: 'redis.something', }, apis: { clsi: { url: 'http://clsi.example.com', }, }, clsiCookie: { ttl: Math.random(), key: 'coooookie', }, } this.requires = { '../../infrastructure/RedisWrapper': (this.RedisWrapper = { client: () => this.redis, }), '@overleaf/settings': this.settings, request: this.request, } return (this.ClsiCookieManager = SandboxedModule.require(modulePath, { requires: this.requires, })()) }) describe('getServerId', function () { it('should call get for the key', function (done) { this.redis.get.callsArgWith(1, null, 'clsi-7') return this.ClsiCookieManager._getServerId( this.project_id, (err, serverId) => { this.redis.get .calledWith(`clsiserver:${this.project_id}`) .should.equal(true) serverId.should.equal('clsi-7') return done() } ) }) it('should _populateServerIdViaRequest if no key is found', function (done) { this.ClsiCookieManager._populateServerIdViaRequest = sinon .stub() .callsArgWith(1) this.redis.get.callsArgWith(1, null) return this.ClsiCookieManager._getServerId( this.project_id, (err, serverId) => { this.ClsiCookieManager._populateServerIdViaRequest .calledWith(this.project_id) .should.equal(true) return done() } ) }) it('should _populateServerIdViaRequest if no key is blank', function (done) { this.ClsiCookieManager._populateServerIdViaRequest = sinon .stub() .callsArgWith(1) this.redis.get.callsArgWith(1, null, '') return this.ClsiCookieManager._getServerId( this.project_id, (err, serverId) => { this.ClsiCookieManager._populateServerIdViaRequest .calledWith(this.project_id) .should.equal(true) return done() } ) }) }) describe('_populateServerIdViaRequest', function () { beforeEach(function () { this.response = 'some data' this.request.post.callsArgWith(1, null, this.response) return (this.ClsiCookieManager.setServerId = sinon .stub() .callsArgWith(2, null, 'clsi-9')) }) it('should make a request to the clsi', function (done) { return this.ClsiCookieManager._populateServerIdViaRequest( this.project_id, (err, serverId) => { const args = this.ClsiCookieManager.setServerId.args[0] args[0].should.equal(this.project_id) args[1].should.deep.equal(this.response) return done() } ) }) it('should return the server id', function (done) { return this.ClsiCookieManager._populateServerIdViaRequest( this.project_id, (err, serverId) => { serverId.should.equal('clsi-9') return done() } ) }) }) describe('setServerId', function () { beforeEach(function () { this.response = 'dsadsakj' this.ClsiCookieManager._parseServerIdFromResponse = sinon .stub() .returns('clsi-8') }) it('should set the server id with a ttl', function (done) { return this.ClsiCookieManager.setServerId( this.project_id, this.response, err => { this.redis.setex .calledWith( `clsiserver:${this.project_id}`, this.settings.clsiCookie.ttl, 'clsi-8' ) .should.equal(true) return done() } ) }) it('should return the server id', function (done) { return this.ClsiCookieManager.setServerId( this.project_id, this.response, (err, serverId) => { serverId.should.equal('clsi-8') return done() } ) }) it('should not set the server id if clsiCookies are not enabled', function (done) { delete this.settings.clsiCookie.key this.ClsiCookieManager = SandboxedModule.require(modulePath, { globals: { console: console, }, requires: this.requires, })() return this.ClsiCookieManager.setServerId( this.project_id, this.response, (err, serverId) => { this.redis.setex.called.should.equal(false) return done() } ) }) it('should not set the server id there is no server id in the response', function (done) { this.ClsiCookieManager._parseServerIdFromResponse = sinon .stub() .returns(null) return this.ClsiCookieManager.setServerId( this.project_id, this.response, (err, serverId) => { this.redis.setex.called.should.equal(false) return done() } ) }) it('should also set in the secondary if secondary redis is enabled', function (done) { this.redis_secondary = { setex: sinon.stub().callsArg(3) } this.settings.redis.clsi_cookie_secondary = {} this.RedisWrapper.client = sinon.stub() this.RedisWrapper.client.withArgs('clsi_cookie').returns(this.redis) this.RedisWrapper.client .withArgs('clsi_cookie_secondary') .returns(this.redis_secondary) this.ClsiCookieManager = SandboxedModule.require(modulePath, { globals: { console: console, }, requires: this.requires, })() this.ClsiCookieManager._parseServerIdFromResponse = sinon .stub() .returns('clsi-8') return this.ClsiCookieManager.setServerId( this.project_id, this.response, (err, serverId) => { this.redis_secondary.setex .calledWith( `clsiserver:${this.project_id}`, this.settings.clsiCookie.ttl, 'clsi-8' ) .should.equal(true) return done() } ) }) }) describe('getCookieJar', function () { beforeEach(function () { return (this.ClsiCookieManager._getServerId = sinon .stub() .callsArgWith(1, null, 'clsi-11')) }) it('should return a jar with the cookie set populated from redis', function (done) { return this.ClsiCookieManager.getCookieJar( this.project_id, (err, jar) => { jar._jar.store.idx['clsi.example.com']['/'][ this.settings.clsiCookie.key ].key.should.equal jar._jar.store.idx['clsi.example.com']['/'][ this.settings.clsiCookie.key ].value.should.equal('clsi-11') return done() } ) }) it('should return empty cookie jar if clsiCookies are not enabled', function (done) { delete this.settings.clsiCookie.key this.ClsiCookieManager = SandboxedModule.require(modulePath, { globals: { console: console, }, requires: this.requires, })() return this.ClsiCookieManager.getCookieJar( this.project_id, (err, jar) => { assert.deepEqual(jar, realRequst.jar()) return done() } ) }) }) })
overleaf/web/test/unit/src/Compile/ClsiCookieManagerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Compile/ClsiCookieManagerTests.js", "repo_id": "overleaf", "token_count": 3904 }
556
/* 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 SandboxedModule = require('sandboxed-module') const sinon = require('sinon') const { expect } = require('chai') const modulePath = require('path').join( __dirname, '../../../../app/src/Features/Editor/EditorController' ) const MockClient = require('../helpers/MockClient') const assert = require('assert') const { ObjectId } = require('mongodb') describe('EditorController', function () { beforeEach(function () { this.project_id = 'test-project-id' this.source = 'dropbox' this.user_id = new ObjectId() this.doc = { _id: (this.doc_id = 'test-doc-id') } this.docName = 'doc.tex' this.docLines = ['1234', 'dskl'] this.file = { _id: (this.file_id = 'dasdkjk') } this.fileName = 'file.png' this.fsPath = '/folder/file.png' this.linkedFileData = { provider: 'url' } this.newFile = { _id: 'new-file-id' } this.folder_id = '123ksajdn' this.folder = { _id: this.folder_id } this.folderName = 'folder' this.callback = sinon.stub() return (this.EditorController = SandboxedModule.require(modulePath, { requires: { '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}), '../Project/ProjectOptionsHandler': (this.ProjectOptionsHandler = { setCompiler: sinon.stub().yields(), setImageName: sinon.stub().yields(), setSpellCheckLanguage: sinon.stub().yields(), }), '../Project/ProjectDetailsHandler': (this.ProjectDetailsHandler = { setProjectDescription: sinon.stub().yields(), renameProject: sinon.stub().yields(), setPublicAccessLevel: sinon.stub().yields(), }), '../Project/ProjectDeleter': (this.ProjectDeleter = {}), '../DocumentUpdater/DocumentUpdaterHandler': (this.DocumentUpdaterHandler = { flushDocToMongo: sinon.stub().yields(), setDocument: sinon.stub().yields(), }), './EditorRealTimeController': (this.EditorRealTimeController = { emitToRoom: sinon.stub(), }), '@overleaf/metrics': (this.Metrics = { inc: sinon.stub() }), }, })) }) describe('addDoc', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.addDocWithRanges = sinon .stub() .yields(null, this.doc, this.folder_id) return this.EditorController.addDoc( this.project_id, this.folder_id, this.docName, this.docLines, this.source, this.user_id, this.callback ) }) it('should add the doc using the project entity handler', function () { return this.ProjectEntityUpdateHandler.addDocWithRanges .calledWith( this.project_id, this.folder_id, this.docName, this.docLines, {} ) .should.equal(true) }) it('should send the update out to the users in the project', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewDoc', this.folder_id, this.doc, this.source, this.user_id ) .should.equal(true) }) it('calls the callback', function () { return this.callback.calledWith(null, this.doc).should.equal(true) }) }) describe('addFile', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.addFile = sinon .stub() .yields(null, this.file, this.folder_id) return this.EditorController.addFile( this.project_id, this.folder_id, this.fileName, this.fsPath, this.linkedFileData, this.source, this.user_id, this.callback ) }) it('should add the folder using the project entity handler', function () { return this.ProjectEntityUpdateHandler.addFile .calledWith( this.project_id, this.folder_id, this.fileName, this.fsPath, this.linkedFileData, this.user_id ) .should.equal(true) }) it('should send the update of a new folder out to the users in the project', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFile', this.folder_id, this.file, this.source, this.linkedFileData, this.user_id ) .should.equal(true) }) it('calls the callback', function () { return this.callback.calledWith(null, this.file).should.equal(true) }) }) describe('upsertDoc', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.upsertDoc = sinon .stub() .yields(null, this.doc, false) return this.EditorController.upsertDoc( this.project_id, this.folder_id, this.docName, this.docLines, this.source, this.user_id, this.callback ) }) it('upserts the doc using the project entity handler', function () { return this.ProjectEntityUpdateHandler.upsertDoc .calledWith( this.project_id, this.folder_id, this.docName, this.docLines, this.source ) .should.equal(true) }) it('returns the doc', function () { return this.callback.calledWith(null, this.doc).should.equal(true) }) describe('doc does not exist', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.upsertDoc = sinon .stub() .yields(null, this.doc, true) return this.EditorController.upsertDoc( this.project_id, this.folder_id, this.docName, this.docLines, this.source, this.user_id, this.callback ) }) it('sends an update out to users in the project', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewDoc', this.folder_id, this.doc, this.source, this.user_id ) .should.equal(true) }) }) }) describe('upsertFile', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.upsertFile = sinon .stub() .yields(null, this.newFile, false, this.file) return this.EditorController.upsertFile( this.project_id, this.folder_id, this.fileName, this.fsPath, this.linkedFileData, this.source, this.user_id, this.callback ) }) it('upserts the file using the project entity handler', function () { return this.ProjectEntityUpdateHandler.upsertFile .calledWith( this.project_id, this.folder_id, this.fileName, this.fsPath, this.linkedFileData, this.user_id ) .should.equal(true) }) it('returns the file', function () { return this.callback.calledWith(null, this.newFile).should.equal(true) }) describe('file does not exist', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.upsertFile = sinon .stub() .yields(null, this.file, true) return this.EditorController.upsertFile( this.project_id, this.folder_id, this.fileName, this.fsPath, this.linkedFileData, this.source, this.user_id, this.callback ) }) it('should send the update out to users in the project', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFile', this.folder_id, this.file, this.source, this.linkedFileData, this.user_id ) .should.equal(true) }) }) }) describe('upsertDocWithPath', function () { beforeEach(function () { this.docPath = '/folder/doc' this.ProjectEntityUpdateHandler.upsertDocWithPath = sinon .stub() .yields(null, this.doc, false, [], this.folder) return this.EditorController.upsertDocWithPath( this.project_id, this.docPath, this.docLines, this.source, this.user_id, this.callback ) }) it('upserts the doc using the project entity handler', function () { return this.ProjectEntityUpdateHandler.upsertDocWithPath .calledWith(this.project_id, this.docPath, this.docLines, this.source) .should.equal(true) }) describe('doc does not exist', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.upsertDocWithPath = sinon .stub() .yields(null, this.doc, true, [], this.folder) return this.EditorController.upsertDocWithPath( this.project_id, this.docPath, this.docLines, this.source, this.user_id, this.callback ) }) it('should send the update for the doc out to users in the project', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewDoc', this.folder_id, this.doc, this.source, this.user_id ) .should.equal(true) }) }) describe('folders required for doc do not exist', function () { beforeEach(function () { const folders = [ (this.folderA = { _id: 2, parentFolder_id: 1 }), (this.folderB = { _id: 3, parentFolder_id: 2 }), ] this.ProjectEntityUpdateHandler.upsertDocWithPath = sinon .stub() .yields(null, this.doc, true, folders, this.folderB) return this.EditorController.upsertDocWithPath( this.project_id, this.docPath, this.docLines, this.source, this.user_id, this.callback ) }) it('should send the update for each folder to users in the project', function () { this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFolder', this.folderA.parentFolder_id, this.folderA ) .should.equal(true) return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFolder', this.folderB.parentFolder_id, this.folderB ) .should.equal(true) }) }) }) describe('upsertFileWithPath', function () { beforeEach(function () { this.filePath = '/folder/file' this.ProjectEntityUpdateHandler.upsertFileWithPath = sinon .stub() .yields(null, this.newFile, false, this.file, [], this.folder) return this.EditorController.upsertFileWithPath( this.project_id, this.filePath, this.fsPath, this.linkedFileData, this.source, this.user_id, this.callback ) }) it('upserts the file using the project entity handler', function () { return this.ProjectEntityUpdateHandler.upsertFileWithPath .calledWith( this.project_id, this.filePath, this.fsPath, this.linkedFileData ) .should.equal(true) }) describe('file does not exist', function () { beforeEach(function () { this.ProjectEntityUpdateHandler.upsertFileWithPath = sinon .stub() .yields(null, this.file, true, undefined, [], this.folder) return this.EditorController.upsertFileWithPath( this.project_id, this.filePath, this.fsPath, this.linkedFileData, this.source, this.user_id, this.callback ) }) it('should send the update for the file out to users in the project', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFile', this.folder_id, this.file, this.source, this.linkedFileData, this.user_id ) .should.equal(true) }) }) describe('folders required for file do not exist', function () { beforeEach(function () { const folders = [ (this.folderA = { _id: 2, parentFolder_id: 1 }), (this.folderB = { _id: 3, parentFolder_id: 2 }), ] this.ProjectEntityUpdateHandler.upsertFileWithPath = sinon .stub() .yields(null, this.file, true, undefined, folders, this.folderB) return this.EditorController.upsertFileWithPath( this.project_id, this.filePath, this.fsPath, this.linkedFileData, this.source, this.user_id, this.callback ) }) it('should send the update for each folder to users in the project', function () { this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFolder', this.folderA.parentFolder_id, this.folderA ) .should.equal(true) return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveNewFolder', this.folderB.parentFolder_id, this.folderB ) .should.equal(true) }) }) }) describe('addFolder', function () { beforeEach(function () { this.EditorController._notifyProjectUsersOfNewFolder = sinon .stub() .yields() this.ProjectEntityUpdateHandler.addFolder = sinon .stub() .yields(null, this.folder, this.folder_id) return this.EditorController.addFolder( this.project_id, this.folder_id, this.folderName, this.source, this.user_id, this.callback ) }) it('should add the folder using the project entity handler', function () { return this.ProjectEntityUpdateHandler.addFolder .calledWith(this.project_id, this.folder_id, this.folderName) .should.equal(true) }) it('should notifyProjectUsersOfNewFolder', function () { return this.EditorController._notifyProjectUsersOfNewFolder .calledWith(this.project_id, this.folder_id, this.folder, this.user_id) .should.equal(true) }) it('should return the folder in the callback', function () { return this.callback.calledWith(null, this.folder).should.equal(true) }) }) describe('mkdirp', function () { beforeEach(function () { this.path = 'folder1/folder2' this.folders = [ (this.folderA = { _id: 2, parentFolder_id: 1 }), (this.folderB = { _id: 3, parentFolder_id: 2 }), ] this.EditorController._notifyProjectUsersOfNewFolders = sinon .stub() .yields() this.ProjectEntityUpdateHandler.mkdirp = sinon .stub() .yields(null, this.folders, this.folder) return this.EditorController.mkdirp( this.project_id, this.path, this.callback ) }) it('should create the folder using the project entity handler', function () { return this.ProjectEntityUpdateHandler.mkdirp .calledWith(this.project_id, this.path) .should.equal(true) }) it('should notifyProjectUsersOfNewFolder', function () { return this.EditorController._notifyProjectUsersOfNewFolders.calledWith( this.project_id, this.folders ) }) it('should return the folder in the callback', function () { return this.callback .calledWith(null, this.folders, this.folder) .should.equal(true) }) }) describe('deleteEntity', function () { beforeEach(function () { this.entity_id = 'entity_id_here' this.type = 'doc' this.ProjectEntityUpdateHandler.deleteEntity = sinon.stub().yields() return this.EditorController.deleteEntity( this.project_id, this.entity_id, this.type, this.source, this.user_id, this.callback ) }) it('should delete the folder using the project entity handler', function () { return this.ProjectEntityUpdateHandler.deleteEntity .calledWith(this.project_id, this.entity_id, this.type, this.user_id) .should.equal(true) }) it('notify users an entity has been deleted', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'removeEntity', this.entity_id, this.source ) .should.equal(true) }) }) describe('deleteEntityWithPath', function () { beforeEach(function () { this.entity_id = 'entity_id_here' this.ProjectEntityUpdateHandler.deleteEntityWithPath = sinon .stub() .yields(null, this.entity_id) this.path = 'folder1/folder2' return this.EditorController.deleteEntityWithPath( this.project_id, this.path, this.source, this.user_id, this.callback ) }) it('should delete the folder using the project entity handler', function () { return this.ProjectEntityUpdateHandler.deleteEntityWithPath .calledWith(this.project_id, this.path, this.user_id) .should.equal(true) }) it('notify users an entity has been deleted', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'removeEntity', this.entity_id, this.source ) .should.equal(true) }) }) describe('updateProjectDescription', function () { beforeEach(function () { this.description = 'new description' return this.EditorController.updateProjectDescription( this.project_id, this.description, this.callback ) }) it('should send the new description to the project details handler', function () { return this.ProjectDetailsHandler.setProjectDescription .calledWith(this.project_id, this.description) .should.equal(true) }) it('should notify the other clients about the updated description', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'projectDescriptionUpdated', this.description ) .should.equal(true) }) }) describe('deleteProject', function () { beforeEach(function () { this.err = 'errro' return (this.ProjectDeleter.deleteProject = sinon .stub() .callsArgWith(1, this.err)) }) it('should call the project handler', function (done) { return this.EditorController.deleteProject(this.project_id, err => { err.should.equal(this.err) this.ProjectDeleter.deleteProject .calledWith(this.project_id) .should.equal(true) return done() }) }) }) describe('renameEntity', function () { beforeEach(function (done) { this.entity_id = 'entity_id_here' this.entityType = 'doc' this.newName = 'bobsfile.tex' this.ProjectEntityUpdateHandler.renameEntity = sinon.stub().yields() return this.EditorController.renameEntity( this.project_id, this.entity_id, this.entityType, this.newName, this.user_id, done ) }) it('should call the project handler', function () { return this.ProjectEntityUpdateHandler.renameEntity .calledWith( this.project_id, this.entity_id, this.entityType, this.newName, this.user_id ) .should.equal(true) }) it('should emit the update to the room', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveEntityRename', this.entity_id, this.newName ) .should.equal(true) }) }) describe('moveEntity', function () { beforeEach(function () { this.entity_id = 'entity_id_here' this.entityType = 'doc' this.ProjectEntityUpdateHandler.moveEntity = sinon.stub().yields() return this.EditorController.moveEntity( this.project_id, this.entity_id, this.folder_id, this.entityType, this.user_id, this.callback ) }) it('should call the ProjectEntityUpdateHandler', function () { return this.ProjectEntityUpdateHandler.moveEntity .calledWith( this.project_id, this.entity_id, this.folder_id, this.entityType, this.user_id ) .should.equal(true) }) it('should emit the update to the room', function () { return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'reciveEntityMove', this.entity_id, this.folder_id ) .should.equal(true) }) it('calls the callback', function () { return this.callback.called.should.equal(true) }) }) describe('renameProject', function () { beforeEach(function () { this.err = 'errro' this.newName = 'new name here' return this.EditorController.renameProject( this.project_id, this.newName, this.callback ) }) it('should call the EditorController', function () { return this.ProjectDetailsHandler.renameProject .calledWith(this.project_id, this.newName) .should.equal(true) }) it('should emit the update to the room', function () { return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'projectNameUpdated', this.newName) .should.equal(true) }) }) describe('setCompiler', function () { beforeEach(function () { this.compiler = 'latex' return this.EditorController.setCompiler( this.project_id, this.compiler, this.callback ) }) it('should send the new compiler and project id to the project options handler', function () { this.ProjectOptionsHandler.setCompiler .calledWith(this.project_id, this.compiler) .should.equal(true) return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'compilerUpdated', this.compiler) .should.equal(true) }) }) describe('setImageName', function () { beforeEach(function () { this.imageName = 'texlive-1234.5' return this.EditorController.setImageName( this.project_id, this.imageName, this.callback ) }) it('should send the new imageName and project id to the project options handler', function () { this.ProjectOptionsHandler.setImageName .calledWith(this.project_id, this.imageName) .should.equal(true) return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'imageNameUpdated', this.imageName) .should.equal(true) }) }) describe('setSpellCheckLanguage', function () { beforeEach(function () { this.languageCode = 'fr' return this.EditorController.setSpellCheckLanguage( this.project_id, this.languageCode, this.callback ) }) it('should send the new languageCode and project id to the project options handler', function () { this.ProjectOptionsHandler.setSpellCheckLanguage .calledWith(this.project_id, this.languageCode) .should.equal(true) return this.EditorRealTimeController.emitToRoom .calledWith( this.project_id, 'spellCheckLanguageUpdated', this.languageCode ) .should.equal(true) }) }) describe('setPublicAccessLevel', function () { describe('when setting to private', function () { beforeEach(function () { this.newAccessLevel = 'private' this.ProjectDetailsHandler.ensureTokensArePresent = sinon .stub() .yields(null, this.tokens) return this.EditorController.setPublicAccessLevel( this.project_id, this.newAccessLevel, this.callback ) }) it('should set the access level', function () { return this.ProjectDetailsHandler.setPublicAccessLevel .calledWith(this.project_id, this.newAccessLevel) .should.equal(true) }) it('should broadcast the access level change', function () { return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:publicAccessLevel:changed') .should.equal(true) }) it('should not ensure tokens are present for project', function () { return this.ProjectDetailsHandler.ensureTokensArePresent .calledWith(this.project_id) .should.equal(false) }) it('should not broadcast a token change', function () { return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:tokens:changed', { tokens: this.tokens, }) .should.equal(false) }) }) describe('when setting to tokenBased', function () { beforeEach(function () { this.newAccessLevel = 'tokenBased' this.tokens = { readOnly: 'aaa', readAndWrite: '42bbb' } this.ProjectDetailsHandler.ensureTokensArePresent = sinon .stub() .yields(null, this.tokens) return this.EditorController.setPublicAccessLevel( this.project_id, this.newAccessLevel, this.callback ) }) it('should set the access level', function () { return this.ProjectDetailsHandler.setPublicAccessLevel .calledWith(this.project_id, this.newAccessLevel) .should.equal(true) }) it('should broadcast the access level change', function () { return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:publicAccessLevel:changed') .should.equal(true) }) it('should ensure tokens are present for project', function () { return this.ProjectDetailsHandler.ensureTokensArePresent .calledWith(this.project_id) .should.equal(true) }) it('should broadcast the token change too', function () { return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'project:tokens:changed', { tokens: this.tokens, }) .should.equal(true) }) }) }) describe('setRootDoc', function () { beforeEach(function () { this.newRootDocID = '21312321321' this.ProjectEntityUpdateHandler.setRootDoc = sinon.stub().yields() return this.EditorController.setRootDoc( this.project_id, this.newRootDocID, this.callback ) }) it('should call the ProjectEntityUpdateHandler', function () { return this.ProjectEntityUpdateHandler.setRootDoc .calledWith(this.project_id, this.newRootDocID) .should.equal(true) }) it('should emit the update to the room', function () { return this.EditorRealTimeController.emitToRoom .calledWith(this.project_id, 'rootDocUpdated', this.newRootDocID) .should.equal(true) }) }) })
overleaf/web/test/unit/src/Editor/EditorControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Editor/EditorControllerTests.js", "repo_id": "overleaf", "token_count": 12596 }
557
const { expect } = require('chai') const SandboxedModule = require('sandboxed-module') const MODULE_PATH = require('path').join( __dirname, '../../../../app/src/Features/Helpers/SafeHTMLSubstitution.js' ) describe('SafeHTMLSubstitution', function () { let SafeHTMLSubstitution before(function () { SafeHTMLSubstitution = SandboxedModule.require(MODULE_PATH) }) describe('SPLIT_REGEX', function () { const CASES = { 'PRE<0>INNER</0>POST': ['PRE', '0', 'INNER', 'POST'], '<0>INNER</0>': ['', '0', 'INNER', ''], '<0></0>': ['', '0', '', ''], '<0>INNER</0><0>INNER2</0>': ['', '0', 'INNER', '', '0', 'INNER2', ''], '<0><1>INNER</1></0>': ['', '0', '<1>INNER</1>', ''], 'PLAIN TEXT': ['PLAIN TEXT'], } Object.entries(CASES).forEach(([input, output]) => { it(`should parse "${input}" as expected`, function () { expect(input.split(SafeHTMLSubstitution.SPLIT_REGEX)).to.deep.equal( output ) }) }) }) describe('render', function () { describe('substitution', function () { it('should substitute a single component', function () { expect( SafeHTMLSubstitution.render('<0>good</0>', [{ name: 'b' }]) ).to.equal('<b>good</b>') }) it('should substitute a single component as string', function () { expect(SafeHTMLSubstitution.render('<0>good</0>', ['b'])).to.equal( '<b>good</b>' ) }) it('should substitute a single component twice', function () { expect( SafeHTMLSubstitution.render('<0>one</0><0>two</0>', [{ name: 'b' }]) ).to.equal('<b>one</b><b>two</b>') }) it('should substitute two components', function () { expect( SafeHTMLSubstitution.render('<0>one</0><1>two</1>', [ { name: 'b' }, { name: 'i' }, ]) ).to.equal('<b>one</b><i>two</i>') }) it('should substitute a single component with a class', function () { expect( SafeHTMLSubstitution.render('<0>text</0>', [ { name: 'b', attrs: { class: 'magic', }, }, ]) ).to.equal('<b class="magic">text</b>') }) it('should substitute two nested components', function () { expect( SafeHTMLSubstitution.render('<0><1>nested</1></0>', [ { name: 'b' }, { name: 'i' }, ]) ).to.equal('<b><i>nested</i></b>') }) it('should handle links', function () { expect( SafeHTMLSubstitution.render('<0>Go to Login</0>', [ { name: 'a', attrs: { href: 'https://www.overleaf.com/login' } }, ]) ).to.equal('<a href="https://www.overleaf.com/login">Go to Login</a>') }) it('should not complain about too many components', function () { expect( SafeHTMLSubstitution.render('<0>good</0>', [ { name: 'b' }, { name: 'i' }, { name: 'u' }, ]) ).to.equal('<b>good</b>') }) }) describe('pug.escape', function () { it('should handle plain text', function () { expect(SafeHTMLSubstitution.render('plain text')).to.equal('plain text') }) it('should keep a simple string delimiter', function () { expect(SafeHTMLSubstitution.render("'")).to.equal(`'`) }) it('should escape double quotes', function () { expect(SafeHTMLSubstitution.render('"')).to.equal(`&quot;`) }) it('should escape &', function () { expect(SafeHTMLSubstitution.render('&')).to.equal(`&amp;`) }) it('should escape <', function () { expect(SafeHTMLSubstitution.render('<')).to.equal(`&lt;`) }) it('should escape >', function () { expect(SafeHTMLSubstitution.render('>')).to.equal(`&gt;`) }) it('should escape html', function () { expect(SafeHTMLSubstitution.render('<b>bad</b>')).to.equal( '&lt;b&gt;bad&lt;/b&gt;' ) }) }) describe('escape around substitutions', function () { it('should escape text inside a component', function () { expect( SafeHTMLSubstitution.render('<0><i>inner</i></0>', [{ name: 'b' }]) ).to.equal('<b>&lt;i&gt;inner&lt;/i&gt;</b>') }) it('should escape text in front of a component', function () { expect( SafeHTMLSubstitution.render('<i>PRE</i><0>inner</0>', [{ name: 'b' }]) ).to.equal('&lt;i&gt;PRE&lt;/i&gt;<b>inner</b>') }) it('should escape text after of a component', function () { expect( SafeHTMLSubstitution.render('<0>inner</0><i>POST</i>', [ { name: 'b' }, ]) ).to.equal('<b>inner</b>&lt;i&gt;POST&lt;/i&gt;') }) }) }) })
overleaf/web/test/unit/src/HelperFiles/SafeHTMLSubstituteTests.js/0
{ "file_path": "overleaf/web/test/unit/src/HelperFiles/SafeHTMLSubstituteTests.js", "repo_id": "overleaf", "token_count": 2346 }
558
const SandboxedModule = require('sandboxed-module') const sinon = require('sinon') const modulePath = require('path').join( __dirname, '../../../../app/src/Features/Notifications/NotificationsController.js' ) describe('NotificationsController', function () { const userId = '123nd3ijdks' const notificationId = '123njdskj9jlk' beforeEach(function () { this.handler = { getUserNotifications: sinon.stub().callsArgWith(1), markAsRead: sinon.stub().callsArgWith(2), } this.req = { params: { notificationId, }, session: { user: { _id: userId, }, }, i18n: { translate() {}, }, } this.AuthenticationController = { getLoggedInUserId: sinon.stub().returns(this.req.session.user._id), } this.controller = SandboxedModule.require(modulePath, { requires: { './NotificationsHandler': this.handler, '../Authentication/AuthenticationController': this .AuthenticationController, }, }) }) it('should ask the handler for all unread notifications', function (done) { const allNotifications = [{ _id: notificationId, user_id: userId }] this.handler.getUserNotifications = sinon .stub() .callsArgWith(1, null, allNotifications) this.controller.getAllUnreadNotifications(this.req, { send: body => { body.should.deep.equal(allNotifications) this.handler.getUserNotifications.calledWith(userId).should.equal(true) done() }, }) }) it('should send a delete request when a delete has been received to mark a notification', function (done) { this.controller.markNotificationAsRead(this.req, { sendStatus: () => { this.handler.markAsRead .calledWith(userId, notificationId) .should.equal(true) done() }, }) }) })
overleaf/web/test/unit/src/Notifications/NotificationsControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Notifications/NotificationsControllerTests.js", "repo_id": "overleaf", "token_count": 772 }
559
const { expect } = require('chai') const sinon = require('sinon') const Errors = require('../../../../app/src/Features/Errors/Errors') const SandboxedModule = require('sandboxed-module') const { ObjectId } = require('mongodb') const MODULE_PATH = '../../../../app/src/Features/Project/ProjectEntityUpdateHandler' describe('ProjectEntityUpdateHandler', function () { const projectId = '4eecb1c1bffa66588e0000a1' const projectHistoryId = '123456' const docId = '4eecb1c1bffa66588e0000a2' const fileId = '4eecaffcbffa66588e000009' const folderId = '4eecaffcbffa66588e000008' const newFileId = '4eecaffcbffa66588e000099' const userId = 1234 beforeEach(function () { this.project = { _id: projectId, name: 'project name', overleaf: { history: { id: projectHistoryId, }, }, } this.fileUrl = 'filestore.example.com/file' this.user = { _id: new ObjectId() } this.DocModel = class Doc { constructor(options) { this.name = options.name this.lines = options.lines this._id = docId this.rev = 0 } } this.FileModel = class File { constructor(options) { this.name = options.name // use a new id for replacement files if (this.name === 'dummy-upload-filename') { this._id = newFileId } else { this._id = fileId } this.rev = 0 if (options.linkedFileData != null) { this.linkedFileData = options.linkedFileData } if (options.hash != null) { this.hash = options.hash } } } this.docName = 'doc-name' this.docLines = ['1234', 'abc'] this.doc = { _id: new ObjectId(), name: this.docName } this.fileName = 'something.jpg' this.fileSystemPath = 'somehintg' this.file = { _id: new ObjectId(), name: this.fileName, rev: 2 } this.linkedFileData = { provider: 'url' } this.source = 'editor' this.callback = sinon.stub() this.DocstoreManager = { getDoc: sinon.stub(), isDocDeleted: sinon.stub(), updateDoc: sinon.stub(), deleteDoc: sinon.stub(), } this.DocumentUpdaterHandler = { flushDocToMongo: sinon.stub().yields(), updateProjectStructure: sinon.stub().yields(), setDocument: sinon.stub(), resyncProjectHistory: sinon.stub(), deleteDoc: sinon.stub().yields(), } this.fs = { unlink: sinon.stub().yields(), } this.LockManager = { runWithLock: sinon.spy((namespace, id, runner, callback) => runner(callback) ), } this.ProjectModel = { updateOne: sinon.stub(), } this.ProjectGetter = { getProject: sinon.stub(), getProjectWithoutDocLines: sinon.stub(), } this.ProjectLocator = { findElement: sinon.stub(), findElementByPath: sinon.stub(), } this.ProjectUpdater = { markAsUpdated: sinon.stub(), } this.ProjectEntityHandler = { getDocPathByProjectIdAndDocId: sinon.stub(), getAllEntitiesFromProject: sinon.stub(), } this.ProjectEntityMongoUpdateHandler = { addDoc: sinon.stub(), addFile: sinon.stub(), addFolder: sinon.stub(), _confirmFolder: sinon.stub(), _putElement: sinon.stub(), _insertDeletedFileReference: sinon.stub(), replaceFileWithNew: sinon.stub(), mkdirp: sinon.stub(), moveEntity: sinon.stub(), renameEntity: sinon.stub(), deleteEntity: sinon.stub(), replaceDocWithFile: sinon.stub(), replaceFileWithDoc: sinon.stub(), } this.TpdsUpdateSender = { addFile: sinon.stub().yields(), addDoc: sinon.stub(), deleteEntity: sinon.stub().yields(), moveEntity: sinon.stub(), promises: { moveEntity: sinon.stub().resolves(), }, } this.FileStoreHandler = { copyFile: sinon.stub(), uploadFileFromDisk: sinon.stub(), deleteFile: sinon.stub(), } this.FileWriter = { writeLinesToDisk: sinon.stub(), } this.EditorRealTimeController = { emitToRoom: sinon.stub(), } this.ProjectEntityUpdateHandler = SandboxedModule.require(MODULE_PATH, { requires: { '@overleaf/settings': { validRootDocExtensions: ['tex'] }, fs: this.fs, '../../models/Doc': { Doc: this.DocModel }, '../Docstore/DocstoreManager': this.DocstoreManager, '../../Features/DocumentUpdater/DocumentUpdaterHandler': this .DocumentUpdaterHandler, '../../models/File': { File: this.FileModel }, '../FileStore/FileStoreHandler': this.FileStoreHandler, '../../infrastructure/LockManager': this.LockManager, '../../models/Project': { Project: this.ProjectModel }, './ProjectGetter': this.ProjectGetter, './ProjectLocator': this.ProjectLocator, './ProjectUpdateHandler': this.ProjectUpdater, './ProjectEntityHandler': this.ProjectEntityHandler, './ProjectEntityMongoUpdateHandler': this .ProjectEntityMongoUpdateHandler, '../ThirdPartyDataStore/TpdsUpdateSender': this.TpdsUpdateSender, '../Editor/EditorRealTimeController': this.EditorRealTimeController, '../../infrastructure/FileWriter': this.FileWriter, }, }) }) describe('updateDocLines', function () { beforeEach(function () { this.path = '/somewhere/something.tex' this.doc = { _id: docId, } this.version = 42 this.ranges = { mock: 'ranges' } this.lastUpdatedAt = new Date().getTime() this.lastUpdatedBy = 'fake-last-updater-id' this.DocstoreManager.isDocDeleted.yields(null, false) this.ProjectGetter.getProject.yields(null, this.project) this.ProjectLocator.findElement.yields(null, this.doc, { fileSystem: this.path, }) this.TpdsUpdateSender.addDoc.yields() }) describe('when the doc has been modified', function () { beforeEach(function () { this.DocstoreManager.updateDoc.yields(null, true, (this.rev = 5)) this.ProjectEntityUpdateHandler.updateDocLines( projectId, docId, this.docLines, this.version, this.ranges, this.lastUpdatedAt, this.lastUpdatedBy, this.callback ) }) it('should get the project with very few fields', function () { this.ProjectGetter.getProject .calledWith(projectId, { name: true, rootFolder: true, }) .should.equal(true) }) it('should find the doc', function () { this.ProjectLocator.findElement .calledWith({ project: this.project, type: 'docs', element_id: docId, }) .should.equal(true) }) it('should update the doc in the docstore', function () { this.DocstoreManager.updateDoc .calledWith( projectId, docId, this.docLines, this.version, this.ranges ) .should.equal(true) }) it('should mark the project as updated', function () { sinon.assert.calledWith( this.ProjectUpdater.markAsUpdated, projectId, this.lastUpdatedAt, this.lastUpdatedBy ) }) it('should send the doc the to the TPDS', function () { this.TpdsUpdateSender.addDoc .calledWith({ project_id: projectId, project_name: this.project.name, doc_id: docId, rev: this.rev, path: this.path, }) .should.equal(true) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('when the doc has not been modified', function () { beforeEach(function () { this.DocstoreManager.updateDoc.yields(null, false, (this.rev = 5)) this.ProjectEntityUpdateHandler.updateDocLines( projectId, docId, this.docLines, this.version, this.ranges, this.lastUpdatedAt, this.lastUpdatedBy, this.callback ) }) it('should not mark the project as updated', function () { this.ProjectUpdater.markAsUpdated.called.should.equal(false) }) it('should not send the doc the to the TPDS', function () { this.TpdsUpdateSender.addDoc.called.should.equal(false) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('when the doc has been deleted', function () { beforeEach(function () { this.ProjectGetter.getProject.yields(null, this.project) this.ProjectLocator.findElement.yields(new Errors.NotFoundError()) this.DocstoreManager.isDocDeleted.yields(null, true) this.DocstoreManager.updateDoc.yields() this.ProjectEntityUpdateHandler.updateDocLines( projectId, docId, this.docLines, this.version, this.ranges, this.lastUpdatedAt, this.lastUpdatedBy, this.callback ) }) it('should update the doc in the docstore', function () { this.DocstoreManager.updateDoc .calledWith( projectId, docId, this.docLines, this.version, this.ranges ) .should.equal(true) }) it('should not mark the project as updated', function () { this.ProjectUpdater.markAsUpdated.called.should.equal(false) }) it('should not send the doc the to the TPDS', function () { this.TpdsUpdateSender.addDoc.called.should.equal(false) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('when projects and docs collection are de-synced', function () { beforeEach(function () { this.ProjectGetter.getProject.yields(null, this.project) // The doc is not in the file-tree, but also not marked as deleted. // This should not happen, but web should handle it. this.ProjectLocator.findElement.yields(new Errors.NotFoundError()) this.DocstoreManager.isDocDeleted.yields(null, false) this.DocstoreManager.updateDoc.yields() this.ProjectEntityUpdateHandler.updateDocLines( projectId, docId, this.docLines, this.version, this.ranges, this.lastUpdatedAt, this.lastUpdatedBy, this.callback ) }) it('should update the doc in the docstore', function () { this.DocstoreManager.updateDoc .calledWith( projectId, docId, this.docLines, this.version, this.ranges ) .should.equal(true) }) it('should not mark the project as updated', function () { this.ProjectUpdater.markAsUpdated.called.should.equal(false) }) it('should not send the doc the to the TPDS', function () { this.TpdsUpdateSender.addDoc.called.should.equal(false) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('when the doc is not related to the project', function () { beforeEach(function () { this.ProjectGetter.getProject.yields(null, this.project) this.ProjectLocator.findElement.yields(new Errors.NotFoundError()) this.DocstoreManager.isDocDeleted.yields(new Errors.NotFoundError()) this.ProjectEntityUpdateHandler.updateDocLines( projectId, docId, this.docLines, this.version, this.ranges, this.lastUpdatedAt, this.lastUpdatedBy, this.callback ) }) it('should return a not found error', function () { this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) it('should not update the doc', function () { this.DocstoreManager.updateDoc.called.should.equal(false) }) it('should not send the doc the to the TPDS', function () { this.TpdsUpdateSender.addDoc.called.should.equal(false) }) }) describe('when the project is not found', function () { beforeEach(function () { this.ProjectGetter.getProject.yields(new Errors.NotFoundError()) this.ProjectEntityUpdateHandler.updateDocLines( projectId, docId, this.docLines, this.version, this.ranges, this.lastUpdatedAt, this.lastUpdatedBy, this.callback ) }) it('should return a not found error', function () { this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) it('should not update the doc', function () { this.DocstoreManager.updateDoc.called.should.equal(false) }) it('should not send the doc the to the TPDS', function () { this.TpdsUpdateSender.addDoc.called.should.equal(false) }) }) }) describe('setRootDoc', function () { beforeEach(function () { this.rootDocId = 'root-doc-id-123123' }) it('should call Project.updateOne when the doc exists and has a valid extension', function () { this.ProjectEntityHandler.getDocPathByProjectIdAndDocId.yields( null, `/main.tex` ) this.ProjectEntityUpdateHandler.setRootDoc( projectId, this.rootDocId, () => {} ) this.ProjectModel.updateOne .calledWith({ _id: projectId }, { rootDoc_id: this.rootDocId }) .should.equal(true) }) it("should not call Project.updateOne when the doc doesn't exist", function () { this.ProjectEntityHandler.getDocPathByProjectIdAndDocId.yields( Errors.NotFoundError ) this.ProjectEntityUpdateHandler.setRootDoc( projectId, this.rootDocId, () => {} ) this.ProjectModel.updateOne .calledWith({ _id: projectId }, { rootDoc_id: this.rootDocId }) .should.equal(false) }) it('should call the callback with an UnsupportedFileTypeError when the doc has an unaccepted file extension', function () { this.ProjectEntityHandler.getDocPathByProjectIdAndDocId.yields( null, `/foo/bar.baz` ) this.ProjectEntityUpdateHandler.setRootDoc( projectId, this.rootDocId, this.callback ) expect(this.callback.firstCall.args[0]).to.be.an.instanceof( Errors.UnsupportedFileTypeError ) }) }) describe('unsetRootDoc', function () { it('should call Project.updateOne', function () { this.ProjectEntityUpdateHandler.unsetRootDoc(projectId) this.ProjectModel.updateOne .calledWith({ _id: projectId }, { $unset: { rootDoc_id: true } }) .should.equal(true) }) }) describe('addDoc', function () { describe('adding a doc', function () { beforeEach(function () { this.path = '/path/to/doc' this.newDoc = new this.DocModel({ name: this.docName, lines: undefined, _id: docId, rev: 0, }) this.DocstoreManager.updateDoc.yields(null, false, (this.rev = 5)) this.TpdsUpdateSender.addDoc.yields() this.ProjectEntityMongoUpdateHandler.addDoc.yields( null, { path: { fileSystem: this.path } }, this.project ) this.ProjectEntityUpdateHandler.addDoc( projectId, docId, this.docName, this.docLines, userId, this.callback ) }) it('creates the doc without history', function () { this.DocstoreManager.updateDoc .calledWith(projectId, docId, this.docLines, 0, {}) .should.equal(true) }) it('sends the change in project structure to the doc updater', function () { const newDocs = [ { doc: this.newDoc, path: this.path, docLines: this.docLines.join('\n'), }, ] this.DocumentUpdaterHandler.updateProjectStructure .calledWith(projectId, projectHistoryId, userId, { newDocs, newProject: this.project, }) .should.equal(true) }) }) describe('adding a doc with an invalid name', function () { beforeEach(function () { this.path = '/path/to/doc' this.newDoc = { _id: docId } this.ProjectEntityUpdateHandler.addDoc( projectId, folderId, `*${this.docName}`, this.docLines, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) }) describe('addFile', function () { describe('adding a file', function () { beforeEach(function () { this.path = '/path/to/file' this.newFile = { _id: fileId, rev: 0, name: this.fileName, linkedFileData: this.linkedFileData, } this.FileStoreHandler.uploadFileFromDisk.yields( null, this.fileUrl, this.newFile ) this.TpdsUpdateSender.addFile.yields() this.ProjectEntityMongoUpdateHandler.addFile.yields( null, { path: { fileSystem: this.path } }, this.project ) this.ProjectEntityUpdateHandler.addFile( projectId, folderId, this.fileName, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('updates the file in the filestore', function () { this.FileStoreHandler.uploadFileFromDisk .calledWith( projectId, { name: this.fileName, linkedFileData: this.linkedFileData }, this.fileSystemPath ) .should.equal(true) }) it('updates the file in mongo', function () { const fileMatcher = sinon.match(file => { return file.name === this.fileName }) this.ProjectEntityMongoUpdateHandler.addFile .calledWithMatch(projectId, folderId, fileMatcher) .should.equal(true) }) it('notifies the tpds', function () { this.TpdsUpdateSender.addFile .calledWith({ project_id: projectId, project_name: this.project.name, file_id: fileId, rev: 0, path: this.path, }) .should.equal(true) }) it('should mark the project as updated', function () { const args = this.ProjectUpdater.markAsUpdated.args[0] args[0].should.equal(projectId) args[1].should.exist args[2].should.equal(userId) }) it('sends the change in project structure to the doc updater', function () { const newFiles = [ { file: this.newFile, path: this.path, url: this.fileUrl, }, ] this.DocumentUpdaterHandler.updateProjectStructure .calledWith(projectId, projectHistoryId, userId, { newFiles, newProject: this.project, }) .should.equal(true) }) }) describe('adding a file with an invalid name', function () { beforeEach(function () { this.path = '/path/to/file' this.newFile = { _id: fileId, rev: 0, name: this.fileName, linkedFileData: this.linkedFileData, } this.TpdsUpdateSender.addFile.yields() this.ProjectEntityMongoUpdateHandler.addFile.yields( null, { path: { fileSystem: this.path } }, this.project ) this.ProjectEntityUpdateHandler.addFile( projectId, folderId, `*${this.fileName}`, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) }) describe('replaceFile', function () { beforeEach(function () { // replacement file now creates a new file object this.newFileUrl = 'new-file-url' this.newFile = { _id: newFileId, name: 'dummy-upload-filename', rev: 0, linkedFileData: this.linkedFileData, } this.oldFile = { _id: fileId, rev: 3 } this.path = '/path/to/file' this.newProject = 'new project' this.FileStoreHandler.uploadFileFromDisk.yields( null, this.newFileUrl, this.newFile ) this.ProjectEntityMongoUpdateHandler._insertDeletedFileReference.yields() this.ProjectEntityMongoUpdateHandler.replaceFileWithNew.yields( null, this.oldFile, this.project, { fileSystem: this.path }, this.newProject ) this.ProjectEntityUpdateHandler.replaceFile( projectId, fileId, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('uploads a new version of the file', function () { this.FileStoreHandler.uploadFileFromDisk .calledWith( projectId, { name: 'dummy-upload-filename', linkedFileData: this.linkedFileData, }, this.fileSystemPath ) .should.equal(true) }) it('replaces the file in mongo', function () { this.ProjectEntityMongoUpdateHandler.replaceFileWithNew .calledWith(projectId, fileId, this.newFile) .should.equal(true) }) it('notifies the tpds', function () { this.TpdsUpdateSender.addFile .calledWith({ project_id: projectId, project_name: this.project.name, file_id: newFileId, rev: this.oldFile.rev + 1, path: this.path, }) .should.equal(true) }) it('should mark the project as updated', function () { const args = this.ProjectUpdater.markAsUpdated.args[0] args[0].should.equal(projectId) args[1].should.exist args[2].should.equal(userId) }) it('updates the project structure in the doc updater', function () { const oldFiles = [ { file: this.oldFile, path: this.path, }, ] const newFiles = [ { file: this.newFile, path: this.path, url: this.newFileUrl, }, ] this.DocumentUpdaterHandler.updateProjectStructure .calledWith(projectId, projectHistoryId, userId, { oldFiles, newFiles, newProject: this.newProject, }) .should.equal(true) }) }) describe('upsertDoc', function () { describe('upserting into an invalid folder', function () { beforeEach(function () { this.ProjectLocator.findElement.yields() this.ProjectEntityUpdateHandler.upsertDoc( projectId, folderId, this.docName, this.docLines, this.source, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Error) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) describe('updating an existing doc', function () { beforeEach(function () { this.existingDoc = { _id: docId, name: this.docName } this.existingFile = { _id: fileId, name: this.fileName } this.folder = { _id: folderId, docs: [this.existingDoc], fileRefs: [this.existingFile], } this.ProjectLocator.findElement.yields(null, this.folder) this.DocumentUpdaterHandler.setDocument.yields() this.ProjectEntityUpdateHandler.upsertDoc( projectId, folderId, this.docName, this.docLines, this.source, userId, this.callback ) }) it('tries to find the folder', function () { this.ProjectLocator.findElement .calledWith({ project_id: projectId, element_id: folderId, type: 'folder', }) .should.equal(true) }) it('updates the doc contents', function () { this.DocumentUpdaterHandler.setDocument .calledWith( projectId, this.existingDoc._id, userId, this.docLines, this.source ) .should.equal(true) }) it('flushes the doc contents', function () { this.DocumentUpdaterHandler.flushDocToMongo .calledWith(projectId, this.existingDoc._id) .should.equal(true) }) it('returns the doc', function () { this.callback.calledWith(null, this.existingDoc, false) }) }) describe('creating a new doc', function () { beforeEach(function () { this.folder = { _id: folderId, docs: [], fileRefs: [] } this.newDoc = { _id: docId } this.ProjectLocator.findElement.yields(null, this.folder) this.ProjectEntityUpdateHandler.addDocWithRanges = { withoutLock: sinon.stub().yields(null, this.newDoc), } this.ProjectEntityUpdateHandler.upsertDoc( projectId, folderId, this.docName, this.docLines, this.source, userId, this.callback ) }) it('tries to find the folder', function () { this.ProjectLocator.findElement .calledWith({ project_id: projectId, element_id: folderId, type: 'folder', }) .should.equal(true) }) it('adds the doc', function () { this.ProjectEntityUpdateHandler.addDocWithRanges.withoutLock .calledWith( projectId, folderId, this.docName, this.docLines, {}, userId ) .should.equal(true) }) it('returns the doc', function () { this.callback.calledWith(null, this.newDoc, true) }) }) describe('upserting a new doc with an invalid name', function () { beforeEach(function () { this.folder = { _id: folderId, docs: [], fileRefs: [] } this.newDoc = { _id: docId } this.ProjectLocator.findElement.yields(null, this.folder) this.ProjectEntityUpdateHandler.addDocWithRanges = { withoutLock: sinon.stub().yields(null, this.newDoc), } this.ProjectEntityUpdateHandler.upsertDoc( projectId, folderId, `*${this.docName}`, this.docLines, this.source, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) describe('upserting a doc on top of a file', function () { beforeEach(function () { this.newProject = { name: 'new project', overleaf: { history: { id: projectHistoryId } }, } this.existingFile = { _id: fileId, name: 'foo.tex', rev: 12 } this.folder = { _id: folderId, docs: [], fileRefs: [this.existingFile] } this.newDoc = { _id: docId } this.docLines = ['line one', 'line two'] this.folderPath = '/path/to/folder' this.filePath = '/path/to/folder/foo.tex' this.ProjectLocator.findElement .withArgs({ project_id: projectId, element_id: this.folder._id, type: 'folder', }) .yields(null, this.folder, { fileSystem: this.folderPath, }) this.DocstoreManager.updateDoc.yields() this.ProjectEntityMongoUpdateHandler.replaceFileWithDoc.yields( null, this.newProject ) this.TpdsUpdateSender.addDoc.yields() this.ProjectEntityUpdateHandler.upsertDoc( projectId, folderId, 'foo.tex', this.docLines, this.source, userId, this.callback ) }) it('notifies docstore of the new doc', function () { expect(this.DocstoreManager.updateDoc).to.have.been.calledWith( projectId, this.newDoc._id, this.docLines ) }) it('adds the new doc and removes the file in one go', function () { expect( this.ProjectEntityMongoUpdateHandler.replaceFileWithDoc ).to.have.been.calledWithMatch( projectId, this.existingFile._id, this.newDoc ) }) it('sends the doc to TPDS', function () { expect(this.TpdsUpdateSender.addDoc).to.have.been.calledWith({ project_id: projectId, doc_id: this.newDoc._id, path: this.filePath, project_name: this.newProject.name, rev: this.existingFile.rev + 1, }) }) it('sends the updates to the doc updater', function () { const oldFiles = [ { file: this.existingFile, path: this.filePath, }, ] const newDocs = [ { doc: sinon.match(this.newDoc), path: this.filePath, docLines: this.docLines.join('\n'), }, ] expect( this.DocumentUpdaterHandler.updateProjectStructure ).to.have.been.calledWith(projectId, projectHistoryId, userId, { oldFiles, newDocs, newProject: this.newProject, }) }) it('should notify everyone of the file deletion', function () { expect( this.EditorRealTimeController.emitToRoom ).to.have.been.calledWith( projectId, 'removeEntity', this.existingFile._id, 'convertFileToDoc' ) }) }) }) describe('upsertFile', function () { beforeEach(function () { this.FileStoreHandler.uploadFileFromDisk.yields( null, this.fileUrl, this.newFile ) }) describe('upserting into an invalid folder', function () { beforeEach(function () { this.ProjectLocator.findElement.yields() this.ProjectEntityUpdateHandler.upsertFile( projectId, folderId, this.fileName, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Error) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) describe('updating an existing file', function () { beforeEach(function () { this.existingFile = { _id: fileId, name: this.fileName } this.folder = { _id: folderId, fileRefs: [this.existingFile], docs: [] } this.ProjectLocator.findElement.yields(null, this.folder) this.ProjectEntityUpdateHandler.replaceFile = { mainTask: sinon.stub().yields(null, this.newFile), } this.ProjectEntityUpdateHandler.upsertFile( projectId, folderId, this.fileName, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('replaces the file', function () { expect( this.ProjectEntityUpdateHandler.replaceFile.mainTask ).to.be.calledWith( projectId, fileId, this.fileSystemPath, this.linkedFileData, userId ) }) it('returns the file', function () { this.callback.calledWith(null, this.existingFile, false) }) }) describe('creating a new file', function () { beforeEach(function () { this.folder = { _id: folderId, fileRefs: [], docs: [] } this.newFile = { _id: fileId } this.ProjectLocator.findElement.yields(null, this.folder) this.ProjectEntityUpdateHandler.addFile = { mainTask: sinon.stub().yields(null, this.newFile), } this.ProjectEntityUpdateHandler.upsertFile( projectId, folderId, this.fileName, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('tries to find the folder', function () { this.ProjectLocator.findElement .calledWith({ project_id: projectId, element_id: folderId, type: 'folder', }) .should.equal(true) }) it('adds the file', function () { this.ProjectEntityUpdateHandler.addFile.mainTask .calledWith( projectId, folderId, this.fileName, this.fileSystemPath, this.linkedFileData, userId ) .should.equal(true) }) it('returns the file', function () { this.callback.calledWith(null, this.newFile, true) }) }) describe('upserting a new file with an invalid name', function () { beforeEach(function () { this.folder = { _id: folderId, fileRefs: [] } this.newFile = { _id: fileId } this.ProjectLocator.findElement.yields(null, this.folder) this.ProjectEntityUpdateHandler.addFile = { mainTask: sinon.stub().yields(null, this.newFile), } this.ProjectEntityUpdateHandler.upsertFile( projectId, folderId, `*${this.fileName}`, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) describe('upserting file on top of a doc', function () { beforeEach(function (done) { this.path = '/path/to/doc' this.existingDoc = { _id: new ObjectId(), name: this.fileName } this.folder = { _id: folderId, fileRefs: [], docs: [this.existingDoc], } this.ProjectLocator.findElement .withArgs({ project_id: this.project._id.toString(), element_id: folderId, type: 'folder', }) .yields(null, this.folder) this.ProjectLocator.findElement .withArgs({ project_id: this.project._id.toString(), element_id: this.existingDoc._id, type: 'doc', }) .yields(null, this.existingDoc, { fileSystem: this.path }) this.newFileUrl = 'new-file-url' this.newFile = { _id: newFileId, name: 'dummy-upload-filename', rev: 0, linkedFileData: this.linkedFileData, } this.newProject = { name: 'new project', overleaf: { history: { id: projectHistoryId } }, } this.FileStoreHandler.uploadFileFromDisk.yields( null, this.newFileUrl, this.newFile ) this.ProjectEntityMongoUpdateHandler.replaceDocWithFile.yields( null, this.newProject ) this.ProjectEntityUpdateHandler.upsertFile( projectId, folderId, this.fileName, this.fileSystemPath, this.linkedFileData, userId, done ) }) it('replaces the existing doc with a file', function () { expect( this.ProjectEntityMongoUpdateHandler.replaceDocWithFile ).to.have.been.calledWith(projectId, this.existingDoc._id, this.newFile) }) it('updates the doc structure', function () { const oldDocs = [ { doc: this.existingDoc, path: this.path, }, ] const newFiles = [ { file: this.newFile, path: this.path, url: this.newFileUrl, }, ] const updates = { oldDocs, newFiles, newProject: this.newProject, } expect( this.DocumentUpdaterHandler.updateProjectStructure ).to.have.been.calledWith(projectId, projectHistoryId, userId, updates) }) it('tells everyone in the room the doc is removed', function () { expect( this.EditorRealTimeController.emitToRoom ).to.have.been.calledWith( projectId, 'removeEntity', this.existingDoc._id, 'convertDocToFile' ) }) }) }) describe('upsertDocWithPath', function () { describe('upserting a doc', function () { beforeEach(function () { this.path = '/folder/doc.tex' this.newFolders = ['mock-a', 'mock-b'] this.folder = { _id: folderId } this.doc = { _id: docId } this.isNewDoc = true this.ProjectEntityUpdateHandler.mkdirp = { withoutLock: sinon.stub().yields(null, this.newFolders, this.folder), } this.ProjectEntityUpdateHandler.upsertDoc = { withoutLock: sinon.stub().yields(null, this.doc, this.isNewDoc), } this.ProjectEntityUpdateHandler.upsertDocWithPath( projectId, this.path, this.docLines, this.source, userId, this.callback ) }) it('creates any necessary folders', function () { this.ProjectEntityUpdateHandler.mkdirp.withoutLock .calledWith(projectId, '/folder') .should.equal(true) }) it('upserts the doc', function () { this.ProjectEntityUpdateHandler.upsertDoc.withoutLock .calledWith( projectId, this.folder._id, 'doc.tex', this.docLines, this.source, userId ) .should.equal(true) }) it('calls the callback', function () { this.callback .calledWith( null, this.doc, this.isNewDoc, this.newFolders, this.folder ) .should.equal(true) }) }) describe('upserting a doc with an invalid path', function () { beforeEach(function () { this.path = '/*folder/doc.tex' this.newFolders = ['mock-a', 'mock-b'] this.folder = { _id: folderId } this.doc = { _id: docId } this.isNewDoc = true this.ProjectEntityUpdateHandler.mkdirp = { withoutLock: sinon.stub().yields(null, this.newFolders, this.folder), } this.ProjectEntityUpdateHandler.upsertDoc = { withoutLock: sinon.stub().yields(null, this.doc, this.isNewDoc), } this.ProjectEntityUpdateHandler.upsertDocWithPath( projectId, this.path, this.docLines, this.source, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) describe('upserting a doc with an invalid name', function () { beforeEach(function () { this.path = '/folder/*doc.tex' this.newFolders = ['mock-a', 'mock-b'] this.folder = { _id: folderId } this.doc = { _id: docId } this.isNewDoc = true this.ProjectEntityUpdateHandler.mkdirp = { withoutLock: sinon.stub().yields(null, this.newFolders, this.folder), } this.ProjectEntityUpdateHandler.upsertDoc = { withoutLock: sinon.stub().yields(null, this.doc, this.isNewDoc), } this.ProjectEntityUpdateHandler.upsertDocWithPath( projectId, this.path, this.docLines, this.source, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) }) describe('upsertFileWithPath', function () { describe('upserting a file', function () { beforeEach(function () { this.path = '/folder/file.png' this.newFolders = ['mock-a', 'mock-b'] this.folder = { _id: folderId } this.file = { _id: fileId } this.isNewFile = true this.FileStoreHandler.uploadFileFromDisk.yields( null, this.fileUrl, this.newFile ) this.ProjectEntityUpdateHandler.mkdirp = { withoutLock: sinon.stub().yields(null, this.newFolders, this.folder), } this.ProjectEntityUpdateHandler.upsertFile = { mainTask: sinon.stub().yields(null, this.file, this.isNewFile), } this.ProjectEntityUpdateHandler.upsertFileWithPath( projectId, this.path, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('creates any necessary folders', function () { this.ProjectEntityUpdateHandler.mkdirp.withoutLock .calledWith(projectId, '/folder') .should.equal(true) }) it('upserts the file', function () { this.ProjectEntityUpdateHandler.upsertFile.mainTask .calledWith( projectId, this.folder._id, 'file.png', this.fileSystemPath, this.linkedFileData, userId ) .should.equal(true) }) it('calls the callback', function () { this.callback .calledWith( null, this.file, this.isNewFile, undefined, this.newFolders, this.folder ) .should.equal(true) }) }) describe('upserting a file with an invalid path', function () { beforeEach(function () { this.path = '/*folder/file.png' this.newFolders = ['mock-a', 'mock-b'] this.folder = { _id: folderId } this.file = { _id: fileId } this.isNewFile = true this.ProjectEntityUpdateHandler.mkdirp = { withoutLock: sinon.stub().yields(null, this.newFolders, this.folder), } this.ProjectEntityUpdateHandler.upsertFile = { mainTask: sinon.stub().yields(null, this.file, this.isNewFile), } this.ProjectEntityUpdateHandler.upsertFileWithPath( projectId, this.path, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) describe('upserting a file with an invalid name', function () { beforeEach(function () { this.path = '/folder/*file.png' this.newFolders = ['mock-a', 'mock-b'] this.folder = { _id: folderId } this.file = { _id: fileId } this.isNewFile = true this.ProjectEntityUpdateHandler.mkdirp = { withoutLock: sinon.stub().yields(null, this.newFolders, this.folder), } this.ProjectEntityUpdateHandler.upsertFile = { mainTask: sinon.stub().yields(null, this.file, this.isNewFile), } this.ProjectEntityUpdateHandler.upsertFileWithPath( projectId, this.path, this.fileSystemPath, this.linkedFileData, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) }) describe('deleteEntity', function () { beforeEach(function () { this.path = '/path/to/doc.tex' this.doc = { _id: docId } this.projectBeforeDeletion = { _id: projectId, name: 'project' } this.newProject = 'new-project' this.ProjectEntityMongoUpdateHandler.deleteEntity.yields( null, this.doc, { fileSystem: this.path }, this.projectBeforeDeletion, this.newProject ) this.ProjectEntityUpdateHandler._cleanUpEntity = sinon.stub().yields() this.ProjectEntityUpdateHandler.deleteEntity( projectId, docId, 'doc', userId, this.callback ) }) it('deletes the entity in mongo', function () { this.ProjectEntityMongoUpdateHandler.deleteEntity .calledWith(projectId, docId, 'doc') .should.equal(true) }) it('cleans up the doc in the docstore', function () { this.ProjectEntityUpdateHandler._cleanUpEntity .calledWith( this.projectBeforeDeletion, this.newProject, this.doc, 'doc', this.path, userId ) .should.equal(true) }) it('it notifies the tpds', function () { this.TpdsUpdateSender.deleteEntity .calledWith({ project_id: projectId, path: this.path, project_name: this.projectBeforeDeletion.name, }) .should.equal(true) }) it('retuns the entity_id', function () { this.callback.calledWith(null, docId).should.equal(true) }) }) describe('deleteEntityWithPath', function () { describe('when the entity exists', function () { beforeEach(function () { this.doc = { _id: docId } this.ProjectLocator.findElementByPath.yields(null, this.doc, 'doc') this.ProjectEntityUpdateHandler.deleteEntity = { withoutLock: sinon.stub().yields(), } this.path = '/path/to/doc.tex' this.ProjectEntityUpdateHandler.deleteEntityWithPath( projectId, this.path, userId, this.callback ) }) it('finds the entity', function () { this.ProjectLocator.findElementByPath .calledWith({ project_id: projectId, path: this.path }) .should.equal(true) }) it('deletes the entity', function () { this.ProjectEntityUpdateHandler.deleteEntity.withoutLock .calledWith(projectId, this.doc._id, 'doc', userId, this.callback) .should.equal(true) }) }) describe('when the entity does not exist', function () { beforeEach(function () { this.ProjectLocator.findElementByPath.yields() this.path = '/doc.tex' this.ProjectEntityUpdateHandler.deleteEntityWithPath( projectId, this.path, userId, this.callback ) }) it('returns an error', function () { this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) }) }) describe('mkdirp', function () { beforeEach(function () { this.docPath = '/folder/doc.tex' this.ProjectEntityMongoUpdateHandler.mkdirp.yields() this.ProjectEntityUpdateHandler.mkdirp( projectId, this.docPath, this.callback ) }) it('calls ProjectEntityMongoUpdateHandler', function () { this.ProjectEntityMongoUpdateHandler.mkdirp .calledWith(projectId, this.docPath) .should.equal(true) }) }) describe('mkdirpWithExactCase', function () { beforeEach(function () { this.docPath = '/folder/doc.tex' this.ProjectEntityMongoUpdateHandler.mkdirp.yields() this.ProjectEntityUpdateHandler.mkdirpWithExactCase( projectId, this.docPath, this.callback ) }) it('calls ProjectEntityMongoUpdateHandler', function () { this.ProjectEntityMongoUpdateHandler.mkdirp .calledWith(projectId, this.docPath, { exactCaseMatch: true }) .should.equal(true) }) }) describe('addFolder', function () { describe('adding a folder', function () { beforeEach(function () { this.parentFolderId = '123asdf' this.folderName = 'new-folder' this.ProjectEntityMongoUpdateHandler.addFolder.yields() this.ProjectEntityUpdateHandler.addFolder( projectId, this.parentFolderId, this.folderName, this.callback ) }) it('calls ProjectEntityMongoUpdateHandler', function () { this.ProjectEntityMongoUpdateHandler.addFolder .calledWith(projectId, this.parentFolderId, this.folderName) .should.equal(true) }) }) describe('adding a folder with an invalid name', function () { beforeEach(function () { this.parentFolderId = '123asdf' this.folderName = '*new-folder' this.ProjectEntityMongoUpdateHandler.addFolder.yields() this.ProjectEntityUpdateHandler.addFolder( projectId, this.parentFolderId, this.folderName, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) }) describe('moveEntity', function () { beforeEach(function () { this.project_name = 'project name' this.startPath = '/a.tex' this.endPath = '/folder/b.tex' this.rev = 2 this.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] } this.ProjectEntityMongoUpdateHandler.moveEntity.yields( null, this.project, this.startPath, this.endPath, this.rev, this.changes ) this.ProjectEntityUpdateHandler.moveEntity( projectId, docId, folderId, 'doc', userId, this.callback ) }) it('moves the entity in mongo', function () { this.ProjectEntityMongoUpdateHandler.moveEntity .calledWith(projectId, docId, folderId, 'doc') .should.equal(true) }) it('notifies tpds', function () { this.TpdsUpdateSender.promises.moveEntity .calledWith({ project_id: projectId, project_name: this.project_name, startPath: this.startPath, endPath: this.endPath, rev: this.rev, }) .should.equal(true) }) it('sends the changes in project structure to the doc updater', function () { this.DocumentUpdaterHandler.updateProjectStructure .calledWith( projectId, projectHistoryId, userId, this.changes, this.callback ) .should.equal(true) }) }) describe('renameEntity', function () { describe('renaming an entity', function () { beforeEach(function () { this.project_name = 'project name' this.startPath = '/folder/a.tex' this.endPath = '/folder/b.tex' this.rev = 2 this.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] } this.newDocName = 'b.tex' this.ProjectEntityMongoUpdateHandler.renameEntity.yields( null, this.project, this.startPath, this.endPath, this.rev, this.changes ) this.ProjectEntityUpdateHandler.renameEntity( projectId, docId, 'doc', this.newDocName, userId, this.callback ) }) it('moves the entity in mongo', function () { this.ProjectEntityMongoUpdateHandler.renameEntity .calledWith(projectId, docId, 'doc', this.newDocName) .should.equal(true) }) it('notifies tpds', function () { this.TpdsUpdateSender.promises.moveEntity .calledWith({ project_id: projectId, project_name: this.project_name, startPath: this.startPath, endPath: this.endPath, rev: this.rev, }) .should.equal(true) }) it('sends the changes in project structure to the doc updater', function () { this.DocumentUpdaterHandler.updateProjectStructure .calledWith( projectId, projectHistoryId, userId, this.changes, this.callback ) .should.equal(true) }) }) describe('renaming an entity to an invalid name', function () { beforeEach(function () { this.project_name = 'project name' this.startPath = '/folder/a.tex' this.endPath = '/folder/b.tex' this.rev = 2 this.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] } this.newDocName = '*b.tex' this.ProjectEntityMongoUpdateHandler.renameEntity.yields( null, this.project, this.startPath, this.endPath, this.rev, this.changes ) this.ProjectEntityUpdateHandler.renameEntity( projectId, docId, 'doc', this.newDocName, userId, this.callback ) }) it('returns an error', function () { const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError) this.callback.calledWithMatch(errorMatcher).should.equal(true) }) }) }) describe('resyncProjectHistory', function () { describe('a deleted project', function () { beforeEach(function () { this.ProjectGetter.getProject.yields() this.ProjectEntityUpdateHandler.resyncProjectHistory( projectId, this.callback ) }) it('should return an error', function () { expect(this.callback).to.have.been.calledWith( sinon.match .instanceOf(Errors.ProjectHistoryDisabledError) .and( sinon.match.has( 'message', `project history not enabled for ${projectId}` ) ) ) }) }) describe('a project without project-history enabled', function () { beforeEach(function () { this.project.overleaf = {} this.ProjectGetter.getProject.yields(null, this.project) this.ProjectEntityUpdateHandler.resyncProjectHistory( projectId, this.callback ) }) it('should return an error', function () { expect(this.callback).to.have.been.calledWith( sinon.match .instanceOf(Errors.ProjectHistoryDisabledError) .and( sinon.match.has( 'message', `project history not enabled for ${projectId}` ) ) ) }) }) describe('a project with project-history enabled', function () { beforeEach(function () { this.ProjectGetter.getProject.yields(null, this.project) const docs = [ { doc: { _id: docId, }, path: 'main.tex', }, ] const files = [ { file: { _id: fileId, }, path: 'universe.png', }, ] this.ProjectEntityHandler.getAllEntitiesFromProject.yields( null, docs, files ) this.FileStoreHandler._buildUrl = (projectId, fileId) => `www.filestore.test/${projectId}/${fileId}` this.DocumentUpdaterHandler.resyncProjectHistory.yields() this.ProjectEntityUpdateHandler.resyncProjectHistory( projectId, this.callback ) }) it('gets the project', function () { this.ProjectGetter.getProject.calledWith(projectId).should.equal(true) }) it('gets the entities for the project', function () { this.ProjectEntityHandler.getAllEntitiesFromProject .calledWith(this.project) .should.equal(true) }) it('tells the doc updater to sync the project', function () { const docs = [ { doc: docId, path: 'main.tex', }, ] const files = [ { file: fileId, path: 'universe.png', url: `www.filestore.test/${projectId}/${fileId}`, }, ] this.DocumentUpdaterHandler.resyncProjectHistory .calledWith(projectId, projectHistoryId, docs, files) .should.equal(true) }) it('calls the callback', function () { this.callback.called.should.equal(true) }) }) }) describe('_cleanUpEntity', function () { beforeEach(function () { this.entityId = '4eecaffcbffa66588e000009' this.FileStoreHandler.deleteFile.yields() this.ProjectEntityUpdateHandler.unsetRootDoc = sinon.stub().yields() this.ProjectEntityMongoUpdateHandler._insertDeletedFileReference.yields() }) describe('a file', function () { beforeEach(function (done) { this.path = '/file/system/path.png' this.entity = { _id: this.entityId } this.newProject = 'new-project' this.ProjectEntityUpdateHandler._cleanUpEntity( this.project, this.newProject, this.entity, 'file', this.path, userId, done ) }) it('should insert the file into the deletedFiles collection', function () { this.ProjectEntityMongoUpdateHandler._insertDeletedFileReference .calledWith(this.project._id, this.entity) .should.equal(true) }) it('should not delete the file from FileStoreHandler', function () { this.FileStoreHandler.deleteFile .calledWith(projectId, this.entityId) .should.equal(false) }) it('should not attempt to delete from the document updater', function () { this.DocumentUpdaterHandler.deleteDoc.called.should.equal(false) }) it('should should send the update to the doc updater', function () { const oldFiles = [{ file: this.entity, path: this.path }] this.DocumentUpdaterHandler.updateProjectStructure .calledWith(projectId, projectHistoryId, userId, { oldFiles, newProject: this.newProject, }) .should.equal(true) }) }) describe('a doc', function () { beforeEach(function (done) { this.path = '/file/system/path.tex' this.ProjectEntityUpdateHandler._cleanUpDoc = sinon.stub().yields() this.entity = { _id: this.entityId } this.newProject = 'new-project' this.ProjectEntityUpdateHandler._cleanUpEntity( this.project, this.newProject, this.entity, 'doc', this.path, userId, done ) }) it('should clean up the doc', function () { this.ProjectEntityUpdateHandler._cleanUpDoc .calledWith(this.project, this.entity, this.path, userId) .should.equal(true) }) it('should should send the update to the doc updater', function () { const oldDocs = [{ doc: this.entity, path: this.path }] this.DocumentUpdaterHandler.updateProjectStructure .calledWith(projectId, projectHistoryId, userId, { oldDocs, newProject: this.newProject, }) .should.equal(true) }) }) describe('a folder', function () { beforeEach(function (done) { this.folder = { folders: [ { name: 'subfolder', fileRefs: [ (this.file1 = { _id: 'file-id-1', name: 'file-name-1' }), ], docs: [(this.doc1 = { _id: 'doc-id-1', name: 'doc-name-1' })], folders: [], }, ], fileRefs: [(this.file2 = { _id: 'file-id-2', name: 'file-name-2' })], docs: [(this.doc2 = { _id: 'doc-id-2', name: 'doc-name-2' })], } this.ProjectEntityUpdateHandler._cleanUpDoc = sinon.stub().yields() this.ProjectEntityUpdateHandler._cleanUpFile = sinon.stub().yields() const path = '/folder' this.newProject = 'new-project' this.ProjectEntityUpdateHandler._cleanUpEntity( this.project, this.newProject, this.folder, 'folder', path, userId, done ) }) it('should clean up all sub files', function () { this.ProjectEntityUpdateHandler._cleanUpFile .calledWith( this.project, this.file1, '/folder/subfolder/file-name-1', userId ) .should.equal(true) this.ProjectEntityUpdateHandler._cleanUpFile .calledWith(this.project, this.file2, '/folder/file-name-2', userId) .should.equal(true) }) it('should clean up all sub docs', function () { this.ProjectEntityUpdateHandler._cleanUpDoc .calledWith( this.project, this.doc1, '/folder/subfolder/doc-name-1', userId ) .should.equal(true) this.ProjectEntityUpdateHandler._cleanUpDoc .calledWith(this.project, this.doc2, '/folder/doc-name-2', userId) .should.equal(true) }) it('should should send one update to the doc updater for all docs and files', function () { const oldFiles = [ { file: this.file2, path: '/folder/file-name-2' }, { file: this.file1, path: '/folder/subfolder/file-name-1' }, ] const oldDocs = [ { doc: this.doc2, path: '/folder/doc-name-2' }, { doc: this.doc1, path: '/folder/subfolder/doc-name-1' }, ] this.DocumentUpdaterHandler.updateProjectStructure .calledWith(projectId, projectHistoryId, userId, { oldFiles, oldDocs, newProject: this.newProject, }) .should.equal(true) }) }) }) describe('_cleanUpDoc', function () { beforeEach(function () { this.doc = { _id: ObjectId(), name: 'test.tex', } this.path = '/path/to/doc' this.ProjectEntityUpdateHandler.unsetRootDoc = sinon.stub().yields() this.DocstoreManager.deleteDoc.yields() }) describe('when the doc is the root doc', function () { beforeEach(function () { this.project.rootDoc_id = this.doc._id this.ProjectEntityUpdateHandler._cleanUpDoc( this.project, this.doc, this.path, userId, this.callback ) }) it('should unset the root doc', function () { this.ProjectEntityUpdateHandler.unsetRootDoc .calledWith(projectId) .should.equal(true) }) it('should delete the doc in the doc updater', function () { this.DocumentUpdaterHandler.deleteDoc .calledWith(projectId, this.doc._id.toString()) .should.equal(true) }) it('should delete the doc in the doc store', function () { this.DocstoreManager.deleteDoc .calledWith(projectId, this.doc._id.toString(), 'test.tex') .should.equal(true) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) describe('when the doc is not the root doc', function () { beforeEach(function () { this.project.rootDoc_id = ObjectId() this.ProjectEntityUpdateHandler._cleanUpDoc( this.project, this.doc, this.path, userId, this.callback ) }) it('should not unset the root doc', function () { this.ProjectEntityUpdateHandler.unsetRootDoc.called.should.equal(false) }) it('should call the callback', function () { this.callback.called.should.equal(true) }) }) }) describe('convertDocToFile', function () { beforeEach(function () { this.docPath = '/folder/doc.tex' this.docLines = ['line one', 'line two'] this.tmpFilePath = '/tmp/file' this.fileStoreUrl = 'http://filestore/file' this.folder = { _id: new ObjectId() } this.rev = 3 this.ProjectLocator.findElement .withArgs({ project_id: this.project._id, element_id: this.doc._id, type: 'doc', }) .yields(null, this.doc, { fileSystem: this.path }) this.ProjectLocator.findElement .withArgs({ project_id: this.project._id.toString(), element_id: this.file._id, type: 'file', }) .yields(null, this.file, this.docPath, this.folder) this.DocstoreManager.getDoc .withArgs(this.project._id, this.doc._id) .yields(null, this.docLines, this.rev) this.FileWriter.writeLinesToDisk.yields(null, this.tmpFilePath) this.FileStoreHandler.uploadFileFromDisk.yields( null, this.fileStoreUrl, this.file ) this.ProjectEntityMongoUpdateHandler.replaceDocWithFile.yields( null, this.project ) }) describe('successfully', function () { beforeEach(function (done) { this.ProjectEntityUpdateHandler.convertDocToFile( this.project._id, this.doc._id, this.user._id, done ) }) it('deletes the document in doc updater', function () { expect(this.DocumentUpdaterHandler.deleteDoc).to.have.been.calledWith( this.project._id, this.doc._id ) }) it('uploads the file to filestore', function () { expect( this.FileStoreHandler.uploadFileFromDisk ).to.have.been.calledWith( this.project._id, { name: this.doc.name, rev: this.rev + 1 }, this.tmpFilePath ) }) it('cleans up the temporary file', function () { expect(this.fs.unlink).to.have.been.calledWith(this.tmpFilePath) }) it('replaces the doc with the file', function () { expect( this.ProjectEntityMongoUpdateHandler.replaceDocWithFile ).to.have.been.calledWith(this.project._id, this.doc._id, this.file) }) it('notifies document updater of changes', function () { expect( this.DocumentUpdaterHandler.updateProjectStructure ).to.have.been.calledWith( this.project._id, this.project.overleaf.history.id, this.user._id, { oldDocs: [{ doc: this.doc, path: this.path }], newFiles: [ { file: this.file, path: this.path, url: this.fileStoreUrl }, ], newProject: this.project, } ) }) it('should notify real-time of the doc deletion', function () { expect( this.EditorRealTimeController.emitToRoom ).to.have.been.calledWith( this.project._id, 'removeEntity', this.doc._id, 'convertDocToFile' ) }) it('should notify real-time of the file creation', function () { expect( this.EditorRealTimeController.emitToRoom ).to.have.been.calledWith( this.project._id, 'reciveNewFile', this.folder._id, this.file, 'convertDocToFile', null ) }) }) describe('when the doc has ranges', function () { it('should throw a DocHasRangesError', function (done) { this.ranges = { comments: [{ id: 123 }] } this.DocstoreManager.getDoc .withArgs(this.project._id, this.doc._id) .yields(null, this.docLines, 'rev', 'version', this.ranges) this.ProjectEntityUpdateHandler.convertDocToFile( this.project._id, this.doc._id, this.user._id, err => { expect(err).to.be.instanceof(Errors.DocHasRangesError) done() } ) }) }) }) })
overleaf/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js", "repo_id": "overleaf", "token_count": 32865 }
560
/* eslint-disable node/handle-callback-err, max-len, mocha/no-identical-title, 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, expect } = require('chai') const sinon = require('sinon') const modulePath = '../../../../app/src/Features/References/ReferencesHandler' describe('ReferencesHandler', function () { beforeEach(function () { this.projectId = '222' this.fakeProject = { _id: this.projectId, owner_ref: (this.fakeOwner = { _id: 'some_owner', features: { references: false, }, }), rootFolder: [ { docs: [ { name: 'one.bib', _id: 'aaa' }, { name: 'two.txt', _id: 'bbb' }, ], folders: [ { docs: [{ name: 'three.bib', _id: 'ccc' }], fileRefs: [{ name: 'four.bib', _id: 'ghg' }], folders: [], }, ], }, ], } this.docIds = ['aaa', 'ccc'] this.handler = SandboxedModule.require(modulePath, { requires: { '@overleaf/settings': (this.settings = { apis: { references: { url: 'http://some.url/references' }, docstore: { url: 'http://some.url/docstore' }, filestore: { url: 'http://some.url/filestore' }, }, }), request: (this.request = { get: sinon.stub(), post: sinon.stub(), }), '../Project/ProjectGetter': (this.ProjectGetter = { getProject: sinon.stub().callsArgWith(2, null, this.fakeProject), }), '../User/UserGetter': (this.UserGetter = { getUser: sinon.stub(), }), '../DocumentUpdater/DocumentUpdaterHandler': (this.DocumentUpdaterHandler = { flushDocToMongo: sinon.stub().callsArgWith(2, null), }), '../../infrastructure/Features': (this.Features = { hasFeature: sinon.stub().returns(true), }), }, }) return (this.fakeResponseData = { projectId: this.projectId, keys: ['k1', 'k2'], }) }) describe('index', function () { beforeEach(function () { sinon.stub(this.handler, '_findBibDocIds') sinon.stub(this.handler, '_findBibFileIds') sinon.stub(this.handler, '_isFullIndex').callsArgWith(1, null, true) this.request.post.callsArgWith( 1, null, { statusCode: 200 }, this.fakeResponseData ) return (this.call = callback => { return this.handler.index(this.projectId, this.docIds, callback) }) }) describe('when references feature is disabled', function () { beforeEach(function () { this.Features.hasFeature.withArgs('references').returns(false) }) it('should not try to retrieve any user information', function (done) { this.call(() => { this.UserGetter.getUser.callCount.should.equal(0) done() }) }) it('should not produce an error', function (done) { return this.call(err => { expect(err).to.equal(undefined) return done() }) }) }) describe('with docIds as an array', function () { beforeEach(function () { return (this.docIds = ['aaa', 'ccc']) }) it('should not call _findBibDocIds', function (done) { return this.call((err, data) => { this.handler._findBibDocIds.callCount.should.equal(0) return done() }) }) it('should call ProjectGetter.getProject', function (done) { return this.call((err, data) => { this.ProjectGetter.getProject.callCount.should.equal(1) this.ProjectGetter.getProject .calledWith(this.projectId) .should.equal(true) return done() }) }) it('should not call _findBibDocIds', function (done) { return this.call((err, data) => { this.handler._findBibDocIds.callCount.should.equal(0) return done() }) }) it('should call DocumentUpdaterHandler.flushDocToMongo', function (done) { return this.call((err, data) => { this.DocumentUpdaterHandler.flushDocToMongo.callCount.should.equal(2) this.docIds.forEach(docId => { return this.DocumentUpdaterHandler.flushDocToMongo .calledWith(this.projectId, docId) .should.equal(true) }) return done() }) }) it('should make a request to references service', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(1) const arg = this.request.post.firstCall.args[0] expect(arg.json).to.have.all.keys('docUrls', 'fullIndex') expect(arg.json.docUrls.length).to.equal(2) expect(arg.json.fullIndex).to.equal(true) return done() }) }) it('should not produce an error', function (done) { return this.call((err, data) => { expect(err).to.equal(null) return done() }) }) it('should return data', function (done) { return this.call((err, data) => { expect(data).to.not.equal(null) expect(data).to.not.equal(undefined) expect(data).to.equal(this.fakeResponseData) return done() }) }) }) describe('when ProjectGetter.getProject produces an error', function () { beforeEach(function () { return this.ProjectGetter.getProject.callsArgWith(2, new Error('woops')) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) it('should not send request', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(0) return done() }) }) }) describe('when _isFullIndex produces an error', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject) return this.handler._isFullIndex.callsArgWith(1, new Error('woops')) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) it('should not send request', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(0) return done() }) }) }) describe('when flushDocToMongo produces an error', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject) this.handler._isFullIndex.callsArgWith(1, false) return this.DocumentUpdaterHandler.flushDocToMongo.callsArgWith( 2, new Error('woops') ) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) it('should not send request', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(0) return done() }) }) }) describe('when request produces an error', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject) this.handler._isFullIndex.callsArgWith(1, null, false) this.DocumentUpdaterHandler.flushDocToMongo.callsArgWith(2, null) return this.request.post.callsArgWith(1, new Error('woops')) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) }) describe('when request responds with error status', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject) this.handler._isFullIndex.callsArgWith(1, null, false) return this.request.post.callsArgWith( 1, null, { statusCode: 500 }, null ) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) }) }) describe('indexAll', function () { beforeEach(function () { sinon.stub(this.handler, '_findBibDocIds').returns(['aaa', 'ccc']) sinon.stub(this.handler, '_findBibFileIds').returns(['fff', 'ggg']) sinon.stub(this.handler, '_isFullIndex').callsArgWith(1, null, true) this.request.post.callsArgWith( 1, null, { statusCode: 200 }, this.fakeResponseData ) return (this.call = callback => { return this.handler.indexAll(this.projectId, callback) }) }) it('should call _findBibDocIds', function (done) { return this.call((err, data) => { this.handler._findBibDocIds.callCount.should.equal(1) this.handler._findBibDocIds .calledWith(this.fakeProject) .should.equal(true) return done() }) }) it('should call _findBibFileIds', function (done) { return this.call((err, data) => { this.handler._findBibDocIds.callCount.should.equal(1) this.handler._findBibDocIds .calledWith(this.fakeProject) .should.equal(true) return done() }) }) it('should call DocumentUpdaterHandler.flushDocToMongo', function (done) { return this.call((err, data) => { this.DocumentUpdaterHandler.flushDocToMongo.callCount.should.equal(2) return done() }) }) it('should make a request to references service', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(1) const arg = this.request.post.firstCall.args[0] expect(arg.json).to.have.all.keys('docUrls', 'fullIndex') expect(arg.json.docUrls.length).to.equal(4) expect(arg.json.fullIndex).to.equal(true) return done() }) }) it('should not produce an error', function (done) { return this.call((err, data) => { expect(err).to.equal(null) return done() }) }) it('should return data', function (done) { return this.call((err, data) => { expect(data).to.not.equal(null) expect(data).to.not.equal(undefined) expect(data).to.equal(this.fakeResponseData) return done() }) }) describe('when ProjectGetter.getProject produces an error', function () { beforeEach(function () { return this.ProjectGetter.getProject.callsArgWith(2, new Error('woops')) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) it('should not send request', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(0) return done() }) }) }) describe('when _isFullIndex produces an error', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject) return this.handler._isFullIndex.callsArgWith(1, new Error('woops')) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) it('should not send request', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(0) return done() }) }) }) describe('when flushDocToMongo produces an error', function () { beforeEach(function () { this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject) this.handler._isFullIndex.callsArgWith(1, false) return this.DocumentUpdaterHandler.flushDocToMongo.callsArgWith( 2, new Error('woops') ) }) it('should produce an error', function (done) { return this.call((err, data) => { expect(err).to.not.equal(null) expect(err).to.be.instanceof(Error) expect(data).to.equal(undefined) return done() }) }) it('should not send request', function (done) { return this.call((err, data) => { this.request.post.callCount.should.equal(0) return done() }) }) }) }) describe('_findBibDocIds', function () { beforeEach(function () { this.fakeProject = { rootFolder: [ { docs: [ { name: 'one.bib', _id: 'aaa' }, { name: 'two.txt', _id: 'bbb' }, ], folders: [ { docs: [{ name: 'three.bib', _id: 'ccc' }], folders: [] }, ], }, ], } return (this.expectedIds = ['aaa', 'ccc']) }) it('should select the correct docIds', function () { const result = this.handler._findBibDocIds(this.fakeProject) return expect(result).to.deep.equal(this.expectedIds) }) it('should not error with a non array of folders from dirty data', function () { this.fakeProject.rootFolder[0].folders[0].folders = {} const result = this.handler._findBibDocIds(this.fakeProject) return expect(result).to.deep.equal(this.expectedIds) }) }) describe('_findBibFileIds', function () { beforeEach(function () { this.fakeProject = { rootFolder: [ { docs: [ { name: 'one.bib', _id: 'aaa' }, { name: 'two.txt', _id: 'bbb' }, ], fileRefs: [{ name: 'other.bib', _id: 'ddd' }], folders: [ { docs: [{ name: 'three.bib', _id: 'ccc' }], fileRefs: [{ name: 'four.bib', _id: 'ghg' }], folders: [], }, ], }, ], } return (this.expectedIds = ['ddd', 'ghg']) }) it('should select the correct docIds', function () { const result = this.handler._findBibFileIds(this.fakeProject) return expect(result).to.deep.equal(this.expectedIds) }) }) describe('_isFullIndex', function () { beforeEach(function () { this.fakeProject = { owner_ref: (this.owner_ref = 'owner-ref-123') } this.owner = { features: { references: false, }, } this.UserGetter.getUser = sinon.stub() this.UserGetter.getUser .withArgs(this.owner_ref, { features: true }) .yields(null, this.owner) return (this.call = callback => { return this.handler._isFullIndex(this.fakeProject, callback) }) }) describe('with references feature on', function () { beforeEach(function () { return (this.owner.features.references = true) }) it('should return true', function () { return this.call((err, isFullIndex) => { expect(err).to.equal(null) return expect(isFullIndex).to.equal(true) }) }) }) describe('with references feature off', function () { beforeEach(function () { return (this.owner.features.references = false) }) it('should return false', function () { return this.call((err, isFullIndex) => { expect(err).to.equal(null) return expect(isFullIndex).to.equal(false) }) }) }) describe('with referencesSearch', function () { beforeEach(function () { return (this.owner.features = { referencesSearch: true, references: false, }) }) it('should return true', function () { return this.call((err, isFullIndex) => { expect(err).to.equal(null) return expect(isFullIndex).to.equal(true) }) }) }) }) })
overleaf/web/test/unit/src/References/ReferencesHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/References/ReferencesHandlerTests.js", "repo_id": "overleaf", "token_count": 7977 }
561
/* eslint-disable max-len, mocha/handle-done-callback, 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 sinon = require('sinon') const { expect } = require('chai') const MockRequest = require('../helpers/MockRequest') const MockResponse = require('../helpers/MockResponse') const modulePath = '../../../../app/src/Features/Subscription/SubscriptionController' const Errors = require('../../../../app/src/Features/Errors/Errors') const SubscriptionErrors = require('../../../../app/src/Features/Subscription/Errors') const mockSubscriptions = { 'subscription-123-active': { uuid: 'subscription-123-active', plan: { name: 'Gold', plan_code: 'gold', }, current_period_ends_at: new Date(), state: 'active', unit_amount_in_cents: 999, account: { account_code: 'user-123', }, }, } describe('SubscriptionController', function () { beforeEach(function () { this.user = { email: 'tom@yahoo.com', _id: 'one', signUpDate: new Date('2000-10-01'), } this.activeRecurlySubscription = mockSubscriptions['subscription-123-active'] this.SessionManager = { getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user), getLoggedInUserId: sinon.stub().returns(this.user._id), getSessionUser: sinon.stub().returns(this.user), isUserLoggedIn: sinon.stub().returns(true), } this.SubscriptionHandler = { createSubscription: sinon.stub().callsArgWith(3), updateSubscription: sinon.stub().callsArgWith(3), reactivateSubscription: sinon.stub().callsArgWith(1), cancelSubscription: sinon.stub().callsArgWith(1), syncSubscription: sinon.stub().yields(), attemptPaypalInvoiceCollection: sinon.stub().yields(), startFreeTrial: sinon.stub(), promises: { createSubscription: sinon.stub().resolves(), updateSubscription: sinon.stub().resolves(), reactivateSubscription: sinon.stub().resolves(), cancelSubscription: sinon.stub().resolves(), syncSubscription: sinon.stub().resolves(), attemptPaypalInvoiceCollection: sinon.stub().resolves(), startFreeTrial: sinon.stub().resolves(), }, } this.PlansLocator = { findLocalPlanInSettings: sinon.stub() } this.LimitationsManager = { hasPaidSubscription: sinon.stub(), userHasV1OrV2Subscription: sinon.stub(), userHasV2Subscription: sinon.stub(), promises: { hasPaidSubscription: sinon.stub().resolves(), userHasV1OrV2Subscription: sinon.stub().resolves(), userHasV2Subscription: sinon.stub().resolves(), }, } this.SubscriptionViewModelBuilder = { buildUsersSubscriptionViewModel: sinon.stub().callsArgWith(1, null, {}), buildPlansList: sinon.stub(), promises: { buildUsersSubscriptionViewModel: sinon.stub().resolves({}), }, } this.settings = { coupon_codes: { upgradeToAnnualPromo: { student: 'STUDENTCODEHERE', collaborator: 'COLLABORATORCODEHERE', }, }, apis: { recurly: { subdomain: 'sl', }, }, siteUrl: 'http://de.sharelatex.dev:3000', gaExperiments: {}, } this.GeoIpLookup = { getCurrencyCode: sinon.stub(), promises: { getCurrencyCode: sinon.stub(), }, } this.UserGetter = { getUser: sinon.stub().callsArgWith(2, null, this.user), promises: { getUser: sinon.stub().resolves(this.user), }, } this.SubscriptionController = SandboxedModule.require(modulePath, { requires: { '../Authentication/SessionManager': this.SessionManager, './SubscriptionHandler': this.SubscriptionHandler, './PlansLocator': this.PlansLocator, './SubscriptionViewModelBuilder': this.SubscriptionViewModelBuilder, './LimitationsManager': this.LimitationsManager, '../../infrastructure/GeoIpLookup': this.GeoIpLookup, '@overleaf/settings': this.settings, '../User/UserGetter': this.UserGetter, './RecurlyWrapper': (this.RecurlyWrapper = { updateAccountEmailAddress: sinon.stub().yields(), }), './FeaturesUpdater': (this.FeaturesUpdater = {}), './GroupPlansData': (this.GroupPlansData = {}), './V1SubscriptionManager': (this.V1SubscriptionManager = {}), '../Errors/HttpErrorHandler': (this.HttpErrorHandler = { unprocessableEntity: sinon.stub(), }), './Errors': SubscriptionErrors, '../Analytics/AnalyticsManager': (this.AnalyticsManager = { recordEvent: sinon.stub(), setUserProperty: sinon.stub(), }), '../SplitTests/SplitTestHandler': (this.SplitTestHandler = { getTestSegmentation: () => {}, }), }, }) this.res = new MockResponse() this.req = new MockRequest() this.req.body = {} this.req.query = { planCode: '123123' } return (this.stubbedCurrencyCode = 'GBP') }) describe('plansPage', function () { beforeEach(function () { this.req.ip = '1234.3123.3131.333 313.133.445.666 653.5345.5345.534' return this.GeoIpLookup.promises.getCurrencyCode.resolves({ currencyCode: this.stubbedCurrencyCode, }) }) }) describe('paymentPage', function () { beforeEach(function () { this.req.headers = {} this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly = sinon .stub() .resolves(true) return this.GeoIpLookup.promises.getCurrencyCode.resolves({ currencyCode: this.stubbedCurrencyCode, }) }) describe('with a user without a subscription', function () { beforeEach(function () { this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves( false ) return this.PlansLocator.findLocalPlanInSettings.returns({}) }) describe('with a valid plan code', function () { it('should render the new subscription page', function (done) { this.res.render = (page, opts) => { page.should.equal('subscriptions/new') done() } this.SubscriptionController.paymentPage(this.req, this.res) }) }) }) describe('with a user with subscription', function () { it('should redirect to the subscription dashboard', function (done) { this.PlansLocator.findLocalPlanInSettings.returns({}) this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves( true ) this.res.redirect = url => { url.should.equal('/user/subscription?hasSubscription=true') return done() } return this.SubscriptionController.paymentPage(this.req, this.res) }) }) describe('with an invalid plan code', function () { it('should return 422 error - Unprocessable Entity', function (done) { this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves( false ) this.PlansLocator.findLocalPlanInSettings.returns(null) this.HttpErrorHandler.unprocessableEntity = sinon.spy( (req, res, message) => { expect(req).to.exist expect(res).to.exist expect(message).to.deep.equal('Plan not found') done() } ) return this.SubscriptionController.paymentPage(this.req, this.res) }) }) describe('which currency to use', function () { beforeEach(function () { this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves( false ) return this.PlansLocator.findLocalPlanInSettings.returns({}) }) it('should use the set currency from the query string', function (done) { this.req.query.currency = 'EUR' this.res.render = (page, opts) => { opts.currency.should.equal('EUR') opts.currency.should.not.equal(this.stubbedCurrencyCode) return done() } return this.SubscriptionController.paymentPage(this.req, this.res) }) it('should upercase the currency code', function (done) { this.req.query.currency = 'eur' this.res.render = (page, opts) => { opts.currency.should.equal('EUR') return done() } return this.SubscriptionController.paymentPage(this.req, this.res) }) it('should use the geo ip currency if non is provided', function (done) { this.req.query.currency = null this.res.render = (page, opts) => { opts.currency.should.equal(this.stubbedCurrencyCode) done() } this.SubscriptionController.paymentPage(this.req, this.res) }) }) describe('with a recurly subscription already', function () { it('should redirect to the subscription dashboard', function (done) { this.PlansLocator.findLocalPlanInSettings.returns({}) this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves( false ) this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly.resolves( false ) this.res.redirect = url => { url.should.equal('/user/subscription?hasSubscription=true') return done() } return this.SubscriptionController.paymentPage(this.req, this.res) }) }) }) describe('successfulSubscription', function () { beforeEach(function (done) { this.SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel.callsArgWith( 1, null, {} ) this.res.callback = done return this.SubscriptionController.successfulSubscription( this.req, this.res ) }) }) describe('userSubscriptionPage', function () { beforeEach(function (done) { this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves( { personalSubscription: (this.personalSubscription = { 'personal-subscription': 'mock', }), memberGroupSubscriptions: (this.memberGroupSubscriptions = { 'group-subscriptions': 'mock', }), } ) this.SubscriptionViewModelBuilder.buildPlansList.returns( (this.plans = { plans: 'mock' }) ) this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(false) this.res.render = (view, data) => { this.data = data expect(view).to.equal('subscriptions/dashboard') done() } this.SubscriptionController.userSubscriptionPage(this.req, this.res) }) it('should load the personal, groups and v1 subscriptions', function () { expect(this.data.personalSubscription).to.deep.equal( this.personalSubscription ) return expect(this.data.memberGroupSubscriptions).to.deep.equal( this.memberGroupSubscriptions ) }) it('should load the user', function () { return expect(this.data.user).to.deep.equal(this.user) }) it('should load the plans', function () { return expect(this.data.plans).to.deep.equal(this.plans) }) }) describe('createSubscription', function () { beforeEach(function (done) { this.res = { sendStatus() { return done() }, } sinon.spy(this.res, 'sendStatus') this.subscriptionDetails = { card: '1234', cvv: '123', } this.recurlyTokenIds = { billing: '1234', threeDSecureActionResult: '5678', } this.req.body.recurly_token_id = this.recurlyTokenIds.billing this.req.body.recurly_three_d_secure_action_result_token_id = this.recurlyTokenIds.threeDSecureActionResult this.req.body.subscriptionDetails = this.subscriptionDetails this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false) return this.SubscriptionController.createSubscription(this.req, this.res) }) it('should send the user and subscriptionId to the handler', function (done) { this.SubscriptionHandler.createSubscription .calledWithMatch( this.user, this.subscriptionDetails, this.recurlyTokenIds ) .should.equal(true) return done() }) it('should redurect to the subscription page', function (done) { this.res.sendStatus.calledWith(201).should.equal(true) return done() }) }) describe('createSubscription with errors', function () { it('should handle users with subscription', function (done) { this.LimitationsManager.userHasV1OrV2Subscription.yields(null, true) this.SubscriptionController.createSubscription(this.req, { sendStatus: status => { expect(status).to.equal(409) this.SubscriptionHandler.createSubscription.called.should.equal(false) done() }, }) }) it('should handle 3DSecure errors', function (done) { this.next = sinon.stub() this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false) this.SubscriptionHandler.createSubscription.yields( new SubscriptionErrors.RecurlyTransactionError({}) ) this.HttpErrorHandler.unprocessableEntity = sinon.spy( (req, res, message) => { expect(req).to.exist expect(res).to.exist expect(message).to.deep.equal('Unknown transaction error') done() } ) this.SubscriptionController.createSubscription(this.req, this.res) }) it('should handle validation errors', function (done) { this.next = sinon.stub() this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false) this.SubscriptionHandler.createSubscription.yields( new Errors.InvalidError('invalid error test') ) this.HttpErrorHandler.unprocessableEntity = sinon.spy( (req, res, message) => { expect(req).to.exist expect(res).to.exist expect(message).to.deep.equal('invalid error test') done() } ) this.SubscriptionController.createSubscription(this.req, this.res) }) it('should handle recurly errors', function (done) { this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false) this.SubscriptionHandler.createSubscription.yields( new SubscriptionErrors.RecurlyTransactionError({}) ) this.HttpErrorHandler.unprocessableEntity = sinon.spy( (req, res, info) => { expect(req).to.exist expect(res).to.exist expect(info).to.deep.equal('Unknown transaction error') done() } ) return this.SubscriptionController.createSubscription(this.req, this.res) }) it('should handle invalid error', function (done) { this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false) this.SubscriptionHandler.createSubscription.yields( new Errors.InvalidError({}) ) this.HttpErrorHandler.unprocessableEntity = sinon.spy((req, res) => { expect(req).to.exist expect(res).to.exist done() }) return this.SubscriptionController.createSubscription(this.req, this.res) }) }) describe('updateSubscription via post', function () { beforeEach(function (done) { this.res = { redirect() { return done() }, } sinon.spy(this.res, 'redirect') this.plan_code = '1234' this.req.body.plan_code = this.plan_code return this.SubscriptionController.updateSubscription(this.req, this.res) }) it('should send the user and subscriptionId to the handler', function (done) { this.SubscriptionHandler.updateSubscription .calledWith(this.user, this.plan_code) .should.equal(true) return done() }) it('should redurect to the subscription page', function (done) { this.res.redirect.calledWith('/user/subscription').should.equal(true) return done() }) }) describe('updateAccountEmailAddress via put', function () { it('should send the user and subscriptionId to RecurlyWrapper', function () { this.res.sendStatus = sinon.spy() this.SubscriptionController.updateAccountEmailAddress(this.req, this.res) this.RecurlyWrapper.updateAccountEmailAddress .calledWith(this.user._id, this.user.email) .should.equal(true) }) it('should respond with 200', function () { this.res.sendStatus = sinon.spy() this.SubscriptionController.updateAccountEmailAddress(this.req, this.res) this.res.sendStatus.calledWith(200).should.equal(true) }) it('should send the error to the next handler when updating recurly account email fails', function (done) { this.RecurlyWrapper.updateAccountEmailAddress.yields(new Error()) this.next = sinon.spy(error => { expect(error).instanceOf(Error) done() }) this.SubscriptionController.updateAccountEmailAddress( this.req, this.res, this.next ) }) }) describe('reactivateSubscription', function () { beforeEach(function (done) { this.res = { redirect() { return done() }, } sinon.spy(this.res, 'redirect') return this.SubscriptionController.reactivateSubscription( this.req, this.res ) }) it('should tell the handler to reactivate this user', function (done) { this.SubscriptionHandler.reactivateSubscription .calledWith(this.user) .should.equal(true) return done() }) it('should redurect to the subscription page', function (done) { this.res.redirect.calledWith('/user/subscription').should.equal(true) return done() }) }) describe('cancelSubscription', function () { beforeEach(function (done) { this.res = { redirect() { return done() }, } sinon.spy(this.res, 'redirect') return this.SubscriptionController.cancelSubscription(this.req, this.res) }) it('should tell the handler to cancel this user', function (done) { this.SubscriptionHandler.cancelSubscription .calledWith(this.user) .should.equal(true) return done() }) it('should redurect to the subscription page', function (done) { this.res.redirect .calledWith('/user/subscription/canceled') .should.equal(true) return done() }) }) describe('recurly callback', function () { describe('with a sync subscription request', function () { beforeEach(function (done) { this.req = { body: { expired_subscription_notification: { account: { account_code: this.user._id, }, subscription: { uuid: this.activeRecurlySubscription.uuid, plan: { plan_code: 'collaborator', state: 'active', }, }, }, }, } this.res = { sendStatus() { return done() }, } sinon.spy(this.res, 'sendStatus') return this.SubscriptionController.recurlyCallback(this.req, this.res) }) it('should tell the SubscriptionHandler to process the recurly callback', function (done) { this.SubscriptionHandler.syncSubscription.called.should.equal(true) return done() }) it('should send a 200', function (done) { this.res.sendStatus.calledWith(200) return done() }) }) describe('with a billing info updated request', function () { beforeEach(function (done) { this.req = { body: { billing_info_updated_notification: { account: { account_code: 'mock-account-code', }, }, }, } this.res = { sendStatus() { done() }, } sinon.spy(this.res, 'sendStatus') this.SubscriptionController.recurlyCallback(this.req, this.res) }) it('should call attemptPaypalInvoiceCollection', function (done) { this.SubscriptionHandler.attemptPaypalInvoiceCollection .calledWith('mock-account-code') .should.equal(true) done() }) it('should send a 200', function (done) { this.res.sendStatus.calledWith(200) done() }) }) describe('with a non-actionable request', function () { beforeEach(function (done) { this.user.id = this.activeRecurlySubscription.account.account_code this.req = { body: { renewed_subscription_notification: { account: { account_code: this.user._id, }, subscription: { uuid: this.activeRecurlySubscription.uuid, plan: { plan_code: 'collaborator', state: 'active', }, }, }, }, } this.res = { sendStatus() { return done() }, } sinon.spy(this.res, 'sendStatus') return this.SubscriptionController.recurlyCallback(this.req, this.res) }) it('should not call the subscriptionshandler', function () { this.SubscriptionHandler.syncSubscription.called.should.equal(false) this.SubscriptionHandler.attemptPaypalInvoiceCollection.called.should.equal( false ) }) it('should respond with a 200 status', function () { return this.res.sendStatus.calledWith(200) }) }) }) describe('renderUpgradeToAnnualPlanPage', function () { it('should redirect to the plans page if the user does not have a subscription', function (done) { this.LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false) this.res.redirect = function (url) { url.should.equal('/user/subscription/plans') return done() } return this.SubscriptionController.renderUpgradeToAnnualPlanPage( this.req, this.res ) }) it('should pass the plan code to the view - student', function (done) { this.LimitationsManager.userHasV2Subscription.callsArgWith( 1, null, true, { planCode: 'Student free trial 14 days' } ) this.res.render = function (view, opts) { view.should.equal('subscriptions/upgradeToAnnual') opts.planName.should.equal('student') return done() } return this.SubscriptionController.renderUpgradeToAnnualPlanPage( this.req, this.res ) }) it('should pass the plan code to the view - collaborator', function (done) { this.LimitationsManager.userHasV2Subscription.callsArgWith( 1, null, true, { planCode: 'free trial for Collaborator free trial 14 days' } ) this.res.render = function (view, opts) { opts.planName.should.equal('collaborator') return done() } return this.SubscriptionController.renderUpgradeToAnnualPlanPage( this.req, this.res ) }) it('should pass annual as the plan name if the user is already on an annual plan', function (done) { this.LimitationsManager.userHasV2Subscription.callsArgWith( 1, null, true, { planCode: 'student annual with free trial' } ) this.res.render = function (view, opts) { opts.planName.should.equal('annual') return done() } return this.SubscriptionController.renderUpgradeToAnnualPlanPage( this.req, this.res ) }) }) describe('processUpgradeToAnnualPlan', function () { beforeEach(function () {}) it('should tell the subscription handler to update the subscription with the annual plan and apply a coupon code', function (done) { this.req.body = { planName: 'student' } this.res.sendStatus = () => { this.SubscriptionHandler.updateSubscription .calledWith(this.user, 'student-annual', 'STUDENTCODEHERE') .should.equal(true) return done() } return this.SubscriptionController.processUpgradeToAnnualPlan( this.req, this.res ) }) it('should get the collaborator coupon code', function (done) { this.req.body = { planName: 'collaborator' } this.res.sendStatus = url => { this.SubscriptionHandler.updateSubscription .calledWith(this.user, 'collaborator-annual', 'COLLABORATORCODEHERE') .should.equal(true) return done() } return this.SubscriptionController.processUpgradeToAnnualPlan( this.req, this.res ) }) }) })
overleaf/web/test/unit/src/Subscription/SubscriptionControllerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Subscription/SubscriptionControllerTests.js", "repo_id": "overleaf", "token_count": 10868 }
562
const { expect } = require('chai') const sinon = require('sinon') const SandboxedModule = require('sandboxed-module') const { ObjectId } = require('mongodb') const { Project } = require('../helpers/models/Project') const MODULE_PATH = '../../../../app/src/Features/ThirdPartyDataStore/TpdsProjectFlusher' describe('TpdsProjectFlusher', function () { beforeEach(function () { this.project = { _id: ObjectId() } this.docs = { '/doc/one': { _id: 'mock-doc-1', lines: ['one'], rev: 5 }, '/doc/two': { _id: 'mock-doc-2', lines: ['two'], rev: 6 }, } this.files = { '/file/one': { _id: 'mock-file-1', rev: 7 }, '/file/two': { _id: 'mock-file-2', rev: 8 }, } this.DocumentUpdaterHandler = { promises: { flushProjectToMongo: sinon.stub().resolves(), }, } this.ProjectGetter = { promises: { getProject: sinon.stub().resolves(this.project), }, } this.ProjectEntityHandler = { promises: { getAllDocs: sinon.stub().withArgs(this.project._id).resolves(this.docs), getAllFiles: sinon .stub() .withArgs(this.project._id) .resolves(this.files), }, } this.TpdsUpdateSender = { promises: { addDoc: sinon.stub().resolves(), addFile: sinon.stub().resolves(), }, } this.ProjectMock = sinon.mock(Project) this.TpdsProjectFlusher = SandboxedModule.require(MODULE_PATH, { requires: { '../DocumentUpdater/DocumentUpdaterHandler': this .DocumentUpdaterHandler, '../Project/ProjectGetter': this.ProjectGetter, '../Project/ProjectEntityHandler': this.ProjectEntityHandler, '../../models/Project': { Project }, './TpdsUpdateSender': this.TpdsUpdateSender, }, }) }) afterEach(function () { this.ProjectMock.restore() }) describe('flushProjectToTpds', function () { describe('usually', function () { beforeEach(async function () { await this.TpdsProjectFlusher.promises.flushProjectToTpds( this.project._id ) }) it('should flush the project from the doc updater', function () { expect( this.DocumentUpdaterHandler.promises.flushProjectToMongo ).to.have.been.calledWith(this.project._id) }) it('should flush each doc to the TPDS', function () { for (const [path, doc] of Object.entries(this.docs)) { expect(this.TpdsUpdateSender.promises.addDoc).to.have.been.calledWith( { project_id: this.project._id, doc_id: doc._id, project_name: this.project.name, rev: doc.rev, path, } ) } }) it('should flush each file to the TPDS', function () { for (const [path, file] of Object.entries(this.files)) { expect( this.TpdsUpdateSender.promises.addFile ).to.have.been.calledWith({ project_id: this.project._id, file_id: file._id, project_name: this.project.name, rev: file.rev, path, }) } }) }) describe('when a TPDS flush is pending', function () { beforeEach(async function () { this.project.deferredTpdsFlushCounter = 2 this.ProjectMock.expects('updateOne') .withArgs( { _id: this.project._id, deferredTpdsFlushCounter: { $lte: 2 }, }, { $set: { deferredTpdsFlushCounter: 0 } } ) .chain('exec') .resolves() await this.TpdsProjectFlusher.promises.flushProjectToTpds( this.project._id ) }) it('resets the deferred flush counter', function () { this.ProjectMock.verify() }) }) }) describe('deferProjectFlushToTpds', function () { beforeEach(async function () { this.ProjectMock.expects('updateOne') .withArgs( { _id: this.project._id, }, { $inc: { deferredTpdsFlushCounter: 1 } } ) .chain('exec') .resolves() await this.TpdsProjectFlusher.promises.deferProjectFlushToTpds( this.project._id ) }) it('increments the deferred flush counter', function () { this.ProjectMock.verify() }) }) describe('flushProjectToTpdsIfNeeded', function () { let cases = [0, undefined] cases.forEach(counterValue => { describe(`when the deferred flush counter is ${counterValue}`, function () { beforeEach(async function () { this.project.deferredTpdsFlushCounter = counterValue await this.TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded( this.project._id ) }) it("doesn't flush the project from the doc updater", function () { expect(this.DocumentUpdaterHandler.promises.flushProjectToMongo).not .to.have.been.called }) it("doesn't flush any doc", function () { expect(this.TpdsUpdateSender.promises.addDoc).not.to.have.been.called }) it("doesn't flush any file", function () { expect(this.TpdsUpdateSender.promises.addFile).not.to.have.been.called }) }) }) cases = [1, 2] cases.forEach(counterValue => { describe(`when the deferred flush counter is ${counterValue}`, function () { beforeEach(async function () { this.project.deferredTpdsFlushCounter = counterValue this.ProjectMock.expects('updateOne') .withArgs( { _id: this.project._id, deferredTpdsFlushCounter: { $lte: counterValue }, }, { $set: { deferredTpdsFlushCounter: 0 } } ) .chain('exec') .resolves() await this.TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded( this.project._id ) }) it('flushes the project from the doc updater', function () { expect( this.DocumentUpdaterHandler.promises.flushProjectToMongo ).to.have.been.calledWith(this.project._id) }) it('flushes each doc to the TPDS', function () { for (const [path, doc] of Object.entries(this.docs)) { expect( this.TpdsUpdateSender.promises.addDoc ).to.have.been.calledWith({ project_id: this.project._id, doc_id: doc._id, project_name: this.project.name, rev: doc.rev, path, }) } }) it('flushes each file to the TPDS', function () { for (const [path, file] of Object.entries(this.files)) { expect( this.TpdsUpdateSender.promises.addFile ).to.have.been.calledWith({ project_id: this.project._id, file_id: file._id, project_name: this.project.name, rev: file.rev, path, }) } }) it('resets the deferred flush counter', function () { this.ProjectMock.verify() }) }) }) }) })
overleaf/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js/0
{ "file_path": "overleaf/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js", "repo_id": "overleaf", "token_count": 3511 }
563
/* 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 path = require('path') const sinon = require('sinon') const modulePath = path.join( __dirname, '../../../../app/src/Features/User/UserEmailsConfirmationHandler' ) const { expect } = require('chai') const Errors = require('../../../../app/src/Features/Errors/Errors') const EmailHelper = require('../../../../app/src/Features/Helpers/EmailHelper') describe('UserEmailsConfirmationHandler', function () { beforeEach(function () { this.UserEmailsConfirmationHandler = SandboxedModule.require(modulePath, { requires: { '@overleaf/settings': (this.settings = { siteUrl: 'emails.example.com', }), '../Security/OneTimeTokenHandler': (this.OneTimeTokenHandler = {}), './UserUpdater': (this.UserUpdater = {}), './UserGetter': (this.UserGetter = { getUser: sinon.stub().yields(null, this.mockUser), }), '../Email/EmailHandler': (this.EmailHandler = {}), '../Helpers/EmailHelper': EmailHelper, }, }) this.mockUser = { _id: 'mock-user-id', email: 'mock@example.com', emails: [{ email: 'mock@example.com' }], } this.user_id = this.mockUser._id this.email = this.mockUser.email return (this.callback = sinon.stub()) }) describe('sendConfirmationEmail', function () { beforeEach(function () { this.OneTimeTokenHandler.getNewToken = sinon .stub() .yields(null, (this.token = 'new-token')) return (this.EmailHandler.sendEmail = sinon.stub().yields()) }) describe('successfully', function () { beforeEach(function () { return this.UserEmailsConfirmationHandler.sendConfirmationEmail( this.user_id, this.email, this.callback ) }) it('should generate a token for the user which references their id and email', function () { return this.OneTimeTokenHandler.getNewToken .calledWith( 'email_confirmation', { user_id: this.user_id, email: this.email }, { expiresIn: 90 * 24 * 60 * 60 } ) .should.equal(true) }) it('should send an email to the user', function () { return this.EmailHandler.sendEmail .calledWith('confirmEmail', { to: this.email, confirmEmailUrl: 'emails.example.com/user/emails/confirm?token=new-token', sendingUser_id: this.user_id, }) .should.equal(true) }) it('should call the callback', function () { return this.callback.called.should.equal(true) }) }) describe('with invalid email', function () { beforeEach(function () { return this.UserEmailsConfirmationHandler.sendConfirmationEmail( this.user_id, '!"£$%^&*()', this.callback ) }) it('should return an error', function () { return this.callback .calledWith(sinon.match.instanceOf(Error)) .should.equal(true) }) }) describe('a custom template', function () { beforeEach(function () { return this.UserEmailsConfirmationHandler.sendConfirmationEmail( this.user_id, this.email, 'myCustomTemplate', this.callback ) }) it('should send an email with the given template', function () { return this.EmailHandler.sendEmail .calledWith('myCustomTemplate') .should.equal(true) }) }) }) describe('confirmEmailFromToken', function () { beforeEach(function () { this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon .stub() .yields(null, { user_id: this.user_id, email: this.email }) return (this.UserUpdater.confirmEmail = sinon.stub().yields()) }) describe('successfully', function () { beforeEach(function () { return this.UserEmailsConfirmationHandler.confirmEmailFromToken( (this.token = 'mock-token'), this.callback ) }) it('should call getValueFromTokenAndExpire', function () { return this.OneTimeTokenHandler.getValueFromTokenAndExpire .calledWith('email_confirmation', this.token) .should.equal(true) }) it('should confirm the email of the user_id', function () { return this.UserUpdater.confirmEmail .calledWith(this.user_id, this.email) .should.equal(true) }) it('should call the callback', function () { return this.callback.called.should.equal(true) }) }) describe('with an expired token', function () { beforeEach(function () { this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon .stub() .yields(null, null) return this.UserEmailsConfirmationHandler.confirmEmailFromToken( (this.token = 'mock-token'), this.callback ) }) it('should call the callback with a NotFoundError', function () { return this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) }) describe('with no user_id in the token', function () { beforeEach(function () { this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon .stub() .yields(null, { email: this.email }) return this.UserEmailsConfirmationHandler.confirmEmailFromToken( (this.token = 'mock-token'), this.callback ) }) it('should call the callback with a NotFoundError', function () { return this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) }) describe('with no email in the token', function () { beforeEach(function () { this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon .stub() .yields(null, { user_id: this.user_id }) return this.UserEmailsConfirmationHandler.confirmEmailFromToken( (this.token = 'mock-token'), this.callback ) }) it('should call the callback with a NotFoundError', function () { return this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) }) describe('with no user found', function () { beforeEach(function () { this.UserGetter.getUser.yields(null, null) return this.UserEmailsConfirmationHandler.confirmEmailFromToken( (this.token = 'mock-token'), this.callback ) }) it('should call the callback with a NotFoundError', function () { return this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) }) describe('with secondary email missing on user', function () { beforeEach(function () { this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon .stub() .yields(null, { user_id: this.user_id, email: 'deleted@email.com' }) return this.UserEmailsConfirmationHandler.confirmEmailFromToken( (this.token = 'mock-token'), this.callback ) }) it('should call the callback with a NotFoundError', function () { return this.callback .calledWith(sinon.match.instanceOf(Errors.NotFoundError)) .should.equal(true) }) }) }) })
overleaf/web/test/unit/src/User/UserEmailsConfirmationHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/User/UserEmailsConfirmationHandlerTests.js", "repo_id": "overleaf", "token_count": 3378 }
564
const SandboxedModule = require('sandboxed-module') const mongoose = require('mongoose') /** * Imports a model as we would usually do with e.g. `require('models/User')` * an returns a model an schema, but without connecting to Mongo. This allows * us to use model classes in tests, and to use them with `sinon-mongoose` * * @param modelName the name of the model - e.g. 'User' * @param requires additional `requires` to be passed to SanboxedModule in * the event that these also need to be stubbed. For example, * additional dependent models to be included * * @return model and schema pair - e.g. { User, UserSchema } */ module.exports = (modelName, requires = {}) => { const model = {} requires['../infrastructure/Mongoose'] = { createConnection: () => { return { model: () => {}, } }, model: (modelName, schema) => { model[modelName + 'Schema'] = schema model[modelName] = mongoose.model(modelName, schema) }, Schema: mongoose.Schema, Types: mongoose.Types, } SandboxedModule.require('../../../../app/src/models/' + modelName, { requires: requires, }) return model }
overleaf/web/test/unit/src/helpers/MockModel.js/0
{ "file_path": "overleaf/web/test/unit/src/helpers/MockModel.js", "repo_id": "overleaf", "token_count": 431 }
565
/* 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: * 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 */ const sinon = require('sinon') const path = require('path') const modulePath = path.join( __dirname, '../../../../../app/src/infrastructure/LockManager.js' ) const SandboxedModule = require('sandboxed-module') describe('LockManager - getting the lock', function () { beforeEach(function () { this.LockManager = SandboxedModule.require(modulePath, { requires: { './RedisWrapper': { client() { return { auth() {} } }, }, '@overleaf/settings': { redis: {}, lockManager: { lockTestInterval: 50, maxTestInterval: 1000, maxLockWaitTime: 10000, redisLockExpiry: 30, slowExecutionThreshold: 5000, }, }, '@overleaf/metrics': { inc() {}, gauge() {}, }, }, }) this.callback = sinon.stub() this.key = 'lock:web:lockName:project-id}' return (this.namespace = 'lockName') }) describe('when the lock is not set', function () { beforeEach(function (done) { this.LockManager._tryLock = sinon.stub().yields(null, true) return this.LockManager._getLock(this.key, this.namespace, (...args) => { this.callback(...Array.from(args || [])) return done() }) }) it('should try to get the lock', function () { return this.LockManager._tryLock .calledWith(this.key, this.namespace) .should.equal(true) }) it('should only need to try once', function () { return this.LockManager._tryLock.callCount.should.equal(1) }) it('should return the callback', function () { return this.callback.calledWith(null).should.equal(true) }) }) describe('when the lock is initially set', function () { beforeEach(function (done) { const startTime = Date.now() let tries = 0 this.LockManager.LOCK_TEST_INTERVAL = 5 this.LockManager._tryLock = function (key, namespace, callback) { if (callback == null) { callback = function (error, isFree) {} } if (Date.now() - startTime < 20 || tries < 2) { tries = tries + 1 return callback(null, false) } else { return callback(null, true) } } sinon.spy(this.LockManager, '_tryLock') return this.LockManager._getLock(this.key, this.namespace, (...args) => { this.callback(...Array.from(args || [])) return done() }) }) it('should call tryLock multiple times until free', function () { return (this.LockManager._tryLock.callCount > 1).should.equal(true) }) it('should return the callback', function () { return this.callback.calledWith(null).should.equal(true) }) }) describe('when the lock times out', function () { beforeEach(function (done) { const time = Date.now() this.LockManager.LOCK_TEST_INTERVAL = 1 this.LockManager.MAX_LOCK_WAIT_TIME = 5 this.LockManager._tryLock = sinon.stub().yields(null, false) return this.LockManager._getLock(this.key, this.namespace, (...args) => { this.callback(...Array.from(args || [])) return done() }) }) it('should return the callback with an error', function () { this.callback.should.have.been.calledWith( sinon.match.instanceOf(Error).and(sinon.match.has('message', 'Timeout')) ) }) }) describe('when there are multiple requests for the same lock', function () { beforeEach(function (done) { let locked = false this.results = [] this.LockManager.LOCK_TEST_INTERVAL = 1 this.LockManager._tryLock = function (key, namespace, callback) { if (callback == null) { callback = function (error, gotLock, lockValue) {} } if (locked) { return callback(null, false) } else { locked = true // simulate getting the lock return callback(null, true) } } // Start ten lock requests in order at 1ms 2ms 3ms... // with them randomly holding the lock for 0-10ms. // Use predefined values for the random delay to make the test // deterministic. const randomDelays = [5, 4, 1, 8, 6, 8, 3, 4, 2, 4] let startTime = 0 return Array.from(randomDelays).map((randomDelay, i) => ((randomDelay, i) => { startTime += 1 return setTimeout(() => { // changing the next line to the old method of LockManager._getLockByPolling // should give results in a random order and cause the test to fail. return this.LockManager._getLock( this.key, this.namespace, (...args) => { setTimeout( () => (locked = false), // release the lock after a random amount of time randomDelay ) this.results.push(i) if (this.results.length === 10) { return done() } } ) }, startTime) })(randomDelay, i) ) }) it('should process the requests in order', function () { return this.results.should.deep.equal([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) }) }) })
overleaf/web/test/unit/src/infrastructure/LockManager/getLockTests.js/0
{ "file_path": "overleaf/web/test/unit/src/infrastructure/LockManager/getLockTests.js", "repo_id": "overleaf", "token_count": 2475 }
566
# UI Test suite types FULL = 1 FEDERATED = 2 NOTIFICATIONS = 3 ALPINE_GIT = "alpine/git:latest" APACHE_TIKA = "apache/tika:2.8.0.0" KEYCLOAK = "quay.io/keycloak/keycloak:24.0.1" MINIO_MC = "minio/mc:RELEASE.2021-10-07T04-19-58Z" OC_CI_ALPINE = "owncloudci/alpine:latest" OC_CI_BAZEL_BUILDIFIER = "owncloudci/bazel-buildifier" OC_CI_DRONE_ANSIBLE = "owncloudci/drone-ansible:latest" OC_CI_DRONE_SKIP_PIPELINE = "owncloudci/drone-skip-pipeline" OC_CI_GOLANG = "owncloudci/golang:1.22" OC_CI_HUGO = "owncloudci/hugo:0.115.2" OC_CI_NODEJS = "owncloudci/nodejs:18" OC_CI_PHP = "owncloudci/php:7.4" OC_CI_WAIT_FOR = "owncloudci/wait-for:latest" OC_TESTING_MIDDLEWARE = "owncloud/owncloud-test-middleware:2.0.0" OC_UBUNTU = "owncloud/ubuntu:20.04" PLUGINS_DOCKER = "plugins/docker:20.14" PLUGINS_GH_PAGES = "plugins/gh-pages:1" PLUGINS_GIT_ACTION = "plugins/git-action:1" PLUGINS_GITHUB_RELEASE = "plugins/github-release:1" PLUGINS_S3 = "plugins/s3" PLUGINS_S3_CACHE = "plugins/s3-cache:1" PLUGINS_SLACK = "plugins/slack:1" POSTGRES_ALPINE = "postgres:alpine3.18" SELENIUM_STANDALONE_CHROME = "selenium/standalone-chrome:104.0-20220812" SELENIUM_STANDALONE_FIREFOX = "selenium/standalone-firefox:104.0-20220812" SONARSOURCE_SONAR_SCANNER_CLI = "sonarsource/sonar-scanner-cli:5.0" TOOLHIPPIE_CALENS = "toolhippie/calens:latest" WEB_PUBLISH_NPM_PACKAGES = ["babel-preset", "eslint-config", "extension-sdk", "prettier-config", "tsconfig", "web-client", "web-pkg"] WEB_PUBLISH_NPM_ORGANIZATION = "@ownclouders" dir = { "base": "/var/www/owncloud", "federated": "/var/www/owncloud/federated", "server": "/var/www/owncloud/server", "web": "/var/www/owncloud/web", "ocis": "/var/www/owncloud/ocis", "commentsFile": "/var/www/owncloud/web/comments.file", "app": "/srv/app", "ocisConfig": "/var/www/owncloud/web/tests/drone/config-ocis.json", "webKeycloakConfig": "/var/www/owncloud/web/tests/drone/web-keycloak.json", "ocisIdentifierRegistrationConfig": "/var/www/owncloud/web/tests/drone/identifier-registration.yml", "ocisRevaDataRoot": "/srv/app/tmp/ocis/owncloud/data/", "testingDataDir": "/srv/app/testing/data/", } config = { "app": "web", "rocketchat": { "channel": "builds", "from_secret": "rocketchat_talk_webhook", }, "branches": [ "master", ], "pnpmlint": True, "e2e": { "oCIS-1": { "earlyFail": True, "skip": False, "suites": [ "journeys", "smoke", ], }, "oCIS-2": { "earlyFail": True, "skip": False, "suites": [ "admin-settings", "spaces", ], }, "oCIS-3": { "earlyFail": True, "skip": False, "tikaNeeded": True, "suites": [ "search", "shares", ], }, "oCIS-app-provider": { "skip": False, "suites": [ "app-provider", ], }, }, "acceptance": { "webUI": { "type": FULL, "servers": [ "", ], "suites": { "oCISBasic": [ "webUIPreview", "webUILogin", ], "oCISFiles1": [ "webUICreateFilesFolders", "webUIDeleteFilesFolders", ], "oCISFiles2": [ "webUIFilesDetails", ], "oCISFiles3": [ "webUIRenameFiles", ], "oCISFiles4": [ "webUIRenameFolders", ], "oCISFiles5": [ "webUIFilesCopy", "webUITextEditor", ], "oCISSharingInternal1": [ "webUISharingInternalGroupsEdgeCases", ], "oCISSharingInternal2": [ "webUISharingInternalUsers", ], "oCISSharingInternal3": [ "webUISharingInternalGroupsSharingIndicator", "webUISharingInternalUsersSharingIndicator", ], "oCISSharingAutocompletionResharing": [ "webUISharingAutocompletion", ], "oCISSharingPublic1": [ "webUISharingPublicBasic", ], "oCISSharingPublic2": [ "webUISharingPublicManagement", ], "oCISSharingPublic3": [ "webUISharingPublicDifferentRoles", ], "oCISUploadMove": [ "webUIUpload", "webUIMoveFilesFolders", ], "oCISTrashbinJourney": [ "webUITrashbinDelete", "webUITrashbinFilesFolders", "webUITrashbinRestore", ], }, "extraEnvironment": { "NODE_TLS_REJECT_UNAUTHORIZED": "0", "SERVER_HOST": "https://ocis:9200", "BACKEND_HOST": "https://ocis:9200", "TESTING_DATA_DIR": "%s" % dir["testingDataDir"], "OCIS_REVA_DATA_ROOT": "%s" % dir["ocisRevaDataRoot"], "WEB_UI_CONFIG_FILE": "%s" % dir["ocisConfig"], "EXPECTED_FAILURES_FILE": "%s/tests/acceptance/expected-failures-with-ocis-server-ocis-storage.md" % dir["web"], }, "filterTags": "not @skip", "screenShots": True, }, }, "build": True, } basicTestSuites = [ "webUICreateFilesFolders", "webUIDeleteFilesFolders", "webUIFiles", "webUIFilesCopy", "webUIFilesDetails", "webUILogin", "webUIMoveFilesFolders", "webUIPreview", "webUIRenameFiles", "webUIRenameFolders", "webUISharingAcceptShares", "webUISharingAutocompletion", "webUISharingInternalGroupsEdgeCases", "webUISharingInternalGroupsSharingIndicator", "webUISharingInternalUsers", "webUISharingInternalUsersSharingIndicator", "webUISharingPublicBasic", "webUISharingPublicDifferentRoles", "webUISharingPublicManagement", "webUITextEditor", "webUITrashbinDelete", "webUITrashbinFilesFolders", "webUITrashbinRestore", "webUIUpload", ] # minio mc environment variables minio_mc_environment = { "CACHE_BUCKET": { "from_secret": "cache_s3_bucket", }, "MC_HOST": { "from_secret": "cache_s3_server", }, "AWS_ACCESS_KEY_ID": { "from_secret": "cache_s3_access_key", }, "AWS_SECRET_ACCESS_KEY": { "from_secret": "cache_s3_secret_key", }, } go_step_volumes = [{ "name": "server", "path": dir["app"], }, { "name": "gopath", "path": "/go", }] web_workspace = { "base": dir["base"], "path": config["app"], } def checkTestSuites(): for testGroupName, test in config["acceptance"].items(): suites = [] for key, items in test["suites"].items(): if (type(items) == "list"): suites += items elif (type(items) == "string"): suites.append(key) else: print("Error: invalid value for suite, it must be a list or string") return False expected = [] if (test["type"] == FULL): expected += basicTestSuites if (sorted(suites) != sorted(expected)): print("Error: Suites dont match " + testGroupName) print(Diff(sorted(suites), sorted(expected))) return True def Diff(li1, li2): li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return li_dif def main(ctx): uiSuitesCheck = checkTestSuites() if (uiSuitesCheck == False): print("Errors detected. Review messages above.") return [] before = beforePipelines(ctx) stages = pipelinesDependsOn(stagePipelines(ctx), before) if (stages == False): print("Errors detected. Review messages above.") return [] after = pipelinesDependsOn(afterPipelines(ctx), stages) pipelines = before + stages + after deploys = example_deploys(ctx) if ctx.build.event != "cron": # run example deploys on cron even if some prior pipelines fail deploys = pipelinesDependsOn(deploys, pipelines) pipelines = pipelines + deploys + pipelinesDependsOn( [ purgeBuildArtifactCache(ctx), ], pipelines, ) pipelineSanityChecks(ctx, pipelines) return pipelines def beforePipelines(ctx): return checkStarlark() + \ licenseCheck(ctx) + \ checkTestSuitesInExpectedFailures(ctx) + \ documentation(ctx) + \ changelog(ctx) + \ pnpmCache(ctx) + \ cacheOcisPipeline(ctx) + \ pipelinesDependsOn(buildCacheWeb(ctx), pnpmCache(ctx)) + \ pipelinesDependsOn(pnpmlint(ctx), pnpmCache(ctx)) def stagePipelines(ctx): unit_test_pipelines = unitTests(ctx) e2e_pipelines = e2eTests(ctx) acceptance_pipelines = acceptance(ctx) keycloak_pipelines = e2eTestsOnKeycloak(ctx) return unit_test_pipelines + buildAndTestDesignSystem(ctx) + pipelinesDependsOn(e2e_pipelines + keycloak_pipelines + acceptance_pipelines, unit_test_pipelines) def afterPipelines(ctx): return build(ctx) + pipelinesDependsOn(notify(), build(ctx)) def pnpmCache(ctx): return [{ "kind": "pipeline", "type": "docker", "name": "cache-pnpm", "workspace": { "base": dir["base"], "path": config["app"], }, "steps": skipIfUnchanged(ctx, "cache") + installPnpm() + installPlaywright() + rebuildBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + rebuildBuildArtifactCache(ctx, "playwright", ".playwright"), "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, }] def pnpmlint(ctx): pipelines = [] if "pnpmlint" not in config: return pipelines if type(config["pnpmlint"]) == "bool": if not config["pnpmlint"]: return pipelines result = { "kind": "pipeline", "type": "docker", "name": "lint", "workspace": { "base": dir["base"], "path": config["app"], }, "steps": skipIfUnchanged(ctx, "lint") + restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + installPnpm() + lint(), "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, } for branch in config["branches"]: result["trigger"]["ref"].append("refs/heads/%s" % branch) pipelines.append(result) return pipelines def build(ctx): pipelines = [] if "build" not in config: return pipelines if type(config["build"]) == "bool": if not config["build"]: return pipelines steps = restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + installPnpm() + buildRelease(ctx) if determineReleasePackage(ctx) == None: steps += buildDockerImage() result = { "kind": "pipeline", "type": "docker", "name": "build", "workspace": { "base": dir["base"], "path": config["app"], }, "steps": steps, "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", ], }, } pipelines.append(result) return pipelines def changelog(ctx): pipelines = [] repo_slug = ctx.build.source_repo if ctx.build.source_repo else ctx.repo.slug result = { "kind": "pipeline", "type": "docker", "name": "changelog", "clone": { "disable": True, }, "steps": [ { "name": "clone", "image": PLUGINS_GIT_ACTION, "settings": { "actions": [ "clone", ], "remote": "https://github.com/%s" % (repo_slug), "branch": ctx.build.source if ctx.build.event == "pull_request" else "master", "path": "/drone/src", "netrc_machine": "github.com", "netrc_username": { "from_secret": "github_username", }, "netrc_password": { "from_secret": "github_token", }, }, }, { "name": "generate", "image": TOOLHIPPIE_CALENS, "commands": [ "calens >| CHANGELOG.md", ], }, { "name": "diff", "image": OC_CI_ALPINE, "commands": [ "git diff", ], }, { "name": "output", "image": TOOLHIPPIE_CALENS, "commands": [ "cat CHANGELOG.md", ], }, { "name": "publish", "image": PLUGINS_GIT_ACTION, "settings": { "actions": [ "commit", "push", ], "message": "Automated changelog update [skip ci]", "branch": "master", "author_email": "devops@owncloud.com", "author_name": "ownClouders", "netrc_machine": "github.com", "netrc_username": { "from_secret": "github_username", }, "netrc_password": { "from_secret": "github_token", }, }, "when": { "ref": { "exclude": [ "refs/pull/**", "refs/tags/**", ], }, }, }, ], "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/pull/**", ], }, } pipelines.append(result) return pipelines def buildCacheWeb(ctx): return [{ "kind": "pipeline", "type": "docker", "name": "cache-web", "workspace": { "base": dir["base"], "path": config["app"], }, "steps": skipIfUnchanged(ctx, "cache") + restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + installPnpm() + [{ "name": "build-web", "image": OC_CI_NODEJS, "environment": { "NO_INSTALL": "true", }, "commands": [ "make dist", ], }] + rebuildBuildArtifactCache(ctx, "web-dist", "dist"), "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, }] def unitTests(ctx): sonar_env = { "SONAR_TOKEN": { "from_secret": "sonar_token", }, } if ctx.build.event == "pull_request": sonar_env.update({ "SONAR_PULL_REQUEST_BASE": "%s" % (ctx.build.target), "SONAR_PULL_REQUEST_BRANCH": "%s" % (ctx.build.source), "SONAR_PULL_REQUEST_KEY": "%s" % (ctx.build.ref.replace("refs/pull/", "").split("/")[0]), }) repo_slug = ctx.build.source_repo if ctx.build.source_repo else ctx.repo.slug fork_handling = [] if ctx.build.source_repo != "" and ctx.build.source_repo != ctx.repo.slug: fork_handling = [ "git remote add fork https://github.com/%s.git" % (ctx.build.source_repo), "git fetch fork", ] return [{ "kind": "pipeline", "type": "docker", "name": "unit-tests", "workspace": { "base": dir["base"], "path": config["app"], }, "clone": { "disable": True, # Sonarcloud does not apply issues on already merged branch }, "steps": [ { "name": "clone", "image": ALPINE_GIT, "commands": [ # Always use the owncloud/web repository as base to have an up to date default branch. # This is needed for the skipIfUnchanged step, since it references a commit on master (which could be absent on a fork) "git clone https://github.com/%s.git ." % (ctx.repo.slug), ] + fork_handling + [ "git checkout $DRONE_COMMIT", ], }, ] + skipIfUnchanged(ctx, "unit-tests") + restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + installPnpm() + [ { "name": "unit-tests", "image": OC_CI_NODEJS, "commands": [ "pnpm build:tokens", "pnpm test:unit --coverage", ], }, { "name": "sonarcloud", "image": SONARSOURCE_SONAR_SCANNER_CLI, "environment": sonar_env, }, ], "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, }] def e2eTests(ctx): e2e_workspace = { "base": dir["base"], "path": config["app"], } e2e_volumes = [{ "name": "uploads", "temp": {}, }, { "name": "configs", "temp": {}, }, { "name": "gopath", "temp": {}, }, { "name": "ocis-config", "temp": {}, }] default = { "skip": False, "logLevel": "2", "reportTracing": "false", "db": "mysql:5.5", "suites": [], "tikaNeeded": False, } e2e_trigger = { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], } pipelines = [] params = {} matrices = config["e2e"] for suite, matrix in matrices.items(): for item in default: params[item] = matrix[item] if item in matrix else default[item] if suite == "oCIS-app-provider" and not "full-ci" in ctx.build.title.lower() and ctx.build.event != "cron": continue if params["skip"]: continue if ("with-tracing" in ctx.build.title.lower()): params["reportTracing"] = "true" environment = { "HEADLESS": "true", "RETRY": "1", "REPORT_TRACING": params["reportTracing"], } services = [] depends_on = [] steps = skipIfUnchanged(ctx, "e2e-tests") + \ restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + \ restoreBuildArtifactCache(ctx, "playwright", ".playwright") + \ installPnpm() + \ installPlaywright() + \ restoreBuildArtifactCache(ctx, "web-dist", "dist") if ctx.build.event == "cron": steps += restoreBuildArtifactCache(ctx, "ocis", "ocis") else: steps += restoreOcisCache() # oCIS specific environment variables environment["BASE_URL_OCIS"] = "ocis:9200" # oCIS specific dependencies depends_on = ["cache-ocis"] if suite == "oCIS-app-provider": # app-provider specific steps steps += collaboraService() + \ onlyofficeService() + \ ocisService("app-provider") + \ wopiServer() + \ appProviderService("collabora") + \ appProviderService("onlyoffice") else: # oCIS specific steps steps += copyFilesForUpload() + \ (tikaService() if params["tikaNeeded"] else []) + \ ocisService("e2e-tests", tika_enabled = params["tikaNeeded"]) steps += getSkeletonFiles() + \ [{ "name": "e2e-tests", "image": OC_CI_NODEJS, "environment": environment, "commands": [ "cd tests/e2e", "bash run-e2e.sh --suites %s" % ",".join(params["suites"]), ], }] + \ uploadTracingResult(ctx) + \ logTracingResult(ctx, "e2e-tests %s" % suite) pipelines.append({ "kind": "pipeline", "type": "docker", "name": "e2e-tests-%s" % suite, "workspace": e2e_workspace, "steps": steps, "services": services, "depends_on": depends_on, "trigger": e2e_trigger, "volumes": e2e_volumes, }) return pipelines def acceptance(ctx): pipelines = [] if "acceptance" not in config: return pipelines if type(config["acceptance"]) == "bool": if not config["acceptance"]: return pipelines errorFound = False default = { "servers": [], "browsers": ["chrome"], "databases": ["mysql:5.5"], "extraEnvironment": {}, "cronOnly": False, "filterTags": "not @skip", "logLevel": "2", "notificationsAppNeeded": False, "screenShots": False, "openIdConnect": False, "skip": False, "debugSuites": [], "retry": True, } if "defaults" in config: if "acceptance" in config["defaults"]: for item in config["defaults"]["acceptance"]: default[item] = config["defaults"]["acceptance"][item] for category, matrix in config["acceptance"].items(): if type(matrix["suites"]) == "list": suites = {} for suite in matrix["suites"]: suites[suite] = suite else: suites = matrix["suites"] if "debugSuites" in matrix and len(matrix["debugSuites"]) != 0: if type(matrix["debugSuites"]) == "list": suites = {} for suite in matrix["debugSuites"]: suites[suite] = suite else: suites = matrix["debugSuites"] for key, value in suites.items(): if type(value) == "list": suite = value suiteName = key alternateSuiteName = key else: suite = key alternateSuiteName = value suiteName = value params = {} for item in default: params[item] = matrix[item] if item in matrix else default[item] for server in params["servers"]: for browser in params["browsers"]: for db in params["databases"]: if params["skip"]: continue browserString = "" if browser == "" else "-" + browser serverString = "" if server == "" else "-" + server.replace("daily-", "").replace("-qa", "") name = "%s%s%s" % (suiteName, browserString, serverString) maxLength = 50 nameLength = len(name) if nameLength > maxLength: print("Error: generated stage name of length", nameLength, "is not supported. The maximum length is " + str(maxLength) + ".", name) errorFound = True steps = [] # TODO: don't start services if we skip it -> maybe we need to convert them to steps steps += skipIfUnchanged(ctx, "acceptance-tests") steps += restoreBuildArtifactCache(ctx, "web-dist", "dist") services = browserService(alternateSuiteName, browser) + middlewareService() if ctx.build.event == "cron": steps += restoreBuildArtifactCache(ctx, "ocis", "ocis") else: steps += restoreOcisCache() # Services and steps required for running tests with oCIS steps += ocisService("acceptance-tests", enforce_password_public_link = True) + getSkeletonFiles() # Wait for test-related services to be up steps += waitForBrowserService() steps += waitForMiddlewareService() # run the acceptance tests steps += runWebuiAcceptanceTests(ctx, suite, alternateSuiteName, params["filterTags"], params["extraEnvironment"], params["screenShots"], params["retry"]) # Capture the screenshots from acceptance tests (only runs on failure) if (params["screenShots"]): steps += uploadScreenshots() + logAcceptanceTestsScreenshotsResult(suiteName) result = { "kind": "pipeline", "type": "docker", "name": name, "workspace": { "base": dir["base"], "path": config["app"], }, "steps": steps, "services": services, "trigger": { "ref": [ "refs/tags/**", "refs/pull/**", ], }, "volumes": [{ "name": "uploads", "temp": {}, }, { "name": "configs", "temp": {}, }, { "name": "gopath", "temp": {}, }], } result = pipelineDependsOn(result, cacheOcisPipeline(ctx)) for branch in config["branches"]: result["trigger"]["ref"].append("refs/heads/%s" % branch) if (params["cronOnly"]): result["trigger"]["event"] = ["cron"] pipelines.append(result) if errorFound: return False return pipelines def notify(): pipelines = [] result = { "kind": "pipeline", "type": "docker", "name": "chat-notifications", "clone": { "disable": True, }, "steps": [ { "name": "notify-rocketchat", "image": PLUGINS_SLACK, "settings": { "webhook": { "from_secret": config["rocketchat"]["from_secret"], }, "channel": config["rocketchat"]["channel"], }, }, ], "trigger": { "ref": [ "refs/tags/**", ], "status": [ "success", "failure", ], }, } for branch in config["branches"]: result["trigger"]["ref"].append("refs/heads/%s" % branch) pipelines.append(result) return pipelines def browserService(alternateSuiteName, browser): if browser == "chrome": return [{ "name": "selenium", "image": SELENIUM_STANDALONE_CHROME, "volumes": [{ "name": "uploads", "path": "/uploads", }], }] if browser == "firefox": return [{ "name": "selenium", "image": SELENIUM_STANDALONE_FIREFOX, "volumes": [{ "name": "uploads", "path": "/uploads", }], }] return [] def waitForBrowserService(): return [{ "name": "wait-for-browser-service", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it selenium:4444 -t 300", ], }] def installPnpm(): return [{ "name": "pnpm-install", "image": OC_CI_NODEJS, "commands": [ 'npm install --silent --global --force "$(jq -r ".packageManager" < package.json)"', "pnpm config set store-dir ./.pnpm-store", "pnpm install", ], }] def installPlaywright(): return [{ "name": "playwright-install", "image": OC_CI_NODEJS, "environment": { "PLAYWRIGHT_BROWSERS_PATH": ".playwright", }, "commands": [ "pnpm exec playwright install --with-deps", ], }] def lint(): return [{ "name": "lint", "image": OC_CI_NODEJS, "commands": [ "pnpm lint", ], }] def buildDockerImage(): return [{ "name": "docker", "image": PLUGINS_DOCKER, "settings": { "username": { "from_secret": "docker_username", }, "password": { "from_secret": "docker_password", }, "auto_tag": True, "dockerfile": "docker/Dockerfile", "repo": "owncloud/web", }, "when": { "ref": { "exclude": [ "refs/pull/**", ], }, }, }] def determineReleasePackage(ctx): if ctx.build.event != "tag": return None matches = [p for p in WEB_PUBLISH_NPM_PACKAGES if ctx.build.ref.startswith("refs/tags/%s-v" % p)] if len(matches) > 0: return matches[0] return None def determineReleaseVersion(ctx): package = determineReleasePackage(ctx) if package == None: return ctx.build.ref.replace("refs/tags/v", "") return ctx.build.ref.replace("refs/tags/" + package + "-v", "") def buildRelease(ctx): steps = [] package = determineReleasePackage(ctx) version = determineReleaseVersion(ctx) if package == None: steps += [ { "name": "make", "image": OC_CI_NODEJS, "environment": { "NO_INSTALL": "true", }, "commands": [ "cd %s" % dir["web"], "make -f Makefile.release", ], }, { "name": "changelog", "image": TOOLHIPPIE_CALENS, "commands": [ "calens --version %s -o dist/CHANGELOG.md -t changelog/CHANGELOG-Release.tmpl" % version.split("-")[0], ], "when": { "ref": [ "refs/tags/**", ], }, }, { "name": "publish", "image": PLUGINS_GITHUB_RELEASE, "settings": { "api_key": { "from_secret": "github_token", }, "files": [ "release/*", ], "checksum": [ "md5", "sha256", ], "title": ctx.build.ref.replace("refs/tags/v", ""), "note": "dist/CHANGELOG.md", "overwrite": True, }, "when": { "ref": [ "refs/tags/**", ], }, }, ] else: steps.append( { "name": "publish", "image": OC_CI_NODEJS, "environment": { "NPM_TOKEN": { "from_secret": "npm_token", }, }, "commands": [ "echo " + package + " " + version, "[ \"$(jq -r '.version' < packages/%s/package.json)\" = \"%s\" ] || (echo \"git tag does not match version in packages/%s/package.json\"; exit 1)" % (package, version, package), "git checkout .", "git clean -fd", "git diff", "git status", # until https://github.com/pnpm/pnpm/issues/5775 is resolved, we print pnpm whoami because that fails when the npm_token is invalid "env \"npm_config_//registry.npmjs.org/:_authToken=$${NPM_TOKEN}\" pnpm whoami", "env \"npm_config_//registry.npmjs.org/:_authToken=$${NPM_TOKEN}\" pnpm publish --no-git-checks --filter %s --access public --tag latest" % ("%s/%s" % (WEB_PUBLISH_NPM_ORGANIZATION, package)), ], "when": { "ref": [ "refs/tags/**", ], }, }, ) return steps def documentation(ctx): return [ { "kind": "pipeline", "type": "docker", "name": "documentation", "platform": { "os": "linux", "arch": "amd64", }, "steps": [ { "name": "prepare", "image": OC_CI_ALPINE, "commands": [ "make docs-copy", ], }, { "name": "test", "image": OC_CI_HUGO, "commands": [ "cd hugo", "hugo", ], }, { "name": "list", "image": OC_CI_ALPINE, "commands": [ "tree hugo/public", ], }, { "name": "publish", "image": PLUGINS_GH_PAGES, "settings": { "username": { "from_secret": "github_username", }, "password": { "from_secret": "github_token", }, "pages_directory": "docs/", "copy_contents": "true", "target_branch": "docs", "delete": "true", }, "when": { "ref": { "exclude": [ "refs/pull/**", ], }, }, }, ], "trigger": { "ref": [ "refs/heads/master", "refs/pull/**", ], }, }, ] def getSkeletonFiles(): return [{ "name": "setup-skeleton-files", "image": OC_CI_PHP, "commands": [ "git clone https://github.com/owncloud/testing.git /srv/app/testing", ], "volumes": [{ "name": "gopath", "path": dir["app"], }], }] def webService(): return [{ "name": "web", "image": OC_CI_PHP, "environment": { "APACHE_WEBROOT": "%s/dist" % dir["web"], "APACHE_LOGGING_PATH": "/dev/null", }, "commands": [ "mkdir -p %s/dist" % dir["web"], "/usr/local/bin/apachectl -D FOREGROUND", ], }] def ocisService(type, tika_enabled = False, enforce_password_public_link = False): environment = { "IDM_ADMIN_PASSWORD": "admin", # override the random admin password from `ocis init` "OCIS_INSECURE": "true", "OCIS_LOG_LEVEL": "error", "OCIS_URL": "https://ocis:9200", "LDAP_GROUP_SUBSTRING_FILTER_TYPE": "any", "LDAP_USER_SUBSTRING_FILTER_TYPE": "any", "PROXY_ENABLE_BASIC_AUTH": True, "WEB_ASSET_CORE_PATH": "%s/dist" % dir["web"], "FRONTEND_SEARCH_MIN_LENGTH": "2", "FRONTEND_OCS_ENABLE_DENIALS": True, "OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST": "%s/tests/drone/banned-passwords.txt" % dir["web"], } if type == "keycloak": environment["PROXY_AUTOPROVISION_ACCOUNTS"] = "true" environment["PROXY_ROLE_ASSIGNMENT_DRIVER"] = "oidc" environment["OCIS_OIDC_ISSUER"] = "https://keycloak:8443/realms/oCIS" environment["PROXY_OIDC_REWRITE_WELLKNOWN"] = "true" environment["WEB_OIDC_CLIENT_ID"] = "web" environment["PROXY_USER_OIDC_CLAIM"] = "preferred_username" environment["PROXY_USER_CS3_CLAIM"] = "username" environment["OCIS_ADMIN_USER_ID"] = "" environment["OCIS_EXCLUDE_RUN_SERVICES"] = "idp" environment["GRAPH_ASSIGN_DEFAULT_USER_ROLE"] = "false" environment["GRAPH_USERNAME_MATCH"] = "none" # TODO: after ocis issue is fixed # - use config from dir["ocisConfig"] # - remove config file from dir["webKeycloakConfig"] # issue: https://github.com/owncloud/ocis/issues/8703 environment["WEB_UI_CONFIG_FILE"] = "%s" % dir["webKeycloakConfig"] elif type == "app-provider": environment["GATEWAY_GRPC_ADDR"] = "0.0.0.0:9142" environment["MICRO_REGISTRY"] = "nats-js-kv" environment["MICRO_REGISTRY_ADDRESS"] = "0.0.0.0:9233" environment["NATS_NATS_HOST"] = "0.0.0.0" environment["NATS_NATS_PORT"] = 9233 else: environment["WEB_UI_CONFIG_FILE"] = "%s" % dir["ocisConfig"] if tika_enabled: environment["FRONTEND_FULL_TEXT_SEARCH_ENABLED"] = True environment["SEARCH_EXTRACTOR_TYPE"] = "tika" environment["SEARCH_EXTRACTOR_TIKA_TIKA_URL"] = "http://tika:9998" environment["SEARCH_EXTRACTOR_CS3SOURCE_INSECURE"] = True if enforce_password_public_link: environment["OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD"] = False environment["FRONTEND_PASSWORD_POLICY_MIN_CHARACTERS"] = 0 environment["FRONTEND_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS"] = 0 environment["FRONTEND_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS"] = 0 environment["FRONTEND_PASSWORD_POLICY_MIN_DIGITS"] = 0 environment["FRONTEND_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS"] = 0 return [ { "name": "ocis", "image": OC_CI_GOLANG, "detach": True, "environment": environment, "commands": [ "mkdir -p %s" % dir["ocisRevaDataRoot"], "mkdir -p /srv/app/tmp/ocis/storage/users/", "./ocis init", "cp %s/tests/drone/app-registry.yaml /root/.ocis/config/app-registry.yaml" % dir["web"], "./ocis server", ], "volumes": [{ "name": "gopath", "path": dir["app"], }, { "name": "ocis-config", "path": "/root/.ocis/config", }], }, { "name": "wait-for-ocis-server", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it ocis:9200 -t 300", ], }, ] def checkForExistingOcisCache(ctx): web_repo_path = "https://raw.githubusercontent.com/owncloud/web/%s" % ctx.build.commit return [ { "name": "check-for-existing-cache", "image": MINIO_MC, "environment": minio_mc_environment, "commands": [ "curl -o .drone.env %s/.drone.env" % web_repo_path, "curl -o check-oCIS-cache.sh %s/tests/drone/check-oCIS-cache.sh" % web_repo_path, ". ./.drone.env", "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", "mc ls --recursive s3/$CACHE_BUCKET/ocis-build", "bash check-oCIS-cache.sh", ], }, ] def copyFilesForUpload(): return [{ "name": "copy-files-for-upload", "image": OC_CI_PHP, "volumes": [{ "name": "uploads", "path": "/filesForUpload", }], "commands": [ "ls -la /filesForUpload", "cp -a %s/tests/e2e/filesForUpload/. /filesForUpload" % dir["web"], "ls -la /filesForUpload", ], }] def runWebuiAcceptanceTests(ctx, suite, alternateSuiteName, filterTags, extraEnvironment, screenShots, retry): environment = {} if (filterTags != ""): environment["TEST_TAGS"] = filterTags environment["LOCAL_UPLOAD_DIR"] = "/uploads" if type(suite) == "list": paths = "" for path in suite: paths = paths + "features/" + path + " " environment["TEST_PATHS"] = paths elif (suite != "all"): environment["TEST_CONTEXT"] = suite if (ctx.build.event == "cron") or (not retry): environment["RERUN_FAILED_WEBUI_SCENARIOS"] = "false" if (screenShots): environment["SCREENSHOTS"] = "true" environment["SERVER_HOST"] = "http://web" environment["BACKEND_HOST"] = "http://owncloud" environment["COMMENTS_FILE"] = "%s" % dir["commentsFile"] environment["MIDDLEWARE_HOST"] = "http://middleware:3000" environment["REMOTE_UPLOAD_DIR"] = "/usr/src/app/filesForUpload" environment["WEB_UI_CONFIG_FILE"] = "%s/dist/config.json" % dir["web"] for env in extraEnvironment: environment[env] = extraEnvironment[env] return restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + installPnpm() + [{ "name": "webui-acceptance-tests", "image": OC_CI_NODEJS, "environment": environment, "commands": [ "cd %s/tests/acceptance && ./run.sh" % dir["web"], ], "volumes": [{ "name": "gopath", "path": dir["app"], }], }] def cacheOcisPipeline(ctx): steps = [] if ctx.build.event == "cron": steps = getOcislatestCommitId(ctx) + \ buildOcis() + \ rebuildBuildArtifactCache(ctx, "ocis", "ocis") else: steps = checkForExistingOcisCache(ctx) + \ buildOcis() + \ cacheOcis() return [{ "kind": "pipeline", "type": "docker", "name": "cache-ocis", "workspace": web_workspace, "clone": { "disable": True, }, "steps": steps, "volumes": [{ "name": "gopath", "temp": {}, }], "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, }] def restoreOcisCache(): return [{ "name": "restore-ocis-cache", "image": MINIO_MC, "environment": minio_mc_environment, "commands": [ ". ./.drone.env", "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", "mc cp -r -a s3/$CACHE_BUCKET/ocis-build/$OCIS_COMMITID/ocis %s" % dir["web"], ], }] def buildOcis(): ocis_repo_url = "https://github.com/owncloud/ocis.git" return [ { "name": "clone-ocis", "image": OC_CI_GOLANG, "commands": [ "source .drone.env", # NOTE: it is important to not start repo name with ocis* # because we copy ocis binary to root workspace # and upload binary <workspace>/ocis to cache bucket. # This prevents accidental upload of ocis repo to the cache "git clone -b $OCIS_BRANCH --single-branch %s repo_ocis" % ocis_repo_url, "cd repo_ocis", "git checkout $OCIS_COMMITID", ], "volumes": go_step_volumes, }, { "name": "generate-ocis", "image": OC_CI_NODEJS, "commands": [ "cd repo_ocis", "retry -t 3 'make ci-node-generate'", ], "volumes": go_step_volumes, }, { "name": "build-ocis", "image": OC_CI_GOLANG, "commands": [ "source .drone.env", "cd repo_ocis/ocis", "retry -t 3 'make build'", "cp bin/ocis %s" % dir["web"], ], "volumes": go_step_volumes, }, ] def cacheOcis(): return [{ "name": "upload-ocis-cache", "image": MINIO_MC, "environment": minio_mc_environment, "commands": [ ". ./.drone.env", "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", "mc cp -a %s/ocis s3/$CACHE_BUCKET/ocis-build/$OCIS_COMMITID/" % dir["web"], "mc ls --recursive s3/$CACHE_BUCKET/ocis-build", ], }] def uploadScreenshots(): return [{ "name": "upload-screenshots", "image": PLUGINS_S3, "pull": "if-not-exists", "settings": { "bucket": { "from_secret": "cache_public_s3_bucket", }, "endpoint": { "from_secret": "cache_public_s3_server", }, "path_style": True, "source": "%s/tests/acceptance/reports/screenshots/**/*" % dir["web"], "strip_prefix": "%s/tests/acceptance/reports/screenshots" % dir["web"], "target": "/${DRONE_REPO}/${DRONE_BUILD_NUMBER}/screenshots", }, "environment": { "AWS_ACCESS_KEY_ID": { "from_secret": "cache_public_s3_access_key", }, "AWS_SECRET_ACCESS_KEY": { "from_secret": "cache_public_s3_secret_key", }, }, "when": { "status": [ "failure", ], "event": [ "pull_request", ], }, }] def example_deploys(ctx): on_merge_deploy = [ "ocis_web/latest.yml", ] nightly_deploy = [ "ocis_web/daily.yml", ] # if on master branch: configs = on_merge_deploy rebuild = "false" if ctx.build.event == "tag": configs = nightly_deploy rebuild = "false" if ctx.build.event == "cron": configs = on_merge_deploy + nightly_deploy rebuild = "true" deploys = [] for config in configs: deploys.append(deploy(ctx, config, rebuild)) return deploys def deploy(ctx, config, rebuild): return { "kind": "pipeline", "type": "docker", "name": "deploy_%s" % (config), "platform": { "os": "linux", "arch": "amd64", }, "steps": [ { "name": "clone continuous deployment playbook", "image": ALPINE_GIT, "commands": [ "cd deployments/continuous-deployment-config", "git clone https://github.com/owncloud-devops/continuous-deployment.git", ], }, { "name": "deploy", "image": OC_CI_DRONE_ANSIBLE, "failure": "ignore", "environment": { "CONTINUOUS_DEPLOY_SERVERS_CONFIG": "../%s" % (config), "REBUILD": "%s" % (rebuild), "HCLOUD_API_TOKEN": { "from_secret": "hcloud_api_token", }, "CLOUDFLARE_API_TOKEN": { "from_secret": "cloudflare_api_token", }, }, "settings": { "playbook": "deployments/continuous-deployment-config/continuous-deployment/playbook-all.yml", "galaxy": "deployments/continuous-deployment-config/continuous-deployment/requirements.yml", "requirements": "deployments/continuous-deployment-config/continuous-deployment/py-requirements.txt", "inventory": "localhost", "private_key": { "from_secret": "ssh_private_key", }, }, }, ], "trigger": { "ref": [ "refs/heads/master", ], }, } def checkStarlark(): return [{ "kind": "pipeline", "type": "docker", "name": "check-starlark", "steps": [ { "name": "format-check-starlark", "image": OC_CI_BAZEL_BUILDIFIER, "commands": [ "buildifier --mode=check .drone.star", ], }, { "name": "show-diff", "image": OC_CI_BAZEL_BUILDIFIER, "commands": [ "buildifier --mode=fix .drone.star", "git diff", ], "when": { "status": [ "failure", ], }, }, ], "trigger": { "ref": [ "refs/pull/**", ], }, }] def licenseCheck(ctx): return [{ "kind": "pipeline", "type": "docker", "name": "license-check", "platform": { "os": "linux", "arch": "amd64", }, "steps": installPnpm() + [ { "name": "node-check-licenses", "image": OC_CI_NODEJS, "commands": [ "pnpm licenses:check", ], }, { "name": "node-save-licenses", "image": OC_CI_NODEJS, "commands": [ "pnpm licenses:csv", "pnpm licenses:save", ], }, ], "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, }] def checkTestSuitesInExpectedFailures(ctx): return [{ "kind": "pipeline", "type": "docker", "name": "check-suites-in-expected-failures", "workspace": { "base": dir["base"], "path": config["app"], }, "steps": [ { "name": "check-suites", "image": OC_CI_ALPINE, "commands": [ "%s/tests/acceptance/check-deleted-suites-in-expected-failure.sh" % dir["web"], ], }, ], "trigger": { "ref": [ "refs/pull/**", ], }, }] def middlewareService(): environment = { "BACKEND_HOST": "https://ocis:9200", "OCIS_REVA_DATA_ROOT": "/srv/app/tmp/ocis/storage/owncloud/", "RUN_ON_OCIS": "true", "REMOTE_UPLOAD_DIR": "/uploads", "NODE_TLS_REJECT_UNAUTHORIZED": "0", "MIDDLEWARE_HOST": "middleware", "TEST_WITH_GRAPH_API": "true", } return [{ "name": "middleware", "image": OC_TESTING_MIDDLEWARE, "environment": environment, "volumes": [{ "name": "gopath", "path": dir["app"], }, { "name": "uploads", "path": "/uploads", }], }] def waitForMiddlewareService(): return [{ "name": "wait-for-middleware-service", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it middleware:3000 -t 300", ], }] def pipelineDependsOn(pipeline, dependant_pipelines): if "depends_on" in pipeline.keys(): pipeline["depends_on"] = pipeline["depends_on"] + getPipelineNames(dependant_pipelines) else: pipeline["depends_on"] = getPipelineNames(dependant_pipelines) return pipeline def pipelinesDependsOn(pipelines, dependant_pipelines): pipes = [] for pipeline in pipelines: pipes.append(pipelineDependsOn(pipeline, dependant_pipelines)) return pipes def getPipelineNames(pipelines = []): """getPipelineNames returns names of pipelines as a string array Args: pipelines: array of drone pipelines Returns: names of the given pipelines as string array """ names = [] for pipeline in pipelines: names.append(pipeline["name"]) return names def skipIfUnchanged(ctx, type): if ("full-ci" in ctx.build.title.lower()): return [] skip_step = { "name": "skip-if-unchanged", "image": OC_CI_DRONE_SKIP_PIPELINE, "when": { "event": [ "pull_request", ], }, } base_skip_steps = [ "^.github/.*", "^changelog/.*", "^config/.*", "^deployments/.*", "^dev/.*", "^docs/.*", "^packages/web-app-skeleton/.*", "README.md", ] if type == "cache" or type == "lint": skip_step["settings"] = { "ALLOW_SKIP_CHANGED": base_skip_steps, } return [skip_step] if type == "acceptance-tests": acceptance_skip_steps = [ "^__fixtures__/.*", "^__mocks__/.*", "^packages/.*/tests/.*", "^tests/e2e/.*", "^tests/unit/.*", ] skip_step["settings"] = { "ALLOW_SKIP_CHANGED": base_skip_steps + acceptance_skip_steps, } return [skip_step] if type == "e2e-tests": e2e_skip_steps = [ "^__fixtures__/.*", "^__mocks__/.*", "^packages/.*/tests/.*", "^tests/acceptance/.*", "^tests/unit/.*", ] skip_step["settings"] = { "ALLOW_SKIP_CHANGED": base_skip_steps + e2e_skip_steps, } return [skip_step] if type == "unit-tests": unit_skip_steps = [ "^tests/acceptance/.*", ] skip_step["settings"] = { "ALLOW_SKIP_CHANGED": base_skip_steps + unit_skip_steps, } return [skip_step] return [] def genericCache(name, action, mounts, cache_path): rebuild = "false" restore = "false" if action == "rebuild": rebuild = "true" action = "rebuild" else: restore = "true" action = "restore" step = { "name": "%s_%s" % (action, name), "image": PLUGINS_S3_CACHE, "settings": { "endpoint": { "from_secret": "cache_s3_server", }, "rebuild": rebuild, "restore": restore, "mount": mounts, "access_key": { "from_secret": "cache_s3_access_key", }, "secret_key": { "from_secret": "cache_s3_secret_key", }, "filename": "%s.tar" % (name), "path": cache_path, "fallback_path": cache_path, }, } return step def genericCachePurge(flush_path): return { "kind": "pipeline", "type": "docker", "name": "purge_build_artifact_cache", "clone": { "disable": True, }, "platform": { "os": "linux", "arch": "amd64", }, "steps": [ { "name": "purge-cache", "image": PLUGINS_S3_CACHE, "settings": { "access_key": { "from_secret": "cache_s3_access_key", }, "endpoint": { "from_secret": "cache_s3_server", }, "secret_key": { "from_secret": "cache_s3_secret_key", }, "flush": True, "flush_age": 1, "flush_path": flush_path, }, }, ], "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], "status": [ "success", "failure", ], }, } def genericBuildArtifactCache(ctx, name, action, path): if action == "rebuild" or action == "restore": cache_path = "%s/%s/%s" % ("cache", ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}") name = "%s_build_artifact_cache" % (name) return genericCache(name, action, [path], cache_path) if action == "purge": flush_path = "%s/%s" % ("cache", ctx.repo.slug) return genericCachePurge(flush_path) return [] def restoreBuildArtifactCache(ctx, name, path): return [genericBuildArtifactCache(ctx, name, "restore", path)] def rebuildBuildArtifactCache(ctx, name, path): return [genericBuildArtifactCache(ctx, name, "rebuild", path)] def purgeBuildArtifactCache(ctx): return genericBuildArtifactCache(ctx, "", "purge", []) def pipelineSanityChecks(ctx, pipelines): """pipelineSanityChecks helps the CI developers to find errors before running it These sanity checks are only executed on when converting starlark to yaml. Error outputs are only visible when the conversion is done with the drone cli. Args: ctx: drone passes a context with information which the pipeline can be adapted to pipelines: pipelines to be checked, normally you should run this on the return value of main() Returns: none """ # check if name length of pipeline and steps are exceeded. max_name_length = 50 for pipeline in pipelines: pipeline_name = pipeline["name"] if len(pipeline_name) > max_name_length: print("Error: pipeline name %s is longer than 50 characters" % (pipeline_name)) for step in pipeline["steps"]: step_name = step["name"] if len(step_name) > max_name_length: print("Error: step name %s in pipeline %s is longer than 50 characters" % (step_name, pipeline_name)) # check for non existing depends_on possible_depends = [] for pipeline in pipelines: possible_depends.append(pipeline["name"]) for pipeline in pipelines: if "depends_on" in pipeline.keys(): for depends in pipeline["depends_on"]: if not depends in possible_depends: print("Error: depends_on %s for pipeline %s is not defined" % (depends, pipeline["name"])) # check for non declared volumes for pipeline in pipelines: pipeline_volumes = [] if "volumes" in pipeline.keys(): for volume in pipeline["volumes"]: pipeline_volumes.append(volume["name"]) for step in pipeline["steps"]: if "volumes" in step.keys(): for volume in step["volumes"]: if not volume["name"] in pipeline_volumes: print("Warning: volume %s for step %s is not defined in pipeline %s" % (volume["name"], step["name"], pipeline["name"])) # list used docker images print("") print("List of used docker images:") images = {} for pipeline in pipelines: for step in pipeline["steps"]: image = step["image"] if image in images.keys(): images[image] = images[image] + 1 else: images[image] = 1 for image in images.keys(): print(" %sx\t%s" % (images[image], image)) def logAcceptanceTestsScreenshotsResult(suite): return [{ "name": "log-acceptance-tests-screenshot", "image": OC_UBUNTU, "commands": [ "cd %s/tests/acceptance/reports/screenshots/" % dir["web"], 'echo "To see the screenshots, please visit the following path"', 'for f in *.png; do echo "### $f\n" \'!\'"(https://cache.owncloud.com/public/${DRONE_REPO}/${DRONE_BUILD_NUMBER}/screenshots/$f) \n"; done', ], "when": { "status": [ "failure", ], "event": [ "pull_request", ], }, }] def uploadTracingResult(ctx): status = ["failure"] if ("with-tracing" in ctx.build.title.lower()): status = ["failure", "success"] return [{ "name": "upload-tracing-result", "image": PLUGINS_S3, "pull": "if-not-exists", "settings": { "bucket": { "from_secret": "cache_public_s3_bucket", }, "endpoint": { "from_secret": "cache_public_s3_server", }, "path_style": True, "source": "%s/reports/e2e/playwright/tracing/**/*" % dir["web"], "strip_prefix": "%s/reports/e2e/playwright/tracing" % dir["web"], "target": "/${DRONE_REPO}/${DRONE_BUILD_NUMBER}/tracing", }, "environment": { "AWS_ACCESS_KEY_ID": { "from_secret": "cache_public_s3_access_key", }, "AWS_SECRET_ACCESS_KEY": { "from_secret": "cache_public_s3_secret_key", }, }, "when": { "status": status, "event": [ "pull_request", "cron", ], }, }] def logTracingResult(ctx, suite): status = ["failure"] if ("with-tracing" in ctx.build.title.lower()): status = ["failure", "success"] return [{ "name": "log-tracing-result", "image": OC_UBUNTU, "commands": [ "cd %s/reports/e2e/playwright/tracing/" % dir["web"], 'echo "To see the trace, please open the following link in the console"', 'for f in *.zip; do echo "npx playwright show-trace https://cache.owncloud.com/public/${DRONE_REPO}/${DRONE_BUILD_NUMBER}/tracing/$f \n"; done', ], "when": { "status": status, "event": [ "pull_request", "cron", ], }, }] def tikaService(): return [ { "name": "tika", "type": "docker", "image": APACHE_TIKA, "detach": True, }, { "name": "wait-for-tika-service", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it tika:9998 -t 300", ], }, ] def wopiServer(): return [ { "name": "wopiserver", "type": "docker", "image": "cs3org/wopiserver:v10.3.0", "detach": True, "commands": [ "echo 'LoremIpsum567' > /etc/wopi/wopisecret", "cp %s/tests/drone/wopiserver/wopiserver.conf /etc/wopi/wopiserver.conf" % dir["web"], "/app/wopiserver.py", ], }, { "name": "wait-for-wopi-server", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it wopiserver:8880 -t 300", ], }, ] def collaboraService(): return [ { "name": "collabora", "type": "docker", "image": "collabora/code:23.05.6.5.1", "detach": True, "environment": { "DONT_GEN_SSL_CERT": "set", "extra_params": "--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=https://ocis:9200", }, }, { "name": "wait-for-collabora-service", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it collabora:9980 -t 300", ], }, ] def onlyofficeService(): return [ { "name": "onlyoffice", "type": "docker", "image": "onlyoffice/documentserver:7.5.1", "detach": True, "environment": { "WOPI_ENABLED": "true", "USE_UNAUTHORIZED_STORAGE": "true", # self signed certificates }, "commands": [ "cp %s/tests/drone/onlyoffice/local.json /etc/onlyoffice/documentserver/local.json" % dir["web"], "openssl req -x509 -newkey rsa:4096 -keyout onlyoffice.key -out onlyoffice.crt -sha256 -days 365 -batch -nodes", "mkdir -p /var/www/onlyoffice/Data/certs", "cp onlyoffice.key /var/www/onlyoffice/Data/certs/", "cp onlyoffice.crt /var/www/onlyoffice/Data/certs/", "chmod 400 /var/www/onlyoffice/Data/certs/onlyoffice.key", "/app/ds/run-document-server.sh", ], }, { "name": "wait-for-onlyoffice-service", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it onlyoffice:443 -t 300", ], }, ] def appProviderService(name): environment = { "APP_PROVIDER_LOG_LEVEL": "error", "REVA_GATEWAY": "com.owncloud.api.gateway", "APP_PROVIDER_GRPC_ADDR": "0.0.0.0:9164", "APP_PROVIDER_DRIVER": "wopi", "APP_PROVIDER_WOPI_INSECURE": True, "APP_PROVIDER_WOPI_WOPI_SERVER_EXTERNAL_URL": "http://wopiserver:8880", "APP_PROVIDER_WOPI_FOLDER_URL_BASE_URL": "https://ocis:9200", "MICRO_REGISTRY": "nats-js-kv", "MICRO_REGISTRY_ADDRESS": "ocis:9233", } if name == "collabora": environment["APP_PROVIDER_SERVICE_NAME"] = "app-provider-collabora" environment["APP_PROVIDER_EXTERNAL_ADDR"] = "com.owncloud.api.app-provider-collabora" environment["APP_PROVIDER_WOPI_APP_NAME"] = "Collabora" environment["APP_PROVIDER_WOPI_APP_ICON_URI"] = "https://collabora:9980/favicon.ico" environment["APP_PROVIDER_WOPI_APP_URL"] = "https://collabora:9980" elif name == "onlyoffice": environment["APP_PROVIDER_SERVICE_NAME"] = "app-provider-onlyoffice" environment["APP_PROVIDER_EXTERNAL_ADDR"] = "com.owncloud.api.app-provider-onlyoffice" environment["APP_PROVIDER_WOPI_APP_NAME"] = "OnlyOffice" environment["APP_PROVIDER_WOPI_APP_ICON_URI"] = "https://onlyoffice/web-apps/apps/documenteditor/main/resources/img/favicon.ico" environment["APP_PROVIDER_WOPI_APP_URL"] = "https://onlyoffice" return [ { "name": "%s-app-provider" % name, "image": OC_CI_GOLANG, "detach": True, "environment": environment, "commands": [ "./ocis app-provider server", ], "volumes": [ { "name": "gopath", "path": dir["app"], }, { "name": "ocis-config", "path": "/root/.ocis/config", }, ], }, ] def buildDesignSystemDocs(): return [{ "name": "build-design-system-docs", "image": OC_CI_NODEJS, "commands": [ "pnpm --filter @ownclouders/design-system build:docs", ], }] def runDesignSystemDocsE2eTests(): return [{ "name": "run-design-system-docs-e2e-tests", "image": OC_CI_NODEJS, "environment": { "PLAYWRIGHT_BROWSERS_PATH": ".playwright", }, "commands": [ "pnpm --filter @ownclouders/design-system test:e2e", ], }] def buildAndTestDesignSystem(ctx): design_system_trigger = { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], } steps = restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + \ restoreBuildArtifactCache(ctx, "playwright", ".playwright") + \ installPnpm() + \ installPlaywright() + \ buildDesignSystemDocs() + \ runDesignSystemDocsE2eTests() return [{ "kind": "pipeline", "type": "docker", "name": "design-system-build-and-test", "workspace": { "base": dir["base"], "path": config["app"], }, "steps": steps, "trigger": design_system_trigger, }] def postgresService(): return [ { "name": "postgres", "image": POSTGRES_ALPINE, "environment": { "POSTGRES_DB": "keycloak", "POSTGRES_USER": "keycloak", "POSTGRES_PASSWORD": "keycloak", }, }, ] def keycloakService(): return [ { "name": "generate-keycloak-certs", "image": OC_CI_NODEJS, "commands": [ "mkdir -p keycloak-certs", "openssl req -x509 -newkey rsa:2048 -keyout keycloak-certs/keycloakkey.pem -out keycloak-certs/keycloakcrt.pem -nodes -days 365 -subj '/CN=keycloak'", "chmod -R 777 keycloak-certs", ], "volumes": [ { "name": "certs", "path": "/keycloak-certs", }, ], }, { "name": "wait-for-postgres", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it postgres:5432 -t 300", ], }, { "name": "keycloak", "image": KEYCLOAK, "detach": True, "environment": { "OCIS_DOMAIN": "ocis:9200", "KC_HOSTNAME": "keycloak:8443", "KC_DB": "postgres", "KC_DB_URL": "jdbc:postgresql://postgres:5432/keycloak", "KC_DB_USERNAME": "keycloak", "KC_DB_PASSWORD": "keycloak", "KC_FEATURES": "impersonation", "KEYCLOAK_ADMIN": "admin", "KEYCLOAK_ADMIN_PASSWORD": "admin", "KC_HTTPS_CERTIFICATE_FILE": "./keycloak-certs/keycloakcrt.pem", "KC_HTTPS_CERTIFICATE_KEY_FILE": "./keycloak-certs/keycloakkey.pem", }, "commands": [ "mkdir -p /opt/keycloak/data/import", "cp tests/drone/ocis_keycloak/ocis-ci-realm.dist.json /opt/keycloak/data/import/ocis-realm.json", "/opt/keycloak/bin/kc.sh start-dev --proxy=edge --spi-connections-http-client-default-disable-trust-manager=true --import-realm --health-enabled=true", ], "volumes": [ { "name": "certs", "path": "/keycloak-certs", }, ], }, { "name": "wait-for-keycloak", "image": OC_CI_WAIT_FOR, "commands": [ "wait-for -it keycloak:8443 -t 300", ], }, ] def e2eTestsOnKeycloak(ctx): e2e_volumes = [ { "name": "uploads", "temp": {}, }, { "name": "configs", "temp": {}, }, { "name": "gopath", "temp": {}, }, { "name": "ocis-config", "temp": {}, }, { "name": "certs", "temp": {}, }, ] if not "full-ci" in ctx.build.title.lower() and ctx.build.event != "cron": return [] steps = restoreBuildArtifactCache(ctx, "pnpm", ".pnpm-store") + \ restoreBuildArtifactCache(ctx, "playwright", ".playwright") + \ installPnpm() + \ installPlaywright() + \ keycloakService() + \ restoreBuildArtifactCache(ctx, "web-dist", "dist") if ctx.build.event == "cron": steps += restoreBuildArtifactCache(ctx, "ocis", "ocis") else: steps += restoreOcisCache() steps += ocisService("keycloak") + \ [ { "name": "e2e-tests", "image": OC_CI_NODEJS, "environment": { "BASE_URL_OCIS": "ocis:9200", "HEADLESS": "true", "RETRY": "1", "REPORT_TRACING": "true", "KEYCLOAK": "true", "KEYCLOAK_HOST": "keycloak:8443", }, "commands": [ "pnpm test:e2e:cucumber tests/e2e/cucumber/features/journeys", ], }, ] + \ uploadTracingResult(ctx) + \ logTracingResult(ctx, "e2e-tests keycloack-journey-suite") return [{ "kind": "pipeline", "type": "docker", "name": "e2e-test-on-keycloak", "workspace": web_workspace, "steps": steps, "services": postgresService(), "volumes": e2e_volumes, "trigger": { "ref": [ "refs/heads/master", "refs/heads/stable-*", "refs/tags/**", "refs/pull/**", ], }, }] def getOcislatestCommitId(ctx): web_repo_path = "https://raw.githubusercontent.com/owncloud/web/%s" % ctx.build.commit return [ { "name": "get-ocis-latest-commit-id", "image": OC_CI_ALPINE, "commands": [ "curl -o .drone.env %s/.drone.env" % web_repo_path, "curl -o get-latest-ocis-commit-id.sh %s/tests/drone/get-latest-ocis-commit-id.sh" % web_repo_path, ". ./.drone.env", "bash get-latest-ocis-commit-id.sh", ], }, ]
owncloud/web/.drone.star/0
{ "file_path": "owncloud/web/.drone.star", "repo_id": "owncloud", "token_count": 43108 }
567
module.exports = { presets: ['@ownclouders/babel-preset'] }
owncloud/web/babel.config.cjs/0
{ "file_path": "owncloud/web/babel.config.cjs", "repo_id": "owncloud", "token_count": 25 }
568
Change: Move status indicators under the resource name We've moved the sharing status indicators from an own column in the files list to a second row under the resource name. https://github.com/owncloud/web/pull/3617
owncloud/web/changelog/0.11.0_2020-06-26/move-indicators-under-resource/0
{ "file_path": "owncloud/web/changelog/0.11.0_2020-06-26/move-indicators-under-resource", "repo_id": "owncloud", "token_count": 53 }
569
Change: Don't fallback to appId in case the route of file action is not defined When opening a file in a editor or a viewer the path was falling back to an appId. This made it impossible to navigate via the file actions into an app which doesn't have duplicate appId in the route. We've stopped falling back to this value and in case that the route of the file action is not defined, we use the root path of the app. https://github.com/owncloud/product/issues/69 https://github.com/owncloud/ocis/issues/356 https://github.com/owncloud/web/pull/3740
owncloud/web/changelog/0.12.0_2020-07-10/file-editors-path/0
{ "file_path": "owncloud/web/changelog/0.12.0_2020-07-10/file-editors-path", "repo_id": "owncloud", "token_count": 146 }
570
Change: Get rid of static "Shared with:" label We removed the static "Shared with:" text label in the indicator row of file items. From now on, if a file item has no indicators, it will fall back to the one-row layout (resource name vertically centered). https://github.com/owncloud/product/issues/123 https://github.com/owncloud/web/pull/3808
owncloud/web/changelog/0.14.0_2020-08-17/remove-shared-with/0
{ "file_path": "owncloud/web/changelog/0.14.0_2020-08-17/remove-shared-with", "repo_id": "owncloud", "token_count": 94 }
571
Change: Update ODS to 1.11.0 We updated owncloud design system (ODS) to 1.11.0. This brings some features and required some changes: - Buttons: - require to be placed in a grid or with uk-flex for side by side positioning, - don't have an icon property anymore, - have a slot so that content of the button can be just anything - placement of the content in the button can be modified with new props `justify-content` and `gap` - new icons, which are used in the sidebar and for quick actions - sidebar has a property for hiding the navigation. It doesn't have internal logic anymore for hiding the navigation automatically. https://github.com/owncloud/web/pull/4086
owncloud/web/changelog/0.17.0_2020-09-25/update-ods-1.11.0/0
{ "file_path": "owncloud/web/changelog/0.17.0_2020-09-25/update-ods-1.11.0", "repo_id": "owncloud", "token_count": 184 }
572
Change: App sidebar accordion instead of tabs We replaced the tabs in the right app-sidebar with an accordion. https://github.com/owncloud/web/pull/4249
owncloud/web/changelog/0.23.0_2020-10-30/sidebar-accordion/0
{ "file_path": "owncloud/web/changelog/0.23.0_2020-10-30/sidebar-accordion", "repo_id": "owncloud", "token_count": 45 }
573
Change: Configurable home path We introduced a config.json option `homeFolder` which let's you specify a default location when opening the `All files` view. Please refer to the documentation for details. https://github.com/owncloud/web/pull/4411 https://owncloud.github.io/clients/web/getting-started/
owncloud/web/changelog/0.28.0_2020-12-04/configurable-home-path/0
{ "file_path": "owncloud/web/changelog/0.28.0_2020-12-04/configurable-home-path", "repo_id": "owncloud", "token_count": 81 }
574
Change: Improve UI/UX of collaborator forms Applied several UI/UX improvements to the collaborator forms (adding and editing). - Showing avatars for selected collaborators on a new share and fixed styling/layouting of said collaborators in the list. - Added sensible margins on text about missing permissions for re-sharing in the sharing sidebar. - Fixed alignment of displayed collaborator in editing view for collaborators. - Removed separators from the forms that were cluttering the view. - Moved role description on role selection (links and collaborators) into the form element. Not shown below the form element anymore. https://github.com/owncloud/web/issues/1186
owncloud/web/changelog/0.4.0_2020-02-14/1186-1/0
{ "file_path": "owncloud/web/changelog/0.4.0_2020-02-14/1186-1", "repo_id": "owncloud", "token_count": 145 }
575
Bugfix: Responsive buttons layout in app bar when multiple files are selected We've fixed the responsive buttons layout in files app bar when multiple files are selected where bulk actions where overlapping and height of the buttons was increased. https://github.com/owncloud/web/issues/3011 https://github.com/owncloud/web/pull/3083
owncloud/web/changelog/0.5.0_2020-03-02/3011/0
{ "file_path": "owncloud/web/changelog/0.5.0_2020-03-02/3011", "repo_id": "owncloud", "token_count": 79 }
576
Change: Align columns in file lists to the right We've aligned columns in all file lists to the right so it is easier for the user to compare them. https://github.com/owncloud/web/issues/3036 https://github.com/owncloud/web/pull/3163
owncloud/web/changelog/0.6.0_2020-03-16/3163/0
{ "file_path": "owncloud/web/changelog/0.6.0_2020-03-16/3163", "repo_id": "owncloud", "token_count": 69 }
577
Bugfix: Remove duplicate error display in input prompt Validation errors within the input prompt dialog were showing up twice. One of them is a leftover from the old version. We've fixed the dialog by removing the old validation error type. https://github.com/owncloud/web/pull/3342
owncloud/web/changelog/0.9.0_2020-04-27/3342/0
{ "file_path": "owncloud/web/changelog/0.9.0_2020-04-27/3342", "repo_id": "owncloud", "token_count": 68 }
578
Enhancement: Position of main dom node div#main is now positioned relative, this way child apps are able to orientate their containers absolute to it. https://github.com/owncloud/ocis/issues/1052 https://github.com/owncloud/web/pull/4489 https://github.com/owncloud/owncloud-design-system/pull/1002
owncloud/web/changelog/1.0.0_2020-12-16/main-position/0
{ "file_path": "owncloud/web/changelog/1.0.0_2020-12-16/main-position", "repo_id": "owncloud", "token_count": 90 }
579
Bugfix: NODE_ENV based on rollup mode The NODE_ENV was set to production by default, now we use development if rollup is started in watch mode so that the vue devtools can be used. https://github.com/owncloud/web/issues/4819 https://github.com/owncloud/web/pull/4820
owncloud/web/changelog/2.1.0_2021-03-24/bugfix-node-env/0
{ "file_path": "owncloud/web/changelog/2.1.0_2021-03-24/bugfix-node-env", "repo_id": "owncloud", "token_count": 85 }
580
Enhancement: Runtime theming It's now possible to specify a custom theme and have logos, brand slogan and colors changed to modify the appearance of your ownCloud web frontend. https://github.com/owncloud/web/pull/4822 https://github.com/owncloud/web/issues/2362
owncloud/web/changelog/3.0.0_2021-04-21/enhancement-runtime-theming/0
{ "file_path": "owncloud/web/changelog/3.0.0_2021-04-21/enhancement-runtime-theming", "repo_id": "owncloud", "token_count": 76 }
581
Enhancement: Show search button in search bar https://github.com/owncloud/web/pull/4985
owncloud/web/changelog/3.1.0_2021-05-12/enhancement-show-search-button/0
{ "file_path": "owncloud/web/changelog/3.1.0_2021-05-12/enhancement-show-search-button", "repo_id": "owncloud", "token_count": 28 }
582
Bugfix: Do not call Vuex create store multiple times We've moved the create Vuex store logic into the index file of Web runtime to prevent initialising the store multiple times. https://github.com/owncloud/web/pull/5254
owncloud/web/changelog/3.3.0_2021-06-23/bugfix-remove-vuex-circular-init/0
{ "file_path": "owncloud/web/changelog/3.3.0_2021-06-23/bugfix-remove-vuex-circular-init", "repo_id": "owncloud", "token_count": 58 }
583
Enhancement: Confirmation message when copying links We've added confirmation messages (toasts) when a private or public link is copied to the clipboard. https://github.com/owncloud/web/pull/5147
owncloud/web/changelog/3.3.0_2021-06-23/enhancement-copy-link-toasts/0
{ "file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-copy-link-toasts", "repo_id": "owncloud", "token_count": 51 }
584
Enhancement: Ability to update file resource fields We've introduced the ability to update individual resource fields only instead of updating the whole resource at once. https://github.com/owncloud/web/pull/5311
owncloud/web/changelog/3.3.0_2021-06-23/enhancement-resource-field-update/0
{ "file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-resource-field-update", "repo_id": "owncloud", "token_count": 51 }
585
Enhancement: Batch actions for accepting and declining shares We've added batch actions for accepting and declining multiple selected incoming shares at once. https://github.com/owncloud/web/issues/5204 https://github.com/owncloud/web/pull/5374 https://github.com/owncloud/web/issues/2513 https://github.com/owncloud/web/issues/3101 https://github.com/owncloud/web/issues/5435
owncloud/web/changelog/3.4.0_2021-07-09/enhancement-share-batch-actions/0
{ "file_path": "owncloud/web/changelog/3.4.0_2021-07-09/enhancement-share-batch-actions", "repo_id": "owncloud", "token_count": 112 }
586
Enhancement: Add filter & search to files app We've changed the existing searchbar to use the custom search service. It is now able to be used at the same time as a filter (on the frontend) and, if the backend is capable of search, as a search input. https://github.com/owncloud/web/pull/5415
owncloud/web/changelog/4.0.0_2021-08-04/enhancement-search-filter-files/0
{ "file_path": "owncloud/web/changelog/4.0.0_2021-08-04/enhancement-search-filter-files", "repo_id": "owncloud", "token_count": 83 }
587
Enhancement: Add missing tooltips We've added tooltips to the "view option dropdown" and "toggle sidebar" buttons. https://github.com/owncloud/web/issues/5723 https://github.com/owncloud/web/pull/5724
owncloud/web/changelog/4.2.0_2021-09-14/enhancement-more-tooltips/0
{ "file_path": "owncloud/web/changelog/4.2.0_2021-09-14/enhancement-more-tooltips", "repo_id": "owncloud", "token_count": 63 }
588