text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
---
title: Модул тајмера
date: "2019-05-22T03:15:00"
author: Y_Less
---
Ово је sneak-peek једног од унапређених модула који смо завршили, за тајмере у open.mp:
```pawn
native SetTimer(const func[], msInterval, bool:repeat) = SetTimerEx;
native SetTimerEx(const func[], msInterval, bool:repeat, const params[], GLOBAL_TAG_TYPES:...);
native KillTimer(timer) = Timer_Kill;
// CreateTimer
native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...);
// KillTimer
native bool:Timer_Kill(Timer:timer);
// Враћа време до следећег позива.
native Timer_GetTimeRemaining(Timer:timer);
// Добија број преосталих позива (0 for unlimited).
native Timer_GetCallsRemaining(Timer:timer);
// Добија `repeatCount` параметар.
native Timer_GetTotalCalls(Timer:timer);
// Добија `usInterval` параметар.
native Timer_GetInterval(Timer:timer);
// Враћа преостало време на почетну вредност до следећег позива за `usInterval`.
native bool:Timer_Restart(Timer:timer);
```
Прва два су због компактибилности, остатак је унапређен API:
```pawn
native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...);
```
- `func` - Врло очигледно; шта да се позове.
- `usDelay` - Опет очигледно, време пре позива (у микросекундама).
- `usInterval` - На шта да ресетује `usDelay` након првог позива. Тако да, ако си хтео тајмер на сваких сат времена, али је тренутно 8:47, позив би био `Timer_Create("OnTheHour", 780 SECONDS, 3600 SECONDS, 0);`
- `repeatCount` - Не као старе функције, које су само "једном" или "заувек", уместо тога ово је број колико ће бута бити позвана функија. "Једном" би било `1`, `500` би зауставило тајмер након 500 позива, и (компактибилност стареог API-а) `0` значи "заувек".
- `GLOBAL_TAG_TYPES` - Као и `{Float, ...}`, али са више ознака.
| openmultiplayer/web/frontend/content/sr/blog/timers.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/sr/blog/timers.mdx",
"repo_id": "openmultiplayer",
"token_count": 1233
} | 482 |
---
title: 10,000 Members!
date: "2021-07-16T02:51:00"
author: Potassium
---
Всім привіт!
Нещодавно ми досягли дивовижної віхи: ми офіційно досягли 10000 користувачів у нашому Discord! 🥳🔟🥳
Ми думали, що скористаємося цією можливістю, щоб дати невелике оновлення, оскільки ми знаємо, що минуло деякий час, і всім цікаво, що відбувається!
Оскільки вся команда розробників має роботу на повний робочий день та інші зобов’язання, ми всі дійсно заплуталися з ситуацією з COVID. Це означає, що ми вже деякий час не маємо багато часу, щоб присвятити open.mp.
Але нещодавно ситуація знову пожвавилася, ми все ще живі, проект справді рухається швидше, ніж будь-коли, і за останні кілька тижнів ми досягли більшого прогресу, ніж за довгий час!
Ми дуже пишаємось нашою роботою та надзвичайною витонченою командою, яка у нас є.
У найближчі місяці ми надамо більш детальну інформацію, але ми просто хотіли переконатися, що всі знають, що ми не відмовились від open.mp, пристрасть все ще існує, і ми робимо все можливе. Тож будь ласка, залишайтесь з нами, оскільки незабаром у нас будуть деякі новини, а також деякі скріншоти та відео!
Тим часом, приходьте тусити з нами на Discord! Дякуємо всім 10.000 участникам і більше 🥰
Наш сервер Discord — це тепле та приємне місце для гравців та друзів ВСІХ багатокористувацьких модів та спільнот San Andreas! Деякі речі, які ми рекламуємо, це:
✅ Community: Спілкуйтеся зі звичайними відвідувачами, знайомтеся з новими людьми, знайдіть старих друзів та гравців-ветеранів, знайдіть людей з вашої країни / регіону на мовних каналах, познайомтесь з людьми із SA-MP / MTA / інших багатокористувацьких модів.
✅ Scripting: Навчіться скриптити, отримуйте допомогу зі своїми скриптами, допомагайте іншим.
✅ Server advertisements: Розкажіть про свій сервер SA-MP на певних каналах.
✅ Programming and tech: Обговоріть та отримайте допомогу щодо інших мов програмування та розробки програмного забезпечення, технічної підтримки, познайомтесь з іншими однодумцями з тієї ж сфери.
✅ Gaming: Знаходьте людей з котрими можна грати (не лише з SA). Обговорюйте новини та оновлення ігор.
✅ Showcase: Ви ютубер? Стример? Дизайнер? Вмієте писати круту музику? Чи ви кухар? Можливо, ви ловите рибу? Або навіть будуєте автомобілі? Чим би ви не пишалися, продемонструйте це!
✅ open.mp: Будьте в курсі останніх досягнень розробки open.mp та GitHub, спілкуйтеся з командою, дивіться наші ексклюзивні потоки розробників Discord VIP, коли вони відновляться та працюють!
| openmultiplayer/web/frontend/content/uk/blog/10k-members.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/uk/blog/10k-members.mdx",
"repo_id": "openmultiplayer",
"token_count": 2608
} | 483 |
---
title: SA-MP 安卓(移动端)
date: "2021-01-30T12:46:46"
author: Potassium
---
open.mp 团队对安卓版 SA-MP 的看法
大家好,
我们只是想写一篇简短的博客,谈谈我们对安卓版 SA-MP 的看法,因为我们在 YouTube 视频和 Discord 上收到了很多关于它的评论。
正如我们在 YouTube 视频中所说,我们不支持当前的安卓版 SA-MP。这个 app 使用了从 SA-MP 团队窃取的源代码实现的,是非法的。
我们不容忍窃取他人代码的行为,也不容忍使用窃取的代码。我们也不与非法活动联系在一起。
我们看到《侠盗猎车手:圣安地列斯》联机的移动端拥有庞大的社区群体,我们欢迎并希望这个社区能加入到 open.mp 中。
我们目前正在讨论如何为 SA 移动端创建我们自己的联机模组,以便它被合法,公平地完成!:)
这意味着未来很有可能会有移动端的 open.mp,所以在我们想办法的时候,请继续支持我们。
我们邀请移动端的社区加入我们拥有 7000 多名成员的官方 Discord,我们已经创建了一个#samp-android 频道,期待听到你们的想法和意见。
不见不散!
https://discord.gg/samp
| openmultiplayer/web/frontend/content/zh-cn/blog/samp-mobile.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/zh-cn/blog/samp-mobile.mdx",
"repo_id": "openmultiplayer",
"token_count": 813
} | 484 |
import { WarningTwoIcon } from "@chakra-ui/icons";
import { Heading, Stack, Text } from "@chakra-ui/layout";
import React, { FC } from "react";
import { APIError } from "src/types/_generated_Error";
type Props = APIError;
const ErrorBanner: FC<Props> = ({ error, message, suggested }) => {
return (
<section>
<Stack spacing={4}>
<header>
<WarningTwoIcon w={7} h={7} />
<Heading my="0">An Error Occurred</Heading>
</header>
<Text>{message ?? "An unexpected error occurred."}</Text>
{suggested && (
<Text>
<em>Suggested action:</em> {suggested}
</Text>
)}
<pre>{error ?? "(no detailed error information was provided)"}</pre>
</Stack>
<style jsx>{`
section {
max-width: 40em;
margin: auto;
padding: 3em;
background-color: var(--chakra-colors-red-300);
}
header {
display: flex;
align-items: center;
gap: 0.5em;
}
`}</style>
</section>
);
};
export default ErrorBanner;
| openmultiplayer/web/frontend/src/components/ErrorBanner.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/ErrorBanner.tsx",
"repo_id": "openmultiplayer",
"token_count": 523
} | 485 |
import {
Box,
Button,
Flex,
Heading,
HStack,
Image,
Link,
Text,
useClipboard,
VStack,
} from "@chakra-ui/react";
import { ChakraProps } from "@chakra-ui/system";
import NextLink from "next/link";
import { FC, useCallback } from "react";
import { useIsAdmin } from "src/auth/hooks";
import { useDeleteServer } from "src/components/listing/hooks";
import { Essential } from "src/types/_generated_Server";
type CopyBadgeProps = { text: string };
const CopyBadge: FC<CopyBadgeProps> = ({ text }) => {
const { onCopy, hasCopied } = useClipboard(text);
return (
<HStack>
<Text fontSize="xl" fontWeight="bold" marginTop="0">
{text}
</Text>
<Button
size="xs"
onClick={onCopy}
style={hasCopied ? { backgroundColor: "#81C784", color: "white" } : {}}
>
{hasCopied ? "COPIED" : "COPY"}
</Button>
</HStack>
);
};
type ServerRowProps = { server: Essential };
const ServerRow: FC<ServerRowProps & ChakraProps> = ({ server, sx }) => {
const deleteServer = useDeleteServer();
const onDelete = useCallback(
() => deleteServer(server.ip),
[deleteServer, server]
);
const admin = useIsAdmin();
return (
<Box sx={sx}>
<Box>
<Flex justifyContent="space-between" alignItems="start">
<NextLink href={"/servers/" + server.ip} passHref>
<Link>
<Heading
wordBreak={"break-word"}
fontSize={"xl"}
style={{ marginTop: "0" }}
_hover={{ textDecor: "underline", cursor: "pointer" }}
>
{server.hn}
</Heading>
</Link>
</NextLink>
<HStack>
{server.pr && (
<Image
src="https://assets.open.mp/assets/images/assets/partners.png"
alt="partner server"
title="Has partnership!"
maxWidth={7}
maxHeight={7}
width={7}
height={7}
unoptimized={true}
/>
)}
{server.omp && (
<Image
src="https://assets.open.mp/assets/images/assets/logo-light-trans.svg"
alt="open.mp server"
title="open.mp server"
maxWidth={7}
maxHeight={7}
width={7}
height={7}
unoptimized={true}
/>
)}
</HStack>
</Flex>
<Flex
justifyContent="space-between"
alignItems="start"
my="0.3em"
flexWrap="wrap"
>
<VStack align="left">
<Text style={{ marginTop: "0" }}>{server.gm}</Text>
{/* <Text style={{ marginTop: "0" }}>{"website"}</Text> */}
<CopyBadge text={server.ip} />
</VStack>
<VStack align="end">
<Flex
flexDirection="row"
alignItems="center"
gridGap=".5em"
flexWrap="wrap"
>
<Text
fontWeight={"bold"}
fontSize="2xl"
style={{ marginTop: "0" }}
>
{server.pc}/{server.pm}
</Text>
<Text style={{ marginTop: "0" }}>players</Text>
</Flex>
<Box display={admin ? "block" : "none"}>
<Button onClick={onDelete}>Delete</Button>
</Box>
</VStack>
</Flex>
</Box>
</Box>
);
};
export default ServerRow;
| openmultiplayer/web/frontend/src/components/listing/ServerRow.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/listing/ServerRow.tsx",
"repo_id": "openmultiplayer",
"token_count": 1962
} | 486 |
import VersionWarn from "./version-warning";
import LowercaseNote from "./lowercase-note";
import TipNPCCallbacks from "./npc-callbacks-tip";
import VersionWarnID from "./translations/id/version-warning";
import LowercaseNoteID from "./translations/id/lowercase-note";
import TipNPCCallbacksID from "./translations/id/npc-callbacks-tip";
import VersionWarnPT_BR from "./translations/pt-BR/version-warning";
import LowercaseNotePT_BR from "./translations/pt-BR/lowercase-note";
import TipNPCCallbacksPT_BR from "./translations/pt-BR/npc-callbacks-tip";
import VersionWarnES from "./translations/es/version-warning";
import LowercaseNoteES from "./translations/es/lowercase-note";
import TipNPCCallbacksES from "./translations/es/npc-callbacks-tip";
import VersionWarnCN from "./translations/zh-cn/version-warning";
import LowercaseNoteCN from "./translations/zh-cn/lowercase-note";
import TipNPCCallbacksCN from "./translations/zh-cn/npc-callbacks-tip";
import VersionWarnTR from "./translations/tr/version-warning";
import LowercaseNoteTR from "./translations/tr/lowercase-note";
import TipNPCCallbacksTR from "./translations/tr/npc-callbacks-tip";
import VersionWarnBS from "./translations/bs/version-warning";
import LowercaseNoteBS from "./translations/bs/lowercase-note";
import TipNPCCallbacksBS from "./translations/bs/npc-callbacks-tip";
import Image from "./Image";
const templates = {
img: Image,
VersionWarn,
LowercaseNote,
TipNPCCallbacks,
VersionWarnID,
LowercaseNoteID,
TipNPCCallbacksID,
VersionWarnPT: VersionWarnPT_BR,
LowercaseNotePT: LowercaseNotePT_BR,
TipNPCCallbacksPT: TipNPCCallbacksPT_BR,
VersionWarnES,
LowercaseNoteES,
TipNPCCallbacksES,
VersionWarnCN,
LowercaseNoteCN,
TipNPCCallbacksCN,
VersionWarnTR,
LowercaseNoteTR,
TipNPCCallbacksTR,
VersionWarnBS,
LowercaseNoteBS,
TipNPCCallbacksBS,
};
export default templates;
| openmultiplayer/web/frontend/src/components/templates/index.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/index.ts",
"repo_id": "openmultiplayer",
"token_count": 643
} | 487 |
import Admonition from "../../../Admonition";
export default function TipNpcCallback() {
return (
<Admonition type="tip">
<p>Bu geri çağırma aynı zamanda NPC tarafından da çağrılabilir.</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/tr/npc-callbacks-tip.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/tr/npc-callbacks-tip.tsx",
"repo_id": "openmultiplayer",
"token_count": 99
} | 488 |
import Image from "next/image";
export default function Custom404() {
return (
<section className="measure-wide center">
<h1 className="tc">404 - Page Not Found</h1>
<Image
src="https://assets.open.mp/assets/images/assets/404.jpg"
width={1280}
height={720}
/>
</section>
);
}
| openmultiplayer/web/frontend/src/pages/404.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/404.tsx",
"repo_id": "openmultiplayer",
"token_count": 140
} | 489 |
import { GetServerSideProps } from "next";
import { FC } from "react";
import ErrorBanner from "src/components/ErrorBanner";
import MemberView from "src/components/member/MemberView";
import { apiSSP, SSP } from "src/fetcher/fetcher";
import { User, UserSchema } from "src/types/_generated_User";
type Props = SSP<User>;
const Page: FC<Props> = (props) => {
if (props.success === false) {
return <ErrorBanner {...props.error} />;
}
return <MemberView user={props.data} />;
};
export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
const id = ctx.params?.["id"];
return {
props: await apiSSP<User>(`/users/${id}`, ctx, {
schema: UserSchema,
}),
};
};
export default Page;
| openmultiplayer/web/frontend/src/pages/members/[id].tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/members/[id].tsx",
"repo_id": "openmultiplayer",
"token_count": 271
} | 490 |
import * as z from "zod"
export const LinkSchema = z.object({
url: z.string(),
})
export type Link = z.infer<typeof LinkSchema>
export const CallbackSchema = z.object({
state: z.string(),
code: z.string(),
})
export type Callback = z.infer<typeof CallbackSchema>
| openmultiplayer/web/frontend/src/types/_generated_Discord.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/types/_generated_Discord.ts",
"repo_id": "openmultiplayer",
"token_count": 97
} | 491 |
{
"framework": "nextjs",
"git": {
"deploymentEnabled": {
"master": true
}
}
} | openmultiplayer/web/frontend/vercel.json/0 | {
"file_path": "openmultiplayer/web/frontend/vercel.json",
"repo_id": "openmultiplayer",
"token_count": 67
} | 492 |
package web
import (
"encoding/json"
"net/http"
"github.com/Southclaws/qstring"
"github.com/asaskevich/govalidator"
)
func ParseQuery(w http.ResponseWriter, r *http.Request, out interface{}) bool {
if err := qstring.Unmarshal(r.URL.Query(), out); err != nil {
StatusBadRequest(w, err)
return false
}
if _, err := govalidator.ValidateStruct(out); err != nil {
StatusBadRequest(w, err)
return false
}
return true
}
func ParseBody(w http.ResponseWriter, r *http.Request, out interface{}) bool {
if err := json.NewDecoder(r.Body).Decode(out); err != nil {
StatusBadRequest(w, WithSuggestion(err,
"Could not process request data",
"Please try again, if the issue persists contact the support team."))
return false
}
if _, err := govalidator.ValidateStruct(out); err != nil {
StatusBadRequest(w, WithSuggestion(err,
"Could not validate request",
"Please try again, if the issue persists contact the support team."))
return false
}
return true
}
| openmultiplayer/web/internal/web/decode.go/0 | {
"file_path": "openmultiplayer/web/internal/web/decode.go",
"repo_id": "openmultiplayer",
"token_count": 351
} | 493 |
-- AlterTable
ALTER TABLE "Server" ADD COLUMN "omp" BOOL NOT NULL DEFAULT false;
| openmultiplayer/web/prisma/migrations/20230927192536_add_omp_column/migration.sql/0 | {
"file_path": "openmultiplayer/web/prisma/migrations/20230927192536_add_omp_column/migration.sql",
"repo_id": "openmultiplayer",
"token_count": 30
} | 494 |
.sb-show-main.modal-open {
overflow-y: auto !important;
}
.sb-show-main .modal-backdrop {
display: none;
}
.sb-show-main .modal {
position: relative;
}
| overleaf/web/.storybook/preview.css/0 | {
"file_path": "overleaf/web/.storybook/preview.css",
"repo_id": "overleaf",
"token_count": 68
} | 495 |
const AuthenticationController = require('./../Authentication/AuthenticationController')
const AnalyticsController = require('./AnalyticsController')
const AnalyticsProxy = require('./AnalyticsProxy')
const RateLimiterMiddleware = require('./../Security/RateLimiterMiddleware')
module.exports = {
apply(webRouter, privateApiRouter, publicApiRouter) {
webRouter.post(
'/event/:event([a-z0-9-_]+)',
RateLimiterMiddleware.rateLimit({
endpointName: 'analytics-record-event',
maxRequests: 200,
timeInterval: 60,
}),
AnalyticsController.recordEvent
)
webRouter.put(
'/editingSession/:projectId',
RateLimiterMiddleware.rateLimit({
endpointName: 'analytics-update-editing-session',
params: ['projectId'],
maxRequests: 20,
timeInterval: 60,
}),
AnalyticsController.updateEditingSession
)
publicApiRouter.use(
'/analytics/uniExternalCollaboration',
AuthenticationController.requirePrivateApiAuth(),
RateLimiterMiddleware.rateLimit({
endpointName: 'analytics-uni-external-collab-proxy',
maxRequests: 20,
timeInterval: 60,
}),
AnalyticsProxy.call('/uniExternalCollaboration')
)
},
}
| overleaf/web/app/src/Features/Analytics/AnalyticsRouter.js/0 | {
"file_path": "overleaf/web/app/src/Features/Analytics/AnalyticsRouter.js",
"repo_id": "overleaf",
"token_count": 489
} | 496 |
const OError = require('@overleaf/o-error')
const HttpErrorHandler = require('../../Features/Errors/HttpErrorHandler')
const { ObjectId } = require('mongodb')
const CollaboratorsHandler = require('./CollaboratorsHandler')
const CollaboratorsGetter = require('./CollaboratorsGetter')
const OwnershipTransferHandler = require('./OwnershipTransferHandler')
const SessionManager = require('../Authentication/SessionManager')
const EditorRealTimeController = require('../Editor/EditorRealTimeController')
const TagsHandler = require('../Tags/TagsHandler')
const Errors = require('../Errors/Errors')
const logger = require('logger-sharelatex')
const { expressify } = require('../../util/promises')
module.exports = {
removeUserFromProject: expressify(removeUserFromProject),
removeSelfFromProject: expressify(removeSelfFromProject),
getAllMembers: expressify(getAllMembers),
setCollaboratorInfo: expressify(setCollaboratorInfo),
transferOwnership: expressify(transferOwnership),
}
async function removeUserFromProject(req, res, next) {
const projectId = req.params.Project_id
const userId = req.params.user_id
await _removeUserIdFromProject(projectId, userId)
EditorRealTimeController.emitToRoom(projectId, 'project:membership:changed', {
members: true,
})
res.sendStatus(204)
}
async function removeSelfFromProject(req, res, next) {
const projectId = req.params.Project_id
const userId = SessionManager.getLoggedInUserId(req.session)
await _removeUserIdFromProject(projectId, userId)
res.sendStatus(204)
}
async function getAllMembers(req, res, next) {
const projectId = req.params.Project_id
logger.log({ projectId }, 'getting all active members for project')
let members
try {
members = await CollaboratorsGetter.promises.getAllInvitedMembers(projectId)
} catch (err) {
throw OError.tag(err, 'error getting members for project', { projectId })
}
res.json({ members })
}
async function setCollaboratorInfo(req, res, next) {
try {
const projectId = req.params.Project_id
const userId = req.params.user_id
const { privilegeLevel } = req.body
await CollaboratorsHandler.promises.setCollaboratorPrivilegeLevel(
projectId,
userId,
privilegeLevel
)
EditorRealTimeController.emitToRoom(
projectId,
'project:membership:changed',
{ members: true }
)
res.sendStatus(204)
} catch (err) {
if (err instanceof Errors.NotFoundError) {
HttpErrorHandler.notFound(req, res)
} else {
next(err)
}
}
}
async function transferOwnership(req, res, next) {
const sessionUser = SessionManager.getSessionUser(req.session)
const projectId = req.params.Project_id
const toUserId = req.body.user_id
try {
await OwnershipTransferHandler.promises.transferOwnership(
projectId,
toUserId,
{
allowTransferToNonCollaborators: sessionUser.isAdmin,
sessionUserId: ObjectId(sessionUser._id),
}
)
res.sendStatus(204)
} catch (err) {
if (err instanceof Errors.ProjectNotFoundError) {
HttpErrorHandler.notFound(req, res, `project not found: ${projectId}`)
} else if (err instanceof Errors.UserNotFoundError) {
HttpErrorHandler.notFound(req, res, `user not found: ${toUserId}`)
} else if (err instanceof Errors.UserNotCollaboratorError) {
HttpErrorHandler.forbidden(
req,
res,
`user ${toUserId} should be a collaborator in project ${projectId} prior to ownership transfer`
)
} else {
next(err)
}
}
}
async function _removeUserIdFromProject(projectId, userId) {
await CollaboratorsHandler.promises.removeUserFromProject(projectId, userId)
EditorRealTimeController.emitToRoom(
projectId,
'userRemovedFromProject',
userId
)
await TagsHandler.promises.removeProjectFromAllTags(userId, projectId)
}
| overleaf/web/app/src/Features/Collaborators/CollaboratorsController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Collaborators/CollaboratorsController.js",
"repo_id": "overleaf",
"token_count": 1313
} | 497 |
const AuthenticationController = require('../Authentication/AuthenticationController')
const SessionManager = require('../Authentication/SessionManager')
const ContactController = require('./ContactController')
const Settings = require('@overleaf/settings')
function contactsAuthenticationMiddleware() {
if (!Settings.allowAnonymousReadAndWriteSharing) {
return AuthenticationController.requireLogin()
} else {
return (req, res, next) => {
if (SessionManager.isUserLoggedIn(req.session)) {
next()
} else {
res.send({ contacts: [] })
}
}
}
}
module.exports = {
apply(webRouter) {
webRouter.get(
'/user/contacts',
contactsAuthenticationMiddleware(),
ContactController.getContacts
)
},
}
| overleaf/web/app/src/Features/Contacts/ContactRouter.js/0 | {
"file_path": "overleaf/web/app/src/Features/Contacts/ContactRouter.js",
"repo_id": "overleaf",
"token_count": 255
} | 498 |
const { callbackify } = require('util')
const Settings = require('@overleaf/settings')
const EmailBuilder = require('./EmailBuilder')
const EmailSender = require('./EmailSender')
const EMAIL_SETTINGS = Settings.email || {}
module.exports = {
sendEmail: callbackify(sendEmail),
promises: {
sendEmail,
},
}
async function sendEmail(emailType, opts) {
const email = EmailBuilder.buildEmail(emailType, opts)
if (email.type === 'lifecycle' && !EMAIL_SETTINGS.lifecycle) {
return
}
opts.html = email.html
opts.text = email.text
opts.subject = email.subject
await EmailSender.promises.sendEmail(opts)
}
| overleaf/web/app/src/Features/Email/EmailHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Email/EmailHandler.js",
"repo_id": "overleaf",
"token_count": 214
} | 499 |
const { UserSchema } = require('../../models/User')
module.exports = {
hasAnyStaffAccess,
}
function hasAnyStaffAccess(user) {
if (user.isAdmin) {
return true
}
if (!user.staffAccess) {
return false
}
for (const key of Object.keys(UserSchema.obj.staffAccess)) {
if (user.staffAccess[key]) return true
}
return false
}
| overleaf/web/app/src/Features/Helpers/AuthorizationHelper.js/0 | {
"file_path": "overleaf/web/app/src/Features/Helpers/AuthorizationHelper.js",
"repo_id": "overleaf",
"token_count": 127
} | 500 |
const { callbackify } = require('util')
const UserGetter = require('../User/UserGetter')
const UserMembershipsHandler = require('../UserMembership/UserMembershipsHandler')
const UserMembershipEntityConfigs = require('../UserMembership/UserMembershipEntityConfigs')
async function _getCurrentAffiliations(userId) {
const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
// current are those confirmed and not with lapsed reconfirmations
return fullEmails
.filter(
emailData =>
emailData.confirmedAt &&
emailData.affiliation &&
emailData.affiliation.institution &&
emailData.affiliation.institution.confirmed &&
!emailData.affiliation.pastReconfirmDate
)
.map(emailData => emailData.affiliation)
}
async function getCurrentInstitutionIds(userId) {
// current are those confirmed and not with lapsed reconfirmations
// only 1 record returned per current institutionId
const institutionIds = new Set()
const currentAffiliations = await _getCurrentAffiliations(userId)
currentAffiliations.forEach(affiliation => {
institutionIds.add(affiliation.institution.id)
})
return [...institutionIds]
}
const InstitutionsGetter = {
getConfirmedAffiliations(userId, callback) {
UserGetter.getUserFullEmails(userId, function (error, emailsData) {
if (error) {
return callback(error)
}
const confirmedAffiliations = emailsData
.filter(
emailData =>
emailData.confirmedAt &&
emailData.affiliation &&
emailData.affiliation.institution &&
emailData.affiliation.institution.confirmed
)
.map(emailData => emailData.affiliation)
callback(null, confirmedAffiliations)
})
},
getCurrentInstitutionIds: callbackify(getCurrentInstitutionIds),
getManagedInstitutions(userId, callback) {
UserMembershipsHandler.getEntitiesByUser(
UserMembershipEntityConfigs.institution,
userId,
callback
)
},
}
InstitutionsGetter.promises = {
getCurrentInstitutionIds,
}
module.exports = InstitutionsGetter
| overleaf/web/app/src/Features/Institutions/InstitutionsGetter.js/0 | {
"file_path": "overleaf/web/app/src/Features/Institutions/InstitutionsGetter.js",
"repo_id": "overleaf",
"token_count": 747
} | 501 |
const settings = require('@overleaf/settings')
const request = require('request')
const logger = require('logger-sharelatex')
const _ = require('lodash')
const notificationsApi = _.get(settings, ['apis', 'notifications', 'url'])
const oneSecond = 1000
const makeRequest = function (opts, callback) {
if (notificationsApi) {
request(opts, callback)
} else {
callback(null, { statusCode: 200 })
}
}
module.exports = {
getUserNotifications(userId, callback) {
const opts = {
uri: `${notificationsApi}/user/${userId}`,
json: true,
timeout: oneSecond,
method: 'GET',
}
makeRequest(opts, function (err, res, unreadNotifications) {
const statusCode = res ? res.statusCode : 500
if (err || statusCode !== 200) {
logger.err(
{ err, statusCode },
'something went wrong getting notifications'
)
callback(null, [])
} else {
if (unreadNotifications == null) {
unreadNotifications = []
}
callback(null, unreadNotifications)
}
})
},
createNotification(
userId,
key,
templateKey,
messageOpts,
expiryDateTime,
forceCreate,
callback
) {
if (!callback) {
callback = forceCreate
forceCreate = true
}
const payload = {
key,
messageOpts,
templateKey,
forceCreate,
}
if (expiryDateTime) {
payload.expires = expiryDateTime
}
const opts = {
uri: `${notificationsApi}/user/${userId}`,
timeout: oneSecond,
method: 'POST',
json: payload,
}
makeRequest(opts, callback)
},
markAsReadWithKey(userId, key, callback) {
const opts = {
uri: `${notificationsApi}/user/${userId}`,
method: 'DELETE',
timeout: oneSecond,
json: {
key,
},
}
makeRequest(opts, callback)
},
markAsRead(userId, notificationId, callback) {
const opts = {
method: 'DELETE',
uri: `${notificationsApi}/user/${userId}/notification/${notificationId}`,
timeout: oneSecond,
}
makeRequest(opts, callback)
},
// removes notification by key, without regard for user_id,
// should not be exposed to user via ui/router
markAsReadByKeyOnly(key, callback) {
const opts = {
uri: `${notificationsApi}/key/${key}`,
method: 'DELETE',
timeout: oneSecond,
}
makeRequest(opts, callback)
},
}
| overleaf/web/app/src/Features/Notifications/NotificationsHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Notifications/NotificationsHandler.js",
"repo_id": "overleaf",
"token_count": 1035
} | 502 |
const { callbackify } = require('util')
const { callbackifyMultiResult } = require('../../util/promises')
const _ = require('underscore')
const logger = require('logger-sharelatex')
const path = require('path')
const { ObjectId } = require('mongodb')
const Settings = require('@overleaf/settings')
const OError = require('@overleaf/o-error')
const CooldownManager = require('../Cooldown/CooldownManager')
const Errors = require('../Errors/Errors')
const { Folder } = require('../../models/Folder')
const LockManager = require('../../infrastructure/LockManager')
const { Project } = require('../../models/Project')
const ProjectEntityHandler = require('./ProjectEntityHandler')
const ProjectGetter = require('./ProjectGetter')
const ProjectLocator = require('./ProjectLocator')
const FolderStructureBuilder = require('./FolderStructureBuilder')
const SafePath = require('./SafePath')
const { DeletedFile } = require('../../models/DeletedFile')
const LOCK_NAMESPACE = 'mongoTransaction'
const ENTITY_TYPE_TO_MONGO_PATH_SEGMENT = {
doc: 'docs',
docs: 'docs',
file: 'fileRefs',
files: 'fileRefs',
fileRefs: 'fileRefs',
folder: 'folders',
folders: 'folders',
}
module.exports = {
LOCK_NAMESPACE,
addDoc: callbackifyMultiResult(wrapWithLock(addDoc), ['result', 'project']),
addFile: callbackifyMultiResult(wrapWithLock(addFile), ['result', 'project']),
addFolder: callbackifyMultiResult(wrapWithLock(addFolder), [
'folder',
'parentFolderId',
]),
replaceFileWithNew: callbackifyMultiResult(wrapWithLock(replaceFileWithNew), [
'oldFileRef',
'project',
'path',
'newProject',
]),
replaceDocWithFile: callbackify(replaceDocWithFile),
replaceFileWithDoc: callbackify(replaceFileWithDoc),
mkdirp: callbackifyMultiResult(wrapWithLock(mkdirp), [
'newFolders',
'folder',
]),
moveEntity: callbackifyMultiResult(wrapWithLock(moveEntity), [
'project',
'startPath',
'endPath',
'rev',
'changes',
]),
deleteEntity: callbackifyMultiResult(wrapWithLock(deleteEntity), [
'entity',
'path',
'projectBeforeDeletion',
'newProject',
]),
renameEntity: callbackifyMultiResult(wrapWithLock(renameEntity), [
'project',
'startPath',
'endPath',
'rev',
'changes',
]),
createNewFolderStructure: callbackify(wrapWithLock(createNewFolderStructure)),
_insertDeletedFileReference: callbackify(_insertDeletedFileReference),
_putElement: callbackifyMultiResult(_putElement, ['result', 'project']),
_confirmFolder,
promises: {
addDoc: wrapWithLock(addDoc),
addFile: wrapWithLock(addFile),
addFolder: wrapWithLock(addFolder),
replaceFileWithNew: wrapWithLock(replaceFileWithNew),
replaceDocWithFile: wrapWithLock(replaceDocWithFile),
replaceFileWithDoc: wrapWithLock(replaceFileWithDoc),
mkdirp: wrapWithLock(mkdirp),
moveEntity: wrapWithLock(moveEntity),
deleteEntity: wrapWithLock(deleteEntity),
renameEntity: wrapWithLock(renameEntity),
createNewFolderStructure: wrapWithLock(createNewFolderStructure),
_insertDeletedFileReference,
_putElement,
},
}
function wrapWithLock(methodWithoutLock) {
// This lock is used whenever we read or write to an existing project's
// structure. Some operations to project structure cannot be done atomically
// in mongo, this lock is used to prevent reading the structure between two
// parts of a staged update.
async function methodWithLock(projectId, ...rest) {
return LockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
methodWithoutLock(projectId, ...rest)
)
}
return methodWithLock
}
async function addDoc(projectId, folderId, doc) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{
rootFolder: true,
name: true,
overleaf: true,
}
)
folderId = _confirmFolder(project, folderId)
const { result, project: newProject } = await _putElement(
project,
folderId,
doc,
'doc'
)
return { result, project: newProject }
}
async function addFile(projectId, folderId, fileRef) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
folderId = _confirmFolder(project, folderId)
const { result, project: newProject } = await _putElement(
project,
folderId,
fileRef,
'file'
)
return { result, project: newProject }
}
async function addFolder(projectId, parentFolderId, folderName) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
parentFolderId = _confirmFolder(project, parentFolderId)
const folder = new Folder({ name: folderName })
await _putElement(project, parentFolderId, folder, 'folder')
return { folder, parentFolderId }
}
async function replaceFileWithNew(projectId, fileId, newFileRef) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
const { element: fileRef, path } = await ProjectLocator.promises.findElement({
project,
element_id: fileId,
type: 'file',
})
await _insertDeletedFileReference(projectId, fileRef)
const newProject = await Project.findOneAndUpdate(
{ _id: project._id },
{
$set: {
[`${path.mongo}._id`]: newFileRef._id,
[`${path.mongo}.created`]: new Date(),
[`${path.mongo}.linkedFileData`]: newFileRef.linkedFileData,
[`${path.mongo}.hash`]: newFileRef.hash,
},
$inc: {
version: 1,
[`${path.mongo}.rev`]: 1,
},
},
{ new: true }
).exec()
// Note: Mongoose uses new:true to return the modified document
// https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
// but Mongo uses returnNewDocument:true instead
// https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/
// We are using Mongoose here, but if we ever switch to a direct mongo call
// the next line will need to be updated.
return { oldFileRef: fileRef, project, path, newProject }
}
async function replaceDocWithFile(projectId, docId, fileRef) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
const { path } = await ProjectLocator.promises.findElement({
project,
element_id: docId,
type: 'doc',
})
const folderMongoPath = _getParentMongoPath(path.mongo)
const newProject = await Project.findOneAndUpdate(
{ _id: project._id },
{
$pull: {
[`${folderMongoPath}.docs`]: { _id: docId },
},
$push: {
[`${folderMongoPath}.fileRefs`]: fileRef,
},
$inc: { version: 1 },
},
{ new: true }
).exec()
return newProject
}
async function replaceFileWithDoc(projectId, fileId, newDoc) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
const { path } = await ProjectLocator.promises.findElement({
project,
element_id: fileId,
type: 'file',
})
const folderMongoPath = _getParentMongoPath(path.mongo)
const newProject = await Project.findOneAndUpdate(
{ _id: project._id },
{
$pull: {
[`${folderMongoPath}.fileRefs`]: { _id: fileId },
},
$push: {
[`${folderMongoPath}.docs`]: newDoc,
},
$inc: { version: 1 },
},
{ new: true }
).exec()
return newProject
}
async function mkdirp(projectId, path, options = {}) {
// defaults to case insensitive paths, use options {exactCaseMatch:true}
// to make matching case-sensitive
let folders = path.split('/')
folders = _.select(folders, folder => folder.length !== 0)
const project = await ProjectGetter.promises.getProjectWithOnlyFolders(
projectId
)
if (path === '/') {
return { newFolders: [], folder: project.rootFolder[0] }
}
const newFolders = []
let builtUpPath = ''
let lastFolder = null
for (const folderName of folders) {
builtUpPath += `/${folderName}`
try {
const {
element: foundFolder,
} = await ProjectLocator.promises.findElementByPath({
project,
path: builtUpPath,
exactCaseMatch: options.exactCaseMatch,
})
lastFolder = foundFolder
} catch (err) {
// Folder couldn't be found. Create it.
const parentFolderId = lastFolder && lastFolder._id
const {
folder: newFolder,
parentFolderId: newParentFolderId,
} = await addFolder(projectId, parentFolderId, folderName)
newFolder.parentFolder_id = newParentFolderId
lastFolder = newFolder
newFolders.push(newFolder)
}
}
return { folder: lastFolder, newFolders }
}
async function moveEntity(projectId, entityId, destFolderId, entityType) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
const {
element: entity,
path: entityPath,
} = await ProjectLocator.promises.findElement({
project,
element_id: entityId,
type: entityType,
})
// Prevent top-level docs/files with reserved names (to match v1 behaviour)
if (_blockedFilename(entityPath, entityType)) {
throw new Errors.InvalidNameError('blocked element name')
}
await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
const {
docs: oldDocs,
files: oldFiles,
} = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
// For safety, insert the entity in the destination
// location first, and then remove the original. If
// there is an error the entity may appear twice. This
// will cause some breakage but is better than being
// lost, which is what happens if this is done in the
// opposite order.
const { result } = await _putElement(
project,
destFolderId,
entity,
entityType
)
// Note: putElement always pushes onto the end of an
// array so it will never change an existing mongo
// path. Therefore it is safe to remove an element
// from the project with an existing path after
// calling putElement. But we must be sure that we
// have not moved a folder subfolder of itself (which
// is done by _checkValidMove above) because that
// would lead to it being deleted.
const newProject = await _removeElementFromMongoArray(
Project,
projectId,
entityPath.mongo,
entityId
)
const {
docs: newDocs,
files: newFiles,
} = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
const startPath = entityPath.fileSystem
const endPath = result.path.fileSystem
const changes = {
oldDocs,
newDocs,
oldFiles,
newFiles,
newProject,
}
// check that no files have been lost (or duplicated)
if (
oldFiles.length !== newFiles.length ||
oldDocs.length !== newDocs.length
) {
logger.warn(
{
projectId,
oldDocs: oldDocs.length,
newDocs: newDocs.length,
oldFiles: oldFiles.length,
newFiles: newFiles.length,
origProject: project,
newProject,
},
"project corrupted moving files - shouldn't happen"
)
throw new Error('unexpected change in project structure')
}
return { project, startPath, endPath, rev: entity.rev, changes }
}
async function deleteEntity(projectId, entityId, entityType, callback) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ name: true, rootFolder: true, overleaf: true, rootDoc_id: true }
)
const deleteRootDoc =
project.rootDoc_id &&
entityId &&
project.rootDoc_id.toString() === entityId.toString()
const { element: entity, path } = await ProjectLocator.promises.findElement({
project,
element_id: entityId,
type: entityType,
})
const newProject = await _removeElementFromMongoArray(
Project,
projectId,
path.mongo,
entityId,
deleteRootDoc
)
return { entity, path, projectBeforeDeletion: project, newProject }
}
async function renameEntity(
projectId,
entityId,
entityType,
newName,
callback
) {
const project = await ProjectGetter.promises.getProjectWithoutLock(
projectId,
{ rootFolder: true, name: true, overleaf: true }
)
const {
element: entity,
path: entPath,
folder: parentFolder,
} = await ProjectLocator.promises.findElement({
project,
element_id: entityId,
type: entityType,
})
const startPath = entPath.fileSystem
const endPath = path.join(path.dirname(entPath.fileSystem), newName)
// Prevent top-level docs/files with reserved names (to match v1 behaviour)
if (_blockedFilename({ fileSystem: endPath }, entityType)) {
throw new Errors.InvalidNameError('blocked element name')
}
// check if the new name already exists in the current folder
_checkValidElementName(parentFolder, newName)
const {
docs: oldDocs,
files: oldFiles,
} = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
// we need to increment the project version number for any structure change
const newProject = await Project.findOneAndUpdate(
{ _id: projectId },
{ $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
{ new: true }
).exec()
const {
docs: newDocs,
files: newFiles,
} = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
return {
project,
startPath,
endPath,
rev: entity.rev,
changes: { oldDocs, newDocs, oldFiles, newFiles, newProject },
}
}
async function _insertDeletedFileReference(projectId, fileRef) {
await DeletedFile.create({
projectId,
_id: fileRef._id,
name: fileRef.name,
linkedFileData: fileRef.linkedFileData,
hash: fileRef.hash,
deletedAt: new Date(),
})
}
async function _removeElementFromMongoArray(
model,
modelId,
path,
elementId,
deleteRootDoc = false
) {
const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
const options = { new: true }
const query = { _id: modelId }
const update = {
$pull: { [nonArrayPath]: { _id: elementId } },
$inc: { version: 1 },
}
if (deleteRootDoc) {
update.$unset = { rootDoc_id: 1 }
}
return model.findOneAndUpdate(query, update, options).exec()
}
function _countElements(project) {
function countFolder(folder) {
if (folder == null) {
return 0
}
let total = 0
if (folder.folders) {
total += folder.folders.length
for (const subfolder of folder.folders) {
total += countFolder(subfolder)
}
}
if (folder.docs) {
total += folder.docs.length
}
if (folder.fileRefs) {
total += folder.fileRefs.length
}
return total
}
return countFolder(project.rootFolder[0])
}
async function _putElement(project, folderId, element, type) {
if (element == null || element._id == null) {
logger.warn(
{ projectId: project._id, folderId, element, type },
'failed trying to insert element as it was null'
)
throw new Error('no element passed to be inserted')
}
const pathSegment = _getMongoPathSegmentFromType(type)
// original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
// check if name is allowed
if (!SafePath.isCleanFilename(element.name)) {
logger.warn(
{ projectId: project._id, folderId, element, type },
'failed trying to insert element as name was invalid'
)
throw new Errors.InvalidNameError('invalid element name')
}
if (folderId == null) {
folderId = project.rootFolder[0]._id
}
if (_countElements(project) > Settings.maxEntitiesPerProject) {
logger.warn(
{ projectId: project._id },
'project too big, stopping insertions'
)
CooldownManager.putProjectOnCooldown(project._id)
throw new Error('project_has_too_many_files')
}
const { element: folder, path } = await ProjectLocator.promises.findElement({
project,
element_id: folderId,
type: 'folder',
})
const newPath = {
fileSystem: `${path.fileSystem}/${element.name}`,
mongo: path.mongo,
}
// check if the path would be too long
if (!SafePath.isAllowedLength(newPath.fileSystem)) {
throw new Errors.InvalidNameError('path too long')
}
// Prevent top-level docs/files with reserved names (to match v1 behaviour)
if (_blockedFilename(newPath, type)) {
throw new Errors.InvalidNameError('blocked element name')
}
_checkValidElementName(folder, element.name)
element._id = ObjectId(element._id.toString())
const mongoPath = `${path.mongo}.${pathSegment}`
const newProject = await Project.findOneAndUpdate(
{ _id: project._id },
{ $push: { [mongoPath]: element }, $inc: { version: 1 } },
{ new: true }
).exec()
return { result: { path: newPath }, project: newProject }
}
function _blockedFilename(entityPath, entityType) {
// check if name would be blocked in v1
// javascript reserved names are forbidden for docs and files
// at the top-level (but folders with reserved names are allowed).
const isFolder = entityType === 'folder'
const dir = path.dirname(entityPath.fileSystem)
const file = path.basename(entityPath.fileSystem)
const isTopLevel = dir === '/'
if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
return true
} else {
return false
}
}
function _getMongoPathSegmentFromType(type) {
const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
if (pathSegment == null) {
throw new Error(`Unknown entity type: ${type}`)
}
return pathSegment
}
/**
* Check if the name is already taken by a doc, file or folder. If so, return an
* error "file already exists".
*/
function _checkValidElementName(folder, name) {
if (folder == null) {
return
}
const elements = []
.concat(folder.docs || [])
.concat(folder.fileRefs || [])
.concat(folder.folders || [])
for (const element of elements) {
if (element.name === name) {
throw new Errors.InvalidNameError('file already exists')
}
}
}
function _confirmFolder(project, folderId) {
if (folderId == null) {
return project.rootFolder[0]._id
} else {
return folderId
}
}
async function _checkValidMove(
project,
entityType,
entity,
entityPath,
destFolderId
) {
const {
element: destEntity,
path: destFolderPath,
} = await ProjectLocator.promises.findElement({
project,
element_id: destFolderId,
type: 'folder',
})
// check if there is already a doc/file/folder with the same name
// in the destination folder
_checkValidElementName(destEntity, entity.name)
if (/folder/.test(entityType)) {
const isNestedFolder =
destFolderPath.fileSystem.slice(0, entityPath.fileSystem.length) ===
entityPath.fileSystem
if (isNestedFolder) {
throw new Errors.InvalidNameError(
'destination folder is a child folder of me'
)
}
}
}
/**
* Create an initial file tree out of a list of doc and file entries
*
* Each entry specifies a path to the doc or file. Folders are automatically
* created.
*
* @param {ObjectId} projectId - id of the project
* @param {DocEntry[]} docEntries - list of docs to add
* @param {FileEntry[]} fileEntries - list of files to add
* @return {Promise<string>} the project version after the operation
*/
async function createNewFolderStructure(projectId, docEntries, fileEntries) {
try {
const rootFolder = FolderStructureBuilder.buildFolderStructure(
docEntries,
fileEntries
)
const project = await Project.findOneAndUpdate(
{
_id: projectId,
'rootFolder.0.folders.0': { $exists: false },
'rootFolder.0.docs.0': { $exists: false },
'rootFolder.0.files.0': { $exists: false },
},
{
$set: { rootFolder: [rootFolder] },
$inc: { version: 1 },
},
{
new: true,
lean: true,
fields: { version: 1 },
}
).exec()
if (project == null) {
throw new OError('project not found or folder structure already exists', {
projectId,
})
}
return project.version
} catch (err) {
throw OError.tag(err, 'failed to create folder structure', { projectId })
}
}
/**
* Given a Mongo path to an entity, return the Mongo path to the parent folder
*/
function _getParentMongoPath(mongoPath) {
const segments = mongoPath.split('.')
if (segments.length <= 2) {
throw new Error('Root folder has no parents')
}
return segments.slice(0, -2).join('.')
}
| overleaf/web/app/src/Features/Project/ProjectEntityMongoUpdateHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectEntityMongoUpdateHandler.js",
"repo_id": "overleaf",
"token_count": 7305
} | 503 |
/* eslint-disable
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ReferencesController
const logger = require('logger-sharelatex')
const ReferencesHandler = require('./ReferencesHandler')
const settings = require('@overleaf/settings')
const EditorRealTimeController = require('../Editor/EditorRealTimeController')
module.exports = ReferencesController = {
index(req, res) {
const projectId = req.params.Project_id
const { shouldBroadcast } = req.body
const { docIds } = req.body
if (!docIds || !(docIds instanceof Array)) {
logger.err(
{ projectId, docIds },
"docIds is not valid, should be either Array or String 'ALL'"
)
return res.sendStatus(400)
}
return ReferencesHandler.index(projectId, docIds, function (err, data) {
if (err != null) {
logger.err({ err, projectId }, 'error indexing all references')
return res.sendStatus(500)
}
return ReferencesController._handleIndexResponse(
req,
res,
projectId,
shouldBroadcast,
data
)
})
},
indexAll(req, res) {
const projectId = req.params.Project_id
const { shouldBroadcast } = req.body
return ReferencesHandler.indexAll(projectId, function (err, data) {
if (err != null) {
logger.err({ err, projectId }, 'error indexing all references')
return res.sendStatus(500)
}
return ReferencesController._handleIndexResponse(
req,
res,
projectId,
shouldBroadcast,
data
)
})
},
_handleIndexResponse(req, res, projectId, shouldBroadcast, data) {
if (data == null || data.keys == null) {
return res.json({ projectId, keys: [] })
}
if (shouldBroadcast) {
EditorRealTimeController.emitToRoom(
projectId,
'references:keys:updated',
data.keys
)
}
return res.json(data)
},
}
| overleaf/web/app/src/Features/References/ReferencesController.js/0 | {
"file_path": "overleaf/web/app/src/Features/References/ReferencesController.js",
"repo_id": "overleaf",
"token_count": 861
} | 504 |
/* eslint-disable
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let UniversityController
const settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const Settings = require('@overleaf/settings')
module.exports = UniversityController = {
getPage(req, res, next) {
const url =
req.url != null ? req.url.toLowerCase().replace('.html', '') : undefined
return res.redirect(`/i${url}`)
},
getIndexPage(req, res) {
return res.redirect('/i/university')
},
}
| overleaf/web/app/src/Features/StaticPages/UniversityController.js/0 | {
"file_path": "overleaf/web/app/src/Features/StaticPages/UniversityController.js",
"repo_id": "overleaf",
"token_count": 263
} | 505 |
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const AuthenticationController = require('../Authentication/AuthenticationController')
const SubscriptionController = require('./SubscriptionController')
const SubscriptionGroupController = require('./SubscriptionGroupController')
const TeamInvitesController = require('./TeamInvitesController')
const RateLimiterMiddleware = require('../Security/RateLimiterMiddleware')
const Settings = require('@overleaf/settings')
module.exports = {
apply(webRouter, privateApiRouter, publicApiRouter) {
if (!Settings.enableSubscriptions) {
return
}
webRouter.get('/user/subscription/plans', SubscriptionController.plansPage)
webRouter.get(
'/user/subscription',
AuthenticationController.requireLogin(),
SubscriptionController.userSubscriptionPage
)
webRouter.get(
'/user/subscription/new',
AuthenticationController.requireLogin(),
SubscriptionController.paymentPage
)
webRouter.get(
'/user/subscription/thank-you',
AuthenticationController.requireLogin(),
SubscriptionController.successfulSubscription
)
webRouter.get(
'/user/subscription/canceled',
AuthenticationController.requireLogin(),
SubscriptionController.canceledSubscription
)
webRouter.delete(
'/subscription/group/user',
AuthenticationController.requireLogin(),
SubscriptionGroupController.removeSelfFromGroup
)
// Team invites
webRouter.get(
'/subscription/invites/:token/',
AuthenticationController.requireLogin(),
TeamInvitesController.viewInvite
)
webRouter.put(
'/subscription/invites/:token/',
AuthenticationController.requireLogin(),
RateLimiterMiddleware.rateLimit({
endpointName: 'team-invite',
maxRequests: 10,
timeInterval: 60,
}),
TeamInvitesController.acceptInvite
)
// recurly callback
publicApiRouter.post(
'/user/subscription/callback',
AuthenticationController.requireBasicAuth({
[Settings.apis.recurly.webhookUser]: Settings.apis.recurly.webhookPass,
}),
SubscriptionController.recurlyNotificationParser,
SubscriptionController.recurlyCallback
)
// user changes their account state
webRouter.post(
'/user/subscription/create',
AuthenticationController.requireLogin(),
SubscriptionController.createSubscription
)
webRouter.post(
'/user/subscription/update',
AuthenticationController.requireLogin(),
SubscriptionController.updateSubscription
)
webRouter.post(
'/user/subscription/cancel-pending',
AuthenticationController.requireLogin(),
SubscriptionController.cancelPendingSubscriptionChange
)
webRouter.post(
'/user/subscription/cancel',
AuthenticationController.requireLogin(),
SubscriptionController.cancelSubscription
)
webRouter.post(
'/user/subscription/reactivate',
AuthenticationController.requireLogin(),
SubscriptionController.reactivateSubscription
)
webRouter.post(
'/user/subscription/v1/cancel',
AuthenticationController.requireLogin(),
SubscriptionController.cancelV1Subscription
)
webRouter.put(
'/user/subscription/extend',
AuthenticationController.requireLogin(),
SubscriptionController.extendTrial
)
webRouter.get(
'/user/subscription/upgrade-annual',
AuthenticationController.requireLogin(),
SubscriptionController.renderUpgradeToAnnualPlanPage
)
webRouter.post(
'/user/subscription/upgrade-annual',
AuthenticationController.requireLogin(),
SubscriptionController.processUpgradeToAnnualPlan
)
webRouter.post(
'/user/subscription/account/email',
AuthenticationController.requireLogin(),
SubscriptionController.updateAccountEmailAddress
)
// Currently used in acceptance tests only, as a way to trigger the syncing logic
return publicApiRouter.post(
'/user/:user_id/features/sync',
AuthenticationController.requirePrivateApiAuth(),
SubscriptionController.refreshUserFeatures
)
},
}
| overleaf/web/app/src/Features/Subscription/SubscriptionRouter.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionRouter.js",
"repo_id": "overleaf",
"token_count": 1548
} | 506 |
let parseParams
const TpdsUpdateHandler = require('./TpdsUpdateHandler')
const UpdateMerger = require('./UpdateMerger')
const Errors = require('../Errors/Errors')
const logger = require('logger-sharelatex')
const Path = require('path')
const metrics = require('@overleaf/metrics')
const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
const SessionManager = require('../Authentication/SessionManager')
const TpdsQueueManager = require('./TpdsQueueManager').promises
module.exports = {
// mergeUpdate and deleteUpdate are used by Dropbox, where the project is only passed as the name, as the
// first part of the file path. They have to check the project exists, find it, and create it if not.
// They also ignore 'noisy' files like .DS_Store, .gitignore, etc.
mergeUpdate(req, res) {
metrics.inc('tpds.merge-update')
const { filePath, userId, projectName } = parseParams(req)
const source = req.headers['x-sl-update-source'] || 'unknown'
TpdsUpdateHandler.newUpdate(
userId,
projectName,
filePath,
req,
source,
err => {
if (err) {
if (err.name === 'TooManyRequestsError') {
logger.warn(
{ err, userId, filePath },
'tpds update failed to be processed, too many requests'
)
res.sendStatus(429)
} else if (err.message === 'project_has_too_many_files') {
logger.warn(
{ err, userId, filePath },
'tpds trying to append to project over file limit'
)
NotificationsBuilder.tpdsFileLimit(userId).create(projectName)
res.sendStatus(400)
} else {
logger.err(
{ err, userId, filePath },
'error receiving update from tpds'
)
res.sendStatus(500)
}
} else {
res.sendStatus(200)
}
}
)
},
deleteUpdate(req, res) {
metrics.inc('tpds.delete-update')
const { filePath, userId, projectName } = parseParams(req)
const source = req.headers['x-sl-update-source'] || 'unknown'
TpdsUpdateHandler.deleteUpdate(
userId,
projectName,
filePath,
source,
err => {
if (err) {
logger.err(
{ err, userId, filePath },
'error receiving update from tpds'
)
res.sendStatus(500)
} else {
res.sendStatus(200)
}
}
)
},
// updateProjectContents and deleteProjectContents are used by GitHub. The project_id is known so we
// can skip right ahead to creating/updating/deleting the file. These methods will not ignore noisy
// files like .DS_Store, .gitignore, etc because people are generally more explicit with the files they
// want in git.
updateProjectContents(req, res, next) {
const projectId = req.params.project_id
const path = `/${req.params[0]}` // UpdateMerger expects leading slash
const source = req.headers['x-sl-update-source'] || 'unknown'
UpdateMerger.mergeUpdate(null, projectId, path, req, source, error => {
if (error) {
if (error.constructor === Errors.InvalidNameError) {
return res.sendStatus(422)
} else {
return next(error)
}
}
res.sendStatus(200)
})
},
deleteProjectContents(req, res, next) {
const projectId = req.params.project_id
const path = `/${req.params[0]}` // UpdateMerger expects leading slash
const source = req.headers['x-sl-update-source'] || 'unknown'
UpdateMerger.deleteUpdate(null, projectId, path, source, error => {
if (error) {
return next(error)
}
res.sendStatus(200)
})
},
async getQueues(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
try {
res.json(await TpdsQueueManager.getQueues(userId))
} catch (err) {
next(err)
}
},
parseParams: (parseParams = function (req) {
let filePath, projectName
let path = req.params[0]
const userId = req.params.user_id
path = Path.join('/', path)
if (path.substring(1).indexOf('/') === -1) {
filePath = '/'
projectName = path.substring(1)
} else {
filePath = path.substring(path.indexOf('/', 1))
projectName = path.substring(0, path.indexOf('/', 1))
projectName = projectName.replace('/', '')
}
return { filePath, userId, projectName }
}),
}
| overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsController.js/0 | {
"file_path": "overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsController.js",
"repo_id": "overleaf",
"token_count": 1848
} | 507 |
const { ObjectId } = require('mongodb')
const EmailHandler = require('../Email/EmailHandler')
const Errors = require('../Errors/Errors')
const InstitutionsAPI = require('../Institutions/InstitutionsAPI')
const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
const OError = require('@overleaf/o-error')
const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
const UserAuditLogHandler = require('../User/UserAuditLogHandler')
const UserGetter = require('../User/UserGetter')
const UserUpdater = require('../User/UserUpdater')
const logger = require('logger-sharelatex')
const { User } = require('../../models/User')
async function _addAuditLogEntry(
link,
userId,
auditLog,
institutionEmail,
providerId,
providerName
) {
const operation = link ? 'link-institution-sso' : 'unlink-institution-sso'
await UserAuditLogHandler.promises.addEntry(
userId,
operation,
auditLog.initiatorId,
auditLog.ipAddress,
{
institutionEmail,
providerId,
providerName,
}
)
}
async function _ensureCanAddIdentifier(userId, institutionEmail, providerId) {
const userWithProvider = await UserGetter.promises.getUser(
{ _id: ObjectId(userId), 'samlIdentifiers.providerId': providerId },
{ _id: 1 }
)
if (userWithProvider) {
throw new Errors.SAMLAlreadyLinkedError()
}
const userWithEmail = await UserGetter.promises.getUserByAnyEmail(
institutionEmail
)
if (!userWithEmail) {
// email doesn't exist; all good
return
}
const emailBelongToUser = userWithEmail._id.toString() === userId.toString()
const existingEmailData = userWithEmail.emails.find(
emailData => emailData.email === institutionEmail
)
if (!emailBelongToUser && existingEmailData.samlProviderId) {
// email exists and institution link.
// Return back to requesting page with error
throw new Errors.SAMLIdentityExistsError()
}
if (!emailBelongToUser) {
// email exists but not linked, so redirect to linking page
// which will tell this user to log out to link
throw new Errors.EmailExistsError()
}
// email belongs to user. Make sure it's already affiliated with the provider
const fullEmails = await UserGetter.promises.getUserFullEmails(
userWithEmail._id
)
const existingFullEmailData = fullEmails.find(
emailData => emailData.email === institutionEmail
)
if (!existingFullEmailData.affiliation) {
throw new Errors.SAMLEmailNotAffiliatedError()
}
if (
existingFullEmailData.affiliation.institution.id.toString() !== providerId
) {
throw new Errors.SAMLEmailAffiliatedWithAnotherInstitutionError()
}
}
async function _addIdentifier(
userId,
externalUserId,
providerId,
hasEntitlement,
institutionEmail,
providerName,
auditLog
) {
providerId = providerId.toString()
await _ensureCanAddIdentifier(userId, institutionEmail, providerId)
await _addAuditLogEntry(
true,
userId,
auditLog,
institutionEmail,
providerId,
providerName
)
hasEntitlement = !!hasEntitlement
const query = {
_id: userId,
'samlIdentifiers.providerId': {
$ne: providerId,
},
}
const update = {
$push: {
samlIdentifiers: {
hasEntitlement,
externalUserId,
providerId,
},
},
}
try {
// update v2 user record
const updatedUser = await User.findOneAndUpdate(query, update, {
new: true,
}).exec()
if (!updatedUser) {
throw new OError('No update while linking user')
}
return updatedUser
} catch (err) {
if (err.code === 11000) {
throw new Errors.SAMLIdentityExistsError()
} else {
throw OError.tag(err)
}
}
}
async function _addInstitutionEmail(userId, email, providerId, auditLog) {
const user = await UserGetter.promises.getUser(userId)
const query = {
_id: userId,
'emails.email': email,
}
const update = {
$set: {
'emails.$.samlProviderId': providerId.toString(),
},
}
if (user == null) {
throw new Errors.NotFoundError('user not found')
}
const emailAlreadyAssociated = user.emails.find(e => e.email === email)
if (emailAlreadyAssociated && emailAlreadyAssociated.confirmedAt) {
await UserUpdater.promises.updateUser(query, update)
} else if (emailAlreadyAssociated) {
await UserUpdater.promises.updateUser(query, update)
} else {
await UserUpdater.promises.addEmailAddress(
user._id,
email,
{ university: { id: providerId }, rejectIfBlocklisted: true },
auditLog
)
await UserUpdater.promises.updateUser(query, update)
}
}
async function _sendLinkedEmail(userId, providerName, institutionEmail) {
const user = await UserGetter.promises.getUser(userId, { email: 1 })
const emailOptions = {
to: user.email,
actionDescribed: `an Institutional SSO account at ${providerName} was linked to your account ${user.email}`,
action: 'institutional SSO account linked',
message: [
`<span style="display:inline-block;padding: 0 20px;width:100%;">Linked: <br/><b>${institutionEmail}</b></span>`,
],
}
EmailHandler.sendEmail('securityAlert', emailOptions, error => {
if (error) {
logger.warn({ err: error })
}
})
}
function _sendUnlinkedEmail(primaryEmail, providerName, institutionEmail) {
const emailOptions = {
to: primaryEmail,
actionDescribed: `an Institutional SSO account at ${providerName} was unlinked from your account ${primaryEmail}`,
action: 'institutional SSO account no longer linked',
message: [
`<span style="display:inline-block;padding: 0 20px;width:100%;">No longer linked: <br/><b>${institutionEmail}</b></span>`,
],
}
EmailHandler.sendEmail('securityAlert', emailOptions, error => {
if (error) {
logger.warn({ err: error })
}
})
}
async function getUser(providerId, externalUserId) {
if (!providerId || !externalUserId) {
throw new Error(
`invalid arguments: providerId: ${providerId}, externalUserId: ${externalUserId}`
)
}
const user = await User.findOne({
'samlIdentifiers.externalUserId': externalUserId.toString(),
'samlIdentifiers.providerId': providerId.toString(),
}).exec()
return user
}
async function redundantSubscription(userId, providerId, providerName) {
const subscription = await SubscriptionLocator.promises.getUserIndividualSubscription(
userId
)
if (subscription) {
await NotificationsBuilder.promises
.redundantPersonalSubscription(
{
institutionId: providerId,
institutionName: providerName,
},
{ _id: userId }
)
.create()
}
}
async function linkAccounts(
userId,
externalUserId,
institutionEmail,
providerId,
providerName,
hasEntitlement,
auditLog
) {
await _addIdentifier(
userId,
externalUserId,
providerId,
hasEntitlement,
institutionEmail,
providerName,
auditLog
)
try {
await _addInstitutionEmail(userId, institutionEmail, providerId, auditLog)
} catch (error) {
await _removeIdentifier(userId, providerId)
throw error
}
await UserUpdater.promises.confirmEmail(userId, institutionEmail) // will set confirmedAt if not set, and will always update reconfirmedAt
await _sendLinkedEmail(userId, providerName, institutionEmail)
// update v1 affiliations record
if (hasEntitlement) {
await InstitutionsAPI.promises.addEntitlement(userId, institutionEmail)
try {
await redundantSubscription(userId, providerId, providerName)
} catch (error) {
logger.err({ err: error }, 'error checking redundant subscription')
}
} else {
await InstitutionsAPI.promises.removeEntitlement(userId, institutionEmail)
}
}
async function unlinkAccounts(
userId,
institutionEmail,
primaryEmail,
providerId,
providerName,
auditLog
) {
providerId = providerId.toString()
await _addAuditLogEntry(
false,
userId,
auditLog,
institutionEmail,
providerId,
providerName
)
// update v2 user
await _removeIdentifier(userId, providerId)
// update v1 affiliations record
await InstitutionsAPI.promises.removeEntitlement(userId, institutionEmail)
// send email
_sendUnlinkedEmail(primaryEmail, providerName, institutionEmail)
}
async function _removeIdentifier(userId, providerId) {
providerId = providerId.toString()
const query = {
_id: userId,
}
const update = {
$pull: {
samlIdentifiers: {
providerId,
},
},
}
await User.updateOne(query, update).exec()
}
async function updateEntitlement(
userId,
institutionEmail,
providerId,
hasEntitlement
) {
providerId = providerId.toString()
hasEntitlement = !!hasEntitlement
const query = {
_id: userId,
'samlIdentifiers.providerId': providerId.toString(),
}
const update = {
$set: {
'samlIdentifiers.$.hasEntitlement': hasEntitlement,
},
}
// update v2 user
await User.updateOne(query, update).exec()
// update v1 affiliations record
if (hasEntitlement) {
await InstitutionsAPI.promises.addEntitlement(userId, institutionEmail)
} else {
await InstitutionsAPI.promises.removeEntitlement(userId, institutionEmail)
}
}
function entitlementAttributeMatches(entitlementAttribute, entitlementMatcher) {
if (Array.isArray(entitlementAttribute)) {
entitlementAttribute = entitlementAttribute.join(' ')
}
if (
typeof entitlementAttribute !== 'string' ||
typeof entitlementMatcher !== 'string'
) {
return false
}
try {
const entitlementRegExp = new RegExp(entitlementMatcher)
return !!entitlementAttribute.match(entitlementRegExp)
} catch (err) {
logger.error({ err }, 'Invalid SAML entitlement matcher')
// this is likely caused by an invalid regex in the matcher string
// log the error but do not bubble so that user can still sign in
// even if they don't have the entitlement
return false
}
}
function userHasEntitlement(user, providerId) {
providerId = providerId.toString()
if (!user || !Array.isArray(user.samlIdentifiers)) {
return false
}
for (const samlIdentifier of user.samlIdentifiers) {
if (providerId && samlIdentifier.providerId !== providerId) {
continue
}
if (samlIdentifier.hasEntitlement) {
return true
}
}
return false
}
const SAMLIdentityManager = {
entitlementAttributeMatches,
getUser,
linkAccounts,
redundantSubscription,
unlinkAccounts,
updateEntitlement,
userHasEntitlement,
}
module.exports = SAMLIdentityManager
| overleaf/web/app/src/Features/User/SAMLIdentityManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/SAMLIdentityManager.js",
"repo_id": "overleaf",
"token_count": 3694
} | 508 |
const OError = require('@overleaf/o-error')
const Settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const Async = require('async')
const _ = require('underscore')
const { promisify } = require('util')
const UserSessionsRedis = require('./UserSessionsRedis')
const rclient = UserSessionsRedis.client()
const UserSessionsManager = {
// mimic the key used by the express sessions
_sessionKey(sessionId) {
return `sess:${sessionId}`
},
trackSession(user, sessionId, callback) {
if (!user) {
return callback(null)
}
if (!sessionId) {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
const value = UserSessionsManager._sessionKey(sessionId)
rclient
.multi()
.sadd(sessionSetKey, value)
.pexpire(sessionSetKey, `${Settings.cookieSessionLength}`) // in milliseconds
.exec(function (err, response) {
if (err) {
OError.tag(
err,
'error while adding session key to UserSessions set',
{
user_id: user._id,
sessionSetKey,
}
)
return callback(err)
}
UserSessionsManager._checkSessions(user, function () {})
callback()
})
},
untrackSession(user, sessionId, callback) {
if (!callback) {
callback = function () {}
}
if (!user) {
return callback(null)
}
if (!sessionId) {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
const value = UserSessionsManager._sessionKey(sessionId)
rclient
.multi()
.srem(sessionSetKey, value)
.pexpire(sessionSetKey, `${Settings.cookieSessionLength}`) // in milliseconds
.exec(function (err, response) {
if (err) {
OError.tag(
err,
'error while removing session key from UserSessions set',
{
user_id: user._id,
sessionSetKey,
}
)
return callback(err)
}
UserSessionsManager._checkSessions(user, function () {})
callback()
})
},
getAllUserSessions(user, exclude, callback) {
exclude = _.map(exclude, UserSessionsManager._sessionKey)
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
rclient.smembers(sessionSetKey, function (err, sessionKeys) {
if (err) {
OError.tag(err, 'error getting all session keys for user from redis', {
user_id: user._id,
})
return callback(err)
}
sessionKeys = _.filter(sessionKeys, k => !_.contains(exclude, k))
if (sessionKeys.length === 0) {
logger.log({ user_id: user._id }, 'no other sessions found, returning')
return callback(null, [])
}
Async.mapSeries(
sessionKeys,
(k, cb) => rclient.get(k, cb),
function (err, sessions) {
if (err) {
OError.tag(err, 'error getting all sessions for user from redis', {
user_id: user._id,
})
return callback(err)
}
const result = []
for (let session of Array.from(sessions)) {
if (!session) {
continue
}
session = JSON.parse(session)
let sessionUser = session.passport && session.passport.user
if (!sessionUser) {
sessionUser = session.user
}
result.push({
ip_address: sessionUser.ip_address,
session_created: sessionUser.session_created,
})
}
callback(null, result)
}
)
})
},
revokeAllUserSessions(user, retain, callback) {
if (!retain) {
retain = []
}
retain = retain.map(i => UserSessionsManager._sessionKey(i))
if (!user) {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
rclient.smembers(sessionSetKey, function (err, sessionKeys) {
if (err) {
OError.tag(err, 'error getting contents of UserSessions set', {
user_id: user._id,
sessionSetKey,
})
return callback(err)
}
const keysToDelete = _.filter(
sessionKeys,
k => !Array.from(retain).includes(k)
)
if (keysToDelete.length === 0) {
logger.log(
{ user_id: user._id },
'no sessions in UserSessions set to delete, returning'
)
return callback(null)
}
logger.log(
{ user_id: user._id, count: keysToDelete.length },
'deleting sessions for user'
)
const deletions = keysToDelete.map(k => cb => rclient.del(k, cb))
Async.series(deletions, function (err, _result) {
if (err) {
OError.tag(err, 'error revoking all sessions for user', {
user_id: user._id,
sessionSetKey,
})
return callback(err)
}
rclient.srem(sessionSetKey, keysToDelete, function (err) {
if (err) {
OError.tag(err, 'error removing session set for user', {
user_id: user._id,
sessionSetKey,
})
return callback(err)
}
callback(null)
})
})
})
},
touch(user, callback) {
if (!user) {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
rclient.pexpire(
sessionSetKey,
`${Settings.cookieSessionLength}`, // in milliseconds
function (err, response) {
if (err) {
OError.tag(err, 'error while updating ttl on UserSessions set', {
user_id: user._id,
})
return callback(err)
}
callback(null)
}
)
},
_checkSessions(user, callback) {
if (!user) {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
rclient.smembers(sessionSetKey, function (err, sessionKeys) {
if (err) {
OError.tag(err, 'error getting contents of UserSessions set', {
user_id: user._id,
sessionSetKey,
})
return callback(err)
}
Async.series(
sessionKeys.map(key => next =>
rclient.get(key, function (err, val) {
if (err) {
return next(err)
}
if (!val) {
rclient.srem(sessionSetKey, key, function (err, result) {
return next(err)
})
} else {
next()
}
})
),
function (err, results) {
callback(err)
}
)
})
},
}
UserSessionsManager.promises = {
getAllUserSessions: promisify(UserSessionsManager.getAllUserSessions),
revokeAllUserSessions: promisify(UserSessionsManager.revokeAllUserSessions),
}
module.exports = UserSessionsManager
| overleaf/web/app/src/Features/User/UserSessionsManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserSessionsManager.js",
"repo_id": "overleaf",
"token_count": 3273
} | 509 |
const logger = require('logger-sharelatex')
const Settings = require('@overleaf/settings')
const querystring = require('querystring')
const _ = require('lodash')
const Url = require('url')
const Path = require('path')
const moment = require('moment')
const pug = require('pug-runtime')
const IS_DEV_ENV = ['development', 'test'].includes(process.env.NODE_ENV)
const Features = require('./Features')
const SessionManager = require('../Features/Authentication/SessionManager')
const PackageVersions = require('./PackageVersions')
const Modules = require('./Modules')
const SafeHTMLSubstitute = require('../Features/Helpers/SafeHTMLSubstitution')
let webpackManifest
if (!IS_DEV_ENV) {
// Only load webpack manifest file in production. In dev, the web and webpack
// containers can't coordinate, so there no guarantee that the manifest file
// exists when the web server boots. We therefore ignore the manifest file in
// dev reload
webpackManifest = require(`../../../public/manifest.json`)
}
const I18N_HTML_INJECTIONS = new Set()
module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
webRouter.use(function (req, res, next) {
res.locals.session = req.session
next()
})
function addSetContentDisposition(req, res, next) {
res.setContentDisposition = function (type, opts) {
const directives = _.map(
opts,
(v, k) => `${k}="${encodeURIComponent(v)}"`
)
const contentDispositionValue = `${type}; ${directives.join('; ')}`
res.setHeader('Content-Disposition', contentDispositionValue)
}
next()
}
webRouter.use(addSetContentDisposition)
privateApiRouter.use(addSetContentDisposition)
publicApiRouter.use(addSetContentDisposition)
webRouter.use(function (req, res, next) {
req.externalAuthenticationSystemUsed =
Features.externalAuthenticationSystemUsed
res.locals.externalAuthenticationSystemUsed =
Features.externalAuthenticationSystemUsed
req.hasFeature = res.locals.hasFeature = Features.hasFeature
next()
})
webRouter.use(function (req, res, next) {
let staticFilesBase
const cdnAvailable =
Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
const cdnBlocked = req.query.nocdn === 'true' || req.session.cdnBlocked
const userId = SessionManager.getLoggedInUserId(req.session)
if (cdnBlocked && req.session.cdnBlocked == null) {
logger.log(
{ user_id: userId, ip: req != null ? req.ip : undefined },
'cdnBlocked for user, not using it and turning it off for future requets'
)
req.session.cdnBlocked = true
}
const host = req.headers && req.headers.host
const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
if (cdnAvailable && !isSmoke && !cdnBlocked) {
staticFilesBase = Settings.cdn.web.host
} else {
staticFilesBase = ''
}
res.locals.buildBaseAssetPath = function () {
// Return the base asset path (including the CDN url) so that webpack can
// use this to dynamically fetch scripts (e.g. PDFjs worker)
return Url.resolve(staticFilesBase, '/')
}
res.locals.buildJsPath = function (jsFile) {
let path
if (IS_DEV_ENV) {
// In dev: resolve path within JS asset directory
// We are *not* guaranteed to have a manifest file when the server
// starts up
path = Path.join('/js', jsFile)
} else {
// In production: resolve path from webpack manifest file
// We are guaranteed to have a manifest file since webpack compiles in
// the build
path = `/${webpackManifest[jsFile]}`
}
return Url.resolve(staticFilesBase, path)
}
// Temporary hack while jQuery/Angular dependencies are *not* bundled,
// instead copied into output directory
res.locals.buildCopiedJsAssetPath = function (jsFile) {
let path
if (IS_DEV_ENV) {
// In dev: resolve path to root directory
// We are *not* guaranteed to have a manifest file when the server
// starts up
path = Path.join('/', jsFile)
} else {
// In production: resolve path from webpack manifest file
// We are guaranteed to have a manifest file since webpack compiles in
// the build
path = `/${webpackManifest[jsFile]}`
}
return Url.resolve(staticFilesBase, path)
}
res.locals.mathJaxPath = `/js/libs/mathjax/MathJax.js?${querystring.stringify(
{
config: 'TeX-AMS_HTML,Safe',
v: require('mathjax/package.json').version,
}
)}`
res.locals.lib = PackageVersions.lib
res.locals.moment = moment
const IEEE_BRAND_ID = 15
res.locals.isIEEE = brandVariation =>
(brandVariation != null ? brandVariation.brand_id : undefined) ===
IEEE_BRAND_ID
res.locals.getCssThemeModifier = function (userSettings, brandVariation) {
// Themes only exist in OL v2
if (Settings.overleaf != null) {
// The IEEE theme takes precedence over the user personal setting, i.e. a user with
// a theme setting of "light" will still get the IEE theme in IEEE branded projects.
if (res.locals.isIEEE(brandVariation)) {
return 'ieee-'
} else if (userSettings && userSettings.overallTheme != null) {
return userSettings.overallTheme
}
}
}
res.locals.buildStylesheetPath = function (cssFileName) {
let path
if (IS_DEV_ENV) {
// In dev: resolve path within CSS asset directory
// We are *not* guaranteed to have a manifest file when the server
// starts up
path = Path.join('/stylesheets/', cssFileName)
} else {
// In production: resolve path from webpack manifest file
// We are guaranteed to have a manifest file since webpack compiles in
// the build
path = `/${webpackManifest[cssFileName]}`
}
return Url.resolve(staticFilesBase, path)
}
res.locals.buildCssPath = function (themeModifier = '') {
return res.locals.buildStylesheetPath(`${themeModifier}style.css`)
}
res.locals.buildImgPath = function (imgFile) {
const path = Path.join('/img/', imgFile)
return Url.resolve(staticFilesBase, path)
}
next()
})
webRouter.use(function (req, res, next) {
res.locals.translate = function (key, vars, components) {
vars = vars || {}
if (Settings.i18n.checkForHTMLInVars) {
Object.entries(vars).forEach(([field, value]) => {
if (pug.escape(value) !== value) {
const violationsKey = key + field
// do not flood the logs, log one sample per pod + key + field
if (!I18N_HTML_INJECTIONS.has(violationsKey)) {
logger.warn(
{ key, field, value },
'html content in translations context vars'
)
I18N_HTML_INJECTIONS.add(violationsKey)
}
}
})
}
vars.appName = Settings.appName
const locale = req.i18n.translate(key, vars)
if (components) {
return SafeHTMLSubstitute.render(locale, components)
} else {
return locale
}
}
// Don't include the query string parameters, otherwise Google
// treats ?nocdn=true as the canonical version
const parsedOriginalUrl = Url.parse(req.originalUrl)
res.locals.currentUrl = parsedOriginalUrl.pathname
res.locals.currentUrlWithQueryParams = parsedOriginalUrl.path
res.locals.capitalize = function (string) {
if (string.length === 0) {
return ''
}
return string.charAt(0).toUpperCase() + string.slice(1)
}
next()
})
webRouter.use(function (req, res, next) {
res.locals.getUserEmail = function () {
const user = SessionManager.getSessionUser(req.session)
const email = (user != null ? user.email : undefined) || ''
return email
}
next()
})
webRouter.use(function (req, res, next) {
res.locals.StringHelper = require('../Features/Helpers/StringHelper')
next()
})
webRouter.use(function (req, res, next) {
res.locals.buildReferalUrl = function (referalMedium) {
let url = Settings.siteUrl
const currentUser = SessionManager.getSessionUser(req.session)
if (
currentUser != null &&
(currentUser != null ? currentUser.referal_id : undefined) != null
) {
url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
}
return url
}
res.locals.getReferalId = function () {
const currentUser = SessionManager.getSessionUser(req.session)
if (
currentUser != null &&
(currentUser != null ? currentUser.referal_id : undefined) != null
) {
return currentUser.referal_id
}
}
next()
})
webRouter.use(function (req, res, next) {
res.locals.csrfToken = req != null ? req.csrfToken() : undefined
next()
})
webRouter.use(function (req, res, next) {
res.locals.gaToken =
Settings.analytics && Settings.analytics.ga && Settings.analytics.ga.token
res.locals.gaOptimizeId = _.get(Settings, ['analytics', 'gaOptimize', 'id'])
next()
})
webRouter.use(function (req, res, next) {
res.locals.getReqQueryParam = field =>
req.query != null ? req.query[field] : undefined
next()
})
webRouter.use(function (req, res, next) {
const currentUser = SessionManager.getSessionUser(req.session)
if (currentUser != null) {
res.locals.user = {
email: currentUser.email,
first_name: currentUser.first_name,
last_name: currentUser.last_name,
}
}
next()
})
webRouter.use(function (req, res, next) {
res.locals.getLoggedInUserId = () =>
SessionManager.getLoggedInUserId(req.session)
res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
next()
})
webRouter.use(function (req, res, next) {
// Clone the nav settings so they can be modified for each request
res.locals.nav = {}
for (const key in Settings.nav) {
res.locals.nav[key] = _.clone(Settings.nav[key])
}
res.locals.templates = Settings.templateLinks
next()
})
webRouter.use(function (req, res, next) {
if (Settings.reloadModuleViewsOnEachRequest) {
Modules.loadViewIncludes()
}
res.locals.moduleIncludes = Modules.moduleIncludes
res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
next()
})
webRouter.use(function (req, res, next) {
// TODO
if (Settings.overleaf != null) {
res.locals.overallThemes = [
{
name: 'Default',
val: '',
path: res.locals.buildCssPath(),
},
{
name: 'Light',
val: 'light-',
path: res.locals.buildCssPath('light-'),
},
]
}
next()
})
webRouter.use(function (req, res, next) {
res.locals.settings = Settings
next()
})
webRouter.use(function (req, res, next) {
res.locals.ExposedSettings = {
isOverleaf: Settings.overleaf != null,
appName: Settings.appName,
hasSamlBeta: req.session.samlBeta,
hasSamlFeature: Features.hasFeature('saml'),
samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
hasLinkUrlFeature: Features.hasFeature('link-url'),
hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
hasLinkedProjectOutputFileFeature: Features.hasFeature(
'linked-project-output-file'
),
siteUrl: Settings.siteUrl,
emailConfirmationDisabled: Settings.emailConfirmationDisabled,
maxEntitiesPerProject: Settings.maxEntitiesPerProject,
maxUploadSize: Settings.maxUploadSize,
recaptchaSiteKeyV3:
Settings.recaptcha != null ? Settings.recaptcha.siteKeyV3 : undefined,
recaptchaDisabled:
Settings.recaptcha != null ? Settings.recaptcha.disabled : undefined,
textExtensions: Settings.textExtensions,
validRootDocExtensions: Settings.validRootDocExtensions,
sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
sentryDsn: Settings.sentry.publicDSN,
sentryEnvironment: Settings.sentry.environment,
sentryRelease: Settings.sentry.release,
enableSubscriptions: Settings.enableSubscriptions,
}
next()
})
}
| overleaf/web/app/src/infrastructure/ExpressLocals.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/ExpressLocals.js",
"repo_id": "overleaf",
"token_count": 4871
} | 510 |
/* eslint-disable
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let RedirectManager
const settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const URL = require('url')
const querystring = require('querystring')
module.exports = RedirectManager = {
apply(webRouter) {
return (() => {
const result = []
for (var redirectUrl in settings.redirects) {
var target = settings.redirects[redirectUrl]
result.push(
Array.from(target.methods || ['get']).map(method =>
webRouter[method](
redirectUrl,
RedirectManager.createRedirect(target)
)
)
)
}
return result
})()
},
createRedirect(target) {
return function (req, res, next) {
let url
if (
(req.headers != null ? req.headers['x-skip-redirects'] : undefined) !=
null
) {
return next()
}
let code = 302
if (typeof target === 'string') {
url = target
} else {
if (req.method !== 'GET') {
code = 307
}
if (typeof target.url === 'function') {
url = target.url(req.params)
if (!url) {
return next()
}
} else {
;({ url } = target)
}
if (target.baseUrl != null) {
url = `${target.baseUrl}${url}`
}
}
return res.redirect(code, url + getQueryString(req))
}
},
}
// Naively get the query params string. Stringifying the req.query object may
// have differences between Express and Rails, so safer to just pass the raw
// string
var getQueryString = function (req) {
const { search } = URL.parse(req.url)
if (search) {
return search
} else {
return ''
}
}
| overleaf/web/app/src/infrastructure/RedirectManager.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/RedirectManager.js",
"repo_id": "overleaf",
"token_count": 926
} | 511 |
const mongoose = require('../infrastructure/Mongoose')
const { Schema } = mongoose
const DocSnapshotSchema = new Schema(
{
project_id: Schema.Types.ObjectId,
doc_id: Schema.Types.ObjectId,
version: Number,
lines: [String],
pathname: String,
ranges: Schema.Types.Mixed,
ts: Date,
},
{ collection: 'docSnapshots' }
)
exports.DocSnapshot = mongoose.model('DocSnapshot', DocSnapshotSchema)
| overleaf/web/app/src/models/DocSnapshot.js/0 | {
"file_path": "overleaf/web/app/src/models/DocSnapshot.js",
"repo_id": "overleaf",
"token_count": 164
} | 512 |
const mongoose = require('../infrastructure/Mongoose')
const { Schema } = mongoose
// Note that for legacy reasons, user_id and project_ids are plain strings,
// not ObjectIds.
const TagSchema = new Schema({
user_id: { type: String, required: true },
name: { type: String, required: true },
project_ids: [String],
})
exports.Tag = mongoose.model('Tag', TagSchema)
exports.TagSchema = TagSchema
| overleaf/web/app/src/models/Tag.js/0 | {
"file_path": "overleaf/web/app/src/models/Tag.js",
"repo_id": "overleaf",
"token_count": 133
} | 513 |
mixin pagination(pages, page_path, max_btns)
//- @param pages.current_page the current page viewed
//- @param pages.total_pages previously calculated,
//- based on total entries and entries per page
//- @param page_path the relative path, minus a trailing slash and page param
//- @param max_btns max number of buttons on either side of the current page
//- button and excludes first, prev, next, last
if pages && pages.current_page && pages.total_pages && pages.total_pages > 1
- var max_btns = max_btns || 4
- var prev_page = Math.max(parseInt(pages.current_page, 10) - max_btns, 1)
- var next_page = parseInt(pages.current_page, 10) + 1
- var next_index = 0;
- var full_page_path = page_path + "/page/"
nav(role="navigation" aria-label="Pagination Navigation")
ul.pagination
if pages.current_page > 1
li
a(
aria-label="Go to first page"
href=page_path
) « First
li
a(
aria-label="Go to previous page"
href=full_page_path + (parseInt(pages.current_page, 10) - 1)
rel="prev"
) ‹ Prev
if pages.current_page - max_btns > 1
li
span …
while prev_page < pages.current_page
li
a(
aria-label="Go to page " + prev_page
href=full_page_path + prev_page
) #{prev_page}
- prev_page++
li(class="active")
span(
aria-label="Current Page, Page " + pages.current_page
aria-current="true"
) #{pages.current_page}
if pages.current_page < pages.total_pages
while next_page <= pages.total_pages && next_index < max_btns
li
a(
aria-label="Go to page " + next_page
href=full_page_path + next_page
) #{next_page}
- next_page++
- next_index++
if next_page <= pages.total_pages
li
span …
li
a(
aria-label="Go to next page"
href=full_page_path + (parseInt(pages.current_page, 10) + 1)
rel="next"
) Next ›
li
a(
aria-label="Go to last page"
href=full_page_path + pages.total_pages
) Last »
| overleaf/web/app/views/_mixins/pagination.pug/0 | {
"file_path": "overleaf/web/app/views/_mixins/pagination.pug",
"repo_id": "overleaf",
"token_count": 945
} | 514 |
nav.navbar.navbar-default.navbar-main
.container-fluid
.navbar-header
button.navbar-toggle(ng-init="navCollapsed = true", ng-click="navCollapsed = !navCollapsed", ng-class="{active: !navCollapsed}", aria-label="Toggle " + translate('navigation'))
i.fa.fa-bars(aria-hidden="true")
if settings.nav.custom_logo
a(href='/', aria-label=settings.appName, style='background-image:url("'+settings.nav.custom_logo+'")').navbar-brand
else if (nav.title)
a(href='/', aria-label=settings.appName, ng-non-bindable).navbar-title #{nav.title}
else
a(href='/', aria-label=settings.appName).navbar-brand
.navbar-collapse.collapse(collapse="navCollapsed")
ul.nav.navbar-nav.navbar-right
if (getSessionUser() && getSessionUser().isAdmin)
li.dropdown(class="subdued", dropdown)
a.dropdown-toggle(href, dropdown-toggle)
| Admin
b.caret
ul.dropdown-menu
li
a(href="/admin") Manage Site
li
a(href="/admin/user") Manage Users
// loop over header_extras
each item in nav.header_extras
-
if ((item.only_when_logged_in && getSessionUser())
|| (item.only_when_logged_out && (!getSessionUser()))
|| (!item.only_when_logged_out && !item.only_when_logged_in && !item.only_content_pages)
|| (item.only_content_pages && (typeof(suppressNavContentLinks) == "undefined" || !suppressNavContentLinks))
){
var showNavItem = true
} else {
var showNavItem = false
}
if showNavItem
if item.dropdown
li.dropdown(class=item.class, dropdown)
a.dropdown-toggle(href, dropdown-toggle)
| !{translate(item.text)}
b.caret
ul.dropdown-menu
each child in item.dropdown
if child.divider
li.divider
else
li
if child.url
a(href=child.url, class=child.class) !{translate(child.text)}
else
| !{translate(child.text)}
else
li(class=item.class)
if item.url
a(href=item.url, class=item.class) !{translate(item.text)}
else
| !{translate(item.text)}
// logged out
if !getSessionUser()
// register link
if hasFeature('registration-page')
li
a(href="/register") #{translate('register')}
// login link
li
a(href="/login") #{translate('log_in')}
// projects link and account menu
if getSessionUser()
li
a(href="/project") #{translate('Projects')}
li.dropdown(dropdown)
a.dropdown-toggle(href, dropdown-toggle)
| #{translate('Account')}
b.caret
ul.dropdown-menu
li
div.subdued {{ usersEmail }}
li.divider.hidden-xs.hidden-sm
li
a(href="/user/settings") #{translate('Account Settings')}
if nav.showSubscriptionLink
li
a(href="/user/subscription") #{translate('subscription')}
li.divider.hidden-xs.hidden-sm
li
form(method="POST" action="/logout")
input(name='_csrf', type='hidden', value=csrfToken)
button.btn-link.text-left.dropdown-menu-button #{translate('log_out')}
| overleaf/web/app/views/layout/navbar.pug/0 | {
"file_path": "overleaf/web/app/views/layout/navbar.pug",
"repo_id": "overleaf",
"token_count": 1530
} | 515 |
aside.editor-sidebar.full-size(
ng-controller="HistoryV2FileTreeController"
ng-if="ui.view == 'history' && history.isV2"
)
.history-file-tree-inner
history-file-tree(
files="history.selection.files"
selected-pathname="history.selection.pathname"
on-selected-file-change="handleFileSelection(file)"
is-loading="history.loadingFileTree"
)
script(type="text/ng-template", id="historyFileTreeTpl")
.history-file-tree
history-file-entity(
ng-repeat="fileEntity in $ctrl._fileTree | orderBy : [ '-type', 'operation', 'name' ]"
file-entity="fileEntity"
ng-show="!$ctrl.isLoading"
)
script(type="text/ng-template", id="historyFileEntityTpl")
.history-file-entity-wrapper
a.history-file-entity-link(
href
ng-click="$ctrl.isSelected ? '' : $ctrl.handleClick()"
ng-class="{ 'history-file-entity-link-selected': $ctrl.isSelected }"
)
span.history-file-entity-name-container
i.history-file-entity-icon.history-file-entity-icon-folder-state.fa.fa-fw(
ng-class="{\
'fa-chevron-down': ($ctrl.fileEntity.type === 'folder' && $ctrl.isOpen),\
'fa-chevron-right': ($ctrl.fileEntity.type === 'folder' && !$ctrl.isOpen)\
}"
)
i.history-file-entity-icon.fa(
ng-class="::$ctrl.entityTypeIconClass"
)
span.history-file-entity-name(
ng-class="::$ctrl.entityOpTextClass"
) {{ ::$ctrl.fileEntity.name }}
span.history-file-entity-operation-badge(
ng-if="::$ctrl.hasOperation && $ctrl.fileEntity.operation !== 'renamed' && $ctrl.fileEntity.operation !== 'removed'"
) {{ ::$ctrl.getFileOperationName() }}
span.history-file-entity-operation-badge(
ng-if="::$ctrl.hasOperation && $ctrl.fileEntity.operation === 'renamed'"
tooltip-append-to-body="true"
tooltip-placement="right"
tooltip-class="tooltip-history-file-tree"
tooltip-html=`::$ctrl.getRenameTooltip()`
) {{ ::$ctrl.getFileOperationName() }}
div(
ng-show="$ctrl.isOpen"
)
history-file-entity(
ng-repeat="childEntity in $ctrl.fileEntity.children"
file-entity="childEntity"
)
| overleaf/web/app/views/project/editor/history/fileTreeV2.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/history/fileTreeV2.pug",
"repo_id": "overleaf",
"token_count": 859
} | 516 |
script(type='text/ng-template', id='newTagModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("create_new_folder")}
.modal-body
form(name="newTagForm", novalidate)
input.form-control(
type="text",
placeholder="New Folder Name",
required,
ng-model="inputs.newTagName",
on-enter="create()",
focus-on="open",
stop-propagation="click"
)
.modal-footer
.modal-footer-left
span.text-danger.error(ng-show="state.error") #{translate("generic_something_went_wrong")}
//- We stop propagation to stop the clicks from closing the
//- 'move to folder' menu.
button.btn.btn-default(
ng-click="cancel()"
stop-propagation="click"
) #{translate("cancel")}
button.btn.btn-primary(
ng-disabled="newTagForm.$invalid || state.inflight"
ng-click="create()"
stop-propagation="click"
)
span(ng-show="!state.inflight") #{translate("create")}
span(ng-show="state.inflight") #{translate("creating")}…
script(type='text/ng-template', id='deleteTagModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("delete_folder")}
.modal-body
p #{translate("about_to_delete_folder")}
ul
li
strong {{tag.name}}
.modal-footer
.modal-footer-left
span.text-danger.error(ng-show="state.error") #{translate("generic_something_went_wrong")}
button.btn.btn-default(
ng-click="cancel()"
) #{translate("cancel")}
button.btn.btn-danger(
ng-click="delete()",
ng-disabled="state.inflight"
)
span(ng-show="state.inflight") #{translate("deleting")}…
span(ng-show="!state.inflight") #{translate("delete")}
script(type='text/ng-template', id='renameTagModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("rename_folder")}
.modal-body
form(name="renameTagForm", novalidate)
input.form-control(
type="text",
placeholder="Tag Name",
ng-model="inputs.tagName",
required,
on-enter="rename()",
focus-on="open"
)
.modal-footer
.modal-footer-left
span.text-danger.error(ng-show="state.error") #{translate("generic_something_went_wrong")}
button.btn.btn-default(ng-click="cancel()") #{translate("cancel")}
button.btn.btn-primary(
ng-click="rename()",
ng-disabled="renameTagForm.$invalid || state.inflight"
)
span(ng-show="!state.inflight") #{translate("rename")}
span(ng-show="state.inflight") #{translate("renaming")}…
script(type='text/ng-template', id='renameProjectModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("rename_project")}
.modal-body
.alert.alert-danger(ng-show="state.error.message") {{state.error.message}}
.alert.alert-danger(ng-show="state.error && !state.error.message") #{translate("generic_something_went_wrong")}
form(name="renameProjectForm", novalidate)
input.form-control(
type="text",
placeholder="Project Name",
ng-model="inputs.projectName",
required,
on-enter="rename()",
focus-on="open"
)
.modal-footer
button.btn.btn-default(ng-click="cancel()") #{translate("cancel")}
button.btn.btn-primary(
ng-click="rename()",
ng-disabled="renameProjectForm.$invalid || state.inflight"
)
span(ng-show="!state.inflight") #{translate("rename")}
span(ng-show="state.inflight") #{translate("renaming")}…
script(type='text/ng-template', id='cloneProjectModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("copy_project")}
.modal-body
.alert.alert-danger(ng-show="state.error.message") {{state.error.message === "invalid element name" ? "#{translate("invalid_element_name")}" : state.error.message}}
.alert.alert-danger(ng-show="state.error && !state.error.message") #{translate("generic_something_went_wrong")}
form(name="cloneProjectForm", novalidate)
.form-group
label #{translate("new_name")}
input.form-control(
type="text",
placeholder="New Project Name",
required,
ng-model="inputs.projectName",
on-enter="clone()",
focus-on="open"
)
.modal-footer
button.btn.btn-default(
ng-disabled="state.inflight"
ng-click="cancel()"
) #{translate("cancel")}
button.btn.btn-primary(
ng-disabled="cloneProjectForm.$invalid || state.inflight"
ng-click="clone()"
)
span(ng-hide="state.inflight") #{translate("copy")}
span(ng-show="state.inflight") #{translate("copying")} …
script(type='text/ng-template', id='newProjectModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("new_project")}
.modal-body
.alert.alert-danger(ng-show="state.error.message") {{state.error.message}}
.alert.alert-danger(ng-show="state.error && !state.error.message") #{translate("generic_something_went_wrong")}
form(novalidate, name="newProjectForm")
input.form-control(
type="text",
placeholder="Project Name",
required,
ng-model="inputs.projectName",
on-enter="create()",
focus-on="open"
)
.modal-footer
button.btn.btn-default(
ng-disabled="state.inflight"
ng-click="cancel()"
) #{translate("cancel")}
button.btn.btn-primary(
ng-disabled="newProjectForm.$invalid || state.inflight"
ng-click="create()"
)
span(ng-hide="state.inflight") #{translate("create")}
span(ng-show="state.inflight") #{translate("creating")} …
script(type='text/ng-template', id='archiveTrashLeaveOrDeleteProjectsModalTemplate')
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3(ng-if="action === 'archive'") #{translate("archive_projects")}
h3(ng-if="action === 'trash'") #{translate("trash_projects")}
h3(ng-if="action === 'leave'") #{translate("leave_projects")}
h3(ng-if="action === 'delete'") #{translate("delete_projects")}
h3(ng-if="action === 'leaveOrDelete'") #{translate("delete_and_leave_projects")}
.modal-body
div(ng-if="action !== 'leaveOrDelete'")
p(ng-if="action === 'archive'") #{translate("about_to_archive_projects")}
p(ng-if="action === 'trash'") #{translate("about_to_trash_projects")}
p(ng-if="action === 'leave'") #{translate("about_to_leave_projects")}
p(ng-if="action === 'delete'") #{translate("about_to_delete_projects")}
ul
li(ng-repeat="project in projects | orderBy:'name'")
strong {{project.name}}
div(ng-if="action === 'archive'")
p #{translate("archiving_projects_wont_affect_collaborators")}
|
a(
href="https://www.overleaf.com/blog/new-feature-using-archive-and-trash-to-keep-your-projects-organized"
target="_blank"
) #{translate("find_out_more_nt")}
div(ng-if="action === 'trash'")
p #{translate("trashing_projects_wont_affect_collaborators")}
|
a(
href="https://www.overleaf.com/blog/new-feature-using-archive-and-trash-to-keep-your-projects-organized"
target="_blank"
) #{translate("find_out_more_nt")}
.project-action-alert.alert.alert-warning(ng-if="action === 'leave' || action === 'delete'")
i.fa.fa-fw.fa-exclamation-triangle
.project-action-alert-msg #{translate("this_action_cannot_be_undone")}
div(ng-if="action === 'leaveOrDelete'")
p #{translate("about_to_delete_projects")}
ul
li(ng-repeat="project in projects | filter:{accessLevel: 'owner'} | orderBy:'name'")
strong {{project.name}}
p #{translate("about_to_leave_projects")}
ul
li(ng-repeat="project in projects | filter:{accessLevel: '!owner'} | orderBy:'name'")
strong {{project.name}}
.project-action-alert.alert.alert-warning
i.fa.fa-fw.fa-exclamation-triangle
.project-action-alert-msg #{translate("this_action_cannot_be_undone")}
.modal-footer
button.btn.btn-default(
ng-click="cancel()"
) #{translate("cancel")}
button.btn.btn-danger(
ng-click="confirm()"
) #{translate("confirm")}
script(type="text/template", id="qq-project-uploader-template")
div.qq-uploader-selector
div(qq-hide-dropzone="").qq-upload-drop-area-selector.qq-upload-drop-area
span.qq-upload-drop-area-text-selector #{translate('drop_files_here_to_upload')}
div.qq-upload-button-selector.btn.btn-primary.btn-lg
div #{translate('select_a_zip_file')}
span.or.btn-lg #{translate('or')}
span.drag-here.btn-lg #{translate('drag_a_zip_file')}
ul.qq-upload-list-selector
li
div.qq-progress-bar-container-selector
div(
role="progressbar"
aria-valuenow="0"
aria-valuemin="0"
aria-valuemax="100"
class="qq-progress-bar-selector qq-progress-bar"
)
span.qq-upload-file-selector.qq-upload-file
span.qq-upload-size-selector.qq-upload-size
a(type="button").qq-btn.qq-upload-cancel-selector.qq-upload-cancel #{translate('cancel')}
button(type="button").qq-btn.qq-upload-retry-selector.qq-upload-retry #{translate('retry')}
span(role="status").qq-upload-status-text-selector.qq-upload-status-text
script(type="text/ng-template", id="uploadProjectModalTemplate")
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("upload_zipped_project")}
.modal-body(
fine-upload
endpoint="/project/new/upload"
template-id="qq-project-uploader-template"
multiple="false"
size-limit=zipFileSizeLimit
allowed-extensions="['zip']"
on-complete-callback="onComplete"
)
.modal-footer
button.btn.btn-default(ng-click="cancel()") #{translate("cancel")}
| overleaf/web/app/views/project/list/modals.pug/0 | {
"file_path": "overleaf/web/app/views/project/list/modals.pug",
"repo_id": "overleaf",
"token_count": 4325
} | 517 |
each affiliation in confirmedMemberAffiliations
if (affiliation.licence && affiliation.licence != 'free')
-hasDisplayedSubscription = true
p
| You have a
|
strong(ng-non-bindable) Professional
|
| #{settings.appName} account as a confirmed member of
|
strong(ng-non-bindable)= affiliation.institution.name
hr
| overleaf/web/app/views/subscriptions/dashboard/_institution_memberships.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard/_institution_memberships.pug",
"repo_id": "overleaf",
"token_count": 120
} | 518 |
extends ../layout
block content
.masthead
.container
.row
.col-md-12
h1(ng-non-bindable) !{viewData.title}
.row.row-spaced
.pattern-container
.content
.container
.row
.col-md-10.col-md-offset-1
.card
.row(ng-non-bindable)
| !{viewData.html}
| overleaf/web/app/views/university/case_study.pug/0 | {
"file_path": "overleaf/web/app/views/university/case_study.pug",
"repo_id": "overleaf",
"token_count": 160
} | 519 |
extends ../layout
block content
main.content.content-alt#main-content
.container
.row
.col-md-10.col-md-offset-1
h3(ng-non-bindable) #{entityName} "#{entityId}" does not exists in v2
form(
enctype='application/json',
method='post',
action=''
)
input(name="_csrf", type="hidden", value=csrfToken)
button.btn.btn-primary.text-capitalize(
type="submit",
ng-non-bindable
) Create #{entityName} in v2
| overleaf/web/app/views/user_membership/new.pug/0 | {
"file_path": "overleaf/web/app/views/user_membership/new.pug",
"repo_id": "overleaf",
"token_count": 224
} | 520 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../base'
import qq from 'fineuploader'
export default App.directive('fineUpload', $timeout => ({
scope: {
multiple: '=',
endpoint: '@',
templateId: '@',
sizeLimit: '@',
allowedExtensions: '=',
onCompleteCallback: '=',
onUploadCallback: '=',
onValidateBatch: '=',
onErrorCallback: '=',
onSubmitCallback: '=',
onCancelCallback: '=',
autoUpload: '=',
params: '=',
control: '=',
},
link(scope, element, attrs) {
let autoUpload, validation
const multiple = scope.multiple || false
const { endpoint } = scope
const { templateId } = scope
if (scope.allowedExtensions != null) {
validation = { allowedExtensions: scope.allowedExtensions }
} else {
validation = {}
}
if (scope.sizeLimit) {
validation.sizeLimit = scope.sizeLimit
}
const maxConnections = scope.maxConnections || 1
const onComplete = scope.onCompleteCallback || function () {}
const onUpload = scope.onUploadCallback || function () {}
const onError = scope.onErrorCallback || function () {}
const onValidateBatch = scope.onValidateBatch || function () {}
const onSubmit = scope.onSubmitCallback || function () {}
const onCancel = scope.onCancelCallback || function () {}
if (scope.autoUpload == null) {
autoUpload = true
} else {
;({ autoUpload } = scope)
}
const params = scope.params || {}
params._csrf = window.csrfToken
const q = new qq.FineUploader({
element: element[0],
multiple,
autoUpload,
disabledCancelForFormUploads: true,
validation,
maxConnections,
request: {
endpoint,
forceMultipart: true,
params,
paramsInBody: false,
},
callbacks: {
onComplete,
onUpload,
onValidateBatch,
onError,
onSubmit,
onCancel,
},
template: templateId,
failedUploadTextDisplay: {
mode: 'custom',
responseProperty: 'error',
},
})
window.q = q
if (scope.control != null) {
scope.control.q = q
}
return q
},
}))
| overleaf/web/frontend/js/directives/fineUpload.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/fineUpload.js",
"repo_id": "overleaf",
"token_count": 968
} | 521 |
import PropTypes from 'prop-types'
import { getHueForUserId } from '../../../shared/utils/colors'
import MessageContent from './message-content'
function Message({ message, userId }) {
function hue(user) {
return user ? getHueForUserId(user.id, userId) : 0
}
function getMessageStyle(user) {
return {
borderColor: `hsl(${hue(user)}, 85%, 40%)`,
backgroundColor: `hsl(${hue(user)}, 85%, 40%`,
}
}
function getArrowStyle(user) {
return {
borderColor: `hsl(${hue(user)}, 85%, 40%)`,
}
}
const isMessageFromSelf = message.user ? message.user.id === userId : false
return (
<div className="message-wrapper">
{!isMessageFromSelf && (
<div className="name">
<span>{message.user.first_name || message.user.email}</span>
</div>
)}
<div className="message" style={getMessageStyle(message.user)}>
{!isMessageFromSelf && (
<div className="arrow" style={getArrowStyle(message.user)} />
)}
<div className="message-content">
{message.contents.map((content, index) => (
<MessageContent key={index} content={content} />
))}
</div>
</div>
</div>
)
}
Message.propTypes = {
message: PropTypes.shape({
contents: PropTypes.arrayOf(PropTypes.string).isRequired,
user: PropTypes.shape({
id: PropTypes.string,
email: PropTypes.string,
first_name: PropTypes.string,
}),
}),
userId: PropTypes.string.isRequired,
}
export default Message
| overleaf/web/frontend/js/features/chat/components/message.js/0 | {
"file_path": "overleaf/web/frontend/js/features/chat/components/message.js",
"repo_id": "overleaf",
"token_count": 637
} | 522 |
import { useEffect, useState, useRef } from 'react'
import PropTypes from 'prop-types'
import { OverlayTrigger, Tooltip } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'
import Icon from '../../../shared/components/icon'
function ProjectNameEditableLabel({
projectName,
hasRenamePermissions,
onChange,
className,
}) {
const { t } = useTranslation()
const [isRenaming, setIsRenaming] = useState(false)
const canRename = hasRenamePermissions && !isRenaming
const [inputContent, setInputContent] = useState(projectName)
const inputRef = useRef(null)
useEffect(() => {
if (isRenaming) {
inputRef.current.select()
}
}, [isRenaming])
function startRenaming() {
if (canRename) {
setInputContent(projectName)
setIsRenaming(true)
}
}
function handleKeyDown(event) {
if (event.key === 'Enter') {
event.preventDefault()
setIsRenaming(false)
onChange(event.target.value)
}
}
function handleOnChange(event) {
setInputContent(event.target.value)
}
function handleBlur() {
setIsRenaming(false)
}
return (
<div className={classNames('project-name', className)}>
{!isRenaming && (
<span className="name" onDoubleClick={startRenaming}>
{projectName}
</span>
)}
{isRenaming && (
<input
ref={inputRef}
type="text"
className="form-control"
onKeyDown={handleKeyDown}
onChange={handleOnChange}
onBlur={handleBlur}
value={inputContent}
/>
)}
{canRename && (
<OverlayTrigger
placement="bottom"
trigger={['hover', 'focus']}
overlay={<Tooltip id="tooltip-online-user">{t('rename')}</Tooltip>}
>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid, jsx-a11y/click-events-have-key-events, jsx-a11y/interactive-supports-focus */}
<a className="rename" role="button" onClick={startRenaming}>
<Icon type="pencil" modifier="fw" />
</a>
</OverlayTrigger>
)}
</div>
)
}
ProjectNameEditableLabel.propTypes = {
projectName: PropTypes.string.isRequired,
hasRenamePermissions: PropTypes.bool,
onChange: PropTypes.func.isRequired,
className: PropTypes.string,
}
export default ProjectNameEditableLabel
| overleaf/web/frontend/js/features/editor-navigation-toolbar/components/project-name-editable-label.js/0 | {
"file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/project-name-editable-label.js",
"repo_id": "overleaf",
"token_count": 999
} | 523 |
import { Trans } from 'react-i18next'
import { Alert, Button } from 'react-bootstrap'
import { useCallback, useState } from 'react'
import PropTypes from 'prop-types'
import Uppy from '@uppy/core'
import XHRUpload from '@uppy/xhr-upload'
import { Dashboard, useUppy } from '@uppy/react'
import { useFileTreeActionable } from '../../../contexts/file-tree-actionable'
import { useFileTreeMainContext } from '../../../contexts/file-tree-main'
import '@uppy/core/dist/style.css'
import '@uppy/dashboard/dist/style.css'
import { refreshProjectMetadata } from '../../../util/api'
import ErrorMessage from '../error-message'
export default function FileTreeUploadDoc() {
const { parentFolderId, cancel, isDuplicate } = useFileTreeActionable()
const { projectId } = useFileTreeMainContext()
const [error, setError] = useState()
const [conflicts, setConflicts] = useState([])
const [overwrite, setOverwrite] = useState(false)
const maxNumberOfFiles = 40
const maxFileSize = window.ExposedSettings.maxUploadSize
// calculate conflicts
const buildConflicts = files =>
Object.values(files).filter(file =>
isDuplicate(parentFolderId, file.meta.name)
)
// initialise the Uppy object
const uppy = useUppy(() => {
let endpoint = `/project/${projectId}/upload`
if (parentFolderId) {
endpoint += `?folder_id=${parentFolderId}`
}
return (
new Uppy({
// logger: Uppy.debugLogger,
allowMultipleUploads: false,
restrictions: {
maxNumberOfFiles,
maxFileSize: maxFileSize || null,
},
onBeforeUpload: files => {
let result = true
setOverwrite(overwrite => {
if (!overwrite) {
setConflicts(() => {
const conflicts = buildConflicts(files)
result = conflicts.length === 0
return conflicts
})
}
return overwrite
})
return result
},
autoProceed: true,
})
// use the basic XHR uploader
.use(XHRUpload, {
endpoint,
headers: {
'X-CSRF-TOKEN': window.csrfToken,
},
// limit: maxConnections || 1,
limit: 1,
fieldName: 'qqfile', // "qqfile" field inherited from FineUploader
})
// close the modal when all the uploads completed successfully
.on('complete', result => {
if (!result.failed.length) {
// $scope.$emit('done', { name: name })
cancel()
}
})
// broadcast doc metadata after each successful upload
.on('upload-success', (file, response) => {
if (response.body.entity_type === 'doc') {
window.setTimeout(() => {
refreshProjectMetadata(projectId, response.body.entity_id)
}, 250)
}
})
// handle upload errors
.on('upload-error', (file, error, response) => {
switch (response?.status) {
case 429:
setError('rate-limit-hit')
break
case 403:
setError('not-logged-in')
break
default:
setError(response.body.error)
break
}
})
)
})
// handle forced overwriting of conflicting files
const handleOverwrite = useCallback(() => {
setOverwrite(true)
window.setTimeout(() => {
uppy.upload()
}, 10)
}, [uppy])
// whether to show a message about conflicting files
const showConflicts = !overwrite && conflicts.length > 0
return (
<>
{error && (
<UploadErrorMessage error={error} maxNumberOfFiles={maxNumberOfFiles} />
)}
{showConflicts ? (
<UploadConflicts
cancel={cancel}
conflicts={conflicts}
handleOverwrite={handleOverwrite}
/>
) : (
<Dashboard
uppy={uppy}
showProgressDetails
// note={`Up to ${maxNumberOfFiles} files, up to ${maxFileSize / (1024 * 1024)}MB`}
height={400}
width="100%"
showLinkToFileUploadResult={false}
proudlyDisplayPoweredByUppy={false}
locale={{
strings: {
// Text to show on the droppable area.
// `%{browse}` is replaced with a link that opens the system file selection dialog.
// TODO: 'drag_here' or 'drop_files_here_to_upload'?
// dropHereOr: `${t('drag_here')} ${t('or')} %{browse}`,
dropPasteFiles: `Drag here or %{browseFiles}`,
// Used as the label for the link that opens the system file selection dialog.
// browseFiles: t('select_from_your_computer')
browseFiles: 'select from your computer',
},
}}
/>
)}
</>
)
}
function UploadErrorMessage({ error, maxNumberOfFiles }) {
switch (error) {
case 'too-many-files':
return (
<Trans
i18nKey="maximum_files_uploaded_together"
values={{ max: maxNumberOfFiles }}
/>
)
default:
return <ErrorMessage error={error} />
}
}
UploadErrorMessage.propTypes = {
error: PropTypes.string.isRequired,
maxNumberOfFiles: PropTypes.number.isRequired,
}
function UploadConflicts({ cancel, conflicts, handleOverwrite }) {
return (
<Alert bsStyle="warning" className="small">
<p className="text-center">
The following files already exist in this project:
</p>
<ul className="text-center list-unstyled row-spaced-small">
{conflicts.map((conflict, index) => (
<li key={index}>
<strong>{conflict.meta.name}</strong>
</li>
))}
</ul>
<p className="text-center row-spaced-small">
Do you want to overwrite them?
</p>
<p className="text-center">
<Button bsStyle="primary" onClick={handleOverwrite}>
Overwrite
</Button>
<Button bsStyle="primary" onClick={cancel}>
Cancel
</Button>
</p>
</Alert>
)
}
UploadConflicts.propTypes = {
cancel: PropTypes.func.isRequired,
conflicts: PropTypes.array.isRequired,
handleOverwrite: PropTypes.func.isRequired,
}
| overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-upload-doc.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-upload-doc.js",
"repo_id": "overleaf",
"token_count": 2797
} | 524 |
import { Button, Modal } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import { useFileTreeActionable } from '../../contexts/file-tree-actionable'
import {
InvalidFilenameError,
BlockedFilenameError,
DuplicateFilenameError,
DuplicateFilenameMoveError,
} from '../../errors'
function FileTreeModalError() {
const { t } = useTranslation()
const { isRenaming, isMoving, cancel, error } = useFileTreeActionable()
// the modal will not be rendered; return early
if (!error) return null
if (!isRenaming && !isMoving) return null
function handleHide() {
cancel()
}
function errorTitle() {
switch (error.constructor) {
case DuplicateFilenameError:
case DuplicateFilenameMoveError:
return t('duplicate_file')
case InvalidFilenameError:
case BlockedFilenameError:
return t('invalid_file_name')
default:
return t('error')
}
}
function errorMessage() {
switch (error.constructor) {
case DuplicateFilenameError:
return t('file_already_exists')
case DuplicateFilenameMoveError:
return (
<Trans
i18nKey="file_already_exists_in_this_location"
components={[<strong />]} // eslint-disable-line react/jsx-key
values={{ fileName: error.entityName }}
/>
)
case InvalidFilenameError:
return t('files_cannot_include_invalid_characters')
case BlockedFilenameError:
return t('blocked_filename')
default:
return t('generic_something_went_wrong')
}
}
return (
<Modal show onHide={handleHide}>
<Modal.Header>
<Modal.Title>{errorTitle()}</Modal.Title>
</Modal.Header>
<Modal.Body>
<div role="alert" aria-label={errorMessage()}>
{errorMessage()}
</div>
</Modal.Body>
<Modal.Footer>
<Button onClick={handleHide}>{t('ok')}</Button>
</Modal.Footer>
</Modal>
)
}
export default FileTreeModalError
| overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-error.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-error.js",
"repo_id": "overleaf",
"token_count": 825
} | 525 |
import OError from '@overleaf/o-error'
export function findInTreeOrThrow(tree, id) {
const found = findInTree(tree, id)
if (found) return found
throw new OError('Entity not found in tree', { entityId: id })
}
export function findAllInTreeOrThrow(tree, ids) {
const list = new Set()
ids.forEach(id => {
list.add(findInTreeOrThrow(tree, id))
})
return list
}
export function findAllFolderIdsInFolder(folder) {
const list = new Set([folder._id])
for (const index in folder.folders) {
const subFolder = folder.folders[index]
findAllFolderIdsInFolder(subFolder).forEach(subFolderId => {
list.add(subFolderId)
})
}
return list
}
export function findAllFolderIdsInFolders(folders) {
const list = new Set()
folders.forEach(folder => {
findAllFolderIdsInFolder(folder).forEach(folderId => {
list.add(folderId)
})
})
return list
}
export function findInTree(tree, id, path) {
if (!path) {
path = [tree._id]
}
for (const index in tree.docs) {
const doc = tree.docs[index]
if (doc._id === id) {
return {
entity: doc,
type: 'doc',
parent: tree.docs,
parentFolderId: tree._id,
path,
index,
}
}
}
for (const index in tree.fileRefs) {
const file = tree.fileRefs[index]
if (file._id === id) {
return {
entity: file,
type: 'fileRef',
parent: tree.fileRefs,
parentFolderId: tree._id,
path,
index,
}
}
}
for (const index in tree.folders) {
const folder = tree.folders[index]
if (folder._id === id) {
return {
entity: folder,
type: 'folder',
parent: tree.folders,
parentFolderId: tree._id,
path,
index,
}
}
const found = findInTree(folder, id, path.concat(folder._id))
if (found) return found
}
return null
}
| overleaf/web/frontend/js/features/file-tree/util/find-in-tree.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/util/find-in-tree.js",
"repo_id": "overleaf",
"token_count": 818
} | 526 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import OutlineList from './outline-list'
function OutlineRoot({ outline, jumpToLine, highlightedLine }) {
const { t } = useTranslation()
return (
<div>
{outline.length ? (
<OutlineList
outline={outline}
jumpToLine={jumpToLine}
isRoot
highlightedLine={highlightedLine}
/>
) : (
<div className="outline-body-no-elements">
{t('we_cant_find_any_sections_or_subsections_in_this_file')}.{' '}
<a
href="/learn/how-to/Using_the_File_Outline_feature"
className="outline-body-link"
target="_blank"
rel="noopener noreferrer"
>
{t('find_out_more_about_the_file_outline')}
</a>
</div>
)}
</div>
)
}
OutlineRoot.propTypes = {
outline: PropTypes.array.isRequired,
jumpToLine: PropTypes.func.isRequired,
highlightedLine: PropTypes.number,
}
export default OutlineRoot
| overleaf/web/frontend/js/features/outline/components/outline-root.js/0 | {
"file_path": "overleaf/web/frontend/js/features/outline/components/outline-root.js",
"repo_id": "overleaf",
"token_count": 490
} | 527 |
import { useState, useMemo } from 'react'
import { useTranslation, Trans } from 'react-i18next'
import { Form, FormGroup, FormControl, Button } from 'react-bootstrap'
import { useMultipleSelection } from 'downshift'
import { useShareProjectContext } from './share-project-modal'
import SelectCollaborators from './select-collaborators'
import { resendInvite, sendInvite } from '../utils/api'
import { useUserContacts } from '../hooks/use-user-contacts'
import useIsMounted from '../../../shared/hooks/use-is-mounted'
import { useProjectContext } from '../../../shared/context/project-context'
export default function AddCollaborators() {
const [privileges, setPrivileges] = useState('readAndWrite')
const isMounted = useIsMounted()
const { data: contacts } = useUserContacts()
const { t } = useTranslation()
const { updateProject, setInFlight, setError } = useShareProjectContext()
const project = useProjectContext()
const currentMemberEmails = useMemo(
() => (project.members || []).map(member => member.email).sort(),
[project.members]
)
const nonMemberContacts = useMemo(() => {
if (!contacts) {
return null
}
return contacts.filter(
contact => !currentMemberEmails.includes(contact.email)
)
}, [contacts, currentMemberEmails])
const multipleSelectionProps = useMultipleSelection({
initialActiveIndex: 0,
initialSelectedItems: [],
})
const { reset, selectedItems } = multipleSelectionProps
async function handleSubmit(event) {
event.preventDefault()
if (!selectedItems.length) {
return
}
// reset the selected items
reset()
setError(undefined)
setInFlight(true)
for (const contact of selectedItems) {
// unmounting means can't add any more collaborators
if (!isMounted.current) {
break
}
const email = contact.type === 'user' ? contact.email : contact.display
const normalisedEmail = email.toLowerCase()
if (currentMemberEmails.includes(normalisedEmail)) {
continue
}
let data
try {
const invite = (project.invites || []).find(
invite => invite.email === normalisedEmail
)
if (invite) {
data = await resendInvite(project, invite)
} else {
data = await sendInvite(project, email, privileges)
}
} catch (error) {
setInFlight(false)
setError(
error.data?.errorReason ||
(error.response?.status === 429
? 'too_many_requests'
: 'generic_something_went_wrong')
)
break
}
if (data.error) {
setError(data.error)
setInFlight(false)
} else if (data.invite) {
updateProject({
invites: project.invites.concat(data.invite),
})
} else if (data.users) {
updateProject({
members: project.members.concat(data.users),
})
} else if (data.user) {
updateProject({
members: project.members.concat(data.user),
})
}
// wait for a short time, so canAddCollaborators has time to update with new collaborator information
await new Promise(resolve => setTimeout(resolve, 100))
}
setInFlight(false)
}
return (
<Form onSubmit={handleSubmit}>
<FormGroup>
<SelectCollaborators
loading={!nonMemberContacts}
options={nonMemberContacts || []}
placeholder="joe@example.com, sue@example.com, …"
multipleSelectionProps={multipleSelectionProps}
/>
</FormGroup>
<FormGroup>
<div className="pull-right">
<FormControl
componentClass="select"
className="privileges"
bsSize="sm"
value={privileges}
onChange={event => setPrivileges(event.target.value)}
>
<option value="readAndWrite">{t('can_edit')}</option>
<option value="readOnly">{t('read_only')}</option>
</FormControl>
<span> </span>
<Button type="submit" bsStyle="info">
<Trans i18nKey="share" />
</Button>
</div>
</FormGroup>
</Form>
)
}
| overleaf/web/frontend/js/features/share-project-modal/components/add-collaborators.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/components/add-collaborators.js",
"repo_id": "overleaf",
"token_count": 1744
} | 528 |
import {
deleteJSON,
getJSON,
postJSON,
putJSON,
} from '../../../infrastructure/fetch-json'
import { executeV2Captcha } from './captcha'
export function sendInvite(project, email, privileges) {
return executeV2Captcha(
window.ExposedSettings.recaptchaDisabled?.invite
).then(grecaptchaResponse => {
return postJSON(`/project/${project._id}/invite`, {
body: {
email, // TODO: normalisedEmail?
privileges,
'g-recaptcha-response': grecaptchaResponse,
},
})
})
}
export function resendInvite(project, invite) {
return postJSON(`/project/${project._id}/invite/${invite._id}/resend`)
}
export function revokeInvite(project, invite) {
return deleteJSON(`/project/${project._id}/invite/${invite._id}`)
}
export function updateMember(project, member, data) {
return putJSON(`/project/${project._id}/users/${member._id}`, {
body: data,
})
}
export function removeMemberFromProject(project, member) {
return deleteJSON(`/project/${project._id}/users/${member._id}`)
}
export function transferProjectOwnership(project, member) {
return postJSON(`/project/${project._id}/transfer-ownership`, {
body: {
user_id: member._id,
},
})
}
export function setProjectAccessLevel(project, publicAccessLevel) {
return postJSON(`/project/${project._id}/settings/admin`, {
body: { publicAccessLevel },
})
}
// export function updateProjectAdminSettings(project, data) {
// return postJSON(`/project/${project._id}/settings/admin`, {
// body: data
// })
// }
export function listProjectMembers(project) {
return getJSON(`/project/${project._id}/members`)
}
export function listProjectInvites(project) {
return getJSON(`/project/${project._id}/invites`)
}
| overleaf/web/frontend/js/features/share-project-modal/utils/api.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/utils/api.js",
"repo_id": "overleaf",
"token_count": 629
} | 529 |
import { useEffect, useState } from 'react'
import PropTypes from 'prop-types'
import WordCountModalContent from './word-count-modal-content'
import { fetchWordCount } from '../utils/api'
function WordCountModal({ clsiServerId, handleHide, projectId, show }) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
const [data, setData] = useState()
useEffect(() => {
if (!show) {
return
}
setData(undefined)
setError(false)
setLoading(true)
fetchWordCount(projectId, clsiServerId)
.then(data => {
setData(data.texcount)
})
.catch(error => {
if (error.cause?.name !== 'AbortError') {
setError(true)
}
})
.finally(() => {
setLoading(false)
})
}, [show, projectId, clsiServerId])
return (
<WordCountModalContent
data={data}
error={error}
show={show}
handleHide={handleHide}
loading={loading}
/>
)
}
WordCountModal.propTypes = {
clsiServerId: PropTypes.string,
handleHide: PropTypes.func.isRequired,
projectId: PropTypes.string.isRequired,
show: PropTypes.bool.isRequired,
}
export default WordCountModal
| overleaf/web/frontend/js/features/word-count-modal/components/word-count-modal.js/0 | {
"file_path": "overleaf/web/frontend/js/features/word-count-modal/components/word-count-modal.js",
"repo_id": "overleaf",
"token_count": 490
} | 530 |
/* eslint-disable
camelcase,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
// NOTE: this file is being refactored over to frontend/js/shared/utils/colors.js
import CryptoJS from 'crypto-js/md5'
let ColorManager
export default ColorManager = {
getColorScheme(hue, element) {
if (this.isDarkTheme(element)) {
return {
cursor: `hsl(${hue}, 70%, 50%)`,
labelBackgroundColor: `hsl(${hue}, 70%, 50%)`,
highlightBackgroundColor: `hsl(${hue}, 100%, 28%);`,
strikeThroughBackgroundColor: `hsl(${hue}, 100%, 20%);`,
strikeThroughForegroundColor: `hsl(${hue}, 100%, 60%);`,
}
} else {
return {
cursor: `hsl(${hue}, 70%, 50%)`,
labelBackgroundColor: `hsl(${hue}, 70%, 50%)`,
highlightBackgroundColor: `hsl(${hue}, 70%, 85%);`,
strikeThroughBackgroundColor: `hsl(${hue}, 70%, 95%);`,
strikeThroughForegroundColor: `hsl(${hue}, 70%, 40%);`,
}
}
},
isDarkTheme(element) {
const rgb = element.find('.ace_editor').css('background-color')
let [m, r, g, b] = Array.from(
rgb.match(/rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)/)
)
r = parseInt(r, 10)
g = parseInt(g, 10)
b = parseInt(b, 10)
return r + g + b < 3 * 128
},
ANONYMOUS_HUE: 100,
OWN_HUE: 200, // We will always appear as this color to ourselves
OWN_HUE_BLOCKED_SIZE: 20, // no other user should havea HUE in this range
TOTAL_HUES: 360, // actually 361, but 360 for legacy reasons
getHueForUserId(user_id) {
if (user_id == null || user_id === 'anonymous-user') {
return this.ANONYMOUS_HUE
}
if (window.user.id === user_id) {
return this.OWN_HUE
}
let hue = this.getHueForId(user_id)
// if `hue` is within `OWN_HUE_BLOCKED_SIZE` degrees of the personal hue
// (`OWN_HUE`), shift `hue` to the end of available hues by adding
if (
hue > this.OWN_HUE - this.OWN_HUE_BLOCKED_SIZE &&
hue < this.OWN_HUE + this.OWN_HUE_BLOCKED_SIZE
) {
hue = hue - this.OWN_HUE // `hue` now at 0 +/- `OWN_HUE_BLOCKED_SIZE`
hue = hue + this.TOTAL_HUES - this.OWN_HUE_BLOCKED_SIZE
}
return hue
},
getHueForTagId(tag_id) {
return this.getHueForId(tag_id)
},
getHueForId(id) {
const hash = CryptoJS(id)
const hue =
parseInt(hash.toString().slice(0, 8), 16) %
(this.TOTAL_HUES - this.OWN_HUE_BLOCKED_SIZE * 2)
return hue
},
}
| overleaf/web/frontend/js/ide/colors/ColorManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/colors/ColorManager.js",
"repo_id": "overleaf",
"token_count": 1198
} | 531 |
import _ from 'lodash'
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* 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 topHundred from './snippets/TopHundredSnippets'
let CommandManager
class Parser {
static initClass() {
// Ignore single letter commands since auto complete is moot then.
this.prototype.commandRegex = /\\([a-zA-Z]{2,})/
}
constructor(doc, prefix) {
this.doc = doc
this.prefix = prefix
}
parse() {
// Safari regex is super slow, freezes browser for minutes on end,
// hacky solution: limit iterations
let command
let limit = null
if (
__guard__(
typeof window !== 'undefined' && window !== null
? window._ide
: undefined,
x => x.browserIsSafari
)
) {
limit = 5000
}
// fully formed commands
const realCommands = []
// commands which match the prefix exactly,
// and could be partially typed or malformed
const incidentalCommands = []
const seen = {}
let iterations = 0
while ((command = this.nextCommand())) {
iterations += 1
if (limit && iterations > limit) {
return realCommands
}
const docState = this.doc
let optionalArgs = 0
while (this.consumeArgument('[', ']')) {
optionalArgs++
}
let args = 0
while (this.consumeArgument('{', '}')) {
args++
}
const commandHash = `${command}\\${optionalArgs}\\${args}`
if (this.prefix != null && `\\${command}` === this.prefix) {
incidentalCommands.push([command, optionalArgs, args])
} else {
if (seen[commandHash] == null) {
seen[commandHash] = true
realCommands.push([command, optionalArgs, args])
}
}
// Reset to before argument to handle nested commands
this.doc = docState
}
// check incidentals, see if we should pluck out a match
if (incidentalCommands.length > 1) {
const bestMatch = incidentalCommands.sort(
(a, b) => b[1] + b[2] - (a[1] + a[2])
)[0]
realCommands.push(bestMatch)
}
return realCommands
}
nextCommand() {
const i = this.doc.search(this.commandRegex)
if (i === -1) {
return false
} else {
const match = this.doc.match(this.commandRegex)[1]
this.doc = this.doc.substr(i + match.length + 1)
return match
}
}
consumeWhitespace() {
const match = this.doc.match(/^[ \t\n]*/m)[0]
return (this.doc = this.doc.substr(match.length))
}
consumeArgument(openingBracket, closingBracket) {
this.consumeWhitespace()
if (this.doc[0] === openingBracket) {
let i = 1
let bracketParity = 1
while (bracketParity > 0 && i < this.doc.length) {
if (this.doc[i] === openingBracket) {
bracketParity++
} else if (this.doc[i] === closingBracket) {
bracketParity--
}
i++
}
if (bracketParity === 0) {
this.doc = this.doc.substr(i)
return true
} else {
return false
}
} else {
return false
}
}
}
Parser.initClass()
export default CommandManager = class CommandManager {
constructor(metadataManager) {
this.metadataManager = metadataManager
}
getCompletions(editor, session, pos, prefix, callback) {
const commandNames = {}
for (var snippet of Array.from(topHundred)) {
commandNames[snippet.caption.match(/\w+/)[0]] = true
}
const packages = this.metadataManager.getAllPackages()
const packageCommands = []
for (const pkg in packages) {
const snippets = packages[pkg]
for (snippet of Array.from(snippets)) {
packageCommands.push(snippet)
commandNames[snippet.caption.match(/\w+/)[0]] = true
}
}
const doc = session.getValue()
const parser = new Parser(doc, prefix)
const commands = parser.parse()
let completions = []
for (const command of Array.from(commands)) {
if (!commandNames[command[0]]) {
let caption = `\\${command[0]}`
const score = caption === prefix ? 99 : 50
snippet = caption
var i = 1
_.times(command[1], function () {
snippet += `[\${${i}}]`
caption += '[]'
return i++
})
_.times(command[2], function () {
snippet += `{\${${i}}}`
caption += '{}'
return i++
})
completions.push({
caption,
snippet,
meta: 'cmd',
score,
})
}
}
completions = completions.concat(topHundred, packageCommands)
return callback(null, completions)
}
loadCommandsFromDoc(doc) {
const parser = new Parser(doc)
return (this.commands = parser.parse())
}
getSuggestions(commandFragment) {
const matchingCommands = _.filter(
this.commands,
command => command[0].slice(0, commandFragment.length) === commandFragment
)
return _.map(matchingCommands, function (command) {
let completionAfterCursor, completionBeforeCursor
const base = `\\${commandFragment}`
let args = ''
_.times(command[1], () => (args = args + '[]'))
_.times(command[2], () => (args = args + '{}'))
const completionBase = command[0].slice(commandFragment.length)
const squareArgsNo = command[1]
const curlyArgsNo = command[2]
const totalArgs = squareArgsNo + curlyArgsNo
if (totalArgs === 0) {
completionBeforeCursor = completionBase
completionAfterCursor = ''
} else {
completionBeforeCursor = completionBase + args[0]
completionAfterCursor = args.slice(1)
}
return {
base,
completion: completionBase + args,
completionBeforeCursor,
completionAfterCursor,
}
})
}
}
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/CommandManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/CommandManager.js",
"repo_id": "overleaf",
"token_count": 2641
} | 532 |
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.directive('toggleSwitch', () => ({
restrict: 'E',
scope: {
description: '@',
labelFalse: '@',
labelTrue: '@',
ngModel: '=',
},
template: `\
<fieldset class="toggle-switch">
<legend class="sr-only">{{description}}</legend>
<input
type="radio"
name="toggle-switch-{{$id}}"
class="toggle-switch-input"
id="toggle-switch-false-{{$id}}"
ng-value="false"
ng-model="ngModel"
>
<label for="toggle-switch-false-{{$id}}" class="toggle-switch-label">{{labelFalse}}</label>
<input
type="radio"
class="toggle-switch-input"
name="toggle-switch-{{$id}}"
id="toggle-switch-true-{{$id}}"
ng-value="true"
ng-model="ngModel"
>
<label for="toggle-switch-true-{{$id}}" class="toggle-switch-label">{{labelTrue}}</label>
<span class="toggle-switch-selection" aria-hidden="true"></span>
</fieldset>\
`,
}))
| overleaf/web/frontend/js/ide/editor/directives/toggleSwitch.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/toggleSwitch.js",
"repo_id": "overleaf",
"token_count": 469
} | 533 |
import _ from 'lodash'
// 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'
const historyFileTreeController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.handleEntityClick = file => ctrl.onSelectedFileChange({ file })
ctrl._fileTree = []
$scope.$watch('$ctrl.files', function (files) {
if (files != null && files.length > 0) {
ctrl._fileTree = _.reduce(files, _reducePathsToTree, [])
}
})
function _reducePathsToTree(currentFileTree, fileObject) {
const filePathParts = fileObject.pathname.split('/')
let currentFileTreeLocation = currentFileTree
for (let index = 0; index < filePathParts.length; index++) {
var fileTreeEntity
var pathPart = filePathParts[index]
const isFile = index === filePathParts.length - 1
if (isFile) {
fileTreeEntity = _.clone(fileObject)
fileTreeEntity.name = pathPart
fileTreeEntity.type = 'file'
currentFileTreeLocation.push(fileTreeEntity)
} else {
fileTreeEntity = _.find(
currentFileTreeLocation,
entity => entity.name === pathPart
)
if (fileTreeEntity == null) {
fileTreeEntity = {
name: pathPart,
type: 'folder',
children: [],
}
currentFileTreeLocation.push(fileTreeEntity)
}
currentFileTreeLocation = fileTreeEntity.children
}
}
return currentFileTree
}
}
export default App.component('historyFileTree', {
bindings: {
files: '<',
selectedPathname: '<',
onSelectedFileChange: '&',
isLoading: '<',
},
controller: historyFileTreeController,
templateUrl: 'historyFileTreeTpl',
})
| overleaf/web/frontend/js/ide/history/components/historyFileTree.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/components/historyFileTree.js",
"repo_id": "overleaf",
"token_count": 752
} | 534 |
/* eslint-disable
node/handle-callback-err,
max-len,
new-cap,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
import PDFJS from './pdfJsLoader'
import { captureMessage } from '../../../infrastructure/error-reporter'
export default App.factory(
'PDFRenderer',
function ($timeout, pdfAnnotations, pdfTextLayer, pdfSpinner) {
let PDFRenderer
return (PDFRenderer = (function () {
PDFRenderer = class PDFRenderer {
static initClass() {
this.prototype.JOB_QUEUE_INTERVAL = 25
this.prototype.PAGE_LOAD_TIMEOUT = 60 * 1000
this.prototype.INDICATOR_DELAY1 = 100 // time to delay before showing the indicator
this.prototype.INDICATOR_DELAY2 = 250 // time until the indicator starts animating
this.prototype.TEXTLAYER_TIMEOUT = 100
}
constructor(url, options) {
// set up external character mappings - needed for Japanese etc
this.url = url
this.options = options
this.scale = this.options.scale || 1
let disableFontFace
if (
__guard__(
window.location != null ? window.location.search : undefined,
x => x.indexOf('disable-font-face=true')
) >= 0
) {
disableFontFace = true
} else {
disableFontFace = false
}
this.pdfjs = PDFJS.getDocument({
url: this.url,
cMapUrl: window.pdfCMapsPath,
cMapPacked: true,
disableFontFace,
// Enable fetching with Range headers to restrict individual
// requests to 128kb.
// To do this correctly we must:
// a) disable auto-fetching of the whole file upfront
// b) disable streaming (which in this context means streaming of
// the response into memory). This isn't supported when using
// Range headers, but shouldn't be a problem since we are already
// limiting individual response size through chunked range
// requests
rangeChunkSize: 128 * 1024,
disableAutoFetch: !!this.options.disableAutoFetch,
disableStream: !!this.options.disableAutoFetch,
})
this.errorCallback = this.options.errorCallback
this.pageSizeChangeCallback = this.options.pageSizeChangeCallback
this.pdfjs.onProgress = this.options.progressCallback
this.document = this.pdfjs
this.navigateFn = this.options.navigateFn
this.spinner = new pdfSpinner()
this.resetState()
this.document.promise
.then(pdfDocument => {
return pdfDocument.getDownloadInfo().then(() => {
return this.options.loadedCallback()
})
})
.catch(exception => {
// error getting document
return this.errorCallback(exception)
})
}
resetState() {
this.renderQueue = []
if (this.queueTimer != null) {
clearTimeout(this.queueTimer)
}
// clear any existing timers, render tasks
for (const timer of Array.from(this.spinTimer || [])) {
clearTimeout(timer)
}
for (const page of Array.from(this.pageState || [])) {
__guard__(page != null ? page.loadTask : undefined, x => x.cancel())
__guard__(page != null ? page.renderTask : undefined, x1 =>
x1.cancel()
)
}
// initialise/reset the state
this.pageState = []
this.spinTimer = [] // timers for starting the spinners (to avoid jitter)
this.spinTimerDone = [] // array of pages where the spinner has activated
return (this.jobs = 0)
}
getNumPages() {
return this.document.promise.then(pdfDocument => pdfDocument.numPages)
}
getPage(pageNum) {
return this.document.promise.then(pdfDocument =>
pdfDocument.getPage(pageNum)
)
}
getPdfViewport(pageNum, scale) {
if (scale == null) {
;({ scale } = this)
}
return this.document.promise.then(pdfDocument => {
return pdfDocument.getPage(pageNum).then(
function (page) {
let viewport
return (viewport = page.getViewport({ scale: scale }))
},
error => {
return typeof this.errorCallback === 'function'
? this.errorCallback(error)
: undefined
}
)
})
}
getDestinations() {
return this.document.promise.then(pdfDocument =>
pdfDocument.getDestinations()
)
}
getDestination(dest) {
return this.document.promise.then(
pdfDocument => pdfDocument.getDestination(dest),
error => {
return typeof this.errorCallback === 'function'
? this.errorCallback(error)
: undefined
}
)
}
getPageIndex(ref) {
return this.document.promise.then(pdfDocument => {
return pdfDocument.getPageIndex(ref).then(
idx => idx,
error => {
return typeof this.errorCallback === 'function'
? this.errorCallback(error)
: undefined
}
)
})
}
getScale() {
return this.scale
}
setScale(scale) {
this.scale = scale
return this.resetState()
}
triggerRenderQueue(interval) {
if (interval == null) {
interval = this.JOB_QUEUE_INTERVAL
}
if (this.queueTimer != null) {
clearTimeout(this.queueTimer)
}
return (this.queueTimer = setTimeout(() => {
this.queueTimer = null
return this.processRenderQueue()
}, interval))
}
removeCompletedJob(pagenum) {
this.jobs = this.jobs - 1
return this.triggerRenderQueue(0)
}
renderPages(pages) {
if (this.shuttingDown) {
return
}
this.renderQueue = Array.from(pages).map(page => ({
element: page.elementChildren,
pagenum: page.pageNum,
}))
return this.triggerRenderQueue()
}
renderPage(page) {
if (this.shuttingDown) {
return
}
const current = {
element: page.elementChildren,
pagenum: page.pageNum,
}
this.renderQueue.push(current)
return this.processRenderQueue()
}
getPageDetails(page) {
return [page.element.canvas, page.pagenum]
}
// handle the loading indicators for each page
startIndicators() {
// make an array of the pages in the queue
this.queuedPages = []
for (var page of Array.from(this.renderQueue)) {
this.queuedPages[page.pagenum] = true
}
// clear any unfinished spinner timers on pages that aren't in the queue any more
for (const pagenum in this.spinTimer) {
if (!this.queuedPages[pagenum]) {
clearTimeout(this.spinTimer[pagenum])
delete this.spinTimer[pagenum]
}
}
// add indicators for any new pages in the current queue
return (() => {
const result = []
for (page of Array.from(this.renderQueue)) {
if (
!this.spinTimer[page.pagenum] &&
!this.spinTimerDone[page.pagenum]
) {
result.push(this.startIndicator(page))
}
}
return result
})()
}
startIndicator(page) {
const [canvas, pagenum] = Array.from(this.getPageDetails(page))
canvas.addClass('pdfng-loading')
return (this.spinTimer[pagenum] = setTimeout(() => {
for (const queuedPage of Array.from(this.renderQueue)) {
if (pagenum === queuedPage.pagenum) {
this.spinner.add(canvas, { static: true })
this.spinTimerDone[pagenum] = true
break
}
}
return delete this.spinTimer[pagenum]
}, this.INDICATOR_DELAY1))
}
updateIndicator(page) {
const [canvas, pagenum] = Array.from(this.getPageDetails(page))
// did the spinner insert itself already?
if (this.spinTimerDone[pagenum]) {
return (this.spinTimer[pagenum] = setTimeout(() => {
this.spinner.start(canvas)
return delete this.spinTimer[pagenum]
}, this.INDICATOR_DELAY2))
} else {
// stop the existing spin timer
clearTimeout(this.spinTimer[pagenum])
// start a new one which will also start spinning
return (this.spinTimer[pagenum] = setTimeout(() => {
this.spinner.add(canvas, { static: true })
this.spinTimerDone[pagenum] = true
return (this.spinTimer[pagenum] = setTimeout(() => {
this.spinner.start(canvas)
return delete this.spinTimer[pagenum]
}, this.INDICATOR_DELAY2))
}, this.INDICATOR_DELAY1))
}
}
clearIndicator(page) {
const [canvas, pagenum] = Array.from(this.getPageDetails(page))
this.spinner.stop(canvas)
clearTimeout(this.spinTimer[pagenum])
delete this.spinTimer[pagenum]
return (this.spinTimerDone[pagenum] = true)
}
// handle the queue of pages to be rendered
processRenderQueue() {
let pageState
if (this.shuttingDown) {
return
}
// mark all pages in the queue as loading
this.startIndicators()
// bail out if there is already a render job running
if (this.jobs > 0) {
return
}
// take the first page in the queue
let page = this.renderQueue.shift()
// check if it is in action already
while (page != null && this.pageState[page.pagenum] != null) {
page = this.renderQueue.shift()
}
if (page == null) {
return
}
const [element, pagenum] = Array.from([page.element, page.pagenum])
this.jobs = this.jobs + 1
// update the spinner to make it spinning (signifies loading has begun)
this.updateIndicator(page)
let timedOut = false
const timer = $timeout(() => {
// page load timed out
if (loadTask.cancelled) {
return
} // return from cancelled page load
captureMessage(
`pdfng page load timed out after ${this.PAGE_LOAD_TIMEOUT}ms`
)
timedOut = true
this.clearIndicator(page)
// @jobs = @jobs - 1
// @triggerRenderQueue(0)
return typeof this.errorCallback === 'function'
? this.errorCallback('timeout')
: undefined
}, this.PAGE_LOAD_TIMEOUT)
var loadTask = this.getPage(pagenum)
loadTask.cancel = function () {
return (this.cancelled = true)
}
this.pageState[pagenum] = pageState = { loadTask }
return loadTask
.then(pageObject => {
// page load success
$timeout.cancel(timer)
if (loadTask.cancelled) {
return
} // return from cancelled page load
const timePDFFetched = performance.now()
const visible = !document.hidden
if (!visible) {
// Flush the fetch time early, omit the render time.
if (typeof this.options.firstRenderDone === 'function') {
this.options.firstRenderDone({ timePDFFetched })
// Do not submit the actual rendering time.
this.options.firstRenderDone = null
}
}
pageState.renderTask = this.doRender(element, pagenum, pageObject)
return pageState.renderTask.promise.then(
() => {
if (typeof this.options.firstRenderDone === 'function') {
const timePDFRendered = performance.now()
this.options.firstRenderDone({
timePDFFetched,
timePDFRendered,
})
// The rendering pipeline is processed repeatedly, skip the next ones.
this.options.firstRenderDone = null
}
// render task success
this.clearIndicator(page)
pageState.complete = true
delete pageState.renderTask
return this.removeCompletedJob(pagenum)
},
() => {
// render task failed
// could display an error icon
pageState.complete = false
delete pageState.renderTask
return this.removeCompletedJob(pagenum)
}
)
})
.catch(error => {
// page load error
$timeout.cancel(timer)
return this.clearIndicator(page)
})
}
doRender(element, pagenum, page) {
const self = this
const { scale } = this
if (scale == null) {
// scale is undefined, returning
return
}
const canvas = $(
'<canvas class="pdf-canvas pdfng-rendering"></canvas>'
)
// In Windows+IE we must have the canvas in the DOM during
// rendering to see the fonts defined in the DOM. If we try to
// render 'offscreen' then all the text will be sans-serif.
// Previously we rendered offscreen and added in the canvas
// when rendering was complete.
element.canvas.replaceWith(canvas)
const viewport = page.getViewport({ scale: scale })
const devicePixelRatio = window.devicePixelRatio || 1
const ctx = canvas[0].getContext('2d')
const backingStoreRatio =
ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio ||
1
const pixelRatio = devicePixelRatio / backingStoreRatio
const scaledWidth = (Math.floor(viewport.width) * pixelRatio) | 0
const scaledHeight = (Math.floor(viewport.height) * pixelRatio) | 0
const newWidth = Math.floor(viewport.width)
const newHeight = Math.floor(viewport.height)
canvas[0].height = scaledHeight
canvas[0].width = scaledWidth
canvas.height(newHeight + 'px')
canvas.width(newWidth + 'px')
const oldHeight = element.canvas.height()
const oldWidth = element.canvas.width()
if (newHeight !== oldHeight || newWidth !== oldWidth) {
element.canvas.height(newHeight + 'px')
element.canvas.width(newWidth + 'px')
element.container.height(newHeight + 'px')
element.container.width(newWidth + 'px')
if (typeof this.pageSizeChangeCallback === 'function') {
this.pageSizeChangeCallback(pagenum, newHeight - oldHeight)
}
}
const textLayer = new pdfTextLayer({
textLayerDiv: element.text[0],
viewport,
renderer: PDFJS.renderTextLayer,
})
const annotationsLayer = new pdfAnnotations({
annotations: element.annotations[0],
viewport,
navigateFn: this.navigateFn,
})
const result = page.render({
canvasContext: ctx,
viewport,
transform: [pixelRatio, 0, 0, pixelRatio, 0, 0],
})
const textLayerTimeout = this.TEXTLAYER_TIMEOUT
result.promise
.then(function () {
// page render success
canvas.removeClass('pdfng-rendering')
page.getTextContent({ normalizeWhitespace: true }).then(
function (textContent) {
textLayer.setTextContent(textContent)
return textLayer.render(textLayerTimeout)
},
error =>
typeof self.errorCallback === 'function'
? self.errorCallback(error)
: undefined
)
return page.getAnnotations().then(
annotations => annotationsLayer.setAnnotations(annotations),
error =>
typeof self.errorCallback === 'function'
? self.errorCallback(error)
: undefined
)
})
.catch(function (error) {
// page render failed
if (error.name === 'RenderingCancelledException') {
// do nothing when cancelled
} else {
return typeof self.errorCallback === 'function'
? self.errorCallback(error)
: undefined
}
})
return result
}
destroy() {
this.shuttingDown = true
this.resetState()
return this.pdfjs.promise
.then(function (document) {
document.cleanup()
return document.destroy()
})
.catch(() => {})
}
}
PDFRenderer.initClass()
return PDFRenderer
})())
}
)
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
function __guardMethod__(obj, methodName, transform) {
if (
typeof obj !== 'undefined' &&
obj !== null &&
typeof obj[methodName] === 'function'
) {
return transform(obj, methodName)
} else {
return undefined
}
}
| overleaf/web/frontend/js/ide/pdfng/directives/pdfRenderer.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/pdfng/directives/pdfRenderer.js",
"repo_id": "overleaf",
"token_count": 9381
} | 535 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.directive('changeEntry', $timeout => ({
restrict: 'E',
templateUrl: 'changeEntryTemplate',
scope: {
entry: '=',
user: '=',
permissions: '=',
onAccept: '&',
onReject: '&',
onIndicatorClick: '&',
onBodyClick: '&',
},
link(scope, element, attrs) {
scope.contentLimit = 40
scope.isCollapsed = true
scope.needsCollapsing = false
element.on('click', function (e) {
if (
$(e.target).is(
'.rp-entry, .rp-entry-description, .rp-entry-body, .rp-entry-action-icon i'
)
) {
return scope.onBodyClick()
}
})
scope.toggleCollapse = function () {
scope.isCollapsed = !scope.isCollapsed
return $timeout(() => scope.$emit('review-panel:layout'))
}
return scope.$watch(
'entry.content.length',
contentLength =>
(scope.needsCollapsing = contentLength > scope.contentLimit)
)
},
}))
| overleaf/web/frontend/js/ide/review-panel/directives/changeEntry.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/directives/changeEntry.js",
"repo_id": "overleaf",
"token_count": 529
} | 536 |
import { captureException } from './error-reporter'
import { ErrorBoundary } from 'react-error-boundary'
function errorHandler(error, componentStack) {
captureException(error, scope => {
scope.setExtra('componentStack', componentStack)
scope.setTag('handler', 'react-error-boundary')
return scope
})
}
function DefaultFallbackComponent() {
return <></>
}
function withErrorBoundary(WrappedComponent, FallbackComponent) {
function ErrorBoundaryWrapper(props) {
return (
<ErrorBoundary
FallbackComponent={FallbackComponent || DefaultFallbackComponent}
onError={errorHandler}
>
<WrappedComponent {...props} />
</ErrorBoundary>
)
}
ErrorBoundaryWrapper.propTypes = WrappedComponent.propTypes
ErrorBoundaryWrapper.displayName = `WithErrorBoundaryWrapper${
WrappedComponent.displayName || WrappedComponent.name || 'Component'
}`
return ErrorBoundaryWrapper
}
export default withErrorBoundary
| overleaf/web/frontend/js/infrastructure/error-boundary.js/0 | {
"file_path": "overleaf/web/frontend/js/infrastructure/error-boundary.js",
"repo_id": "overleaf",
"token_count": 317
} | 537 |
import _ from 'lodash'
import App from '../../../base'
import getMeta from '../../../utils/meta'
export default App.controller(
'UserAffiliationsReconfirmController',
function ($scope, $http, $window) {
const samlInitPath = ExposedSettings.samlInitPath
$scope.reconfirm = {}
$scope.ui = $scope.ui || {} // $scope.ui inherited on settings page
$scope.userEmails = getMeta('ol-userEmails')
$scope.reconfirmedViaSAML = getMeta('ol-reconfirmedViaSAML')
// For portals:
const portalAffiliation = getMeta('ol-portalAffiliation')
if (portalAffiliation) {
$scope.portalInReconfirmNotificationPeriod =
portalAffiliation && portalAffiliation.inReconfirmNotificationPeriod
$scope.userEmail = $scope.portalInReconfirmNotificationPeriod // mixin to show notification uses userEmail
}
// For settings page:
$scope.reconfirmationRemoveEmail = getMeta('ol-reconfirmationRemoveEmail')
// For dashboard:
$scope.allInReconfirmNotificationPeriods = getMeta(
'ol-allInReconfirmNotificationPeriods'
)
function sendReconfirmEmail(email) {
$scope.ui.hasError = false
$scope.ui.isMakingRequest = true
$http
.post('/user/emails/send-reconfirmation', {
email,
_csrf: window.csrfToken,
})
.then(() => {
$scope.reconfirm[email].reconfirmationSent = true
})
.catch(error => {
$scope.ui.hasError = true
})
.finally(() => ($scope.ui.isMakingRequest = false))
}
$scope.requestReconfirmation = function (obj, userEmail) {
const email = userEmail.email
// For the settings page, disable other parts of affiliation UI
$scope.ui.isMakingRequest = true
$scope.ui.isProcessing = true
// create UI scope for requested email
$scope.reconfirm[email] = $scope.reconfirm[email] || {} // keep existing scope for resend email requests
const location = obj.currentTarget.getAttribute('data-location')
const institutionId = _.get(userEmail, [
'affiliation',
'institution',
'id',
])
const ssoEnabled = _.get(userEmail, [
'affiliation',
'institution',
'ssoEnabled',
])
if (ssoEnabled) {
$window.location.href = `${samlInitPath}?university_id=${institutionId}&reconfirm=${location}`
} else {
sendReconfirmEmail(email)
}
}
}
)
| overleaf/web/frontend/js/main/affiliations/controllers/UserAffiliationsReconfirmController.js/0 | {
"file_path": "overleaf/web/frontend/js/main/affiliations/controllers/UserAffiliationsReconfirmController.js",
"repo_id": "overleaf",
"token_count": 992
} | 538 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../base'
App.controller(
'RenameProjectModalController',
function ($scope, $modalInstance, $timeout, project, queuedHttp) {
$scope.inputs = { projectName: project.name }
$scope.state = {
inflight: false,
error: false,
}
$modalInstance.opened.then(() =>
$timeout(() => $scope.$broadcast('open'), 200)
)
$scope.rename = function () {
$scope.state.inflight = true
$scope.state.error = false
return $scope
.renameProject(project, $scope.inputs.projectName)
.then(function () {
$scope.state.inflight = false
$scope.state.error = false
return $modalInstance.close()
})
.catch(function (response) {
const { data, status } = response
$scope.state.inflight = false
if (status === 400) {
return ($scope.state.error = { message: data })
} else {
return ($scope.state.error = true)
}
})
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
App.controller(
'CloneProjectModalController',
function ($scope, $modalInstance, $timeout, project) {
$scope.inputs = { projectName: project.name + ' (Copy)' }
$scope.state = {
inflight: false,
error: false,
}
$modalInstance.opened.then(() =>
$timeout(() => $scope.$broadcast('open'), 200)
)
$scope.clone = function () {
$scope.state.inflight = true
return $scope
.cloneProject(project, $scope.inputs.projectName)
.then(function () {
$scope.state.inflight = false
$scope.state.error = false
return $modalInstance.close()
})
.catch(function (response) {
const { data, status } = response
$scope.state.inflight = false
if (status === 400) {
return ($scope.state.error = { message: data })
} else {
return ($scope.state.error = true)
}
})
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
App.controller(
'NewProjectModalController',
function ($scope, $modalInstance, $timeout, template) {
$scope.inputs = { projectName: '' }
$scope.state = {
inflight: false,
error: false,
}
$modalInstance.opened.then(() =>
$timeout(() => $scope.$broadcast('open'), 200)
)
$scope.create = function () {
$scope.state.inflight = true
$scope.state.error = false
return $scope
.createProject($scope.inputs.projectName, template)
.then(function (response) {
const { data } = response
$scope.state.inflight = false
$scope.state.error = false
return $modalInstance.close(data.project_id)
})
.catch(function (response) {
const { data, status } = response
$scope.state.inflight = false
if (status === 400) {
return ($scope.state.error = { message: data })
} else {
return ($scope.state.error = true)
}
})
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
App.controller(
'ArchiveTrashLeaveOrDeleteProjectsModalController',
function ($scope, $modalInstance, $timeout, projects, action) {
$scope.projects = projects
$scope.action = action
$scope.confirm = () => $modalInstance.close({ projects, action })
$scope.cancel = () => $modalInstance.dismiss('cancel')
}
)
App.controller(
'UploadProjectModalController',
function ($scope, $modalInstance, $timeout) {
$scope.cancel = () => $modalInstance.dismiss('cancel')
return ($scope.onComplete = function (error, name, response) {
if (response.project_id != null) {
return (window.location = `/project/${response.project_id}`)
}
})
}
)
App.controller(
'V1ImportModalController',
function ($scope, $modalInstance, project) {
$scope.project = project
return ($scope.dismiss = () => $modalInstance.dismiss('cancel'))
}
)
export default App.controller(
'ShowErrorModalController',
function ($scope, $modalInstance, error) {
$scope.error = error
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
| overleaf/web/frontend/js/main/project-list/modal-controllers.js/0 | {
"file_path": "overleaf/web/frontend/js/main/project-list/modal-controllers.js",
"repo_id": "overleaf",
"token_count": 1946
} | 539 |
/* 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
*/
//
// * An Angular service which helps with creating recursive directives.
// * @author Mark Lagendijk
// * @license MIT
//
// From: https://github.com/marklagendijk/angular-recursion
/* 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
*/
//
// * An Angular service which helps with creating recursive directives.
// * @author Mark Lagendijk
// * @license MIT
//
// From: https://github.com/marklagendijk/angular-recursion
angular.module('RecursionHelper', []).factory('RecursionHelper', [
'$compile',
function ($compile) {
/*
Manually compiles the element, fixing the recursion loop.
@param element
@param [link] A post-link function, or an object with function(s) registered via pre and post properties.
@returns An object containing the linking functions.
*/
return {
compile(element, link) {
// Normalize the link parameter
if (angular.isFunction(link)) {
link = { post: link }
}
// Break the recursion loop by removing the contents
const contents = element.contents().remove()
let compiledContents
return {
pre: link && link.pre ? link.pre : null,
/*
Compiles and re-adds the contents
*/
post(scope, element) {
// Compile the contents
if (!compiledContents) {
compiledContents = $compile(contents)
}
// Re-add the compiled contents to the element
compiledContents(scope, function (clone) {
element.append(clone)
})
// Call the post-linking function, if any
if (link && link.post) {
link.post.apply(null, arguments)
}
},
}
},
}
},
])
| overleaf/web/frontend/js/modules/recursionHelper.js/0 | {
"file_path": "overleaf/web/frontend/js/modules/recursionHelper.js",
"repo_id": "overleaf",
"token_count": 894
} | 540 |
import PropTypes from 'prop-types'
import { Button, Tooltip, OverlayTrigger } from 'react-bootstrap'
function TooltipButton({ id, description, onClick, children }) {
const tooltip = <Tooltip id={`${id}_tooltip`}>{description}</Tooltip>
return (
<OverlayTrigger placement="bottom" overlay={tooltip}>
<Button onClick={onClick}>{children}</Button>
</OverlayTrigger>
)
}
TooltipButton.propTypes = {
id: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
onClick: PropTypes.func,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]),
}
export default TooltipButton
| overleaf/web/frontend/js/shared/components/tooltip-button.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/components/tooltip-button.js",
"repo_id": "overleaf",
"token_count": 222
} | 541 |
import { useState, useCallback } from 'react'
import localStorage from '../../infrastructure/local-storage'
function usePersistedState(key, defaultValue) {
const [value, setValue] = useState(() => {
const keyExists = localStorage.getItem(key) != null
return keyExists ? localStorage.getItem(key) : defaultValue
})
const updateFunction = useCallback(
newValue => {
if (newValue === defaultValue) {
localStorage.removeItem(key)
} else {
localStorage.setItem(key, newValue)
}
setValue(newValue)
},
[key, defaultValue]
)
return [value, updateFunction]
}
export default usePersistedState
| overleaf/web/frontend/js/shared/hooks/use-persisted-state.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/hooks/use-persisted-state.js",
"repo_id": "overleaf",
"token_count": 232
} | 542 |
/**
* ng-context-menu - v0.1.4 - An AngularJS directive to display a context menu when a right-click event is triggered
*
* @author Ian Kennington Walter (http://ianvonwalter.com)
*/
angular
.module('ng-context-menu', [])
.factory('ContextMenuService', function() {
return {
element: null,
menuElement: null,
container: null
};
})
.directive('contextMenu', ['$document', 'ContextMenuService', function($document, ContextMenuService) {
return {
restrict: 'A',
scope: {
'callback': '&contextMenu',
'disabled': '&contextMenuDisabled'
},
link: function($scope, $element, $attrs) {
var opened = false;
function open(event, menuElement, container) {
menuElement.addClass('open');
if (container) {
container.append(menuElement);
}
var doc = $document[0].documentElement;
var docLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
docTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0),
elementHeight = menuElement[0].scrollHeight;
var docHeight = doc.clientHeight + docTop,
totalHeight = elementHeight + event.pageY,
top = Math.max(event.pageY - docTop, 0);
if (totalHeight > docHeight) {
top = top - (totalHeight - docHeight);
}
menuElement.css('top', top + 'px');
menuElement.css('left', Math.max(event.pageX - docLeft, 0) + 'px');
opened = true;
}
function close(menuElement) {
menuElement.removeClass('open');
opened = false;
}
$element.bind('contextmenu', function(event) {
if (!$scope.disabled()) {
if (ContextMenuService.menuElement !== null) {
close(ContextMenuService.menuElement);
}
ContextMenuService.menuElement = angular.element(document.getElementById($attrs.target));
if (typeof($attrs.contextMenuContainer) != "undefined") {
ContextMenuService.container = angular.element($attrs.contextMenuContainer)
}
ContextMenuService.element = event.target;
// console.log('set', ContextMenuService.element);
event.preventDefault();
event.stopPropagation();
$scope.$apply(function() {
$scope.callback({ $event: event });
open(event, ContextMenuService.menuElement, ContextMenuService.container);
});
}
});
function handleKeyUpEvent(event) {
//console.log('keyup');
if (!$scope.disabled() && opened && event.keyCode === 27) {
$scope.$apply(function() {
close(ContextMenuService.menuElement);
});
}
}
function handleClickEvent(event) {
if (!$scope.disabled() &&
opened &&
(event.button !== 2 || event.target !== ContextMenuService.element)) {
$scope.$apply(function() {
close(ContextMenuService.menuElement);
});
}
}
$document.bind('keyup', handleKeyUpEvent);
// Firefox treats a right-click as a click and a contextmenu event while other browsers
// just treat it as a contextmenu event
$document.bind('click', handleClickEvent);
$document.bind('contextmenu', handleClickEvent);
$scope.$on('$destroy', function() {
//console.log('destroy');
$document.unbind('keyup', handleKeyUpEvent);
$document.unbind('click', handleClickEvent);
$document.unbind('contextmenu', handleClickEvent);
});
}
};
}]);
| overleaf/web/frontend/js/vendor/libs/ng-context-menu-0.1.4.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/ng-context-menu-0.1.4.js",
"repo_id": "overleaf",
"token_count": 1643
} | 543 |
;(function(undefined) {
'use strict';
var __instances = {};
/**
* This is the sigma instances constructor. One instance of sigma represent
* one graph. It is possible to represent this grapĥ with several renderers
* at the same time. By default, the default renderer (WebGL + Canvas
* polyfill) will be used as the only renderer, with the container specified
* in the configuration.
*
* @param {?*} conf The configuration of the instance. There are a lot of
* different recognized forms to instantiate sigma, check
* example files, documentation in this file and unit
* tests to know more.
* @return {sigma} The fresh new sigma instance.
*
* Instanciating sigma:
* ********************
* If no parameter is given to the constructor, the instance will be created
* without any renderer or camera. It will just instantiate the graph, and
* other modules will have to be instantiated through the public methods,
* like "addRenderer" etc:
*
* > s0 = new sigma();
* > s0.addRenderer({
* > type: 'canvas',
* > container: 'my-container-id'
* > });
*
* In most of the cases, sigma will simply be used with the default renderer.
* Then, since the only required parameter is the DOM container, there are
* some simpler way to call the constructor. The four following calls do the
* exact same things:
*
* > s1 = new sigma('my-container-id');
* > s2 = new sigma(document.getElementById('my-container-id'));
* > s3 = new sigma({
* > container: document.getElementById('my-container-id')
* > });
* > s4 = new sigma({
* > renderers: [{
* > container: document.getElementById('my-container-id')
* > }]
* > });
*
* Recognized parameters:
* **********************
* Here is the exhaustive list of every accepted parameters, when calling the
* constructor with to top level configuration object (fourth case in the
* previous examples):
*
* {?string} id The id of the instance. It will be generated
* automatically if not specified.
* {?array} renderers An array containing objects describing renderers.
* {?object} graph An object containing an array of nodes and an array
* of edges, to avoid having to add them by hand later.
* {?object} settings An object containing instance specific settings that
* will override the default ones defined in the object
* sigma.settings.
*/
var sigma = function(conf) {
// Local variables:
// ****************
var i,
l,
a,
c,
o,
id;
sigma.classes.dispatcher.extend(this);
// Private attributes:
// *******************
var _self = this,
_conf = conf || {};
// Little shortcut:
// ****************
// The configuration is supposed to have a list of the configuration
// objects for each renderer.
// - If there are no configuration at all, then nothing is done.
// - If there are no renderer list, the given configuration object will be
// considered as describing the first and only renderer.
// - If there are no renderer list nor "container" object, it will be
// considered as the container itself (a DOM element).
// - If the argument passed to sigma() is a string, it will be considered
// as the ID of the DOM container.
if (
typeof _conf === 'string' ||
_conf instanceof HTMLElement
)
_conf = {
renderers: [_conf]
};
else if (Object.prototype.toString.call(_conf) === '[object Array]')
_conf = {
renderers: _conf
};
// Also check "renderer" and "container" keys:
o = _conf.renderers || _conf.renderer || _conf.container;
if (!_conf.renderers || _conf.renderers.length === 0)
if (
typeof o === 'string' ||
o instanceof HTMLElement ||
(typeof o === 'object' && 'container' in o)
)
_conf.renderers = [o];
// Recense the instance:
if (_conf.id) {
if (__instances[_conf.id])
throw 'sigma: Instance "' + _conf.id + '" already exists.';
Object.defineProperty(this, 'id', {
value: _conf.id
});
} else {
id = 0;
while (__instances[id])
id++;
Object.defineProperty(this, 'id', {
value: '' + id
});
}
__instances[this.id] = this;
// Initialize settings function:
this.settings = new sigma.classes.configurable(
sigma.settings,
_conf.settings || {}
);
// Initialize locked attributes:
Object.defineProperty(this, 'graph', {
value: new sigma.classes.graph(this.settings),
configurable: true
});
Object.defineProperty(this, 'middlewares', {
value: [],
configurable: true
});
Object.defineProperty(this, 'cameras', {
value: {},
configurable: true
});
Object.defineProperty(this, 'renderers', {
value: {},
configurable: true
});
Object.defineProperty(this, 'renderersPerCamera', {
value: {},
configurable: true
});
Object.defineProperty(this, 'cameraFrames', {
value: {},
configurable: true
});
Object.defineProperty(this, 'camera', {
get: function() {
return this.cameras[0];
}
});
Object.defineProperty(this, 'events', {
value: [
'click',
'rightClick',
'clickStage',
'doubleClickStage',
'rightClickStage',
'clickNode',
'clickNodes',
'doubleClickNode',
'doubleClickNodes',
'rightClickNode',
'rightClickNodes',
'overNode',
'overNodes',
'outNode',
'outNodes',
'downNode',
'downNodes',
'upNode',
'upNodes'
],
configurable: true
});
// Add a custom handler, to redispatch events from renderers:
this._handler = (function(e) {
var k,
data = {};
for (k in e.data)
data[k] = e.data[k];
data.renderer = e.target;
this.dispatchEvent(e.type, data);
}).bind(this);
// Initialize renderers:
a = _conf.renderers || [];
for (i = 0, l = a.length; i < l; i++)
this.addRenderer(a[i]);
// Initialize middlewares:
a = _conf.middlewares || [];
for (i = 0, l = a.length; i < l; i++)
this.middlewares.push(
typeof a[i] === 'string' ?
sigma.middlewares[a[i]] :
a[i]
);
// Check if there is already a graph to fill in:
if (typeof _conf.graph === 'object' && _conf.graph) {
this.graph.read(_conf.graph);
// If a graph is given to the to the instance, the "refresh" method is
// directly called:
this.refresh();
}
// Deal with resize:
window.addEventListener('resize', function() {
if (_self.settings)
_self.refresh();
});
};
/**
* This methods will instantiate and reference a new camera. If no id is
* specified, then an automatic id will be generated.
*
* @param {?string} id Eventually the camera id.
* @return {sigma.classes.camera} The fresh new camera instance.
*/
sigma.prototype.addCamera = function(id) {
var self = this,
camera;
if (!arguments.length) {
id = 0;
while (this.cameras['' + id])
id++;
id = '' + id;
}
if (this.cameras[id])
throw 'sigma.addCamera: The camera "' + id + '" already exists.';
camera = new sigma.classes.camera(id, this.graph, this.settings);
this.cameras[id] = camera;
// Add a quadtree to the camera:
camera.quadtree = new sigma.classes.quad();
// Add an edgequadtree to the camera:
if (sigma.classes.edgequad !== undefined) {
camera.edgequadtree = new sigma.classes.edgequad();
}
camera.bind('coordinatesUpdated', function(e) {
self.renderCamera(camera, camera.isAnimated);
});
this.renderersPerCamera[id] = [];
return camera;
};
/**
* This method kills a camera, and every renderer attached to it.
*
* @param {string|camera} v The camera to kill or its ID.
* @return {sigma} Returns the instance.
*/
sigma.prototype.killCamera = function(v) {
v = typeof v === 'string' ? this.cameras[v] : v;
if (!v)
throw 'sigma.killCamera: The camera is undefined.';
var i,
l,
a = this.renderersPerCamera[v.id];
for (l = a.length, i = l - 1; i >= 0; i--)
this.killRenderer(a[i]);
delete this.renderersPerCamera[v.id];
delete this.cameraFrames[v.id];
delete this.cameras[v.id];
if (v.kill)
v.kill();
return this;
};
/**
* This methods will instantiate and reference a new renderer. The "type"
* argument can be the constructor or its name in the "sigma.renderers"
* package. If no type is specified, then "sigma.renderers.def" will be used.
* If no id is specified, then an automatic id will be generated.
*
* @param {?object} options Eventually some options to give to the renderer
* constructor.
* @return {renderer} The fresh new renderer instance.
*
* Recognized parameters:
* **********************
* Here is the exhaustive list of every accepted parameters in the "options"
* object:
*
* {?string} id Eventually the renderer id.
* {?(function|string)} type Eventually the renderer constructor or its
* name in the "sigma.renderers" package.
* {?(camera|string)} camera Eventually the renderer camera or its
* id.
*/
sigma.prototype.addRenderer = function(options) {
var id,
fn,
camera,
renderer,
o = options || {};
// Polymorphism:
if (typeof o === 'string')
o = {
container: document.getElementById(o)
};
else if (o instanceof HTMLElement)
o = {
container: o
};
// If the container still is a string, we get it by id
if (typeof o.container === 'string')
o.container = document.getElementById(o.container);
// Reference the new renderer:
if (!('id' in o)) {
id = 0;
while (this.renderers['' + id])
id++;
id = '' + id;
} else
id = o.id;
if (this.renderers[id])
throw 'sigma.addRenderer: The renderer "' + id + '" already exists.';
// Find the good constructor:
fn = typeof o.type === 'function' ? o.type : sigma.renderers[o.type];
fn = fn || sigma.renderers.def;
// Find the good camera:
camera = 'camera' in o ?
(
o.camera instanceof sigma.classes.camera ?
o.camera :
this.cameras[o.camera] || this.addCamera(o.camera)
) :
this.addCamera();
if (this.cameras[camera.id] !== camera)
throw 'sigma.addRenderer: The camera is not properly referenced.';
// Instantiate:
renderer = new fn(this.graph, camera, this.settings, o);
this.renderers[id] = renderer;
Object.defineProperty(renderer, 'id', {
value: id
});
// Bind events:
if (renderer.bind)
renderer.bind(
[
'click',
'rightClick',
'clickStage',
'doubleClickStage',
'rightClickStage',
'clickNode',
'clickNodes',
'clickEdge',
'clickEdges',
'doubleClickNode',
'doubleClickNodes',
'doubleClickEdge',
'doubleClickEdges',
'rightClickNode',
'rightClickNodes',
'rightClickEdge',
'rightClickEdges',
'overNode',
'overNodes',
'overEdge',
'overEdges',
'outNode',
'outNodes',
'outEdge',
'outEdges',
'downNode',
'downNodes',
'downEdge',
'downEdges',
'upNode',
'upNodes',
'upEdge',
'upEdges'
],
this._handler
);
// Reference the renderer by its camera:
this.renderersPerCamera[camera.id].push(renderer);
return renderer;
};
/**
* This method kills a renderer.
*
* @param {string|renderer} v The renderer to kill or its ID.
* @return {sigma} Returns the instance.
*/
sigma.prototype.killRenderer = function(v) {
v = typeof v === 'string' ? this.renderers[v] : v;
if (!v)
throw 'sigma.killRenderer: The renderer is undefined.';
var a = this.renderersPerCamera[v.camera.id],
i = a.indexOf(v);
if (i >= 0)
a.splice(i, 1);
if (v.kill)
v.kill();
delete this.renderers[v.id];
return this;
};
/**
* This method calls the "render" method of each renderer, with the same
* arguments than the "render" method, but will also check if the renderer
* has a "process" method, and call it if it exists.
*
* It is useful for quadtrees or WebGL processing, for instance.
*
* @param {?object} options Eventually some options to give to the refresh
* method.
* @return {sigma} Returns the instance itself.
*
* Recognized parameters:
* **********************
* Here is the exhaustive list of every accepted parameters in the "options"
* object:
*
* {?boolean} skipIndexation A flag specifying wether or not the refresh
* function should reindex the graph in the
* quadtrees or not (default: false).
*/
sigma.prototype.refresh = function(options) {
var i,
l,
k,
a,
c,
bounds,
prefix = 0;
options = options || {};
// Call each middleware:
a = this.middlewares || [];
for (i = 0, l = a.length; i < l; i++)
a[i].call(
this,
(i === 0) ? '' : 'tmp' + prefix + ':',
(i === l - 1) ? 'ready:' : ('tmp' + (++prefix) + ':')
);
// Then, for each camera, call the "rescale" middleware, unless the
// settings specify not to:
for (k in this.cameras) {
c = this.cameras[k];
if (
c.settings('autoRescale') &&
this.renderersPerCamera[c.id] &&
this.renderersPerCamera[c.id].length
)
sigma.middlewares.rescale.call(
this,
a.length ? 'ready:' : '',
c.readPrefix,
{
width: this.renderersPerCamera[c.id][0].width,
height: this.renderersPerCamera[c.id][0].height
}
);
else
sigma.middlewares.copy.call(
this,
a.length ? 'ready:' : '',
c.readPrefix
);
if (!options.skipIndexation) {
// Find graph boundaries:
bounds = sigma.utils.getBoundaries(
this.graph,
c.readPrefix
);
// Refresh quadtree:
c.quadtree.index(this.graph.nodes(), {
prefix: c.readPrefix,
bounds: {
x: bounds.minX,
y: bounds.minY,
width: bounds.maxX - bounds.minX,
height: bounds.maxY - bounds.minY
}
});
// Refresh edgequadtree:
if (
c.edgequadtree !== undefined &&
c.settings('drawEdges') &&
c.settings('enableEdgeHovering')
) {
c.edgequadtree.index(this.graph, {
prefix: c.readPrefix,
bounds: {
x: bounds.minX,
y: bounds.minY,
width: bounds.maxX - bounds.minX,
height: bounds.maxY - bounds.minY
}
});
}
}
}
// Call each renderer:
a = Object.keys(this.renderers);
for (i = 0, l = a.length; i < l; i++)
if (this.renderers[a[i]].process) {
if (this.settings('skipErrors'))
try {
this.renderers[a[i]].process();
} catch (e) {
console.log(
'Warning: The renderer "' + a[i] + '" crashed on ".process()"'
);
}
else
this.renderers[a[i]].process();
}
this.render();
return this;
};
/**
* This method calls the "render" method of each renderer.
*
* @return {sigma} Returns the instance itself.
*/
sigma.prototype.render = function() {
var i,
l,
a,
prefix = 0;
// Call each renderer:
a = Object.keys(this.renderers);
for (i = 0, l = a.length; i < l; i++)
if (this.settings('skipErrors'))
try {
this.renderers[a[i]].render();
} catch (e) {
if (this.settings('verbose'))
console.log(
'Warning: The renderer "' + a[i] + '" crashed on ".render()"'
);
}
else
this.renderers[a[i]].render();
return this;
};
/**
* This method calls the "render" method of each renderer that is bound to
* the specified camera. To improve the performances, if this method is
* called too often, the number of effective renderings is limitated to one
* per frame, unless you are using the "force" flag.
*
* @param {sigma.classes.camera} camera The camera to render.
* @param {?boolean} force If true, will render the camera
* directly.
* @return {sigma} Returns the instance itself.
*/
sigma.prototype.renderCamera = function(camera, force) {
var i,
l,
a,
self = this;
if (force) {
a = this.renderersPerCamera[camera.id];
for (i = 0, l = a.length; i < l; i++)
if (this.settings('skipErrors'))
try {
a[i].render();
} catch (e) {
if (this.settings('verbose'))
console.log(
'Warning: The renderer "' + a[i].id + '" crashed on ".render()"'
);
}
else
a[i].render();
} else {
if (!this.cameraFrames[camera.id]) {
a = this.renderersPerCamera[camera.id];
for (i = 0, l = a.length; i < l; i++)
if (this.settings('skipErrors'))
try {
a[i].render();
} catch (e) {
if (this.settings('verbose'))
console.log(
'Warning: The renderer "' +
a[i].id +
'" crashed on ".render()"'
);
}
else
a[i].render();
this.cameraFrames[camera.id] = requestAnimationFrame(function() {
delete self.cameraFrames[camera.id];
});
}
}
return this;
};
/**
* This method calls the "kill" method of each module and destroys any
* reference from the instance.
*/
sigma.prototype.kill = function() {
var k;
// Dispatching event
this.dispatchEvent('kill');
// Kill graph:
this.graph.kill();
// Kill middlewares:
delete this.middlewares;
// Kill each renderer:
for (k in this.renderers)
this.killRenderer(this.renderers[k]);
// Kill each camera:
for (k in this.cameras)
this.killCamera(this.cameras[k]);
delete this.renderers;
delete this.cameras;
// Kill everything else:
for (k in this)
if (this.hasOwnProperty(k))
delete this[k];
delete __instances[this.id];
};
/**
* Returns a clone of the instances object or a specific running instance.
*
* @param {?string} id Eventually an instance ID.
* @return {object} The related instance or a clone of the instances
* object.
*/
sigma.instances = function(id) {
return arguments.length ?
__instances[id] :
sigma.utils.extend({}, __instances);
};
/**
* The current version of sigma:
*/
sigma.version = '1.0.3';
/**
* EXPORT:
* *******
*/
if (typeof this.sigma !== 'undefined')
throw 'An object called sigma is already in the global scope.';
this.sigma = sigma;
}).call(this);
/**
* conrad.js is a tiny JavaScript jobs scheduler,
*
* Version: 0.1.0
* Sources: http://github.com/jacomyal/conrad.js
* Doc: http://github.com/jacomyal/conrad.js#readme
*
* License:
* --------
* Copyright © 2013 Alexis Jacomy, Sciences-Po médialab
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising
* from, out of or in connection with the software or the use or other dealings
* in the Software.
*/
(function(global) {
'use strict';
// Check that conrad.js has not been loaded yet:
if (global.conrad)
throw new Error('conrad already exists');
/**
* PRIVATE VARIABLES:
* ******************
*/
/**
* A flag indicating whether conrad is running or not.
*
* @type {Number}
*/
var _lastFrameTime;
/**
* A flag indicating whether conrad is running or not.
*
* @type {Boolean}
*/
var _isRunning = false;
/**
* The hash of registered jobs. Each job must at least have a unique ID
* under the key "id" and a function under the key "job". This hash
* contains each running job and each waiting job.
*
* @type {Object}
*/
var _jobs = {};
/**
* The hash of currently running jobs.
*
* @type {Object}
*/
var _runningJobs = {};
/**
* The array of currently running jobs, sorted by priority.
*
* @type {Array}
*/
var _sortedByPriorityJobs = [];
/**
* The array of currently waiting jobs.
*
* @type {Object}
*/
var _waitingJobs = {};
/**
* The array of finished jobs. They are stored in an array, since two jobs
* with the same "id" can happen at two different times.
*
* @type {Array}
*/
var _doneJobs = [];
/**
* A dirty flag to keep conrad from starting: Indeed, when addJob() is called
* with several jobs, conrad must be started only at the end. This flag keeps
* me from duplicating the code that effectively adds a job.
*
* @type {Boolean}
*/
var _noStart = false;
/**
* An hash containing some global settings about how conrad.js should
* behave.
*
* @type {Object}
*/
var _parameters = {
frameDuration: 20,
history: true
};
/**
* This object contains every handlers bound to conrad events. It does not
* requirea any DOM implementation, since the events are all JavaScript.
*
* @type {Object}
*/
var _handlers = Object.create(null);
/**
* PRIVATE FUNCTIONS:
* ******************
*/
/**
* Will execute the handler everytime that the indicated event (or the
* indicated events) will be triggered.
*
* @param {string|array|object} events The name of the event (or the events
* separated by spaces).
* @param {function(Object)} handler The handler to bind.
* @return {Object} Returns conrad.
*/
function _bind(events, handler) {
var i,
i_end,
event,
eArray;
if (!arguments.length)
return;
else if (
arguments.length === 1 &&
Object(arguments[0]) === arguments[0]
)
for (events in arguments[0])
_bind(events, arguments[0][events]);
else if (arguments.length > 1) {
eArray =
Array.isArray(events) ?
events :
events.split(/ /);
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) {
event = eArray[i];
if (!_handlers[event])
_handlers[event] = [];
// Using an object instead of directly the handler will make possible
// later to add flags
_handlers[event].push({
handler: handler
});
}
}
}
/**
* Removes the handler from a specified event (or specified events).
*
* @param {?string} events The name of the event (or the events
* separated by spaces). If undefined,
* then all handlers are removed.
* @param {?function(Object)} handler The handler to unbind. If undefined,
* each handler bound to the event or the
* events will be removed.
* @return {Object} Returns conrad.
*/
function _unbind(events, handler) {
var i,
i_end,
j,
j_end,
a,
event,
eArray = Array.isArray(events) ?
events :
events.split(/ /);
if (!arguments.length)
_handlers = Object.create(null);
else if (handler) {
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) {
event = eArray[i];
if (_handlers[event]) {
a = [];
for (j = 0, j_end = _handlers[event].length; j !== j_end; j += 1)
if (_handlers[event][j].handler !== handler)
a.push(_handlers[event][j]);
_handlers[event] = a;
}
if (_handlers[event] && _handlers[event].length === 0)
delete _handlers[event];
}
} else
for (i = 0, i_end = eArray.length; i !== i_end; i += 1)
delete _handlers[eArray[i]];
}
/**
* Executes each handler bound to the event.
*
* @param {string} events The name of the event (or the events separated
* by spaces).
* @param {?Object} data The content of the event (optional).
* @return {Object} Returns conrad.
*/
function _dispatch(events, data) {
var i,
j,
i_end,
j_end,
event,
eventName,
eArray = Array.isArray(events) ?
events :
events.split(/ /);
data = data === undefined ? {} : data;
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) {
eventName = eArray[i];
if (_handlers[eventName]) {
event = {
type: eventName,
data: data || {}
};
for (j = 0, j_end = _handlers[eventName].length; j !== j_end; j += 1)
try {
_handlers[eventName][j].handler(event);
} catch (e) {}
}
}
}
/**
* Executes the most prioritary job once, and deals with filling the stats
* (done, time, averageTime, currentTime, etc...).
*
* @return {?Object} Returns the job object if it has to be killed, null else.
*/
function _executeFirstJob() {
var i,
l,
test,
kill,
pushed = false,
time = __dateNow(),
job = _sortedByPriorityJobs.shift();
// Execute the job and look at the result:
test = job.job();
// Deal with stats:
time = __dateNow() - time;
job.done++;
job.time += time;
job.currentTime += time;
job.weightTime = job.currentTime / (job.weight || 1);
job.averageTime = job.time / job.done;
// Check if the job has to be killed:
kill = job.count ? (job.count <= job.done) : !test;
// Reset priorities:
if (!kill) {
for (i = 0, l = _sortedByPriorityJobs.length; i < l; i++)
if (_sortedByPriorityJobs[i].weightTime > job.weightTime) {
_sortedByPriorityJobs.splice(i, 0, job);
pushed = true;
break;
}
if (!pushed)
_sortedByPriorityJobs.push(job);
}
return kill ? job : null;
}
/**
* Activates a job, by adding it to the _runningJobs object and the
* _sortedByPriorityJobs array. It also initializes its currentTime value.
*
* @param {Object} job The job to activate.
*/
function _activateJob(job) {
var l = _sortedByPriorityJobs.length;
// Add the job to the running jobs:
_runningJobs[job.id] = job;
job.status = 'running';
// Add the job to the priorities:
if (l) {
job.weightTime = _sortedByPriorityJobs[l - 1].weightTime;
job.currentTime = job.weightTime * (job.weight || 1);
}
// Initialize the job and dispatch:
job.startTime = __dateNow();
_dispatch('jobStarted', __clone(job));
_sortedByPriorityJobs.push(job);
}
/**
* The main loop of conrad.js:
* . It executes job such that they all occupate the same processing time.
* . It stops jobs that do not need to be executed anymore.
* . It triggers callbacks when it is relevant.
* . It starts waiting jobs when they need to be started.
* . It injects frames to keep a constant frapes per second ratio.
* . It stops itself when there are no more jobs to execute.
*/
function _loop() {
var k,
o,
l,
job,
time,
deadJob;
// Deal with the newly added jobs (the _jobs object):
for (k in _jobs) {
job = _jobs[k];
if (job.after)
_waitingJobs[k] = job;
else
_activateJob(job);
delete _jobs[k];
}
// Set the _isRunning flag to false if there are no running job:
_isRunning = !!_sortedByPriorityJobs.length;
// Deal with the running jobs (the _runningJobs object):
while (
_sortedByPriorityJobs.length &&
__dateNow() - _lastFrameTime < _parameters.frameDuration
) {
deadJob = _executeFirstJob();
// Deal with the case where the job has ended:
if (deadJob) {
_killJob(deadJob.id);
// Check for waiting jobs:
for (k in _waitingJobs)
if (_waitingJobs[k].after === deadJob.id) {
_activateJob(_waitingJobs[k]);
delete _waitingJobs[k];
}
}
}
// Check if conrad still has jobs to deal with, and kill it if not:
if (_isRunning) {
// Update the _lastFrameTime:
_lastFrameTime = __dateNow();
_dispatch('enterFrame');
setTimeout(_loop, 0);
} else
_dispatch('stop');
}
/**
* Adds one or more jobs, and starts the loop if no job was running before. A
* job is at least a unique string "id" and a function, and there are some
* parameters that you can specify for each job to modify the way conrad will
* execute it. If a job is added with the "id" of another job that is waiting
* or still running, an error will be thrown.
*
* When a job is added, it is referenced in the _jobs object, by its id.
* Then, if it has to be executed right now, it will be also referenced in
* the _runningJobs object. If it has to wait, then it will be added into the
* _waitingJobs object, until it can start.
*
* Keep reading this documentation to see how to call this method.
*
* @return {Object} Returns conrad.
*
* Adding one job:
* ***************
* Basically, a job is defined by its string id and a function (the job). It
* is also possible to add some parameters:
*
* > conrad.addJob('myJobId', myJobFunction);
* > conrad.addJob('myJobId', {
* > job: myJobFunction,
* > someParameter: someValue
* > });
* > conrad.addJob({
* > id: 'myJobId',
* > job: myJobFunction,
* > someParameter: someValue
* > });
*
* Adding several jobs:
* ********************
* When adding several jobs at the same time, it is possible to specify
* parameters for each one individually or for all:
*
* > conrad.addJob([
* > {
* > id: 'myJobId1',
* > job: myJobFunction1,
* > someParameter1: someValue1
* > },
* > {
* > id: 'myJobId2',
* > job: myJobFunction2,
* > someParameter2: someValue2
* > }
* > ], {
* > someCommonParameter: someCommonValue
* > });
* > conrad.addJob({
* > myJobId1: {,
* > job: myJobFunction1,
* > someParameter1: someValue1
* > },
* > myJobId2: {,
* > job: myJobFunction2,
* > someParameter2: someValue2
* > }
* > }, {
* > someCommonParameter: someCommonValue
* > });
* > conrad.addJob({
* > myJobId1: myJobFunction1,
* > myJobId2: myJobFunction2
* > }, {
* > someCommonParameter: someCommonValue
* > });
*
* Recognized parameters:
* **********************
* Here is the exhaustive list of every accepted parameters:
*
* {?Function} end A callback to execute when the job is ended. It is
* not executed if the job is killed instead of ended
* "naturally".
* {?Integer} count The number of time the job has to be executed.
* {?Number} weight If specified, the job will be executed as it was
* added "weight" times.
* {?String} after The id of another job (eventually not added yet).
* If specified, this job will start only when the
* specified "after" job is ended.
*/
function _addJob(v1, v2) {
var i,
l,
o;
// Array of jobs:
if (Array.isArray(v1)) {
// Keep conrad to start until the last job is added:
_noStart = true;
for (i = 0, l = v1.length; i < l; i++)
_addJob(v1[i].id, __extend(v1[i], v2));
_noStart = false;
if (!_isRunning) {
// Update the _lastFrameTime:
_lastFrameTime = __dateNow();
_dispatch('start');
_loop();
}
} else if (typeof v1 === 'object') {
// One job (object):
if (typeof v1.id === 'string')
_addJob(v1.id, v1);
// Hash of jobs:
else {
// Keep conrad to start until the last job is added:
_noStart = true;
for (i in v1)
if (typeof v1[i] === 'function')
_addJob(i, __extend({
job: v1[i]
}, v2));
else
_addJob(i, __extend(v1[i], v2));
_noStart = false;
if (!_isRunning) {
// Update the _lastFrameTime:
_lastFrameTime = __dateNow();
_dispatch('start');
_loop();
}
}
// One job (string, *):
} else if (typeof v1 === 'string') {
if (_hasJob(v1))
throw new Error(
'[conrad.addJob] Job with id "' + v1 + '" already exists.'
);
// One job (string, function):
if (typeof v2 === 'function') {
o = {
id: v1,
done: 0,
time: 0,
status: 'waiting',
currentTime: 0,
averageTime: 0,
weightTime: 0,
job: v2
};
// One job (string, object):
} else if (typeof v2 === 'object') {
o = __extend(
{
id: v1,
done: 0,
time: 0,
status: 'waiting',
currentTime: 0,
averageTime: 0,
weightTime: 0
},
v2
);
// If none of those cases, throw an error:
} else
throw new Error('[conrad.addJob] Wrong arguments.');
// Effectively add the job:
_jobs[v1] = o;
_dispatch('jobAdded', __clone(o));
// Check if the loop has to be started:
if (!_isRunning && !_noStart) {
// Update the _lastFrameTime:
_lastFrameTime = __dateNow();
_dispatch('start');
_loop();
}
// If none of those cases, throw an error:
} else
throw new Error('[conrad.addJob] Wrong arguments.');
return this;
}
/**
* Kills one or more jobs, indicated by their ids. It is only possible to
* kill running jobs or waiting jobs. If you try to kill a job that does not
* exists or that is already killed, a warning will be thrown.
*
* @param {Array|String} v1 A string job id or an array of job ids.
* @return {Object} Returns conrad.
*/
function _killJob(v1) {
var i,
l,
k,
a,
job,
found = false;
// Array of job ids:
if (Array.isArray(v1))
for (i = 0, l = v1.length; i < l; i++)
_killJob(v1[i]);
// One job's id:
else if (typeof v1 === 'string') {
a = [_runningJobs, _waitingJobs, _jobs];
// Remove the job from the hashes:
for (i = 0, l = a.length; i < l; i++)
if (v1 in a[i]) {
job = a[i][v1];
if (_parameters.history) {
job.status = 'done';
_doneJobs.push(job);
}
_dispatch('jobEnded', __clone(job));
delete a[i][v1];
if (typeof job.end === 'function')
job.end();
found = true;
}
// Remove the priorities array:
a = _sortedByPriorityJobs;
for (i = 0, l = a.length; i < l; i++)
if (a[i].id === v1) {
a.splice(i, 1);
break;
}
if (!found)
throw new Error('[conrad.killJob] Job "' + v1 + '" not found.');
// If none of those cases, throw an error:
} else
throw new Error('[conrad.killJob] Wrong arguments.');
return this;
}
/**
* Kills every running, waiting, and just added jobs.
*
* @return {Object} Returns conrad.
*/
function _killAll() {
var k,
jobs = __extend(_jobs, _runningJobs, _waitingJobs);
// Take every jobs and push them into the _doneJobs object:
if (_parameters.history)
for (k in jobs) {
jobs[k].status = 'done';
_doneJobs.push(jobs[k]);
if (typeof jobs[k].end === 'function')
jobs[k].end();
}
// Reinitialize the different jobs lists:
_jobs = {};
_waitingJobs = {};
_runningJobs = {};
_sortedByPriorityJobs = [];
// In case some jobs are added right after the kill:
_isRunning = false;
return this;
}
/**
* Returns true if a job with the specified id is currently running or
* waiting, and false else.
*
* @param {String} id The id of the job.
* @return {?Object} Returns the job object if it exists.
*/
function _hasJob(id) {
var job = _jobs[id] || _runningJobs[id] || _waitingJobs[id];
return job ? __extend(job) : null;
}
/**
* This method will set the setting specified by "v1" to the value specified
* by "v2" if both are given, and else return the current value of the
* settings "v1".
*
* @param {String} v1 The name of the property.
* @param {?*} v2 Eventually, a value to set to the specified
* property.
* @return {Object|*} Returns the specified settings value if "v2" is not
* given, and conrad else.
*/
function _settings(v1, v2) {
var o;
if (typeof a1 === 'string' && arguments.length === 1)
return _parameters[a1];
else {
o = (typeof a1 === 'object' && arguments.length === 1) ?
a1 || {} :
{};
if (typeof a1 === 'string')
o[a1] = a2;
for (var k in o)
if (o[k] !== undefined)
_parameters[k] = o[k];
else
delete _parameters[k];
return this;
}
}
/**
* Returns true if conrad is currently running, and false else.
*
* @return {Boolean} Returns _isRunning.
*/
function _getIsRunning() {
return _isRunning;
}
/**
* Unreference every jobs that are stored in the _doneJobs object. It will
* not be possible anymore to get stats about these jobs, but it will release
* the memory.
*
* @return {Object} Returns conrad.
*/
function _clearHistory() {
_doneJobs = [];
return this;
}
/**
* Returns a snapshot of every data about jobs that wait to be started, are
* currently running or are done.
*
* It is possible to get only running, waiting or done jobs by giving
* "running", "waiting" or "done" as fist argument.
*
* It is also possible to get every job with a specified id by giving it as
* first argument. Also, using a RegExp instead of an id will return every
* jobs whose ids match the RegExp. And these two last use cases work as well
* by giving before "running", "waiting" or "done".
*
* @return {Array} The array of the matching jobs.
*
* Some call examples:
* *******************
* > conrad.getStats('running')
* > conrad.getStats('waiting')
* > conrad.getStats('done')
* > conrad.getStats('myJob')
* > conrad.getStats(/test/)
* > conrad.getStats('running', 'myRunningJob')
* > conrad.getStats('running', /test/)
*/
function _getStats(v1, v2) {
var a,
k,
i,
l,
stats,
pattern,
isPatternString;
if (!arguments.length) {
stats = [];
for (k in _jobs)
stats.push(_jobs[k]);
for (k in _waitingJobs)
stats.push(_waitingJobs[k]);
for (k in _runningJobs)
stats.push(_runningJobs[k]);
stats = stats.concat(_doneJobs);
}
if (typeof v1 === 'string')
switch (v1) {
case 'waiting':
stats = __objectValues(_waitingJobs);
break;
case 'running':
stats = __objectValues(_runningJobs);
break;
case 'done':
stats = _doneJobs;
break;
default:
pattern = v1;
}
if (v1 instanceof RegExp)
pattern = v1;
if (!pattern && (typeof v2 === 'string' || v2 instanceof RegExp))
pattern = v2;
// Filter jobs if a pattern is given:
if (pattern) {
isPatternString = typeof pattern === 'string';
if (stats instanceof Array) {
a = stats;
} else if (typeof stats === 'object') {
a = [];
for (k in stats)
a = a.concat(stats[k]);
} else {
a = [];
for (k in _jobs)
a.push(_jobs[k]);
for (k in _waitingJobs)
a.push(_waitingJobs[k]);
for (k in _runningJobs)
a.push(_runningJobs[k]);
a = a.concat(_doneJobs);
}
stats = [];
for (i = 0, l = a.length; i < l; i++)
if (isPatternString ? a[i].id === pattern : a[i].id.match(pattern))
stats.push(a[i]);
}
return __clone(stats);
}
/**
* TOOLS FUNCTIONS:
* ****************
*/
/**
* This function takes any number of objects as arguments, copies from each
* of these objects each pair key/value into a new object, and finally
* returns this object.
*
* The arguments are parsed from the last one to the first one, such that
* when two objects have keys in common, the "earliest" object wins.
*
* Example:
* ********
* > var o1 = {
* > a: 1,
* > b: 2,
* > c: '3'
* > },
* > o2 = {
* > c: '4',
* > d: [ 5 ]
* > };
* > __extend(o1, o2);
* > // Returns: {
* > // a: 1,
* > // b: 2,
* > // c: '3',
* > // d: [ 5 ]
* > // };
*
* @param {Object+} Any number of objects.
* @return {Object} The merged object.
*/
function __extend() {
var i,
k,
res = {},
l = arguments.length;
for (i = l - 1; i >= 0; i--)
for (k in arguments[i])
res[k] = arguments[i][k];
return res;
}
/**
* This function simply clones an object. This object must contain only
* objects, arrays and immutable values. Since it is not public, it does not
* deal with cyclic references, DOM elements and instantiated objects - so
* use it carefully.
*
* @param {Object} The object to clone.
* @return {Object} The clone.
*/
function __clone(item) {
var result, i, k, l;
if (!item)
return item;
if (Array.isArray(item)) {
result = [];
for (i = 0, l = item.length; i < l; i++)
result.push(__clone(item[i]));
} else if (typeof item === 'object') {
result = {};
for (i in item)
result[i] = __clone(item[i]);
} else
result = item;
return result;
}
/**
* Returns an array containing the values of an object.
*
* @param {Object} The object.
* @return {Array} The array of values.
*/
function __objectValues(o) {
var k,
a = [];
for (k in o)
a.push(o[k]);
return a;
}
/**
* A short "Date.now()" polyfill.
*
* @return {Number} The current time (in ms).
*/
function __dateNow() {
return Date.now ? Date.now() : new Date().getTime();
}
/**
* Polyfill for the Array.isArray function:
*/
if (!Array.isArray)
Array.isArray = function(v) {
return Object.prototype.toString.call(v) === '[object Array]';
};
/**
* EXPORT PUBLIC API:
* ******************
*/
var conrad = {
hasJob: _hasJob,
addJob: _addJob,
killJob: _killJob,
killAll: _killAll,
settings: _settings,
getStats: _getStats,
isRunning: _getIsRunning,
clearHistory: _clearHistory,
// Events management:
bind: _bind,
unbind: _unbind,
// Version:
version: '0.1.0'
};
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = conrad;
exports.conrad = conrad;
}
global.conrad = conrad;
})(this);
// Hardcoded export for the node.js version:
var sigma = this.sigma,
conrad = this.conrad;
sigma.conrad = conrad;
// Dirty polyfills to permit sigma usage in node
if (HTMLElement === undefined)
var HTMLElement = function() {};
if (window === undefined)
var window = {
addEventListener: function() {}
};
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = sigma;
exports.sigma = sigma;
}
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
var _root = this;
// Initialize packages:
sigma.utils = sigma.utils || {};
/**
* MISC UTILS:
*/
/**
* This function takes any number of objects as arguments, copies from each
* of these objects each pair key/value into a new object, and finally
* returns this object.
*
* The arguments are parsed from the last one to the first one, such that
* when several objects have keys in common, the "earliest" object wins.
*
* Example:
* ********
* > var o1 = {
* > a: 1,
* > b: 2,
* > c: '3'
* > },
* > o2 = {
* > c: '4',
* > d: [ 5 ]
* > };
* > sigma.utils.extend(o1, o2);
* > // Returns: {
* > // a: 1,
* > // b: 2,
* > // c: '3',
* > // d: [ 5 ]
* > // };
*
* @param {object+} Any number of objects.
* @return {object} The merged object.
*/
sigma.utils.extend = function() {
var i,
k,
res = {},
l = arguments.length;
for (i = l - 1; i >= 0; i--)
for (k in arguments[i])
res[k] = arguments[i][k];
return res;
};
/**
* A short "Date.now()" polyfill.
*
* @return {Number} The current time (in ms).
*/
sigma.utils.dateNow = function() {
return Date.now ? Date.now() : new Date().getTime();
};
/**
* Takes a package name as parameter and checks at each lebel if it exists,
* and if it does not, creates it.
*
* Example:
* ********
* > sigma.utils.pkg('a.b.c');
* > a.b.c;
* > // Object {};
* >
* > sigma.utils.pkg('a.b.d');
* > a.b;
* > // Object { c: {}, d: {} };
*
* @param {string} pkgName The name of the package to create/find.
* @return {object} The related package.
*/
sigma.utils.pkg = function(pkgName) {
return (pkgName || '').split('.').reduce(function(context, objName) {
return (objName in context) ?
context[objName] :
(context[objName] = {});
}, _root);
};
/**
* Returns a unique incremental number ID.
*
* Example:
* ********
* > sigma.utils.id();
* > // 1;
* >
* > sigma.utils.id();
* > // 2;
* >
* > sigma.utils.id();
* > // 3;
*
* @param {string} pkgName The name of the package to create/find.
* @return {object} The related package.
*/
sigma.utils.id = (function() {
var i = 0;
return function() {
return ++i;
};
})();
/**
* This function takes an hexa color (for instance "#ffcc00" or "#fc0") or a
* rgb / rgba color (like "rgb(255,255,12)" or "rgba(255,255,12,1)") and
* returns an integer equal to "r * 255 * 255 + g * 255 + b", to gain some
* memory in the data given to WebGL shaders.
*
* @param {string} val The hexa or rgba color.
* @return {number} The number value.
*/
sigma.utils.floatColor = function(val) {
var result = [0, 0, 0];
if (val.match(/^#/)) {
val = (val || '').replace(/^#/, '');
result = (val.length === 3) ?
[
parseInt(val.charAt(0) + val.charAt(0), 16),
parseInt(val.charAt(1) + val.charAt(1), 16),
parseInt(val.charAt(2) + val.charAt(2), 16)
] :
[
parseInt(val.charAt(0) + val.charAt(1), 16),
parseInt(val.charAt(2) + val.charAt(3), 16),
parseInt(val.charAt(4) + val.charAt(5), 16)
];
} else if (val.match(/^ *rgba? *\(/)) {
val = val.match(
/^ *rgba? *\( *([0-9]*) *, *([0-9]*) *, *([0-9]*) *(,.*)?\) *$/
);
result = [
+val[1],
+val[2],
+val[3]
];
}
return (
result[0] * 256 * 256 +
result[1] * 256 +
result[2]
);
};
/**
* Perform a zoom into a camera, with or without animation, to the
* coordinates indicated using a specified ratio.
*
* Recognized parameters:
* **********************
* Here is the exhaustive list of every accepted parameters in the animation
* object:
*
* {?number} duration An amount of time that means the duration of the
* animation. If this parameter doesn't exist the
* zoom will be performed without animation.
* {?function} onComplete A function to perform it after the animation. It
* will be performed even if there is no duration.
*
* @param {camera} The camera where perform the zoom.
* @param {x} The X coordiantion where the zoom goes.
* @param {y} The Y coordiantion where the zoom goes.
* @param {ratio} The ratio to apply it to the current camera ratio.
* @param {?animation} A dictionary with options for a possible animation.
*/
sigma.utils.zoomTo = function(camera, x, y, ratio, animation) {
var settings = camera.settings,
count,
newRatio,
animationSettings,
coordinates;
// Create the newRatio dealing with min / max:
newRatio = Math.max(
settings('zoomMin'),
Math.min(
settings('zoomMax'),
camera.ratio * ratio
)
);
// Check that the new ratio is different from the initial one:
if (newRatio !== camera.ratio) {
// Create the coordinates variable:
ratio = newRatio / camera.ratio;
coordinates = {
x: x * (1 - ratio) + camera.x,
y: y * (1 - ratio) + camera.y,
ratio: newRatio
};
if (animation && animation.duration) {
// Complete the animation setings:
count = sigma.misc.animation.killAll(camera);
animation = sigma.utils.extend(
animation,
{
easing: count ? 'quadraticOut' : 'quadraticInOut'
}
);
sigma.misc.animation.camera(camera, coordinates, animation);
} else {
camera.goTo(coordinates);
if (animation && animation.onComplete)
animation.onComplete();
}
}
};
/**
* Return the control point coordinates for a quadratic bezier curve.
*
* @param {number} x1 The X coordinate of the start point.
* @param {number} y1 The Y coordinate of the start point.
* @param {number} x2 The X coordinate of the end point.
* @param {number} y2 The Y coordinate of the end point.
* @return {x,y} The control point coordinates.
*/
sigma.utils.getQuadraticControlPoint = function(x1, y1, x2, y2) {
return {
x: (x1 + x2) / 2 + (y2 - y1) / 4,
y: (y1 + y2) / 2 + (x1 - x2) / 4
};
};
/**
* Compute the coordinates of the point positioned
* at length t in the quadratic bezier curve.
*
* @param {number} t In [0,1] the step percentage to reach
* the point in the curve from the context point.
* @param {number} x1 The X coordinate of the context point.
* @param {number} y1 The Y coordinate of the context point.
* @param {number} x2 The X coordinate of the ending point.
* @param {number} y2 The Y coordinate of the ending point.
* @param {number} xi The X coordinate of the control point.
* @param {number} yi The Y coordinate of the control point.
* @return {object} {x,y}.
*/
sigma.utils.getPointOnQuadraticCurve = function(t, x1, y1, x2, y2, xi, yi) {
// http://stackoverflow.com/a/5634528
return {
x: Math.pow(1 - t, 2) * x1 + 2 * (1 - t) * t * xi + Math.pow(t, 2) * x2,
y: Math.pow(1 - t, 2) * y1 + 2 * (1 - t) * t * yi + Math.pow(t, 2) * y2
};
};
/**
* Compute the coordinates of the point positioned
* at length t in the cubic bezier curve.
*
* @param {number} t In [0,1] the step percentage to reach
* the point in the curve from the context point.
* @param {number} x1 The X coordinate of the context point.
* @param {number} y1 The Y coordinate of the context point.
* @param {number} x2 The X coordinate of the end point.
* @param {number} y2 The Y coordinate of the end point.
* @param {number} cx The X coordinate of the first control point.
* @param {number} cy The Y coordinate of the first control point.
* @param {number} dx The X coordinate of the second control point.
* @param {number} dy The Y coordinate of the second control point.
* @return {object} {x,y} The point at t.
*/
sigma.utils.getPointOnBezierCurve =
function(t, x1, y1, x2, y2, cx, cy, dx, dy) {
// http://stackoverflow.com/a/15397596
// Blending functions:
var B0_t = Math.pow(1 - t, 3),
B1_t = 3 * t * Math.pow(1 - t, 2),
B2_t = 3 * Math.pow(t, 2) * (1 - t),
B3_t = Math.pow(t, 3);
return {
x: (B0_t * x1) + (B1_t * cx) + (B2_t * dx) + (B3_t * x2),
y: (B0_t * y1) + (B1_t * cy) + (B2_t * dy) + (B3_t * y2)
};
};
/**
* Return the coordinates of the two control points for a self loop (i.e.
* where the start point is also the end point) computed as a cubic bezier
* curve.
*
* @param {number} x The X coordinate of the node.
* @param {number} y The Y coordinate of the node.
* @param {number} size The node size.
* @return {x1,y1,x2,y2} The coordinates of the two control points.
*/
sigma.utils.getSelfLoopControlPoints = function(x , y, size) {
return {
x1: x - size * 7,
y1: y,
x2: x,
y2: y + size * 7
};
};
/**
* Return the euclidian distance between two points of a plane
* with an orthonormal basis.
*
* @param {number} x1 The X coordinate of the first point.
* @param {number} y1 The Y coordinate of the first point.
* @param {number} x2 The X coordinate of the second point.
* @param {number} y2 The Y coordinate of the second point.
* @return {number} The euclidian distance.
*/
sigma.utils.getDistance = function(x0, y0, x1, y1) {
return Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2));
};
/**
* Return the coordinates of the intersection points of two circles.
*
* @param {number} x0 The X coordinate of center location of the first
* circle.
* @param {number} y0 The Y coordinate of center location of the first
* circle.
* @param {number} r0 The radius of the first circle.
* @param {number} x1 The X coordinate of center location of the second
* circle.
* @param {number} y1 The Y coordinate of center location of the second
* circle.
* @param {number} r1 The radius of the second circle.
* @return {xi,yi} The coordinates of the intersection points.
*/
sigma.utils.getCircleIntersection = function(x0, y0, r0, x1, y1, r1) {
// http://stackoverflow.com/a/12219802
var a, dx, dy, d, h, rx, ry, x2, y2;
// dx and dy are the vertical and horizontal distances between the circle
// centers:
dx = x1 - x0;
dy = y1 - y0;
// Determine the straight-line distance between the centers:
d = Math.sqrt((dy * dy) + (dx * dx));
// Check for solvability:
if (d > (r0 + r1)) {
// No solution. circles do not intersect.
return false;
}
if (d < Math.abs(r0 - r1)) {
// No solution. one circle is contained in the other.
return false;
}
//'point 2' is the point where the line through the circle intersection
// points crosses the line between the circle centers.
// Determine the distance from point 0 to point 2:
a = ((r0 * r0) - (r1 * r1) + (d * d)) / (2.0 * d);
// Determine the coordinates of point 2:
x2 = x0 + (dx * a / d);
y2 = y0 + (dy * a / d);
// Determine the distance from point 2 to either of the intersection
// points:
h = Math.sqrt((r0 * r0) - (a * a));
// Determine the offsets of the intersection points from point 2:
rx = -dy * (h / d);
ry = dx * (h / d);
// Determine the absolute intersection points:
var xi = x2 + rx;
var xi_prime = x2 - rx;
var yi = y2 + ry;
var yi_prime = y2 - ry;
return {xi: xi, xi_prime: xi_prime, yi: yi, yi_prime: yi_prime};
};
/**
* Check if a point is on a line segment.
*
* @param {number} x The X coordinate of the point to check.
* @param {number} y The Y coordinate of the point to check.
* @param {number} x1 The X coordinate of the line start point.
* @param {number} y1 The Y coordinate of the line start point.
* @param {number} x2 The X coordinate of the line end point.
* @param {number} y2 The Y coordinate of the line end point.
* @param {number} epsilon The precision (consider the line thickness).
* @return {boolean} True if point is "close to" the line
* segment, false otherwise.
*/
sigma.utils.isPointOnSegment = function(x, y, x1, y1, x2, y2, epsilon) {
// http://stackoverflow.com/a/328122
var crossProduct = Math.abs((y - y1) * (x2 - x1) - (x - x1) * (y2 - y1)),
d = sigma.utils.getDistance(x1, y1, x2, y2),
nCrossProduct = crossProduct / d; // normalized cross product
return (nCrossProduct < epsilon &&
Math.min(x1, x2) <= x && x <= Math.max(x1, x2) &&
Math.min(y1, y2) <= y && y <= Math.max(y1, y2));
};
/**
* Check if a point is on a quadratic bezier curve segment with a thickness.
*
* @param {number} x The X coordinate of the point to check.
* @param {number} y The Y coordinate of the point to check.
* @param {number} x1 The X coordinate of the curve start point.
* @param {number} y1 The Y coordinate of the curve start point.
* @param {number} x2 The X coordinate of the curve end point.
* @param {number} y2 The Y coordinate of the curve end point.
* @param {number} cpx The X coordinate of the curve control point.
* @param {number} cpy The Y coordinate of the curve control point.
* @param {number} epsilon The precision (consider the line thickness).
* @return {boolean} True if (x,y) is on the curve segment,
* false otherwise.
*/
sigma.utils.isPointOnQuadraticCurve =
function(x, y, x1, y1, x2, y2, cpx, cpy, epsilon) {
// Fails if the point is too far from the extremities of the segment,
// preventing for more costly computation:
var dP1P2 = sigma.utils.getDistance(x1, y1, x2, y2);
if (Math.abs(x - x1) > dP1P2 || Math.abs(y - y1) > dP1P2) {
return false;
}
var dP1 = sigma.utils.getDistance(x, y, x1, y1),
dP2 = sigma.utils.getDistance(x, y, x2, y2),
t = 0.5,
r = (dP1 < dP2) ? -0.01 : 0.01,
rThreshold = 0.001,
i = 100,
pt = sigma.utils.getPointOnQuadraticCurve(t, x1, y1, x2, y2, cpx, cpy),
dt = sigma.utils.getDistance(x, y, pt.x, pt.y),
old_dt;
// This algorithm minimizes the distance from the point to the curve. It
// find the optimal t value where t=0 is the start point and t=1 is the end
// point of the curve, starting from t=0.5.
// It terminates because it runs a maximum of i interations.
while (i-- > 0 &&
t >= 0 && t <= 1 &&
(dt > epsilon) &&
(r > rThreshold || r < -rThreshold)) {
old_dt = dt;
pt = sigma.utils.getPointOnQuadraticCurve(t, x1, y1, x2, y2, cpx, cpy);
dt = sigma.utils.getDistance(x, y, pt.x, pt.y);
if (dt > old_dt) {
// not the right direction:
// halfstep in the opposite direction
r = -r / 2;
t += r;
}
else if (t + r < 0 || t + r > 1) {
// oops, we've gone too far:
// revert with a halfstep
r = r / 2;
dt = old_dt;
}
else {
// progress:
t += r;
}
}
return dt < epsilon;
};
/**
* Check if a point is on a cubic bezier curve segment with a thickness.
*
* @param {number} x The X coordinate of the point to check.
* @param {number} y The Y coordinate of the point to check.
* @param {number} x1 The X coordinate of the curve start point.
* @param {number} y1 The Y coordinate of the curve start point.
* @param {number} x2 The X coordinate of the curve end point.
* @param {number} y2 The Y coordinate of the curve end point.
* @param {number} cpx1 The X coordinate of the 1st curve control point.
* @param {number} cpy1 The Y coordinate of the 1st curve control point.
* @param {number} cpx2 The X coordinate of the 2nd curve control point.
* @param {number} cpy2 The Y coordinate of the 2nd curve control point.
* @param {number} epsilon The precision (consider the line thickness).
* @return {boolean} True if (x,y) is on the curve segment,
* false otherwise.
*/
sigma.utils.isPointOnBezierCurve =
function(x, y, x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2, epsilon) {
// Fails if the point is too far from the extremities of the segment,
// preventing for more costly computation:
var dP1CP1 = sigma.utils.getDistance(x1, y1, cpx1, cpy1);
if (Math.abs(x - x1) > dP1CP1 || Math.abs(y - y1) > dP1CP1) {
return false;
}
var dP1 = sigma.utils.getDistance(x, y, x1, y1),
dP2 = sigma.utils.getDistance(x, y, x2, y2),
t = 0.5,
r = (dP1 < dP2) ? -0.01 : 0.01,
rThreshold = 0.001,
i = 100,
pt = sigma.utils.getPointOnBezierCurve(
t, x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2),
dt = sigma.utils.getDistance(x, y, pt.x, pt.y),
old_dt;
// This algorithm minimizes the distance from the point to the curve. It
// find the optimal t value where t=0 is the start point and t=1 is the end
// point of the curve, starting from t=0.5.
// It terminates because it runs a maximum of i interations.
while (i-- > 0 &&
t >= 0 && t <= 1 &&
(dt > epsilon) &&
(r > rThreshold || r < -rThreshold)) {
old_dt = dt;
pt = sigma.utils.getPointOnBezierCurve(
t, x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2);
dt = sigma.utils.getDistance(x, y, pt.x, pt.y);
if (dt > old_dt) {
// not the right direction:
// halfstep in the opposite direction
r = -r / 2;
t += r;
}
else if (t + r < 0 || t + r > 1) {
// oops, we've gone too far:
// revert with a halfstep
r = r / 2;
dt = old_dt;
}
else {
// progress:
t += r;
}
}
return dt < epsilon;
};
/**
* ************
* EVENTS UTILS:
* ************
*/
/**
* Here are some useful functions to unify extraction of the information we
* need with mouse events and touch events, from different browsers:
*/
/**
* Extract the local X position from a mouse or touch event.
*
* @param {event} e A mouse or touch event.
* @return {number} The local X value of the mouse.
*/
sigma.utils.getX = function(e) {
return (
(e.offsetX !== undefined && e.offsetX) ||
(e.layerX !== undefined && e.layerX) ||
(e.clientX !== undefined && e.clientX)
);
};
/**
* Extract the local Y position from a mouse or touch event.
*
* @param {event} e A mouse or touch event.
* @return {number} The local Y value of the mouse.
*/
sigma.utils.getY = function(e) {
return (
(e.offsetY !== undefined && e.offsetY) ||
(e.layerY !== undefined && e.layerY) ||
(e.clientY !== undefined && e.clientY)
);
};
/**
* Extract the width from a mouse or touch event.
*
* @param {event} e A mouse or touch event.
* @return {number} The width of the event's target.
*/
sigma.utils.getWidth = function(e) {
var w = (!e.target.ownerSVGElement) ?
e.target.width :
e.target.ownerSVGElement.width;
return (
(typeof w === 'number' && w) ||
(w !== undefined && w.baseVal !== undefined && w.baseVal.value)
);
};
/**
* Extract the height from a mouse or touch event.
*
* @param {event} e A mouse or touch event.
* @return {number} The height of the event's target.
*/
sigma.utils.getHeight = function(e) {
var h = (!e.target.ownerSVGElement) ?
e.target.height :
e.target.ownerSVGElement.height;
return (
(typeof h === 'number' && h) ||
(h !== undefined && h.baseVal !== undefined && h.baseVal.value)
);
};
/**
* Extract the wheel delta from a mouse or touch event.
*
* @param {event} e A mouse or touch event.
* @return {number} The wheel delta of the mouse.
*/
sigma.utils.getDelta = function(e) {
return (
(e.wheelDelta !== undefined && e.wheelDelta) ||
(e.detail !== undefined && -e.detail)
);
};
/**
* Returns the offset of a DOM element.
*
* @param {DOMElement} dom The element to retrieve the position.
* @return {object} The offset of the DOM element (top, left).
*/
sigma.utils.getOffset = function(dom) {
var left = 0,
top = 0;
while (dom) {
top = top + parseInt(dom.offsetTop);
left = left + parseInt(dom.offsetLeft);
dom = dom.offsetParent;
}
return {
top: top,
left: left
};
};
/**
* Simulates a "double click" event.
*
* @param {HTMLElement} target The event target.
* @param {string} type The event type.
* @param {function} callback The callback to execute.
*/
sigma.utils.doubleClick = function(target, type, callback) {
var clicks = 0,
self = this,
handlers;
target._doubleClickHandler = target._doubleClickHandler || {};
target._doubleClickHandler[type] = target._doubleClickHandler[type] || [];
handlers = target._doubleClickHandler[type];
handlers.push(function(e) {
clicks++;
if (clicks === 2) {
clicks = 0;
return callback(e);
} else if (clicks === 1) {
setTimeout(function() {
clicks = 0;
}, sigma.settings.doubleClickTimeout);
}
});
target.addEventListener(type, handlers[handlers.length - 1], false);
};
/**
* Unbind simulated "double click" events.
*
* @param {HTMLElement} target The event target.
* @param {string} type The event type.
*/
sigma.utils.unbindDoubleClick = function(target, type) {
var handler,
handlers = (target._doubleClickHandler || {})[type] || [];
while ((handler = handlers.pop())) {
target.removeEventListener(type, handler);
}
delete (target._doubleClickHandler || {})[type];
};
/**
* Here are just some of the most basic easing functions, used for the
* animated camera "goTo" calls.
*
* If you need some more easings functions, don't hesitate to add them to
* sigma.utils.easings. But I will not add some more here or merge PRs
* containing, because I do not want sigma sources full of overkill and never
* used stuff...
*/
sigma.utils.easings = sigma.utils.easings || {};
sigma.utils.easings.linearNone = function(k) {
return k;
};
sigma.utils.easings.quadraticIn = function(k) {
return k * k;
};
sigma.utils.easings.quadraticOut = function(k) {
return k * (2 - k);
};
sigma.utils.easings.quadraticInOut = function(k) {
if ((k *= 2) < 1)
return 0.5 * k * k;
return - 0.5 * (--k * (k - 2) - 1);
};
sigma.utils.easings.cubicIn = function(k) {
return k * k * k;
};
sigma.utils.easings.cubicOut = function(k) {
return --k * k * k + 1;
};
sigma.utils.easings.cubicInOut = function(k) {
if ((k *= 2) < 1)
return 0.5 * k * k * k;
return 0.5 * ((k -= 2) * k * k + 2);
};
/**
* ************
* WEBGL UTILS:
* ************
*/
/**
* Loads a WebGL shader and returns it.
*
* @param {WebGLContext} gl The WebGLContext to use.
* @param {string} shaderSource The shader source.
* @param {number} shaderType The type of shader.
* @param {function(string): void} error Callback for errors.
* @return {WebGLShader} The created shader.
*/
sigma.utils.loadShader = function(gl, shaderSource, shaderType, error) {
var compiled,
shader = gl.createShader(shaderType);
// Load the shader source
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check the compile status
compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
// If something went wrong:
if (!compiled) {
if (error) {
error(
'Error compiling shader "' + shader + '":' +
gl.getShaderInfoLog(shader)
);
}
gl.deleteShader(shader);
return null;
}
return shader;
};
/**
* Creates a program, attaches shaders, binds attrib locations, links the
* program and calls useProgram.
*
* @param {Array.<WebGLShader>} shaders The shaders to attach.
* @param {Array.<string>} attribs The attribs names.
* @param {Array.<number>} locations The locations for the attribs.
* @param {function(string): void} error Callback for errors.
* @return {WebGLProgram} The created program.
*/
sigma.utils.loadProgram = function(gl, shaders, attribs, loc, error) {
var i,
linked,
program = gl.createProgram();
for (i = 0; i < shaders.length; ++i)
gl.attachShader(program, shaders[i]);
if (attribs)
for (i = 0; i < attribs.length; ++i)
gl.bindAttribLocation(
program,
locations ? locations[i] : i,
opt_attribs[i]
);
gl.linkProgram(program);
// Check the link status
linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
if (error)
error('Error in program linking: ' + gl.getProgramInfoLog(program));
gl.deleteProgram(program);
return null;
}
return program;
};
/**
* *********
* MATRICES:
* *********
* The following utils are just here to help generating the transformation
* matrices for the WebGL renderers.
*/
sigma.utils.pkg('sigma.utils.matrices');
/**
* The returns a 3x3 translation matrix.
*
* @param {number} dx The X translation.
* @param {number} dy The Y translation.
* @return {array} Returns the matrix.
*/
sigma.utils.matrices.translation = function(dx, dy) {
return [
1, 0, 0,
0, 1, 0,
dx, dy, 1
];
};
/**
* The returns a 3x3 or 2x2 rotation matrix.
*
* @param {number} angle The rotation angle.
* @param {boolean} m2 If true, the function will return a 2x2 matrix.
* @return {array} Returns the matrix.
*/
sigma.utils.matrices.rotation = function(angle, m2) {
var cos = Math.cos(angle),
sin = Math.sin(angle);
return m2 ? [
cos, -sin,
sin, cos
] : [
cos, -sin, 0,
sin, cos, 0,
0, 0, 1
];
};
/**
* The returns a 3x3 or 2x2 homothetic transformation matrix.
*
* @param {number} ratio The scaling ratio.
* @param {boolean} m2 If true, the function will return a 2x2 matrix.
* @return {array} Returns the matrix.
*/
sigma.utils.matrices.scale = function(ratio, m2) {
return m2 ? [
ratio, 0,
0, ratio
] : [
ratio, 0, 0,
0, ratio, 0,
0, 0, 1
];
};
/**
* The returns a 3x3 or 2x2 homothetic transformation matrix.
*
* @param {array} a The first matrix.
* @param {array} b The second matrix.
* @param {boolean} m2 If true, the function will assume both matrices are
* 2x2.
* @return {array} Returns the matrix.
*/
sigma.utils.matrices.multiply = function(a, b, m2) {
var l = m2 ? 2 : 3,
a00 = a[0 * l + 0],
a01 = a[0 * l + 1],
a02 = a[0 * l + 2],
a10 = a[1 * l + 0],
a11 = a[1 * l + 1],
a12 = a[1 * l + 2],
a20 = a[2 * l + 0],
a21 = a[2 * l + 1],
a22 = a[2 * l + 2],
b00 = b[0 * l + 0],
b01 = b[0 * l + 1],
b02 = b[0 * l + 2],
b10 = b[1 * l + 0],
b11 = b[1 * l + 1],
b12 = b[1 * l + 2],
b20 = b[2 * l + 0],
b21 = b[2 * l + 1],
b22 = b[2 * l + 2];
return m2 ? [
a00 * b00 + a01 * b10,
a00 * b01 + a01 * b11,
a10 * b00 + a11 * b10,
a10 * b01 + a11 * b11
] : [
a00 * b00 + a01 * b10 + a02 * b20,
a00 * b01 + a01 * b11 + a02 * b21,
a00 * b02 + a01 * b12 + a02 * b22,
a10 * b00 + a11 * b10 + a12 * b20,
a10 * b01 + a11 * b11 + a12 * b21,
a10 * b02 + a11 * b12 + a12 * b22,
a20 * b00 + a21 * b10 + a22 * b20,
a20 * b01 + a21 * b11 + a22 * b21,
a20 * b02 + a21 * b12 + a22 * b22
];
};
}).call(this);
;(function(global) {
'use strict';
/**
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
* http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
* requestAnimationFrame polyfill by Erik Möller.
* fixes from Paul Irish and Tino Zijdel
* MIT license
*/
var x,
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
for (x = 0; x < vendors.length && !global.requestAnimationFrame; x++) {
global.requestAnimationFrame =
global[vendors[x] + 'RequestAnimationFrame'];
global.cancelAnimationFrame =
global[vendors[x] + 'CancelAnimationFrame'] ||
global[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!global.requestAnimationFrame)
global.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = global.setTimeout(
function() {
callback(currTime + timeToCall);
},
timeToCall
);
lastTime = currTime + timeToCall;
return id;
};
if (!global.cancelAnimationFrame)
global.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
/**
* Function.prototype.bind polyfill found on MDN.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
* Public domain
*/
if (!Function.prototype.bind)
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function')
// Closest thing possible to the ECMAScript 5 internal IsCallable
// function:
throw new TypeError(
'Function.prototype.bind - what is trying to be bound is not callable'
);
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP,
fBound;
fNOP = function() {};
fBound = function() {
return fToBind.apply(
this instanceof fNOP && oThis ?
this :
oThis,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
})(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Packages initialization:
sigma.utils.pkg('sigma.settings');
var settings = {
/**
* GRAPH SETTINGS:
* ***************
*/
// {boolean} Indicates if the data have to be cloned in methods to add
// nodes or edges.
clone: true,
// {boolean} Indicates if nodes "id" values and edges "id", "source" and
// "target" values must be set as immutable.
immutable: true,
// {boolean} Indicates if sigma can log its errors and warnings.
verbose: false,
/**
* RENDERERS SETTINGS:
* *******************
*/
// {string}
classPrefix: 'sigma',
// {string}
defaultNodeType: 'def',
// {string}
defaultEdgeType: 'def',
// {string}
defaultLabelColor: '#000',
// {string}
defaultEdgeColor: '#000',
// {string}
defaultNodeColor: '#000',
// {string}
defaultLabelSize: 14,
// {string} Indicates how to choose the edges color. Available values:
// "source", "target", "default"
edgeColor: 'source',
// {number} Defines the minimal edge's arrow display size.
minArrowSize: 0,
// {string}
font: 'arial',
// {string} Example: 'bold'
fontStyle: '',
// {string} Indicates how to choose the labels color. Available values:
// "node", "default"
labelColor: 'default',
// {string} Indicates how to choose the labels size. Available values:
// "fixed", "proportional"
labelSize: 'fixed',
// {string} The ratio between the font size of the label and the node size.
labelSizeRatio: 1,
// {number} The minimum size a node must have to see its label displayed.
labelThreshold: 8,
// {number} The oversampling factor used in WebGL renderer.
webglOversamplingRatio: 2,
// {number} The size of the border of hovered nodes.
borderSize: 0,
// {number} The default hovered node border's color.
defaultNodeBorderColor: '#000',
// {number} The hovered node's label font. If not specified, will heritate
// the "font" value.
hoverFont: '',
// {boolean} If true, then only one node can be hovered at a time.
singleHover: true,
// {string} Example: 'bold'
hoverFontStyle: '',
// {string} Indicates how to choose the hovered nodes shadow color.
// Available values: "node", "default"
labelHoverShadow: 'default',
// {string}
labelHoverShadowColor: '#000',
// {string} Indicates how to choose the hovered nodes color.
// Available values: "node", "default"
nodeHoverColor: 'node',
// {string}
defaultNodeHoverColor: '#000',
// {string} Indicates how to choose the hovered nodes background color.
// Available values: "node", "default"
labelHoverBGColor: 'default',
// {string}
defaultHoverLabelBGColor: '#fff',
// {string} Indicates how to choose the hovered labels color.
// Available values: "node", "default"
labelHoverColor: 'default',
// {string}
defaultLabelHoverColor: '#000',
// {string} Indicates how to choose the edges hover color. Available values:
// "edge", "default"
edgeHoverColor: 'edge',
// {number} The size multiplicator of hovered edges.
edgeHoverSizeRatio: 1,
// {string}
defaultEdgeHoverColor: '#000',
// {boolean} Indicates if the edge extremities must be hovered when the
// edge is hovered.
edgeHoverExtremities: false,
// {booleans} The different drawing modes:
// false: Layered not displayed.
// true: Layered displayed.
drawEdges: true,
drawNodes: true,
drawLabels: true,
drawEdgeLabels: false,
// {boolean} Indicates if the edges must be drawn in several frames or in
// one frame, as the nodes and labels are drawn.
batchEdgesDrawing: false,
// {boolean} Indicates if the edges must be hidden during dragging and
// animations.
hideEdgesOnMove: false,
// {numbers} The different batch sizes, when elements are displayed in
// several frames.
canvasEdgesBatchSize: 500,
webglEdgesBatchSize: 1000,
/**
* RESCALE SETTINGS:
* *****************
*/
// {string} Indicates of to scale the graph relatively to its container.
// Available values: "inside", "outside"
scalingMode: 'inside',
// {number} The margin to keep around the graph.
sideMargin: 0,
// {number} Determine the size of the smallest and the biggest node / edges
// on the screen. This mapping makes easier to display the graph,
// avoiding too big nodes that take half of the screen, or too
// small ones that are not readable. If the two parameters are
// equals, then the minimal display size will be 0. And if they
// are both equal to 0, then there is no mapping, and the radius
// of the nodes will be their size.
minEdgeSize: 0.5,
maxEdgeSize: 1,
minNodeSize: 1,
maxNodeSize: 8,
/**
* CAPTORS SETTINGS:
* *****************
*/
// {boolean}
touchEnabled: true,
// {boolean}
mouseEnabled: true,
// {boolean}
mouseWheelEnabled: true,
// {boolean}
doubleClickEnabled: true,
// {boolean} Defines whether the custom events such as "clickNode" can be
// used.
eventsEnabled: true,
// {number} Defines by how much multiplicating the zooming level when the
// user zooms with the mouse-wheel.
zoomingRatio: 1.7,
// {number} Defines by how much multiplicating the zooming level when the
// user zooms by double clicking.
doubleClickZoomingRatio: 2.2,
// {number} The minimum zooming level.
zoomMin: 0.0625,
// {number} The maximum zooming level.
zoomMax: 2,
// {number} The duration of animations following a mouse scrolling.
mouseZoomDuration: 200,
// {number} The duration of animations following a mouse double click.
doubleClickZoomDuration: 200,
// {number} The duration of animations following a mouse dropping.
mouseInertiaDuration: 200,
// {number} The inertia power (mouse captor).
mouseInertiaRatio: 3,
// {number} The duration of animations following a touch dropping.
touchInertiaDuration: 200,
// {number} The inertia power (touch captor).
touchInertiaRatio: 3,
// {number} The maximum time between two clicks to make it a double click.
doubleClickTimeout: 300,
// {number} The maximum time between two taps to make it a double tap.
doubleTapTimeout: 300,
// {number} The maximum time of dragging to trigger intertia.
dragTimeout: 200,
/**
* GLOBAL SETTINGS:
* ****************
*/
// {boolean} Determines whether the instance has to refresh itself
// automatically when a "resize" event is dispatched from the
// window object.
autoResize: true,
// {boolean} Determines whether the "rescale" middleware has to be called
// automatically for each camera on refresh.
autoRescale: true,
// {boolean} If set to false, the camera method "goTo" will basically do
// nothing.
enableCamera: true,
// {boolean} If set to false, the nodes cannot be hovered.
enableHovering: true,
// {boolean} If set to true, the edges can be hovered.
enableEdgeHovering: false,
// {number} The size of the area around the edges to activate hovering.
edgeHoverPrecision: 5,
// {boolean} If set to true, the rescale middleware will ignore node sizes
// to determine the graphs boundings.
rescaleIgnoreSize: false,
// {boolean} Determines if the core has to try to catch errors on
// rendering.
skipErrors: false,
/**
* CAMERA SETTINGS:
* ****************
*/
// {number} The power degrees applied to the nodes/edges size relatively to
// the zooming level. Basically:
// > onScreenR = Math.pow(zoom, nodesPowRatio) * R
// > onScreenT = Math.pow(zoom, edgesPowRatio) * T
nodesPowRatio: 0.5,
edgesPowRatio: 0.5,
/**
* ANIMATIONS SETTINGS:
* ********************
*/
// {number} The default animation time.
animationsTime: 200
};
// Export the previously designed settings:
sigma.settings = sigma.utils.extend(sigma.settings || {}, settings);
}).call(this);
;(function() {
'use strict';
/**
* Dispatcher constructor.
*
* @return {dispatcher} The new dispatcher instance.
*/
var dispatcher = function() {
Object.defineProperty(this, '_handlers', {
value: {}
});
};
/**
* Will execute the handler everytime that the indicated event (or the
* indicated events) will be triggered.
*
* @param {string} events The name of the event (or the events
* separated by spaces).
* @param {function(Object)} handler The handler to bind.
* @return {dispatcher} Returns the instance itself.
*/
dispatcher.prototype.bind = function(events, handler) {
var i,
l,
event,
eArray;
if (
arguments.length === 1 &&
typeof arguments[0] === 'object'
)
for (events in arguments[0])
this.bind(events, arguments[0][events]);
else if (
arguments.length === 2 &&
typeof arguments[1] === 'function'
) {
eArray = typeof events === 'string' ? events.split(' ') : events;
for (i = 0, l = eArray.length; i !== l; i += 1) {
event = eArray[i];
// Check that event is not '':
if (!event)
continue;
if (!this._handlers[event])
this._handlers[event] = [];
// Using an object instead of directly the handler will make possible
// later to add flags
this._handlers[event].push({
handler: handler
});
}
} else
throw 'bind: Wrong arguments.';
return this;
};
/**
* Removes the handler from a specified event (or specified events).
*
* @param {?string} events The name of the event (or the events
* separated by spaces). If undefined,
* then all handlers are removed.
* @param {?function(object)} handler The handler to unbind. If undefined,
* each handler bound to the event or the
* events will be removed.
* @return {dispatcher} Returns the instance itself.
*/
dispatcher.prototype.unbind = function(events, handler) {
var i,
n,
j,
m,
k,
a,
event,
eArray = typeof events === 'string' ? events.split(' ') : events;
if (!arguments.length) {
for (k in this._handlers)
delete this._handlers[k];
return this;
}
if (handler) {
for (i = 0, n = eArray.length; i !== n; i += 1) {
event = eArray[i];
if (this._handlers[event]) {
a = [];
for (j = 0, m = this._handlers[event].length; j !== m; j += 1)
if (this._handlers[event][j].handler !== handler)
a.push(this._handlers[event][j]);
this._handlers[event] = a;
}
if (this._handlers[event] && this._handlers[event].length === 0)
delete this._handlers[event];
}
} else
for (i = 0, n = eArray.length; i !== n; i += 1)
delete this._handlers[eArray[i]];
return this;
};
/**
* Executes each handler bound to the event
*
* @param {string} events The name of the event (or the events separated
* by spaces).
* @param {?object} data The content of the event (optional).
* @return {dispatcher} Returns the instance itself.
*/
dispatcher.prototype.dispatchEvent = function(events, data) {
var i,
n,
j,
m,
a,
event,
eventName,
self = this,
eArray = typeof events === 'string' ? events.split(' ') : events;
data = data === undefined ? {} : data;
for (i = 0, n = eArray.length; i !== n; i += 1) {
eventName = eArray[i];
if (this._handlers[eventName]) {
event = self.getEvent(eventName, data);
a = [];
for (j = 0, m = this._handlers[eventName].length; j !== m; j += 1) {
this._handlers[eventName][j].handler(event);
if (!this._handlers[eventName][j].one)
a.push(this._handlers[eventName][j]);
}
this._handlers[eventName] = a;
}
}
return this;
};
/**
* Return an event object.
*
* @param {string} events The name of the event.
* @param {?object} data The content of the event (optional).
* @return {object} Returns the instance itself.
*/
dispatcher.prototype.getEvent = function(event, data) {
return {
type: event,
data: data || {},
target: this
};
};
/**
* A useful function to deal with inheritance. It will make the target
* inherit the prototype of the class dispatcher as well as its constructor.
*
* @param {object} target The target.
*/
dispatcher.extend = function(target, args) {
var k;
for (k in dispatcher.prototype)
if (dispatcher.prototype.hasOwnProperty(k))
target[k] = dispatcher.prototype[k];
dispatcher.apply(target, args);
};
/**
* EXPORT:
* *******
*/
if (typeof this.sigma !== 'undefined') {
this.sigma.classes = this.sigma.classes || {};
this.sigma.classes.dispatcher = dispatcher;
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = dispatcher;
exports.dispatcher = dispatcher;
} else
this.dispatcher = dispatcher;
}).call(this);
;(function() {
'use strict';
/**
* This utils aims to facilitate the manipulation of each instance setting.
* Using a function instead of an object brings two main advantages: First,
* it will be easier in the future to catch settings updates through a
* function than an object. Second, giving it a full object will "merge" it
* to the settings object properly, keeping us to have to always add a loop.
*
* @return {configurable} The "settings" function.
*/
var configurable = function() {
var i,
l,
data = {},
datas = Array.prototype.slice.call(arguments, 0);
/**
* The method to use to set or get any property of this instance.
*
* @param {string|object} a1 If it is a string and if a2 is undefined,
* then it will return the corresponding
* property. If it is a string and if a2 is
* set, then it will set a2 as the property
* corresponding to a1, and return this. If
* it is an object, then each pair string +
* object(or any other type) will be set as a
* property.
* @param {*?} a2 The new property corresponding to a1 if a1
* is a string.
* @return {*|configurable} Returns itself or the corresponding
* property.
*
* Polymorphism:
* *************
* Here are some basic use examples:
*
* > settings = new configurable();
* > settings('mySetting', 42);
* > settings('mySetting'); // Logs: 42
* > settings('mySetting', 123);
* > settings('mySetting'); // Logs: 123
* > settings({mySetting: 456});
* > settings('mySetting'); // Logs: 456
*
* Also, it is possible to use the function as a fallback:
* > settings({mySetting: 'abc'}, 'mySetting'); // Logs: 'abc'
* > settings({hisSetting: 'abc'}, 'mySetting'); // Logs: 456
*/
var settings = function(a1, a2) {
var o,
i,
l,
k;
if (arguments.length === 1 && typeof a1 === 'string') {
if (data[a1] !== undefined)
return data[a1];
for (i = 0, l = datas.length; i < l; i++)
if (datas[i][a1] !== undefined)
return datas[i][a1];
return undefined;
} else if (typeof a1 === 'object' && typeof a2 === 'string') {
return (a1 || {})[a2] !== undefined ? a1[a2] : settings(a2);
} else {
o = (typeof a1 === 'object' && a2 === undefined) ? a1 : {};
if (typeof a1 === 'string')
o[a1] = a2;
for (i = 0, k = Object.keys(o), l = k.length; i < l; i++)
data[k[i]] = o[k[i]];
return this;
}
};
/**
* This method returns a new configurable function, with new objects
*
* @param {object*} Any number of objects to search in.
* @return {function} Returns the function. Check its documentation to know
* more about how it works.
*/
settings.embedObjects = function() {
var args = datas.concat(
data
).concat(
Array.prototype.splice.call(arguments, 0)
);
return configurable.apply({}, args);
};
// Initialize
for (i = 0, l = arguments.length; i < l; i++)
settings(arguments[i]);
return settings;
};
/**
* EXPORT:
* *******
*/
if (typeof this.sigma !== 'undefined') {
this.sigma.classes = this.sigma.classes || {};
this.sigma.classes.configurable = configurable;
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = configurable;
exports.configurable = configurable;
} else
this.configurable = configurable;
}).call(this);
;(function(undefined) {
'use strict';
var _methods = Object.create(null),
_indexes = Object.create(null),
_initBindings = Object.create(null),
_methodBindings = Object.create(null),
_methodBeforeBindings = Object.create(null),
_defaultSettings = {
immutable: true,
clone: true
},
_defaultSettingsFunction = function(key) {
return _defaultSettings[key];
};
/**
* The graph constructor. It initializes the data and the indexes, and binds
* the custom indexes and methods to its own scope.
*
* Recognized parameters:
* **********************
* Here is the exhaustive list of every accepted parameters in the settings
* object:
*
* {boolean} clone Indicates if the data have to be cloned in methods
* to add nodes or edges.
* {boolean} immutable Indicates if nodes "id" values and edges "id",
* "source" and "target" values must be set as
* immutable.
*
* @param {?configurable} settings Eventually a settings function.
* @return {graph} The new graph instance.
*/
var graph = function(settings) {
var k,
fn,
data;
/**
* DATA:
* *****
* Every data that is callable from graph methods are stored in this "data"
* object. This object will be served as context for all these methods,
* and it is possible to add other type of data in it.
*/
data = {
/**
* SETTINGS FUNCTION:
* ******************
*/
settings: settings || _defaultSettingsFunction,
/**
* MAIN DATA:
* **********
*/
nodesArray: [],
edgesArray: [],
/**
* GLOBAL INDEXES:
* ***************
* These indexes just index data by ids.
*/
nodesIndex: Object.create(null),
edgesIndex: Object.create(null),
/**
* LOCAL INDEXES:
* **************
* These indexes refer from node to nodes. Each key is an id, and each
* value is the array of the ids of related nodes.
*/
inNeighborsIndex: Object.create(null),
outNeighborsIndex: Object.create(null),
allNeighborsIndex: Object.create(null),
inNeighborsCount: Object.create(null),
outNeighborsCount: Object.create(null),
allNeighborsCount: Object.create(null)
};
// Execute bindings:
for (k in _initBindings)
_initBindings[k].call(data);
// Add methods to both the scope and the data objects:
for (k in _methods) {
fn = __bindGraphMethod(k, data, _methods[k]);
this[k] = fn;
data[k] = fn;
}
};
/**
* A custom tool to bind methods such that function that are bound to it will
* be executed anytime the method is called.
*
* @param {string} methodName The name of the method to bind.
* @param {object} scope The scope where the method must be executed.
* @param {function} fn The method itself.
* @return {function} The new method.
*/
function __bindGraphMethod(methodName, scope, fn) {
var result = function() {
var k,
res;
// Execute "before" bound functions:
for (k in _methodBeforeBindings[methodName])
_methodBeforeBindings[methodName][k].apply(scope, arguments);
// Apply the method:
res = fn.apply(scope, arguments);
// Execute bound functions:
for (k in _methodBindings[methodName])
_methodBindings[methodName][k].apply(scope, arguments);
// Return res:
return res;
};
return result;
}
/**
* This custom tool function removes every pair key/value from an hash. The
* goal is to avoid creating a new object while some other references are
* still hanging in some scopes...
*
* @param {object} obj The object to empty.
* @return {object} The empty object.
*/
function __emptyObject(obj) {
var k;
for (k in obj)
if (!('hasOwnProperty' in obj) || obj.hasOwnProperty(k))
delete obj[k];
return obj;
}
/**
* This global method adds a method that will be bound to the futurly created
* graph instances.
*
* Since these methods will be bound to their scope when the instances are
* created, it does not use the prototype. Because of that, methods have to
* be added before instances are created to make them available.
*
* Here is an example:
*
* > graph.addMethod('getNodesCount', function() {
* > return this.nodesArray.length;
* > });
* >
* > var myGraph = new graph();
* > console.log(myGraph.getNodesCount()); // outputs 0
*
* @param {string} methodName The name of the method.
* @param {function} fn The method itself.
* @return {object} The global graph constructor.
*/
graph.addMethod = function(methodName, fn) {
if (
typeof methodName !== 'string' ||
typeof fn !== 'function' ||
arguments.length !== 2
)
throw 'addMethod: Wrong arguments.';
if (_methods[methodName] || graph[methodName])
throw 'The method "' + methodName + '" already exists.';
_methods[methodName] = fn;
_methodBindings[methodName] = Object.create(null);
_methodBeforeBindings[methodName] = Object.create(null);
return this;
};
/**
* This global method returns true if the method has already been added, and
* false else.
*
* Here are some examples:
*
* > graph.hasMethod('addNode'); // returns true
* > graph.hasMethod('hasMethod'); // returns true
* > graph.hasMethod('unexistingMethod'); // returns false
*
* @param {string} methodName The name of the method.
* @return {boolean} The result.
*/
graph.hasMethod = function(methodName) {
return !!(_methods[methodName] || graph[methodName]);
};
/**
* This global methods attaches a function to a method. Anytime the specified
* method is called, the attached function is called right after, with the
* same arguments and in the same scope. The attached function is called
* right before if the last argument is true, unless the method is the graph
* constructor.
*
* To attach a function to the graph constructor, use 'constructor' as the
* method name (first argument).
*
* The main idea is to have a clean way to keep custom indexes up to date,
* for instance:
*
* > var timesAddNodeCalled = 0;
* > graph.attach('addNode', 'timesAddNodeCalledInc', function() {
* > timesAddNodeCalled++;
* > });
* >
* > var myGraph = new graph();
* > console.log(timesAddNodeCalled); // outputs 0
* >
* > myGraph.addNode({ id: '1' }).addNode({ id: '2' });
* > console.log(timesAddNodeCalled); // outputs 2
*
* The idea for calling a function before is to provide pre-processors, for
* instance:
*
* > var colorPalette = { Person: '#C3CBE1', Place: '#9BDEBD' };
* > graph.attach('addNode', 'applyNodeColorPalette', function(n) {
* > n.color = colorPalette[n.category];
* > }, true);
* >
* > var myGraph = new graph();
* > myGraph.addNode({ id: 'n0', category: 'Person' });
* > console.log(myGraph.nodes('n0').color); // outputs '#C3CBE1'
*
* @param {string} methodName The name of the related method or
* "constructor".
* @param {string} key The key to identify the function to attach.
* @param {function} fn The function to bind.
* @param {boolean} before If true the function is called right before.
* @return {object} The global graph constructor.
*/
graph.attach = function(methodName, key, fn, before) {
if (
typeof methodName !== 'string' ||
typeof key !== 'string' ||
typeof fn !== 'function' ||
arguments.length < 3 ||
arguments.length > 4
)
throw 'attach: Wrong arguments.';
var bindings;
if (methodName === 'constructor')
bindings = _initBindings;
else {
if (before) {
if (!_methodBeforeBindings[methodName])
throw 'The method "' + methodName + '" does not exist.';
bindings = _methodBeforeBindings[methodName];
}
else {
if (!_methodBindings[methodName])
throw 'The method "' + methodName + '" does not exist.';
bindings = _methodBindings[methodName];
}
}
if (bindings[key])
throw 'A function "' + key + '" is already attached ' +
'to the method "' + methodName + '".';
bindings[key] = fn;
return this;
};
/**
* Alias of attach(methodName, key, fn, true).
*/
graph.attachBefore = function(methodName, key, fn) {
return this.attach(methodName, key, fn, true);
};
/**
* This methods is just an helper to deal with custom indexes. It takes as
* arguments the name of the index and an object containing all the different
* functions to bind to the methods.
*
* Here is a basic example, that creates an index to keep the number of nodes
* in the current graph. It also adds a method to provide a getter on that
* new index:
*
* > sigma.classes.graph.addIndex('nodesCount', {
* > constructor: function() {
* > this.nodesCount = 0;
* > },
* > addNode: function() {
* > this.nodesCount++;
* > },
* > dropNode: function() {
* > this.nodesCount--;
* > }
* > });
* >
* > sigma.classes.graph.addMethod('getNodesCount', function() {
* > return this.nodesCount;
* > });
* >
* > var myGraph = new sigma.classes.graph();
* > console.log(myGraph.getNodesCount()); // outputs 0
* >
* > myGraph.addNode({ id: '1' }).addNode({ id: '2' });
* > console.log(myGraph.getNodesCount()); // outputs 2
*
* @param {string} name The name of the index.
* @param {object} bindings The object containing the functions to bind.
* @return {object} The global graph constructor.
*/
graph.addIndex = function(name, bindings) {
if (
typeof name !== 'string' ||
Object(bindings) !== bindings ||
arguments.length !== 2
)
throw 'addIndex: Wrong arguments.';
if (_indexes[name])
throw 'The index "' + name + '" already exists.';
var k;
// Store the bindings:
_indexes[name] = bindings;
// Attach the bindings:
for (k in bindings)
if (typeof bindings[k] !== 'function')
throw 'The bindings must be functions.';
else
graph.attach(k, name, bindings[k]);
return this;
};
/**
* This method adds a node to the graph. The node must be an object, with a
* string under the key "id". Except for this, it is possible to add any
* other attribute, that will be preserved all along the manipulations.
*
* If the graph option "clone" has a truthy value, the node will be cloned
* when added to the graph. Also, if the graph option "immutable" has a
* truthy value, its id will be defined as immutable.
*
* @param {object} node The node to add.
* @return {object} The graph instance.
*/
graph.addMethod('addNode', function(node) {
// Check that the node is an object and has an id:
if (Object(node) !== node || arguments.length !== 1)
throw 'addNode: Wrong arguments.';
if (typeof node.id !== 'string' && typeof node.id !== 'number')
throw 'The node must have a string or number id.';
if (this.nodesIndex[node.id])
throw 'The node "' + node.id + '" already exists.';
var k,
id = node.id,
validNode = Object.create(null);
// Check the "clone" option:
if (this.settings('clone')) {
for (k in node)
if (k !== 'id')
validNode[k] = node[k];
} else
validNode = node;
// Check the "immutable" option:
if (this.settings('immutable'))
Object.defineProperty(validNode, 'id', {
value: id,
enumerable: true
});
else
validNode.id = id;
// Add empty containers for edges indexes:
this.inNeighborsIndex[id] = Object.create(null);
this.outNeighborsIndex[id] = Object.create(null);
this.allNeighborsIndex[id] = Object.create(null);
this.inNeighborsCount[id] = 0;
this.outNeighborsCount[id] = 0;
this.allNeighborsCount[id] = 0;
// Add the node to indexes:
this.nodesArray.push(validNode);
this.nodesIndex[validNode.id] = validNode;
// Return the current instance:
return this;
});
/**
* This method adds an edge to the graph. The edge must be an object, with a
* string under the key "id", and strings under the keys "source" and
* "target" that design existing nodes. Except for this, it is possible to
* add any other attribute, that will be preserved all along the
* manipulations.
*
* If the graph option "clone" has a truthy value, the edge will be cloned
* when added to the graph. Also, if the graph option "immutable" has a
* truthy value, its id, source and target will be defined as immutable.
*
* @param {object} edge The edge to add.
* @return {object} The graph instance.
*/
graph.addMethod('addEdge', function(edge) {
// Check that the edge is an object and has an id:
if (Object(edge) !== edge || arguments.length !== 1)
throw 'addEdge: Wrong arguments.';
if (typeof edge.id !== 'string' && typeof edge.id !== 'number')
throw 'The edge must have a string or number id.';
if ((typeof edge.source !== 'string' && typeof edge.source !== 'number') ||
!this.nodesIndex[edge.source])
throw 'The edge source must have an existing node id.';
if ((typeof edge.target !== 'string' && typeof edge.target !== 'number') ||
!this.nodesIndex[edge.target])
throw 'The edge target must have an existing node id.';
if (this.edgesIndex[edge.id])
throw 'The edge "' + edge.id + '" already exists.';
var k,
validEdge = Object.create(null);
// Check the "clone" option:
if (this.settings('clone')) {
for (k in edge)
if (k !== 'id' && k !== 'source' && k !== 'target')
validEdge[k] = edge[k];
} else
validEdge = edge;
// Check the "immutable" option:
if (this.settings('immutable')) {
Object.defineProperty(validEdge, 'id', {
value: edge.id,
enumerable: true
});
Object.defineProperty(validEdge, 'source', {
value: edge.source,
enumerable: true
});
Object.defineProperty(validEdge, 'target', {
value: edge.target,
enumerable: true
});
} else {
validEdge.id = edge.id;
validEdge.source = edge.source;
validEdge.target = edge.target;
}
// Add the edge to indexes:
this.edgesArray.push(validEdge);
this.edgesIndex[validEdge.id] = validEdge;
if (!this.inNeighborsIndex[validEdge.target][validEdge.source])
this.inNeighborsIndex[validEdge.target][validEdge.source] =
Object.create(null);
this.inNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] =
validEdge;
if (!this.outNeighborsIndex[validEdge.source][validEdge.target])
this.outNeighborsIndex[validEdge.source][validEdge.target] =
Object.create(null);
this.outNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] =
validEdge;
if (!this.allNeighborsIndex[validEdge.source][validEdge.target])
this.allNeighborsIndex[validEdge.source][validEdge.target] =
Object.create(null);
this.allNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] =
validEdge;
if (validEdge.target !== validEdge.source) {
if (!this.allNeighborsIndex[validEdge.target][validEdge.source])
this.allNeighborsIndex[validEdge.target][validEdge.source] =
Object.create(null);
this.allNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] =
validEdge;
}
// Keep counts up to date:
this.inNeighborsCount[validEdge.target]++;
this.outNeighborsCount[validEdge.source]++;
this.allNeighborsCount[validEdge.target]++;
this.allNeighborsCount[validEdge.source]++;
return this;
});
/**
* This method drops a node from the graph. It also removes each edge that is
* bound to it, through the dropEdge method. An error is thrown if the node
* does not exist.
*
* @param {string} id The node id.
* @return {object} The graph instance.
*/
graph.addMethod('dropNode', function(id) {
// Check that the arguments are valid:
if ((typeof id !== 'string' && typeof id !== 'number') ||
arguments.length !== 1)
throw 'dropNode: Wrong arguments.';
if (!this.nodesIndex[id])
throw 'The node "' + id + '" does not exist.';
var i, k, l;
// Remove the node from indexes:
delete this.nodesIndex[id];
for (i = 0, l = this.nodesArray.length; i < l; i++)
if (this.nodesArray[i].id === id) {
this.nodesArray.splice(i, 1);
break;
}
// Remove related edges:
for (i = this.edgesArray.length - 1; i >= 0; i--)
if (this.edgesArray[i].source === id || this.edgesArray[i].target === id)
this.dropEdge(this.edgesArray[i].id);
// Remove related edge indexes:
delete this.inNeighborsIndex[id];
delete this.outNeighborsIndex[id];
delete this.allNeighborsIndex[id];
delete this.inNeighborsCount[id];
delete this.outNeighborsCount[id];
delete this.allNeighborsCount[id];
for (k in this.nodesIndex) {
delete this.inNeighborsIndex[k][id];
delete this.outNeighborsIndex[k][id];
delete this.allNeighborsIndex[k][id];
}
return this;
});
/**
* This method drops an edge from the graph. An error is thrown if the edge
* does not exist.
*
* @param {string} id The edge id.
* @return {object} The graph instance.
*/
graph.addMethod('dropEdge', function(id) {
// Check that the arguments are valid:
if ((typeof id !== 'string' && typeof id !== 'number') ||
arguments.length !== 1)
throw 'dropEdge: Wrong arguments.';
if (!this.edgesIndex[id])
throw 'The edge "' + id + '" does not exist.';
var i, l, edge;
// Remove the edge from indexes:
edge = this.edgesIndex[id];
delete this.edgesIndex[id];
for (i = 0, l = this.edgesArray.length; i < l; i++)
if (this.edgesArray[i].id === id) {
this.edgesArray.splice(i, 1);
break;
}
delete this.inNeighborsIndex[edge.target][edge.source][edge.id];
if (!Object.keys(this.inNeighborsIndex[edge.target][edge.source]).length)
delete this.inNeighborsIndex[edge.target][edge.source];
delete this.outNeighborsIndex[edge.source][edge.target][edge.id];
if (!Object.keys(this.outNeighborsIndex[edge.source][edge.target]).length)
delete this.outNeighborsIndex[edge.source][edge.target];
delete this.allNeighborsIndex[edge.source][edge.target][edge.id];
if (!Object.keys(this.allNeighborsIndex[edge.source][edge.target]).length)
delete this.allNeighborsIndex[edge.source][edge.target];
if (edge.target !== edge.source) {
delete this.allNeighborsIndex[edge.target][edge.source][edge.id];
if (!Object.keys(this.allNeighborsIndex[edge.target][edge.source]).length)
delete this.allNeighborsIndex[edge.target][edge.source];
}
this.inNeighborsCount[edge.target]--;
this.outNeighborsCount[edge.source]--;
this.allNeighborsCount[edge.source]--;
this.allNeighborsCount[edge.target]--;
return this;
});
/**
* This method destroys the current instance. It basically empties each index
* and methods attached to the graph.
*/
graph.addMethod('kill', function() {
// Delete arrays:
this.nodesArray.length = 0;
this.edgesArray.length = 0;
delete this.nodesArray;
delete this.edgesArray;
// Delete indexes:
delete this.nodesIndex;
delete this.edgesIndex;
delete this.inNeighborsIndex;
delete this.outNeighborsIndex;
delete this.allNeighborsIndex;
delete this.inNeighborsCount;
delete this.outNeighborsCount;
delete this.allNeighborsCount;
});
/**
* This method empties the nodes and edges arrays, as well as the different
* indexes.
*
* @return {object} The graph instance.
*/
graph.addMethod('clear', function() {
this.nodesArray.length = 0;
this.edgesArray.length = 0;
// Due to GC issues, I prefer not to create new object. These objects are
// only available from the methods and attached functions, but still, it is
// better to prevent ghost references to unrelevant data...
__emptyObject(this.nodesIndex);
__emptyObject(this.edgesIndex);
__emptyObject(this.nodesIndex);
__emptyObject(this.inNeighborsIndex);
__emptyObject(this.outNeighborsIndex);
__emptyObject(this.allNeighborsIndex);
__emptyObject(this.inNeighborsCount);
__emptyObject(this.outNeighborsCount);
__emptyObject(this.allNeighborsCount);
return this;
});
/**
* This method reads an object and adds the nodes and edges, through the
* proper methods "addNode" and "addEdge".
*
* Here is an example:
*
* > var myGraph = new graph();
* > myGraph.read({
* > nodes: [
* > { id: 'n0' },
* > { id: 'n1' }
* > ],
* > edges: [
* > {
* > id: 'e0',
* > source: 'n0',
* > target: 'n1'
* > }
* > ]
* > });
* >
* > console.log(
* > myGraph.nodes().length,
* > myGraph.edges().length
* > ); // outputs 2 1
*
* @param {object} g The graph object.
* @return {object} The graph instance.
*/
graph.addMethod('read', function(g) {
var i,
a,
l;
a = g.nodes || [];
for (i = 0, l = a.length; i < l; i++)
this.addNode(a[i]);
a = g.edges || [];
for (i = 0, l = a.length; i < l; i++)
this.addEdge(a[i]);
return this;
});
/**
* This methods returns one or several nodes, depending on how it is called.
*
* To get the array of nodes, call "nodes" without argument. To get a
* specific node, call it with the id of the node. The get multiple node,
* call it with an array of ids, and it will return the array of nodes, in
* the same order.
*
* @param {?(string|array)} v Eventually one id, an array of ids.
* @return {object|array} The related node or array of nodes.
*/
graph.addMethod('nodes', function(v) {
// Clone the array of nodes and return it:
if (!arguments.length)
return this.nodesArray.slice(0);
// Return the related node:
if (arguments.length === 1 &&
(typeof v === 'string' || typeof v === 'number'))
return this.nodesIndex[v];
// Return an array of the related node:
if (
arguments.length === 1 &&
Object.prototype.toString.call(v) === '[object Array]'
) {
var i,
l,
a = [];
for (i = 0, l = v.length; i < l; i++)
if (typeof v[i] === 'string' || typeof v[i] === 'number')
a.push(this.nodesIndex[v[i]]);
else
throw 'nodes: Wrong arguments.';
return a;
}
throw 'nodes: Wrong arguments.';
});
/**
* This methods returns the degree of one or several nodes, depending on how
* it is called. It is also possible to get incoming or outcoming degrees
* instead by specifying 'in' or 'out' as a second argument.
*
* @param {string|array} v One id, an array of ids.
* @param {?string} which Which degree is required. Values are 'in',
* 'out', and by default the normal degree.
* @return {number|array} The related degree or array of degrees.
*/
graph.addMethod('degree', function(v, which) {
// Check which degree is required:
which = {
'in': this.inNeighborsCount,
'out': this.outNeighborsCount
}[which || ''] || this.allNeighborsCount;
// Return the related node:
if (typeof v === 'string' || typeof v === 'number')
return which[v];
// Return an array of the related node:
if (Object.prototype.toString.call(v) === '[object Array]') {
var i,
l,
a = [];
for (i = 0, l = v.length; i < l; i++)
if (typeof v[i] === 'string' || typeof v[i] === 'number')
a.push(which[v[i]]);
else
throw 'degree: Wrong arguments.';
return a;
}
throw 'degree: Wrong arguments.';
});
/**
* This methods returns one or several edges, depending on how it is called.
*
* To get the array of edges, call "edges" without argument. To get a
* specific edge, call it with the id of the edge. The get multiple edge,
* call it with an array of ids, and it will return the array of edges, in
* the same order.
*
* @param {?(string|array)} v Eventually one id, an array of ids.
* @return {object|array} The related edge or array of edges.
*/
graph.addMethod('edges', function(v) {
// Clone the array of edges and return it:
if (!arguments.length)
return this.edgesArray.slice(0);
// Return the related edge:
if (arguments.length === 1 &&
(typeof v === 'string' || typeof v === 'number'))
return this.edgesIndex[v];
// Return an array of the related edge:
if (
arguments.length === 1 &&
Object.prototype.toString.call(v) === '[object Array]'
) {
var i,
l,
a = [];
for (i = 0, l = v.length; i < l; i++)
if (typeof v[i] === 'string' || typeof v[i] === 'number')
a.push(this.edgesIndex[v[i]]);
else
throw 'edges: Wrong arguments.';
return a;
}
throw 'edges: Wrong arguments.';
});
/**
* EXPORT:
* *******
*/
if (typeof sigma !== 'undefined') {
sigma.classes = sigma.classes || Object.create(null);
sigma.classes.graph = graph;
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = graph;
exports.graph = graph;
} else
this.graph = graph;
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
sigma.utils.pkg('sigma.classes');
/**
* The camera constructor. It just initializes its attributes and methods.
*
* @param {string} id The id.
* @param {sigma.classes.graph} graph The graph.
* @param {configurable} settings The settings function.
* @param {?object} options Eventually some overriding options.
* @return {camera} Returns the fresh new camera instance.
*/
sigma.classes.camera = function(id, graph, settings, options) {
sigma.classes.dispatcher.extend(this);
Object.defineProperty(this, 'graph', {
value: graph
});
Object.defineProperty(this, 'id', {
value: id
});
Object.defineProperty(this, 'readPrefix', {
value: 'read_cam' + id + ':'
});
Object.defineProperty(this, 'prefix', {
value: 'cam' + id + ':'
});
this.x = 0;
this.y = 0;
this.ratio = 1;
this.angle = 0;
this.isAnimated = false;
this.settings = (typeof options === 'object' && options) ?
settings.embedObject(options) :
settings;
};
/**
* Updates the camera position.
*
* @param {object} coordinates The new coordinates object.
* @return {camera} Returns the camera.
*/
sigma.classes.camera.prototype.goTo = function(coordinates) {
if (!this.settings('enableCamera'))
return this;
var i,
l,
c = coordinates || {},
keys = ['x', 'y', 'ratio', 'angle'];
for (i = 0, l = keys.length; i < l; i++)
if (c[keys[i]] !== undefined) {
if (typeof c[keys[i]] === 'number' && !isNaN(c[keys[i]]))
this[keys[i]] = c[keys[i]];
else
throw 'Value for "' + keys[i] + '" is not a number.';
}
this.dispatchEvent('coordinatesUpdated');
return this;
};
/**
* This method takes a graph and computes for each node and edges its
* coordinates relatively to the center of the camera. Basically, it will
* compute the coordinates that will be used by the graphic renderers.
*
* Since it should be possible to use different cameras and different
* renderers, it is possible to specify a prefix to put before the new
* coordinates (to get something like "node.camera1_x")
*
* @param {?string} read The prefix of the coordinates to read.
* @param {?string} write The prefix of the coordinates to write.
* @param {?object} options Eventually an object of options. Those can be:
* - A restricted nodes array.
* - A restricted edges array.
* - A width.
* - A height.
* @return {camera} Returns the camera.
*/
sigma.classes.camera.prototype.applyView = function(read, write, options) {
options = options || {};
write = write !== undefined ? write : this.prefix;
read = read !== undefined ? read : this.readPrefix;
var nodes = options.nodes || this.graph.nodes(),
edges = options.edges || this.graph.edges();
var i,
l,
node,
cos = Math.cos(this.angle),
sin = Math.sin(this.angle);
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
node[write + 'x'] =
(
((node[read + 'x'] || 0) - this.x) * cos +
((node[read + 'y'] || 0) - this.y) * sin
) / this.ratio + (options.width || 0) / 2;
node[write + 'y'] =
(
((node[read + 'y'] || 0) - this.y) * cos -
((node[read + 'x'] || 0) - this.x) * sin
) / this.ratio + (options.height || 0) / 2;
node[write + 'size'] =
(node[read + 'size'] || 0) /
Math.pow(this.ratio, this.settings('nodesPowRatio'));
}
for (i = 0, l = edges.length; i < l; i++) {
edges[i][write + 'size'] =
(edges[i][read + 'size'] || 0) /
Math.pow(this.ratio, this.settings('edgesPowRatio'));
}
return this;
};
/**
* This function converts the coordinates of a point from the frame of the
* camera to the frame of the graph.
*
* @param {number} x The X coordinate of the point in the frame of the
* camera.
* @param {number} y The Y coordinate of the point in the frame of the
* camera.
* @return {object} The point coordinates in the frame of the graph.
*/
sigma.classes.camera.prototype.graphPosition = function(x, y, vector) {
var X = 0,
Y = 0,
cos = Math.cos(this.angle),
sin = Math.sin(this.angle);
// Revert the origin differential vector:
if (!vector) {
X = - (this.x * cos + this.y * sin) / this.ratio;
Y = - (this.y * cos - this.x * sin) / this.ratio;
}
return {
x: (x * cos + y * sin) / this.ratio + X,
y: (y * cos - x * sin) / this.ratio + Y
};
};
/**
* This function converts the coordinates of a point from the frame of the
* graph to the frame of the camera.
*
* @param {number} x The X coordinate of the point in the frame of the
* graph.
* @param {number} y The Y coordinate of the point in the frame of the
* graph.
* @return {object} The point coordinates in the frame of the camera.
*/
sigma.classes.camera.prototype.cameraPosition = function(x, y, vector) {
var X = 0,
Y = 0,
cos = Math.cos(this.angle),
sin = Math.sin(this.angle);
// Revert the origin differential vector:
if (!vector) {
X = - (this.x * cos + this.y * sin) / this.ratio;
Y = - (this.y * cos - this.x * sin) / this.ratio;
}
return {
x: ((x - X) * cos - (y - Y) * sin) * this.ratio,
y: ((y - Y) * cos + (x - X) * sin) * this.ratio
};
};
/**
* This method returns the transformation matrix of the camera. This is
* especially useful to apply the camera view directly in shaders, in case of
* WebGL rendering.
*
* @return {array} The transformation matrix.
*/
sigma.classes.camera.prototype.getMatrix = function() {
var scale = sigma.utils.matrices.scale(1 / this.ratio),
rotation = sigma.utils.matrices.rotation(this.angle),
translation = sigma.utils.matrices.translation(-this.x, -this.y),
matrix = sigma.utils.matrices.multiply(
translation,
sigma.utils.matrices.multiply(
rotation,
scale
)
);
return matrix;
};
/**
* Taking a width and a height as parameters, this method returns the
* coordinates of the rectangle representing the camera on screen, in the
* graph's referentiel.
*
* To keep displaying labels of nodes going out of the screen, the method
* keeps a margin around the screen in the returned rectangle.
*
* @param {number} width The width of the screen.
* @param {number} height The height of the screen.
* @return {object} The rectangle as x1, y1, x2 and y2, representing
* two opposite points.
*/
sigma.classes.camera.prototype.getRectangle = function(width, height) {
var widthVect = this.cameraPosition(width, 0, true),
heightVect = this.cameraPosition(0, height, true),
centerVect = this.cameraPosition(width / 2, height / 2, true),
marginX = this.cameraPosition(width / 4, 0, true).x,
marginY = this.cameraPosition(0, height / 4, true).y;
return {
x1: this.x - centerVect.x - marginX,
y1: this.y - centerVect.y - marginY,
x2: this.x - centerVect.x + marginX + widthVect.x,
y2: this.y - centerVect.y - marginY + widthVect.y,
height: Math.sqrt(
Math.pow(heightVect.x, 2) +
Math.pow(heightVect.y + 2 * marginY, 2)
)
};
};
}).call(this);
;(function(undefined) {
'use strict';
/**
* Sigma Quadtree Module
* =====================
*
* Author: Guillaume Plique (Yomguithereal)
* Version: 0.2
*/
/**
* Quad Geometric Operations
* -------------------------
*
* A useful batch of geometric operations used by the quadtree.
*/
var _geom = {
/**
* Transforms a graph node with x, y and size into an
* axis-aligned square.
*
* @param {object} A graph node with at least a point (x, y) and a size.
* @return {object} A square: two points (x1, y1), (x2, y2) and height.
*/
pointToSquare: function(n) {
return {
x1: n.x - n.size,
y1: n.y - n.size,
x2: n.x + n.size,
y2: n.y - n.size,
height: n.size * 2
};
},
/**
* Checks whether a rectangle is axis-aligned.
*
* @param {object} A rectangle defined by two points
* (x1, y1) and (x2, y2).
* @return {boolean} True if the rectangle is axis-aligned.
*/
isAxisAligned: function(r) {
return r.x1 === r.x2 || r.y1 === r.y2;
},
/**
* Compute top points of an axis-aligned rectangle. This is useful in
* cases when the rectangle has been rotated (left, right or bottom up) and
* later operations need to know the top points.
*
* @param {object} An axis-aligned rectangle defined by two points
* (x1, y1), (x2, y2) and height.
* @return {object} A rectangle: two points (x1, y1), (x2, y2) and height.
*/
axisAlignedTopPoints: function(r) {
// Basic
if (r.y1 === r.y2 && r.x1 < r.x2)
return r;
// Rotated to right
if (r.x1 === r.x2 && r.y2 > r.y1)
return {
x1: r.x1 - r.height, y1: r.y1,
x2: r.x1, y2: r.y1,
height: r.height
};
// Rotated to left
if (r.x1 === r.x2 && r.y2 < r.y1)
return {
x1: r.x1, y1: r.y2,
x2: r.x2 + r.height, y2: r.y2,
height: r.height
};
// Bottom's up
return {
x1: r.x2, y1: r.y1 - r.height,
x2: r.x1, y2: r.y1 - r.height,
height: r.height
};
},
/**
* Get coordinates of a rectangle's lower left corner from its top points.
*
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2).
* @return {object} Coordinates of the corner (x, y).
*/
lowerLeftCoor: function(r) {
var width = (
Math.sqrt(
Math.pow(r.x2 - r.x1, 2) +
Math.pow(r.y2 - r.y1, 2)
)
);
return {
x: r.x1 - (r.y2 - r.y1) * r.height / width,
y: r.y1 + (r.x2 - r.x1) * r.height / width
};
},
/**
* Get coordinates of a rectangle's lower right corner from its top points
* and its lower left corner.
*
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2).
* @param {object} A corner's coordinates (x, y).
* @return {object} Coordinates of the corner (x, y).
*/
lowerRightCoor: function(r, llc) {
return {
x: llc.x - r.x1 + r.x2,
y: llc.y - r.y1 + r.y2
};
},
/**
* Get the coordinates of all the corners of a rectangle from its top point.
*
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2).
* @return {array} An array of the four corners' coordinates (x, y).
*/
rectangleCorners: function(r) {
var llc = this.lowerLeftCoor(r),
lrc = this.lowerRightCoor(r, llc);
return [
{x: r.x1, y: r.y1},
{x: r.x2, y: r.y2},
{x: llc.x, y: llc.y},
{x: lrc.x, y: lrc.y}
];
},
/**
* Split a square defined by its boundaries into four.
*
* @param {object} Boundaries of the square (x, y, width, height).
* @return {array} An array containing the four new squares, themselves
* defined by an array of their four corners (x, y).
*/
splitSquare: function(b) {
return [
[
{x: b.x, y: b.y},
{x: b.x + b.width / 2, y: b.y},
{x: b.x, y: b.y + b.height / 2},
{x: b.x + b.width / 2, y: b.y + b.height / 2}
],
[
{x: b.x + b.width / 2, y: b.y},
{x: b.x + b.width, y: b.y},
{x: b.x + b.width / 2, y: b.y + b.height / 2},
{x: b.x + b.width, y: b.y + b.height / 2}
],
[
{x: b.x, y: b.y + b.height / 2},
{x: b.x + b.width / 2, y: b.y + b.height / 2},
{x: b.x, y: b.y + b.height},
{x: b.x + b.width / 2, y: b.y + b.height}
],
[
{x: b.x + b.width / 2, y: b.y + b.height / 2},
{x: b.x + b.width, y: b.y + b.height / 2},
{x: b.x + b.width / 2, y: b.y + b.height},
{x: b.x + b.width, y: b.y + b.height}
]
];
},
/**
* Compute the four axis between corners of rectangle A and corners of
* rectangle B. This is needed later to check an eventual collision.
*
* @param {array} An array of rectangle A's four corners (x, y).
* @param {array} An array of rectangle B's four corners (x, y).
* @return {array} An array of four axis defined by their coordinates (x,y).
*/
axis: function(c1, c2) {
return [
{x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y},
{x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y},
{x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y},
{x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y}
];
},
/**
* Project a rectangle's corner on an axis.
*
* @param {object} Coordinates of a corner (x, y).
* @param {object} Coordinates of an axis (x, y).
* @return {object} The projection defined by coordinates (x, y).
*/
projection: function(c, a) {
var l = (
(c.x * a.x + c.y * a.y) /
(Math.pow(a.x, 2) + Math.pow(a.y, 2))
);
return {
x: l * a.x,
y: l * a.y
};
},
/**
* Check whether two rectangles collide on one particular axis.
*
* @param {object} An axis' coordinates (x, y).
* @param {array} Rectangle A's corners.
* @param {array} Rectangle B's corners.
* @return {boolean} True if the rectangles collide on the axis.
*/
axisCollision: function(a, c1, c2) {
var sc1 = [],
sc2 = [];
for (var ci = 0; ci < 4; ci++) {
var p1 = this.projection(c1[ci], a),
p2 = this.projection(c2[ci], a);
sc1.push(p1.x * a.x + p1.y * a.y);
sc2.push(p2.x * a.x + p2.y * a.y);
}
var maxc1 = Math.max.apply(Math, sc1),
maxc2 = Math.max.apply(Math, sc2),
minc1 = Math.min.apply(Math, sc1),
minc2 = Math.min.apply(Math, sc2);
return (minc2 <= maxc1 && maxc2 >= minc1);
},
/**
* Check whether two rectangles collide on each one of their four axis. If
* all axis collide, then the two rectangles do collide on the plane.
*
* @param {array} Rectangle A's corners.
* @param {array} Rectangle B's corners.
* @return {boolean} True if the rectangles collide.
*/
collision: function(c1, c2) {
var axis = this.axis(c1, c2),
col = true;
for (var i = 0; i < 4; i++)
col = col && this.axisCollision(axis[i], c1, c2);
return col;
}
};
/**
* Quad Functions
* ------------
*
* The Quadtree functions themselves.
* For each of those functions, we consider that in a splitted quad, the
* index of each node is the following:
* 0: top left
* 1: top right
* 2: bottom left
* 3: bottom right
*
* Moreover, the hereafter quad's philosophy is to consider that if an element
* collides with more than one nodes, this element belongs to each of the
* nodes it collides with where other would let it lie on a higher node.
*/
/**
* Get the index of the node containing the point in the quad
*
* @param {object} point A point defined by coordinates (x, y).
* @param {object} quadBounds Boundaries of the quad (x, y, width, heigth).
* @return {integer} The index of the node containing the point.
*/
function _quadIndex(point, quadBounds) {
var xmp = quadBounds.x + quadBounds.width / 2,
ymp = quadBounds.y + quadBounds.height / 2,
top = (point.y < ymp),
left = (point.x < xmp);
if (top) {
if (left)
return 0;
else
return 1;
}
else {
if (left)
return 2;
else
return 3;
}
}
/**
* Get a list of indexes of nodes containing an axis-aligned rectangle
*
* @param {object} rectangle A rectangle defined by two points (x1, y1),
* (x2, y2) and height.
* @param {array} quadCorners An array of the quad nodes' corners.
* @return {array} An array of indexes containing one to
* four integers.
*/
function _quadIndexes(rectangle, quadCorners) {
var indexes = [];
// Iterating through quads
for (var i = 0; i < 4; i++)
if ((rectangle.x2 >= quadCorners[i][0].x) &&
(rectangle.x1 <= quadCorners[i][1].x) &&
(rectangle.y1 + rectangle.height >= quadCorners[i][0].y) &&
(rectangle.y1 <= quadCorners[i][2].y))
indexes.push(i);
return indexes;
}
/**
* Get a list of indexes of nodes containing a non-axis-aligned rectangle
*
* @param {array} corners An array containing each corner of the
* rectangle defined by its coordinates (x, y).
* @param {array} quadCorners An array of the quad nodes' corners.
* @return {array} An array of indexes containing one to
* four integers.
*/
function _quadCollision(corners, quadCorners) {
var indexes = [];
// Iterating through quads
for (var i = 0; i < 4; i++)
if (_geom.collision(corners, quadCorners[i]))
indexes.push(i);
return indexes;
}
/**
* Subdivide a quad by creating a node at a precise index. The function does
* not generate all four nodes not to potentially create unused nodes.
*
* @param {integer} index The index of the node to create.
* @param {object} quad The quad object to subdivide.
* @return {object} A new quad representing the node created.
*/
function _quadSubdivide(index, quad) {
var next = quad.level + 1,
subw = Math.round(quad.bounds.width / 2),
subh = Math.round(quad.bounds.height / 2),
qx = Math.round(quad.bounds.x),
qy = Math.round(quad.bounds.y),
x,
y;
switch (index) {
case 0:
x = qx;
y = qy;
break;
case 1:
x = qx + subw;
y = qy;
break;
case 2:
x = qx;
y = qy + subh;
break;
case 3:
x = qx + subw;
y = qy + subh;
break;
}
return _quadTree(
{x: x, y: y, width: subw, height: subh},
next,
quad.maxElements,
quad.maxLevel
);
}
/**
* Recursively insert an element into the quadtree. Only points
* with size, i.e. axis-aligned squares, may be inserted with this
* method.
*
* @param {object} el The element to insert in the quadtree.
* @param {object} sizedPoint A sized point defined by two top points
* (x1, y1), (x2, y2) and height.
* @param {object} quad The quad in which to insert the element.
* @return {undefined} The function does not return anything.
*/
function _quadInsert(el, sizedPoint, quad) {
if (quad.level < quad.maxLevel) {
// Searching appropriate quads
var indexes = _quadIndexes(sizedPoint, quad.corners);
// Iterating
for (var i = 0, l = indexes.length; i < l; i++) {
// Subdividing if necessary
if (quad.nodes[indexes[i]] === undefined)
quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad);
// Recursion
_quadInsert(el, sizedPoint, quad.nodes[indexes[i]]);
}
}
else {
// Pushing the element in a leaf node
quad.elements.push(el);
}
}
/**
* Recursively retrieve every elements held by the node containing the
* searched point.
*
* @param {object} point The searched point (x, y).
* @param {object} quad The searched quad.
* @return {array} An array of elements contained in the relevant
* node.
*/
function _quadRetrievePoint(point, quad) {
if (quad.level < quad.maxLevel) {
var index = _quadIndex(point, quad.bounds);
// If node does not exist we return an empty list
if (quad.nodes[index] !== undefined) {
return _quadRetrievePoint(point, quad.nodes[index]);
}
else {
return [];
}
}
else {
return quad.elements;
}
}
/**
* Recursively retrieve every elements contained within an rectangular area
* that may or may not be axis-aligned.
*
* @param {object|array} rectData The searched area defined either by
* an array of four corners (x, y) in
* the case of a non-axis-aligned
* rectangle or an object with two top
* points (x1, y1), (x2, y2) and height.
* @param {object} quad The searched quad.
* @param {function} collisionFunc The collision function used to search
* for node indexes.
* @param {array?} els The retrieved elements.
* @return {array} An array of elements contained in the
* area.
*/
function _quadRetrieveArea(rectData, quad, collisionFunc, els) {
els = els || {};
if (quad.level < quad.maxLevel) {
var indexes = collisionFunc(rectData, quad.corners);
for (var i = 0, l = indexes.length; i < l; i++)
if (quad.nodes[indexes[i]] !== undefined)
_quadRetrieveArea(
rectData,
quad.nodes[indexes[i]],
collisionFunc,
els
);
} else
for (var j = 0, m = quad.elements.length; j < m; j++)
if (els[quad.elements[j].id] === undefined)
els[quad.elements[j].id] = quad.elements[j];
return els;
}
/**
* Creates the quadtree object itself.
*
* @param {object} bounds The boundaries of the quad defined by an
* origin (x, y), width and heigth.
* @param {integer} level The level of the quad in the tree.
* @param {integer} maxElements The max number of element in a leaf node.
* @param {integer} maxLevel The max recursion level of the tree.
* @return {object} The quadtree object.
*/
function _quadTree(bounds, level, maxElements, maxLevel) {
return {
level: level || 0,
bounds: bounds,
corners: _geom.splitSquare(bounds),
maxElements: maxElements || 20,
maxLevel: maxLevel || 4,
elements: [],
nodes: []
};
}
/**
* Sigma Quad Constructor
* ----------------------
*
* The quad API as exposed to sigma.
*/
/**
* The quad core that will become the sigma interface with the quadtree.
*
* property {object} _tree Property holding the quadtree object.
* property {object} _geom Exposition of the _geom namespace for testing.
* property {object} _cache Cache for the area method.
*/
var quad = function() {
this._geom = _geom;
this._tree = null;
this._cache = {
query: false,
result: false
};
};
/**
* Index a graph by inserting its nodes into the quadtree.
*
* @param {array} nodes An array of nodes to index.
* @param {object} params An object of parameters with at least the quad
* bounds.
* @return {object} The quadtree object.
*
* Parameters:
* ----------
* bounds: {object} boundaries of the quad defined by its origin (x, y)
* width and heigth.
* prefix: {string?} a prefix for node geometric attributes.
* maxElements: {integer?} the max number of elements in a leaf node.
* maxLevel: {integer?} the max recursion level of the tree.
*/
quad.prototype.index = function(nodes, params) {
// Enforcing presence of boundaries
if (!params.bounds)
throw 'sigma.classes.quad.index: bounds information not given.';
// Prefix
var prefix = params.prefix || '';
// Building the tree
this._tree = _quadTree(
params.bounds,
0,
params.maxElements,
params.maxLevel
);
// Inserting graph nodes into the tree
for (var i = 0, l = nodes.length; i < l; i++) {
// Inserting node
_quadInsert(
nodes[i],
_geom.pointToSquare({
x: nodes[i][prefix + 'x'],
y: nodes[i][prefix + 'y'],
size: nodes[i][prefix + 'size']
}),
this._tree
);
}
// Reset cache:
this._cache = {
query: false,
result: false
};
// remove?
return this._tree;
};
/**
* Retrieve every graph nodes held by the quadtree node containing the
* searched point.
*
* @param {number} x of the point.
* @param {number} y of the point.
* @return {array} An array of nodes retrieved.
*/
quad.prototype.point = function(x, y) {
return this._tree ?
_quadRetrievePoint({x: x, y: y}, this._tree) || [] :
[];
};
/**
* Retrieve every graph nodes within a rectangular area. The methods keep the
* last area queried in cache for optimization reason and will act differently
* for the same reason if the area is axis-aligned or not.
*
* @param {object} A rectangle defined by two top points (x1, y1), (x2, y2)
* and height.
* @return {array} An array of nodes retrieved.
*/
quad.prototype.area = function(rect) {
var serialized = JSON.stringify(rect),
collisionFunc,
rectData;
// Returning cache?
if (this._cache.query === serialized)
return this._cache.result;
// Axis aligned ?
if (_geom.isAxisAligned(rect)) {
collisionFunc = _quadIndexes;
rectData = _geom.axisAlignedTopPoints(rect);
}
else {
collisionFunc = _quadCollision;
rectData = _geom.rectangleCorners(rect);
}
// Retrieving nodes
var nodes = this._tree ?
_quadRetrieveArea(
rectData,
this._tree,
collisionFunc
) :
[];
// Object to array
var nodesArray = [];
for (var i in nodes)
nodesArray.push(nodes[i]);
// Caching
this._cache.query = serialized;
this._cache.result = nodesArray;
return nodesArray;
};
/**
* EXPORT:
* *******
*/
if (typeof this.sigma !== 'undefined') {
this.sigma.classes = this.sigma.classes || {};
this.sigma.classes.quad = quad;
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = quad;
exports.quad = quad;
} else
this.quad = quad;
}).call(this);
;(function(undefined) {
'use strict';
/**
* Sigma Quadtree Module for edges
* ===============================
*
* Author: Sébastien Heymann,
* from the quad of Guillaume Plique (Yomguithereal)
* Version: 0.2
*/
/**
* Quad Geometric Operations
* -------------------------
*
* A useful batch of geometric operations used by the quadtree.
*/
var _geom = {
/**
* Transforms a graph node with x, y and size into an
* axis-aligned square.
*
* @param {object} A graph node with at least a point (x, y) and a size.
* @return {object} A square: two points (x1, y1), (x2, y2) and height.
*/
pointToSquare: function(n) {
return {
x1: n.x - n.size,
y1: n.y - n.size,
x2: n.x + n.size,
y2: n.y - n.size,
height: n.size * 2
};
},
/**
* Transforms a graph edge with x1, y1, x2, y2 and size into an
* axis-aligned square.
*
* @param {object} A graph edge with at least two points
* (x1, y1), (x2, y2) and a size.
* @return {object} A square: two points (x1, y1), (x2, y2) and height.
*/
lineToSquare: function(e) {
if (e.y1 < e.y2) {
// (e.x1, e.y1) on top
if (e.x1 < e.x2) {
// (e.x1, e.y1) on left
return {
x1: e.x1 - e.size,
y1: e.y1 - e.size,
x2: e.x2 + e.size,
y2: e.y1 - e.size,
height: e.y2 - e.y1 + e.size * 2
};
}
// (e.x1, e.y1) on right
return {
x1: e.x2 - e.size,
y1: e.y1 - e.size,
x2: e.x1 + e.size,
y2: e.y1 - e.size,
height: e.y2 - e.y1 + e.size * 2
};
}
// (e.x2, e.y2) on top
if (e.x1 < e.x2) {
// (e.x1, e.y1) on left
return {
x1: e.x1 - e.size,
y1: e.y2 - e.size,
x2: e.x2 + e.size,
y2: e.y2 - e.size,
height: e.y1 - e.y2 + e.size * 2
};
}
// (e.x2, e.y2) on right
return {
x1: e.x2 - e.size,
y1: e.y2 - e.size,
x2: e.x1 + e.size,
y2: e.y2 - e.size,
height: e.y1 - e.y2 + e.size * 2
};
},
/**
* Transforms a graph edge of type 'curve' with x1, y1, x2, y2,
* control point and size into an axis-aligned square.
*
* @param {object} e A graph edge with at least two points
* (x1, y1), (x2, y2) and a size.
* @param {object} cp A control point (x,y).
* @return {object} A square: two points (x1, y1), (x2, y2) and height.
*/
quadraticCurveToSquare: function(e, cp) {
var pt = sigma.utils.getPointOnQuadraticCurve(
0.5,
e.x1,
e.y1,
e.x2,
e.y2,
cp.x,
cp.y
);
// Bounding box of the two points and the point at the middle of the
// curve:
var minX = Math.min(e.x1, e.x2, pt.x),
maxX = Math.max(e.x1, e.x2, pt.x),
minY = Math.min(e.y1, e.y2, pt.y),
maxY = Math.max(e.y1, e.y2, pt.y);
return {
x1: minX - e.size,
y1: minY - e.size,
x2: maxX + e.size,
y2: minY - e.size,
height: maxY - minY + e.size * 2
};
},
/**
* Transforms a graph self loop into an axis-aligned square.
*
* @param {object} n A graph node with a point (x, y) and a size.
* @return {object} A square: two points (x1, y1), (x2, y2) and height.
*/
selfLoopToSquare: function(n) {
// Fitting to the curve is too costly, we compute a larger bounding box
// using the control points:
var cp = sigma.utils.getSelfLoopControlPoints(n.x, n.y, n.size);
// Bounding box of the point and the two control points:
var minX = Math.min(n.x, cp.x1, cp.x2),
maxX = Math.max(n.x, cp.x1, cp.x2),
minY = Math.min(n.y, cp.y1, cp.y2),
maxY = Math.max(n.y, cp.y1, cp.y2);
return {
x1: minX - n.size,
y1: minY - n.size,
x2: maxX + n.size,
y2: minY - n.size,
height: maxY - minY + n.size * 2
};
},
/**
* Checks whether a rectangle is axis-aligned.
*
* @param {object} A rectangle defined by two points
* (x1, y1) and (x2, y2).
* @return {boolean} True if the rectangle is axis-aligned.
*/
isAxisAligned: function(r) {
return r.x1 === r.x2 || r.y1 === r.y2;
},
/**
* Compute top points of an axis-aligned rectangle. This is useful in
* cases when the rectangle has been rotated (left, right or bottom up) and
* later operations need to know the top points.
*
* @param {object} An axis-aligned rectangle defined by two points
* (x1, y1), (x2, y2) and height.
* @return {object} A rectangle: two points (x1, y1), (x2, y2) and height.
*/
axisAlignedTopPoints: function(r) {
// Basic
if (r.y1 === r.y2 && r.x1 < r.x2)
return r;
// Rotated to right
if (r.x1 === r.x2 && r.y2 > r.y1)
return {
x1: r.x1 - r.height, y1: r.y1,
x2: r.x1, y2: r.y1,
height: r.height
};
// Rotated to left
if (r.x1 === r.x2 && r.y2 < r.y1)
return {
x1: r.x1, y1: r.y2,
x2: r.x2 + r.height, y2: r.y2,
height: r.height
};
// Bottom's up
return {
x1: r.x2, y1: r.y1 - r.height,
x2: r.x1, y2: r.y1 - r.height,
height: r.height
};
},
/**
* Get coordinates of a rectangle's lower left corner from its top points.
*
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2).
* @return {object} Coordinates of the corner (x, y).
*/
lowerLeftCoor: function(r) {
var width = (
Math.sqrt(
Math.pow(r.x2 - r.x1, 2) +
Math.pow(r.y2 - r.y1, 2)
)
);
return {
x: r.x1 - (r.y2 - r.y1) * r.height / width,
y: r.y1 + (r.x2 - r.x1) * r.height / width
};
},
/**
* Get coordinates of a rectangle's lower right corner from its top points
* and its lower left corner.
*
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2).
* @param {object} A corner's coordinates (x, y).
* @return {object} Coordinates of the corner (x, y).
*/
lowerRightCoor: function(r, llc) {
return {
x: llc.x - r.x1 + r.x2,
y: llc.y - r.y1 + r.y2
};
},
/**
* Get the coordinates of all the corners of a rectangle from its top point.
*
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2).
* @return {array} An array of the four corners' coordinates (x, y).
*/
rectangleCorners: function(r) {
var llc = this.lowerLeftCoor(r),
lrc = this.lowerRightCoor(r, llc);
return [
{x: r.x1, y: r.y1},
{x: r.x2, y: r.y2},
{x: llc.x, y: llc.y},
{x: lrc.x, y: lrc.y}
];
},
/**
* Split a square defined by its boundaries into four.
*
* @param {object} Boundaries of the square (x, y, width, height).
* @return {array} An array containing the four new squares, themselves
* defined by an array of their four corners (x, y).
*/
splitSquare: function(b) {
return [
[
{x: b.x, y: b.y},
{x: b.x + b.width / 2, y: b.y},
{x: b.x, y: b.y + b.height / 2},
{x: b.x + b.width / 2, y: b.y + b.height / 2}
],
[
{x: b.x + b.width / 2, y: b.y},
{x: b.x + b.width, y: b.y},
{x: b.x + b.width / 2, y: b.y + b.height / 2},
{x: b.x + b.width, y: b.y + b.height / 2}
],
[
{x: b.x, y: b.y + b.height / 2},
{x: b.x + b.width / 2, y: b.y + b.height / 2},
{x: b.x, y: b.y + b.height},
{x: b.x + b.width / 2, y: b.y + b.height}
],
[
{x: b.x + b.width / 2, y: b.y + b.height / 2},
{x: b.x + b.width, y: b.y + b.height / 2},
{x: b.x + b.width / 2, y: b.y + b.height},
{x: b.x + b.width, y: b.y + b.height}
]
];
},
/**
* Compute the four axis between corners of rectangle A and corners of
* rectangle B. This is needed later to check an eventual collision.
*
* @param {array} An array of rectangle A's four corners (x, y).
* @param {array} An array of rectangle B's four corners (x, y).
* @return {array} An array of four axis defined by their coordinates (x,y).
*/
axis: function(c1, c2) {
return [
{x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y},
{x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y},
{x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y},
{x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y}
];
},
/**
* Project a rectangle's corner on an axis.
*
* @param {object} Coordinates of a corner (x, y).
* @param {object} Coordinates of an axis (x, y).
* @return {object} The projection defined by coordinates (x, y).
*/
projection: function(c, a) {
var l = (
(c.x * a.x + c.y * a.y) /
(Math.pow(a.x, 2) + Math.pow(a.y, 2))
);
return {
x: l * a.x,
y: l * a.y
};
},
/**
* Check whether two rectangles collide on one particular axis.
*
* @param {object} An axis' coordinates (x, y).
* @param {array} Rectangle A's corners.
* @param {array} Rectangle B's corners.
* @return {boolean} True if the rectangles collide on the axis.
*/
axisCollision: function(a, c1, c2) {
var sc1 = [],
sc2 = [];
for (var ci = 0; ci < 4; ci++) {
var p1 = this.projection(c1[ci], a),
p2 = this.projection(c2[ci], a);
sc1.push(p1.x * a.x + p1.y * a.y);
sc2.push(p2.x * a.x + p2.y * a.y);
}
var maxc1 = Math.max.apply(Math, sc1),
maxc2 = Math.max.apply(Math, sc2),
minc1 = Math.min.apply(Math, sc1),
minc2 = Math.min.apply(Math, sc2);
return (minc2 <= maxc1 && maxc2 >= minc1);
},
/**
* Check whether two rectangles collide on each one of their four axis. If
* all axis collide, then the two rectangles do collide on the plane.
*
* @param {array} Rectangle A's corners.
* @param {array} Rectangle B's corners.
* @return {boolean} True if the rectangles collide.
*/
collision: function(c1, c2) {
var axis = this.axis(c1, c2),
col = true;
for (var i = 0; i < 4; i++)
col = col && this.axisCollision(axis[i], c1, c2);
return col;
}
};
/**
* Quad Functions
* ------------
*
* The Quadtree functions themselves.
* For each of those functions, we consider that in a splitted quad, the
* index of each node is the following:
* 0: top left
* 1: top right
* 2: bottom left
* 3: bottom right
*
* Moreover, the hereafter quad's philosophy is to consider that if an element
* collides with more than one nodes, this element belongs to each of the
* nodes it collides with where other would let it lie on a higher node.
*/
/**
* Get the index of the node containing the point in the quad
*
* @param {object} point A point defined by coordinates (x, y).
* @param {object} quadBounds Boundaries of the quad (x, y, width, heigth).
* @return {integer} The index of the node containing the point.
*/
function _quadIndex(point, quadBounds) {
var xmp = quadBounds.x + quadBounds.width / 2,
ymp = quadBounds.y + quadBounds.height / 2,
top = (point.y < ymp),
left = (point.x < xmp);
if (top) {
if (left)
return 0;
else
return 1;
}
else {
if (left)
return 2;
else
return 3;
}
}
/**
* Get a list of indexes of nodes containing an axis-aligned rectangle
*
* @param {object} rectangle A rectangle defined by two points (x1, y1),
* (x2, y2) and height.
* @param {array} quadCorners An array of the quad nodes' corners.
* @return {array} An array of indexes containing one to
* four integers.
*/
function _quadIndexes(rectangle, quadCorners) {
var indexes = [];
// Iterating through quads
for (var i = 0; i < 4; i++)
if ((rectangle.x2 >= quadCorners[i][0].x) &&
(rectangle.x1 <= quadCorners[i][1].x) &&
(rectangle.y1 + rectangle.height >= quadCorners[i][0].y) &&
(rectangle.y1 <= quadCorners[i][2].y))
indexes.push(i);
return indexes;
}
/**
* Get a list of indexes of nodes containing a non-axis-aligned rectangle
*
* @param {array} corners An array containing each corner of the
* rectangle defined by its coordinates (x, y).
* @param {array} quadCorners An array of the quad nodes' corners.
* @return {array} An array of indexes containing one to
* four integers.
*/
function _quadCollision(corners, quadCorners) {
var indexes = [];
// Iterating through quads
for (var i = 0; i < 4; i++)
if (_geom.collision(corners, quadCorners[i]))
indexes.push(i);
return indexes;
}
/**
* Subdivide a quad by creating a node at a precise index. The function does
* not generate all four nodes not to potentially create unused nodes.
*
* @param {integer} index The index of the node to create.
* @param {object} quad The quad object to subdivide.
* @return {object} A new quad representing the node created.
*/
function _quadSubdivide(index, quad) {
var next = quad.level + 1,
subw = Math.round(quad.bounds.width / 2),
subh = Math.round(quad.bounds.height / 2),
qx = Math.round(quad.bounds.x),
qy = Math.round(quad.bounds.y),
x,
y;
switch (index) {
case 0:
x = qx;
y = qy;
break;
case 1:
x = qx + subw;
y = qy;
break;
case 2:
x = qx;
y = qy + subh;
break;
case 3:
x = qx + subw;
y = qy + subh;
break;
}
return _quadTree(
{x: x, y: y, width: subw, height: subh},
next,
quad.maxElements,
quad.maxLevel
);
}
/**
* Recursively insert an element into the quadtree. Only points
* with size, i.e. axis-aligned squares, may be inserted with this
* method.
*
* @param {object} el The element to insert in the quadtree.
* @param {object} sizedPoint A sized point defined by two top points
* (x1, y1), (x2, y2) and height.
* @param {object} quad The quad in which to insert the element.
* @return {undefined} The function does not return anything.
*/
function _quadInsert(el, sizedPoint, quad) {
if (quad.level < quad.maxLevel) {
// Searching appropriate quads
var indexes = _quadIndexes(sizedPoint, quad.corners);
// Iterating
for (var i = 0, l = indexes.length; i < l; i++) {
// Subdividing if necessary
if (quad.nodes[indexes[i]] === undefined)
quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad);
// Recursion
_quadInsert(el, sizedPoint, quad.nodes[indexes[i]]);
}
}
else {
// Pushing the element in a leaf node
quad.elements.push(el);
}
}
/**
* Recursively retrieve every elements held by the node containing the
* searched point.
*
* @param {object} point The searched point (x, y).
* @param {object} quad The searched quad.
* @return {array} An array of elements contained in the relevant
* node.
*/
function _quadRetrievePoint(point, quad) {
if (quad.level < quad.maxLevel) {
var index = _quadIndex(point, quad.bounds);
// If node does not exist we return an empty list
if (quad.nodes[index] !== undefined) {
return _quadRetrievePoint(point, quad.nodes[index]);
}
else {
return [];
}
}
else {
return quad.elements;
}
}
/**
* Recursively retrieve every elements contained within an rectangular area
* that may or may not be axis-aligned.
*
* @param {object|array} rectData The searched area defined either by
* an array of four corners (x, y) in
* the case of a non-axis-aligned
* rectangle or an object with two top
* points (x1, y1), (x2, y2) and height.
* @param {object} quad The searched quad.
* @param {function} collisionFunc The collision function used to search
* for node indexes.
* @param {array?} els The retrieved elements.
* @return {array} An array of elements contained in the
* area.
*/
function _quadRetrieveArea(rectData, quad, collisionFunc, els) {
els = els || {};
if (quad.level < quad.maxLevel) {
var indexes = collisionFunc(rectData, quad.corners);
for (var i = 0, l = indexes.length; i < l; i++)
if (quad.nodes[indexes[i]] !== undefined)
_quadRetrieveArea(
rectData,
quad.nodes[indexes[i]],
collisionFunc,
els
);
} else
for (var j = 0, m = quad.elements.length; j < m; j++)
if (els[quad.elements[j].id] === undefined)
els[quad.elements[j].id] = quad.elements[j];
return els;
}
/**
* Creates the quadtree object itself.
*
* @param {object} bounds The boundaries of the quad defined by an
* origin (x, y), width and heigth.
* @param {integer} level The level of the quad in the tree.
* @param {integer} maxElements The max number of element in a leaf node.
* @param {integer} maxLevel The max recursion level of the tree.
* @return {object} The quadtree object.
*/
function _quadTree(bounds, level, maxElements, maxLevel) {
return {
level: level || 0,
bounds: bounds,
corners: _geom.splitSquare(bounds),
maxElements: maxElements || 40,
maxLevel: maxLevel || 8,
elements: [],
nodes: []
};
}
/**
* Sigma Quad Constructor
* ----------------------
*
* The edgequad API as exposed to sigma.
*/
/**
* The edgequad core that will become the sigma interface with the quadtree.
*
* property {object} _tree Property holding the quadtree object.
* property {object} _geom Exposition of the _geom namespace for testing.
* property {object} _cache Cache for the area method.
* property {boolean} _enabled Can index and retreive elements.
*/
var edgequad = function() {
this._geom = _geom;
this._tree = null;
this._cache = {
query: false,
result: false
};
this._enabled = true;
};
/**
* Index a graph by inserting its edges into the quadtree.
*
* @param {object} graph A graph instance.
* @param {object} params An object of parameters with at least the quad
* bounds.
* @return {object} The quadtree object.
*
* Parameters:
* ----------
* bounds: {object} boundaries of the quad defined by its origin (x, y)
* width and heigth.
* prefix: {string?} a prefix for edge geometric attributes.
* maxElements: {integer?} the max number of elements in a leaf node.
* maxLevel: {integer?} the max recursion level of the tree.
*/
edgequad.prototype.index = function(graph, params) {
if (!this._enabled)
return this._tree;
// Enforcing presence of boundaries
if (!params.bounds)
throw 'sigma.classes.edgequad.index: bounds information not given.';
// Prefix
var prefix = params.prefix || '',
cp,
source,
target,
n,
e;
// Building the tree
this._tree = _quadTree(
params.bounds,
0,
params.maxElements,
params.maxLevel
);
var edges = graph.edges();
// Inserting graph edges into the tree
for (var i = 0, l = edges.length; i < l; i++) {
source = graph.nodes(edges[i].source);
target = graph.nodes(edges[i].target);
e = {
x1: source[prefix + 'x'],
y1: source[prefix + 'y'],
x2: target[prefix + 'x'],
y2: target[prefix + 'y'],
size: edges[i][prefix + 'size'] || 0
};
// Inserting edge
if (edges[i].type === 'curve' || edges[i].type === 'curvedArrow') {
if (source.id === target.id) {
n = {
x: source[prefix + 'x'],
y: source[prefix + 'y'],
size: source[prefix + 'size'] || 0
};
_quadInsert(
edges[i],
_geom.selfLoopToSquare(n),
this._tree);
}
else {
cp = sigma.utils.getQuadraticControlPoint(e.x1, e.y1, e.x2, e.y2);
_quadInsert(
edges[i],
_geom.quadraticCurveToSquare(e, cp),
this._tree);
}
}
else {
_quadInsert(
edges[i],
_geom.lineToSquare(e),
this._tree);
}
}
// Reset cache:
this._cache = {
query: false,
result: false
};
// remove?
return this._tree;
};
/**
* Retrieve every graph edges held by the quadtree node containing the
* searched point.
*
* @param {number} x of the point.
* @param {number} y of the point.
* @return {array} An array of edges retrieved.
*/
edgequad.prototype.point = function(x, y) {
if (!this._enabled)
return [];
return this._tree ?
_quadRetrievePoint({x: x, y: y}, this._tree) || [] :
[];
};
/**
* Retrieve every graph edges within a rectangular area. The methods keep the
* last area queried in cache for optimization reason and will act differently
* for the same reason if the area is axis-aligned or not.
*
* @param {object} A rectangle defined by two top points (x1, y1), (x2, y2)
* and height.
* @return {array} An array of edges retrieved.
*/
edgequad.prototype.area = function(rect) {
if (!this._enabled)
return [];
var serialized = JSON.stringify(rect),
collisionFunc,
rectData;
// Returning cache?
if (this._cache.query === serialized)
return this._cache.result;
// Axis aligned ?
if (_geom.isAxisAligned(rect)) {
collisionFunc = _quadIndexes;
rectData = _geom.axisAlignedTopPoints(rect);
}
else {
collisionFunc = _quadCollision;
rectData = _geom.rectangleCorners(rect);
}
// Retrieving edges
var edges = this._tree ?
_quadRetrieveArea(
rectData,
this._tree,
collisionFunc
) :
[];
// Object to array
var edgesArray = [];
for (var i in edges)
edgesArray.push(edges[i]);
// Caching
this._cache.query = serialized;
this._cache.result = edgesArray;
return edgesArray;
};
/**
* EXPORT:
* *******
*/
if (typeof this.sigma !== 'undefined') {
this.sigma.classes = this.sigma.classes || {};
this.sigma.classes.edgequad = edgequad;
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = edgequad;
exports.edgequad = edgequad;
} else
this.edgequad = edgequad;
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.captors');
/**
* The user inputs default captor. It deals with mouse events, keyboards
* events and touch events.
*
* @param {DOMElement} target The DOM element where the listeners will be
* bound.
* @param {camera} camera The camera related to the target.
* @param {configurable} settings The settings function.
* @return {sigma.captor} The fresh new captor instance.
*/
sigma.captors.mouse = function(target, camera, settings) {
var _self = this,
_target = target,
_camera = camera,
_settings = settings,
// CAMERA MANAGEMENT:
// ******************
// The camera position when the user starts dragging:
_startCameraX,
_startCameraY,
_startCameraAngle,
// The latest stage position:
_lastCameraX,
_lastCameraY,
_lastCameraAngle,
_lastCameraRatio,
// MOUSE MANAGEMENT:
// *****************
// The mouse position when the user starts dragging:
_startMouseX,
_startMouseY,
_isMouseDown,
_isMoving,
_hasDragged,
_downStartTime,
_movingTimeoutId;
sigma.classes.dispatcher.extend(this);
sigma.utils.doubleClick(_target, 'click', _doubleClickHandler);
_target.addEventListener('DOMMouseScroll', _wheelHandler, false);
_target.addEventListener('mousewheel', _wheelHandler, false);
_target.addEventListener('mousemove', _moveHandler, false);
_target.addEventListener('mousedown', _downHandler, false);
_target.addEventListener('click', _clickHandler, false);
_target.addEventListener('mouseout', _outHandler, false);
document.addEventListener('mouseup', _upHandler, false);
/**
* This method unbinds every handlers that makes the captor work.
*/
this.kill = function() {
sigma.utils.unbindDoubleClick(_target, 'click');
_target.removeEventListener('DOMMouseScroll', _wheelHandler);
_target.removeEventListener('mousewheel', _wheelHandler);
_target.removeEventListener('mousemove', _moveHandler);
_target.removeEventListener('mousedown', _downHandler);
_target.removeEventListener('click', _clickHandler);
_target.removeEventListener('mouseout', _outHandler);
document.removeEventListener('mouseup', _upHandler);
};
// MOUSE EVENTS:
// *************
/**
* The handler listening to the 'move' mouse event. It will effectively
* drag the graph.
*
* @param {event} e A mouse event.
*/
function _moveHandler(e) {
var x,
y,
pos;
// Dispatch event:
if (_settings('mouseEnabled'))
_self.dispatchEvent('mousemove', {
x: sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2,
y: sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
if (_settings('mouseEnabled') && _isMouseDown) {
_isMoving = true;
_hasDragged = true;
if (_movingTimeoutId)
clearTimeout(_movingTimeoutId);
_movingTimeoutId = setTimeout(function() {
_isMoving = false;
}, _settings('dragTimeout'));
sigma.misc.animation.killAll(_camera);
_camera.isMoving = true;
pos = _camera.cameraPosition(
sigma.utils.getX(e) - _startMouseX,
sigma.utils.getY(e) - _startMouseY,
true
);
x = _startCameraX - pos.x;
y = _startCameraY - pos.y;
if (x !== _camera.x || y !== _camera.y) {
_lastCameraX = _camera.x;
_lastCameraY = _camera.y;
_camera.goTo({
x: x,
y: y
});
}
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
e.stopPropagation();
return false;
}
}
/**
* The handler listening to the 'up' mouse event. It will stop dragging the
* graph.
*
* @param {event} e A mouse event.
*/
function _upHandler(e) {
if (_settings('mouseEnabled') && _isMouseDown) {
_isMouseDown = false;
if (_movingTimeoutId)
clearTimeout(_movingTimeoutId);
_camera.isMoving = false;
var x = sigma.utils.getX(e),
y = sigma.utils.getY(e);
if (_isMoving) {
sigma.misc.animation.killAll(_camera);
sigma.misc.animation.camera(
_camera,
{
x: _camera.x +
_settings('mouseInertiaRatio') * (_camera.x - _lastCameraX),
y: _camera.y +
_settings('mouseInertiaRatio') * (_camera.y - _lastCameraY)
},
{
easing: 'quadraticOut',
duration: _settings('mouseInertiaDuration')
}
);
} else if (
_startMouseX !== x ||
_startMouseY !== y
)
_camera.goTo({
x: _camera.x,
y: _camera.y
});
_self.dispatchEvent('mouseup', {
x: x - sigma.utils.getWidth(e) / 2,
y: y - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
// Update _isMoving flag:
_isMoving = false;
}
}
/**
* The handler listening to the 'down' mouse event. It will start observing
* the mouse position for dragging the graph.
*
* @param {event} e A mouse event.
*/
function _downHandler(e) {
if (_settings('mouseEnabled')) {
_startCameraX = _camera.x;
_startCameraY = _camera.y;
_lastCameraX = _camera.x;
_lastCameraY = _camera.y;
_startMouseX = sigma.utils.getX(e);
_startMouseY = sigma.utils.getY(e);
_hasDragged = false;
_downStartTime = (new Date()).getTime();
switch (e.which) {
case 2:
// Middle mouse button pressed
// Do nothing.
break;
case 3:
// Right mouse button pressed
_self.dispatchEvent('rightclick', {
x: _startMouseX - sigma.utils.getWidth(e) / 2,
y: _startMouseY - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
break;
// case 1:
default:
// Left mouse button pressed
_isMouseDown = true;
_self.dispatchEvent('mousedown', {
x: _startMouseX - sigma.utils.getWidth(e) / 2,
y: _startMouseY - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
}
}
}
/**
* The handler listening to the 'out' mouse event. It will just redispatch
* the event.
*
* @param {event} e A mouse event.
*/
function _outHandler(e) {
if (_settings('mouseEnabled'))
_self.dispatchEvent('mouseout');
}
/**
* The handler listening to the 'click' mouse event. It will redispatch the
* click event, but with normalized X and Y coordinates.
*
* @param {event} e A mouse event.
*/
function _clickHandler(e) {
if (_settings('mouseEnabled'))
_self.dispatchEvent('click', {
x: sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2,
y: sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey,
isDragging:
(((new Date()).getTime() - _downStartTime) > 100) &&
_hasDragged
});
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
e.stopPropagation();
return false;
}
/**
* The handler listening to the double click custom event. It will
* basically zoom into the graph.
*
* @param {event} e A mouse event.
*/
function _doubleClickHandler(e) {
var pos,
ratio,
animation;
if (_settings('mouseEnabled')) {
ratio = 1 / _settings('doubleClickZoomingRatio');
_self.dispatchEvent('doubleclick', {
x: _startMouseX - sigma.utils.getWidth(e) / 2,
y: _startMouseY - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
if (_settings('doubleClickEnabled')) {
pos = _camera.cameraPosition(
sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2,
sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2,
true
);
animation = {
duration: _settings('doubleClickZoomDuration')
};
sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation);
}
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
e.stopPropagation();
return false;
}
}
/**
* The handler listening to the 'wheel' mouse event. It will basically zoom
* in or not into the graph.
*
* @param {event} e A mouse event.
*/
function _wheelHandler(e) {
var pos,
ratio,
animation;
if (_settings('mouseEnabled') && _settings('mouseWheelEnabled')) {
ratio = sigma.utils.getDelta(e) > 0 ?
1 / _settings('zoomingRatio') :
_settings('zoomingRatio');
pos = _camera.cameraPosition(
sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2,
sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2,
true
);
animation = {
duration: _settings('mouseZoomDuration')
};
sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation);
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
e.stopPropagation();
return false;
}
}
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.captors');
/**
* The user inputs default captor. It deals with mouse events, keyboards
* events and touch events.
*
* @param {DOMElement} target The DOM element where the listeners will be
* bound.
* @param {camera} camera The camera related to the target.
* @param {configurable} settings The settings function.
* @return {sigma.captor} The fresh new captor instance.
*/
sigma.captors.touch = function(target, camera, settings) {
var _self = this,
_target = target,
_camera = camera,
_settings = settings,
// CAMERA MANAGEMENT:
// ******************
// The camera position when the user starts dragging:
_startCameraX,
_startCameraY,
_startCameraAngle,
_startCameraRatio,
// The latest stage position:
_lastCameraX,
_lastCameraY,
_lastCameraAngle,
_lastCameraRatio,
// TOUCH MANAGEMENT:
// *****************
// Touches that are down:
_downTouches = [],
_startTouchX0,
_startTouchY0,
_startTouchX1,
_startTouchY1,
_startTouchAngle,
_startTouchDistance,
_touchMode,
_isMoving,
_doubleTap,
_movingTimeoutId;
sigma.classes.dispatcher.extend(this);
sigma.utils.doubleClick(_target, 'touchstart', _doubleTapHandler);
_target.addEventListener('touchstart', _handleStart, false);
_target.addEventListener('touchend', _handleLeave, false);
_target.addEventListener('touchcancel', _handleLeave, false);
_target.addEventListener('touchleave', _handleLeave, false);
_target.addEventListener('touchmove', _handleMove, false);
function position(e) {
var offset = sigma.utils.getOffset(_target);
return {
x: e.pageX - offset.left,
y: e.pageY - offset.top
};
}
/**
* This method unbinds every handlers that makes the captor work.
*/
this.kill = function() {
sigma.utils.unbindDoubleClick(_target, 'touchstart');
_target.addEventListener('touchstart', _handleStart);
_target.addEventListener('touchend', _handleLeave);
_target.addEventListener('touchcancel', _handleLeave);
_target.addEventListener('touchleave', _handleLeave);
_target.addEventListener('touchmove', _handleMove);
};
// TOUCH EVENTS:
// *************
/**
* The handler listening to the 'touchstart' event. It will set the touch
* mode ("_touchMode") and start observing the user touch moves.
*
* @param {event} e A touch event.
*/
function _handleStart(e) {
if (_settings('touchEnabled')) {
var x0,
x1,
y0,
y1,
pos0,
pos1;
_downTouches = e.touches;
switch (_downTouches.length) {
case 1:
_camera.isMoving = true;
_touchMode = 1;
_startCameraX = _camera.x;
_startCameraY = _camera.y;
_lastCameraX = _camera.x;
_lastCameraY = _camera.y;
pos0 = position(_downTouches[0]);
_startTouchX0 = pos0.x;
_startTouchY0 = pos0.y;
break;
case 2:
_camera.isMoving = true;
_touchMode = 2;
pos0 = position(_downTouches[0]);
pos1 = position(_downTouches[1]);
x0 = pos0.x;
y0 = pos0.y;
x1 = pos1.x;
y1 = pos1.y;
_lastCameraX = _camera.x;
_lastCameraY = _camera.y;
_startCameraAngle = _camera.angle;
_startCameraRatio = _camera.ratio;
_startCameraX = _camera.x;
_startCameraY = _camera.y;
_startTouchX0 = x0;
_startTouchY0 = y0;
_startTouchX1 = x1;
_startTouchY1 = y1;
_startTouchAngle = Math.atan2(
_startTouchY1 - _startTouchY0,
_startTouchX1 - _startTouchX0
);
_startTouchDistance = Math.sqrt(
Math.pow(_startTouchY1 - _startTouchY0, 2) +
Math.pow(_startTouchX1 - _startTouchX0, 2)
);
e.preventDefault();
return false;
}
}
}
/**
* The handler listening to the 'touchend', 'touchcancel' and 'touchleave'
* event. It will update the touch mode if there are still at least one
* finger, and stop dragging else.
*
* @param {event} e A touch event.
*/
function _handleLeave(e) {
if (_settings('touchEnabled')) {
_downTouches = e.touches;
var inertiaRatio = _settings('touchInertiaRatio');
if (_movingTimeoutId) {
_isMoving = false;
clearTimeout(_movingTimeoutId);
}
switch (_touchMode) {
case 2:
if (e.touches.length === 1) {
_handleStart(e);
e.preventDefault();
break;
}
/* falls through */
case 1:
_camera.isMoving = false;
_self.dispatchEvent('stopDrag');
if (_isMoving) {
_doubleTap = false;
sigma.misc.animation.camera(
_camera,
{
x: _camera.x +
inertiaRatio * (_camera.x - _lastCameraX),
y: _camera.y +
inertiaRatio * (_camera.y - _lastCameraY)
},
{
easing: 'quadraticOut',
duration: _settings('touchInertiaDuration')
}
);
}
_isMoving = false;
_touchMode = 0;
break;
}
}
}
/**
* The handler listening to the 'touchmove' event. It will effectively drag
* the graph, and eventually zooms and turn it if the user is using two
* fingers.
*
* @param {event} e A touch event.
*/
function _handleMove(e) {
if (!_doubleTap && _settings('touchEnabled')) {
var x0,
x1,
y0,
y1,
cos,
sin,
end,
pos0,
pos1,
diff,
start,
dAngle,
dRatio,
newStageX,
newStageY,
newStageRatio,
newStageAngle;
_downTouches = e.touches;
_isMoving = true;
if (_movingTimeoutId)
clearTimeout(_movingTimeoutId);
_movingTimeoutId = setTimeout(function() {
_isMoving = false;
}, _settings('dragTimeout'));
switch (_touchMode) {
case 1:
pos0 = position(_downTouches[0]);
x0 = pos0.x;
y0 = pos0.y;
diff = _camera.cameraPosition(
x0 - _startTouchX0,
y0 - _startTouchY0,
true
);
newStageX = _startCameraX - diff.x;
newStageY = _startCameraY - diff.y;
if (newStageX !== _camera.x || newStageY !== _camera.y) {
_lastCameraX = _camera.x;
_lastCameraY = _camera.y;
_camera.goTo({
x: newStageX,
y: newStageY
});
_self.dispatchEvent('mousemove', {
x: pos0.x - sigma.utils.getWidth(e) / 2,
y: pos0.y - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
_self.dispatchEvent('drag');
}
break;
case 2:
pos0 = position(_downTouches[0]);
pos1 = position(_downTouches[1]);
x0 = pos0.x;
y0 = pos0.y;
x1 = pos1.x;
y1 = pos1.y;
start = _camera.cameraPosition(
(_startTouchX0 + _startTouchX1) / 2 -
sigma.utils.getWidth(e) / 2,
(_startTouchY0 + _startTouchY1) / 2 -
sigma.utils.getHeight(e) / 2,
true
);
end = _camera.cameraPosition(
(x0 + x1) / 2 - sigma.utils.getWidth(e) / 2,
(y0 + y1) / 2 - sigma.utils.getHeight(e) / 2,
true
);
dAngle = Math.atan2(y1 - y0, x1 - x0) - _startTouchAngle;
dRatio = Math.sqrt(
Math.pow(y1 - y0, 2) + Math.pow(x1 - x0, 2)
) / _startTouchDistance;
// Translation:
x0 = start.x;
y0 = start.y;
// Homothetic transformation:
newStageRatio = _startCameraRatio / dRatio;
x0 = x0 * dRatio;
y0 = y0 * dRatio;
// Rotation:
newStageAngle = _startCameraAngle - dAngle;
cos = Math.cos(-dAngle);
sin = Math.sin(-dAngle);
x1 = x0 * cos + y0 * sin;
y1 = y0 * cos - x0 * sin;
x0 = x1;
y0 = y1;
// Finalize:
newStageX = x0 - end.x + _startCameraX;
newStageY = y0 - end.y + _startCameraY;
if (
newStageRatio !== _camera.ratio ||
newStageAngle !== _camera.angle ||
newStageX !== _camera.x ||
newStageY !== _camera.y
) {
_lastCameraX = _camera.x;
_lastCameraY = _camera.y;
_lastCameraAngle = _camera.angle;
_lastCameraRatio = _camera.ratio;
_camera.goTo({
x: newStageX,
y: newStageY,
angle: newStageAngle,
ratio: newStageRatio
});
_self.dispatchEvent('drag');
}
break;
}
e.preventDefault();
return false;
}
}
/**
* The handler listening to the double tap custom event. It will
* basically zoom into the graph.
*
* @param {event} e A touch event.
*/
function _doubleTapHandler(e) {
var pos,
ratio,
animation;
if (e.touches && e.touches.length === 1 && _settings('touchEnabled')) {
_doubleTap = true;
ratio = 1 / _settings('doubleClickZoomingRatio');
pos = position(e.touches[0]);
_self.dispatchEvent('doubleclick', {
x: pos.x - sigma.utils.getWidth(e) / 2,
y: pos.y - sigma.utils.getHeight(e) / 2,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
if (_settings('doubleClickEnabled')) {
pos = _camera.cameraPosition(
pos.x - sigma.utils.getWidth(e) / 2,
pos.y - sigma.utils.getHeight(e) / 2,
true
);
animation = {
duration: _settings('doubleClickZoomDuration'),
onComplete: function() {
_doubleTap = false;
}
};
sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation);
}
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
e.stopPropagation();
return false;
}
}
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
if (typeof conrad === 'undefined')
throw 'conrad is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.renderers');
/**
* This function is the constructor of the canvas sigma's renderer.
*
* @param {sigma.classes.graph} graph The graph to render.
* @param {sigma.classes.camera} camera The camera.
* @param {configurable} settings The sigma instance settings
* function.
* @param {object} object The options object.
* @return {sigma.renderers.canvas} The renderer instance.
*/
sigma.renderers.canvas = function(graph, camera, settings, options) {
if (typeof options !== 'object')
throw 'sigma.renderers.canvas: Wrong arguments.';
if (!(options.container instanceof HTMLElement))
throw 'Container not found.';
var k,
i,
l,
a,
fn,
self = this;
sigma.classes.dispatcher.extend(this);
// Initialize main attributes:
Object.defineProperty(this, 'conradId', {
value: sigma.utils.id()
});
this.graph = graph;
this.camera = camera;
this.contexts = {};
this.domElements = {};
this.options = options;
this.container = this.options.container;
this.settings = (
typeof options.settings === 'object' &&
options.settings
) ?
settings.embedObjects(options.settings) :
settings;
// Node indexes:
this.nodesOnScreen = [];
this.edgesOnScreen = [];
// Conrad related attributes:
this.jobs = {};
// Find the prefix:
this.options.prefix = 'renderer' + this.conradId + ':';
// Initialize the DOM elements:
if (
!this.settings('batchEdgesDrawing')
) {
this.initDOM('canvas', 'scene');
this.contexts.edges = this.contexts.scene;
this.contexts.nodes = this.contexts.scene;
this.contexts.labels = this.contexts.scene;
} else {
this.initDOM('canvas', 'edges');
this.initDOM('canvas', 'scene');
this.contexts.nodes = this.contexts.scene;
this.contexts.labels = this.contexts.scene;
}
this.initDOM('canvas', 'mouse');
this.contexts.hover = this.contexts.mouse;
// Initialize captors:
this.captors = [];
a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch];
for (i = 0, l = a.length; i < l; i++) {
fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]];
this.captors.push(
new fn(
this.domElements.mouse,
this.camera,
this.settings
)
);
}
// Deal with sigma events:
sigma.misc.bindEvents.call(this, this.options.prefix);
sigma.misc.drawHovers.call(this, this.options.prefix);
this.resize(false);
};
/**
* This method renders the graph on the canvases.
*
* @param {?object} options Eventually an object of options.
* @return {sigma.renderers.canvas} Returns the instance itself.
*/
sigma.renderers.canvas.prototype.render = function(options) {
options = options || {};
var a,
i,
k,
l,
o,
id,
end,
job,
start,
edges,
renderers,
rendererType,
batchSize,
tempGCO,
index = {},
graph = this.graph,
nodes = this.graph.nodes,
prefix = this.options.prefix || '',
drawEdges = this.settings(options, 'drawEdges'),
drawNodes = this.settings(options, 'drawNodes'),
drawLabels = this.settings(options, 'drawLabels'),
drawEdgeLabels = this.settings(options, 'drawEdgeLabels'),
embedSettings = this.settings.embedObjects(options, {
prefix: this.options.prefix
});
// Call the resize function:
this.resize(false);
// Check the 'hideEdgesOnMove' setting:
if (this.settings(options, 'hideEdgesOnMove'))
if (this.camera.isAnimated || this.camera.isMoving)
drawEdges = false;
// Apply the camera's view:
this.camera.applyView(
undefined,
this.options.prefix,
{
width: this.width,
height: this.height
}
);
// Clear canvases:
this.clear();
// Kill running jobs:
for (k in this.jobs)
if (conrad.hasJob(k))
conrad.killJob(k);
// Find which nodes are on screen:
this.edgesOnScreen = [];
this.nodesOnScreen = this.camera.quadtree.area(
this.camera.getRectangle(this.width, this.height)
);
for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
index[a[i].id] = a[i];
// Draw edges:
// - If settings('batchEdgesDrawing') is true, the edges are displayed per
// batches. If not, they are drawn in one frame.
if (drawEdges) {
// First, let's identify which edges to draw. To do this, we just keep
// every edges that have at least one extremity displayed according to
// the quadtree and the "hidden" attribute. We also do not keep hidden
// edges.
for (a = graph.edges(), i = 0, l = a.length; i < l; i++) {
o = a[i];
if (
(index[o.source] || index[o.target]) &&
(!o.hidden && !nodes(o.source).hidden && !nodes(o.target).hidden)
)
this.edgesOnScreen.push(o);
}
// If the "batchEdgesDrawing" settings is true, edges are batched:
if (this.settings(options, 'batchEdgesDrawing')) {
id = 'edges_' + this.conradId;
batchSize = embedSettings('canvasEdgesBatchSize');
edges = this.edgesOnScreen;
l = edges.length;
start = 0;
end = Math.min(edges.length, start + batchSize);
job = function() {
tempGCO = this.contexts.edges.globalCompositeOperation;
this.contexts.edges.globalCompositeOperation = 'destination-over';
renderers = sigma.canvas.edges;
for (i = start; i < end; i++) {
o = edges[i];
(renderers[
o.type || this.settings(options, 'defaultEdgeType')
] || renderers.def)(
o,
graph.nodes(o.source),
graph.nodes(o.target),
this.contexts.edges,
embedSettings
);
}
// Draw edge labels:
if (drawEdgeLabels) {
renderers = sigma.canvas.edges.labels;
for (i = start; i < end; i++) {
o = edges[i];
if (!o.hidden)
(renderers[
o.type || this.settings(options, 'defaultEdgeType')
] || renderers.def)(
o,
graph.nodes(o.source),
graph.nodes(o.target),
this.contexts.labels,
embedSettings
);
}
}
// Restore original globalCompositeOperation:
this.contexts.edges.globalCompositeOperation = tempGCO;
// Catch job's end:
if (end === edges.length) {
delete this.jobs[id];
return false;
}
start = end + 1;
end = Math.min(edges.length, start + batchSize);
return true;
};
this.jobs[id] = job;
conrad.addJob(id, job.bind(this));
// If not, they are drawn in one frame:
} else {
renderers = sigma.canvas.edges;
for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) {
o = a[i];
(renderers[
o.type || this.settings(options, 'defaultEdgeType')
] || renderers.def)(
o,
graph.nodes(o.source),
graph.nodes(o.target),
this.contexts.edges,
embedSettings
);
}
// Draw edge labels:
// - No batching
if (drawEdgeLabels) {
renderers = sigma.canvas.edges.labels;
for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++)
if (!a[i].hidden)
(renderers[
a[i].type || this.settings(options, 'defaultEdgeType')
] || renderers.def)(
a[i],
graph.nodes(a[i].source),
graph.nodes(a[i].target),
this.contexts.labels,
embedSettings
);
}
}
}
// Draw nodes:
// - No batching
if (drawNodes) {
renderers = sigma.canvas.nodes;
for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
if (!a[i].hidden)
(renderers[
a[i].type || this.settings(options, 'defaultNodeType')
] || renderers.def)(
a[i],
this.contexts.nodes,
embedSettings
);
}
// Draw labels:
// - No batching
if (drawLabels) {
renderers = sigma.canvas.labels;
for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
if (!a[i].hidden)
(renderers[
a[i].type || this.settings(options, 'defaultNodeType')
] || renderers.def)(
a[i],
this.contexts.labels,
embedSettings
);
}
this.dispatchEvent('render');
return this;
};
/**
* This method creates a DOM element of the specified type, switches its
* position to "absolute", references it to the domElements attribute, and
* finally appends it to the container.
*
* @param {string} tag The label tag.
* @param {string} id The id of the element (to store it in "domElements").
*/
sigma.renderers.canvas.prototype.initDOM = function(tag, id) {
var dom = document.createElement(tag);
dom.style.position = 'absolute';
dom.setAttribute('class', 'sigma-' + id);
this.domElements[id] = dom;
this.container.appendChild(dom);
if (tag.toLowerCase() === 'canvas')
this.contexts[id] = dom.getContext('2d');
};
/**
* This method resizes each DOM elements in the container and stores the new
* dimensions. Then, it renders the graph.
*
* @param {?number} width The new width of the container.
* @param {?number} height The new height of the container.
* @return {sigma.renderers.canvas} Returns the instance itself.
*/
sigma.renderers.canvas.prototype.resize = function(w, h) {
var k,
oldWidth = this.width,
oldHeight = this.height,
pixelRatio = 1;
// TODO:
// *****
// This pixelRatio is the solution to display with the good definition
// on canvases on Retina displays (ie oversampling). Unfortunately, it
// has a huge performance cost...
// > pixelRatio = window.devicePixelRatio || 1;
if (w !== undefined && h !== undefined) {
this.width = w;
this.height = h;
} else {
this.width = this.container.offsetWidth;
this.height = this.container.offsetHeight;
w = this.width;
h = this.height;
}
if (oldWidth !== this.width || oldHeight !== this.height) {
for (k in this.domElements) {
this.domElements[k].style.width = w + 'px';
this.domElements[k].style.height = h + 'px';
if (this.domElements[k].tagName.toLowerCase() === 'canvas') {
this.domElements[k].setAttribute('width', (w * pixelRatio) + 'px');
this.domElements[k].setAttribute('height', (h * pixelRatio) + 'px');
if (pixelRatio !== 1)
this.contexts[k].scale(pixelRatio, pixelRatio);
}
}
}
return this;
};
/**
* This method clears each canvas.
*
* @return {sigma.renderers.canvas} Returns the instance itself.
*/
sigma.renderers.canvas.prototype.clear = function() {
var k;
for (k in this.domElements)
if (this.domElements[k].tagName === 'CANVAS')
this.domElements[k].width = this.domElements[k].width;
return this;
};
/**
* This method kills contexts and other attributes.
*/
sigma.renderers.canvas.prototype.kill = function() {
var k,
captor;
// Kill captors:
while ((captor = this.captors.pop()))
captor.kill();
delete this.captors;
// Kill contexts:
for (k in this.domElements) {
this.domElements[k].parentNode.removeChild(this.domElements[k]);
delete this.domElements[k];
delete this.contexts[k];
}
delete this.domElements;
delete this.contexts;
};
/**
* The labels, nodes and edges renderers are stored in the three following
* objects. When an element is drawn, its type will be checked and if a
* renderer with the same name exists, it will be used. If not found, the
* default renderer will be used instead.
*
* They are stored in different files, in the "./canvas" folder.
*/
sigma.utils.pkg('sigma.canvas.nodes');
sigma.utils.pkg('sigma.canvas.edges');
sigma.utils.pkg('sigma.canvas.labels');
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.renderers');
/**
* This function is the constructor of the canvas sigma's renderer.
*
* @param {sigma.classes.graph} graph The graph to render.
* @param {sigma.classes.camera} camera The camera.
* @param {configurable} settings The sigma instance settings
* function.
* @param {object} object The options object.
* @return {sigma.renderers.canvas} The renderer instance.
*/
sigma.renderers.webgl = function(graph, camera, settings, options) {
if (typeof options !== 'object')
throw 'sigma.renderers.webgl: Wrong arguments.';
if (!(options.container instanceof HTMLElement))
throw 'Container not found.';
var k,
i,
l,
a,
fn,
_self = this;
sigma.classes.dispatcher.extend(this);
// Conrad related attributes:
this.jobs = {};
Object.defineProperty(this, 'conradId', {
value: sigma.utils.id()
});
// Initialize main attributes:
this.graph = graph;
this.camera = camera;
this.contexts = {};
this.domElements = {};
this.options = options;
this.container = this.options.container;
this.settings = (
typeof options.settings === 'object' &&
options.settings
) ?
settings.embedObjects(options.settings) :
settings;
// Find the prefix:
this.options.prefix = this.camera.readPrefix;
// Initialize programs hash
Object.defineProperty(this, 'nodePrograms', {
value: {}
});
Object.defineProperty(this, 'edgePrograms', {
value: {}
});
Object.defineProperty(this, 'nodeFloatArrays', {
value: {}
});
Object.defineProperty(this, 'edgeFloatArrays', {
value: {}
});
// Initialize the DOM elements:
if (this.settings(options, 'batchEdgesDrawing')) {
this.initDOM('canvas', 'edges', true);
this.initDOM('canvas', 'nodes', true);
} else {
this.initDOM('canvas', 'scene', true);
this.contexts.nodes = this.contexts.scene;
this.contexts.edges = this.contexts.scene;
}
this.initDOM('canvas', 'labels');
this.initDOM('canvas', 'mouse');
this.contexts.hover = this.contexts.mouse;
// Initialize captors:
this.captors = [];
a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch];
for (i = 0, l = a.length; i < l; i++) {
fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]];
this.captors.push(
new fn(
this.domElements.mouse,
this.camera,
this.settings
)
);
}
// Deal with sigma events:
sigma.misc.bindEvents.call(this, this.camera.prefix);
sigma.misc.drawHovers.call(this, this.camera.prefix);
this.resize();
};
/**
* This method will generate the nodes and edges float arrays. This step is
* separated from the "render" method, because to keep WebGL efficient, since
* all the camera and middlewares are modelised as matrices and they do not
* require the float arrays to be regenerated.
*
* Basically, when the user moves the camera or applies some specific linear
* transformations, this process step will be skipped, and the "render"
* method will efficiently refresh the rendering.
*
* And when the user modifies the graph colors or positions (applying a new
* layout or filtering the colors, for instance), this "process" step will be
* required to regenerate the float arrays.
*
* @return {sigma.renderers.webgl} Returns the instance itself.
*/
sigma.renderers.webgl.prototype.process = function() {
var a,
i,
l,
k,
type,
renderer,
graph = this.graph,
options = sigma.utils.extend(options, this.options);
// Empty float arrays:
for (k in this.nodeFloatArrays)
delete this.nodeFloatArrays[k];
for (k in this.edgeFloatArrays)
delete this.edgeFloatArrays[k];
// Sort edges and nodes per types:
for (a = graph.edges(), i = 0, l = a.length; i < l; i++) {
type = a[i].type || this.settings(options, 'defaultEdgeType');
k = (type && sigma.webgl.edges[type]) ? type : 'def';
if (!this.edgeFloatArrays[k])
this.edgeFloatArrays[k] = {
edges: []
};
this.edgeFloatArrays[k].edges.push(a[i]);
}
for (a = graph.nodes(), i = 0, l = a.length; i < l; i++) {
type = a[i].type || this.settings(options, 'defaultNodeType');
k = (type && sigma.webgl.nodes[type]) ? type : 'def';
if (!this.nodeFloatArrays[k])
this.nodeFloatArrays[k] = {
nodes: []
};
this.nodeFloatArrays[k].nodes.push(a[i]);
}
// Push edges:
for (k in this.edgeFloatArrays) {
renderer = sigma.webgl.edges[k];
for (a = this.edgeFloatArrays[k].edges, i = 0, l = a.length; i < l; i++) {
if (!this.edgeFloatArrays[k].array)
this.edgeFloatArrays[k].array = new Float32Array(
a.length * renderer.POINTS * renderer.ATTRIBUTES
);
// Just check that the edge and both its extremities are visible:
if (
!a[i].hidden &&
!graph.nodes(a[i].source).hidden &&
!graph.nodes(a[i].target).hidden
)
renderer.addEdge(
a[i],
graph.nodes(a[i].source),
graph.nodes(a[i].target),
this.edgeFloatArrays[k].array,
i * renderer.POINTS * renderer.ATTRIBUTES,
options.prefix,
this.settings
);
}
}
// Push nodes:
for (k in this.nodeFloatArrays) {
renderer = sigma.webgl.nodes[k];
for (a = this.nodeFloatArrays[k].nodes, i = 0, l = a.length; i < l; i++) {
if (!this.nodeFloatArrays[k].array)
this.nodeFloatArrays[k].array = new Float32Array(
a.length * renderer.POINTS * renderer.ATTRIBUTES
);
// Just check that the edge and both its extremities are visible:
if (
!a[i].hidden
)
renderer.addNode(
a[i],
this.nodeFloatArrays[k].array,
i * renderer.POINTS * renderer.ATTRIBUTES,
options.prefix,
this.settings
);
}
}
return this;
};
/**
* This method renders the graph. It basically calls each program (and
* generate them if they do not exist yet) to render nodes and edges, batched
* per renderer.
*
* As in the canvas renderer, it is possible to display edges, nodes and / or
* labels in batches, to make the whole thing way more scalable.
*
* @param {?object} params Eventually an object of options.
* @return {sigma.renderers.webgl} Returns the instance itself.
*/
sigma.renderers.webgl.prototype.render = function(params) {
var a,
i,
l,
k,
o,
program,
renderer,
self = this,
graph = this.graph,
nodesGl = this.contexts.nodes,
edgesGl = this.contexts.edges,
matrix = this.camera.getMatrix(),
options = sigma.utils.extend(params, this.options),
drawLabels = this.settings(options, 'drawLabels'),
drawEdges = this.settings(options, 'drawEdges'),
drawNodes = this.settings(options, 'drawNodes');
// Call the resize function:
this.resize(false);
// Check the 'hideEdgesOnMove' setting:
if (this.settings(options, 'hideEdgesOnMove'))
if (this.camera.isAnimated || this.camera.isMoving)
drawEdges = false;
// Clear canvases:
this.clear();
// Translate matrix to [width/2, height/2]:
matrix = sigma.utils.matrices.multiply(
matrix,
sigma.utils.matrices.translation(this.width / 2, this.height / 2)
);
// Kill running jobs:
for (k in this.jobs)
if (conrad.hasJob(k))
conrad.killJob(k);
if (drawEdges) {
if (this.settings(options, 'batchEdgesDrawing'))
(function() {
var a,
k,
i,
id,
job,
arr,
end,
start,
renderer,
batchSize,
currentProgram;
id = 'edges_' + this.conradId;
batchSize = this.settings(options, 'webglEdgesBatchSize');
a = Object.keys(this.edgeFloatArrays);
if (!a.length)
return;
i = 0;
renderer = sigma.webgl.edges[a[i]];
arr = this.edgeFloatArrays[a[i]].array;
start = 0;
end = Math.min(
start + batchSize * renderer.POINTS,
arr.length / renderer.ATTRIBUTES
);
job = function() {
// Check program:
if (!this.edgePrograms[a[i]])
this.edgePrograms[a[i]] = renderer.initProgram(edgesGl);
if (start < end) {
edgesGl.useProgram(this.edgePrograms[a[i]]);
renderer.render(
edgesGl,
this.edgePrograms[a[i]],
arr,
{
settings: this.settings,
matrix: matrix,
width: this.width,
height: this.height,
ratio: this.camera.ratio,
scalingRatio: this.settings(
options,
'webglOversamplingRatio'
),
start: start,
count: end - start
}
);
}
// Catch job's end:
if (
end >= arr.length / renderer.ATTRIBUTES &&
i === a.length - 1
) {
delete this.jobs[id];
return false;
}
if (end >= arr.length / renderer.ATTRIBUTES) {
i++;
arr = this.edgeFloatArrays[a[i]].array;
renderer = sigma.webgl.edges[a[i]];
start = 0;
end = Math.min(
start + batchSize * renderer.POINTS,
arr.length / renderer.ATTRIBUTES
);
} else {
start = end;
end = Math.min(
start + batchSize * renderer.POINTS,
arr.length / renderer.ATTRIBUTES
);
}
return true;
};
this.jobs[id] = job;
conrad.addJob(id, job.bind(this));
}).call(this);
else {
for (k in this.edgeFloatArrays) {
renderer = sigma.webgl.edges[k];
// Check program:
if (!this.edgePrograms[k])
this.edgePrograms[k] = renderer.initProgram(edgesGl);
// Render
if (this.edgeFloatArrays[k]) {
edgesGl.useProgram(this.edgePrograms[k]);
renderer.render(
edgesGl,
this.edgePrograms[k],
this.edgeFloatArrays[k].array,
{
settings: this.settings,
matrix: matrix,
width: this.width,
height: this.height,
ratio: this.camera.ratio,
scalingRatio: this.settings(options, 'webglOversamplingRatio')
}
);
}
}
}
}
if (drawNodes) {
// Enable blending:
nodesGl.blendFunc(nodesGl.SRC_ALPHA, nodesGl.ONE_MINUS_SRC_ALPHA);
nodesGl.enable(nodesGl.BLEND);
for (k in this.nodeFloatArrays) {
renderer = sigma.webgl.nodes[k];
// Check program:
if (!this.nodePrograms[k])
this.nodePrograms[k] = renderer.initProgram(nodesGl);
// Render
if (this.nodeFloatArrays[k]) {
nodesGl.useProgram(this.nodePrograms[k]);
renderer.render(
nodesGl,
this.nodePrograms[k],
this.nodeFloatArrays[k].array,
{
settings: this.settings,
matrix: matrix,
width: this.width,
height: this.height,
ratio: this.camera.ratio,
scalingRatio: this.settings(options, 'webglOversamplingRatio')
}
);
}
}
}
if (drawLabels) {
a = this.camera.quadtree.area(
this.camera.getRectangle(this.width, this.height)
);
// Apply camera view to these nodes:
this.camera.applyView(
undefined,
undefined,
{
nodes: a,
edges: [],
width: this.width,
height: this.height
}
);
o = function(key) {
return self.settings({
prefix: self.camera.prefix
}, key);
};
for (i = 0, l = a.length; i < l; i++)
if (!a[i].hidden)
(
sigma.canvas.labels[
a[i].type ||
this.settings(options, 'defaultNodeType')
] || sigma.canvas.labels.def
)(a[i], this.contexts.labels, o);
}
this.dispatchEvent('render');
return this;
};
/**
* This method creates a DOM element of the specified type, switches its
* position to "absolute", references it to the domElements attribute, and
* finally appends it to the container.
*
* @param {string} tag The label tag.
* @param {string} id The id of the element (to store it in
* "domElements").
* @param {?boolean} webgl Will init the WebGL context if true.
*/
sigma.renderers.webgl.prototype.initDOM = function(tag, id, webgl) {
var gl,
dom = document.createElement(tag),
self = this;
dom.style.position = 'absolute';
dom.setAttribute('class', 'sigma-' + id);
this.domElements[id] = dom;
this.container.appendChild(dom);
if (tag.toLowerCase() === 'canvas') {
this.contexts[id] = dom.getContext(webgl ? 'experimental-webgl' : '2d', {
preserveDrawingBuffer: true
});
// Adding webgl context loss listeners
if (webgl) {
dom.addEventListener('webglcontextlost', function(e) {
e.preventDefault();
}, false);
dom.addEventListener('webglcontextrestored', function(e) {
self.render();
}, false);
}
}
};
/**
* This method resizes each DOM elements in the container and stores the new
* dimensions. Then, it renders the graph.
*
* @param {?number} width The new width of the container.
* @param {?number} height The new height of the container.
* @return {sigma.renderers.webgl} Returns the instance itself.
*/
sigma.renderers.webgl.prototype.resize = function(w, h) {
var k,
oldWidth = this.width,
oldHeight = this.height;
if (w !== undefined && h !== undefined) {
this.width = w;
this.height = h;
} else {
this.width = this.container.offsetWidth;
this.height = this.container.offsetHeight;
w = this.width;
h = this.height;
}
if (oldWidth !== this.width || oldHeight !== this.height) {
for (k in this.domElements) {
this.domElements[k].style.width = w + 'px';
this.domElements[k].style.height = h + 'px';
if (this.domElements[k].tagName.toLowerCase() === 'canvas') {
// If simple 2D canvas:
if (this.contexts[k] && this.contexts[k].scale) {
this.domElements[k].setAttribute('width', w + 'px');
this.domElements[k].setAttribute('height', h + 'px');
} else {
this.domElements[k].setAttribute(
'width',
(w * this.settings('webglOversamplingRatio')) + 'px'
);
this.domElements[k].setAttribute(
'height',
(h * this.settings('webglOversamplingRatio')) + 'px'
);
}
}
}
}
// Scale:
for (k in this.contexts)
if (this.contexts[k] && this.contexts[k].viewport)
this.contexts[k].viewport(
0,
0,
this.width * this.settings('webglOversamplingRatio'),
this.height * this.settings('webglOversamplingRatio')
);
return this;
};
/**
* This method clears each canvas.
*
* @return {sigma.renderers.webgl} Returns the instance itself.
*/
sigma.renderers.webgl.prototype.clear = function() {
var k;
for (k in this.domElements)
if (this.domElements[k].tagName === 'CANVAS')
this.domElements[k].width = this.domElements[k].width;
this.contexts.nodes.clear(this.contexts.nodes.COLOR_BUFFER_BIT);
this.contexts.edges.clear(this.contexts.edges.COLOR_BUFFER_BIT);
return this;
};
/**
* This method kills contexts and other attributes.
*/
sigma.renderers.webgl.prototype.kill = function() {
var k,
captor;
// Kill captors:
while ((captor = this.captors.pop()))
captor.kill();
delete this.captors;
// Kill contexts:
for (k in this.domElements) {
this.domElements[k].parentNode.removeChild(this.domElements[k]);
delete this.domElements[k];
delete this.contexts[k];
}
delete this.domElements;
delete this.contexts;
};
/**
* The object "sigma.webgl.nodes" contains the different WebGL node
* renderers. The default one draw nodes as discs. Here are the attributes
* any node renderer must have:
*
* {number} POINTS The number of points required to draw a node.
* {number} ATTRIBUTES The number of attributes needed to draw one point.
* {function} addNode A function that adds a node to the data stack that
* will be given to the buffer. Here is the arguments:
* > {object} node
* > {number} index The node index in the
* nodes array.
* > {Float32Array} data The stack.
* > {object} options Some options.
* {function} render The function that will effectively render the nodes
* into the buffer.
* > {WebGLRenderingContext} gl
* > {WebGLProgram} program
* > {Float32Array} data The stack to give to the
* buffer.
* > {object} params An object containing some
* options, like width,
* height, the camera ratio.
* {function} initProgram The function that will initiate the program, with
* the relevant shaders and parameters. It must return
* the newly created program.
*
* Check sigma.webgl.nodes.def or sigma.webgl.nodes.fast to see how it
* works more precisely.
*/
sigma.utils.pkg('sigma.webgl.nodes');
/**
* The object "sigma.webgl.edges" contains the different WebGL edge
* renderers. The default one draw edges as direct lines. Here are the
* attributes any edge renderer must have:
*
* {number} POINTS The number of points required to draw an edge.
* {number} ATTRIBUTES The number of attributes needed to draw one point.
* {function} addEdge A function that adds an edge to the data stack that
* will be given to the buffer. Here is the arguments:
* > {object} edge
* > {object} source
* > {object} target
* > {Float32Array} data The stack.
* > {object} options Some options.
* {function} render The function that will effectively render the edges
* into the buffer.
* > {WebGLRenderingContext} gl
* > {WebGLProgram} program
* > {Float32Array} data The stack to give to the
* buffer.
* > {object} params An object containing some
* options, like width,
* height, the camera ratio.
* {function} initProgram The function that will initiate the program, with
* the relevant shaders and parameters. It must return
* the newly created program.
*
* Check sigma.webgl.edges.def or sigma.webgl.edges.fast to see how it
* works more precisely.
*/
sigma.utils.pkg('sigma.webgl.edges');
/**
* The object "sigma.canvas.labels" contains the different
* label renderers for the WebGL renderer. Since displaying texts in WebGL is
* definitely painful and since there a way less labels to display than nodes
* or edges, the default renderer simply renders them in a canvas.
*
* A labels renderer is a simple function, taking as arguments the related
* node, the renderer and a settings function.
*/
sigma.utils.pkg('sigma.canvas.labels');
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
if (typeof conrad === 'undefined')
throw 'conrad is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.renderers');
/**
* This function is the constructor of the svg sigma's renderer.
*
* @param {sigma.classes.graph} graph The graph to render.
* @param {sigma.classes.camera} camera The camera.
* @param {configurable} settings The sigma instance settings
* function.
* @param {object} object The options object.
* @return {sigma.renderers.svg} The renderer instance.
*/
sigma.renderers.svg = function(graph, camera, settings, options) {
if (typeof options !== 'object')
throw 'sigma.renderers.svg: Wrong arguments.';
if (!(options.container instanceof HTMLElement))
throw 'Container not found.';
var i,
l,
a,
fn,
self = this;
sigma.classes.dispatcher.extend(this);
// Initialize main attributes:
this.graph = graph;
this.camera = camera;
this.domElements = {
graph: null,
groups: {},
nodes: {},
edges: {},
labels: {},
hovers: {}
};
this.measurementCanvas = null;
this.options = options;
this.container = this.options.container;
this.settings = (
typeof options.settings === 'object' &&
options.settings
) ?
settings.embedObjects(options.settings) :
settings;
// Is the renderer meant to be freestyle?
this.settings('freeStyle', !!this.options.freeStyle);
// SVG xmlns
this.settings('xmlns', 'http://www.w3.org/2000/svg');
// Indexes:
this.nodesOnScreen = [];
this.edgesOnScreen = [];
// Find the prefix:
this.options.prefix = 'renderer' + sigma.utils.id() + ':';
// Initialize the DOM elements
this.initDOM('svg');
// Initialize captors:
this.captors = [];
a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch];
for (i = 0, l = a.length; i < l; i++) {
fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]];
this.captors.push(
new fn(
this.domElements.graph,
this.camera,
this.settings
)
);
}
// Bind resize:
window.addEventListener('resize', function() {
self.resize();
});
// Deal with sigma events:
// TODO: keep an option to override the DOM events?
sigma.misc.bindDOMEvents.call(this, this.domElements.graph);
this.bindHovers(this.options.prefix);
// Resize
this.resize(false);
};
/**
* This method renders the graph on the svg scene.
*
* @param {?object} options Eventually an object of options.
* @return {sigma.renderers.svg} Returns the instance itself.
*/
sigma.renderers.svg.prototype.render = function(options) {
options = options || {};
var a,
i,
k,
e,
l,
o,
source,
target,
start,
edges,
renderers,
subrenderers,
index = {},
graph = this.graph,
nodes = this.graph.nodes,
prefix = this.options.prefix || '',
drawEdges = this.settings(options, 'drawEdges'),
drawNodes = this.settings(options, 'drawNodes'),
drawLabels = this.settings(options, 'drawLabels'),
embedSettings = this.settings.embedObjects(options, {
prefix: this.options.prefix,
forceLabels: this.options.forceLabels
});
// Check the 'hideEdgesOnMove' setting:
if (this.settings(options, 'hideEdgesOnMove'))
if (this.camera.isAnimated || this.camera.isMoving)
drawEdges = false;
// Apply the camera's view:
this.camera.applyView(
undefined,
this.options.prefix,
{
width: this.width,
height: this.height
}
);
// Hiding everything
// TODO: find a more sensible way to perform this operation
this.hideDOMElements(this.domElements.nodes);
this.hideDOMElements(this.domElements.edges);
this.hideDOMElements(this.domElements.labels);
// Find which nodes are on screen
this.edgesOnScreen = [];
this.nodesOnScreen = this.camera.quadtree.area(
this.camera.getRectangle(this.width, this.height)
);
// Node index
for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
index[a[i].id] = a[i];
// Find which edges are on screen
for (a = graph.edges(), i = 0, l = a.length; i < l; i++) {
o = a[i];
if (
(index[o.source] || index[o.target]) &&
(!o.hidden && !nodes(o.source).hidden && !nodes(o.target).hidden)
)
this.edgesOnScreen.push(o);
}
// Display nodes
//---------------
renderers = sigma.svg.nodes;
subrenderers = sigma.svg.labels;
//-- First we create the nodes which are not already created
if (drawNodes)
for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) {
if (!a[i].hidden && !this.domElements.nodes[a[i].id]) {
// Node
e = (renderers[a[i].type] || renderers.def).create(
a[i],
embedSettings
);
this.domElements.nodes[a[i].id] = e;
this.domElements.groups.nodes.appendChild(e);
// Label
e = (subrenderers[a[i].type] || subrenderers.def).create(
a[i],
embedSettings
);
this.domElements.labels[a[i].id] = e;
this.domElements.groups.labels.appendChild(e);
}
}
//-- Second we update the nodes
if (drawNodes)
for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) {
if (a[i].hidden)
continue;
// Node
(renderers[a[i].type] || renderers.def).update(
a[i],
this.domElements.nodes[a[i].id],
embedSettings
);
// Label
(subrenderers[a[i].type] || subrenderers.def).update(
a[i],
this.domElements.labels[a[i].id],
embedSettings
);
}
// Display edges
//---------------
renderers = sigma.svg.edges;
//-- First we create the edges which are not already created
if (drawEdges)
for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) {
if (!this.domElements.edges[a[i].id]) {
source = nodes(a[i].source);
target = nodes(a[i].target);
e = (renderers[a[i].type] || renderers.def).create(
a[i],
source,
target,
embedSettings
);
this.domElements.edges[a[i].id] = e;
this.domElements.groups.edges.appendChild(e);
}
}
//-- Second we update the edges
if (drawEdges)
for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) {
source = nodes(a[i].source);
target = nodes(a[i].target);
(renderers[a[i].type] || renderers.def).update(
a[i],
this.domElements.edges[a[i].id],
source,
target,
embedSettings
);
}
this.dispatchEvent('render');
return this;
};
/**
* This method creates a DOM element of the specified type, switches its
* position to "absolute", references it to the domElements attribute, and
* finally appends it to the container.
*
* @param {string} tag The label tag.
* @param {string} id The id of the element (to store it in "domElements").
*/
sigma.renderers.svg.prototype.initDOM = function(tag) {
var dom = document.createElementNS(this.settings('xmlns'), tag),
c = this.settings('classPrefix'),
g,
l,
i;
dom.style.position = 'absolute';
dom.setAttribute('class', c + '-svg');
// Setting SVG namespace
dom.setAttribute('xmlns', this.settings('xmlns'));
dom.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
dom.setAttribute('version', '1.1');
// Creating the measurement canvas
var canvas = document.createElement('canvas');
canvas.setAttribute('class', c + '-measurement-canvas');
// Appending elements
this.domElements.graph = this.container.appendChild(dom);
// Creating groups
var groups = ['edges', 'nodes', 'labels', 'hovers'];
for (i = 0, l = groups.length; i < l; i++) {
g = document.createElementNS(this.settings('xmlns'), 'g');
g.setAttributeNS(null, 'id', c + '-group-' + groups[i]);
g.setAttributeNS(null, 'class', c + '-group');
this.domElements.groups[groups[i]] =
this.domElements.graph.appendChild(g);
}
// Appending measurement canvas
this.container.appendChild(canvas);
this.measurementCanvas = canvas.getContext('2d');
};
/**
* This method hides a batch of SVG DOM elements.
*
* @param {array} elements An array of elements to hide.
* @param {object} renderer The renderer to use.
* @return {sigma.renderers.svg} Returns the instance itself.
*/
sigma.renderers.svg.prototype.hideDOMElements = function(elements) {
var o,
i;
for (i in elements) {
o = elements[i];
sigma.svg.utils.hide(o);
}
return this;
};
/**
* This method binds the hover events to the renderer.
*
* @param {string} prefix The renderer prefix.
*/
// TODO: add option about whether to display hovers or not
sigma.renderers.svg.prototype.bindHovers = function(prefix) {
var renderers = sigma.svg.hovers,
self = this,
hoveredNode;
function overNode(e) {
var node = e.data.node,
embedSettings = self.settings.embedObjects({
prefix: prefix
});
if (!embedSettings('enableHovering'))
return;
var hover = (renderers[node.type] || renderers.def).create(
node,
self.domElements.nodes[node.id],
self.measurementCanvas,
embedSettings
);
self.domElements.hovers[node.id] = hover;
// Inserting the hover in the dom
self.domElements.groups.hovers.appendChild(hover);
hoveredNode = node;
}
function outNode(e) {
var node = e.data.node,
embedSettings = self.settings.embedObjects({
prefix: prefix
});
if (!embedSettings('enableHovering'))
return;
// Deleting element
self.domElements.groups.hovers.removeChild(
self.domElements.hovers[node.id]
);
hoveredNode = null;
delete self.domElements.hovers[node.id];
// Reinstate
self.domElements.groups.nodes.appendChild(
self.domElements.nodes[node.id]
);
}
// OPTIMIZE: perform a real update rather than a deletion
function update() {
if (!hoveredNode)
return;
var embedSettings = self.settings.embedObjects({
prefix: prefix
});
// Deleting element before update
self.domElements.groups.hovers.removeChild(
self.domElements.hovers[hoveredNode.id]
);
delete self.domElements.hovers[hoveredNode.id];
var hover = (renderers[hoveredNode.type] || renderers.def).create(
hoveredNode,
self.domElements.nodes[hoveredNode.id],
self.measurementCanvas,
embedSettings
);
self.domElements.hovers[hoveredNode.id] = hover;
// Inserting the hover in the dom
self.domElements.groups.hovers.appendChild(hover);
}
// Binding events
this.bind('overNode', overNode);
this.bind('outNode', outNode);
// Update on render
this.bind('render', update);
};
/**
* This method resizes each DOM elements in the container and stores the new
* dimensions. Then, it renders the graph.
*
* @param {?number} width The new width of the container.
* @param {?number} height The new height of the container.
* @return {sigma.renderers.svg} Returns the instance itself.
*/
sigma.renderers.svg.prototype.resize = function(w, h) {
var oldWidth = this.width,
oldHeight = this.height,
pixelRatio = 1;
if (w !== undefined && h !== undefined) {
this.width = w;
this.height = h;
} else {
this.width = this.container.offsetWidth;
this.height = this.container.offsetHeight;
w = this.width;
h = this.height;
}
if (oldWidth !== this.width || oldHeight !== this.height) {
this.domElements.graph.style.width = w + 'px';
this.domElements.graph.style.height = h + 'px';
if (this.domElements.graph.tagName.toLowerCase() === 'svg') {
this.domElements.graph.setAttribute('width', (w * pixelRatio));
this.domElements.graph.setAttribute('height', (h * pixelRatio));
}
}
return this;
};
/**
* The labels, nodes and edges renderers are stored in the three following
* objects. When an element is drawn, its type will be checked and if a
* renderer with the same name exists, it will be used. If not found, the
* default renderer will be used instead.
*
* They are stored in different files, in the "./svg" folder.
*/
sigma.utils.pkg('sigma.svg.nodes');
sigma.utils.pkg('sigma.svg.edges');
sigma.utils.pkg('sigma.svg.labels');
}).call(this);
;(function(global) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.renderers');
// Check if WebGL is enabled:
var canvas,
webgl = !!global.WebGLRenderingContext;
if (webgl) {
canvas = document.createElement('canvas');
try {
webgl = !!(
canvas.getContext('webgl') ||
canvas.getContext('experimental-webgl')
);
} catch (e) {
webgl = false;
}
}
// Copy the good renderer:
sigma.renderers.def = webgl ?
sigma.renderers.webgl :
sigma.renderers.canvas;
})(this);
;(function() {
'use strict';
sigma.utils.pkg('sigma.webgl.nodes');
/**
* This node renderer will display nodes as discs, shaped in triangles with
* the gl.TRIANGLES display mode. So, to be more precise, to draw one node,
* it will store three times the center of node, with the color and the size,
* and an angle indicating which "corner" of the triangle to draw.
*
* The fragment shader does not deal with anti-aliasing, so make sure that
* you deal with it somewhere else in the code (by default, the WebGL
* renderer will oversample the rendering through the webglOversamplingRatio
* value).
*/
sigma.webgl.nodes.def = {
POINTS: 3,
ATTRIBUTES: 5,
addNode: function(node, data, i, prefix, settings) {
var color = sigma.utils.floatColor(
node.color || settings('defaultNodeColor')
);
data[i++] = node[prefix + 'x'];
data[i++] = node[prefix + 'y'];
data[i++] = node[prefix + 'size'];
data[i++] = color;
data[i++] = 0;
data[i++] = node[prefix + 'x'];
data[i++] = node[prefix + 'y'];
data[i++] = node[prefix + 'size'];
data[i++] = color;
data[i++] = 2 * Math.PI / 3;
data[i++] = node[prefix + 'x'];
data[i++] = node[prefix + 'y'];
data[i++] = node[prefix + 'size'];
data[i++] = color;
data[i++] = 4 * Math.PI / 3;
},
render: function(gl, program, data, params) {
var buffer;
// Define attributes:
var positionLocation =
gl.getAttribLocation(program, 'a_position'),
sizeLocation =
gl.getAttribLocation(program, 'a_size'),
colorLocation =
gl.getAttribLocation(program, 'a_color'),
angleLocation =
gl.getAttribLocation(program, 'a_angle'),
resolutionLocation =
gl.getUniformLocation(program, 'u_resolution'),
matrixLocation =
gl.getUniformLocation(program, 'u_matrix'),
ratioLocation =
gl.getUniformLocation(program, 'u_ratio'),
scaleLocation =
gl.getUniformLocation(program, 'u_scale');
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);
gl.uniform2f(resolutionLocation, params.width, params.height);
gl.uniform1f(
ratioLocation,
1 / Math.pow(params.ratio, params.settings('nodesPowRatio'))
);
gl.uniform1f(scaleLocation, params.scalingRatio);
gl.uniformMatrix3fv(matrixLocation, false, params.matrix);
gl.enableVertexAttribArray(positionLocation);
gl.enableVertexAttribArray(sizeLocation);
gl.enableVertexAttribArray(colorLocation);
gl.enableVertexAttribArray(angleLocation);
gl.vertexAttribPointer(
positionLocation,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.vertexAttribPointer(
sizeLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
8
);
gl.vertexAttribPointer(
colorLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
12
);
gl.vertexAttribPointer(
angleLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
16
);
gl.drawArrays(
gl.TRIANGLES,
params.start || 0,
params.count || (data.length / this.ATTRIBUTES)
);
},
initProgram: function(gl) {
var vertexShader,
fragmentShader,
program;
vertexShader = sigma.utils.loadShader(
gl,
[
'attribute vec2 a_position;',
'attribute float a_size;',
'attribute float a_color;',
'attribute float a_angle;',
'uniform vec2 u_resolution;',
'uniform float u_ratio;',
'uniform float u_scale;',
'uniform mat3 u_matrix;',
'varying vec4 color;',
'varying vec2 center;',
'varying float radius;',
'void main() {',
// Multiply the point size twice:
'radius = a_size * u_ratio;',
// Scale from [[-1 1] [-1 1]] to the container:
'vec2 position = (u_matrix * vec3(a_position, 1)).xy;',
// 'center = (position / u_resolution * 2.0 - 1.0) * vec2(1, -1);',
'center = position * u_scale;',
'center = vec2(center.x, u_scale * u_resolution.y - center.y);',
'position = position +',
'2.0 * radius * vec2(cos(a_angle), sin(a_angle));',
'position = (position / u_resolution * 2.0 - 1.0) * vec2(1, -1);',
'radius = radius * u_scale;',
'gl_Position = vec4(position, 0, 1);',
// Extract the color:
'float c = a_color;',
'color.b = mod(c, 256.0); c = floor(c / 256.0);',
'color.g = mod(c, 256.0); c = floor(c / 256.0);',
'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;',
'color.a = 1.0;',
'}'
].join('\n'),
gl.VERTEX_SHADER
);
fragmentShader = sigma.utils.loadShader(
gl,
[
'precision mediump float;',
'varying vec4 color;',
'varying vec2 center;',
'varying float radius;',
'void main(void) {',
'vec4 color0 = vec4(0.0, 0.0, 0.0, 0.0);',
'vec2 m = gl_FragCoord.xy - center;',
'float diff = radius - sqrt(m.x * m.x + m.y * m.y);',
// Here is how we draw a disc instead of a square:
'if (diff > 0.0)',
'gl_FragColor = color;',
'else',
'gl_FragColor = color0;',
'}'
].join('\n'),
gl.FRAGMENT_SHADER
);
program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);
return program;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.webgl.nodes');
/**
* This node renderer will display nodes in the fastest way: Nodes are basic
* squares, drawn through the gl.POINTS drawing method. The size of the nodes
* are represented with the "gl_PointSize" value in the vertex shader.
*
* It is the fastest node renderer here since the buffer just takes one line
* to draw each node (with attributes "x", "y", "size" and "color").
*
* Nevertheless, this method has some problems, especially due to some issues
* with the gl.POINTS:
* - First, if the center of a node is outside the scene, the point will not
* be drawn, even if it should be partly on screen.
* - I tried applying a fragment shader similar to the one in the default
* node renderer to display them as discs, but it did not work fine on
* some computers settings, filling the discs with weird gradients not
* depending on the actual color.
*/
sigma.webgl.nodes.fast = {
POINTS: 1,
ATTRIBUTES: 4,
addNode: function(node, data, i, prefix, settings) {
data[i++] = node[prefix + 'x'];
data[i++] = node[prefix + 'y'];
data[i++] = node[prefix + 'size'];
data[i++] = sigma.utils.floatColor(
node.color || settings('defaultNodeColor')
);
},
render: function(gl, program, data, params) {
var buffer;
// Define attributes:
var positionLocation =
gl.getAttribLocation(program, 'a_position'),
sizeLocation =
gl.getAttribLocation(program, 'a_size'),
colorLocation =
gl.getAttribLocation(program, 'a_color'),
resolutionLocation =
gl.getUniformLocation(program, 'u_resolution'),
matrixLocation =
gl.getUniformLocation(program, 'u_matrix'),
ratioLocation =
gl.getUniformLocation(program, 'u_ratio'),
scaleLocation =
gl.getUniformLocation(program, 'u_scale');
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);
gl.uniform2f(resolutionLocation, params.width, params.height);
gl.uniform1f(
ratioLocation,
1 / Math.pow(params.ratio, params.settings('nodesPowRatio'))
);
gl.uniform1f(scaleLocation, params.scalingRatio);
gl.uniformMatrix3fv(matrixLocation, false, params.matrix);
gl.enableVertexAttribArray(positionLocation);
gl.enableVertexAttribArray(sizeLocation);
gl.enableVertexAttribArray(colorLocation);
gl.vertexAttribPointer(
positionLocation,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.vertexAttribPointer(
sizeLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
8
);
gl.vertexAttribPointer(
colorLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
12
);
gl.drawArrays(
gl.POINTS,
params.start || 0,
params.count || (data.length / this.ATTRIBUTES)
);
},
initProgram: function(gl) {
var vertexShader,
fragmentShader,
program;
vertexShader = sigma.utils.loadShader(
gl,
[
'attribute vec2 a_position;',
'attribute float a_size;',
'attribute float a_color;',
'uniform vec2 u_resolution;',
'uniform float u_ratio;',
'uniform float u_scale;',
'uniform mat3 u_matrix;',
'varying vec4 color;',
'void main() {',
// Scale from [[-1 1] [-1 1]] to the container:
'gl_Position = vec4(',
'((u_matrix * vec3(a_position, 1)).xy /',
'u_resolution * 2.0 - 1.0) * vec2(1, -1),',
'0,',
'1',
');',
// Multiply the point size twice:
// - x SCALING_RATIO to correct the canvas scaling
// - x 2 to correct the formulae
'gl_PointSize = a_size * u_ratio * u_scale * 2.0;',
// Extract the color:
'float c = a_color;',
'color.b = mod(c, 256.0); c = floor(c / 256.0);',
'color.g = mod(c, 256.0); c = floor(c / 256.0);',
'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;',
'color.a = 1.0;',
'}'
].join('\n'),
gl.VERTEX_SHADER
);
fragmentShader = sigma.utils.loadShader(
gl,
[
'precision mediump float;',
'varying vec4 color;',
'void main(void) {',
'gl_FragColor = color;',
'}'
].join('\n'),
gl.FRAGMENT_SHADER
);
program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);
return program;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.webgl.edges');
/**
* This edge renderer will display edges as lines going from the source node
* to the target node. To deal with edge thicknesses, the lines are made of
* two triangles forming rectangles, with the gl.TRIANGLES drawing mode.
*
* It is expensive, since drawing a single edge requires 6 points, each
* having 7 attributes (source position, target position, thickness, color
* and a flag indicating which vertice of the rectangle it is).
*/
sigma.webgl.edges.def = {
POINTS: 6,
ATTRIBUTES: 7,
addEdge: function(edge, source, target, data, i, prefix, settings) {
var w = (edge[prefix + 'size'] || 1) / 2,
x1 = source[prefix + 'x'],
y1 = source[prefix + 'y'],
x2 = target[prefix + 'x'],
y2 = target[prefix + 'y'],
color = edge.color;
if (!color)
switch (settings('edgeColor')) {
case 'source':
color = source.color || settings('defaultNodeColor');
break;
case 'target':
color = target.color || settings('defaultNodeColor');
break;
default:
color = settings('defaultEdgeColor');
break;
}
// Normalize color:
color = sigma.utils.floatColor(color);
data[i++] = x1;
data[i++] = y1;
data[i++] = x2;
data[i++] = y2;
data[i++] = w;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = 1.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x1;
data[i++] = y1;
data[i++] = x2;
data[i++] = y2;
data[i++] = w;
data[i++] = 1.0;
data[i++] = color;
data[i++] = x1;
data[i++] = y1;
data[i++] = x2;
data[i++] = y2;
data[i++] = w;
data[i++] = 0.0;
data[i++] = color;
},
render: function(gl, program, data, params) {
var buffer;
// Define attributes:
var colorLocation =
gl.getAttribLocation(program, 'a_color'),
positionLocation1 =
gl.getAttribLocation(program, 'a_position1'),
positionLocation2 =
gl.getAttribLocation(program, 'a_position2'),
thicknessLocation =
gl.getAttribLocation(program, 'a_thickness'),
minusLocation =
gl.getAttribLocation(program, 'a_minus'),
resolutionLocation =
gl.getUniformLocation(program, 'u_resolution'),
matrixLocation =
gl.getUniformLocation(program, 'u_matrix'),
matrixHalfPiLocation =
gl.getUniformLocation(program, 'u_matrixHalfPi'),
matrixHalfPiMinusLocation =
gl.getUniformLocation(program, 'u_matrixHalfPiMinus'),
ratioLocation =
gl.getUniformLocation(program, 'u_ratio'),
scaleLocation =
gl.getUniformLocation(program, 'u_scale');
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
gl.uniform2f(resolutionLocation, params.width, params.height);
gl.uniform1f(
ratioLocation,
params.ratio / Math.pow(params.ratio, params.settings('edgesPowRatio'))
);
gl.uniform1f(scaleLocation, params.scalingRatio);
gl.uniformMatrix3fv(matrixLocation, false, params.matrix);
gl.uniformMatrix2fv(
matrixHalfPiLocation,
false,
sigma.utils.matrices.rotation(Math.PI / 2, true)
);
gl.uniformMatrix2fv(
matrixHalfPiMinusLocation,
false,
sigma.utils.matrices.rotation(-Math.PI / 2, true)
);
gl.enableVertexAttribArray(colorLocation);
gl.enableVertexAttribArray(positionLocation1);
gl.enableVertexAttribArray(positionLocation2);
gl.enableVertexAttribArray(thicknessLocation);
gl.enableVertexAttribArray(minusLocation);
gl.vertexAttribPointer(positionLocation1,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.vertexAttribPointer(positionLocation2,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
8
);
gl.vertexAttribPointer(thicknessLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
16
);
gl.vertexAttribPointer(minusLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
20
);
gl.vertexAttribPointer(colorLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
24
);
gl.drawArrays(
gl.TRIANGLES,
params.start || 0,
params.count || (data.length / this.ATTRIBUTES)
);
},
initProgram: function(gl) {
var vertexShader,
fragmentShader,
program;
vertexShader = sigma.utils.loadShader(
gl,
[
'attribute vec2 a_position1;',
'attribute vec2 a_position2;',
'attribute float a_thickness;',
'attribute float a_minus;',
'attribute float a_color;',
'uniform vec2 u_resolution;',
'uniform float u_ratio;',
'uniform float u_scale;',
'uniform mat3 u_matrix;',
'uniform mat2 u_matrixHalfPi;',
'uniform mat2 u_matrixHalfPiMinus;',
'varying vec4 color;',
'void main() {',
// Find the good point:
'vec2 position = a_thickness * u_ratio *',
'normalize(a_position2 - a_position1);',
'mat2 matrix = a_minus * u_matrixHalfPiMinus +',
'(1.0 - a_minus) * u_matrixHalfPi;',
'position = matrix * position + a_position1;',
// Scale from [[-1 1] [-1 1]] to the container:
'gl_Position = vec4(',
'((u_matrix * vec3(position, 1)).xy /',
'u_resolution * 2.0 - 1.0) * vec2(1, -1),',
'0,',
'1',
');',
// Extract the color:
'float c = a_color;',
'color.b = mod(c, 256.0); c = floor(c / 256.0);',
'color.g = mod(c, 256.0); c = floor(c / 256.0);',
'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;',
'color.a = 1.0;',
'}'
].join('\n'),
gl.VERTEX_SHADER
);
fragmentShader = sigma.utils.loadShader(
gl,
[
'precision mediump float;',
'varying vec4 color;',
'void main(void) {',
'gl_FragColor = color;',
'}'
].join('\n'),
gl.FRAGMENT_SHADER
);
program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);
return program;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.webgl.edges');
/**
* This edge renderer will display edges as lines with the gl.LINES display
* mode. Since this mode does not support well thickness, edges are all drawn
* with the same thickness (3px), independantly of the edge attributes or the
* zooming ratio.
*/
sigma.webgl.edges.fast = {
POINTS: 2,
ATTRIBUTES: 3,
addEdge: function(edge, source, target, data, i, prefix, settings) {
var w = (edge[prefix + 'size'] || 1) / 2,
x1 = source[prefix + 'x'],
y1 = source[prefix + 'y'],
x2 = target[prefix + 'x'],
y2 = target[prefix + 'y'],
color = edge.color;
if (!color)
switch (settings('edgeColor')) {
case 'source':
color = source.color || settings('defaultNodeColor');
break;
case 'target':
color = target.color || settings('defaultNodeColor');
break;
default:
color = settings('defaultEdgeColor');
break;
}
// Normalize color:
color = sigma.utils.floatColor(color);
data[i++] = x1;
data[i++] = y1;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = color;
},
render: function(gl, program, data, params) {
var buffer;
// Define attributes:
var colorLocation =
gl.getAttribLocation(program, 'a_color'),
positionLocation =
gl.getAttribLocation(program, 'a_position'),
resolutionLocation =
gl.getUniformLocation(program, 'u_resolution'),
matrixLocation =
gl.getUniformLocation(program, 'u_matrix');
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);
gl.uniform2f(resolutionLocation, params.width, params.height);
gl.uniformMatrix3fv(matrixLocation, false, params.matrix);
gl.enableVertexAttribArray(positionLocation);
gl.enableVertexAttribArray(colorLocation);
gl.vertexAttribPointer(positionLocation,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.vertexAttribPointer(colorLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
8
);
gl.lineWidth(3);
gl.drawArrays(
gl.LINES,
params.start || 0,
params.count || (data.length / this.ATTRIBUTES)
);
},
initProgram: function(gl) {
var vertexShader,
fragmentShader,
program;
vertexShader = sigma.utils.loadShader(
gl,
[
'attribute vec2 a_position;',
'attribute float a_color;',
'uniform vec2 u_resolution;',
'uniform mat3 u_matrix;',
'varying vec4 color;',
'void main() {',
// Scale from [[-1 1] [-1 1]] to the container:
'gl_Position = vec4(',
'((u_matrix * vec3(a_position, 1)).xy /',
'u_resolution * 2.0 - 1.0) * vec2(1, -1),',
'0,',
'1',
');',
// Extract the color:
'float c = a_color;',
'color.b = mod(c, 256.0); c = floor(c / 256.0);',
'color.g = mod(c, 256.0); c = floor(c / 256.0);',
'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;',
'color.a = 1.0;',
'}'
].join('\n'),
gl.VERTEX_SHADER
);
fragmentShader = sigma.utils.loadShader(
gl,
[
'precision mediump float;',
'varying vec4 color;',
'void main(void) {',
'gl_FragColor = color;',
'}'
].join('\n'),
gl.FRAGMENT_SHADER
);
program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);
return program;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.webgl.edges');
/**
* This edge renderer will display edges as arrows going from the source node
* to the target node. To deal with edge thicknesses, the lines are made of
* three triangles: two forming rectangles, with the gl.TRIANGLES drawing
* mode.
*
* It is expensive, since drawing a single edge requires 9 points, each
* having a lot of attributes.
*/
sigma.webgl.edges.arrow = {
POINTS: 9,
ATTRIBUTES: 11,
addEdge: function(edge, source, target, data, i, prefix, settings) {
var w = (edge[prefix + 'size'] || 1) / 2,
x1 = source[prefix + 'x'],
y1 = source[prefix + 'y'],
x2 = target[prefix + 'x'],
y2 = target[prefix + 'y'],
targetSize = target[prefix + 'size'],
color = edge.color;
if (!color)
switch (settings('edgeColor')) {
case 'source':
color = source.color || settings('defaultNodeColor');
break;
case 'target':
color = target.color || settings('defaultNodeColor');
break;
default:
color = settings('defaultEdgeColor');
break;
}
// Normalize color:
color = sigma.utils.floatColor(color);
data[i++] = x1;
data[i++] = y1;
data[i++] = x2;
data[i++] = y2;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 1.0;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x1;
data[i++] = y1;
data[i++] = x2;
data[i++] = y2;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 0.0;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x1;
data[i++] = y1;
data[i++] = x2;
data[i++] = y2;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = 0.0;
data[i++] = color;
// Arrow head:
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 1.0;
data[i++] = -1.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = color;
data[i++] = x2;
data[i++] = y2;
data[i++] = x1;
data[i++] = y1;
data[i++] = w;
data[i++] = targetSize;
data[i++] = 1.0;
data[i++] = 0.0;
data[i++] = 1.0;
data[i++] = 1.0;
data[i++] = color;
},
render: function(gl, program, data, params) {
var buffer;
// Define attributes:
var positionLocation1 =
gl.getAttribLocation(program, 'a_pos1'),
positionLocation2 =
gl.getAttribLocation(program, 'a_pos2'),
thicknessLocation =
gl.getAttribLocation(program, 'a_thickness'),
targetSizeLocation =
gl.getAttribLocation(program, 'a_tSize'),
delayLocation =
gl.getAttribLocation(program, 'a_delay'),
minusLocation =
gl.getAttribLocation(program, 'a_minus'),
headLocation =
gl.getAttribLocation(program, 'a_head'),
headPositionLocation =
gl.getAttribLocation(program, 'a_headPosition'),
colorLocation =
gl.getAttribLocation(program, 'a_color'),
resolutionLocation =
gl.getUniformLocation(program, 'u_resolution'),
matrixLocation =
gl.getUniformLocation(program, 'u_matrix'),
matrixHalfPiLocation =
gl.getUniformLocation(program, 'u_matrixHalfPi'),
matrixHalfPiMinusLocation =
gl.getUniformLocation(program, 'u_matrixHalfPiMinus'),
ratioLocation =
gl.getUniformLocation(program, 'u_ratio'),
nodeRatioLocation =
gl.getUniformLocation(program, 'u_nodeRatio'),
arrowHeadLocation =
gl.getUniformLocation(program, 'u_arrowHead'),
scaleLocation =
gl.getUniformLocation(program, 'u_scale');
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
gl.uniform2f(resolutionLocation, params.width, params.height);
gl.uniform1f(
ratioLocation,
params.ratio / Math.pow(params.ratio, params.settings('edgesPowRatio'))
);
gl.uniform1f(
nodeRatioLocation,
Math.pow(params.ratio, params.settings('nodesPowRatio')) /
params.ratio
);
gl.uniform1f(arrowHeadLocation, 5.0);
gl.uniform1f(scaleLocation, params.scalingRatio);
gl.uniformMatrix3fv(matrixLocation, false, params.matrix);
gl.uniformMatrix2fv(
matrixHalfPiLocation,
false,
sigma.utils.matrices.rotation(Math.PI / 2, true)
);
gl.uniformMatrix2fv(
matrixHalfPiMinusLocation,
false,
sigma.utils.matrices.rotation(-Math.PI / 2, true)
);
gl.enableVertexAttribArray(positionLocation1);
gl.enableVertexAttribArray(positionLocation2);
gl.enableVertexAttribArray(thicknessLocation);
gl.enableVertexAttribArray(targetSizeLocation);
gl.enableVertexAttribArray(delayLocation);
gl.enableVertexAttribArray(minusLocation);
gl.enableVertexAttribArray(headLocation);
gl.enableVertexAttribArray(headPositionLocation);
gl.enableVertexAttribArray(colorLocation);
gl.vertexAttribPointer(positionLocation1,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.vertexAttribPointer(positionLocation2,
2,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
8
);
gl.vertexAttribPointer(thicknessLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
16
);
gl.vertexAttribPointer(targetSizeLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
20
);
gl.vertexAttribPointer(delayLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
24
);
gl.vertexAttribPointer(minusLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
28
);
gl.vertexAttribPointer(headLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
32
);
gl.vertexAttribPointer(headPositionLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
36
);
gl.vertexAttribPointer(colorLocation,
1,
gl.FLOAT,
false,
this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
40
);
gl.drawArrays(
gl.TRIANGLES,
params.start || 0,
params.count || (data.length / this.ATTRIBUTES)
);
},
initProgram: function(gl) {
var vertexShader,
fragmentShader,
program;
vertexShader = sigma.utils.loadShader(
gl,
[
'attribute vec2 a_pos1;',
'attribute vec2 a_pos2;',
'attribute float a_thickness;',
'attribute float a_tSize;',
'attribute float a_delay;',
'attribute float a_minus;',
'attribute float a_head;',
'attribute float a_headPosition;',
'attribute float a_color;',
'uniform vec2 u_resolution;',
'uniform float u_ratio;',
'uniform float u_nodeRatio;',
'uniform float u_arrowHead;',
'uniform float u_scale;',
'uniform mat3 u_matrix;',
'uniform mat2 u_matrixHalfPi;',
'uniform mat2 u_matrixHalfPiMinus;',
'varying vec4 color;',
'void main() {',
// Find the good point:
'vec2 pos = normalize(a_pos2 - a_pos1);',
'mat2 matrix = (1.0 - a_head) *',
'(',
'a_minus * u_matrixHalfPiMinus +',
'(1.0 - a_minus) * u_matrixHalfPi',
') + a_head * (',
'a_headPosition * u_matrixHalfPiMinus * 0.6 +',
'(a_headPosition * a_headPosition - 1.0) * mat2(1.0)',
');',
'pos = a_pos1 + (',
// Deal with body:
'(1.0 - a_head) * a_thickness * u_ratio * matrix * pos +',
// Deal with head:
'a_head * u_arrowHead * a_thickness * u_ratio * matrix * pos +',
// Deal with delay:
'a_delay * pos * (',
'a_tSize / u_nodeRatio +',
'u_arrowHead * a_thickness * u_ratio',
')',
');',
// Scale from [[-1 1] [-1 1]] to the container:
'gl_Position = vec4(',
'((u_matrix * vec3(pos, 1)).xy /',
'u_resolution * 2.0 - 1.0) * vec2(1, -1),',
'0,',
'1',
');',
// Extract the color:
'float c = a_color;',
'color.b = mod(c, 256.0); c = floor(c / 256.0);',
'color.g = mod(c, 256.0); c = floor(c / 256.0);',
'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;',
'color.a = 1.0;',
'}'
].join('\n'),
gl.VERTEX_SHADER
);
fragmentShader = sigma.utils.loadShader(
gl,
[
'precision mediump float;',
'varying vec4 color;',
'void main(void) {',
'gl_FragColor = color;',
'}'
].join('\n'),
gl.FRAGMENT_SHADER
);
program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);
return program;
}
};
})();
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.canvas.labels');
/**
* This label renderer will just display the label on the right of the node.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.labels.def = function(node, context, settings) {
var fontSize,
prefix = settings('prefix') || '',
size = node[prefix + 'size'];
if (size < settings('labelThreshold'))
return;
if (!node.label || typeof node.label !== 'string')
return;
fontSize = (settings('labelSize') === 'fixed') ?
settings('defaultLabelSize') :
settings('labelSizeRatio') * size;
context.font = (settings('fontStyle') ? settings('fontStyle') + ' ' : '') +
fontSize + 'px ' + settings('font');
context.fillStyle = (settings('labelColor') === 'node') ?
(node.color || settings('defaultNodeColor')) :
settings('defaultLabelColor');
context.fillText(
node.label,
Math.round(node[prefix + 'x'] + size + 3),
Math.round(node[prefix + 'y'] + fontSize / 3)
);
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.canvas.hovers');
/**
* This hover renderer will basically display the label with a background.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.hovers.def = function(node, context, settings) {
var x,
y,
w,
h,
e,
fontStyle = settings('hoverFontStyle') || settings('fontStyle'),
prefix = settings('prefix') || '',
size = node[prefix + 'size'],
fontSize = (settings('labelSize') === 'fixed') ?
settings('defaultLabelSize') :
settings('labelSizeRatio') * size;
// Label background:
context.font = (fontStyle ? fontStyle + ' ' : '') +
fontSize + 'px ' + (settings('hoverFont') || settings('font'));
context.beginPath();
context.fillStyle = settings('labelHoverBGColor') === 'node' ?
(node.color || settings('defaultNodeColor')) :
settings('defaultHoverLabelBGColor');
if (node.label && settings('labelHoverShadow')) {
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 8;
context.shadowColor = settings('labelHoverShadowColor');
}
if (node.label && typeof node.label === 'string') {
x = Math.round(node[prefix + 'x'] - fontSize / 2 - 2);
y = Math.round(node[prefix + 'y'] - fontSize / 2 - 2);
w = Math.round(
context.measureText(node.label).width + fontSize / 2 + size + 7
);
h = Math.round(fontSize + 4);
e = Math.round(fontSize / 2 + 2);
context.moveTo(x, y + e);
context.arcTo(x, y, x + e, y, e);
context.lineTo(x + w, y);
context.lineTo(x + w, y + h);
context.lineTo(x + e, y + h);
context.arcTo(x, y + h, x, y + h - e, e);
context.lineTo(x, y + e);
context.closePath();
context.fill();
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 0;
}
// Node border:
if (settings('borderSize') > 0) {
context.beginPath();
context.fillStyle = settings('nodeBorderColor') === 'node' ?
(node.color || settings('defaultNodeColor')) :
settings('defaultNodeBorderColor');
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
size + settings('borderSize'),
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
}
// Node:
var nodeRenderer = sigma.canvas.nodes[node.type] || sigma.canvas.nodes.def;
nodeRenderer(node, context, settings);
// Display the label:
if (node.label && typeof node.label === 'string') {
context.fillStyle = (settings('labelHoverColor') === 'node') ?
(node.color || settings('defaultNodeColor')) :
settings('defaultLabelHoverColor');
context.fillText(
node.label,
Math.round(node[prefix + 'x'] + size + 3),
Math.round(node[prefix + 'y'] + fontSize / 3)
);
}
};
}).call(this);
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edges');
/**
* The default edge renderer. It renders the edge as a simple line.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edges.def = function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
size = edge[prefix + 'size'] || 1,
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor');
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(
source[prefix + 'x'],
source[prefix + 'y']
);
context.lineTo(
target[prefix + 'x'],
target[prefix + 'y']
);
context.stroke();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edges');
/**
* This edge renderer will display edges as curves.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edges.curve = function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
size = edge[prefix + 'size'] || 1,
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
cp = {},
sSize = source[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'];
cp = (source.id === target.id) ?
sigma.utils.getSelfLoopControlPoints(sX, sY, sSize) :
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY);
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
if (source.id === target.id) {
context.bezierCurveTo(cp.x1, cp.y1, cp.x2, cp.y2, tX, tY);
} else {
context.quadraticCurveTo(cp.x, cp.y, tX, tY);
}
context.stroke();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edges');
/**
* This edge renderer will display edges as arrows going from the source node
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edges.arrow = function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
size = edge[prefix + 'size'] || 1,
tSize = target[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'],
aSize = Math.max(size * 2.5, settings('minArrowSize')),
d = Math.sqrt(Math.pow(tX - sX, 2) + Math.pow(tY - sY, 2)),
aX = sX + (tX - sX) * (d - aSize - tSize) / d,
aY = sY + (tY - sY) * (d - aSize - tSize) / d,
vX = (tX - sX) * aSize / d,
vY = (tY - sY) * aSize / d;
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
context.lineTo(
aX,
aY
);
context.stroke();
context.fillStyle = color;
context.beginPath();
context.moveTo(aX + vX, aY + vY);
context.lineTo(aX + vY * 0.6, aY - vX * 0.6);
context.lineTo(aX - vY * 0.6, aY + vX * 0.6);
context.lineTo(aX + vX, aY + vY);
context.closePath();
context.fill();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edges');
/**
* This edge renderer will display edges as curves with arrow heading.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edges.curvedArrow =
function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
cp = {},
size = edge[prefix + 'size'] || 1,
tSize = target[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'],
aSize = Math.max(size * 2.5, settings('minArrowSize')),
d,
aX,
aY,
vX,
vY;
cp = (source.id === target.id) ?
sigma.utils.getSelfLoopControlPoints(sX, sY, tSize) :
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY);
if (source.id === target.id) {
d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2));
aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d;
aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d;
vX = (tX - cp.x1) * aSize / d;
vY = (tY - cp.y1) * aSize / d;
}
else {
d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2));
aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d;
aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d;
vX = (tX - cp.x) * aSize / d;
vY = (tY - cp.y) * aSize / d;
}
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
if (source.id === target.id) {
context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY);
} else {
context.quadraticCurveTo(cp.x, cp.y, aX, aY);
}
context.stroke();
context.fillStyle = color;
context.beginPath();
context.moveTo(aX + vX, aY + vY);
context.lineTo(aX + vY * 0.6, aY - vX * 0.6);
context.lineTo(aX - vY * 0.6, aY + vX * 0.6);
context.lineTo(aX + vX, aY + vY);
context.closePath();
context.fill();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edgehovers');
/**
* This hover renderer will display the edge with a different color or size.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edgehovers.def =
function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
size = edge[prefix + 'size'] || 1,
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor');
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
if (settings('edgeHoverColor') === 'edge') {
color = edge.hover_color || color;
} else {
color = edge.hover_color || settings('defaultEdgeHoverColor') || color;
}
size *= settings('edgeHoverSizeRatio');
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(
source[prefix + 'x'],
source[prefix + 'y']
);
context.lineTo(
target[prefix + 'x'],
target[prefix + 'y']
);
context.stroke();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edgehovers');
/**
* This hover renderer will display the edge with a different color or size.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edgehovers.curve =
function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
size = settings('edgeHoverSizeRatio') * (edge[prefix + 'size'] || 1),
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
cp = {},
sSize = source[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'];
cp = (source.id === target.id) ?
sigma.utils.getSelfLoopControlPoints(sX, sY, sSize) :
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY);
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
if (settings('edgeHoverColor') === 'edge') {
color = edge.hover_color || color;
} else {
color = edge.hover_color || settings('defaultEdgeHoverColor') || color;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
if (source.id === target.id) {
context.bezierCurveTo(cp.x1, cp.y1, cp.x2, cp.y2, tX, tY);
} else {
context.quadraticCurveTo(cp.x, cp.y, tX, tY);
}
context.stroke();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edgehovers');
/**
* This hover renderer will display the edge with a different color or size.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edgehovers.arrow =
function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
size = edge[prefix + 'size'] || 1,
tSize = target[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'];
size = (edge.hover) ?
settings('edgeHoverSizeRatio') * size : size;
var aSize = size * 2.5,
d = Math.sqrt(Math.pow(tX - sX, 2) + Math.pow(tY - sY, 2)),
aX = sX + (tX - sX) * (d - aSize - tSize) / d,
aY = sY + (tY - sY) * (d - aSize - tSize) / d,
vX = (tX - sX) * aSize / d,
vY = (tY - sY) * aSize / d;
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
if (settings('edgeHoverColor') === 'edge') {
color = edge.hover_color || color;
} else {
color = edge.hover_color || settings('defaultEdgeHoverColor') || color;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
context.lineTo(
aX,
aY
);
context.stroke();
context.fillStyle = color;
context.beginPath();
context.moveTo(aX + vX, aY + vY);
context.lineTo(aX + vY * 0.6, aY - vX * 0.6);
context.lineTo(aX - vY * 0.6, aY + vX * 0.6);
context.lineTo(aX + vX, aY + vY);
context.closePath();
context.fill();
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edgehovers');
/**
* This hover renderer will display the edge with a different color or size.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edgehovers.curvedArrow =
function(edge, source, target, context, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
cp = {},
size = settings('edgeHoverSizeRatio') * (edge[prefix + 'size'] || 1),
tSize = target[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'],
d,
aSize,
aX,
aY,
vX,
vY;
cp = (source.id === target.id) ?
sigma.utils.getSelfLoopControlPoints(sX, sY, tSize) :
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY);
if (source.id === target.id) {
d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2));
aSize = size * 2.5;
aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d;
aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d;
vX = (tX - cp.x1) * aSize / d;
vY = (tY - cp.y1) * aSize / d;
}
else {
d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2));
aSize = size * 2.5;
aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d;
aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d;
vX = (tX - cp.x) * aSize / d;
vY = (tY - cp.y) * aSize / d;
}
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
if (settings('edgeHoverColor') === 'edge') {
color = edge.hover_color || color;
} else {
color = edge.hover_color || settings('defaultEdgeHoverColor') || color;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
if (source.id === target.id) {
context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY);
} else {
context.quadraticCurveTo(cp.x, cp.y, aX, aY);
}
context.stroke();
context.fillStyle = color;
context.beginPath();
context.moveTo(aX + vX, aY + vY);
context.lineTo(aX + vY * 0.6, aY - vX * 0.6);
context.lineTo(aX - vY * 0.6, aY + vX * 0.6);
context.lineTo(aX + vX, aY + vY);
context.closePath();
context.fill();
};
})();
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.canvas.extremities');
/**
* The default renderer for hovered edge extremities. It renders the edge
* extremities as hovered.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.extremities.def =
function(edge, source, target, context, settings) {
// Source Node:
(
sigma.canvas.hovers[source.type] ||
sigma.canvas.hovers.def
) (
source, context, settings
);
// Target Node:
(
sigma.canvas.hovers[target.type] ||
sigma.canvas.hovers.def
) (
target, context, settings
);
};
}).call(this);
;(function() {
'use strict';
sigma.utils.pkg('sigma.svg.utils');
/**
* Some useful functions used by sigma's SVG renderer.
*/
sigma.svg.utils = {
/**
* SVG Element show.
*
* @param {DOMElement} element The DOM element to show.
*/
show: function(element) {
element.style.display = '';
return this;
},
/**
* SVG Element hide.
*
* @param {DOMElement} element The DOM element to hide.
*/
hide: function(element) {
element.style.display = 'none';
return this;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.svg.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*/
sigma.svg.nodes.def = {
/**
* SVG Element creation.
*
* @param {object} node The node object.
* @param {configurable} settings The settings function.
*/
create: function(node, settings) {
var prefix = settings('prefix') || '',
circle = document.createElementNS(settings('xmlns'), 'circle');
// Defining the node's circle
circle.setAttributeNS(null, 'data-node-id', node.id);
circle.setAttributeNS(null, 'class', settings('classPrefix') + '-node');
circle.setAttributeNS(
null, 'fill', node.color || settings('defaultNodeColor'));
// Returning the DOM Element
return circle;
},
/**
* SVG Element update.
*
* @param {object} node The node object.
* @param {DOMElement} circle The node DOM element.
* @param {configurable} settings The settings function.
*/
update: function(node, circle, settings) {
var prefix = settings('prefix') || '';
// Applying changes
// TODO: optimize - check if necessary
circle.setAttributeNS(null, 'cx', node[prefix + 'x']);
circle.setAttributeNS(null, 'cy', node[prefix + 'y']);
circle.setAttributeNS(null, 'r', node[prefix + 'size']);
// Updating only if not freestyle
if (!settings('freeStyle'))
circle.setAttributeNS(
null, 'fill', node.color || settings('defaultNodeColor'));
// Showing
circle.style.display = '';
return this;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.svg.edges');
/**
* The default edge renderer. It renders the node as a simple line.
*/
sigma.svg.edges.def = {
/**
* SVG Element creation.
*
* @param {object} edge The edge object.
* @param {object} source The source node object.
* @param {object} target The target node object.
* @param {configurable} settings The settings function.
*/
create: function(edge, source, target, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor');
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
var line = document.createElementNS(settings('xmlns'), 'line');
// Attributes
line.setAttributeNS(null, 'data-edge-id', edge.id);
line.setAttributeNS(null, 'class', settings('classPrefix') + '-edge');
line.setAttributeNS(null, 'stroke', color);
return line;
},
/**
* SVG Element update.
*
* @param {object} edge The edge object.
* @param {DOMElement} line The line DOM Element.
* @param {object} source The source node object.
* @param {object} target The target node object.
* @param {configurable} settings The settings function.
*/
update: function(edge, line, source, target, settings) {
var prefix = settings('prefix') || '';
line.setAttributeNS(null, 'stroke-width', edge[prefix + 'size'] || 1);
line.setAttributeNS(null, 'x1', source[prefix + 'x']);
line.setAttributeNS(null, 'y1', source[prefix + 'y']);
line.setAttributeNS(null, 'x2', target[prefix + 'x']);
line.setAttributeNS(null, 'y2', target[prefix + 'y']);
// Showing
line.style.display = '';
return this;
}
};
})();
;(function() {
'use strict';
sigma.utils.pkg('sigma.svg.edges');
/**
* The curve edge renderer. It renders the node as a bezier curve.
*/
sigma.svg.edges.curve = {
/**
* SVG Element creation.
*
* @param {object} edge The edge object.
* @param {object} source The source node object.
* @param {object} target The target node object.
* @param {configurable} settings The settings function.
*/
create: function(edge, source, target, settings) {
var color = edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor');
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
var path = document.createElementNS(settings('xmlns'), 'path');
// Attributes
path.setAttributeNS(null, 'data-edge-id', edge.id);
path.setAttributeNS(null, 'class', settings('classPrefix') + '-edge');
path.setAttributeNS(null, 'stroke', color);
return path;
},
/**
* SVG Element update.
*
* @param {object} edge The edge object.
* @param {DOMElement} line The line DOM Element.
* @param {object} source The source node object.
* @param {object} target The target node object.
* @param {configurable} settings The settings function.
*/
update: function(edge, path, source, target, settings) {
var prefix = settings('prefix') || '';
path.setAttributeNS(null, 'stroke-width', edge[prefix + 'size'] || 1);
// Control point
var cx = (source[prefix + 'x'] + target[prefix + 'x']) / 2 +
(target[prefix + 'y'] - source[prefix + 'y']) / 4,
cy = (source[prefix + 'y'] + target[prefix + 'y']) / 2 +
(source[prefix + 'x'] - target[prefix + 'x']) / 4;
// Path
var p = 'M' + source[prefix + 'x'] + ',' + source[prefix + 'y'] + ' ' +
'Q' + cx + ',' + cy + ' ' +
target[prefix + 'x'] + ',' + target[prefix + 'y'];
// Updating attributes
path.setAttributeNS(null, 'd', p);
path.setAttributeNS(null, 'fill', 'none');
// Showing
path.style.display = '';
return this;
}
};
})();
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.svg.labels');
/**
* The default label renderer. It renders the label as a simple text.
*/
sigma.svg.labels.def = {
/**
* SVG Element creation.
*
* @param {object} node The node object.
* @param {configurable} settings The settings function.
*/
create: function(node, settings) {
var prefix = settings('prefix') || '',
size = node[prefix + 'size'],
text = document.createElementNS(settings('xmlns'), 'text');
var fontSize = (settings('labelSize') === 'fixed') ?
settings('defaultLabelSize') :
settings('labelSizeRatio') * size;
var fontColor = (settings('labelColor') === 'node') ?
(node.color || settings('defaultNodeColor')) :
settings('defaultLabelColor');
text.setAttributeNS(null, 'data-label-target', node.id);
text.setAttributeNS(null, 'class', settings('classPrefix') + '-label');
text.setAttributeNS(null, 'font-size', fontSize);
text.setAttributeNS(null, 'font-family', settings('font'));
text.setAttributeNS(null, 'fill', fontColor);
text.innerHTML = node.label;
text.textContent = node.label;
return text;
},
/**
* SVG Element update.
*
* @param {object} node The node object.
* @param {DOMElement} text The label DOM element.
* @param {configurable} settings The settings function.
*/
update: function(node, text, settings) {
var prefix = settings('prefix') || '',
size = node[prefix + 'size'];
var fontSize = (settings('labelSize') === 'fixed') ?
settings('defaultLabelSize') :
settings('labelSizeRatio') * size;
// Case when we don't want to display the label
if (!settings('forceLabels') && size < settings('labelThreshold'))
return;
if (typeof node.label !== 'string')
return;
// Updating
text.setAttributeNS(null, 'x',
Math.round(node[prefix + 'x'] + size + 3));
text.setAttributeNS(null, 'y',
Math.round(node[prefix + 'y'] + fontSize / 3));
// Showing
text.style.display = '';
return this;
}
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.svg.hovers');
/**
* The default hover renderer.
*/
sigma.svg.hovers.def = {
/**
* SVG Element creation.
*
* @param {object} node The node object.
* @param {CanvasElement} measurementCanvas A fake canvas handled by
* the svg to perform some measurements and
* passed by the renderer.
* @param {DOMElement} nodeCircle The node DOM Element.
* @param {configurable} settings The settings function.
*/
create: function(node, nodeCircle, measurementCanvas, settings) {
// Defining visual properties
var x,
y,
w,
h,
e,
d,
fontStyle = settings('hoverFontStyle') || settings('fontStyle'),
prefix = settings('prefix') || '',
size = node[prefix + 'size'],
fontSize = (settings('labelSize') === 'fixed') ?
settings('defaultLabelSize') :
settings('labelSizeRatio') * size,
fontColor = (settings('labelHoverColor') === 'node') ?
(node.color || settings('defaultNodeColor')) :
settings('defaultLabelHoverColor');
// Creating elements
var group = document.createElementNS(settings('xmlns'), 'g'),
rectangle = document.createElementNS(settings('xmlns'), 'rect'),
circle = document.createElementNS(settings('xmlns'), 'circle'),
text = document.createElementNS(settings('xmlns'), 'text');
// Defining properties
group.setAttributeNS(null, 'class', settings('classPrefix') + '-hover');
group.setAttributeNS(null, 'data-node-id', node.id);
if (typeof node.label === 'string') {
// Text
text.innerHTML = node.label;
text.textContent = node.label;
text.setAttributeNS(
null,
'class',
settings('classPrefix') + '-hover-label');
text.setAttributeNS(null, 'font-size', fontSize);
text.setAttributeNS(null, 'font-family', settings('font'));
text.setAttributeNS(null, 'fill', fontColor);
text.setAttributeNS(null, 'x',
Math.round(node[prefix + 'x'] + size + 3));
text.setAttributeNS(null, 'y',
Math.round(node[prefix + 'y'] + fontSize / 3));
// Measures
// OPTIMIZE: Find a better way than a measurement canvas
x = Math.round(node[prefix + 'x'] - fontSize / 2 - 2);
y = Math.round(node[prefix + 'y'] - fontSize / 2 - 2);
w = Math.round(
measurementCanvas.measureText(node.label).width +
fontSize / 2 + size + 9
);
h = Math.round(fontSize + 4);
e = Math.round(fontSize / 2 + 2);
// Circle
circle.setAttributeNS(
null,
'class',
settings('classPrefix') + '-hover-area');
circle.setAttributeNS(null, 'fill', '#fff');
circle.setAttributeNS(null, 'cx', node[prefix + 'x']);
circle.setAttributeNS(null, 'cy', node[prefix + 'y']);
circle.setAttributeNS(null, 'r', e);
// Rectangle
rectangle.setAttributeNS(
null,
'class',
settings('classPrefix') + '-hover-area');
rectangle.setAttributeNS(null, 'fill', '#fff');
rectangle.setAttributeNS(null, 'x', node[prefix + 'x'] + e / 4);
rectangle.setAttributeNS(null, 'y', node[prefix + 'y'] - e);
rectangle.setAttributeNS(null, 'width', w);
rectangle.setAttributeNS(null, 'height', h);
}
// Appending childs
group.appendChild(circle);
group.appendChild(rectangle);
group.appendChild(text);
group.appendChild(nodeCircle);
return group;
}
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.middlewares');
sigma.utils.pkg('sigma.utils');
/**
* This middleware will rescale the graph such that it takes an optimal space
* on the renderer.
*
* As each middleware, this function is executed in the scope of the sigma
* instance.
*
* @param {?string} readPrefix The read prefix.
* @param {?string} writePrefix The write prefix.
* @param {object} options The parameters.
*/
sigma.middlewares.rescale = function(readPrefix, writePrefix, options) {
var i,
l,
a,
b,
c,
d,
scale,
margin,
n = this.graph.nodes(),
e = this.graph.edges(),
settings = this.settings.embedObjects(options || {}),
bounds = settings('bounds') || sigma.utils.getBoundaries(
this.graph,
readPrefix,
true
),
minX = bounds.minX,
minY = bounds.minY,
maxX = bounds.maxX,
maxY = bounds.maxY,
sizeMax = bounds.sizeMax,
weightMax = bounds.weightMax,
w = settings('width') || 1,
h = settings('height') || 1,
rescaleSettings = settings('autoRescale'),
validSettings = {
nodePosition: 1,
nodeSize: 1,
edgeSize: 1
};
/**
* What elements should we rescale?
*/
if (!(rescaleSettings instanceof Array))
rescaleSettings = ['nodePosition', 'nodeSize', 'edgeSize'];
for (i = 0, l = rescaleSettings.length; i < l; i++)
if (!validSettings[rescaleSettings[i]])
throw new Error(
'The rescale setting "' + rescaleSettings[i] + '" is not recognized.'
);
var np = ~rescaleSettings.indexOf('nodePosition'),
ns = ~rescaleSettings.indexOf('nodeSize'),
es = ~rescaleSettings.indexOf('edgeSize');
/**
* First, we compute the scaling ratio, without considering the sizes
* of the nodes : Each node will have its center in the canvas, but might
* be partially out of it.
*/
scale = settings('scalingMode') === 'outside' ?
Math.max(
w / Math.max(maxX - minX, 1),
h / Math.max(maxY - minY, 1)
) :
Math.min(
w / Math.max(maxX - minX, 1),
h / Math.max(maxY - minY, 1)
);
/**
* Then, we correct that scaling ratio considering a margin, which is
* basically the size of the biggest node.
* This has to be done as a correction since to compare the size of the
* biggest node to the X and Y values, we have to first get an
* approximation of the scaling ratio.
**/
margin =
(
settings('rescaleIgnoreSize') ?
0 :
(settings('maxNodeSize') || sizeMax) / scale
) +
(settings('sideMargin') || 0);
maxX += margin;
minX -= margin;
maxY += margin;
minY -= margin;
// Fix the scaling with the new extrema:
scale = settings('scalingMode') === 'outside' ?
Math.max(
w / Math.max(maxX - minX, 1),
h / Math.max(maxY - minY, 1)
) :
Math.min(
w / Math.max(maxX - minX, 1),
h / Math.max(maxY - minY, 1)
);
// Size homothetic parameters:
if (!settings('maxNodeSize') && !settings('minNodeSize')) {
a = 1;
b = 0;
} else if (settings('maxNodeSize') === settings('minNodeSize')) {
a = 0;
b = +settings('maxNodeSize');
} else {
a = (settings('maxNodeSize') - settings('minNodeSize')) / sizeMax;
b = +settings('minNodeSize');
}
if (!settings('maxEdgeSize') && !settings('minEdgeSize')) {
c = 1;
d = 0;
} else if (settings('maxEdgeSize') === settings('minEdgeSize')) {
c = 0;
d = +settings('minEdgeSize');
} else {
c = (settings('maxEdgeSize') - settings('minEdgeSize')) / weightMax;
d = +settings('minEdgeSize');
}
// Rescale the nodes and edges:
for (i = 0, l = e.length; i < l; i++)
e[i][writePrefix + 'size'] =
e[i][readPrefix + 'size'] * (es ? c : 1) + (es ? d : 0);
for (i = 0, l = n.length; i < l; i++) {
n[i][writePrefix + 'size'] =
n[i][readPrefix + 'size'] * (ns ? a : 1) + (ns ? b : 0);
n[i][writePrefix + 'x'] =
(n[i][readPrefix + 'x'] - (maxX + minX) / 2) * (np ? scale : 1);
n[i][writePrefix + 'y'] =
(n[i][readPrefix + 'y'] - (maxY + minY) / 2) * (np ? scale : 1);
}
};
sigma.utils.getBoundaries = function(graph, prefix, doEdges) {
var i,
l,
e = graph.edges(),
n = graph.nodes(),
weightMax = -Infinity,
sizeMax = -Infinity,
minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
if (doEdges)
for (i = 0, l = e.length; i < l; i++)
weightMax = Math.max(e[i][prefix + 'size'], weightMax);
for (i = 0, l = n.length; i < l; i++) {
sizeMax = Math.max(n[i][prefix + 'size'], sizeMax);
maxX = Math.max(n[i][prefix + 'x'], maxX);
minX = Math.min(n[i][prefix + 'x'], minX);
maxY = Math.max(n[i][prefix + 'y'], maxY);
minY = Math.min(n[i][prefix + 'y'], minY);
}
weightMax = weightMax || 1;
sizeMax = sizeMax || 1;
return {
weightMax: weightMax,
sizeMax: sizeMax,
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY
};
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.middlewares');
/**
* This middleware will just copy the graphic properties.
*
* @param {?string} readPrefix The read prefix.
* @param {?string} writePrefix The write prefix.
*/
sigma.middlewares.copy = function(readPrefix, writePrefix) {
var i,
l,
a;
if (writePrefix + '' === readPrefix + '')
return;
a = this.graph.nodes();
for (i = 0, l = a.length; i < l; i++) {
a[i][writePrefix + 'x'] = a[i][readPrefix + 'x'];
a[i][writePrefix + 'y'] = a[i][readPrefix + 'y'];
a[i][writePrefix + 'size'] = a[i][readPrefix + 'size'];
}
a = this.graph.edges();
for (i = 0, l = a.length; i < l; i++)
a[i][writePrefix + 'size'] = a[i][readPrefix + 'size'];
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.misc.animation.running');
/**
* Generates a unique ID for the animation.
*
* @return {string} Returns the new ID.
*/
var _getID = (function() {
var id = 0;
return function() {
return '' + (++id);
};
})();
/**
* This function animates a camera. It has to be called with the camera to
* animate, the values of the coordinates to reach and eventually some
* options. It returns a number id, that you can use to kill the animation,
* with the method sigma.misc.animation.kill(id).
*
* The available options are:
*
* {?number} duration The duration of the animation.
* {?function} onNewFrame A callback to execute when the animation
* enter a new frame.
* {?function} onComplete A callback to execute when the animation
* is completed or killed.
* {?(string|function)} easing The name of a function from the package
* sigma.utils.easings, or a custom easing
* function.
*
* @param {camera} camera The camera to animate.
* @param {object} target The coordinates to reach.
* @param {?object} options Eventually an object to specify some options to
* the function. The available options are
* presented in the description of the function.
* @return {number} The animation id, to make it easy to kill
* through the method "sigma.misc.animation.kill".
*/
sigma.misc.animation.camera = function(camera, val, options) {
if (
!(camera instanceof sigma.classes.camera) ||
typeof val !== 'object' ||
!val
)
throw 'animation.camera: Wrong arguments.';
if (
typeof val.x !== 'number' &&
typeof val.y !== 'number' &&
typeof val.ratio !== 'number' &&
typeof val.angle !== 'number'
)
throw 'There must be at least one valid coordinate in the given val.';
var fn,
id,
anim,
easing,
duration,
initialVal,
o = options || {},
start = sigma.utils.dateNow();
// Store initial values:
initialVal = {
x: camera.x,
y: camera.y,
ratio: camera.ratio,
angle: camera.angle
};
duration = o.duration;
easing = typeof o.easing !== 'function' ?
sigma.utils.easings[o.easing || 'quadraticInOut'] :
o.easing;
fn = function() {
var coef,
t = o.duration ? (sigma.utils.dateNow() - start) / o.duration : 1;
// If the animation is over:
if (t >= 1) {
camera.isAnimated = false;
camera.goTo({
x: val.x !== undefined ? val.x : initialVal.x,
y: val.y !== undefined ? val.y : initialVal.y,
ratio: val.ratio !== undefined ? val.ratio : initialVal.ratio,
angle: val.angle !== undefined ? val.angle : initialVal.angle
});
cancelAnimationFrame(id);
delete sigma.misc.animation.running[id];
// Check callbacks:
if (typeof o.onComplete === 'function')
o.onComplete();
// Else, let's keep going:
} else {
coef = easing(t);
camera.isAnimated = true;
camera.goTo({
x: val.x !== undefined ?
initialVal.x + (val.x - initialVal.x) * coef :
initialVal.x,
y: val.y !== undefined ?
initialVal.y + (val.y - initialVal.y) * coef :
initialVal.y,
ratio: val.ratio !== undefined ?
initialVal.ratio + (val.ratio - initialVal.ratio) * coef :
initialVal.ratio,
angle: val.angle !== undefined ?
initialVal.angle + (val.angle - initialVal.angle) * coef :
initialVal.angle
});
// Check callbacks:
if (typeof o.onNewFrame === 'function')
o.onNewFrame();
anim.frameId = requestAnimationFrame(fn);
}
};
id = _getID();
anim = {
frameId: requestAnimationFrame(fn),
target: camera,
type: 'camera',
options: o,
fn: fn
};
sigma.misc.animation.running[id] = anim;
return id;
};
/**
* Kills a running animation. It triggers the eventual onComplete callback.
*
* @param {number} id The id of the animation to kill.
* @return {object} Returns the sigma.misc.animation package.
*/
sigma.misc.animation.kill = function(id) {
if (arguments.length !== 1 || typeof id !== 'number')
throw 'animation.kill: Wrong arguments.';
var o = sigma.misc.animation.running[id];
if (o) {
cancelAnimationFrame(id);
delete sigma.misc.animation.running[o.frameId];
if (o.type === 'camera')
o.target.isAnimated = false;
// Check callbacks:
if (typeof (o.options || {}).onComplete === 'function')
o.options.onComplete();
}
return this;
};
/**
* Kills every running animations, or only the one with the specified type,
* if a string parameter is given.
*
* @param {?(string|object)} filter A string to filter the animations to kill
* on their type (example: "camera"), or an
* object to filter on their target.
* @return {number} Returns the number of animations killed
* that way.
*/
sigma.misc.animation.killAll = function(filter) {
var o,
id,
count = 0,
type = typeof filter === 'string' ? filter : null,
target = typeof filter === 'object' ? filter : null,
running = sigma.misc.animation.running;
for (id in running)
if (
(!type || running[id].type === type) &&
(!target || running[id].target === target)
) {
o = sigma.misc.animation.running[id];
cancelAnimationFrame(o.frameId);
delete sigma.misc.animation.running[id];
if (o.type === 'camera')
o.target.isAnimated = false;
// Increment counter:
count++;
// Check callbacks:
if (typeof (o.options || {}).onComplete === 'function')
o.options.onComplete();
}
return count;
};
/**
* Returns "true" if any animation that is currently still running matches
* the filter given to the function.
*
* @param {string|object} filter A string to filter the animations to kill
* on their type (example: "camera"), or an
* object to filter on their target.
* @return {boolean} Returns true if any running animation
* matches.
*/
sigma.misc.animation.has = function(filter) {
var id,
type = typeof filter === 'string' ? filter : null,
target = typeof filter === 'object' ? filter : null,
running = sigma.misc.animation.running;
for (id in running)
if (
(!type || running[id].type === type) &&
(!target || running[id].target === target)
)
return true;
return false;
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.misc');
/**
* This helper will bind any no-DOM renderer (for instance canvas or WebGL)
* to its captors, to properly dispatch the good events to the sigma instance
* to manage clicking, hovering etc...
*
* It has to be called in the scope of the related renderer.
*/
sigma.misc.bindEvents = function(prefix) {
var i,
l,
mX,
mY,
captor,
self = this;
function getNodes(e) {
if (e) {
mX = 'x' in e.data ? e.data.x : mX;
mY = 'y' in e.data ? e.data.y : mY;
}
var i,
j,
l,
n,
x,
y,
s,
inserted,
selected = [],
modifiedX = mX + self.width / 2,
modifiedY = mY + self.height / 2,
point = self.camera.cameraPosition(
mX,
mY
),
nodes = self.camera.quadtree.point(
point.x,
point.y
);
if (nodes.length)
for (i = 0, l = nodes.length; i < l; i++) {
n = nodes[i];
x = n[prefix + 'x'];
y = n[prefix + 'y'];
s = n[prefix + 'size'];
if (
!n.hidden &&
modifiedX > x - s &&
modifiedX < x + s &&
modifiedY > y - s &&
modifiedY < y + s &&
Math.sqrt(
Math.pow(modifiedX - x, 2) +
Math.pow(modifiedY - y, 2)
) < s
) {
// Insert the node:
inserted = false;
for (j = 0; j < selected.length; j++)
if (n.size > selected[j].size) {
selected.splice(j, 0, n);
inserted = true;
break;
}
if (!inserted)
selected.push(n);
}
}
return selected;
}
function getEdges(e) {
if (!self.settings('enableEdgeHovering')) {
// No event if the setting is off:
return [];
}
var isCanvas = (
sigma.renderers.canvas && self instanceof sigma.renderers.canvas);
if (!isCanvas) {
// A quick hardcoded rule to prevent people from using this feature
// with the WebGL renderer (which is not good enough at the moment):
throw new Error(
'The edge events feature is not compatible with the WebGL renderer'
);
}
if (e) {
mX = 'x' in e.data ? e.data.x : mX;
mY = 'y' in e.data ? e.data.y : mY;
}
var i,
j,
l,
a,
edge,
s,
maxEpsilon = self.settings('edgeHoverPrecision'),
source,
target,
cp,
nodeIndex = {},
inserted,
selected = [],
modifiedX = mX + self.width / 2,
modifiedY = mY + self.height / 2,
point = self.camera.cameraPosition(
mX,
mY
),
edges = [];
if (isCanvas) {
var nodesOnScreen = self.camera.quadtree.area(
self.camera.getRectangle(self.width, self.height)
);
for (a = nodesOnScreen, i = 0, l = a.length; i < l; i++)
nodeIndex[a[i].id] = a[i];
}
if (self.camera.edgequadtree !== undefined) {
edges = self.camera.edgequadtree.point(
point.x,
point.y
);
}
function insertEdge(selected, edge) {
inserted = false;
for (j = 0; j < selected.length; j++)
if (edge.size > selected[j].size) {
selected.splice(j, 0, edge);
inserted = true;
break;
}
if (!inserted)
selected.push(edge);
}
if (edges.length)
for (i = 0, l = edges.length; i < l; i++) {
edge = edges[i];
source = self.graph.nodes(edge.source);
target = self.graph.nodes(edge.target);
// (HACK) we can't get edge[prefix + 'size'] on WebGL renderer:
s = edge[prefix + 'size'] ||
edge['read_' + prefix + 'size'];
// First, let's identify which edges are drawn. To do this, we keep
// every edges that have at least one extremity displayed according to
// the quadtree and the "hidden" attribute. We also do not keep hidden
// edges.
// Then, let's check if the mouse is on the edge (we suppose that it
// is a line segment).
if (
!edge.hidden &&
!source.hidden && !target.hidden &&
(!isCanvas ||
(nodeIndex[edge.source] || nodeIndex[edge.target])) &&
sigma.utils.getDistance(
source[prefix + 'x'],
source[prefix + 'y'],
modifiedX,
modifiedY) > source[prefix + 'size'] &&
sigma.utils.getDistance(
target[prefix + 'x'],
target[prefix + 'y'],
modifiedX,
modifiedY) > target[prefix + 'size']
) {
if (edge.type == 'curve' || edge.type == 'curvedArrow') {
if (source.id === target.id) {
cp = sigma.utils.getSelfLoopControlPoints(
source[prefix + 'x'],
source[prefix + 'y'],
source[prefix + 'size']
);
if (
sigma.utils.isPointOnBezierCurve(
modifiedX,
modifiedY,
source[prefix + 'x'],
source[prefix + 'y'],
target[prefix + 'x'],
target[prefix + 'y'],
cp.x1,
cp.y1,
cp.x2,
cp.y2,
Math.max(s, maxEpsilon)
)) {
insertEdge(selected, edge);
}
}
else {
cp = sigma.utils.getQuadraticControlPoint(
source[prefix + 'x'],
source[prefix + 'y'],
target[prefix + 'x'],
target[prefix + 'y']);
if (
sigma.utils.isPointOnQuadraticCurve(
modifiedX,
modifiedY,
source[prefix + 'x'],
source[prefix + 'y'],
target[prefix + 'x'],
target[prefix + 'y'],
cp.x,
cp.y,
Math.max(s, maxEpsilon)
)) {
insertEdge(selected, edge);
}
}
} else if (
sigma.utils.isPointOnSegment(
modifiedX,
modifiedY,
source[prefix + 'x'],
source[prefix + 'y'],
target[prefix + 'x'],
target[prefix + 'y'],
Math.max(s, maxEpsilon)
)) {
insertEdge(selected, edge);
}
}
}
return selected;
}
function bindCaptor(captor) {
var nodes,
edges,
overNodes = {},
overEdges = {};
function onClick(e) {
if (!self.settings('eventsEnabled'))
return;
self.dispatchEvent('click', e.data);
nodes = getNodes(e);
edges = getEdges(e);
if (nodes.length) {
self.dispatchEvent('clickNode', {
node: nodes[0],
captor: e.data
});
self.dispatchEvent('clickNodes', {
node: nodes,
captor: e.data
});
} else if (edges.length) {
self.dispatchEvent('clickEdge', {
edge: edges[0],
captor: e.data
});
self.dispatchEvent('clickEdges', {
edge: edges,
captor: e.data
});
} else
self.dispatchEvent('clickStage', {captor: e.data});
}
function onDoubleClick(e) {
if (!self.settings('eventsEnabled'))
return;
self.dispatchEvent('doubleClick', e.data);
nodes = getNodes(e);
edges = getEdges(e);
if (nodes.length) {
self.dispatchEvent('doubleClickNode', {
node: nodes[0],
captor: e.data
});
self.dispatchEvent('doubleClickNodes', {
node: nodes,
captor: e.data
});
} else if (edges.length) {
self.dispatchEvent('doubleClickEdge', {
edge: edges[0],
captor: e.data
});
self.dispatchEvent('doubleClickEdges', {
edge: edges,
captor: e.data
});
} else
self.dispatchEvent('doubleClickStage', {captor: e.data});
}
function onRightClick(e) {
if (!self.settings('eventsEnabled'))
return;
self.dispatchEvent('rightClick', e.data);
nodes = getNodes(e);
edges = getEdges(e);
if (nodes.length) {
self.dispatchEvent('rightClickNode', {
node: nodes[0],
captor: e.data
});
self.dispatchEvent('rightClickNodes', {
node: nodes,
captor: e.data
});
} else if (edges.length) {
self.dispatchEvent('rightClickEdge', {
edge: edges[0],
captor: e.data
});
self.dispatchEvent('rightClickEdges', {
edge: edges,
captor: e.data
});
} else
self.dispatchEvent('rightClickStage', {captor: e.data});
}
function onOut(e) {
if (!self.settings('eventsEnabled'))
return;
var k,
i,
l,
le,
outNodes = [],
outEdges = [];
for (k in overNodes)
outNodes.push(overNodes[k]);
overNodes = {};
// Dispatch both single and multi events:
for (i = 0, l = outNodes.length; i < l; i++)
self.dispatchEvent('outNode', {
node: outNodes[i],
captor: e.data
});
if (outNodes.length)
self.dispatchEvent('outNodes', {
nodes: outNodes,
captor: e.data
});
overEdges = {};
// Dispatch both single and multi events:
for (i = 0, le = outEdges.length; i < le; i++)
self.dispatchEvent('outEdge', {
edge: outEdges[i],
captor: e.data
});
if (outEdges.length)
self.dispatchEvent('outEdges', {
edges: outEdges,
captor: e.data
});
}
function onMove(e) {
if (!self.settings('eventsEnabled'))
return;
nodes = getNodes(e);
edges = getEdges(e);
var i,
k,
node,
edge,
newOutNodes = [],
newOverNodes = [],
currentOverNodes = {},
l = nodes.length,
newOutEdges = [],
newOverEdges = [],
currentOverEdges = {},
le = edges.length;
// Check newly overred nodes:
for (i = 0; i < l; i++) {
node = nodes[i];
currentOverNodes[node.id] = node;
if (!overNodes[node.id]) {
newOverNodes.push(node);
overNodes[node.id] = node;
}
}
// Check no more overred nodes:
for (k in overNodes)
if (!currentOverNodes[k]) {
newOutNodes.push(overNodes[k]);
delete overNodes[k];
}
// Dispatch both single and multi events:
for (i = 0, l = newOverNodes.length; i < l; i++)
self.dispatchEvent('overNode', {
node: newOverNodes[i],
captor: e.data
});
for (i = 0, l = newOutNodes.length; i < l; i++)
self.dispatchEvent('outNode', {
node: newOutNodes[i],
captor: e.data
});
if (newOverNodes.length)
self.dispatchEvent('overNodes', {
nodes: newOverNodes,
captor: e.data
});
if (newOutNodes.length)
self.dispatchEvent('outNodes', {
nodes: newOutNodes,
captor: e.data
});
// Check newly overred edges:
for (i = 0; i < le; i++) {
edge = edges[i];
currentOverEdges[edge.id] = edge;
if (!overEdges[edge.id]) {
newOverEdges.push(edge);
overEdges[edge.id] = edge;
}
}
// Check no more overred edges:
for (k in overEdges)
if (!currentOverEdges[k]) {
newOutEdges.push(overEdges[k]);
delete overEdges[k];
}
// Dispatch both single and multi events:
for (i = 0, le = newOverEdges.length; i < le; i++)
self.dispatchEvent('overEdge', {
edge: newOverEdges[i],
captor: e.data
});
for (i = 0, le = newOutEdges.length; i < le; i++)
self.dispatchEvent('outEdge', {
edge: newOutEdges[i],
captor: e.data
});
if (newOverEdges.length)
self.dispatchEvent('overEdges', {
edges: newOverEdges,
captor: e.data
});
if (newOutEdges.length)
self.dispatchEvent('outEdges', {
edges: newOutEdges,
captor: e.data
});
}
// Bind events:
captor.bind('click', onClick);
captor.bind('mousedown', onMove);
captor.bind('mouseup', onMove);
captor.bind('mousemove', onMove);
captor.bind('mouseout', onOut);
captor.bind('doubleclick', onDoubleClick);
captor.bind('rightclick', onRightClick);
self.bind('render', onMove);
}
for (i = 0, l = this.captors.length; i < l; i++)
bindCaptor(this.captors[i]);
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.misc');
/**
* This helper will bind any DOM renderer (for instance svg)
* to its captors, to properly dispatch the good events to the sigma instance
* to manage clicking, hovering etc...
*
* It has to be called in the scope of the related renderer.
*/
sigma.misc.bindDOMEvents = function(container) {
var self = this,
graph = this.graph;
// DOMElement abstraction
function Element(domElement) {
// Helpers
this.attr = function(attrName) {
return domElement.getAttributeNS(null, attrName);
};
// Properties
this.tag = domElement.tagName;
this.class = this.attr('class');
this.id = this.attr('id');
// Methods
this.isNode = function() {
return !!~this.class.indexOf(self.settings('classPrefix') + '-node');
};
this.isEdge = function() {
return !!~this.class.indexOf(self.settings('classPrefix') + '-edge');
};
this.isHover = function() {
return !!~this.class.indexOf(self.settings('classPrefix') + '-hover');
};
}
// Click
function click(e) {
if (!self.settings('eventsEnabled'))
return;
// Generic event
self.dispatchEvent('click', e);
// Are we on a node?
var element = new Element(e.target);
if (element.isNode())
self.dispatchEvent('clickNode', {
node: graph.nodes(element.attr('data-node-id'))
});
else
self.dispatchEvent('clickStage');
e.preventDefault();
e.stopPropagation();
}
// Double click
function doubleClick(e) {
if (!self.settings('eventsEnabled'))
return;
// Generic event
self.dispatchEvent('doubleClick', e);
// Are we on a node?
var element = new Element(e.target);
if (element.isNode())
self.dispatchEvent('doubleClickNode', {
node: graph.nodes(element.attr('data-node-id'))
});
else
self.dispatchEvent('doubleClickStage');
e.preventDefault();
e.stopPropagation();
}
// On over
function onOver(e) {
var target = e.toElement || e.target;
if (!self.settings('eventsEnabled') || !target)
return;
var el = new Element(target);
if (el.isNode()) {
self.dispatchEvent('overNode', {
node: graph.nodes(el.attr('data-node-id'))
});
}
else if (el.isEdge()) {
var edge = graph.edges(el.attr('data-edge-id'));
self.dispatchEvent('overEdge', {
edge: edge,
source: graph.nodes(edge.source),
target: graph.nodes(edge.target)
});
}
}
// On out
function onOut(e) {
var target = e.fromElement || e.originalTarget;
if (!self.settings('eventsEnabled'))
return;
var el = new Element(target);
if (el.isNode()) {
self.dispatchEvent('outNode', {
node: graph.nodes(el.attr('data-node-id'))
});
}
else if (el.isEdge()) {
var edge = graph.edges(el.attr('data-edge-id'));
self.dispatchEvent('outEdge', {
edge: edge,
source: graph.nodes(edge.source),
target: graph.nodes(edge.target)
});
}
}
// Registering Events:
// Click
container.addEventListener('click', click, false);
sigma.utils.doubleClick(container, 'click', doubleClick);
// Touch counterparts
container.addEventListener('touchstart', click, false);
sigma.utils.doubleClick(container, 'touchstart', doubleClick);
// Mouseover
container.addEventListener('mouseover', onOver, true);
// Mouseout
container.addEventListener('mouseout', onOut, true);
};
}).call(this);
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.misc');
/**
* This method listens to "overNode", "outNode", "overEdge" and "outEdge"
* events from a renderer and renders the nodes differently on the top layer.
* The goal is to make any node label readable with the mouse, and to
* highlight hovered nodes and edges.
*
* It has to be called in the scope of the related renderer.
*/
sigma.misc.drawHovers = function(prefix) {
var self = this,
hoveredNodes = {},
hoveredEdges = {};
this.bind('overNode', function(event) {
var node = event.data.node;
if (!node.hidden) {
hoveredNodes[node.id] = node;
draw();
}
});
this.bind('outNode', function(event) {
delete hoveredNodes[event.data.node.id];
draw();
});
this.bind('overEdge', function(event) {
var edge = event.data.edge;
if (!edge.hidden) {
hoveredEdges[edge.id] = edge;
draw();
}
});
this.bind('outEdge', function(event) {
delete hoveredEdges[event.data.edge.id];
draw();
});
this.bind('render', function(event) {
draw();
});
function draw() {
// Clear self.contexts.hover:
self.contexts.hover.canvas.width = self.contexts.hover.canvas.width;
var k,
source,
target,
hoveredNode,
hoveredEdge,
defaultNodeType = self.settings('defaultNodeType'),
defaultEdgeType = self.settings('defaultEdgeType'),
nodeRenderers = sigma.canvas.hovers,
edgeRenderers = sigma.canvas.edgehovers,
extremitiesRenderers = sigma.canvas.extremities,
embedSettings = self.settings.embedObjects({
prefix: prefix
});
// Node render: single hover
if (
embedSettings('enableHovering') &&
embedSettings('singleHover') &&
Object.keys(hoveredNodes).length
) {
hoveredNode = hoveredNodes[Object.keys(hoveredNodes)[0]];
(
nodeRenderers[hoveredNode.type] ||
nodeRenderers[defaultNodeType] ||
nodeRenderers.def
)(
hoveredNode,
self.contexts.hover,
embedSettings
);
}
// Node render: multiple hover
if (
embedSettings('enableHovering') &&
!embedSettings('singleHover')
)
for (k in hoveredNodes)
(
nodeRenderers[hoveredNodes[k].type] ||
nodeRenderers[defaultNodeType] ||
nodeRenderers.def
)(
hoveredNodes[k],
self.contexts.hover,
embedSettings
);
// Edge render: single hover
if (
embedSettings('enableEdgeHovering') &&
embedSettings('singleHover') &&
Object.keys(hoveredEdges).length
) {
hoveredEdge = hoveredEdges[Object.keys(hoveredEdges)[0]];
source = self.graph.nodes(hoveredEdge.source);
target = self.graph.nodes(hoveredEdge.target);
if (! hoveredEdge.hidden) {
(
edgeRenderers[hoveredEdge.type] ||
edgeRenderers[defaultEdgeType] ||
edgeRenderers.def
) (
hoveredEdge,
source,
target,
self.contexts.hover,
embedSettings
);
if (embedSettings('edgeHoverExtremities')) {
(
extremitiesRenderers[hoveredEdge.type] ||
extremitiesRenderers.def
)(
hoveredEdge,
source,
target,
self.contexts.hover,
embedSettings
);
} else {
// Avoid edges rendered over nodes:
(
sigma.canvas.nodes[source.type] ||
sigma.canvas.nodes.def
) (
source,
self.contexts.hover,
embedSettings
);
(
sigma.canvas.nodes[target.type] ||
sigma.canvas.nodes.def
) (
target,
self.contexts.hover,
embedSettings
);
}
}
}
// Edge render: multiple hover
if (
embedSettings('enableEdgeHovering') &&
!embedSettings('singleHover')
) {
for (k in hoveredEdges) {
hoveredEdge = hoveredEdges[k];
source = self.graph.nodes(hoveredEdge.source);
target = self.graph.nodes(hoveredEdge.target);
if (!hoveredEdge.hidden) {
(
edgeRenderers[hoveredEdge.type] ||
edgeRenderers[defaultEdgeType] ||
edgeRenderers.def
) (
hoveredEdge,
source,
target,
self.contexts.hover,
embedSettings
);
if (embedSettings('edgeHoverExtremities')) {
(
extremitiesRenderers[hoveredEdge.type] ||
extremitiesRenderers.def
)(
hoveredEdge,
source,
target,
self.contexts.hover,
embedSettings
);
} else {
// Avoid edges rendered over nodes:
(
sigma.canvas.nodes[source.type] ||
sigma.canvas.nodes.def
) (
source,
self.contexts.hover,
embedSettings
);
(
sigma.canvas.nodes[target.type] ||
sigma.canvas.nodes.def
) (
target,
self.contexts.hover,
embedSettings
);
}
}
}
}
}
};
}).call(this);
| overleaf/web/frontend/js/vendor/libs/sigma-master/sigma.require.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/sigma-master/sigma.require.js",
"repo_id": "overleaf",
"token_count": 163320
} | 544 |
import Icon from '../js/shared/components/icon'
export const Type = args => {
return (
<>
<Icon {...args} />
<div>
<a
href="https://fontawesome.com/v4.7.0/icons/"
target="_blank"
rel="noopener"
>
Font Awesome icons
</a>
</div>
</>
)
}
Type.args = {
type: 'tasks',
}
export const Spinner = args => {
return <Icon {...args} />
}
Spinner.args = {
type: 'spinner',
spin: true,
}
export const FixedWidth = args => {
return <Icon {...args} />
}
FixedWidth.args = {
type: 'tasks',
modifier: 'fw',
}
export const AccessibilityLabel = args => {
return <Icon {...args} />
}
AccessibilityLabel.args = {
type: 'check',
accessibilityLabel: 'Check',
}
export default {
title: 'Icon',
component: Icon,
}
| overleaf/web/frontend/stories/icon.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/icon.stories.js",
"repo_id": "overleaf",
"token_count": 354
} | 545 |
import { ContextRoot } from '../../js/shared/context/root-context'
// Unfortunately, we cannot currently use decorators here, since we need to
// set a value on window, before the contexts are rendered.
// When using decorators, the contexts are rendered before the story, so we
// don't have the opportunity to set the window value first.
export function withContextRoot(Story, scope) {
const ide = {
...window._ide,
$scope: {
...window._ide.$scope,
...scope,
},
}
return (
<ContextRoot ide={ide} settings={{}}>
{Story}
</ContextRoot>
)
}
| overleaf/web/frontend/stories/utils/with-context-root.js/0 | {
"file_path": "overleaf/web/frontend/stories/utils/with-context-root.js",
"repo_id": "overleaf",
"token_count": 189
} | 546 |
/*
Styling for content pages
Including: about, home, blog, /for/__, legal, contact, portals, wiki
*/
.content-page {
word-break: break-word;
/*
Links and Buttons
*/
a {
color: @link-color-alt;
&:hover {
color: @link-hover-color-alt;
}
}
// correct color property set on <a> above:
.reset-btns;
.alert {
.alert;
}
.alert-info {
.btn-info {
.btn-alert-info;
}
}
hr {
border-color: @hr-border-alt;
}
.quote-by {
min-width: 80px;
overflow: hidden;
}
.page-header {
margin-top: 0;
}
/*
section
*/
section {
padding: @line-height-computed (@grid-gutter-width / 2);
&.color-block {
&.green-dark {
background-color: @ol-dark-green;
}
&.green {
background-color: @ol-green;
.no-card * {
.btn-primary,
.btn-success {
// only correct button colors when green on green
.btn-primary-on-primary-bg;
}
}
}
&.blue-gray-dark {
background-color: @ol-blue-gray-5;
}
&.blue-gray-light {
background-color: @ol-blue-gray-1;
}
&.green,
&.green-dark,
&.blue-gray-dark {
.no-card * {
color: @white;
a {
text-decoration: underline;
}
.btn {
text-decoration: none;
}
.form-control {
color: @input-color;
}
}
}
}
.section-row {
margin: 0 auto;
/* match .col-sm-10 */
/* @grid-gutter-width is used for margins */
max-width: (@screen-sm * (10/12)) - @grid-gutter-width;
@media (min-width: @screen-md-min) {
max-width: (@screen-md * (10/12)) - @grid-gutter-width;
}
@media (min-width: @screen-lg-min) {
max-width: (@screen-lg * (10/12)) - @grid-gutter-width;
}
}
}
.content-container > section:first-child {
/* header */
padding-bottom: 0;
padding-top: 0;
}
.content-container > section:nth-child(2) {
/* first content section */
padding-top: 0;
}
section.no-top-padding {
/* opt out of padding via the CMS */
padding-top: 0;
}
.container-small {
section .section-row {
/* match col-sm-8 */
/* @grid-gutter-width is used for margins */
max-width: (@screen-sm * (8/12)) - @grid-gutter-width;
@media (min-width: @screen-md-min) {
max-width: (@screen-md * (8/12)) - @grid-gutter-width;
}
@media (min-width: @screen-lg-min) {
max-width: (@screen-lg * (8/12)) - @grid-gutter-width;
}
}
}
/*
lists
*/
.list-without-style {
list-style: none;
margin: 0;
padding: 0;
}
}
| overleaf/web/frontend/stylesheets/app/content_page.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/content_page.less",
"repo_id": "overleaf",
"token_count": 1375
} | 547 |
@rt-font-family-serif: 'Palatino Linotype', 'Book Antiqua', Palatino, serif;
@rt-line-padding: 8%;
.rich-text .CodeMirror {
font-family: @rt-font-family-serif;
font-size: 1.15em;
pre {
font-family: @rt-font-family-serif;
}
.CodeMirror-line {
// Add horizontal padding, to emulate a manuscript more closely
padding: 0 @rt-line-padding;
}
.CodeMirror-linenumber {
font-size: 0.8em;
}
// TODO: Change prefix away from wl- ?
/****************************************************************************/
.preamble h1 {
text-align: center;
font-size: 2em;
color: @text-color;
}
.preamble ul.authors {
margin-left: 0;
padding-left: 0;
list-style: none;
text-align: center;
}
.preamble ul.authors li {
padding-bottom: 5px;
}
/****************************************************************************/
// wl-indent-X is used to add extra left padding to nested itemize/enumerate
// environments, so that the inner list appears more indented than the outer
.wl-indent-0 {
padding-left: calc(~'2.5em + @{rt-line-padding}') !important;
}
.wl-indent-1 {
padding-left: calc(~'3.5em + @{rt-line-padding}') !important;
}
.wl-indent-2 {
padding-left: calc(~'4.5em + @{rt-line-padding}') !important;
}
.wl-indent-3 {
padding-left: calc(~'5.5em + @{rt-line-padding}') !important;
}
.wl-indent-4 {
padding-left: calc(~'6.5em + @{rt-line-padding}') !important;
}
// wl-indent-env-X is used to add extra left padding to empty nested itemize/
// enumerate environments
.wl-indent-env-0 {
padding-left: calc(~'4px + @{rt-line-padding}') !important;
}
.wl-indent-env-1 {
padding-left: calc(~'1.5em + @{rt-line-padding}') !important;
}
.wl-indent-env-2 {
padding-left: calc(~'2.5em + @{rt-line-padding}') !important;
}
.wl-indent-env-3 {
padding-left: calc(~'3.5em + @{rt-line-padding}') !important;
}
.wl-indent-env-4 {
padding-left: calc(~'4.5em + @{rt-line-padding}') !important;
}
.wl-enumerate-item-open {
text-align: right;
width: 1.5em;
display: inline-block;
padding-right: 0.2em;
}
.wl-item-open {
text-align: right;
width: 1.5em;
display: inline-block;
padding-right: 0.2em;
}
.wl-input {
font-style: oblique;
}
/****************************************************************************/
.wl-abstract-open,
.wl-abstract-close {
border-top: 1px solid #999;
font-size: large;
font-weight: bold;
width: 100%;
}
.wl-figure {
max-height: 120px;
width: auto;
margin: 0 auto;
}
.wl-figure-wrap {
padding: 10px 0;
background-color: #f5f5f5;
box-shadow: 1.3px 2px 2px #dfdfdf;
width: 96%;
margin: 0 auto;
text-align: center;
}
.wl-figure-caption {
padding: 3px 0 4px;
font-size: small;
margin: 0 auto;
text-align: center;
}
/****************************************************************************/
.wl-chapter,
.wl-chapter-open,
.wl-chapter-close {
font-size: 2.2em;
font-weight: bold;
}
.wl-chapter-open,
.wl-chapter-close {
color: #999;
}
/****************************************************************************/
.wl-section,
.wl-section-open,
.wl-section-close {
font-size: 1.8em;
font-weight: bold;
}
.wl-section-open,
.wl-section-close {
color: #999;
}
/****************************************************************************/
.wl-subsection,
.wl-subsection-open,
.wl-subsection-close {
font-size: 1.5em;
font-weight: bold;
}
.wl-subsection-open,
.wl-subsection-close {
color: #999;
}
/****************************************************************************/
.wl-subsubsection,
.wl-subsubsection-open,
.wl-subsubsection-close {
font-size: 1.1em;
font-weight: bold;
}
.wl-subsubsection-open,
.wl-subsubsection-close {
color: #999;
}
/****************************************************************************/
.wl-textbf {
font-weight: bold;
}
.wl-textbf-open {
font-weight: bold;
color: #999;
}
.wl-textbf-close {
font-weight: bold;
color: #999;
}
.wl-label-bracket {
font-weight: bold;
color: #999;
}
.wl-label-open,
.wl-input-link {
.wl-icon {
padding-left: 5px;
padding-right: 2px;
vertical-align: middle;
// @include wl-icon-size(inherit);
}
}
.wl-img-default {
width: 0.9em;
padding: 0 1px 1px;
}
.wl-label-close {
background-color: #f7f7f9;
border: 1px solid #e1e1e8;
border-radius: 4px;
font-size: small;
}
/****************************************************************************/
.wl-textit {
font-style: italic;
}
.wl-textit-open {
font-style: italic;
color: #999;
}
.wl-textit-close {
font-style: italic;
color: #999;
}
.spelling-error {
background-image: url(/img/spellcheck-underline.png);
background-repeat: repeat-x;
background-position: bottom;
}
}
| overleaf/web/frontend/stylesheets/app/editor/rich-text.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/editor/rich-text.less",
"repo_id": "overleaf",
"token_count": 2045
} | 548 |
.renderColorSwatchClasses(@colorName) {
@colorVal: @@colorName;
@colorValRed: red(@colorVal);
@colorValGreen: green(@colorVal);
@colorValBlue: blue(@colorVal);
@colorValAsRGB: 'rgb(@{colorValRed}, @{colorValGreen}, @{colorValBlue})';
&.@{colorName} {
.color-swatch {
background-color: @colorVal;
}
.color-less-var::before {
content: '@@{colorName}';
}
.color-hex-val::before {
content: '@{colorVal}';
}
.color-rgb-val::before {
font-size: 10px;
content: '@{colorValAsRGB}';
}
}
}
.color-row {
display: flex;
justify-content: space-between;
}
.color-box {
background: white;
margin: 10px 4px;
border-radius: 4px;
width: 16.666%;
.renderColorSwatchClasses(ol-blue-gray-1);
.renderColorSwatchClasses(ol-blue-gray-2);
.renderColorSwatchClasses(ol-blue-gray-3);
.renderColorSwatchClasses(ol-blue-gray-4);
.renderColorSwatchClasses(ol-blue-gray-5);
.renderColorSwatchClasses(ol-blue-gray-6);
.renderColorSwatchClasses(ol-green);
.renderColorSwatchClasses(ol-dark-green);
.renderColorSwatchClasses(ol-blue);
.renderColorSwatchClasses(ol-dark-blue);
.renderColorSwatchClasses(ol-red);
.renderColorSwatchClasses(ol-dark-red);
}
.color-swatch {
height: 100px;
width: 100px;
margin: 10px auto;
border-radius: 4px;
}
.color-label {
display: flex;
flex-direction: column;
margin: 0 3px 10px;
}
.color-label pre {
font-size: 12px;
line-height: 1.8em;
margin: 0 auto;
}
| overleaf/web/frontend/stylesheets/app/ol-style-guide.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/ol-style-guide.less",
"repo_id": "overleaf",
"token_count": 628
} | 549 |
.wiki {
.contents {
ul {
padding: 0;
li {
font-size: 14px;
list-style: none;
margin-bottom: 6px;
}
}
h2 {
font-size: 18px;
}
}
.page-header {
a {
font-size: 0.8em;
line-height: 1;
}
}
.editsection {
display: none;
}
.toctogglespan {
display: none;
}
.toc {
ul {
list-style: none;
.tocnumber::after {
content: '.';
}
}
}
table {
th,
td {
padding: (@line-height-computed / 4) (@line-height-computed / 2);
border-bottom: 1px solid @gray-lighter;
}
th {
font-weight: 700;
text-align: left;
font-family: @font-family-serif;
}
margin-bottom: @line-height-computed / 2;
}
.table-no-borders {
th,
td {
border: 0px;
}
}
.example {
max-width: 100%;
.code {
pre {
background-color: @gray-lightest;
border-radius: 6px;
padding: (@line-height-computed / 2);
white-space: pre-wrap;
margin: 0;
}
}
.output {
text-align: center;
padding-top: 10px;
img {
width: auto;
height: auto;
max-width: 100%;
box-shadow: 0 1px 3px @gray-light;
border-radius: 6px;
}
}
}
@media (min-width: 1360px) {
.example {
margin-right: -200px;
}
}
@media (max-width: @screen-sm) {
.contents {
margin-top: @margin-lg;
}
}
/*<![CDATA[*/
.source-latex {
line-height: normal;
}
.source-latex li,
.source-latex pre {
line-height: normal;
border: 0px none white;
}
/**
* GeSHi Dynamically Generated Stylesheet
* --------------------------------------
* Dynamically generated stylesheet for latex
* CSS class: source-latex, CSS id:
* GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
* (http://qbnz.com/highlighter/ and http://geshi.org/)
* --------------------------------------
*/
.latex.source-latex .imp {
font-weight: bold;
color: red;
}
.latex.source-latex li,
.latex.source-latex .li1 {
font-weight: normal;
vertical-align: top;
}
.latex.source-latex .ln {
width: 1px;
text-align: right;
margin: 0;
padding: 0 2px;
vertical-align: top;
}
.latex.source-latex .li2 {
font-weight: bold;
vertical-align: top;
}
.latex.source-latex .kw1 {
color: #800000;
}
.latex.source-latex .co1 {
color: #2c922c;
font-style: italic;
}
.latex.source-latex .es0 {
color: #000000;
font-weight: bold;
}
.latex.source-latex .sy0 {
color: #e02020;
}
.latex.source-latex .st0 {
color: #000000;
}
.latex.source-latex .re1 {
color: #8020e0;
font-weight: normal;
}
.latex.source-latex .re2 {
color: #c08020;
font-weight: normal;
}
.latex.source-latex .re3 {
color: #8020e0;
font-weight: normal;
}
.latex.source-latex .re4 {
color: #800000;
font-weight: normal;
}
.latex.source-latex .re5 {
color: #00008b;
font-weight: bold;
}
.latex.source-latex .re6 {
color: #800000;
font-weight: normal;
}
.latex.source-latex .re7 {
color: #0000d0;
font-weight: normal;
}
.latex.source-latex .re8 {
color: #c00000;
font-weight: normal;
}
.latex.source-latex .re9 {
color: #2020c0;
font-weight: normal;
}
.latex.source-latex .re10 {
color: #800000;
font-weight: normal;
}
.latex.source-latex .re11 {
color: #e00000;
font-weight: normal;
}
.latex.source-latex .re12 {
color: #800000;
font-weight: normal;
}
.latex.source-latex .ln-xtra,
.latex.source-latex li.ln-xtra,
.latex.source-latex div.ln-xtra {
background-color: #ffc;
}
.latex.source-latex span.xtra {
display: block;
}
/*]]>*/
a.search-result {
display: block;
margin-top: @line-height-computed / 2;
.search-result-content {
margin-top: @line-height-computed / 4;
white-space: pre-wrap;
font-size: 0.8em;
color: @gray-dark;
em {
font-weight: bold;
}
}
&:hover,
&:active,
&:focus {
text-decoration: none;
.search-result-content {
color: @gray-darker;
}
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.35);
}
}
/* Keep the below rules in sync with the wiki pages */
img {
height: auto;
max-width: 100%;
}
img.add-vertical-space {
padding-bottom: 20px;
padding-top: 20px;
}
th.no-wrap {
white-space: nowrap;
text-align: left;
}
/* LATEX and TEX artwork */
span.TEX {
letter-spacing: -0.125em;
padding-right: 0.5ex;
}
span.TEX span.E {
position: relative;
top: 0.5ex;
padding-right: 0.1ex;
}
a span.TEX span.E {
text-decoration: none;
}
span.LATEX span.A {
position: relative;
top: -0.5ex;
left: -0.4em;
font-size: 75%;
}
span.LATEX span.TEX {
position: relative;
left: -0.4em;
margin-right: -0.5ex;
}
}
| overleaf/web/frontend/stylesheets/app/wiki.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/wiki.less",
"repo_id": "overleaf",
"token_count": 2435
} | 550 |
/*
* Original version: 1.0 © 2010 Andrew Valums ( andrew(at)valums.com )
* Current Maintainer (2.0+): 2012, Ray Nicholus ( fineuploader(at)garstasio.com )
*
* Licensed under MIT license, GNU GPL 2 or later, GNU LGPL 2 or later, see license.txt.
*/
.qq-uploader-selector {
position: relative;
width: 100%;
}
.qq-uploader-selector {
text-align: center;
border: 1px dashed #666;
border-radius: 6px;
vertical-align: middle;
.help {
margin-top: 6px;
}
min-height: 300px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: center;
}
/*.qq-upload-button-selector {
display: block;
width: 105px;
padding: 7px 0;
text-align: center;
background: #880000;
border-bottom: 1px solid #DDD;
color: #FFF;
}
.qq-upload-button-hover-selector {
background: #CC0000;
}
.qq-upload-button-focus-selector {
outline: 1px dotted #000000;
}*/
.qq-upload-drop-area-selector,
.qq-upload-extra-drop-area-selector {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
min-height: 30px;
z-index: 2;
background: @orange;
text-align: center;
}
.qq-upload-drop-area-selector span {
display: block;
position: absolute;
top: 50%;
width: 100%;
margin-top: -12px;
font-size: 16px;
color: white;
}
.qq-upload-extra-drop-area-selector {
position: relative;
margin-top: 50px;
font-size: 16px;
padding-top: 30px;
height: 20px;
min-height: 40px;
}
.qq-upload-drop-area-active-selector {
background: darken(@orange, 15%);
}
.qq-upload-list-selector {
margin: 0;
padding: 0;
list-style: none;
}
.qq-upload-list-selector li {
margin: 0;
margin-top: 10px;
padding: 9px;
line-height: 15px;
font-size: 16px;
background-color: @gray-lightest;
}
.qq-upload-file-selector,
.qq-upload-spinner-selector,
.qq-upload-size-selector,
.qq-upload-cancel-selector,
.qq-upload-retry-selector,
.qq-upload-failed-text-selector,
.qq-upload-finished-selector,
.qq-upload-delete-selector {
margin-right: 12px;
}
.qq-upload-file-selector {
word-break: break-word;
}
.qq-upload-spinner-selector {
display: inline-block;
width: 15px;
height: 15px;
vertical-align: text-bottom;
}
.qq-upload-finished-selector {
display: none;
width: 15px;
height: 15px;
vertical-align: text-bottom;
}
.qq-upload-retry-selector,
.qq-upload-delete-selector {
display: none;
}
.qq-upload-retryable-selector .qq-upload-retry-selector {
display: inline;
}
.qq-upload-size-selector,
.qq-upload-cancel-selector,
.qq-upload-retry-selector,
.qq-upload-delete-selector {
font-size: 12px;
font-weight: normal;
}
.qq-upload-failed-text-selector {
display: none;
font-style: italic;
font-weight: bold;
}
.qq-upload-failed-icon-selector {
display: none;
width: 15px;
height: 15px;
vertical-align: text-bottom;
}
.qq-upload-fail-selector .qq-upload-failed-text-selector {
display: inline;
}
.qq-upload-retrying-selector .qq-upload-failed-text-selector {
display: inline;
color: #d60000;
}
.qq-upload-list-selector li.qq-upload-success-selector {
background-color: @green;
color: #ffffff;
}
.qq-upload-list-selector li.qq-upload-fail-selector {
background-color: @red;
color: #ffffff;
}
.qq-progress-bar-selector {
width: 0%;
height: @line-height-computed;
margin-bottom: @line-height-computed / 2;
font-size: @font-size-small;
line-height: @line-height-computed;
color: @progress-bar-color;
text-align: center;
background-color: @progress-bar-info-bg;
.box-shadow(inset 0 -1px 0 rgba(0, 0, 0, 0.15));
.transition(width 0.6s ease);
border-radius: @border-radius-base 0 0 @border-radius-base;
}
a.qq-btn {
&:hover {
cursor: pointer !important;
}
}
| overleaf/web/frontend/stylesheets/components/fineupload.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/fineupload.less",
"repo_id": "overleaf",
"token_count": 1477
} | 551 |
.nav-pills {
> li {
> a {
border-radius: @btn-border-radius-base;
}
}
}
| overleaf/web/frontend/stylesheets/components/navs-ol.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/navs-ol.less",
"repo_id": "overleaf",
"token_count": 48
} | 552 |
//
// Tooltips
// --------------------------------------------------
// Base class
.tooltip {
position: absolute;
z-index: @zindex-tooltip;
display: block;
visibility: visible;
font-size: @font-size-small;
line-height: 1.4;
.opacity(0);
&.in {
.opacity(@tooltip-opacity);
}
&.top {
margin-top: -3px;
padding: @tooltip-arrow-width 0;
}
&.right {
margin-left: 3px;
padding: 0 @tooltip-arrow-width;
}
&.bottom {
margin-top: 3px;
padding: @tooltip-arrow-width 0;
}
&.left {
margin-left: -3px;
padding: 0 @tooltip-arrow-width;
}
}
// Wrapper for the tooltip content
.tooltip-inner {
max-width: @tooltip-max-width;
padding: 3px 8px;
color: @tooltip-color;
text-align: center;
text-decoration: none;
background-color: @tooltip-bg;
border-radius: @border-radius-base;
}
// Arrows
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip {
&.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -@tooltip-arrow-width;
border-width: @tooltip-arrow-width @tooltip-arrow-width 0;
border-top-color: @tooltip-arrow-color;
}
&.top-left .tooltip-arrow {
bottom: 0;
left: @tooltip-arrow-width;
border-width: @tooltip-arrow-width @tooltip-arrow-width 0;
border-top-color: @tooltip-arrow-color;
}
&.top-right .tooltip-arrow {
bottom: 0;
right: @tooltip-arrow-width;
border-width: @tooltip-arrow-width @tooltip-arrow-width 0;
border-top-color: @tooltip-arrow-color;
}
&.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -@tooltip-arrow-width;
border-width: @tooltip-arrow-width @tooltip-arrow-width @tooltip-arrow-width
0;
border-right-color: @tooltip-arrow-color;
}
&.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -@tooltip-arrow-width;
border-width: @tooltip-arrow-width 0 @tooltip-arrow-width
@tooltip-arrow-width;
border-left-color: @tooltip-arrow-color;
}
&.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -@tooltip-arrow-width;
border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;
border-bottom-color: @tooltip-arrow-color;
}
&.bottom-left .tooltip-arrow {
top: 0;
left: @tooltip-arrow-width;
border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;
border-bottom-color: @tooltip-arrow-color;
}
&.bottom-right .tooltip-arrow {
top: 0;
right: @tooltip-arrow-width;
border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;
border-bottom-color: @tooltip-arrow-color;
}
}
| overleaf/web/frontend/stylesheets/components/tooltip.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/tooltip.less",
"repo_id": "overleaf",
"token_count": 1100
} | 553 |
@import 'style.less';
@import 'core/ol-ieee-variables.less';
@is-overleaf-light: false;
@show-rich-text: true;
@ieee-wedge: 30px;
body > .portal-ieee {
padding-top: @header-height;
}
.portal-ieee {
.ieee-header {
background-color: @ieee-blue;
margin-bottom: @margin-xl;
padding-bottom: @padding-sm;
padding-top: @padding-sm;
h1 {
margin: 0;
}
.ieee-logo {
width: @navbar-brand-width;
}
}
.ieee-subheader {
background-color: @ieee-blue;
color: #ffffff;
line-height: 1;
padding: @padding-md @ieee-wedge;
position: relative;
&:after {
content: '';
display: block;
position: absolute;
border-style: solid;
left: -1px;
top: -1px;
border-color: @content-alt-bg-color transparent;
border-width: @ieee-wedge @ieee-wedge 0 0;
}
}
}
| overleaf/web/frontend/stylesheets/ieee-style.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/ieee-style.less",
"repo_id": "overleaf",
"token_count": 407
} | 554 |
{
"generic_linked_file_compile_error": "Dette projekts udfiler er ikke tilgængelige, fordi det ikke kunne kompilere. Du kan se detaljerede kompileringsfejl, hvis du åbner projektet.",
"chat_error": "Kunne ikke indlæse chatbeskeder, prøv venligst igen.",
"reconnect": "Prøv igen",
"no_pdf_error_title": "Ingen PDF",
"no_pdf_error_explanation": "Denne kompilering producerede ikke nogen PDF. Det kan ske, hvis:",
"no_pdf_error_reason_unrecoverable_error": "Der er en uoprettelig LaTeX-fejl. Hvis der er LaTeX-fejl vist herunder, eller i de rå logge, så forsøg at rette dem, og kompiler så ingen.",
"no_pdf_error_reason_no_content": "<code>document</code>-blokken har ikke noget indhold. Hvis den er tom, må du give den noget indhold, og så kompilere igen.",
"no_pdf_error_reason_output_pdf_already_exists": "Dette projekt indeholder en fil, som hedder <code>output.pdf</code>. Hvis den fil eksisterer, er du nødt til at omnavngive den, og så kompilere igen.",
"logs_pane_info_message": "Vi tester en ny rude til logge",
"logs_pane_info_message_popup": "Vi tester en ny rude til logge. Klik her for at fortælle os din mening",
"github_symlink_error": "Dit github repository indeholder symbolske lænkefiler, som ikke på nuværende tidpunkt er understøttet af Overleaf. Du må fjerne de filer, og derefter prøve igen.",
"address_line_1": "Adresse",
"address_line_2": "Adresse (2. linje, valgfri)",
"postal_code": "Postnummer",
"reload_editor": "Genindlæs skriveprogram",
"compile_error_description": "Dette projekt kompilerede ikke på grund af en fejl",
"validation_issue_description": "Dette projekt kompilerede ikke på grund af et valideringsproblem",
"compile_error_entry_description": "En fejl, som forhindrede dette projekt i at kompilere",
"validation_issue_entry_description": "Et valideringsproblem, som forhindrede dette projekt i at kompilere",
"github_file_name_error": "Dit projekt har fil(er) med ugyldigt filnavn. Kig dit repository igennem, og prøv igen.",
"raw_logs_description": "Rå logger fra LaTeX–kompileringsprogrammet",
"raw_logs": "Rå logger",
"first_error_popup_label": "Dette projekt havde fejl. Det her er den frøste.",
"dismiss_error_popup": "Afvis første fejlmeddelelse",
"go_to_error_location": "Gå til fejlens placering",
"log_entry_description": "Logoptegnelse med niveau: __level__",
"navigate_log_source": "Naviger til loggens tilsvarende sted i kildekoden: __location__",
"other_output_files": "Hent andre udfiler",
"refresh": "Genindlæs",
"toggle_output_files_list": "Udfil–liste",
"n_warnings": "__count__ advarsel",
"n_warnings_plural": "__count__ advarsler",
"n_errors": "__count__ fejl",
"n_errors_plural": "__count__ fejl",
"toggle_compile_options_menu": "Kompiléringsindstillingsmenu",
"view_pdf": "Se PDF",
"view_logs": "Se log",
"recompile_from_scratch": "Genkompilér fra bunden",
"tagline_free": "Perfekt at starte med",
"also_provides_free_plan": "__appName__ har også et gratis abonnement—du skal bare <0>registrere dig</0> for at komme igang.",
"compile_timeout": "Tidsgrænse for kompiléring (minutter)",
"collabs_per_proj_single": "__collabcount__ samarbejdspartnere per projekt",
"premium_features": "Premium funktioner",
"special_price_student": "Studenterabonnementer Til Specialpris",
"hide_outline": "Skjul disposition",
"show_outline": "Vis disposition",
"expand": "Fold ud",
"collapse": "Fold sammen",
"file_outline": "Disposition",
"we_cant_find_any_sections_or_subsections_in_this_file": "Vi kan ikke finde nogen sektioner eller undersektioner i denne fil",
"find_out_more_about_the_file_outline": "Få mere at vide om dispositionen",
"wed_love_you_to_stay": "Vi ville elske, hvis du blev",
"yes_move_me_to_student_plan": "Ja, flyt mig til et studenterabonnement",
"last_login": "Sidste log–ind",
"thank_you_for_being_part_of_our_beta_program": "Mange tak fordi du deltager i vores Betaprogram, hvor du kan få tidlig adgang til nye funktioner, og hjælpe os med bedre at forstå dine behov",
"you_will_be_able_to_contact_us_any_time_to_share_your_feedback": "Du vil kunne kontakte os når som helst, for at give din feedback",
"we_may_also_contact_you_from_time_to_time_by_email_with_a_survey": "Vi kontakter måske også dig fra tid til anden via email med et spørgeskema, eller for at se, om du har lyst til at deltage i andre brugerundersøgelsesinitiativer",
"you_can_opt_in_and_out_of_the_program_at_any_time_on_this_page": "Du kan på denne side til enhver tid til– og framelde dig programmet",
"give_feedback": "Giv feedback",
"beta_feature_badge": "Betafunktions–skilt",
"invalid_filename": "Overførsel mislykkedes: Check filnavnet for specialtegn eller ekstra mellemrum, og at det er kortere end __nameLimit__ tegn",
"clsi_unavailable": "Beklager, kompileringsserveren til dit projekt var midlertidigt utilgængelig. Prøv igen om lidt.",
"x_price_per_month": "<0>__price__</0> per måned",
"x_price_per_year": "<0>__price__</0> per år",
"x_price_for_first_month": "<0>__price__</0> for din første måned",
"x_price_for_first_year": "<0>__price__</0> for dit første år",
"normally_x_price_per_month": "Normalt __price__ per måned",
"normally_x_price_per_year": "Normalt __price__ per år",
"then_x_price_per_month": "Derefter __price__ per måned",
"then_x_price_per_year": "Derefter __price__ per år",
"for_your_first": "for din/dit første",
"sso_not_linked": "Du har ikke forbundet din konto til __provider__. Du bliver nødt til først at logge ind med en anden metode, og forbinde din __provider__–konto i dine kontoindstillinger.",
"template_gallery": "Skabelonsgalleri",
"template_not_found_description": "Denne vej til at lave nye projekter ud fra skabeloner er blevet fjernet. Du kan kigge i vores skabelonsgalleri efter flere skabeloner.",
"dropbox_checking_sync_status": "Checker status for Dopboxintegration",
"dropbox_sync_in": "Opdaterer Overleaf",
"dropbox_sync_out": "Opdaterer Dropbox",
"dropbox_sync_both": "Opdaterer Overleaf og Dropbox",
"dropbox_synced": "Overleaf og Dropbox er fuldt opdaterede",
"dropbox_sync_status_error": "Der er sket en fejl i Dropboxintegrationen",
"requesting_password_reset": "Beder om nulstilling af kodeord",
"tex_live_version": "TeX Live–version",
"github_timeout_error": "Synkroniséringen af dit Overleaf–projekt med Github har overskredet tidsgrænsen. Det kan skyldes, at dit projekt er for stort, eller at der er for mange ændringer eller nye filer.",
"github_large_files_error": "Merge mislykkedes: Dit Github reopsitory indeholder filer, som er større end grænsen på 50MB ",
"no_history_available": "Dette projekt har ikke nogen historie endnu. Prøv at lave nogen ændringer, og vend så tilbage.",
"project_approaching_file_limit": "Dette projekt nærmer sig grænsen for filer",
"project_has_too_many_files": "Dette projekt har nået grænsen på 2000 filer",
"processing_your_request": "Vent venligst, mens vi behandler din forespørgsel.",
"github_repository_diverged": "Master branch i det forbundne repository er blevet force–pushet. Det kan desynkronisere Overleaf og Github at pulle ændringer efter et force push. Det vil muligvis være nødvendigt at pushe ændringer efter pullet for blive synkroniseret igen.",
"unlink_github_repository": "Afskær Github Repository",
"unlinking": "Fjerner forbindelse",
"github_no_master_branch_error": "Dette repository kan ikke forbindes, da det ikke har nogen master branch. Du må først være sikker på, at projektet har en master branch",
"confirmation_token_invalid": "Beklager, din bekræftelsespolet er ugyldig eller udløbet. Vi må bede dig bestille en ny email med et bekræftelseslink.",
"confirmation_link_broken": "Beklager, der er noget galt med dit bekræftelseslink. Du kan prøve at kopiere og indsætte linket i bunden af din bekræftelsesmail.",
"duplicate_file": "Duplikér Fil",
"file_already_exists_in_this_location": "Et emne med navnet <0>__fileName__</0> findes allerede på denne placering. Hvis du vil gennemføre flytningen, skal du først omdøbe eller flytte den fil, som er i vejen, og derefter prøve igen.",
"blocked_filename": "Der er blokeret for det her filnavn.",
"group_full": "Denne gruppe er allerede fuld",
"no_selection_select_file": "Der er ikke valgt nogen fil. Du kan vælge en fil at få vist i filtræet.",
"no_selection_create_new_file": "Dit projekt er tomt. Lav venligst en ny fil.",
"files_selected": "filer valgt.",
"home": "Hjem",
"this_action_cannot_be_undone": "Denne handling kan ikke fortrydes.",
"dropbox_email_not_verified": "Vi har ikke kunnet hente opdateringer fra din Dropbox–konto. Dropbox rapporterer, at din emailadresse ikke er bekræftet. For at løse dette, må du bekræfte din emailadresse overfor Dropbox.",
"token_access_success": "Adgang tildelt",
"token_access_failure": "Kan ikke tildele adgang; kontakt projektejeren for hjælp",
"trashed_projects": "Kassérede projekter",
"trash": "Kassér",
"untrash": "Gendan",
"delete_and_leave": "Slet / Forlad",
"trash_projects": "Kassér Projekter",
"about_to_trash_projects": "Du er ved at kassére følgende projekter:",
"archived_projects_info_note": "Arkivet fungerer nu på individuel brugerbasis. Projekter, som du bleslutter at arkivere, arkiveres kun for dig, og ikke dine samarbejdspartnere.",
"trashed_projects_info_note": "Overleaf har nu en kasse til projekter, du vil af med. Det påvirker ikke dine samarbejdspartnere, hvis du Kassérer et projekt.",
"register_intercept_sso": "Du kan forbinde din __authProviderName__–konto fra din Kontoindstillingsside, efter du har logget ind.",
"continue_to": "Fortsæt til __appName__",
"project_ownership_transfer_confirmation_1": "Er du sikker på, at du vil gøre <0>__user__</0> til ejer af <1>__project__</1>?",
"project_ownership_transfer_confirmation_2": "Denne handling kan ikke fortrydes. Den nye ejer får besked, og vil kunne ændre projektets adgangsindstillinger (inklusive at fratage din egen adgang).",
"change_owner": "Skift ejer",
"change_project_owner": "Skift Projektejer",
"password_too_long_please_reset": "Maksimal kodeordslængde overskredet. Start venligst forfra med dit kodeord.",
"view_other_options_to_log_in": "Se andre muligheder for at logge ind",
"we_logged_you_in": "Vi har logget dig ind.",
"will_need_to_log_out_from_and_in_with": "Du bliver nødt til at <b>logge ud</b> fra din konto for <b>__email1__</b>, og derefter logge ind med <b>__email2__</b>.",
"resubmit_institutional_email": "Genindsend venligst din institutionelle email.",
"opted_out_linking": "Du har fravalgt at forbinde din <b>__appName__</b>–konto for <b>__email__</b> til din institutionelle konto.",
"please_link_to_institution_account": "Forbind din <b>__appName__</b>–konto for <b>__email__</b> med din institutionelle konto hos <b>__institutionName__</b>.",
"register_with_another_email": "<a href=\"__link__\">Bliv registreret hos __appName__</a> med en anden emailadresse.",
"register_with_email_provided": "<a href=\"__link__\">Bliv registreret hos __appName__</a> med den emailadresse og det kodeord, du har oplyst.",
"security_reasons_linked_accts": "Af sikkerhedsårsager, fordi din institutionelle email allerede er associeret med <b>__appName__</b>–kontoen for <b>__email__</b>, kan vi kun tillade en forbindelse med den specifikke konto.",
"this_grants_access_to_features": "Dette giver dig adgang til <b>__appName__</b> <b>__featureType__</b> funktioner.",
"to_add_email_accounts_need_to_be_linked": "For at tilføje denne email skal din <b>__appName__</b>– og din <b>__institutionName__</b>–konto først forbindes.",
"tried_to_log_in_with_email": "Du har prøvet at logge ind med <b>__email__</b>.",
"tried_to_register_with_email": "Du har forsøgt at blive registreret som <b>__email__</b>, hvilken allerede er registreret hos <b>__appName__</b> som en institutionel konto.",
"log_in_with_email": "Log ind med __email__",
"log_in_with_existing_institution_email": "For at forbinde din <b>__appName__</b>– og din <b>__institutionName__</b>–konto, er du nødt til først at logge ind med din eksisterende <b>__appName__</b>–konto.",
"log_out_from": "Log __email__ ud",
"logged_in_with_acct_that_cannot_be_linked": "Du har logget ind med en <b>__appName__</b>–konto, som ikke kan forbindes med din institutionelle konto.",
"logged_in_with_email": "Du er i øjeblikket logget ind i <b>__appName__</b> med emailen <b>__email__</b>.",
"looks_like_logged_in_with_email": "Det ser ud til, at du allerede er logget ind i <b>__appName__</b> med emailen <b>__email__</b>.",
"make_primary_to_log_in_through_institution": "Sæt <b>__email__</b> som din primære email for at kunne logge ind gemmen din institutions portal. ",
"make_primary_which_will_allow_log_in_through_institution": "Hvis du sætter den som din <b>primære __appName__</b> email vil du blive i stand til at logge ind gennem din institutions portal.",
"need_to_do_this_to_access_license": "Det er nødvendigt for, at du kan drage nytte af de fordele, som følger med den site licens, som tilhører <b>__institutionName__</b>",
"institutional_login_not_supported": "Dit universitet understøtter ikke <b>institutionel indlogning</b> endnu, men du kan stadig blive registreret med en institutionel email.",
"link_account": "Forbind Konto",
"link_accounts": "Forbind Kontoer",
"link_accounts_and_add_email": "Forbind Kontoer og Tilføj Email",
"link_your_accounts": "Forbind dine kontoer",
"log_in_and_link": "Log ind og forbind",
"log_in_and_link_accounts": "Log ind og forbind kontoer",
"log_in_first_to_proceed": "Du kan først fortsætte, når du har <b>logget ind</b>.",
"log_in_through_institution": "Log ind via din institution",
"if_have_existing_can_link": "Hvis du har en eksisterende <b>__appName__</b>–konto under en anden email, kan du forbinde den til din <b>__institutionName__</b>–konto ved at klikke <b>__clickText__</b>",
"if_owner_can_link": "Hvis du ejer <b>__appName__</b>–kontoen under <b>__email__</b>, vil du få mulighed for at forbinde den til din institutionelle konto hos <b>__institutionName__</b>.",
"ignore_and_continue_institution_linking": "Du kan også springe det over, og <a href=\"__link__\">fortsætte til __appName__ med kontoen for <b>__email__</b></a>.",
"get_in_touch_having_problems": "<a href=\"__link__\">Kontakt support</a>, hvis du oplever problemer",
"create_new_account": "Opret en ny konto",
"upgrade_for_longer_compiles": "Opgradér for at forlænge din tidsgrænse",
"ask_proj_owner_to_upgrade_for_longer_compiles": "Du må få projektets ejer til at opgradere, for at få forlænget tidsgrænsen.",
"subscription_admins_cannot_be_deleted": "Du kan ikke slette din konto med et abonnement. Du må annullere dit abonnement, før du kan fortsætte. Hvis du bliver ved med at se denne besked, så kontakt os.",
"delete_acct_no_existing_pw": "Du bliver nødt til at bruge nulstillelsesformularen til at indstille et kodeord, før du kan slette din konto.",
"empty_zip_file": "Zip indeholder ikke nogen filer",
"you_can_now_login_through_overleaf_sl": "Du kan nu logge ind på din ShareLaTeX–konto via Overleaf.",
"find_out_more_nt": "Find ud af mere.",
"register_error": "Registreringsfejl",
"login_error": "Log–ind–fejl",
"more_info": "Mere info",
"synctex_failed": "Kunne ikke finde den tilhørende kildefil",
"linked_collabratec_description": "Brug Collabratec til at holde styr på dine __appName__–projekter.",
"reset_from_sl": "Før din ShareLaTeX–konto kan flyttes til Overleaf er du nødt til at nulstille dit kodeord i ShareLaTeX, og logge ind der",
"dropbox_already_linked_error": "Kan ikke forbinde til din Dropbox–konto, fordi den allerede er forbundet til en anden Overleaf–konto.",
"github_too_many_files_error": "Dette repository kan ikke importeres, fordi det indeholder flere end det maksimalt tilladte antal filer",
"linked_accounts": "forbundne konti",
"linked_accounts_explained": "Du kan forbinde din __appName__–konto med andre tjenester for at gøre brug af funktionerne beskrevet herunder",
"no_existing_password": "Brug formularen til at nulstille dit kodeord",
" to_reactivate_your_subscription_go_to": "Genaktivér dit abonnement ved at gå til",
"subscription_canceled": "Abonnement Annulleret",
"coupons_not_included": "Dette inkluderer ikke dine nuværende rabatter. De bliver automatisk lagt ind før din næste betaling",
"email_already_registered_secondary": "Denne email er allerede registreret som en sekundær email",
"secondary_email_password_reset": "Den email er registreret som en sekundær email. Du kan kun logges ind, hvis du skriver din kontos primære email.",
"if_registered_email_sent": "Hvis du har en konto, har vi sendt dig en email.",
"reconfirm": "genbekræft",
"request_reconfirmation_email": "bed om en genbekræftelsesmail",
"reconfirm_explained": "Vi er nødt til at genbekræfte din konto. Derfor må vi bede dig om at få tilsendt en nulstillingsmail til dit kodeord via formularen herunder. Hvis du møder problemer, er du velkommen til at kontakte os på",
"upload_failed": "Overførsel mislykkedes",
"file_too_large": "For stor fil",
"zip_contents_too_large": "For stort indhold i zip–fil",
"invalid_zip_file": "Ugyldig zip–fil",
"make_primary": "Gør Til Primær",
"make_email_primary_description": "Gør dette til den primære email, som bruges til at logge ind med",
"github_sync_repository_not_found_description": "Det forbundne repository er enten blevet fjernet, eller du har ikke længere adgang til det. Du kan forbinde til et nyt repository ved at klone projektet, og vælge punktet 'Github' i menuen. Du kan også fjerne forbindelsen mellem projektet og repository'et.",
"unarchive": "Gendan",
"cant_see_what_youre_looking_for_question": "Er der noget, der mangler?",
"something_went_wrong_canceling_your_subscription": "Der gik noget galt med annulleringen af dit abonnement. Du bliver nødt til at kontakte supporten.",
"department": "Afdeling",
"notification_features_upgraded_by_affiliation": "Godt nyt! Organisationen __institutionName__, som du tilhører, har et partnerskab med Overleaf, og du har nu adgang til alle Overleafs Professionelle funktioner.",
"github_private_description": "Du vælger hvem der kan se, og committe til, dette repository.",
"notification_project_invite_message": "<b>__userName__</b> vil gerne have dig med i <b>__projectName__</b>",
"notification_project_invite_accepted_message": "Du er nu med i <b>__projectName__</b>",
"subject_to_additional_vat": "Priser kan skulle pålægges yderligere afgifter, afhængigt af hvor du er.",
"select_country_vat": "Når du har valgt dit land på betalingssiden kan vi vise den totale pris inklusive moms.",
"to_change_access_permissions": "Hvis du vil ændre adgangstilladelser må du bede ejeren af projektet om det",
"file_name_in_this_project": "Filnavn I Dette Projekt",
"new_snippet_project": "Unavngivet",
"there_was_an_error_opening_your_content": "Der var en fejl i oprettelsen af dit projekt",
"sorry_something_went_wrong_opening_the_document_please_try_again": "Beklager, der skete en uventet fejl i forsøget på at åbne dette indhold i Overleaf. Prøv venligst igen.",
"password_change_passwords_do_not_match": "Kodeord er ikke ens",
"browsing_project_latest_for_pseudo_label": "Kigger på dit projekts nuværende indhold",
"history_label_project_current_state": "Nuværende indhold",
"download_project_at_this_version": "Hent denne version af projektet",
"submit": "indsend",
"help_articles_matching": "Hjælpeartikler magen til dit emne",
"dropbox_for_link_share_projs": "Du har adgang til dette projekt via link–deling, og det kan derfor ikke synkroniseres til din Dropbox medmindre du bliver inviteret via email af projektejeren.",
"clear_search": "ryd søgning",
"access_your_projects_with_git": "Tilgå dine projekter med Git",
"ask_proj_owner_to_upgrade_for_git_bridge": "Bed projektejeren om at opgradere sin konto for at kunne bruge git",
"export_csv": "Eksportér CSV",
"add_comma_separated_emails_help": "Brug komma–tegn (,) til at adskille emailadresser.",
"members_management": "Styring af medlemmer",
"managers_management": "Styring af ledere",
"institution_account": "Institutionskonto",
"git": "Git",
"clone_with_git": "Klon med Git",
"git_bridge_modal_description": "Du kan <code>git</code> <code>clone</code> dit projekt med linket herunder.",
"managers_cannot_remove_admin": "Administratorer kan ikke fjernes",
"managers_cannot_remove_self": "Ledere kan ikke fjerne sig selv",
"user_not_found": "Bruger ikke fundet",
"user_already_added": "Bruger allerede tilføjet",
"bonus_twitter_share_text": "Jeg bruger __appName__, det gratis online kollaborative LaTeX–skriveprogram—det er fedt og nemt at bruge!",
"bonus_email_share_header": "Online LaTeX–skriveprogram, du måske synes om",
"bonus_email_share_body": "Hey, jeg har brugt online LaTeX–skriveprogrammet __appName__ på det seneste, og tænkte, at du måske også har lyst til at kigge på det.",
"bonus_share_link_text": "Online LaTeX–skriveprogram __appName__",
"bonus_facebook_name": "__appName__ – Online LaTeX–skriveprogram",
"bonus_facebook_caption": "Gratis Ubegrænsede Projekter og Kompileringer",
"bonus_facebook_description": "__appName__ er et gratis online LaTeX–skriveprogram. Live samarbejde som i Google Docs, med Dropbox, historie og autofuldførelse.",
"password_change_failed_attempt": "Kodeordsskift slog fejl",
"password_change_successful": "Kodeord udskiftet",
"not_registered": "Ikke registreret",
"try_again": "Prøv venligst igen",
"email_required": "Email påkrævet",
"registration_error": "Registreringsfejl",
"newsletter-accept": "Jeg vil gerne modtage emails om produkttilbud og virksomhedsnyheder og –begivenheder.",
"resending_confirmation_email": "Gensender bekræftelsesmail",
"register_using_service": "Registrér med __service__",
"login_to_overleaf": "Log ind i Overleaf",
"login_with_email": "Log ind med din email",
"login_with_service": "Log ind med __service__",
"first_time_sl_user": "Første gang her som ShareLaTeX–bruger",
"migrate_from_sl": "Migrer fra ShareLaTeX",
"dont_have_account": "Ingen konto?",
"register_using_email": "Registrér dig med din email",
"login_register_or": "eller",
"to_add_more_collaborators": "For at få tilføjet flere samarbejdspartnere eller aktiveret linkdeling, skal du bede projektejeren om at gøre det",
"by": "af",
"emails": "Emails",
"editor_theme": "Tema for skrivevinduet",
"thousands_templates": "Flere tusind skabeloner",
"get_instant_access_to": "Få øjeblikkelig adgang til",
"currently_seeing_only_24_hrs_history": "Du ser nu på de sidste 24 timers ændringer i dette projekt.",
"archive_projects": "Arkivér Projekter",
"archive_and_leave_projects": "Arkivér og Forlad Projekter",
"about_to_archive_projects": "Du er på vej til at arkivére følgende projekter:",
"please_confirm_your_email_before_making_it_default": "Din emailadresse skal bekræftes, før du kan gøre den til din standardadresse.",
"back_to_editor": "Tilbage til skrivevinduet",
"generic_history_error": "Noget gik galt i forsøget på at hente dit projekts historie. Hvis fejlen fortsætter, så kontakt os via:",
"unconfirmed": "Ikke bekræftet",
"please_check_your_inbox": "Kig i din indboks",
"resend_confirmation_email": "Gensend bekræftelsesmail",
"history_label_created_by": "Oprettet af",
"history_label_this_version": "Sæt mærkat på denne version",
"history_add_label": "Tilføj mærkat",
"history_adding_label": "Tilføjer mærkat",
"history_new_label_name": "Navn på ny mærkat",
"history_new_label_added_at": "En ny mærkat bliver tilføjet fra og med",
"history_delete_label": "Slet mærkat",
"history_deleting_label": "Sletter mærkat",
"history_are_you_sure_delete_label": "Er du sikker på, at du vil slette følgende mærkat",
"browsing_project_labelled": "Kigger på projektversion mærket",
"history_view_all": "Komplet historie",
"history_view_labels": "Mærkater",
"history_view_a11y_description": "Vis den komplette projekthistorie, eller kun mærkede versioner.",
"add_another_email": "Tilføj endnu en email",
"start_by_adding_your_email": "Begynd ved at tilføje din email–adresse.",
"let_us_know": "Fortæl os om det",
"add_new_email": "Tilføj ny email",
"error_performing_request": "Der skete en fejl i forsøget på at udføre din forespørgesel.",
"save_or_cancel-save": "Gem",
"save_or_cancel-or": "eller",
"save_or_cancel-cancel": "Annuller",
"remove": "fjern",
"confirm_email": "Bekræft Email",
"file_action_edited": "Ændrede i",
"file_action_renamed": "Omdøbte",
"file_action_created": "Oprettede",
"file_action_deleted": "Slettede",
"browsing_project_as_of": "Kigger i projekt, som det så ud",
"font_family": "Skrifttypefamilie",
"line_height": "Linjehøjde",
"compact": "Kompakt",
"wide": "Bred",
"default": "Standard",
"leave": "Forlad",
"archived_projects": "Arkiverede projekter",
"archive": "Arkiv",
"find_out_more": "Find ud af mere",
"in_good_company": "Du Er I Godt Selskab",
"powerful_latex_editor": "Stærkt LaTeX–skriveprogram",
"latex_editor_info": "Alt hvad du har brug for i et moderne LaTeX–skriveprogram—stavekontrol, intelligent autofuldførelse, syntaksfremhævning, mange farvetemaer, tastaturbindinger fra vim og emacs, hjælp med LaTeXs advarsler og fejlmeddelelser, og meget mere.",
"number_collab": "Antal samarbejdspartnere",
"hundreds_templates": "Flere hundrede skabeloner",
"tooltip_hide_pdf": "Tryk for at skjule PDF'en",
"tooltip_show_pdf": "Tryk for at vise PDF'en",
"tooltip_hide_filetree": "Tryk for at skjule fil-træet",
"tooltip_show_filetree": "Tryk for at vise fil-træet",
"cannot_verify_user_not_robot": "Vi har desværre ikke kunnet verificere, at du ikke er en robot. Tjek venligst at Google reCAPTCHA ikke bliver blokeret af en adblocker eller en firewall.",
"uncompiled_changes": "Ukompilerede ændringer",
"code_check_failed": "Kode tjek fejlede",
"code_check_failed_explanation": "Din kode har fejl, der skal rettes før auto-kompileren kan køre",
"tags_slash_folders": "Tags/Mapper",
"file_already_exists": "Der eksisterer allerede en fil eller mappe med dette navn",
"import_project_to_v2": "Importer projekt til V2",
"open_in_v1": "Åben i V1",
"import_to_v2": "Importer til V2",
"never_mind_open_in_v1": "Ligegyldigt, åben i V1",
"yes_im_sure": "Ja, jeg er sikker",
"drop_files_here_to_upload": "Slip filer her for at uploade",
"drag_here": "træk her",
"creating_project": "Opretter projekt",
"select_a_zip_file": "Vælg en .zip fil",
"drag_a_zip_file": "træk en .zip fil",
"v1_badge": "V1 Skilt",
"v1_projects": "V1 Projekter",
"open_your_billing_details_page": "Åben siden med dine betalingsoplysninger",
"try_out_link_sharing": "Prøv den nye link-delingsfunktion!",
"try_link_sharing": "Prøv Link Deling",
"try_link_sharing_description": "Giv adgang til dit projekt ved at dele et link.",
"learn_more_about_link_sharing": "Lær mere om Link Deling",
"link_sharing": "Link Deling",
"tc_guests": "Gæster",
"select_all_projects": "Vælg alle",
"select_project": "Vælg",
"main_file_not_found": "Ukendt hoveddokument",
"please_set_main_file": "Vælg venligst projektets primære fil i projekt menuen. ",
"link_sharing_is_off": "Link deling er slået fra; kun inviterede personer kan se dette projekt.",
"turn_on_link_sharing": "Slå link deling til",
"link_sharing_is_on": "Link deling er slået til",
"turn_off_link_sharing": "Slå link deling fra",
"anyone_with_link_can_edit": "Alle med dette link kan redigere dette projekt",
"anyone_with_link_can_view": "Alle med dette link kan se dette projekt",
"turn_on_link_sharing_consequences": "Når link deling er slået til, vil alle med det relevante link kunne tilgå eller redigere dette projekt",
"turn_off_link_sharing_consequences": "Når link deling er slået fra, er det kun inviterede personer, som har adgang til dette projekt",
"autocompile_disabled": "Automatisk kompilering slået fra",
"autocompile_disabled_reason": "Grundet høj serverbelastning er baggrunds kompilering midlertidig slået fra. Genkompiler venligst ved at klikke på ovenstående knap.",
"auto_compile_onboarding_description": "Når det er slået til, vil du projekt kompilere imens du skriver.",
"try_out_auto_compile_setting": "Prøv den nye indstilling for automatisk kompilering",
"got_it": "Forstået",
"pdf_compile_in_progress_error": "Kompilering kører allerede i et andet vindue",
"pdf_compile_try_again": "Vent venlist til din anden kompilering er færdig før en ny startes",
"invalid_email": "En email adresse er forkert",
"auto_compile": "Kompilér automatisk",
"on": "Til",
"tc_everyone": "Alle",
"per_user_tc_title": "Følg individuelle ændringer",
"you_can_use_per_user_tc": "Nu kan du følge ændringer for hver enkelt bruger",
"turn_tc_on_individuals": "Aktiver 'Følg ændringer' for individuelle brugere",
"keep_tc_on_like_before": "Eller følg alle, som før",
"auto_close_brackets": "Luk automatisk firkantede parenteser",
"auto_pair_delimiters": "Par automatisk afgrænsninger",
"successfull_dropbox_link": "Dropbox er blevet forbundet, omdirigerer til indstillinger",
"show_link": "Vis Link",
"hide_link": "Skjul Link",
"aggregate_changed": "Ændrede",
"aggregate_to": "til",
"confirm_password_to_continue": "Bekræft kodeordet for at fortsætte",
"confirm_password_footer": "Vi vil ikke bede om dit kodeord igen i et stykke tid.",
"accept_all": "Accepter alle",
"reject_all": "Afvis alle",
"bulk_accept_confirm": "Er du sikker på, at du vil acceptere de valgte __nChanges__ ændringer?",
"bulk_reject_confirm": "Er du sikker på, at du vil afvise de valgte __nChanges__ ændringer?",
"uncategorized": "Ikke kategoriseret",
"pdf_compile_rate_limit_hit": "Grænsen for kompilerings hyppigheden er nået",
"project_flagged_too_many_compiles": "Dette projekt er blevet markeret for at kompilere for ofte. Grænsen bliver snart løftet.",
"reauthorize_github_account": "Autoriser din GitHub konto igen",
"github_credentials_expired": "Dine GitHub autorisations oplysninger er udløbet",
"hit_enter_to_reply": "Tryk på Enter for at svare",
"add_your_comment_here": "Tilføj din kommentar her",
"resolved_comments": "Løste kommentarer",
"try_it_for_free": "Prøv det gratis",
"please_ask_the_project_owner_to_upgrade_to_track_changes": "Spørg projektejeren om at bruge \"Følg Ændringer\"",
"mark_as_resolved": "Markér som løst",
"reopen": "Genåben",
"add_comment": "Tilføj kommentar",
"no_resolved_threads": "Ingen løse tråde",
"upgrade_to_track_changes": "Opgrader til \"Følg Ændringer\"",
"see_changes_in_your_documents_live": "Se ændringer i dokumentet live",
"track_any_change_in_real_time": "Følg alle ændringer i realtime",
"review_your_peers_work": "Lav review af dine partneres arbejde",
"accept_or_reject_each_changes_individually": "Accepter eller afvis hver rettelse individuelt",
"accept": "Accepter",
"reject": "Afvis",
"no_comments": "Ingen kommentarer",
"edit": "Rediger",
"are_you_sure": "Er du sikker?",
"resolve": "Løs",
"reply": "Svar",
"quoted_text_in": "Tekst i gåseøjne i",
"review": "Review",
"track_changes_is_on": "Følg ændringer er slået <strong>til</strong>",
"track_changes_is_off": "Følg ændringer er slået <strong>fra</strong>",
"current_file": "Nuværende fil",
"overview": "Oversigt",
"tracked_change_added": "Tilføjet",
"tracked_change_deleted": "Slettet",
"show_all": "vis alle",
"show_less": "vis færre",
"dropbox_sync_error": "Fejl i synkronisering med Dropbox",
"send": "Send",
"sending": "Sender",
"invalid_password": "Ugyldigt password",
"error": "Fejl",
"other_actions": "Andre handlinger",
"send_test_email": "Send en test email",
"email_sent": "Email sendt",
"create_first_admin_account": "Opret den første Admin konto",
"ldap": "LDAP",
"ldap_create_admin_instructions": "Vælg en email adresse for den første __appName__ admin konto. Denne skal svare til en konto i LDAP systemet. Du vil derefter blive bedt om at logge på med denne konto.",
"saml": "SAML",
"saml_create_admin_instructions": "Vælg en email adresse for den første __appName__ admin konto. Denne skal svare til en konto i SAML systemet. Du vil derefter blive bedt om at logge på med denne konto.",
"admin_user_created_message": "Admin bruger oprettet, <a href=\"__link__\">Log ind her</a> for at fortsætte",
"status_checks": "Status tjek",
"editor_resources": "Editor ressourcer",
"checking": "Tjekker",
"cannot_invite_self": "Kan ikke sende invitation til dig selv",
"cannot_invite_non_user": "Invitation kan ikke sendes. Modtager må allerede have en __appName__ konto",
"log_in_with": "Log ind med __provider__",
"return_to_login_page": "Tilbage til log ind siden",
"login_failed": "Log ind fejlede",
"delete_account_warning_message_3": "Du er ved at <strong>slette alle din kontos data</strong>, herunder dine projekter og indstillinger, permanent. Skriv venligst din kontos email adresse og kodeord i nedenstående felter for at fortsætte.",
"delete_account_warning_message_2": "Du er ved at <strong>slette alle din kontos data</strong>, herunder dine projekter og indstillinger, permanent. Skriv venligst din kontos email adresse i nedenstående felt for at fortsætte.",
"your_sessions": "Dine sessioner",
"clear_sessions_description": "Dette er en liste over alle din brugers aktive sessioner (logins), undtagen din nuværende session. Klik på knappen \"Ryd sessioner\" nedenunder for at logge dem af.",
"no_other_sessions": "Ingen aktive sessioner",
"ip_address": "IP adresse",
"session_created_at": "Session oprettet på",
"clear_sessions": "Ryd sessioner",
"clear_sessions_success": "Sessioner ryddet",
"sessions": "Sessioner",
"manage_sessions": "Kontroller dine sessioner",
"syntax_validation": "Kode tjek",
"history": "Historie",
"joining": "Tilslutter",
"open_project": "Åben projekt",
"files_cannot_include_invalid_characters": "Filnavnet er tomt, eller indeholder ugyldige karakterer",
"invalid_file_name": "Ugyldigt filnavn",
"autocomplete_references": "Automatisk reference-udfyldelse (indeni en <code>\\cite{}</code> blok)",
"autocomplete": "Auto udfyld",
"failed_compile_check": "Det ser ud til at dit projekt har nogle fatale syntaksfejl, som skal rettes før vi kan kompilere det",
"failed_compile_check_try": "Prøv at kompilere alligevel",
"failed_compile_option_or": "eller",
"failed_compile_check_ignore": "slå syntaks tjek fra",
"compile_time_checks": "Syntaks Tjek",
"stop_on_validation_error": "Syntaks tjek før kompilering",
"ignore_validation_errors": "Undlad at tjekke syntaks",
"run_syntax_check_now": "Tjek syntaks nu",
"your_billing_details_were_saved": "Dine betalingsoplysninger blev gemt",
"security_code": "Sikkerheds kode",
"paypal_upgrade": "For at opgradere skal du klikke på nedenstående knap og logge på PayPal via din email og password",
"upgrade_cc_btn": "Opgrader nu, betal efter 7 dage",
"upgrade_paypal_btn": "Fortsæt",
"notification_project_invite": "<b>__userName__</b> vil gerne have dig til at deltage i <b>__projectName__</b> <a class=\"btn btn-sm btn-info pull-right\" href=\"/project/__projectId__/invite/token/__token__\">Deltag i Projektet</a>",
"file_restored": "Din fil (__filename__) er blevet reddet",
"file_restored_back_to_editor": "Du kan gå tilbage til skrivevinduet og arbejde videre.",
"file_restored_back_to_editor_btn": "Tilbage til skrivevinduet",
"view_project": "Vis projekt",
"join_project": "Deltag i Projektet",
"invite_not_accepted": "Invitationen er endnu ikke accepteret",
"resend": "Gensend",
"syntax_check": "Syntaks tjek",
"revoke_invite": "Tilbagekald invitation",
"pending": "Venter",
"invite_not_valid": "Dette er ikke en gyldig projekt invitation",
"invite_not_valid_description": "Invitationen kan være udløbet. Kontakt venligst projektets ejer",
"accepting_invite_as": "Du accepterer denne invitation som",
"accept_invite": "Accepter invitation",
"log_hint_ask_extra_feedback": "Vil du hjælpe os med at forstå, hvorfor dette hint ikke var til hjælp?",
"log_hint_extra_feedback_didnt_understand": "Jeg forstod ikke hintet",
"log_hint_extra_feedback_not_applicable": "Jeg kan ikke bruge løsningen i mit dokument",
"log_hint_extra_feedback_incorrect": "Dette fjerner ikke fejlen",
"log_hint_extra_feedback_other": "Andet:",
"log_hint_extra_feedback_submit": "Indsend",
"if_you_are_registered": "Hvis du allerede er registreret",
"stop_compile": "Stop kompilering",
"terminated": "Kompilation annulleret",
"compile_terminated_by_user": "Kompileringen blev annulleret via knappen 'Stop Kompilering'. Du kan se loggen for information om hvor kompileringen stoppede.",
"site_description": "Et online LaTeX–skriveprogram, der er let at bruge. Ingen installation, live samarbejde, versionskontrol, flere hundrede LaTeX–skabeloner, og meget mere.",
"knowledge_base": "videns base",
"contact_message_label": "Besked",
"kb_suggestions_enquiry": "Har du tjekket vores <0>__kbLink__</0>?",
"answer_yes": "Ja",
"answer_no": "Nej",
"log_hint_extra_info": "Lær mere",
"log_hint_feedback_label": "Var dette til hjælp?",
"log_hint_feedback_gratitude": "Tak for din tilbagemelding!",
"recompile_pdf": "Omkompilér PDF’en",
"about_paulo_reis": "er en front-end software udvikler and forsker i bruger oplevelse, bosiddende i Aveiro, Portugal. Paulo har en PhD i bruger oplevelse og er passioneret i at designe teknologi til menneskers brug - enten via koncept eller testing/validering i design eller implementation.",
"login_or_password_wrong_try_again": "Dit login eller password er forkert. Prøv venligst igen",
"manage_beta_program_membership": "Administrer Beta Program medlemsskab",
"beta_program_opt_out_action": "Fravælg Beta Program",
"disable_beta": "Deaktiver Beta",
"beta_program_badge_description": "Når du bruger __appName__ vil du beta funktioner være markeret med dette mærke:",
"beta_program_current_beta_features_description": "Vi tester på nuværende tidspunkt følgende nye funktioner i beta:",
"enable_beta": "Aktiver Beta",
"user_in_beta_program": "Bruger deltager i Beta Programmet",
"beta_program_already_participating": "Du er tilmeldt Betaprogrammet",
"sharelatex_beta_program": "__appName__ Beta Program",
"beta_program_benefits": "Vi forbedrer altid __appName__. Ved at tilmelde dig vores Beta program får du hurtigt adgang til nye funktioner og mulighed for at hjælpe os til at forstå dine behov bedre.",
"beta_program_opt_in_action": "Tilmeld Beta Program",
"conflicting_paths_found": "Modstridende stier blev fundet",
"following_paths_conflict": "Følgende filer og mapper kan ikke have samme sti",
"open_a_file_on_the_left": "Open en fil til venstre",
"reference_error_relink_hint": "Hvis fejlen fortsat opstår, så forsøg at genforbinde din konto her:",
"pdf_rendering_error": "PDF oversættelses fejl",
"something_went_wrong_rendering_pdf": "Noget gik galt i oversættelsen af denne PDF",
"mendeley_reference_loading_error_expired": "Mendeley polet udløbet, genforbind venligst din konto",
"zotero_reference_loading_error_expired": "Zotero polet udløbet, genforbind venligst din konto",
"mendeley_reference_loading_error_forbidden": "Kunne ikke indlæse referencer fra Mendeley, genforbind venligst din konto og prøv igen",
"zotero_reference_loading_error_forbidden": "Kunne ikke indlæse referencer fra Zotero, genforbind venligst din konto og prøv igen",
"mendeley_integration": "Mendeley integration",
"mendeley_sync_description": "Med integration af Mendeley kan du importere dine referencer fra Mendeley ind i dine __appName__ projekter.",
"mendeley_is_premium": "Integration af Mendeley er en betalt funktion",
"link_to_mendeley": "Link til Mendeley",
"unlink_to_mendeley": "Fjern link til Mendeley",
"mendeley_reference_loading": "Indlæser referencer fra Mendeley",
"mendeley_reference_loading_success": "Indlæste referencer fra Mendeley",
"mendeley_reference_loading_error": "Fejl, kunne ikke indlæse referencer fra Mendeley",
"zotero_integration": "Zotero integration.",
"zotero_sync_description": "Med integration af Zotero kan du importere dine referencer fra Zotero ind i dine __appName__ projekter.",
"zotero_is_premium": "Integration af Zotero er en betalt funktion",
"link_to_zotero": "Link til Zotero",
"unlink_to_zotero": "Fjern link til Zotero",
"zotero_reference_loading": "Indlæser referencer fra Zotero",
"zotero_reference_loading_success": "Indlæste referencer fra Zotero",
"zotero_reference_loading_error": "Fejl, kunne ikke indlæse referencer fra Zotero",
"reference_import_button": "Importer referencer til",
"unlink_reference": "Fjern link til reference udbyder",
"unlink_warning_reference": "Advarsel: Når du fjerner linket til denne udbyder fra din konto, vil du ikke længere have mulighed for at importere referencer ind i dine projekter.",
"mendeley": "Mendeley",
"zotero": "Zotero",
"suggest_new_doc": "Foreslå nyt dokument",
"request_sent_thank_you": "Besked sendt! Vores hold kigger på det, og svarer på email.",
"suggestion": "Foreslag",
"project_url": "Påvirket projekts URL",
"subject": "Emne",
"confirm": "Bekræft",
"cancel_personal_subscription_first": "Du har allerede et personligt abonnement. Ønsker du, at dette abonnement annulleres inden du tilslutter dig gruppe licensen?",
"delete_projects": "Slet projekter",
"leave_projects": "Forlad projecter",
"delete_and_leave_projects": "Slet og forlad projekter",
"too_recently_compiled": "Dette projekt er lige blevet kompileret, hvorfor denne kompilering er blevet udsat.",
"clsi_maintenance": "Kompilerings serverne er lukkede grundet vedligeholdelse, men vil være klar om et øjeblik.",
"references_search_hint": "Hold Ctrl-Mellemrum nede for at søge",
"ask_proj_owner_to_upgrade_for_references_search": "Spørg venligst projektets ejer om at opgradere for at bruge søgning i referencerne.",
"ask_proj_owner_to_upgrade_for_faster_compiles": "Spørg venligst projektets ejer om at opgradere for at bruge hurtigere kompileringer og forøge tidsbegrænsningen.",
"search_bib_files": "Søg efter forfatter, titel, år",
"leave_group": "Forlad gruppe",
"leave_now": "Forlad nu",
"sure_you_want_to_leave_group": "Er du sikker på, at du ønsker, at forlade denne gruppe?",
"notification_group_invite": "Du er blevet inviteret til at deltage i __groupName__, <a href=\"/user/subscription/__subscription_id__/group/invited\">Deltag her</a>.",
"search_references": "Søg i .bib filerne fra dette projekt",
"no_search_results": "Ingen Søge Resultater",
"email_already_registered": "Denne mail er allerede registreret",
"compile_mode": "Kompilering metode",
"normal": "Normal",
"fast": "Hurtig",
"rename_folder": "Omdøb mappe",
"delete_folder": "Slet mappe",
"about_to_delete_folder": "Du er ved at slette følgende mapper (ingen af mappernes projekter vil blive slettet):",
"to_modify_your_subscription_go_to": "For at administrere dit abonnement, gå til",
"manage_subscription": "Administrer Abonnement",
"activate_account": "Aktiver din konto",
"yes_please": "Ja tak!",
"nearly_activated": "Du er ét skridt fra at aktivere din __appName__ konto!",
"please_set_a_password": "Vælg venligst et kodeord",
"activation_token_expired": "Din aktiverings-polet er udløbet og du er nød til at få en anden tilsendt.",
"activate": "Aktiver",
"activating": "Aktiverer",
"ill_take_it": "Jeg tager det!",
"cancel_your_subscription": "Stop dit abonnoment",
"no_thanks_cancel_now": "Nej tak, jeg ønsker fortsat at ophæve",
"cancel_my_account": "Ophæv dit abonnoment",
"sure_you_want_to_cancel": "Er du sikker på, at du ønsker at ophæve?",
"i_want_to_stay": "Jeg ønsker at blive",
"have_more_days_to_try": "Få ydereligere <strong>__days__ dage</strong> på din prøveperiode!",
"interested_in_cheaper_plan": "Ville du være interesseret i en billigere <strong>__price__</strong> løsning for studerende?",
"session_expired_redirecting_to_login": "Session udløbet. Du omdirigeres til login siden om __seconds__ sekunder",
"maximum_files_uploaded_together": "Maksimalt __max__ filer uploaded sammen",
"too_many_files_uploaded_throttled_short_period": "For mange filer uploaded; dine uploads er blevet begrænset i en kort periode. Vent helst 15 minutter, før du prøver igen.",
"compile_larger_projects": "Kompilér større projekter",
"upgrade_to_get_feature": "Opgrader for at få __feature__, plus:",
"new_group": "Ny gruppe",
"about_to_delete_groups": "Du er på vej til at slette følgende grupper:",
"removing": "Sletter",
"adding": "Tilføjer",
"groups": "Grupper",
"rename_group": "Omdøb Gruppe",
"renaming": "Omdøber",
"create_group": "Opret Gruppe",
"delete_group": "Slet gruppe",
"delete_groups": "Slet Grupper",
"your_groups": "Dine Grupper",
"group_name": "Gruppenavn",
"no_groups": "Ingen Grupper",
"Subscription": "Abonnoment",
"Documentation": "Dokumentation",
"Universities": "Universiteter",
"Account Settings": "Kontoindstillinger",
"Projects": "Projekter",
"Account": "Konto",
"global": "globale",
"Terms": "Vilkår",
"Security": "Sikkerhed",
"About": "Om",
"editor_disconected_click_to_reconnect": "Skriveprogrammets forbindelse afbrudt, klik hvor som helst for at forbinde igen.",
"word_count": "Ordoptælling",
"please_compile_pdf_before_word_count": "Kompilér venligst dit projekt før du udfører en ordoptælling",
"total_words": "Totale Antal Ord",
"headers": "Overskrifter",
"math_inline": "Inkluderet matematik",
"math_display": "Vist Matematik",
"connected_users": "Forbundne Brugere",
"projects": "Projekter",
"upload_project": "Overfør projekt",
"all_projects": "Alle Projekter",
"your_projects": "Dine projekter",
"shared_with_you": "Delt med dig",
"deleted_projects": "Slettede projekter",
"templates": "Skabeloner",
"new_folder": "Ny mappe",
"create_your_first_project": "Lav dit første projekt!",
"complete": "Færdig",
"on_free_sl": "Du bruger den gratis version af __appName__",
"upgrade": "Opgrader",
"or_unlock_features_bonus": "eller låse op for nogle gratis bonus funktioner ved at",
"sharing_sl": "del __appName__",
"add_to_folder": "Tilføj til mappe",
"create_new_folder": "Opret ny mappe",
"more": "Mere",
"rename": "Omdøb",
"make_copy": "Lav en kopi",
"restore": "Gendan",
"title": "Titel",
"last_modified": "Sidst ændret",
"no_projects": "Ingen projekter",
"welcome_to_sl": "Velkommen til __appName__!",
"new_to_latex_look_at": "Ny til LaTeX? Start med at se på vores",
"or": "eller",
"or_create_project_left": "eller opret dit første projekt til venstre.",
"thanks_settings_updated": "Tak, dine indstillinger er blevet opdateret.",
"update_account_info": "Opdater Konto Info",
"must_be_email_address": "Skal være en email adresse",
"first_name": "Fornavn",
"last_name": "Efternavn",
"update": "Opdater",
"change_password": "Skift Kodeord",
"current_password": "Nuværende Kodeord",
"new_password": "Nyt Kodeord",
"confirm_new_password": "Bekræft Nyt Kodeord",
"required": "Nødvendig",
"doesnt_match": "Matcher ikke",
"dropbox_integration": "Dropbox Integration",
"learn_more": "Lær mere",
"dropbox_is_premium": "Dropbox synkronisering er en betalt funktion",
"account_is_linked": "Konto er forbundet",
"unlink_dropbox": "Fjern Dropbox forbindelse",
"link_to_dropbox": "Forbind til Dropbox",
"newsletter_info_and_unsubscribe": "Vi sender et nyhedsbrev en gang i mellem, der opsummere de nye funktioner der er tilgængelige. Hvis du fortækker ikke at modtage dette brev kan du afmelde dig når som helst.",
"unsubscribed": "Afmeldt",
"unsubscribing": "Afmelder",
"unsubscribe": "Afmeld",
"need_to_leave": "Nød til at gå?",
"delete_your_account": "Slet din konto",
"delete_account": "Slet Konto",
"delete_account_warning_message": "Du er ved at <strong>slette al din data</strong> permanent, inklusive dine projekter og indstillinger. Skriv din kontos email adresse i feltet herunder for at fortsætte.",
"deleting": "Sletter",
"delete": "Slet",
"sl_benefits_plans": "__appName__er verdens nemmeste LaTeX–program at bruge. Hold dig opdateret med dine samarbejdspartnere, hold styr på alle ændringer i dit arbejde og brug vores LaTeX–miljø fra hvor som helst på jorden.",
"monthly": "Månedtlig",
"personal": "Personlig",
"free": "Gratis",
"one_collaborator": "Kun en samarbejdspartner",
"collaborator": "Samarbejdspartner",
"collabs_per_proj": "__collabcount__ samarbejdspartnere per projekt",
"full_doc_history": "Fuld ændrings historik",
"sync_to_dropbox": "Synkroniser til Dropbox",
"start_free_trial": "Start gratis prøve!",
"professional": "Professionel",
"unlimited_collabs": "Ubegrænset antal samarbejdspartnere",
"name": "Navn",
"student": "Studerende",
"university": "Universitet",
"position": "Stilling",
"choose_plan_works_for_you": "Vælg den plan der fungere for dig med vores __len__-dags gratis prøveperiode. Afbryd når som helst.",
"interested_in_group_licence": "Intresseret i at bruge __appName__ med en gruppe-, hold- eller afdelingskonto?",
"get_in_touch_for_details": "Kontakt os for detaljer!",
"group_plan_enquiry": "Gruppe Plans Forespørgelse",
"enjoy_these_features": "Nyd alle disse fantastiske funktioner",
"create_unlimited_projects": "Opret så mange projekter som du har brug for.",
"never_loose_work": "Aldrig kløjes i det, vi har dig dækket ind.",
"access_projects_anywhere": "Få adgang til dine projekter hvor som helst.",
"log_in": "Log Ind",
"login": "Log Ind",
"logging_in": "Logger ind",
"forgot_your_password": "Glemt dit kodeord",
"password_reset": "Nulstil Kodeord",
"password_reset_email_sent": "Vi har sent dig en email for at fuldføre nulstillingen af dit kodeord.",
"please_enter_email": "Skriv din email adresse",
"request_password_reset": "Anmod om nulstilling af kodeord",
"reset_your_password": "Nulstil dit kodeord",
"password_has_been_reset": "Dit kodeord er blevet nulstillet",
"login_here": "Log ind her",
"set_new_password": "Sæt nyt kodeord",
"user_wants_you_to_see_project": "__username__ ønsker at du deltager i __projectname__",
"join_sl_to_view_project": "Tilmeld dig til __appName__ for at se dette projekt",
"register_to_edit_template": "Register for at redigere i __templateName__ skabelonen",
"already_have_sl_account": "Har du allerede en __appName__ bruger?",
"register": "Registrer",
"password": "Kodeord",
"registering": "Registrerer",
"planned_maintenance": "Planlagt Vedligeholdelse",
"no_planned_maintenance": "Der er lige nu ingen planlagt vedligeholdelse",
"cant_find_page": "Beklager, vi kan ikke finde siden du leder efter.",
"take_me_home": "Tag mig hjem!",
"no_preview_available": "Der er intet smugkig til rådighed.",
"no_messages": "Ingen beskeder",
"send_first_message": "Send din første besked til dine samarbejdspartnere",
"account_not_linked_to_dropbox": "Din konto er ikke forbundet til Dropbox",
"update_dropbox_settings": "Opdater Dropbox Indstillinger",
"refresh_page_after_starting_free_trial": "Opdater denne side efter du har startet din gratis prøve.",
"checking_dropbox_status": "kontrollere Dropbox status",
"dismiss": "Afvis",
"new_file": "Ny Fil",
"upload_file": "Overfør Fil",
"create": "Opret",
"creating": "Opretter",
"upload_files": "Overfør Fil(er)",
"sure_you_want_to_delete": "Er du sikker på, at du ønsker at slette følgende filer permanent?",
"common": "Almindelig",
"navigation": "Navigation",
"editing": "Redigering",
"ok": "OK",
"source": "Kilde",
"actions": "Handliger",
"copy_project": "Kopier Projekt",
"publish_as_template": "Offentliggør som Skabelon",
"sync": "Synkroniser",
"settings": "Indstillinger",
"main_document": "Hoveddokument",
"off": "Fra",
"auto_complete": "Udfyld automatisk",
"theme": "Tema",
"font_size": "Skriftsstørrelse",
"pdf_viewer": "PDF viser",
"built_in": "Indbygget",
"native": "Indbygget",
"show_hotkeys": "Vis Genveje",
"new_name": "Nyt Navn",
"copying": "Kopierer",
"copy": "Kopier",
"compiling": "Kompilerer",
"click_here_to_preview_pdf": "Klik her for at se dit arbejde som en PDF.",
"server_error": "Server Fejl",
"somthing_went_wrong_compiling": "Beklager, noget gik galt og dit projekt kunne ikke kompiléres. Vent lidt og prøv igen.",
"timedout": "Timed out",
"proj_timed_out_reason": "Din kompiléring overskred tidsgrænsen og blev standset. Dette kan skyldes en LaTeX–fejl, eller for mange komplicerede diagrammer eller billeder i høj opløsning.",
"no_errors_good_job": "Ingen fejl, godt arbejde!",
"compile_error": "Kompilérings Fejl",
"generic_failed_compile_message": "Beklager, din LaTeX kode kunne ikke kompilére. Du kan gennemgå fejlmeddelelserne herunder for detaljer, eller se den rå logfil",
"other_logs_and_files": "Andre logger og filer",
"view_raw_logs": "Vis rå logs",
"hide_raw_logs": "Skjul rå logs",
"clear_cache": "Ryd cache",
"clear_cache_explanation": "Dette vil fjerne alle gemte LaTeX filer (.aux, .bbl, etc) fra vores kompiléringsserver. Du behøver generelt ikke at gøre dette, med mindre du har problemer med referencer.",
"clear_cache_is_safe": "Det projekt vil ikke blive slettet eller ændret.",
"clearing": "Rydder",
"template_description": "Skabelons Beskrivelse",
"project_last_published_at": "Dit projekt var sidst blevet offentliggjort den",
"problem_talking_to_publishing_service": "Der er et problem med vores udgivelses tjeneste, prøv igen om nogle få minutter",
"unpublishing": "Annullerer udgivelsen",
"republish": "Genudgiv",
"publishing": "Publicering",
"share_project": "Del Projek",
"this_project_is_private": "Dette projekt er privat og er kun tilgængelig for nedenstående folk.",
"make_public": "Gør Offentlig",
"this_project_is_public": "Dette projekt er offentligt og kan redigeres af enhver med URL'en.",
"make_private": "Gør Privat",
"can_edit": "Kan Redigere",
"share_with_your_collabs": "Del med dine samarbejdspartnere",
"share": "Del",
"need_to_upgrade_for_more_collabs": "Du bliver nød til at opgradere din konto for at tilføje flere samarbejdspartnere",
"make_project_public": "Gør projekt offentligt",
"make_project_public_consequences": "Hvis du gør dit projekt offentligt så kan alle med URL'en tilgå det.",
"allow_public_editing": "Tillad offentlig redigering",
"allow_public_read_only": "Tillad offentlig skrivebeskyttet adgang",
"make_project_private": "Deaktiver link deling",
"make_project_private_consequences": "Hvis du gør dit projekt privat vil kun de personer du selv vælger få adgang til det.",
"need_to_upgrade_for_history": "Du skal opgradere din konto for at forbinde til Dropbox.",
"ask_proj_owner_to_upgrade_for_history": "Venligst foreslå projektets ejer at opgradere projektet til at bruge versions historik funktionen",
"anonymous": "Anonym",
"generic_something_went_wrong": "Beklager, noget gik galt",
"restoring": "Gendanner",
"restore_to_before_these_changes": "Gendanner til før disse ændringer",
"profile_complete_percentage": "Din profil er __percentval__% færdig",
"file_has_been_deleted": "__filename__ blev slettet",
"sure_you_want_to_restore_before": "Er du sikker på du vil gendanne <0>__filename__</0> til før ændringerne den __date__?",
"rename_project": "Omdøb projekt",
"about_to_delete_projects": "Du er på vej til at slette følgende projekter:",
"about_to_leave_projects": "Du er på vej til at forlade følgende projekter:",
"upload_zipped_project": "Upload komprimeret projekt",
"upload_a_zipped_project": "Upload et komprimeret projekt",
"your_profile": "Din profil",
"institution": "Institution",
"role": "Rolle",
"folders": "Mapper",
"disconnected": "Forbindelsen blev afbrudt",
"please_refresh": "Venligst opdater siden for at fortsætte",
"lost_connection": "Forbindelsen blev afbrudt",
"reconnecting_in_x_secs": "Genopretter om __seconds__ sekunder",
"try_now": "Prøv nu",
"reconnecting": "Genopretter",
"saving_notification_with_seconds": "Gemmer __docname__... (Ændringerne har ikke været gemt i __seconds__ sekunder)",
"help_us_spread_word": "Hjælp os med at udbrede __appName__",
"share_sl_to_get_rewards": "Del __appName__ med dine venner og kollegaer og vi belønner dig med nedenstående",
"post_on_facebook": "Del på Facebook",
"share_us_on_googleplus": "Del os på Google+",
"email_us_to_your_friends": "Send en email til dine venner omkring os",
"link_to_us": "Link til __appName__ fra din hjemmeside",
"direct_link": "Direkte link",
"sl_gives_you_free_stuff_see_progress_below": "Når nogen begynder at bruge __appName__ på grund af din anbefaling vil vi give dig nogle <strong>gratis ting</strong> som tak! Se dit fremskridt nedenunder.",
"spread_the_word_and_fill_bar": "Spred budskabet og fyld baren",
"one_free_collab": "Kun en fri samarbejdspartner",
"three_free_collab": "Tre gratis samarbejdspartnere",
"free_dropbox_and_history": "Gratis Dropbox og Historie",
"you_not_introed_anyone_to_sl": "Du har ikke introduceret nogen til __appName__. Kom igang!",
"you_introed_small_number": " Du har introduceret <0>__numberOfPeople__</0> person til __appName__. Godt arbejde, men kan du få flere?",
"you_introed_high_number": " Du har introduceret <0>__numberOfPeople__</0> personer til __appName__. Godt arbejde!",
"link_to_sl": "Link til __appName__",
"can_link_to_sl_with_html": "Du kan linke til __appName__ med følgende HTML:",
"year": "år",
"month": "måned",
"subscribe_to_this_plan": "Abonner på dette abonnement",
"your_plan": "Dit abonnement",
"your_subscription": "Dit abonnement",
"on_free_trial_expiring_at": "Du benytter pt en gratis prøve version som udløber på __expiresAt__.",
"choose_a_plan_below": "Vælg et af følgende abonnementer at abonnere på.",
"currently_subscribed_to_plan": "Du abonnerer pt. på <0>__planName__</0> abonnementet.",
"change_plan": "Ændre abonnement",
"next_payment_of_x_collectected_on_y": "Den næste betaling på <0>__paymentAmmount__</0> vil blive opkrævet <1>__collectionDate__</1>.",
"update_your_billing_details": "Opdater dine betalingsoplysninger",
"subscription_canceled_and_terminate_on_x": " Dit abonnement er blevet annulleret, og vil blive opsagt på <0>__terminateDate__</0>. Ingen yderligere betalinger vil blive opkrævet.",
"your_subscription_has_expired": "Dit abonnement er udløbet.",
"create_new_subscription": "Lav nyt abonnement",
"problem_with_subscription_contact_us": "Der er et problem med dit abonnement. Kontakt os venligst for mere information.",
"manage_group": "Administrer gruppe",
"loading_billing_form": "Henter betalingsoplysning fra",
"you_have_added_x_of_group_size_y": "Du har tilføjet <0>__addedUsersSize__</0> af <1>__groupSize__</1> tilgængelige medlemmer",
"remove_from_group": "Fjern fra gruppe",
"group_account": "Gruppekonto",
"registered": "Registreret",
"no_members": "Ingen medlemmer",
"add_more_members": "Tilføj flere medlemmer",
"add": "Tilføj",
"thanks_for_subscribing": "Tak fordi du abonnerer!",
"your_card_will_be_charged_soon": "Pengene vil blive hævet snart",
"if_you_dont_want_to_be_charged": "Hvis du ikke ønsker at betale mere ",
"add_your_first_group_member_now": "Tilføj de første medlemmer til din gruppe nu",
"thanks_for_subscribing_you_help_sl": "Tak fordi du abonnerer på __planName__ plan. Det er supporten fra folk som dig, der giver __appName__ mulighed for at vokse og blive bedre.",
"back_to_your_projects": "Tilbage til dine projekter",
"goes_straight_to_our_inboxes": "Det går direkte til begge vores indbakker",
"need_anything_contact_us_at": "Hvis der skulle være noget du har brug for, så kontakt os endeligt direkte på",
"regards": "Venligst",
"about": "Om",
"comment": "Kommentar",
"restricted_no_permission": "Beskyttet side. Beklager, men du har ikke rettigheder til at se denne side.",
"online_latex_editor": "Online LaTeX–skriveprogram",
"meet_team_behind_latex_editor": "Mød holdet bag dit ynglings online LaTeX–skriveprogram.",
"follow_me_on_twitter": "Følg mig på Twitter",
"motivation": "Motivation",
"evolved": "er vokset",
"the_easy_online_collab_latex_editor": "Den nemme, online, samarbejdende LaTeX editor",
"get_started_now": "Kom igang med det samme",
"sl_used_over_x_people_at": "__appName__ bliver brugt af mere end __numberOfUsers__ studerende og akademikere på:",
"collaboration": "Samarbejde",
"work_on_single_version": "Arbejd sammen på en enkelt version",
"view_collab_edits": "Vis samarbejdspartners ændringer ",
"ease_of_use": "Nem af bruge",
"no_complicated_latex_install": "Ingen kompliceret LaTeX installation",
"all_packages_and_templates": "Alle de pakker og <0>__templatesLink__</0> du har brug for",
"document_history": "Dokument historik",
"see_what_has_been": "Se hvad der har ",
"added": "tilføjet",
"and": "og",
"removed": "fjernet",
"restore_to_any_older_version": "Gendan en ældre version",
"work_from_anywhere": "Arbejd alle steder fra",
"acces_work_from_anywhere": "Få adgang til dine dokumenter fra hele verden",
"work_offline_and_sync_with_dropbox": "Arbejd offline og sync dine filer via Dropbox og GitHub",
"over": "over",
"view_templates": "Se skabeloner",
"nothing_to_install_ready_to_go": "Der er ingen komplicerede eller svære ting at installere, og du kan <0>__start_now__</0> , selvom du aldrig har set det før. __appName__ indeholder et komplet LaTeX miljø, der kører på vores servere.",
"start_using_latex_now": "start med at bruge LaTeX med det samme",
"get_same_latex_setup": "Med __appName__ får du de samme LaTeX indstillinger, hvor end du er. Ved at arbejde med dine kollegaer eller studerende på __appName__, er du sikker på, at I ikke får problemer med version inkonsistens eller pakke konflikter.",
"support_lots_of_features": "Vi understøtter næsten alle LaTeX funktioner, inklusiv billeder, litteraturlister, ligninger, og meget mere! Læs mere om alle de eksisterende ting du kan gøre med __appName__ i vores <0>__help_guides_link__</0>",
"latex_guides": "LaTeX guider",
"reset_password": "Nulstil dit kodeord",
"set_password": "Kodeord",
"updating_site": "Opdater side",
"bonus_please_recommend_us": "Bonus - Anbefal os",
"admin": "admin",
"subscribe": "Tilmeld",
"update_billing_details": "Opdatere betalingsdetaljer",
"group_admin": "Gruppe admin",
"all_templates": "Alle skabeloner",
"your_settings": "Dine indstillinger",
"maintenance": "Vedligeholdelse",
"to_many_login_requests_2_mins": "Der er forsøgt at logge ind på denne konto for mange gange. Vent venligst 2 minutter før du prøver at logge ind igen",
"email_or_password_wrong_try_again": "Din email eller kodeord er ikke korrekt. Venligst prøv igen",
"rate_limit_hit_wait": "Bedøm limit hit. Vent venligst før du prøver ugen",
"problem_changing_email_address": "Der var et problem med at ændre din email adresse. Prøv venligst igen om lidt. Fortsætter problemet, så kontakt os venligst",
"single_version_easy_collab_blurb": "__appName__ sørger for at du altid er opdateret med dine samarbejdspartnere og hvad de laver. Der er kun én hovedversion af hvert dokument som alle har adgang til. Det er umuligt at lave ændringer i konflikt med hovedversionen, og du behøver ikke vente på at dine kollegaer sender dig det seneste udkast for at arbejde videre.",
"can_see_collabs_type_blurb": "Hvis flere personer ønsker at arbejde på et dokument samtidig, så er det intet problem. Du kan se hvor dine kollegaer skriver direkte i skrivevinduet, og deres ændringer viser sig på din skærm med det samme.",
"work_directly_with_collabs": "Arbejd direkte med dine samarbejdspartnere",
"work_with_word_users": "Arbejd sammen med Word brugere",
"work_with_word_users_blurb": "__appName__ er så let at komme i gang med, at du vil kunne invitere dine ikke-LaTeX kollegaer til at bidrage direkte til dine LaTeX dokumenter. De vil være produktive fra dag et og lære små dele af LaTeX imens.",
"view_which_changes": "Se hvilke ændringer der har",
"sl_included_history_of_changes_blurb": "__appName__ indeholder en historik af alle dine/jeres ændringer, så du kan se præcis hvem har ændret hvad og hvornår. Dette gør det ekstremt let at holde sig ajour med eventuelle fremskridt dine samarbejdspartnere har lavet, og giver dig mulighed for at gennemgå deres seneste arbejde.",
"can_revert_back_blurb": "I et samarbejde eller alene, sker der nogle gang fejl. At vende tilbage til tidligere versioner er simpelt, hvilket fjerner risiko for at miste arbejde eller fortryde en ændring.",
"start_using_sl_now": "Begynd at bruge __appName__ nu",
"over_x_templates_easy_getting_started": "Der er flere tusind __templates__ i vores skabelongalleri, så det er rigtig let at komme igang, uanset om du skriver en artikel til et tidsskrift, en afhandling, et CV eller noget andet.",
"done": "Færdig",
"change": "Ændre",
"page_not_found": "Side ikke fundet",
"please_see_help_for_more_info": "Se vores guide for mere information",
"this_project_will_appear_in_your_dropbox_folder_at": "Projektet kan findes i din Dropbox i ",
"member_of_group_subscription": "Du er medlem af et gruppe abonnement, der er styret af __admin_email__. Kontakt venligst dem for at ændre dit abonnement.\n",
"about_henry_oswald": "er en software ingeniør, der bor i London. Han byggede den originale prototype af __appName__ og har været ansvarlig for at opbygge en stabil og skalerbar platform. Henry er en stærk fortale for Test Driven Development og sørger for, at vi holder __appName__ koden ren og let at vedligeholde.",
"about_james_allen": "har en PhD i teoretisk fysik og er passioneret omkring LaTeX. Han skabte en af de første online LaTeX–programmer, ScribTeX, og har spillet en stor rolle i udviklingen af teknologien, der gør __appName__ mulig.",
"two_strong_principles_behind_sl": "Der er to stærke ledende principper bag vores arbejde hos __appName__:",
"want_to_improve_workflow_of_as_many_people_as_possible": "Vi ønsker at forbedre så mange folks workflow som muligt",
"detail_on_improve_peoples_workflow": "LaTeX er meget svært at bruge, og samarbejdet er altid svært at koordinere. Vi mener, at vi har udviklet nogle gode løsninger til at hjælpe folk, som står over for disse problemer, og vi ønsker at være sikker på, at __appName__ er tilgængelig til så mange mennesker som muligt. Vi har prøvet at bevare et fair prisniveau, og vi har udgivet meget af __appName__ som open source, så alle kan hoste deres egen.",
"want_to_create_sustainable_lasting_legacy": "Vi ønsker at skabe et bæredygtigt og varigt resultat.",
"details_on_legacy": "Udvikling og vedligeholdelse af et produkt som __appName__ tager meget tid og arbejde, så det er vigtigt, at vi kan finde en forretningsmodel, som kan understøtte det både nu og i fremtiden. Vi ønsker ikke, at __appName__ er afhængig af ekstern funding og blive nedlagt på grund af en mislykket forretningsmodel. Jeg er glad for at kunne sige, at vi på nuværende tidspunkt kan drive en profitabel virksomhed med __appName__, og vi forventer også at kunne gøre dette i fremtiden.",
"get_in_touch": "Kom i kontakt med os",
"want_to_hear_from_you_email_us_at": "Vi vil gerne høre fra alle, som bruger __appName__, eller som ønsker at høre hvad vi laver. Du kan komme i kontakt med os på ",
"cant_find_email": "Denne email adresse er desværre ikke registreret.",
"plans_amper_pricing": "Abonnomenter og priser",
"documentation": "Dokumentation",
"account": "Konto",
"subscription": "Abonnoment",
"log_out": "Log ud",
"en": "Engelsk",
"pt": "Portugisisk",
"es": "Spansk",
"fr": "Fransk",
"de": "Tysk",
"it": "Italiensk",
"da": "Dansk",
"sv": "Svensk",
"no": "Norsk",
"nl": "Hollandsk",
"pl": "Polsk",
"ru": "Russisk",
"uk": "Ukrainsk",
"ro": "Romænsk",
"click_here_to_view_sl_in_lng": "Klik her for at bruge __appName__ på <0>__lngName__</0>",
"language": "Sprog",
"upload": "Upload",
"menu": "Menu",
"full_screen": "Fuld skærm",
"logs_and_output_files": "Log og output filer",
"download_pdf": "Hent PDF",
"split_screen": "Skærmopdeling",
"clear_cached_files": "Ryd cachede filer",
"go_to_code_location_in_pdf": "Gå til kodes placering i PDF",
"please_compile_pdf_before_download": "Kompilér venligst dit projekt før du downloader PDF'en",
"remove_collaborator": "Fjern kollaborator",
"add_to_folders": "Tilføj til mapper",
"download_zip_file": "Hent -zip fil",
"price": "Pris",
"close": "Luk",
"keybindings": "Genvejstaster",
"restricted": "Begrænset",
"start_x_day_trial": "Start din __len__-dages prøvetid i dag!",
"buy_now": "Køb nu!",
"cs": "Tjekkisk",
"view_all": "Se alt",
"terms": "Vilkår",
"privacy": "Privathed",
"contact": "Kontakt",
"change_to_this_plan": "Ændring til dette abonnoment",
"processing": "processere",
"sure_you_want_to_change_plan": "Er du sikker på du vil skifte abonnoment til <0>__planName__</0>?",
"move_to_annual_billing": "Skift til årlig betaling",
"annual_billing_enabled": "Årlig betaling aktiveret",
"move_to_annual_billing_now": "Skift til årlig betaling nu",
"change_to_annual_billing_and_save": "Spar <0>__percentage__</0> ved årlig betaling. Hvis du skifter nu sparer du <1>__yearlySaving__</1> pr. år.",
"missing_template_question": "Manglende skabelon?",
"tell_us_about_the_template": "Hvis vi mangler en skabelon kan du enten: Sende os en kopi af skabelonen, en __appName__ url til skabelonen, eller fortælle os hvor vi kan finde den. Husk også at tilføje en lille beskrivelse af skabelonen.",
"email_us": "Email os",
"this_project_is_public_read_only": "Dette projekt er offentligt og kan ses, men ikke redigeres, af alle med linket",
"tr": "Tyrkis",
"select_files": "Vælg fil(er)",
"drag_files": "Træk fil(er)",
"upload_failed_sorry": "Upload mislykkes. Undskyld :(",
"inserting_files": "Indsætter fil...",
"password_reset_token_expired": "Din mulighed for nulstilling af din adgangskode er udløbet. Anmod om en ny nulstilling af adgangskode og følg linket i din mail.",
"merge_project_with_github": "Flet projekt sammen med GitHub",
"pull_github_changes_into_sharelatex": "Pull GitHub ændringer ind i __appName__",
"push_sharelatex_changes_to_github": "Push __appName__ ændringer til GitHub",
"features": "Funktioner",
"commit": "Commit",
"commiting": "Committer",
"importing_and_merging_changes_in_github": "Importerer og sammenfletter ændringer i GitHub",
"upgrade_for_faster_compiles": "Opgrader for hurtigere kompiléring og for at få forlænget tidsgrænsen",
"free_accounts_have_timeout_upgrade_to_increase": "Gratis konti har en tidsgrænse på ét minut, hvorimod opgraderede konti har en tidsgrænse på fire minutter.",
"learn_how_to_make_documents_compile_quickly": "Lær hvordan du undgår at overskride tidsgrænsen på kompiléring",
"zh-CN": "Kinesisk",
"cn": "Kinesisk (forenklet)",
"sync_to_github": "Synkroniser til GitHub",
"sync_to_dropbox_and_github": "Synkroniser til Dropbox og GitHub",
"project_too_large": "Projekt er for stort",
"project_too_large_please_reduce": "Dette projekt har for meget redigérbar tekst, prøv venligst at reducere det. De største filer er:",
"please_ask_the_project_owner_to_link_to_github": "Vær venlig at og spørg projekt ejeren om at linke dette projekt til en GitHub arkiv",
"go_to_pdf_location_in_code": "Gå til PDF placering i kode",
"ko": "Koreansk",
"ja": "Japansk",
"about_brian_gough": "er en software udvikler og tidligere høj energis fysiker ved Fermilab og Los Alamos. I mange år udgav han gratise software manualer kommercielt ved brug af TeX og LaTeX, og var også vedligeholderen af GNU Videnskabelige Bibliotek",
"first_few_days_free": "Første __ trailLen__ dage gratis",
"every": "per",
"credit_card": "Kredit kort",
"credit_card_number": "Kort nummer",
"invalid": "Ugyldigt",
"expiry": "Udløbsdato",
"january": "Januar",
"february": "Februar",
"march": "Marts",
"april": "April",
"may": "Maj",
"june": "Juni",
"july": "Juli",
"august": "August",
"september": "September",
"october": "Oktober",
"november": "November",
"december": "December",
"zip_post_code": "Postnummer",
"city": "By",
"address": "Adresse",
"coupon_code": "Rabatkode",
"country": "Land",
"billing_address": "Faktureringsadresse",
"upgrade_now": "Opgrader nu",
"state": "Stat",
"vat_number": "CVR nummer",
"you_have_joined": "Du har forbundet dig __groupName__",
"claim_premium_account": "Du har indløst din Premium kontro fra __groupName__.",
"you_are_invited_to_group": "Du er inviteret til at forbinde til __groupName__",
"you_can_claim_premium_account": "Du kan indløse din Premium kontro fra __groupName__ ved at verificere din email",
"not_now": "Ikke nu",
"verify_email_join_group": "Verificer din email og forbind gruppen",
"check_email_to_complete_group": "Tjek venligst din email for endeligt at forbinde dig til gruppen",
"verify_email_address": "verificer email adresse",
"group_provides_you_with_premium_account": "__groupName__ giver dig en Premium konto. Verificer din email adresse for at opgradere din konto.",
"check_email_to_complete_the_upgrade": "Tjek venligst din email for at færdiggøre opgraderingen",
"email_link_expired": "Linket tilsendt din email er udløbet. Du bedes anmode om et nyt.",
"services": "Tjenester",
"about_shane_kilkelly": "er en software udvikler, bosat i Edinburgh. Shane er en stærk fortaler for funktionel programmering, test drevet udvikling og sætter en ære i at bygge kvalitets software.",
"this_is_your_template": "Dette er din skabelon fra dit projekt",
"links": "Links",
"account_settings": "Konto-indstillinger",
"search_projects": "Søg efter projekter",
"clone_project": "Dupliker Projekt",
"delete_project": "Slet Projekt",
"download_zip": "Hent Zip",
"new_project": "Nyt Projekt",
"blank_project": "Tomt Projekt",
"example_project": "Eksempel Projekt",
"from_template": "Fra Skabelon",
"cv_or_resume": "CV",
"cover_letter": "Følge Brev",
"journal_article": "Avisartikel",
"presentation": "Præsentation",
"thesis": "Speciale",
"bibliographies": "Bibliografier",
"terms_of_service": "Servicevilkår",
"privacy_policy": "Fortrolighedspolitik",
"plans_and_pricing": "Abonnementer og priser",
"university_licences": "Universitets licenser",
"security": "Sikkerhed",
"contact_us": "Kontakt Os",
"thanks": "Tak",
"blog": "Blog",
"latex_editor": "LaTeX–skriveprogram",
"get_free_stuff": "Få gratis ting",
"chat": "Chat",
"your_message": "Din besked",
"loading": "Indlæser",
"connecting": "Forbinder",
"recompile": "Genkompilér",
"download": "Hent",
"email": "Email",
"owner": "Ejer",
"read_and_write": "Læs og Skriv",
"read_only": "Skrivebeskyttet",
"publish": "Publicer",
"view_in_template_gallery": "Se den i skabelon galleriet.",
"unpublish": "Træk tilbage",
"hotkeys": "Genveje",
"saving": "Gemmer",
"cancel": "Annuller",
"project_name": "Projektnavn",
"root_document": "Hoveddokument",
"spell_check": "Stavekontrol",
"compiler": "Kompilér",
"private": "Privat",
"public": "Offentlig",
"delete_forever": "Slet for evigt",
"support_and_feedback": "Hjælp og tilbagemeldinger",
"help": "Hjælp",
"latex_templates": "LaTeX Skabeloner",
"info": "Info",
"latex_help_guide": "LaTeX hjælpeguide",
"choose_your_plan": "Vælg dit abonnoment",
"indvidual_plans": "Individuelle abonnomenter",
"free_forever": "Gratis for evigt",
"low_priority_compile": "Lav prioritets kompiléring",
"unlimited_projects": "Ubegrænset antal projekter",
"unlimited_compiles": "Ubegrænset antal kompileringer",
"full_history_of_changes": "Fuld ændringshistorik",
"highest_priority_compiling": "Højeste prioritets kompiléring",
"dropbox_sync": "Dropbox synkronisering",
"beta": "Beta",
"sign_up_now": "Tilmeld nu",
"annual": "Årlig",
"half_price_student": "Studenterabonnomenter til halv pris",
"about_us": "Om os",
"loading_recent_github_commits": "Indlæs nylige commits",
"no_new_commits_in_github": "Ingen nye commits i GitHib siden sidste sammenfletning",
"dropbox_sync_description": "Hold dine __appName__ projekter synkroniseret med din Dropbox. Ændringer i __appName__ sendes automatisk til din Dropbox, og omvendt.",
"github_sync_description": "Med GitHub synkronisering kan du linke dine __appName__ projekter til et GitHub lager. Opret nye commits fra __appName__, og flet sammen med commits, som er lavet offline eller i GitHub.",
"github_import_description": "Med GitHub synkronisering kan du importere dine __appName__ projekter til et GitHub lager. Opret nye commits fra __appName__, og flet sammen med commits, som er lavet offline eller i GitHub.",
"link_to_github_description": "Du skal godkende __appName__ for at få adgang til din GitHub konto for at give os mulighed for at synkronisere dine projekter.",
"unlink": "Fjern link",
"unlink_github_warning": "Eventuelle projekter, som du har synkroniseret med GitHub, afbrydes og synkroniseres ikke længere med GitHub. Er du sikker på du vil fjerne linket til din GitHub konto?",
"github_account_successfully_linked": "GitHub konto er nu linket!",
"github_successfully_linked_description": "Vi har linket din GitHub konto til __appName__. Du kan nu eksportere dine __appName__ projekter til GitHub, eller importere projekter fra et GitHub lager.",
"import_from_github": "Importer fra GitHub",
"github_sync_error": "Der var desværre en fejl i kommunikationen til vores GitHub server. Prøv igen om et øjeblik.",
"loading_github_repositories": "Indlæser dit GitHub lager",
"select_github_repository": "Vælg et GitHub lager som skal importeres til __appName__.",
"import_to_sharelatex": "Importer til __appName__",
"importing": "Importerer",
"github_sync": "GitHub synkronisering",
"checking_project_github_status": "Tjekker projektstatus i GitHub",
"account_not_linked_to_github": "Din konto er ikke linket til GitHub",
"project_not_linked_to_github": "Dette projekt er ikke linket til et GitHub lager. Du kan skabe et lager for det på GitHub:",
"create_project_in_github": "Skab et GitHub lager",
"project_synced_with_git_repo_at": "Dette projekt er synkroniseret med GitHub lageret på",
"recent_commits_in_github": "Seneste commits i GitHub",
"sync_project_to_github": "Synkroniser projekt til GitHub",
"sync_project_to_github_explanation": "Ændringer som du har lavet i __appName__ vil blive committed og flettet sammen med opdateringer i GitHub",
"github_merge_failed": "Dine ændringer i __appName__ og GitHub kunne ikke automatisk ‘merge’-es. ‘Merge’ manuelt <0>__sharelatex_branch__</0> grenen ind i <1>__master_branch__</1> grenen i git. Tryk nedenfor for at forsætte, efter at du manuelt har ‘merge’-et dem.",
"continue_github_merge": "I have flettet manuelt. Fortsæt",
"export_project_to_github": "Eksporter projekt til GitHub",
"github_validation_check": "Kontroller venligst at lagernavnet er valid, og at du har tilladelse til at lave et lager.",
"repository_name": "Lagernavn",
"optional": "Valgfrit",
"github_public_description": "Alle kan se dette lager. Du kan vælge hvem der kan comitte.",
"github_commit_message_placeholder": "Commit besked for ændringer i __appName__...",
"merge": "Flet",
"merging": "Fletter",
"github_account_is_linked": "Din GitHub konto er nu linket.",
"unlink_github": "Fjern link til din GitHub konto",
"link_to_github": "Link til din GitHub konto",
"github_integration": "Github integration",
"github_is_premium": "GitHub synkronisering er en betalt funktion",
"please_change_primary_to_remove": "Du må ændre din primære e–mailadresse for at kunne fjerne",
"thank_you": "Tak!"
}
| overleaf/web/locales/da.json/0 | {
"file_path": "overleaf/web/locales/da.json",
"repo_id": "overleaf",
"token_count": 31475
} | 555 |
{
"chat_error": "无法加载聊天消息,请重试。",
"reconnect": "重试",
"no_pdf_error_title": "无 PDF",
"no_pdf_error_explanation": "此编译未生成 PDF。 在以下情况下可能会发生这种情况:",
"no_pdf_error_reason_unrecoverable_error": "存在不可恢复的 LaTeX 错误。 如果在下面或原始日志中存在 LaTeX 错误,请尝试修复它们并重新编译。",
"no_pdf_error_reason_no_content": "<code>document</code> 环境不包含任何内容。 如果为空,请添加一些内容并重新编译。",
"no_pdf_error_reason_output_pdf_already_exists": "该项目包含一个名为 <code>output.pdf</code> 的文件。 如果该文件存在,请重命名并重新编译。",
"logs_pane_info_message": "我们正在测试一个新的日志窗格",
"logs_pane_info_message_popup": "我们正在测试一个新的日志窗格。单击此处提供反馈。",
"github_symlink_error": "您的Github存储库包含符号链接文件,Overleaf 暂时不支持这些文件。请删除这些文件并重试。",
"address_line_1": "地址",
"address_line_2": "地址(第2行,可选)",
"postal_code": "邮政编码",
"reload_editor": "重新加载编辑器",
"compile_error_description": "由于出现错误,此项目未编译成功",
"validation_issue_description": "由于验证问题,此项目未编译",
"compile_error_entry_description": "一个阻止此项目编译的错误",
"validation_issue_entry_description": "阻止此项目编译的验证问题",
"github_file_name_error": "您的项目包含文件名无效的文件。请检查您的存储库并重试。",
"raw_logs_description": "来自 LaTeX 编译器的原始日志",
"raw_logs": "原始日志",
"first_error_popup_label": "此项目有错误。这是第一个错误。",
"dismiss_error_popup": "忽略第一个错误提示",
"go_to_error_location": "转到错误位置",
"view_error": "查看错误",
"view_error_plural": "查看全部错误",
"log_entry_description": "级别为__level__的日志条目",
"navigate_log_source": "导航到源代码中的日志位置:__location__",
"other_output_files": "下载其他输出文件",
"refresh": "刷新",
"toggle_output_files_list": "切换输出文件列表",
"n_warnings": "__count__ 个警告",
"n_warnings_plural": "__count__ 个警告",
"n_errors": "__count__ 个错误",
"n_errors_plural": "__count__个错误",
"toggle_compile_options_menu": "切换编译选项菜单",
"view_pdf": "查看 PDF",
"your_project_has_an_error": "本项目有错误",
"your_project_has_an_error_plural": "本项目有错误",
"view_warning": "查看警告",
"view_warning_plural": "查看警告",
"view_logs": "查看日志",
"recompile_from_scratch": "从头开始重新编译",
"tagline_free": "非常适合入门",
"also_provides_free_plan": "__appName__ 也提供免费计划 -- 只需 <0>在此处注册</0> 即可开始。",
"compile_timeout": "编译超时(分钟)",
"collabs_per_proj_single": "__collabcount__ 个合作者每个项目",
"premium_features": "高级功能",
"special_price_student": "特价学生计划",
"hide_outline": "隐藏文件大纲",
"show_outline": "显示文件大纲",
"expand": "展开",
"collapse": "合上",
"file_outline": "文件大纲",
"we_cant_find_any_sections_or_subsections_in_this_file": "在此文件中找不到任何 sections 或 subsections",
"find_out_more_about_the_file_outline": "了解有关文件大纲的更多信息",
"invalid_institutional_email": "您机构的SSO服务返回的您的电子邮件地址是 __email__,但该域名并没有在我们这里注册。您可以通过您的机构将您的主要电子邮件地址更改为您所在机构域的电子邮件地址。如果您有任何问题,请联系您的IT部门。",
"wed_love_you_to_stay": "我们希望你留下来",
"yes_move_me_to_student_plan": "是的,把我转到学生计划",
"last_login": "最后登录",
"thank_you_for_being_part_of_our_beta_program": "感谢您参与我们的测试计划,您可以尽早体验新功能,并帮助我们更好地了解您的需求",
"you_will_be_able_to_contact_us_any_time_to_share_your_feedback": "您可以随时联系我们分享您的反馈",
"we_may_also_contact_you_from_time_to_time_by_email_with_a_survey": "我们也可能通过电子邮件与您联系,进行调查,或询问您是否愿意参与其他用户研究计划",
"you_can_opt_in_and_out_of_the_program_at_any_time_on_this_page": "您可以随时在此页面上选择加入或退出该计划",
"give_feedback": "给予反馈",
"beta_feature_badge": "Beta功能徽章",
"invalid_filename": "上传失败:检查文件名是否包含特殊字符、尾随/前导空格或超过 __nameLimit__ 个字符",
"clsi_unavailable": "抱歉,项目的编译服务器暂时不可用。请稍后再试。",
"x_price_per_month": "每月 <0>__price__</0>",
"x_price_per_year": "每年 <0>__price__</0>",
"x_price_for_first_month": "首月 <0>__price__</0>",
"x_price_for_first_year": "首年 <0>__price__</0>",
"x_price_per_month_tax": "每月 <0>__total__</0> (__subtotal__ + __tax__ tax)",
"x_price_per_year_tax": "每年 <0>__total__</0> (__subtotal__ + __tax__ tax)",
"x_price_for_first_month_tax": "首月 <0>__total__</0> (__subtotal__ + __tax__ tax)",
"x_price_for_first_year_tax": "首年 <0>__total__</0> (__subtotal__ + __tax__ tax)",
"normally_x_price_per_month": "通常每月__price__",
"normally_x_price_per_year": "通常每年__price__",
"then_x_price_per_month": "接着每月__price__",
"then_x_price_per_year": "接着每年__price__",
"for_your_first": "你的第一",
"sso_not_linked": "您尚未将帐户绑定到 __provider__。请以另一种方式登录到您的帐户,并通过您的帐户设置绑定您的 __provider__ 帐户。",
"template_gallery": "模板库",
"template_not_found_description": "这种从模板创建项目的方法已被删除。请访问我们的模板库以查找更多模板。",
"dropbox_checking_sync_status": "正在检查 Dropbox 集成状态",
"dropbox_sync_in": "更新 Overleaf",
"dropbox_sync_out": "更新 Dropbox",
"dropbox_sync_both": "更新 Overleaf 和 Dropbox",
"dropbox_synced": "Overleaf 和 Dropbox 是最新的",
"dropbox_sync_status_error": "集成 Dropbox 时出现错误",
"requesting_password_reset": "请求密码重置",
"tex_live_version": "TeX Live 版本",
"email_does_not_belong_to_university": "我们不认为该域与您的大学有关联。请与我们联系添加从属关系。",
"company_name": "公司名称",
"add_company_details": "添加公司详细信息",
"github_timeout_error": "将 Overleaf 项目与 Github 同步时超时。这可能是由于项目的总体大小,或者要同步的文件/更改的数量太大。",
"github_large_files_error": "合并失败:您的 Github 存储库包含超过 50mb 文件大小限制的文件 ",
"no_history_available": "这个项目还没有任何历史。请对项目进行一些更改,然后重试。",
"project_approaching_file_limit": "此项目已接近文件限制",
"recurly_email_updated": "您的帐单邮件地址已成功更新",
"recurly_email_update_needed": "您当前的帐单邮件地址为 <0>__recurlyEmail__</0>。如果需要,您可以将帐单地址修改为 <1>__userEmail__</1>。",
"project_has_too_many_files": "此项目已达到 2000 个文件限制",
"processing_your_request": "我们正在处理您的请求,请稍候。",
"github_repository_diverged": "已强制推送到链接存储库的主分支。在强制推送之后拉取 GitHub 更改可能会导致 Overleaf 和 GitHub 不同步。您可能需要在拉取后推送更改以恢复同步。",
"unlink_github_repository": "取消链接 Github 存储库",
"unlinking": "取消链接",
"github_no_master_branch_error": "无法导入此存储库,因为它缺少主分支。请确保项目有一个主分支",
"confirmation_token_invalid": "抱歉,您的确认令牌无效或已过期。请请求新的电子邮件确认链接。",
"confirmation_link_broken": "抱歉,您的确认链接有问题。请尝试复制并粘贴邮件底部的链接。",
"duplicate_file": "重复文件",
"file_already_exists_in_this_location": "此位置中已存在名为 <0>__fileName__</0> 的项。如果要移动此文件,请重命名或删除冲突文件,然后重试。",
"blocked_filename": "此文件名被阻止。",
"group_full": "此组已满",
"no_selection_select_file": "当前未选择任何文件。请从文件树中选择一个文件。",
"no_selection_create_new_file": "您的项目当前为空。请创建一个新文件。",
"files_selected": "个文件被选中。",
"home": "主页",
"this_action_cannot_be_undone": "此操作无法撤消。",
"dropbox_email_not_verified": "我们无法从您的 Dropbox 帐户检索更新。Dropbox 报告您的电子邮件地址未经验证。请在 Dropbox 帐户中验证您的电子邮件地址以解决此问题。",
"portal_add_affiliation_to_join": "您似乎已经登录到 __appName__!如果你有一封 __portalTitle__ 邮件,现在就可以添加了。",
"token_access_success": "已授予访问权限",
"token_access_failure": "无法授予访问权限;联系项目负责人寻求帮助",
"trashed_projects": "已删除项目",
"trash": "回收站",
"untrash": "恢复",
"delete_and_leave": "删除/保留",
"trash_projects": "已删除项目",
"about_to_trash_projects": "您将要把以下项目移至回收站:",
"archived_projects_info_note": "存档现在以每个用户为单位工作。您决定存档的项目将只为您而不是您的合作者存档。",
"trashed_projects_info_note": "对于您想要删除的项目,Overleaf 现在支持垃圾箱。 删除项目不会影响您的合作者。",
"archiving_projects_wont_affect_collaborators": "归档项目不会影响您的合作者。",
"trashing_projects_wont_affect_collaborators": "删除项目不会影响你的合作者。",
"register_intercept_sso": "登录后,您可以从“帐户设置”页绑定您的 __authProviderName__ 帐户。",
"continue_to": "返回 __appName__",
"project_ownership_transfer_confirmation_1": "是否确定要将 <0>__user__</0> 设为 <1>__project__</1> 的所有者?",
"project_ownership_transfer_confirmation_2": "此操作无法撤消。新所有者将收到通知,并可以更改项目访问权限设置(包括删除您自己的访问权限)。",
"change_owner": "更改所有者",
"change_project_owner": "变更项目所有者",
"faq_pay_by_invoice_answer": "是的,如果您想购买团体帐户或站点许可证,并且希望通过发票付款,或者需要发出采购订单,<0>请告诉我们</0>。\n对于个人账户或按月计费的账户,我们只接受通过信用卡、借记卡或贝宝的在线支付。",
"password_too_long_please_reset": "超过最大密码长度限制。请重新设置密码。",
"view_other_options_to_log_in": "查看其他登录选项",
"we_logged_you_in": "我们已为您登录。",
"will_need_to_log_out_from_and_in_with": "您需要从 <b>__email1__</b> 帐户<b>注销</b>,然后使用 <b>__email2__</b> 登录。",
"resubmit_institutional_email": "请重新提交您的机构电子邮件。",
"opted_out_linking": "您已选择取消将您的 <b>__email__</b> <b>__appName__</b> 帐户绑定到您的机构帐户。",
"please_link_to_institution_account": "请将您的 <b>__email__</b> <b>__appName__</b> 账户绑定到您的 <b>__institutionName__</b> 帐户。",
"register_with_another_email": "使用另一个邮件地址<a href=\"__link__\">注册 __appName__</a>",
"register_with_email_provided": "使用您提供的邮件地址和密码,<a href=\"__link__\">注册 __appName__</a>。",
"security_reasons_linked_accts": "出于安全原因,由于您的机构电子邮件已与 <b>__email__</b> <b>__appName__</b> 账户关联,我们只能允许帐户与该特定帐户链接。",
"this_grants_access_to_features": "这将授予您访问 <b>__appName__</b> <b>__featureType__</b> 特性。",
"to_add_email_accounts_need_to_be_linked": "要添加此电子邮件,需要链接您的 <b>__appName__</b> 账户和 <b>__institutionName__</b> 帐户。",
"tried_to_log_in_with_email": "您已尝试使用 <b>__email__</b> 登录。",
"tried_to_register_with_email": "您已尝试使用 <b>__email__</b> 注册,但它已在 <b>__appName__</b> 注册为机构账户。",
"log_in_with_email": "使用 __email__ 登录",
"log_in_with_existing_institution_email": "请使用您现有的 <b>__appName__</b> 帐户登录,以便将您的<b>__appName__</b>和<b>__institutionName__</b> 机构帐户关联起来。",
"log_out_from": "从 __email__ 注销",
"logged_in_with_acct_that_cannot_be_linked": "您使用无法链接到您的机构帐户的<b>__appName__</b>帐户登录。",
"logged_in_with_email": "您当前使用 <b>__email__</b> 登录到<b>__appName__</b>。",
"looks_like_logged_in_with_email": "您似乎已经使用 <b>__email__</b> 登录到 <b>__appName__</b>。",
"make_primary_to_log_in_through_institution": "将您的 <b>__email__</b> 设为主要电子邮件,以便通过您的机构门户登录。 ",
"make_primary_which_will_allow_log_in_through_institution": "将其设为您的<b>__appName__ 主要</b>电子邮件将允许您通过机构门户登录。",
"need_to_do_this_to_access_license": "您需要这样做,才能从 <b>__institutionName__</b> 站点许可证中获得好处。",
"institutional_login_not_supported": "您的大学还不支持<b>机构登录</b>,但您仍然可以通过机构电子邮件注册。",
"institutional_login_unknown": "抱歉,我们不知道是哪个机构发的那个电子邮件地址。您可以浏览我们的\n<a href=\"__link__\">机构列表</a> 找到您的机构,也可以在此处使用您的电子邮件地址和密码注册。",
"link_account": "链接帐户",
"link_accounts": "链接帐户",
"link_accounts_and_add_email": "链接帐户并添加电子邮件",
"link_your_accounts": "链接您的帐户",
"log_in_and_link": "登录并链接",
"log_in_and_link_accounts": "登录并链接帐户",
"log_in_first_to_proceed": "您需要先<b>登录</b>才能继续。",
"log_in_through_institution": "通过您的机构登录",
"if_have_existing_can_link": "如果您在另一封电子邮件中有一个现有的 <b>__appName__</b> 帐户,您可以通过单击 <b>__clickText__</b> 将其链接到您的 <b>__institutionName__</b> 账户。",
"if_owner_can_link": "如果您在<b>__appName__</b>拥有账户<b>__email__</b>,您可以将其链接到您的 <b>__institutionName__</b> 机构帐户。",
"ignore_and_continue_institution_linking": "您也可以忽略此项,然后<a href=\"__link__\">继续在 __appName__ 上使用您的 <b>__email__</b> 帐户</a>。",
"in_order_to_match_institutional_metadata": "为了匹配您的机构元数据,我们使用电子邮件 <b>__email__</b> 链接了您的帐户。",
"in_order_to_match_institutional_metadata_associated": "为了匹配您的机构元数据,您的帐户与电子邮件 <b>__email__</b> 相关联。",
"institution_account_tried_to_add_already_registered": "您试图添加的电子邮件/机构帐户<b>已在__appName__注册</b>。",
"institution_account_tried_to_add_already_linked": "此机构已通过另一个电子邮件地址与您的帐户<b>链接</b>。",
"institution_account_tried_to_add_not_affiliated": "此电子邮件已与您的帐户<b>关联</b>,但未与此机构关联。",
"institution_account_tried_to_add_affiliated_with_another_institution": "此电子邮件<b>已与您的帐户关联</b>,但隶属于其他机构。",
"institution_acct_successfully_linked": "您的 <b>__appName__</b>帐户已成功链接到您的 <b>__institutionName__</b> 机构帐户。",
"institution_account_tried_to_confirm_saml": "此电子邮件无法确认。请从您的帐户中删除电子邮件,然后再次尝试添加。",
"institution_email_new_to_app": "您的 <b>__institutionName__</b> 电子邮件地址 (<b>__email__</b>) 对__appName__ 是新的。",
"institutional": "机构",
"doing_this_allow_log_in_through_institution": "这样做将允许您通过机构门户登录到 <b>__appName__</b> 。",
"doing_this_will_verify_affiliation_and_allow_log_in": "这样做将验证您与<b>__institutionName__</b>的关系,并将允许您通过您的机构登录到 <b>__appName__</b> 。",
"email_already_associated_with": "<b>__email1__</b>已与<b>__email2__</b> <b>__appName__</b>帐户相关联。",
"enter_institution_email_to_log_in": "输入您的机构电子邮件以通过您的机构登录。",
"find_out_more_about_institution_login": "了解有关机构登录的更多信息",
"get_in_touch_having_problems": "如果遇到问题,请<a href=\"__link__\">与支持部门联系</a>",
"go_back_and_link_accts": "<a href=\"__link__\">返回</a>并链接您的帐户",
"go_back_and_log_in": "<a href=\"__link__\">返回</a>并再次登录",
"go_back_to_institution": "回到你的机构",
"can_link_institution_email_by_clicking": "您可以通过单击 <b>__clickText__</b> 将您的 <b>__email__</b> <b>__appName__</b> 账户链接到您的 <b>__institutionName__</b> 帐户。",
"can_link_institution_email_to_login": "您可以将您的 <b>__email__</b> <b>__appName__</b> 账户链接到你的 <b>__institutionName__</b> 账户,这将允许您通过机构门户登录到<b>__appName__</b> 。",
"can_link_your_institution_acct": "现在,您可以将您的 <b>link</b> your <b>__appName__</b> 帐户链接到您的 <b>__institutionName__</b> 机构帐户。",
"can_now_link_to_institution_acct": "您可以将您的 <b>__email__</b> <b>__appName__</b> 账户链接到您的<b>__institutionName__</b> 机构账户。",
"click_link_to_proceed": "单击下面的 <b>__clickText__</b> 继续。",
"continue_with_email": "使用你的<b> __email__ </b>账户<a href=\"__link__\">继续访问 __appName__ </a>",
"create_new_account": "创建新帐户",
"do_not_have_acct_or_do_not_want_to_link": "如果您没有 <b>__appName__</b> 帐户,或者您不想链接到您的 <b>__institutionName__</b> 帐户,请单击 <b>__clickText__</b>。",
"do_not_link_accounts": "不链接帐户",
"account_has_been_link_to_institution_account": "您在 __appName__ 上的 <b>__email__</b> 帐户已链接到您的 <b>__institutionName__</b> 机构帐户。",
"account_linking": "帐户链接",
"account_with_email_exists": "看起来在 <b>__appName__</b> 已经存在一个电子邮件为<b>__email__</b>的账户。",
"acct_linked_to_institution_acct": "您可以通过 <b>__institutionName__</b> 机构<b>登录</b> Overleaf。",
"alternatively_create_new_institution_account": "或者,您可以通过单击<b>__clickText__</b>来使用机构电子邮件(<b>__email__</b>)创建一个<b>新帐户</b>。",
"as_a_member_of_sso": "作为 <b>__institutionName__</b> 的成员,您可以通过您的机构门户网站登录到 <b>__appName__</b> 。",
"as_a_member_of_sso_required": "作为 <b>__institutionName__</b> 的成员,您必须通过您的机构门户网站登录到 <b>__appName__</b> 。",
"can_link_institution_email_acct_to_institution_acct": "您现在可以将您的 <b>__appName__</b> 账户 <b>__email__</b> 与您的 <b>__institutionName__</b> 机构账户关联。",
"can_link_institution_email_acct_to_institution_acct_alt": "您可以将您的 <b>__appName__</b> 账户 <b>__email__</b> 与您的 <b>__institutionName__</b> 机构账户关联。",
"user_deletion_error": "抱歉,删除您的帐户时出错。请稍后再试。",
"card_must_be_authenticated_by_3dsecure": "在继续之前,您的卡必须通过3D安全验证",
"view_your_invoices": "查看您的账单",
"payment_provider_unreachable_error": "抱歉,与我们的支付提供商交谈时出错。请稍后再试。\n如果您在浏览器中使用任何广告或脚本阻止扩展,则可能需要暂时禁用它们。",
"dropbox_unlinked_because_access_denied": "您的Dropbox帐户已取消链接,因为Dropbox服务拒绝了您存储的凭据。请重新链接您的Dropbox帐户,以便在Overleaf继续使用。",
"dropbox_unlinked_because_full": "您的Dropbox帐户已满,因此已取消链接,我们无法再向其发送更新。请释放一些空间并重新链接您的Dropbox帐户,以便在Overleaf继续使用。",
"upgrade_for_longer_compiles": "升级以增加超时限制。",
"ask_proj_owner_to_upgrade_for_longer_compiles": "请要求项目所有者升级以增加超时限制。",
"plus_upgraded_accounts_receive": "用你的高级账户来增加超时限制",
"sso_account_already_linked": "帐户已链接到另一个__appName__用户",
"subscription_admins_cannot_be_deleted": "订阅时不能删除您的帐户。请取消订阅并重试。如果您一直看到此消息,请与我们联系。",
"delete_acct_no_existing_pw": "在删除您的帐户之前,请使用密码重置表单设置密码",
"empty_zip_file": "Zip不包含任何文件",
"you_can_now_login_through_overleaf_sl": "您现在可以通过Overleaf登录到您的ShareLaTeX帐户。",
"find_out_more_nt": "了解更多。",
"register_error": "注册错误",
"login_error": "登录错误",
"sso_link_error": "链接SSO帐户时出错",
"more_info": "更多信息",
"synctex_failed": "找不到相应的源文件",
"linked_collabratec_description": "使用Collabratec管理您的__appName__项目。",
"reset_from_sl": "请在ShareLaTeX中重置您的密码,并在那里登录以将您的帐户移到Overleaf",
"dropbox_already_linked_error": "您的Dropbox帐户无法链接,因为它已与另一个Overleaf帐户链接。",
"github_too_many_files_error": "无法导入此存储库,因为它超过了允许的最大文件数",
"linked_accounts": "关联账户",
"linked_accounts_explained": "您可以将您的__appName__帐户与其他服务链接,以启用下面描述的功能",
"oauth_orcid_description": " <a href=\"__link__\">通过将您的 ORCID iD 链接到您的__appName__帐户</a>,安全地建立您的身份。提交给参与发布者的文件将自动包含您的ORCID iD,以改进工作流和可见性。 ",
"no_existing_password": "请使用密码重置表单设置密码",
" to_reactivate_your_subscription_go_to": "要重新激活订阅,请转到",
"subscription_canceled": "订阅已取消",
"coupons_not_included": "这不包括您当前的折扣,它将在您下次付款前自动应用",
"email_already_registered_secondary": "此电子邮件已注册为辅助电子邮件",
"secondary_email_password_reset": "该电子邮件已注册为辅助电子邮件。请输入您帐户的主要电子邮件。",
"if_registered_email_sent": "如果你有账户,我们会给你发邮件。",
"reconfirm": "再次确认",
"request_reconfirmation_email": "请求再确认电子邮件",
"reconfirm_explained": "我们需要再次确认你的帐户。请通过以下表格申请密码重置链接,以重新确认您的帐户。如果您在重新确认您的帐户时有任何问题,请联系我们",
"upload_failed": "上传失败",
"file_too_large": "文件太大",
"zip_contents_too_large": "压缩包太大",
"invalid_zip_file": "zip文件无效",
"make_primary": "设为主要",
"make_email_primary_description": "将此作为主要电子邮件,用于登录",
"github_sync_repository_not_found_description": "链接的存储库已被删除,或者您不再有权访问它。通过克隆项目并使用“Github”菜单项,可以设置与新存储库的同步。您还可以取消存储库与此项目的链接。",
"unarchive": "恢复",
"cant_see_what_youre_looking_for_question": "找不到?",
"something_went_wrong_canceling_your_subscription": "取消订阅时出错。请联系支持人员。",
"department": "部门",
"notification_features_upgraded_by_affiliation": "好消息!您的组织__institutionName__与Overleaf有合作关系,现在您可以访问Overleaf的所有专业功能。",
"notification_personal_subscription_not_required_due_to_affiliation": " 好消息!您的组织__institutionName__与Overleaf有合作关系。您可以取消您的个人订阅,而不会失去访问您的任何利益。",
"github_private_description": "您可以选择谁可以查看并提交到此存储库。",
"notification_project_invite_message": "<b>__userName__</b> 希望您加入 <b>__projectName__</b>",
"notification_project_invite_accepted_message": "您已加入 <b>__projectName__</b>",
"subject_to_additional_vat": "价格可能会受到额外的增值税,取决于您的国家。",
"select_country_vat": "请在付款页面上选择您所在的国家,以查看包括任何增值税在内的总价。",
"to_change_access_permissions": "若要更改访问权限,请询问项目所有者",
"file_name_in_this_project": "此项目中的文件名",
"new_snippet_project": "未命名",
"loading_content": "正在创建项目",
"there_was_an_error_opening_your_content": "创建项目时出错",
"sorry_something_went_wrong_opening_the_document_please_try_again": "很抱歉,尝试在Overleaf打开此内容时发生意外错误。请再试一次。",
"the_required_parameters_were_not_supplied": "在Overleaf打开此内容的链接缺少一些必需的参数。如果某个网站的链接经常出现这种情况,请向他们报告。",
"more_than_one_kind_of_snippet_was_requested": "在Overleaf打开此内容的链接包含一些无效参数。如果某个网站的链接经常出现这种情况,请向他们报告。",
"the_supplied_parameters_were_invalid": "在Overleaf打开此内容的链接包含一些无效参数。如果某个网站的链接经常出现这种情况,请向他们报告。",
"unable_to_extract_the_supplied_zip_file": "在Overleaf打开此内容失败,因为无法提取zip文件。请确保它是有效的zip文件。如果某个网站的链接经常出现这种情况,请向他们报告。",
"the_file_supplied_is_of_an_unsupported_type ": "在Overleaf打开此内容的链接指向错误的文件类型。有效的文件类型是.tex文档和.zip文件。如果某个网站的链接经常出现这种情况,请向他们报告。",
"the_requested_publisher_was_not_found": "在Overleaf打开此内容的链接指定了找不到的发布者。如果某个网站的链接经常出现这种情况,请向他们报告。",
"the_supplied_uri_is_invalid": "在Overleaf打开此内容的链接包含无效的URI。如果某个网站的链接经常出现这种情况,请向他们报告。",
"the_requested_conversion_job_was_not_found": "在Overleaf打开此内容的链接指定了找不到的转换作业。作业可能已过期,需要重新运行。如果某个网站的链接经常出现这种情况,请向他们报告。",
"not_found_error_from_the_supplied_url": "在Overleaf打开此内容的链接指向找不到的文件。如果某个网站的链接经常出现这种情况,请向他们报告。",
"too_many_requests": "短时间内收到的请求太多。请稍等片刻,然后重试。",
"password_change_passwords_do_not_match": "密码不匹配",
"github_for_link_shared_projects": "此项目是通过链接共享访问的,除非项目所有者通过电子邮件邀请您,否则不会与您的Github同步。",
"browsing_project_latest_for_pseudo_label": "浏览项目的当前状态",
"history_label_project_current_state": "当前状态",
"download_project_at_this_version": "下载项目的这个版本",
"submit": "提交",
"submit_title": "提交",
"help_articles_matching": "符合你的主题的帮助文章",
"dropbox_for_link_share_projs": "此项目是通过链接共享访问的,除非项目所有者通过电子邮件邀请您,否则不会同步到您的Dropbox。",
"clear_search": "清除搜索",
"email_registered_try_alternative": "抱歉,我们没有与这些凭据匹配的帐户。也许你是用不同的提供商注册的?",
"access_your_projects_with_git": "使用Git访问您的项目",
"ask_proj_owner_to_upgrade_for_git_bridge": "要求项目所有者升级他们的帐户以使用git",
"export_csv": "导出CSV",
"add_comma_separated_emails_help": "使用逗号(,)字符分隔多个电子邮件地址。",
"members_management": "成员管理",
"managers_management": "管理管理者",
"institution_account": "机构帐户",
"git": "Git",
"clone_with_git": "用Git克隆",
"git_bridge_modal_description": "您可以使用下面显示的链接来<code>git</code><code>clone</code>您的项目。",
"managers_cannot_remove_admin": "管理员无法删除",
"managers_cannot_remove_self": "管理者不能删除自己",
"user_not_found": "找不到用户",
"user_already_added": "用户已添加",
"bonus_twitter_share_text": "我使用的是免费的在线协作 LaTeX 编辑器 __appName__,它非常棒,而且很容易使用!",
"bonus_email_share_header": "你可能喜欢的在线LaTeX编辑器",
"bonus_email_share_body": "嘿,我最近一直在使用在线乳胶编辑器__appName__,我想你可能会想看看。",
"bonus_share_link_text": "在线LaTeX编辑器 __appName__",
"bonus_facebook_name": "__appName__ - 在线LaTeX编辑器",
"bonus_facebook_caption": "免费无限的项目和编译",
"bonus_facebook_description": "__appName__是一个免费的在线LaTeX编辑器。和谷歌文档一样实时协作,支持 Dropbox,历史和自动完成。",
"remove_manager": "删除管理者",
"invalid_element_name": "无法复制项目,因为文件名包含无效字符,(如星号、斜杠或控制字符)。请重命名文件并重试。",
"collabratec_account_not_registered": "未注册 IEEE Collabratec™ 帐户。请从IEEE Collabratec™连接到Overleaf 或者使用其他帐户登录。",
"password_change_failed_attempt": "密码更改失败",
"password_change_successful": "密码已更改",
"not_registered": "未注册",
"featured_latex_templates": "特色LaTeX模板",
"no_featured_templates": "无特色模板",
"try_again": "请再试一次",
"email_required": "需要电子邮件",
"registration_error": "注册错误",
"newsletter-accept": "我想要关于产品报价和公司新闻和事件的电子邮件。",
"resending_confirmation_email": "重新发送确认电子邮件",
"please_confirm_email": "请点击电子邮件中的链接确认您的电子邮件地址 __emailAddress__ ",
"register_using_service": "使用__service__服务注册",
"login_to_overleaf": "登录到Overleaf",
"login_with_email": "使用电子邮件登录",
"login_with_service": "使用__service__登录",
"first_time_sl_user": "第一次以ShareLaTeX用户的身份出现在这里",
"migrate_from_sl": "从ShareLaTeX迁移",
"dont_have_account": "没有账户?",
"sl_extra_info_tooltip": "请登录ShareLaTeX将您的帐户移到Overleaf。只需要几秒钟。如果您有ShareLaTeX订阅,它将自动转移到Overleaf。",
"register_using_email": "使用电子邮件注册",
"login_register_or": "或者",
"to_add_more_collaborators": "若要添加更多合作者或打开链接共享,请询问项目所有者",
"by": "由",
"emails": "邮箱",
"editor_theme": "编辑器主题",
"overall_theme": "全局主题",
"faq_how_does_free_trial_works_answer": "在为期__len__天的免费试用期间,您可以完全访问所选的__appName__计划。试用结束后不能继续免费。您的卡将在试用期结束时收费,除非您在此之前取消。您可以通过订阅设置取消。",
"thousands_templates": "数千个模板",
"get_instant_access_to": "立即访问",
"ask_proj_owner_to_upgrade_for_full_history": "请要求项目所有者升级以访问此项目的完整历史记录。",
"currently_seeing_only_24_hrs_history": "您当前正在看到此项目中最近24小时的更改。",
"archive_projects": "归档项目",
"archive_and_leave_projects": "归档并保留项目",
"about_to_archive_projects": "您将要归档以下项目:",
"please_confirm_your_email_before_making_it_default": "请先确认您的电子邮件,然后再将其作为主要邮件。",
"back_to_editor": "回到编辑器",
"generic_history_error": "试图获取项目的历史记录时出错。如果错误仍然存在,请通过以下方式与我们联系:",
"unconfirmed": "未确认的",
"please_check_your_inbox": "请检查您的收件箱",
"resend_confirmation_email": "重新发送确认电子邮件",
"history_label_created_by": "创建人",
"history_label_this_version": "标记此版本",
"history_add_label": "添加标记",
"history_adding_label": "正在添加标记",
"history_new_label_name": "新标记名称",
"history_new_label_added_at": "新标记将添加为",
"history_delete_label": "删除标记",
"history_deleting_label": "正在删除标记",
"history_are_you_sure_delete_label": "您确实要删除以下标记吗",
"browsing_project_labelled": "浏览项目标记为",
"history_view_all": "所有历史",
"history_view_labels": "标记",
"history_view_a11y_description": "显示所有项目历史记录或仅显示带标签的版本。",
"add_another_email": "添加其他电子邮件",
"start_by_adding_your_email": "从添加电子邮件地址开始。",
"is_email_affiliated": "你的邮件是附属机构的吗? ",
"let_us_know": "让我们知道",
"add_new_email": "添加新电子邮件",
"error_performing_request": "执行请求时出错。",
"reload_emails_and_affiliations": "重新加载电子邮件和从属关系",
"emails_and_affiliations_title": "电子邮件和从属关系",
"emails_and_affiliations_explanation": "向您的帐户添加其他电子邮件地址,以访问您的大学或机构的任何升级,使合作者更容易找到您,并确保您可以恢复您的帐户。",
"institution_and_role": "机构和角色",
"add_role_and_department": "添加角色和部门",
"save_or_cancel-save": "保存",
"save_or_cancel-or": "或者",
"save_or_cancel-cancel": "取消",
"make_default": "设为默认值",
"remove": "删除",
"confirm_email": "确认电子邮件",
"invited_to_join_team": "您被邀请加入一个团队",
"join_team": "加入团队",
"accepted_invite": "已接受的邀请",
"invited_to_group": "__inviterName__邀请您加入__appName__上的团队",
"join_team_explanation": "请单击下面的按钮加入团队并享受升级的__appName__帐户的好处",
"accept_invitation": "接受邀请",
"joined_team": "您已加入由__inviterName__管理的团队",
"compare_to_another_version": "与其他版本比较",
"file_action_edited": "编辑",
"file_action_renamed": "重命名",
"file_action_created": "创建",
"file_action_deleted": "删除",
"browsing_project_as_of": "浏览项目在",
"view_single_version": "查看单个版本",
"font_family": "字体",
"line_height": "行高",
"compact": "紧凑的",
"wide": "宽松的",
"default": "默认",
"leave": "离开",
"archived_projects": "已归档项目",
"archive": "归档",
"student_disclaimer": "教育折扣适用于中学和大专院校(学校和大学)的所有学生。我们可以与您联系,确认您有资格享受折扣。",
"billed_after_x_days": "在你的__len__天试用期结束之前,你不会收到帐单。",
"looking_multiple_licenses": "寻找多个许可证?",
"reduce_costs_group_licenses": "您可以通过我们的团体优惠许可证减少工作并降低成本。",
"find_out_more": "了解更多",
"compare_plan_features": "比较计划特性",
"in_good_company": "你在一个好的公司",
"unlimited": "无限的",
"priority_support": "优先支持",
"dropbox_integration_lowercase": "Dropbox 支持",
"github_integration_lowercase": "Git 和 GitHub 支持",
"discounted_group_accounts": "折扣团体帐户",
"referring_your_friends": "介绍你的朋友",
"still_have_questions": "还有问题?",
"quote_erdogmus": "跟踪变化的能力和实时协作性是ShareLaTeX与众不同的地方。",
"quote_henderson": "ShareLaTeX已被证明是一个强大而强大的协作工具,在我们学校得到广泛应用。",
"best_value": "最佳性价比",
"faq_how_free_trial_works_question": "如何体验免费使用?",
"faq_change_plans_question": "之后可以更改付款方案吗?",
"faq_do_collab_need_premium_question": "我的合作者也需要高级账户吗?",
"faq_need_more_collab_question": "如果我需要更多合作者该怎么办?",
"faq_purchase_more_licenses_question": "可以为我的同事购买许可吗?",
"faq_monthly_or_annual_question": "应当选择月付还是年付方案?",
"faq_how_to_pay_question": "可以在线使用信用卡、储蓄卡、或者paypal支付吗?",
"faq_pay_by_invoice_question": "可以稍后支付吗",
"reference_search": "高级搜索",
"reference_search_info": "可以通过引用关键词搜索,高级搜索还可以用作者、题目、年份、期刊名称等搜索",
"reference_sync": "同步参考文献",
"reference_sync_info": "在Mendeley中管理您的参考库,并将其直接链接到背页的.bib文件,这样您就可以很容易地引用Mendeley库中的任何内容。",
"faq_how_free_trial_works_answer": "在为期__len__天的免费试用期间,您可以完全访问所选的__appName__计划。试用结束后不能继续免费。您的卡将在试用期结束时收费,除非您在此之前取消。您可以通过订阅设置取消。",
"faq_change_plans_answer": "是的,您可以随时通过订阅设置更改计划。这包括切换到不同计划的选项,或在每月和每年计费选项之间切换的选项,或取消降级到免费计划的选项。",
"faq_do_collab_need_premium_answer": "高级功能(如跟踪的更改)将对您创建的项目的合作者可用,即使这些合作者有免费帐户。",
"faq_need_more_collab_answer": "您可以升级到我们的一个付费帐户,它支持更多的合作者。你也可以通过__referFriendsLink__ 获得额外的合作者。",
"faq_purchase_more_licenses_answer": "是的,我们提供了__groupLink__,它们易于管理,有助于节省文书工作,并降低购买多个许可证的成本。",
"faq_monthly_or_annual_answer": "年度帐单提供了一种方法来减少你的管理和文书工作。如果你想管理一个单一的付款每年,而不是十二个,年度帐单适合你。",
"faq_how_to_pay_answer": "是的,你可以。所有主要的信用卡和借记卡和贝宝都支持。选择你喜欢的计划上面,你将有选择支付卡或通过贝宝时,它的时间来设置支付。",
"powerful_latex_editor": "强大的LaTeX编辑器",
"realtime_track_changes": "实时跟踪更改",
"realtime_track_changes_info": "现在您不必在跟踪更改和LaTeX排版之间进行选择。留下评论,跟踪待办事项,接受或拒绝他人的更改。",
"full_doc_history_info": "回到过去看看任何版本和谁做了改变。不管发生什么,我们都支持。",
"dropbox_integration_info": "使用双向Dropbox同步,在线和离线无缝工作。您在本地所做的更改将自动发送到Overleaf,反之亦然。",
"github_integration_info": "与GitHub或直接从Git进行提交和拉取提交,因此您或您的合作者可以在Git上脱机工作,并在Overleaf上在线工作。",
"latex_editor_info": "在一个现代的LaTeX编辑器中,你需要的一切——拼写检查、智能自动完成、语法高亮显示、几十个颜色主题、vim和emacs绑定、LaTeX警告和错误消息帮助等等。",
"change_plans_any_time": "您可以随时更改计划或更改帐户。 ",
"number_collab": "合作者数量",
"unlimited_private_info": "默认情况下,所有项目都是私有的。通过电子邮件地址或发送秘密链接邀请合作者阅读或编辑。",
"unlimited_private": "无限私人项目",
"realtime_collab": "实时协作",
"realtime_collab_info": "当你们一起工作时,你们可以实时看到合作者的光标和他们的变化,所以每个人都有最新的版本。",
"hundreds_templates": "数百个模板",
"hundreds_templates_info": "从我们的 LaTeX 模板库开始,为期刊、会议、论文、报告、简历等制作漂亮的文档。",
"instant_access": "马上使用 __appName__",
"tagline_personal": "理想的个人项目实现",
"tagline_collaborator": "非常适合共同合作的项目",
"tagline_professional": "对多人合作多项目来说",
"tagline_student_annual": "节省更多",
"tagline_student_monthly": "对单次使用来说简直完美",
"all_premium_features": "所有高级付费功能",
"sync_dropbox_github": "与dropbox或Github同步",
"demonstrating_git_integration": "演示Git集成",
"collaborate_online_and_offline": "使用自己的工作流进行在线和离线协作",
"get_collaborative_benefits": "从 __appName__ 获得协作优势,即使你喜欢离线工作",
"use_your_own_machine": "使用你自己的机器,有你自己的设置",
"store_your_work": "将工作存储在自己的硬件上",
"track_changes": "修订",
"tooltip_hide_pdf": "单击隐藏PDF",
"tooltip_show_pdf": "单击显示PDF",
"tooltip_hide_filetree": "单击隐藏文件树",
"tooltip_show_filetree": "单击显示文件树",
"cannot_verify_user_not_robot": "抱歉,您没有通过“我不是个机器人”验证,请检查您的防火墙或网页插件是否阻碍了您的验证。",
"uncompiled_changes": "未编译的改动",
"code_check_failed": "代码检查失败",
"code_check_failed_explanation": "您的代码有问题,无法自动编译",
"tags_slash_folders": "标签/文件夹",
"file_already_exists": "同名文件或文件夹已存在",
"import_project_to_v2": "打开项目到V2",
"open_in_v1": "在V1中打开",
"import_to_v2": "倒入到V2",
"never_mind_open_in_v1": "忽略,用V1打开",
"yes_im_sure": "我确定",
"drop_files_here_to_upload": "拖动文件到这里以上传",
"drag_here": "拖到这里",
"creating_project": "创立项目",
"select_a_zip_file": "选择一个.zip文件",
"drag_a_zip_file": "拖动.zip文件",
"v1_badge": "V1 徽章",
"v1_projects": "V1 项目列表",
"open_your_billing_details_page": "打开付款信息页面",
"try_out_link_sharing": "试用链接分享功能!",
"try_link_sharing": "试用链接分享",
"try_link_sharing_description": "通过分享链接进入项目",
"learn_more_about_link_sharing": "了解分享链接",
"link_sharing": "分享链接",
"tc_switch_everyone_tip": "为所有用户切换记录模式",
"tc_switch_user_tip": "为当前用户切换记录模式",
"tc_switch_guests_tip": "为所有分享链接用户切换记录模式",
"tc_guests": "受邀用户",
"select_all_projects": "全选",
"select_project": "选择",
"main_file_not_found": "未知主文件",
"please_set_main_file": "请在项目菜单中选择此项目的主文件。",
"link_sharing_is_off": "链接分享已关闭,只有被邀请的用户才能浏览此项目。",
"turn_on_link_sharing": "开启通过链接分享功能。",
"link_sharing_is_on": "通过链接分享功能已开启。",
"turn_off_link_sharing": "关闭通过链接分享功能。",
"anyone_with_link_can_edit": "任何人可以通过此链接编辑此项目。",
"anyone_with_link_can_view": "任何人可以通过此链接浏览此项目。",
"turn_on_link_sharing_consequences": "当“通过链接分享”功能开启时,任何人都可以通过链接浏览或编辑此项目。",
"turn_off_link_sharing_consequences": "当“通过链接分享”功能关闭时,只有被邀请的用户可以通过链接浏览或编辑此项目。",
"autocompile_disabled": "自动编译已关闭",
"autocompile_disabled_reason": "由于服务器过载,暂时无法自动实时编译,请点击上方按钮进行编译",
"auto_compile_onboarding_description": "开启后将会进行实时编译",
"try_out_auto_compile_setting": "试用新的自动编译功能!",
"got_it": "了解",
"pdf_compile_in_progress_error": "之前的编译仍在运行。 请稍等片刻,然后再尝试编译。",
"pdf_compile_try_again": "请等待其他项目编译完成后再试",
"invalid_email": "有未验证的邮箱",
"auto_compile": "自动编译",
"on": "开",
"tc_everyone": "所有人",
"per_user_tc_title": "个人用户记录更改历史",
"you_can_use_per_user_tc": "现在您可以记录每个用户的更改记录",
"turn_tc_on_individuals": "为个人用户开启更改记录",
"keep_tc_on_like_before": "或者向全体保留",
"auto_close_brackets": "自动补全括号",
"auto_pair_delimiters": "自动补全分隔符",
"successfull_dropbox_link": "已成功链接到 Dropbox,正在跳转到设置页",
"show_link": "显示链接",
"hide_link": "隐藏链接",
"aggregate_changed": "替换",
"aggregate_to": "为",
"confirm_password_to_continue": "确认密码以继续",
"confirm_password_footer": "短时间内我们将不会再要求输入密码",
"accept_all": "采纳全部",
"reject_all": "拒绝全部",
"bulk_accept_confirm": "您确认采纳__nChanges__ 个变动吗?",
"bulk_reject_confirm": "您确认拒绝__nChanges__ 个变动吗?",
"uncategorized": "未分类",
"pdf_compile_rate_limit_hit": "编译率达到限制",
"project_flagged_too_many_compiles": "因频繁编译,项目被标旗。编译上限会稍后解除。",
"reauthorize_github_account": "重新授权 GitHub 帐号",
"github_credentials_expired": "您的 Github 授权凭证已过期",
"hit_enter_to_reply": "点击确认键重试",
"add_your_comment_here": "在此添加评论",
"resolved_comments": "已折叠的评论",
"try_it_for_free": "免费体验",
"please_ask_the_project_owner_to_upgrade_to_track_changes": "请要求项目所有者升级以使用历史查询功能。",
"mark_as_resolved": "标记为已解决",
"reopen": "重新打开",
"add_comment": "添加评论",
"no_resolved_threads": "没有未解决线程",
"upgrade_to_track_changes": "升级以记录文档修改历史",
"see_changes_in_your_documents_live": "实时查看文档修改情况",
"track_any_change_in_real_time": "实时记录文档的任何修改情况",
"review_your_peers_work": "同行评议",
"accept_or_reject_each_changes_individually": "接受或拒绝修改意见",
"accept": "采纳",
"reject": "不要",
"no_comments": "没有评论",
"edit": "编辑",
"are_you_sure": "您确认吗?",
"resolve": "解决",
"reply": "回复",
"quoted_text_in": "引文内容",
"review": "审阅",
"track_changes_is_on": "修改追踪功能 <strong>开启</strong>",
"track_changes_is_off": "修改追踪功能 <strong>关闭</strong>",
"current_file": "当前文件",
"overview": "概览",
"tracked_change_added": "已添加",
"tracked_change_deleted": "已删除",
"show_all": "显示全部",
"show_less": "折叠",
"dropbox_sync_error": "Dropbox 同步错误",
"send": "发送",
"sending": "发送中",
"invalid_password": "密码错误",
"error": "错误",
"other_actions": "其他",
"send_test_email": "发送测试邮件",
"email_sent": "邮件已发送",
"create_first_admin_account": "创建首个管理员账户",
"ldap": "LDAP",
"ldap_create_admin_instructions": "输入邮箱,创建您的第一个__appName__管理员账户。这个账户对应您在LDAP系统中的账户,请使用此账户登陆系统。",
"saml": "SAML",
"saml_create_admin_instructions": "输入邮箱,创建您的第一个__appName__管理员账户。这个账户对应您在SAML系统中的账户,请使用此账户登陆系统。",
"admin_user_created_message": "管理员账户已创建, <a href=\"__link__\">登陆</a> 以继续",
"status_checks": "状态检查",
"editor_resources": "编辑资源",
"checking": "检查中",
"cannot_invite_self": "不能向自己发送邀请",
"cannot_invite_non_user": "邀请发送失败。被邀人可能已有__appName__账户。",
"log_in_with": "用 __provider__ 账户登陆",
"return_to_login_page": "回到登录页",
"login_failed": "登陆失败",
"delete_account_warning_message_3": "您即将永久<strong>删除您的所有账户数据</strong>,包括您的项目和设置。请输入账户邮箱地址和密码以继续。",
"delete_account_warning_message_2": "您即将永久<strong>删除您的所有账户数据</strong>,包括您的项目和设置。请输入账户邮件地主以继续",
"your_sessions": "我的会话",
"clear_sessions_description": "这是您的账户中当前活跃的会话信息(不包含当前会话)。点击“清理会话”按钮可以退出这些会话。",
"no_other_sessions": "暂无其他活跃对话",
"ip_address": "IP地址",
"session_created_at": "会话创建于",
"clear_sessions": "清理会话",
"clear_sessions_success": "会话已清理",
"sessions": "会话",
"manage_sessions": "管理会话",
"syntax_validation": "代码检查",
"history": "历史记录",
"joining": "加入",
"open_project": "打开项目",
"files_cannot_include_invalid_characters": "文件名为空或包含无效字符",
"invalid_file_name": "文件名无效",
"autocomplete_references": "参考文献自动补全(在 <code>\\cite{}</code> 中)",
"autocomplete": "自动补全",
"failed_compile_check": "您的项目中似乎含有关键性语法错误,请修改后重试",
"failed_compile_check_try": "强制编译",
"failed_compile_option_or": "或者",
"failed_compile_check_ignore": "关闭语法检查",
"compile_time_checks": "语法检查",
"stop_on_validation_error": "编译前检查语法",
"ignore_validation_errors": "忽略语法检查",
"run_syntax_check_now": "运行语法检查",
"your_billing_details_were_saved": "您的账单细节已保存",
"security_code": "安全码",
"paypal_upgrade": "如要升级,请点击下面链接按钮,用你的邮箱和密码登录到PayPal。",
"upgrade_cc_btn": "现在升级,7天后付款",
"upgrade_paypal_btn": "继续",
"notification_project_invite": "<b>__userName__</b> 想让您加入 <b>__projectName__</b> <a class=\"btn btn-sm btn-info pull-right\" href=\"/project/__projectId__/invite/token/__token__\">加入项目</a>",
"file_restored": "您的文档 (__filename__) 已恢复。",
"file_restored_back_to_editor": "您可以返回进行修改并继续编辑。",
"file_restored_back_to_editor_btn": "返回编辑器",
"view_project": "查看项目",
"join_project": "加入项目",
"invite_not_accepted": "邀请尚未接受",
"resend": "重发",
"syntax_check": "语法检查",
"revoke": "撤回",
"revoke_invite": "撤销邀请",
"pending": "待定",
"invite_not_valid": "项目邀请无效",
"invite_not_valid_description": "邀请已经过期。请联系项目所有者",
"accepting_invite_as": "接受邀请",
"accept_invite": "接受邀请",
"log_hint_ask_extra_feedback": "您能帮我们理解为什么该提示没有帮助吗?",
"log_hint_extra_feedback_didnt_understand": "我不理解该提示",
"log_hint_extra_feedback_not_applicable": "该解决办法对我的文档无效",
"log_hint_extra_feedback_incorrect": "无法纠正错误",
"log_hint_extra_feedback_other": "其它:",
"log_hint_extra_feedback_submit": "提交",
"if_you_are_registered": "如果您已有账号",
"stop_compile": "停止编译",
"terminated": "编译取消",
"compile_terminated_by_user": "由于点击了“停止编译”按钮,故取消了编译。您可以下载原始日志以查看编译停止的位置。",
"site_description": "一个简洁的在线 LaTeX 编辑器。无需安装,实时共享,版本控制,数百免费模板……",
"knowledge_base": "知识库",
"contact_message_label": "信息",
"kb_suggestions_enquiry": "您检查过我们的 <0>__kbLink__</0> 了吗?",
"answer_yes": "确认",
"answer_no": "否",
"log_hint_extra_info": "了解更多",
"log_hint_feedback_label": "该提示有帮助吗?",
"log_hint_feedback_gratitude": "感谢您的反馈!",
"recompile_pdf": "重新编译该PDF",
"about_paulo_reis": "是一个前端软件开发员和用户体验设计师,目前居住在葡萄牙阿威罗。Paulo有一个用户体验专业的博士学位,他致力于让人们在方方面面更便捷地掌握和实用技术:概念、测试、设计乃至实施。",
"login_or_password_wrong_try_again": "注册名或密码错误,请重试",
"manage_beta_program_membership": "管理 Beta 计划账户",
"beta_program_opt_out_action": "退出 Beta 计划",
"disable_beta": "禁用Beta版本",
"beta_badge_tooltip": "我们对__feature__做了一些改进。希望你喜欢!单击此处管理您的测试版计划成员资格",
"beta_program_badge_description": "在使用 __appName__ 过程中,测试功能会被这样标记:",
"beta_program_current_beta_features_description": "在Beta版本中,我们正在测试以下新功能:",
"enable_beta": "开启Beta版本",
"user_in_beta_program": "用户在参加Beta版测试",
"beta_program_already_participating": "您加入了 Beta 版测试",
"sharelatex_beta_program": "__appName__ Beta版项目",
"beta_program_benefits": "我们一直致力于改进 __appName__。通过加入 Beta 计划,您可以更早体验新功能,并帮助我们更好地满足您的需求。",
"beta_program_opt_in_action": "退出Beta版测试",
"conflicting_paths_found": "发现冲突路径",
"following_paths_conflict": "下面的文件和文件夹拥有冲突的相同路径",
"open_a_file_on_the_left": "打开左侧的一个文件",
"reference_error_relink_hint": "如果仍出现此错误,请尝试在此重新关联您的账户:",
"pdf_rendering_error": "PDF渲染错误",
"something_went_wrong_rendering_pdf": "渲染此PDF时出错了。",
"mendeley_reference_loading_error_expired": "Mendeley令牌过期,请重新关联您的账户",
"zotero_reference_loading_error_expired": "Zotero令牌过期,请重新关联您的账户",
"mendeley_reference_loading_error_forbidden": "无法加载Mendeley的参考文献,请重新关联您的账户后重试",
"zotero_reference_loading_error_forbidden": "无法加载Zotero的参考文献,请重新关联您的账户后重试",
"mendeley_integration": "Mendeley集成",
"mendeley_sync_description": "集成 Mendeley 后,您可以将 mendeley 的参考文献导入 __appName__ 项目。",
"mendeley_is_premium": "Mendeley集成是一个高级功能",
"link_to_mendeley": "关联至Mendeley",
"unlink_to_mendeley": "取消关联Mendeley",
"mendeley_reference_loading": "加载Mendeley的参考文献",
"mendeley_reference_loading_success": "已加载Mendeley的参考文献",
"mendeley_reference_loading_error": "错误,无法加载Mendeley的参考文献",
"mendeley_groups_loading_error": "从 Mendeley 加载群组时出错",
"zotero_integration": "Zotero集成。",
"zotero_sync_description": "集成Zotero后,您可以将Zotero的参考文献导入__appName__项目。",
"zotero_is_premium": "Zotero集成是一个高级功能",
"link_to_zotero": "关联至Zotero",
"unlink_to_zotero": "取消关联Zotero",
"zotero_reference_loading": "加载Zotero的参考文献",
"zotero_reference_loading_success": "已加载Zotero的参考文献",
"zotero_reference_loading_error": "错误,无法加载Zotero的参考文献",
"zotero_groups_loading_error": "从 Zotero 加载群组时出错",
"reference_import_button": "导入参考文献至",
"unlink_reference": "取消关联参考文献提供者",
"unlink_warning_reference": "警告:如果将账户与此提供者取消关联,您将无法把参考文献导入到项目中。",
"mendeley": "Mendeley",
"zotero": "Zotero",
"from_provider": "来自__provider__",
"suggest_new_doc": "建议新文件",
"request_sent_thank_you": "请求已发送,我们的团队将审核并通过电子邮件回复。",
"suggestion": "建议",
"project_url": "受影响的项目URL",
"subject": "主题",
"confirm": "确认",
"cancel_personal_subscription_first": "您已有个人订阅。是否要取消此订阅,然后再加入群组许可?",
"delete_projects": "删除项目",
"leave_projects": "离开项目",
"delete_and_leave_projects": "删除并离开项目",
"too_recently_compiled": "此项目是最近编译的,所以已跳过此编译。",
"clsi_maintenance": "编译服务器停机维护,将很快恢复正常。",
"references_search_hint": "按CTRL-空格以搜索",
"ask_proj_owner_to_upgrade_for_references_search": "请要求项目所有者升级以使用参考文献搜索功能。",
"ask_proj_owner_to_upgrade_for_faster_compiles": "请要求项目所有者升级以取得更快的编译速度,并增加您的超时限制。",
"search_bib_files": "按作者、标题、年份搜索",
"leave_group": "退出群",
"leave_now": "现在退出",
"sure_you_want_to_leave_group": "您确定要退出该群吗?",
"notification_group_invite": "您被邀请加入 __groupName__ , <a href=\"/user/subscription/__subscription_id__/group/invited\">点击加入</a>。",
"search_references": "搜索此项目中的.bib文件",
"no_search_results": "没有搜索到结果",
"email_already_registered": "改邮箱已被注册",
"compile_mode": "编译模式",
"normal": "常规",
"fast": "快速",
"rename_folder": "重命名文件夹",
"delete_folder": "删除文件夹",
"about_to_delete_folder": "您即将删除下列文件夹 (里面的所有项目也会被删除)",
"to_modify_your_subscription_go_to": "如需修改您的订阅,请到",
"manage_subscription": "管理订购",
"activate_account": "激活账户",
"yes_please": "是",
"nearly_activated": "还有一步您的 __appName__ 账户就会被激活了!",
"please_set_a_password": "请设置密码",
"activation_token_expired": "您的激活码已经过期,您需要另外一个",
"activate": "激活",
"activating": "激活中",
"ill_take_it": "我要它!",
"cancel_your_subscription": "取消订购",
"no_thanks_cancel_now": "不,谢谢,我还是想取消",
"cancel_my_account": "取消我的订购",
"sure_you_want_to_cancel": "您确认要取消订购吗?",
"i_want_to_stay": "我要留下",
"have_more_days_to_try": "试用期增加<strong>__days__ days</strong>!",
"interested_in_cheaper_plan": "您是否对便宜点的<strong>__price__</strong>学生方案感兴趣?",
"session_expired_redirecting_to_login": "会话过期。将在__seconds__秒后重定向至登录页面",
"maximum_files_uploaded_together": "最多可同时上传__max__个文件",
"too_many_files_uploaded_throttled_short_period": "上传的文件太多,您的上传将暂停一会儿。请等待15分钟,然后重试。",
"compile_larger_projects": "编译更大项目",
"upgrade_to_get_feature": "升级以获得__feature__,以及:",
"new_group": "新群",
"about_to_delete_groups": "您将删除下面的群:",
"removing": "删除",
"adding": "添加",
"groups": "群",
"rename_group": "重命名群",
"renaming": "重命名中",
"create_group": "建立群",
"delete_group": "删除群",
"delete_groups": "删除群",
"your_groups": "你的群",
"group_name": "群名",
"no_groups": "没有群",
"Subscription": "订购",
"Documentation": "文档",
"Universities": "大学",
"Account Settings": "账户设置",
"Projects": "项目",
"Account": "账户",
"global": "整体的",
"Terms": "条款",
"Security": "安全性",
"About": "关于",
"editor_disconected_click_to_reconnect": "编辑器与网络的连接已经断开,重新连接请点击任何位置。",
"word_count": "字数统计",
"please_compile_pdf_before_word_count": "请您在统计字数之前先编译您的的项目",
"total_words": "总字数",
"headers": "标题",
"math_inline": "行内数学符号",
"math_display": "数学表达式",
"connected_users": "已连接的用户",
"projects": "项目",
"upload_project": "上传项目",
"all_projects": "所有项目",
"your_projects": "您的项目",
"shared_with_you": "与您共享的",
"deleted_projects": "已删除的项目",
"templates": "模板",
"new_folder": "新建目录",
"create_your_first_project": "创建您的第一个项目!",
"complete": "完成",
"on_free_sl": "您正在使用的是免费版的 __appName__",
"upgrade": "升级",
"or_unlock_features_bonus": "或者通过以下方式解除对一些免费赠送额外功能的锁定",
"sharing_sl": "分享 __appName__",
"add_to_folder": "添加到目录",
"create_new_folder": "创建新目录",
"more": "更多的",
"rename": "重命名",
"make_copy": "制作一份拷贝",
"restore": "恢复",
"title": "标题",
"last_modified": "最近一次修改",
"no_projects": "没有任何项目",
"welcome_to_sl": "欢迎使用 __appName__!",
"new_to_latex_look_at": "刚刚接触LaTeX?看看我们的",
"or": "或者",
"or_create_project_left": "或者在左边创建您的第一个项目",
"thanks_settings_updated": "谢谢,您的设置已更新",
"update_account_info": "更新账户信息",
"must_be_email_address": "必须是电邮地址",
"first_name": "名",
"last_name": "姓",
"update": "更新",
"change_password": "更换密码",
"current_password": "正在使用的密码",
"new_password": "新密码",
"confirm_new_password": "确认新密码",
"required": "必填",
"doesnt_match": "不一致",
"dropbox_integration": "Dropbox整合",
"learn_more": "学习更多",
"dropbox_is_premium": "Dropbox同步是一个高级功能",
"account_is_linked": "账户已链接",
"unlink_dropbox": "解除与Dropbox的链接",
"link_to_dropbox": "链接到Dropbox",
"newsletter_info_and_unsubscribe": "我们会每隔几个月会发送有关可用的新功能的讯息,如果您不想接收邮件您可以随时取消订阅。",
"unsubscribed": "订阅被取消",
"unsubscribing": "正在取消订阅",
"unsubscribe": "取消订阅",
"need_to_leave": "确定要放弃?",
"delete_your_account": "删除您的账户",
"delete_account": "删除账户",
"delete_account_warning_message": "您即将永久<strong>删除您的所有账户数据</strong>,包括您的项目和设置。请输入账户邮箱以继续。",
"deleting": "正在删除",
"delete": "删除",
"sl_benefits_plans": "__appName__是世界上最易用的LaTeX编辑器。协同工作,版本跟踪,从世界上任何一个角落您都可以使用我们的LaTeX环境。",
"monthly": "每个月",
"personal": "个人",
"free": "免费",
"one_collaborator": "仅一个合作者",
"collaborator": "合作者",
"collabs_per_proj": "每个项目的__collabcount__ 个合作者",
"full_doc_history": "完整的文档历史",
"sync_to_dropbox": "同步到Dropbox",
"start_free_trial": "开始免费试用",
"professional": "专业",
"unlimited_collabs": "无限制的合作者数",
"name": "名字",
"student": "学生",
"university": "大学",
"position": "职位",
"choose_plan_works_for_you": "选择适合您的 __len__-天免费试用版。可以随时取消。",
"interested_in_group_licence": "对在群组、团队或部门中使用 __appName__ 感兴趣吗?",
"get_in_touch_for_details": "联系我们以获取更多资讯",
"group_plan_enquiry": "询问群组使用方案",
"enjoy_these_features": "享受以下这些美妙的付费功能吧!",
"create_unlimited_projects": "随心所欲的创建项目",
"never_loose_work": "有了您的支持,我们将做得更好!",
"access_projects_anywhere": "在任何地方访问您的项目",
"log_in": "登录",
"login": "登录",
"logging_in": "正在登录",
"forgot_your_password": "忘记密码",
"password_reset": "重置密码",
"password_reset_email_sent": "已给您发送邮件以完成密码重置",
"please_enter_email": "请输入您的电邮地址",
"request_password_reset": "请求重置密码",
"reset_your_password": "重置您的密码",
"password_has_been_reset": "您的密码已重置",
"login_here": "在此登录",
"set_new_password": "设置新密码",
"user_wants_you_to_see_project": "__username__ 邀请您加入 __projectname__",
"join_sl_to_view_project": "加入 __appName__ 来查看此项目",
"register_to_edit_template": "请注册以编辑 __templateName__ 模板",
"already_have_sl_account": "已经拥有 __appName__ 账户了吗?",
"register": "注册",
"password": "密码",
"registering": "正在注册",
"planned_maintenance": "计划中的维护",
"no_planned_maintenance": "目前没有维护计划",
"cant_find_page": "抱歉,没有找到您查找的页面",
"take_me_home": "我要返回!",
"no_preview_available": "抱歉,无法预览。",
"no_messages": "无消息",
"send_first_message": "向你的合作者发送第一条信息",
"account_not_linked_to_dropbox": "您的账户没有链接到Dropbox",
"update_dropbox_settings": "更新Dropbox设置",
"refresh_page_after_starting_free_trial": "请在您开始免费试用之后刷新此页面",
"refresh_page_after_linking_dropbox": "请在将您的帐户链接到Dropbox后刷新此页。",
"checking_dropbox_status": "检查 Dropbox 状态",
"manage_files_from_your_dropbox_folder": "管理Dropbox文件夹中的文件",
"have_an_extra_backup": "有一个额外的备份",
"work_with_non_overleaf_users": "和非Overleaf用户一起工作",
"work_offline": "离线工作",
"easily_manage_your_project_files_everywhere": "随时随地轻松管理您的项目文件",
"dismiss": "离开",
"new_file": "新建文件",
"upload_file": "上传文件",
"create": "创建",
"creating": "正在创建",
"upload_files": "上传文件",
"sure_you_want_to_delete": "您确定要永久删除以下文件吗?",
"common": "通用",
"navigation": "导航",
"editing": "正在编辑",
"ok": "好的",
"source": "源码",
"actions": "执行",
"copy_project": "复制项目",
"publish_as_template": "管理模版",
"sync": "同步",
"settings": "设置",
"main_document": "主目录",
"off": "关闭",
"auto_complete": "自动补全",
"theme": "主题",
"font_size": "字号",
"pdf_viewer": "PDF阅读器",
"built_in": "内嵌",
"native": "本机",
"show_hotkeys": "显示快捷键",
"new_name": "新名字",
"copying": "正在复制",
"copy": "复制",
"compiling": "正在编译",
"click_here_to_preview_pdf": "点击预览PDF",
"server_error": "服务器错误",
"somthing_went_wrong_compiling": "抱歉,出错了,您的项目无法编译。请在几分钟后再试。",
"timedout": "超时",
"proj_timed_out_reason": "抱歉,您的编译运行时间太长,已超时。这可能是由于LaTeX错误,或大量的高分辨率图像或复杂的图表。",
"no_errors_good_job": "没有错误,好样的!",
"compile_error": "编译错误",
"generic_failed_compile_message": "抱歉,由于一些原因,您的LaTeX代码无法编译。更多细节请检查下面报出的错误信息,或查看原始日志",
"other_logs_and_files": "其他日志和文件",
"view_raw_logs": "查看原始日志",
"hide_raw_logs": "隐藏原始日志",
"clear_cache": "清空缓存",
"clear_cache_explanation": "将从我们的编译服务器中清除所有隐藏的LaTeX文件(.aux .bbl等)。通常情况下您不需要这么做,除非您遇到了与其相关的麻烦。",
"clear_cache_is_safe": "您的项目文件不会被删除或修改",
"clearing": "正在清除",
"template_description": "模板描述",
"project_last_published_at": "您的项目最近一次被发布在",
"template_title_taken_from_project_title": "模板标题将自动从项目标题中获取",
"problem_talking_to_publishing_service": "我们的发布服务出现故障,请在几分钟后再试",
"unpublishing": "取消发布",
"republish": "重新发布",
"publishing": "正在发表",
"share_project": "共享该项目",
"this_project_is_private": "此项目是私有的,只能被下面的人访问",
"make_public": "允许公共访问",
"this_project_is_public": "此项目是公共的,可以被任何人通过URL编辑",
"make_private": "允许私有访问",
"can_edit": "可以编辑",
"share_with_your_collabs": "和您的合作者共享",
"share": "共享",
"need_to_upgrade_for_more_collabs": "您的账户需要升级方可添加更多的合作者",
"make_project_public": "允许公共访问该项目",
"make_project_public_consequences": "如果允许公共访问您的项目,任何人将可以通过URL访问它",
"allow_public_editing": "允许公共编辑",
"allow_public_read_only": "允许公共只读访问",
"make_project_private": "禁用共享链接",
"make_project_private_consequences": "如果设定您的项目为私有,它只可以被您选定共享的人所访问。",
"need_to_upgrade_for_history": "需要升级您的账户方可使用历史功能",
"ask_proj_owner_to_upgrade_for_history": "请要求项目所有者升级账户以使用历史功能",
"anonymous": "匿名",
"generic_something_went_wrong": "抱歉,出错了",
"generic_if_problem_continues_contact_us": "如果问题仍然存在,请与我们联系",
"restoring": "正在恢复",
"restore_to_before_these_changes": "恢复到未更改时的版本",
"profile_complete_percentage": "您的资料完成了 __percentval__%",
"file_has_been_deleted": "__filename__ 已被删除",
"sure_you_want_to_restore_before": "您确定要恢复 <0>__filename__</0> 到 __date__ 之前的版本?",
"rename_project": "重命名项目",
"about_to_delete_projects": "您将删除下面的项目:",
"about_to_leave_projects": "您将离开下面的项目",
"upload_zipped_project": "上传项目的压缩包",
"upload_a_zipped_project": "上传一个项目的压缩包",
"your_profile": "您的资料",
"institution": "机构",
"role": "角色",
"folders": "目录",
"disconnected": "连接已断开",
"please_refresh": "请刷新页面以继续",
"lost_connection": "丢失连接",
"reconnecting_in_x_secs": "__seconds__ 秒后重新连接",
"try_now": "立刻尝试",
"reconnecting": "正在重新连接",
"saving_notification_with_seconds": "保存 __docname__... (剩余 __seconds__ 秒)",
"help_us_spread_word": "帮助我们推广 __appName__",
"share_sl_to_get_rewards": "和您的朋友和同事分享 __appName__ 以解锁下面的奖励",
"post_on_facebook": "发布到Facebook",
"share_us_on_googleplus": "通过Google+分享",
"email_us_to_your_friends": "通过邮件分享给朋友",
"link_to_us": "从您的站点上链接到我们",
"direct_link": "直接的链接",
"sl_gives_you_free_stuff_see_progress_below": "当有人利用您的推荐开始使用 __appName__ 后,我们会给您一些 <strong>免费奖励</strong> 以表示感谢! 检查您的下面的进度。",
"spread_the_word_and_fill_bar": "传播并填入此栏",
"one_free_collab": "1个免费的合作者",
"three_free_collab": "3个免费的合作者",
"free_dropbox_and_history": "免费的Dropbox和历史功能",
"you_not_introed_anyone_to_sl": "您还没有把 __appName__ 介绍给其它人。开始吧!",
"you_introed_small_number": " 您已经把 __appName__ 介绍给了 <0>__numberOfPeople__</0> 个人。不错,能介绍给更多人吗?",
"you_introed_high_number": " 您已经把 __appName__ 介绍给了 <0>__numberOfPeople__</0> 个人。太棒了!",
"link_to_sl": "链接到 __appName__",
"can_link_to_sl_with_html": "您可以用下面的HTML链接到 __appName__:",
"year": "年",
"month": "月",
"subscribe_to_this_plan": "订购此项",
"your_plan": "您的订购",
"your_new_plan": "你的新计划",
"your_subscription": "您的订阅",
"on_free_trial_expiring_at": "您正在使用免费试用版,将在 __expiresAt__.到期",
"choose_a_plan_below": "选择一个套餐",
"currently_subscribed_to_plan": "您现在订阅的是 <0>__planName__</0> 套餐。",
"your_plan_is_changing_at_term_end": "在当前计费周期结束时,您的计划将更改为<0>__pendingPlanName__</0>。",
"want_change_to_apply_before_plan_end": "如果您希望在当前计费周期结束前应用此更改,请与我们联系。",
"change_plan": "改变套餐",
"next_payment_of_x_collectected_on_y": "<0>__paymentAmmount__</0> 的下次支付时间为<1>__collectionDate__</1> 。",
"additional_licenses": "您的订阅包括<0>__additionalLicenses__</0>个附加许可证,共有<1>__totalLicenses__</1>个许可证。",
"pending_additional_licenses": "您的订阅正在更改为包括<0>__pendingAdditionalLicenses__</0>个附加许可证,总共有<1>__pendingTotalLicenses__</1>个许可证。",
"update_your_billing_details": "更新您的帐单细节",
"subscription_canceled_and_terminate_on_x": " 您的订阅已被取消,将于 <0>__terminateDate__</0> 停止。不必支付其他费用。",
"your_subscription_has_expired": "您的订购已过期",
"account_has_past_due_invoice_change_plan_warning": "您的帐户当前有逾期账单。在这个问题解决之前,你不能改变你的计划。",
"create_new_subscription": "新建订购",
"problem_with_subscription_contact_us": "您的订购出现了问题。请联系我们以获得更多信息。",
"manage_group": "管理群组",
"loading_billing_form": "正在加载帐单细节表格",
"you_have_added_x_of_group_size_y": "您已经添加 <0>__addedUsersSize__</0> / <1>__groupSize__</1> 个可用成员。",
"remove_from_group": "从群组中移除",
"group_account": "群组账户",
"registered": "已注册",
"no_members": "没有成员",
"add_more_members": "添加更多成员",
"add": "添加",
"thanks_for_subscribing": "感谢订购!",
"your_card_will_be_charged_soon": "您的银行卡不久将被扣款",
"if_you_dont_want_to_be_charged": "如果您不想再被扣款 ",
"add_your_first_group_member_now": "现在添加您的第一个组成员",
"thanks_for_subscribing_you_help_sl": "感谢您订购套餐 __planName__ 。正是由于您的支持使得 __appName__ 继续成长和进步。",
"back_to_your_projects": "返回您的项目",
"goes_straight_to_our_inboxes": "直接发送到我们的电邮收件箱",
"need_anything_contact_us_at": "您有任何需要,请直接联系我们",
"regards": "感谢",
"about": "关于",
"comment": "评论",
"restricted_no_permission": "受限,抱歉您没有权限访问此页面",
"online_latex_editor": "在线LaTeX编辑器",
"meet_team_behind_latex_editor": "和您最喜欢的在线LaTeX编辑器的团队接触",
"follow_me_on_twitter": "加我的Twitter",
"motivation": "动机",
"evolved": "衍生产品",
"the_easy_online_collab_latex_editor": "易用、在线、协同合作的LaTeX编辑器",
"get_started_now": "立即开始",
"sl_used_over_x_people_at": "已有来自以下学校的超过 __numberOfUsers__ 学生和学者在使用 __appName__",
"collaboration": "合作",
"work_on_single_version": "在单一版本上合作",
"view_collab_edits": "查看合作者的编辑 ",
"view_collab_edits_in_real_time": "实时查看协作者的修改。",
"ease_of_use": " 易于使用",
"no_complicated_latex_install": "不需要复杂的LaTeX安装",
"all_packages_and_templates": "所有您所需要的包和<0>__templatesLink__</0>",
"document_history": "文档历史",
"see_what_has_been": "看到了什么 ",
"added": "已添加",
"and": "和",
"removed": "已被移除",
"restore_to_any_older_version": "回滚到任意历史版本",
"work_from_anywhere": "在任何地点使用",
"acces_work_from_anywhere": "从世界上任何地点使用",
"work_offline_and_sync_with_dropbox": "离线使用通过Dropbox和GitHub同步您的文件",
"over": "超过",
"view_templates": "预览模板",
"nothing_to_install_ready_to_go": "您的安装不会有任何的复杂和困难,并且您可以 <0>__start_now__</0>,即使您从来没见过它。 __appName__ 运行在我们的服务器上,提供了一个完整的、随时可以使用的LaTeX环境。",
"start_using_latex_now": "立即使用LaTex",
"get_same_latex_setup": "您到任何地方都可以用 __appName__ 实现LaTeX的功能。由于您和您的同事和学生可以在 __appName__ 上共同工作,不会出现版本不一致和包冲突的情况。",
"support_lots_of_features": "我们支持了几乎所有的LaTeX功能,包括插入图片、参考文献、公式以及更多!在我们的<0>__help_guides_link__</0>中,阅读您可以在__appName__ 做的所有令人激动的事",
"latex_guides": "LaTex手册",
"reset_password": "重置密码",
"set_password": "设置密码",
"updating_site": "升级站点",
"bonus_please_recommend_us": "奖励 - 请推荐我们",
"admin": "管理员",
"subscribe": "提交",
"update_billing_details": "更新帐单细节",
"group_admin": "群组管理员",
"all_templates": "所有模板",
"your_settings": "您的设置",
"maintenance": "维护",
"to_many_login_requests_2_mins": "您的账户尝试登录次数过多。请等待2分钟后再试",
"email_or_password_wrong_try_again": "您的邮件地址或密码不正确。请重试",
"rate_limit_hit_wait": "速度限制。请等会再试",
"problem_changing_email_address": "无法更改您的email地址。请您过一会儿重试。如果问题持续,请联系我们。",
"single_version_easy_collab_blurb": "__appName__ 确保您和您的合作者是同步的,并且知道他们在做什么。每个文档只有一个单一的主版本,每个人都可以访问。因改变而出现冲突是不可能的,并且您可以继续工作而不必等待您的合作者发送的最新版本。",
"can_see_collabs_type_blurb": "如果多个人想要同时一起完成一份文档是没有问题的。您可以在编辑器中直接看到您的合作者在哪打字,并且对文档的改变会直接立即显示在您的屏幕上。",
"work_directly_with_collabs": "和您的合作者直接合作",
"work_with_word_users": "和Word使用者一起工作",
"work_with_word_users_blurb": "__appName__ 是如此易于上手以至于您可以邀请非LaTeX的合作者来直接对您的LaTeX文档做出贡献。他们一开始就可以工作,并且随着接下来的使用能够不费力地学会少量的LaTeX知识。",
"view_which_changes": "查看哪些被更改了",
"sl_included_history_of_changes_blurb": "__appName__能够保存您做过的所有更改,从而你可以看到有谁在何时做过何种修改。 这使得您可以非常容易的和您的合作者保持同一进度,并且可以允许您回顾最近的工作。",
"can_revert_back_blurb": "无论是合作项目或者个人项目,有时候出现错误是难免的。 在__appName__中恢复早期版本很简单,这样就降低了失误的风险。",
"start_using_sl_now": "立即开始使用 __appName__",
"over_x_templates_easy_getting_started": "我们的模板库中有成千上万个__templates__,所以无论你是在写期刊文章、论文、简历还是其他什么,都很容易开始。",
"done": "完成",
"change": "改变",
"change_or_cancel-change": "改变",
"change_or_cancel-or": "或者",
"change_or_cancel-cancel": "取消",
"page_not_found": "找不到页面",
"please_see_help_for_more_info": "了解更多信息请参看我们的帮助手册",
"this_project_will_appear_in_your_dropbox_folder_at": "此项目将显示在您的Dropbox的目录 ",
"member_of_group_subscription": "您是由__admin_email__管理下的团体认购中的一员。请联系他们来管理您的认购。\n",
"about_henry_oswald": "是居住在伦敦的一名软件工程师。他构建了 __appName__ 的原型,并且一直负责构建一个稳定并具有上升空间到平台。Henry是测试驱动开发的强烈拥护者,并且督促我们保持 __appName__ 代码始终整洁且易于维护。",
"about_james_allen": "拥有理论物理学博士学位并且对LaTeX充满热情。他开发了最早的在线LaTeX编辑器中的一个,ScribTeX,并且在新技术开发中起了很大作用。正是有了这些新技术, __appName__ 才得以面世。",
"two_strong_principles_behind_sl": "我们关于 __appName__ 的工作背后有两个非常强烈的推动原则:",
"want_to_improve_workflow_of_as_many_people_as_possible": "我们想要完善尽可能多的人的工作流程",
"detail_on_improve_peoples_workflow": "LaTeX一向以极其难用著称,且非常难以合作使用。 我们相信我们已经研发了一些非常有效的方案来帮助人们解决困难,并且我们保证__appName__会对尽可能多的人开放。 我们一直尝试保持公道的价格,并且公布了 __appName__ 的大部分的代码做为开源代码。",
"want_to_create_sustainable_lasting_legacy": "我们想要创造一个可持续的和持久的传统",
"details_on_legacy": "发展和维护像 __appName__ 一样的产品需要大量的时间和工作,所以我们能找到一个商业模式以得到长期的支持是十分重要的。我们不想 __appName__ 依赖于外来的基金或者由于商业模式的失败而消失。我们很高兴得告诉大家,现在 __appName__ 是可持续的、盈利的,并且预期能够长期盈利。",
"get_in_touch": "联系",
"want_to_hear_from_you_email_us_at": "我们喜欢倾听任何使用 __appName__ 以及想知道我们在做什么的人。您可以和我们联系 ",
"cant_find_email": "邮箱尚未注册,抱歉。",
"plans_amper_pricing": "套餐 & 价格",
"documentation": "文档",
"account": "账户",
"subscription": "订购",
"log_out": "退出",
"en": "英语",
"pt": "葡萄牙语",
"es": "西班牙语",
"fr": "法语",
"de": "德语",
"it": "意大利语",
"da": "丹麦语",
"sv": "瑞典语",
"no": "挪威语",
"nl": "荷兰语",
"pl": "波兰语",
"ru": "俄罗斯语",
"uk": "乌克兰语",
"ro": "罗马尼亚语",
"click_here_to_view_sl_in_lng": "点此以使用<0>__lngName__</0> 的 __appName__",
"language": "语言",
"upload": "上传",
"menu": "菜单",
"full_screen": "全屏",
"logs_and_output_files": "日志和生成的文件",
"download_pdf": "下载PDF",
"split_screen": "分屏",
"clear_cached_files": "清除缓存文件",
"go_to_code_location_in_pdf": "转到PDF中的位置",
"please_compile_pdf_before_download": "请在下载PDF之前编译您的项目",
"remove_collaborator": "移除合作者",
"add_to_folders": "添加到目录",
"download_zip_file": "下载ZIP格式文件",
"download_file": "下载<0>__type__</0> 文件",
"price": "价格",
"close": "关闭",
"keybindings": "组合键",
"restricted": "受限的",
"start_x_day_trial": "开始您的__len__天免费试用之旅",
"buy_now": "现在购买!",
"cs": "捷克语",
"view_all": "预览所有",
"terms": "条款",
"privacy": "隐私",
"contact": "联系",
"change_to_this_plan": "该为这个订购项",
"keep_current_plan": "保持我现在的计划",
"processing": "处理中",
"sure_you_want_to_change_plan": "您确定想要改变套餐为 <0>__planName__</0>?",
"sure_you_want_to_cancel_plan_change": "是否确实要撤销计划的套餐更改?您将继续订阅<0>__planName__</0>。",
"revert_pending_plan_change": "撤销计划的套餐更改",
"existing_plan_active_until_term_end": "您的现有计划及其功能将保持活动状态,直到当前计费周期结束。",
"move_to_annual_billing": "转为包年套餐",
"annual_billing_enabled": "包年套餐已启用",
"move_to_annual_billing_now": "立即转为包年套餐",
"change_to_annual_billing_and_save": "包年套餐立省 <0>__percentage__</0> 。现在选择每年立省 <1>__yearlySaving__</1> 。",
"missing_template_question": "模板不全?",
"tell_us_about_the_template": "如果我们模板中没有您要找的,请您发给我们您的模版,该模版的 __appName__ 网址,或者告诉我们哪里可以找到您要的模版。此外,请您简单描述一下该模版的用处。",
"email_us": "电邮我们",
"this_project_is_public_read_only": "该项目是公开的,任何人都可以通过该URL查看,但是不能编辑。",
"tr": "土耳其语",
"select_files": "选取文件",
"drag_files": "拖动文件",
"upload_failed_sorry": "抱歉,上传失败。",
"inserting_files": "正在插入文件",
"password_reset_token_expired": "您的密码重置链接已过期。请申请新的密码重置email,并按照email中的链接操作。",
"merge_project_with_github": "将项目与GitHub合并",
"pull_github_changes_into_sharelatex": "将GitHub中的更改调入 __appName__",
"push_sharelatex_changes_to_github": "将 __appName__ 中的更改推送到GitHub",
"features": "功能",
"commit": "交付",
"commiting": "提交中",
"importing_and_merging_changes_in_github": "正在导入合并GitHub中的更改",
"upgrade_for_faster_compiles": "升级以取得更快的编译速度,并增加您的超时限制。",
"free_accounts_have_timeout_upgrade_to_increase": "免费帐户有一分钟的超时限制,而升级的帐户有四分钟的超时限制。",
"learn_how_to_make_documents_compile_quickly": "了解如何修复编译超时",
"zh-CN": "中文",
"cn": "中文 (简体)",
"sync_to_github": "同步到 GitHub",
"sync_to_dropbox_and_github": "同步到 Dropbox 和 GitHub",
"project_too_large": "项目太大",
"project_too_large_please_reduce": "此项目的可编辑文本太多,请尝试减少它。最大的文件是:",
"project_too_much_editable_text": "该项目具有太多可编辑文本,请尝试减少它。",
"please_ask_the_project_owner_to_link_to_github": "请让项目的拥有者将该项目链接到一个GitHub存储库",
"go_to_pdf_location_in_code": "转到PDF中对应的位置",
"ko": "韩语",
"ja": "日语",
"about_brian_gough": "是一名软件工程师及 Fermilab 和 Los Alamos的前任理论高能物理学家。多年来,他用TeX和LaTeX出版了很多自由软件的使用手册,并且是GNU科学图书馆的一名维护人员。",
"first_few_days_free": "前__trialLen__ 天免费",
"every": "每个",
"credit_card": "信用卡",
"credit_card_number": "信用卡号码",
"invalid": "无效的",
"expiry": "过期日期",
"january": "一月",
"february": "二月",
"march": "三月",
"april": "四月",
"may": "五月",
"june": "六月",
"july": "七月",
"august": "八月",
"september": "九月",
"october": "十月",
"november": "十一月",
"december": "十二月",
"zip_post_code": "邮编",
"city": "城市",
"address": "地址",
"coupon_code": "优惠码",
"country": "国家",
"billing_address": "账单地址",
"upgrade_now": "现在升级",
"state": "州",
"vat_number": "增值税号",
"you_have_joined": "你已经加入 __groupName__",
"claim_premium_account": "你已经获得由__groupName__提供的高级账户权限",
"you_are_invited_to_group": "您被邀请加入__groupName__",
"you_can_claim_premium_account": "你可以通过验证你的电子邮箱来获得由 __groupName__ 提供的高级账户权限",
"not_now": "稍后",
"verify_email_join_group": "验证电子邮箱并加入群",
"check_email_to_complete_group": "请查看您的电子邮件以便成功加入该群",
"verify_email_address": "验证电子邮箱",
"group_provides_you_with_premium_account": "__groupName__ 为你提供了一个高级账户。验证你的电子邮箱来升级你的账户。",
"check_email_to_complete_the_upgrade": "请查看您的电子邮件以完成升级",
"email_link_expired": "电子邮件链接已过期,请申请一个新的链接。",
"services": "服务",
"about_shane_kilkelly": "是居住在爱丁堡的软件开发员。 Shane 积极主张函数式编程和测试驱动开发,且以设计高质量软件而引以为豪。",
"this_is_your_template": "这是从你的项目提取的模版",
"links": "链接",
"account_settings": "账户设置",
"search_projects": "搜索项目",
"clone_project": "克隆项目",
"delete_project": "删除项目",
"download_zip": "下载Zip压缩包",
"new_project": "创建新项目",
"blank_project": "空白项目",
"example_project": "样例项目",
"from_template": "从模板导入",
"cv_or_resume": "简历",
"cover_letter": "附信",
"journal_article": "期刊文章",
"presentation": "幻灯片",
"thesis": "论文",
"bibliographies": "参考文献",
"terms_of_service": "服务条款",
"privacy_policy": "隐私政策",
"plans_and_pricing": "套餐及价格",
"university_licences": "大学许可证",
"security": "安全性",
"contact_us": "联系我们",
"thanks": "谢谢",
"blog": "博客",
"latex_editor": "LeTeX编辑器",
"get_free_stuff": "免费获取",
"chat": "聊天",
"your_message": "您的信息",
"loading": "正在加载",
"connecting": "正在连接",
"recompile": "重新编译",
"download": "下载",
"email": "电邮",
"owner": "拥有者",
"read_and_write": "读/写",
"read_only": "只读",
"publish": "发布",
"view_in_template_gallery": "在模板库查看",
"unpublish": "未出版",
"hotkeys": "快捷键",
"saving": "正在保存",
"cancel": "取消",
"project_name": "项目名称",
"root_document": "根目录",
"spell_check": "拼写检查",
"compiler": "编译器",
"private": "私有",
"public": "公共",
"delete_forever": "永远删除",
"support_and_feedback": "支持和反馈",
"help": "帮助",
"latex_templates": "LeTeX模板",
"info": "信息",
"latex_help_guide": "LeTeX帮助指南",
"choose_your_plan": "选择您的支付方案",
"indvidual_plans": "个人方案",
"free_forever": "永久免费",
"low_priority_compile": "低的编译优先级",
"unlimited_projects": "项目无限制",
"unlimited_compiles": "编译无限制",
"full_history_of_changes": "改动的所有历史记录",
"highest_priority_compiling": "最高编译优先级",
"dropbox_sync": "Dropbox同步",
"beta": "试用版",
"sign_up_now": "现在注册",
"annual": "每年",
"half_price_student": "学生半价",
"about_us": "关于我们",
"loading_recent_github_commits": "正在装载最近的提交",
"no_new_commits_in_github": "自上次合并后GitHub未收到新的提交",
"dropbox_sync_description": "保持您的 __appName__ 项目与您的Dropbox同步。SharaLaTeX中的更改将被自动发送到Dropbox,反之亦然。",
"github_sync_description": "通过与GitHub同步,你可以将您的__appName__项目关联到GitHub的存储库,从 __appName__ 创建新的提交,并与线下或者GitHub中的提交合并。",
"github_import_description": "通过与GitHub同步,你可以将GitHub的存储库导入 __appName__,从 __appName__ 创建新的提交,并与线下或者GitHub中的提交合并。",
"link_to_github_description": "您需要授权 __appName__ 访问您的GitHub账户,从而允许我们同步您的项目。",
"unlink": "取消关联",
"unlink_github_warning": "任何您已经同步到GitHub的项目将被切断联系,并且不再保持与GitHub同步。您确定要取消与您的GitHub账户的关联吗?",
"github_account_successfully_linked": "GitHub账户已经成功关联。",
"github_successfully_linked_description": "谢谢,您已成功建立了您的GitHub账户与 __appName__ 的关联。您现在可以导出您的 __appName__ 项目到GitHub,或者从您的GitHub存储困导入项目。",
"import_from_github": "从GitHub导入",
"github_sync_error": "抱歉,与我们的GitHub服务器连接出错。请稍后重试。",
"loading_github_repositories": "正在读取您的GitHub存储库",
"select_github_repository": "选取要导入 __appName__ 的GitHub存储库",
"import_to_sharelatex": "导入 __appName__",
"importing": "正在倒入",
"github_sync": "GitHub同步",
"checking_project_github_status": "正在检查GitHub中的项目状态",
"account_not_linked_to_github": "您的帐号未与GitHub关联",
"project_not_linked_to_github": "该项目未与GitHub任一存储库关联。您可以在GitHub中为该项目创建一个存储库:",
"create_project_in_github": "创建一个GitHub存储库",
"project_synced_with_git_repo_at": "该项目已与GitHub存储库同步,时间为",
"recent_commits_in_github": "GitHub中最近的提交",
"sync_project_to_github": "同步项目到GitHub",
"sync_project_to_github_explanation": "您在 __appName__ 中所做的任何更改将被交付并与GitHub中任何升级合并。",
"github_merge_failed": "您在 __appName__ 和 GitHub 中的更改未能自动合并。请您手动将 <0>__sharelatex_branch__</0> 分支合并到git中的 <1>__master_branch__</1> 分支。当您手动合并完成后,点击下面继续。",
"continue_github_merge": "我已经手动合并。继续",
"export_project_to_github": "将项目导出到GitHub",
"github_validation_check": "请检查存储库的名字是否已被占用,且您有权限创建存储库。",
"github_git_folder_error": "此项目在顶层包含一个.git文件夹,表示它已经是git存储库。Overleaf的Github同步服务无法同步git历史记录。请删除.git文件夹,然后重试。",
"repository_name": "存储库名称",
"optional": "可选的",
"github_public_description": "任何人都可以看到该存储库。您可以选择谁有权提交。",
"github_commit_message_placeholder": "为 __appName__ 中的更改提交信息",
"merge": "合并",
"merging": "正在合并",
"github_account_is_linked": "您的GitHub账户已经成功关联。",
"unlink_github": "取消与您的GitHub账户的关联",
"link_to_github": "建立与您的GitHub账户的关联",
"github_integration": "GitHub 整合",
"github_is_premium": "与GitHub同步是一项付费功能",
"remote_service_error": "远程服务产生错误",
"linked_file": "导入的文件",
"n_items": "__count__ 个项目",
"n_items_plural": "__count__ 个项目",
"you_can_now_log_in_sso": "您现在可以通过您的机构登录,并可以获得<0>免费的 __appName__ 专业功能!</0>",
"link_institutional_email_get_started": "将机构电子邮件地址链接到您的帐户以开始。",
"looks_like_youre_at": "看起来你在<0>__institutionName__</0>!",
"add_affiliation": "添加从属关系",
"did_you_know_institution_providing_professional": "你知道吗__institutionName__向__institutionName__的每个人提供<0>免费的 __appName__ 专业功能</0>吗?",
"add_email_to_claim_features": "添加一个机构电子邮件地址来声明您的功能。",
"please_change_primary_to_remove": "请更改您的主要电子邮件以删除它",
"please_reconfirm_your_affiliation_before_making_this_primary": "请确认您的从属关系,然后再将此作为主要。",
"please_link_before_making_primary": "请确认您的电子邮件链接到您的机构帐户,然后再将其作为主要电子邮件。",
"dropbox_duplicate_project_names": "您的 Dropbox 帐户已取消关联,因为您有多个名为 <0>\"__projectName__\"</0> 的项目。",
"dropbox_duplicate_project_names_suggestion": "请让您的项目名称在您的所有<0>活动、存档和废弃</0>项目中唯一,然后重新关联您的 Dropbox 帐户。",
"please_reconfirm_institutional_email": "请花点时间确认您的机构电子邮件地址,或<0>将其从您的帐户中删除</0>。",
"need_to_add_new_primary_before_remove": "在删除此电子邮件地址之前,您需要添加一个新的主电子邮件地址。",
"are_you_still_at": "你还在<0>__institutionName__</0>吗?",
"confirm_affiliation": "确认从属关系",
"please_check_your_inbox_to_confirm": "请检查您的电子邮件收件箱以确认您属于<0>__institutionName__</0> 。",
"your_affiliation_is_confirmed": "您已确认属于<0>__institutionName__</0>。",
"thank_you": "谢谢您!",
"imported_from_mendeley_at_date": "于 __formattedDate__ __relativeDate__,从Mendeley导入",
"imported_from_zotero_at_date": "于 __formattedDate__ __relativeDate__,从Zotero导入",
"imported_from_external_provider_at_date": "于 __formattedDate__ __relativeDate__,从<0>__shortenedUrlHTML__</0>导入",
"imported_from_another_project_at_date": "于 __formattedDate__ __relativeDate__,从<0>另一个项目</0>/__sourceEntityPathHTML__导入",
"imported_from_the_output_of_another_project_at_date": "于 __formattedDate__ __relativeDate__,从<0>另一个项目</0>的输出导入: __sourceOutputFilePathHTML__",
"refreshing": "正在刷新",
"if_error_persists_try_relinking_provider": "如果此错误仍然存在,请尝试在此处重新链接您的__provider__帐户",
"select_from_source_files": "从源文件中选择",
"select_from_output_files": "从输出文件中选择",
"select_a_project": "选择一个项目",
"please_select_a_project": "请选择项目",
"no_other_projects_found": "找不到其他项目,请先创建另一个项目",
"select_an_output_file": "选择输出文件",
"please_select_an_output_file": "请选择输出文件",
"select_a_file": "选择一个文件",
"please_select_a_file": "请选择一个文件",
"url_to_fetch_the_file_from": "获取文件的URL",
"invalid_request": "无效的请求。请更正数据并重试。",
"session_error": "会话错误。请检查是否已启用Cookie。如果问题仍然存在,请尝试清除缓存和cookies。",
"too_many_attempts": "尝试太多。请稍等片刻,然后再试一次。",
"something_went_wrong_server": "与服务器交谈时出错 :(。请再试一次。",
"file_name": "文件名",
"from_another_project": "从另一个项目",
"from_external_url": "从外部URL",
"thank_you_exclamation": "谢谢您!",
"add_files": "添加文件",
"hotkey_find_and_replace": "查找(并替换)",
"hotkey_compile": "编译",
"hotkey_undo": "撤销",
"hotkey_redo": "重做",
"hotkey_beginning_of_document": "文件开头",
"hotkey_end_of_document": "文件末尾",
"hotkey_go_to_line": "转到行",
"hotkey_toggle_comment": "切换评论",
"hotkey_delete_current_line": "删除当前行",
"hotkey_select_all": "全选",
"hotkey_to_uppercase": "改为大写",
"hotkey_to_lowercase": "改为小写",
"hotkey_indent_selection": "缩进选择",
"hotkey_bold_text": "粗体",
"hotkey_italic_text": "斜体",
"hotkey_autocomplete_menu": "自动完成菜单",
"hotkey_select_candidate": "选择候选",
"hotkey_insert_candidate": "插入候选",
"hotkey_search_references": "搜索引用",
"hotkey_toggle_review_panel": "切换审阅面板",
"hotkey_toggle_track_changes": "切换历史记录",
"hotkey_add_a_comment": "添加评论",
"category_greek": "希腊字符",
"category_arrows": "箭头字符",
"category_operators": "运算字符",
"category_relations": "关系字符",
"category_misc": "杂项",
"no_symbols_found": "找不到符号",
"find_out_more_about_latex_symbols": "了解有关 LaTeX 符号的更多信息",
"search": "搜索",
"also": "也",
"add_email": "添加电子邮件",
"dropbox_unlinked_premium_feature": "<0>您的 Dropbox 帐户已取消关联</0>,因为 Dropbox Sync 是您通过机构许可获得的一项高级功能。",
"confirm_affiliation_to_relink_dropbox": "请确认您仍在该机构并持有他们的许可证,或升级您的帐户以重新关联您的 Dropbox 帐户。",
"pay_with_visa_mastercard_or_amex": "使用万事达卡、Visa卡或美国运通支付",
"pay_with_paypal": "使用PayPal支付",
"this_field_is_required": "此字段必填",
"by_subscribing_you_agree_to_our_terms_of_service": "订阅即表示您同意我们的<0>服务条款</0>。",
"cancel_anytime": "我们相信您会喜欢__appName__,但如果不喜欢,您可以随时取消。如果您在30天内通知我们,我们将把钱还给您,不问任何问题。",
"for_visa_mastercard_and_discover": "对于<0>Visa卡、万事达卡和Discover卡</0>,这是您卡<2>背面的</2><1>3位数字</1>。",
"for_american_express": "对于<0>美国运通<0>,这是信用卡<2>正面</2>的<1>4位数字</1>。</0></0>",
"request_password_reset_to_reconfirm": "请求密码重置邮件以重新确认",
"go_next_page": "转到下一页",
"go_prev_page": "转到上一页",
"page_current": "页面 __page__,当前页面",
"go_page": "转到第 __page__ 页",
"pagination_navigation": "分页导航",
"can_now_relink_dropbox": "您现在可以<0>重新关联您的 Dropbox 帐户</0>。",
"skip_to_content": "跳到内容"
}
| overleaf/web/locales/zh-CN.json/0 | {
"file_path": "overleaf/web/locales/zh-CN.json",
"repo_id": "overleaf",
"token_count": 57791
} | 556 |
/* 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: {
key: 1,
},
name: 'key_1',
},
{
key: {
user_id: 1,
},
name: 'user_id_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.notifications, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.notifications, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145014_create_notifications_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145014_create_notifications_indexes.js",
"repo_id": "overleaf",
"token_count": 310
} | 557 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['server-pro', 'saas']
const indexes = [
{
unique: true,
key: {
project_id: 1,
},
name: 'project_id_1',
},
{
key: {
user_id: 1,
},
name: 'user_id_1',
},
{
key: {
name: 1,
},
name: 'name_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.templates, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.templates, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145030_create_templates_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145030_create_templates_indexes.js",
"repo_id": "overleaf",
"token_count": 305
} | 558 |
const Helpers = require('./lib/helpers')
exports.tags = ['server-ce', 'server-pro', 'saas']
const indexes = [
{
key: {
projectId: 1,
},
name: 'projectId_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.deletedFiles, indexes)
}
exports.rollback = async client => {
const { db } = client
await Helpers.dropIndexesFromCollection(db.deletedFiles, indexes)
}
| overleaf/web/migrations/20210310111225_create_deletedFiles_projectId_index.js/0 | {
"file_path": "overleaf/web/migrations/20210310111225_create_deletedFiles_projectId_index.js",
"repo_id": "overleaf",
"token_count": 168
} | 559 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
import './controllers/LaunchpadController'
| overleaf/web/modules/launchpad/frontend/js/main/index.js/0 | {
"file_path": "overleaf/web/modules/launchpad/frontend/js/main/index.js",
"repo_id": "overleaf",
"token_count": 40
} | 560 |
const Path = require('path')
const UserGetter = require('../../../../app/src/Features/User/UserGetter')
const ErrorController = require('../../../../app/src/Features/Errors/ErrorController')
module.exports = {
activateAccountPage(req, res, next) {
// An 'activation' is actually just a password reset on an account that
// was set with a random password originally.
if (req.query.user_id == null || req.query.token == null) {
return ErrorController.notFound(req, res)
}
if (typeof req.query.user_id !== 'string') {
return ErrorController.forbidden(req, res)
}
UserGetter.getUser(
req.query.user_id,
{ email: 1, loginCount: 1 },
(error, user) => {
if (error != null) {
return next(error)
}
if (!user) {
return ErrorController.notFound(req, res)
}
if (user.loginCount > 0) {
// Already seen this user, so account must be activate
// This lets users keep clicking the 'activate' link in their email
// as a way to log in which, if I know our users, they will.
res.redirect(`/login`)
} else {
req.session.doLoginAfterPasswordReset = true
res.render(Path.resolve(__dirname, '../views/user/activate'), {
title: 'activate_account',
email: user.email,
token: req.query.token,
})
}
}
)
},
}
| overleaf/web/modules/user-activate/app/src/UserActivateController.js/0 | {
"file_path": "overleaf/web/modules/user-activate/app/src/UserActivateController.js",
"repo_id": "overleaf",
"token_count": 604
} | 561 |
<svg xmlns="http://www.w3.org/2000/svg" width="777.28" height="777.28" viewBox="0 0 777.28 777.28">
<g>
<g>
<circle cx="388.64" cy="388.64" r="388.64" fill="#798ed2" opacity="0.05"/>
<g>
<rect x="241.27" y="232.25" width="294.75" height="294.75" fill="#c1c2c5"/>
<path d="M388.64,468.11a88.49,88.49,0,1,0-88.49-88.49A88.66,88.66,0,0,0,388.64,468.11Z" fill="#919296" fill-rule="evenodd"/>
<path d="M352.86,366.1a13.27,13.27,0,1,1-13.27,13.27,13.27,13.27,0,0,1,13.27-13.27Zm71.9,0a13.27,13.27,0,1,1-13.27,13.27A13.27,13.27,0,0,1,424.75,366.1Z" fill="#505050" fill-rule="evenodd"/>
</g>
</g>
</g>
</svg>
| overleaf/web/public/img/brand/500-visual-socket.svg/0 | {
"file_path": "overleaf/web/public/img/brand/500-visual-socket.svg",
"repo_id": "overleaf",
"token_count": 382
} | 562 |
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<title>favicon</title>
<path d="M6.12,4.38A7.08,7.08,0,0,0,2.67,10.2,5.07,5.07,0,1,0,9.55,5.46a4.68,4.68,0,0,0-1.8-.34A7.48,7.48,0,0,0,5.2,8.07a3.33,3.33,0,1,1,2.54,5.47A3.33,3.33,0,0,1,5.2,12.37,4,4,0,0,1,4.24,9C4.89,5.11,9.55,2.87,13,2a35.85,35.85,0,0,0-4.6,2.65c4.17,1.61,4.84-1.9,6.79-3.47C13.25.42,6.13.14,6.12,4.38Z"/>
</svg>
| overleaf/web/public/mask-favicon.svg/0 | {
"file_path": "overleaf/web/public/mask-favicon.svg",
"repo_id": "overleaf",
"token_count": 314
} | 563 |
// Script to create projects with sharelatex history for testing
// Example:
// node scripts/create_project.js --user-id=5dca84e11e71ae002ff73bd4 --name="My Test Project" --old-history
const fs = require('fs')
const path = require('path')
const _ = require('underscore')
const parseArgs = require('minimist')
const OError = require('@overleaf/o-error')
const { waitForDb } = require('../app/src/infrastructure/mongodb')
const { User } = require('../app/src/models/User')
const ProjectCreationHandler = require('../app/src/Features/Project/ProjectCreationHandler')
const ProjectEntityUpdateHandler = require('../app/src/Features/Project/ProjectEntityUpdateHandler')
const argv = parseArgs(process.argv.slice(2), {
string: ['user-id', 'name'],
boolean: ['old-history'],
unknown: function (arg) {
console.error('unrecognised argument', arg)
process.exit(1)
},
})
console.log('argv', argv)
const userId = argv['user-id']
const projectName = argv.name || `Test Project ${new Date().toISOString()}`
const oldHistory = argv['old-history']
console.log('userId', userId)
async function _createRootDoc(project, ownerId, docLines) {
try {
const { doc } = await ProjectEntityUpdateHandler.promises.addDoc(
project._id,
project.rootFolder[0]._id,
'main.tex',
docLines,
ownerId
)
await ProjectEntityUpdateHandler.promises.setRootDoc(project._id, doc._id)
} catch (error) {
throw OError.tag(error, 'error adding root doc when creating project')
}
}
async function _addDefaultExampleProjectFiles(ownerId, projectName, project) {
const mainDocLines = await _buildTemplate('main.tex', ownerId, projectName)
await _createRootDoc(project, ownerId, mainDocLines)
const referenceDocLines = await _buildTemplate(
'references.bib',
ownerId,
projectName
)
await ProjectEntityUpdateHandler.promises.addDoc(
project._id,
project.rootFolder[0]._id,
'references.bib',
referenceDocLines,
ownerId
)
const universePath = path.resolve(
__dirname + '/../app/templates/project_files/universe.jpg'
)
await ProjectEntityUpdateHandler.promises.addFile(
project._id,
project.rootFolder[0]._id,
'universe.jpg',
universePath,
null,
ownerId
)
}
async function _buildTemplate(templateName, userId, projectName) {
const user = await User.findById(userId, 'first_name last_name')
const templatePath = path.resolve(
__dirname + `/../app/templates/project_files/${templateName}`
)
const template = fs.readFileSync(templatePath)
const data = {
project_name: projectName,
user,
year: new Date().getUTCFullYear(),
month: new Date().getUTCMonth(),
}
const output = _.template(template.toString())(data)
return output.split('\n')
}
async function createProject() {
await waitForDb()
const user = await User.findById(userId)
console.log('Will create project')
console.log('user_id:', userId, '=>', user.email)
console.log('project name:', projectName)
const attributes = oldHistory ? { overleaf: {} } : {}
const project = await ProjectCreationHandler.promises.createBlankProject(
userId,
projectName,
attributes
)
await _addDefaultExampleProjectFiles(userId, projectName, project)
return project
}
createProject()
.then(project => {
console.log('Created project', project._id)
process.exit()
})
.catch(err => {
console.error(err)
process.exit(1)
})
| overleaf/web/scripts/create_project.js/0 | {
"file_path": "overleaf/web/scripts/create_project.js",
"repo_id": "overleaf",
"token_count": 1187
} | 564 |
const Path = require('path')
const fs = require('fs')
const fetch = require('node-fetch')
const CACHE_IN = Path.join(
Path.dirname(Path.dirname(Path.dirname(__dirname))),
'data',
'learnPages'
)
async function scrape(baseUrl, page) {
const uri = new URL(baseUrl + '/learn-scripts/api.php')
uri.search = new URLSearchParams({
page,
action: 'parse',
format: 'json',
redirects: true,
}).toString()
const response = await fetch(uri)
if (response.status !== 200) {
console.error(response.status, page, response)
}
return await response.text()
}
const crypto = require('crypto')
function hash(blob) {
return crypto.createHash('sha1').update(blob).digest('hex')
}
function getName(page) {
let enc = encodeURIComponent(page)
// There are VERY long titles in media wiki.
// Add percent encoding and they exceed the filename size on my Ubuntu box.
if (enc.length > 100) {
enc = enc.slice(0, 100) + hash(page)
}
return enc
}
async function scrapeAndCachePage(baseUrl, page) {
const path = Path.join(CACHE_IN, getName(page) + '.json')
try {
return JSON.parse(await fs.promises.readFile(path, 'utf-8'))
} catch (e) {
const blob = await scrape(baseUrl, page)
const parsed = JSON.parse(blob).parse
if (!parsed) {
console.error(page, blob)
throw new Error('bad contents')
}
await fs.promises.mkdir(CACHE_IN, { recursive: true })
await fs.promises.writeFile(path, JSON.stringify(parsed, null, 2), 'utf-8')
return parsed
}
}
async function getAllPagesFrom(baseUrl, continueFrom) {
// https://learn.overleaf.com/learn/Special:ApiSandbox#action=query&format=json&generator=allpages&gapfilterredir=nonredirects
const uri = new URL(baseUrl + '/learn-scripts/api.php')
uri.search = new URLSearchParams({
action: 'query',
format: 'json',
generator: 'allpages',
// Ignore pages with redirects. We do not want to check page content twice.
gapfilterredir: 'nonredirects',
// Bump the default page size of 10.
gaplimit: 100,
...continueFrom,
}).toString()
const response = await fetch(uri)
if (response.status !== 200) {
console.error(response.status, continueFrom, response)
}
const blob = await response.json()
const nextContinueFrom = blob && blob.continue
const pagesRaw = (blob && blob.query && blob.query.pages) || {}
const pages = Object.values(pagesRaw).map(page => page.title)
return { nextContinueFrom, pages }
}
async function getAllPages(baseUrl) {
let continueFrom = {}
let allPages = []
while (true) {
const { nextContinueFrom, pages } = await getAllPagesFrom(
baseUrl,
continueFrom
)
allPages = allPages.concat(pages)
if (!nextContinueFrom) break
continueFrom = nextContinueFrom
}
return allPages.sort()
}
async function getAllPagesAndCache(baseUrl) {
const path = Path.join(CACHE_IN, 'allPages.txt')
try {
return JSON.parse(await fs.promises.readFile(path, 'utf-8'))
} catch (e) {
const allPages = await getAllPages(baseUrl)
await fs.promises.mkdir(CACHE_IN, { recursive: true })
await fs.promises.writeFile(path, JSON.stringify(allPages), 'utf-8')
return allPages
}
}
module.exports = {
getAllPagesAndCache,
scrapeAndCachePage,
}
| overleaf/web/scripts/learn/checkSanitize/scrape.js/0 | {
"file_path": "overleaf/web/scripts/learn/checkSanitize/scrape.js",
"repo_id": "overleaf",
"token_count": 1189
} | 565 |
let userOptions
try {
userOptions = require('../../data/onesky.json')
} catch (err) {
if (!process.env.ONE_SKY_PUBLIC_KEY) {
console.error(
'Cannot detect onesky credentials.\n\tDevelopers: see the docs at',
'https://github.com/overleaf/developer-manual/blob/master/code/translations.md#testing-translations-scripts',
'\n\tOps: environment variable ONE_SKY_PUBLIC_KEY is not set'
)
process.exit(1)
}
}
function withAuth(options) {
return Object.assign(
options,
{
apiKey: process.env.ONE_SKY_PUBLIC_KEY,
secret: process.env.ONE_SKY_PRIVATE_KEY,
projectId: '25049',
},
userOptions
)
}
module.exports = {
withAuth,
}
| overleaf/web/scripts/translations/config.js/0 | {
"file_path": "overleaf/web/scripts/translations/config.js",
"repo_id": "overleaf",
"token_count": 290
} | 566 |
const chai = require('chai')
chai.should()
chai.use(require('chai-as-promised'))
chai.use(require('chaid'))
chai.use(require('sinon-chai'))
// Do not truncate assertion errors
chai.config.truncateThreshold = 0
| overleaf/web/test/acceptance/bootstrap.js/0 | {
"file_path": "overleaf/web/test/acceptance/bootstrap.js",
"repo_id": "overleaf",
"token_count": 82
} | 567 |
const { expect } = require('chai')
const { exec } = require('child_process')
const { ObjectId } = require('mongodb')
const User = require('./helpers/User').promises
describe('ConvertArchivedState', function () {
let userOne, userTwo, userThree, userFour
let projectOne, projectOneId
let projectTwo, projectTwoId
let projectThree, projectThreeId
let projectFour, projectFourId
beforeEach(async function () {
userOne = new User()
userTwo = new User()
userThree = new User()
userFour = new User()
await userOne.login()
await userTwo.login()
await userThree.login()
await userFour.login()
projectOneId = await userOne.createProject('old-archived-1', {
template: 'blank',
})
projectOne = await userOne.getProject(projectOneId)
projectOne.archived = true
projectOne.collaberator_refs.push(userTwo._id)
projectOne.tokenAccessReadOnly_refs.push(userThree._id)
await userOne.saveProject(projectOne)
projectTwoId = await userOne.createProject('old-archived-2', {
template: 'blank',
})
projectTwo = await userOne.getProject(projectTwoId)
projectTwo.archived = true
projectTwo.tokenAccessReadAndWrite_refs.push(userThree._id)
projectTwo.tokenAccessReadOnly_refs.push(userFour._id)
await userOne.saveProject(projectTwo)
projectThreeId = await userOne.createProject('already-new-archived', {
template: 'blank',
})
projectThree = await userOne.getProject(projectThreeId)
projectThree.archived = [
ObjectId(userOne._id),
ObjectId(userTwo._id),
ObjectId(userFour._id),
]
projectThree.collaberator_refs.push(userTwo._id)
projectThree.tokenAccessReadOnly_refs.push(userFour._id)
await userOne.saveProject(projectThree)
projectFourId = await userOne.createProject('not-archived', {
template: 'blank',
})
projectFour = await userOne.getProject(projectFourId)
projectFour.archived = false
await userOne.saveProject(projectFour)
})
beforeEach(function (done) {
exec(
'CONNECT_DELAY=1 node scripts/convert_archived_state.js FIRST,SECOND',
(error, stdout, stderr) => {
console.log(stdout)
console.error(stderr)
if (error) {
return done(error)
}
done()
}
)
})
describe('main method', function () {
it('should change a project archived boolean to an array', async function () {
projectOne = await userOne.getProject(projectOneId)
projectTwo = await userOne.getProject(projectTwoId)
expect(convertObjectIdsToStrings(projectOne.archived)).to.deep.equal([
userOne._id,
userTwo._id,
userThree._id,
])
expect(convertObjectIdsToStrings(projectTwo.archived)).to.deep.equal([
userOne._id,
userThree._id,
userFour._id,
])
})
it('should not change the value of a project already archived with an array', async function () {
projectThree = await userOne.getProject(projectThreeId)
expect(convertObjectIdsToStrings(projectThree.archived)).to.deep.equal([
userOne._id,
userTwo._id,
userFour._id,
])
})
it('should change a none-archived project with a boolean value to an array', async function () {
projectFour = await userOne.getProject(projectFourId)
expect(convertObjectIdsToStrings(projectFour.archived)).to.deep.equal([])
})
})
function convertObjectIdsToStrings(ids) {
if (typeof ids === 'object') {
return ids.map(id => {
return id.toString()
})
}
}
})
| overleaf/web/test/acceptance/src/ConvertArchivedState.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/ConvertArchivedState.js",
"repo_id": "overleaf",
"token_count": 1381
} | 568 |
const { expect } = require('chai')
const User = require('./helpers/User').promises
describe('Project ownership transfer', function () {
beforeEach(async function () {
this.ownerSession = new User()
this.collaboratorSession = new User()
this.strangerSession = new User()
this.adminSession = new User()
await this.adminSession.ensureUserExists()
await this.adminSession.ensureAdmin()
await this.ownerSession.login()
await this.collaboratorSession.login()
await this.strangerSession.login()
await this.adminSession.login()
this.owner = await this.ownerSession.get()
this.collaborator = await this.collaboratorSession.get()
this.stranger = await this.strangerSession.get()
this.admin = await this.adminSession.get()
this.projectId = await this.ownerSession.createProject('Test project')
await this.ownerSession.addUserToProject(
this.projectId,
this.collaborator,
'readAndWrite'
)
})
describe('happy path', function () {
beforeEach(async function () {
await this.ownerSession.transferProjectOwnership(
this.projectId,
this.collaborator._id
)
})
it('changes the project owner', async function () {
const project = await this.collaboratorSession.getProject(this.projectId)
expect(project.owner_ref.toString()).to.equal(
this.collaborator._id.toString()
)
})
it('adds the previous owner as a read/write collaborator', async function () {
const project = await this.collaboratorSession.getProject(this.projectId)
expect(project.collaberator_refs.map(x => x.toString())).to.have.members([
this.owner._id.toString(),
])
})
it('lets the new owner open the project', async function () {
await this.collaboratorSession.openProject(this.projectId)
})
it('lets the previous owner open the project', async function () {
await this.ownerSession.openProject(this.projectId)
})
})
describe('validation', function () {
it('lets only the project owner transfer ownership', async function () {
await expect(
this.collaboratorSession.transferProjectOwnership(
this.projectId,
this.collaborator._id
)
).to.be.rejectedWith('Unexpected status code: 403')
})
it('prevents transfers to a non-collaborator', async function () {
await expect(
this.ownerSession.transferProjectOwnership(
this.projectId,
this.stranger._id
)
).to.be.rejectedWith('Unexpected status code: 403')
})
it('allows an admin to transfer to any project to a non-collaborator', async function () {
await expect(
this.adminSession.transferProjectOwnership(
this.projectId,
this.stranger._id
)
).to.be.fulfilled
})
})
})
| overleaf/web/test/acceptance/src/ProjectOwnershipTransferTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/ProjectOwnershipTransferTests.js",
"repo_id": "overleaf",
"token_count": 1056
} | 569 |
const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
const Institution = require('./helpers/Institution')
const Subscription = require('./helpers/Subscription')
const Publisher = require('./helpers/Publisher')
describe('UserMembershipAuthorization', function () {
beforeEach(function (done) {
this.user = new User()
async.series([this.user.ensureUserExists.bind(this.user)], done)
})
describe('group', function () {
beforeEach(function (done) {
this.subscription = new Subscription({
groupPlan: true,
})
async.series(
[
this.subscription.ensureExists.bind(this.subscription),
cb => this.user.login(cb),
],
done
)
})
describe('users management', function () {
it('should allow managers only', function (done) {
const url = `/manage/groups/${this.subscription._id}/members`
async.series(
[
expectAccess(this.user, url, 403),
cb => this.subscription.setManagerIds([this.user._id], cb),
expectAccess(this.user, url, 200),
],
done
)
})
})
describe('managers management', function () {
it('should allow managers only', function (done) {
const url = `/manage/groups/${this.subscription._id}/managers`
async.series(
[
expectAccess(this.user, url, 403),
cb => this.subscription.setManagerIds([this.user._id], cb),
expectAccess(this.user, url, 200),
],
done
)
})
})
})
describe('institution', function () {
beforeEach(function (done) {
this.institution = new Institution()
async.series([this.institution.ensureExists.bind(this.institution)], done)
})
describe('users management', function () {
it('should allow managers only', function (done) {
const url = `/manage/institutions/${this.institution.v1Id}/managers`
async.series(
[
this.user.login.bind(this.user),
expectAccess(this.user, url, 403),
cb => this.institution.setManagerIds([this.user._id], cb),
expectAccess(this.user, url, 200),
],
done
)
})
})
describe('creation', function () {
it('should allow staff only', function (done) {
const url = `/entities/institution/create/foo`
async.series(
[
this.user.login.bind(this.user),
expectAccess(this.user, url, 403),
cb => this.user.ensureStaffAccess('institutionManagement', cb),
this.user.login.bind(this.user),
expectAccess(this.user, url, 200),
],
done
)
})
})
})
describe('publisher', function () {
beforeEach(function (done) {
this.publisher = new Publisher({})
async.series(
[
this.publisher.ensureExists.bind(this.publisher),
cb => this.user.login(cb),
],
done
)
})
describe('managers management', function () {
it('should allow managers only', function (done) {
const url = `/manage/publishers/${this.publisher.slug}/managers`
async.series(
[
expectAccess(this.user, url, 403),
cb => this.publisher.setManagerIds([this.user._id], cb),
expectAccess(this.user, url, 200),
],
done
)
})
})
describe('creation', function () {
it('should redirect staff only', function (done) {
const url = `/manage/publishers/foo/managers`
async.series(
[
this.user.login.bind(this.user),
expectAccess(this.user, url, 404),
cb => this.user.ensureStaffAccess('publisherManagement', cb),
this.user.login.bind(this.user),
expectAccess(this.user, url, 302, /\/create/),
],
done
)
})
it('should allow staff only', function (done) {
const url = `/entities/publisher/create/foo`
async.series(
[
expectAccess(this.user, url, 403),
cb => this.user.ensureStaffAccess('publisherManagement', cb),
this.user.login.bind(this.user),
expectAccess(this.user, url, 200),
],
done
)
})
})
})
})
function expectAccess(user, url, status, pattern) {
return callback => {
user.request.get({ url }, (error, response, body) => {
if (error) {
return callback(error)
}
expect(response.statusCode).to.equal(status)
if (pattern) {
expect(body).to.match(pattern)
}
callback()
})
}
}
| overleaf/web/test/acceptance/src/UserMembershipAuthorizationTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/UserMembershipAuthorizationTests.js",
"repo_id": "overleaf",
"token_count": 2207
} | 570 |
function filterOutput(line) {
return (
!line.startsWith('Using settings from ') &&
!line.startsWith('Using default settings from ') &&
!line.startsWith('CoffeeScript settings file')
)
}
module.exports = { filterOutput }
| overleaf/web/test/acceptance/src/helpers/settings.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/helpers/settings.js",
"repo_id": "overleaf",
"token_count": 81
} | 571 |
import { expect } from 'chai'
import sinon from 'sinon'
import { screen, render, fireEvent } from '@testing-library/react'
import MessageInput from '../../../../../frontend/js/features/chat/components/message-input'
describe('<MessageInput />', function () {
let resetUnreadMessages, sendMessage
beforeEach(function () {
resetUnreadMessages = sinon.stub()
sendMessage = sinon.stub()
})
it('renders successfully', function () {
render(
<MessageInput
sendMessage={sendMessage}
resetUnreadMessages={resetUnreadMessages}
/>
)
screen.getByLabelText('Your Message')
})
it('sends a message after typing and hitting enter', function () {
render(
<MessageInput
sendMessage={sendMessage}
resetUnreadMessages={resetUnreadMessages}
/>
)
const input = screen.getByRole('textbox')
fireEvent.change(input, { target: { value: 'hello world' } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(sendMessage).to.be.calledOnce
expect(sendMessage).to.be.calledWith('hello world')
})
it('resets the number of unread messages after clicking on the input', function () {
render(
<MessageInput
sendMessage={sendMessage}
resetUnreadMessages={resetUnreadMessages}
/>
)
const input = screen.getByPlaceholderText('Your Message…')
fireEvent.click(input)
expect(resetUnreadMessages).to.be.calledOnce
})
})
| overleaf/web/test/frontend/features/chat/components/message-input.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/chat/components/message-input.test.js",
"repo_id": "overleaf",
"token_count": 527
} | 572 |
import { expect } from 'chai'
import { screen, fireEvent } from '@testing-library/react'
import renderWithContext from '../helpers/render-with-context'
import FileTreeFolder from '../../../../../frontend/js/features/file-tree/components/file-tree-folder'
describe('<FileTreeFolder/>', function () {
beforeEach(function () {
global.localStorage.clear()
})
it('renders unselected', function () {
renderWithContext(
<FileTreeFolder
name="foo"
id="123abc"
folders={[]}
docs={[]}
files={[]}
/>
)
screen.getByRole('treeitem', { selected: false })
expect(screen.queryByRole('tree')).to.not.exist
})
it('renders selected', function () {
renderWithContext(
<FileTreeFolder
name="foo"
id="123abc"
folders={[]}
docs={[]}
files={[]}
/>,
{
contextProps: {
rootFolder: [
{
docs: [{ _id: '123abc' }],
fileRefs: [],
folders: [],
},
],
},
}
)
const treeitem = screen.getByRole('treeitem', { selected: false })
fireEvent.click(treeitem)
screen.getByRole('treeitem', { selected: true })
expect(screen.queryByRole('tree')).to.not.exist
})
it('expands', function () {
renderWithContext(
<FileTreeFolder
name="foo"
id="123abc"
folders={[]}
docs={[]}
files={[]}
/>,
{
contextProps: {
rootFolder: [
{
docs: [{ _id: '123abc' }],
fileRefs: [],
folders: [],
},
],
},
}
)
screen.getByRole('treeitem')
const expandButton = screen.getByRole('button', { name: 'Expand' })
fireEvent.click(expandButton)
screen.getByRole('tree')
})
it('saves the expanded state for the next render', function () {
const { unmount } = renderWithContext(
<FileTreeFolder
name="foo"
id="123abc"
folders={[]}
docs={[]}
files={[]}
/>,
{
contextProps: {
rootFolder: [
{
docs: [{ _id: '123abc' }],
fileRefs: [],
folders: [],
},
],
},
}
)
expect(screen.queryByRole('tree')).to.not.exist
const expandButton = screen.getByRole('button', { name: 'Expand' })
fireEvent.click(expandButton)
screen.getByRole('tree')
unmount()
renderWithContext(
<FileTreeFolder
name="foo"
id="123abc"
folders={[]}
docs={[]}
files={[]}
/>
)
screen.getByRole('tree')
})
})
| overleaf/web/test/frontend/features/file-tree/components/file-tree-folder.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/file-tree/components/file-tree-folder.test.js",
"repo_id": "overleaf",
"token_count": 1357
} | 573 |
import { render, screen } from '@testing-library/react'
import HotkeysModal from '../../../../../frontend/js/features/hotkeys-modal/components/hotkeys-modal'
import { expect } from 'chai'
import sinon from 'sinon'
const modalProps = {
show: true,
handleHide: sinon.stub(),
trackChangesVisible: false,
}
describe('<HotkeysModal />', function () {
it('renders the translated modal title', async function () {
const { baseElement } = render(<HotkeysModal {...modalProps} />)
expect(baseElement.querySelector('.modal-title').textContent).to.equal(
'Hotkeys'
)
})
it('renders translated heading with embedded code', function () {
const { baseElement } = render(<HotkeysModal {...modalProps} />)
const results = baseElement.querySelectorAll('h3 code')
expect(results).to.have.length(1)
})
it('renders the hotkey descriptions', function () {
const { baseElement } = render(<HotkeysModal {...modalProps} />)
const hotkeys = baseElement.querySelectorAll(
'[data-test-selector="hotkey"]'
)
expect(hotkeys).to.have.length(19)
})
it('adds extra hotkey descriptions when Track Changes is enabled', function () {
const { baseElement } = render(
<HotkeysModal {...modalProps} trackChangesVisible />
)
const hotkeys = baseElement.querySelectorAll(
'[data-test-selector="hotkey"]'
)
expect(hotkeys).to.have.length(22)
})
it('uses Ctrl for non-macOS', function () {
render(<HotkeysModal {...modalProps} />)
expect(screen.getAllByText(/Ctrl/)).to.have.length(16)
expect(screen.queryByText(/Cmd/)).to.not.exist
})
it('uses Cmd for macOS', function () {
render(<HotkeysModal {...modalProps} isMac />)
expect(screen.getAllByText(/Cmd/)).to.have.length(16)
expect(screen.queryByText(/Ctrl/)).to.not.exist
})
})
| overleaf/web/test/frontend/features/hotkeys-modal/components/hotkeys-modal.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/hotkeys-modal/components/hotkeys-modal.test.js",
"repo_id": "overleaf",
"token_count": 674
} | 574 |
import { render, screen, cleanup } from '@testing-library/react'
import WordCountModal from '../../../../../frontend/js/features/word-count-modal/components/word-count-modal'
import { expect } from 'chai'
import sinon from 'sinon'
import fetchMock from 'fetch-mock'
describe('<WordCountModal />', function () {
afterEach(function () {
fetchMock.reset()
cleanup()
})
const modalProps = {
projectId: 'project-1',
clsiServerId: 'clsi-server-1',
show: true,
handleHide: sinon.stub(),
}
it('renders the translated modal title', async function () {
render(<WordCountModal {...modalProps} />)
await screen.findByText('Word Count')
})
it('renders a loading message when loading', async function () {
fetchMock.get('express:/project/:projectId/wordcount', () => {
return { status: 200, body: { texcount: { messages: 'This is a test' } } }
})
render(<WordCountModal {...modalProps} />)
await screen.findByText('Loading…')
await screen.findByText('This is a test')
})
it('renders an error message and hides loading message on error', async function () {
fetchMock.get('express:/project/:projectId/wordcount', 500)
render(<WordCountModal {...modalProps} />)
await screen.findByText('Sorry, something went wrong')
expect(screen.queryByText(/Loading/)).to.not.exist
})
it('displays messages', async function () {
fetchMock.get('express:/project/:projectId/wordcount', () => {
return {
status: 200,
body: {
texcount: {
messages: 'This is a test',
},
},
}
})
render(<WordCountModal {...modalProps} />)
await screen.findByText('This is a test')
})
it('displays counts data', async function () {
fetchMock.get('express:/project/:projectId/wordcount', () => {
return {
status: 200,
body: {
texcount: {
textWords: 100,
mathDisplay: 200,
mathInline: 300,
headers: 400,
},
},
}
})
render(<WordCountModal {...modalProps} />)
await screen.findByText((content, element) =>
element.textContent.trim().match(/^Total Words\s*:\s*100$/)
)
await screen.findByText((content, element) =>
element.textContent.trim().match(/^Math Display\s*:\s*200$/)
)
await screen.findByText((content, element) =>
element.textContent.trim().match(/^Math Inline\s*:\s*300$/)
)
await screen.findByText((content, element) =>
element.textContent.trim().match(/^Headers\s*:\s*400$/)
)
})
})
| overleaf/web/test/frontend/features/word-count-modal/components/word-count-modal.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/word-count-modal/components/word-count-modal.test.js",
"repo_id": "overleaf",
"token_count": 1056
} | 575 |
class Fixture {
constructor() {
this.el = document.createElement('div')
document.body.appendChild(this.el)
}
load(html) {
this.el.innerHTML = html
return this.el.firstChild
}
cleanUp() {
this.el.innerHTML = ''
}
}
const fixture = new Fixture()
export default fixture
| overleaf/web/test/karma/support/fixture.js/0 | {
"file_path": "overleaf/web/test/karma/support/fixture.js",
"repo_id": "overleaf",
"token_count": 112
} | 576 |
const sinon = require('sinon')
const { expect } = require('chai')
const SandboxedModule = require('sandboxed-module')
const { ObjectId } = require('mongodb')
const AuthenticationErrors = require('../../../../app/src/Features/Authentication/AuthenticationErrors')
const modulePath =
'../../../../app/src/Features/Authentication/AuthenticationManager.js'
describe('AuthenticationManager', function () {
beforeEach(function () {
this.settings = { security: { bcryptRounds: 4 } }
this.AuthenticationManager = SandboxedModule.require(modulePath, {
requires: {
'../../models/User': {
User: (this.User = {}),
},
'../../infrastructure/mongodb': {
db: (this.db = { users: {} }),
ObjectId,
},
bcrypt: (this.bcrypt = {}),
'@overleaf/settings': this.settings,
'../User/UserGetter': (this.UserGetter = {}),
'./AuthenticationErrors': AuthenticationErrors,
},
})
this.callback = sinon.stub()
})
describe('with real bcrypt', function () {
beforeEach(function () {
const bcrypt = require('bcrypt')
this.bcrypt.compare = bcrypt.compare
this.bcrypt.getRounds = bcrypt.getRounds
this.bcrypt.genSalt = bcrypt.genSalt
this.bcrypt.hash = bcrypt.hash
// Hash of 'testpassword'
this.testPassword =
'$2a$04$DcU/3UeJf1PfsWlQL./5H.rGTQL1Z1iyz6r7bN9Do8cy6pVWxpKpK'
})
describe('authenticate', function () {
beforeEach(function () {
this.user = {
_id: 'user-id',
email: (this.email = 'USER@sharelatex.com'),
}
this.User.findOne = sinon.stub().callsArgWith(1, null, this.user)
})
describe('when the hashed password matches', function () {
beforeEach(function (done) {
this.unencryptedPassword = 'testpassword'
this.user.hashedPassword = this.testPassword
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencryptedPassword,
(error, user) => {
this.callback(error, user)
done()
}
)
})
it('should look up the correct user in the database', function () {
this.User.findOne.calledWith({ email: this.email }).should.equal(true)
})
it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
describe('when the encrypted passwords do not match', function () {
beforeEach(function () {
this.AuthenticationManager.authenticate(
{ email: this.email },
'notthecorrectpassword',
this.callback
)
})
it('should not return the user', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
})
describe('setUserPasswordInV2', function () {
beforeEach(function () {
this.user = {
_id: '5c8791477192a80b5e76ca7e',
email: (this.email = 'USER@sharelatex.com'),
}
this.db.users.updateOne = sinon
this.User.findOne = sinon.stub().callsArgWith(2, null, this.user)
this.db.users.updateOne = sinon
.stub()
.callsArgWith(2, null, { modifiedCount: 1 })
})
it('should not produce an error', function (done) {
this.AuthenticationManager.setUserPasswordInV2(
this.user,
'testpassword',
(err, updated) => {
expect(err).to.not.exist
expect(updated).to.equal(true)
done()
}
)
})
it('should set the hashed password', function (done) {
this.AuthenticationManager.setUserPasswordInV2(
this.user,
'testpassword',
err => {
expect(err).to.not.exist
const {
hashedPassword,
} = this.db.users.updateOne.lastCall.args[1].$set
expect(hashedPassword).to.exist
expect(hashedPassword.length).to.equal(60)
expect(hashedPassword).to.match(/^\$2a\$04\$[a-zA-Z0-9/.]{53}$/)
done()
}
)
})
})
})
describe('authenticate', function () {
describe('when the user exists in the database', function () {
beforeEach(function () {
this.user = {
_id: 'user-id',
email: (this.email = 'USER@sharelatex.com'),
}
this.unencryptedPassword = 'banana'
this.User.findOne = sinon.stub().callsArgWith(1, null, this.user)
})
describe('when the hashed password matches', function () {
beforeEach(function (done) {
this.user.hashedPassword = this.hashedPassword = 'asdfjadflasdf'
this.bcrypt.compare = sinon.stub().callsArgWith(2, null, true)
this.bcrypt.getRounds = sinon.stub().returns(4)
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencryptedPassword,
(error, user) => {
this.callback(error, user)
done()
}
)
})
it('should look up the correct user in the database', function () {
this.User.findOne.calledWith({ email: this.email }).should.equal(true)
})
it('should check that the passwords match', function () {
this.bcrypt.compare
.calledWith(this.unencryptedPassword, this.hashedPassword)
.should.equal(true)
})
it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
describe('when the encrypted passwords do not match', function () {
beforeEach(function () {
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencryptedPassword,
this.callback
)
})
it('should not return the user', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
describe('when the hashed password matches but the number of rounds is too low', function () {
beforeEach(function (done) {
this.user.hashedPassword = this.hashedPassword = 'asdfjadflasdf'
this.bcrypt.compare = sinon.stub().callsArgWith(2, null, true)
this.bcrypt.getRounds = sinon.stub().returns(1)
this.AuthenticationManager.setUserPassword = sinon
.stub()
.callsArgWith(2, null)
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencryptedPassword,
(error, user) => {
this.callback(error, user)
done()
}
)
})
it('should look up the correct user in the database', function () {
this.User.findOne.calledWith({ email: this.email }).should.equal(true)
})
it('should check that the passwords match', function () {
this.bcrypt.compare
.calledWith(this.unencryptedPassword, this.hashedPassword)
.should.equal(true)
})
it('should check the number of rounds', function () {
this.bcrypt.getRounds.called.should.equal(true)
})
it('should set the users password (with a higher number of rounds)', function () {
this.AuthenticationManager.setUserPassword
.calledWith(this.user, this.unencryptedPassword)
.should.equal(true)
})
it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
describe('when the hashed password matches but the number of rounds is too low, but upgrades disabled', function () {
beforeEach(function (done) {
this.settings.security.disableBcryptRoundsUpgrades = true
this.user.hashedPassword = this.hashedPassword = 'asdfjadflasdf'
this.bcrypt.compare = sinon.stub().callsArgWith(2, null, true)
this.bcrypt.getRounds = sinon.stub().returns(1)
this.AuthenticationManager.setUserPassword = sinon
.stub()
.callsArgWith(2, null)
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencryptedPassword,
(error, user) => {
this.callback(error, user)
done()
}
)
})
it('should not check the number of rounds', function () {
this.bcrypt.getRounds.called.should.equal(false)
})
it('should not set the users password (with a higher number of rounds)', function () {
this.AuthenticationManager.setUserPassword
.calledWith(this.user, this.unencryptedPassword)
.should.equal(false)
})
it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
})
describe('when the user does not exist in the database', function () {
beforeEach(function () {
this.User.findOne = sinon.stub().callsArgWith(1, null, null)
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencrpytedPassword,
this.callback
)
})
it('should not return a user', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
})
describe('validateEmail', function () {
describe('valid', function () {
it('should return null', function () {
const result = this.AuthenticationManager.validateEmail(
'foo@example.com'
)
expect(result).to.equal(null)
})
})
describe('invalid', function () {
it('should return validation error object for no email', function () {
const result = this.AuthenticationManager.validateEmail('')
expect(result).to.an.instanceOf(AuthenticationErrors.InvalidEmailError)
expect(result.message).to.equal('email not valid')
})
it('should return validation error object for invalid', function () {
const result = this.AuthenticationManager.validateEmail('notanemail')
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidEmailError
)
expect(result.message).to.equal('email not valid')
})
})
})
describe('validatePassword', function () {
beforeEach(function () {
// 73 characters:
this.longPassword =
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef012345678'
})
describe('with a null password', function () {
it('should return an error', function () {
const result = this.AuthenticationManager.validatePassword()
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal('password not set')
expect(result.info.code).to.equal('not_set')
})
})
describe('password length', function () {
describe('with the default password length options', function () {
it('should reject passwords that are too short', function () {
const result1 = this.AuthenticationManager.validatePassword('')
expect(result1).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result1.message).to.equal('password is too short')
expect(result1.info.code).to.equal('too_short')
const result2 = this.AuthenticationManager.validatePassword('foo')
expect(result2).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result2.message).to.equal('password is too short')
expect(result2.info.code).to.equal('too_short')
})
it('should reject passwords that are too long', function () {
const result = this.AuthenticationManager.validatePassword(
this.longPassword
)
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal('password is too long')
expect(result.info.code).to.equal('too_long')
})
it('should accept passwords that are a good length', function () {
expect(
this.AuthenticationManager.validatePassword('l337h4x0r')
).to.equal(null)
})
})
describe('when the password length is specified in settings', function () {
beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
min: 10,
max: 12,
},
}
})
it('should reject passwords that are too short', function () {
const result = this.AuthenticationManager.validatePassword(
'012345678'
)
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal('password is too short')
expect(result.info.code).to.equal('too_short')
})
it('should accept passwords of exactly minimum length', function () {
expect(
this.AuthenticationManager.validatePassword('0123456789')
).to.equal(null)
})
it('should reject passwords that are too long', function () {
const result = this.AuthenticationManager.validatePassword(
'0123456789abc'
)
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal('password is too long')
expect(result.info.code).to.equal('too_long')
})
it('should accept passwords of exactly maximum length', function () {
expect(
this.AuthenticationManager.validatePassword('0123456789ab')
).to.equal(null)
})
})
describe('when the maximum password length is set to >72 characters in settings', function () {
beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
max: 128,
},
}
})
it('should still reject passwords > 72 characters in length', function () {
const result = this.AuthenticationManager.validatePassword(
this.longPassword
)
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal('password is too long')
expect(result.info.code).to.equal('too_long')
})
})
})
describe('allowed characters', function () {
describe('with the default settings for allowed characters', function () {
it('should allow passwords with valid characters', function () {
expect(
this.AuthenticationManager.validatePassword(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
)
).to.equal(null)
expect(
this.AuthenticationManager.validatePassword(
'1234567890@#$%^&*()-_=+[]{};:<>/?!£€.,'
)
).to.equal(null)
})
it('should not allow passwords with invalid characters', function () {
const result = this.AuthenticationManager.validatePassword(
'correct horse battery staple'
)
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal(
'password contains an invalid character'
)
expect(result.info.code).to.equal('invalid_character')
})
})
describe('when valid characters are overridden in settings', function () {
beforeEach(function () {
this.settings.passwordStrengthOptions = {
chars: {
symbols: ' ',
},
}
})
it('should allow passwords with valid characters', function () {
expect(
this.AuthenticationManager.validatePassword(
'correct horse battery staple'
)
).to.equal(null)
})
it('should disallow passwords with invalid characters', function () {
const result = this.AuthenticationManager.validatePassword(
'1234567890@#$%^&*()-_=+[]{};:<>/?!£€.,'
)
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
)
expect(result.message).to.equal(
'password contains an invalid character'
)
expect(result.info.code).to.equal('invalid_character')
})
})
describe('when allowAnyChars is set', function () {
beforeEach(function () {
this.settings.passwordStrengthOptions = {
allowAnyChars: true,
}
})
it('should allow any characters', function () {
expect(
this.AuthenticationManager.validatePassword(
'correct horse battery staple'
)
).to.equal(null)
expect(
this.AuthenticationManager.validatePassword(
'1234567890@#$%^&*()-_=+[]{};:<>/?!£€.,'
)
).to.equal(null)
})
})
})
})
describe('setUserPassword', function () {
beforeEach(function () {
this.user_id = ObjectId()
this.user = {
_id: this.user_id,
email: 'user@example.com',
}
this.password = 'banana'
this.hashedPassword = 'asdkjfa;osiuvandf'
this.salt = 'saltaasdfasdfasdf'
this.bcrypt.genSalt = sinon.stub().callsArgWith(2, null, this.salt)
this.bcrypt.hash = sinon.stub().callsArgWith(2, null, this.hashedPassword)
this.User.findOne = sinon.stub().callsArgWith(2, null, this.user)
this.db.users.updateOne = sinon.stub().callsArg(2)
})
describe('too long', function () {
beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
max: 10,
},
}
this.password = 'dsdsadsadsadsadsadkjsadjsadjsadljs'
})
it('should return and error', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
err => {
expect(err).to.exist
done()
}
)
})
it('should not start the bcrypt process', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
() => {
this.bcrypt.genSalt.called.should.equal(false)
this.bcrypt.hash.called.should.equal(false)
done()
}
)
})
})
describe('contains full email', function () {
beforeEach(function () {
this.password = `some${this.user.email}password`
})
it('should reject the password', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
err => {
expect(err).to.exist
expect(err.name).to.equal('InvalidPasswordError')
done()
}
)
})
})
describe('contains first part of email', function () {
beforeEach(function () {
this.password = `some${this.user.email.split('@')[0]}password`
})
it('should reject the password', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
err => {
expect(err).to.exist
expect(err.name).to.equal('InvalidPasswordError')
done()
}
)
})
})
describe('too short', function () {
beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
max: 10,
min: 6,
},
}
this.password = 'dsd'
})
it('should return and error', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
err => {
expect(err).to.exist
done()
}
)
})
it('should not start the bcrypt process', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
() => {
this.bcrypt.genSalt.called.should.equal(false)
this.bcrypt.hash.called.should.equal(false)
done()
}
)
})
})
describe('successful password set attempt', function () {
beforeEach(function () {
this.UserGetter.getUser = sinon.stub().yields(null, { overleaf: null })
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
this.callback
)
})
it("should update the user's password in the database", function () {
const { args } = this.db.users.updateOne.lastCall
expect(args[0]).to.deep.equal({
_id: ObjectId(this.user_id.toString()),
})
expect(args[1]).to.deep.equal({
$set: {
hashedPassword: this.hashedPassword,
},
$unset: {
password: true,
},
})
})
it('should hash the password', function () {
this.bcrypt.genSalt.calledWith(4).should.equal(true)
this.bcrypt.hash.calledWith(this.password, this.salt).should.equal(true)
})
it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
})
})
| overleaf/web/test/unit/src/Authentication/AuthenticationManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Authentication/AuthenticationManagerTests.js",
"repo_id": "overleaf",
"token_count": 9981
} | 577 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Compile/ClsiFormatChecker.js'
const SandboxedModule = require('sandboxed-module')
describe('ClsiFormatChecker', function () {
beforeEach(function () {
this.ClsiFormatChecker = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': (this.settings = {
compileBodySizeLimitMb: 5,
}),
},
})
return (this.project_id = 'project-id')
})
describe('checkRecoursesForProblems', function () {
beforeEach(function () {
return (this.resources = [
{
path: 'main.tex',
content: 'stuff',
},
{
path: 'chapters/chapter1',
content: 'other stuff',
},
{
path: 'stuff/image/image.png',
url: `http:somewhere.com/project/${this.project_id}/file/1234124321312`,
modified: 'more stuff',
},
])
})
it('should call _checkDocsAreUnderSizeLimit and _checkForConflictingPaths', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null)
this.ClsiFormatChecker._checkDocsAreUnderSizeLimit = sinon
.stub()
.callsArgWith(1)
return this.ClsiFormatChecker.checkRecoursesForProblems(
this.resources,
(err, problems) => {
this.ClsiFormatChecker._checkForConflictingPaths.called.should.equal(
true
)
this.ClsiFormatChecker._checkDocsAreUnderSizeLimit.called.should.equal(
true
)
return done()
}
)
})
it('should remove undefined errors', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null, [])
this.ClsiFormatChecker._checkDocsAreUnderSizeLimit = sinon
.stub()
.callsArgWith(1, null, {})
return this.ClsiFormatChecker.checkRecoursesForProblems(
this.resources,
(err, problems) => {
expect(problems).to.not.exist
expect(problems).to.not.exist
return done()
}
)
})
it('should keep populated arrays', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null, [{ path: 'somewhere/main.tex' }])
this.ClsiFormatChecker._checkDocsAreUnderSizeLimit = sinon
.stub()
.callsArgWith(1, null, {})
return this.ClsiFormatChecker.checkRecoursesForProblems(
this.resources,
(err, problems) => {
problems.conflictedPaths[0].path.should.equal('somewhere/main.tex')
expect(problems.sizeCheck).to.not.exist
return done()
}
)
})
it('should keep populated object', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null, [])
this.ClsiFormatChecker._checkDocsAreUnderSizeLimit = sinon
.stub()
.callsArgWith(1, null, {
resources: [{ 'a.tex': 'a.tex' }, { 'b.tex': 'b.tex' }],
totalSize: 1000000,
})
return this.ClsiFormatChecker.checkRecoursesForProblems(
this.resources,
(err, problems) => {
problems.sizeCheck.resources.length.should.equal(2)
problems.sizeCheck.totalSize.should.equal(1000000)
expect(problems.conflictedPaths).to.not.exist
return done()
}
)
})
describe('_checkForConflictingPaths', function () {
beforeEach(function () {
this.resources.push({
path: 'chapters/chapter1.tex',
content: 'other stuff',
})
return this.resources.push({
path: 'chapters.tex',
content: 'other stuff',
})
})
it('should flag up when a nested file has folder with same subpath as file elsewhere', function (done) {
this.resources.push({
path: 'stuff/image',
url: 'http://somwhere.com',
})
return this.ClsiFormatChecker._checkForConflictingPaths(
this.resources,
(err, conflictPathErrors) => {
conflictPathErrors.length.should.equal(1)
conflictPathErrors[0].path.should.equal('stuff/image')
return done()
}
)
})
it('should flag up when a root level file has folder with same subpath as file elsewhere', function (done) {
this.resources.push({
path: 'stuff',
content: 'other stuff',
})
return this.ClsiFormatChecker._checkForConflictingPaths(
this.resources,
(err, conflictPathErrors) => {
conflictPathErrors.length.should.equal(1)
conflictPathErrors[0].path.should.equal('stuff')
return done()
}
)
})
it('should not flag up when the file is a substring of a path', function (done) {
this.resources.push({
path: 'stuf',
content: 'other stuff',
})
return this.ClsiFormatChecker._checkForConflictingPaths(
this.resources,
(err, conflictPathErrors) => {
conflictPathErrors.length.should.equal(0)
return done()
}
)
})
})
describe('_checkDocsAreUnderSizeLimit', function () {
it('should error when there is more than 5mb of data', function (done) {
this.resources.push({
path: 'massive.tex',
content: 'hello world'.repeat(833333), // over 5mb limit
})
while (this.resources.length < 20) {
this.resources.push({
path: 'chapters/chapter1.tex',
url: 'http://somwhere.com',
})
}
return this.ClsiFormatChecker._checkDocsAreUnderSizeLimit(
this.resources,
(err, sizeError) => {
sizeError.totalSize.should.equal(16 + 833333 * 11) // 16 is for earlier resources
sizeError.resources.length.should.equal(10)
sizeError.resources[0].path.should.equal('massive.tex')
sizeError.resources[0].size.should.equal(833333 * 11)
return done()
}
)
})
it('should return nothing when project is correct size', function (done) {
this.resources.push({
path: 'massive.tex',
content: 'x'.repeat(2 * 1000 * 1000),
})
while (this.resources.length < 20) {
this.resources.push({
path: 'chapters/chapter1.tex',
url: 'http://somwhere.com',
})
}
return this.ClsiFormatChecker._checkDocsAreUnderSizeLimit(
this.resources,
(err, sizeError) => {
expect(sizeError).to.not.exist
return done()
}
)
})
})
})
})
| overleaf/web/test/unit/src/Compile/ClsiFormatCheckerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Compile/ClsiFormatCheckerTests.js",
"repo_id": "overleaf",
"token_count": 3391
} | 578 |
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const { expect } = require('chai')
const { ObjectId } = require('mongodb')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const MODULE_PATH = '../../../../app/src/Features/Editor/EditorHttpController'
describe('EditorHttpController', function () {
beforeEach(function () {
this.ownerId = new ObjectId()
this.project = {
_id: new ObjectId(),
owner_ref: this.ownerId,
}
this.user = {
_id: new ObjectId(),
projects: {},
}
this.projectView = {
_id: this.project._id,
owner: {
_id: 'owner',
email: 'owner@example.com',
other_property: true,
},
members: [{ one: 1 }, { two: 2 }],
}
this.reducedProjectView = {
_id: this.projectView._id,
owner: { _id: this.projectView.owner._id },
members: [],
}
this.doc = { _id: new ObjectId(), name: 'excellent-original-idea.tex' }
this.file = { _id: new ObjectId() }
this.folder = { _id: new ObjectId() }
this.parentFolderId = 'mock-folder-id'
this.req = { i18n: { translate: string => string } }
this.res = {
send: sinon.stub().returns(this.res),
status: sinon.stub().returns(this.res),
sendStatus: sinon.stub().returns(this.res),
json: sinon.stub().returns(this.res),
}
this.next = sinon.stub()
this.token = null
this.docLines = ['hello', 'overleaf']
this.AuthorizationManager = {
isRestrictedUser: sinon.stub().returns(false),
promises: {
getPrivilegeLevelForProject: sinon.stub().resolves('owner'),
},
}
this.CollaboratorsGetter = {
promises: {
getInvitedMembersWithPrivilegeLevels: sinon
.stub()
.resolves(['members', 'mock']),
},
}
this.CollaboratorsHandler = {
promises: {
userIsTokenMember: sinon.stub().resolves(false),
},
}
this.CollaboratorsInviteHandler = {
promises: {
getAllInvites: sinon.stub().resolves([
{
_id: 'invite_one',
email: 'user-one@example.com',
privileges: 'readOnly',
projectId: this.project._id,
},
{
_id: 'invite_two',
email: 'user-two@example.com',
privileges: 'readOnly',
projectId: this.project._id,
},
]),
},
}
this.EditorController = {
promises: {
addDoc: sinon.stub().resolves(this.doc),
addFile: sinon.stub().resolves(this.file),
addFolder: sinon.stub().resolves(this.folder),
renameEntity: sinon.stub().resolves(),
moveEntity: sinon.stub().resolves(),
deleteEntity: sinon.stub().resolves(),
},
}
this.ProjectDeleter = {
promises: {
unmarkAsDeletedByExternalSource: sinon.stub().resolves(),
},
}
this.ProjectGetter = {
promises: {
getProjectWithoutDocLines: sinon.stub().resolves(this.project),
},
}
this.ProjectEditorHandler = {
buildProjectModelView: sinon.stub().returns(this.projectView),
}
this.Metrics = { inc: sinon.stub() }
this.TokenAccessHandler = {
getRequestToken: sinon.stub().returns(this.token),
protectTokens: sinon.stub(),
}
this.SessionManager = {
getLoggedInUserId: sinon.stub().returns(this.user._id),
}
this.ProjectEntityUpdateHandler = {
promises: {
convertDocToFile: sinon.stub().resolves(this.file),
},
}
this.DocstoreManager = {
promises: {
getAllDeletedDocs: sinon.stub().resolves([]),
},
}
this.HttpErrorHandler = {
notFound: sinon.stub(),
unprocessableEntity: sinon.stub(),
}
this.EditorHttpController = SandboxedModule.require(MODULE_PATH, {
requires: {
'../Project/ProjectDeleter': this.ProjectDeleter,
'../Project/ProjectGetter': this.ProjectGetter,
'../Authorization/AuthorizationManager': this.AuthorizationManager,
'../Project/ProjectEditorHandler': this.ProjectEditorHandler,
'./EditorController': this.EditorController,
'@overleaf/metrics': this.Metrics,
'../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter,
'../Collaborators/CollaboratorsHandler': this.CollaboratorsHandler,
'../Collaborators/CollaboratorsInviteHandler': this
.CollaboratorsInviteHandler,
'../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
'../Authentication/SessionManager': this.SessionManager,
'../../infrastructure/FileWriter': this.FileWriter,
'../Project/ProjectEntityUpdateHandler': this
.ProjectEntityUpdateHandler,
'../Docstore/DocstoreManager': this.DocstoreManager,
'../Errors/HttpErrorHandler': this.HttpErrorHandler,
},
})
})
describe('joinProject', function () {
beforeEach(function () {
this.req.params = { Project_id: this.project._id }
this.req.query = { user_id: this.user._id }
})
describe('successfully', function () {
beforeEach(function (done) {
this.res.json.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res)
})
it('should return the project and privilege level', function () {
expect(this.res.json).to.have.been.calledWith({
project: this.projectView,
privilegeLevel: 'owner',
isRestrictedUser: false,
})
})
it('should not try to unmark the project as deleted', function () {
expect(this.ProjectDeleter.promises.unmarkAsDeletedByExternalSource).not
.to.have.been.called
})
it('should send an inc metric', function () {
expect(this.Metrics.inc).to.have.been.calledWith('editor.join-project')
})
})
describe('when the project is marked as deleted', function () {
beforeEach(function (done) {
this.projectView.deletedByExternalDataSource = true
this.res.json.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res)
})
it('should unmark the project as deleted', function () {
expect(
this.ProjectDeleter.promises.unmarkAsDeletedByExternalSource
).to.have.been.calledWith(this.project._id)
})
})
describe('with a restricted user', function () {
beforeEach(function (done) {
this.AuthorizationManager.isRestrictedUser.returns(true)
this.AuthorizationManager.promises.getPrivilegeLevelForProject.resolves(
'readOnly'
)
this.res.json.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res)
})
it('should mark the user as restricted, and hide details of owner', function () {
expect(this.res.json).to.have.been.calledWith({
project: this.reducedProjectView,
privilegeLevel: 'readOnly',
isRestrictedUser: true,
})
})
})
describe('when not authorized', function () {
beforeEach(function (done) {
this.AuthorizationManager.promises.getPrivilegeLevelForProject.resolves(
null
)
this.res.sendStatus.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res)
})
it('should send a 403 response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(403)
})
})
describe('with an anonymous user', function () {
beforeEach(function (done) {
this.req.query = { user_id: 'anonymous-user' }
this.res.json.callsFake(() => done())
this.AuthorizationManager.isRestrictedUser
.withArgs(null, 'readOnly', false)
.returns(true)
this.AuthorizationManager.promises.getPrivilegeLevelForProject
.withArgs(null, this.project._id, this.token)
.resolves('readOnly')
this.EditorHttpController.joinProject(this.req, this.res)
})
it('should mark the user as restricted', function () {
expect(this.res.json).to.have.been.calledWith({
project: this.reducedProjectView,
privilegeLevel: 'readOnly',
isRestrictedUser: true,
})
})
})
describe('when project is not found', function () {
beforeEach(function (done) {
this.ProjectGetter.promises.getProjectWithoutDocLines.resolves(null)
this.next.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res, this.next)
})
it('should handle return not found error', function () {
expect(this.next).to.have.been.calledWith(
sinon.match.instanceOf(Errors.NotFoundError)
)
})
})
})
describe('addDoc', function () {
beforeEach(function () {
this.req.params = { Project_id: this.project._id }
this.req.body = {
name: (this.name = 'doc-name'),
parent_folder_id: this.parentFolderId,
}
})
describe('successfully', function () {
beforeEach(function (done) {
this.res.json.callsFake(() => done())
this.EditorHttpController.addDoc(this.req, this.res)
})
it('should call EditorController.addDoc', function () {
expect(this.EditorController.promises.addDoc).to.have.been.calledWith(
this.project._id,
this.parentFolderId,
this.name,
[],
'editor',
this.user._id
)
})
it('should send the doc back as JSON', function () {
expect(this.res.json).to.have.been.calledWith(this.doc)
})
})
describe('unsuccesfully', function () {
it('handle name too short', function (done) {
this.req.body.name = ''
this.res.sendStatus.callsFake(status => {
expect(status).to.equal(400)
done()
})
this.EditorHttpController.addDoc(this.req, this.res)
})
it('handle too many files', function (done) {
this.EditorController.promises.addDoc.rejects(
new Error('project_has_too_many_files')
)
this.res.json.callsFake(payload => {
expect(payload).to.equal('project_has_too_many_files')
expect(this.res.status).to.have.been.calledWith(400)
done()
})
this.res.status.returns(this.res)
this.EditorHttpController.addDoc(this.req, this.res)
})
})
})
describe('addFolder', function () {
beforeEach(function () {
this.folderName = 'folder-name'
this.req.params = { Project_id: this.project._id }
this.req.body = {
name: this.folderName,
parent_folder_id: this.parentFolderId,
}
})
describe('successfully', function () {
beforeEach(function (done) {
this.res.json.callsFake(() => done())
this.EditorHttpController.addFolder(this.req, this.res)
})
it('should call EditorController.addFolder', function () {
expect(
this.EditorController.promises.addFolder
).to.have.been.calledWith(
this.project._id,
this.parentFolderId,
this.folderName,
'editor'
)
})
it('should send the folder back as JSON', function () {
expect(this.res.json).to.have.been.calledWith(this.folder)
})
})
describe('unsuccesfully', function () {
it('handle name too short', function (done) {
this.req.body.name = ''
this.res.sendStatus.callsFake(status => {
expect(status).to.equal(400)
done()
})
this.EditorHttpController.addFolder(this.req, this.res)
})
it('handle too many files', function (done) {
this.EditorController.promises.addFolder.rejects(
new Error('project_has_too_many_files')
)
this.res.json.callsFake(payload => {
expect(payload).to.equal('project_has_too_many_files')
expect(this.res.status).to.have.been.calledWith(400)
done()
})
this.res.status.returns(this.res)
this.EditorHttpController.addFolder(this.req, this.res)
})
it('handle invalid element name', function (done) {
this.EditorController.promises.addFolder.rejects(
new Error('invalid element name')
)
this.res.json.callsFake(payload => {
expect(payload).to.equal('invalid_file_name')
expect(this.res.status).to.have.been.calledWith(400)
done()
})
this.res.status.returns(this.res)
this.EditorHttpController.addFolder(this.req, this.res)
})
})
})
describe('renameEntity', function () {
beforeEach(function () {
this.entityId = 'entity-id-123'
this.entityType = 'entity-type'
this.req.params = {
Project_id: this.project._id,
entity_id: this.entityId,
entity_type: this.entityType,
}
})
describe('successfully', function () {
beforeEach(function (done) {
this.newName = 'new-name'
this.req.body = { name: this.newName }
this.res.sendStatus.callsFake(() => done())
this.EditorHttpController.renameEntity(this.req, this.res)
})
it('should call EditorController.renameEntity', function () {
expect(
this.EditorController.promises.renameEntity
).to.have.been.calledWith(
this.project._id,
this.entityId,
this.entityType,
this.newName,
this.user._id
)
})
it('should send back a success response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(204)
})
})
describe('with long name', function () {
beforeEach(function () {
this.newName = 'long'.repeat(100)
this.req.body = { name: this.newName }
this.EditorHttpController.renameEntity(this.req, this.res)
})
it('should send back a bad request status code', function () {
expect(this.res.sendStatus).to.have.been.calledWith(400)
})
})
describe('with 0 length name', function () {
beforeEach(function () {
this.newName = ''
this.req.body = { name: this.newName }
this.EditorHttpController.renameEntity(this.req, this.res)
})
it('should send back a bad request status code', function () {
expect(this.res.sendStatus).to.have.been.calledWith(400)
})
})
})
describe('moveEntity', function () {
beforeEach(function (done) {
this.entityId = 'entity-id-123'
this.entityType = 'entity-type'
this.folderId = 'folder-id-123'
this.req.params = {
Project_id: this.project._id,
entity_id: this.entityId,
entity_type: this.entityType,
}
this.req.body = { folder_id: this.folderId }
this.res.sendStatus.callsFake(() => done())
this.EditorHttpController.moveEntity(this.req, this.res)
})
it('should call EditorController.moveEntity', function () {
expect(this.EditorController.promises.moveEntity).to.have.been.calledWith(
this.project._id,
this.entityId,
this.folderId,
this.entityType,
this.user._id
)
})
it('should send back a success response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(204)
})
})
describe('deleteEntity', function () {
beforeEach(function (done) {
this.entityId = 'entity-id-123'
this.entityType = 'entity-type'
this.req.params = {
Project_id: this.project._id,
entity_id: this.entityId,
entity_type: this.entityType,
}
this.res.sendStatus.callsFake(() => done())
this.EditorHttpController.deleteEntity(this.req, this.res)
})
it('should call EditorController.deleteEntity', function () {
expect(
this.EditorController.promises.deleteEntity
).to.have.been.calledWith(
this.project._id,
this.entityId,
this.entityType,
'editor',
this.user._id
)
})
it('should send back a success response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(204)
})
})
describe('convertDocToFile', function () {
beforeEach(function (done) {
this.req.params = {
Project_id: this.project._id.toString(),
entity_id: this.doc._id.toString(),
}
this.req.body = { userId: this.user._id.toString() }
this.res.json.callsFake(() => done())
this.EditorHttpController.convertDocToFile(this.req, this.res)
})
describe('when successful', function () {
it('should convert the doc to a file', function () {
expect(
this.ProjectEntityUpdateHandler.promises.convertDocToFile
).to.have.been.calledWith(
this.project._id.toString(),
this.doc._id.toString(),
this.user._id.toString()
)
})
it('should return the file id in the response', function () {
expect(this.res.json).to.have.been.calledWith({
fileId: this.file._id.toString(),
})
})
})
describe('when the doc has ranges', function () {
it('should return a 422 - Unprocessable Entity', function (done) {
this.ProjectEntityUpdateHandler.promises.convertDocToFile.rejects(
new Errors.DocHasRangesError({})
)
this.HttpErrorHandler.unprocessableEntity = sinon.spy(
(req, res, message) => {
expect(req).to.exist
expect(res).to.exist
expect(message).to.equal('Document has comments or tracked changes')
done()
}
)
this.EditorHttpController.convertDocToFile(this.req, this.res)
})
})
describe("when the doc does't exist", function () {
it('should return a 404 - not found', function (done) {
this.ProjectEntityUpdateHandler.promises.convertDocToFile.rejects(
new Errors.NotFoundError({})
)
this.HttpErrorHandler.notFound = sinon.spy((req, res, message) => {
expect(req).to.exist
expect(res).to.exist
expect(message).to.equal('Document not found')
done()
})
this.EditorHttpController.convertDocToFile(this.req, this.res)
})
})
})
})
| overleaf/web/test/unit/src/Editor/EditorHttpControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Editor/EditorHttpControllerTests.js",
"repo_id": "overleaf",
"token_count": 8014
} | 579 |
const { expect } = require('chai')
const SandboxedModule = require('sandboxed-module')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Helpers/UrlHelper.js'
)
describe('UrlHelper', function () {
beforeEach(function () {
this.settings = {
apis: { linkedUrlProxy: { url: undefined } },
siteUrl: 'http://localhost:3000',
}
this.UrlHelper = SandboxedModule.require(modulePath, {
requires: { '@overleaf/settings': this.settings },
})
})
describe('getSafeRedirectPath', function () {
it('sanitize redirect path to prevent open redirects', function () {
expect(this.UrlHelper.getSafeRedirectPath('https://evil.com')).to.be
.undefined
expect(this.UrlHelper.getSafeRedirectPath('//evil.com')).to.be.undefined
expect(this.UrlHelper.getSafeRedirectPath('//ol.com/evil')).to.equal(
'/evil'
)
expect(this.UrlHelper.getSafeRedirectPath('////evil.com')).to.be.undefined
expect(this.UrlHelper.getSafeRedirectPath('%2F%2Fevil.com')).to.equal(
'/%2F%2Fevil.com'
)
expect(
this.UrlHelper.getSafeRedirectPath('http://foo.com//evil.com/bad')
).to.equal('/evil.com/bad')
return expect(this.UrlHelper.getSafeRedirectPath('.evil.com')).to.equal(
'/.evil.com'
)
})
})
})
| overleaf/web/test/unit/src/HelperFiles/UrlHelperTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/HelperFiles/UrlHelperTests.js",
"repo_id": "overleaf",
"token_count": 545
} | 580 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const { assert } = require('chai')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Notifications/NotificationsHandler.js'
)
const _ = require('underscore')
describe('NotificationsHandler', function () {
const user_id = '123nd3ijdks'
const notification_id = '123njdskj9jlk'
const notificationUrl = 'notification.sharelatex.testing'
beforeEach(function () {
this.request = sinon.stub().callsArgWith(1)
return (this.handler = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': {
apis: { notifications: { url: notificationUrl } },
},
request: this.request,
},
}))
})
describe('getUserNotifications', function () {
it('should get unread notifications', function (done) {
const stubbedNotifications = [{ _id: notification_id, user_id }]
this.request.callsArgWith(
1,
null,
{ statusCode: 200 },
stubbedNotifications
)
return this.handler.getUserNotifications(
user_id,
(err, unreadNotifications) => {
stubbedNotifications.should.deep.equal(unreadNotifications)
const getOpts = {
uri: `${notificationUrl}/user/${user_id}`,
json: true,
timeout: 1000,
method: 'GET',
}
this.request.calledWith(getOpts).should.equal(true)
return done()
}
)
})
it('should return empty arrays if there are no notifications', function () {
this.request.callsArgWith(1, null, { statusCode: 200 }, null)
return this.handler.getUserNotifications(
user_id,
(err, unreadNotifications) => {
return unreadNotifications.length.should.equal(0)
}
)
})
})
describe('markAsRead', function () {
beforeEach(function () {
return (this.key = 'some key here')
})
it('should send a delete request when a delete has been received to mark a notification', function (done) {
return this.handler.markAsReadWithKey(user_id, this.key, () => {
const opts = {
uri: `${notificationUrl}/user/${user_id}`,
json: {
key: this.key,
},
timeout: 1000,
method: 'DELETE',
}
this.request.calledWith(opts).should.equal(true)
return done()
})
})
})
describe('createNotification', function () {
beforeEach(function () {
this.key = 'some key here'
this.messageOpts = { value: 12344 }
this.templateKey = 'renderThisHtml'
return (this.expiry = null)
})
it('should post the message over', function (done) {
return this.handler.createNotification(
user_id,
this.key,
this.templateKey,
this.messageOpts,
this.expiry,
() => {
const args = this.request.args[0][0]
args.uri.should.equal(`${notificationUrl}/user/${user_id}`)
args.timeout.should.equal(1000)
const expectedJson = {
key: this.key,
templateKey: this.templateKey,
messageOpts: this.messageOpts,
forceCreate: true,
}
assert.deepEqual(args.json, expectedJson)
return done()
}
)
})
describe('when expiry date is supplied', function () {
beforeEach(function () {
this.key = 'some key here'
this.messageOpts = { value: 12344 }
this.templateKey = 'renderThisHtml'
return (this.expiry = new Date())
})
it('should post the message over with expiry field', function (done) {
return this.handler.createNotification(
user_id,
this.key,
this.templateKey,
this.messageOpts,
this.expiry,
() => {
const args = this.request.args[0][0]
args.uri.should.equal(`${notificationUrl}/user/${user_id}`)
args.timeout.should.equal(1000)
const expectedJson = {
key: this.key,
templateKey: this.templateKey,
messageOpts: this.messageOpts,
expires: this.expiry,
forceCreate: true,
}
assert.deepEqual(args.json, expectedJson)
return done()
}
)
})
})
})
describe('markAsReadByKeyOnly', function () {
beforeEach(function () {
return (this.key = 'some key here')
})
it('should send a delete request when a delete has been received to mark a notification', function (done) {
return this.handler.markAsReadByKeyOnly(this.key, () => {
const opts = {
uri: `${notificationUrl}/key/${this.key}`,
timeout: 1000,
method: 'DELETE',
}
this.request.calledWith(opts).should.equal(true)
return done()
})
})
})
})
| overleaf/web/test/unit/src/Notifications/NotificationsHandlerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Notifications/NotificationsHandlerTests.js",
"repo_id": "overleaf",
"token_count": 2404
} | 581 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.