text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
---
title: SetPlayerArmour
description: Set a player's armor level.
tags: ["player"]
---
## คำอธิบาย
Set a player's armor level.
| Name | Description |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player to set the armour of. |
| Float:armour | The amount of armour to set, as a percentage (float). Values larger than 100 are valid, but won't be displayed in the HUD's armour bar. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute. This means the player specified does not exist.
## ตัวอย่าง
```c
public OnPlayerSpawn(playerid)
{
// Give players full armour (100%) when they spawn.
SetPlayerArmour(playerid, 100.0);
return 1;
}
```
## บันทึก
:::tip
The function's name is armour, not armor (Americanized). This is inconsistent with the rest of SA-MP, so remember that.
:::
:::warning
Armour is obtained rounded to integers: set 50.15, but get 50.0
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerArmour: Find out how much armour a player has.
- SetPlayerHealth: Set a player's health.
- GetPlayerHealth: Find out how much health a player has.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerArmour.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerArmour.md",
"repo_id": "openmultiplayer",
"token_count": 665
} | 438 |
---
title: SetPlayerObjectMaterial
description: Replace the texture of a player-object with the texture from another model in the game.
tags: ["player"]
---
## คำอธิบาย
Replace the texture of a player-object with the texture from another model in the game.
| Name | Description |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| playerid | The ID of the player the object is associated to. |
| objectid | The ID of the object to replace the texture of |
| materialindex | The material index on the object to change (0 to 15) |
| modelid | The modelid on which replacement texture is located. Use 0 for alpha. Use -1 to change the material color without altering the existing texture. |
| txdname | The name of the txd file which contains the replacement texture (use "none" if not required) |
| texturename | The name of the texture to use as the replacement (use "none" if not required) |
| materialcolor | The object color to set, as an integer or hex in ARGB format. Using 0 keeps the existing material color. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext,"/objmat",true))
{
new Float:X, Float:Y, Float:Z;
new myobject;
GetPlayerPos(playerid, X, Y, Z);
myobject = CreatePlayerObject(playerid, 19371, X, Y, Z+0.5, 0.0, 0.0, 0.0, 300.0);
SetPlayerObjectMaterial(playerid, myobject, 0, 19341, "egg_texts", "easter_egg01", 0xFFFFFFFF);
// Replaces the texture of our player-object with the texture of model 19341
return 1;
}
return 0;
}
```
## บันทึก
:::tip
Vertex lightning of the object will disappear if material color is changed.
:::
:::warning
You MUST use ARGB color format, not RGBA like used in client messages etc.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetObjectMaterial: Replace the texture of an object with the texture from another model in the game.
- Ultimate Creator by Nexius
- Texture Studio by [uL]Pottus
- Fusez's Map Editor by RedFusion
- Map Editor I by adri1
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerObjectMaterial.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerObjectMaterial.md",
"repo_id": "openmultiplayer",
"token_count": 1348
} | 439 |
---
title: SetPlayerVirtualWorld
description: Set the virtual world of a player.
tags: ["player"]
---
## คำอธิบาย
Set the virtual world of a player. They can only see other players or vehicles that are in that same world.
| Name | Description |
| -------- | ---------------------------------------------------------- |
| playerid | The ID of the player you want to set the virtual world of. |
| worldid | The virtual world ID to put the player in. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player is not connected.
## ตัวอย่าง
```c
if (strcmp(cmdtext, "/world3", true) == 0)
{
SetPlayerVirtualWorld(playerid, 3);
return 1;
}
```
## บันทึก
:::tip
The default virtual world is 0.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerVirtualWorld: Check what virtual world a player is in.
- SetVehicleVirtualWorld: Set the virtual world of a vehicle.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerVirtualWorld.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerVirtualWorld.md",
"repo_id": "openmultiplayer",
"token_count": 427
} | 440 |
---
title: SetVehicleParamsEx
description: Sets a vehicle's parameters for all players.
tags: ["vehicle"]
---
## คำอธิบาย
Sets a vehicle's parameters for all players.
| Name | Description |
| --------- | --------------------------------------------------------------- |
| vehicleid | The ID of the vehicle to set the parameters of. |
| engine | Engine status. 0 - Off, 1 - On. |
| lights | Light status. 0 - Off, 1 - On. |
| alarm | Vehicle alarm status. If on, the alarm starts. 0 - Off, 1 - On. |
| doors | Door lock status. 0 - Unlocked, 1 - Locked. |
| bonnet | Bonnet (hood) status. 0 - Closed, 1 - Open. |
| boot | Boot/trunk status. 0 - Closed, 1 - Open. |
| objective | Toggle the objective arrow above the vehicle. 0 - Off, 1 - On. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the vehicle does not exist.
## ตัวอย่าง
```c
// If setting a single parameter, you should obtain the current parameters so they aren't ALL changed
new engine, lights, alarm, doors, bonnet, boot, objective;
GetVehicleParamsEx(vehicleid, engine, lights, alarm, doors, bonnet, boot, objective);
SetVehicleParamsEx(vehicleid, VEHICLE_PARAMS_ON, lights, alarm, doors, bonnet, boot, objective); // ONLY the engine param was changed to VEHICLE_PARAMS_ON (1)
new Timer_VehAlarm[MAX_VEHICLES];
SetVehicleParamsEx_Fixed(vehicleid, &engine, &lights, &alarm, &doors, &bonnet, &boot, &objective)
{
SetVehicleParamsEx(vehicleid, engine, lights, alarm, doors, bonnet, boot, objective);
if (alarm)
{
KillTimer(Timer_VehAlarm[vehicleid]);
Timer_VehAlarm[vehicleid] = SetTimerEx("DisableVehicleAlarm", 20000, false, "d", vehicleid);
}
}
forward DisableVehicleAlarm(vehicleid);
public DisableVehicleAlarm(vehicleid)
{
new engine, lights, alarm, doors, bonnet, boot, objective;
GetVehicleParamsEx(vehicleid, engine, lights, alarm, doors, bonnet, boot, objective);
if (alarm == VEHICLE_PARAMS_ON)
{
SetVehicleParamsEx(vehicleid, engine, lights, VEHICLE_PARAMS_OFF, doors, bonnet, boot, objective);
}
}
```
## บันทึก
:::tip
The alarm will not reset when finished, you'll need to reset it by yourself with this function. Lights also operate during the day (Only when ManualVehicleEngineAndLights is enabled).
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetVehicleParamsEx: Get a vehicle's parameters.
- SetVehicleParamsForPlayer: Set the parameters of a vehicle for a player.
- UpdateVehicleDamageStatus: Update the vehicle damage.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleParamsEx.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleParamsEx.md",
"repo_id": "openmultiplayer",
"token_count": 1130
} | 441 |
---
title: StopAudioStreamForPlayer
description: Stops the current audio stream for a player.
tags: ["player"]
---
:::warning
This function was added in SA-MP 0.3d and will not work in earlier versions!
:::
## คำอธิบาย
Stops the current audio stream for a player.
| Name | Description |
| -------- | ------------------------------------------------- |
| playerid | The player you want to stop the audio stream for. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
// If the player exits a vehicle
if (oldstate == PLAYER_STATE_DRIVER || oldstate == PLAYER_STATE_PASSENGER)
{
StopAudioStreamForPlayer(playerid); // Stop the audio stream
}
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- PlayAudioStreamForPlayer: Plays a audio stream for a player.
- PlayerPlaySound: Play a sound for a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/StopAudioStreamForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/StopAudioStreamForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 420
} | 442 |
---
title: TextDrawSetPreviewModel
description: Set the model for a textdraw model preview.
tags: ["textdraw"]
---
## คำอธิบาย
Set the model for a textdraw model preview. Click here to see this function's effect.
| Name | Description |
| ---------- | ------------------------------------------------- |
| text | The textdraw id that will display the 3D preview. |
| modelindex | The GTA SA or SA:MP model ID to display. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
new Text:textdraw;
public OnGameModeInit()
{
textdraw = TextDrawCreate(320.0, 240.0, "_");
TextDrawFont(textdraw, TEXT_DRAW_FONT_MODEL_PREVIEW);
TextDrawUseBox(textdraw, true);
TextDrawBoxColor(textdraw, 0x000000FF);
TextDrawTextSize(textdraw, 40.0, 40.0);
TextDrawSetPreviewModel(textdraw, 411); //Display model 411 (Infernus)
//TextDrawSetPreviewModel(textdraw, 1); //Display model 1 (CJ Skin)
//TextDrawSetPreviewModel(textdraw, 18646); //Display model 18646 (Police light object)
//You still have to use TextDrawShowForAll/TextDrawShowForPlayer to make the textdraw visible.
return 1;
}
```
## บันทึก
:::tip
Use [TextDrawBackgroundColor](TextDrawBackgroundColor) to set the background color behind the model.
:::
:::warning
The textdraw MUST use the font type `TEXT_DRAW_FONT_MODEL_PREVIEW` in order for this function to have effect.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [TextDrawSetPreviewRot](../functions/TextDrawSetPreviewRot.md): Set rotation of a 3D textdraw preview.
- [TextDrawSetPreviewVehCol](../functions/TextDrawSetPreviewVehCol.md): Set the colours of a vehicle in a 3D textdraw preview.
- [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw.
- [PlayerTextDrawSetPreviewModel](../functions/PlayerTextDrawSetPreviewModel.md): Set model ID of a 3D player textdraw preview.
## Related Callbacks
- [OnPlayerClickTextDraw](../callbacks/OnPlayerClickTextDraw.md): Called when a player clicks on a textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetPreviewModel.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetPreviewModel.md",
"repo_id": "openmultiplayer",
"token_count": 785
} | 443 |
---
title: Update3DTextLabelText
description: Updates a 3D Text Label text and color.
tags: ["3dtextlabel"]
---
## คำอธิบาย
Updates a 3D Text Label text and color.
| Name | Description |
| --------- | ------------------------------------------------------------- |
| Text3D:textid | The 3D Text Label you want to update. |
| color | The color the 3D Text Label should have from now on. |
| text[] | The new text which the 3D Text Label should have from now on. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnGameModeInit()
{
new Text3D:mylabel;
mylabel = Create3DTextLabel("I'm at the coordinates:\n30.0,40.0,50.0",0x008080FF,30.0,40.0,50.0,40.0,0);
Update3DTextLabelText(mylabel, 0xFFFFFFFF, "New text.");
return 1;
}
```
## บันทึก
:::warning
If text[] is empty, the server/clients next to the text might crash!
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [Create3DTextLabel](../functions/Create3DTextLabel.md): Create a 3D text label.
- [Delete3DTextLabel](../functions/Delete3DTextLabel.md): Delete a 3D text label.
- [Attach3DTextLabelToPlayer](../functions/Attach3DTextLabelToPlayer.md): Attach a 3D text label to a player.
- [Attach3DTextLabelToVehicle](../functions/Attach3DTextLabelToVehicle.md): Attach a 3D text label to a vehicle.
- [CreatePlayer3DTextLabel](../functions/CreatePlayer3DTextLabel.md): Create A 3D text label for one player.
- [DeletePlayer3DTextLabel](../functions/DeletePlayer3DTextLabel.md): Delete a player's 3D text label.
- [UpdatePlayer3DTextLabelText](../functions/UpdatePlayer3DTextLabelText.md): Change the text of a player's 3D text label.
| openmultiplayer/web/docs/translations/th/scripting/functions/Update3DTextLabelText.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/Update3DTextLabelText.md",
"repo_id": "openmultiplayer",
"token_count": 735
} | 444 |
---
title: fclose
description: Closes a file.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Closes a file. Files should always be closed when the script no longer needs them (after reading/writing).
| Name | Description |
| ----------- | -------------------------------------------- |
| File:handle | The file handle to close. Returned by fopen. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The file could not be closed. It may already be closed.
## ตัวอย่าง
```c
// Open "file.txt" in "append only" mode
new File:handle = fopen("file.txt", io_append);
// Check, if file is open
if (handle)
{
// Success
// Write "Hi there!" into the file
fwrite(handle, "Hi there!");
// Close the file
fclose(handle);
}
else
{
// Error
print("Failed to open file \"file.txt\".");
}
```
## บันทึก
:::warning
Using an invalid handle will crash your server! Get a valid handle by using fopen or ftemp.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [fopen](../functions/fopen): Open a file.
- [ftemp](../functions/ftemp): Create a temporary file stream.
- [fremove](../functions/fremove): Remove a file.
- [fwrite](../functions/fwrite): Write to a file.
- [fread](../functions/fread): Read a file.
- [fputchar](../functions/fputchar): Put a character in a file.
- [fgetchar](../functions/fgetchar): Get a character from a file.
- [fblockwrite](../functions/fblockwrite): Write blocks of data into a file.
- [fblockread](../functions/fblockread): Read blocks of data from a file.
- [fseek](../functions/fseek): Jump to a specific character in a file.
- [flength](../functions/flength): Get the file length.
- [fexist](../functions/fexist): Check, if a file exists.
- [fmatch](../functions/fmatch): Check, if patterns with a file name matches.
| openmultiplayer/web/docs/translations/th/scripting/functions/fclose.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fclose.md",
"repo_id": "openmultiplayer",
"token_count": 728
} | 445 |
---
title: floatsqroot
description: Calculates the square root of given value.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Calculates the square root of given value.
| Name | Description |
| ----- | ------------------------------------------ |
| value | The value to calculate the square root of. |
## ส่งคืน
The square root of the input value, as a float.
## ตัวอย่าง
```c
floatsqroot(25.0); // Returns 5, because 5x5 = 25
```
## บันทึก
:::tip
This function raises a “domain” error if the input value is negative. You may use floatabs to get the absolute (positive) value.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [floatpower](../functions/floatpower): Raises given value to a power of exponent.
- [floatlog](../functions/floatlog): Get the logarithm of the float value.
| openmultiplayer/web/docs/translations/th/scripting/functions/floatsqroot.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatsqroot.md",
"repo_id": "openmultiplayer",
"token_count": 375
} | 446 |
---
title: getproperty
description: Get a specific property from the memory, the string is returned as a packed string!.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Get a specific property from the memory, the string is returned as a packed string!
| Name | Description |
| -------- | ------------------------------------------------------------------------------ |
| id | The virtual machine to use, you should keep this zero. |
| name[] | The property's name, you should keep this "". |
| value | The property's unique ID, Use the hash-function to calculate it from a string. |
| string[] | The variable to store the result in, passed by reference. |
## ส่งคืน
The value of a property when the name is passed in; fills in the string argument when the value is passed in. If the property does not exist, this function returns zero.
## ตัวอย่าง
```c
new value[16];
getproperty(0, "", 123984334, value);
strunpack(value, value, sizeof(value));
print(value);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- Setproperty: Set a property.
- Deleteproperty: Delete a property.
- Existproperty: Check if a property exists.
| openmultiplayer/web/docs/translations/th/scripting/functions/getproperty.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/getproperty.md",
"repo_id": "openmultiplayer",
"token_count": 552
} | 447 |
---
title: strcat
description: This function concatenates (joins together) two strings into the destination string.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function concatenates (joins together) two strings into the destination string.
| Name | Description |
| --------------------- | ---------------------------------------------------- |
| dest[] | The string to store the two concatenated strings in. |
| const source[] | The source string. |
| maxlength=sizeof dest | The maximum length of the destination. |
## ส่งคืน
The length of the new destination string.
## ตัวอย่าง
```c
new string[40] = "Hello";
strcat(string, " World!");
// The string is now 'Hello World!'
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- strcmp: Compare two strings to check if they are the same.
- strfind: Search for a string in another string.
- strtok: Get the next 'token' (word/parameter) in a string.
- strdel: Delete part of a string.
- strins: Insert text into a string.
- strlen: Get the length of a string.
- strmid: Extract part of a string into another string.
- strpack: Pack a string into a destination string.
- strval: Convert a string into an integer.
| openmultiplayer/web/docs/translations/th/scripting/functions/strcat.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/strcat.md",
"repo_id": "openmultiplayer",
"token_count": 544
} | 448 |
---
title: Click Sources
description: Click Sources
---
To be used with [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer)
| Value | Constant symbol |
| ----- | ----------------------- |
| 0 | CLICK_SOURCE_SCOREBOARD |
| - | - |
| openmultiplayer/web/docs/translations/th/scripting/resources/clicksources.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/clicksources.md",
"repo_id": "openmultiplayer",
"token_count": 108
} | 449 |
---
title: Limits
description: A list of all limitations imposed by the game/server.
tags: []
---
## In-game Entities
| Type | Limit |
| ------------------------------------------------------------- | --------------- |
| Players | 1000 |
| Vehicles (4)(6) | 2000 |
| Vehicle Models (1) | Unlimited |
| Objects (4)(6) | 1000 |
| Virtual Worlds | 2,147,483,647 |
| Interiors | 256 |
| Classes | 320 |
| Map Icons (4) | 100 |
| Race Checkpoints (4) | 1 |
| Checkpoints (4) | 1 |
| Pickups (4) | 4096 |
| Global 3D Labels (4) | 1024 |
| Per-player 3D Text Labels (4) | 1024 |
| Chat Bubble String | 144 characters |
| SetObjectMaterialText,SetPlayerObjectMaterialText Text length | 2048 characters |
| Gangzones | 1024 |
| Menus | 128 |
| Attached player objects | 10 |
| Player Variables | 800 |
| Actors (since 0.3.7) (4)(5) | 1000 |
## Server Properties
| Type | Limit |
| --------------------------- | --------------------- |
| Gamemodes | 16 |
| Filterscripts | 16 |
| Text Input (Chat/Commands) | 128 cells (512 bytes) |
| Text Output | 144 cells (576 bytes) |
| Name Length (SetPlayerName) | 24 characters |
## Textdraws
| Type | Limit |
| ------------------------------------------- | --------------- |
| String Length (2) | 1024 characters |
| Shown In A Single Client's Screen (3) | 2048 + 256 |
| Shown In A Single Client's Screen (sprites) | 100 |
| Created Serverwise (Global) | 2048 |
| Created Serverwise (Per-Player) | 256 |
## Dialogs
| Type | Limit |
| ------------------------------------------------------------ | ----- |
| Dialog IDs | 32768 |
| Info (Main text) | 4096 |
| Caption | 64 |
| Input Text Box (DIALOG_STYLE_INPUT/PASSWORD) | 128 |
| Tab List Columns (DIALOG_STYLE_TABLIST(\_HEADERS)) | 4 |
| Tab List Column Characters (DIALOG_STYLE_TABLIST(\_HEADERS)) | 128 |
| Tab List Row Characters (DIALOG_STYLE_TABLIST(\_HEADERS)) | 256 |
Notes:
1. Although the vehicle model limit in 0.3 is unlimited, if you use a large amount of vehicle models then it will affect client performance.
2. Although the textdraw string limit is 1024 characters, if colour codes (e.g. ~r~) are used beyond the 255th character it may crash the client.
3. It is possible to show all Textdraws at the same time for one player, however this is not recommended.
4. To circumvent these limits, it is possible to use a [streamer](https://github.com/samp-incognito/samp-streamer-plugin). Streamers work by only creating the entities etc. that are close to players.
5. Due to client limitations only up to 51 actors may actually be shown at a time.
6. Vehicle IDs start at ID 1 and thus range from 1 to 1999, even if MAX_VEHICLES is 2000. Objects and player objects also start at ID 1.
| openmultiplayer/web/docs/translations/th/scripting/resources/limits.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/limits.md",
"repo_id": "openmultiplayer",
"token_count": 2460
} | 450 |
---
title: Weapon Skills
description: Weapon skill values to be used with SetPlayerSkillLevel.
---
## คำอธิบาย
List of weapon skills that are used to set player's skill level using [SetPlayerSkillLevel](../functions/SetPlayerSkillLevel.md) function.
## Skill Levels
```c
0 - WEAPONSKILL_PISTOL
1 - WEAPONSKILL_PISTOL_SILENCED
2 - WEAPONSKILL_DESERT_EAGLE
3 - WEAPONSKILL_SHOTGUN
4 - WEAPONSKILL_SAWNOFF_SHOTGUN
5 - WEAPONSKILL_SPAS12_SHOTGUN
6 - WEAPONSKILL_MICRO_UZI
7 - WEAPONSKILL_MP5
8 - WEAPONSKILL_AK47
9 - WEAPONSKILL_M4
10 - WEAPONSKILL_SNIPERRIFLE
```
| openmultiplayer/web/docs/translations/th/scripting/resources/weaponskills.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/weaponskills.md",
"repo_id": "openmultiplayer",
"token_count": 246
} | 451 |
# SA-MP Wiki ve open.mp Dokümanı
Geniş SA-MP topluluğu ve open.mp ekibi tarafından geliştirilen SA-MP wiki'ye hoşgeldiniz!
Bu site, SA-MP ve neticede open.mp için kolay erişilebilmeyi, doküman kaynağına kolay katkı sağlamayı hedefliyor.
## SA-MP wiki artık yok
Maalesef SA-MP wiki Eylül ayının sonlarına doğru kapatıldı. Buna rağmen bir çok SA-MP wiki içeriği halka açık internet arşivlerinde bulunabilir durumda.
Eyvah, eski wiki içeriğini yeni evine yani buraya taşımaya yardım edecek bir topluluğa ihtiyaç duyuyoruz.
Eğer ilgilenirseniz, daha fazla bilgi için [bu sayfaya](/docs/meta/Contributing) bakabilirsiniz.
Eğer daha önce GitHub kullanmadıysanız ya da HTML'e dönüştürmeyi deneyimlemediyseniz endişelenmeyin! Bize karşılaştığınız sorunlar hakkında bilgi vererek (Discord Burgershot veya sosyal medya aracılığıyla) yardımcı olabilirsiniz ve tabiki en önemlisi: _duyurmak!_ bu yüzden bu siteye yer işareti koyduğunuzdan emin olun ve SA-MP Wiki'nin nereye gittiğini merak eden tüm tanıdıklarınızla paylaşın.
Biz, dokümantasyonu, aynı şekilde öğreticileri, basit oyun modları inşa etmek, yaygın kütüphaneler ve eklentiler için rehberleri geliştirmek amacıyla yapılan katkıları memnuniyetle karşılıyoruz. Eğer katkı sağlamakla ilgileniyorsanız [GitHub page](https://github.com/openmultiplayer/web) adresine gidin.
| openmultiplayer/web/docs/translations/tr/index.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/index.md",
"repo_id": "openmultiplayer",
"token_count": 636
} | 452 |
---
title: OnPlayerClickTextDraw
description: This callback is called when a player clicks on a textdraw or cancels the select mode with the Escape key.
tags: ["player", "textdraw"]
---
## Açıklama
Bu callback bir oyuncu bir textdrawa tıkladığında yada ESC tuşu ile seçim modunu iptal ettiğinde çağırılır.
| İsim | Açıklama |
| --------- | --------------------------------------------------------------------------------------- |
| playerid | Textdrawa tıklayan oyuncunun ID'si. |
| clickedid | Tıklanan tectdraw ID'si. Eğer seçim iptal edilirse INVALID_TEXT_DRAW değeri döndürülür. |
## Çalışınca Vereceği Sonuçlar
Filterscriptlerde her zaman ilk çağırılır, 1 değerini döndürmek diğer filterscriptlerin görmesini engeller.
## Örnekler
```c
new Text:gTextDraw;
public OnGameModeInit()
{
gTextDraw = TextDrawCreate(10.000000, 141.000000, "MyTextDraw");
TextDrawTextSize(gTextDraw,60.000000, 20.000000);
TextDrawAlignment(gTextDraw,0);
TextDrawBackgroundColor(gTextDraw,0x000000ff);
TextDrawFont(gTextDraw,1);
TextDrawLetterSize(gTextDraw,0.250000, 1.000000);
TextDrawColor(gTextDraw,0xffffffff);
TextDrawSetProportional(gTextDraw,1);
TextDrawSetShadow(gTextDraw,1);
TextDrawSetSelectable(gTextDraw, 1);
return 1;
}
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (newkeys == KEY_SUBMISSION)
{
TextDrawShowForPlayer(playerid, gTextDraw);
SelectTextDraw(playerid, 0xFF4040AA);
}
return 1;
}
public OnPlayerClickTextDraw(playerid, Text:clickedid)
{
if (clickedid == gTextDraw)
{
SendClientMessage(playerid, 0xFFFFFFAA, "Bir textdrawa tıkladın.");
CancelSelectTextDraw(playerid);
return 1;
}
return 0;
}
```
## Notlar
:::warning
Tıklanılabilir bölge TextDrawTextSize tarafından belirlenir. X ve Y paremetreleri sıfır yada negatif bir değer olmamalıdır. Bu callbackte CancelSelectTextDraw koşulsuz olarak kullanmayın, bu sonsuz bir döngü ile sonuçlanır.
:::
## Bağlantılı Fonksiyonlar
- [OnPlayerClickPlayerTextDraw](OnPlayerClickPlayerTextDraw.md): Bir oyuncu player-textdrawa tıkladığında çağırılır.
- [OnPlayerClickPlayer](OnPlayerClickPlayer.md): Bir oyuncu başka bir oyuncuya tıkladığında çağırılır.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerClickTextDraw.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerClickTextDraw.md",
"repo_id": "openmultiplayer",
"token_count": 1073
} | 453 |
---
title: OnPlayerKeyStateChange
description: Bu fonksiyon, desteklenen herhangi bir tuşun durumu değiştirildiğinde (basıldığında / bırakıldığında) çağrılır.
tags: ["player"]
---
## Açıklama
Bu fonksiyon, desteklenen(../resources/keys) herhangi bir tuşun durumu değiştirildiğinde (basıldığında / bırakıldığında) çağrılır. <br/>Yön tuşları, OnPlayerKeyStateChange'i (yukarı / aşağı / sola / sağa) tetiklemez.
| Parametre | Açıklama |
| --------- | ------------------------------------------------------------------------------------------------ |
| playerid | Tuşu tetikleyen oyuncunun ID'si. |
| newkeys | Oyuncunun bastığı tuş - [bkz.](../resources/keys) |
| oldkeys | Oyuncunun geçerli değişiklikten önce bastığı tuş - [bkz](../resources/keys) |
## Çalışınca Vereceği Sonuçlar
- Bu fonksiyon herhangi bir sonuç vermez.
- Oyun modunda her zaman ilk olarak çağrılır.
## Notlar
:::info
Bu fonksiyon, NPC tarafından da çağrılabilir.
:::
:::tip
Yön tuşları, OnPlayerKeyStateChange'i (yukarı / aşağı / sola / sağa) tetiklemez. Yalnıza zamanlayıcı (timer) veya [OnPlayerUpdate](../callbacks/OnPlayerUpdate) içerisinde kullanılan [GetPlayerKeys](../functions/GetPlayerKeys) ile tetiklenebilir.
:::
## Bağlantılı Fonksiyonlar
#test
- [GetPlayerKeys](../functions/GetPlayerKeys): Oyuncunun hangi tuşlara bastığını kontrol etme.
## EK BİLGİ
### Giriş
Bu fonksiyon, bir oyuncu desteklenen tuşlardan birine bastığında veya bıraktığında çağrılır (bkz. [Tuşlar](../resources/keys)). <br/>Desteklenen tuşlar gerçek klavye tuşları değildir, ancak San Andreas eşlenmiş işlevi Bu, örneğin, birisinin <strong>boşluk</strong> tuşuna bastığını algılayamayacağınız, ancak sprint tuşuna bastığını algılayabileceğiniz anlamına gelir (bu, boşluk çubuğuna atanabilir veya atanmayabilir).
### Parametreler
Bu işlevin parametreleri, o anda basılı tutulan tüm tuşların ve bir süre önce basılı tutulan tüm tuşların bir listesidir. Fonksiyon, bir tuş durumu değiştiğinde (yani, bir tuşa basıldığında veya bırakıldığında) ve bu değişiklikten önceki ve sonraki durumları veya tüm tuşları geçtiğinde çağrılır. Bu bilgi, tam olarak ne olduğunu görmek için kullanılabilir, ancak değişkenler, diğer işlevler için parametrelerle aynı şekilde doğrudan kullanılamaz. Değişkenlerin sayısını azaltmak için bir tuşu temsil etmek için yalnızca tek bir BIT kullanılır; bu, bir değişkenin aynı anda birden çok anahtar içerebileceği ve basitçe değerleri karşılaştırmanın her zaman işe yaramayacağı anlamına gelir.
### Tuş nasıl KONTROL EDİLMEZ
Bir oyuncunun ATEŞ ETME düğmesine bastığını tespit etmek istediğinizi varsayalım, bariz kod şöyle olacaktır:
```c
if (newkeys == KEY_FIRE)
```
Bu kod testinizde bile işe yarayabilir, ancak bu yanlış ve testiniz yetersiz. Çömelmeyi ve ateşe basmayı deneyin - kodunuz anında çalışmayı durduracaktır. Neden? "newkeys" artık "KEY_FIRE" ile aynı olmadığından, "KEY_CROUCH" İLE BİRLEŞTİRİLEN "KEY_FIRE" ile aynıdır.
### Tuş nasıl kontrol edilir
Öyleyse, değişken aynı anda birden fazla tuş içerebiliyorsa, yalnızca tek bir anahtarı nasıl kontrol edersiniz? Cevap biraz maskelemedir. Her tuşun değişkende kendi biti vardır (bazı tuşlar aynı bit'e sahiptir, ancak bunlar ayak üzerinde / boş tuşlardır, bu nedenle hiçbir zaman aynı anda basılamaz) ve sadece o tek biti kontrol etmeniz gerekir:
```c
if (newkeys & KEY_FIRE)
```
Tekli <strong>&</strong> 'nin doğru olduğunu unutmayın - bu, iki ve işareti olarak adlandırılan mantıksal bir VE değil, bitsel VE'dir.
Şimdi bu kodu test ederseniz, ateş tuşuna bastığınızda çömelmiş veya ayakta dursanız da çalışacaktır. Ancak yine de küçük bir sorun var - tuşu tuttuğunuz sürece ateşlenecek. OnPlayerKeyStateChange, bir anahtar her değiştiğinde çağrılır ve ateşleme tuşu her basılı tutulduğunda bu kod doğrudur. Ateş tuşuna basarsanız, o tuş basılı tutulursa ve çömelme tuşuna basarsanız, kod tekrar çalışacaktır çünkü bir tuş (çömelme) değişmiştir ve ateş hala basılıdır Bir tuşa ilk basıldığında nasıl anlarsınız, ancak Hala tutulduğunda ve başka bir tuş değiştiğinde tekrar tetiklenmiyor mu?
### Basılan bir tuş nasıl kontrol edilir
Burası "oldkeys" in devreye girdiği yerdir. Bir tuşa yeni basılmış olup olmadığını kontrol etmek için önce "yeni tuşlar" olarak ayarlanıp ayarlanmadığını kontrol etmeniz gerekir - yani basılı tutulduğu anlamına gelir ve sonra "oldkeys" de OLMADIĞINI kontrol edin - yani sadece tutuldu. Aşağıdaki kod bunu yapar:
```c
if ((newkeys & KEY_FIRE) && !(oldkeys & KEY_FIRE))
```
Bu YALNIZCA ATEŞ tuşuna ilk basıldığında doğru olacaktır, basılı tutulduğunda ve başka bir tuş değiştiğinde değil.
### Basılması bırakılmış bir tuş nasıl kontrol edilir
Yukarıdaki ile tamamen aynı prensip, ancak tersine çevirdik:
```c
if ((oldkeys & KEY_FIRE) && !(newkeys & KEY_FIRE))
```
### Birden çok tuş nasıl kontrol edilir
Çömelip ateş eden oyuncuları kontrol etmek istiyorsanız, aşağıdaki kod işe yarayacaktır:
```c
if ((newkeys & KEY_FIRE) && (newkeys & KEY_CROUCH))
```
Ancak, İLK ateşe bastığında ve çömeldiklerinde tespit etmek istiyorsanız, bu kod ÇALIŞMAYACAKTIR. İki tuşa tam olarak aynı anda basmayı başarırlarsa işe yarayacak, ancak fraksiyonel olarak dışarıdaysa (yarım saniyeden çok daha az) işe yaramayacaktır:
```c
if ((newkeys & KEY_FIRE) && !(oldkeys & KEY_FIRE) && (newkeys & KEY_CROUCH) && !(oldkeys & KEY_CROUCH))
```
Neden olmasın? Çünkü OnPlayerKeyStateChange, tek bir tuş her değiştiğinde çağrılır. Böylece "KEY_FIRE" tuşuna basarlar - OnPlayerKeyStateChange, "oldkeys" değil "KEY_FIRE" ile çağrılır, sonra "KEY_CROUCH" tuşuna basarlar - OnPlayerKeyStateChange, "KEY_CROUCH" ve "KEY_FIRE" ile çağrılır "newkeys", ancak " KEY_FIRE "zaten basıldığı için artık "oldkeys"de bulunuyor, bu nedenle (oldkeys & KEY_FIRE) başarısız olacaktır. Neyse ki çözüm çok basittir (aslında orijinal koddan daha basit):
```c
if ((newkeys & (KEY_FIRE | KEY_CROUCH)) == (KEY_FIRE | KEY_CROUCH) && (oldkeys & (KEY_FIRE | KEY_CROUCH)) != (KEY_FIRE | KEY_CROUCH))
```
Bu karmaşık görünebilir, ancak her iki tuşun da "newkeys" olarak ayarlandığını ve her iki tuşun da "oldkeys" olarak ayarlanıp ayarlanmadığını kontrol eder, eğer bunlardan biri "oldkeys" olarak ayarlanmışsa, her ikisi de önemli değildir. Tüm bunlar tanımlarla büyük ölçüde basitleştirilebilir.
## Basitleştirme
### Tuş tutarken algılama
Tanım:
```c
// HOLDING(keys)
#define HOLDING(%0) \
((newkeys & (%0)) == (%0))
```
Bir tuşa basılu tutmak:
```c
if (HOLDING( KEY_FIRE ))
```
Birden fazla tuşa basılması:
```c
if (HOLDING( KEY_FIRE | KEY_CROUCH ))
```
### Tuşu ilk basılıyorken algılama
Tanım:
```c
// PRESSED(keys)
#define PRESSED(%0) \
(((newkeys & (%0)) == (%0)) && ((oldkeys & (%0)) != (%0)))
```
Tuşa basıldığında:
```c
if (PRESSED( KEY_FIRE ))
```
Birden fazla tuşa basıldığında:
```c
if (PRESSED( KEY_FIRE | KEY_CROUCH ))
```
### Bir oyuncunun şu anda bir tuşa basıp basmadığını algılama
Tanım:
```c
// PRESSING(keyVariable, keys)
#define PRESSING(%0,%1) \
(%0 & (%1))
```
Bir tuşa basma:
```c
if (PRESSING( newkeys, KEY_FIRE ))
```
Birden fazla tuşa basma:
```c
if (PRESSING( newkeys, KEY_FIRE | KEY_CROUCH ))
```
### Tutması bırakılmış tuşu algılama
Tanım:
```c
// RELEASED(keys)
#define RELEASED(%0) \
(((newkeys & (%0)) != (%0)) && ((oldkeys & (%0)) == (%0)))
```
Tuş bırakıldığında:
```c
if (RELEASED( KEY_FIRE ))
```
Birden fazla tuş bırakıldığında:
```c
if (RELEASED( KEY_FIRE | KEY_CROUCH ))
```
## Örnekler
### Oyuncu ateş etme tuşuna bastığında nitro ekleme.
```c
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (PRESSED(KEY_FIRE))
{
if (IsPlayerInAnyVehicle(playerid))
{
AddVehicleComponent(GetPlayerVehicleID(playerid), 1010);
}
}
return 1;
}
```
### Süper zıplama
```c
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (PRESSED(KEY_JUMP))
{
new
Float:x,
Float:y,
Float:z;
GetPlayerPos(playerid, x, y, z);
SetPlayerPos(playerid, x, y, z + 10.0);
}
return 1;
}
```
### Kullanım sırasında ölümsüzlük
```c
new
Float:gPlayerHealth[MAX_PLAYERS];
#if !defined INFINITY
#define INFINITY (Float:0x7F800000)
#endif
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (PRESSED(KEY_ACTION))
{
// Oyuncu tuşa bastı
// ve eski canını bir tanım üzerine kaydetti.
GetPlayerHealth(playerid, gPlayerHealth[playerid]);
SetPlayerHealth(playerid, INFINITY);
}
else if (RELEASED(KEY_ACTION))
{
// Tuşu bıraktığında tanım üzerindeki canı tekrar oyuncuya verildi.
SetPlayerHealth(playerid, gPlayerHealth[playerid]);
}
return 1;
}
```
### Açıklama
NASIL yapıldığı konusunda endişelenmenize gerek yok. HOLDING (BASMAK), bir tuşa (veya tuşlara) basıp basmadıklarını algılar, daha önce basmış olup olmadıklarına bakılmaksızın, PRESSED (BASILI), yalnızca tuş (lar) a basıp basmadıklarını algılar ve RELEASED (BIRAKMAK), yalnızca bir tuş (lar) ı bırakıp bırakmadıklarını algılar. Ancak daha fazlasını öğrenmek istiyorsanız okumaya devam edin.
Bunu sadece & veya == kullanarak değil, bu şekilde yapmanız gerekmesinin nedeni, basılabilecek veya basılmayabilecek diğerlerini göz ardı ederek tam olarak istediğiniz tuşları algılamaktır. İkili olarak KEY_SPRINT:
```
0b00001000
```
ve KEY_JUMP:
```
0b00100000
```
böylece onları istenen anahtarlara ORing (bunları bu örnekte de ekleyebiliriz, ancak bu her zaman böyle değildir) verir:
```
0b00101000
```
Sadece & kullanıyor olsaydık ve OnPlayerKeyStateChange, atlamaya basan bir oyuncu için çağrılsaydı, aşağıdaki kodu alırdık:
```
newkeys = 0b00100000
wanted = 0b00101000
ANDed = 0b00100000
```
İki sayının VE değeri 0 değildir, dolayısıyla kontrolün sonucu doğrudur, ki istediğimiz bu değildir.
Eğer sadece == kullansaydık, iki sayı açıkça aynı değildir, bu yüzden kontrol başarısız olur, istediğimiz de budur.
Oyuncu zıplama, koşma ve çömelme tuşuna basıyorsa, aşağıdaki kodu alırdık:
```
newkeys = 0b00101010
wanted = 0b00101000
ANDed = 0b00101000
```
VE'li versiyonu, gerekli tuşlarla aynıdır ve 0 değildir, bu nedenle doğru cevabı verecektir, ancak iki orijinal sayı aynı olmadığından == başarısız olacaktır. Her iki örnekte de ikisinden biri doğru cevabı vermiş ve biri yanlış cevabı vermiştir. İlkini & ve == kullanarak karşılaştırırsak şunu elde ederiz:
```
newkeys = 0b00100000
wanted = 0b00101000
ANDed = 0b00100000
```
Açıkçası istenen ve VE'li aynı değildir, bu nedenle kontrol başarısız olur, bu doğru. İkinci örnek için:
```
newkeys = 0b00101010
wanted = 0b00101000
ANDed = 0b00101000
```
Aranan ve VE'li aynıdır, bu yüzden onları eşit olarak karşılaştırmak, yine doğru olan gerçek bir sonuçla sonuçlanacaktır.
Dolayısıyla, bu yöntemi kullanarak, basılabilen veya basılamayan diğer tüm tuşları göz ardı ederek belirli tuşlara basılıp basılmadığını doğru bir şekilde kontrol edebiliriz. eski tuş kontrolü, gerekli tuşlara önceden basılmadığından emin olmak için == yerine sadece != kullanır, bu nedenle bunlardan birine basıldığını biliyoruz.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerKeyStateChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerKeyStateChange.md",
"repo_id": "openmultiplayer",
"token_count": 5679
} | 454 |
---
title: OnPlayerUpdate
description: Bu fonksiyon, bir istemci veya oyuncu sunucuyu durumlarıyla her güncellediğinde çağrılır.
tags: ["player"]
---
## Açıklama
Bu fonksiyon, bir istemci veya oyuncu sunucu durumlarıyla ilgili her güncellendiğinde çağrılır. Genellikle, sağlık veya zırh güncellemeleri veya silah değiştiren oyuncular gibi sunucu tarafından aktif olarak izlenmeyen istemci güncellemeleri için özel çağrıları oluşturmak için kullanılır.
| Parametre | Açıklama |
| --------- | ------------------------------------------- |
| playerid | Güncelleme paketi gönderen oyuncunun ID'si. |
## Çalışınca Vereceği Sonuçlar
0 - Bu oyuncunun güncellemesi diğer oyunculara/istemcilere senkronize edilmeyecektir.
1 - Bu güncellemenin normal şekilde işlenebileceğini ve diğer oyunculara gönderilebileceğini gösterir.
Filterscript komutlarında her zaman ilk olarak çağrılır.
## Örnekler
```c
public OnPlayerUpdate(playerid)
{
new iCurWeap = GetPlayerWeapon(playerid); // Oyuncunun eline aldığı silahı kontrol etmek için değişken oluşturuyoruz.
if (iCurWeap != GetPVarInt(playerid, "iCurrentWeapon")) // Son güncellemeden bu yana silah değiştirdiyse...
{
// OnPlayerChangeWeapon adlı fonksiyonu çağıralım.
OnPlayerChangeWeapon(playerid, GetPVarInt(playerid, "iCurrentWeapon"), iCurWeap);
SetPVarInt(playerid, "iCurrentWeapon", iCurWeap);// Silah değişkenini güncelleyelim.
}
return 1; // Bu güncellemeyi diğer oyunculara gönderin.
}
stock OnPlayerChangeWeapon(playerid, oldweapon, newweapon)
{
new s[128],
oWeapon[24],
nWeapon[24];
GetWeaponName(oldweapon, oWeapon, sizeof(oWeapon));
GetWeaponName(newweapon, nWeapon, sizeof(nWeapon));
format(s, sizeof(s), "Eski silahın olan %s numaralı silahı yeni silahın %s ile değiştirdin!", oWeapon, nWeapon);
SendClientMessage(playerid, 0xFFFFFFFF, s);
}
public OnPlayerUpdate(playerid)
{
new Float:fHealth;
GetPlayerHealth(playerid, fHealth);
if (fHealth != GetPVarFloat(playerid, "faPlayerHealth"))
{
// Can kazanıp kazanmadığını kontrol edelim, anti-sağlık hilesi? ;)
if (fHealth > GetPVarFloat(playerid, "faPlayerHealth"))
{
// Oyuncu can kazanmış! D-d-dostum bu adam bir Hile mi?
// Bu manyak herife kendi senaryolarını yazıp, istediğin şeyleri yapabilirsin.
}
else
{
// Oyuncu can kazanmamış.
}
SetPVarFloat(playerid, "faPlayerHealth", fHealth);
}
}
```
## Notlar
<TipNPCCallbacks />
:::warning
Bu fonksiyon, oyuncu başına ortalama olarak saniyede 30 kez çağrılır; yalnızca ne anlama geldiğini (veya daha da önemlisi ne anlama gelmediğini) bildiğiniz zaman kullanın. Her oyuncu için bu çağrılma sıklığı, oyuncunun ne yaptığına bağlı olarak değişir. Araba kullanmak veya ateş etmek, rölantiden çok daha fazla güncellemeyi tetikleyecektir.
:::
## Bağlantılı Fonksiyonlar
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerUpdate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerUpdate.md",
"repo_id": "openmultiplayer",
"token_count": 1430
} | 455 |
---
title: AddMenuItem
description: Belirli bir menüye öğe ekler.
tags: ["menu"]
---
## Açıklama
Belirli bir menüye öğe ekler.
| İsim | Açıklama |
| ------- | ------------------------------ |
| menuid | Öğe eklemek için menü kimliği. |
| column | Öğenin ekleneceği sütun. |
| title[] | Yeni menü öğesinin başlığı. |
## Çalışınca Vereceği Sonuçlar
Bu öğenin eklendiği satırın dizini.
## Örnekler
```c
new Menu:examplemenu;
public OnGameModeInit()
{
examplemenu = CreateMenu("Your Menu", 2, 200.0, 100.0, 150.0, 150.0);
AddMenuItem(examplemenu, 0, "item 1");
AddMenuItem(examplemenu, 0, "item 2");
return 1;
}
```
## Notlar
:::tip
Geçersiz bir menü kimliği geçtiğinde çöker. Menü başına yalnızca 12 öğe olabilir (13. Sütun adı üstbilgisinin sağ tarafına gider (renkli), 14. Ve üstü hiç görüntülenmez). Yalnızca 2 sütun (0 ve 1) kullanabilirsiniz.Bir öğe başına yalnızca 8 renk kodu ekleyebilirsiniz (~r~,~g~ vb.). Menü öğesinin maksimum uzunluğu 31 simgedir.
:::
## Bağlantılı Fonksiyonlar
- [CreateMenu](CreateMenu.md): Menü oluşturmak.
- [SetMenuColumnHeader](SetMenuColumnHeader.md): Menüdeki sütunlardan birinin başlığını ayarlayın.
- [DestroyMenu](DestroyMenu.md): Menüyü yok et.
- [OnPlayerSelectedMenuRow](../callbacks/OnPlayerSelectedMenuRow.md): Oynatıcı menüde bir satır seçtiğinde çağrılır.
- [OnPlayerExitedMenu](../callbacks/OnPlayerExitedMenu.md): Oynatıcı menüden çıktığında çağırılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/AddMenuItem.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AddMenuItem.md",
"repo_id": "openmultiplayer",
"token_count": 718
} | 456 |
---
title: Attach3DTextLabelToVehicle
description: Bir araca 3D text label bağlar.
tags: ["vehicle", "3dtextlabel"]
---
## Description
Bu fonksiyon bir araca 3D text label bağlamanızı sağlar.
| Parametre | Açıklama |
| --------- | ---------------------------------------------------------------------------- |
| Text3D:textid | Bağlamak istediğiniz 3D text labelin ID'si. |
| vehicleid | Bağlamak istediğiniz aracın ID'si. |
| OffsetX | Aracın X-ofset koordinatı (aracın ortası, yani '0.0, 0.0, 0.0'dan başlar) |
| OffsetY | Aracın Y-ofset koordinatı (aracın ortası, yani '0.0, 0.0, 0.0'dan başlar) |
| OffsetZ | Aracın Z-ofset koordinatı (aracın ortası, yani '0.0, 0.0, 0.0'dan başlar) |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon dönüt vermez.
## Örnekler
```c
new
Text3D:gVehicle3dText[MAX_VEHICLES], // Daha sonra kullanmak için bir 3D text label yaratıyoruz
gVehicleId;
public OnGameModeInit ( )
{
gVehicleId = CreateVehicle(510, 0.0. 0.0, 15.0, 5, 0, 120); // Aracımızı yaratıyoruz
gVehicle3dText[gVehicleId] = Create3DTextLabel("Example Text", 0xFF0000AA, 0.0, 0.0, 0.0, 50.0, 0, 1);
Attach3DTextLabelToVehicle(gVehicle3dText[gVehicleId], vehicle_id, 0.0, 0.0, 2.0); // Labeli araca bağlıyoruz
}
public OnGameModeExit ( )
{
Delete3DTextLabel(gVehicle3dText[gVehicleId]);
return true;
}
```
## Bağlantılı Fonksiyonlar
- [Create3DTextLabel](Create3DTextLabel): 3D text label oluşturun.
- [Delete3DTextLabel](Delete3DTextLabel): 3D text label silin.
- [Attach3DTextLabelToPlayer](Attach3DTextLabelToPlayer): Attach a 3D text label to a player.
- [Update3DTextLabelText](Update3DTextLabelText): Bir 3D text labelin metnini değiştirin.
- [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): Sadece bir oyuncuya özel 3D text label oluşturun.
- [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): Oyuncuya bağlı 3D text labeli silin.
- [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): Oyuncuya özel 3D text labelin metnini değiştirin.
| openmultiplayer/web/docs/translations/tr/scripting/functions/Attach3DTextLabelToVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/Attach3DTextLabelToVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 1010
} | 457 |
---
title: ConnectNPC
description: Sunucuya NPC bağlama.
tags: ["npc"]
---
## Açıklama
Sunucuya NPC bağlama.
| Parametre | Açıklama |
| --------- | ----------------------------------------------------------------------------------------- |
| name[] | NPC'ye verilen isim. Normal oyuncu isimleriyle aynı kurallara uymalıdır (ğ,ü içermez vb) |
| script[] | npcmodes klasöründe bulunan NPC uzantılı komut dosyası adı. (.amx uzantısı olmadan) |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon her zaman 1 döndürür.
## Örnekler
```c
public OnGameModeInit()
{
ConnectNPC("[BOT]Pilot", "pilot");
return 1;
}
```
## Notlar
:::tip
Bağlanan NPC'lerin isim etiketleri bulunmaz. Attach3DTextLabelToPlayer ile yapılabilir.
:::
## Bağlantılı Fonksiyonlar
- [IsPlayerNPC](IsPlayerNPC): Bir oyuncunun bir NPC veya gerçek bir oyuncu olup olmadığını kontrol etme.
- [OnPlayerConnect](../callbacks/OnPlayerConnect): Bu fonksiyon, bir oyuncu sunucuya bağlandığında çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/ConnectNPC.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/ConnectNPC.md",
"repo_id": "openmultiplayer",
"token_count": 513
} | 458 |
---
title: acos
description: .
tags: []
---
<LowercaseNoteTR />
## Açıklama
Radyanlardaki bir ark kosininin ters değerini alın.
| İsim | Açıklama |
| ----------- | -------------------- |
| Float:value | ark kosinüsü girişi. |
## Çalışınca Vereceği Sonuçlar
[0, pi] radyanlarda x'in ana ark kosinüsü. Bir radyan 180/PI'ye eşdeğerdir.
## Örnek
```c
//0.500000'in ark kosinüsü 60.000000 derecedir.
public OnGameModeInit()
{
new Float:param, Float:result;
param = 0.5;
result = acos(param);
printf("%f yay kosinüsü %f derece.", param, result);
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [floatsin](floatsin.md): Sinüsü belirli bir açıdan alın.
- [floatcos](floatcos.md): Kosinüsü belirli bir açıdan alın.
- [floattan](floattan.md): Tanjantı belirli bir açıdan alın.
| openmultiplayer/web/docs/translations/tr/scripting/functions/acos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/acos.md",
"repo_id": "openmultiplayer",
"token_count": 396
} | 459 |
---
title: Araç parça yuvaları
---
:::info
Aşağıdaki araç parça yuvaları, [GetVehicleComponentInSlot](../functions/GetVehicleComponentInSlot) fonksiyonunda kullanılabilir.
:::
| Yuva | Tanım |
|------|--------------------------|
| 0 | CARMODTYPE_SPOILER |
| 1 | CARMODTYPE_HOOD |
| 2 | CARMODTYPE_ROOF |
| 3 | CARMODTYPE_SIDESKIRT |
| 4 | CARMODTYPE_LAMPS |
| 5 | CARMODTYPE_NITRO |
| 6 | CARMODTYPE_EXHAUST |
| 7 | CARMODTYPE_WHEELS |
| 8 | CARMODTYPE_STEREO |
| 9 | CARMODTYPE_HYDRAULICS |
| 10 | CARMODTYPE_FRONT_BUMPER |
| 11 | CARMODTYPE_REAR_BUMPER |
| 12 | CARMODTYPE_VENT_RIGHT |
| 13 | CARMODTYPE_VENT_LEFT |
| 14 | CARMODTYPE_FRONT_BULLBAR |
| 15 | CARMODTYPE_REAR_BULLBAR |
| openmultiplayer/web/docs/translations/tr/scripting/resources/Componentslots.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/resources/Componentslots.md",
"repo_id": "openmultiplayer",
"token_count": 446
} | 460 |
---
title: OnActorStreamOut
description: 当演员被玩家的客户端流出时,就会调用这个回调。
tags: []
---
<VersionWarnCN name='回调' version='SA-MP 0.3.7' />
## 描述
当演员被玩家的客户端流出时,就会调用这个回调。
| 参数名 | 描述 |
| ----------- | ----------------------- |
| actorid | 已为玩家流出的演员 ID。 |
| forplayerid | 让演员流出的玩家的 ID。 |
## 返回值
它在过滤脚本中总是先被调用。
## 案例
```c
public OnActorStreamOut(actorid, forplayerid)
{
new string[40];
format(string, sizeof(string), "演员 %d 现在正为你流出。", actorid);
SendClientMessage(forplayerid, 0xFFFFFFFF, string);
return 1;
}
```
## 相关回调
<TipNPCCallbacksCN />
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnActorStreamOut.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnActorStreamOut.md",
"repo_id": "openmultiplayer",
"token_count": 439
} | 461 |
---
title: OnNPCSpawn
description: 当npc生成时调用此回调。
tags: []
---
## 描述
当 npc 生成时调用此回调。
## 案例
```c
public OnNPCSpawn()
{
print("NPC 生成了");
SendChat("你好世界. 我是个机器人.");
return 1;
}
```
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 156
} | 462 |
---
title: OnPlayerExitedMenu
description: 当玩家退出菜单时调用。
tags: ["player", "menu"]
---
## 描述
当玩家退出菜单时调用。
| 参数名 | 描述 |
| -------- | ------------------- |
| playerid | 退出菜单的玩家的 ID |
## 返回值
它在游戏模式中总是先被调用。
## 案例
```c
public OnPlayerExitedMenu(playerid)
{
TogglePlayerControllable(playerid,1); // 当玩家退出菜单时解除冻结
return 1;
}
```
## 相关函数
- [CreateMenu](../functions/CreateMenu): 创建一个目录。
- [DestroyMenu](../functions/DestroyMenu): 销毁一个目录。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerExitedMenu.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerExitedMenu.md",
"repo_id": "openmultiplayer",
"token_count": 341
} | 463 |
---
title: OnPlayerStateChange
description: 当玩家改变状态时,这个回调函数被调用。例如,当一名玩家从一辆车的司机变成了步行。
tags: ["player"]
---
## 描述
当玩家改变状态时,这个回调函数被调用。例如,当一名玩家从一辆车的司机变成了步行。
| 参数名 | 描述 |
| -------- | ------------------- |
| playerid | 改变状态的玩家 ID。 |
| newstate | 玩家的新状态。 |
| oldstate | 玩家之前的状态。 |
参考 [玩家状态](../resources/playerstates) 来获取所有可用的玩家状态列表。
## 返回值
它在过滤脚本中总是先被调用。
## 案例
```c
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
if (oldstate == PLAYER_STATE_ONFOOT && newstate == PLAYER_STATE_DRIVER) // 玩家以驾驶员的身份进入车辆
{
new vehicleid = GetPlayerVehicleID(playerid);
AddVehicleComponent(vehicleid, 1010); // 添加氮气
}
return 1;
}
```
## 要点
<TipNPCCallbacksCN />
## 相关函数
- [GetPlayerState](../functions/GetPlayerState): 获取玩家的当前状态。
- [GetPlayerSpecialAction](../functions/GetPlayerSpecialAction): 获得玩家当前的特殊动作。
- [SetPlayerSpecialAction](../functions/SetPlayerSpecialAction): 设定玩家的特殊动作。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerStateChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerStateChange.md",
"repo_id": "openmultiplayer",
"token_count": 736
} | 464 |
---
title: OnVehicleRespray
description: 这个回调是在玩家离开改装店时调用的,即使车辆颜色没有改变。
tags: ["vehicle"]
---
## 描述
这个回调是在玩家离开改装店时调用的,即使车辆颜色没有改变。注意,回调函数名称有歧义,Pay 'n' Spray 商店不会调用该回调。
| 参数名 | 描述 |
| --------- | ------------------------- |
| playerid | 驾驶车辆的玩家的 ID。 |
| vehicleid | 被重新喷漆的那辆车的 ID。 |
| color1 | 车辆的主色被改变的颜色。 |
| color2 | 车辆的辅色被改变的颜色。 |
## 返回值
它总是在游戏模式中先被调用,所以返回 0 也会阻止其他过滤脚本看到它。
## 案例
```c
public OnVehicleRespray(playerid, vehicleid, color1, color2)
{
new string[48];
format(string, sizeof(string), "你重新喷涂了 %d 颜色为 %d 和 %d!", vehicleid, color1, color2);
SendClientMessage(playerid, COLOR_GREEN, string);
return 1;
}
```
## 要点
:::tip
这个回调不被 ChangeVehicleColor 函数调用。值得一提的是 Pay 'n' Spray 商店不会调用该回调。(仅改装店)。
此处修正: http://pastebin.com/G81da7N1
:::
:::warning
已知 BUG(s):
在改装店中预览组件可能会调用这个回调函数。
:::
## 相关函数
- [ChangeVehicleColor](../functions/ChangeVehicleColor): 改变车辆的颜色。
- [ChangeVehiclePaintjob](../functions/ChangeVehiclePaintjob): 改变车辆的油漆涂鸦样式。
## 相关回调
- [OnVehiclePaintjob](OnVehiclePaintjob): 当车辆的油漆涂鸦样式被改变时调用。
- [OnVehicleMod](OnVehicleMod): 当车辆被改装时调用。
- [OnEnterExitModShop](OnEnterExitModShop): 当车辆进入或离开改装店时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleRespray.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleRespray.md",
"repo_id": "openmultiplayer",
"token_count": 1071
} | 465 |
---
title: AllowInteriorWeapons
description: 切换是否允许在内部空间使用武器。
tags: []
---
## 描述
切换是否允许在内部空间使用武器。
| 参数名 | 说明 |
| ------ | ------------------------------------------------------------------ |
| allow | 1 表示在内部空间启用武器(默认为启用),0 表示在内部空间禁用武器。 |
## 返回值
该函数不返回任何特定的值。
## 案例
```c
public OnGameModeInit()
{
// 这将允许在内部空间使用武器
AllowInteriorWeapons(1);
return 1;
}
```
## 要点
:::warning
这个函数在当前的 SA:MP 版本中不起作用!
:::
## 相关函数
- [SetPlayerInterior](SetPlayerInterior): 设置某个玩家的内部空间。
- [GetPlayerInterior](GetPlayerInterior): 获取某个玩家目前的内部空间。
- [OnPlayerInteriorChange](../callbacks/OnPlayerInteriorChange): 当某个玩家的内部空间改变时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AllowInteriorWeapons.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AllowInteriorWeapons.md",
"repo_id": "openmultiplayer",
"token_count": 578
} | 466 |
---
title: DisableInteriorEnterExits
description: 禁用游戏中所有的内部空间入口和出口(门前的黄色箭头)。
tags: []
---
## 描述
禁用游戏中所有的内部空间入口和出口(门前的黄色箭头)。
## 案例
```c
public OnGameModeInit()
{
DisableInteriorEnterExits();
return 1;
}
```
## 要点
:::tip
这个函数只有在玩家连接之前使用才会有效(建议在 OnGameModeInit 中使用)。它不会删除目前已连接的玩家的标记。
:::
:::warning
如果在使用这个函数后改变了游戏模式,而新的游戏模式没有禁用标记,那么对于已经连接的玩家来说,标记将不会重新出现(但对于新连接的玩家来说会出现)。
:::
## 相关函数
- [AllowInteriorWeapons](AllowInteriorWeapons): 决定是否可以在内部空间使用武器。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/DisableInteriorEnterExits.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/DisableInteriorEnterExits.md",
"repo_id": "openmultiplayer",
"token_count": 538
} | 467 |
---
title: UpdatePlayer3DTextLabelText
description: 更新玩家的三维文本标签的文本和颜色。
tags: ["player", "3dtextlabel"]
---
## 描述
更新玩家的三维文本标签的文本和颜色。
| 参数名 | 说明 |
| --------------- | ---------------------------------- |
| playerid | 三维文本标签所对应的玩家 ID。 |
| PlayerText3D:textid | 您想要更新的三维文本标签的 ID。 |
| color | 从现在起,三维文本标签的颜色。 |
| text[] | 从现在起,三维文本标签的文本内容。 |
## 返回值
该函数不返回任何特定的值。
## 要点
:::warning
如果 text[] 参数是空的,服务端或位于文本标签旁的玩家客户端可能会崩溃!
:::
## 相关函数
- [Create3DTextLabel](Create3DTextLabel): 创建一个三维文本标签。
- [Delete3DTextLabel](Delete3DTextLabel): 删除一个三维文本标签。
- [Attach3DTextLabelToPlayer](Attach3DTextLabelToPlayer): 将三维文本标签附加到玩家身上。
- [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): 将一个三维文本标签附加到载具。
- [Update3DTextLabelText](Update3DTextLabelText): 改变三维文本标签的文本内容和颜色。
- [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): 为玩家创建一个三维文本标签。
- [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): 删除一个为玩家创建的三维文本标签。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/UpdatePlayer3DTextLabelText.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/UpdatePlayer3DTextLabelText.md",
"repo_id": "openmultiplayer",
"token_count": 849
} | 468 |
# fly.toml file generated for openmultiplayer on 2022-08-13T10:47:12+01:00
app = "openmultiplayer"
kill_signal = "SIGINT"
kill_timeout = 5
processes = []
[experimental]
allowed_public_ports = []
auto_rollback = true
[env]
LOG_LEVEL = "debug"
PACKAGES_DB = "/data/packages.db"
CACHED_SERVERS_FILE = "/data/cachedServers.json"
PRODUCTION = "true"
PUBLIC_WEB_ADDRESS = "https://www.open.mp"
LAUNCHER_BACKEND_ADDRESS = "http://localhost:1420"
[mounts]
destination = "/data"
source = "openmp"
[[services]]
http_checks = []
internal_port = 8000
processes = ["app"]
protocol = "tcp"
script_checks = []
[services.concurrency]
hard_limit = 25
soft_limit = 20
type = "connections"
[[services.ports]]
force_https = true
handlers = ["http"]
port = 80
[[services.ports]]
handlers = ["tls", "http"]
port = 443
[[services.tcp_checks]]
grace_period = "1s"
interval = "15s"
restart_limit = 0
timeout = "2s"
| openmultiplayer/web/fly.toml/0 | {
"file_path": "openmultiplayer/web/fly.toml",
"repo_id": "openmultiplayer",
"token_count": 588
} | 469 |
---
title: Turfs (formerly gangzones) module
date: "2019-10-19T04:20:00"
author: J0sh
---
Zdravo! Upravo sam završio našu Turf implementaciju na server i mislio sam da objavim pregled ovog modula i da pokažem da nismo odustali ili bilo šta!
```pawn
// Creates a Turf. A playerid can be passed in order to make it a player turf.
native Turf:Turf_Create(Float:minx, Float:miny, Float:maxx, Float:maxy, Player:owner = INVALID_PLAYER_ID);
// Destroys a turf.
native Turf_Destroy(Turf:turf);
// Shows a Turf to a player or players.
// Will send to all players if playerid = INVALID_PLAYER_ID.
native Turf_Show(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID);
// Hides a Turf from a player or players.
// Will send to all players if playerid = INVALID_PLAYER_ID.
native Turf_Hide(Turf:turf, Player:playerid = INVALID_PLAYER_ID);
// Flashes a Turf for a player or players.
// Will send to all players if playerid = INVALID_PLAYER_ID.
native Turf_Flash(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID);
// Stops a Turf from flashing for player(s).
// Will send to all players if playerid = INVALID_PLAYER_ID.
native Turf_StopFlashing(Turf:turf, Player:playerid = INVALID_PLAYER_ID);
```
Ovo se očito razlikuje od tradicionalnog API-ja, ali ne brinite, postojat će omoti za ovu vrstu stvari kako bi se osiguralo da se normalna skripta može ponovo kompajlirati bez problema i bez izmjena.
Još jedna važna činjenica koju biste možda željeli znati je da je svaki travnjak u istom bazenu i da postoji maksimalno 4,294,967,295 travnjaka koje treba kreirati iz skripte. Međutim, klijent može rukovati samo sa 1024 travnjaka odjednom.
| openmultiplayer/web/frontend/content/bs/blog/turfs-formerly-gangzones-module.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/bs/blog/turfs-formerly-gangzones-module.mdx",
"repo_id": "openmultiplayer",
"token_count": 654
} | 470 |
---
title: SA-MP Android (Mobile Version)
date: "2021-01-30T12:46:46"
author: Potassium
---
The open.mp team's views on SA-MP for Android
Hi everyone,
We just wanted to write a quick blog post about our views on SA-MP for Android, because we have been getting a lot of comments about it on our YouTube videos and on Discord.
As we stated in our YouTube video, we do not support the current version of SA-MP for Android. This app was created using source code which was stolen from the SA-MP team, which makes the app illegal.
We do not condone the theft of other people's code, and we do not condone the use of stolen code. We also do not associate with illegal activities.
We see that GTA SA multiplayer for mobile has a large community, and we would like to welcome this community into open.mp.
We are currently discussing how we can create our own multiplayer mod for SA mobile, so that it will be done legally and fairly! :)
This means that it is very possible that there will be open.mp for mobile in the future, so please keep supporting us while we figure it out!
We invite the mobile community to join our official Discord with over 7000 members, we have created a channel for you at #samp-android and we look forward to hearing your thoughts and opinions!
See you there!
https://discord.gg/samp
| openmultiplayer/web/frontend/content/en/blog/samp-mobile.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/en/blog/samp-mobile.mdx",
"repo_id": "openmultiplayer",
"token_count": 326
} | 471 |
<div dir="rtl" style={{ textAlign: "right" }}>
# اوپن مولتی پلیر
یک مود چند نفره در راه برای بازی _Grand Theft Auto: San Andreas_ که کاملا با مود فعلی چند نفره _San Andreas Multiplayer_ سازگار خواهد بود.
<br />
این به این معناست که **کلاینت SA:MP فعلی و تمام اسکریپت های SA:MP که وجود دارند در open.mp کار خواهد کرد** و علاوه بر این، تعداد بسیاری از مشکلات بدون نیاز به هک و راه حل در نرم افزار سرور برطرف خواهند شد.
اگر شما حیرت زده شدید که چه موقع برای انتشار عمومی برنامه ریزی شده است یا شما چگونه میتوانید در این پروژه مشارکت داشته باشید لطفا [این موضوع در انجمن](https://forum.open.mp/showthread.php?tid=99) را برای اطلاعات بیشتر ببینید
# [سوالات متداول](/faq)
</div> | openmultiplayer/web/frontend/content/fa/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/fa/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 613
} | 472 |
# FAQ
<hr />
## რა არის open.mp?
open.mp (Open Multiplayer) არის ერთ-ერთი მოდიფიკაცია San Andreas-ის თვის, რომლის შექმნის ინიციატივა გამოიწვია პრობლემების ზრდამ განახლებებსა და მენეჯმენთზე SA:MP-ში. პირველი ვერსიის მიზანი იქნება მხოლოდ და მხოლოდ სასერვერო პროგრამის ჩანაცვლება. ამჟამინდელი SA:MP-ის კლიენტით შესაძლებელი იქნება open.mp სერვერთან დაკავშირება. მომავალში კი open.mp-ის კლიენტი იქნება ხელმისაწვდომი, რომელიც მეტ შესაძლებლობებს შემოგვთავაზებს.
<hr />
## არის თუ არა ეს განშტოება?
არა. ეს არის კოდის აბსოლუტურად ხელახლა გადაწერა დიდხნიანი ცოდნისა და გამოცდილების გამოყენებით. უკვე იყო SA:MP განშტოებების შექმნის მცდელობები, მაგრამ ჩვენ გვჯერა, რომ მათ ჰქონდათ ორი ძირითადი პრობლემა:
- ისინი დაფუძნებული იყვნენ "გაჟონილი" SA:MP-ის კოდზე. ამ მოდიფიკაციების ავტორებს არ ჰქონდათ ამ კოდის გამოყენების უფლება; ისინი მორალურადაც და ლეგალურადაც ყოველთვის უკანა ფლანგზე იყვნენ. ჩვენ, რა თქმა უნდა, უარს ვამბობთ ამ კოდის გამოყენებაზე. ეს ოდნავ აფერხებს განვითარების სისწრაფეს, თუმცა, ეს სწორი ნაბიჯია სტაბილური გაშვებისთვის.
- მათ სცადეს თავიდან გამოეგონებინათ ძალიან ბევრი რამ ერთ ჯერზე: სკრიპტინიგ ძრავის შეცვლა, შესაძლებლობების მოშორება სხვა შესაძლებლობების დამატებისას, სხვადასხვა რაღაცების ერთმანეთთან შეუთავსებლად დაკავშირება. ეს იწვევს იმ სერვერების განვითარების შეფერხებას, რომლებსაც დიდი რაოდენობის მოთამაშეები და კარგად დამუშავებული სკრიპტი აქვთ, რადგან მათ მოუწევდათ თავიდან დაეწერათ ბევრი რამ. ჩვენ სერიოზულად ვაპირებთ დავამატოთ ბევრი ახალი რამ, ამასთანავე ვზრუნავთ მიმდინარე სერვერებზე: ვუწყობთ ხელს, რომ გამოიყენონ ჩვენი პროდუქტი თავიანთი კოდის შეცვლის გარეშე.
<hr />
## რატომ ვაკეთებთ ჩვენ ამას?
მიუხედავად დიდი მცდელობებისა SA:MP-ის დეველოფმენთში ოფიციალურად ჩართვისა სხვადასხვა ფორმებით (რჩევებით, სიახლეების მოთხოვნით, ბეტა ტესტერის პოზიციაზე ყოფნის ინიციატივის გამოჩენით) ჩვენ არანაირი პროგრესი არ დაგვინახავს. ეს ყოველივე მიჩნეული იყო როგორც ინტერესის კარგვა ამ მოდის გაუმჯობესებაში, რაც თავის მხრივ პრობლემა არაა, მაგრამ არც წარმატებაა. იმის მაგივრად, რომ განვითარება გაგრძელებულიყო თუნდაც იმ ხალხის მიერ ვისაც ეს უნდოდა, დამაარებელს სურდა მიექცია ყურადღება: აკავშირებდა სხვადასხვა საქმეებს მინიმალური შედეგის მისაღებად. ზოგი ფიქრობს, რომ ეს დაბალი შემოსავლის ბრალია, თუმცა ამის არანაირი მტკიცებულება არ არსებობს. მიუხედავად დიდი ინტერესისა და მზარდი მოთამაშეების რიცხვისა, მას სჯეროდა, რომ მხოლოდ 1 ან 2 წელი ჰქონდა დარჩენილი ამ მოდს, და ის საზოგადოება, რომელმაც წვლილი შეიტანა, გაეხადა SA:MP-ი ის, რაც დღეს არის, არ იმსახურებდა ამ საქმის გაგრძელებას.
ჩვენ არ ვეთანხმებით.
<hr />
## რა არის თქვენი აზრი კალკორის/SA:MP/სხვა რამის შესახებ?
ჩვენ გვიყვარს SA:MP-ი, რაც არის ჩვენი აქ ყოფნის პირველი მიზეზი და ჩვენ ვალში ვართ Kalcor-თან მისი შექმნისთვის. მას მრავალწლიანი ღვაწლი მიუძღვის ამ მოდისთვის, რომელიც არ უნდა იყოს დავიწყებული ან/და დაიგნორებული. ქმედებები, რომლებიც მიუძღვის open.mp-ს წინ, გამოწვეულია იმის გამო, რომ ჩვენ არ ვეთანხმებით მის რამდენიმე გადაწყვეტილებას და ასევე მის ერთსა და იმავე მცდელობას, რომელიც მოდიფიკაციის არასწორი მიმართულებით წაყვანას ცდილობს, ეს მცდელობები კი პრობლემებს არ ჭრის. ამის გამო, ჩვენ ვალდებულები ვართ, რომ მივიღოთ ასეთი გადაწყვეტილება და განვაგრძოთ SA:MP-ი Kalcor-ის გარეშე. ჩვენი ეს გადაწყვეტილება არ არის მიღებული პირადი მიზნებისთვის და არც არავის შეურაცხყოფა არაა, როგორც ეს შეიძლება ზოგმა გაიგოს.
<hr />
## არ არის ეს საზოგადოების გაყოფა?
ეს არ არის ჩვენი მიზანი. ჩვენი იდეების თანახმად, ეს არ არის მომხმარებლების გაყოფა, მაგრამ რაღაციდან გამოცალკევება და სხვა რამის გადარჩენა უკეთესია, ვიდრე არაფერი. ფაქტის თანახმად, ვინაიდან ამ მოდს ჰყავს დიდი რაოდენობით არაინგლუსურენოვანი მომხმარებელი, მათ მაინც მიიღეს ინგლისურენოვანი მომხმარებლების საზოგადოება. მომხმარებლები ნელ-ნელა იყოფოდნენ ერთმანეთისგან და, მაშასადამე, ჩვენი იდეა იმაშიც მდგომარეობს, რომ ისევ გავაერთიანოთ მოთამაშეები და დავაბრუნოთ მათი ერთობა. ბევრი მომხმარებელი იყო დაბლოკილი ოფიციალური SA:MP-ის ფორუმიდან ( და რამდენიმე შემთხვევაში მათი პოსტებისა და კომენტარების ისტორიაც წაიშალა), მაგრამ Kalcor-მა განაცხადა, რომ SA:MP-ის ოფიციალური ფორუმი არ არის SA:MP-ი, და არც მისი ნაწილი. ბევრ მოთამაშესა და სერვერის მფლობელს არ აქვთ დაპოსტილი ამ ფორუმზე, უფრო მეტიც: არც არიან დარეგისტრირებულნი.
<hr />
## ვინაიდან და რადგანაც ის არის "Open" Multiplayer, იქნება თუ არა მისი კოდი ყველასათვის ხელმისაწვდომი?
დიახ, არის ჩვენი პასუხი, თუმცა ამჟამად ჩვენ ვცდილობთ, დავამყაროთ ღია კომუნიკაცია და გამჭირვალობა დეველოფმენთის შესახებ (რომელიც უკვე გაუმჯობესებაა). მომავალში კი, როცა ყველაფერი თავის ადგილას დალაგდება, გავხდით კოდს ხელმისაწვდომს.
<hr />
## როდის გაეშვება?
ეს საკმაოდ რთული შეკითხვაა, რომელსაც ერთი, თუმცა არასრული პასუხი აქვს: როცაც მზად იქნება. არ არსებობს გზა, რომელიც მიგვითითებს, თუ რამდენი ხანი დასჭირდება მსგავსი პროექტის დასრულებას. დიდი ხანია მიმდინარეობს პროექტზე მუშაობა და მისი აქტივობა სამწუხაროდ ცვალებადია, ამის ფაქტორი კი იმ ხალხის შეზღუდული თავისუფალი დრო გახლავთ, რომლებიც პროექტზე მუშაობენ. თუმცა, აღსანიშნავია, რომ პროექტი სწრაფად პროგრესირებს გარკვეული მიზეზების გამო, რომლებზეც დეტალურად მომავალში ვისაუბრებთ.
<hr />
## როგორ შეგიძლია დაგვეხმარო?
თვალი ადევნე ფორუმს. ჩვენ გვაქვს გახსნილი სტატია ამ თემაზე, რომელსაც მაშინვე ვანახლებთ, როგორც კი განახლებას ვაკეთებთ პროდუქტზე. მიუხედავად იმისა, რომ პროექტი დაგეგმიზლე ადრე გამჟღავნდა საზოგადოებაში, ჩვენ უკვე ახლოს ვართ პირველი ვერსიის გამოშვებასთან. თუმცა, ეს არ ნიშავს, რომ მეტი დახმარება არ დაფასდება. მადლობა ყველას წინასწარ ამ პროექტში დაინტერესებისთვის და იმედის ქონისთვის:
[სტატია - "How to help"](https://forum.open.mp/showthread.php?tid=99)
<hr />
## რა არის burgershot.gg?
burgershot.gg არის გეიმინგ ფორუმი და არაფერი სხვა. ბევრი მომხმარებელი არის ჩართული ორივე პროექტში და გარკვეული open.mp-ს განვითარება-განახლება იპოსტება აქ, თუმცა, ეს ორი სხვადასხვა დამოუკიდებელი პროექტია. burgershot.gg არ არის OMP ფორუმი, არც OMP არის burgershot-ის საკუთრება. როცა OMP საიტი სრულად გაეშვება, ეს ორიც განთავისუფლდება ერთმანეთისგან (SA:MP-იც დაჰოსტილი იყო GTAForums მიერ სანამ საკუთარ საიტს გაუშვებდა).
<hr />
## რას ვფიქრობთ OpenMP -ზე?
Open Multi-Processing პროექტი არის "OpenMP", ჩვენ ვართ "open.mp" - აბსოლუტურად სხვადასხვა.
| openmultiplayer/web/frontend/content/ka/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/ka/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 14358
} | 473 |
# Open Multiplayer
Грядущая мультиплеерная модификация для _Grand Theft Auto: San Andreas_, которая будет полностью обратно совместимой с существующей мультиплеерной модификацией, известной как _San Andreas Multiplayer._
<br />
Это значит, что **существующий клиент SA-MP и все скрипты будут работать с open.mp**, а также многие ошибки в серверной части мультиплеера будут исправлены без необходимости для хаков и временных решений.
Если Вы заинтересованы новостями о публичном релизе или хотите внести свой вклад в проект, пройдите в <a href="https://forum.open.mp/showthread.php?tid=99">эту тему на форуме</a> для изучения дальнейшей информации.
# [FAQ](/faq)
| openmultiplayer/web/frontend/content/ru/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/ru/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 604
} | 474 |
# Open Multiplayer
_Grand Theft Auto: San Andreas_, olarak bilinen oyuna hazırlanan ve San Andreas Multiplayer ile uyumlu bir çok oyunculu mod.
<br />
Bu, mevcut **SA:MP istemcisinin ve tüm kodların Open Multiplayer ile eş zamanlı olarak çalıştırılabileceği anlamına geliyor. open.mp**, ekstra olarak çok oyunculu sunucu tarafında birçok hatayı düzeltecek ve geçici çözümler ile insanları oyalamadan sorunları düzeltecektir.
Open.MP ile ilgili haberlerle ilgileniyorsanız veya projeye katkıda bulunmak istiyorsanız, [Forum üzerinden](https://forum.open.mp/showthread.php?tid=99) daha fazla bilgi edinebilirsiniz.
# [SSS](/faq)
| openmultiplayer/web/frontend/content/tr/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/tr/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 277
} | 475 |
---
title: 10,000 名用户!
date: "2021-07-16T02:51:00"
author: Potassium
---
嗨,大家好!
我们最近达到了一个惊人的里程碑:我们的 Discord 正式达到了 10,000 名用户! 🥳🔟🥳
我们认为我们应该借此机会给大家一个小小的更新,因为我们知道已经有一段时间没更新了,大家都想知道发生了什么!
所有的开发团队的成员都有本职工作和其他不得不做的事,加上我们都被新冠疫情搞得焦头烂额,意味着我们已经有一段时间没有太多精力投入在 open.mp 了。
但最近情况又好转了,我们还活着,项目进展得比以往任何时候都快,过去几周我们取得的进展比很长一段时间都要多!
我们为这项工作感到自豪,也为我们拥有的令人惊叹的精致团队而感到自豪。
我们将在未来几个月提供更详细的信息,但现在我们只想让大家知道,我们没有放弃 open.mp,我们的热情依然存在,我们正在尽力而为。所以请继续关注我们,我们很快就会有一些新消息,一些截图和视频!
与此同时,请在 Discord 上和我们一起玩耍吧! 感谢所有 10,000 多位朋友 🥰。
我们的 Discord 服务器是一个温馨的地方,欢迎所有圣安地列斯的多人游戏模组的玩家和社区的朋友!我们提倡以下这些事:
✅ 社区:与常客一起玩耍,认识新朋友,寻找老朋友和老玩家,在特定语言频道中寻找来自你所在国家/地区的人,认识来自 SA-MP/MTA/其他多人游戏模组的人
✅ 脚本:学习编写脚本,在你编写的脚本方面的获得帮助,帮助他人
✅ 服务器广告:在专用频道中炫耀你的 SA-MP 服务器
✅ 编程和技术:讨论并获得其他编程语言和软件开发、技术支持方面的帮助,结识其他志同道合的人一起工作
✅ 游戏:寻找可以一起玩游戏的人(不仅仅是 SA!),讨论游戏新闻和更新内容。
✅ 展示:你是一名 YouTuber?主播?艺术家?玩很酷的音乐?是一位厨师?也许你会钓鱼?或者建造汽车?不管你为什么而感到自豪,都要展示出来!
✅ open.mp: 了解 open.mp 的最新开发进展和 GitHub 动态,与团队一起玩耍,当我们的 Discord VIP 专属直播开发恢复运行时,欢迎观看我们的直播!
| openmultiplayer/web/frontend/content/zh-cn/blog/10k-members.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/zh-cn/blog/10k-members.mdx",
"repo_id": "openmultiplayer",
"token_count": 1685
} | 476 |
import React from "react";
type AdType = {
ifmClass: string;
keyword: string;
emoji: string;
svg: JSX.Element;
};
// copied from https://github.com/elviswolcott/remark-admonitions/blob/master/lib/index.js
const types: { [key: string]: AdType } = {
note: {
ifmClass: "secondary",
keyword: "note",
emoji: "ℹ️", // 'ℹ'
svg: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="16"
viewBox="0 0 14 16"
>
<path
fillRule="evenodd"
d="M6.3 5.69a.942.942 0 0 1-.28-.7c0-.28.09-.52.28-.7.19-.18.42-.28.7-.28.28 0 .52.09.7.28.18.19.28.42.28.7 0 .28-.09.52-.28.7a1 1 0 0 1-.7.3c-.28 0-.52-.11-.7-.3zM8 7.99c-.02-.25-.11-.48-.31-.69-.2-.19-.42-.3-.69-.31H6c-.27.02-.48.13-.69.31-.2.2-.3.44-.31.69h1v3c.02.27.11.5.31.69.2.2.42.31.69.31h1c.27 0 .48-.11.69-.31.2-.19.3-.42.31-.69H8V7.98v.01zM7 2.3c-3.14 0-5.7 2.54-5.7 5.68 0 3.14 2.56 5.7 5.7 5.7s5.7-2.55 5.7-5.7c0-3.15-2.56-5.69-5.7-5.69v.01zM7 .98c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.12-7-7 3.14-7 7-7z"
/>
</svg>
),
},
tip: {
ifmClass: "success",
keyword: "tip",
emoji: "💡", //'💡'
svg: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="16"
viewBox="0 0 12 16"
>
<path
fillRule="evenodd"
d="M6.5 0C3.48 0 1 2.19 1 5c0 .92.55 2.25 1 3 1.34 2.25 1.78 2.78 2 4v1h5v-1c.22-1.22.66-1.75 2-4 .45-.75 1-2.08 1-3 0-2.81-2.48-5-5.5-5zm3.64 7.48c-.25.44-.47.8-.67 1.11-.86 1.41-1.25 2.06-1.45 3.23-.02.05-.02.11-.02.17H5c0-.06 0-.13-.02-.17-.2-1.17-.59-1.83-1.45-3.23-.2-.31-.42-.67-.67-1.11C2.44 6.78 2 5.65 2 5c0-2.2 2.02-4 4.5-4 1.22 0 2.36.42 3.22 1.19C10.55 2.94 11 3.94 11 5c0 .66-.44 1.78-.86 2.48zM4 14h5c-.23 1.14-1.3 2-2.5 2s-2.27-.86-2.5-2z"
/>
</svg>
),
},
warning: {
ifmClass: "danger",
keyword: "warning",
emoji: "🔥", //'🔥'
svg: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="16"
viewBox="0 0 12 16"
>
<path
fillRule="evenodd"
d="M5.05.31c.81 2.17.41 3.38-.52 4.31C3.55 5.67 1.98 6.45.9 7.98c-1.45 2.05-1.7 6.53 3.53 7.7-2.2-1.16-2.67-4.52-.3-6.61-.61 2.03.53 3.33 1.94 2.86 1.39-.47 2.3.53 2.27 1.67-.02.78-.31 1.44-1.13 1.81 3.42-.59 4.78-3.42 4.78-5.56 0-2.84-2.53-3.22-1.25-5.61-1.52.13-2.03 1.13-1.89 2.75.09 1.08-1.02 1.8-1.86 1.33-.67-.41-.66-1.19-.06-1.78C8.18 5.31 8.68 2.45 5.05.32L5.03.3l.02.01z"
/>
</svg>
),
},
important: {
ifmClass: "info",
keyword: "important",
emoji: "❗️", //'❗'
svg: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="16"
viewBox="0 0 14 16"
>
<path
fillRule="evenodd"
d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"
/>
</svg>
),
},
caution: {
ifmClass: "warning",
keyword: "caution",
emoji: "⚠️", // '⚠️'
svg: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
>
<path
fillRule="evenodd"
d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"
/>
</svg>
),
},
};
type Props = {
type: string;
title?: string;
children: React.ReactNode;
};
const Admonition = ({ type, title, children }: Props) => {
const adtype = types[type];
return (
<div className={`admonition admonition-${type} alert alert--success`}>
<div className="admonition-heading">
<h5>
<span className="admonition-icon">{adtype.svg}</span>
{adtype.keyword} {title}
</h5>
</div>
<div className="admonition-content">{children}</div>
</div>
);
};
export default Admonition;
| openmultiplayer/web/frontend/src/components/Admonition.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/Admonition.tsx",
"repo_id": "openmultiplayer",
"token_count": 2539
} | 477 |
import React from "react";
const Pull = ({ fill = "white", display = "inline" }) => (
<svg
className="octicon octicon-git-pull-request"
viewBox="0 0 12 16"
version="1.1"
width="12"
height="16"
aria-hidden="true"
focusable="false"
role="img"
xmlns="http://www.w3.org/2000/svg"
fill={fill}
display={display}
>
<path
fillRule="evenodd"
d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"
/>
</svg>
);
export default Pull;
| openmultiplayer/web/frontend/src/components/icons/Pull.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/icons/Pull.tsx",
"repo_id": "openmultiplayer",
"token_count": 597
} | 478 |
import { CloseIcon, HamburgerIcon } from "@chakra-ui/icons";
import {
Box,
Button,
Flex,
IconButton,
Link,
Menu,
MenuButton,
MenuDivider,
MenuGroup,
MenuItem,
MenuList,
useColorMode,
useDisclosure,
} from "@chakra-ui/react";
import {
MoonIcon,
SunIcon
} from '@chakra-ui/icons';
import { FC, useRef } from "react";
import { useRouter } from "next/router";
import NextLink from "next/link";
import { useAuth } from "src/auth/hooks";
import LanguageSelect from "./LanguageSelect";
export type NavItem = {
name: string;
path: string;
exact?: boolean;
extra?: string;
};
export type Props = {
items: NavItem[];
route: string;
};
const ON_DESKTOP = { base: "none", md: "flex" };
const ON_MOBILE = { base: "flex", md: "none" };
const NavMenu: FC<Props> = ({ items, route }) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const { user } = useAuth();
const { colorMode, toggleColorMode } = useColorMode();
const languageRef = useRef<{ open: () => void }>(null);
const router = useRouter()
const isCurrent = (path: string) => path === route;
return (
<Box p="2">
<Flex gridGap={1} alignItems={"center"} justifyContent={"space-between"}>
<Flex gridGap={1} display={ON_DESKTOP}>
{items.map((link) => (
<NavLink
key={link.path}
item={link}
current={isCurrent(link.path)}
/>
))}
<IconButton cursor="pointer" as="div" size="sm" aria-label="Toggle Mode" onClick={toggleColorMode}>
{colorMode === 'light' ? <MoonIcon/> : <SunIcon/>}
</IconButton>
</Flex>
<IconButton cursor="pointer" display={ON_MOBILE} size="sm" aria-label="Toggle Mode" onClick={toggleColorMode}>
{colorMode === 'light' ? <MoonIcon/> : <SunIcon/>}
</IconButton>
<Menu isOpen={isOpen} onOpen={onOpen} onClose={onClose}>
<MenuButton
as={IconButton}
aria-label="Navigation Menu"
icon={isOpen ? <CloseIcon /> : <HamburgerIcon />}
size="sm"
variant="ghost"
/>
<MenuList>
<MenuGroup>
{items.map(({ path, name }) => (
<MenuItem
key={path}
display={ON_MOBILE}
current={isCurrent(path).toString()}
onClick={() => router.push(path)}
>
{name}
</MenuItem>
))}
</MenuGroup>
<MenuDivider display={ON_MOBILE} />
<MenuGroup>
{user ? (
<MenuItem onClick={() => router.push('/dashboard')}>
Dashboard
</MenuItem>
) : (
<MenuItem onClick={() => router.push('/login')}>
Login
</MenuItem>
)}
<MenuItem onClick={()=> languageRef.current?.open()}>
<LanguageSelect title="Language" ref={languageRef} />
</MenuItem>
</MenuGroup>
</MenuList>
</Menu>
</Flex>
</Box>
);
};
type NavLinkProps = { item: NavItem; current: boolean };
const NavLink: FC<NavLinkProps> = ({ item, current }) => (
<NextLink href={item.path} passHref>
<Link _hover={undefined} _focus={{ outline: 'none', border: 'none' }}>
<Button as="div" variant={current ? "outline" : "ghost"} size="sm">
{item.name}
</Button>
</Link>
</NextLink>
);
export default NavMenu;
| openmultiplayer/web/frontend/src/components/site/NavMenu.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/site/NavMenu.tsx",
"repo_id": "openmultiplayer",
"token_count": 1727
} | 479 |
import Admonition from "../../../Admonition";
export default function WarningVersion({
version,
name = "function",
}: {
version: string;
name: string;
}) {
return (
<Admonition type="warning">
<p>
Esta {name} foi implementada no {version} e não funcionará em
versões anteriores.
</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/pt-BR/version-warning.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/pt-BR/version-warning.tsx",
"repo_id": "openmultiplayer",
"token_count": 145
} | 480 |
import React from "react";
import mdx from "@mdx-js/mdx";
import { MDXProvider, mdx as mdxReact } from "@mdx-js/react";
import { transformAsync } from "@babel/core";
import presetEnv from "@babel/preset-env";
import presetReact from "@babel/preset-react";
import { renderToString as reactRenderToString } from "react-dom/server";
import { readLocaleContent } from "src/utils/content";
import { MDX_COMPONENTS } from "./components";
import { MarkdownContent, MarkdownRenderConfig } from "./types";
import pluginBrowser from "./babel-plugin-mdx-browser";
// Renders markdown content on the server for the given locale. Uses
// readLocaleContent under the hood which handles fallbacks/extensions.
export const markdownSSR = async (
locale: string,
file: string
): Promise<MarkdownContent> => {
const { source } = await readLocaleContent(file, locale);
return await renderToString(source, {
components: MDX_COMPONENTS,
});
};
// Stolen from Hashicorp's next-mdx-remote!
export const renderToString = async (
source: Buffer | string,
{ components, mdxOptions, scope = {} }: MarkdownRenderConfig
): Promise<MarkdownContent> => {
// transform it into react
const code = await mdx(source, { ...mdxOptions, skipExport: true });
// mdx gives us back es6 code, we then need to transform into two formats:
// - first a version we can render to string right now as a "serialized" result
// - next a version that is fully browser-compatible that we can eval to rehydrate
// this one is for immediate evaluation so we can renderToString below
const now = await transformAsync(code, {
presets: [presetReact, presetEnv],
configFile: false,
});
// this one is for the browser to eval and rehydrate, later
const later = await transformAsync(code, {
presets: [presetReact, presetEnv],
plugins: [pluginBrowser],
configFile: false,
});
// evaluate the code
// NOTES:
// - relative imports can't be expected to work with remote files, we'd need
// an extra babel transform to be able to import specific file paths
const fn = new Function(
"React",
"MDXProvider",
"mdx",
"components",
...Object.keys(scope),
`${now?.code}
return React.createElement(MDXProvider, { components },
React.createElement(MDXContent, {})
);`
);
const component = fn(
React,
MDXProvider,
mdxReact,
components,
...Object.values(scope)
);
// react: render to string
const renderedOutput = reactRenderToString(component);
return {
compiledSource: later?.code || "",
renderedOutput,
scope,
};
};
| openmultiplayer/web/frontend/src/mdx-helpers/ssr.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/mdx-helpers/ssr.ts",
"repo_id": "openmultiplayer",
"token_count": 822
} | 481 |
import { withoutAuth } from "src/auth/hoc";
import GitHubIcon from "src/components/icons/GitHub";
import DiscordIcon from "src/components/icons/Discord";
import OAuthButton from "src/components/OAuthButton";
const Page = () => (
<section className="measure center pa3">
<h1>Login</h1>
<p>Please log in using one of the providers below.</p>
<p>Email based login is not currently available.</p>
<p>
You can link multiple account types to your open.mp account from your
dashboard once you've logged in.
</p>
<br />
<ul className="list pa0">
<OAuthButton bg="black" icon={<GitHubIcon width={24} />} type="github" />
<OAuthButton
bg="#2C2F33"
icon={<DiscordIcon width={24} fill="white" />}
type="discord"
/>
</ul>
</section>
);
export default withoutAuth(Page);
| openmultiplayer/web/frontend/src/pages/login.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/login.tsx",
"repo_id": "openmultiplayer",
"token_count": 328
} | 482 |
/* This is a theme distributed by `starry-night`.
* It’s based on what GitHub uses on their site.
* See <https://github.com/wooorm/starry-night> for more info. */
:root {
--color-prettylights-syntax-comment: #6e7781;
--color-prettylights-syntax-constant: #0550ae;
--color-prettylights-syntax-entity: #6639ba;
--color-prettylights-syntax-storage-modifier-import: #24292f;
--color-prettylights-syntax-entity-tag: #116329;
--color-prettylights-syntax-keyword: #cf222e;
--color-prettylights-syntax-string: #0a3069;
--color-prettylights-syntax-variable: #953800;
--color-prettylights-syntax-brackethighlighter-unmatched: #82071e;
--color-prettylights-syntax-invalid-illegal-text: #f6f8fa;
--color-prettylights-syntax-invalid-illegal-bg: #82071e;
--color-prettylights-syntax-carriage-return-text: #f6f8fa;
--color-prettylights-syntax-carriage-return-bg: #cf222e;
--color-prettylights-syntax-string-regexp: #116329;
--color-prettylights-syntax-markup-list: #3b2300;
--color-prettylights-syntax-markup-heading: #0550ae;
--color-prettylights-syntax-markup-italic: #24292f;
--color-prettylights-syntax-markup-bold: #24292f;
--color-prettylights-syntax-markup-deleted-text: #82071e;
--color-prettylights-syntax-markup-deleted-bg: #ffebe9;
--color-prettylights-syntax-markup-inserted-text: #116329;
--color-prettylights-syntax-markup-inserted-bg: #dafbe1;
--color-prettylights-syntax-markup-changed-text: #953800;
--color-prettylights-syntax-markup-changed-bg: #ffd8b5;
--color-prettylights-syntax-markup-ignored-text: #eaeef2;
--color-prettylights-syntax-markup-ignored-bg: #0550ae;
--color-prettylights-syntax-meta-diff-range: #8250df;
--color-prettylights-syntax-brackethighlighter-angle: #57606a;
--color-prettylights-syntax-sublimelinter-gutter-mark: #8c959f;
--color-prettylights-syntax-constant-other-reference-link: #0a3069;
--color-prettylights-syntax-comment: #6e7781;
--color-prettylights-syntax-constant: #0550ae;
--color-prettylights-syntax-entity: #6639ba;
--color-prettylights-syntax-storage-modifier-import: #24292f;
--color-prettylights-syntax-entity-tag: #116329;
--color-prettylights-syntax-keyword: #cf222e;
--color-prettylights-syntax-string: #0a3069;
--color-prettylights-syntax-variable: #953800;
--color-prettylights-syntax-brackethighlighter-unmatched: #82071e;
--color-prettylights-syntax-invalid-illegal-text: #f6f8fa;
--color-prettylights-syntax-invalid-illegal-bg: #82071e;
--color-prettylights-syntax-carriage-return-text: #f6f8fa;
--color-prettylights-syntax-carriage-return-bg: #cf222e;
--color-prettylights-syntax-string-regexp: #116329;
--color-prettylights-syntax-markup-list: #3b2300;
--color-prettylights-syntax-markup-heading: #0550ae;
--color-prettylights-syntax-markup-italic: #24292f;
--color-prettylights-syntax-markup-bold: #24292f;
--color-prettylights-syntax-markup-deleted-text: #82071e;
--color-prettylights-syntax-markup-deleted-bg: #ffebe9;
--color-prettylights-syntax-markup-inserted-text: #116329;
--color-prettylights-syntax-markup-inserted-bg: #dafbe1;
--color-prettylights-syntax-markup-changed-text: #953800;
--color-prettylights-syntax-markup-changed-bg: #ffd8b5;
--color-prettylights-syntax-markup-ignored-text: #eaeef2;
--color-prettylights-syntax-markup-ignored-bg: #0550ae;
--color-prettylights-syntax-meta-diff-range: #8250df;
--color-prettylights-syntax-brackethighlighter-angle: #57606a;
--color-prettylights-syntax-sublimelinter-gutter-mark: #8c959f;
--color-prettylights-syntax-constant-other-reference-link: #0a3069;
}
:root {
.chakra-ui-dark {
--color-prettylights-syntax-comment: #768390;
--color-prettylights-syntax-constant: #3399FF;
--color-prettylights-syntax-entity: #CF4181;
--color-prettylights-syntax-storage-modifier-import: #adbac7;
--color-prettylights-syntax-entity-tag: #8ddb8c;
--color-prettylights-syntax-keyword: #F25B4F;
--color-prettylights-syntax-string: #2397AB;
--color-prettylights-syntax-variable: #f69d50;
--color-prettylights-syntax-brackethighlighter-unmatched: #e5534b;
--color-prettylights-syntax-invalid-illegal-text: #cdd9e5;
--color-prettylights-syntax-invalid-illegal-bg: #922323;
--color-prettylights-syntax-carriage-return-text: #cdd9e5;
--color-prettylights-syntax-carriage-return-bg: #ad2e2c;
--color-prettylights-syntax-string-regexp: #8ddb8c;
--color-prettylights-syntax-markup-list: #eac55f;
--color-prettylights-syntax-markup-heading: #316dca;
--color-prettylights-syntax-markup-italic: #adbac7;
--color-prettylights-syntax-markup-bold: #adbac7;
--color-prettylights-syntax-markup-deleted-text: #ffd8d3;
--color-prettylights-syntax-markup-deleted-bg: #78191b;
--color-prettylights-syntax-markup-inserted-text: #b4f1b4;
--color-prettylights-syntax-markup-inserted-bg: #1b4721;
--color-prettylights-syntax-markup-changed-text: #ffddb0;
--color-prettylights-syntax-markup-changed-bg: #682d0f;
--color-prettylights-syntax-markup-ignored-text: #adbac7;
--color-prettylights-syntax-markup-ignored-bg: #255ab2;
--color-prettylights-syntax-meta-diff-range: #dcbdfb;
--color-prettylights-syntax-brackethighlighter-angle: #768390;
--color-prettylights-syntax-sublimelinter-gutter-mark: #545d68;
--color-prettylights-syntax-constant-other-reference-link: #96d0ff;
}
}
.pl-c {
color: var(--color-prettylights-syntax-comment);
}
.pl-c1,
.pl-s .pl-v {
color: var(--color-prettylights-syntax-constant);
}
.pl-e,
.pl-en {
color: var(--color-prettylights-syntax-entity);
}
.pl-smi,
.pl-s .pl-s1 {
color: var(--color-prettylights-syntax-storage-modifier-import);
}
.pl-ent {
color: var(--color-prettylights-syntax-entity-tag);
}
.pl-k {
color: var(--color-prettylights-syntax-keyword);
}
.pl-s,
.pl-pds,
.pl-s .pl-pse .pl-s1,
.pl-sr,
.pl-sr .pl-cce,
.pl-sr .pl-sre,
.pl-sr .pl-sra {
color: var(--color-prettylights-syntax-string);
}
.pl-v,
.pl-smw {
color: var(--color-prettylights-syntax-variable);
}
.pl-bu {
color: var(--color-prettylights-syntax-brackethighlighter-unmatched);
}
.pl-ii {
color: var(--color-prettylights-syntax-invalid-illegal-text);
background-color: var(--color-prettylights-syntax-invalid-illegal-bg);
}
.pl-c2 {
color: var(--color-prettylights-syntax-carriage-return-text);
background-color: var(--color-prettylights-syntax-carriage-return-bg);
}
.pl-sr .pl-cce {
font-weight: bold;
color: var(--color-prettylights-syntax-string-regexp);
}
.pl-ml {
color: var(--color-prettylights-syntax-markup-list);
}
.pl-mh,
.pl-mh .pl-en,
.pl-ms {
font-weight: bold;
color: var(--color-prettylights-syntax-markup-heading);
}
.pl-mi {
font-style: italic;
color: var(--color-prettylights-syntax-markup-italic);
}
.pl-mb {
font-weight: bold;
color: var(--color-prettylights-syntax-markup-bold);
}
.pl-md {
color: var(--color-prettylights-syntax-markup-deleted-text);
background-color: var(--color-prettylights-syntax-markup-deleted-bg);
}
.pl-mi1 {
color: var(--color-prettylights-syntax-markup-inserted-text);
background-color: var(--color-prettylights-syntax-markup-inserted-bg);
}
.pl-mc {
color: var(--color-prettylights-syntax-markup-changed-text);
background-color: var(--color-prettylights-syntax-markup-changed-bg);
}
.pl-mi2 {
color: var(--color-prettylights-syntax-markup-ignored-text);
background-color: var(--color-prettylights-syntax-markup-ignored-bg);
}
.pl-mdr {
font-weight: bold;
color: var(--color-prettylights-syntax-meta-diff-range);
}
.pl-ba {
color: var(--color-prettylights-syntax-brackethighlighter-angle);
}
.pl-sg {
color: var(--color-prettylights-syntax-sublimelinter-gutter-mark);
}
.pl-corl {
text-decoration: underline;
color: var(--color-prettylights-syntax-constant-other-reference-link);
} | openmultiplayer/web/frontend/src/styles/starry-night.css/0 | {
"file_path": "openmultiplayer/web/frontend/src/styles/starry-night.css",
"repo_id": "openmultiplayer",
"token_count": 3231
} | 483 |
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"downlevelIteration": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
| openmultiplayer/web/frontend/tsconfig.json/0 | {
"file_path": "openmultiplayer/web/frontend/tsconfig.json",
"repo_id": "openmultiplayer",
"token_count": 245
} | 484 |
package version
// Version is set at compile time with ldflags.
var Version = "unknown"
| openmultiplayer/web/internal/version/version.go/0 | {
"file_path": "openmultiplayer/web/internal/version/version.go",
"repo_id": "openmultiplayer",
"token_count": 24
} | 485 |
-- AlterEnum
ALTER TYPE "AuthMethod" ADD VALUE 'UNDEFINED';
-- RenameIndex
ALTER INDEX "Discord.accountId_unique" RENAME TO "Discord_accountId_key";
-- RenameIndex
ALTER INDEX "Discord.email_unique" RENAME TO "Discord_email_key";
-- RenameIndex
ALTER INDEX "Discord.username_unique" RENAME TO "Discord_username_key";
-- RenameIndex
ALTER INDEX "GitHub.accountId_unique" RENAME TO "GitHub_accountId_key";
-- RenameIndex
ALTER INDEX "GitHub.email_unique" RENAME TO "GitHub_email_key";
-- RenameIndex
ALTER INDEX "GitHub.username_unique" RENAME TO "GitHub_username_key";
-- RenameIndex
ALTER INDEX "Rule_serverId_rule_name_index" RENAME TO "Rule_name_serverId_key";
-- RenameIndex
ALTER INDEX "Server.ip_unique" RENAME TO "Server_ip_key";
-- RenameIndex
ALTER INDEX "User.email_unique" RENAME TO "User_email_key";
| openmultiplayer/web/prisma/migrations/20211101120856_undefined_auth_method/migration.sql/0 | {
"file_path": "openmultiplayer/web/prisma/migrations/20211101120856_undefined_auth_method/migration.sql",
"repo_id": "openmultiplayer",
"token_count": 313
} | 486 |
const path = require('path')
// NOTE: must be set before webpack config is imported
process.env.SHARELATEX_CONFIG = path.resolve(
__dirname,
'../config/settings.webpack.js'
)
const customConfig = require('../webpack.config.dev')
module.exports = {
stories: [
'../frontend/stories/**/*.stories.js',
'../modules/**/stories/**/*.stories.js',
],
addons: ['@storybook/addon-essentials', '@storybook/addon-a11y'],
webpackFinal: storybookConfig => {
// Combine Storybook's webpack loaders with our webpack loaders
const rules = [
// Filter out the Storybook font file loader, which overrides our font
// file loader causing the font to fail to load
...storybookConfig.module.rules.filter(
rule => !rule.test.toString().includes('woff')
),
// Replace the less rule, adding to-string-loader
// Filter out the MiniCSS extraction, which conflicts with the built-in CSS loader
...customConfig.module.rules.filter(
rule =>
!rule.test.toString().includes('less') &&
!rule.test.toString().includes('css')
),
{
test: /\.less$/,
use: ['to-string-loader', 'css-loader', 'less-loader'],
},
]
// Combine Storybook's webpack plugins with our webpack plugins
const plugins = [...storybookConfig.plugins, ...customConfig.plugins]
return {
...storybookConfig,
module: {
...storybookConfig.module,
rules,
},
plugins,
}
},
}
| overleaf/web/.storybook/main.js/0 | {
"file_path": "overleaf/web/.storybook/main.js",
"repo_id": "overleaf",
"token_count": 572
} | 487 |
var RefererParser = require('referer-parser')
const { URL } = require('url')
const AnalyticsManager = require('./AnalyticsManager')
function clearSource(session) {
if (session) {
delete session.required_login_for
}
}
const UTM_KEYS = [
'utm_campaign',
'utm_source',
'utm_term',
'utm_medium',
'utm_count',
]
function parseUtm(query) {
var utmValues = {}
for (const utmKey of UTM_KEYS) {
if (query[utmKey]) {
utmValues[utmKey] = query[utmKey]
}
}
return Object.keys(utmValues).length > 0 ? utmValues : null
}
function parseReferrer(referrer, url) {
if (!referrer) {
return {
medium: 'direct',
detail: 'none',
}
}
const parsedReferrer = new RefererParser(referrer, url)
const referrerValues = {
medium: parsedReferrer.medium,
detail: parsedReferrer.referer,
}
if (referrerValues.medium === 'unknown') {
try {
const referrerHostname = new URL(referrer).hostname
if (referrerHostname) {
referrerValues.medium = 'link'
referrerValues.detail = referrerHostname
}
} catch (error) {
// ignore referrer parsing errors
}
}
return referrerValues
}
function setInbound(session, url, query, referrer) {
const inboundSession = {
referrer: parseReferrer(referrer, url),
utm: parseUtm(query),
}
if (inboundSession.referrer || inboundSession.utm) {
session.inbound = inboundSession
}
}
function clearInbound(session) {
if (session) {
delete session.inbound
}
}
function addUserProperties(userId, session) {
if (!session) {
return
}
if (session.referal_id) {
AnalyticsManager.setUserProperty(
userId,
`registered-from-bonus-scheme`,
true
)
}
if (session.required_login_for) {
AnalyticsManager.setUserProperty(
userId,
`registered-from-${session.required_login_for}`,
true
)
}
if (session.inbound) {
if (session.inbound.referrer) {
AnalyticsManager.setUserProperty(
userId,
`registered-from-referrer-${session.inbound.referrer.medium}`,
session.inbound.referrer.detail || 'other'
)
}
if (session.inbound.utm) {
for (const utmKey of UTM_KEYS) {
if (session.inbound.utm[utmKey]) {
AnalyticsManager.setUserProperty(
userId,
`registered-from-${utmKey.replace('_', '-')}`,
session.inbound.utm[utmKey]
)
}
}
}
}
}
module.exports = {
clearSource,
setInbound,
clearInbound,
addUserProperties,
}
| overleaf/web/app/src/Features/Analytics/AnalyticsRegistrationSourceHelper.js/0 | {
"file_path": "overleaf/web/app/src/Features/Analytics/AnalyticsRegistrationSourceHelper.js",
"repo_id": "overleaf",
"token_count": 1071
} | 488 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ChatApiHandler
const OError = require('@overleaf/o-error')
const request = require('request')
const settings = require('@overleaf/settings')
module.exports = ChatApiHandler = {
_apiRequest(opts, callback) {
if (callback == null) {
callback = function (error, data) {}
}
return request(opts, function (error, response, data) {
if (error != null) {
return callback(error)
}
if (response.statusCode >= 200 && response.statusCode < 300) {
return callback(null, data)
} else {
error = new OError(
`chat api returned non-success code: ${response.statusCode}`,
opts
)
error.statusCode = response.statusCode
return callback(error)
}
})
},
sendGlobalMessage(project_id, user_id, content, callback) {
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/messages`,
method: 'POST',
json: { user_id, content },
},
callback
)
},
getGlobalMessages(project_id, limit, before, callback) {
const qs = {}
if (limit != null) {
qs.limit = limit
}
if (before != null) {
qs.before = before
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/messages`,
method: 'GET',
qs,
json: true,
},
callback
)
},
sendComment(project_id, thread_id, user_id, content, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/thread/${thread_id}/messages`,
method: 'POST',
json: { user_id, content },
},
callback
)
},
getThreads(project_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/threads`,
method: 'GET',
json: true,
},
callback
)
},
resolveThread(project_id, thread_id, user_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/thread/${thread_id}/resolve`,
method: 'POST',
json: { user_id },
},
callback
)
},
reopenThread(project_id, thread_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/thread/${thread_id}/reopen`,
method: 'POST',
},
callback
)
},
deleteThread(project_id, thread_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/thread/${thread_id}`,
method: 'DELETE',
},
callback
)
},
editMessage(project_id, thread_id, message_id, content, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/thread/${thread_id}/messages/${message_id}/edit`,
method: 'POST',
json: {
content,
},
},
callback
)
},
deleteMessage(project_id, thread_id, message_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
url: `${settings.apis.chat.internal_url}/project/${project_id}/thread/${thread_id}/messages/${message_id}`,
method: 'DELETE',
},
callback
)
},
}
| overleaf/web/app/src/Features/Chat/ChatApiHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Chat/ChatApiHandler.js",
"repo_id": "overleaf",
"token_count": 1857
} | 489 |
/* eslint-disable
camelcase,
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
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ContactsController
const SessionManager = require('../Authentication/SessionManager')
const ContactManager = require('./ContactManager')
const UserGetter = require('../User/UserGetter')
const logger = require('logger-sharelatex')
const Modules = require('../../infrastructure/Modules')
module.exports = ContactsController = {
getContacts(req, res, next) {
const user_id = SessionManager.getLoggedInUserId(req.session)
return ContactManager.getContactIds(
user_id,
{ limit: 50 },
function (error, contact_ids) {
if (error != null) {
return next(error)
}
return UserGetter.getUsers(
contact_ids,
{
email: 1,
first_name: 1,
last_name: 1,
holdingAccount: 1,
},
function (error, contacts) {
if (error != null) {
return next(error)
}
// UserGetter.getUsers may not preserve order so put them back in order
const positions = {}
for (let i = 0; i < contact_ids.length; i++) {
const contact_id = contact_ids[i]
positions[contact_id] = i
}
contacts.sort(
(a, b) =>
positions[a._id != null ? a._id.toString() : undefined] -
positions[b._id != null ? b._id.toString() : undefined]
)
// Don't count holding accounts to discourage users from repeating mistakes (mistyped or wrong emails, etc)
contacts = contacts.filter(c => !c.holdingAccount)
contacts = contacts.map(ContactsController._formatContact)
return Modules.hooks.fire(
'getContacts',
user_id,
contacts,
function (error, additional_contacts) {
if (error != null) {
return next(error)
}
contacts = contacts.concat(
...Array.from(additional_contacts || [])
)
return res.send({
contacts,
})
}
)
}
)
}
)
},
_formatContact(contact) {
return {
id: contact._id != null ? contact._id.toString() : undefined,
email: contact.email || '',
first_name: contact.first_name || '',
last_name: contact.last_name || '',
type: 'user',
}
},
}
| overleaf/web/app/src/Features/Contacts/ContactController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Contacts/ContactController.js",
"repo_id": "overleaf",
"token_count": 1342
} | 490 |
const _ = require('underscore')
module.exports = _.template(`\
<table class="row" style="border-collapse: collapse; border-spacing: 0; display: table; padding: 0; position: relative; text-align: left; vertical-align: top; width: 100%;">
<tbody>
<tr style="padding: 0; vertical-align: top;">
<th class="small-12 columns" style="line-height: 1.3; margin: 0 auto; padding: 0; padding-bottom: 16px; padding-left: 16px; padding-right: 16px; text-align: left;">
<table style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3;">
<tr style="padding: 0; text-align: left; vertical-align: top;">
<th style="margin: 0; padding: 0; text-align: left;">
<% if (title) { %>
<h3 class="force-overleaf-style" style="margin: 0; color: #5D6879; font-family: Georgia, serif; font-size: 24px; font-weight: normal; line-height: 1.3; padding: 0; text-align: left; word-wrap: normal;">
<%= title %>
</h3>
<% } %>
</th>
<tr>
<td>
<p style="height: 20px; margin: 0; padding: 0;"> </p>
<% if (greeting) { %>
<p style="margin: 0 0 10px 0; padding: 0;">
<%= greeting %>
</p>
<% } %>
<% (message).forEach(function(paragraph) { %>
<p class="force-overleaf-style" style="margin: 0 0 10px 0; padding: 0;">
<%= paragraph %>
</p>
<% }) %>
<p style="margin: 0; padding: 0;"> </p>
<table style="border-collapse: collapse; border-spacing: 0; float: none; margin: 0 auto; padding: 0; text-align: center; vertical-align: top; width: auto;">
<tr style="padding: 0; text-align: left; vertical-align: top;">
<td style="-moz-hyphens: auto; -webkit-hyphens: auto; border-collapse: collapse !important; border-radius: 9999px; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;">
<table style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%;">
<tr style="padding: 0; text-align: left; vertical-align: top;">
<td style="-moz-hyphens: auto; -webkit-hyphens: auto; background: #4F9C45; border: none; border-collapse: collapse !important; border-radius: 9999px; color: #fefefe; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;">
<a href="<%= ctaURL %>" style="border: 0 solid #4F9C45; border-radius: 9999px; color: #fefefe; display: inline-block; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: bold; line-height: 1.3; margin: 0; padding: 8px 16px 8px 16px; text-align: left; text-decoration: none;">
<%= ctaText %>
</a>
</td>
</tr>
</table>
</td>
</tr>
</table>
<% if (secondaryMessage && secondaryMessage.length > 0) { %>
<p style="margin: 0; padding: 0;"> </p>
<% (secondaryMessage).forEach(function(paragraph) { %>
<p class="force-overleaf-style">
<%= paragraph %>
</p>
<% }) %>
<% } %>
<p style="margin: 0; padding: 0;"> </p>
<p class="force-overleaf-style" style="font-size: 12px;">
If the button above does not appear, please copy and paste this link into your browser's address bar:
</p>
<p class="force-overleaf-style" style="font-size: 12px;">
<%= ctaURL %>
</p>
</td>
</tr>
</tr>
</table>
</th>
</tr>
</tbody>
</table>
<% if (gmailGoToAction) { %>
<script type="application/ld+json">
<%=
StringHelper.stringifyJsonForScript({
"@context": "http://schema.org",
"@type": "EmailMessage",
"potentialAction": {
"@type": "ViewAction",
"target": gmailGoToAction.target,
"url": gmailGoToAction.target,
"name": gmailGoToAction.name
},
"description": gmailGoToAction.description
})
%>
</script>
<% } %>
\
`)
| overleaf/web/app/src/Features/Email/Bodies/cta-email.js/0 | {
"file_path": "overleaf/web/app/src/Features/Email/Bodies/cta-email.js",
"repo_id": "overleaf",
"token_count": 2105
} | 491 |
const RedisWrapper = require('../../infrastructure/RedisWrapper')
const rclient = RedisWrapper.client('health_check')
const settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const UserGetter = require('../User/UserGetter')
const {
SmokeTestFailure,
runSmokeTests,
} = require('./../../../../test/smoke/src/SmokeTests')
module.exports = {
check(req, res, next) {
if (!settings.siteIsOpen || !settings.editorIsOpen) {
// always return successful health checks when site is closed
res.contentType('application/json')
res.sendStatus(200)
} else {
// detach from express for cleaner stack traces
setTimeout(() => runSmokeTestsDetached(req, res).catch(next))
}
},
checkActiveHandles(req, res, next) {
if (!(settings.maxActiveHandles > 0) || !process._getActiveHandles) {
return next()
}
const activeHandlesCount = (process._getActiveHandles() || []).length
if (activeHandlesCount > settings.maxActiveHandles) {
logger.err(
{ activeHandlesCount, maxActiveHandles: settings.maxActiveHandles },
'exceeded max active handles, failing health check'
)
return res.sendStatus(500)
} else {
logger.debug(
{ activeHandlesCount, maxActiveHandles: settings.maxActiveHandles },
'active handles are below maximum'
)
next()
}
},
checkApi(req, res, next) {
rclient.healthCheck(err => {
if (err) {
logger.err({ err }, 'failed api redis health check')
return res.sendStatus(500)
}
UserGetter.getUserEmail(settings.smokeTest.userId, (err, email) => {
if (err) {
logger.err({ err }, 'failed api mongo health check')
return res.sendStatus(500)
}
if (email == null) {
logger.err({ err }, 'failed api mongo health check (no email)')
return res.sendStatus(500)
}
res.sendStatus(200)
})
})
},
checkRedis(req, res, next) {
return rclient.healthCheck(function (error) {
if (error != null) {
logger.err({ err: error }, 'failed redis health check')
return res.sendStatus(500)
} else {
return res.sendStatus(200)
}
})
},
checkMongo(req, res, next) {
return UserGetter.getUserEmail(
settings.smokeTest.userId,
function (err, email) {
if (err != null) {
logger.err({ err }, 'mongo health check failed, error present')
return res.sendStatus(500)
} else if (email == null) {
logger.err(
{ err },
'mongo health check failed, no emai present in find result'
)
return res.sendStatus(500)
} else {
return res.sendStatus(200)
}
}
)
},
}
function prettyJSON(blob) {
return JSON.stringify(blob, null, 2) + '\n'
}
async function runSmokeTestsDetached(req, res) {
function isAborted() {
return req.aborted
}
const stats = { start: new Date(), steps: [] }
let status, response
try {
try {
await runSmokeTests({ isAborted, stats })
} finally {
stats.end = new Date()
stats.duration = stats.end - stats.start
}
status = 200
response = { stats }
} catch (e) {
let err = e
if (!(e instanceof SmokeTestFailure)) {
err = new SmokeTestFailure('low level error', {}, e)
}
logger.err({ err, stats }, 'health check failed')
status = 500
response = { stats, error: err.message }
}
if (isAborted()) return
res.contentType('application/json')
res.status(status).send(prettyJSON(response))
}
| overleaf/web/app/src/Features/HealthCheck/HealthCheckController.js/0 | {
"file_path": "overleaf/web/app/src/Features/HealthCheck/HealthCheckController.js",
"repo_id": "overleaf",
"token_count": 1487
} | 492 |
const OError = require('@overleaf/o-error')
const UserGetter = require('../User/UserGetter')
const { addAffiliation } = require('../Institutions/InstitutionsAPI')
const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
const async = require('async')
const ASYNC_AFFILIATIONS_LIMIT = 10
module.exports = {
confirmDomain(req, res, next) {
const { hostname } = req.body
affiliateUsers(hostname, function (error) {
if (error) {
return next(error)
}
res.sendStatus(200)
})
},
}
var affiliateUsers = function (hostname, callback) {
const reversedHostname = hostname.trim().split('').reverse().join('')
UserGetter.getUsersByHostname(hostname, { _id: 1 }, function (error, users) {
if (error) {
OError.tag(error, 'problem fetching users by hostname')
return callback(error)
}
async.mapLimit(
users,
ASYNC_AFFILIATIONS_LIMIT,
(user, innerCallback) => {
UserGetter.getUserFullEmails(user._id, (error, emails) => {
if (error) return innerCallback(error)
user.emails = emails
affiliateUserByReversedHostname(user, reversedHostname, innerCallback)
})
},
callback
)
})
}
var affiliateUserByReversedHostname = function (
user,
reversedHostname,
callback
) {
const matchingEmails = user.emails.filter(
email => email.reversedHostname === reversedHostname
)
async.mapSeries(
matchingEmails,
(email, innerCallback) => {
addAffiliation(
user._id,
email.email,
{
confirmedAt: email.confirmedAt,
entitlement:
email.samlIdentifier && email.samlIdentifier.hasEntitlement,
},
error => {
if (error) {
OError.tag(
error,
'problem adding affiliation while confirming hostname'
)
return innerCallback(error)
}
FeaturesUpdater.refreshFeatures(
user._id,
'affiliate-user-by-reversed-hostname',
innerCallback
)
}
)
},
callback
)
}
| overleaf/web/app/src/Features/Institutions/InstitutionsController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Institutions/InstitutionsController.js",
"repo_id": "overleaf",
"token_count": 931
} | 493 |
const NotificationsHandler = require('./NotificationsHandler')
const { promisifyAll } = require('../../util/promises')
const request = require('request')
const settings = require('@overleaf/settings')
function dropboxDuplicateProjectNames(userId) {
return {
key: `dropboxDuplicateProjectNames-${userId}`,
create(projectName, callback) {
if (callback == null) {
callback = function () {}
}
NotificationsHandler.createNotification(
userId,
this.key,
'notification_dropbox_duplicate_project_names',
{ projectName },
null,
true,
callback
)
},
read(callback) {
if (callback == null) {
callback = function () {}
}
NotificationsHandler.markAsReadWithKey(userId, this.key, callback)
},
}
}
function dropboxUnlinkedDueToLapsedReconfirmation(userId) {
return {
key: 'drobox-unlinked-due-to-lapsed-reconfirmation',
create(callback) {
NotificationsHandler.createNotification(
userId,
this.key,
'notification_dropbox_unlinked_due_to_lapsed_reconfirmation',
{},
null,
true,
callback
)
},
read(callback) {
NotificationsHandler.markAsReadWithKey(userId, this.key, callback)
},
}
}
function featuresUpgradedByAffiliation(affiliation, user) {
return {
key: `features-updated-by=${affiliation.institutionId}`,
create(callback) {
if (callback == null) {
callback = function () {}
}
const messageOpts = { institutionName: affiliation.institutionName }
NotificationsHandler.createNotification(
user._id,
this.key,
'notification_features_upgraded_by_affiliation',
messageOpts,
null,
false,
callback
)
},
read(callback) {
if (callback == null) {
callback = function () {}
}
NotificationsHandler.markAsReadWithKey(user._id, this.key, callback)
},
}
}
function redundantPersonalSubscription(affiliation, user) {
return {
key: `redundant-personal-subscription-${affiliation.institutionId}`,
create(callback) {
if (callback == null) {
callback = function () {}
}
const messageOpts = { institutionName: affiliation.institutionName }
NotificationsHandler.createNotification(
user._id,
this.key,
'notification_personal_subscription_not_required_due_to_affiliation',
messageOpts,
null,
false,
callback
)
},
read(callback) {
if (callback == null) {
callback = function () {}
}
NotificationsHandler.markAsReadWithKey(user._id, this.key, callback)
},
}
}
function projectInvite(invite, project, sendingUser, user) {
return {
key: `project-invite-${invite._id}`,
create(callback) {
if (callback == null) {
callback = function () {}
}
const messageOpts = {
userName: sendingUser.first_name,
projectName: project.name,
projectId: project._id.toString(),
token: invite.token,
}
NotificationsHandler.createNotification(
user._id,
this.key,
'notification_project_invite',
messageOpts,
invite.expires,
callback
)
},
read(callback) {
if (callback == null) {
callback = function () {}
}
NotificationsHandler.markAsReadByKeyOnly(this.key, callback)
},
}
}
function ipMatcherAffiliation(userId) {
return {
create(ip, callback) {
if (callback == null) {
callback = function () {}
}
if (!settings.apis.v1.url) {
// service is not configured
return callback()
}
request(
{
method: 'GET',
url: `${settings.apis.v1.url}/api/v2/users/${userId}/ip_matcher`,
auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass },
body: { ip },
json: true,
timeout: 20 * 1000,
},
function (error, response, body) {
if (error != null) {
return callback(error)
}
if (response.statusCode !== 200) {
return callback()
}
const key = `ip-matched-affiliation-${body.id}`
const portalPath = body.portal_slug
? `/${body.is_university ? 'edu' : 'org'}/${body.portal_slug}`
: undefined
const messageOpts = {
university_name: body.name,
institutionId: body.id,
content: body.enrolment_ad_html,
portalPath,
ssoEnabled: body.sso_enabled,
}
NotificationsHandler.createNotification(
userId,
key,
'notification_ip_matched_affiliation',
messageOpts,
null,
false,
callback
)
}
)
},
read(universityId, callback) {
if (callback == null) {
callback = function () {}
}
const key = `ip-matched-affiliation-${universityId}`
NotificationsHandler.markAsReadWithKey(userId, key, callback)
},
}
}
function tpdsFileLimit(userId) {
return {
key: `tpdsFileLimit-${userId}`,
create(projectName, callback) {
if (callback == null) {
callback = function () {}
}
const messageOpts = {
projectName: projectName,
}
NotificationsHandler.createNotification(
userId,
this.key,
'notification_tpds_file_limit',
messageOpts,
null,
true,
callback
)
},
read(callback) {
if (callback == null) {
callback = function () {}
}
NotificationsHandler.markAsReadByKeyOnly(this.key, callback)
},
}
}
const NotificationsBuilder = {
// Note: notification keys should be url-safe
dropboxUnlinkedDueToLapsedReconfirmation,
dropboxDuplicateProjectNames,
featuresUpgradedByAffiliation,
redundantPersonalSubscription,
projectInvite,
ipMatcherAffiliation,
tpdsFileLimit,
}
NotificationsBuilder.promises = {
dropboxUnlinkedDueToLapsedReconfirmation: function (userId) {
return promisifyAll(dropboxUnlinkedDueToLapsedReconfirmation(userId))
},
redundantPersonalSubscription: function (affiliation, user) {
return promisifyAll(redundantPersonalSubscription(affiliation, user))
},
}
module.exports = NotificationsBuilder
| overleaf/web/app/src/Features/Notifications/NotificationsBuilder.js/0 | {
"file_path": "overleaf/web/app/src/Features/Notifications/NotificationsBuilder.js",
"repo_id": "overleaf",
"token_count": 2857
} | 494 |
/* eslint-disable
max-len,
*/
// 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 ProjectEditorHandler
const _ = require('underscore')
const Path = require('path')
function mergeDeletedDocs(a, b) {
const docIdsInA = new Set(a.map(doc => doc._id.toString()))
return a.concat(b.filter(doc => !docIdsInA.has(doc._id.toString())))
}
module.exports = ProjectEditorHandler = {
trackChangesAvailable: false,
buildProjectModelView(project, members, invites, deletedDocsFromDocstore) {
let owner, ownerFeatures
if (!Array.isArray(project.deletedDocs)) {
project.deletedDocs = []
}
project.deletedDocs.forEach(doc => {
// The frontend does not use this field.
delete doc.deletedAt
})
const result = {
_id: project._id,
name: project.name,
rootDoc_id: project.rootDoc_id,
rootFolder: [this.buildFolderModelView(project.rootFolder[0])],
publicAccesLevel: project.publicAccesLevel,
dropboxEnabled: !!project.existsInDropbox,
compiler: project.compiler,
description: project.description,
spellCheckLanguage: project.spellCheckLanguage,
deletedByExternalDataSource: project.deletedByExternalDataSource || false,
deletedDocs: mergeDeletedDocs(
project.deletedDocs,
deletedDocsFromDocstore
),
members: [],
invites,
tokens: project.tokens,
imageName:
project.imageName != null
? Path.basename(project.imageName)
: undefined,
}
if (result.invites == null) {
result.invites = []
}
result.invites.forEach(invite => {
delete invite.token
})
;({ owner, ownerFeatures, members } = this.buildOwnerAndMembersViews(
members
))
result.owner = owner
result.members = members
result.features = _.defaults(ownerFeatures || {}, {
collaborators: -1, // Infinite
versioning: false,
dropbox: false,
compileTimeout: 60,
compileGroup: 'standard',
templates: false,
references: false,
referencesSearch: false,
mendeley: false,
trackChanges: false,
trackChangesVisible: ProjectEditorHandler.trackChangesAvailable,
})
if (result.features.trackChanges) {
result.trackChangesState = project.track_changes || false
}
// Originally these two feature flags were both signalled by the now-deprecated `references` flag.
// For older users, the presence of the `references` feature flag should still turn on these features.
result.features.referencesSearch =
result.features.referencesSearch || result.features.references
result.features.mendeley =
result.features.mendeley || result.features.references
return result
},
buildOwnerAndMembersViews(members) {
let owner = null
let ownerFeatures = null
const filteredMembers = []
for (const member of Array.from(members || [])) {
if (member.privilegeLevel === 'owner') {
ownerFeatures = member.user.features
owner = this.buildUserModelView(member.user, 'owner')
} else {
filteredMembers.push(
this.buildUserModelView(member.user, member.privilegeLevel)
)
}
}
return {
owner,
ownerFeatures,
members: filteredMembers,
}
},
buildUserModelView(user, privileges) {
return {
_id: user._id,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
privileges,
signUpDate: user.signUpDate,
}
},
buildFolderModelView(folder) {
let file
const fileRefs = _.filter(folder.fileRefs || [], file => file != null)
return {
_id: folder._id,
name: folder.name,
folders: Array.from(folder.folders || []).map(childFolder =>
this.buildFolderModelView(childFolder)
),
fileRefs: (() => {
const result = []
for (file of Array.from(fileRefs)) {
result.push(this.buildFileModelView(file))
}
return result
})(),
docs: Array.from(folder.docs || []).map(doc =>
this.buildDocModelView(doc)
),
}
},
buildFileModelView(file) {
return {
_id: file._id,
name: file.name,
linkedFileData: file.linkedFileData,
created: file.created,
}
},
buildDocModelView(doc) {
return {
_id: doc._id,
name: doc.name,
}
},
}
| overleaf/web/app/src/Features/Project/ProjectEditorHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectEditorHandler.js",
"repo_id": "overleaf",
"token_count": 1864
} | 495 |
const _ = require('underscore')
const { User } = require('../../models/User')
const Settings = require('@overleaf/settings')
let ReferalFeatures
module.exports = ReferalFeatures = {
getBonusFeatures(userId, callback) {
if (callback == null) {
callback = function () {}
}
const query = { _id: userId }
User.findOne(query, { refered_user_count: 1 }, function (error, user) {
if (error) {
return callback(error)
}
if (user == null) {
return callback(new Error(`user not found ${userId} for assignBonus`))
}
if (user.refered_user_count != null && user.refered_user_count > 0) {
const newFeatures = ReferalFeatures._calculateFeatures(user)
callback(null, newFeatures)
} else {
callback(null, {})
}
})
},
_calculateFeatures(user) {
const bonusLevel = ReferalFeatures._getBonusLevel(user)
return (
(Settings.bonus_features != null
? Settings.bonus_features[`${bonusLevel}`]
: undefined) || {}
)
},
_getBonusLevel(user) {
let highestBonusLevel = 0
_.each(_.keys(Settings.bonus_features), function (level) {
const levelIsLessThanUser = level <= user.refered_user_count
const levelIsMoreThanCurrentHighest = level >= highestBonusLevel
if (levelIsLessThanUser && levelIsMoreThanCurrentHighest) {
return (highestBonusLevel = level)
}
})
return highestBonusLevel
},
}
| overleaf/web/app/src/Features/Referal/ReferalFeatures.js/0 | {
"file_path": "overleaf/web/app/src/Features/Referal/ReferalFeatures.js",
"repo_id": "overleaf",
"token_count": 568
} | 496 |
/* 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 extensionsToProxy = [
'.png',
'.xml',
'.jpeg',
'.json',
'.zip',
'.eps',
'.gif',
'.jpg',
]
const _ = require('underscore')
module.exports = {
shouldProxy(url) {
const shouldProxy = _.find(
extensionsToProxy,
extension => url.indexOf(extension) !== -1
)
return shouldProxy
},
}
| overleaf/web/app/src/Features/StaticPages/StaticPageHelpers.js/0 | {
"file_path": "overleaf/web/app/src/Features/StaticPages/StaticPageHelpers.js",
"repo_id": "overleaf",
"token_count": 234
} | 497 |
/**
* If the user changes to a less expensive plan, we shouldn't apply the change immediately.
* This is to avoid unintended/artifical credits on users Recurly accounts.
*/
function shouldPlanChangeAtTermEnd(oldPlan, newPlan) {
return oldPlan.price > newPlan.price
}
module.exports = {
shouldPlanChangeAtTermEnd,
}
| overleaf/web/app/src/Features/Subscription/SubscriptionHelper.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionHelper.js",
"repo_id": "overleaf",
"token_count": 92
} | 498 |
/* eslint-disable
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
module.exports = {
saveTemplateDataInSession(req, res, next) {
if (req.query.templateName) {
req.session.templateData = req.query
}
return next()
},
}
| overleaf/web/app/src/Features/Templates/TemplatesMiddleware.js/0 | {
"file_path": "overleaf/web/app/src/Features/Templates/TemplatesMiddleware.js",
"repo_id": "overleaf",
"token_count": 199
} | 499 |
const Path = require('path')
const fs = require('fs-extra')
const { callbackify } = require('util')
const ArchiveManager = require('./ArchiveManager')
const { Doc } = require('../../models/Doc')
const DocstoreManager = require('../Docstore/DocstoreManager')
const DocumentHelper = require('../Documents/DocumentHelper')
const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
const FileStoreHandler = require('../FileStore/FileStoreHandler')
const FileSystemImportManager = require('./FileSystemImportManager')
const ProjectCreationHandler = require('../Project/ProjectCreationHandler')
const ProjectEntityMongoUpdateHandler = require('../Project/ProjectEntityMongoUpdateHandler')
const ProjectRootDocManager = require('../Project/ProjectRootDocManager')
const ProjectDetailsHandler = require('../Project/ProjectDetailsHandler')
const ProjectDeleter = require('../Project/ProjectDeleter')
const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
const logger = require('logger-sharelatex')
module.exports = {
createProjectFromZipArchive: callbackify(createProjectFromZipArchive),
createProjectFromZipArchiveWithName: callbackify(
createProjectFromZipArchiveWithName
),
promises: {
createProjectFromZipArchive,
createProjectFromZipArchiveWithName,
},
}
async function createProjectFromZipArchive(ownerId, defaultName, zipPath) {
const contentsPath = await _extractZip(zipPath)
const {
path,
content,
} = await ProjectRootDocManager.promises.findRootDocFileFromDirectory(
contentsPath
)
const projectName =
DocumentHelper.getTitleFromTexContent(content || '') || defaultName
const uniqueName = await _generateUniqueName(ownerId, projectName)
const project = await ProjectCreationHandler.promises.createBlankProject(
ownerId,
uniqueName
)
try {
await _initializeProjectWithZipContents(ownerId, project, contentsPath)
if (path) {
await ProjectRootDocManager.promises.setRootDocFromName(project._id, path)
}
} catch (err) {
// no need to wait for the cleanup here
ProjectDeleter.promises
.deleteProject(project._id)
.catch(err =>
logger.error(
{ err, projectId: project._id },
'there was an error cleaning up project after importing a zip failed'
)
)
throw err
}
await fs.remove(contentsPath)
return project
}
async function createProjectFromZipArchiveWithName(
ownerId,
proposedName,
zipPath,
attributes = {}
) {
const contentsPath = await _extractZip(zipPath)
const uniqueName = await _generateUniqueName(ownerId, proposedName)
const project = await ProjectCreationHandler.promises.createBlankProject(
ownerId,
uniqueName,
attributes
)
try {
await _initializeProjectWithZipContents(ownerId, project, contentsPath)
await ProjectRootDocManager.promises.setRootDocAutomatically(project._id)
} catch (err) {
// no need to wait for the cleanup here
ProjectDeleter.promises
.deleteProject(project._id)
.catch(err =>
logger.error(
{ err, projectId: project._id },
'there was an error cleaning up project after importing a zip failed'
)
)
throw err
}
await fs.remove(contentsPath)
return project
}
async function _extractZip(zipPath) {
const destination = Path.join(
Path.dirname(zipPath),
`${Path.basename(zipPath, '.zip')}-${Date.now()}`
)
await ArchiveManager.promises.extractZipArchive(zipPath, destination)
return destination
}
async function _generateUniqueName(ownerId, originalName) {
const fixedName = ProjectDetailsHandler.fixProjectName(originalName)
const uniqueName = await ProjectDetailsHandler.promises.generateUniqueName(
ownerId,
fixedName
)
return uniqueName
}
async function _initializeProjectWithZipContents(
ownerId,
project,
contentsPath
) {
const topLevelDir = await ArchiveManager.promises.findTopLevelDirectory(
contentsPath
)
const importEntries = await FileSystemImportManager.promises.importDir(
topLevelDir
)
const { fileEntries, docEntries } = await _createEntriesFromImports(
project._id,
importEntries
)
const projectVersion = await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure(
project._id,
docEntries,
fileEntries
)
await _notifyDocumentUpdater(project, ownerId, {
newFiles: fileEntries,
newDocs: docEntries,
newProject: { version: projectVersion },
})
await TpdsProjectFlusher.promises.flushProjectToTpds(project._id)
}
async function _createEntriesFromImports(projectId, importEntries) {
const fileEntries = []
const docEntries = []
for (const importEntry of importEntries) {
switch (importEntry.type) {
case 'doc': {
const docEntry = await _createDoc(
projectId,
importEntry.projectPath,
importEntry.lines
)
docEntries.push(docEntry)
break
}
case 'file': {
const fileEntry = await _createFile(
projectId,
importEntry.projectPath,
importEntry.fsPath
)
fileEntries.push(fileEntry)
break
}
default: {
throw new Error(`Invalid import type: ${importEntry.type}`)
}
}
}
return { fileEntries, docEntries }
}
async function _createDoc(projectId, projectPath, docLines) {
const docName = Path.basename(projectPath)
const doc = new Doc({ name: docName })
await DocstoreManager.promises.updateDoc(
projectId.toString(),
doc._id.toString(),
docLines,
0,
{}
)
return { doc, path: projectPath, docLines: docLines.join('\n') }
}
async function _createFile(projectId, projectPath, fsPath) {
const fileName = Path.basename(projectPath)
const { fileRef, url } = await FileStoreHandler.promises.uploadFileFromDisk(
projectId,
{ name: fileName },
fsPath
)
return { file: fileRef, path: projectPath, url }
}
async function _notifyDocumentUpdater(project, userId, changes) {
const projectHistoryId =
project.overleaf && project.overleaf.history && project.overleaf.history.id
await DocumentUpdaterHandler.promises.updateProjectStructure(
project._id,
projectHistoryId,
userId,
changes
)
}
| overleaf/web/app/src/Features/Uploads/ProjectUploadManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Uploads/ProjectUploadManager.js",
"repo_id": "overleaf",
"token_count": 2159
} | 500 |
const Queues = require('../../infrastructure/Queues')
const UserGetter = require('./UserGetter')
const {
promises: InstitutionsAPIPromises,
} = require('../Institutions/InstitutionsAPI')
const AnalyticsManager = require('../Analytics/AnalyticsManager')
const Features = require('../../infrastructure/Features')
const ONE_DAY_MS = 24 * 60 * 60 * 1000
class UserPostRegistrationAnalyticsManager {
constructor() {
this.queue = Queues.getPostRegistrationAnalyticsQueue()
this.queue.process(async job => {
const { userId } = job.data
await postRegistrationAnalytics(userId)
})
}
async schedulePostRegistrationAnalytics(user) {
await this.queue.add({ userId: user._id }, { delay: ONE_DAY_MS })
}
}
async function postRegistrationAnalytics(userId) {
const user = await UserGetter.promises.getUser({ _id: userId }, { email: 1 })
if (!user) {
return
}
await checkAffiliations(userId)
}
async function checkAffiliations(userId) {
const affiliationsData = await InstitutionsAPIPromises.getUserAffiliations(
userId
)
const hasCommonsAccountAffiliation = affiliationsData.some(
affiliationData =>
affiliationData.institution && affiliationData.institution.commonsAccount
)
if (hasCommonsAccountAffiliation) {
await AnalyticsManager.setUserProperty(
userId,
'registered-from-commons-account',
true
)
}
}
class NoopManager {
async schedulePostRegistrationAnalytics() {}
}
module.exports = Features.hasFeature('saas')
? new UserPostRegistrationAnalyticsManager()
: new NoopManager()
| overleaf/web/app/src/Features/User/UserPostRegistrationAnalyticsManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserPostRegistrationAnalyticsManager.js",
"repo_id": "overleaf",
"token_count": 511
} | 501 |
const crypto = require('crypto')
const path = require('path')
module.exports = function ({
reportUri,
reportPercentage,
reportOnly = false,
exclude = [],
percentage,
}) {
return function (req, res, next) {
const originalRender = res.render
res.render = (...args) => {
const view = relativeViewPath(args[0])
// enable the CSP header for a percentage of requests
const belowCutoff = Math.random() * 100 <= percentage
if (belowCutoff && !exclude.includes(view)) {
res.locals.cspEnabled = true
const scriptNonce = crypto.randomBytes(16).toString('base64')
res.locals.scriptNonce = scriptNonce
const directives = [
`script-src 'nonce-${scriptNonce}' 'unsafe-inline' 'strict-dynamic' https: 'report-sample'`,
`object-src 'none'`,
`base-uri 'none'`,
]
// enable the report URI for a percentage of CSP-enabled requests
const belowReportCutoff = Math.random() * 100 <= reportPercentage
if (reportUri && belowReportCutoff) {
directives.push(`report-uri ${reportUri}`)
// NOTE: implement report-to once it's more widely supported
}
const policy = directives.join('; ')
// Note: https://csp-evaluator.withgoogle.com/ is useful for checking the policy
const header = reportOnly
? 'Content-Security-Policy-Report-Only'
: 'Content-Security-Policy'
res.set(header, policy)
}
originalRender.apply(res, args)
}
next()
}
}
const webRoot = path.resolve(__dirname, '..', '..', '..')
// build the view path relative to the web root
function relativeViewPath(view) {
return path.isAbsolute(view)
? path.relative(webRoot, view)
: path.join('app', 'views', view)
}
| overleaf/web/app/src/infrastructure/CSP.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/CSP.js",
"repo_id": "overleaf",
"token_count": 702
} | 502 |
/* 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
*/
let trackOpenSockets
const _ = require('underscore')
const metrics = require('@overleaf/metrics')
;(trackOpenSockets = function () {
metrics.gauge(
'http.open-sockets',
_.size(require('http').globalAgent.sockets.length),
0.5
)
return setTimeout(trackOpenSockets, 1000)
})()
| overleaf/web/app/src/infrastructure/RandomLogging.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/RandomLogging.js",
"repo_id": "overleaf",
"token_count": 205
} | 503 |
const mongoose = require('../infrastructure/Mongoose')
const { UserSchema } = require('./User')
const { Schema } = mongoose
const { ObjectId } = Schema
const DeleterDataSchema = new Schema({
deleterId: { type: ObjectId, ref: 'User' },
deleterIpAddress: { type: String },
deletedAt: { type: Date },
deletedUserId: { type: ObjectId },
deletedUserLastLoggedIn: { type: Date },
deletedUserSignUpDate: { type: Date },
deletedUserLoginCount: { type: Number },
deletedUserReferralId: { type: String },
deletedUserReferredUsers: [{ type: ObjectId, ref: 'User' }],
deletedUserReferredUserCount: { type: Number },
deletedUserOverleafId: { type: Number },
})
const DeletedUserSchema = new Schema(
{
deleterData: DeleterDataSchema,
user: UserSchema,
},
{ collection: 'deletedUsers' }
)
exports.DeletedUser = mongoose.model('DeletedUser', DeletedUserSchema)
exports.DeletedUserSchema = DeletedUserSchema
| overleaf/web/app/src/models/DeletedUser.js/0 | {
"file_path": "overleaf/web/app/src/models/DeletedUser.js",
"repo_id": "overleaf",
"token_count": 316
} | 504 |
const mongoose = require('../infrastructure/Mongoose')
const { TeamInviteSchema } = require('./TeamInvite')
const { Schema } = mongoose
const { ObjectId } = Schema
const SubscriptionSchema = new Schema({
admin_id: {
type: ObjectId,
ref: 'User',
index: { unique: true, dropDups: true },
},
manager_ids: {
type: [ObjectId],
ref: 'User',
required: true,
validate: function (managers) {
// require at least one manager
return !!managers.length
},
},
member_ids: [{ type: ObjectId, ref: 'User' }],
invited_emails: [String],
teamInvites: [TeamInviteSchema],
recurlySubscription_id: String,
teamName: { type: String },
teamNotice: { type: String },
planCode: { type: String },
groupPlan: { type: Boolean, default: false },
membersLimit: { type: Number, default: 0 },
customAccount: Boolean,
overleaf: {
id: {
type: Number,
index: {
unique: true,
partialFilterExpression: { 'overleaf.id': { $exists: true } },
},
},
},
})
// Subscriptions have no v1 data to fetch
SubscriptionSchema.method('fetchV1Data', function (callback) {
callback(null, this)
})
exports.Subscription = mongoose.model('Subscription', SubscriptionSchema)
exports.SubscriptionSchema = SubscriptionSchema
| overleaf/web/app/src/models/Subscription.js/0 | {
"file_path": "overleaf/web/app/src/models/Subscription.js",
"repo_id": "overleaf",
"token_count": 475
} | 505 |
mixin faq_search(headerText, headerClass)
if (typeof(settings.algolia) != "undefined" && typeof(settings.algolia.indexes) != "undefined" && typeof(settings.algolia.indexes.wiki) != "undefined")
if headerText
div(class=headerClass, ng-non-bindable) #{headerText}
.wiki(ng-controller="SearchWikiController")
form.project-search.form-horizontal(role="search")
.form-group.has-feedback.has-feedback-left
.col-sm-12
input.form-control(type='text', ng-model='searchQueryText', ng-keyup='search()', placeholder="Search help library…")
i.fa.fa-search.form-control-feedback-left(aria-hidden="true")
i.fa.fa-times.form-control-feedback(
ng-click="clearSearchText()",
style="cursor: pointer;",
ng-show="searchQueryText.length > 0"
aria-hidden="true"
)
button.sr-only(
type="button"
ng-click="clearSearchText()",
ng-show="searchQueryText.length > 0"
) #{translate('clear_search')}
.row(role="region" aria-label="search results")
.col-md-12(ng-cloak)
span.sr-only(ng-show="searchQueryText.length > 0" aria-live="polite")
span(ng-if="hits_total > config_hits_per_page") Showing first {{hits.length}} results of {{hits_total}} for {{searchQueryText}}
span(ng-if="hits_total <= config_hits_per_page") {{hits.length}} results for {{searchQueryText}}
a(ng-href='{{hit.url}}',ng-repeat='hit in hits').search-result.card.card-thin
span(ng-bind-html='hit.name')
div.search-result-content(ng-show="hit.content != ''", ng-bind-html='hit.content')
.row-spaced-small.search-result.card.card-thin(ng-if="!processingSearch && searchQueryText.length > 1 && hits.length === 0")
p #{translate("no_search_results")}
| overleaf/web/app/views/_mixins/faq_search.pug/0 | {
"file_path": "overleaf/web/app/views/_mixins/faq_search.pug",
"repo_id": "overleaf",
"token_count": 722
} | 506 |
footer.site-footer
.site-footer-content.hidden-print
.row
ul.col-md-9
if Object.keys(settings.i18n.subdomainLang).length > 1
li.dropdown.dropup.subdued(dropdown)
a.dropdown-toggle(
href="#",
dropdown-toggle,
data-toggle="dropdown",
aria-haspopup="true",
aria-expanded="false",
aria-label="Select " + translate('language')
tooltip=translate('language')
)
figure(class="sprite-icon sprite-icon-lang sprite-icon-"+currentLngCode alt=translate(currentLngCode))
ul.dropdown-menu(role="menu")
li.dropdown-header #{translate("language")}
each subdomainDetails, subdomain in settings.i18n.subdomainLang
if !subdomainDetails.hide
li.lngOption
a.menu-indent(href=subdomainDetails.url+currentUrlWithQueryParams)
figure(class="sprite-icon sprite-icon-lang sprite-icon-"+subdomainDetails.lngCode alt=translate(subdomainDetails.lngCode))
| #{translate(subdomainDetails.lngCode)}
//- img(src="/img/flags/24/.png")
each item in nav.left_footer
li
if item.url
a(href=item.url, class=item.class) !{translate(item.text)}
else
| !{item.text}
ul.col-md-3.text-right
each item in nav.right_footer
li(ng-non-bindable)
if item.url
a(href=item.url, class=item.class, aria-label=item.label) !{item.text}
else
| !{item.text}
| overleaf/web/app/views/layout/footer.pug/0 | {
"file_path": "overleaf/web/app/views/layout/footer.pug",
"repo_id": "overleaf",
"token_count": 690
} | 507 |
aside.change-list(
ng-if="!history.isV2"
ng-controller="HistoryListController"
infinite-scroll="loadMore()"
infinite-scroll-disabled="history.loading || history.atEnd"
infinite-scroll-initialize="ui.view == 'history'"
)
.infinite-scroll-inner
ul.list-unstyled(
ng-class="{\
'hover-state': history.hoveringOverListSelectors\
}"
)
li.change(
ng-repeat="update in history.updates"
ng-class="{\
'first-in-day': update.meta.first_in_day,\
'selected': update.inSelection,\
'selected-to': update.selectedTo,\
'selected-from': update.selectedFrom,\
'hover-selected': update.inHoverSelection,\
'hover-selected-to': update.hoverSelectedTo,\
'hover-selected-from': update.hoverSelectedFrom,\
}"
ng-controller="HistoryListItemController"
)
div.day(ng-show="update.meta.first_in_day") {{ update.meta.end_ts | relativeDate }}
div.selectors
div.range
form
input.selector-from(
type="radio"
name="fromVersion"
ng-model="update.selectedFrom"
ng-value="true"
ng-mouseover="mouseOverSelectedFrom()"
ng-mouseout="mouseOutSelectedFrom()"
ng-show="update.afterSelection || update.inSelection"
)
form
input.selector-to(
type="radio"
name="toVersion"
ng-model="update.selectedTo"
ng-value="true"
ng-mouseover="mouseOverSelectedTo()"
ng-mouseout="mouseOutSelectedTo()"
ng-show="update.beforeSelection || update.inSelection"
)
div.description(ng-click="select()")
div.time {{ update.meta.end_ts | formatDate:'h:mm a' }}
div.action.action-edited(ng-if="history.isV2 && update.pathnames.length > 0")
| #{translate("file_action_edited")}
div.docs(ng-repeat="pathname in update.pathnames")
.doc {{ pathname }}
div.docs(ng-repeat="project_op in update.project_ops")
div(ng-if="project_op.rename")
.action #{translate("file_action_renamed")}
.doc {{ project_op.rename.pathname }} → {{ project_op.rename.newPathname }}
div(ng-if="project_op.add")
.action #{translate("file_action_created")}
.doc {{ project_op.add.pathname }}
div(ng-if="project_op.remove")
.action #{translate("file_action_deleted")}
.doc {{ project_op.remove.pathname }}
div.users
div.user(ng-repeat="update_user in update.meta.users")
.color-square(ng-if="update_user != null", ng-style="{'background-color': 'hsl({{ update_user.hue }}, 70%, 50%)'}")
.color-square(ng-if="update_user == null", ng-style="{'background-color': 'hsl(100, 70%, 50%)'}")
.name(ng-if="update_user && update_user.id != user.id" ng-bind="displayName(update_user)")
.name(ng-if="update_user && update_user.id == user.id") You
.name(ng-if="update_user == null") #{translate("anonymous")}
div.user(ng-if="update.meta.users.length == 0")
.color-square(style="background-color: hsl(100, 100%, 50%)")
span #{translate("anonymous")}
.loading(ng-show="history.loading")
i.fa.fa-spin.fa-refresh
| #{translate("loading")}…
| overleaf/web/app/views/project/editor/history/entriesListV1.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/history/entriesListV1.pug",
"repo_id": "overleaf",
"token_count": 1477
} | 508 |
.row.row-spaced
.col-xs-12
.card.card-thin
div.welcome.text-centered(ng-cloak)
h2 #{translate("welcome_to_sl")}
p #{translate("new_to_latex_look_at")}
a(href="/templates") #{translate("templates").toLowerCase()}
| #{translate("or")}
a(href="/learn") #{translate("latex_help_guide")}
.row
.col-md-offset-4.col-md-4
.dropdown.minimal-create-proj-dropdown(dropdown)
a.btn.btn-success.dropdown-toggle(
href="#",
data-toggle="dropdown",
dropdown-toggle
)
| Create First Project
ul.dropdown-menu.minimal-create-proj-dropdown-menu(role="menu")
li
a(
href,
ng-click="openCreateProjectModal()"
) #{translate("blank_project")}
li
a(
href,
ng-click="openCreateProjectModal('example')"
) #{translate("example_project")}
li
a(
href,
ng-click="openUploadProjectModal()"
) #{translate("upload_project")}
!= moduleIncludes("newProjectMenu", locals)
if (templates)
li.divider
li.dropdown-header #{translate("templates")}
each item in templates
li
a.menu-indent(href=item.url) #{translate(item.name)}
| overleaf/web/app/views/project/list/empty-project-list.pug/0 | {
"file_path": "overleaf/web/app/views/project/list/empty-project-list.pug",
"repo_id": "overleaf",
"token_count": 702
} | 509 |
mixin printPlan(plan)
if (!plan.hideFromUsers)
tr(ng-controller="ChangePlanFormController", ng-init="plan="+JSON.stringify(plan))
td
strong(ng-non-bindable) #{plan.name}
td
if (plan.annual)
| {{price}} / #{translate("year")}
else
| {{price}} / #{translate("month")}
td
if (typeof(personalSubscription.planCode) != "undefined" && plan.planCode == personalSubscription.planCode.split("_")[0])
if (personalSubscription.pendingPlan)
form
input(type="hidden", ng-model="plan_code", name="plan_code", value=plan.planCode)
input(type="submit", ng-click="cancelPendingPlanChange()", value=translate("keep_current_plan")).btn.btn-success
else
button.btn.disabled #{translate("your_plan")}
else if (personalSubscription.pendingPlan && typeof(personalSubscription.pendingPlan.planCode) != "undefined" && plan.planCode == personalSubscription.pendingPlan.planCode.split("_")[0])
button.btn.disabled #{translate("your_new_plan")}
else
form
input(type="hidden", ng-model="plan_code", name="plan_code", value=plan.planCode)
input(type="submit", ng-click="changePlan()", value=translate("change_to_this_plan")).btn.btn-success
mixin printPlans(plans)
each plan in plans
+printPlan(plan)
| overleaf/web/app/views/subscriptions/dashboard/_change_plans_mixins.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard/_change_plans_mixins.pug",
"repo_id": "overleaf",
"token_count": 505
} | 510 |
extends ../layout
block content
main.content.content-alt#main-content
.container(ng-controller="AnnualUpgradeController")
.row(ng-cloak)
.col-md-6.col-md-offset-3
.card(ng-init="planName = "+JSON.stringify(planName))
.page-header
h1.text-centered #{translate("move_to_annual_billing")}
div(ng-hide="upgradeComplete")
.row
div.col-md-12 !{translate("change_to_annual_billing_and_save", {percentage:'20%', yearlySaving:'${{yearlySaving}}'}, ['strong', 'strong'])}
.row
.row
div.col-md-12
center
button.btn.btn-success(ng-click="completeAnnualUpgrade()", ng-disabled="inflight")
span(ng-show="inflight") #{translate("processing")}
span(ng-hide="inflight") #{translate("move_to_annual_billing")} now
div(ng-show="upgradeComplete")
h3 #{translate("annual_billing_enabled")}, #{translate("thank_you")}.
| overleaf/web/app/views/subscriptions/upgradeToAnnual.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/upgradeToAnnual.pug",
"repo_id": "overleaf",
"token_count": 431
} | 511 |
mixin providerList()
ul.list-like-table
li(ng-repeat="(key, provider) in providers" ng-if="!provider.hideWhenNotLinked || (provider.hideWhenNotLinked && thirdPartyIds[key])")
.row
.col-xs-12.col-sm-8.col-md-10
h4 {{provider.name}}
p.small(ng-bind-html="provider.description")
.col-xs-2.col-sm-4.col-md-2.text-right
//- Unlink
button.btn.btn-default(
ng-click="unlink(key)"
ng-disabled="providers[key].ui.isProcessing"
ng-if="thirdPartyIds[key]"
)
span(ng-if="!providers[key].ui.isProcessing") #{translate("unlink")}
span(ng-if="providers[key].ui.isProcessing") #{translate("processing")}
//- Link
a.btn.btn-primary.text-capitalize(
ng-href="{{provider.linkPath}}?intent=link"
ng-if="!thirdPartyIds[key] && !provider.hideWhenNotLinked"
) #{translate("link")}
//- unlink error
.row(
ng-if="providers[key].ui.hasError"
)
.col-sm-12
//- to do: fix CSS so that we don't need inline styling
.alert.alert-danger(
ng-if="providers[key].ui.hasError"
style="display: block; margin-bottom: 10px;"
)
i.fa.fa-fw.fa-exclamation-triangle(aria-hidden="true")
| {{providers[key].ui.errorMessage}}
.row(
ng-controller="UserOauthController"
ng-cloak
)
.col-xs-12
h3.text-capitalize#linked-accounts #{translate("linked_accounts")}
p.small #{translate("linked_accounts_explained", {appName:'{{settings.appName}}'})}
+providerList()
| overleaf/web/app/views/user/settings/user-oauth.pug/0 | {
"file_path": "overleaf/web/app/views/user/settings/user-oauth.pug",
"repo_id": "overleaf",
"token_count": 686
} | 512 |
import _ from 'lodash'
/* eslint-disable
camelcase,
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
*/
// For sending event data to metabase and google analytics
// ---
// by default,
// event not sent to MB.
// for MB, add event-tracking-mb='true'
// by default, event sent to MB via sendMB
// event not sent to GA.
// for GA, add event-tracking-ga attribute, where the value is the GA category
// Either GA or MB can use the attribute event-tracking-send-once='true' to
// send event just once
// MB will use the key and GA will use the action to determine if the event
// has been sent
// event-tracking-trigger attribute is required to send event
/* eslint-disable
camelcase,
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
*/
// For sending event data to metabase and google analytics
// ---
// by default,
// event not sent to MB.
// for MB, add event-tracking-mb='true'
// by default, event sent to MB via sendMB
// event not sent to GA.
// for GA, add event-tracking-ga attribute, where the value is the GA category
// Either GA or MB can use the attribute event-tracking-send-once='true' to
// send event just once
// MB will use the key and GA will use the action to determine if the event
// has been sent
// event-tracking-trigger attribute is required to send event
import App from '../base'
const isInViewport = function (element) {
const elTop = element.offset().top
const elBtm = elTop + element.outerHeight()
const viewportTop = $(window).scrollTop()
const viewportBtm = viewportTop + $(window).height()
return elBtm > viewportTop && elTop < viewportBtm
}
export default App.directive('eventTracking', eventTracking => ({
scope: {
eventTracking: '@',
eventSegmentation: '=?',
},
link(scope, element, attrs) {
const sendGA = attrs.eventTrackingGa || false
const sendMB = attrs.eventTrackingMb || false
const sendMBFunction = attrs.eventTrackingSendOnce ? 'sendMBOnce' : 'sendMB'
const sendGAFunction = attrs.eventTrackingSendOnce ? 'sendGAOnce' : 'send'
const segmentation = scope.eventSegmentation || {}
segmentation.page = window.location.pathname
const sendEvent = function (scrollEvent) {
/*
@param {boolean} scrollEvent Use to unbind scroll event
*/
if (sendMB) {
eventTracking[sendMBFunction](scope.eventTracking, segmentation)
}
if (sendGA) {
eventTracking[sendGAFunction](
attrs.eventTrackingGa,
attrs.eventTrackingAction || scope.eventTracking,
attrs.eventTrackingLabel || ''
)
}
if (scrollEvent) {
return $(window).unbind('resize scroll')
}
}
if (attrs.eventTrackingTrigger === 'load') {
return sendEvent()
} else if (attrs.eventTrackingTrigger === 'click') {
return element.on('click', e => sendEvent())
} else if (attrs.eventTrackingTrigger === 'hover') {
let timer = null
let timeoutAmt = 500
if (attrs.eventHoverAmt) {
timeoutAmt = parseInt(attrs.eventHoverAmt, 10)
}
return element
.on('mouseenter', function () {
timer = setTimeout(() => sendEvent(), timeoutAmt)
})
.on('mouseleave', () => clearTimeout(timer))
} else if (
attrs.eventTrackingTrigger === 'scroll' &&
!eventTracking.eventInCache(scope.eventTracking)
) {
$(window).on(
'resize scroll',
_.throttle(() => {
if (isInViewport(element)) {
sendEvent(true)
}
}, 500)
)
}
},
}))
| overleaf/web/frontend/js/directives/eventTracking.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/eventTracking.js",
"repo_id": "overleaf",
"token_count": 1515
} | 513 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
function MessageInput({ resetUnreadMessages, sendMessage }) {
const { t } = useTranslation()
function handleKeyDown(event) {
if (event.key === 'Enter') {
event.preventDefault()
sendMessage(event.target.value)
event.target.value = '' // clears the textarea content
}
}
return (
<div className="new-message">
<label htmlFor="chat-input" className="sr-only">
{t('your_message')}
</label>
<textarea
id="chat-input"
placeholder={`${t('your_message')}…`}
onKeyDown={handleKeyDown}
onClick={resetUnreadMessages}
/>
</div>
)
}
MessageInput.propTypes = {
resetUnreadMessages: PropTypes.func.isRequired,
sendMessage: PropTypes.func.isRequired,
}
export default MessageInput
| overleaf/web/frontend/js/features/chat/components/message-input.js/0 | {
"file_path": "overleaf/web/frontend/js/features/chat/components/message-input.js",
"repo_id": "overleaf",
"token_count": 335
} | 514 |
import React from 'react'
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import { Dropdown, MenuItem, OverlayTrigger, Tooltip } from 'react-bootstrap'
import Icon from '../../../shared/components/icon'
import { getHueForUserId } from '../../../shared/utils/colors'
import ControlledDropdown from '../../../shared/components/controlled-dropdown'
function OnlineUsersWidget({ onlineUsers, goToUser }) {
const { t } = useTranslation()
const shouldDisplayDropdown = onlineUsers.length >= 4
if (shouldDisplayDropdown) {
return (
<ControlledDropdown id="online-users" className="online-users" pullRight>
<DropDownToggleButton
bsRole="toggle"
onlineUserCount={onlineUsers.length}
/>
<Dropdown.Menu>
<MenuItem header>{t('connected_users')}</MenuItem>
{onlineUsers.map((user, index) => (
<MenuItem
as="button"
key={`${user.user_id}_${index}`}
eventKey={user}
onSelect={goToUser}
>
<UserIcon user={user} onClick={goToUser} showName />
</MenuItem>
))}
</Dropdown.Menu>
</ControlledDropdown>
)
} else {
return (
<div className="online-users">
{onlineUsers.map((user, index) => (
<OverlayTrigger
key={`${user.user_id}_${index}`}
placement="bottom"
trigger={['hover', 'focus']}
overlay={<Tooltip id="tooltip-online-user">{user.name}</Tooltip>}
>
<span>
{/* OverlayTrigger won't fire unless UserIcon is wrapped in a span */}
<UserIcon user={user} onClick={goToUser} />
</span>
</OverlayTrigger>
))}
</div>
)
}
}
OnlineUsersWidget.propTypes = {
onlineUsers: PropTypes.arrayOf(
PropTypes.shape({
user_id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
})
).isRequired,
goToUser: PropTypes.func.isRequired,
}
function UserIcon({ user, showName, onClick }) {
const backgroundColor = `hsl(${getHueForUserId(user.user_id)}, 70%, 50%)`
function handleOnClick() {
onClick(user)
}
return (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<span onClick={handleOnClick}>
<span className="online-user" style={{ backgroundColor }}>
{user.name.slice(0, 1)}
</span>
{showName && user.name}
</span>
)
}
UserIcon.propTypes = {
user: PropTypes.shape({
user_id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
}),
showName: PropTypes.bool,
onClick: PropTypes.func.isRequired,
}
const DropDownToggleButton = React.forwardRef((props, ref) => {
const { t } = useTranslation()
return (
<OverlayTrigger
placement="left"
overlay={
<Tooltip id="tooltip-connected-users">{t('connected_users')}</Tooltip>
}
>
<button
className="btn online-user online-user-multi"
onClick={props.onClick} // required by Bootstrap Dropdown to trigger an opening
>
<strong>{props.onlineUserCount}</strong>
<Icon type="users" modifier="fw" />
</button>
</OverlayTrigger>
)
})
DropDownToggleButton.displayName = 'DropDownToggleButton'
DropDownToggleButton.propTypes = {
onlineUserCount: PropTypes.number.isRequired,
onClick: PropTypes.func,
}
export default OnlineUsersWidget
| overleaf/web/frontend/js/features/editor-navigation-toolbar/components/online-users-widget.js/0 | {
"file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/online-users-widget.js",
"repo_id": "overleaf",
"token_count": 1496
} | 515 |
import { useState, useCallback, useEffect, useMemo } from 'react'
import { Button, ControlLabel, FormControl, FormGroup } from 'react-bootstrap'
import Icon from '../../../../../shared/components/icon'
import FileTreeCreateNameInput from '../file-tree-create-name-input'
import { useTranslation } from 'react-i18next'
import PropTypes from 'prop-types'
import { useUserProjects } from '../../../hooks/use-user-projects'
import { useProjectEntities } from '../../../hooks/use-project-entities'
import { useProjectOutputFiles } from '../../../hooks/use-project-output-files'
import { useFileTreeActionable } from '../../../contexts/file-tree-actionable'
import { useFileTreeCreateName } from '../../../contexts/file-tree-create-name'
import { useFileTreeCreateForm } from '../../../contexts/file-tree-create-form'
import { useFileTreeMainContext } from '../../../contexts/file-tree-main'
import ErrorMessage from '../error-message'
export default function FileTreeImportFromProject() {
const { t } = useTranslation()
const {
hasLinkedProjectFileFeature,
hasLinkedProjectOutputFileFeature,
} = window.ExposedSettings
const canSwitchOutputFilesMode =
hasLinkedProjectFileFeature && hasLinkedProjectOutputFileFeature
const { name, setName, validName } = useFileTreeCreateName()
const { setValid } = useFileTreeCreateForm()
const { projectId } = useFileTreeMainContext()
const { error, finishCreatingLinkedFile } = useFileTreeActionable()
const [selectedProject, setSelectedProject] = useState()
const [selectedProjectEntity, setSelectedProjectEntity] = useState()
const [selectedProjectOutputFile, setSelectedProjectOutputFile] = useState()
const [isOutputFilesMode, setOutputFilesMode] = useState(
// default to project file mode, unless the feature is not enabled
!hasLinkedProjectFileFeature
)
// use the basename of a path as the file name
const setNameFromPath = useCallback(
path => {
const filename = path.split('/').pop()
if (filename) {
setName(filename)
}
},
[setName]
)
// update the name when an output file is selected
useEffect(() => {
if (selectedProjectOutputFile) {
if (
selectedProjectOutputFile.path === 'output.pdf' &&
selectedProject.name
) {
// if the output PDF is selected, use the project's name as the filename
setName(`${selectedProject.name}.pdf`)
} else {
setNameFromPath(selectedProjectOutputFile.path)
}
}
}, [selectedProject, selectedProjectOutputFile, setName, setNameFromPath])
// update the name when an entity is selected
useEffect(() => {
if (selectedProjectEntity) {
setNameFromPath(selectedProjectEntity.path)
}
}, [selectedProjectEntity, setNameFromPath])
// form validation: name is valid and entity or output file is selected
useEffect(() => {
const hasSelectedEntity = Boolean(
isOutputFilesMode ? selectedProjectOutputFile : selectedProjectEntity
)
setValid(validName && hasSelectedEntity)
}, [
setValid,
validName,
isOutputFilesMode,
selectedProjectEntity,
selectedProjectOutputFile,
])
// form submission: create a linked file with this name, from this entity or output file
const handleSubmit = event => {
event.preventDefault()
if (isOutputFilesMode) {
finishCreatingLinkedFile({
name,
provider: 'project_output_file',
data: {
source_project_id: selectedProject._id,
source_output_file_path: selectedProjectOutputFile.path,
build_id: selectedProjectOutputFile.build,
},
})
} else {
finishCreatingLinkedFile({
name,
provider: 'project_file',
data: {
source_project_id: selectedProject._id,
source_entity_path: selectedProjectEntity.path,
},
})
}
}
return (
<form className="form-controls" id="create-file" onSubmit={handleSubmit}>
<SelectProject
projectId={projectId}
selectedProject={selectedProject}
setSelectedProject={setSelectedProject}
/>
{isOutputFilesMode ? (
<SelectProjectOutputFile
selectedProjectId={selectedProject?._id}
selectedProjectOutputFile={selectedProjectOutputFile}
setSelectedProjectOutputFile={setSelectedProjectOutputFile}
/>
) : (
<SelectProjectEntity
selectedProjectId={selectedProject?._id}
selectedProjectEntity={selectedProjectEntity}
setSelectedProjectEntity={setSelectedProjectEntity}
/>
)}
{canSwitchOutputFilesMode && (
<div className="toggle-file-type-button">
or
<Button
bsStyle="link"
type="button"
onClick={() => setOutputFilesMode(value => !value)}
>
<span>
{isOutputFilesMode
? t('select_from_source_files')
: t('select_from_output_files')}
</span>
</Button>
</div>
)}
<FileTreeCreateNameInput
label={t('file_name_in_this_project')}
classes={{
formGroup: 'form-controls row-spaced-small',
}}
placeholder="example.tex"
error={error}
/>
{error && <ErrorMessage error={error} />}
</form>
)
}
function SelectProject({ projectId, selectedProject, setSelectedProject }) {
const { t } = useTranslation()
const { data, error, loading } = useUserProjects()
const filteredData = useMemo(() => {
if (!data) {
return null
}
return data.filter(item => item._id !== projectId)
}, [data, projectId])
if (error) {
return <ErrorMessage error={error} />
}
return (
<FormGroup className="form-controls" controlId="project-select">
<ControlLabel>{t('select_a_project')}</ControlLabel>
{loading && (
<span>
<Icon type="spinner" spin />
</span>
)}
<FormControl
componentClass="select"
disabled={!data}
value={selectedProject ? selectedProject._id : ''}
onChange={event => {
const projectId = event.target.value
const project = data.find(item => item._id === projectId)
setSelectedProject(project)
}}
>
<option disabled value="">
- {t('please_select_a_project')}
</option>
{filteredData &&
filteredData.map(project => (
<option key={project._id} value={project._id}>
{project.name}
</option>
))}
</FormControl>
{filteredData && !filteredData.length && (
<small>{t('no_other_projects_found')}</small>
)}
</FormGroup>
)
}
SelectProject.propTypes = {
projectId: PropTypes.string.isRequired,
selectedProject: PropTypes.object,
setSelectedProject: PropTypes.func.isRequired,
}
function SelectProjectOutputFile({
selectedProjectId,
selectedProjectOutputFile,
setSelectedProjectOutputFile,
}) {
const { t } = useTranslation()
const { data, error, loading } = useProjectOutputFiles(selectedProjectId)
if (error) {
return <ErrorMessage error={error} />
}
return (
<FormGroup
className="form-controls row-spaced-small"
controlId="project-output-file-select"
>
<ControlLabel>{t('select_an_output_file')}</ControlLabel>
{loading && (
<span>
<Icon type="spinner" spin />
</span>
)}
<FormControl
componentClass="select"
disabled={!data}
value={selectedProjectOutputFile?.path || ''}
onChange={event => {
const path = event.target.value
const file = data.find(item => item.path === path)
setSelectedProjectOutputFile(file)
}}
>
<option disabled value="">
- {t('please_select_an_output_file')}
</option>
{data &&
data.map(file => (
<option key={file.path} value={file.path}>
{file.path}
</option>
))}
</FormControl>
</FormGroup>
)
}
SelectProjectOutputFile.propTypes = {
selectedProjectId: PropTypes.string,
selectedProjectOutputFile: PropTypes.object,
setSelectedProjectOutputFile: PropTypes.func.isRequired,
}
function SelectProjectEntity({
selectedProjectId,
selectedProjectEntity,
setSelectedProjectEntity,
}) {
const { t } = useTranslation()
const { data, error, loading } = useProjectEntities(selectedProjectId)
if (error) {
return <ErrorMessage error={error} />
}
return (
<FormGroup
className="form-controls row-spaced-small"
controlId="project-entity-select"
>
<ControlLabel>{t('select_a_file')}</ControlLabel>
{loading && (
<span>
<Icon type="spinner" spin />
</span>
)}
<FormControl
componentClass="select"
disabled={!data}
value={selectedProjectEntity?.path || ''}
onChange={event => {
const path = event.target.value
const entity = data.find(item => item.path === path)
setSelectedProjectEntity(entity)
}}
>
<option disabled value="">
- {t('please_select_a_file')}
</option>
{data &&
data.map(entity => (
<option key={entity.path} value={entity.path}>
{entity.path.slice(1)}
</option>
))}
</FormControl>
</FormGroup>
)
}
SelectProjectEntity.propTypes = {
selectedProjectId: PropTypes.string,
selectedProjectEntity: PropTypes.object,
setSelectedProjectEntity: PropTypes.func.isRequired,
}
| overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-project.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-project.js",
"repo_id": "overleaf",
"token_count": 3900
} | 516 |
import { useState } from 'react'
import PropTypes from 'prop-types'
import { Button, Modal } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import { useRefWithAutoFocus } from '../../../../shared/hooks/use-ref-with-auto-focus'
import AccessibleModal from '../../../../shared/components/accessible-modal'
import { useFileTreeActionable } from '../../contexts/file-tree-actionable'
import { DuplicateFilenameError } from '../../errors'
import { isCleanFilename } from '../../util/safe-path'
function FileTreeModalCreateFolder() {
const { t } = useTranslation()
const [name, setName] = useState('')
const [validName, setValidName] = useState(true)
const {
isCreatingFolder,
inFlight,
finishCreatingFolder,
cancel,
error,
} = useFileTreeActionable()
if (!isCreatingFolder) return null // the modal will not be rendered; return early
function handleHide() {
cancel()
}
function handleCreateFolder() {
finishCreatingFolder(name)
}
function errorMessage() {
switch (error.constructor) {
case DuplicateFilenameError:
return t('file_already_exists')
default:
return t('generic_something_went_wrong')
}
}
return (
<AccessibleModal show onHide={handleHide}>
<Modal.Header>
<Modal.Title>{t('new_folder')}</Modal.Title>
</Modal.Header>
<Modal.Body>
<InputName
name={name}
setName={setName}
validName={validName}
setValidName={setValidName}
handleCreateFolder={handleCreateFolder}
/>
{!validName ? (
<div
role="alert"
aria-label={t('files_cannot_include_invalid_characters')}
className="alert alert-danger file-tree-modal-alert"
>
{t('files_cannot_include_invalid_characters')}
</div>
) : null}
{error ? (
<div
role="alert"
aria-label={errorMessage()}
className="alert alert-danger file-tree-modal-alert"
>
{errorMessage()}
</div>
) : null}
</Modal.Body>
<Modal.Footer>
{inFlight ? (
<Button bsStyle="primary" disabled>
{t('creating')}…
</Button>
) : (
<>
<Button onClick={handleHide}>{t('cancel')}</Button>
<Button
bsStyle="primary"
onClick={handleCreateFolder}
disabled={!validName}
>
{t('create')}
</Button>
</>
)}
</Modal.Footer>
</AccessibleModal>
)
}
function InputName({
name,
setName,
validName,
setValidName,
handleCreateFolder,
}) {
const { autoFocusedRef } = useRefWithAutoFocus()
function handleFocus(ev) {
ev.target.setSelectionRange(0, -1)
}
function handleChange(ev) {
setValidName(isCleanFilename(ev.target.value.trim()))
setName(ev.target.value)
}
function handleKeyDown(ev) {
if (ev.key === 'Enter' && validName) {
handleCreateFolder()
}
}
return (
<input
ref={autoFocusedRef}
className="form-control"
type="text"
value={name}
onKeyDown={handleKeyDown}
onChange={handleChange}
onFocus={handleFocus}
/>
)
}
InputName.propTypes = {
name: PropTypes.string.isRequired,
setName: PropTypes.func.isRequired,
validName: PropTypes.bool.isRequired,
setValidName: PropTypes.func.isRequired,
handleCreateFolder: PropTypes.func.isRequired,
}
export default FileTreeModalCreateFolder
| overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-folder.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-folder.js",
"repo_id": "overleaf",
"token_count": 1585
} | 517 |
import { postJSON } from '../../../infrastructure/fetch-json'
export const refreshProjectMetadata = (projectId, entityId) =>
postJSON(`/project/${projectId}/doc/${entityId}/metadata`)
| overleaf/web/frontend/js/features/file-tree/util/api.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/util/api.js",
"repo_id": "overleaf",
"token_count": 60
} | 518 |
import PropTypes from 'prop-types'
import classNames from 'classnames'
import OutlineItem from './outline-item'
function OutlineList({ outline, jumpToLine, isRoot, highlightedLine }) {
const listClasses = classNames('outline-item-list', {
'outline-item-list-root': isRoot,
})
return (
<ul className={listClasses} role={isRoot ? 'tree' : 'group'}>
{outline.map((outlineItem, idx) => {
return (
<OutlineItem
key={`${outlineItem.level}-${idx}`}
outlineItem={outlineItem}
jumpToLine={jumpToLine}
highlightedLine={highlightedLine}
/>
)
})}
</ul>
)
}
OutlineList.propTypes = {
outline: PropTypes.array.isRequired,
jumpToLine: PropTypes.func.isRequired,
isRoot: PropTypes.bool,
highlightedLine: PropTypes.number,
}
export default OutlineList
| overleaf/web/frontend/js/features/outline/components/outline-list.js/0 | {
"file_path": "overleaf/web/frontend/js/features/outline/components/outline-list.js",
"repo_id": "overleaf",
"token_count": 359
} | 519 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import PreviewLogsPaneEntry from './preview-logs-pane-entry'
function PreviewValidationIssue({ name, details }) {
const { t } = useTranslation()
let validationTitle
let validationContent
if (name === 'sizeCheck') {
validationTitle = t('project_too_large')
validationContent = (
<>
<div>{t('project_too_large_please_reduce')}</div>
<ul className="list-no-margin-bottom">
{details.resources.map((resource, index) => (
<li key={index}>
{resource.path} — {resource.kbSize}
kb
</li>
))}
</ul>
</>
)
} else if (name === 'conflictedPaths') {
validationTitle = t('conflicting_paths_found')
validationContent = (
<>
<div>{t('following_paths_conflict')}</div>
<ul className="list-no-margin-bottom">
{details.map((detail, index) => (
<li key={index}>/{detail.path}</li>
))}
</ul>
</>
)
} else if (name === 'mainFile') {
validationTitle = t('main_file_not_found')
validationContent = <>{t('please_set_main_file')}</>
}
return validationTitle ? (
<PreviewLogsPaneEntry
headerTitle={validationTitle}
formattedContent={validationContent}
entryAriaLabel={t('validation_issue_entry_description')}
level="error"
/>
) : null
}
PreviewValidationIssue.propTypes = {
name: PropTypes.string.isRequired,
details: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array,
PropTypes.bool,
]),
}
export default PreviewValidationIssue
| overleaf/web/frontend/js/features/preview/components/preview-validation-issue.js/0 | {
"file_path": "overleaf/web/frontend/js/features/preview/components/preview-validation-issue.js",
"repo_id": "overleaf",
"token_count": 710
} | 520 |
import App from '../../../base'
import { react2angular } from 'react2angular'
import ShareProjectModal from '../components/share-project-modal'
import { rootContext } from '../../../shared/context/root-context'
import { listProjectInvites, listProjectMembers } from '../utils/api'
App.component(
'shareProjectModal',
react2angular(
rootContext.use(ShareProjectModal),
Object.keys(ShareProjectModal.propTypes)
)
)
export default App.controller(
'ReactShareProjectModalController',
function ($scope, eventTracking, ide) {
$scope.isAdmin = false
$scope.show = false
$scope.handleHide = () => {
$scope.$applyAsync(() => {
$scope.show = false
})
}
$scope.openShareProjectModal = isAdmin => {
eventTracking.sendMBOnce('ide-open-share-modal-once')
$scope.$applyAsync(() => {
$scope.isAdmin = isAdmin
$scope.show = true
})
}
/* tokens */
ide.socket.on('project:tokens:changed', data => {
if (data.tokens != null) {
$scope.$applyAsync(() => {
$scope.project.tokens = data.tokens
})
}
})
ide.socket.on('project:membership:changed', data => {
if (data.members) {
listProjectMembers($scope.project)
.then(({ members }) => {
if (members) {
$scope.$applyAsync(() => {
$scope.project.members = members
})
}
})
.catch(() => {
console.error('Error fetching members for project')
})
}
if (data.invites) {
listProjectInvites($scope.project)
.then(({ invites }) => {
if (invites) {
$scope.$applyAsync(() => {
$scope.project.invites = invites
})
}
})
.catch(() => {
console.error('Error fetching invites for project')
})
}
})
}
)
| overleaf/web/frontend/js/features/share-project-modal/controllers/react-share-project-modal-controller.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/controllers/react-share-project-modal-controller.js",
"repo_id": "overleaf",
"token_count": 897
} | 521 |
import moment from 'moment'
moment.updateLocale('en', {
calendar: {
lastDay: '[Yesterday]',
sameDay: '[Today]',
nextDay: '[Tomorrow]',
lastWeek: 'ddd, Do MMM YY',
nextWeek: 'ddd, Do MMM YY',
sameElse: 'ddd, Do MMM YY',
},
})
export function formatTime(date) {
return moment(date).format('h:mm a')
}
export function relativeDate(date) {
return moment(date).calendar()
}
| overleaf/web/frontend/js/features/utils/format-date.js/0 | {
"file_path": "overleaf/web/frontend/js/features/utils/format-date.js",
"repo_id": "overleaf",
"token_count": 162
} | 522 |
// Angular
import './controllers/CloneProjectController'
import './controllers/CloneProjectModalController'
// React
import '../../features/clone-project-modal/controllers/left-menu-clone-project-modal-controller'
| overleaf/web/frontend/js/ide/clone/index.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/clone/index.js",
"repo_id": "overleaf",
"token_count": 63
} | 523 |
import _ from 'lodash'
/* eslint-disable
camelcase,
max-len
*/
import App from '../../../base'
import UndoManager from './aceEditor/undo/UndoManager'
import AutoCompleteManager from './aceEditor/auto-complete/AutoCompleteManager'
import SpellCheckManager from './aceEditor/spell-check/SpellCheckManager'
import SpellCheckAdapter from './aceEditor/spell-check/SpellCheckAdapter'
import HighlightsManager from './aceEditor/highlights/HighlightsManager'
import CursorPositionManager from './aceEditor/cursor-position/CursorPositionManager'
import CursorPositionAdapter from './aceEditor/cursor-position/CursorPositionAdapter'
import TrackChangesManager from './aceEditor/track-changes/TrackChangesManager'
import TrackChangesAdapter from './aceEditor/track-changes/TrackChangesAdapter'
import MetadataManager from './aceEditor/metadata/MetadataManager'
import 'ace/ace'
import 'ace/ext-searchbox'
import 'ace/ext-modelist'
import 'ace/keybinding-vim'
import '../../metadata/services/metadata'
import '../../graphics/services/graphics'
import '../../preamble/services/preamble'
import '../../files/services/files'
let syntaxValidationEnabled
const { EditSession } = ace.require('ace/edit_session')
const ModeList = ace.require('ace/ext/modelist')
const { Vim } = ace.require('ace/keyboard/vim')
const SearchBox = ace.require('ace/ext/searchbox')
// Set the base path that ace will fetch modes/snippets/workers from
if (window.aceBasePath !== '') {
syntaxValidationEnabled = true
ace.config.set('basePath', `${window.aceBasePath}`)
} else {
syntaxValidationEnabled = false
}
// By default, don't use workers - enable them per-session as required
ace.config.setDefaultValue('session', 'useWorker', false)
// Ace loads its script itself, so we need to hook in to be able to clear
// the cache.
if (ace.config._moduleUrl == null) {
ace.config._moduleUrl = ace.config.moduleUrl
ace.config.moduleUrl = function (...args) {
const url = ace.config._moduleUrl(...Array.from(args || []))
return url
}
}
App.directive(
'aceEditor',
function (
ide,
$timeout,
$compile,
$rootScope,
eventTracking,
localStorage,
$cacheFactory,
metadata,
graphics,
preamble,
files,
$http,
$q,
$window
) {
monkeyPatchSearch($rootScope, $compile)
return {
scope: {
theme: '=',
showPrintMargin: '=',
keybindings: '=',
fontSize: '=',
autoComplete: '=',
autoPairDelimiters: '=',
sharejsDoc: '=',
spellCheck: '=',
spellCheckLanguage: '=',
highlights: '=',
text: '=',
readOnly: '=',
annotations: '=',
navigateHighlights: '=',
fileName: '=',
onCtrlEnter: '=', // Compile
onCtrlJ: '=', // Toggle the review panel
onCtrlShiftC: '=', // Add a new comment
onCtrlShiftA: '=', // Toggle track-changes on/off
onSave: '=', // Cmd/Ctrl-S or :w in Vim
syntaxValidation: '=',
reviewPanel: '=',
eventsBridge: '=',
trackChanges: '=',
docId: '=',
rendererData: '=',
lineHeight: '=',
fontFamily: '=',
},
link(scope, element, attrs) {
// Don't freak out if we're already in an apply callback
let spellCheckManager
scope.$originalApply = scope.$apply
scope.$apply = function (fn) {
if (fn == null) {
fn = function () {}
}
const phase = this.$root.$$phase
if (phase === '$apply' || phase === '$digest') {
return fn()
} else {
return this.$originalApply(fn)
}
}
const editor = ace.edit(element.find('.ace-editor-body')[0])
editor.$blockScrolling = Infinity
// Besides the main editor, other elements will re-use this directive
// for displaying read-only content -- e.g. the history panes.
const editorAcceptsChanges = attrs.aceEditor === 'editor'
if (editorAcceptsChanges) {
// end-to-end check for edits -> acks, globally on any doc
// This may catch a missing attached ShareJsDoc that in turn bails out
// on missing acks.
ide.globalEditorWatchdogManager.attachToEditor('Ace', editor)
}
// auto-insertion of braces, brackets, dollars
editor.setOption('behavioursEnabled', scope.autoPairDelimiters || false)
editor.setOption('wrapBehavioursEnabled', false)
ide.$scope.$on('editor:replace-selection', (event, text) => {
editor.focus()
const document = editor.session.getDocument()
const ranges = editor.selection.getAllRanges()
for (const range of ranges) {
document.replace(range, text)
}
})
ide.$scope.$on('symbol-palette-toggled', (event, isToggled) => {
if (!isToggled) {
editor.focus()
}
})
scope.$watch('autoPairDelimiters', autoPairDelimiters => {
if (autoPairDelimiters) {
return editor.setOption('behavioursEnabled', true)
} else {
return editor.setOption('behavioursEnabled', false)
}
})
if (!window._debug_editors) {
window._debug_editors = []
}
window._debug_editors.push(editor)
scope.name = attrs.aceEditor
if (scope.spellCheck) {
// only enable spellcheck when explicitly required
spellCheckManager = new SpellCheckManager(
scope,
$cacheFactory,
$http,
$q,
new SpellCheckAdapter(editor)
)
}
/* eslint-disable no-unused-vars */
const undoManager = new UndoManager(editor)
const highlightsManager = new HighlightsManager(scope, editor, element)
const cursorPositionManager = new CursorPositionManager(
scope,
new CursorPositionAdapter(editor),
localStorage
)
const trackChangesManager = new TrackChangesManager(
scope,
editor,
element,
new TrackChangesAdapter(editor)
)
const metadataManager = new MetadataManager(
scope,
editor,
element,
metadata
)
const autoCompleteManager = new AutoCompleteManager(
scope,
editor,
element,
metadataManager,
graphics,
preamble,
files
)
// prevent user entering null and non-BMP unicode characters in Ace
const BAD_CHARS_REGEXP = /[\0\uD800-\uDFFF]/g
const BAD_CHARS_REPLACEMENT_CHAR = '\uFFFD'
// the 'exec' event fires for ace functions before they are executed.
// you can modify the input or reject the event with e.preventDefault()
editor.commands.on('exec', function (e) {
// replace bad characters in paste content
if (e.command && e.command.name === 'paste') {
BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
if (e.args && BAD_CHARS_REGEXP.test(e.args.text)) {
e.args.text = e.args.text.replace(
BAD_CHARS_REGEXP,
BAD_CHARS_REPLACEMENT_CHAR
)
}
}
// replace bad characters in keyboard input
if (e.command && e.command.name === 'insertstring') {
BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
if (e.args && BAD_CHARS_REGEXP.test(e.args)) {
e.args = e.args.replace(
BAD_CHARS_REGEXP,
BAD_CHARS_REPLACEMENT_CHAR
)
}
}
})
/* eslint-enable no-unused-vars */
scope.$watch('onSave', function (callback) {
if (callback != null) {
Vim.defineEx('write', 'w', callback)
editor.commands.addCommand({
name: 'save',
bindKey: {
win: 'Ctrl-S',
mac: 'Command-S',
},
exec: callback,
readOnly: true,
})
// Not technically 'save', but Ctrl-. recompiles in OL v1
// so maintain compatibility
return editor.commands.addCommand({
name: 'recompile_v1',
bindKey: {
win: 'Ctrl-.',
mac: 'Ctrl-.',
},
exec: callback,
readOnly: true,
})
}
})
editor.commands.removeCommand('transposeletters')
editor.commands.removeCommand('showSettingsMenu')
editor.commands.removeCommand('foldall')
// For European keyboards, the / is above 7 so needs Shift pressing.
// This comes through as Command-Shift-/ on OS X, which is mapped to
// toggleBlockComment.
// This doesn't do anything for LaTeX, so remap this to togglecomment to
// work for European keyboards as normal.
// On Windows, the key combo comes as Ctrl-Shift-7.
editor.commands.removeCommand('toggleBlockComment')
editor.commands.removeCommand('togglecomment')
editor.commands.addCommand({
name: 'togglecomment',
bindKey: {
win: 'Ctrl-/|Ctrl-Shift-7',
mac: 'Command-/|Command-Shift-/',
},
exec(editor) {
return editor.toggleCommentLines()
},
multiSelectAction: 'forEachLine',
scrollIntoView: 'selectionPart',
})
// Trigger search AND replace on CMD+F
editor.commands.addCommand({
name: 'find',
bindKey: {
win: 'Ctrl-F',
mac: 'Command-F',
},
exec(editor) {
return SearchBox.Search(editor, true)
},
readOnly: true,
})
// Bold text on CMD+B
editor.commands.addCommand({
name: 'bold',
bindKey: {
win: 'Ctrl-B',
mac: 'Command-B',
},
exec(editor) {
const selection = editor.getSelection()
if (selection.isEmpty()) {
editor.insert('\\textbf{}')
return editor.navigateLeft(1)
} else {
const text = editor.getCopyText()
return editor.insert(`\\textbf{${text}}`)
}
},
readOnly: false,
})
// Italicise text on CMD+I
editor.commands.addCommand({
name: 'italics',
bindKey: {
win: 'Ctrl-I',
mac: 'Command-I',
},
exec(editor) {
const selection = editor.getSelection()
if (selection.isEmpty()) {
editor.insert('\\textit{}')
return editor.navigateLeft(1)
} else {
const text = editor.getCopyText()
return editor.insert(`\\textit{${text}}`)
}
},
readOnly: false,
})
scope.$watch('onCtrlEnter', function (callback) {
if (callback != null) {
return editor.commands.addCommand({
name: 'compile',
bindKey: {
win: 'Ctrl-Enter',
mac: 'Command-Enter',
},
exec: editor => {
return callback()
},
readOnly: true,
})
}
})
scope.$watch('onCtrlJ', function (callback) {
if (callback != null) {
return editor.commands.addCommand({
name: 'toggle-review-panel',
bindKey: {
win: 'Ctrl-J',
mac: 'Command-J',
},
exec: editor => {
return callback()
},
readOnly: true,
})
}
})
scope.$watch('onCtrlShiftC', function (callback) {
if (callback != null) {
return editor.commands.addCommand({
name: 'add-new-comment',
bindKey: {
win: 'Ctrl-Shift-C',
mac: 'Command-Shift-C',
},
exec: editor => {
return callback()
},
readOnly: true,
})
}
})
scope.$watch('onCtrlShiftA', function (callback) {
if (callback != null) {
return editor.commands.addCommand({
name: 'toggle-track-changes',
bindKey: {
win: 'Ctrl-Shift-A',
mac: 'Command-Shift-A',
},
exec: editor => {
return callback()
},
readOnly: true,
})
}
})
// Make '/' work for search in vim mode.
editor.showCommandLine = arg => {
if (arg === '/') {
return SearchBox.Search(editor, true)
}
}
const getCursorScreenPosition = function () {
const session = editor.getSession()
const cursorPosition = session.selection.getCursor()
const sessionPos = session.documentToScreenPosition(
cursorPosition.row,
cursorPosition.column
)
return (
sessionPos.row * editor.renderer.lineHeight - session.getScrollTop()
)
}
if (attrs.resizeOn != null) {
for (const event of Array.from(attrs.resizeOn.split(','))) {
scope.$on(event, function () {
scope.$applyAsync(() => {
const previousScreenPosition = getCursorScreenPosition()
editor.resize()
// Put cursor back to same vertical position on screen
const newScreenPosition = getCursorScreenPosition()
const session = editor.getSession()
return session.setScrollTop(
session.getScrollTop() +
newScreenPosition -
previousScreenPosition
)
})
})
}
}
scope.$on(`${scope.name}:set-scroll-size`, function (e, size) {
// Make sure that the editor has enough scroll margin above and below
// to scroll the review panel with the given size
const marginTop = size.overflowTop
const { maxHeight } = editor.renderer.layerConfig
const marginBottom = Math.max(size.height - maxHeight, 0)
return setScrollMargins(marginTop, marginBottom)
})
var setScrollMargins = function (marginTop, marginBottom) {
let marginChanged = false
if (editor.renderer.scrollMargin.top !== marginTop) {
editor.renderer.scrollMargin.top = marginTop
marginChanged = true
}
if (editor.renderer.scrollMargin.bottom !== marginBottom) {
editor.renderer.scrollMargin.bottom = marginBottom
marginChanged = true
}
if (marginChanged) {
return editor.renderer.updateFull()
}
}
const resetScrollMargins = () => setScrollMargins(0, 0)
scope.$watch('theme', value => editor.setTheme(`ace/theme/${value}`))
scope.$watch('showPrintMargin', value =>
editor.setShowPrintMargin(value)
)
scope.$watch('keybindings', function (value) {
if (['vim', 'emacs'].includes(value)) {
return editor.setKeyboardHandler(`ace/keyboard/${value}`)
} else {
return editor.setKeyboardHandler(null)
}
})
scope.$watch('fontSize', value =>
element.find('.ace_editor, .ace_content').css({
'font-size': value + 'px',
})
)
scope.$watch('fontFamily', function (value) {
const monospaceFamilies = [
'Monaco',
'Menlo',
'Ubuntu Mono',
'Consolas',
'monospace',
]
if (value != null) {
switch (value) {
case 'monaco':
return editor.setOption(
'fontFamily',
monospaceFamilies.join(', ')
)
case 'lucida':
return editor.setOption(
'fontFamily',
'"Lucida Console", "Source Code Pro", monospace'
)
default:
return editor.setOption('fontFamily', null)
}
}
})
scope.$watch('lineHeight', function (value) {
if (value != null) {
switch (value) {
case 'compact':
editor.container.style.lineHeight = 1.33
break
case 'normal':
editor.container.style.lineHeight = 1.6
break
case 'wide':
editor.container.style.lineHeight = 2
break
default:
editor.container.style.lineHeight = 1.6
}
return editor.renderer.updateFontSize()
}
})
scope.$watch('sharejsDoc', function (sharejs_doc, old_sharejs_doc) {
if (old_sharejs_doc != null) {
scope.$broadcast('beforeChangeDocument')
detachFromAce(old_sharejs_doc)
}
if (sharejs_doc != null) {
attachToAce(sharejs_doc)
}
if (sharejs_doc != null && old_sharejs_doc != null) {
return scope.$broadcast('afterChangeDocument')
}
})
scope.$watch('text', function (text) {
if (text != null) {
editor.setValue(text, -1)
const session = editor.getSession()
return session.setUseWrapMode(true)
}
})
scope.$watch('annotations', function (annotations) {
const session = editor.getSession()
return session.setAnnotations(annotations)
})
scope.$watch('readOnly', value => editor.setReadOnly(!!value))
scope.$watch('syntaxValidation', function (value) {
// ignore undefined settings here
// only instances of ace with an explicit value should set useWorker
// the history instance will have syntaxValidation undefined
if (value != null && syntaxValidationEnabled) {
const session = editor.getSession()
return session.setOption('useWorker', value)
}
})
editor.setOption('scrollPastEnd', true)
let updateCount = 0
const onChange = function () {
updateCount++
if (updateCount === 100) {
eventTracking.send('editor-interaction', 'multi-doc-update')
}
return scope.$emit(`${scope.name}:change`)
}
let currentFirstVisibleRow = null
const emitMiddleVisibleRowChanged = () => {
const firstVisibleRow = editor.getFirstVisibleRow()
if (firstVisibleRow === currentFirstVisibleRow) return
currentFirstVisibleRow = firstVisibleRow
const lastVisibleRow = editor.getLastVisibleRow()
scope.$emit(
`scroll:editor:update`,
Math.floor((firstVisibleRow + lastVisibleRow) / 2)
)
}
const onScroll = function (scrollTop) {
if (scope.eventsBridge == null) {
return
}
const height = editor.renderer.layerConfig.maxHeight
emitMiddleVisibleRowChanged()
return scope.eventsBridge.emit('aceScroll', scrollTop, height)
}
const onScrollbarVisibilityChanged = function (event, vRenderer) {
if (scope.eventsBridge == null) {
return
}
return scope.eventsBridge.emit(
'aceScrollbarVisibilityChanged',
vRenderer.scrollBarV.isVisible,
vRenderer.scrollBarV.width
)
}
if (scope.eventsBridge != null) {
editor.renderer.on(
'scrollbarVisibilityChanged',
onScrollbarVisibilityChanged
)
scope.eventsBridge.on('externalScroll', position =>
editor.getSession().setScrollTop(position)
)
scope.eventsBridge.on('refreshScrollPosition', function () {
const session = editor.getSession()
session.setScrollTop(session.getScrollTop() + 1)
return session.setScrollTop(session.getScrollTop() - 1)
})
}
const onSessionChangeForSpellCheck = function (e) {
spellCheckManager.onSessionChange()
if (e.oldSession != null) {
e.oldSession.getDocument().off('change', spellCheckManager.onChange)
}
e.session.getDocument().on('change', spellCheckManager.onChange)
if (e.oldSession != null) {
e.oldSession.off('changeScrollTop', spellCheckManager.onScroll)
}
return e.session.on('changeScrollTop', spellCheckManager.onScroll)
}
const initSpellCheck = function () {
if (!spellCheckManager) return
spellCheckManager.init()
editor.on('changeSession', onSessionChangeForSpellCheck)
onSessionChangeForSpellCheck({
session: editor.getSession(),
}) // Force initial setup
return editor.on('nativecontextmenu', spellCheckManager.onContextMenu)
}
const tearDownSpellCheck = function () {
if (!spellCheckManager) return
editor.off('changeSession', onSessionChangeForSpellCheck)
return editor.off(
'nativecontextmenu',
spellCheckManager.onContextMenu
)
}
const initTrackChanges = function () {
trackChangesManager.rangesTracker = scope.sharejsDoc.ranges
// Force onChangeSession in order to set up highlights etc.
trackChangesManager.onChangeSession()
if (!trackChangesManager) return
editor.on('changeSelection', trackChangesManager.onChangeSelection)
// Selection also moves with updates elsewhere in the document
editor.on('change', trackChangesManager.onChangeSelection)
editor.on('changeSession', trackChangesManager.onChangeSession)
editor.on('cut', trackChangesManager.onCut)
editor.on('paste', trackChangesManager.onPaste)
editor.renderer.on('resize', trackChangesManager.onResize)
}
const tearDownTrackChanges = function () {
if (!trackChangesManager) return
trackChangesManager.tearDown()
editor.off('changeSelection', trackChangesManager.onChangeSelection)
editor.off('change', trackChangesManager.onChangeSelection)
editor.off('changeSession', trackChangesManager.onChangeSession)
editor.off('cut', trackChangesManager.onCut)
editor.off('paste', trackChangesManager.onPaste)
editor.renderer.off('resize', trackChangesManager.onResize)
}
const initUndo = function () {
// Emulate onChangeSession event. Note: listening to changeSession
// event is unnecessary since this method is called when we switch
// sessions (via ShareJS changing) anyway
undoManager.onChangeSession(editor.getSession())
editor.on('change', undoManager.onChange)
}
const tearDownUndo = function () {
editor.off('change', undoManager.onChange)
}
const onSessionChangeForCursorPosition = function (e) {
if (e.oldSession != null) {
e.oldSession.selection.off(
'changeCursor',
cursorPositionManager.onCursorChange
)
}
return e.session.selection.on(
'changeCursor',
cursorPositionManager.onCursorChange
)
}
const onUnloadForCursorPosition = () =>
cursorPositionManager.onUnload(editor.getSession())
const initCursorPosition = function () {
editor.on('changeSession', onSessionChangeForCursorPosition)
// Force initial setup
onSessionChangeForCursorPosition({ session: editor.getSession() })
return $(window).on('unload', onUnloadForCursorPosition)
}
const tearDownCursorPosition = function () {
editor.off('changeSession', onSessionChangeForCursorPosition)
return $(window).off('unload', onUnloadForCursorPosition)
}
initCursorPosition()
// Trigger the event once *only* - this is called after Ace is connected
// to the ShareJs instance but this event should only be triggered the
// first time the editor is opened. Not every time the docs opened
const triggerEditorInitEvent = _.once(() =>
scope.$broadcast('editorInit')
)
var attachToAce = function (sharejs_doc) {
let mode
const lines = sharejs_doc.getSnapshot().split('\n')
let session = editor.getSession()
if (session != null) {
session.destroy()
}
// see if we can lookup a suitable mode from ace
// but fall back to text by default
try {
if (/\.(Rtex|bbl|tikz)$/i.test(scope.fileName)) {
// recognise Rtex and bbl as latex
mode = 'ace/mode/latex'
} else if (/\.(sty|cls|clo)$/.test(scope.fileName)) {
// recognise some common files as tex
mode = 'ace/mode/tex'
} else {
;({ mode } = ModeList.getModeForPath(scope.fileName))
// we prefer plain_text mode over text mode because ace's
// text mode is actually for code and has unwanted
// indenting (see wrapMethod in ace edit_session.js)
if (mode === 'ace/mode/text') {
mode = 'ace/mode/plain_text'
}
}
} catch (error) {
mode = 'ace/mode/plain_text'
}
// create our new session
session = new EditSession(lines, mode)
session.setUseWrapMode(true)
// use syntax validation only when explicitly set
if (
scope.syntaxValidation != null &&
syntaxValidationEnabled &&
!/\.bib$/.test(scope.fileName)
) {
session.setOption('useWorker', scope.syntaxValidation)
}
// set to readonly until document change handlers are attached
editor.setReadOnly(true)
// now attach session to editor
editor.setSession(session)
const doc = session.getDocument()
doc.on('change', onChange)
editor.initing = true
sharejs_doc.attachToAce(editor)
editor.initing = false
// now ready to edit document
// respect the readOnly setting, normally false
editor.setReadOnly(scope.readOnly)
triggerEditorInitEvent()
if (!scope.readOnly) {
initSpellCheck()
}
initTrackChanges()
initUndo()
resetScrollMargins()
// need to set annotations after attaching because attaching
// deletes and then inserts document content
session.setAnnotations(scope.annotations)
session.on('changeScrollTop', eventTracking.editingSessionHeartbeat)
angular
.element($window)
.on('click', eventTracking.editingSessionHeartbeat)
scope.$on('$destroy', () =>
angular
.element($window)
.off('click', eventTracking.editingSessionHeartbeat)
)
if (scope.eventsBridge != null) {
session.on('changeScrollTop', onScroll)
}
$rootScope.hasLintingError = false
session.on('changeAnnotation', function () {
// Both linter errors and compile logs are set as error annotations,
// however when the user types something, the compile logs are
// replaced with linter errors. When we check for lint errors before
// autocompile we are guaranteed to get linter errors
const hasErrors =
session
.getAnnotations()
.filter(annotation => annotation.type !== 'info').length > 0
if ($rootScope.hasLintingError !== hasErrors) {
return ($rootScope.hasLintingError = hasErrors)
}
})
setTimeout(() =>
// Let any listeners init themselves
onScroll(editor.renderer.getScrollTop())
)
return editor.focus()
}
var detachFromAce = function (sharejs_doc) {
tearDownSpellCheck()
tearDownTrackChanges()
tearDownUndo()
sharejs_doc.detachFromAce()
sharejs_doc.off('remoteop.recordRemote')
const session = editor.getSession()
session.off('changeScrollTop')
const doc = session.getDocument()
return doc.off('change', onChange)
}
if (scope.rendererData != null) {
editor.renderer.on('changeCharacterSize', () => {
scope.$apply(
() => (scope.rendererData.lineHeight = editor.renderer.lineHeight)
)
})
}
scope.$watch('rendererData', function (rendererData) {
if (rendererData != null) {
return (rendererData.lineHeight = editor.renderer.lineHeight)
}
})
scope.$on('$destroy', function () {
if (scope.sharejsDoc != null) {
scope.$broadcast('changeEditor')
tearDownSpellCheck()
tearDownCursorPosition()
tearDownUndo()
detachFromAce(scope.sharejsDoc)
const session = editor.getSession()
if (session != null) {
session.destroy()
}
return scope.eventsBridge.emit(
'aceScrollbarVisibilityChanged',
false,
0
)
}
})
return scope.$emit(`${scope.name}:inited`, editor)
},
template: `\
<div class="ace-editor-wrapper">
<div
class="undo-conflict-warning alert alert-danger small"
ng-show="undo.show_remote_warning"
>
<strong>Watch out!</strong>
We had to undo some of your collaborators changes before we could undo yours.
<a
href="#"
class="pull-right"
ng-click="undo.show_remote_warning = false"
>Dismiss</a>
</div>
<div class="ace-editor-body"></div>
<spell-menu
open="spellMenu.open"
top="spellMenu.top"
left="spellMenu.left"
layout-from-bottom="spellMenu.layoutFromBottom"
highlight="spellMenu.highlight"
replace-word="replaceWord(highlight, suggestion)"
learn-word="learnWord(highlight)"
></spell-menu>
<div
class="annotation-label"
ng-show="annotationLabel.show"
ng-style="{
position: 'absolute',
left: annotationLabel.left,
right: annotationLabel.right,
bottom: annotationLabel.bottom,
top: annotationLabel.top,
'background-color': annotationLabel.backgroundColor
}"
>
{{ annotationLabel.text }}
</div>
<a
href
class="highlights-before-label btn btn-info btn-xs"
ng-show="updateLabels.highlightsBefore > 0"
ng-click="gotoHighlightAbove()"
>
<i class="fa fa-fw fa-arrow-up"></i>
{{ updateLabels.highlightsBefore }} more update{{ updateLabels.highlightsBefore > 1 && "" || "s" }} above
</a>
<a
href
class="highlights-after-label btn btn-info btn-xs"
ng-show="updateLabels.highlightsAfter > 0"
ng-click="gotoHighlightBelow()"
>
<i class="fa fa-fw fa-arrow-down"></i>
{{ updateLabels.highlightsAfter }} more update{{ updateLabels.highlightsAfter > 1 && "" || "s" }} below
</a>
</div>\
`,
}
}
)
function monkeyPatchSearch($rootScope, $compile) {
const searchHtml = `\
<div class="ace_search right">
<a href type="button" action="hide" class="ace_searchbtn_close">
<i class="fa fa-fw fa-times"></i>
</a>
<div class="ace_search_form">
<input class="ace_search_field form-control input-sm" placeholder="Search for" spellcheck="false"></input>
<div class="btn-group">
<button type="button" action="findNext" class="ace_searchbtn next btn btn-default btn-sm">
<i class="fa fa-chevron-down fa-fw"></i>
</button>
<button type="button" action="findPrev" class="ace_searchbtn prev btn btn-default btn-sm">
<i class="fa fa-chevron-up fa-fw"></i>
</button>
</div>
</div>
<div class="ace_replace_form">
<input class="ace_search_field form-control input-sm" placeholder="Replace with" spellcheck="false"></input>
<div class="btn-group">
<button type="button" action="replaceAndFindNext" class="ace_replacebtn btn btn-default btn-sm">Replace</button>
<button type="button" action="replaceAll" class="ace_replacebtn btn btn-default btn-sm">All</button>
</div>
</div>
<div class="ace_search_options">
<div class="btn-group">
<button action="toggleRegexpMode" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="RegExp Search">.*</button>
<button action="toggleCaseSensitive" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="CaseSensitive Search">Aa</button>
<button action="toggleWholeWords" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="Whole Word Search">"..."</button>
<button action="searchInSelection" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="Search Within Selection"><i class="fa fa-align-left"></i></button>
</div>
<span class="ace_search_counter"></span>
</div>
<div action="toggleReplace" class="hidden"></div>
</div>\
`
// Remove Ace CSS
$('#ace_searchbox').remove()
const SB = SearchBox.SearchBox
const { $init } = SB.prototype
SB.prototype.$init = function () {
this.element = $compile(searchHtml)($rootScope.$new())[0]
return $init.apply(this)
}
}
| overleaf/web/frontend/js/ide/editor/directives/aceEditor.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor.js",
"repo_id": "overleaf",
"token_count": 15662
} | 524 |
/* eslint-disable
camelcase,
max-len
*/
import EditorShareJsCodec from '../../../EditorShareJsCodec'
import 'ace/ace'
import '../../../../../utils/EventEmitter'
import '../../../../colors/ColorManager'
const { Range } = ace.require('ace/range')
class TrackChangesManager {
constructor($scope, editor, element, adapter) {
this._doneUpdateThisLoop = false
this._pendingUpdates = false
this.onChangeSession = this.onChangeSession.bind(this)
this.onChangeSelection = this.onChangeSelection.bind(this)
this.onCut = this.onCut.bind(this)
this.onPaste = this.onPaste.bind(this)
this.onResize = this.onResize.bind(this)
this.tearDown = this.tearDown.bind(this)
this.$scope = $scope
this.editor = editor
this.element = element
this.adapter = adapter
this._scrollTimeout = null
this.changingSelection = false
if (window.trackChangesManager == null) {
window.trackChangesManager = this
}
this.$scope.$watch('trackChanges', track_changes => {
if (track_changes == null) {
return
}
this.setTrackChanges(track_changes)
})
this.$scope.$watch('sharejsDoc', (doc, oldDoc) => {
if (doc == null) {
return
}
if (oldDoc != null) {
this.disconnectFromDoc(oldDoc)
}
this.setTrackChanges(this.$scope.trackChanges)
this.connectToDoc(doc)
})
this.$scope.$on('comment:add', (e, thread_id, offset, length) => {
this.addCommentToSelection(thread_id, offset, length)
})
this.$scope.$on('comment:select_line', e => {
this.selectLineIfNoSelection()
})
this.$scope.$on('changes:accept', (e, change_ids) => {
this.acceptChangeIds(change_ids)
})
this.$scope.$on('changes:reject', (e, change_ids) => {
this.rejectChangeIds(change_ids)
})
this.$scope.$on('comment:remove', (e, comment_id) => {
this.removeCommentId(comment_id)
})
this.$scope.$on('comment:resolve_threads', (e, thread_ids) => {
this.hideCommentsByThreadIds(thread_ids)
})
this.$scope.$on('comment:unresolve_thread', (e, thread_id) => {
this.showCommentByThreadId(thread_id)
})
this.$scope.$on('review-panel:recalculate-screen-positions', () => {
this.recalculateReviewEntriesScreenPositions()
})
this._resetCutState()
}
onChangeSession(e) {
this.clearAnnotations()
this.redrawAnnotations()
if (this.editor) {
this.editor.session.on('changeScrollTop', this.onChangeScroll.bind(this))
}
}
onChangeScroll() {
if (this._scrollTimeout == null) {
return (this._scrollTimeout = setTimeout(() => {
this.recalculateVisibleEntries()
this.$scope.$apply()
return (this._scrollTimeout = null)
}, 200))
}
}
onChangeSelection() {
// Deletes can send about 5 changeSelection events, so
// just act on the last one.
if (!this.changingSelection) {
this.changingSelection = true
return this.$scope.$evalAsync(() => {
this.changingSelection = false
return this.updateFocus()
})
}
}
onResize() {
this.recalculateReviewEntriesScreenPositions()
}
connectToDoc(doc) {
this.rangesTracker = doc.ranges
this.setTrackChanges(this.$scope.trackChanges)
doc.on('ranges:dirty', () => {
this.updateAnnotations()
})
doc.on('ranges:clear', () => {
this.clearAnnotations()
})
doc.on('ranges:redraw', () => {
this.redrawAnnotations()
})
}
disconnectFromDoc(doc) {
doc.off('ranges:clear')
doc.off('ranges:redraw')
doc.off('ranges:dirty')
}
tearDown() {
this.adapter.tearDown()
}
setTrackChanges(value) {
if (value) {
if (this.$scope.sharejsDoc != null) {
this.$scope.sharejsDoc.track_changes_as = window.user.id || 'anonymous'
}
} else {
if (this.$scope.sharejsDoc != null) {
this.$scope.sharejsDoc.track_changes_as = null
}
}
}
clearAnnotations() {
this.adapter.clearAnnotations()
}
redrawAnnotations() {
for (const change of Array.from(this.rangesTracker.changes)) {
if (change.op.i != null) {
this.adapter.onInsertAdded(change)
} else if (change.op.d != null) {
this.adapter.onDeleteAdded(change)
}
}
Array.from(this.rangesTracker.comments).forEach(comment => {
if (!this.isCommentResolved(comment)) {
this.adapter.onCommentAdded(comment)
}
})
this.broadcastChange()
}
updateAnnotations() {
// Doc updates with multiple ops, like search/replace or block comments
// will call this with every individual op in a single event loop. So only
// do the first this loop, then schedule an update for the next loop for
// the rest.
if (!this._doneUpdateThisLoop) {
this._doUpdateAnnotations()
this._doneUpdateThisLoop = true
return setTimeout(() => {
if (this._pendingUpdates) {
this._doUpdateAnnotations()
}
this._doneUpdateThisLoop = false
this._pendingUpdates = false
})
} else {
this._pendingUpdates = true
}
}
_doUpdateAnnotations() {
let change, comment
const dirty = this.rangesTracker.getDirtyState()
let updateMarkers = false
for (var id in dirty.change.added) {
change = dirty.change.added[id]
if (change.op.i != null) {
this.adapter.onInsertAdded(change)
} else if (change.op.d != null) {
this.adapter.onDeleteAdded(change)
}
}
for (id in dirty.change.removed) {
change = dirty.change.removed[id]
if (change.op.i != null) {
this.adapter.onInsertRemoved(change)
} else if (change.op.d != null) {
this.adapter.onDeleteRemoved(change)
}
}
for (id in dirty.change.moved) {
change = dirty.change.moved[id]
updateMarkers = true
this.adapter.onChangeMoved(change)
}
for (id in dirty.comment.added) {
comment = dirty.comment.added[id]
if (!this.isCommentResolved(comment)) {
this.adapter.onCommentAdded(comment)
}
}
for (id in dirty.comment.removed) {
comment = dirty.comment.removed[id]
if (!this.isCommentResolved(comment)) {
this.adapter.onCommentRemoved(comment)
}
}
for (id in dirty.comment.moved) {
comment = dirty.comment.moved[id]
if (this.adapter.onCommentMoved && !this.isCommentResolved(comment)) {
updateMarkers = true
this.adapter.onCommentMoved(comment)
}
}
/**
* For now, if not using ACE don't worry about the markers
*/
if (!this.editor) {
updateMarkers = false
}
this.rangesTracker.resetDirtyState()
if (updateMarkers) {
this.editor.renderer.updateBackMarkers()
}
this.broadcastChange()
}
addComment(offset, content, thread_id) {
const op = { c: content, p: offset, t: thread_id }
// @rangesTracker.applyOp op # Will apply via sharejs
this.$scope.sharejsDoc.submitOp(op)
}
addCommentToSelection(thread_id, offset, length) {
const start = this.adapter.shareJsOffsetToRowColumn(offset)
const end = this.adapter.shareJsOffsetToRowColumn(offset + length)
const range = new Range(start.row, start.column, end.row, end.column)
const content = this.editor.session.getTextRange(range)
this.addComment(offset, content, thread_id)
}
isCommentResolved(comment) {
return this.rangesTracker.resolvedThreadIds[comment.op.t]
}
selectLineIfNoSelection() {
if (this.editor.selection.isEmpty()) {
this.editor.selection.selectLine()
}
}
acceptChangeIds(change_ids) {
this.rangesTracker.removeChangeIds(change_ids)
this.updateAnnotations()
this.updateFocus()
}
rejectChangeIds(change_ids) {
const changes = this.rangesTracker.getChanges(change_ids)
if (changes.length === 0) {
return
}
// When doing bulk rejections, adjacent changes might interact with each other.
// Consider an insertion with an adjacent deletion (which is a common use-case, replacing words):
//
// "foo bar baz" -> "foo quux baz"
//
// The change above will be modeled with two ops, with the insertion going first:
//
// foo quux baz
// |--| -> insertion of "quux", op 1, at position 4
// | -> deletion of "bar", op 2, pushed forward by "quux" to position 8
//
// When rejecting these changes at once, if the insertion is rejected first, we get unexpected
// results. What happens is:
//
// 1) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
// starting from position 4;
//
// "foo quux baz" -> "foo baz"
// |--| -> 4 characters to be removed
//
// 2) Rejecting the deletion adds the deleted word "bar" at position 8 (i.e. it will act as if
// the word "quuux" was still present).
//
// "foo baz" -> "foo bazbar"
// | -> deletion of "bar" is reverted by reinserting "bar" at position 8
//
// While the intended result would be "foo bar baz", what we get is:
//
// "foo bazbar" (note "bar" readded at position 8)
//
// The issue happens because of step 1. To revert the insertion of "quux", 4 characters are deleted
// from position 4. This includes the position where the deletion exists; when that position is
// cleared, the RangesTracker considers that the deletion is gone and stops tracking/updating it.
// As we still hold a reference to it, the code tries to revert it by readding the deleted text, but
// does so at the outdated position (position 8, which was valid when "quux" was present).
//
// To avoid this kind of problem, we need to make sure that reverting operations doesn't affect
// subsequent operations that come after. Reverse sorting the operations based on position will
// achieve it; in the case above, it makes sure that the the deletion is reverted first:
//
// 1) Rejecting the deletion adds the deleted word "bar" at position 8
//
// "foo quux baz" -> "foo quuxbar baz"
// | -> deletion of "bar" is reverted by
// reinserting "bar" at position 8
//
// 2) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
// starting from position 4 and achieves the expected result:
//
// "foo quuxbar baz" -> "foo bar baz"
// |--| -> 4 characters to be removed
changes.sort((a, b) => b.op.p - a.op.p)
const session = this.editor.getSession()
for (const change of Array.from(changes)) {
if (change.op.d != null) {
const content = change.op.d
const position = this.adapter.shareJsOffsetToRowColumn(change.op.p)
session.$fromReject = true // Tell track changes to cancel out delete
session.insert(position, content)
session.$fromReject = false
} else if (change.op.i != null) {
const start = this.adapter.shareJsOffsetToRowColumn(change.op.p)
const end = this.adapter.shareJsOffsetToRowColumn(
change.op.p + change.op.i.length
)
const editor_text = session.getDocument().getTextRange({ start, end })
if (editor_text !== change.op.i) {
throw new Error(
`Op to be removed (${JSON.stringify(
change.op
)}), does not match editor text, '${editor_text}'`
)
}
session.$fromReject = true
session.remove({ start, end })
session.$fromReject = false
} else {
throw new Error(`unknown change: ${JSON.stringify(change)}`)
}
}
setTimeout(() => this.updateFocus())
}
removeCommentId(comment_id) {
this.rangesTracker.removeCommentId(comment_id)
return this.updateAnnotations()
}
hideCommentsByThreadIds(thread_ids) {
const resolve_ids = {}
const comments = this.rangesTracker.comments || []
for (const id of Array.from(thread_ids)) {
resolve_ids[id] = true
}
for (const comment of comments) {
if (resolve_ids[comment.op.t]) {
this.adapter.onCommentRemoved(comment)
}
}
return this.broadcastChange()
}
showCommentByThreadId(thread_id) {
const comments = this.rangesTracker.comments || []
for (const comment of comments) {
if (comment.op.t === thread_id && !this.isCommentResolved(comment)) {
this.adapter.onCommentAdded(comment)
}
}
return this.broadcastChange()
}
_resetCutState() {
return (this._cutState = {
text: null,
comments: [],
docId: null,
})
}
onCut() {
this._resetCutState()
const selection = this.editor.getSelectionRange()
const selection_start = this._rangeToShareJs(selection.start)
const selection_end = this._rangeToShareJs(selection.end)
this._cutState.text = this.editor.getSelectedText()
this._cutState.docId = this.$scope.docId
return (() => {
const result = []
for (const comment of Array.from(this.rangesTracker.comments)) {
const comment_start = comment.op.p
const comment_end = comment_start + comment.op.c.length
if (selection_start <= comment_start && comment_end <= selection_end) {
result.push(
this._cutState.comments.push({
offset: comment.op.p - selection_start,
text: comment.op.c,
comment,
})
)
} else {
result.push(undefined)
}
}
return result
})()
}
onPaste() {
this.editor.once('change', change => {
if (change.action !== 'insert') {
return
}
const pasted_text = change.lines.join('\n')
const paste_offset = this._rangeToShareJs(change.start)
// We have to wait until the change has been processed by the range
// tracker, since if we move the ops into place beforehand, they will be
// moved again when the changes are processed by the range tracker. This
// ranges:dirty event is fired after the doc has applied the changes to
// the range tracker.
this.$scope.sharejsDoc.on('ranges:dirty.paste', () => {
// Doc event emitter uses namespaced events
this.$scope.sharejsDoc.off('ranges:dirty.paste')
if (
pasted_text === this._cutState.text &&
this.$scope.docId === this._cutState.docId
) {
for (const { comment, offset, text } of Array.from(
this._cutState.comments
)) {
const op = { c: text, p: paste_offset + offset, t: comment.id }
this.$scope.sharejsDoc.submitOp(op)
} // Resubmitting an existing comment op (by thread id) will move it
}
this._resetCutState()
// Check that comments still match text. Will throw error if not.
this.rangesTracker.validate(this.editor.getValue())
})
})
}
checkMapping() {
// TODO: reintroduce this check
let background_marker_id, callout_marker_id, end, marker, op, start
const session = this.editor.getSession()
// Make a copy of session.getMarkers() so we can modify it
const markers = {}
const object = session.getMarkers()
for (var marker_id in object) {
marker = object[marker_id]
markers[marker_id] = marker
}
const expected_markers = []
for (var change of Array.from(this.rangesTracker.changes)) {
if (this.adapter.changeIdToMarkerIdMap[change.id] != null) {
;({ op } = change)
;({
background_marker_id,
callout_marker_id,
} = this.adapter.changeIdToMarkerIdMap[change.id])
start = this.adapter.shareJsOffsetToRowColumn(op.p)
if (op.i != null) {
end = this.adapter.shareJsOffsetToRowColumn(op.p + op.i.length)
} else if (op.d != null) {
end = start
}
expected_markers.push({
marker_id: background_marker_id,
start,
end,
})
expected_markers.push({
marker_id: callout_marker_id,
start,
end: start,
})
}
}
for (const comment of Array.from(this.rangesTracker.comments)) {
if (this.adapter.changeIdToMarkerIdMap[comment.id] != null) {
;({
background_marker_id,
callout_marker_id,
} = this.adapter.changeIdToMarkerIdMap[comment.id])
start = this.adapter.shareJsOffsetToRowColumn(comment.op.p)
end = this.adapter.shareJsOffsetToRowColumn(
comment.op.p + comment.op.c.length
)
expected_markers.push({
marker_id: background_marker_id,
start,
end,
})
expected_markers.push({
marker_id: callout_marker_id,
start,
end: start,
})
}
}
for ({ marker_id, start, end } of Array.from(expected_markers)) {
marker = markers[marker_id]
delete markers[marker_id]
if (
marker.range.start.row !== start.row ||
marker.range.start.column !== start.column ||
marker.range.end.row !== end.row ||
marker.range.end.column !== end.column
) {
console.error("Change doesn't match marker anymore", {
change,
marker,
start,
end,
})
}
}
return (() => {
const result = []
for (marker_id in markers) {
marker = markers[marker_id]
if (/track-changes/.test(marker.clazz)) {
result.push(console.error('Orphaned ace marker', marker))
} else {
result.push(undefined)
}
}
return result
})()
}
broadcastChange() {
this.$scope.$emit('editor:track-changes:changed', this.$scope.docId)
}
recalculateReviewEntriesScreenPositions() {
const session = this.editor.getSession()
const { renderer } = this.editor
const entries = this._getCurrentDocEntries()
const object = entries || {}
for (const entry_id in object) {
const entry = object[entry_id]
const doc_position = this.adapter.shareJsOffsetToRowColumn(entry.offset)
const screen_position = session.documentToScreenPosition(
doc_position.row,
doc_position.column
)
const y = screen_position.row * renderer.lineHeight
if (entry.screenPos == null) {
entry.screenPos = {}
}
entry.screenPos.y = y
entry.docPos = doc_position
}
this.recalculateVisibleEntries()
this.$scope.$apply()
}
recalculateVisibleEntries() {
const OFFSCREEN_ROWS = 20
// With less than this number of entries, don't bother culling to avoid
// little UI jumps when scrolling.
const CULL_AFTER = 100
const { firstRow, lastRow } = this.editor.renderer.layerConfig
const entries = this._getCurrentDocEntries() || {}
const entriesLength = Object.keys(entries).length
let changed = false
for (const entry_id in entries) {
const entry = entries[entry_id]
const old = entry.visible
entry.visible =
entriesLength < CULL_AFTER ||
(firstRow - OFFSCREEN_ROWS <= entry.docPos.row &&
entry.docPos.row <= lastRow + OFFSCREEN_ROWS)
if (entry.visible !== old) {
changed = true
}
}
if (changed) {
this.$scope.$emit('editor:track-changes:visibility_changed')
}
}
_getCurrentDocEntries() {
const doc_id = this.$scope.docId
const entries = this.$scope.reviewPanel.entries[doc_id] || {}
return entries
}
updateFocus() {
if (this.editor) {
const selection = this.editor.getSelectionRange()
const selection_start = this._rangeToShareJs(selection.start)
const selection_end = this._rangeToShareJs(selection.end)
const is_selection = selection_start !== selection_end
this.$scope.$emit(
'editor:focus:changed',
selection_start,
selection_end,
is_selection
)
}
}
_rangeToShareJs(range) {
const lines = this.editor.getSession().getDocument().getLines(0, range.row)
return EditorShareJsCodec.rangeToShareJs(range, lines)
}
_changeToShareJs(delta) {
const lines = this.editor
.getSession()
.getDocument()
.getLines(0, delta.start.row)
return EditorShareJsCodec.changeToShareJs(delta, lines)
}
}
export default TrackChangesManager
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesManager.js",
"repo_id": "overleaf",
"token_count": 8511
} | 525 |
import _ from 'lodash'
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
import ColorManager from '../../colors/ColorManager'
import displayNameForUser from '../util/displayNameForUser'
const historyEntryController = function ($scope, $element, $attrs) {
const ctrl = this
// This method (and maybe the one below) will be removed soon. User details data will be
// injected into the history API responses, so we won't need to fetch user data from other
// local data structures.
const _getUserById = id =>
_.find(ctrl.users, function (user) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
return curUserId === id
})
ctrl.displayName = displayNameForUser
ctrl.displayNameById = id => displayNameForUser(_getUserById(id))
ctrl.getProjectOpDoc = function (projectOp) {
if (projectOp.rename != null) {
return `${projectOp.rename.pathname} → ${projectOp.rename.newPathname}`
} else if (projectOp.add != null) {
return `${projectOp.add.pathname}`
} else if (projectOp.remove != null) {
return `${projectOp.remove.pathname}`
}
}
ctrl.getUserCSSStyle = function (user) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
const hue = ColorManager.getHueForUserId(curUserId) || 100
if (ctrl.isEntrySelected() || ctrl.isEntryHoverSelected()) {
return { color: '#FFF' }
} else {
return { color: `hsl(${hue}, 70%, 50%)` }
}
}
ctrl.isEntrySelected = function () {
if (ctrl.rangeSelectionEnabled) {
return (
ctrl.entry.toV <= ctrl.selectedHistoryRange.toV &&
ctrl.entry.fromV >= ctrl.selectedHistoryRange.fromV
)
} else {
return ctrl.entry.toV === ctrl.selectedHistoryVersion
}
}
ctrl.isEntryHoverSelected = function () {
return (
ctrl.rangeSelectionEnabled &&
ctrl.entry.toV <= ctrl.hoveredHistoryRange.toV &&
ctrl.entry.fromV >= ctrl.hoveredHistoryRange.fromV
)
}
ctrl.onDraggingStart = () => {
ctrl.historyEntriesList.onDraggingStart()
}
ctrl.onDraggingStop = (isValidDrop, boundary) =>
ctrl.historyEntriesList.onDraggingStop(isValidDrop, boundary)
ctrl.onDrop = boundary => {
if (boundary === 'toV') {
$scope.$applyAsync(() =>
ctrl.historyEntriesList.setRangeToV(ctrl.entry.toV)
)
} else if (boundary === 'fromV') {
$scope.$applyAsync(() =>
ctrl.historyEntriesList.setRangeFromV(ctrl.entry.fromV)
)
}
}
ctrl.onOver = boundary => {
if (boundary === 'toV') {
$scope.$applyAsync(() =>
ctrl.historyEntriesList.setHoveredRangeToV(ctrl.entry.toV)
)
} else if (boundary === 'fromV') {
$scope.$applyAsync(() =>
ctrl.historyEntriesList.setHoveredRangeFromV(ctrl.entry.fromV)
)
}
}
ctrl.$onInit = () => {
ctrl.$entryEl = $element.find('> .history-entry')
ctrl.$entryDetailsEl = $element.find('.history-entry-details')
ctrl.$toVHandleEl = $element.find('.history-entry-toV-handle')
ctrl.$fromVHandleEl = $element.find('.history-entry-fromV-handle')
ctrl.historyEntriesList.onEntryLinked(ctrl.entry, ctrl.$entryEl)
}
}
export default App.component('historyEntry', {
bindings: {
entry: '<',
currentUser: '<',
users: '<',
rangeSelectionEnabled: '<',
isDragging: '<',
selectedHistoryVersion: '<?',
selectedHistoryRange: '<?',
hoveredHistoryRange: '<?',
onSelect: '&',
onLabelDelete: '&',
},
require: {
historyEntriesList: '^historyEntriesList',
},
controller: historyEntryController,
templateUrl: 'historyEntryTpl',
})
| overleaf/web/frontend/js/ide/history/components/historyEntry.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/components/historyEntry.js",
"repo_id": "overleaf",
"token_count": 1568
} | 526 |
/* 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:
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let displayNameForUser
export default displayNameForUser = function (user) {
if (user == null) {
return 'Anonymous'
}
if (user.id === window.user.id) {
return 'you'
}
if (user.name != null) {
return user.name
}
let name = [user.first_name, user.last_name]
.filter(n => n != null)
.join(' ')
.trim()
if (name === '') {
name = user.email.split('@')[0]
}
if (name == null || name === '') {
return '?'
}
return name
}
| overleaf/web/frontend/js/ide/history/util/displayNameForUser.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/util/displayNameForUser.js",
"repo_id": "overleaf",
"token_count": 315
} | 527 |
/*
* Adapted from https://github.com/mozilla/pdfjs-dist/blob/e9492b7a725ec4edd466880223474f4295a5fb45/webpack.js
* The PDF.js worker needs to be loaded in a Web Worker. This can be done
* automatically with webpack via worker-loader.
* PDF.js has the above file to do this, however it uses the webpack loader
* module loading syntax, which prevents us from customising the loader.
* We need to output the worker file to the public/js directory, and so we need
* to customise the loader's options. However the rest of the file is identical
* to the one provided by PDF.js.
*/
/*
* Adapted from https://github.com/mozilla/pdfjs-dist/blob/e9492b7a725ec4edd466880223474f4295a5fb45/webpack.js
* The PDF.js worker needs to be loaded in a Web Worker. This can be done
* automatically with webpack via worker-loader.
* PDF.js has the above file to do this, however it uses the webpack loader
* module loading syntax, which prevents us from customising the loader.
* We need to output the worker file to the public/js directory, and so we need
* to customise the loader's options. However the rest of the file is identical
* to the one provided by PDF.js.
*/
var pdfjs = require('libs/pdfjs-dist/build/pdf.js')
var PdfjsWorker = require('libs/pdfjs-dist/build/pdf.worker.js')
if (typeof window !== 'undefined' && 'Worker' in window) {
pdfjs.GlobalWorkerOptions.workerPort = new PdfjsWorker()
}
module.exports = pdfjs
| overleaf/web/frontend/js/ide/pdfng/directives/pdfJsLoader.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/pdfng/directives/pdfJsLoader.js",
"repo_id": "overleaf",
"token_count": 438
} | 528 |
/* 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('aggregateChangeEntry', $timeout => ({
restrict: 'E',
templateUrl: 'aggregateChangeEntryTemplate',
scope: {
entry: '=',
user: '=',
permissions: '=',
onAccept: '&',
onReject: '&',
onIndicatorClick: '&',
onBodyClick: '&',
},
link(scope, element, attrs) {
scope.contentLimit = 17
scope.isDeletionCollapsed = true
scope.isInsertionCollapsed = true
scope.deletionNeedsCollapsing = false
scope.insertionNeedsCollapsing = 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.toggleDeletionCollapse = function () {
scope.isDeletionCollapsed = !scope.isDeletionCollapsed
return $timeout(() => scope.$emit('review-panel:layout'))
}
scope.toggleInsertionCollapse = function () {
scope.isInsertionCollapsed = !scope.isInsertionCollapsed
return $timeout(() => scope.$emit('review-panel:layout'))
}
scope.$watch(
'entry.metadata.replaced_content.length',
deletionContentLength =>
(scope.deletionNeedsCollapsing =
deletionContentLength > scope.contentLimit)
)
return scope.$watch(
'entry.content.length',
insertionContentLength =>
(scope.insertionNeedsCollapsing =
insertionContentLength > scope.contentLimit)
)
},
}))
| overleaf/web/frontend/js/ide/review-panel/directives/aggregateChangeEntry.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/directives/aggregateChangeEntry.js",
"repo_id": "overleaf",
"token_count": 738
} | 529 |
/* eslint-disable
camelcase,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.factory('settings', (ide, eventTracking) => ({
saveSettings(data) {
// Tracking code.
for (const key of Array.from(Object.keys(data))) {
const changedSetting = key
const changedSettingVal = data[key]
eventTracking.sendMB('setting-changed', {
changedSetting,
changedSettingVal,
})
}
// End of tracking code.
data._csrf = window.csrfToken
return ide.$http.post('/user/settings', data)
},
saveProjectSettings(data) {
data._csrf = window.csrfToken
return ide.$http.post(`/project/${ide.project_id}/settings`, data)
},
saveProjectAdminSettings(data) {
data._csrf = window.csrfToken
return ide.$http.post(`/project/${ide.project_id}/settings/admin`, data)
},
}))
| overleaf/web/frontend/js/ide/settings/services/settings.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/settings/services/settings.js",
"repo_id": "overleaf",
"token_count": 421
} | 530 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
const inputSuggestionsController = function ($scope, $element, $attrs, Keys) {
const ctrl = this
ctrl.showHint = false
ctrl.hasFocus = false
ctrl.handleFocus = function () {
ctrl.hasFocus = true
return (ctrl.suggestion = null)
}
ctrl.handleBlur = function () {
ctrl.showHint = false
ctrl.hasFocus = false
ctrl.suggestion = null
return ctrl.onBlur()
}
ctrl.handleKeyDown = function ($event) {
if (
($event.which === Keys.TAB || $event.which === Keys.ENTER) &&
ctrl.suggestion != null &&
ctrl.suggestion !== ''
) {
$event.preventDefault()
ctrl.localNgModel += ctrl.suggestion
}
ctrl.suggestion = null
return (ctrl.showHint = false)
}
$scope.$watch('$ctrl.localNgModel', function (newVal, oldVal) {
if (ctrl.hasFocus && newVal !== oldVal) {
ctrl.suggestion = null
ctrl.showHint = false
return ctrl
.getSuggestion({ userInput: newVal })
.then(function (suggestion) {
if (suggestion != null && newVal === ctrl.localNgModel) {
ctrl.showHint = true
return (ctrl.suggestion = suggestion.replace(newVal, ''))
}
})
.catch(() => (ctrl.suggestion = null))
}
})
}
export default App.component('inputSuggestions', {
bindings: {
localNgModel: '=ngModel',
localNgModelOptions: '=?ngModelOptions',
getSuggestion: '&',
onBlur: '&?',
inputId: '@?',
inputName: '@?',
inputPlaceholder: '@?',
inputType: '@?',
inputRequired: '=?',
},
controller: inputSuggestionsController,
template: [
'<div class="input-suggestions">',
'<div class="form-control input-suggestions-shadow">',
'<span ng-bind="$ctrl.localNgModel"',
' class="input-suggestions-shadow-existing"',
' ng-show="$ctrl.showHint">',
'</span>',
'<span ng-bind="$ctrl.suggestion"',
' class="input-suggestions-shadow-suggested"',
' ng-show="$ctrl.showHint">',
'</span>',
'</div>',
'<input type="text"',
' class="form-control input-suggestions-main"',
' ng-focus="$ctrl.handleFocus()"',
' ng-keyDown="$ctrl.handleKeyDown($event)"',
' ng-blur="$ctrl.handleBlur()"',
' ng-model="$ctrl.localNgModel"',
' ng-model-options="$ctrl.localNgModelOptions"',
' ng-model-options="{ debounce: 50 }"',
' ng-attr-id="{{ ::$ctrl.inputId }}"',
' ng-attr-placeholder="{{ ::$ctrl.inputPlaceholder }}"',
' ng-attr-type="{{ ::$ctrl.inputType }}"',
' ng-attr-name="{{ ::$ctrl.inputName }}"',
' ng-required="::$ctrl.inputRequired">',
'</div>',
].join(''),
})
| overleaf/web/frontend/js/main/affiliations/components/inputSuggestions.js/0 | {
"file_path": "overleaf/web/frontend/js/main/affiliations/components/inputSuggestions.js",
"repo_id": "overleaf",
"token_count": 1247
} | 531 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
import './project-list'
import './modal-controllers'
import './tag-controllers'
import './notifications-controller'
import './left-hand-menu-promo-controller'
import '../../services/queued-http'
| overleaf/web/frontend/js/main/project-list/index.js/0 | {
"file_path": "overleaf/web/frontend/js/main/project-list/index.js",
"repo_id": "overleaf",
"token_count": 92
} | 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
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { captureException } from '../infrastructure/error-reporter'
const app = angular.module('ErrorCatcher', [])
const UNHANDLED_REJECTION_ERR_MSG = 'Possibly unhandled rejection: canceled'
app.config([
'$provide',
$provide =>
$provide.decorator('$exceptionHandler', [
'$log',
'$delegate',
($log, $delegate) =>
function (exception, cause) {
if (
exception === UNHANDLED_REJECTION_ERR_MSG &&
cause === undefined
) {
return
}
captureException(exception, scope => {
scope.setTag('handler', 'angular-exception-handler')
return scope
})
return $delegate(exception, cause)
},
]),
])
// Interceptor to check auth failures in all $http requests
// http://bahmutov.calepin.co/catch-all-errors-in-angular-app.html
app.factory('unAuthHttpResponseInterceptor', ($q, $location) => ({
responseError(response) {
// redirect any unauthorised or forbidden responses back to /login
//
// set disableAutoLoginRedirect:true in the http request config
// to disable this behaviour
if (
[401, 403].includes(response.status) &&
!(response.config != null
? response.config.disableAutoLoginRedirect
: undefined)
) {
// for /project urls set the ?redir parameter to come back here
// otherwise just go to the login page
if (window.location.pathname.match(/^\/project/)) {
window.location = `/login?redir=${encodeURI(window.location.pathname)}`
} else {
window.location = '/login'
}
}
// pass the response back to the original requester
return $q.reject(response)
},
}))
app.config([
'$httpProvider',
$httpProvider =>
$httpProvider.interceptors.push('unAuthHttpResponseInterceptor'),
])
| overleaf/web/frontend/js/modules/errorCatcher.js/0 | {
"file_path": "overleaf/web/frontend/js/modules/errorCatcher.js",
"repo_id": "overleaf",
"token_count": 852
} | 533 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import Icon from './icon'
function Processing({ isProcessing }) {
const { t } = useTranslation()
if (isProcessing) {
return (
<div aria-live="polite">
{t('processing')}… <Icon type="fw" modifier="refresh" spin />
</div>
)
} else {
return <></>
}
}
Processing.propTypes = {
isProcessing: PropTypes.bool.isRequired,
}
export default Processing
| overleaf/web/frontend/js/shared/components/processing.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/components/processing.js",
"repo_id": "overleaf",
"token_count": 173
} | 534 |
import { useRef, useState, useLayoutEffect } from 'react'
import classNames from 'classnames'
function useExpandCollapse({
initiallyExpanded = false,
collapsedSize = '0',
dimension = 'height',
classes = {},
} = {}) {
const ref = useRef()
const [isExpanded, setIsExpanded] = useState(initiallyExpanded)
const [sizing, setSizing] = useState({
size: null,
needsExpandCollapse: null,
})
useLayoutEffect(() => {
const expandCollapseEl = ref.current
if (expandCollapseEl) {
const expandedSize =
dimension === 'height'
? expandCollapseEl.scrollHeight
: expandCollapseEl.scrollWidth
const needsExpandCollapse = expandedSize > collapsedSize
if (isExpanded) {
setSizing({ size: expandedSize, needsExpandCollapse })
} else {
setSizing({
size: needsExpandCollapse ? collapsedSize : expandedSize,
needsExpandCollapse,
})
}
}
}, [isExpanded, collapsedSize, dimension])
const expandableClasses = classNames(
'expand-collapse-container',
classes.container,
!isExpanded ? classes.containerCollapsed : null
)
function handleToggle() {
setIsExpanded(!isExpanded)
}
return {
isExpanded,
needsExpandCollapse: sizing.needsExpandCollapse,
expandableProps: {
ref,
style: {
[dimension === 'height' ? 'height' : 'width']: `${sizing.size}px`,
},
className: expandableClasses,
},
toggleProps: {
onClick: handleToggle,
},
}
}
export default useExpandCollapse
| overleaf/web/frontend/js/shared/hooks/use-expand-collapse.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/hooks/use-expand-collapse.js",
"repo_id": "overleaf",
"token_count": 613
} | 535 |
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011–2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
(function ($) {
// Detect touch support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
_mouseDestroy = mouseProto._mouseDestroy,
touchHandled;
/**
* Simulate a mouse event based on a corresponding touch event
* @param {Object} event A touch event
* @param {String} simulatedType The corresponding mouse event
*/
function simulateMouseEvent (event, simulatedType) {
// Ignore multi-touch events
if (event.originalEvent.touches.length > 1) {
return;
}
event.preventDefault();
var touch = event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents');
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
touch.screenX, // screenX
touch.screenY, // screenY
touch.clientX, // clientX
touch.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
/**
* Handle the jQuery UI widget's touchstart events
* @param {Object} event The widget element's touchstart event
*/
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
/**
* Handle the jQuery UI widget's touchmove events
* @param {Object} event The document's touchmove event
*/
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
/**
* Handle the jQuery UI widget's touchend events
* @param {Object} event The document's touchend event
*/
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
/**
* A duck punch of the $.ui.mouse _mouseInit method to support touch events.
* This method extends the widget with bound touch event handlers that
* translate touch events to mouse events and pass them to the widget's
* original mouse event handling methods.
*/
mouseProto._mouseInit = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.bind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
/**
* Remove the touch event handlers
*/
mouseProto._mouseDestroy = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.unbind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse destroy method
_mouseDestroy.call(self);
};
})(jQuery);
| overleaf/web/frontend/js/vendor/libs/jquery.ui.touch-punch.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/jquery.ui.touch-punch.js",
"repo_id": "overleaf",
"token_count": 2001
} | 536 |
import { useEffect } from 'react'
import fetchMock from 'fetch-mock'
/**
* Run callback to mock fetch routes, call restore() when unmounted
*/
export default function useFetchMock(callback) {
useEffect(() => {
return () => {
fetchMock.restore()
}
}, [])
// Running fetchMock.restore() here as well,
// in case there was an error before the component was unmounted.
fetchMock.restore()
// The callback has to be run here, rather than in useEffect,
// so it's run before the component is rendered.
callback(fetchMock)
}
| overleaf/web/frontend/stories/hooks/use-fetch-mock.js/0 | {
"file_path": "overleaf/web/frontend/stories/hooks/use-fetch-mock.js",
"repo_id": "overleaf",
"token_count": 176
} | 537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.