text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
import { TabList, Tab } from '@reach/tabs'
import PropTypes from 'prop-types'
export default function SymbolPaletteTabs({ categories }) {
return (
<TabList aria-label="Symbol Categories" className="symbol-palette-tab-list">
{categories.map(category => (
<Tab key={category.id} className="symbol-palette-tab">
{category.label}
</Tab>
))}
</TabList>
)
}
SymbolPaletteTabs.propTypes = {
categories: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
})
).isRequired,
}
| overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-tabs.js/0 | {
"file_path": "overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-tabs.js",
"repo_id": "overleaf",
"token_count": 238
} | 523 |
import App from '../../../base'
export default App.controller(
'BinaryFileController',
function ($scope, $rootScope, $http, $timeout, $element, ide, waitFor) {
const MAX_FILE_SIZE = 2 * 1024 * 1024
const MAX_URL_LENGTH = 60
const FRONT_OF_URL_LENGTH = 35
const FILLER = '...'
const TAIL_OF_URL_LENGTH =
MAX_URL_LENGTH - FRONT_OF_URL_LENGTH - FILLER.length
const textExtensions = window.ExposedSettings.textExtensions
const imageExtensions = ['png', 'jpg', 'jpeg', 'gif']
const previewableExtensions = []
const extension = file => file.name.split('.').pop().toLowerCase()
$scope.isTextFile = () =>
textExtensions.indexOf(extension($scope.openFile)) > -1
$scope.isImageFile = () =>
imageExtensions.indexOf(extension($scope.openFile)) > -1
$scope.isPreviewableFile = () =>
previewableExtensions.indexOf(extension($scope.openFile)) > -1
$scope.isUnpreviewableFile = () =>
!$scope.isTextFile() &&
!$scope.isImageFile() &&
!$scope.isPreviewableFile()
$scope.textPreview = {
loading: false,
shouldShowDots: false,
error: false,
data: null,
}
$scope.refreshing = false
$scope.refreshError = null
$scope.displayUrl = function (url) {
if (url == null) {
return
}
if (url.length > MAX_URL_LENGTH) {
const front = url.slice(0, FRONT_OF_URL_LENGTH)
const tail = url.slice(url.length - TAIL_OF_URL_LENGTH)
return front + FILLER + tail
}
return url
}
$scope.refreshFile = function (file) {
$scope.refreshing = true
$scope.refreshError = null
window.expectingLinkedFileRefreshedSocketFor = file.name
ide.fileTreeManager
.refreshLinkedFile(file)
.then(function (response) {
const { data } = response
const newFileId = data.new_file_id
$timeout(
() =>
waitFor(() => ide.fileTreeManager.findEntityById(newFileId), 5000)
.then(newFile => {
ide.binaryFilesManager.openFile(newFile)
window.expectingLinkedFileRefreshedSocketFor = null
})
.catch(err => console.warn(err)),
0
)
$scope.refreshError = null
})
.catch(response => ($scope.refreshError = response.data))
.finally(() => {
$scope.refreshing = false
const provider = file.linkedFileData.provider
if (
provider === 'mendeley' ||
provider === 'zotero' ||
file.name.match(/^.*\.bib$/)
) {
ide.$scope.$emit('references:should-reindex', {})
}
})
}
// Callback fired when the `img` tag fails to load,
// `failedLoad` used to show the "No Preview" message
$scope.failedLoad = false
window.sl_binaryFilePreviewError = () => {
$scope.failedLoad = true
$scope.$apply()
}
// Callback fired when the `img` tag is done loading,
// `imgLoaded` is used to show the spinner gif while loading
$scope.imgLoaded = false
window.sl_binaryFilePreviewLoaded = () => {
$scope.imgLoaded = true
$scope.$apply()
}
if ($scope.isTextFile()) {
loadTextFilePreview()
}
function loadTextFilePreview() {
const url = `/project/${window.project_id}/file/${$scope.openFile.id}`
let truncated = false
displayPreviewLoading()
getFileSize(url)
.then(fileSize => {
const opts = {}
if (fileSize > MAX_FILE_SIZE) {
truncated = true
opts.maxSize = MAX_FILE_SIZE
}
return getFileContents(url, opts)
})
.then(contents => {
const displayedContents = truncated
? truncateFileContents(contents)
: contents
displayPreview(displayedContents, truncated)
})
.catch(err => {
console.error(err)
displayPreviewError()
})
}
function getFileSize(url) {
return $http.head(url).then(response => {
const size = parseInt(response.headers('Content-Length'), 10)
if (isNaN(size)) {
throw new Error('Could not parse Content-Length header')
}
return size
})
}
function getFileContents(url, opts = {}) {
const { maxSize } = opts
if (maxSize != null) {
url += `?range=0-${maxSize}`
}
return $http
.get(url, {
transformResponse: null, // Don't parse JSON
})
.then(response => {
return response.data
})
}
function truncateFileContents(contents) {
return contents.replace(/\n.*$/, '')
}
function displayPreviewLoading() {
$scope.textPreview.data = null
$scope.textPreview.loading = true
$scope.textPreview.shouldShowDots = false
$scope.$apply()
}
function displayPreview(contents, truncated) {
$scope.textPreview.error = false
$scope.textPreview.data = contents
$scope.textPreview.shouldShowDots = truncated
$timeout(setPreviewHeight, 0)
}
function displayPreviewError() {
$scope.textPreview.error = true
$scope.textPreview.loading = false
}
function setPreviewHeight() {
const $preview = $element.find('.text-preview .scroll-container')
const $header = $element.find('.binary-file-header')
const maxHeight = $element.height() - $header.height() - 14 // borders + margin
$preview.css({ 'max-height': maxHeight })
// Don't show the preview until we've set the height, otherwise we jump around
$scope.textPreview.loading = false
}
}
)
| overleaf/web/frontend/js/ide/binary-files/controllers/BinaryFileController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/binary-files/controllers/BinaryFileController.js",
"repo_id": "overleaf",
"token_count": 2515
} | 524 |
import _ from 'lodash'
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import Document from './Document'
import './components/spellMenu'
import './directives/aceEditor'
import './directives/toggleSwitch'
import './controllers/SavingNotificationController'
import '../../features/symbol-palette/controllers/symbol-palette-controller'
let EditorManager
export default EditorManager = (function () {
EditorManager = class EditorManager {
static initClass() {
this.prototype._syncTimeout = null
}
constructor(ide, $scope, localStorage, eventTracking) {
this.ide = ide
this.editorOpenDocEpoch = 0 // track pending document loads
this.$scope = $scope
this.localStorage = localStorage
this.$scope.editor = {
sharejs_doc: null,
open_doc_id: null,
open_doc_name: null,
opening: true,
trackChanges: false,
wantTrackChanges: false,
showRichText: this.showRichText(),
showSymbolPalette: false,
toggleSymbolPalette: () => {
const newValue = !this.$scope.editor.showSymbolPalette
this.$scope.editor.showSymbolPalette = newValue
ide.$scope.$emit('symbol-palette-toggled', newValue)
eventTracking.sendMB(
newValue ? 'symbol-palette-show' : 'symbol-palette-hide'
)
},
insertSymbol: symbol => {
ide.$scope.$emit('editor:replace-selection', symbol.command)
eventTracking.sendMB('symbol-palette-insert')
},
}
this.$scope.$on('entity:selected', (event, entity) => {
if (this.$scope.ui.view !== 'history' && entity.type === 'doc') {
return this.openDoc(entity)
}
})
this.$scope.$on('entity:no-selection', () => {
this.$scope.$apply(() => {
this.$scope.ui.view = null
})
})
this.$scope.$on('entity:deleted', (event, entity) => {
if (this.$scope.editor.open_doc_id === entity.id) {
if (!this.$scope.project.rootDoc_id) {
this.$scope.ui.view = null
return
}
const doc = this.ide.fileTreeManager.findEntityById(
this.$scope.project.rootDoc_id
)
if (doc == null) {
this.$scope.ui.view = null
return
}
return this.openDoc(doc)
}
})
let initialized = false
this.$scope.$on('file-tree:initialized', () => {
if (!initialized) {
initialized = true
return this.autoOpenDoc()
}
})
this.$scope.$on('flush-changes', () => {
return Document.flushAll()
})
window.addEventListener('blur', () => {
// The browser may put the tab into sleep as it looses focus.
// Flushing the documents should help with keeping the documents in
// sync: we can use any new version of the doc that the server may
// present us. There should be no need to insert local changes into
// the doc history as the user comes back.
sl_console.log('[EditorManager] forcing flush onblur')
Document.flushAll()
})
this.$scope.$watch('editor.wantTrackChanges', value => {
if (value == null) {
return
}
return this._syncTrackChangesState(this.$scope.editor.sharejs_doc)
})
}
showRichText() {
return (
this.localStorage(`editor.mode.${this.$scope.project_id}`) ===
'rich-text'
)
}
autoOpenDoc() {
const open_doc_id =
this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`) ||
this.$scope.project.rootDoc_id
if (open_doc_id == null) {
return
}
const doc = this.ide.fileTreeManager.findEntityById(open_doc_id)
if (doc == null) {
return
}
return this.openDoc(doc)
}
openDocId(doc_id, options) {
if (options == null) {
options = {}
}
const doc = this.ide.fileTreeManager.findEntityById(doc_id)
if (doc == null) {
return
}
return this.openDoc(doc, options)
}
jumpToLine(options) {
return this.$scope.$broadcast(
'editor:gotoLine',
options.gotoLine,
options.gotoColumn,
options.syncToPdf
)
}
openDoc(doc, options) {
if (options == null) {
options = {}
}
sl_console.log(`[openDoc] Opening ${doc.id}`)
this.$scope.ui.view = 'editor'
const done = isNewDoc => {
this.$scope.$broadcast('doc:after-opened', { isNewDoc })
if (options.gotoLine != null) {
// allow Ace to display document before moving, delay until next tick
// added delay to make this happen later that gotoStoredPosition in
// CursorPositionManager
return setTimeout(() => this.jumpToLine(options), 0)
} else if (options.gotoOffset != null) {
return setTimeout(() => {
return this.$scope.$broadcast(
'editor:gotoOffset',
options.gotoOffset
)
}, 0)
}
}
// If we already have the document open we can return at this point.
// Note: only use forceReopen:true to override this when the document is
// is out of sync and needs to be reloaded from the server.
if (doc.id === this.$scope.editor.open_doc_id && !options.forceReopen) {
// automatically update the file tree whenever the file is opened
this.ide.fileTreeManager.selectEntity(doc)
this.$scope.$apply(() => {
return done(false)
})
return
}
// We're now either opening a new document or reloading a broken one.
this.$scope.editor.open_doc_id = doc.id
this.$scope.editor.open_doc_name = doc.name
this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`, doc.id)
this.ide.fileTreeManager.selectEntity(doc)
this.$scope.editor.opening = true
return this._openNewDocument(doc, (error, sharejs_doc) => {
if (error && error.message === 'another document was loaded') {
sl_console.log(
`[openDoc] another document was loaded while ${doc.id} was loading`
)
return
}
if (error != null) {
this.ide.showGenericMessageModal(
'Error opening document',
'Sorry, something went wrong opening this document. Please try again.'
)
return
}
this._syncTrackChangesState(sharejs_doc)
this.$scope.$broadcast('doc:opened')
return this.$scope.$apply(() => {
this.$scope.editor.opening = false
this.$scope.editor.sharejs_doc = sharejs_doc
return done(true)
})
})
}
_openNewDocument(doc, callback) {
// Leave the current document
// - when we are opening a different new one, to avoid race conditions
// between leaving and joining the same document
// - when the current one has pending ops that need flushing, to avoid
// race conditions from cleanup
const current_sharejs_doc = this.$scope.editor.sharejs_doc
const currentDocId = current_sharejs_doc && current_sharejs_doc.doc_id
const hasBufferedOps =
current_sharejs_doc && current_sharejs_doc.hasBufferedOps()
const changingDoc = current_sharejs_doc && currentDocId !== doc.id
if (changingDoc || hasBufferedOps) {
sl_console.log('[_openNewDocument] Leaving existing open doc...')
// Do not trigger any UI changes from remote operations
this._unbindFromDocumentEvents(current_sharejs_doc)
// Keep listening for out-of-sync and similar errors.
this._attachErrorHandlerToDocument(doc, current_sharejs_doc)
// Teardown the Document -> ShareJsDoc -> sharejs doc
// By the time this completes, the Document instance is no longer
// registered in Document.openDocs and _doOpenNewDocument can start
// from scratch -- read: no corrupted internal state.
const editorOpenDocEpoch = ++this.editorOpenDocEpoch
current_sharejs_doc.leaveAndCleanUp(error => {
if (error) {
sl_console.log(
`[_openNewDocument] error leaving doc ${currentDocId}`,
error
)
return callback(error)
}
if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
sl_console.log(
`[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
)
return callback(new Error('another document was loaded'))
}
this._doOpenNewDocument(doc, callback)
})
} else {
this._doOpenNewDocument(doc, callback)
}
}
_doOpenNewDocument(doc, callback) {
if (callback == null) {
callback = function (error, sharejs_doc) {}
}
sl_console.log('[_doOpenNewDocument] Opening...')
const new_sharejs_doc = Document.getDocument(this.ide, doc.id)
const editorOpenDocEpoch = ++this.editorOpenDocEpoch
return new_sharejs_doc.join(error => {
if (error != null) {
sl_console.log(
`[_doOpenNewDocument] error joining doc ${doc.id}`,
error
)
return callback(error)
}
if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
sl_console.log(
`[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
)
new_sharejs_doc.leaveAndCleanUp()
return callback(new Error('another document was loaded'))
}
this._bindToDocumentEvents(doc, new_sharejs_doc)
return callback(null, new_sharejs_doc)
})
}
_attachErrorHandlerToDocument(doc, sharejs_doc) {
sharejs_doc.on('error', (error, meta, editorContent) => {
let message
if ((error != null ? error.message : undefined) != null) {
;({ message } = error)
} else if (typeof error === 'string') {
message = error
} else {
message = ''
}
if (/maxDocLength/.test(message)) {
this.ide.showGenericMessageModal(
'Document Too Long',
'Sorry, this file is too long to be edited manually. Please upload it directly.'
)
} else if (/too many comments or tracked changes/.test(message)) {
this.ide.showGenericMessageModal(
'Too many comments or tracked changes',
'Sorry, this file has too many comments or tracked changes. Please try accepting or rejecting some existing changes, or resolving and deleting some comments.'
)
} else {
// Do not allow this doc to open another error modal.
sharejs_doc.off('error')
// Preserve the sharejs contents before the teardown.
editorContent =
typeof editorContent === 'string'
? editorContent
: sharejs_doc.doc._doc.snapshot
// Tear down the ShareJsDoc.
if (sharejs_doc.doc) sharejs_doc.doc.clearInflightAndPendingOps()
// Do not re-join after re-connecting.
sharejs_doc.leaveAndCleanUp()
this.ide.connectionManager.disconnect({ permanent: true })
this.ide.reportError(error, meta)
// Tell the user about the error state.
this.$scope.editor.error_state = true
this.ide.showOutOfSyncModal(
'Out of sync',
"Sorry, this file has gone out of sync and we need to do a full refresh. <br> <a target='_blank' rel='noopener noreferrer' href='/learn/Kb/Editor_out_of_sync_problems'>Please see this help guide for more information</a>",
editorContent
)
// Do not forceReopen the document.
return
}
const removeHandler = this.$scope.$on('project:joined', () => {
this.openDoc(doc, { forceReopen: true })
removeHandler()
})
})
}
_bindToDocumentEvents(doc, sharejs_doc) {
this._attachErrorHandlerToDocument(doc, sharejs_doc)
return sharejs_doc.on('externalUpdate', update => {
if (this._ignoreExternalUpdates) {
return
}
if (
_.property(['meta', 'type'])(update) === 'external' &&
_.property(['meta', 'source'])(update) === 'git-bridge'
) {
return
}
return this.ide.showGenericMessageModal(
'Document Updated Externally',
'This document was just updated externally. Any recent changes you have made may have been overwritten. To see previous versions please look in the history.'
)
})
}
_unbindFromDocumentEvents(document) {
return document.off()
}
getCurrentDocValue() {
return this.$scope.editor.sharejs_doc != null
? this.$scope.editor.sharejs_doc.getSnapshot()
: undefined
}
getCurrentDocId() {
return this.$scope.editor.open_doc_id
}
startIgnoringExternalUpdates() {
return (this._ignoreExternalUpdates = true)
}
stopIgnoringExternalUpdates() {
return (this._ignoreExternalUpdates = false)
}
_syncTrackChangesState(doc) {
let tryToggle
if (doc == null) {
return
}
if (this._syncTimeout != null) {
clearTimeout(this._syncTimeout)
this._syncTimeout = null
}
const want = this.$scope.editor.wantTrackChanges
const have = doc.getTrackingChanges()
if (want === have) {
this.$scope.editor.trackChanges = want
return
}
return (tryToggle = () => {
const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
if (saved) {
doc.setTrackingChanges(want)
return this.$scope.$apply(() => {
return (this.$scope.editor.trackChanges = want)
})
} else {
return (this._syncTimeout = setTimeout(tryToggle, 100))
}
})()
}
}
EditorManager.initClass()
return EditorManager
})()
| overleaf/web/frontend/js/ide/editor/EditorManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/EditorManager.js",
"repo_id": "overleaf",
"token_count": 6237
} | 525 |
import _ from 'lodash'
/* eslint-disable
max-len,
no-cond-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
*/
import 'ace/ace'
let MetadataManager
const { Range } = ace.require('ace/range')
const getLastCommandFragment = function (lineUpToCursor) {
let m
if ((m = lineUpToCursor.match(/(\\[^\\]+)$/))) {
return m[1]
} else {
return null
}
}
export default MetadataManager = class MetadataManager {
constructor($scope, editor, element, Metadata) {
this.$scope = $scope
this.editor = editor
this.element = element
this.Metadata = Metadata
this.debouncer = {} // DocId => Timeout
const onChange = change => {
if (change.origin === 'remote') {
return
}
if (!['remove', 'insert'].includes(change.action)) {
return
}
const cursorPosition = this.editor.getCursorPosition()
const { end } = change
let range = new Range(end.row, 0, end.row, end.column)
let lineUpToCursor = this.editor.getSession().getTextRange(range)
if (
lineUpToCursor.trim() === '%' ||
lineUpToCursor.slice(0, 1) === '\\'
) {
range = new Range(end.row, 0, end.row, end.column + 80)
lineUpToCursor = this.editor.getSession().getTextRange(range)
}
const commandFragment = getLastCommandFragment(lineUpToCursor)
const linesContainPackage = _.some(change.lines, line =>
line.match(/^\\usepackage(?:\[.{0,80}?])?{(.{0,80}?)}/)
)
const linesContainReqPackage = _.some(change.lines, line =>
line.match(/^\\RequirePackage(?:\[.{0,80}?])?{(.{0,80}?)}/)
)
const linesContainLabel = _.some(change.lines, line =>
line.match(/\\label{(.{0,80}?)}/)
)
const linesContainMeta =
linesContainPackage || linesContainLabel || linesContainReqPackage
const lastCommandFragmentIsLabel =
(commandFragment != null ? commandFragment.slice(0, 7) : undefined) ===
'\\label{'
const lastCommandFragmentIsPackage =
(commandFragment != null ? commandFragment.slice(0, 11) : undefined) ===
'\\usepackage'
const lastCommandFragmentIsReqPack =
(commandFragment != null ? commandFragment.slice(0, 15) : undefined) ===
'\\RequirePackage'
const lastCommandFragmentIsMeta =
lastCommandFragmentIsPackage ||
lastCommandFragmentIsLabel ||
lastCommandFragmentIsReqPack
if (linesContainMeta || lastCommandFragmentIsMeta) {
return this.Metadata.scheduleLoadDocMetaFromServer(this.$scope.docId)
}
}
this.editor.on('changeSession', e => {
e.oldSession.off('change', onChange)
return e.session.on('change', onChange)
})
}
getAllLabels() {
return this.Metadata.getAllLabels()
}
getAllPackages() {
return this.Metadata.getAllPackages()
}
}
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/metadata/MetadataManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/metadata/MetadataManager.js",
"repo_id": "overleaf",
"token_count": 1277
} | 526 |
import _ from 'lodash'
import App from '../../../base'
export default App.factory('files', function (ide) {
const Files = {
getTeXFiles() {
const texFiles = []
ide.fileTreeManager.forEachEntity(function (entity, _folder, path) {
if (
entity.type === 'doc' &&
/.*\.(tex|md|txt|tikz)/.test(entity.name)
) {
const cloned = _.clone(entity)
cloned.path = path
texFiles.push(cloned)
}
})
return texFiles
},
}
return Files
})
| overleaf/web/frontend/js/ide/files/services/files.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/files/services/files.js",
"repo_id": "overleaf",
"token_count": 249
} | 527 |
/* eslint-disable
max-len,
no-return-assign,
camelcase,
*/
// 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.controller(
'HistoryV2ToolbarController',
($scope, $modal, ide, eventTracking, waitFor) => {
$scope.currentUpdate = null
$scope.currentLabel = null
$scope.restoreState = {
inflight: false,
error: false,
}
$scope.toolbarUIConfig = {
showOnlyLabels: false,
}
const _deregistershowOnlyLabelsWatcher = $scope.$watch(
'history.showOnlyLabels',
showOnlyLabels => {
if (showOnlyLabels != null) {
$scope.toolbarUIConfig.showOnlyLabels = showOnlyLabels
_deregistershowOnlyLabelsWatcher()
}
}
)
$scope.$watch('toolbarUIConfig.showOnlyLabels', (newVal, oldVal) => {
if (newVal != null && newVal !== oldVal) {
if (newVal) {
ide.historyManager.showOnlyLabels()
} else {
ide.historyManager.showAllUpdates()
}
}
})
$scope.$watch('history.viewMode', (newVal, oldVal) => {
if (newVal != null && newVal !== oldVal) {
$scope.currentUpdate = ide.historyManager.getUpdateForVersion(newVal)
}
})
$scope.$watch('history.selection.range.toV', (newVal, oldVal) => {
if (
newVal != null &&
newVal !== oldVal &&
$scope.history.viewMode === $scope.HistoryViewModes.POINT_IN_TIME
) {
$scope.currentUpdate = ide.historyManager.getUpdateForVersion(newVal)
}
})
$scope.toggleHistoryViewMode = () => {
ide.historyManager.toggleHistoryViewMode()
}
$scope.restoreDeletedFile = function () {
const { pathname, deletedAtV } = $scope.history.selection.file
if (pathname == null || deletedAtV == null) {
return
}
eventTracking.sendMB('history-v2-restore-deleted')
$scope.restoreState.inflight = true
return ide.historyManager
.restoreFile(deletedAtV, pathname)
.then(function (response) {
const { data } = response
return openEntity(data)
})
.catch(() =>
ide.showGenericMessageModal(
'Sorry, something went wrong with the restore'
)
)
.finally(() => ($scope.restoreState.inflight = false))
}
$scope.showAddLabelDialog = () => {
$modal.open({
templateUrl: 'historyV2AddLabelModalTemplate',
controller: 'HistoryV2AddLabelModalController',
resolve: {
update() {
return $scope.history.selection.update
},
},
})
}
function openEntity(data) {
const { id, type } = data
return waitFor(() => ide.fileTreeManager.findEntityById(id), 3000)
.then(function (entity) {
if (type === 'doc') {
ide.editorManager.openDoc(entity)
ide.$timeout(() => {
$scope.$broadcast('history:toggle')
}, 0)
} else if (type === 'file') {
ide.binaryFilesManager.openFile(entity)
ide.$timeout(() => {
$scope.$broadcast('history:toggle')
}, 0)
}
})
.catch(err => console.warn(err))
}
}
)
| overleaf/web/frontend/js/ide/history/controllers/HistoryV2ToolbarController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/controllers/HistoryV2ToolbarController.js",
"repo_id": "overleaf",
"token_count": 1563
} | 528 |
import { v4 as uuid } from 'uuid'
import { sendMB } from '../../../infrastructure/event-tracking'
// VERSION should get incremented when making changes to caching behavior or
// adjusting metrics collection.
// Keep in sync with the service worker.
const VERSION = 2
const pdfJsMetrics = {
version: VERSION,
id: uuid(),
epoch: Date.now(),
totalBandwidth: 0,
}
const SAMPLING_RATE = 0.01
export function trackPdfDownload(response, compileTimeClientE2E) {
const { serviceWorkerMetrics, stats, timings } = response
const t0 = performance.now()
let bandwidth = 0
function firstRenderDone({ timePDFFetched, timePDFRendered }) {
const latencyFetch = timePDFFetched - t0
// The renderer does not yield in case the browser tab is hidden.
// It will yield when the browser tab is visible again.
// This will skew our performance metrics for rendering!
// We are omitting the render time in case we detect this state.
let latencyRender
if (timePDFRendered) {
latencyRender = timePDFRendered - timePDFFetched
}
done({ latencyFetch, latencyRender })
}
function updateConsumedBandwidth(bytes) {
pdfJsMetrics.totalBandwidth += bytes - bandwidth
bandwidth = bytes
}
let done
const onFirstRenderDone = new Promise(resolve => {
done = resolve
})
// Submit latency along with compile context.
onFirstRenderDone.then(({ latencyFetch, latencyRender }) => {
submitCompileMetrics({
latencyFetch,
latencyRender,
compileTimeClientE2E,
stats,
timings,
})
})
// Submit bandwidth counter separate from compile context.
submitPDFBandwidth({ pdfJsMetrics, serviceWorkerMetrics })
return {
firstRenderDone,
updateConsumedBandwidth,
}
}
function submitCompileMetrics(metrics) {
const { latencyFetch, latencyRender, compileTimeClientE2E } = metrics
const leanMetrics = {
version: VERSION,
latencyFetch,
latencyRender,
compileTimeClientE2E,
}
sl_console.log('/event/compile-metrics', JSON.stringify(metrics))
sendMB('compile-metrics-v5', leanMetrics, SAMPLING_RATE)
}
function submitPDFBandwidth(metrics) {
const metricsFlat = {}
Object.entries(metrics).forEach(([section, items]) => {
if (!items) return
Object.entries(items).forEach(([key, value]) => {
metricsFlat[section + '_' + key] = value
})
})
const leanMetrics = {}
Object.entries(metricsFlat).forEach(([metric, value]) => {
if (
[
'serviceWorkerMetrics_id',
'serviceWorkerMetrics_cachedBytes',
'serviceWorkerMetrics_fetchedBytes',
'serviceWorkerMetrics_requestedBytes',
'serviceWorkerMetrics_version',
'serviceWorkerMetrics_epoch',
].includes(metric)
) {
leanMetrics[metric] = value
}
})
if (Object.entries(leanMetrics).length === 0) {
return
}
sl_console.log('/event/pdf-bandwidth', JSON.stringify(metrics))
sendMB('pdf-bandwidth-v5', leanMetrics, SAMPLING_RATE)
}
| overleaf/web/frontend/js/ide/pdf/controllers/PdfJsMetrics.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/pdf/controllers/PdfJsMetrics.js",
"repo_id": "overleaf",
"token_count": 1057
} | 529 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
import './controllers/ReviewPanelController'
import './controllers/TrackChangesUpgradeModalController'
import './controllers/BulkActionsModalController'
import './directives/reviewPanelSorted'
import './directives/reviewPanelToggle'
import './directives/changeEntry'
import './directives/aggregateChangeEntry'
import './directives/commentEntry'
import './directives/addCommentEntry'
import './directives/bulkActionsEntry'
import './directives/resolvedCommentEntry'
import './directives/resolvedCommentsDropdown'
import './directives/reviewPanelCollapseHeight'
import './filters/notEmpty'
import './filters/numKeys'
import './filters/orderOverviewEntries'
| overleaf/web/frontend/js/ide/review-panel/ReviewPanelManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/ReviewPanelManager.js",
"repo_id": "overleaf",
"token_count": 219
} | 530 |
// 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.filter(
'orderOverviewEntries',
() =>
function (items) {
const array = []
for (const key in items) {
const value = items[key]
value.entry_id = key
array.push(value)
}
array.sort((a, b) => a.offset - b.offset)
return array
}
)
| overleaf/web/frontend/js/ide/review-panel/filters/orderOverviewEntries.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/filters/orderOverviewEntries.js",
"repo_id": "overleaf",
"token_count": 235
} | 531 |
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import './main/token-access'
import './main/project-list/index'
import './main/account-settings'
import './main/clear-sessions'
import './main/account-upgrade-angular'
import './main/plans'
import './main/post-gateway'
import './main/user-membership'
import './main/scribtex-popup'
import './main/event'
import './main/bonus'
import './main/system-messages'
import './main/translations'
import './main/subscription-dashboard'
import './main/new-subscription'
import './main/annual-upgrade'
import './main/register-users'
import './main/subscription/team-invite-controller'
import './main/subscription/upgrade-subscription'
import './main/learn'
import './main/affiliations/components/affiliationForm'
import './main/affiliations/components/inputSuggestions'
import './main/affiliations/controllers/UserAffiliationsController'
import './main/affiliations/factories/UserAffiliationsDataService'
import './main/affiliations/controllers/UserAffiliationsReconfirmController'
import './main/oauth/controllers/UserOauthController'
import './main/keys'
import './main/importing'
import './directives/autoSubmitForm'
import './directives/asyncForm'
import './directives/complexPassword'
import './directives/stopPropagation'
import './directives/focus'
import './directives/equals'
import './directives/eventTracking'
import './directives/fineUpload'
import './directives/onEnter'
import './directives/selectAll'
import './directives/maxHeight'
import './directives/bookmarkableTabset'
import './services/queued-http'
import './services/validateCaptcha'
import './services/validateCaptchaV3'
import './filters/formatDate'
import '../../modules/modules-main.js'
angular.module('SharelatexApp').config(function ($locationProvider) {
try {
return $locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: false,
})
} catch (e) {
return console.error("Error while trying to fix '#' links: ", e)
}
})
export default angular.bootstrap(document.body, ['SharelatexApp'])
| overleaf/web/frontend/js/main.js/0 | {
"file_path": "overleaf/web/frontend/js/main.js",
"repo_id": "overleaf",
"token_count": 761
} | 532 |
import _ from 'lodash'
import App from '../base'
import '../directives/mathjax'
import '../services/algolia-search'
App.controller(
'SearchWikiController',
function ($scope, algoliaSearch, $modal) {
$scope.hits = []
$scope.hits_total = 0
$scope.config_hits_per_page = 20
$scope.processingSearch = false
$scope.clearSearchText = function () {
$scope.searchQueryText = ''
updateHits([])
}
$scope.safeApply = function (fn) {
const phase = $scope.$root.$$phase
if (phase === '$apply' || phase === '$digest') {
$scope.$eval(fn)
} else {
$scope.$apply(fn)
}
}
const buildHitViewModel = function (hit) {
const pagePath = hit.kb ? 'how-to/' : 'latex/'
const pageSlug = encodeURIComponent(hit.pageName.replace(/\s/g, '_'))
let sectionUnderscored = ''
if (hit.sectionName && hit.sectionName !== '') {
sectionUnderscored = '#' + hit.sectionName.replace(/\s/g, '_')
}
const section = hit._highlightResult.sectionName
let pageName = hit._highlightResult.pageName.value
if (section && section.value && section !== '') {
pageName += ' - ' + section.value
}
let content = hit._highlightResult.content.value
// Replace many new lines
content = content.replace(/\n\n+/g, '\n\n')
const lines = content.split('\n')
// Only show the lines that have a highlighted match
const matchingLines = []
for (const line of lines) {
if (!/^\[edit\]/.test(line)) {
content += line + '\n'
if (/<em>/.test(line)) {
matchingLines.push(line)
}
}
}
content = matchingLines.join('\n...\n')
const result = {
name: pageName,
url: `/learn/${pagePath}${pageSlug}${sectionUnderscored}`,
content,
}
return result
}
var updateHits = (hits, hitsTotal = 0) => {
$scope.safeApply(() => {
$scope.hits = hits
$scope.hits_total = hitsTotal
})
}
$scope.search = function () {
$scope.processingSearch = true
const query = $scope.searchQueryText
if (!query || query.length === 0) {
updateHits([])
return
}
algoliaSearch.searchWiki(
query,
{
hitsPerPage: $scope.config_hits_per_page,
},
function (err, response) {
$scope.processingSearch = false
if (response.hits.length === 0) {
updateHits([])
} else {
const hits = _.map(response.hits, buildHitViewModel)
updateHits(hits, response.nbHits)
}
}
)
}
}
)
export default App.controller('LearnController', function () {})
| overleaf/web/frontend/js/main/learn.js/0 | {
"file_path": "overleaf/web/frontend/js/main/learn.js",
"repo_id": "overleaf",
"token_count": 1253
} | 533 |
import App from '../../base'
export default App.controller(
'UpgradeSubscriptionController',
function ($scope, eventTracking) {
$scope.upgradeSubscription = function () {
eventTracking.send('subscription-funnel', 'subscription-page', 'upgrade')
eventTracking.sendMB('subscription-page-upgrade-button-click')
}
}
)
| overleaf/web/frontend/js/main/subscription/upgrade-subscription.js/0 | {
"file_path": "overleaf/web/frontend/js/main/subscription/upgrade-subscription.js",
"repo_id": "overleaf",
"token_count": 114
} | 534 |
import { OverlayTrigger, Tooltip } from 'react-bootstrap'
import PropTypes from 'prop-types'
export default function BetaBadge({ tooltip, url = '/beta/participate' }) {
return (
<OverlayTrigger
placement={tooltip.placement || 'bottom'}
overlay={<Tooltip id={tooltip.id}>{tooltip.text}</Tooltip>}
delayHide={100}
>
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="badge beta-badge"
>
<span className="sr-only">{tooltip.text}</span>
</a>
</OverlayTrigger>
)
}
BetaBadge.propTypes = {
tooltip: PropTypes.exact({
id: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
placement: PropTypes.string,
}),
url: PropTypes.string,
}
| overleaf/web/frontend/js/shared/components/beta-badge.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/components/beta-badge.js",
"repo_id": "overleaf",
"token_count": 323
} | 535 |
import { useCallback, useEffect, useState } from 'react'
import PropTypes from 'prop-types'
import _ from 'lodash'
import { useIdeContext } from '../ide-context'
/**
* Binds a property in an Angular scope making it accessible in a React
* component. The interface is compatible with React.useState(), including
* the option of passing a function to the setter.
*
* @param {string} path - dot '.' path of a property in the Angular scope.
* @param {boolean} deep
* @returns {[any, function]} - Binded value and setter function tuple.
*/
export default function useScopeValue(path, deep = false) {
const { $scope } = useIdeContext({
$scope: PropTypes.object.isRequired,
})
const [value, setValue] = useState(() => _.get($scope, path))
useEffect(() => {
return $scope.$watch(
path,
newValue => {
setValue(deep ? _.cloneDeep(newValue) : newValue)
},
deep
)
}, [path, $scope, deep])
const scopeSetter = useCallback(
newValue => {
setValue(val => {
const actualNewValue = _.isFunction(newValue) ? newValue(val) : newValue
$scope.$applyAsync(() => _.set($scope, path, actualNewValue))
return actualNewValue
})
},
[path, $scope]
)
return [value, scopeSetter]
}
| overleaf/web/frontend/js/shared/context/util/scope-value-hook.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/context/util/scope-value-hook.js",
"repo_id": "overleaf",
"token_count": 447
} | 536 |
/*
* Copyright 2013 Ivan Pusic
* Contributors:
* Matjaz Lipus
*/
//https://github.com/ivpusic/angular-cookie/blob/master/angular-cookie.js
angular.module('ivpusic.cookie', ['ipCookie']);
angular.module('ipCookie', ['ng']).
factory('ipCookie', ['$document',
function ($document) {
'use strict';
return (function () {
function cookieFun(key, value, options) {
var cookies,
list,
i,
cookie,
pos,
name,
hasCookies,
all,
expiresFor;
options = options || {};
if (value !== undefined) {
// we are setting value
value = typeof value === 'object' ? JSON.stringify(value) : String(value);
if (typeof options.expires === 'number') {
expiresFor = options.expires;
options.expires = new Date();
// Trying to delete a cookie; set a date far in the past
if (expiresFor === -1) {
options.expires = new Date('Thu, 01 Jan 1970 00:00:00 GMT');
// A new
} else if (options.expirationUnit !== undefined) {
if (options.expirationUnit === 'hours') {
options.expires.setHours(options.expires.getHours() + expiresFor);
} else if (options.expirationUnit === 'minutes') {
options.expires.setMinutes(options.expires.getMinutes() + expiresFor);
} else if (options.expirationUnit === 'seconds') {
options.expires.setSeconds(options.expires.getSeconds() + expiresFor);
} else {
options.expires.setDate(options.expires.getDate() + expiresFor);
}
} else {
options.expires.setDate(options.expires.getDate() + expiresFor);
}
}
return ($document[0].cookie = [
encodeURIComponent(key),
'=',
encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '',
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
list = [];
all = $document[0].cookie;
if (all) {
list = all.split('; ');
}
cookies = {};
hasCookies = false;
for (i = 0; i < list.length; ++i) {
if (list[i]) {
cookie = list[i];
pos = cookie.indexOf('=');
name = cookie.substring(0, pos);
value = decodeURIComponent(cookie.substring(pos + 1));
if (key === undefined || key === name) {
try {
cookies[name] = JSON.parse(value);
} catch (e) {
cookies[name] = value;
}
if (key === name) {
return cookies[name];
}
hasCookies = true;
}
}
}
if (hasCookies && key === undefined) {
return cookies;
}
}
cookieFun.remove = function (key, options) {
var hasCookie = cookieFun(key) !== undefined;
if (hasCookie) {
if (!options) {
options = {};
}
options.expires = -1;
cookieFun(key, '', options);
}
return hasCookie;
};
return cookieFun;
}());
}
]); | overleaf/web/frontend/js/vendor/libs/angular-cookie.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/angular-cookie.js",
"repo_id": "overleaf",
"token_count": 1749
} | 537 |
From 6d118ec35e6e6f954938a485178748f1bb8bdd8a Mon Sep 17 00:00:00 2001
From: Jakob Ackermann <jakob.ackermann@overleaf.com>
Date: Mon, 5 Jul 2021 17:28:00 +0100
Subject: [PATCH 2/2] [misc] do not bundle NodeJS stream backend
---
src/pdf.js | 7 +------
1 file changed, 1 insertion(+), 6 deletions(-)
diff --git a/src/pdf.js b/src/pdf.js
index 4ccf2c1a7..7058c7a46 100644
--- a/src/pdf.js
+++ b/src/pdf.js
@@ -32,12 +32,7 @@ let pdfjsDisplayAPICompatibility = require('./display/api_compatibility.js');
if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {
const isNodeJS = require('./shared/is_node.js');
- if (isNodeJS()) {
- let PDFNodeStream = require('./display/node_stream.js').PDFNodeStream;
- pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
- return new PDFNodeStream(params);
- });
- } else {
+ if (!isNodeJS()) {
let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;
let PDFFetchStream;
if (pdfjsDisplayDisplayUtils.isFetchSupported()) {
--
2.17.1
| overleaf/web/frontend/js/vendor/libs/pdfjs-dist/patches/0002-misc-do-not-bundle-NodeJS-stream-backend.patch/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/pdfjs-dist/patches/0002-misc-do-not-bundle-NodeJS-stream-backend.patch",
"repo_id": "overleaf",
"token_count": 418
} | 538 |
import { ContextRoot } from '../js/shared/context/root-context'
import FileView from '../js/features/file-view/components/file-view'
import useFetchMock from './hooks/use-fetch-mock'
const bodies = {
latex: `\\documentclass{article}
\\begin{document}
First document. This is a simple example, with no
extra parameters or packages included.
\\end{document}`,
bibtex: `@book{latexcompanion,
author = "Michel Goossens and Frank Mittelbach and Alexander Samarin",
title = "The \\LaTeX\\ Companion",
year = "1993",
publisher = "Addison-Wesley",
address = "Reading, Massachusetts"
}`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.`,
}
const setupFetchMock = fetchMock => {
return fetchMock
.head('express:/project/:project_id/file/:file_id', {
status: 201,
headers: { 'Content-Length': 10000 },
})
.post('express:/project/:project_id/linked_file/:file_id/refresh', {
status: 204,
})
.post('express:/project/:project_id/references/indexAll', {
status: 204,
})
}
const fileData = {
id: 'file-id',
name: 'file.tex',
created: new Date().toISOString(),
}
export const FileFromUrl = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.latex }
)
)
return <FileView {...args} />
}
FileFromUrl.args = {
file: {
...fileData,
linkedFileData: {
url: 'https://example.com/source-file.tex',
provider: 'url',
},
},
}
export const FileFromProjectWithLinkableProjectId = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.latex }
)
)
return <FileView {...args} />
}
FileFromProjectWithLinkableProjectId.args = {
file: {
...fileData,
linkedFileData: {
source_project_id: 'source-project-id',
source_entity_path: '/source-file.tex',
provider: 'project_file',
},
},
}
export const FileFromProjectWithoutLinkableProjectId = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.latex }
)
)
return <FileView {...args} />
}
FileFromProjectWithoutLinkableProjectId.args = {
file: {
...fileData,
linkedFileData: {
v1_source_doc_id: 'v1-source-id',
source_entity_path: '/source-file.tex',
provider: 'project_file',
},
},
}
export const FileFromProjectOutputWithLinkableProject = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.latex }
)
)
return <FileView {...args} />
}
FileFromProjectOutputWithLinkableProject.args = {
file: {
...fileData,
linkedFileData: {
source_project_id: 'source_project_id',
source_output_file_path: '/source-file.tex',
provider: 'project_output_file',
},
},
}
export const FileFromProjectOutputWithoutLinkableProjectId = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.latex }
)
)
return <FileView {...args} />
}
FileFromProjectOutputWithoutLinkableProjectId.args = {
file: {
...fileData,
linkedFileData: {
v1_source_doc_id: 'v1-source-id',
source_output_file_path: '/source-file.tex',
provider: 'project_output_file',
},
},
}
export const ImageFile = args => {
useFetchMock(setupFetchMock) // NOTE: can't mock img src request
return <FileView {...args} />
}
ImageFile.storyName = 'Image File (Error)'
ImageFile.args = {
file: {
...fileData,
id: '60097ca20454610027c442a8',
name: 'file.jpg',
linkedFileData: {
source_project_id: 'source_project_id',
source_entity_path: '/source-file.jpg',
provider: 'project_file',
},
},
}
export const ThirdPartyReferenceFile = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.bibtex }
)
)
return <FileView {...args} />
}
ThirdPartyReferenceFile.args = {
file: {
...fileData,
name: 'references.bib',
linkedFileData: {
provider: 'zotero',
},
},
}
export const ThirdPartyReferenceFileWithError = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).head(
'express:/project/:project_id/file/:file_id',
{ status: 500 },
{ overwriteRoutes: true }
)
)
return <FileView {...args} />
}
ThirdPartyReferenceFileWithError.storyName =
'Third Party Reference File (Error)'
ThirdPartyReferenceFileWithError.args = {
file: {
...fileData,
id: '500500500500500500500500',
name: 'references.bib',
linkedFileData: {
provider: 'zotero',
},
},
}
export const TextFile = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).get(
'express:/project/:project_id/file/:file_id',
{ body: bodies.text },
{ overwriteRoutes: true }
)
)
return <FileView {...args} />
}
TextFile.args = {
file: {
...fileData,
linkedFileData: {
source_project_id: 'source-project-id',
source_entity_path: '/source-file.txt',
provider: 'project_file',
},
name: 'file.txt',
},
}
export const UploadedFile = args => {
useFetchMock(fetchMock =>
setupFetchMock(fetchMock).head(
'express:/project/:project_id/file/:file_id',
{ status: 500 },
{ overwriteRoutes: true }
)
)
return <FileView {...args} />
}
UploadedFile.storyName = 'Uploaded File (Error)'
UploadedFile.args = {
file: {
...fileData,
linkedFileData: null,
name: 'file.jpg',
},
}
export default {
title: 'FileView',
component: FileView,
argTypes: {
storeReferencesKeys: { action: 'store references keys' },
},
decorators: [
Story => (
<ContextRoot ide={window._ide} settings={{}}>
<Story />
</ContextRoot>
),
],
}
| overleaf/web/frontend/stories/file-view.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/file-view.stories.js",
"repo_id": "overleaf",
"token_count": 2512
} | 539 |
import Pagination from '../js/shared/components/pagination'
export const Interactive = args => {
return <Pagination {...args} />
}
export default {
title: 'Pagination',
component: Pagination,
args: {
currentPage: 1,
totalPages: 10,
handlePageClick: () => {},
},
argTypes: {
currentPage: { control: { type: 'number', min: 1, max: 10, step: 1 } },
totalPages: { control: { disable: true } },
},
}
| overleaf/web/frontend/stories/pagination.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/pagination.stories.js",
"repo_id": "overleaf",
"token_count": 156
} | 540 |
.system-message {
padding: (@line-height-computed / 4) (@line-height-computed / 2);
background-color: @sys-msg-background;
color: @sys-msg-color;
border-bottom: @sys-msg-border;
a {
color: @sidebar-link-color;
text-decoration: underline;
}
}
.system-message .close {
color: #fff;
opacity: 1;
text-shadow: none;
}
.clickable {
cursor: pointer;
}
.img-circle {
display: inline-block;
overflow: hidden;
border-radius: 50%;
width: @line-height-computed * 4;
height: @line-height-computed * 4;
img {
margin-top: -10px;
}
}
@-webkit-keyframes bounce {
0%,
10%,
26%,
40%,
50% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
20%,
21% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
-webkit-transform: translate3d(0, -10px, 0);
transform: translate3d(0, -10px, 0);
}
35% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
-webkit-transform: translate3d(0, -5px, 0);
transform: translate3d(0, -5px, 0);
}
45% {
-webkit-transform: translate3d(0, -2px, 0);
transform: translate3d(0, -2px, 0);
}
50% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
@keyframes bounce {
0%,
10%,
26%,
40%,
50% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
-webkit-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
20%,
21% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
-webkit-transform: translate3d(0, -10px, 0);
-ms-transform: translate3d(0, -10px, 0);
transform: translate3d(0, -10px, 0);
}
35% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
-webkit-transform: translate3d(0, -5px, 0);
-ms-transform: translate3d(0, -5px, 0);
transform: translate3d(0, -5px, 0);
}
45% {
-webkit-transform: translate3d(0, -2px, 0);
-ms-transform: translate3d(0, -2px, 0);
transform: translate3d(0, -2px, 0);
}
50% {
-webkit-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
@keyframes pulse {
0% {
opacity: 0.7;
}
100% {
opacity: 0.9;
}
}
@keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.bounce {
-webkit-animation-duration: 2s;
animation-duration: 2s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
-webkit-animation-name: bounce;
animation-name: bounce;
-webkit-transform-origin: center bottom;
-ms-transform-origin: center bottom;
transform-origin: center bottom;
}
.grecaptcha-badge {
visibility: hidden;
height: 0 !important; // Prevent layout shift
}
.tos-agreement-notice {
text-align: center;
margin-top: (@line-height-computed / 4);
margin-bottom: 0;
font-size: @font-size-small;
&.tos-agreement-notice-homepage {
margin-top: (@line-height-computed / 2);
color: #fff;
& > a {
color: #fff;
text-decoration: underline;
}
}
}
| overleaf/web/frontend/stylesheets/app/base.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/base.less",
"repo_id": "overleaf",
"token_count": 1646
} | 541 |
.logs-pane {
.full-size;
top: @pdf-top-offset;
overflow-y: auto;
background-color: @logs-pane-bg;
}
.logs-pane-content {
display: flex;
flex-direction: column;
padding: @padding-sm;
min-height: 100%;
}
.logs-pane-actions {
display: flex;
justify-content: flex-end;
padding: @padding-sm 0;
flex-grow: 1;
align-items: flex-end;
}
.logs-pane-actions-clear-cache {
.no-outline-ring-on-click;
margin-right: @margin-sm;
}
.log-entry {
margin-bottom: @margin-sm;
border-radius: @border-radius-base;
overflow: hidden;
}
.log-entry-first-error-popup {
border-radius: 0;
overflow: auto;
}
.log-entry-header {
padding: 3px @padding-sm;
display: flex;
align-items: flex-start;
border-radius: @border-radius-base @border-radius-base 0 0;
color: #fff;
}
.log-entry-header-error {
background-color: @ol-red;
}
.log-entry-header-link-error {
.btn-alert-variant(@ol-red);
}
.log-entry-header-warning {
background-color: @orange;
}
.log-entry-header-link-warning {
.btn-alert-variant(@orange);
}
.log-entry-header-typesetting {
background-color: @ol-blue;
}
.log-entry-header-link-typesetting {
.btn-alert-variant(@ol-blue);
}
.log-entry-header-raw {
background-color: @ol-blue-gray-4;
}
.log-entry-header-link-raw {
.btn-alert-variant(@ol-blue-gray-4);
}
.log-entry-header-success {
background-color: @green;
}
.log-entry-header-link-success {
.btn-alert-variant(@green);
}
.log-entry-header-title,
.log-entry-header-link {
font-family: @font-family-sans-serif;
font-size: @font-size-base;
line-height: @line-height-base;
font-weight: 700;
flex-grow: 1;
margin: 0;
color: #fff;
}
.log-entry-header-icon-container {
margin-right: @margin-sm;
}
.log-entry-header-link {
display: flex;
align-items: center;
border-radius: 9999px;
border-width: 0;
flex-grow: 0;
text-align: right;
margin-left: @margin-sm;
max-width: 33%;
padding: 0 @padding-xs;
&:hover,
&:focus {
text-decoration: none;
outline: 0;
color: #fff;
}
&:focus {
text-decoration: none;
}
}
.log-entry-header-link-location {
white-space: nowrap;
direction: rtl;
text-overflow: ellipsis;
overflow: hidden;
padding: 0 @padding-xs;
}
.log-entry-content {
background-color: #fff;
padding: @padding-sm;
}
.log-entry-content-raw-container {
background-color: @ol-blue-gray-1;
border-radius: @border-radius-base;
overflow: hidden;
}
.log-entry-content-raw {
font-size: @font-size-extra-small;
color: @ol-blue-gray-4;
padding: @padding-sm;
margin: 0;
}
.log-entry-content-button-container {
position: relative;
height: 40px;
margin-top: 0;
transition: margin 0.15s ease-in-out, opacity 0.15s ease-in-out;
padding-bottom: @padding-sm;
text-align: center;
background-image: linear-gradient(0, @ol-blue-gray-1, transparent);
border-radius: 0 0 @border-radius-base @border-radius-base;
}
.log-entry-content-button-container-collapsed {
margin-top: -40px;
}
.log-entry-btn-expand-collapse {
position: relative;
z-index: 1;
.no-outline-ring-on-click;
}
.log-entry-formatted-content,
.log-entry-content-link {
font-size: @font-size-small;
margin-top: @margin-xs;
&:first-of-type {
margin-top: 0;
}
}
.log-entry-formatted-content-list {
margin: @margin-xs 0;
padding-left: @padding-md;
}
.first-error-popup {
position: absolute;
z-index: 1;
top: @toolbar-small-height + 2px;
right: @padding-xs;
width: 90%;
max-width: 450px;
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.25);
animation: fade-in 0.15s linear 0s 1 none;
background-color: #fff;
&::before {
content: '';
.triangle(top, @padding-sm, @padding-xs, @ol-red);
top: -@padding-xs;
right: @padding-xl;
}
}
.first-error-popup-actions {
display: flex;
justify-content: space-between;
padding: 0 @padding-sm @padding-sm @padding-sm;
border-radius: 0 0 @border-radius-base @border-radius-base;
}
.first-error-btn {
.no-outline-ring-on-click;
}
.log-location-tooltip {
word-break: break-all;
&.tooltip.in {
opacity: 1;
}
& > .tooltip-inner {
max-width: 450px;
text-align: left;
}
}
| overleaf/web/frontend/stylesheets/app/editor/logs.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/editor/logs.less",
"repo_id": "overleaf",
"token_count": 1723
} | 542 |
.v2-import__img {
.img-responsive;
.center-block;
width: 80%;
}
| overleaf/web/frontend/stylesheets/app/import.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/import.less",
"repo_id": "overleaf",
"token_count": 31
} | 543 |
@rfp-h1-size: 2.442em;
@rfp-h2-size: 1.953em;
@rfp-h3-size: 1.563em;
@rfp-lead-size: 1.25em;
@rfp-sl-red: @red;
@rfp-rp-blue: @rp-type-blue;
@rfp-rp-blue-light: #f8f9fd;
@rfp-rp-blue-dark: shade(@rfp-rp-blue, 50%);
@rfp-rp-blue-darker: shade(@rfp-rp-blue, 65%);
@rfp-rp-blue-darkest: shade(@rfp-rp-blue, 75%);
@rfp-card-shadow: 0 0 30px 5px rgba(0, 0, 0, 0.3);
@rfp-border-radius: 5px;
@rfp-header-height: 80px;
@rfp-header-height-collapsed: 50px;
.rfp-main {
background-color: @content-alt-bg-color;
font-size: 18px;
min-width: 240px;
}
// Typographical scale and basics.
.rfp-h1 {
font-size: @rfp-h2-size;
margin-bottom: 1.6em;
color: inherit;
@media (min-width: @screen-xs-min) {
font-size: @rfp-h1-size;
}
}
.rfp-h1-masthead {
color: #fff;
margin-bottom: 1em;
}
.rfp-h2 {
font-size: @rfp-h2-size;
margin-bottom: 1.6em;
color: inherit;
}
.rfp-h3 {
font-size: @rfp-h3-size;
margin-bottom: 1.6em;
color: inherit;
}
.rfp-h3-cta {
margin-top: 0;
margin-bottom: 40px;
}
.rfp-lead {
margin-bottom: 1.6em;
max-width: 30em;
margin-left: auto;
margin-right: auto;
@media (min-width: @screen-xs-min) {
font-size: @rfp-lead-size;
}
}
.rfp-lead-cta {
margin-top: 0;
margin-bottom: 40px;
}
.rfp-lead-strong {
font-weight: 700;
.rfp-section-masthead & {
margin-bottom: 0;
}
}
.rfp-p {
margin-bottom: 1.6em;
max-width: 30em;
margin-left: auto;
margin-right: auto;
.rfp-section-feature & {
margin-left: initial;
}
.rfp-section-feature-alt & {
margin-left: auto;
margin-right: initial;
}
}
.rfp-highlight {
font-weight: 700;
}
// Sections
.rfp-header {
position: fixed;
top: 0;
width: 100%;
z-index: 2;
height: @rfp-header-height;
transition: height 0.2s;
background-color: fade(@rfp-rp-blue-darkest, 90%);
padding: 15px 20px;
min-width: 320px;
@media (min-width: @screen-xs-min) {
padding-left: 30px;
padding-right: 30px;
}
@media (min-width: @screen-sm-min) {
padding-left: 60px;
padding-right: 60px;
}
.rfp-main-header-collapsed & {
height: @rfp-header-height-collapsed;
padding-top: 10px;
padding-bottom: 10px;
}
}
.rfp-header-wrapper {
display: flex;
align-items: center;
justify-content: space-between;
max-width: @container-large-desktop;
height: 100%;
margin: auto;
}
.rfp-header-logo-container,
.rfp-header-logo {
height: 100%;
}
.rfp-section {
padding: 30px;
text-align: center;
overflow: hidden;
@media (min-width: @screen-xs-min) {
padding: 30px;
}
@media (min-width: @screen-sm-min) {
padding: 60px;
}
}
.rfp-section-masthead {
color: #fff;
background-size: cover;
background-position: center;
background-color: @rfp-rp-blue-darker;
padding-top: @rfp-header-height;
.rfp-lead {
opacity: 0;
transition: opacity 0.8s ease;
}
&.rfp-section-masthead-in {
.rfp-lead {
opacity: 1;
}
}
}
.rfp-section-blockquote {
position: relative;
padding-top: 30px;
padding-bottom: 30px;
background-color: @brand-secondary;
box-shadow: @rfp-card-shadow;
}
.rfp-section-feature {
display: block;
text-align: left;
@media (min-width: @screen-sm-min) {
.rfp-section-wrapper {
display: flex;
align-items: center;
}
}
}
.rfp-feature-description-container,
.rfp-feature-video-container {
flex: 0 0 50%;
}
.rfp-feature-description-container {
@media (min-width: @screen-sm-min) {
padding-right: 1em;
.rfp-section-feature-alt & {
padding-right: 0;
padding-left: 1em;
}
}
}
.rfp-feature-video-container {
@media (min-width: @screen-sm-min) {
padding-left: 1em;
.rfp-section-feature-alt & {
padding-left: 0;
padding-right: 1em;
order: -1;
}
}
}
.rfp-section-feature-alt {
color: #fff;
background-color: @ol-blue-gray-5;
@media (min-width: @screen-sm-min) {
text-align: right;
}
}
.rfp-section-feature-white {
background: #ffffff;
}
.rfp-section-testimonials {
background-color: @rfp-rp-blue-darkest;
}
.rfp-section-final {
background-color: @rfp-rp-blue-darker;
}
.rfp-section-wrapper {
max-width: @container-large-desktop;
margin: 0 auto;
}
// Elements
.rfp-h1-masthead-portion {
display: inline-block;
transform: translate(150px, 0);
opacity: 0;
transition: transform 0.8s ease 0s, opacity 0.8s ease 0s;
&:nth-child(2) {
transition-delay: 0.5s, 0.5s;
}
&:nth-child(3) {
transition-delay: 0.5s, 0.5s;
}
&:nth-child(4) {
transition-delay: 1s, 1s;
}
&:nth-child(5) {
transition-delay: 1s, 1s;
}
.rfp-section-masthead-in & {
transform: translate(0, 0);
opacity: 1;
}
}
.rfp-video {
max-width: 100%;
box-shadow: @rfp-card-shadow;
border-radius: @rfp-border-radius;
}
.rfp-video-masthead {
width: 270px;
height: 163px;
margin-bottom: 2em;
transform: translate(0, 100px);
opacity: 0;
transition: transform 0.8s ease 1s, opacity 0.8s ease 1s;
box-shadow: none;
max-width: none;
@media (min-width: @screen-xs-min) {
width: 400px;
height: 241px;
}
@media (min-width: 600px) {
width: 525px;
height: 316px;
}
@media (min-width: @screen-sm-min) {
width: 633px;
height: 381px;
}
@media (min-width: @screen-sm-min) {
width: 697px;
height: 420px;
}
.rfp-section-masthead-in & {
transform: translate(0, 0);
opacity: 1;
box-shadow: @rfp-card-shadow;
}
}
.rfp-video-anim {
transition: transform 0.8s ease, opacity 0.8s ease;
transform: translate(100%, 0);
opacity: 0;
}
.rfp-video-anim-alt {
transform: translate(-100%, 0);
}
.rfp-video-anim-in {
transform: translate(0, 0);
opacity: 1;
}
.rfp-quote-section {
@media (min-width: @screen-md-min) {
display: flex;
}
}
.rfp-quote {
display: block;
width: 100%;
padding: 20px 40px;
border-left: 0;
max-width: 30em;
font-size: @rfp-lead-size;
quotes: '\201C''\201D';
box-shadow: @rfp-card-shadow;
border-radius: @rfp-border-radius;
background-color: #fff;
color: @rfp-rp-blue-dark;
font-size: 1em;
margin: 0 auto 20px;
@media (min-width: @screen-xs-min) {
font-size: @rfp-lead-size;
}
@media (min-width: @screen-md-min) {
display: flex;
flex-direction: column;
justify-content: space-between;
flex: 0 1 50%;
margin-right: 20px;
}
// Override weird Boostrap default.
p {
display: block;
}
&:last-of-type {
@media (min-width: @screen-md-min) {
margin-right: 0;
}
}
&::before {
content: none;
}
}
.rfp-quote-main {
color: #ffffff;
display: block;
max-width: none;
border-left: 0;
margin: 0 auto;
padding: 0;
quotes: '\201C''\201D';
font-size: @rfp-lead-size;
@media (min-width: @screen-md-min) {
display: flex;
}
// Override weird Boostrap default.
p {
display: block;
}
&::before {
content: none;
}
}
.rfp-quoted-text {
position: relative;
display: inline-block;
font-family: @font-family-serif;
font-style: italic;
text-align: left;
margin: 0 0 40px 0;
&::before {
content: open-quote;
display: block;
position: absolute;
font-family: @font-family-serif;
font-size: @rfp-lead-size;
line-height: inherit;
color: inherit;
left: -0.75em;
}
.rfp-quote-main & {
@media (min-width: @screen-md-min) {
flex: 1 1 70%;
margin: auto 40px auto auto;
}
}
}
.rfp-quoted-person {
display: inline-block;
font-size: 0.8em;
.rfp-quote-main & {
display: flex;
align-items: center;
justify-content: center;
flex: 0 0 30%;
}
}
.rfp-quoted-person-name {
margin: 0;
}
.rfp-quoted-person-affil {
margin: 0;
font-size: 0.8em;
&:hover,
&:focus {
text-decoration: none;
cursor: pointer;
}
.rfp-quote-main & {
color: #fff;
&:hover,
&:focus {
color: #fff;
}
}
}
.rfp-quoted-person-photo {
border-radius: 3em;
width: 6em;
margin-bottom: 20px;
.rfp-quote-main & {
margin-bottom: 0;
margin-right: 20px;
}
}
.rfp-users {
display: flex;
flex-wrap: wrap;
margin: 0 1em 2em;
@media (min-width: @screen-md-min) {
flex-wrap: nowrap;
align-items: center;
}
}
.rfp-user-container {
flex: 0 0 100%;
padding: 10px;
@media (min-width: @screen-xs-min) {
flex-basis: 50%;
}
@media (min-width: @screen-md-min) {
flex-basis: 25%;
padding: 20px;
}
}
.rfp-user-logo {
max-width: 100%;
}
.rfp-cta-container {
max-width: 40em;
margin: 0 auto;
padding: 40px;
background-color: #fff;
color: @rfp-rp-blue-dark;
box-shadow: @rfp-card-shadow;
border-radius: @rfp-border-radius;
}
.rfp-cta-header {
font-size: 1em;
padding: 0.2em 1em;
}
.rfp-cta-main {
display: block;
transition: transform 0.25s;
transform: translate(0, 0);
}
.rfp-cta-extra {
display: block;
position: absolute;
left: 50%;
text-transform: uppercase;
transition: opacity 0.25s, transform 0.25s;
transform: translate(-50%, 100%);
opacity: 0;
font-size: 0.5em;
}
| overleaf/web/frontend/stylesheets/app/review-features-page.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/review-features-page.less",
"repo_id": "overleaf",
"token_count": 4060
} | 544 |
//
// Close icons
// --------------------------------------------------
.close {
float: right;
font-size: (@font-size-base * 1.5);
font-weight: @close-font-weight;
line-height: 1;
color: @close-color;
text-shadow: @close-text-shadow;
.opacity(0.4);
&:hover,
&:focus {
color: @close-color;
text-decoration: none;
cursor: pointer;
.opacity(0.5);
}
// Additional properties for button version
// iOS requires the button element instead of an anchor tag.
// If you want the anchor version, it requires `href="#"`.
button& {
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none;
}
}
| overleaf/web/frontend/stylesheets/components/close.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/close.less",
"repo_id": "overleaf",
"token_count": 242
} | 545 |
//
// Jumbotron
// --------------------------------------------------
.jumbotron {
padding: @jumbotron-padding;
margin-bottom: @jumbotron-padding;
color: @jumbotron-color;
background-color: @jumbotron-bg;
h1,
.h1 {
color: @jumbotron-heading-color;
}
p {
margin-bottom: (@jumbotron-padding / 2);
font-size: @jumbotron-font-size;
font-weight: 200;
}
.container & {
border-radius: @border-radius-large; // Only round corners at higher resolutions if contained in a container
}
.container {
max-width: 100%;
}
@media screen and (min-width: @screen-sm-min) {
padding-top: (@jumbotron-padding * 1.6);
padding-bottom: (@jumbotron-padding * 1.6);
.container & {
padding-left: (@jumbotron-padding * 2);
padding-right: (@jumbotron-padding * 2);
}
h1,
.h1 {
font-size: (@font-size-base * 4.5);
}
}
}
| overleaf/web/frontend/stylesheets/components/jumbotron.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/jumbotron.less",
"repo_id": "overleaf",
"token_count": 368
} | 546 |
//
// Popovers
// --------------------------------------------------
.popover {
position: absolute;
top: 0;
left: 0;
z-index: @zindex-popover;
display: none;
max-width: @popover-max-width;
padding: 1px;
text-align: left; // Reset given new insertion method
background-color: @popover-bg;
background-clip: padding-box;
border: 1px solid @popover-fallback-border-color;
border: 1px solid @popover-border-color;
border-radius: @border-radius-large;
.box-shadow(0 5px 10px rgba(0, 0, 0, 0.2));
// Overrides for proper insertion
white-space: normal;
// Offset the popover to account for the popover arrow
&.top {
margin-top: -@popover-arrow-width;
}
&.right {
margin-left: @popover-arrow-width;
}
&.bottom {
margin-top: @popover-arrow-width;
}
&.left {
margin-left: -@popover-arrow-width;
}
}
.popover-title {
margin: 0; // reset heading margin
padding: 8px 14px;
font-size: @font-size-base;
font-weight: normal;
line-height: 18px;
background-color: @popover-title-bg;
border-bottom: 1px solid darken(@popover-title-bg, 5%);
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
// Arrows
//
// .arrow is outer, .arrow:after is inner
.popover > .arrow {
&,
&:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
}
.popover > .arrow {
border-width: @popover-arrow-outer-width;
}
.popover > .arrow:after {
border-width: @popover-arrow-width;
content: '';
}
.popover {
&.top > .arrow {
left: 50%;
margin-left: -@popover-arrow-outer-width;
border-bottom-width: 0;
border-top-color: @popover-arrow-outer-fallback-color; // IE8 fallback
border-top-color: @popover-arrow-outer-color;
bottom: -@popover-arrow-outer-width;
&:after {
content: ' ';
bottom: 1px;
margin-left: -@popover-arrow-width;
border-bottom-width: 0;
border-top-color: @popover-arrow-color;
}
}
&.right > .arrow {
top: 50%;
left: -@popover-arrow-outer-width;
margin-top: -@popover-arrow-outer-width;
border-left-width: 0;
border-right-color: @popover-arrow-outer-fallback-color; // IE8 fallback
border-right-color: @popover-arrow-outer-color;
&:after {
content: ' ';
left: 1px;
bottom: -@popover-arrow-width;
border-left-width: 0;
border-right-color: @popover-arrow-color;
}
}
&.bottom > .arrow {
left: 50%;
margin-left: -@popover-arrow-outer-width;
border-top-width: 0;
border-bottom-color: @popover-arrow-outer-fallback-color; // IE8 fallback
border-bottom-color: @popover-arrow-outer-color;
top: -@popover-arrow-outer-width;
&:after {
content: ' ';
top: 1px;
margin-left: -@popover-arrow-width;
border-top-width: 0;
border-bottom-color: @popover-arrow-color;
}
}
&.left > .arrow {
top: 50%;
right: -@popover-arrow-outer-width;
margin-top: -@popover-arrow-outer-width;
border-right-width: 0;
border-left-color: @popover-arrow-outer-fallback-color; // IE8 fallback
border-left-color: @popover-arrow-outer-color;
&:after {
content: ' ';
right: 1px;
border-right-width: 0;
border-left-color: @popover-arrow-color;
bottom: -@popover-arrow-width;
}
}
}
| overleaf/web/frontend/stylesheets/components/popovers.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/popovers.less",
"repo_id": "overleaf",
"token_count": 1418
} | 547 |
// Styleguide colors
@ol-green: #138a07;
@ol-dark-green: #004a0e;
@ol-blue: #3e70bb;
@ol-dark-blue: #2857a1;
@ol-red: #c9453e;
@ol-dark-red: #a6312b;
@ol-type-color: @ol-blue-gray-3;
// Sidebar
@sidebar-bg: #fff;
@sidebar-color: @ol-blue-gray-2;
@sidebar-active-bg: @ol-green;
@sidebar-active-color: #fff;
@sidebar-hover-bg: @ol-blue-gray-1;
@sidebar-active-font-weight: normal;
@sidebar-hover-text-decoration: none;
@v2-dash-pane-bg: @ol-blue-gray-1;
@v2-dash-pane-link-color: @ol-blue;
@v2-dash-pane-toggle-color: @ol-blue-gray-3;
@v2-dash-pane-btn-bg: @ol-blue-gray-5;
@v2-dash-pane-btn-hover-bg: @ol-blue-gray-6;
@v2-dash-pane-color: @ol-blue-gray-3;
@progress-bar-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
@progress-bg: @ol-blue-gray-0;
@input-border: @ol-blue-gray-1;
// Editor file-tree
@file-tree-bg: #fff;
@file-tree-line-height: 2.05;
@file-tree-item-color: @ol-blue-gray-3;
@file-tree-item-focus-color: @file-tree-item-color;
@file-tree-item-selected-color: #fff;
@file-tree-item-input-color: @ol-blue-gray-2;
@file-tree-item-toggle-color: @ol-blue-gray-2;
@file-tree-item-icon-color: @ol-blue-gray-2;
@file-tree-item-folder-color: @ol-blue-gray-2;
@file-tree-item-hover-bg: @ol-blue-gray-1;
@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;
@content-alt-bg-color: @ol-blue-gray-0;
// File outline
@outline-line-guide-color: @ol-blue-gray-1;
@outline-header-hover-bg: @file-tree-item-hover-bg;
@outline-highlight-bg: mix(@file-tree-bg, @ol-blue-gray-1);
@vertical-resizable-resizer-bg: @ol-blue-gray-1;
@vertical-resizable-resizer-hover-bg: @file-tree-item-hover-bg;
// Editor resizers
@editor-resizer-bg-color: @ol-blue-gray-1;
@editor-resizer-bg-color-dragging: @ol-blue-gray-1;
@editor-toggler-bg-color: @ol-blue-gray-2;
@editor-toggler-hover-bg-color: @ol-green;
@synctex-controls-z-index: 6;
@synctex-controls-padding: 0;
@editor-border-color: @ol-blue-gray-1;
@toolbar-border-color: @ol-blue-gray-1;
@toolbar-alt-bg-color: #fff;
@editor-toolbar-bg: @toolbar-alt-bg-color;
@toolbar-header-bg-color: #fff;
@toolbar-header-btn-border-color: @ol-blue-gray-1;
@toolbar-header-branded-btn-bg-color: @ol-blue-gray-3;
@toolbar-btn-color: @ol-blue-gray-3;
@toolbar-btn-hover-color: @ol-blue-gray-3;
@toolbar-btn-hover-bg-color: @ol-blue-gray-0;
@toolbar-icon-btn-color: @ol-blue-gray-3;
@toolbar-icon-btn-hover-color: @ol-blue-gray-3;
@editor-header-logo-background: url(/img/ol-brand/overleaf-o.svg) center /
contain no-repeat;
@project-name-color: @ol-blue-gray-3;
@project-rename-link-color: @ol-blue-gray-3;
@project-rename-link-color-hover: @ol-blue-gray-4;
@pdf-bg: @ol-blue-gray-0;
@logs-pane-bg: @ol-blue-gray-1;
// Navbar
@navbar-default-bg: #fff;
@navbar-default-border: @ol-blue-gray-1;
@navbar-default-link-bg: @ol-green;
@navbar-default-link-color: #fff;
@navbar-default-link-border-color: transparent;
@navbar-default-link-hover-bg: @ol-green;
@navbar-default-link-active-bg: @ol-green;
@navbar-default-link-hover-color: @ol-green;
@navbar-title-color: @ol-blue-gray-1;
@navbar-title-color-hover: @ol-blue-gray-2;
@navbar-default-color: @ol-blue-gray-3;
@navbar-brand-image-url: url(/img/ol-brand/overleaf.svg);
@navbar-subdued-color: @ol-blue-gray-3;
@navbar-subdued-hover-bg: @ol-blue-gray-1;
@navbar-subdued-hover-color: @ol-blue-gray-3;
@card-box-shadow: 0 0 0 1px @ol-blue-gray-1;
// v2 History
@history-toolbar-color: @ol-blue-gray-3;
@history-base-bg: @ol-blue-gray-0;
@history-file-badge-bg: rgba(0, 0, 0, 0.25);
@history-file-badge-color: #fff;
// Formatting buttons
@formatting-btn-color: @toolbar-icon-btn-color;
@formatting-btn-bg: transparent;
@formatting-btn-border: @ol-blue-gray-1;
@formatting-menu-bg: #fff;
// Chat
@chat-bg: #fff;
@chat-instructions-color: @ol-blue-gray-3;
@chat-message-color: #fff;
@chat-message-name-color: @ol-blue-gray-3;
@chat-message-date-color: @ol-blue-gray-3;
@chat-new-message-bg: @ol-blue-gray-0;
@chat-new-message-textarea-bg: #fff;
@chat-new-message-textarea-color: @ol-blue-gray-6;
@chat-new-message-border-color: @ol-blue-gray-1;
// Symbol Palette
@symbol-palette-bg: #fff;
@symbol-palette-color: @ol-blue-gray-3;
@symbol-palette-header-background: @ol-blue-gray-1;
@symbol-palette-item-bg: @ol-blue-gray-1;
@symbol-palette-item-color: @ol-blue-gray-3;
@symbol-palette-selected-tab-bg: #fff;
@symbol-palette-selected-tab-color: @ol-blue;
| overleaf/web/frontend/stylesheets/core/ol-light-variables.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/core/ol-light-variables.less",
"repo_id": "overleaf",
"token_count": 2036
} | 548 |
/*!
* ui-select
* http://github.com/angular-ui/ui-select
* Version: 0.19.7 - 2017-04-15T14:28:36.790Z
* License: MIT
*/
/* Style when highlighting a search. */
.ui-select-highlight {
font-weight: bold;
}
.ui-select-offscreen {
clip: rect(0 0 0 0) !important;
width: 1px !important;
height: 1px !important;
border: 0 !important;
margin: 0 !important;
padding: 0 !important;
overflow: hidden !important;
position: absolute !important;
outline: 0 !important;
left: 0px !important;
top: 0px !important;
}
.ui-select-choices-row:hover {
background-color: #f5f5f5;
}
/* Select2 theme */
/* Mark invalid Select2 */
.ng-dirty.ng-invalid > a.select2-choice {
border-color: #D44950;
}
.select2-result-single {
padding-left: 0;
}
.select2-locked > .select2-search-choice-close{
display:none;
}
.select-locked > .ui-select-match-close{
display:none;
}
body > .select2-container.open {
z-index: 9999; /* The z-index Select2 applies to the select2-drop */
}
/* Handle up direction Select2 */
.ui-select-container[theme="select2"].direction-up .ui-select-match,
.ui-select-container.select2.direction-up .ui-select-match {
border-radius: 4px; /* FIXME hardcoded value :-/ */
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.ui-select-container[theme="select2"].direction-up .ui-select-dropdown,
.ui-select-container.select2.direction-up .ui-select-dropdown {
border-radius: 4px; /* FIXME hardcoded value :-/ */
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
border-top-width: 1px; /* FIXME hardcoded value :-/ */
border-top-style: solid;
box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.25);
margin-top: -4px; /* FIXME hardcoded value :-/ */
}
.ui-select-container[theme="select2"].direction-up .ui-select-dropdown .select2-search,
.ui-select-container.select2.direction-up .ui-select-dropdown .select2-search {
margin-top: 4px; /* FIXME hardcoded value :-/ */
}
.ui-select-container[theme="select2"].direction-up.select2-dropdown-open .ui-select-match,
.ui-select-container.select2.direction-up.select2-dropdown-open .ui-select-match {
border-bottom-color: #5897fb;
}
.ui-select-container[theme="select2"] .ui-select-dropdown .ui-select-search-hidden,
.ui-select-container[theme="select2"] .ui-select-dropdown .ui-select-search-hidden input{
opacity: 0;
height: 0;
min-height: 0;
padding: 0;
margin: 0;
border:0;
}
/* Selectize theme */
/* Helper class to show styles when focus */
.selectize-input.selectize-focus{
border-color: #007FBB !important;
}
/* Fix input width for Selectize theme */
.selectize-control.single > .selectize-input > input {
width: 100%;
}
/* Fix line break when there's at least one item selected with the Selectize theme */
.selectize-control.multi > .selectize-input > input {
margin: 0 !important;
}
/* Fix dropdown width for Selectize theme */
.selectize-control > .selectize-dropdown {
width: 100%;
}
/* Mark invalid Selectize */
.ng-dirty.ng-invalid > div.selectize-input {
border-color: #D44950;
}
/* Handle up direction Selectize */
.ui-select-container[theme="selectize"].direction-up .ui-select-dropdown {
box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.25);
margin-top: -2px; /* FIXME hardcoded value :-/ */
}
.ui-select-container[theme="selectize"] input.ui-select-search-hidden{
opacity: 0;
height: 0;
min-height: 0;
padding: 0;
margin: 0;
border:0;
width: 0;
}
/* Bootstrap theme */
/* Helper class to show styles when focus */
.btn-default-focus {
color: #333;
background-color: #EBEBEB;
border-color: #ADADAD;
text-decoration: none;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.ui-select-bootstrap .ui-select-toggle {
position: relative;
}
.ui-select-bootstrap .ui-select-toggle > .caret {
position: absolute;
height: 10px;
top: 50%;
right: 10px;
margin-top: -2px;
}
/* Fix Bootstrap dropdown position when inside a input-group */
.input-group > .ui-select-bootstrap.dropdown {
/* Instead of relative */
position: static;
}
.input-group > .ui-select-bootstrap > input.ui-select-search.form-control {
border-radius: 4px; /* FIXME hardcoded value :-/ */
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group > .ui-select-bootstrap > input.ui-select-search.form-control.direction-up {
border-radius: 4px !important; /* FIXME hardcoded value :-/ */
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
.ui-select-bootstrap .ui-select-search-hidden{
opacity: 0;
height: 0;
min-height: 0;
padding: 0;
margin: 0;
border:0;
}
.ui-select-bootstrap > .ui-select-match > .btn{
/* Instead of center because of .btn */
text-align: left !important;
}
.ui-select-bootstrap > .ui-select-match > .caret {
position: absolute;
top: 45%;
right: 15px;
}
/* See Scrollable Menu with Bootstrap 3 http://stackoverflow.com/questions/19227496 */
.ui-select-bootstrap > .ui-select-choices ,.ui-select-bootstrap > .ui-select-no-choice {
width: 100%;
height: auto;
max-height: 200px;
overflow-x: hidden;
margin-top: -1px;
}
body > .ui-select-bootstrap.open {
z-index: 1000; /* Standard Bootstrap dropdown z-index */
}
.ui-select-multiple.ui-select-bootstrap {
height: auto;
padding: 3px 3px 0 3px;
}
.ui-select-multiple.ui-select-bootstrap input.ui-select-search {
background-color: transparent !important; /* To prevent double background when disabled */
border: none;
outline: none;
height: 1.666666em;
margin-bottom: 3px;
}
.ui-select-multiple.ui-select-bootstrap .ui-select-match .close {
font-size: 1.6em;
line-height: 0.75;
}
.ui-select-multiple.ui-select-bootstrap .ui-select-match-item {
outline: 0;
margin: 0 3px 3px 0;
}
.ui-select-multiple .ui-select-match-item {
position: relative;
}
.ui-select-multiple .ui-select-match-item.dropping .ui-select-match-close {
pointer-events: none;
}
.ui-select-multiple:hover .ui-select-match-item.dropping-before:before {
content: "";
position: absolute;
top: 0;
right: 100%;
height: 100%;
margin-right: 2px;
border-left: 1px solid #428bca;
}
.ui-select-multiple:hover .ui-select-match-item.dropping-after:after {
content: "";
position: absolute;
top: 0;
left: 100%;
height: 100%;
margin-left: 2px;
border-right: 1px solid #428bca;
}
.ui-select-bootstrap .ui-select-choices-row>span {
cursor: pointer;
display: block;
padding: 3px 20px;
clear: both;
font-weight: 400;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
}
.ui-select-bootstrap .ui-select-choices-row>span:hover, .ui-select-bootstrap .ui-select-choices-row>span:focus {
text-decoration: none;
color: #262626;
background-color: #f5f5f5;
}
.ui-select-bootstrap .ui-select-choices-row.active>span {
color: #fff;
text-decoration: none;
outline: 0;
background-color: #428bca;
}
.ui-select-bootstrap .ui-select-choices-row.disabled>span,
.ui-select-bootstrap .ui-select-choices-row.active.disabled>span {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
/* fix hide/show angular animation */
.ui-select-match.ng-hide-add,
.ui-select-search.ng-hide-add {
display: none !important;
}
/* Mark invalid Bootstrap */
.ui-select-bootstrap.ng-dirty.ng-invalid > button.btn.ui-select-match {
border-color: #D44950;
}
/* Handle up direction Bootstrap */
.ui-select-container[theme="bootstrap"].direction-up .ui-select-dropdown {
box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.25);
}
.ui-select-bootstrap .ui-select-match-text {
width: 100%;
padding-right: 1em;
}
.ui-select-bootstrap .ui-select-match-text span {
display: inline-block;
width: 100%;
overflow: hidden;
}
.ui-select-bootstrap .ui-select-toggle > a.btn {
position: absolute;
height: 10px;
right: 10px;
margin-top: -2px;
}
/* Spinner */
.ui-select-refreshing.glyphicon {
position: absolute;
right: 0;
padding: 8px 27px;
}
@-webkit-keyframes ui-select-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes ui-select-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.ui-select-spin {
-webkit-animation: ui-select-spin 2s infinite linear;
animation: ui-select-spin 2s infinite linear;
}
.ui-select-refreshing.ng-animate {
-webkit-animation: none 0s;
}
| overleaf/web/frontend/stylesheets/vendor/select/select.css/0 | {
"file_path": "overleaf/web/frontend/stylesheets/vendor/select/select.css",
"repo_id": "overleaf",
"token_count": 3361
} | 549 |
{
"ask_proj_owner_to_upgrade_for_full_history": "Vraag de projecteigenaar om te upgraden om toegang te krijgen tot de volledige geschiedenis van dit project.",
"archive_projects": "Archiveer projecten",
"archive_and_leave_projects": "Archiveer en verlaat projecten",
"about_to_archive_projects": "Je staat op het punt de volgende projecten te achiveren:",
"please_confirm_your_email_before_making_it_default": "Bevestig uw e-mail voordat u deze als standaard gebruikt.",
"back_to_editor": "Terug naar de editor",
"generic_history_error": "Er is iets misgegaan bij het ophalen van de geschiedenis van je project. Als het probleem blijft bestaan, neem dan contact met ons op via:",
"unconfirmed": "Niet bevestigd",
"please_check_your_inbox": "Controleer uw inbox",
"resend_confirmation_email": "Verstuur bevestigingsmail opnieuw",
"history_label_created_by": "Aangemaakt door",
"history_label_this_version": "Label deze versie",
"history_add_label": "Voeg label toe",
"history_adding_label": "Label aan het toevoegen",
"history_new_label_name": "Nieuwe labelnaam",
"history_new_label_added_at": "Een nieuw label zal worden toegevoegd vanaf",
"history_delete_label": "Verwijder label",
"history_deleting_label": "Label aan het verwijderen",
"history_are_you_sure_delete_label": "Weet u zeker dat u het volgende label wilt verwijderen:",
"browsing_project_labelled": "Bladeren door projectversie gelabeld",
"history_view_all": "Alle geschiedenis",
"history_view_labels": "Labels",
"add_another_email": "Voeg nog een email toe",
"start_by_adding_your_email": "Begin met het toevoegen van je e-mailadres",
"let_us_know": "Laat het ons weten",
"add_new_email": "Voeg nieuwe email toe",
"error_performing_request": "Er is een fout opgetreden tijdens het uitvoeren van uw verzoek.",
"emails_and_affiliations_explanation": "Voeg extra e-mailadressen toe aan uw account om toegang te krijgen tot eventuele upgrades die uw universiteit of instelling heeft, om het voor bijdragers gemakkelijker te maken om u te vinden en om ervoor te zorgen dat u uw account kunt herstellen.",
"institution_and_role": "Instelling en rol",
"add_role_and_department": "Voeg rol en afdeling toe",
"save_or_cancel-save": "Sla op",
"save_or_cancel-or": "of",
"save_or_cancel-cancel": "Anuleer",
"make_default": "Maak standaard",
"remove": "Verwijder",
"confirm_email": "Bevestig email",
"invited_to_join_team": "Je bent uitgenodigd om lid te worden van een team",
"join_team": "Wordt lid van het team",
"accepted_invite": "Uitnodiging geaccepteerd",
"invited_to_group": "__inviterName__ heeft je uitgenodigd om lid te worden van een team op __appName__",
"accept_invitation": "Accepteer de uitnodiging",
"joined_team": "Je bent lid geworden van het team dat door __inviterName__ wordt beheerd",
"compare_to_another_version": "Vergelijk met een andere versie",
"browsing_project_as_of": "Door project aan het bladeren vanaf",
"view_single_version": "Bekijk één versie",
"font_family": "Font familie",
"line_height": "Regel afstand",
"compact": "Compact",
"wide": "Breed",
"default": "Standaard",
"leave": "Verlaten",
"archived_projects": "Gearchiveerde Projecten",
"archive": "Archief",
"looking_multiple_licenses": "Op zoek naar meerdere licenties?",
"reduce_costs_group_licenses": "U kunt de administratie verkleinen en de kosten verlagen met onze scherp geprijsde groeplicenties.",
"find_out_more": "Kom meer te weten",
"in_good_company": "Je bent in goed gezelschap",
"dropbox_integration_lowercase": "Dropbox integratie",
"github_integration_lowercase": "Github integratie",
"still_have_questions": "Zijn er nog meer vragen?",
"best_value": "Voordeligste koop",
"faq_how_free_trial_works_question": "Hoe werkt de gratis proefperiode?",
"faq_do_collab_need_premium_question": "Hebben mijn bijdragers ook een premium accounts nodig?",
"faq_need_more_collab_question": "Wat als ik meer bijdragers nodig heb?",
"number_collab": "Aantal bijdragers",
"hit_enter_to_reply": "Toets Enter om te antwoorden",
"add_your_comment_here": "Voeg uw opmerking hier toe",
"resolved_comments": "Opgeloste opmerkingen",
"try_it_for_free": "Probeer het gratis",
"please_ask_the_project_owner_to_upgrade_to_track_changes": "Vraag alstublieft de projecteigenaar om te upgraden zodat de optie 'Wijzigingen bijhouden' gebruikt kan worden",
"mark_as_resolved": "Markeer als opgelost",
"reopen": "Heropen",
"add_comment": "Voeg opmerking toe",
"no_resolved_threads": "Geen opgeloste onderwerpen",
"upgrade_to_track_changes": "Upgrade naar Wijzigingen Bijhouden",
"see_changes_in_your_documents_live": "Zie verandering in uw documenten, live",
"track_any_change_in_real_time": "Hou alle veranderingen bij, in realtime",
"review_your_peers_work": "Review werk van uw collega's",
"accept_or_reject_each_changes_individually": "Accepteer of verwerp iedere wijziging individueel",
"accept": "Accepteer",
"reject": "Verwerp",
"no_comments": "Geen opmerkingen",
"edit": "Pas aan",
"are_you_sure": "Weet u het zeker?",
"resolve": "Los op",
"reply": "Beantwoord",
"quoted_text_in": "Gequote tekst in",
"review": "Review",
"track_changes_is_on": "Wijzigingen bijhouden staat <strong>aan</strong>",
"track_changes_is_off": "Wijzigingen bijhouden staat <strong>uit</strong>",
"current_file": "Huidige bestand",
"overview": "Overzicht",
"tracked_change_added": "Toegevoegd",
"tracked_change_deleted": "Verwijderd",
"show_all": "Laat alles zien",
"show_less": "Laat minder zien",
"dropbox_sync_error": "synchronisatiefout met Dropbox",
"send": "Verstuur",
"sending": "Versturen",
"invalid_password": "Onjuist Wachtwoord",
"error": "Fout",
"other_actions": "Andere acties",
"send_test_email": "Stuur een test e-mail",
"email_sent": "E-mail verzonden",
"create_first_admin_account": "Creëer het eerste Admin account",
"ldap": "LDAP",
"ldap_create_admin_instructions": "Kies een e-mail adres voor het eerste __appName__ admin account. Dit moet corresponderen met een account in het LDAP systeem. U zal daarna gevraagd worden in te loggen met dit account",
"saml": "SAML",
"saml_create_admin_instructions": "Kies een e-mail adres voor het eerste __appName__ admin account. Dit moet corresponderen met een account in het SAML systeem. U zal daarna gevraagd worden in te loggen met dit account",
"admin_user_created_message": "Admin gebruiker aangemaakt, <a href=\"__link__\">Log hier in</a> om verder te gaan",
"status_checks": "Status Checks",
"editor_resources": "Middelen van de Editor",
"checking": "Controleren",
"cannot_invite_self": "Kan geen uitnodiging naar jezelf sturen",
"cannot_invite_non_user": "Kan geen uitnodiging versturen. Ontvanger moet al een __appName__ account hebben",
"log_in_with": "Log in met __provider__",
"return_to_login_page": "Keer terug naar inlogpagina",
"login_failed": "Login mislukt",
"delete_account_warning_message_3": "Je staat op het punt permanent <strong>all je accountgegevens te verwijderen</strong>, inclusief je projecten en instellingen. Type uw account e-mail adres in onderstaande tekstvakken om verder te gaan",
"delete_account_warning_message_2": "Je staat op het punt <strong>al je accountgegevens pemanent te verwijderen</strong>, inclusief je projecten en instellingen. Type uw account e-mail adres in het onderstaande tekstvak om verder te gaan.",
"your_sessions": "Uw Sessies",
"clear_sessions_description": "Dit is een lijst van andere sessies (logins) die actief zijn op uw account, exclusief uw huidige sessie. Klik de \"Sessies Opschonen\" knop hieronder om ze uit te loggen",
"no_other_sessions": "Geen andere sessies actief",
"ip_address": "IP-adres",
"session_created_at": "Sessie gecreëerd op",
"clear_sessions": "Verwijder sessies",
"clear_sessions_success": "Sessies verwijderd",
"sessions": "Sessies",
"manage_sessions": "Manage Uw Sessies",
"syntax_validation": "Code check",
"history": "Geschiedenis",
"joining": "Aan het toevoegen",
"open_project": "Open Project",
"files_cannot_include_invalid_characters": "Bestandsnaam mag niet '*' of '/' bevatten",
"invalid_file_name": "Ongeldige Bestandsnaam",
"autocomplete_references": "Refereer Autocomplete (in een <code>\\cite{}</code> blok)",
"autocomplete": "Autocomplete",
"failed_compile_check": "Het lijkt erop dat uw project een aantal fatale syntax errors heeft die u zou moeten fixen voordat we het compilen",
"failed_compile_check_try": "Probeer toch te compileren",
"failed_compile_option_or": "of",
"failed_compile_check_ignore": "zet syntax checken uit",
"compile_time_checks": "Syntax checks",
"stop_on_validation_error": "Check syntax voor compileren",
"ignore_validation_errors": "Check syntax niet",
"run_syntax_check_now": "Doe nu een syntax check",
"your_billing_details_were_saved": "Uw betalingsgegevens zijn opgeslagen",
"security_code": "Beveiligingscode",
"paypal_upgrade": "Om op te waarderen, klik op onderstaande knop en log in met PayPal met uw e-mail en wachtwoord",
"upgrade_cc_btn": "Upgrade nu, betaal na 7 dagen",
"upgrade_paypal_btn": "Ga verder",
"notification_project_invite": "<b>__userName__</b> wil dat u deelneemt aan <b>__projectName__</b> <a class=\"btn btn-sm btn-info pull-right\" href=\"/project/__projectId__/invite/token/__token__\">Neem deel aan Project</a>",
"file_restored": "Uw bestand (__filename__) is hersteld",
"file_restored_back_to_editor": "U kan terug gaan naar de editor en er weer aan werken",
"file_restored_back_to_editor_btn": "Terug naar editor",
"view_project": "Bekijk Project",
"join_project": "Neem deel aan Project",
"invite_not_accepted": "Uitnodiging nog niet geaccepteerd",
"resend": "Stuur opnieuw",
"syntax_check": "Syntax check",
"revoke_invite": "Herroep uitnodiging",
"pending": "In afwachting",
"invite_not_valid": "Dit is geen valide projectuitnodiging",
"invite_not_valid_description": "De uitnodiging kan verlopen zijn. Neem contact op met de projecteigenaar",
"accepting_invite_as": "U accepteert deze uitnodiging als",
"accept_invite": "Accepteer uitnodiging",
"log_hint_ask_extra_feedback": "Kan u ons helpen begrijpen waarom de hint niet bruikbaar was?",
"log_hint_extra_feedback_didnt_understand": "Ik begreep de hint niet",
"log_hint_extra_feedback_not_applicable": "Ik kan deze oplossing niet op mijn document toepassen",
"log_hint_extra_feedback_incorrect": "Dit lost de foutmelding niet op",
"log_hint_extra_feedback_other": "Anders:",
"log_hint_extra_feedback_submit": "Verstuur",
"if_you_are_registered": "Als u al geregistreerd bent",
"stop_compile": "Stop met compileren",
"terminated": "Compileren gestopt",
"compile_terminated_by_user": "Het compileren was gestopt door de 'Stop Compilatie' knop. U kan in de log files zien waar het compileren is gestopt",
"site_description": "Een online LaTeX editor die makkelijk te gebruiken is. Geen installatie, real-time samenwerken, versiecontrole, honderden LaTeX templates en meer.",
"knowledge_base": "Kennisbasis",
"contact_message_label": "Bericht",
"kb_suggestions_enquiry": "Heeft u onze <0>__kbLink__</0> al gezien?",
"answer_yes": "Ja",
"answer_no": "Nee",
"log_hint_extra_info": "Meer informatie",
"log_hint_feedback_label": "Was deze hint behulpzaam?",
"log_hint_feedback_gratitude": "Bedankt voor uw feedback!",
"recompile_pdf": "Hercompileer de PDF",
"about_paulo_reis": "is een front-end software developer en user experience researcher uit Aveiro, Portugal. Paulo heeft een PhD in user experience en is gepassioneerd over het sturen van technologie naar menselijk gebruik - in concept of testen/validatie, in design of implementatie",
"login_or_password_wrong_try_again": "Uw inlognaam of wachtwoord is incorrect. Probeer a.u.b. opnieuw",
"manage_beta_program_membership": "Manage Bèta Programma Lidmaatschap",
"beta_program_opt_out_action": "Uitschrijven uit het Bèta Programma",
"disable_beta": "Schakel Bèta uit",
"beta_program_badge_description": "TIjdens het gebruik van __appName__, zullen bèta opties gemarkeerd zijn met deze badge:",
"beta_program_current_beta_features_description": "We testen momenteel de volgende nieuwe opties in bèta:",
"enable_beta": "Schakel Bèta in",
"user_in_beta_program": "Gebruiker participeert in een Bèta Programma",
"beta_program_already_participating": "U neemt al deel aan het Bèta Programma",
"sharelatex_beta_program": "__appName__ Beta Programma",
"beta_program_benefits": "We zijn altijd bezig met het verbeteren van __appName__. Door deel te nemen aan ons Bèta programma heeft u vervroegd toegang tot nieuwe opties en kan u ons helpen uw wensen beter te begrijpen.",
"beta_program_opt_in_action": "Schrijf in voor Bèta Programma",
"conflicting_paths_found": "Conflicterende Bestandspaden Gevonden",
"following_paths_conflict": "De volgende bestanden en folders hebben hetzelfde bestandspad",
"open_a_file_on_the_left": "Open een bestand aan de linkerkant",
"reference_error_relink_hint": "Als deze foutmelding blijft verschijnen, probeer dan uw account hier opnieuw te linken:",
"pdf_rendering_error": "PDF Render Error",
"something_went_wrong_rendering_pdf": "Er is iets misgegaan tijdens het renderen van deze PDF.",
"mendeley_reference_loading_error_expired": "Mendeley token verlopen, gelieve je account opnieuw te koppelen",
"zotero_reference_loading_error_expired": "Zotero token verlopen, gelieve je account opnieuw te koppelen",
"mendeley_reference_loading_error_forbidden": "Kon referenties niet laden vanaf Mendeley, gelieve je account opnieuw te koppelen en nogmaals te proberen",
"zotero_reference_loading_error_forbidden": "Kon referenties niet laden vanaf Zotero, gelieve je account opnieuw te koppelen en nogmaals te proberen",
"mendeley_integration": "Mendeley Integratie",
"mendeley_sync_description": "Met Mendeley integratie kan u uw referenties uit mendeley in uw __appName__ projecten importeren",
"mendeley_is_premium": "Mendeley Integratie is een premium functie",
"link_to_mendeley": "Verbinden met Mendeley",
"unlink_to_mendeley": "Mendeley Ontkoppelen",
"mendeley_reference_loading": "Referenties laden vanaf Mendeley",
"mendeley_reference_loading_success": "Referenties geladen vanaf Mendeley",
"mendeley_reference_loading_error": "Error, kan referenties niet laden vanaf Mendeley",
"zotero_integration": "Zetro Integratie",
"zotero_is_premium": "Zotero Integratie is een premium functie",
"link_to_zotero": "Verbinden met Zotero",
"unlink_to_zotero": "Zotero Ontkoppelen",
"zotero_reference_loading": "Referenties laden vanaf Zotero",
"zotero_reference_loading_success": "Referenties geladen vanaf Zotero",
"zotero_reference_loading_error": "Error, kan referenties niet laden vanaf Mendeley",
"reference_import_button": "Importeer referenties naar",
"unlink_reference": "Ontkoppel Referentie Provider",
"unlink_warning_reference": "Waarschuwing: Wanneer u uw account van deze provider losmaakt kan u geen referenties meer in uw projecten importeren",
"mendeley": "Mendeley",
"zotero": "Zotero",
"suggest_new_doc": "Stel nieuw document voor",
"request_sent_thank_you": "Verzoek verzonden, bedankt.",
"suggestion": "Suggestie",
"project_url": "Getroffen Project URL",
"subject": "Onderwerp",
"confirm": "Bevestig",
"cancel_personal_subscription_first": "U heeft al een persoonlijke inschrijving, wilt u dat wij deze annuleren voordat u deel neemt aan de groepslicentie?",
"delete_projects": "Verwijder projecten",
"leave_projects": "Verlaat projecten",
"delete_and_leave_projects": "Verwijder en verlaat projecten",
"too_recently_compiled": "Dit project is recentelijk nog gecompileerd, daarom is het nu overgeslagen.",
"clsi_maintenance": "De compilatie servers zijn momenteel in onderhoud, en zullen binnenkort weer beschikbaar zijn.",
"references_search_hint": "Druk op CTRL-Spatie om te zoeken",
"ask_proj_owner_to_upgrade_for_references_search": "Vraag alstublieft de projecteigenaar up te graden om de Zoek Referenties optie te gebruiken",
"ask_proj_owner_to_upgrade_for_faster_compiles": "Vraag alstublieft de projecteigenaar up te graden voor snellere compilaties en een verhoging van de timeout limiet",
"search_bib_files": "Zoek op auteur, titel, jaar",
"leave_group": "Verlaat groep",
"leave_now": "Verlaat nu",
"sure_you_want_to_leave_group": "Weet je zeker dat je deze groep wilt verlaten?",
"notification_group_invite": "Je bent uigenodigd om lid te worden van __groupName__, <a href=\"/user/subscription/__subscription_id__/group/invited\">Word lid</a>.",
"search_references": "Doorzoek het .bib bestand in dit project",
"no_search_results": "Geen zoek resultaten",
"email_already_registered": "Dit e-mailadres is al geregistreerd",
"compile_mode": "Compileer Mode",
"normal": "Normaal",
"fast": "Snel",
"rename_folder": "Hernoem map",
"delete_folder": "Verwijder map",
"about_to_delete_folder": "Je staat op het punt de volgende mappen te verwijderen (projecten in deze mappen zullen niet worden verwijderd):",
"to_modify_your_subscription_go_to": "Om je abonnement aan te passen, ga naar",
"manage_subscription": "Beheer abonnementen",
"activate_account": "Activeer je account",
"yes_please": "Ja alsjeblieft!",
"nearly_activated": "Je bent één stap verwijderd van het activeren van je __appName__ account",
"please_set_a_password": "Gelieve een wachtwoord te kiezen",
"activation_token_expired": "Je activatie token is verlopen, je zal een nieuwe moeten laten versturen.",
"activate": "Activeer",
"activating": "Activeren",
"ill_take_it": "Ik neem hem!",
"cancel_your_subscription": "Annuleer je abonnement",
"no_thanks_cancel_now": "Nee bedankt - Ik wil nog steeds annuleren.",
"cancel_my_account": "Annuleer mijn abonnement",
"sure_you_want_to_cancel": "Weet je zeker dat je wilt annuleren?",
"i_want_to_stay": "Ik wil blijven",
"have_more_days_to_try": "Hier zijn <strong>__days__ dagen</strong> extra Proefperiode!",
"interested_in_cheaper_plan": "Zou je geïnteresseerd zijn in de goedkopere <strong>__price__</strong> studentenaanbieding?",
"session_expired_redirecting_to_login": "Sessie verlopen. Doorsturen naar de inlog pagina in __seconds__ seconden.",
"maximum_files_uploaded_together": "Maximum __max__ bestanden tegelijk geüplaod",
"too_many_files_uploaded_throttled_short_period": "Teveel bestanden geüpload, je uploads zijn afgeknepen voor een korte periode.",
"compile_larger_projects": "Compileer grote projecten",
"upgrade_to_get_feature": "Upgrade om __feature__ te krijgen, plus:",
"new_group": "Nieuwe groep",
"about_to_delete_groups": "Je staat op het punt de volgende groepen te verwijderen:",
"removing": "Verwijderen",
"adding": "Toevoegen",
"groups": "Groepen",
"rename_group": "Hernoem groep",
"renaming": "Hernoemen",
"create_group": "Maak groep",
"delete_group": "Verwijder groep",
"delete_groups": "Verwijder groepen",
"your_groups": "Jouw groepen",
"group_name": "Groepsnaam",
"no_groups": "Geen groepen",
"Subscription": "Abonnementen",
"Documentation": "Documentatie",
"Universities": "Universiteiten",
"Account Settings": "Accountinstellingen",
"Projects": "Projecten",
"Account": "Account",
"global": "globaal",
"Terms": "Voorwaarden",
"Security": "Beveiliging",
"About": "Over",
"editor_disconected_click_to_reconnect": "Verbinding Editor verbroken, klik om opnieuw te verbinden",
"word_count": "Aantal woorden",
"please_compile_pdf_before_word_count": "Compileer je project alvorens het aantal woorden te tellen",
"total_words": "Aantal woorden",
"headers": "Koppen",
"math_inline": "Math Inline",
"math_display": "Math Display",
"connected_users": "Verbonden gebruikers",
"projects": "Projecten",
"upload_project": "Project Uploaden",
"all_projects": "Alle projecten",
"your_projects": "Jouw Projecten",
"shared_with_you": "Gedeeld met jou",
"deleted_projects": "Verwijderde Projecten",
"templates": "Sjablonen",
"new_folder": "Nieuwe Map",
"create_your_first_project": "Maak je eerste project!",
"complete": "Klaar",
"on_free_sl": "Je gebruikt de gratis versie van __appName__",
"upgrade": "Upgraden",
"or_unlock_features_bonus": "of verkrijg bepaalde bonusfuncties door",
"sharing_sl": "__appName__ te delen",
"add_to_folder": "Toevoegen aan map",
"create_new_folder": "Nieuwe Map Maken",
"more": "Meer",
"rename": "Hernoemen",
"make_copy": "Een kopie maken",
"restore": "Herstellen",
"title": "Titel",
"last_modified": "Laatst Gewijzigd",
"no_projects": "Geen projecten",
"welcome_to_sl": "Welkom bij __appName__!",
"new_to_latex_look_at": "Onbekend met LaTeX? Begin door te kijken bij onze",
"or": "of",
"or_create_project_left": "of maak je eerste project aan de linkerkant.",
"thanks_settings_updated": "Bedankt, je instellingen zijn bijgewerkt.",
"update_account_info": "Accountinfo Bijwerken",
"must_be_email_address": "Moet een e-mailadres zijn",
"first_name": "Voornaam",
"last_name": "Achternaam",
"update": "Bijwerken",
"change_password": "Wachtwoord Wijzigen",
"current_password": "Huidige Wachtwoord",
"new_password": "Nieuwe Wachtwoord",
"confirm_new_password": "Bevestig Nieuwe Wachtwoord",
"required": "Vereist",
"doesnt_match": "Komt niet overeen",
"dropbox_integration": "Dropboxintegratie",
"learn_more": "Meer weten",
"dropbox_is_premium": "Synchronisatie met Dropbox is een premium functie",
"account_is_linked": "Account is gekoppeld",
"unlink_dropbox": "Dropbox Ontkoppelen",
"link_to_dropbox": "Verbinden met Dropbox",
"newsletter_info_and_unsubscribe": "Elke paar maanden versturen we een nieuwsbrief met een samenvatting van nieuwe functies. Als je deze e-mail niet wilt ontvangen, dan kun je je er altijd voor uitschrijven:",
"unsubscribed": "Uitgeschreven",
"unsubscribing": "Aan het uitschrijven",
"unsubscribe": "Uitschrijven",
"need_to_leave": "Moet je weg?",
"delete_your_account": "Account verwijderen",
"delete_account": "Account verwijderen",
"delete_account_warning_message": "Je staat op het punt <strong>al je accountgegevens pemanent te verwijderen</strong>, inclusief je projecten en instellingen. Type uw account e-mail adres in het onderstaande tekstvak om verder te gaan.",
"deleting": "Aan het verwijderen",
"delete": "Verwijderen",
"sl_benefits_plans": "__appName__ is de makkelijkste LaTeX-verwerker op aarde. Blijf up-to-date met je bijdragers, houd alle wijzigingen in je werk bij en gebruik onze LaTeX-omgeving waar je ook bent.",
"monthly": "Maandelijks",
"personal": "Persoonlijk",
"free": "Gratis",
"one_collaborator": "Slechts één bijdrager",
"collaborator": "Bijdrager",
"collabs_per_proj": "__collabcount__ bijdragers per project",
"full_doc_history": "Volledige documentsgeschiedenis",
"sync_to_dropbox": "Synchroniseren met Dropbox",
"start_free_trial": "Start Gratis Proefperiode!",
"professional": "Professioneel",
"unlimited_collabs": "Onbeperkt aantal bijdragers",
"name": "Naam",
"student": "Student",
"university": "Universiteit",
"position": "Functie",
"choose_plan_works_for_you": "Kies het abonnement dat bij jou past met onze __len__ dagen gratis proefperiode. Annuleren kan altijd.",
"interested_in_group_licence": "Interesse om __appName__ te gebruiken met een groeps-, team- of afdelingsaccount?",
"get_in_touch_for_details": "Contacteer ons voor details!",
"group_plan_enquiry": "Info Aanvragen Over Groepsabonnementen",
"enjoy_these_features": "Geniet van al deze gave functies",
"create_unlimited_projects": "Creëer zoveel projecten als je maar nodig hebt.",
"never_loose_work": "Raak geen stap kwijt, daar zorgen wij voor.",
"access_projects_anywhere": "Krijg overal toegang tot je projecten.",
"log_in": "Inloggen",
"login": "Inloggen",
"logging_in": "Aan het inloggen",
"forgot_your_password": "Wachtwoord vergeten",
"password_reset": "Wachtwoord Herstellen",
"password_reset_email_sent": "Er is een e-mail naar je verstuur om je wachtwoordreset te voltooien.",
"please_enter_email": "Vul je e-mailadres in",
"request_password_reset": "Wachtwoordherstel aanvragen",
"reset_your_password": "Herstel je wachtwoord",
"password_has_been_reset": "Je wachtwoord is hersteld",
"login_here": "Log hier in",
"set_new_password": "Nieuw wachtwoord instellen",
"user_wants_you_to_see_project": "__username__ wil dat u deelneemt aan __projectname__",
"join_sl_to_view_project": "Word lid van __appName__ om dit project te bekijken",
"register_to_edit_template": "Registreet om het sjabloon __templateName__ te bewerken",
"already_have_sl_account": "Heb je al een __appName__-account?",
"register": "Registreren",
"password": "Wachtwoord",
"registering": "Aan het registreren",
"planned_maintenance": "Gepland Onderhoud",
"no_planned_maintenance": "Er is op dit moment geen gepland onderhoud",
"cant_find_page": "Sorry, we kunnen die pagina waar je naar zocht niet vinden.",
"take_me_home": "Terug naar huis dan maar!",
"no_preview_available": "Sorry, er is geen voorbeeld beschikbaar.",
"no_messages": "Geen berichten",
"send_first_message": "Verzend je eerste bericht",
"account_not_linked_to_dropbox": "Je account is niet gekoppeld aan Dropbox",
"update_dropbox_settings": "Dropboxinstellingen Updaten",
"refresh_page_after_starting_free_trial": "Ververs deze pagina nadat je de gratis proefperiode hebt gestart.",
"checking_dropbox_status": "Dropboxstatus aan het controleren",
"dismiss": "Verbergen",
"new_file": "Nieuw Bestand",
"upload_file": "Bestand Uploaden",
"create": "Creëren",
"creating": "Aan het maken",
"upload_files": "Bestand(en) Uploaden",
"sure_you_want_to_delete": "Weet je zeker dat je de volgende bestanden permanent wilt verwijderen?",
"common": "Veelvoorkomend",
"navigation": "Navigatie",
"editing": "Aan het bewerken",
"ok": "OK",
"source": "Bron",
"actions": "Acties",
"copy_project": "Project Kopiëren",
"publish_as_template": "Publiceren als Sjabloon",
"sync": "Synchronisatie",
"settings": "Instellingen",
"main_document": "Hoofddocument",
"off": "Uit",
"auto_complete": "Autocorrectie",
"theme": "Thema",
"font_size": "Lettergrootte",
"pdf_viewer": "PDF-lezer",
"built_in": "Ingebouwd",
"native": "Browserkeuze",
"show_hotkeys": "Sneltoetsen Tonen",
"new_name": "Nieuwe Naam",
"copying": "aan het kopiëren",
"copy": "Kopiëren",
"compiling": "Aan het compileren",
"click_here_to_preview_pdf": "Klik hier om je werk als PDF te bekijken.",
"server_error": "Serverfout",
"somthing_went_wrong_compiling": "Sorry, er ging iets fout en je project kon niet gecompileerd worden. Probeer het over enkele ogenblikken opnieuw.",
"timedout": "Time-out",
"proj_timed_out_reason": "Sorry, je compilatie duurde te lang en bereikte de time-out. Dit zou kunnen komen door een groot aantal afbeeldingen in hoge resolutie, of veel gecompliceerde diagrammen.",
"no_errors_good_job": "Geen fouten, goed bezig!",
"compile_error": "Compilatiefout",
"generic_failed_compile_message": "Sorry, je LaTeX-code kon niet gecompileerd worden om een bepaalde reden. Bekijk de onderstaande foutmeldingen voor meer details, of bekijk de rauwe log",
"other_logs_and_files": "Andere logs en bestanden",
"view_raw_logs": "Rauwe Logs Bekijken",
"hide_raw_logs": "Rauwe Logs Verbergen",
"clear_cache": "Tijdelijk geheugen wissen",
"clear_cache_explanation": "Dit zal alle verborgen LaTeX-bestanden (.aux, .bbl, etc.) van onze compilatieserver verwijderen. Over het algemeen hoef je dit niet te doen, tenzij je problemen hebt met referenties.",
"clear_cache_is_safe": "Je projectbestanden zullen niet verwijderd of gewijzigd worden.",
"clearing": "Aan het leegmaken",
"template_description": "Sjabloonbeschrijving",
"project_last_published_at": "Je project is voor het laatst gepubliceerd om",
"problem_talking_to_publishing_service": "Er is een probleem met onze publicatiedienst, probeer het over enkele minuten opnieuw",
"unpublishing": "Aan het ontpubliceren",
"republish": "Herpubliceren",
"publishing": "Aan het publiceren",
"share_project": "Project Delen",
"this_project_is_private": "Dit project is privé en kan alleen door onderstaande personen bekeken worden.",
"make_public": "Publiek Toegankelijk Maken",
"this_project_is_public": "Dit project is publiek toegankelijk en kan gewijzigd worden door iedereen die de URL heeft.",
"make_private": "Privé Maken",
"can_edit": "Kan Bewerken",
"share_with_your_collabs": "Delen met je bijdragers",
"share": "Delen",
"need_to_upgrade_for_more_collabs": "Je dient je account te upgraden om meer bijdragers toe te voegen",
"make_project_public": "Project publiek toegankelijk maken",
"make_project_public_consequences": "Als je je project publiek toegankelijk maakt, dan kan iedereen die de URL heeft toegang verkrijgen.",
"allow_public_editing": "Publieke wijzigingen toestaan",
"allow_public_read_only": "Publiekelijk alleen-lezen toegang toestaan",
"make_project_private": "Project privé maken",
"make_project_private_consequences": "Als je je project privé maakt, dan kunnen alleen de personen die jij kiest toegang verkrijgen.",
"need_to_upgrade_for_history": "Je moet je account upgraden om de Geschiedenis te gebruiken.",
"ask_proj_owner_to_upgrade_for_history": "Vraag de eigenaar van het project om te upgraden om de Geschiedenis te gebruiken.",
"anonymous": "Anoniem",
"generic_something_went_wrong": "Sorry, er ging iets fout",
"restoring": "Aan het herstellen",
"restore_to_before_these_changes": "Herstellen naar voordat deze wijzigingen waren aangebracht",
"profile_complete_percentage": "Je profiel is __percentval__% volledig",
"file_has_been_deleted": "__filename__ is verwijderd",
"sure_you_want_to_restore_before": "Weet je zeker dat je <0>__filename__</0> wilt herstellen naar de versie voor de veranderingen van __date__?",
"rename_project": "Project Hernoemen",
"about_to_delete_projects": "Je staat op het punt de volgende projecten te verwijderen:",
"about_to_leave_projects": "Je staat op het punt de volgende projecten te verlaten:",
"upload_zipped_project": "Gezipt Project Uploaden",
"upload_a_zipped_project": "Upload een gezipt project",
"your_profile": "Jouw Profiel",
"institution": "Instelling",
"role": "Functie",
"folders": "Mappen",
"disconnected": "Niet Verbonden",
"please_refresh": "Ververs de pagina om door te gaan.",
"lost_connection": "Verbinding Verbroken",
"reconnecting_in_x_secs": "Opnieuw verbinden over __seconds__ seconden",
"try_now": "Nu Proberen",
"reconnecting": "Opnieuw aan het verbinden",
"saving_notification_with_seconds": "__docname__ aan het opslaan... (__seconds__ seconden aan niet-opgeslagen wijzigingen)",
"help_us_spread_word": "Help __appName__ meer naamsbekendheid te krijgen",
"share_sl_to_get_rewards": "Deel __appName__ met je vrienden en collega's en verkrijg onderstaande beloningen",
"post_on_facebook": "Delen op Facebook",
"share_us_on_googleplus": "Deel on op Google+",
"email_us_to_your_friends": "E-mail ons naar je vrienden",
"link_to_us": "Link naar ons op je website",
"direct_link": "Directe Link",
"sl_gives_you_free_stuff_see_progress_below": "Wanneer iemand __appName__ gaat gebruiken dankzij jouw aanbeveling, geven we jou <strong>gratis functies</strong> als bedankje! Bekijk je voortgang hieronder.",
"spread_the_word_and_fill_bar": "Vertel anderen over ons en vul deze balk op",
"one_free_collab": "Één gratis bijdrager",
"three_free_collab": "Drie gratis bijdragers",
"free_dropbox_and_history": "Gratis Dropbox en Geschiedenis",
"you_not_introed_anyone_to_sl": "Je hebt nog niemand geïntroduceerd bij __appName__ . Deel nu!",
"you_introed_small_number": " Je hebt <0>__numberOfPeople__</0> persoon bij __appName__ geïntroduceerd. Goed gedaan, maar kun je er meer overhalen?",
"you_introed_high_number": " Je hebt <0>__numberOfPeople__</0> personen bij __appName__ geïntroduceerd. Goed gedaan!",
"link_to_sl": "Linken naar __appName__",
"can_link_to_sl_with_html": "Je kunt naar __appName__ linken via de volgende HTML-code:",
"year": "jaar",
"month": "maand",
"subscribe_to_this_plan": "Hierop abonneren",
"your_plan": "Jouw abonnement",
"your_subscription": "Jouw Abonnement",
"on_free_trial_expiring_at": "Je zit op dit moment in een gratis proefperiode die eindigt op __expiresAt__.",
"choose_a_plan_below": "Kies hieronder het abonnement om je voor in te schrijven.",
"currently_subscribed_to_plan": "Je bent op dit moment geabonneerd op <0>__planName__</0>.",
"change_plan": "Abonnement wijzigen",
"next_payment_of_x_collectected_on_y": "De volgende betaling van <0>__paymentAmmount__</0> zal worden geïnd op <1>__collectionDate__</1>",
"update_your_billing_details": "Werk Je Factuurgegevens Bij",
"subscription_canceled_and_terminate_on_x": " Je abonnement is geannuleerd en zal eindigen op <0>__terminateDate__</0>. Er zullen geen betalingen meer worden vereist.",
"your_subscription_has_expired": "Je abonnement is verlopen.",
"create_new_subscription": "Nieuw Abonnement Maken",
"problem_with_subscription_contact_us": "Er is een probleem met je abonnement. Neem contact met ons op voor meer informatie.",
"manage_group": "Groep Beheren",
"loading_billing_form": "Factuurgegevens laden van",
"you_have_added_x_of_group_size_y": "Je hebt <0>__addedUsersSize__</0> van de <1>__groupSize__</1> beschikbare leden",
"remove_from_group": "Uit groep verwijderen",
"group_account": "Groepsaccount",
"registered": "Geregistreerd",
"no_members": "Geen leden",
"add_more_members": "Meer leden toevoegen",
"add": "Toevoegen",
"thanks_for_subscribing": "Bedankt voor het abonneren!",
"your_card_will_be_charged_soon": "Je creditcard zal binnenkort worden afgeschreven.",
"if_you_dont_want_to_be_charged": "Als je niet meer gefactureerd wilt worden ",
"add_your_first_group_member_now": "Voeg je eerste groepsleden nu toe",
"thanks_for_subscribing_you_help_sl": "Bedankt voor het abonneren op __planName__. De ondersteuning van mensen zoals jij maakt het mogelijk dat __appName__ groeit en verbetert.",
"back_to_your_projects": "Terug naar je projecten",
"goes_straight_to_our_inboxes": "Het gaat direct naar ons postvak-in",
"need_anything_contact_us_at": "Als er iets is dat je ooit nodig hebt, neem gerust direct contact met ons op via",
"regards": "Groeten",
"about": "Over",
"comment": "Reageren",
"restricted_no_permission": "Beperkt, sorry. Je hebt geen toegang tot deze pagina.",
"online_latex_editor": "Online LaTeX-verwerker",
"meet_team_behind_latex_editor": "Maak kennis met het team achter jouw favoriete online LaTeX-verwerker.",
"follow_me_on_twitter": "Volg mij op Twitter",
"motivation": "Motivatie",
"evolved": "Verfijnd",
"the_easy_online_collab_latex_editor": "De gemakkelijke, online LaTeX-verwerker voor samenwerking",
"get_started_now": "Ga nu aan de slag",
"sl_used_over_x_people_at": "__appName__ wordt gebruikt door meer dan __numberOfUsers__ studenten en academici aan:",
"collaboration": "Samenwerking",
"work_on_single_version": "Werk samen in één versie",
"view_collab_edits": "Bekijk wijzigingen door bijdragers ",
"ease_of_use": " Gebruiksgemak",
"no_complicated_latex_install": "Geen gecompliceerde LaTeX-installatie",
"all_packages_and_templates": "Alle pakketten en <0>__templatesLink__</0> die je nodig hebt",
"document_history": "Documentsgeschiedenis",
"see_what_has_been": "Zie wat er is ",
"added": "toegevoegd",
"and": "en",
"removed": "verwijderd",
"restore_to_any_older_version": "Herstel naar elke willekeurige oudere versie",
"work_from_anywhere": "Werk vanaf waar ook ter wereld",
"acces_work_from_anywhere": "Je werk is overal op aarde toegankelijk",
"work_offline_and_sync_with_dropbox": "Werk offline en synchroniseer je bestanden via Dropbox en GitHub",
"over": "meer dan",
"view_templates": "Sjablonen bekijken",
"nothing_to_install_ready_to_go": "Er is niks moeilijks dat je moet installeren en je kunt <0>__start_now__</0>, zelfs als je het nooit eerder hebt gebruikt. __appName__ bevat een complete LaTeX-omgeving die klaar is voor gebruik en draait op onze servers.",
"start_using_latex_now": "nu beginnen met LaTeX",
"get_same_latex_setup": "Met __appName__ krijg je overal waar je bent dezelfde LaTeX-installatie. Door samen met je collega's en studenten te werken op __appName__, weet je zeker dat je geen versieproblemen of conflicterende pakketten tegen zult komen.",
"support_lots_of_features": "We ondersteunen bijna alle LaTeX-functies, waaronder het invoegen van afbeeldingen, bibliografieën, vergelijkingen en nog veel meer! Lees over alle leuke dingen die je kunt doen met __appName__ in onze <0>__help_guides_link__</0>",
"latex_guides": "LaTeX-gidsen",
"reset_password": "Wachtwoord Herstellen",
"set_password": "Wachtwoord Instellen",
"updating_site": "Site Aan Het Updaten",
"bonus_please_recommend_us": "Bonus - Beveel on aan",
"admin": "beheerder",
"subscribe": "Abonneren",
"update_billing_details": "Factuurgegevens Bijwerken",
"group_admin": "Groepsbeheerder",
"all_templates": "Alles Sjablonen",
"your_settings": "Jouw instellingen",
"maintenance": "Onderhous",
"to_many_login_requests_2_mins": "Er is te vaak geprobeerd bij dit account in te loggen. Wacht 2 minuten alvorens het opnieuw te proberen.",
"email_or_password_wrong_try_again": "Je e-mailadres of wachtwoord is incorrect. Probeer het opnieuw",
"rate_limit_hit_wait": "Frequentielimiet bereikt. Wacht een moment voordat je het nogmaals probeert",
"problem_changing_email_address": "Er was een probleem tijdens het veranderen van je e-mailadres. Probeer het over een ogenblik opnieuw. Als het probleem blijft bestaan, neem dan a.u.b. contact met ons op.",
"single_version_easy_collab_blurb": "__appName__ zorgt ervoor dat je altijd up-to-date bent met je bijdragers en wat zij doen. Er is maar één hoofdversie van elk document, waar iedereen toegang tot heeft. Het is onmogelijk om conflicterende wijzigingen aan te brengen en je hoeft niet te wachten op de bewerkingen van je collega's, voordat je zelf aan de slag kunt gaan.",
"can_see_collabs_type_blurb": "Als meerdere mensen tegelijkertijd willen werken in een document, dan is dat geen enkel probleem. Je kunt direct in de verwerker zien waar je collega's typen en hun wijzigingen zie je meteen op je scherm.",
"work_directly_with_collabs": "Werk direct met je bijdragers",
"work_with_word_users": "Werk samen met Wordgebruikers",
"work_with_word_users_blurb": "__appName__ is zo eenvoudig om mee te beginnen, dat je al je collega's die geen LaTeX kennen gewoon kunt uitnodigen om direct aan je LaTeX-documenten bij te dragen. Ze kunnen productief te werk gaan vanaf dag één en langzamerhand leren omgaan met LaTeX.",
"view_which_changes": "Bekijk welke wijzigingen zijn",
"sl_included_history_of_changes_blurb": "__appName__ houdt een geschiedenis bij van alle wijzigingen, zodat je precies kunt zien wie wat heeft veranderd. Dit maakt het extreem gemakkelijk om up-to-date te blijven met vorderingen gemaakt door je bijdragers en je kunt recent werk beoordelen.",
"can_revert_back_blurb": "Zowel in samenwerkingsverband als in je eentje worden soms fouten gemaakt. Een vorige versie herstellen is eenvoudig en elimineert het risico op verlies van je werk of spijt van een wijziging.",
"start_using_sl_now": "Start nu met __appName__",
"over_x_templates_easy_getting_started": "Er zijn __over__ 400 __templates__ in onze sjablonengalerij, dus het is heel makkelijk om aan de slag te gaan, of je nu een tijdschriftartikel, scriptie, CV of iets anders schrijft.",
"done": "Klaar",
"change": "Wijzigen",
"page_not_found": "Pagina Niet Gevonden",
"please_see_help_for_more_info": "Zie onze hulpgids voor meer informatie",
"this_project_will_appear_in_your_dropbox_folder_at": "Dit project zal verschijnen in je Dropbox map in ",
"member_of_group_subscription": "Je account valt onder een groepsabonnement, beheerd door __admin_email__. Neem contact op met hem/haar om je account te beheren.\n",
"about_henry_oswald": "is een software-ingenieur en woont in Londen. Hij heeft het originele prototype van __appName__ gebouwd en is verantwoordelijk voor het bouwen van een stabiel en schaalbaar platform. Henry is sterke voorstander van Test Driven Development en zorgt ervoor dat we de __appName__-code schoon en makkelijk te onderhouden houden.",
"about_james_allen": "heeft een doctoraat in theoretische natuurkunde en heeft een passie voor LaTeX. Hij heeft één van de eerste online LaTeX-verwerkers, ScribTeX, gecreëerd en heeft een belangrijke rol gespeeld bij de ontwikkeling van de technologieën die __appName__ mogelijk maken.",
"two_strong_principles_behind_sl": "Er zijn twee sterke leidende principes die ten grondslag liggen aan ons werk op __appName__:",
"want_to_improve_workflow_of_as_many_people_as_possible": "We willen de werkstroom van zo veel mogelijk mensen verbeteren.",
"detail_on_improve_peoples_workflow": "LaTeX is berucht om zijn moeilijkheid in gebruik en samenwerking is altijd moeilijk om te coördineren. Wij geloven dat we een aantal goede oplossingen hebben ontwikkeld voor mensen die dit soort problemen hebben. We willen ervoor zorgen dat __appName__ bereikbaar is voor zo veel mogelijk mensen. Daarom proberen we onze prijzen eerlijk te houden en hebben veel van __appName__ open source gemaakt, zodat iedereen zijn eigen versie kan gebruiken.",
"want_to_create_sustainable_lasting_legacy": "We willen een duurzame en doorlopende nalatenschap creëren.",
"details_on_legacy": "Het ontwikkelen en onderhouden van een product als __appName__ kost veel tijd en werk, dus is het belangrijk dat we een bedrijfsmodel vinden dat zowel het heden, als de verre toekomst ondersteunt. We willen niet dat __appName__ afhankelijk is van externe financiering of dat het verdwijnt door een gefaalde bedrijfsstrategie. Ik ben blij dat we op dit moment __appName__ winstgevend en duurzaam kunnen draaien en ik verwacht dat dit ook in de toekomst zo blijft.",
"get_in_touch": "Contacteer ons",
"want_to_hear_from_you_email_us_at": "We horen graag van iedereen die __appName__ gebruikt of die gewoon even wil kletsen met ons over wat we allemaal doen. Je kunt ons bereiken via ",
"cant_find_email": "Dat e-mailadres is niet geregistreerd, sorry.",
"plans_amper_pricing": "Abonnementen en Prijzen",
"documentation": "Documentatie",
"account": "Account",
"subscription": "Abonnementen",
"log_out": "Uitloggen",
"en": "Engels",
"pt": "Portugees",
"es": "Spaans",
"fr": "Frans",
"de": "Duits",
"it": "Italiaans",
"da": "Deens",
"sv": "Zweeds",
"no": "Noors",
"nl": "Nederlands",
"pl": "Pools",
"ru": "Russisch",
"uk": "Oekraïens",
"ro": "Roemeens",
"click_here_to_view_sl_in_lng": "Klik hier om __appName__ te gebruiken in het <0>__lngName__</0>",
"language": "Taal",
"upload": "Uploaden",
"menu": "Menu",
"full_screen": "Volledig scherm",
"logs_and_output_files": "Logs en outputbestanden",
"download_pdf": "PDF Downloaden",
"split_screen": "Gesplitst scherm",
"clear_cached_files": "Wis bestanden in tijdelijke geheugen",
"go_to_code_location_in_pdf": "Ga naar codelocatie in de PDF",
"please_compile_pdf_before_download": "Compileer je project alvorens de PDF te downloaden",
"remove_collaborator": "Bijdrager verwijderen",
"add_to_folders": "Aan mappen toevoegen",
"download_zip_file": "Als .zip-bestand downloaden",
"price": "Prijs",
"close": "Sluiten",
"keybindings": "Sneltoetsen",
"restricted": "Beperkt",
"start_x_day_trial": "Start Jouw __len__ Dagen Durende Gratis Proefperiode Vandaag!",
"buy_now": "Nu kopen!",
"cs": "Tsjechisch",
"view_all": "Alle Bekijken",
"terms": "Voorwaarden",
"privacy": "Privacy",
"contact": "Contact",
"change_to_this_plan": "Overstappen naar dit abonnement",
"processing": "aan het verwerken",
"sure_you_want_to_change_plan": "Weet je zeker dat je wilt overstappen naar <0>__planName__</0>?",
"move_to_annual_billing": "Overstappen op Jaarlijkse Facturen",
"annual_billing_enabled": "Jaarlijkse facturen staan aan",
"move_to_annual_billing_now": "Nu overstappen op jaarlijkse facturen",
"change_to_annual_billing_and_save": "Krijg <0>__percentage__</0> korting met jaarlijkse facturen. Als je nu overstapt, bespaar je <1>__yearlySaving__</1> per jaar.",
"missing_template_question": "Missend Sjabloon?",
"tell_us_about_the_template": "Als we een sjabloon missen, doe dan a.u.b. het volgende: stuur ons een kopie van het sjabloon, een __appName__-URL naar het sjabloon of laat ons weten waar het te vinden is. Vertel ook kort wat het sjabloon inhoudt voor de beschrijving die erbij komt te staan.",
"email_us": "E-mail ons",
"this_project_is_public_read_only": "Dit project is publiek toegankelijk en kan bekeken, maar niet bewerkt worden door iedereen die de URL heeft",
"tr": "Turks",
"select_files": "Selecteer bestand(en)",
"drag_files": "sleep bestand(en)",
"upload_failed_sorry": "Het uploaden is niet gelukt, sorry :(",
"inserting_files": "Bestand aan het invoegen...",
"password_reset_token_expired": "Je wachtwoordherstelsleutel is verlopen. Vraag een nieuwe herstel-e-mail aan en volg daarin de link.",
"merge_project_with_github": "Project samenvoegen met GitHub",
"pull_github_changes_into_sharelatex": "Wijzigingen op GitHub naar __appName__ halen",
"push_sharelatex_changes_to_github": "Wijzigingen op __appName__ naar GitHub verplaatsen",
"features": "Functies",
"commit": "Toevoegen",
"commiting": "Aan het toevoegen",
"importing_and_merging_changes_in_github": "Veranderingen aan het importeren en toevoegen in GitHub",
"upgrade_for_faster_compiles": "Upgrade om sneller te compileren en om de time-out limiet te verhogen.",
"free_accounts_have_timeout_upgrade_to_increase": "Gratis accounts hebben een time-out van een minuut. Upgrade om de time-out limiet te verhogen.",
"learn_how_to_make_documents_compile_quickly": "Leer hoe je project sneller kan compileren",
"zh-CN": "Chinees",
"cn": "Chinees (vereenvoudigd)",
"sync_to_github": "Synchroniseer met GitHub",
"sync_to_dropbox_and_github": "Synchroniseer met Dropbox en GitHub",
"project_too_large": "Project is te groot",
"project_too_large_please_reduce": "Dit project bevat teveel tekst, probeer dit te verminderen. De grootste bestanden zijn:",
"please_ask_the_project_owner_to_link_to_github": "Vraag de projecteigenaar om het project te koppelen aan een GitHub repository",
"go_to_pdf_location_in_code": "Ga naar de PDF-locatie in de code",
"ko": "Koreaans",
"ja": "Japans",
"about_brian_gough": "is een software ontwikkelaar en voormalig theoretische hoogspanningsnatuurkundige aan Fermilab en Los Alamos. Al vele jaren publiceerde hij gratis software handleidingen commercieel gebruikmakend van TeX en LaTeX en was ook de onderhouder van de GNU Scientific Library.",
"first_few_days_free": "Eerste __trialLen__ dagen gratis",
"every": "per",
"credit_card": "Creditcard",
"credit_card_number": "Creditcard nummer",
"invalid": "Ongeldige",
"expiry": "Vervaldatum",
"january": "januari",
"february": "februari",
"march": "maart",
"april": "april",
"may": "mei",
"june": "juni",
"july": "juli",
"august": "augustus",
"september": "september",
"october": "oktober",
"november": "november",
"december": "december",
"zip_post_code": "Postcode",
"city": "Stad",
"address": "Straat",
"coupon_code": "Coupon code",
"country": "Land",
"billing_address": "Factuuradres",
"upgrade_now": "Upgrade Nu",
"state": "Provincie",
"vat_number": "BTW nummer",
"you_have_joined": "Je bent lid geworden van __groupName__",
"claim_premium_account": "Je hebt je premiumaccount via __groupName__ geclaimd.",
"you_are_invited_to_group": "Je bent uitgenodigd om lid te worden van __groupName__",
"you_can_claim_premium_account": "Je kun een premiumaccount claimen dat door __groupName__ wordt aangeboden door je e-mail te verifiëren",
"not_now": "Niet nu",
"verify_email_join_group": "E-mail verifiëren en lid worden van Groep",
"check_email_to_complete_group": "Controleer je e-mail om je lidmaatschap van de groep te voltooien",
"verify_email_address": "E-mailadres Verifiëren",
"group_provides_you_with_premium_account": "__groupName__ voorziet je van een premiumaccount. Verifieer je e-mailadres om je account te upgraden.",
"check_email_to_complete_the_upgrade": "Controleer je e-mail om je upgrade te voltooien",
"email_link_expired": "E-maillink is verlopen, vraag een nieuwe aan.",
"services": "Diensten",
"about_shane_kilkelly": "is een software ontwikkelaar woonachtig in Edinburgh. Shane is een sterk voorstander van Functioneel Programmeren, Test Driven Development en haalt voldoening uit het bouwen van kwaliteits software.",
"this_is_your_template": "Dit is jouw sjabloon uit jouw project",
"links": "Links",
"account_settings": "Accountinstellingen",
"search_projects": "Projecten zoeken",
"clone_project": "Project Klonen",
"delete_project": "Project Verwijderen",
"download_zip": "Downloaden Als Zip",
"new_project": "Nieuw Project",
"blank_project": "Blanco Project",
"example_project": "Voorbeeldproject",
"from_template": "Vanuit sjabloon",
"cv_or_resume": "CV",
"cover_letter": "Sollicitatiebrief",
"journal_article": "Tijdschriftartikel",
"presentation": "Presentatie",
"thesis": "Scriptie",
"bibliographies": "Bibliografieën",
"terms_of_service": "Gebruiksvoorwaarden",
"privacy_policy": "Privacybeleid",
"plans_and_pricing": "Abonnementen en Prijzen",
"university_licences": "Licenties Voor Universiteiten",
"security": "Veiligheid",
"contact_us": "Contact",
"thanks": "Bedankt",
"blog": "Blog",
"latex_editor": "LaTeX-verwerker",
"get_free_stuff": "Verkrijg gratis dingen",
"chat": "Chat",
"your_message": "Jouw Bericht",
"loading": "Aan het laden",
"connecting": "Aan het verbinden",
"recompile": "Hercompileren",
"download": "Downloaden",
"email": "E-mail",
"owner": "Eigenaar",
"read_and_write": "Lezen en Schrijven",
"read_only": "Alleen Lezen",
"publish": "Publiceren",
"view_in_template_gallery": "Bekijk het in de sjablonengalerij",
"description": "Beschrijving",
"unpublish": "Onpubliceren",
"hotkeys": "Sneltoetsen",
"saving": "Aan het opslaan",
"cancel": "Annuleren",
"project_name": "Projectnaam",
"root_document": "Hoofddocument",
"spell_check": "Spellingscontrole",
"compiler": "Compilator",
"private": "Privé",
"public": "Publiek",
"delete_forever": "Voor Altijd Verwijderen",
"support_and_feedback": "Ondersteuning en feedback",
"help": "Help",
"latex_templates": "LaTeX-sjablonen",
"info": "Info",
"latex_help_guide": "LaTeX-hulpgids",
"choose_your_plan": "Kies je abonnement",
"indvidual_plans": "Individuele Abonnementen",
"free_forever": "Voor altijd gratis",
"low_priority_compile": "Compileren met lage prioriteit",
"unlimited_projects": "Onbeperkt aantal projecten",
"unlimited_compiles": "Onbeperkt aantal compilaties",
"full_history_of_changes": "Volledige wijzigingsgeschiedenis",
"highest_priority_compiling": "Hoogste compilatieprioriteit",
"dropbox_sync": "Dropbox-synchronisatie",
"beta": "Beta",
"sign_up_now": "Nu Inschrijven",
"annual": "Jaarlijks",
"half_price_student": "Studentenabonnementen voor de halve prijs",
"about_us": "Over Ons",
"loading_recent_github_commits": "Recente toevoegingen laden",
"no_new_commits_in_github": "Geen nieuwe toevoegingen op GitHub sinds laatste samenvoeging.",
"dropbox_sync_description": "Houd je __appName__-projecten gesynchroniseerd met je Dropbox veranderingen in __appName__ worden automatisch naar Dropbox verzonden en andersom.",
"github_sync_description": "Met GitHub Sync kun je je __appName__-projecten koppelen aan GitHub repositories. Maak nieuwe toevoegingen vanuit __appName__ en voeg deze samen met toevoegingen die offline of in GitHub gemaakt zijn.",
"github_import_description": "Met GitHub Sync kun je je GitHub repositories importeren in __appName__. Maak nieuwe toevoegingen vanuit __appName__ en voeg deze samen met toevoegingen die offline of in GitHub gemaakt zijn.",
"link_to_github_description": "Je dient __appName__ te autoriseren voor toegang tot je GitHub-account om je projecten te synchroniseren.",
"unlink": "Ontkoppelen.",
"unlink_github_warning": "Projecten die je gesynchroniseerd hebt met GitHub zullen niet meer gekoppeld zijn en niet meer gesynchroniseerd worden met GitHub. Weet je zeker dat je je GitHub-account wilt ontkoppelen?",
"github_account_successfully_linked": "GitHub-account Met Succes Gekoppeld!",
"github_successfully_linked_description": "Bedankt, we hebben je GitHub-account kunnen koppelen aan __appName__. Je kunt nu je __appName__-projecten exporteren naar GitHub, of je projecten vanuit je GitHub repositories importeren.",
"import_from_github": "Uit GitHub importeren",
"github_sync_error": "Sorry, er trad een fout op tijdens het communiceren met onze GitHub-dienst. Probeer het opnieuw over een ogenblik.",
"loading_github_repositories": "Bezig met laden van jouw GitHub repositories",
"select_github_repository": "Selecteer een GitHub repository om naar __appName__ te importeren.",
"import_to_sharelatex": "Naar __appName__ importeren",
"importing": "Aan het importeren",
"github_sync": "GitHub-synchonisatie",
"checking_project_github_status": "Bezig met controleren van de projectstatus in GitHub",
"account_not_linked_to_github": "Je account is niet verbonden met GitHub",
"project_not_linked_to_github": "Dit project is niet verbonden aan het GitHub repository. Je kunt er een repository voor aanmaken in GitHub:",
"create_project_in_github": "Een GitHub repository maken",
"project_synced_with_git_repo_at": "Dit project is gesynchroniseerd met de GitHub repository op",
"recent_commits_in_github": "Recente toevoegingen in GitHub",
"sync_project_to_github": "Project synchroniseren met GitHub",
"sync_project_to_github_explanation": "Aangebrachte wijzigingen in __appName__ zullen worden toegevoegd en samengevoegd met updates in GitHub.",
"github_merge_failed": "Jouw wijzigingen in __appName__ en GitHub konden niet automatisch samengevoegd worden. Doe dit handmatig door de <0>__sharelatex_branch__</0>-tak met de <1>__master_branch__</1>-tak in git samen te voegen. Klik hieronder om door te gaan, nadat je handmatig hebt samengevoegd.",
"continue_github_merge": "Ik heb handmatig samengevoegd. Doorgaan.",
"export_project_to_github": "Project exporteren naar GitHub",
"github_validation_check": "Controleer of de naam van de repository geldig is en of je toestemming heb om de repository te maken.",
"repository_name": "Repository-naam",
"optional": "Optioneel",
"github_public_description": "Iedereen kan deze repository zien. Jij kiest wie eraan kan bijdragen.",
"github_commit_message_placeholder": "Bericht voor wijzigingen aangebracht in __appName__...",
"merge": "Samenvoegen",
"merging": "Bezig met samenvoegen",
"github_account_is_linked": "Je GitHubaccount is met succes verbonden.",
"unlink_github": "Ontkoppel je GitHubaccount",
"link_to_github": "Verbinden met je GitHubaccount",
"github_integration": "GitHubintegratie",
"github_is_premium": "GitHubsnychronisatie is een premium functie",
"thank_you": "Dankjewel"
}
| overleaf/web/locales/nl.json/0 | {
"file_path": "overleaf/web/locales/nl.json",
"repo_id": "overleaf",
"token_count": 21345
} | 550 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['server-ce', 'server-pro', 'saas']
const indexes = [
{
key: {
project_id: 1,
},
name: 'project_id_1',
},
{
key: {
ts: 1,
},
name: 'ts_1',
expireAfterSeconds: 2592000,
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.docSnapshots, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.docSnapshots, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145007_create_docSnapshots_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145007_create_docSnapshots_indexes.js",
"repo_id": "overleaf",
"token_count": 274
} | 551 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['server-ce', 'server-pro', 'saas']
const indexes = [
{
key: {
expires: 1,
},
name: 'expires_1',
expireAfterSeconds: 10,
},
{
key: {
projectId: 1,
},
name: 'projectId_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.projectInvites, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.projectInvites, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145023_create_projectInvites_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145023_create_projectInvites_indexes.js",
"repo_id": "overleaf",
"token_count": 271
} | 552 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['server-ce', 'server-pro', 'saas']
exports.migrate = async client => {
const { db } = client
// deletedUsers did not have an index before
await Helpers.dropIndexesFromCollection(db.deletedProjects, [
{
key: {
'deleterData.deletedProjectId': 1,
},
name: 'deleterData.deletedProjectId_1',
},
])
// deletedUsers did not have an index before
await Helpers.addIndexesToCollection(db.deletedProjects, [
{
key: {
'deleterData.deletedProjectId': 1,
},
unique: true,
name: 'deleterData.deletedProjectId_1',
},
])
await Helpers.addIndexesToCollection(db.deletedUsers, [
{
key: {
'deleterData.deletedUserId': 1,
},
unique: true,
name: 'deleterData.deleteUserId_1',
},
])
}
exports.rollback = async client => {
const { db } = client
await Helpers.dropIndexesFromCollection(db.deletedProjects, [
{
key: {
'deleterData.deletedProjectId': 1,
},
unique: true,
name: 'deleterData.deletedProjectId_1',
},
])
await Helpers.dropIndexesFromCollection(db.deletedUsers, [
{
key: {
'deleterData.deletedUserId': 1,
},
unique: true,
name: 'deleterData.deleteUserId_1',
},
])
await Helpers.addIndexesToCollection(db.deletedProjects, [
{
key: {
'deleterData.deletedProjectId': 1,
},
name: 'deleterData.deletedProjectId_1',
},
])
// deletedUsers did not have an index before
}
| overleaf/web/migrations/20200210121103_uniqueify-deletedthings-indexes.js/0 | {
"file_path": "overleaf/web/migrations/20200210121103_uniqueify-deletedthings-indexes.js",
"repo_id": "overleaf",
"token_count": 710
} | 553 |
const Path = require('path')
const {
addCollection,
waitForDb,
db,
} = require('../../app/src/infrastructure/mongodb')
class Adapter {
constructor(params) {
if (
!process.env.SKIP_TAG_CHECK &&
!process.argv.includes('create') &&
!(process.argv.includes('-t') || process.argv.includes('--tags'))
) {
console.error("ERROR: must pass tags using '-t' or '--tags', exiting")
process.exit(1)
}
this.params = params || {}
}
getTemplatePath() {
return Path.resolve(__dirname, 'template.js')
}
async connect() {
await waitForDb()
await addCollection('projectImportFailures')
await addCollection('samllog')
await addCollection('user')
return { db }
}
disconnect() {
return Promise.resolve()
}
async getExecutedMigrationNames() {
const migrations = await db.migrations
.find({}, { sort: { migratedAt: 1 }, projection: { name: 1 } })
.toArray()
return migrations.map(migration => migration.name)
}
async markExecuted(name) {
return db.migrations.insertOne({
name: name,
migratedAt: new Date(),
})
}
async unmarkExecuted(name) {
return db.migrations.deleteOne({
name: name,
})
}
}
module.exports = Adapter
| overleaf/web/migrations/lib/adapter.js/0 | {
"file_path": "overleaf/web/migrations/lib/adapter.js",
"repo_id": "overleaf",
"token_count": 488
} | 554 |
const { waitForDb } = require('../../../app/src/infrastructure/mongodb')
waitForDb()
.then(() => {
console.error('Mongodb is up.')
process.exit(0)
})
.catch(err => {
console.error('Cannot connect to mongodb.')
console.error(err)
process.exit(1)
})
| overleaf/web/modules/server-ce-scripts/scripts/check-mongodb.js/0 | {
"file_path": "overleaf/web/modules/server-ce-scripts/scripts/check-mongodb.js",
"repo_id": "overleaf",
"token_count": 116
} | 555 |
const minimist = require('minimist')
const { batchedUpdateWithResultHandling } = require('./helpers/batchedUpdate')
const argv = minimist(process.argv.slice(2))
const commit = argv.commit !== undefined
if (!commit) {
console.error('DOING DRY RUN. TO SAVE CHANGES PASS --commit')
process.exit(1)
}
batchedUpdateWithResultHandling(
'projects',
{ imageName: null },
{ $set: { imageName: 'quay.io/sharelatex/texlive-full:2014.2' } }
)
| overleaf/web/scripts/backfill_project_image_name.js/0 | {
"file_path": "overleaf/web/scripts/backfill_project_image_name.js",
"repo_id": "overleaf",
"token_count": 158
} | 556 |
const VERBOSE_LOGGING = process.env.VERBOSE_LOGGING === 'true'
const VERBOSE_PROJECT_NAMES = process.env.VERBOSE_PROJECT_NAMES === 'true'
const WRITE_CONCURRENCY = parseInt(process.env.WRITE_CONCURRENCY, 10) || 5
const BATCH_SIZE = parseInt(process.env.BATCH_SIZE, 10) || 100
// persist fallback in order to keep batchedUpdate in-sync
process.env.BATCH_SIZE = BATCH_SIZE
const { ReadPreference, ObjectId } = require('mongodb')
const { db } = require('../../app/src/infrastructure/mongodb')
const { promiseMapWithLimit } = require('../../app/src/util/promises')
const { batchedUpdate } = require('../helpers/batchedUpdate')
const COUNT = {
v2: 0,
v1WithoutConversion: 0,
v1WithConversion: 0,
NoneWithoutConversion: 0,
NoneWithConversion: 0,
NoneWithPreserveHistoryFalse: 0,
DeletedIdNeedsConversion: 0,
DeletedIdWithoutConversion: 0,
}
// Timestamp of when 'Enable history for SL in background' release
const ID_WHEN_FULL_PROJECT_HISTORY_ENABLED = '5a8d8a370000000000000000'
const OBJECT_ID_WHEN_FULL_PROJECT_HISTORY_ENABLED = new ObjectId(
ID_WHEN_FULL_PROJECT_HISTORY_ENABLED
)
const DATETIME_WHEN_FULL_PROJECT_HISTORY_ENABLED = OBJECT_ID_WHEN_FULL_PROJECT_HISTORY_ENABLED.getTimestamp()
async function processBatch(_, projects) {
await promiseMapWithLimit(WRITE_CONCURRENCY, projects, processProject)
console.log(COUNT)
}
async function processProject(project) {
if (
project.overleaf &&
project.overleaf.history &&
project.overleaf.history.id
) {
if (project.overleaf.history.display) {
// v2: full project history, do nothing, (query shoudln't include any, but we should stlll check?)
COUNT.v2 += 1
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} is already v2`
)
}
} else {
if (projectCreatedAfterFullProjectHistoryEnabled(project)) {
// IF project initialised after full project history enabled for all projects
// THEN project history should contain all information we need, without intervention
await doUpgradeForV1WithoutConversion(project) // CASE #1
} else {
// ELSE SL history may predate full project history
// THEN delete full project history and convert their SL history to full project history
// --
// TODO: how to verify this, can get rough start date of SL history, but not full project history
// TODO: check that SL history exists for project, if it doesn't then
// we can just upgrade without conversion?
await doUpgradeForV1WithConversion(project) // CASE #4
}
}
} else if (
project.overleaf &&
project.overleaf.history &&
project.overleaf.history.deleted_id
) {
// TODO: has history key but deleted_id in place of id - these do exist...
// Is it safe to handle these like we would an Upgrade for None history state?
const preserveHistory = await shouldPreserveHistory(project)
const anyDocHistory = await anyDocHistoryExists(project)
const anyDocHistoryIndex = await anyDocHistoryIndexExists(project)
const needsConversion =
preserveHistory && (anyDocHistory || anyDocHistoryIndex)
if (needsConversion) {
COUNT.DeletedIdNeedsConversion += 1
} else {
COUNT.DeletedIdWithoutConversion += 1
}
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} has deleted_id and and ${
needsConversion
? 'requires conversion'
: 'does not require conversion'
}`
)
}
} else {
const preserveHistory = await shouldPreserveHistory(project)
if (preserveHistory) {
const anyDocHistory = await anyDocHistoryExists(project)
const anyDocHistoryIndex = await anyDocHistoryIndexExists(project)
// TODO: also need to check docHistoryIndex???
if (anyDocHistory || anyDocHistoryIndex) {
// IF there is SL history ->
// THEN initialise full project history and convert SL history to full project history
await doUpgradeForNoneWithConversion(project) // CASE #3
} else {
// ELSE there is not any SL history ->
// THEN initialise full project history and sync with current content
await doUpgradeForNoneWithoutConversion(project) // CASE #2
}
} else {
// -> FREE plan, (7 day history?)
// TODO: can we ignore these if we enable in background and stage rollout
COUNT.NoneWithPreserveHistoryFalse += 1
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} is None but preserveHistory is false`
)
}
}
}
}
// Helpers:
async function shouldPreserveHistory(project) {
return await db.projectHistoryMetaData.findOne(
{
$and: [
{ project_id: { $eq: project._id } },
{ preserveHistory: { $eq: true } },
],
},
{ readPreference: ReadPreference.SECONDARY }
)
}
async function anyDocHistoryExists(project) {
return await db.docHistory.findOne(
{ project_id: { $eq: project._id } },
{
projection: { _id: 1 },
readPreference: ReadPreference.SECONDARY,
}
)
}
async function anyDocHistoryIndexExists(project) {
return await db.docHistoryIndex.findOne(
{ project_id: { $eq: project._id } },
{
projection: { _id: 1 },
readPreference: ReadPreference.SECONDARY,
}
)
}
function projectCreatedAfterFullProjectHistoryEnabled(project) {
return (
project._id.getTimestamp() >= DATETIME_WHEN_FULL_PROJECT_HISTORY_ENABLED
)
}
// Do upgrades/conversion:
async function doUpgradeForV1WithoutConversion(project) {
// Simply:
// project.overleaf.history.display = true
// TODO: Sanity check(?)
COUNT.v1WithoutConversion += 1
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} is v1 and does not require conversion`
)
}
}
async function doUpgradeForV1WithConversion(project) {
// Delete full project history (or create new)
// Use conversion script to convert SL history to full project history
COUNT.v1WithConversion += 1
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} is v1 and requires conversion`
)
}
}
async function doUpgradeForNoneWithoutConversion(project) {
// Initialise full project history with current content
COUNT.NoneWithoutConversion += 1
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} is None and and does not require conversion`
)
}
}
async function doUpgradeForNoneWithConversion(project) {
// Initialise full project history
// Use conversion script to convert SL history to full project history
COUNT.NoneWithConversion += 1
if (VERBOSE_LOGGING) {
console.log(
`project ${
project[VERBOSE_PROJECT_NAMES ? 'name' : '_id']
} is None and and requires conversion`
)
}
}
async function main() {
const projection = {
_id: 1,
overleaf: 1,
}
if (VERBOSE_PROJECT_NAMES) {
projection.name = 1
}
await batchedUpdate(
'projects',
{ 'overleaf.history.display': { $ne: true } },
processBatch,
projection
)
console.log('Final')
console.log(COUNT)
}
main()
.then(() => {
console.error('Done.')
process.exit(0)
})
.catch(error => {
console.error({ error })
process.exit(1)
})
| overleaf/web/scripts/history/convert_all_projects_to_full_project_history.js/0 | {
"file_path": "overleaf/web/scripts/history/convert_all_projects_to_full_project_history.js",
"repo_id": "overleaf",
"token_count": 2898
} | 557 |
const { waitForDb } = require('../app/src/infrastructure/mongodb')
const minimist = require('minimist')
const InstitutionsManager = require('../app/src/Features/Institutions/InstitutionsManager')
const institutionId = parseInt(process.argv[2])
if (isNaN(institutionId)) throw new Error('No institution id')
console.log('Upgrading users of institution', institutionId)
waitForDb()
.then(main)
.catch(err => {
console.error(err)
process.exit(1)
})
function main() {
const argv = minimist(process.argv.slice(2))
if (!argv.notify) {
throw new Error('Missing `notify` flag. Please use `--notify true|false`')
}
if (!argv.notify[0]) {
throw new Error('Empty `notify` flag. Please use `--notify true|false`')
}
const notify = argv.notify[0] === 't'
console.log('Running with notify =', notify)
InstitutionsManager.refreshInstitutionUsers(
institutionId,
notify,
function (error) {
if (error) {
console.log(error)
} else {
console.log('DONE 👌')
}
process.exit()
}
)
}
| overleaf/web/scripts/refresh_institution_users.js/0 | {
"file_path": "overleaf/web/scripts/refresh_institution_users.js",
"repo_id": "overleaf",
"token_count": 398
} | 558 |
'use strict'
/**
* Checks that all institutional sso provider certs are still current with the
* data provided by the ukamf export file.
*
* Run with: node check-certs /path/ukamf.xml
*
* The ukamf metadata xml file can be downloaded from:
* http://metadata.ukfederation.org.uk/
*/
const { Certificate } = require('@fidm/x509')
const UKAMFDB = require('./ukamf-db')
const V1Api = require(`../../app/src/Features/V1/V1Api`).promises
const { db, waitForDb } = require('../../app/src/infrastructure/mongodb')
const moment = require('moment')
waitForDb()
.then(main)
.catch(err => {
console.error(err.stack)
})
.then(() => process.exit())
async function main() {
const [, , file] = process.argv
console.log(`loading file ${file}`)
const ukamfDB = new UKAMFDB(file)
await ukamfDB.init()
const activeProviderIds = await getActiveProviderIds()
for (const providerId of activeProviderIds) {
await checkCert(ukamfDB, providerId)
}
}
async function checkCert(ukamfDB, providerId) {
console.log(`Checking certificates for providerId: ${providerId}`)
try {
const { body } = await V1Api.request({
json: true,
qs: { university_id: providerId },
uri: '/api/v1/sharelatex/university_saml',
})
// show notice if sso not currently enabled
if (body.sso_enabled === true) {
console.log(` * SSO enabled`)
} else {
console.log(` ! SSO NOT enabled`)
}
// lookup entity id in ukamf database
const entity = ukamfDB.findByEntityID(body.sso_entity_id)
// if entity found then compare certs
if (entity) {
const samlConfig = entity.getSamlConfig()
// check if certificates match
if (samlConfig.cert === body.sso_cert) {
console.log(' * UKAMF certificate matches configuration')
} else {
console.log(' ! UKAMF certificate DOES NOT match configuration')
}
} else {
console.log(` ! No UKAMF entity found for ${body.sso_entity_id}`)
}
// check expiration on configured certificate
const certificate = Certificate.fromPEM(
Buffer.from(
`-----BEGIN CERTIFICATE-----\n${body.sso_cert}\n-----END CERTIFICATE-----`,
'utf8'
)
)
const validFrom = moment(certificate.validFrom)
const validTo = moment(certificate.validTo)
if (validFrom.isAfter(moment())) {
console.log(` ! Certificate not valid till: ${validFrom.format('LLL')}`)
} else if (validTo.isBefore(moment())) {
console.log(` ! Certificate expired: ${validTo.format('LLL')}`)
} else if (validTo.isBefore(moment().add(60, 'days'))) {
console.log(` ! Certificate expires: ${validTo.format('LLL')}`)
} else {
console.log(` * Certificate expires: ${validTo.format('LLL')}`)
}
} catch (err) {
console.log(` ! ${err.statusCode} Error getting university config from v1`)
}
}
async function getActiveProviderIds() {
return db.users.distinct('samlIdentifiers.providerId', {
'samlIdentifiers.externalUserId': { $exists: true },
})
}
| overleaf/web/scripts/ukamf/check-certs.js/0 | {
"file_path": "overleaf/web/scripts/ukamf/check-certs.js",
"repo_id": "overleaf",
"token_count": 1160
} | 559 |
const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
const request = require('./helpers/request')
const settings = require('@overleaf/settings')
const expectErrorResponse = require('./helpers/expectErrorResponse')
function tryReadAccess(user, projectId, test, callback) {
async.series(
[
cb =>
user.request.get(`/project/${projectId}`, (error, response, body) => {
if (error != null) {
return cb(error)
}
test(response, body)
cb()
}),
cb =>
user.request.get(
`/project/${projectId}/download/zip`,
(error, response, body) => {
if (error != null) {
return cb(error)
}
test(response, body)
cb()
}
),
],
callback
)
}
function trySettingsWriteAccess(user, projectId, test, callback) {
async.series(
[
cb =>
user.request.post(
{
uri: `/project/${projectId}/settings`,
json: {
compiler: 'latex',
},
},
(error, response, body) => {
if (error != null) {
return cb(error)
}
test(response, body)
cb()
}
),
],
callback
)
}
function tryAdminAccess(user, projectId, test, callback) {
async.series(
[
cb =>
user.request.post(
{
uri: `/project/${projectId}/rename`,
json: {
newProjectName: 'new-name',
},
},
(error, response, body) => {
if (error != null) {
return cb(error)
}
test(response, body)
cb()
}
),
cb =>
user.request.post(
{
uri: `/project/${projectId}/settings/admin`,
json: {
publicAccessLevel: 'private',
},
},
(error, response, body) => {
if (error != null) {
return cb(error)
}
test(response, body)
cb()
}
),
],
callback
)
}
function tryContentAccess(user, projectId, test, callback) {
// The real-time service calls this end point to determine the user's
// permissions.
let userId
if (user.id != null) {
userId = user.id
} else {
userId = 'anonymous-user'
}
request.post(
{
url: `/project/${projectId}/join`,
qs: { user_id: userId },
auth: {
user: settings.apis.web.user,
pass: settings.apis.web.pass,
sendImmediately: true,
},
json: true,
jar: false,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
test(response, body)
callback()
}
)
}
function expectReadAccess(user, projectId, callback) {
async.series(
[
cb =>
tryReadAccess(
user,
projectId,
(response, body) =>
expect(response.statusCode).to.be.oneOf([200, 204]),
cb
),
cb =>
tryContentAccess(
user,
projectId,
(response, body) =>
expect(body.privilegeLevel).to.be.oneOf([
'owner',
'readAndWrite',
'readOnly',
]),
cb
),
],
callback
)
}
function expectContentWriteAccess(user, projectId, callback) {
tryContentAccess(
user,
projectId,
(response, body) =>
expect(body.privilegeLevel).to.be.oneOf(['owner', 'readAndWrite']),
callback
)
}
function expectSettingsWriteAccess(user, projectId, callback) {
trySettingsWriteAccess(
user,
projectId,
(response, body) => expect(response.statusCode).to.be.oneOf([200, 204]),
callback
)
}
function expectAdminAccess(user, projectId, callback) {
tryAdminAccess(
user,
projectId,
(response, body) => expect(response.statusCode).to.be.oneOf([200, 204]),
callback
)
}
function expectNoReadAccess(user, projectId, options, callback) {
async.series(
[
cb =>
tryReadAccess(user, projectId, expectErrorResponse.restricted.html, cb),
cb =>
tryContentAccess(
user,
projectId,
(response, body) => {
expect(response.statusCode).to.equal(403)
expect(body).to.equal('Forbidden')
},
cb
),
],
callback
)
}
function expectNoContentWriteAccess(user, projectId, callback) {
tryContentAccess(
user,
projectId,
(response, body) =>
expect(body.privilegeLevel).to.be.oneOf([undefined, null, 'readOnly']),
callback
)
}
function expectNoSettingsWriteAccess(user, projectId, options, callback) {
trySettingsWriteAccess(
user,
projectId,
expectErrorResponse.restricted.json,
callback
)
}
function expectNoAdminAccess(user, projectId, callback) {
tryAdminAccess(
user,
projectId,
(response, body) => {
expect(response.statusCode).to.equal(403)
},
callback
)
}
function expectNoAnonymousAdminAccess(user, projectId, callback) {
tryAdminAccess(
user,
projectId,
expectErrorResponse.requireLogin.json,
callback
)
}
function expectChatAccess(user, projectId, callback) {
user.request.get(
{
url: `/project/${projectId}/messages`,
json: true,
},
(error, response) => {
if (error != null) {
return callback(error)
}
expect(response.statusCode).to.equal(200)
callback()
}
)
}
function expectNoChatAccess(user, projectId, callback) {
user.request.get(
{
url: `/project/${projectId}/messages`,
json: true,
},
(error, response) => {
if (error != null) {
return callback(error)
}
expect(response.statusCode).to.equal(403)
callback()
}
)
}
describe('Authorization', function () {
beforeEach(function (done) {
this.timeout(90000)
this.owner = new User()
this.other1 = new User()
this.other2 = new User()
this.anon = new User()
this.site_admin = new User({ email: 'admin@example.com' })
async.parallel(
[
cb => this.owner.login(cb),
cb => this.other1.login(cb),
cb => this.other2.login(cb),
cb => this.anon.getCsrfToken(cb),
cb => {
this.site_admin.login(err => {
if (err != null) {
return cb(err)
}
return this.site_admin.ensureAdmin(cb)
})
},
],
done
)
})
describe('private project', function () {
beforeEach(function (done) {
this.owner.createProject('private-project', (error, projectId) => {
if (error != null) {
return done(error)
}
this.projectId = projectId
done()
})
})
it('should allow the owner read access to it', function (done) {
expectReadAccess(this.owner, this.projectId, done)
})
it('should allow the owner write access to its content', function (done) {
expectContentWriteAccess(this.owner, this.projectId, done)
})
it('should allow the owner write access to its settings', function (done) {
expectSettingsWriteAccess(this.owner, this.projectId, done)
})
it('should allow the owner admin access to it', function (done) {
expectAdminAccess(this.owner, this.projectId, done)
})
it('should allow the owner user chat messages access', function (done) {
expectChatAccess(this.owner, this.projectId, done)
})
it('should not allow another user read access to the project', function (done) {
expectNoReadAccess(
this.other1,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow another user write access to its content', function (done) {
expectNoContentWriteAccess(this.other1, this.projectId, done)
})
it('should not allow another user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.other1,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow another user admin access to it', function (done) {
expectNoAdminAccess(this.other1, this.projectId, done)
})
it('should not allow another user chat messages access', function (done) {
expectNoChatAccess(this.other1, this.projectId, done)
})
it('should not allow anonymous user read access to it', function (done) {
expectNoReadAccess(
this.anon,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow anonymous user write access to its content', function (done) {
expectNoContentWriteAccess(this.anon, this.projectId, done)
})
it('should not allow anonymous user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.anon,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow anonymous user admin access to it', function (done) {
expectNoAnonymousAdminAccess(this.anon, this.projectId, done)
})
it('should not allow anonymous user chat messages access', function (done) {
expectNoChatAccess(this.anon, this.projectId, done)
})
it('should allow site admin users read access to it', function (done) {
expectReadAccess(this.site_admin, this.projectId, done)
})
it('should allow site admin users write access to its content', function (done) {
expectContentWriteAccess(this.site_admin, this.projectId, done)
})
it('should allow site admin users write access to its settings', function (done) {
expectSettingsWriteAccess(this.site_admin, this.projectId, done)
})
it('should allow site admin users admin access to it', function (done) {
expectAdminAccess(this.site_admin, this.projectId, done)
})
})
describe('shared project', function () {
beforeEach(function (done) {
this.rw_user = this.other1
this.ro_user = this.other2
this.owner.createProject('private-project', (error, projectId) => {
if (error != null) {
return done(error)
}
this.projectId = projectId
this.owner.addUserToProject(
this.projectId,
this.ro_user,
'readOnly',
error => {
if (error != null) {
return done(error)
}
this.owner.addUserToProject(
this.projectId,
this.rw_user,
'readAndWrite',
error => {
if (error != null) {
return done(error)
}
done()
}
)
}
)
})
})
it('should allow the read-only user read access to it', function (done) {
expectReadAccess(this.ro_user, this.projectId, done)
})
it('should allow the read-only user chat messages access', function (done) {
expectChatAccess(this.ro_user, this.projectId, done)
})
it('should not allow the read-only user write access to its content', function (done) {
expectNoContentWriteAccess(this.ro_user, this.projectId, done)
})
it('should not allow the read-only user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.ro_user,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow the read-only user admin access to it', function (done) {
expectNoAdminAccess(this.ro_user, this.projectId, done)
})
it('should allow the read-write user read access to it', function (done) {
expectReadAccess(this.rw_user, this.projectId, done)
})
it('should allow the read-write user write access to its content', function (done) {
expectContentWriteAccess(this.rw_user, this.projectId, done)
})
it('should allow the read-write user write access to its settings', function (done) {
expectSettingsWriteAccess(this.rw_user, this.projectId, done)
})
it('should not allow the read-write user admin access to it', function (done) {
expectNoAdminAccess(this.rw_user, this.projectId, done)
})
it('should allow the read-write user chat messages access', function (done) {
expectChatAccess(this.rw_user, this.projectId, done)
})
})
describe('public read-write project', function () {
beforeEach(function (done) {
this.owner.createProject('public-rw-project', (error, projectId) => {
if (error != null) {
return done(error)
}
this.projectId = projectId
this.owner.makePublic(this.projectId, 'readAndWrite', done)
})
})
it('should allow a user read access to it', function (done) {
expectReadAccess(this.other1, this.projectId, done)
})
it('should allow a user write access to its content', function (done) {
expectContentWriteAccess(this.other1, this.projectId, done)
})
it('should allow a user chat messages access', function (done) {
expectChatAccess(this.other1, this.projectId, done)
})
it('should not allow a user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.other1,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow a user admin access to it', function (done) {
expectNoAdminAccess(this.other1, this.projectId, done)
})
it('should allow an anonymous user read access to it', function (done) {
expectReadAccess(this.anon, this.projectId, done)
})
it('should allow an anonymous user write access to its content', function (done) {
expectContentWriteAccess(this.anon, this.projectId, done)
})
it('should allow an anonymous user chat messages access', function (done) {
expectChatAccess(this.anon, this.projectId, done)
})
it('should not allow an anonymous user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.anon,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow an anonymous user admin access to it', function (done) {
expectNoAnonymousAdminAccess(this.anon, this.projectId, done)
})
})
describe('public read-only project', function () {
beforeEach(function (done) {
this.owner.createProject('public-ro-project', (error, projectId) => {
if (error != null) {
return done(error)
}
this.projectId = projectId
this.owner.makePublic(this.projectId, 'readOnly', done)
})
})
it('should allow a user read access to it', function (done) {
expectReadAccess(this.other1, this.projectId, done)
})
it('should not allow a user write access to its content', function (done) {
expectNoContentWriteAccess(this.other1, this.projectId, done)
})
it('should not allow a user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.other1,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow a user admin access to it', function (done) {
expectNoAdminAccess(this.other1, this.projectId, done)
})
// NOTE: legacy readOnly access does not count as 'restricted' in the new model
it('should allow a user chat messages access', function (done) {
expectChatAccess(this.other1, this.projectId, done)
})
it('should allow an anonymous user read access to it', function (done) {
expectReadAccess(this.anon, this.projectId, done)
})
it('should not allow an anonymous user write access to its content', function (done) {
expectNoContentWriteAccess(this.anon, this.projectId, done)
})
it('should not allow an anonymous user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.anon,
this.projectId,
{ redirect_to: '/restricted' },
done
)
})
it('should not allow an anonymous user admin access to it', function (done) {
expectNoAnonymousAdminAccess(this.anon, this.projectId, done)
})
it('should not allow an anonymous user chat messages access', function (done) {
expectNoChatAccess(this.anon, this.projectId, done)
})
})
})
| overleaf/web/test/acceptance/src/AuthorizationTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/AuthorizationTests.js",
"repo_id": "overleaf",
"token_count": 7049
} | 560 |
const { expect } = require('chai')
const { ObjectId: NativeObjectId } = require('mongodb')
const { ObjectId: MongooseObjectId } = require('mongoose').mongo
const { User: UserModel } = require('../../../app/src/models/User')
const { db } = require('../../../app/src/infrastructure/mongodb')
const {
normalizeQuery,
normalizeMultiQuery,
} = require('../../../app/src/Features/Helpers/Mongo')
const User = require('./helpers/User').promises
describe('MongoTests', function () {
let userIdAsString, userEmail, userIds
beforeEach(async function setUpUsers() {
// the first user in the db should not match the target user
const otherUser = new User()
await otherUser.ensureUserExists()
const user = new User()
await user.ensureUserExists()
userIdAsString = user.id
userEmail = user.email
// the last user in the db should not match the target user
const yetAnotherUser = new User()
await yetAnotherUser.ensureUserExists()
userIds = [otherUser.id, user.id, yetAnotherUser.id]
})
describe('normalizeQuery', function () {
async function expectToWork(blob) {
const query = normalizeQuery(blob)
expect(query).to.exist
expect(query._id).to.be.instanceof(NativeObjectId)
expect(query._id).to.deep.equal(NativeObjectId(userIdAsString))
const user = await db.users.findOne(query)
expect(user).to.exist
expect(user.email).to.equal(userEmail)
}
it('should work with the user id as string', async function () {
await expectToWork(userIdAsString)
})
it('should work with the user id in an object', async function () {
await expectToWork({ _id: userIdAsString })
})
it('should pass back the object with id', function () {
const inputQuery = { _id: userIdAsString, other: 1 }
const query = normalizeMultiQuery(inputQuery)
expect(inputQuery).to.equal(query)
})
describe('with an ObjectId from mongoose', function () {
let user
beforeEach(async function getUser() {
user = await UserModel.findById(userIdAsString).exec()
expect(user).to.exist
expect(user._id).to.exist
expect(user.email).to.equal(userEmail)
})
it('should have a mongoose ObjectId', function () {
expect(user._id).to.be.instanceof(MongooseObjectId)
})
it('should work with the users _id field', async function () {
await expectToWork(user._id)
})
})
describe('with an ObjectId from the native driver', function () {
let user
beforeEach(async function getUser() {
user = await db.users.findOne({ _id: NativeObjectId(userIdAsString) })
expect(user).to.exist
expect(user._id).to.exist
expect(user.email).to.equal(userEmail)
})
it('should have a native ObjectId', function () {
expect(user._id).to.be.instanceof(NativeObjectId)
})
it('should work with the users _id field', async function () {
await expectToWork(user._id)
})
})
})
describe('normalizeMultiQuery', function () {
let ghost
beforeEach(async function addGhost() {
// add a user which is not part of the initial three users
ghost = new User()
ghost.emails[0].email = ghost.email = 'ghost@ghost.com'
await ghost.ensureUserExists()
})
async function expectToFindTheThreeUsers(query) {
const users = await db.users.find(query).toArray()
expect(users).to.have.length(3)
expect(users.map(user => user._id.toString()).sort()).to.deep.equal(
userIds.sort()
)
}
describe('with an array as query', function () {
function expectInQueryWithNativeObjectIds(query) {
expect(query).to.exist
expect(query._id).to.exist
expect(query._id.$in).to.exist
expect(
query._id.$in.map(id => id instanceof NativeObjectId)
).to.deep.equal([true, true, true])
}
it('should transform all strings to native ObjectIds', function () {
const query = normalizeMultiQuery(userIds)
expectInQueryWithNativeObjectIds(query)
})
it('should transform all Mongoose ObjectIds to native ObjectIds', function () {
const query = normalizeMultiQuery(userIds.map(MongooseObjectId))
expectInQueryWithNativeObjectIds(query)
})
it('should leave all native Objects as native ObjectIds', function () {
const query = normalizeMultiQuery(userIds.map(NativeObjectId))
expectInQueryWithNativeObjectIds(query)
})
it('should find the three users from string ids', async function () {
const query = normalizeMultiQuery(userIds)
await expectToFindTheThreeUsers(query)
})
it('should find the three users from Mongoose ObjectIds', async function () {
const query = normalizeMultiQuery(userIds.map(MongooseObjectId))
await expectToFindTheThreeUsers(query)
})
it('should find the three users from native ObjectIds', async function () {
const query = normalizeMultiQuery(userIds.map(NativeObjectId))
await expectToFindTheThreeUsers(query)
})
})
describe('with an object as query', function () {
beforeEach(async function addHiddenFlag() {
// add a mongo field that does not exist on the other users
await ghost.mongoUpdate({ $set: { hidden: 1 } })
})
it('should pass through the query', function () {
const inputQuery = { complex: 1 }
const query = normalizeMultiQuery(inputQuery)
expect(inputQuery).to.equal(query)
})
describe('when searching for hidden users', function () {
it('should match the ghost only', async function () {
const query = normalizeMultiQuery({ hidden: 1 })
const users = await db.users.find(query).toArray()
expect(users).to.have.length(1)
expect(users[0]._id.toString()).to.equal(ghost.id)
})
})
describe('when searching for non hidden users', function () {
it('should find the three users', async function () {
const query = normalizeMultiQuery({ hidden: { $exists: false } })
await expectToFindTheThreeUsers(query)
})
})
})
})
})
| overleaf/web/test/acceptance/src/MongoHelper.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/MongoHelper.js",
"repo_id": "overleaf",
"token_count": 2375
} | 561 |
/* eslint-disable
node/handle-callback-err,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
describe('SettingsPage', function () {
beforeEach(function (done) {
this.user = new User()
return async.series(
[
this.user.ensureUserExists.bind(this.user),
this.user.login.bind(this.user),
],
done
)
})
it('load settings page', function (done) {
return this.user.getUserSettingsPage((err, statusCode) => {
statusCode.should.equal(200)
return done()
})
})
it('update main email address', function (done) {
const newEmail = 'foo@bar.com'
return this.user.updateSettings({ email: newEmail }, error => {
expect(error).not.to.exist
return this.user.get((error, user) => {
user.email.should.equal(newEmail)
user.emails.length.should.equal(1)
user.emails[0].email.should.equal(newEmail)
return done()
})
})
})
})
| overleaf/web/test/acceptance/src/SettingsTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/SettingsTests.js",
"repo_id": "overleaf",
"token_count": 492
} | 562 |
const { db, ObjectId } = require('../../../../app/src/infrastructure/mongodb')
const { expect } = require('chai')
const SubscriptionUpdater = require('../../../../app/src/Features/Subscription/SubscriptionUpdater')
const SubscriptionModel = require('../../../../app/src/models/Subscription')
.Subscription
const DeletedSubscriptionModel = require(`../../../../app/src/models/DeletedSubscription`)
.DeletedSubscription
class Subscription {
constructor(options = {}) {
this.admin_id = options.adminId || ObjectId()
this.overleaf = options.overleaf || {}
this.groupPlan = options.groupPlan
this.manager_ids = options.managerIds || [this.admin_id]
this.member_ids = options.memberIds || []
this.invited_emails = options.invitedEmails || []
this.teamName = options.teamName
this.teamInvites = options.teamInvites || []
this.planCode = options.planCode
this.recurlySubscription_id = options.recurlySubscription_id
}
ensureExists(callback) {
if (this._id) {
return callback(null)
}
const options = { upsert: true, new: true, setDefaultsOnInsert: true }
SubscriptionModel.findOneAndUpdate(
{ admin_id: this.admin_id },
this,
options,
(error, subscription) => {
if (error) {
return callback(error)
}
this._id = subscription._id
callback()
}
)
}
get(callback) {
db.subscriptions.findOne({ _id: ObjectId(this._id) }, callback)
}
setManagerIds(managerIds, callback) {
return SubscriptionModel.findOneAndUpdate(
{ _id: ObjectId(this._id) },
{ manager_ids: managerIds },
callback
)
}
refreshUsersFeatures(callback) {
SubscriptionUpdater.refreshUsersFeatures(this, callback)
}
expectDeleted(deleterData, callback) {
DeletedSubscriptionModel.find(
{ 'subscription._id': this._id },
(error, deletedSubscriptions) => {
if (error) {
return callback(error)
}
expect(deletedSubscriptions.length).to.equal(1)
const deletedSubscription = deletedSubscriptions[0]
expect(deletedSubscription.subscription.teamInvites).to.be.empty
expect(deletedSubscription.subscription.invited_emails).to.be.empty
expect(deletedSubscription.deleterData.deleterIpAddress).to.equal(
deleterData.ip
)
if (deleterData.id) {
expect(deletedSubscription.deleterData.deleterId.toString()).to.equal(
deleterData.id.toString()
)
} else {
expect(deletedSubscription.deleterData.deleterId).to.be.undefined
}
SubscriptionModel.findById(this._id, (error, subscription) => {
expect(subscription).to.be.null
callback(error)
})
}
)
}
}
module.exports = Subscription
| overleaf/web/test/acceptance/src/helpers/Subscription.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/helpers/Subscription.js",
"repo_id": "overleaf",
"token_count": 1140
} | 563 |
const AbstractMockApi = require('./AbstractMockApi')
const _ = require('lodash')
const { ObjectId } = require('mongodb')
class MockProjectHistoryApi extends AbstractMockApi {
reset() {
this.docs = {}
this.oldFiles = {}
this.projectVersions = {}
this.labels = {}
this.projectSnapshots = {}
this.projectHistoryId = 1
}
addOldFile(projectId, version, pathname, content) {
this.oldFiles[`${projectId}:${version}:${pathname}`] = content
}
addProjectSnapshot(projectId, version, snapshot) {
this.projectSnapshots[`${projectId}:${version}`] = snapshot
}
setProjectVersion(projectId, version) {
this.projectVersions[projectId] = { version }
}
setProjectVersionInfo(projectId, versionInfo) {
this.projectVersions[projectId] = versionInfo
}
addLabel(projectId, label) {
if (label.id == null) {
label.id = new ObjectId().toString()
}
if (this.labels[projectId] == null) {
this.labels[projectId] = {}
}
this.labels[projectId][label.id] = label
}
deleteLabel(projectId, labelId) {
delete this.labels[projectId][labelId]
}
getLabels(projectId) {
if (this.labels[projectId] == null) {
return null
}
return _.values(this.labels[projectId])
}
applyRoutes() {
this.app.post('/project', (req, res) => {
res.json({ project: { id: this.projectHistoryId++ } })
})
this.app.delete('/project/:projectId', (req, res) => {
res.sendStatus(204)
})
this.app.get(
'/project/:projectId/version/:version/:pathname',
(req, res) => {
const { projectId, version, pathname } = req.params
const key = `${projectId}:${version}:${pathname}`
if (this.oldFiles[key] != null) {
res.send(this.oldFiles[key])
} else {
res.sendStatus(404)
}
}
)
this.app.get('/project/:projectId/version/:version', (req, res) => {
const { projectId, version } = req.params
const key = `${projectId}:${version}`
if (this.projectSnapshots[key] != null) {
res.json(this.projectSnapshots[key])
} else {
res.sendStatus(404)
}
})
this.app.get('/project/:projectId/version', (req, res) => {
const { projectId } = req.params
if (this.projectVersions[projectId] != null) {
res.json(this.projectVersions[projectId])
} else {
res.sendStatus(404)
}
})
this.app.get('/project/:projectId/labels', (req, res) => {
const { projectId } = req.params
const labels = this.getLabels(projectId)
if (labels != null) {
res.json(labels)
} else {
res.sendStatus(404)
}
})
this.app.post('/project/:projectId/user/:user_id/labels', (req, res) => {
const { projectId } = req.params
const { comment, version } = req.body
const labelId = new ObjectId().toString()
this.addLabel(projectId, { id: labelId, comment, version })
res.json({ label_id: labelId, comment, version })
})
this.app.delete(
'/project/:projectId/user/:user_id/labels/:labelId',
(req, res) => {
const { projectId, labelId } = req.params
const label =
this.labels[projectId] != null
? this.labels[projectId][labelId]
: undefined
if (label != null) {
this.deleteLabel(projectId, labelId)
res.sendStatus(204)
} else {
res.sendStatus(404)
}
}
)
this.app.post('/project/:projectId/flush', (req, res) => {
res.sendStatus(200)
})
}
}
module.exports = MockProjectHistoryApi
// type hint for the inherited `instance` method
/**
* @function instance
* @memberOf MockProjectHistoryApi
* @static
* @returns {MockProjectHistoryApi}
*/
| overleaf/web/test/acceptance/src/mocks/MockProjectHistoryApi.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/mocks/MockProjectHistoryApi.js",
"repo_id": "overleaf",
"token_count": 1615
} | 564 |
import { expect } from 'chai'
import sinon from 'sinon'
import { fireEvent, render, screen } from '@testing-library/react'
import ProjectNameEditableLabel from '../../../../../frontend/js/features/editor-navigation-toolbar/components/project-name-editable-label'
describe('<ProjectNameEditableLabel />', function () {
const defaultProps = { projectName: 'test-project', onChange: () => {} }
it('displays the project name', function () {
render(<ProjectNameEditableLabel {...defaultProps} />)
screen.getByText('test-project')
})
describe('when the name is editable', function () {
const editableProps = { ...defaultProps, hasRenamePermissions: true }
it('displays an editable input when the edit button is clicked', function () {
render(<ProjectNameEditableLabel {...editableProps} />)
fireEvent.click(screen.getByRole('button'))
screen.getByRole('textbox')
})
it('displays an editable input when the project name is double clicked', function () {
render(<ProjectNameEditableLabel {...editableProps} />)
fireEvent.doubleClick(screen.getByText('test-project'))
screen.getByRole('textbox')
})
it('calls "onChange" when the project name is updated', function () {
const props = {
...editableProps,
onChange: sinon.stub(),
}
render(<ProjectNameEditableLabel {...props} />)
fireEvent.doubleClick(screen.getByText('test-project'))
const input = screen.getByRole('textbox')
fireEvent.change(input, { target: { value: 'new project name' } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(props.onChange).to.be.calledWith('new project name')
})
it('cancels renaming when the input loses focus', function () {
render(<ProjectNameEditableLabel {...editableProps} />)
fireEvent.doubleClick(screen.getByText('test-project'))
fireEvent.blur(screen.getByRole('textbox'))
expect(screen.queryByRole('textbox')).to.not.exist
})
})
describe('when the name is not editable', function () {
const nonEditableProps = { hasRenamePermissions: false, ...defaultProps }
it('the edit button is not displayed', function () {
render(<ProjectNameEditableLabel {...nonEditableProps} />)
expect(screen.queryByRole('button')).to.not.exist
})
it('does not display an editable input when the project name is double clicked', function () {
render(<ProjectNameEditableLabel {...nonEditableProps} />)
fireEvent.doubleClick(screen.getByText('test-project'))
expect(screen.queryByRole('textbox')).to.not.exist
})
})
})
| overleaf/web/test/frontend/features/editor-navigation-toolbar/components/project-name-editable-label.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/editor-navigation-toolbar/components/project-name-editable-label.test.js",
"repo_id": "overleaf",
"token_count": 920
} | 565 |
import { expect } from 'chai'
import sinon from 'sinon'
import { screen, fireEvent } from '@testing-library/react'
import fetchMock from 'fetch-mock'
import MockedSocket from 'socket.io-mock'
import {
renderWithEditorContext,
cleanUpContext,
} from '../../../helpers/render-with-context'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
describe('FileTree Rename Entity Flow', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
beforeEach(function () {
global.requestAnimationFrame = sinon.stub()
})
afterEach(function () {
delete global.requestAnimationFrame
fetchMock.restore()
onSelect.reset()
onInit.reset()
cleanUpContext()
})
beforeEach(function () {
const rootFolder = [
{
_id: 'root-folder-id',
docs: [{ _id: '456def', name: 'a.tex' }],
folders: [
{
_id: '987jkl',
name: 'folder',
docs: [],
fileRefs: [
{ _id: '789ghi', name: 'c.tex' },
{ _id: '981gkp', name: 'e.tex' },
],
folders: [],
},
],
fileRefs: [],
},
]
renderWithEditorContext(
<FileTreeRoot
rootFolder={rootFolder}
projectId="123abc"
hasWritePermissions
userHasFeature={() => true}
refProviders={{}}
reindexReferences={() => null}
setRefProviderEnabled={() => null}
setStartedFreeTrial={() => null}
onSelect={onSelect}
onInit={onInit}
isConnected
/>,
{ socket: new MockedSocket() }
)
})
it('renames doc', function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+\/rename/
fetchMock.post(fetchMatcher, 204)
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: 'b.tex' } })
fireEvent.keyDown(input, { key: 'Enter' })
screen.getByRole('treeitem', { name: 'b.tex' })
const lastFetchBody = getLastFetchBody(fetchMatcher)
expect(lastFetchBody.name).to.equal('b.tex')
})
it('renames folder', function () {
const fetchMatcher = /\/project\/\w+\/folder\/\w+\/rename/
fetchMock.post(fetchMatcher, 204)
const input = initItemRename('folder')
fireEvent.change(input, { target: { value: 'new folder name' } })
fireEvent.keyDown(input, { key: 'Enter' })
screen.getByRole('treeitem', { name: 'new folder name' })
const lastFetchBody = getLastFetchBody(fetchMatcher)
expect(lastFetchBody.name).to.equal('new folder name')
})
it('renames file in subfolder', function () {
const fetchMatcher = /\/project\/\w+\/file\/\w+\/rename/
fetchMock.post(fetchMatcher, 204)
const expandButton = screen.queryByRole('button', { name: 'Expand' })
if (expandButton) fireEvent.click(expandButton)
const input = initItemRename('c.tex')
fireEvent.change(input, { target: { value: 'd.tex' } })
fireEvent.keyDown(input, { key: 'Enter' })
screen.getByRole('treeitem', { name: 'folder' })
screen.getByRole('treeitem', { name: 'd.tex' })
const lastFetchBody = getLastFetchBody(fetchMatcher)
expect(lastFetchBody.name).to.equal('d.tex')
})
it('reverts rename on error', async function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+\/rename/
fetchMock.post(fetchMatcher, 500)
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: 'b.tex' } })
fireEvent.keyDown(input, { key: 'Enter' })
screen.getByRole('treeitem', { name: 'b.tex' })
})
it('shows error modal on invalid filename', async function () {
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: '///' } })
fireEvent.keyDown(input, { key: 'Enter' })
await screen.findByRole('alert', {
name: 'File name is empty or contains invalid characters',
hidden: true,
})
})
it('shows error modal on duplicate filename', async function () {
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: 'folder' } })
fireEvent.keyDown(input, { key: 'Enter' })
await screen.findByRole('alert', {
name: 'A file or folder with this name already exists',
hidden: true,
})
})
it('shows error modal on duplicate filename in subfolder', async function () {
const expandButton = screen.queryByRole('button', { name: 'Expand' })
if (expandButton) fireEvent.click(expandButton)
const input = initItemRename('c.tex')
fireEvent.change(input, { target: { value: 'e.tex' } })
fireEvent.keyDown(input, { key: 'Enter' })
await screen.findByRole('alert', {
name: 'A file or folder with this name already exists',
hidden: true,
})
})
it('shows error modal on blocked filename', async function () {
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: 'prototype' } })
fireEvent.keyDown(input, { key: 'Enter' })
await screen.findByRole('alert', {
name: 'This file name is blocked.',
hidden: true,
})
})
describe('via socket event', function () {
it('renames doc', function () {
screen.getByRole('treeitem', { name: 'a.tex' })
window._ide.socket.socketClient.emit(
'reciveEntityRename',
'456def',
'socket.tex'
)
screen.getByRole('treeitem', { name: 'socket.tex' })
})
})
function initItemRename(treeitemName) {
const treeitem = screen.getByRole('treeitem', { name: treeitemName })
fireEvent.click(treeitem)
const toggleButton = screen.getByRole('button', { name: 'Menu' })
fireEvent.click(toggleButton)
const renameButton = screen.getByRole('menuitem', { name: 'Rename' })
fireEvent.click(renameButton)
return screen.getByRole('textbox')
}
function getLastFetchBody(matcher) {
const [, { body }] = fetchMock.lastCall(matcher)
return JSON.parse(body)
}
})
| overleaf/web/test/frontend/features/file-tree/flows/rename-entity.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/file-tree/flows/rename-entity.test.js",
"repo_id": "overleaf",
"token_count": 2385
} | 566 |
import { screen, fireEvent } from '@testing-library/react'
import PreviewLogsPane from '../../../../../frontend/js/features/preview/components/preview-logs-pane'
import sinon from 'sinon'
import { renderWithEditorContext } from '../../../helpers/render-with-context'
const { expect } = require('chai')
describe('<PreviewLogsPane />', function () {
const sampleError1 = {
content: 'error 1 content',
file: 'main.tex',
level: 'error',
line: 17,
message: 'Misplaced alignment tab character &.',
}
const sampleError2 = {
content: 'error 1 content',
file: 'main.tex',
level: 'error',
line: 22,
message: 'Extra alignment tab has been changed to cr.',
}
const sampleWarning = {
file: 'main.tex',
level: 'warning',
line: 30,
message: "Reference `idontexist' on page 1 undefined on input line 30.",
}
const sampleTypesettingIssue = {
file: 'main.tex',
level: 'typesetting',
line: 12,
message: "Reference `idontexist' on page 1 undefined on input line 30.",
}
const sampleRawLog = `
This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) (preloaded format=pdflatex 2020.9.10) 6 NOV 2020 15:23
entering extended mode
\\write18 enabled.
%&-line parsing enabled.
**main.tex
(/compile/main.tex
LaTeX2e <2020-02-02> patch level 5
L3 programming layer <2020-07-17> (/usr/local/texlive/2020/texmf-dist/tex/latex
/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(/usr/local/texlive/2020/texmf-dist/tex/latex/base/size10.clo
File: size10.clo 2019/12/20 v1.4l Standard LaTeX file (size option)
)`
const errors = [sampleError1, sampleError2]
const warnings = [sampleWarning]
const typesetting = [sampleTypesettingIssue]
const logEntries = {
all: [...errors, ...warnings, ...typesetting],
errors,
warnings,
typesetting,
}
const noOp = () => {}
const onLogEntryLocationClick = sinon.stub()
describe('with logs', function () {
beforeEach(function () {
renderWithEditorContext(
<PreviewLogsPane
logEntries={logEntries}
rawLog={sampleRawLog}
onLogEntryLocationClick={onLogEntryLocationClick}
onClearCache={noOp}
/>
)
})
it('renders all log entries with appropriate labels', function () {
const errorEntries = screen.getAllByLabelText(
`Log entry with level: error`
)
const warningEntries = screen.getAllByLabelText(
`Log entry with level: warning`
)
const typesettingEntries = screen.getAllByLabelText(
`Log entry with level: typesetting`
)
expect(errorEntries).to.have.lengthOf(errors.length)
expect(warningEntries).to.have.lengthOf(warnings.length)
expect(typesettingEntries).to.have.lengthOf(typesetting.length)
})
it('renders the raw log', function () {
screen.getByLabelText('Raw logs from the LaTeX compiler')
})
it('renders a link to location button for every error and warning log entry', function () {
logEntries.all.forEach((entry, index) => {
const linkToSourceButton = screen.getByRole('button', {
name: `Navigate to log position in source code: ${entry.file}, ${entry.line}`,
})
fireEvent.click(linkToSourceButton)
expect(onLogEntryLocationClick).to.have.callCount(index + 1)
const call = onLogEntryLocationClick.getCall(index)
expect(
call.calledWith({
file: entry.file,
line: entry.line,
column: entry.column,
})
).to.be.true
})
})
it(' does not render a link to location button for the raw log entry', function () {
const rawLogEntry = screen.getByLabelText(
'Raw logs from the LaTeX compiler'
)
expect(rawLogEntry.querySelector('.log-entry-header-link')).to.not.exist
})
})
describe('with validation issues', function () {
const sampleValidationIssues = {
sizeCheck: {
resources: [
{ path: 'foo/bar', kbSize: 76221 },
{ path: 'bar/baz', kbSize: 2342 },
],
},
mainFile: true,
}
it('renders a validation entry for known issues', function () {
renderWithEditorContext(
<PreviewLogsPane
validationIssues={sampleValidationIssues}
onLogEntryLocationClick={onLogEntryLocationClick}
onClearCache={noOp}
/>
)
const validationEntries = screen.getAllByLabelText(
'A validation issue which prevented this project from compiling'
)
expect(validationEntries).to.have.lengthOf(
Object.keys(sampleValidationIssues).length
)
})
it('ignores unknown issues', function () {
renderWithEditorContext(
<PreviewLogsPane
validationIssues={{ unknownIssue: true }}
onLogEntryLocationClick={onLogEntryLocationClick}
onClearCache={noOp}
/>
)
const validationEntries = screen.queryAllByLabelText(
'A validation issue prevented this project from compiling'
)
expect(validationEntries).to.have.lengthOf(0)
})
})
describe('with compilation errors', function () {
const sampleErrors = {
clsiMaintenance: true,
tooRecentlyCompiled: true,
compileTerminated: true,
}
it('renders an error entry for known errors', function () {
renderWithEditorContext(
<PreviewLogsPane
errors={sampleErrors}
onLogEntryLocationClick={onLogEntryLocationClick}
onClearCache={noOp}
/>
)
const errorEntries = screen.getAllByLabelText(
'An error which prevented this project from compiling'
)
expect(errorEntries).to.have.lengthOf(Object.keys(sampleErrors).length)
})
it('ignores unknown errors', function () {
renderWithEditorContext(
<PreviewLogsPane
errors={{ unknownIssue: true }}
onLogEntryLocationClick={onLogEntryLocationClick}
onClearCache={noOp}
/>
)
const errorEntries = screen.queryAllByLabelText(
'There was an error compiling this project'
)
expect(errorEntries).to.have.lengthOf(0)
})
})
describe('with failing code check', function () {
beforeEach(function () {
renderWithEditorContext(
<PreviewLogsPane
logEntries={logEntries}
rawLog={sampleRawLog}
onLogEntryLocationClick={onLogEntryLocationClick}
onClearCache={noOp}
autoCompileHasLintingError
/>
)
})
it('renders a code check failed entry', function () {
screen.getByText(
'Your code has errors that need to be fixed before the auto-compile can run'
)
})
})
})
| overleaf/web/test/frontend/features/preview/components/preview-logs-pane.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/preview/components/preview-logs-pane.test.js",
"repo_id": "overleaf",
"token_count": 2707
} | 567 |
import fetchMock from 'fetch-mock'
import { expect } from 'chai'
import React from 'react'
import { render, waitFor } from '@testing-library/react'
import useAbortController from '../../../../frontend/js/shared/hooks/use-abort-controller'
import { getJSON } from '../../../../frontend/js/infrastructure/fetch-json'
describe('useAbortController', function () {
let status
beforeEach(function () {
fetchMock.restore()
status = {
loading: false,
success: null,
error: null,
}
})
after(function () {
fetchMock.restore()
})
function AbortableRequest({ url }) {
const { signal } = useAbortController()
React.useEffect(() => {
status.loading = true
getJSON(url, { signal })
.then(() => {
status.success = true
})
.catch(error => {
status.error = error
})
.finally(() => {
status.loading = false
})
}, [signal, url])
return null
}
it('calls then when the request succeeds', async function () {
fetchMock.get('/test', { status: 204 }, { delay: 100 })
render(<AbortableRequest url="/test" />)
expect(status.loading).to.be.true
await waitFor(() => expect(status.loading).to.be.false)
expect(status.success).to.be.true
expect(status.error).to.be.null
})
it('calls catch when the request fails', async function () {
fetchMock.get('/test', { status: 500 }, { delay: 100 })
render(<AbortableRequest url="/test" />)
expect(status.loading).to.be.true
await waitFor(() => expect(status.loading).to.be.false)
expect(status.success).to.be.null
expect(status.error).not.to.be.null
})
it('cancels a request when unmounted', async function () {
fetchMock.get('/test', { status: 204 }, { delay: 100 })
const { unmount } = render(<AbortableRequest url="/test" />)
expect(status.loading).to.be.true
unmount()
await fetchMock.flush(true)
expect(fetchMock.done()).to.be.true
// wait for Promises to be resolved
await new Promise(resolve => setTimeout(resolve, 0))
expect(status.success).to.be.null
expect(status.error).to.be.null
expect(status.loading).to.be.true
})
})
| overleaf/web/test/frontend/shared/hooks/use-abort-controller.test.js/0 | {
"file_path": "overleaf/web/test/frontend/shared/hooks/use-abort-controller.test.js",
"repo_id": "overleaf",
"token_count": 852
} | 568 |
const OError = require('@overleaf/o-error')
class SmokeTestFailure extends OError {}
module.exports = {
SmokeTestFailure,
}
| overleaf/web/test/smoke/src/support/Errors.js/0 | {
"file_path": "overleaf/web/test/smoke/src/support/Errors.js",
"repo_id": "overleaf",
"token_count": 41
} | 569 |
const sinon = require('sinon')
const { expect } = require('chai')
const SandboxedModule = require('sandboxed-module')
const { ObjectId } = require('mongodb')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
const MODULE_PATH =
'../../../../app/src/Features/Collaborators/CollaboratorsController.js'
describe('CollaboratorsController', function () {
beforeEach(function () {
this.res = new MockResponse()
this.req = new MockRequest()
this.user = { _id: ObjectId() }
this.projectId = ObjectId()
this.callback = sinon.stub()
this.CollaboratorsHandler = {
promises: {
removeUserFromProject: sinon.stub().resolves(),
setCollaboratorPrivilegeLevel: sinon.stub().resolves(),
},
}
this.CollaboratorsGetter = {
promises: {
getAllInvitedMembers: sinon.stub(),
},
}
this.EditorRealTimeController = {
emitToRoom: sinon.stub(),
}
this.HttpErrorHandler = {
forbidden: sinon.stub(),
notFound: sinon.stub(),
}
this.TagsHandler = {
promises: {
removeProjectFromAllTags: sinon.stub().resolves(),
},
}
this.SessionManager = {
getSessionUser: sinon.stub().returns(this.user),
getLoggedInUserId: sinon.stub().returns(this.user._id),
}
this.OwnershipTransferHandler = {
promises: {
transferOwnership: sinon.stub().resolves(),
},
}
this.CollaboratorsController = SandboxedModule.require(MODULE_PATH, {
requires: {
mongodb: { ObjectId },
'./CollaboratorsHandler': this.CollaboratorsHandler,
'./CollaboratorsGetter': this.CollaboratorsGetter,
'./OwnershipTransferHandler': this.OwnershipTransferHandler,
'../Editor/EditorRealTimeController': this.EditorRealTimeController,
'../../Features/Errors/HttpErrorHandler': this.HttpErrorHandler,
'../Tags/TagsHandler': this.TagsHandler,
'../Authentication/SessionManager': this.SessionManager,
},
})
})
describe('removeUserFromProject', function () {
beforeEach(function (done) {
this.req.params = {
Project_id: this.projectId,
user_id: this.user._id,
}
this.res.sendStatus = sinon.spy(() => {
done()
})
this.CollaboratorsController.removeUserFromProject(this.req, this.res)
})
it('should from the user from the project', function () {
expect(
this.CollaboratorsHandler.promises.removeUserFromProject
).to.have.been.calledWith(this.projectId, this.user._id)
})
it('should emit a userRemovedFromProject event to the proejct', function () {
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.projectId,
'userRemovedFromProject',
this.user._id
)
})
it('should send the back a success response', function () {
this.res.sendStatus.calledWith(204).should.equal(true)
})
it('should have called emitToRoom', function () {
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.projectId,
'project:membership:changed'
)
})
})
describe('removeSelfFromProject', function () {
beforeEach(function (done) {
this.req.params = { Project_id: this.projectId }
this.res.sendStatus = sinon.spy(() => {
done()
})
this.CollaboratorsController.removeSelfFromProject(this.req, this.res)
})
it('should remove the logged in user from the project', function () {
expect(
this.CollaboratorsHandler.promises.removeUserFromProject
).to.have.been.calledWith(this.projectId, this.user._id)
})
it('should emit a userRemovedFromProject event to the proejct', function () {
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.projectId,
'userRemovedFromProject',
this.user._id
)
})
it('should remove the project from all tags', function () {
expect(
this.TagsHandler.promises.removeProjectFromAllTags
).to.have.been.calledWith(this.user._id, this.projectId)
})
it('should return a success code', function () {
this.res.sendStatus.calledWith(204).should.equal(true)
})
})
describe('getAllMembers', function () {
beforeEach(function (done) {
this.req.params = { Project_id: this.projectId }
this.res.json = sinon.spy(() => {
done()
})
this.next = sinon.stub()
this.members = [{ a: 1 }]
this.CollaboratorsGetter.promises.getAllInvitedMembers.resolves(
this.members
)
this.CollaboratorsController.getAllMembers(this.req, this.res, this.next)
})
it('should not produce an error', function () {
this.next.callCount.should.equal(0)
})
it('should produce a json response', function () {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith({ members: this.members }).should.equal(true)
})
it('should call CollaboratorsGetter.getAllInvitedMembers', function () {
expect(this.CollaboratorsGetter.promises.getAllInvitedMembers).to.have
.been.calledOnce
})
describe('when CollaboratorsGetter.getAllInvitedMembers produces an error', function () {
beforeEach(function (done) {
this.res.json = sinon.stub()
this.next = sinon.spy(() => {
done()
})
this.CollaboratorsGetter.promises.getAllInvitedMembers.rejects(
new Error('woops')
)
this.CollaboratorsController.getAllMembers(
this.req,
this.res,
this.next
)
})
it('should produce an error', function () {
expect(this.next).to.have.been.calledOnce
expect(this.next).to.have.been.calledWithMatch(
sinon.match.instanceOf(Error)
)
})
it('should not produce a json response', function () {
this.res.json.callCount.should.equal(0)
})
})
})
describe('setCollaboratorInfo', function () {
beforeEach(function () {
this.req.params = {
Project_id: this.projectId,
user_id: this.user._id,
}
this.req.body = { privilegeLevel: 'readOnly' }
})
it('should set the collaborator privilege level', function (done) {
this.res.sendStatus = status => {
expect(status).to.equal(204)
expect(
this.CollaboratorsHandler.promises.setCollaboratorPrivilegeLevel
).to.have.been.calledWith(this.projectId, this.user._id, 'readOnly')
done()
}
this.CollaboratorsController.setCollaboratorInfo(this.req, this.res)
})
it('should return a 404 when the project or collaborator is not found', function (done) {
this.HttpErrorHandler.notFound = sinon.spy((req, res) => {
expect(req).to.equal(this.req)
expect(res).to.equal(this.res)
done()
})
this.CollaboratorsHandler.promises.setCollaboratorPrivilegeLevel.rejects(
new Errors.NotFoundError()
)
this.CollaboratorsController.setCollaboratorInfo(this.req, this.res)
})
it('should pass the error to the next handler when setting the privilege level fails', function (done) {
this.next = sinon.spy(err => {
expect(err).instanceOf(Error)
done()
})
this.CollaboratorsHandler.promises.setCollaboratorPrivilegeLevel.rejects(
new Error()
)
this.CollaboratorsController.setCollaboratorInfo(
this.req,
this.res,
this.next
)
})
})
describe('transferOwnership', function () {
beforeEach(function () {
this.req.body = { user_id: this.user._id.toString() }
})
it('returns 204 on success', function (done) {
this.res.sendStatus = status => {
expect(status).to.equal(204)
done()
}
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
it('returns 404 if the project does not exist', function (done) {
this.HttpErrorHandler.notFound = sinon.spy((req, res, message) => {
expect(req).to.equal(this.req)
expect(res).to.equal(this.res)
expect(message).to.match(/project not found/)
done()
})
this.OwnershipTransferHandler.promises.transferOwnership.rejects(
new Errors.ProjectNotFoundError()
)
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
it('returns 404 if the user does not exist', function (done) {
this.HttpErrorHandler.notFound = sinon.spy((req, res, message) => {
expect(req).to.equal(this.req)
expect(res).to.equal(this.res)
expect(message).to.match(/user not found/)
done()
})
this.OwnershipTransferHandler.promises.transferOwnership.rejects(
new Errors.UserNotFoundError()
)
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
it('invokes HTTP forbidden error handler if the user is not a collaborator', function (done) {
this.HttpErrorHandler.forbidden = sinon.spy(() => done())
this.OwnershipTransferHandler.promises.transferOwnership.rejects(
new Errors.UserNotCollaboratorError()
)
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
})
})
| overleaf/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js",
"repo_id": "overleaf",
"token_count": 3832
} | 570 |
/* 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
*/
const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Docstore/DocstoreManager'
const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors.js')
const tk = require('timekeeper')
describe('DocstoreManager', function () {
beforeEach(function () {
this.requestDefaults = sinon.stub().returns((this.request = sinon.stub()))
this.DocstoreManager = SandboxedModule.require(modulePath, {
requires: {
request: {
defaults: this.requestDefaults,
},
'@overleaf/settings': (this.settings = {
apis: {
docstore: {
url: 'docstore.sharelatex.com',
},
},
}),
},
})
this.requestDefaults.calledWith({ jar: false }).should.equal(true)
this.project_id = 'project-id-123'
this.doc_id = 'doc-id-123'
return (this.callback = sinon.stub())
})
describe('deleteDoc', function () {
describe('with a successful response code', function () {
// for assertions on the deletedAt timestamp, we need to freeze the clock.
before(function () {
tk.freeze(Date.now())
})
after(function () {
tk.reset()
})
beforeEach(function () {
this.request.patch = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 }, '')
return this.DocstoreManager.deleteDoc(
this.project_id,
this.doc_id,
'wombat.tex',
new Date(),
this.callback
)
})
it('should delete the doc in the docstore api', function () {
return this.request.patch
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}`,
json: { deleted: true, deletedAt: new Date(), name: 'wombat.tex' },
timeout: 30 * 1000,
})
.should.equal(true)
})
it('should call the callback without an error', function () {
return this.callback.calledWith(null).should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.patch = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.deleteDoc(
this.project_id,
this.doc_id,
'main.tex',
new Date(),
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
describe('with a missing (404) response code', function () {
beforeEach(function () {
this.request.patch = sinon
.stub()
.callsArgWith(1, null, { statusCode: 404 }, '')
return this.DocstoreManager.deleteDoc(
this.project_id,
this.doc_id,
'main.tex',
new Date(),
this.callback
)
})
it('should call the callback with an error', function () {
this.callback
.calledWith(
sinon.match
.instanceOf(Errors.NotFoundError)
.and(
sinon.match.has(
'message',
'tried to delete doc not in docstore'
)
)
)
.should.equal(true)
})
})
})
describe('updateDoc', function () {
beforeEach(function () {
this.lines = ['mock', 'doc', 'lines']
this.rev = 5
this.version = 42
this.ranges = { mock: 'ranges' }
return (this.modified = true)
})
describe('with a successful response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(
1,
null,
{ statusCode: 204 },
{ modified: this.modified, rev: this.rev }
)
return this.DocstoreManager.updateDoc(
this.project_id,
this.doc_id,
this.lines,
this.version,
this.ranges,
this.callback
)
})
it('should update the doc in the docstore api', function () {
return this.request.post
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}`,
timeout: 30 * 1000,
json: {
lines: this.lines,
version: this.version,
ranges: this.ranges,
},
})
.should.equal(true)
})
it('should call the callback with the modified status and revision', function () {
return this.callback
.calledWith(null, this.modified, this.rev)
.should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.updateDoc(
this.project_id,
this.doc_id,
this.lines,
this.version,
this.ranges,
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
})
describe('getDoc', function () {
beforeEach(function () {
return (this.doc = {
lines: (this.lines = ['mock', 'doc', 'lines']),
rev: (this.rev = 5),
version: (this.version = 42),
ranges: (this.ranges = { mock: 'ranges' }),
})
})
describe('with a successful response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 }, this.doc)
return this.DocstoreManager.getDoc(
this.project_id,
this.doc_id,
this.callback
)
})
it('should get the doc from the docstore api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}`,
timeout: 30 * 1000,
json: true,
})
.should.equal(true)
})
it('should call the callback with the lines, version and rev', function () {
return this.callback
.calledWith(null, this.lines, this.rev, this.version, this.ranges)
.should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.getDoc(
this.project_id,
this.doc_id,
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
describe('with include_deleted=true', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 }, this.doc)
return this.DocstoreManager.getDoc(
this.project_id,
this.doc_id,
{ include_deleted: true },
this.callback
)
})
it('should get the doc from the docstore api (including deleted)', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}?include_deleted=true`,
timeout: 30 * 1000,
json: true,
})
.should.equal(true)
})
it('should call the callback with the lines, version and rev', function () {
return this.callback
.calledWith(null, this.lines, this.rev, this.version, this.ranges)
.should.equal(true)
})
})
describe('with a missing (404) response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 404 }, '')
return this.DocstoreManager.getDoc(
this.project_id,
this.doc_id,
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Errors.NotFoundError)
.and(sinon.match.has('message', 'doc not found in docstore'))
)
.should.equal(true)
})
})
})
describe('getAllDocs', function () {
describe('with a successful response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(
1,
null,
{ statusCode: 204 },
(this.docs = [{ _id: 'mock-doc-id' }])
)
return this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
it('should get all the project docs in the docstore api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc`,
timeout: 30 * 1000,
json: true,
})
.should.equal(true)
})
it('should call the callback with the docs', function () {
return this.callback.calledWith(null, this.docs).should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
})
describe('getAllDeletedDocs', function () {
describe('with a successful response code', function () {
beforeEach(function (done) {
this.callback.callsFake(done)
this.docs = [{ _id: 'mock-doc-id', name: 'foo.tex' }]
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 200 }, this.docs)
this.DocstoreManager.getAllDeletedDocs(this.project_id, this.callback)
})
it('should get all the project docs in the docstore api', function () {
this.request.get.should.have.been.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc-deleted`,
timeout: 30 * 1000,
json: true,
})
})
it('should call the callback with the docs', function () {
this.callback.should.have.been.calledWith(null, this.docs)
})
})
describe('with an error', function () {
beforeEach(function (done) {
this.callback.callsFake(() => done())
this.request.get = sinon
.stub()
.callsArgWith(1, new Error('connect failed'))
this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(
sinon.match
.instanceOf(Error)
.and(sinon.match.has('message', 'connect failed'))
)
})
})
describe('with a failed response code', function () {
beforeEach(function (done) {
this.callback.callsFake(() => done())
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
})
})
})
describe('getAllRanges', function () {
describe('with a successful response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(
1,
null,
{ statusCode: 204 },
(this.docs = [{ _id: 'mock-doc-id', ranges: 'mock-ranges' }])
)
return this.DocstoreManager.getAllRanges(this.project_id, this.callback)
})
it('should get all the project doc ranges in the docstore api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/ranges`,
timeout: 30 * 1000,
json: true,
})
.should.equal(true)
})
it('should call the callback with the docs', function () {
return this.callback.calledWith(null, this.docs).should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.getAllRanges(this.project_id, this.callback)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
})
describe('archiveProject', function () {
describe('with a successful response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 })
return this.DocstoreManager.archiveProject(
this.project_id,
this.callback
)
})
it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
return this.DocstoreManager.archiveProject(
this.project_id,
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
})
describe('unarchiveProject', function () {
describe('with a successful response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 })
return this.DocstoreManager.unarchiveProject(
this.project_id,
this.callback
)
})
it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
return this.DocstoreManager.unarchiveProject(
this.project_id,
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
})
describe('destroyProject', function () {
describe('with a successful response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 })
return this.DocstoreManager.destroyProject(
this.project_id,
this.callback
)
})
it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
describe('with a failed response code', function () {
beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
return this.DocstoreManager.destroyProject(
this.project_id,
this.callback
)
})
it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'docstore api responded with non-success code: 500'
)
)
)
.should.equal(true)
})
})
})
})
| overleaf/web/test/unit/src/Docstore/DocstoreManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Docstore/DocstoreManagerTests.js",
"repo_id": "overleaf",
"token_count": 9254
} | 571 |
/* eslint-disable
camelcase,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Exports/ExportsHandler.js'
const SandboxedModule = require('sandboxed-module')
describe('ExportsHandler', function () {
beforeEach(function () {
this.stubRequest = {}
this.request = {
defaults: () => {
return this.stubRequest
},
}
this.ExportsHandler = SandboxedModule.require(modulePath, {
requires: {
'../Project/ProjectGetter': (this.ProjectGetter = {}),
'../Project/ProjectHistoryHandler': (this.ProjectHistoryHandler = {}),
'../Project/ProjectLocator': (this.ProjectLocator = {}),
'../Project/ProjectRootDocManager': (this.ProjectRootDocManager = {}),
'../User/UserGetter': (this.UserGetter = {}),
'@overleaf/settings': (this.settings = {}),
request: this.request,
},
})
this.project_id = 'project-id-123'
this.project_history_id = 987
this.user_id = 'user-id-456'
this.brand_variation_id = 789
this.title = 'title'
this.description = 'description'
this.author = 'author'
this.license = 'other'
this.show_source = true
this.export_params = {
project_id: this.project_id,
brand_variation_id: this.brand_variation_id,
user_id: this.user_id,
title: this.title,
description: this.description,
author: this.author,
license: this.license,
show_source: this.show_source,
}
return (this.callback = sinon.stub())
})
describe('exportProject', function () {
beforeEach(function () {
this.export_data = { iAmAnExport: true }
this.response_body = { iAmAResponseBody: true }
this.ExportsHandler._buildExport = sinon
.stub()
.yields(null, this.export_data)
return (this.ExportsHandler._requestExport = sinon
.stub()
.yields(null, this.response_body))
})
describe('when all goes well', function () {
beforeEach(function (done) {
return this.ExportsHandler.exportProject(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should build the export', function () {
return this.ExportsHandler._buildExport
.calledWith(this.export_params)
.should.equal(true)
})
it('should request the export', function () {
return this.ExportsHandler._requestExport
.calledWith(this.export_data)
.should.equal(true)
})
it('should return the export', function () {
return this.callback
.calledWith(null, this.export_data)
.should.equal(true)
})
})
describe("when request can't be built", function () {
beforeEach(function (done) {
this.ExportsHandler._buildExport = sinon
.stub()
.yields(new Error('cannot export project without root doc'))
return this.ExportsHandler.exportProject(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
describe('when export request returns an error to forward to the user', function () {
beforeEach(function (done) {
this.error_json = { status: 422, message: 'nope' }
this.ExportsHandler._requestExport = sinon
.stub()
.yields(null, { forwardResponse: this.error_json })
return this.ExportsHandler.exportProject(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should return success and the response to forward', function () {
;(this.callback.args[0][0] instanceof Error).should.equal(false)
return this.callback.calledWith(null, {
forwardResponse: this.error_json,
})
})
})
})
describe('_buildExport', function () {
beforeEach(function (done) {
this.project = {
id: this.project_id,
rootDoc_id: 'doc1_id',
compiler: 'pdflatex',
imageName: 'mock-image-name',
overleaf: {
id: this.project_history_id, // for projects imported from v1
history: {
id: this.project_history_id,
},
},
}
this.user = {
id: this.user_id,
first_name: 'Arthur',
last_name: 'Author',
email: 'arthur.author@arthurauthoring.org',
overleaf: {
id: 876,
},
}
this.rootDocPath = 'main.tex'
this.historyVersion = 777
this.ProjectGetter.getProject = sinon.stub().yields(null, this.project)
this.ProjectHistoryHandler.ensureHistoryExistsForProject = sinon
.stub()
.yields(null)
this.ProjectLocator.findRootDoc = sinon
.stub()
.yields(null, [null, { fileSystem: 'main.tex' }])
this.ProjectRootDocManager.ensureRootDocumentIsValid = sinon
.stub()
.callsArgWith(1, null)
this.UserGetter.getUser = sinon.stub().yields(null, this.user)
this.ExportsHandler._requestVersion = sinon
.stub()
.yields(null, this.historyVersion)
return done()
})
describe('when all goes well', function () {
beforeEach(function (done) {
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should ensure the project has history', function () {
return this.ProjectHistoryHandler.ensureHistoryExistsForProject.called.should.equal(
true
)
})
it('should request the project history version', function () {
return this.ExportsHandler._requestVersion.called.should.equal(true)
})
it('should return export data', function () {
const expected_export_data = {
project: {
id: this.project_id,
rootDocPath: this.rootDocPath,
historyId: this.project_history_id,
historyVersion: this.historyVersion,
v1ProjectId: this.project_history_id,
metadata: {
compiler: 'pdflatex',
imageName: 'mock-image-name',
title: this.title,
description: this.description,
author: this.author,
license: this.license,
showSource: this.show_source,
},
},
user: {
id: this.user_id,
firstName: this.user.first_name,
lastName: this.user.last_name,
email: this.user.email,
orcidId: null,
v1UserId: 876,
},
destination: {
brandVariationId: this.brand_variation_id,
},
options: {
callbackUrl: null,
},
}
return this.callback
.calledWith(null, expected_export_data)
.should.equal(true)
})
})
describe('when we send replacement user first and last name', function () {
beforeEach(function (done) {
this.custom_first_name = 'FIRST'
this.custom_last_name = 'LAST'
this.export_params.first_name = this.custom_first_name
this.export_params.last_name = this.custom_last_name
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should send the data from the user input', function () {
const expected_export_data = {
project: {
id: this.project_id,
rootDocPath: this.rootDocPath,
historyId: this.project_history_id,
historyVersion: this.historyVersion,
v1ProjectId: this.project_history_id,
metadata: {
compiler: 'pdflatex',
imageName: 'mock-image-name',
title: this.title,
description: this.description,
author: this.author,
license: this.license,
showSource: this.show_source,
},
},
user: {
id: this.user_id,
firstName: this.custom_first_name,
lastName: this.custom_last_name,
email: this.user.email,
orcidId: null,
v1UserId: 876,
},
destination: {
brandVariationId: this.brand_variation_id,
},
options: {
callbackUrl: null,
},
}
return this.callback
.calledWith(null, expected_export_data)
.should.equal(true)
})
})
describe('when project is not found', function () {
beforeEach(function (done) {
this.ProjectGetter.getProject = sinon
.stub()
.yields(new Error('project not found'))
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
describe('when project has no root doc', function () {
describe('when a root doc can be set automatically', function () {
beforeEach(function (done) {
this.project.rootDoc_id = null
this.ProjectLocator.findRootDoc = sinon
.stub()
.yields(null, [null, { fileSystem: 'other.tex' }])
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should set a root doc', function () {
return this.ProjectRootDocManager.ensureRootDocumentIsValid.called.should.equal(
true
)
})
it('should return export data', function () {
const expected_export_data = {
project: {
id: this.project_id,
rootDocPath: 'other.tex',
historyId: this.project_history_id,
historyVersion: this.historyVersion,
v1ProjectId: this.project_history_id,
metadata: {
compiler: 'pdflatex',
imageName: 'mock-image-name',
title: this.title,
description: this.description,
author: this.author,
license: this.license,
showSource: this.show_source,
},
},
user: {
id: this.user_id,
firstName: this.user.first_name,
lastName: this.user.last_name,
email: this.user.email,
orcidId: null,
v1UserId: 876,
},
destination: {
brandVariationId: this.brand_variation_id,
},
options: {
callbackUrl: null,
},
}
return this.callback
.calledWith(null, expected_export_data)
.should.equal(true)
})
})
})
describe('when project has an invalid root doc', function () {
describe('when a new root doc can be set automatically', function () {
beforeEach(function (done) {
this.fakeDoc_id = '1a2b3c4d5e6f'
this.project.rootDoc_id = this.fakeDoc_id
this.ProjectLocator.findRootDoc = sinon
.stub()
.yields(null, [null, { fileSystem: 'other.tex' }])
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should set a valid root doc', function () {
return this.ProjectRootDocManager.ensureRootDocumentIsValid.called.should.equal(
true
)
})
it('should return export data', function () {
const expected_export_data = {
project: {
id: this.project_id,
rootDocPath: 'other.tex',
historyId: this.project_history_id,
historyVersion: this.historyVersion,
v1ProjectId: this.project_history_id,
metadata: {
compiler: 'pdflatex',
imageName: 'mock-image-name',
title: this.title,
description: this.description,
author: this.author,
license: this.license,
showSource: this.show_source,
},
},
user: {
id: this.user_id,
firstName: this.user.first_name,
lastName: this.user.last_name,
email: this.user.email,
orcidId: null,
v1UserId: 876,
},
destination: {
brandVariationId: this.brand_variation_id,
},
options: {
callbackUrl: null,
},
}
return this.callback
.calledWith(null, expected_export_data)
.should.equal(true)
})
})
describe('when no root doc can be identified', function () {
beforeEach(function (done) {
this.ProjectLocator.findRootDoc = sinon
.stub()
.yields(null, [null, null])
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
})
describe('when user is not found', function () {
beforeEach(function (done) {
this.UserGetter.getUser = sinon
.stub()
.yields(new Error('user not found'))
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
describe('when project history request fails', function () {
beforeEach(function (done) {
this.ExportsHandler._requestVersion = sinon
.stub()
.yields(new Error('project history call failed'))
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
this.callback(error, export_data)
return done()
}
)
})
it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
})
describe('_requestExport', function () {
beforeEach(function (done) {
this.settings.apis = {
v1: {
url: 'http://localhost:5000',
user: 'overleaf',
pass: 'pass',
},
}
this.export_data = { iAmAnExport: true }
this.export_id = 4096
this.stubPost = sinon
.stub()
.yields(null, { statusCode: 200 }, { exportId: this.export_id })
return done()
})
describe('when all goes well', function () {
beforeEach(function (done) {
this.stubRequest.post = this.stubPost
return this.ExportsHandler._requestExport(
this.export_data,
(error, export_v1_id) => {
this.callback(error, export_v1_id)
return done()
}
)
})
it('should issue the request', function () {
return expect(this.stubPost.getCall(0).args[0]).to.deep.equal({
url: this.settings.apis.v1.url + '/api/v1/sharelatex/exports',
auth: {
user: this.settings.apis.v1.user,
pass: this.settings.apis.v1.pass,
},
json: this.export_data,
})
})
it('should return the body with v1 export id', function () {
return this.callback
.calledWith(null, { exportId: this.export_id })
.should.equal(true)
})
})
describe('when the request fails', function () {
beforeEach(function (done) {
this.stubRequest.post = sinon
.stub()
.yields(new Error('export request failed'))
return this.ExportsHandler._requestExport(
this.export_data,
(error, export_v1_id) => {
this.callback(error, export_v1_id)
return done()
}
)
})
it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
describe('when the request returns an error response to forward', function () {
beforeEach(function (done) {
this.error_code = 422
this.error_json = { status: this.error_code, message: 'nope' }
this.stubRequest.post = sinon
.stub()
.yields(null, { statusCode: this.error_code }, this.error_json)
return this.ExportsHandler._requestExport(
this.export_data,
(error, export_v1_id) => {
this.callback(error, export_v1_id)
return done()
}
)
})
it('should return success and the response to forward', function () {
;(this.callback.args[0][0] instanceof Error).should.equal(false)
return this.callback.calledWith(null, {
forwardResponse: this.error_json,
})
})
})
})
describe('fetchExport', function () {
beforeEach(function (done) {
this.settings.apis = {
v1: {
url: 'http://localhost:5000',
user: 'overleaf',
pass: 'pass',
},
}
this.export_id = 897
this.body = '{"id":897, "status_summary":"completed"}'
this.stubGet = sinon
.stub()
.yields(null, { statusCode: 200 }, { body: this.body })
return done()
})
describe('when all goes well', function () {
beforeEach(function (done) {
this.stubRequest.get = this.stubGet
return this.ExportsHandler.fetchExport(
this.export_id,
(error, body) => {
this.callback(error, body)
return done()
}
)
})
it('should issue the request', function () {
return expect(this.stubGet.getCall(0).args[0]).to.deep.equal({
url:
this.settings.apis.v1.url +
'/api/v1/sharelatex/exports/' +
this.export_id,
auth: {
user: this.settings.apis.v1.user,
pass: this.settings.apis.v1.pass,
},
})
})
it('should return the v1 export id', function () {
return this.callback
.calledWith(null, { body: this.body })
.should.equal(true)
})
})
})
describe('fetchDownload', function () {
beforeEach(function (done) {
this.settings.apis = {
v1: {
url: 'http://localhost:5000',
user: 'overleaf',
pass: 'pass',
},
}
this.export_id = 897
this.body =
'https://writelatex-conversions-dev.s3.amazonaws.com/exports/ieee_latexqc/tnb/2912/xggmprcrpfwbsnqzqqmvktddnrbqkqkr.zip?X-Amz-Expires=14400&X-Amz-Date=20180730T181003Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJDGDIJFGLNVGZH6A/20180730/us-east-1/s3/aws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=dec990336913cef9933f0e269afe99722d7ab2830ebf2c618a75673ee7159fee'
this.stubGet = sinon
.stub()
.yields(null, { statusCode: 200 }, { body: this.body })
return done()
})
describe('when all goes well', function () {
beforeEach(function (done) {
this.stubRequest.get = this.stubGet
return this.ExportsHandler.fetchDownload(
this.export_id,
'zip',
(error, body) => {
this.callback(error, body)
return done()
}
)
})
it('should issue the request', function () {
return expect(this.stubGet.getCall(0).args[0]).to.deep.equal({
url:
this.settings.apis.v1.url +
'/api/v1/sharelatex/exports/' +
this.export_id +
'/zip_url',
auth: {
user: this.settings.apis.v1.user,
pass: this.settings.apis.v1.pass,
},
})
})
it('should return the v1 export id', function () {
return this.callback
.calledWith(null, { body: this.body })
.should.equal(true)
})
})
})
})
| overleaf/web/test/unit/src/Exports/ExportsHandlerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Exports/ExportsHandlerTests.js",
"repo_id": "overleaf",
"token_count": 10609
} | 572 |
const SandboxedModule = require('sandboxed-module')
const { expect } = require('chai')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Institutions/InstitutionsGetter.js'
)
describe('InstitutionsGetter', function () {
beforeEach(function () {
this.UserGetter = {
getUserFullEmails: sinon.stub(),
promises: {
getUserFullEmails: sinon.stub(),
},
}
this.InstitutionsGetter = SandboxedModule.require(modulePath, {
requires: {
'../User/UserGetter': this.UserGetter,
'../UserMembership/UserMembershipsHandler': (this.UserMembershipsHandler = {}),
'../UserMembership/UserMembershipEntityConfigs': (this.UserMembershipEntityConfigs = {}),
},
})
this.userId = '12345abcde'
this.confirmedAffiliation = {
confirmedAt: new Date(),
affiliation: {
institution: { id: 456, confirmed: true },
pastReconfirmDate: false,
},
}
this.confirmedAffiliationPastReconfirmation = {
confirmedAt: new Date('2000-01-01'),
affiliation: {
institution: { id: 135, confirmed: true },
pastReconfirmDate: true,
},
}
this.userEmails = [
{
confirmedAt: null,
affiliation: {
institution: { id: 123, confirmed: true, pastReconfirmDate: false },
},
},
this.confirmedAffiliation,
this.confirmedAffiliation,
this.confirmedAffiliationPastReconfirmation,
{ confirmedAt: new Date(), affiliation: null, pastReconfirmDate: false },
{
confirmedAt: new Date(),
affiliation: { institution: null, pastReconfirmDate: false },
},
{
confirmedAt: new Date(),
affiliation: {
institution: { id: 789, confirmed: false, pastReconfirmDate: false },
},
},
]
})
describe('getCurrentInstitutionIds', function () {
it('filters unconfirmed affiliations, those past reconfirmation, and returns only 1 result per institution', async function () {
this.UserGetter.promises.getUserFullEmails.resolves(this.userEmails)
const institutions = await this.InstitutionsGetter.promises.getCurrentInstitutionIds(
this.userId
)
expect(institutions.length).to.equal(1)
expect(institutions[0]).to.equal(456)
})
it('handles empty response', async function () {
this.UserGetter.promises.getUserFullEmails.resolves([])
const institutions = await this.InstitutionsGetter.promises.getCurrentInstitutionIds(
this.userId
)
expect(institutions).to.deep.equal([])
})
it('handles errors', async function () {
this.UserGetter.promises.getUserFullEmails.rejects(new Error('oops'))
let e
try {
await this.InstitutionsGetter.promises.getCurrentInstitutionIds(
this.userId
)
} catch (error) {
e = error
}
expect(e.message).to.equal('oops')
})
})
})
| overleaf/web/test/unit/src/Institutions/InstitutionsGetterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Institutions/InstitutionsGetterTests.js",
"repo_id": "overleaf",
"token_count": 1228
} | 573 |
const modulePath = '../../../../app/src/Features/Project/ProjectDeleter'
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const { expect } = require('chai')
const tk = require('timekeeper')
const moment = require('moment')
const { Project } = require('../helpers/models/Project')
const { DeletedProject } = require('../helpers/models/DeletedProject')
const { ObjectId } = require('mongodb')
const Errors = require('../../../../app/src/Features/Errors/Errors')
describe('ProjectDeleter', function () {
beforeEach(function () {
tk.freeze(Date.now())
this.ip = '192.170.18.1'
this.project = dummyProject()
this.user = {
_id: '588f3ddae8ebc1bac07c9fa4',
first_name: 'bjkdsjfk',
features: {},
}
this.doc = {
_id: '5bd975f54f62e803cb8a8fec',
lines: ['a bunch of lines', 'for a sunny day', 'in London town'],
ranges: {},
project_id: '5cf9270b4eff6e186cf8b05e',
}
this.deletedProjects = [
{
_id: '5cf7f145c1401f0ca0eb1aaa',
deleterData: {
_id: '5cf7f145c1401f0ca0eb1aac',
deletedAt: moment().subtract(95, 'days').toDate(),
deleterId: '588f3ddae8ebc1bac07c9fa4',
deleterIpAddress: '172.19.0.1',
deletedProjectId: '5cf9270b4eff6e186cf8b05e',
},
project: {
_id: '5cf9270b4eff6e186cf8b05e',
overleaf: {
history: {
id: new ObjectId(),
},
},
},
},
{
_id: '5cf8eb11c1401f0ca0eb1ad7',
deleterData: {
_id: '5b74360c0fbe57011ae9938f',
deletedAt: moment().subtract(95, 'days').toDate(),
deleterId: '588f3ddae8ebc1bac07c9fa4',
deleterIpAddress: '172.20.0.1',
deletedProjectId: '5cf8f95a0c87371362c23919',
},
project: {
_id: '5cf8f95a0c87371362c23919',
},
},
]
this.DocumentUpdaterHandler = {
promises: {
flushProjectToMongoAndDelete: sinon.stub().resolves(),
},
}
this.EditorRealTimeController = {
emitToRoom: sinon.stub(),
}
this.TagsHandler = {
promises: {
removeProjectFromAllTags: sinon.stub().resolves(),
},
}
this.CollaboratorsHandler = {
promises: {
removeUserFromAllProjects: sinon.stub().resolves(),
},
}
this.CollaboratorsGetter = {
promises: {
getMemberIds: sinon
.stub()
.withArgs(this.project._id)
.resolves(['member-id-1', 'member-id-2']),
},
}
this.ProjectDetailsHandler = {
promises: {
generateUniqueName: sinon.stub().resolves(this.project.name),
},
}
this.ProjectHelper = {
calculateArchivedArray: sinon.stub(),
}
this.db = {
deletedFiles: {
indexExists: sinon.stub().resolves(false),
deleteMany: sinon.stub(),
},
projects: {
insertOne: sinon.stub().resolves(),
},
}
this.DocstoreManager = {
promises: {
archiveProject: sinon.stub().resolves(),
destroyProject: sinon.stub().resolves(),
},
}
this.HistoryManager = {
promises: {
deleteProject: sinon.stub().resolves(),
},
}
this.ProjectMock = sinon.mock(Project)
this.DeletedProjectMock = sinon.mock(DeletedProject)
this.FileStoreHandler = {
promises: {
deleteProject: sinon.stub().resolves(),
},
}
this.TpdsUpdateSender = {
promises: {
deleteProject: sinon.stub().resolves(),
},
}
this.Features = {
hasFeature: sinon.stub().returns(true),
}
this.ProjectDeleter = SandboxedModule.require(modulePath, {
requires: {
'../../infrastructure/Features': this.Features,
'../Editor/EditorRealTimeController': this.EditorRealTimeController,
'../../models/Project': { Project: Project },
'./ProjectHelper': this.ProjectHelper,
'../../models/DeletedProject': { DeletedProject: DeletedProject },
'../DocumentUpdater/DocumentUpdaterHandler': this
.DocumentUpdaterHandler,
'../Tags/TagsHandler': this.TagsHandler,
'../FileStore/FileStoreHandler': this.FileStoreHandler,
'../ThirdPartyDataStore/TpdsUpdateSender': this.TpdsUpdateSender,
'../Collaborators/CollaboratorsHandler': this.CollaboratorsHandler,
'../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter,
'../Docstore/DocstoreManager': this.DocstoreManager,
'./ProjectDetailsHandler': this.ProjectDetailsHandler,
'../../infrastructure/mongodb': { db: this.db, ObjectId },
'../History/HistoryManager': this.HistoryManager,
},
})
})
afterEach(function () {
tk.reset()
this.DeletedProjectMock.restore()
this.ProjectMock.restore()
})
describe('mark as deleted by external source', function () {
beforeEach(function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
{ deletedByExternalDataSource: true }
)
.chain('exec')
.resolves()
})
it('should update the project with the flag set to true', async function () {
await this.ProjectDeleter.promises.markAsDeletedByExternalSource(
this.project._id
)
this.ProjectMock.verify()
})
it('should tell the editor controler so users are notified', async function () {
await this.ProjectDeleter.promises.markAsDeletedByExternalSource(
this.project._id
)
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.project._id,
'projectRenamedOrDeletedByExternalSource'
)
})
})
describe('unmarkAsDeletedByExternalSource', function () {
beforeEach(async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
{ deletedByExternalDataSource: false }
)
.chain('exec')
.resolves()
await this.ProjectDeleter.promises.unmarkAsDeletedByExternalSource(
this.project._id
)
})
it('should remove the flag from the project', function () {
this.ProjectMock.verify()
})
})
describe('deleteUsersProjects', function () {
beforeEach(function () {
this.projects = [dummyProject(), dummyProject()]
this.ProjectMock.expects('find')
.withArgs({ owner_ref: this.user._id })
.chain('exec')
.resolves(this.projects)
for (const project of this.projects) {
this.ProjectMock.expects('findOne')
.withArgs({ _id: project._id })
.chain('exec')
.resolves(project)
this.ProjectMock.expects('deleteOne')
.withArgs({ _id: project._id })
.chain('exec')
.resolves()
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{ 'deleterData.deletedProjectId': project._id },
{
project,
deleterData: sinon.match.object,
},
{ upsert: true }
)
.resolves()
}
})
it('should delete all projects owned by the user', async function () {
await this.ProjectDeleter.promises.deleteUsersProjects(this.user._id)
this.ProjectMock.verify()
this.DeletedProjectMock.verify()
})
it('should remove any collaboration from this user', async function () {
await this.ProjectDeleter.promises.deleteUsersProjects(this.user._id)
sinon.assert.calledWith(
this.CollaboratorsHandler.promises.removeUserFromAllProjects,
this.user._id
)
sinon.assert.calledOnce(
this.CollaboratorsHandler.promises.removeUserFromAllProjects
)
})
})
describe('deleteProject', function () {
beforeEach(function () {
this.deleterData = {
deletedAt: new Date(),
deletedProjectId: this.project._id,
deletedProjectOwnerId: this.project.owner_ref,
deletedProjectCollaboratorIds: this.project.collaberator_refs,
deletedProjectReadOnlyIds: this.project.readOnly_refs,
deletedProjectReadWriteTokenAccessIds: this.project
.tokenAccessReadAndWrite_refs,
deletedProjectReadOnlyTokenAccessIds: this.project
.tokenAccessReadOnly_refs,
deletedProjectReadWriteToken: this.project.tokens.readAndWrite,
deletedProjectReadOnlyToken: this.project.tokens.readOnly,
deletedProjectOverleafId: this.project.overleaf.id,
deletedProjectOverleafHistoryId: this.project.overleaf.history.id,
deletedProjectLastUpdatedAt: this.project.lastUpdated,
}
this.ProjectMock.expects('findOne')
.withArgs({ _id: this.project._id })
.chain('exec')
.resolves(this.project)
})
it('should save a DeletedProject with additional deleterData', async function () {
this.deleterData.deleterIpAddress = this.ip
this.deleterData.deleterId = this.user._id
this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{ 'deleterData.deletedProjectId': this.project._id },
{
project: this.project,
deleterData: this.deleterData,
},
{ upsert: true }
)
.resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
deleterUser: this.user,
ipAddress: this.ip,
})
this.DeletedProjectMock.verify()
})
it('should flushProjectToMongoAndDelete in doc updater', async function () {
this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
deleterUser: this.user,
ipAddress: this.ip,
})
this.DocumentUpdaterHandler.promises.flushProjectToMongoAndDelete
.calledWith(this.project._id)
.should.equal(true)
})
it('should flush docs out of mongo', async function () {
this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
deleterUser: this.user,
ipAddress: this.ip,
})
expect(
this.DocstoreManager.promises.archiveProject
).to.have.been.calledWith(this.project._id)
})
it('should flush docs out of mongo and ignore errors', async function () {
this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
this.DocstoreManager.promises.archiveProject.rejects(new Error('foo'))
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
deleterUser: this.user,
ipAddress: this.ip,
})
})
it('should removeProjectFromAllTags', async function () {
this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id)
sinon.assert.calledWith(
this.TagsHandler.promises.removeProjectFromAllTags,
'member-id-1',
this.project._id
)
sinon.assert.calledWith(
this.TagsHandler.promises.removeProjectFromAllTags,
'member-id-2',
this.project._id
)
})
it('should remove the project from Mongo', async function () {
this.ProjectMock.expects('deleteOne')
.withArgs({ _id: this.project._id })
.chain('exec')
.resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id)
this.ProjectMock.verify()
})
})
describe('expireDeletedProjectsAfterDuration', function () {
beforeEach(async function () {
for (const deletedProject of this.deletedProjects) {
this.ProjectMock.expects('findById')
.withArgs(deletedProject.deleterData.deletedProjectId)
.chain('exec')
.resolves(null)
}
this.DeletedProjectMock.expects('find')
.withArgs({
'deleterData.deletedAt': {
$lt: new Date(moment().subtract(90, 'days')),
},
project: {
$ne: null,
},
})
.chain('exec')
.resolves(this.deletedProjects)
for (const deletedProject of this.deletedProjects) {
this.DeletedProjectMock.expects('findOne')
.withArgs({
'deleterData.deletedProjectId': deletedProject.project._id,
})
.chain('exec')
.resolves(deletedProject)
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{
_id: deletedProject._id,
},
{
$set: {
'deleterData.deleterIpAddress': null,
project: null,
},
}
)
.chain('exec')
.resolves()
}
await this.ProjectDeleter.promises.expireDeletedProjectsAfterDuration()
})
it('should expire projects older than 90 days', function () {
this.DeletedProjectMock.verify()
})
})
describe('expireDeletedProject', function () {
describe('on an inactive project', function () {
beforeEach(async function () {
this.ProjectMock.expects('findById')
.withArgs(this.deletedProjects[0].deleterData.deletedProjectId)
.chain('exec')
.resolves(null)
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{
_id: this.deletedProjects[0]._id,
},
{
$set: {
'deleterData.deleterIpAddress': null,
project: null,
},
}
)
.chain('exec')
.resolves()
this.DeletedProjectMock.expects('findOne')
.withArgs({
'deleterData.deletedProjectId': this.deletedProjects[0].project._id,
})
.chain('exec')
.resolves(this.deletedProjects[0])
await this.ProjectDeleter.promises.expireDeletedProject(
this.deletedProjects[0].project._id
)
})
it('should find the specified deletedProject and remove its project and ip address', function () {
this.DeletedProjectMock.verify()
})
it('should destroy the docs in docstore', function () {
expect(
this.DocstoreManager.promises.destroyProject
).to.have.been.calledWith(this.deletedProjects[0].project._id)
})
it('should delete the project in history', function () {
expect(
this.HistoryManager.promises.deleteProject
).to.have.been.calledWith(
this.deletedProjects[0].project._id,
this.deletedProjects[0].project.overleaf.history.id
)
})
it('should destroy the files in filestore', function () {
expect(
this.FileStoreHandler.promises.deleteProject
).to.have.been.calledWith(this.deletedProjects[0].project._id)
})
it('should destroy the files in project-archiver', function () {
expect(
this.TpdsUpdateSender.promises.deleteProject
).to.have.been.calledWith({
project_id: this.deletedProjects[0].project._id,
})
})
})
describe('when history-v1 is not available', function () {
beforeEach(async function () {
this.Features.hasFeature.returns(false)
this.ProjectMock.expects('findById')
.withArgs(this.deletedProjects[0].deleterData.deletedProjectId)
.chain('exec')
.resolves(null)
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{
_id: this.deletedProjects[0]._id,
},
{
$set: {
'deleterData.deleterIpAddress': null,
project: null,
},
}
)
.chain('exec')
.resolves()
this.DeletedProjectMock.expects('findOne')
.withArgs({
'deleterData.deletedProjectId': this.deletedProjects[0].project._id,
})
.chain('exec')
.resolves(this.deletedProjects[0])
await this.ProjectDeleter.promises.expireDeletedProject(
this.deletedProjects[0].project._id
)
})
it('should destroy the docs in docstore', function () {
expect(
this.DocstoreManager.promises.destroyProject
).to.have.been.calledWith(this.deletedProjects[0].project._id)
})
it('should not call project history', function () {
expect(this.HistoryManager.promises.deleteProject).to.not.have.been
.called
})
})
describe('on an active project (from an incomplete delete)', function () {
beforeEach(async function () {
this.ProjectMock.expects('findById')
.withArgs(this.deletedProjects[0].deleterData.deletedProjectId)
.chain('exec')
.resolves(this.deletedProjects[0].project)
this.DeletedProjectMock.expects('deleteOne')
.withArgs({
'deleterData.deletedProjectId': this.deletedProjects[0].project._id,
})
.chain('exec')
.resolves()
await this.ProjectDeleter.promises.expireDeletedProject(
this.deletedProjects[0].project._id
)
})
it('should delete the spurious deleted project record', function () {
this.DeletedProjectMock.verify()
})
it('should not destroy the docs in docstore', function () {
expect(this.DocstoreManager.promises.destroyProject).to.not.have.been
.called
})
it('should not delete the project in history', function () {
expect(this.HistoryManager.promises.deleteProject).to.not.have.been
.called
})
it('should not destroy the files in filestore', function () {
expect(this.FileStoreHandler.promises.deleteProject).to.not.have.been
.called
})
it('should not destroy the files in project-archiver', function () {
expect(this.TpdsUpdateSender.promises.deleteProject).to.not.have.been
.called
})
})
})
describe('archiveProject', function () {
beforeEach(function () {
const archived = [ObjectId(this.user._id)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
this.ProjectMock.expects('findOne')
.withArgs({ _id: this.project._id })
.chain('exec')
.resolves(this.project)
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
{
$set: { archived: archived },
$pull: { trashed: ObjectId(this.user._id) },
}
)
.resolves()
})
it('should update the project', async function () {
await this.ProjectDeleter.promises.archiveProject(
this.project._id,
this.user._id
)
this.ProjectMock.verify()
})
it('calculates the archived array', async function () {
await this.ProjectDeleter.promises.archiveProject(
this.project._id,
this.user._id
)
expect(this.ProjectHelper.calculateArchivedArray).to.have.been.calledWith(
this.project,
this.user._id,
'ARCHIVE'
)
})
})
describe('unarchiveProject', function () {
beforeEach(function () {
const archived = [ObjectId(this.user._id)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
this.ProjectMock.expects('findOne')
.withArgs({ _id: this.project._id })
.chain('exec')
.resolves(this.project)
this.ProjectMock.expects('updateOne')
.withArgs({ _id: this.project._id }, { $set: { archived: archived } })
.resolves()
})
it('should update the project', async function () {
await this.ProjectDeleter.promises.unarchiveProject(
this.project._id,
this.user._id
)
this.ProjectMock.verify()
})
it('calculates the archived array', async function () {
await this.ProjectDeleter.promises.unarchiveProject(
this.project._id,
this.user._id
)
expect(this.ProjectHelper.calculateArchivedArray).to.have.been.calledWith(
this.project,
this.user._id,
'UNARCHIVE'
)
})
})
describe('trashProject', function () {
beforeEach(function () {
const archived = [ObjectId(this.user._id)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
this.ProjectMock.expects('findOne')
.withArgs({ _id: this.project._id })
.chain('exec')
.resolves(this.project)
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
{
$addToSet: { trashed: ObjectId(this.user._id) },
$set: { archived: archived },
}
)
.resolves()
})
it('should update the project', async function () {
await this.ProjectDeleter.promises.trashProject(
this.project._id,
this.user._id
)
this.ProjectMock.verify()
})
it('unarchives the project', async function () {
await this.ProjectDeleter.promises.trashProject(
this.project._id,
this.user._id
)
expect(this.ProjectHelper.calculateArchivedArray).to.have.been.calledWith(
this.project,
this.user._id,
'UNARCHIVE'
)
})
})
describe('untrashProject', function () {
beforeEach(function () {
this.ProjectMock.expects('findOne')
.withArgs({ _id: this.project._id })
.chain('exec')
.resolves(this.project)
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
{ $pull: { trashed: ObjectId(this.user._id) } }
)
.resolves()
})
it('should update the project', async function () {
await this.ProjectDeleter.promises.untrashProject(
this.project._id,
this.user._id
)
this.ProjectMock.verify()
})
})
describe('restoreProject', function () {
beforeEach(function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
_id: this.project._id,
},
{
$unset: { archived: true },
}
)
.chain('exec')
.resolves()
})
it('should unset the archive attribute', async function () {
await this.ProjectDeleter.promises.restoreProject(this.project._id)
})
})
describe('undeleteProject', function () {
beforeEach(function () {
this.unknownProjectId = ObjectId()
this.purgedProjectId = ObjectId()
this.deletedProject = {
_id: 'deleted',
project: this.project,
deleterData: {
deletedProjectId: this.project._id,
deletedProjectOwnerId: this.project.owner_ref,
},
}
this.purgedProject = {
_id: 'purged',
deleterData: {
deletedProjectId: this.purgedProjectId,
deletedProjectOwnerId: 'potato',
},
}
this.DeletedProjectMock.expects('findOne')
.withArgs({ 'deleterData.deletedProjectId': this.project._id })
.chain('exec')
.resolves(this.deletedProject)
this.DeletedProjectMock.expects('findOne')
.withArgs({ 'deleterData.deletedProjectId': this.purgedProjectId })
.chain('exec')
.resolves(this.purgedProject)
this.DeletedProjectMock.expects('findOne')
.withArgs({ 'deleterData.deletedProjectId': this.unknownProjectId })
.chain('exec')
.resolves(null)
this.DeletedProjectMock.expects('deleteOne').chain('exec').resolves()
})
it('should return not found if the project does not exist', async function () {
await expect(
this.ProjectDeleter.promises.undeleteProject(
this.unknownProjectId.toString()
)
).to.be.rejectedWith(Errors.NotFoundError, 'project_not_found')
})
it('should return not found if the project has been expired', async function () {
await expect(
this.ProjectDeleter.promises.undeleteProject(
this.purgedProjectId.toString()
)
).to.be.rejectedWith(Errors.NotFoundError, 'project_too_old_to_restore')
})
it('should insert the project into the collection', async function () {
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.db.projects.insertOne,
sinon.match({
_id: this.project._id,
name: this.project.name,
})
)
})
it('should clear the archive bit', async function () {
this.project.archived = true
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.db.projects.insertOne,
sinon.match({ archived: undefined })
)
})
it('should generate a unique name for the project', async function () {
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.ProjectDetailsHandler.promises.generateUniqueName,
this.project.owner_ref
)
})
it('should add a suffix to the project name', async function () {
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.ProjectDetailsHandler.promises.generateUniqueName,
this.project.owner_ref,
this.project.name + ' (Restored)'
)
})
it('should remove the DeletedProject', async function () {
// need to change the mock just to include the methods we want
this.DeletedProjectMock.restore()
this.DeletedProjectMock = sinon.mock(DeletedProject)
this.DeletedProjectMock.expects('findOne')
.withArgs({ 'deleterData.deletedProjectId': this.project._id })
.chain('exec')
.resolves(this.deletedProject)
this.DeletedProjectMock.expects('deleteOne')
.withArgs({ _id: 'deleted' })
.chain('exec')
.resolves()
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
this.DeletedProjectMock.verify()
})
})
})
function dummyProject() {
return {
_id: new ObjectId(),
lastUpdated: new Date(),
rootFolder: [],
collaberator_refs: [new ObjectId(), new ObjectId()],
readOnly_refs: [new ObjectId(), new ObjectId()],
tokenAccessReadAndWrite_refs: [new ObjectId(), new ObjectId()],
tokenAccessReadOnly_refs: [new ObjectId(), new ObjectId()],
owner_ref: new ObjectId(),
tokens: {
readOnly: 'wombat',
readAndWrite: 'potato',
},
overleaf: {
id: 1234,
history: {
id: 5678,
},
},
name: 'a very scientific analysis of spooky ghosts',
}
}
| overleaf/web/test/unit/src/Project/ProjectDeleterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Project/ProjectDeleterTests.js",
"repo_id": "overleaf",
"token_count": 12191
} | 574 |
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Referal/ReferalAllocator.js'
)
describe('ReferalAllocator', function () {
beforeEach(function () {
this.ReferalAllocator = SandboxedModule.require(modulePath, {
requires: {
'../../models/User': {
User: (this.User = {}),
},
'../Subscription/FeaturesUpdater': (this.FeaturesUpdater = {}),
'@overleaf/settings': (this.Settings = {}),
},
})
this.callback = sinon.stub()
this.referal_id = 'referal-id-123'
this.referal_medium = 'twitter'
this.user_id = 'user-id-123'
this.new_user_id = 'new-user-id-123'
this.FeaturesUpdater.refreshFeatures = sinon.stub().yields()
this.User.updateOne = sinon.stub().callsArgWith(3, null)
this.User.findOne = sinon
.stub()
.callsArgWith(2, null, { _id: this.user_id })
})
describe('allocate', function () {
describe('when the referal was a bonus referal', function () {
beforeEach(function () {
this.referal_source = 'bonus'
this.ReferalAllocator.allocate(
this.referal_id,
this.new_user_id,
this.referal_source,
this.referal_medium,
this.callback
)
})
it('should update the referring user with the refered users id', function () {
this.User.updateOne
.calledWith(
{
referal_id: this.referal_id,
},
{
$push: {
refered_users: this.new_user_id,
},
$inc: {
refered_user_count: 1,
},
}
)
.should.equal(true)
})
it('find the referring users id', function () {
this.User.findOne
.calledWith({ referal_id: this.referal_id })
.should.equal(true)
})
it("should refresh the user's subscription", function () {
this.FeaturesUpdater.refreshFeatures
.calledWith(this.user_id)
.should.equal(true)
})
it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
describe('when there is no user for the referal id', function () {
beforeEach(function () {
this.referal_source = 'bonus'
this.referal_id = 'wombat'
this.User.findOne = sinon.stub().callsArgWith(2, null, null)
this.ReferalAllocator.allocate(
this.referal_id,
this.new_user_id,
this.referal_source,
this.referal_medium,
this.callback
)
})
it('should find the referring users id', function () {
this.User.findOne
.calledWith({ referal_id: this.referal_id })
.should.equal(true)
})
it('should not update the referring user with the refered users id', function () {
this.User.updateOne.called.should.equal(false)
})
it('should not assign the user a bonus', function () {
this.FeaturesUpdater.refreshFeatures.called.should.equal(false)
})
it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
describe('when the referal is not a bonus referal', function () {
beforeEach(function () {
this.referal_source = 'public_share'
this.ReferalAllocator.allocate(
this.referal_id,
this.new_user_id,
this.referal_source,
this.referal_medium,
this.callback
)
})
it('should not update the referring user with the refered users id', function () {
this.User.updateOne.called.should.equal(false)
})
it('find the referring users id', function () {
this.User.findOne
.calledWith({ referal_id: this.referal_id })
.should.equal(true)
})
it('should not assign the user a bonus', function () {
this.FeaturesUpdater.refreshFeatures.called.should.equal(false)
})
it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
})
})
| overleaf/web/test/unit/src/Referal/ReferalAllocatorTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Referal/ReferalAllocatorTests.js",
"repo_id": "overleaf",
"token_count": 1952
} | 575 |
const SandboxedModule = require('sandboxed-module')
const { assert, expect } = require('chai')
const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Subscription/FeaturesUpdater'
const { ObjectId } = require('mongodb')
describe('FeaturesUpdater', function () {
beforeEach(function () {
this.user_id = ObjectId().toString()
this.FeaturesUpdater = SandboxedModule.require(modulePath, {
requires: {
'./UserFeaturesUpdater': (this.UserFeaturesUpdater = {}),
'./SubscriptionLocator': (this.SubscriptionLocator = {}),
'./PlansLocator': (this.PlansLocator = {}),
'@overleaf/settings': (this.Settings = {
features: {
personal: {
collaborators: 1,
dropbox: false,
compileTimeout: 60,
compileGroup: 'standard',
},
collaborator: {
collaborators: 10,
dropbox: true,
compileTimeout: 240,
compileGroup: 'priority',
},
professional: {
collaborators: -1,
dropbox: true,
compileTimeout: 240,
compileGroup: 'priority',
},
},
}),
'../Referal/ReferalFeatures': (this.ReferalFeatures = {}),
'./V1SubscriptionManager': (this.V1SubscriptionManager = {}),
'../Institutions/InstitutionsFeatures': (this.InstitutionsFeatures = {}),
'../User/UserGetter': (this.UserGetter = {}),
'../Analytics/AnalyticsManager': (this.AnalyticsManager = {
setUserProperty: sinon.stub(),
}),
'../../infrastructure/Modules': (this.Modules = {
hooks: { fire: sinon.stub() },
}),
},
})
})
describe('refreshFeatures', function () {
beforeEach(function () {
this.user = {
_id: this.user_id,
features: {},
}
this.UserFeaturesUpdater.updateFeatures = sinon
.stub()
.yields(null, { some: 'features' }, true)
this.FeaturesUpdater._getIndividualFeatures = sinon
.stub()
.yields(null, { individual: 'features' })
this.FeaturesUpdater._getGroupFeatureSets = sinon
.stub()
.yields(null, [{ group: 'features' }, { group: 'features2' }])
this.InstitutionsFeatures.getInstitutionsFeatures = sinon
.stub()
.yields(null, { institutions: 'features' })
this.FeaturesUpdater._getV1Features = sinon
.stub()
.yields(null, { v1: 'features' })
this.ReferalFeatures.getBonusFeatures = sinon
.stub()
.yields(null, { bonus: 'features' })
this.FeaturesUpdater._mergeFeatures = sinon
.stub()
.returns({ merged: 'features' })
this.UserGetter.getUser = sinon.stub().yields(null, this.user)
this.callback = sinon.stub()
})
it('should return features and featuresChanged', function () {
this.FeaturesUpdater.refreshFeatures(
this.user_id,
'test',
(err, features, featuresChanged) => {
expect(err).to.not.exist
expect(features).to.exist
expect(featuresChanged).to.exist
}
)
})
describe('normally', function () {
beforeEach(function () {
this.FeaturesUpdater.refreshFeatures(
this.user_id,
'test',
this.callback
)
})
it('should get the individual features', function () {
this.FeaturesUpdater._getIndividualFeatures
.calledWith(this.user_id)
.should.equal(true)
})
it('should get the group features', function () {
this.FeaturesUpdater._getGroupFeatureSets
.calledWith(this.user_id)
.should.equal(true)
})
it('should get the institution features', function () {
this.InstitutionsFeatures.getInstitutionsFeatures
.calledWith(this.user_id)
.should.equal(true)
})
it('should get the v1 features', function () {
this.FeaturesUpdater._getV1Features
.calledWith(this.user_id)
.should.equal(true)
})
it('should get the bonus features', function () {
this.ReferalFeatures.getBonusFeatures
.calledWith(this.user_id)
.should.equal(true)
})
it('should merge from the default features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(this.Settings.defaultFeatures)
.should.equal(true)
})
it('should merge the individual features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { individual: 'features' })
.should.equal(true)
})
it('should merge the group features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { group: 'features' })
.should.equal(true)
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { group: 'features2' })
.should.equal(true)
})
it('should merge the institutions features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { institutions: 'features' })
.should.equal(true)
})
it('should merge the v1 features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { v1: 'features' })
.should.equal(true)
})
it('should merge the bonus features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { bonus: 'features' })
.should.equal(true)
})
it('should update the user with the merged features', function () {
this.UserFeaturesUpdater.updateFeatures
.calledWith(this.user_id, { merged: 'features' })
.should.equal(true)
})
})
describe('analytics user properties', function () {
it('should send the corresponding feature set user property', function () {
this.FeaturesUpdater._mergeFeatures = sinon
.stub()
.returns(this.Settings.features.personal)
this.FeaturesUpdater.refreshFeatures(
this.user_id,
'test',
this.callback
)
sinon.assert.calledWith(
this.AnalyticsManager.setUserProperty,
this.user_id,
'feature-set',
'personal'
)
})
it('should send mixed feature set user property', function () {
this.FeaturesUpdater._mergeFeatures = sinon
.stub()
.returns({ dropbox: true, feature: 'some' })
this.FeaturesUpdater.refreshFeatures(
this.user_id,
'test',
this.callback
)
sinon.assert.calledWith(
this.AnalyticsManager.setUserProperty,
this.user_id,
'feature-set',
'mixed'
)
})
})
describe('when losing dropbox feature', function () {
beforeEach(function () {
this.user = {
_id: this.user_id,
features: { dropbox: true },
}
this.UserGetter.getUser = sinon.stub().yields(null, this.user)
this.FeaturesUpdater._mergeFeatures = sinon
.stub()
.returns({ dropbox: false })
this.FeaturesUpdater.refreshFeatures(
this.user_id,
'test',
this.callback
)
})
it('should fire module hook to unlink dropbox', function () {
this.Modules.hooks.fire
.calledWith('removeDropbox', this.user._id, 'test')
.should.equal(true)
})
})
})
describe('_mergeFeatures', function () {
it('should prefer priority over standard for compileGroup', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
compileGroup: 'priority',
},
{
compileGroup: 'standard',
}
)
).to.deep.equal({
compileGroup: 'priority',
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
compileGroup: 'standard',
},
{
compileGroup: 'priority',
}
)
).to.deep.equal({
compileGroup: 'priority',
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
compileGroup: 'priority',
},
{
compileGroup: 'priority',
}
)
).to.deep.equal({
compileGroup: 'priority',
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
compileGroup: 'standard',
},
{
compileGroup: 'standard',
}
)
).to.deep.equal({
compileGroup: 'standard',
})
})
it('should prefer -1 over any other for collaborators', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
collaborators: -1,
},
{
collaborators: 10,
}
)
).to.deep.equal({
collaborators: -1,
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
collaborators: 10,
},
{
collaborators: -1,
}
)
).to.deep.equal({
collaborators: -1,
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
collaborators: 4,
},
{
collaborators: 10,
}
)
).to.deep.equal({
collaborators: 10,
})
})
it('should prefer the higher of compileTimeout', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
compileTimeout: 20,
},
{
compileTimeout: 10,
}
)
).to.deep.equal({
compileTimeout: 20,
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
compileTimeout: 10,
},
{
compileTimeout: 20,
}
)
).to.deep.equal({
compileTimeout: 20,
})
})
it('should prefer the true over false for other keys', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
github: true,
},
{
github: false,
}
)
).to.deep.equal({
github: true,
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
github: false,
},
{
github: true,
}
)
).to.deep.equal({
github: true,
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
github: true,
},
{
github: true,
}
)
).to.deep.equal({
github: true,
})
expect(
this.FeaturesUpdater._mergeFeatures(
{
github: false,
},
{
github: false,
}
)
).to.deep.equal({
github: false,
})
})
})
describe('doSyncFromV1', function () {
beforeEach(function () {
this.v1UserId = 1
this.user = {
_id: this.user_id,
email: 'user@example.com',
overleaf: {
id: this.v1UserId,
},
}
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, this.user)
this.FeaturesUpdater.refreshFeatures = sinon.stub().yields(null)
this.call = cb => {
this.FeaturesUpdater.doSyncFromV1(this.v1UserId, cb)
}
})
describe('when all goes well', function () {
it('should call getUser', function (done) {
this.call(() => {
expect(this.UserGetter.getUser.callCount).to.equal(1)
expect(
this.UserGetter.getUser.calledWith({ 'overleaf.id': this.v1UserId })
).to.equal(true)
done()
})
})
it('should call refreshFeatures', function (done) {
this.call(() => {
expect(this.FeaturesUpdater.refreshFeatures.callCount).to.equal(1)
expect(
this.FeaturesUpdater.refreshFeatures.calledWith(this.user_id)
).to.equal(true)
done()
})
})
it('should not produce an error', function (done) {
this.call(err => {
expect(err).to.not.exist
done()
})
})
})
describe('when getUser produces an error', function () {
beforeEach(function () {
this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, new Error('woops'))
})
it('should not call refreshFeatures', function () {
expect(this.FeaturesUpdater.refreshFeatures.callCount).to.equal(0)
})
it('should produce an error', function (done) {
this.call(err => {
expect(err).to.exist
done()
})
})
})
describe('when getUser does not find a user', function () {
beforeEach(function () {
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
})
it('should not call refreshFeatures', function (done) {
this.call(() => {
expect(this.FeaturesUpdater.refreshFeatures.callCount).to.equal(0)
done()
})
})
it('should not produce an error', function (done) {
this.call(err => {
expect(err).to.not.exist
done()
})
})
})
})
describe('isFeatureSetBetter', function () {
it('simple comparisons', function () {
const result1 = this.FeaturesUpdater.isFeatureSetBetter(
{
dropbox: true,
},
{
dropbox: false,
}
)
assert.isTrue(result1)
const result2 = this.FeaturesUpdater.isFeatureSetBetter(
{
dropbox: false,
},
{
dropbox: true,
}
)
assert.isFalse(result2)
})
it('compound comparisons with same features', function () {
const result1 = this.FeaturesUpdater.isFeatureSetBetter(
{
collaborators: 9,
dropbox: true,
},
{
collaborators: 10,
dropbox: true,
}
)
assert.isFalse(result1)
const result2 = this.FeaturesUpdater.isFeatureSetBetter(
{
collaborators: -1,
dropbox: true,
},
{
collaborators: 10,
dropbox: true,
}
)
assert.isTrue(result2)
const result3 = this.FeaturesUpdater.isFeatureSetBetter(
{
collaborators: -1,
compileTimeout: 60,
dropbox: true,
},
{
collaborators: 10,
compileTimeout: 60,
dropbox: true,
}
)
assert.isTrue(result3)
})
})
})
| overleaf/web/test/unit/src/Subscription/FeaturesUpdaterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Subscription/FeaturesUpdaterTests.js",
"repo_id": "overleaf",
"token_count": 7382
} | 576 |
/* 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 sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/SystemMessages/SystemMessageManager.js'
)
describe('SystemMessageManager', function () {
beforeEach(function () {
this.messages = ['messages-stub']
this.SystemMessage = {
find: sinon.stub().yields(null, this.messages),
}
this.SystemMessageManager = SandboxedModule.require(modulePath, {
requires: {
'../../models/SystemMessage': { SystemMessage: this.SystemMessage },
},
})
return (this.callback = sinon.stub())
})
it('should look the messages up in the database on import', function () {
sinon.assert.called(this.SystemMessage.find)
})
describe('getMessage', function () {
beforeEach(function () {
this.SystemMessageManager._cachedMessages = this.messages
return this.SystemMessageManager.getMessages(this.callback)
})
it('should return the messages', function () {
return this.callback.calledWith(null, this.messages).should.equal(true)
})
})
describe('clearMessages', function () {
beforeEach(function () {
this.SystemMessage.deleteMany = sinon.stub().callsArg(1)
return this.SystemMessageManager.clearMessages(this.callback)
})
it('should remove the messages from the database', function () {
return this.SystemMessage.deleteMany.calledWith({}).should.equal(true)
})
it('should return the callback', function () {
return this.callback.called.should.equal(true)
})
})
})
| overleaf/web/test/unit/src/SystemMessages/SystemMessageManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/SystemMessages/SystemMessageManagerTests.js",
"repo_id": "overleaf",
"token_count": 679
} | 577 |
const { ObjectId } = require('mongodb')
const sinon = require('sinon')
const { expect } = require('chai')
const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const modulePath = '../../../../app/src/Features/User/SAMLIdentityManager.js'
describe('SAMLIdentityManager', function () {
const linkedEmail = 'another@example.com'
beforeEach(function () {
this.userId = '6005c75b12cbcaf771f4a105'
this.user = {
_id: this.userId,
email: 'not-linked@overleaf.com',
emails: [{ email: 'not-linked@overleaf.com' }],
samlIdentifiers: [],
}
this.auditLog = {
initiatorId: this.userId,
ipAddress: '0:0:0:0',
}
this.userAlreadyLinked = {
_id: '6005c7a012cbcaf771f4a106',
email: 'linked@overleaf.com',
emails: [{ email: 'linked@overleaf.com', samlProviderId: '1' }],
samlIdentifiers: [{ externalUserId: 'linked-id', providerId: '1' }],
}
this.userEmailExists = {
_id: '6005c7a012cbcaf771f4a107',
email: 'exists@overleaf.com',
emails: [{ email: 'exists@overleaf.com' }],
samlIdentifiers: [],
}
this.institution = {
name: 'Overleaf University',
}
this.InstitutionsAPI = {
promises: {
addEntitlement: sinon.stub().resolves(),
removeEntitlement: sinon.stub().resolves(),
},
}
this.SAMLIdentityManager = SandboxedModule.require(modulePath, {
requires: {
'../Email/EmailHandler': (this.EmailHandler = {
sendEmail: sinon.stub().yields(),
}),
'../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
promises: {
redundantPersonalSubscription: sinon
.stub()
.returns({ create: sinon.stub().resolves() }),
},
}),
'../Subscription/SubscriptionLocator': (this.SubscriptionLocator = {
promises: {
getUserIndividualSubscription: sinon.stub().resolves(),
},
}),
'../../models/User': {
User: (this.User = {
findOneAndUpdate: sinon.stub().returns({
exec: sinon.stub().resolves(this.user),
}),
findOne: sinon.stub().returns({
exec: sinon.stub().resolves(),
}),
updateOne: sinon.stub().returns({
exec: sinon.stub().resolves(),
}),
}),
},
'../User/UserAuditLogHandler': (this.UserAuditLogHandler = {
promises: {
addEntry: sinon.stub().resolves(),
},
}),
'../User/UserGetter': (this.UserGetter = {
getUser: sinon.stub(),
promises: {
getUser: sinon.stub().resolves(this.user),
getUserByAnyEmail: sinon.stub().resolves(),
getUserFullEmails: sinon.stub().resolves(),
},
}),
'../User/UserUpdater': (this.UserUpdater = {
addEmailAddress: sinon.stub(),
promises: {
addEmailAddress: sinon.stub().resolves(),
confirmEmail: sinon.stub().resolves(),
updateUser: sinon.stub().resolves(),
},
}),
'../Institutions/InstitutionsAPI': this.InstitutionsAPI,
},
})
})
describe('getUser', function () {
it('should throw an error if missing provider ID and/or external user ID', async function () {
let error
try {
await this.SAMLIdentityManager.getUser(null, null)
} catch (e) {
error = e
} finally {
expect(error).to.exist
}
})
})
describe('linkAccounts', function () {
describe('errors', function () {
beforeEach(function () {
// first call is to get userWithProvider; should be falsy
this.UserGetter.promises.getUser.onFirstCall().resolves()
this.UserGetter.promises.getUser.onSecondCall().resolves(this.user)
})
it('should throw an error if missing data', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
null,
null,
null,
null,
null
)
} catch (e) {
error = e
} finally {
expect(error).to.exist
}
})
describe('when email is already associated with another Overleaf account', function () {
beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(
this.userEmailExists
)
})
it('should throw an EmailExistsError error', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
'6005c75b12cbcaf771f4a105',
'not-linked-id',
'exists@overleaf.com',
'provider-id',
'provider-name',
true,
{
intiatorId: '6005c75b12cbcaf771f4a105',
ip: '0:0:0:0',
}
)
} catch (e) {
error = e
} finally {
expect(error).to.be.instanceof(Errors.EmailExistsError)
expect(this.User.findOneAndUpdate).to.not.have.been.called
}
})
})
describe('when email is not affiliated', function () {
beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(this.user)
this.UserGetter.promises.getUserFullEmails.resolves([
{
email: 'not-affiliated@overleaf.com',
},
])
})
it('should throw SAMLEmailNotAffiliatedError', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
'6005c75b12cbcaf771f4a105',
'not-linked-id',
'not-affiliated@overleaf.com',
'provider-id',
'provider-name',
true,
{
intiatorId: 'user-id-1',
ip: '0:0:0:0',
}
)
} catch (e) {
error = e
} finally {
expect(error).to.be.instanceof(Errors.SAMLEmailNotAffiliatedError)
expect(this.User.findOneAndUpdate).to.not.have.been.called
}
})
})
describe('when email is affiliated with another institution', function () {
beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(this.user)
this.UserGetter.promises.getUserFullEmails.resolves([
{
email: 'affiliated@overleaf.com',
affiliation: { institution: { id: '987' } },
},
])
})
it('should throw SAMLEmailAffiliatedWithAnotherInstitutionError', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
'6005c75b12cbcaf771f4a105',
'not-linked-id',
'affiliated@overleaf.com',
'provider-id',
'provider-name',
true,
{
intiatorId: 'user-id-1',
ip: '0:0:0:0',
}
)
} catch (e) {
error = e
} finally {
expect(error).to.be.instanceof(
Errors.SAMLEmailAffiliatedWithAnotherInstitutionError
)
expect(this.User.findOneAndUpdate).to.not.have.been.called
}
})
})
describe('when institution identifier is already associated with another Overleaf account', function () {
beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(
this.userAlreadyLinked
)
})
it('should throw an SAMLIdentityExistsError error', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
'6005c75b12cbcaf771f4a105',
'already-linked-id',
'linked@overleaf.com',
'provider-id',
'provider-name',
true,
{
intiatorId: '6005c75b12cbcaf771f4a105',
ip: '0:0:0:0',
}
)
} catch (e) {
error = e
} finally {
expect(error).to.be.instanceof(Errors.SAMLIdentityExistsError)
expect(this.User.findOneAndUpdate).to.not.have.been.called
}
})
})
describe('when institution provider is already associated with the user', function () {
beforeEach(function () {
// first call is to get userWithProvider; resolves with any user
this.UserGetter.promises.getUser.onFirstCall().resolves(this.user)
})
it('should throw an SAMLAlreadyLinkedError error', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
'6005c75b12cbcaf771f4a105',
'already-linked-id',
'linked@overleaf.com',
123456,
'provider-name',
true,
{
intiatorId: '6005c75b12cbcaf771f4a105',
ip: '0:0:0:0',
}
)
} catch (e) {
error = e
} finally {
expect(
this.UserGetter.promises.getUser
).to.have.been.calledWithMatch({
_id: ObjectId('6005c75b12cbcaf771f4a105'),
'samlIdentifiers.providerId': '123456',
})
expect(error).to.be.instanceof(Errors.SAMLAlreadyLinkedError)
expect(this.User.findOneAndUpdate).to.not.have.been.called
}
})
})
it('should pass back errors via UserAuditLogHandler', async function () {
let error
const anError = new Error('oops')
this.UserAuditLogHandler.promises.addEntry.rejects(anError)
try {
await this.SAMLIdentityManager.linkAccounts(
this.user._id,
'externalUserId',
this.user.email,
'1',
'Overleaf University',
undefined,
{
intiatorId: '6005c75b12cbcaf771f4a105',
ipAddress: '0:0:0:0',
}
)
} catch (e) {
error = e
} finally {
expect(error).to.exist
expect(error).to.equal(anError)
expect(this.EmailHandler.sendEmail).to.not.have.been.called
expect(this.User.updateOne).to.not.have.been.called
}
})
})
describe('success', function () {
beforeEach(function () {
// first call is to get userWithProvider; should be falsy
this.UserGetter.promises.getUser.onFirstCall().resolves()
this.UserGetter.promises.getUser.onSecondCall().resolves(this.user)
})
it('should update the user audit log', function () {
const auditLog = {
intiatorId: '6005c75b12cbcaf771f4a105',
ip: '0:0:0:0',
}
this.SAMLIdentityManager.linkAccounts(
this.user._id,
'externalUserId',
this.user.email,
'1',
'Overleaf University',
undefined,
auditLog,
() => {
expect(
this.UserAuditLogHandler.promises.addEntry
).to.have.been.calledWith(
this.user._id,
'link-institution-sso',
auditLog.initiatorId,
auditLog.ip,
{
institutionEmail: this.user.email,
providerId: '1',
providerName: 'Overleaf University',
}
)
}
)
})
it('should send an email notification', function () {
this.SAMLIdentityManager.linkAccounts(
this.user._id,
'externalUserId',
this.user.email,
'1',
'Overleaf University',
undefined,
{
intiatorId: '6005c75b12cbcaf771f4a105',
ipAddress: '0:0:0:0',
},
() => {
expect(this.User.updateOne).to.have.been.called
expect(this.EmailHandler.sendEmail).to.have.been.calledOnce
const emailArgs = this.EmailHandler.sendEmail.lastCall.args
expect(emailArgs[0]).to.equal('securityAlert')
expect(emailArgs[1].to).to.equal(this.user.email)
expect(emailArgs[1].actionDescribed).to.contain('was linked')
expect(emailArgs[1].message[0]).to.contain('Linked')
expect(emailArgs[1].message[0]).to.contain(this.user.email)
}
)
})
})
})
describe('unlinkAccounts', function () {
it('should update the audit log', async function () {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
this.user.email,
'1',
'Overleaf University',
this.auditLog
)
expect(
this.UserAuditLogHandler.promises.addEntry
).to.have.been.calledOnce.and.calledWithMatch(
this.user._id,
'unlink-institution-sso',
this.auditLog.initiatorId,
this.auditLog.ipAddress,
{
institutionEmail: linkedEmail,
providerId: '1',
providerName: 'Overleaf University',
}
)
})
it('should remove the identifier', async function () {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
this.user.email,
'1',
'Overleaf University',
this.auditLog
)
const query = {
_id: this.user._id,
}
const update = {
$pull: {
samlIdentifiers: {
providerId: '1',
},
},
}
expect(this.User.updateOne).to.have.been.calledOnce.and.calledWithMatch(
query,
update
)
})
it('should send an email notification', async function () {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
this.user.email,
'1',
'Overleaf University',
this.auditLog
)
expect(this.User.updateOne).to.have.been.called
expect(this.EmailHandler.sendEmail).to.have.been.calledOnce
const emailArgs = this.EmailHandler.sendEmail.lastCall.args
expect(emailArgs[0]).to.equal('securityAlert')
expect(emailArgs[1].to).to.equal(this.user.email)
expect(emailArgs[1].actionDescribed).to.contain('was unlinked')
expect(emailArgs[1].message[0]).to.contain('No longer linked')
expect(emailArgs[1].message[0]).to.contain(linkedEmail)
})
describe('errors', function () {
it('should pass back errors via UserAuditLogHandler', async function () {
let error
const anError = new Error('oops')
this.UserAuditLogHandler.promises.addEntry.rejects(anError)
try {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
this.user.email,
'1',
'Overleaf University',
this.auditLog
)
} catch (e) {
error = e
} finally {
expect(error).to.exist
expect(error).to.equal(anError)
expect(this.EmailHandler.sendEmail).to.not.have.been.called
expect(this.User.updateOne).to.not.have.been.called
}
})
})
})
describe('entitlementAttributeMatches', function () {
it('should return true when entitlement matches on string', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
'foo bar',
'bar'
).should.equal(true)
})
it('should return false when entitlement does not match on string', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
'foo bar',
'bam'
).should.equal(false)
})
it('should return false on an invalid matcher', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
'foo bar',
'('
).should.equal(false)
})
it('should log error on an invalid matcher', function () {
this.SAMLIdentityManager.entitlementAttributeMatches('foo bar', '(')
this.logger.error.firstCall.args[0].err.message.should.equal(
'Invalid regular expression: /(/: Unterminated group'
)
})
it('should return true when entitlement matches on array', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
['foo', 'bar'],
'bar'
).should.equal(true)
})
it('should return false when entitlement does not match array', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
['foo', 'bar'],
'bam'
).should.equal(false)
})
})
describe('redundantSubscription', function () {
const userId = '1bv'
const providerId = 123
const providerName = 'University Name'
describe('with a personal subscription', function () {
beforeEach(function () {
this.SubscriptionLocator.promises.getUserIndividualSubscription.resolves(
{
planCode: 'professional',
}
)
})
it('should create redundant personal subscription notification ', async function () {
try {
await this.SAMLIdentityManager.redundantSubscription(
userId,
providerId,
providerName
)
} catch (error) {
expect(error).to.not.exist
}
expect(this.NotificationsBuilder.promises.redundantPersonalSubscription)
.to.have.been.calledOnce
})
})
describe('without a personal subscription', function () {
it('should create redundant personal subscription notification ', async function () {
try {
await this.SAMLIdentityManager.redundantSubscription(
userId,
providerId,
providerName
)
} catch (error) {
expect(error).to.not.exist
}
expect(this.NotificationsBuilder.promises.redundantPersonalSubscription)
.to.not.have.been.called
})
})
})
})
| overleaf/web/test/unit/src/User/SAMLIdentityManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/User/SAMLIdentityManagerTests.js",
"repo_id": "overleaf",
"token_count": 9136
} | 578 |
const SandboxedModule = require('sandboxed-module')
const path = require('path')
const sinon = require('sinon')
const modulePath = path.join(
__dirname,
'../../../../app/src/Features/User/UserUpdater'
)
const tk = require('timekeeper')
const { expect } = require('chai')
const { normalizeQuery } = require('../../../../app/src/Features/Helpers/Mongo')
describe('UserUpdater', function () {
beforeEach(function () {
tk.freeze(Date.now())
this.mongodb = {
db: {},
ObjectId(id) {
return id
},
}
this.UserGetter = {
getUserEmail: sinon.stub(),
getUserByAnyEmail: sinon.stub(),
promises: {
ensureUniqueEmailAddress: sinon.stub(),
getUser: sinon.stub(),
},
}
this.addAffiliation = sinon.stub().yields()
this.removeAffiliation = sinon.stub().callsArgWith(2, null)
this.refreshFeatures = sinon.stub().yields()
this.NewsletterManager = {
promises: {
changeEmail: sinon.stub(),
},
}
this.RecurlyWrapper = {
promises: {
updateAccountEmailAddress: sinon.stub(),
},
}
this.UserUpdater = SandboxedModule.require(modulePath, {
requires: {
'../Helpers/Mongo': { normalizeQuery },
'../../infrastructure/mongodb': this.mongodb,
'@overleaf/metrics': {
timeAsyncMethod: sinon.stub(),
},
'./UserGetter': this.UserGetter,
'../Institutions/InstitutionsAPI': (this.InstitutionsAPI = {
addAffiliation: this.addAffiliation,
removeAffiliation: this.removeAffiliation,
promises: {
addAffiliation: sinon.stub(),
},
}),
'../Email/EmailHandler': (this.EmailHandler = {
promises: {
sendEmail: sinon.stub(),
},
}),
'../../infrastructure/Features': (this.Features = {
hasFeature: sinon.stub().returns(false),
}),
'../Subscription/FeaturesUpdater': (this.FeaturesUpdater = {
refreshFeatures: this.refreshFeatures,
promises: {
refreshFeatures: sinon.stub().resolves(),
},
}),
'@overleaf/settings': (this.settings = {}),
request: (this.request = {}),
'../Newsletter/NewsletterManager': this.NewsletterManager,
'../Subscription/RecurlyWrapper': this.RecurlyWrapper,
'./UserAuditLogHandler': (this.UserAuditLogHandler = {
promises: {
addEntry: sinon.stub().resolves(),
},
}),
},
})
this.stubbedUserEmail = 'hello@world.com'
this.stubbedUser = {
_id: '3131231',
name: 'bob',
email: this.stubbedUserEmail,
emails: [
{
email: this.stubbedUserEmail,
},
],
}
this.newEmail = 'bob@bob.com'
this.callback = sinon.stub()
})
afterEach(function () {
return tk.reset()
})
describe('addAffiliationForNewUser', function (done) {
beforeEach(function () {
this.UserUpdater.updateUser = sinon
.stub()
.callsArgWith(2, null, { n: 1, nModified: 1, ok: 1 })
})
it('should not remove affiliationUnchecked flag if v1 returns an error', function (done) {
this.addAffiliation.yields(true)
this.UserUpdater.addAffiliationForNewUser(
this.stubbedUser._id,
this.newEmail,
(error, updated) => {
expect(error).to.exist
expect(updated).to.be.undefined
sinon.assert.notCalled(this.UserUpdater.updateUser)
done()
}
)
})
it('should remove affiliationUnchecked flag if v1 does not return an error', function (done) {
this.addAffiliation.yields()
this.UserUpdater.addAffiliationForNewUser(
this.stubbedUser._id,
this.newEmail,
error => {
expect(error).not.to.exist
sinon.assert.calledOnce(this.UserUpdater.updateUser)
sinon.assert.calledWithMatch(
this.UserUpdater.updateUser,
{ _id: this.stubbedUser._id, 'emails.email': this.newEmail },
{ $unset: { 'emails.$.affiliationUnchecked': 1 } }
)
done()
}
)
})
})
describe('changeEmailAddress', function () {
beforeEach(function () {
this.auditLog = {
initiatorId: 'abc123',
ipAddress: '0:0:0:0',
}
this.UserGetter.getUserEmail.callsArgWith(1, null, this.stubbedUser.email)
this.UserUpdater.addEmailAddress = sinon.stub().callsArgWith(4)
this.UserUpdater.setDefaultEmailAddress = sinon.stub().yields()
this.UserUpdater.removeEmailAddress = sinon.stub().callsArgWith(2)
})
it('change email', function (done) {
this.UserUpdater.changeEmailAddress(
this.stubbedUser._id,
this.newEmail,
this.auditLog,
err => {
expect(err).not.to.exist
this.UserUpdater.addEmailAddress
.calledWith(this.stubbedUser._id, this.newEmail, {}, this.auditLog)
.should.equal(true)
this.UserUpdater.setDefaultEmailAddress
.calledWith(
this.stubbedUser._id,
this.newEmail,
true,
this.auditLog,
true
)
.should.equal(true)
this.UserUpdater.removeEmailAddress
.calledWith(this.stubbedUser._id, this.stubbedUser.email)
.should.equal(true)
done()
}
)
})
it('validates email', function (done) {
this.UserUpdater.changeEmailAddress(
this.stubbedUser._id,
'foo',
this.auditLog,
err => {
expect(err).to.exist
done()
}
)
})
it('handle error', function (done) {
this.UserUpdater.removeEmailAddress.callsArgWith(2, new Error('nope'))
this.UserUpdater.changeEmailAddress(
this.stubbedUser._id,
this.newEmail,
this.auditLog,
err => {
expect(err).to.exist
done()
}
)
})
})
describe('addEmailAddress', function () {
beforeEach(function () {
this.UserGetter.promises.ensureUniqueEmailAddress = sinon
.stub()
.resolves()
this.UserUpdater.promises.updateUser = sinon.stub().resolves()
})
it('add email', function (done) {
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
{},
{ initiatorId: this.stubbedUser._id, ipAddress: '127:0:0:0' },
err => {
this.UserGetter.promises.ensureUniqueEmailAddress.called.should.equal(
true
)
expect(err).to.not.exist
const reversedHostname = this.newEmail
.split('@')[1]
.split('')
.reverse()
.join('')
this.UserUpdater.promises.updateUser
.calledWith(this.stubbedUser._id, {
$push: {
emails: {
email: this.newEmail,
createdAt: sinon.match.date,
reversedHostname,
},
},
})
.should.equal(true)
done()
}
)
})
it('add affiliation', function (done) {
const affiliationOptions = {
university: { id: 1 },
role: 'Prof',
department: 'Math',
}
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
affiliationOptions,
{ initiatorId: this.stubbedUser._id, ipAddress: '127:0:0:0' },
err => {
expect(err).not.to.exist
this.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(
true
)
const { args } = this.InstitutionsAPI.promises.addAffiliation.lastCall
args[0].should.equal(this.stubbedUser._id)
args[1].should.equal(this.newEmail)
args[2].should.equal(affiliationOptions)
done()
}
)
})
it('handle affiliation error', function (done) {
this.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
{},
{ initiatorId: this.stubbedUser._id, ipAddress: '127:0:0:0' },
err => {
expect(err).to.exist
this.UserUpdater.promises.updateUser.called.should.equal(false)
done()
}
)
})
it('validates email', function (done) {
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
'bar',
{},
{ initiatorId: this.stubbedUser._id, ipAddress: '127:0:0:0' },
err => {
expect(err).to.exist
done()
}
)
})
it('updates the audit log', function (done) {
this.ip = '127:0:0:0'
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
{},
{ initiatorId: this.stubbedUser._id, ipAddress: this.ip },
error => {
expect(error).to.not.exist
this.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(
true
)
const { args } = this.UserAuditLogHandler.promises.addEntry.lastCall
expect(args[0]).to.equal(this.stubbedUser._id)
expect(args[1]).to.equal('add-email')
expect(args[2]).to.equal(this.stubbedUser._id)
expect(args[3]).to.equal(this.ip)
expect(args[4]).to.deep.equal({
newSecondaryEmail: this.newEmail,
})
done()
}
)
})
describe('errors', function () {
describe('via UserAuditLogHandler', function () {
const anError = new Error('oops')
beforeEach(function () {
this.UserAuditLogHandler.promises.addEntry.throws(anError)
})
it('should not add email and should return error', function (done) {
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
{},
{ initiatorId: this.stubbedUser._id, ipAddress: '127:0:0:0' },
error => {
expect(error).to.exist
expect(error).to.equal(anError)
expect(this.UserUpdater.promises.updateUser).to.not.have.been
.called
done()
}
)
})
})
})
})
describe('removeEmailAddress', function () {
beforeEach(function () {
this.UserUpdater.updateUser = sinon
.stub()
.callsArgWith(2, null, { nMatched: 1 })
})
it('remove email', function (done) {
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).not.to.exist
this.UserUpdater.updateUser
.calledWith(
{ _id: this.stubbedUser._id, email: { $ne: this.newEmail } },
{ $pull: { emails: { email: this.newEmail } } }
)
.should.equal(true)
done()
}
)
})
it('remove affiliation', function (done) {
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).not.to.exist
this.removeAffiliation.calledOnce.should.equal(true)
const { args } = this.removeAffiliation.lastCall
args[0].should.equal(this.stubbedUser._id)
args[1].should.equal(this.newEmail)
done()
}
)
})
it('refresh features', function (done) {
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).not.to.exist
sinon.assert.calledWith(this.refreshFeatures, this.stubbedUser._id)
done()
}
)
})
it('handle error', function (done) {
this.UserUpdater.updateUser = sinon
.stub()
.callsArgWith(2, new Error('nope'))
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).to.exist
done()
}
)
})
it('handle missed update', function (done) {
this.UserUpdater.updateUser = sinon.stub().callsArgWith(2, null, { n: 0 })
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).to.exist
done()
}
)
})
it('handle affiliation error', function (done) {
this.removeAffiliation.callsArgWith(2, new Error('nope'))
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).to.exist
this.UserUpdater.updateUser.called.should.equal(false)
done()
}
)
})
it('validates email', function (done) {
this.UserUpdater.removeEmailAddress(this.stubbedUser._id, 'baz', err => {
expect(err).to.exist
done()
})
})
})
describe('setDefaultEmailAddress', function () {
beforeEach(function () {
this.auditLog = {
initiatorId: this.stubbedUser,
ipAddress: '0:0:0:0',
}
this.stubbedUser.emails = [
{
email: this.newEmail,
confirmedAt: new Date(),
},
]
this.UserGetter.promises.getUser.resolves(this.stubbedUser)
this.NewsletterManager.promises.changeEmail.callsArgWith(2, null)
this.RecurlyWrapper.promises.updateAccountEmailAddress.resolves()
})
it('set default', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
err => {
expect(err).not.to.exist
this.UserUpdater.promises.updateUser
.calledWith(
{ _id: this.stubbedUser._id, 'emails.email': this.newEmail },
{ $set: { email: this.newEmail } }
)
.should.equal(true)
done()
}
)
})
it('set changed the email in newsletter', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
err => {
expect(err).not.to.exist
this.NewsletterManager.promises.changeEmail
.calledWith(this.stubbedUser, this.newEmail)
.should.equal(true)
this.RecurlyWrapper.promises.updateAccountEmailAddress
.calledWith(this.stubbedUser._id, this.newEmail)
.should.equal(true)
done()
}
)
})
it('handle error', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().rejects(Error('nope'))
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
err => {
expect(err).to.exist
done()
}
)
})
it('handle missed update', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 0 })
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
err => {
expect(err).to.exist
done()
}
)
})
it('validates email', function (done) {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
'.edu',
false,
this.auditLog,
err => {
expect(err).to.exist
done()
}
)
})
it('updates audit log', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
error => {
expect(error).to.not.exist
expect(
this.UserAuditLogHandler.promises.addEntry
).to.have.been.calledWith(
this.stubbedUser._id,
'change-primary-email',
this.auditLog.initiatorId,
this.auditLog.ipAddress,
{
newPrimaryEmail: this.newEmail,
oldPrimaryEmail: this.stubbedUser.email,
}
)
done()
}
)
})
it('blocks email update if audit log returns an error', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub()
this.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
error => {
expect(error).to.exist
expect(this.UserUpdater.promises.updateUser).to.not.have.been.called
done()
}
)
})
describe('when email not confirmed', function () {
beforeEach(function () {
this.stubbedUser.emails = [
{
email: this.newEmail,
confirmedAt: null,
},
]
this.UserUpdater.promises.updateUser = sinon.stub()
})
it('should callback with error', function () {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
error => {
expect(error).to.exist
expect(error.name).to.equal('UnconfirmedEmailError')
this.UserUpdater.promises.updateUser.callCount.should.equal(0)
this.NewsletterManager.promises.changeEmail.callCount.should.equal(
0
)
}
)
})
})
describe('when email does not belong to user', function () {
beforeEach(function () {
this.stubbedUser.emails = []
this.UserGetter.promises.getUser.resolves(this.stubbedUser)
this.UserUpdater.promises.updateUser = sinon.stub()
})
it('should callback with error', function () {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
error => {
expect(error).to.exist
expect(error.name).to.equal('Error')
this.UserUpdater.promises.updateUser.callCount.should.equal(0)
this.NewsletterManager.promises.changeEmail.callCount.should.equal(
0
)
}
)
})
})
describe('security alert', function () {
it('should be sent to old and new email when sendSecurityAlert=true', function (done) {
// this.UserGetter.promises.getUser.resolves(this.stubbedUser)
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
true,
error => {
expect(error).to.not.exist
this.EmailHandler.promises.sendEmail.callCount.should.equal(2)
const toOldEmailAlert = this.EmailHandler.promises.sendEmail
.firstCall
expect(toOldEmailAlert.args[0]).to.equal('securityAlert')
const toNewEmailAlert = this.EmailHandler.promises.sendEmail
.lastCall
expect(toOldEmailAlert.args[1].to).to.equal(this.stubbedUser.email)
expect(toNewEmailAlert.args[0]).to.equal('securityAlert')
expect(toNewEmailAlert.args[1].to).to.equal(this.newEmail)
done()
}
)
})
describe('errors', function () {
const anError = new Error('oops')
describe('EmailHandler', function () {
beforeEach(function () {
this.EmailHandler.promises.sendEmail.rejects(anError)
this.UserUpdater.promises.updateUser = sinon
.stub()
.resolves({ n: 1 })
})
it('should log but not pass back the error', function (done) {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
false,
this.auditLog,
true,
error => {
expect(error).to.not.exist
const loggerCall = this.logger.error.firstCall
expect(loggerCall.args[0]).to.deep.equal({
error: anError,
userId: this.stubbedUser._id,
})
expect(loggerCall.args[1]).to.contain(
'could not send security alert email when primary email changed'
)
done()
}
)
})
})
})
})
})
describe('confirmEmail', function () {
beforeEach(function () {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
})
it('should update the email record', function (done) {
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.stubbedUserEmail,
err => {
expect(err).not.to.exist
this.UserUpdater.promises.updateUser
.calledWith(
{
_id: this.stubbedUser._id,
'emails.email': this.stubbedUserEmail,
},
{
$set: {
'emails.$.reconfirmedAt': new Date(),
},
$min: {
'emails.$.confirmedAt': new Date(),
},
}
)
.should.equal(true)
done()
}
)
})
it('add affiliation', function (done) {
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).not.to.exist
this.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(
true
)
sinon.assert.calledWith(
this.InstitutionsAPI.promises.addAffiliation,
this.stubbedUser._id,
this.newEmail,
{ confirmedAt: new Date() }
)
done()
}
)
})
it('handle error', function (done) {
this.UserUpdater.promises.updateUser = sinon
.stub()
.throws(new Error('nope'))
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).to.exist
done()
}
)
})
it('handle missed update', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 0 })
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).to.exist
done()
}
)
})
it('validates email', function (done) {
this.UserUpdater.confirmEmail(this.stubbedUser._id, '@', err => {
expect(err).to.exist
done()
})
})
it('handle affiliation error', function (done) {
this.InstitutionsAPI.promises.addAffiliation.throws(Error('nope'))
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).to.exist
this.UserUpdater.promises.updateUser.called.should.equal(false)
done()
}
)
})
it('refresh features', function (done) {
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.FeaturesUpdater.promises.refreshFeatures,
this.stubbedUser._id
)
done()
}
)
})
})
})
| overleaf/web/test/unit/src/User/UserUpdaterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/User/UserUpdaterTests.js",
"repo_id": "overleaf",
"token_count": 12137
} | 579 |
const mockModel = require('../MockModel')
module.exports = mockModel('Tag')
| overleaf/web/test/unit/src/helpers/models/Tag.js/0 | {
"file_path": "overleaf/web/test/unit/src/helpers/models/Tag.js",
"repo_id": "overleaf",
"token_count": 24
} | 580 |
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const CopyPlugin = require('copy-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const PackageVersions = require('./app/src/infrastructure/PackageVersions')
const MODULES_PATH = path.join(__dirname, '/modules')
// Generate a hash of entry points, including modules
const entryPoints = {
serviceWorker: './frontend/js/serviceWorker.js',
main: './frontend/js/main.js',
ide: './frontend/js/ide.js',
style: './frontend/stylesheets/style.less',
'ieee-style': './frontend/stylesheets/ieee-style.less',
'light-style': './frontend/stylesheets/light-style.less',
}
// Attempt to load frontend entry-points from modules, if they exist
if (fs.existsSync(MODULES_PATH)) {
fs.readdirSync(MODULES_PATH).reduce((acc, module) => {
const entryPath = path.join(MODULES_PATH, module, '/frontend/js/index.js')
if (fs.existsSync(entryPath)) {
acc[module] = entryPath
}
return acc
}, entryPoints)
}
module.exports = {
// Defines the "entry point(s)" for the application - i.e. the file which
// bootstraps the application
entry: entryPoints,
// Define where and how the bundle will be output to disk
// Note: webpack-dev-server does not write the bundle to disk, instead it is
// kept in memory for speed
output: {
path: path.join(__dirname, '/public'),
// By default write into js directory
filename: 'js/[name].js',
// Output as UMD bundle (allows main JS to import with CJS, AMD or global
// style code bundles
libraryTarget: 'umd',
// Name the exported variable from output bundle
library: ['Frontend', '[name]'],
},
// Define how file types are handled by webpack
module: {
rules: [
{
// Pass application JS files through babel-loader, compiling to ES5
test: /\.js$/,
// Only compile application files (npm and vendored dependencies are in
// ES5 already)
exclude: [
/node_modules\/(?!react-dnd\/)/,
path.resolve(__dirname, 'frontend/js/vendor'),
],
use: [
{
loader: 'babel-loader',
options: {
// Configure babel-loader to cache compiled output so that
// subsequent compile runs are much faster
cacheDirectory: true,
},
},
],
},
{
// Wrap PDF.js worker in a Web Worker
test: /pdf\.worker\.js$/,
use: [
{
loader: 'worker-loader',
options: {
// Write into js directory (note: customising this is not possible
// with pdfjs-dist/webpack auto loader)
name: 'js/pdfjs-worker.[hash].js',
// Override dynamically-set publicPath to explicitly use root.
// This prevents a security problem where the Worker - normally
// loaded from a CDN - has cross-origin issues, by forcing it to not
// be loaded from the CDN
publicPath: '/',
},
},
],
},
{
test: /serviceWorker.js$/,
use: [
{
loader: 'worker-loader',
options: {
name: 'serviceWorker.js',
},
},
],
},
{
// Pass Less files through less-loader/css-loader/mini-css-extract-
// plugin (note: run in reverse order)
test: /\.less$/,
use: [
// Allows the CSS to be extracted to a separate .css file
{ loader: MiniCssExtractPlugin.loader },
// Resolves any CSS dependencies (e.g. url())
{ loader: 'css-loader' },
{
// Runs autoprefixer on CSS via postcss
loader: 'postcss-loader',
options: {
// Uniquely identifies the postcss plugin (required by webpack)
ident: 'postcss',
plugins: [require('autoprefixer')],
},
},
// Compiles the Less syntax to CSS
{ loader: 'less-loader' },
],
},
{
// Pass CSS files through css-loader & mini-css-extract-plugin (note: run in reverse order)
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
// Load fonts
test: /\.(woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {
// Output to public/font
outputPath: 'fonts',
publicPath: '/fonts/',
name: '[name].[ext]',
},
},
],
},
{
// These options are necessary for handlebars to have access to helper
// methods
test: /\.handlebars$/,
loader: 'handlebars-loader',
options: {
compat: true,
knownHelpersOnly: false,
runtimePath: 'handlebars/runtime',
},
},
{
// Load translations files with custom loader, to extract and apply
// fallbacks
test: /locales\/(\w{2}(-\w{2})?)\.json$/,
use: [
{
loader: path.resolve('frontend/translations-loader.js'),
},
],
},
// Allow for injection of modules dependencies by reading contents of
// modules directory and adding necessary dependencies
{
test: path.join(__dirname, 'modules/modules-main.js'),
use: [
{
loader: 'val-loader',
},
],
},
{
test: path.join(__dirname, 'modules/modules-ide.js'),
use: [
{
loader: 'val-loader',
},
],
},
{
// Expose jQuery and $ global variables
test: require.resolve('jquery'),
use: [
{
loader: 'expose-loader',
options: 'jQuery',
},
{
loader: 'expose-loader',
options: '$',
},
],
},
{
// Expose angular global variable
test: require.resolve('angular'),
use: [
{
loader: 'expose-loader',
options: 'angular',
},
],
},
],
},
resolve: {
alias: {
// Aliases for AMD modules
// Shortcut to vendored dependencies in frontend/js/vendor/libs
libs: path.join(__dirname, 'frontend/js/vendor/libs'),
// Enables ace/ace shortcut
ace: 'ace-builds/src-noconflict',
// fineupload vendored dependency (which we're aliasing to fineuploadER
// for some reason)
fineuploader: path.join(
__dirname,
`frontend/js/vendor/libs/${PackageVersions.lib('fineuploader')}`
),
},
},
// Split out vendored dependencies that are shared between 2 or more "real
// bundles" (e.g. ide.js/main.js) as a separate "libraries" bundle and ensure
// that they are de-duplicated from the other bundles. This allows the
// libraries bundle to be independently cached (as it likely will change less
// than the other bundles)
optimization: {
splitChunks: {
cacheGroups: {
libraries: {
test: /[\\/]node_modules[\\/]|[\\/]frontend[\\/]js[\\/]vendor[\\/]libs[\\/]/,
name: 'libraries',
chunks: 'initial',
minChunks: 2,
},
},
},
},
plugins: [
// Generate a manifest.json file which is used by the backend to map the
// base filenames to the generated output filenames
new ManifestPlugin({
// Always write the manifest file to disk (even if in dev mode, where
// files are held in memory). This is needed because the server will read
// this file (from disk) when building the script's url
writeToFileEmit: true,
}),
// Prevent moment from loading (very large) locale files that aren't used
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
// Copy the required files for loading MathJax from MathJax NPM package
new CopyPlugin(
[
{ from: 'MathJax.js', to: 'js/libs/mathjax' },
{ from: 'config/**/*', to: 'js/libs/mathjax' },
{ from: 'extensions/**/*', to: 'js/libs/mathjax' },
{ from: 'localization/en/**/*', to: 'js/libs/mathjax' },
{ from: 'jax/output/HTML-CSS/fonts/TeX/**/*', to: 'js/libs/mathjax' },
{ from: 'jax/output/HTML-CSS/**/*.js', to: 'js/libs/mathjax' },
{ from: 'jax/element/**/*', to: 'js/libs/mathjax' },
{ from: 'jax/input/**/*', to: 'js/libs/mathjax' },
{ from: 'fonts/HTML-CSS/TeX/woff/*', to: 'js/libs/mathjax' },
],
{
context: 'node_modules/mathjax',
}
),
new CopyPlugin([
{
from: 'frontend/js/vendor/libs/sigma-master',
to: 'js/libs/sigma-master',
},
{
from: 'node_modules/ace-builds/src-min-noconflict',
to: `js/ace-${PackageVersions.version.ace}/`,
},
// Copy CMap files from pdfjs-dist package to build output. These are used
// to provide support for non-Latin characters
{ from: 'node_modules/pdfjs-dist/cmaps', to: 'js/cmaps' },
]),
],
}
| overleaf/web/webpack.config.js/0 | {
"file_path": "overleaf/web/webpack.config.js",
"repo_id": "overleaf",
"token_count": 4236
} | 581 |
{
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.formatOnSave": true,
"eslint.format.enable": true,
"npm.packageManager": "pnpm",
"typescript.format.enable": false,
"editor.quickSuggestions": {
"strings": true
},
"cucumberautocomplete.steps": [
"tests/e2e/cucumber/steps/**/*.ts"
],
"cucumberautocomplete.strictGherkinCompletion": true,
"typescript.tsdk": "node_modules/typescript/lib"
}
| owncloud/web/.vscode/settings.json/0 | {
"file_path": "owncloud/web/.vscode/settings.json",
"repo_id": "owncloud",
"token_count": 292
} | 582 |
Change: Bring new modal component
We've updated our modal component with a new one coming from ODS.
https://github.com/owncloud/web/issues/2263
https://github.com/owncloud/web/pull/3378
| owncloud/web/changelog/0.11.0_2020-06-26/bring-new-modal-component/0 | {
"file_path": "owncloud/web/changelog/0.11.0_2020-06-26/bring-new-modal-component",
"repo_id": "owncloud",
"token_count": 59
} | 583 |
Bugfix: Public upload now keeps modified time
The public upload for public links now keeps the modification time of local files.
This aligns the behavior with non-public file upload.
https://github.com/owncloud/web/pull/3686
| owncloud/web/changelog/0.11.1_2020-06-29/public-link-keep-mtime/0 | {
"file_path": "owncloud/web/changelog/0.11.1_2020-06-29/public-link-keep-mtime",
"repo_id": "owncloud",
"token_count": 57
} | 584 |
Change: Provide option for hiding the search bar
We introduced a new `options.hideSearchBar` config variable which can be used to disable the search bar entirely.
https://github.com/owncloud/product/issues/116
https://github.com/owncloud/web/pull/3817
| owncloud/web/changelog/0.14.0_2020-08-17/hide-search.md/0 | {
"file_path": "owncloud/web/changelog/0.14.0_2020-08-17/hide-search.md",
"repo_id": "owncloud",
"token_count": 68
} | 585 |
Change: More descriptive loading state
When browsing the different variations of the files list we removed the loader component at the top in favor of a spinner in the center of the viewport. The spinner has one line of text which describes what kind of data is being loaded.
https://github.com/owncloud/web/pull/4099
| owncloud/web/changelog/0.17.0_2020-09-25/files-list-loader/0 | {
"file_path": "owncloud/web/changelog/0.17.0_2020-09-25/files-list-loader",
"repo_id": "owncloud",
"token_count": 75
} | 586 |
Bugfix: OIDC logout
We've fixed the bug that the user sometimes got immediately logged back into the web UI after clicking on logout.
https://github.com/owncloud/product/issues/266
https://github.com/owncloud/web/pull/4211 | owncloud/web/changelog/0.21.0_2020-10-21/fix-logout/0 | {
"file_path": "owncloud/web/changelog/0.21.0_2020-10-21/fix-logout",
"repo_id": "owncloud",
"token_count": 65
} | 587 |
Enhancement: Add custom icons in the new file menu
We've added an option to display own icon in the new file menu.
https://github.com/owncloud/web/pull/4375
| owncloud/web/changelog/0.26.0_2020-11-23/new-file-icon/0 | {
"file_path": "owncloud/web/changelog/0.26.0_2020-11-23/new-file-icon",
"repo_id": "owncloud",
"token_count": 47
} | 588 |
Enhancement: Add theme option to disable default files list status indicators
We've added the option into the theme to disable default files list status indicators.
https://github.com/owncloud/web/issues/2895
https://github.com/owncloud/web/pull/2928
| owncloud/web/changelog/0.3.0_2020-01-31/2895-2/0 | {
"file_path": "owncloud/web/changelog/0.3.0_2020-01-31/2895-2",
"repo_id": "owncloud",
"token_count": 66
} | 589 |
Bugfix: Properly manage escaping of all translations
We've stopped escaping translations which contained resource names or user names because they can contain special characters which were then not properly displayed.
We've done this only with translations which are using mustache syntax which does escaping on its own so we don't introduce potential XSS vulnerability.
For all other translations, we've explicitly set the escaping.
https://github.com/owncloud/web/pull/3032
| owncloud/web/changelog/0.4.0_2020-02-14/3032/0 | {
"file_path": "owncloud/web/changelog/0.4.0_2020-02-14/3032",
"repo_id": "owncloud",
"token_count": 97
} | 590 |
Bugfix: Changed share icons to collaborators icons
Adjust icon in files app navigation bar and also in the file actions
dropdown to use the group icon.
https://github.com/owncloud/web/pull/3116
| owncloud/web/changelog/0.6.0_2020-03-16/3116/0 | {
"file_path": "owncloud/web/changelog/0.6.0_2020-03-16/3116",
"repo_id": "owncloud",
"token_count": 51
} | 591 |
Bugfix: fix oidc redirect after logout
After the logout the idp sent a redirect to `<redirectUri>?state=` which was then redirected to `<redirectUri>?state=#/login` by web. Having the query parameters in between broke the application. To prevent the whole login url `<baseUrl>#/login` should be sent then the query parameter will be appended to the end.
https://github.com/owncloud/web/issues/3285
| owncloud/web/changelog/0.8.0_2020-04-14/3291/0 | {
"file_path": "owncloud/web/changelog/0.8.0_2020-04-14/3291",
"repo_id": "owncloud",
"token_count": 115
} | 592 |
Enhancement: Add support for .vsdx files in the draw.io app
Added the support to open .vsdx files (Microsoft Visio Files) directly
from OwnCloud, instead of creating a new diagram to import the file from
local storage.
https://github.com/owncloud/phoenix/pull/4337
https://github.com/owncloud/phoenix/issues/4327
| owncloud/web/changelog/1.0.0_2020-12-16/drawio-vsdx-support/0 | {
"file_path": "owncloud/web/changelog/1.0.0_2020-12-16/drawio-vsdx-support",
"repo_id": "owncloud",
"token_count": 91
} | 593 |
Change: Update ODS to 2.1.2
We updated the ownCloud Design System to 2.1.2. See the linked releases for details.
https://github.com/owncloud/web/pull/4594
https://github.com/owncloud/owncloud-design-system/releases/tag/v2.1.0
https://github.com/owncloud/owncloud-design-system/releases/tag/v2.1.1
https://github.com/owncloud/owncloud-design-system/releases/tag/v2.1.2
| owncloud/web/changelog/2.0.0_2021-02-16/update-ods-2.1.2/0 | {
"file_path": "owncloud/web/changelog/2.0.0_2021-02-16/update-ods-2.1.2",
"repo_id": "owncloud",
"token_count": 136
} | 594 |
Change: New files list
We integrated the new oc-table-files component from our design system. This includes breaking changes in how we load resources in our files app. We refactored our files app codebase into views, so that only subcomponents live in the components directory.
https://github.com/owncloud/web/pull/4627
| owncloud/web/changelog/3.0.0_2021-04-21/change-new-files-list/0 | {
"file_path": "owncloud/web/changelog/3.0.0_2021-04-21/change-new-files-list",
"repo_id": "owncloud",
"token_count": 79
} | 595 |
Enhancement: Extension config
Loading extension specific config was only possible for file editors. We now also load it in the general app information, so that it's available in the `apps` getter of the global vuex store.
https://github.com/owncloud/web/pull/5024
| owncloud/web/changelog/3.1.0_2021-05-12/enhancement-extension-config/0 | {
"file_path": "owncloud/web/changelog/3.1.0_2021-05-12/enhancement-extension-config",
"repo_id": "owncloud",
"token_count": 68
} | 596 |
Bugfix: Hide left sidebar navigation when switching routes
On smaller screens, the left sidebar containing the extension navigation is collapsed.
We've fixed that when the user expanded the sidebar and navigated to a different route the sidebar is collapsed again.
https://github.com/owncloud/web/pull/5025 | owncloud/web/changelog/3.3.0_2021-06-23/bugfix-hide-navigation-on-route-change/0 | {
"file_path": "owncloud/web/changelog/3.3.0_2021-06-23/bugfix-hide-navigation-on-route-change",
"repo_id": "owncloud",
"token_count": 67
} | 597 |
Enhancement: Accessible status indicators
To make both the clickable (button) and the visible (icon) part of the
status indicators in the files table accessible, we have added a description,
in addition to the tooltip and `aria-label`.
https://github.com/owncloud/web/pull/5182
| owncloud/web/changelog/3.3.0_2021-06-23/enhancement-accessible-status-indicators/0 | {
"file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-accessible-status-indicators",
"repo_id": "owncloud",
"token_count": 75
} | 598 |
Enhancement: Move hint in the Location picker under breadcrumbs
We've moved the hint that is describing how to use the Location picker from sidebar under the breadcrumbs.
There is navigation of the Files extension displayed in the sidebar now instead.
https://github.com/owncloud/web/pull/5008 | owncloud/web/changelog/3.3.0_2021-06-23/enhancement-move-location-picker-hint/0 | {
"file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-move-location-picker-hint",
"repo_id": "owncloud",
"token_count": 72
} | 599 |
Bugfix: Batch action for deleting adhering permissions
We fixed that the batch actions for deleting files and folders was showing for shares that only have viewer permissions.
https://github.com/owncloud/web/pull/5441
| owncloud/web/changelog/3.4.0_2021-07-09/bugfix-delete-batch-action-in-viewer-shares/0 | {
"file_path": "owncloud/web/changelog/3.4.0_2021-07-09/bugfix-delete-batch-action-in-viewer-shares",
"repo_id": "owncloud",
"token_count": 53
} | 600 |
Change: Add custom search service
We've added `search` as another core app that can be utilized by
other (third-party) frontend extensions to provide
filter and search functionality.
Please note that you need to add `search` to the `apps` array of your config.json file, otherwise the search bar with its global file search capabilities will disappear.
https://github.com/owncloud/web/pull/5415
| owncloud/web/changelog/4.0.0_2021-08-04/change-add-customer-search-service/0 | {
"file_path": "owncloud/web/changelog/4.0.0_2021-08-04/change-add-customer-search-service",
"repo_id": "owncloud",
"token_count": 98
} | 601 |
Enhancement: Signout icon
We changed the icon in the personal menu nav item for signing out based on recent user feedback.
https://github.com/owncloud/web/pull/5681
| owncloud/web/changelog/4.1.0_2021-08-20/enhancement-signout-icon/0 | {
"file_path": "owncloud/web/changelog/4.1.0_2021-08-20/enhancement-signout-icon",
"repo_id": "owncloud",
"token_count": 46
} | 602 |
Enhancement: Add AppProvider actions to fileactions
If the AppProvider within oCIS communicates a matching application
for the mime type of a file, there are now additional actions in
the default actions and actions in both the contextmenu and the right sidebar.
https://github.com/owncloud/web/pull/5805
| owncloud/web/changelog/4.3.0_2021-10-07/enhancement-external-app-fileactions/0 | {
"file_path": "owncloud/web/changelog/4.3.0_2021-10-07/enhancement-external-app-fileactions",
"repo_id": "owncloud",
"token_count": 77
} | 603 |
Bugfix: Context menu rendering
We fixed that the context menu was being created for each and every file row of the current page (it was just not made visible). Now it only gets created when it gets activated by the user for a file row.
https://github.com/owncloud/web/pull/5952
| owncloud/web/changelog/4.5.0_2021-11-16/bugfix-context-menu-rendering/0 | {
"file_path": "owncloud/web/changelog/4.5.0_2021-11-16/bugfix-context-menu-rendering",
"repo_id": "owncloud",
"token_count": 70
} | 604 |
Bugfix: Inconsistencies in share expiry dates
* Share expiry dates now always refer to the end of the given day. This change allows users to select the current day as expiry date.
* Displayed expiry dates have been aligned to ensure their consistency.
* Existing expiry dates for public links can now be removed again.
* We now use the Luxon `DateTime` object more consistently across the code base (replacing JavaScript's `new Date()).
https://github.com/owncloud/web/pull/6084
| owncloud/web/changelog/4.7.0_2021-12-16/bugfix-expiry-date-inconsistencies/0 | {
"file_path": "owncloud/web/changelog/4.7.0_2021-12-16/bugfix-expiry-date-inconsistencies",
"repo_id": "owncloud",
"token_count": 122
} | 605 |
Enhancement: MarkdownEditor and MediaViewer can be default
We have updated the extension handlers of two internal
apps to be able to be used as default actions.
https://github.com/owncloud/web/pull/6148
| owncloud/web/changelog/4.7.0_2021-12-16/enhancement-default-markdown-mediaviewer-extensions/0 | {
"file_path": "owncloud/web/changelog/4.7.0_2021-12-16/enhancement-default-markdown-mediaviewer-extensions",
"repo_id": "owncloud",
"token_count": 56
} | 606 |
Bugfix: Focus management in topbar dropdowns
We've fixed issues with focus management upon opening and closing
the dropdown menus in the ApplicationSwitcher and Usermenu.
https://github.com/owncloud/web/pull/6213
| owncloud/web/changelog/5.0.0_2022-02-14/bugfix-topbar-focus-management/0 | {
"file_path": "owncloud/web/changelog/5.0.0_2022-02-14/bugfix-topbar-focus-management",
"repo_id": "owncloud",
"token_count": 56
} | 607 |
Enhancement: Lazy resource table cells
ODS introduced lazy loadable table cells, this feature is now also part of web and enabled by default.
To disable the feature set the displayResourcesLazy option to false.
https://github.com/owncloud/web/pull/6204
| owncloud/web/changelog/5.0.0_2022-02-14/enhancement-lazy-resource-table/0 | {
"file_path": "owncloud/web/changelog/5.0.0_2022-02-14/enhancement-lazy-resource-table",
"repo_id": "owncloud",
"token_count": 66
} | 608 |
Enhancement: Use the Vue store for spaces
Using the store for spaces integrates them seamlessly in our ecosystem and makes it easier to develop spaces even further. E.g. the properties of a space can now be altered without fetching all spaces again. This was achieved by introducing a "buildSpace" method, that transforms a space into a more generic resource object (just like regular files or shares).
https://github.com/owncloud/web/pull/6427
| owncloud/web/changelog/5.1.0_2022-02-18/enhancement-spaces-use-store/0 | {
"file_path": "owncloud/web/changelog/5.1.0_2022-02-18/enhancement-spaces-use-store",
"repo_id": "owncloud",
"token_count": 102
} | 609 |
Bugfix: Thumbnails only for accepted shares
Only accepted shares now display a thumbnail in the "Shared with me" resource table.
https://github.com/owncloud/web/issues/5310
https://github.com/owncloud/web/pull/6534
| owncloud/web/changelog/5.3.0_2022-03-23/bugfix-accepted-share-thumbnails/0 | {
"file_path": "owncloud/web/changelog/5.3.0_2022-03-23/bugfix-accepted-share-thumbnails",
"repo_id": "owncloud",
"token_count": 62
} | 610 |
Enhancement: App context route to query instead of params
We've moved app context information (where you get redirected
when you close an app) into the query instead of a regular
param. This relocates this information further to the back
of the url where it's less confusing for users.
https://github.com/owncloud/web/pull/6622
| owncloud/web/changelog/5.3.0_2022-03-23/enhancement-context-route-name-in-query/0 | {
"file_path": "owncloud/web/changelog/5.3.0_2022-03-23/enhancement-context-route-name-in-query",
"repo_id": "owncloud",
"token_count": 82
} | 611 |
Enhancement: Update the stored space after its members have been changed
We now update the stored space after its members have been changed. Also, the permission-object of a built space has been simplified in the course of this.
https://github.com/owncloud/web/pull/6545
| owncloud/web/changelog/5.3.0_2022-03-23/enhancement-space-update-store/0 | {
"file_path": "owncloud/web/changelog/5.3.0_2022-03-23/enhancement-space-update-store",
"repo_id": "owncloud",
"token_count": 66
} | 612 |
Enhancement: Archive download for oc10 backend
We now offer archive downloads (multifile or folder) as archive with oc10 backends. Since oc10 archive downloads are path based this could only be made possible on pages that follow the folder hierarchy of the logged in user. In other words: on favorites pages the archive download is unavailable for oc10 backends as the selected files/folders don't necessarily share the same parent folder.
https://github.com/owncloud/web/issues/6239
https://github.com/owncloud/web/pull/6697
| owncloud/web/changelog/5.4.0_2022-04-11/enhancement-archiver-v1-service/0 | {
"file_path": "owncloud/web/changelog/5.4.0_2022-04-11/enhancement-archiver-v1-service",
"repo_id": "owncloud",
"token_count": 130
} | 613 |
Enhancement: Spaces link sharing
Spaces and their resources can now be shared via links.
https://github.com/owncloud/web/pull/6633
https://github.com/owncloud/web/issues/6283
| owncloud/web/changelog/5.4.0_2022-04-11/enhancement-spaces-link-sharing/0 | {
"file_path": "owncloud/web/changelog/5.4.0_2022-04-11/enhancement-spaces-link-sharing",
"repo_id": "owncloud",
"token_count": 55
} | 614 |
Bugfix: Changing link permissions to role requiring password
We have added a dialogue option for updates of a link's permissions to a new role that would require a password.
It now prompts the user to add a password instead of failing directly.
https://github.com/owncloud/web/pull/6989
https://github.com/owncloud/web/issues/6974
| owncloud/web/changelog/5.5.0_2022-06-20/bugfix-link-permission-enforced-password/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/bugfix-link-permission-enforced-password",
"repo_id": "owncloud",
"token_count": 84
} | 615 |
Bugfix: Share with people items overflows on long names
We've fixed a bug where:
* Search suggestion overflows the view port, while name is too long
* Selected user overflows the select box item, while name is too long
https://github.com/owncloud/web/pull/6984
https://github.com/owncloud/web/issues/6004
| owncloud/web/changelog/5.5.0_2022-06-20/bugfix-share-with-people-overflow-on-long-names/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/bugfix-share-with-people-overflow-on-long-names",
"repo_id": "owncloud",
"token_count": 86
} | 616 |
Enhancement: Add OcContextualHelper
We've added contextual helpers to provide more information
based on the context
https://github.com/owncloud/web/issues/6590
https://github.com/owncloud/web/pull/6750 | owncloud/web/changelog/5.5.0_2022-06-20/enhancement-add-contextual-help/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/enhancement-add-contextual-help",
"repo_id": "owncloud",
"token_count": 59
} | 617 |
Enhancement: Introduce sharing jail
We've added the sharing jail to oCIS which means that navigating and
working with shares now happens inside the `Shares` navigation item.
https://github.com/owncloud/web/pull/6593
https://github.com/owncloud/web/pull/6909
https://github.com/owncloud/web/pull/6916
https://github.com/owncloud/web/issues/5152
https://github.com/owncloud/web/issues/6448
| owncloud/web/changelog/5.5.0_2022-06-20/enhancement-introduce-sharing-jail/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/enhancement-introduce-sharing-jail",
"repo_id": "owncloud",
"token_count": 122
} | 618 |
Enhancement: Resumable uploads
We've implemented Uppy as a library for handling uploads. This concludes the following features and changes:
- Resumable uploads when the backend supports the Tus-protocol
- A nice looking overview for all files that have been uploaded successfully or failed to upload
- Navigation across Web while uploads are in progress
- Improved rendering of uploadProgress-visualization
- Removed `vue2-dropzone` and `vue-drag-drop` libraries
https://github.com/owncloud/web/pull/6202
https://github.com/owncloud/web/issues/5031
https://github.com/owncloud/web/issues/6268
| owncloud/web/changelog/5.5.0_2022-06-20/enhancement-resumeable-uploads/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/enhancement-resumeable-uploads",
"repo_id": "owncloud",
"token_count": 160
} | 619 |
Enhancement: Separate direct and indirect link shares in sidebar
We have split the list of link shares into two lists, one with direct (and editable) and another one with read-only indirect link shares of parent folders for better structure in the sidebar.
https://github.com/owncloud/web/pull/7140
https://github.com/owncloud/web/issues/7132
| owncloud/web/changelog/5.6.0_2022-06-21/enhancement-split-sidebar-direct-indirect-linkshares/0 | {
"file_path": "owncloud/web/changelog/5.6.0_2022-06-21/enhancement-split-sidebar-direct-indirect-linkshares",
"repo_id": "owncloud",
"token_count": 89
} | 620 |
Bugfix: Files pagination scroll to top
We've fixed a bug where changing the page in a file list (pagination) doesn't scroll to top.
https://github.com/owncloud/web/pull/7322
https://github.com/owncloud/web/issues/7138
| owncloud/web/changelog/5.7.0_2022-09-09/bugfix-files-pagination-scroll-to-top/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/bugfix-files-pagination-scroll-to-top",
"repo_id": "owncloud",
"token_count": 69
} | 621 |
Bugfix: No redirect after disabling space
We've fixed a bug where the user was not redirected to the spaces overview after disabling the space
inside the space view.
https://github.com/owncloud/web/pull/7334
https://github.com/owncloud/web/issues/7291
| owncloud/web/changelog/5.7.0_2022-09-09/bugfix-no-redirect-after-disabling-space/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/bugfix-no-redirect-after-disabling-space",
"repo_id": "owncloud",
"token_count": 69
} | 622 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.