text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
--- title: GetPVarType description: Gets the type (integer, float or string) of a player variable. tags: ["pvar"] --- ## คำอธิบาย Gets the type (integer, float or string) of a player variable. | Name | Description | | -------- | -------------------------------------------------------------- | | playerid | The ID of the player whose player variable to get the type of. | | varname | The name of the player variable to get the type of. | ## ส่งคืน Returns the type of the PVar. See table below. ## ตัวอย่าง ```c stock PrintPVar(playerid, varname[]) { switch(GetPVarType(playerid, varname)) { case PLAYER_VARTYPE_NONE: { return 0; } case PLAYER_VARTYPE_INT: { printf("Integer PVar '%s': %i", varname, GetPVarInt(playerid, varname)); } case PLAYER_VARTYPE_FLOAT: { printf("Float PVar '%s': %f", varname, GetPVarFloat(playerid, varname)); } case PLAYER_VARTYPE_STRING: { new varstring[256]; GetPVarString(playerid, varname, varstring); printf("String PVar '%s': %s", varname, varstring); } } return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPVarInt: Set an integer for a player variable. - GetPVarInt: Get the previously set integer from a player variable. - SetPVarString: Set a string for a player variable. - GetPVarString: Get the previously set string from a player variable. - SetPVarFloat: Set a float for a player variable. - GetPVarFloat: Get the previously set float from a player variable. - DeletePVar: Delete a player variable.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPVarType.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPVarType.md", "repo_id": "openmultiplayer", "token_count": 782 }
424
--- title: GetPlayerColor description: Gets the color of the player's name and radar marker. tags: ["player"] --- ## คำอธิบาย Gets the color of the player's name and radar marker. Only works after SetPlayerColor. | Name | Description | | -------- | ----------------------------------------- | | playerid | The ID of the player to get the color of. | ## ส่งคืน The player's color. 0 if no color set or player not connected. ## ตัวอย่าง ```c SendClientMessage(playerid, GetPlayerColor(playerid), "This message is in your color :)"); new output[144]; format(output, sizeof(output), "You can also use the player's color for {%06x}color embedding!", GetPlayerColor(playerid) >>> 8); SendClientMessage(playerid, -1, output); // will output the message in white, with ''color embedding'' in the player's color ``` ## บันทึก :::warning GetPlayerColor will return nothing (0) unless SetPlayerColor has been used first.Click HERE for a fix. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetPlayerColor](../functions/SetPlayerColor): Set a player's color. - [ChangeVehicleColor](../functions/ChangeVehicleColor): Set the color of a vehicle.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerColor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerColor.md", "repo_id": "openmultiplayer", "token_count": 454 }
425
--- title: GetPlayerObjectModel description: Retrieve the model ID of a player-object. tags: ["player"] --- :::warning ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้! ::: ## คำอธิบาย Retrieve the model ID of a player-object. | Name | Description | | -------- | ------------------------------------------------------------- | | playerid | The ID of the player whose player-object to get the model of | | objectid | The ID of the player-object of which to retrieve the model ID | ## ส่งคืน The model ID of the player object. If the player or object don't exist, it will return -1 or 0 if the player or object does not exist. ## ตัวอย่าง ```c new objectid = CreatePlayerObject(playerid, 1234, 0, 0, 0, 0, 0, 0); new modelid = GetPlayerObjectModel(playerid, objectid); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetObjectModel: Get the model ID of an object.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerObjectModel.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerObjectModel.md", "repo_id": "openmultiplayer", "token_count": 500 }
426
--- title: GetPlayerVehicleID description: This function gets the ID of the vehicle the player is currently in. tags: ["player", "vehicle"] --- ## คำอธิบาย This function gets the ID of the vehicle the player is currently in. Note: NOT the model id of the vehicle. See GetVehicleModel for that. | Name | Description | | -------- | ------------------------------------------------------------------ | | playerid | The ID of the player in the vehicle that you want to get the ID of | ## ส่งคืน ID of the vehicle or 0 if not in a vehicle ## ตัวอย่าง ```c //add 10x Nitro if the player is in a car. Might be called on a command. new vehicle; vehicle = GetPlayerVehicleID(playerid); if (vehicle > 0) { AddVehicleComponent(vehicle, 1010); } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - IsPlayerInVehicle: Check if a player is in a certain vehicle. - IsPlayerInAnyVehicle: Check if a player is in any vehicle. - GetPlayerVehicleSeat: Check what seat a player is in. - GetVehicleModel: Get the model id of a vehicle.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerVehicleID.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerVehicleID.md", "repo_id": "openmultiplayer", "token_count": 434 }
427
--- title: GetServerVarAsBool description: Get the boolean value of a server variable. tags: [] --- :::warning This function, as of 0.3.7 R2, is deprecated. Please see GetConsoleVarAsBool ::: ## คำอธิบาย Get the boolean value of a server variable. | Name | Description | | --------------- | ----------------------------------------------------- | | const varname[] | The name of the boolean variable to get the value of. | ## ส่งคืน The value of the specified server variable. 0 if the specified server variable is not a boolean or doesn't exist. ## ตัวอย่าง ```c public OnGameModeInit() { new queryEnabled = GetServerVarAsBool("query"); if (!queryEnabled) { print("WARNING: Querying is disabled. The server will appear offline in the server browser."); } return 1; } ``` ## บันทึก :::tip Type 'varlist' in the server console to display a list of available server variables and their types. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetServerVarAsString: Retreive a server variable as a string. - GetServerVarAsInt: Retreive a server variable as an integer.
openmultiplayer/web/docs/translations/th/scripting/functions/GetServerVarAsBool.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetServerVarAsBool.md", "repo_id": "openmultiplayer", "token_count": 475 }
428
--- title: GetVehiclePos description: Gets the position of a vehicle. tags: ["vehicle"] --- ## คำอธิบาย Gets the position of a vehicle. | Name | Description | | --------- | ------------------------------------------------------------------------- | | vehicleid | The ID of the vehicle to get the position of. | | &Float:x | A float variable in which to store the X coordinate, passed by reference. | | &Float:y | A float variable in which to store the Y coordinate, passed by reference. | | &Float:z | A float variable in which to store the Z coordinate, passed by reference. | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. The vehicle specified does not exist. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp(cmdtext, "/vehpos", true) == 0) { new currentveh; currentveh = GetPlayerVehicleID(playerid); new Float:vehx, Float:vehy, Float:vehz; GetVehiclePos(currentveh, vehx, vehy, vehz); new vehpostext[96]; format(vehpostext, sizeof(vehpostext), "The current vehicle positions are: %f, %f, %f", vehx, vehy, vehz); SendClientMessage(playerid, 0xFFFFFFFF, vehpostext); return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetVehicleDistanceFromPoint: Get the distance between a vehicle and a point. - SetVehiclePos: Set the position of a vehicle. - GetVehicleZAngle: Check the current angle of a vehicle. - GetVehicleRotation: Get the rotation of a vehicle on the XYZ axis.
openmultiplayer/web/docs/translations/th/scripting/functions/GetVehiclePos.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetVehiclePos.md", "repo_id": "openmultiplayer", "token_count": 704 }
429
--- title: IsPlayerAdmin description: Check if a player is logged in as an RCON admin. tags: ["administration"] --- ## คำอธิบาย Check if a player is logged in as an RCON admin. | Name | Description | | -------- | ------------------------------ | | playerid | The ID of the player to check. | ## ส่งคืน 1: Player is an RCON admin. 0: Player is NOT an RCON admin. ## ตัวอย่าง ```c public OnPlayerSpawn(playerid) { if (IsPlayerAdmin(playerid)) { SendClientMessageToAll(0xDEEE20FF, "An admin spawned."); } return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SendRconCommand](../../scripting/functions/SendRconCommand.md): Sends an RCON command via the script. ## Related Callbacks - [OnRconLoginAttempt](../../scripting/callbacks/OnRconLoginAttempt.md): Called when an attempt to login to RCON is made.
openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerAdmin.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerAdmin.md", "repo_id": "openmultiplayer", "token_count": 386 }
430
--- title: IsVehicleStreamedIn description: Checks if a vehicle is streamed in for a player. tags: ["vehicle"] --- ## คำอธิบาย Checks if a vehicle is streamed in for a player. Only nearby vehicles are streamed in (visible) for a player. | Name | Description | | ----------- | ------------------------------- | | vehicleid | The ID of the vehicle to check. | | forplayerid | The ID of the player to check. | ## ส่งคืน 0: Vehicle is not streamed in for the player, or the function failed to execute (player and/or vehicle do not exist). 1: Vehicle is streamed in for the player. ## ตัวอย่าง ```c new streamedVehicleCount; for(new v = 1; v <= MAX_VEHICLES; v++) { if (IsVehicleStreamedIn(v, playerid)) { streamedVehicleCount++; } } new szString[144]; format(szString, sizeof(szString), "You currently have %i vehicles streamed in to your game.", streamedVehicleCount); SendClientMessage(playerid, -1, szString); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [IsPlayerStreamedIn](../../scripting/functions/IsPlayerStreamedIn.md): Checks if a player is streamed in for another player. - [OnVehicleStreamIn](../../scripting/callbacks/OnVehicleStreamIn.md): Called when a vehicle streams in for a player. - [OnVehicleStreamOut](../../scripting/callbacks/OnVehicleStreamOut.md): Called when a vehicle streams out for a player. - [OnPlayerStreamIn](../../scripting/callbacks/OnPlayerStreamIn.md): Called when a player streams in for another player. - [OnPlayerStreamOut](../../scripting/callbacks/OnPlayerStreamOut.md): Called when a player streams out for another player.
openmultiplayer/web/docs/translations/th/scripting/functions/IsVehicleStreamedIn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsVehicleStreamedIn.md", "repo_id": "openmultiplayer", "token_count": 590 }
431
--- title: NetStats_MessagesSent description: Gets the number of messages the server has sent to the player. tags: [] --- ## คำอธิบาย Gets the number of messages the server has sent to the player. | Name | Description | | -------- | ------------------------------------------ | | playerid | The ID of the player to get the data from. | ## ส่งคืน The number of messages the server has sent to the player. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid,cmdtext[]) { if (!strcmp(cmdtext, "/msgsent")) { new szString[144]; format(szString, sizeof(szString), "You have recieved %i network messages.", NetStats_MessagesSent(playerid)); SendClientMessage(playerid, -1, szString); } return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [GetPlayerNetworkStats](../functions/GetPlayerNetworkStats.md): Gets a player networkstats and saves it into a string. - [GetNetworkStats](../functions/GetNetworkStats.md): Gets the servers networkstats and saves it into a string. - [NetStats_GetConnectedTime](../functions/NetStats_GetConnectedTime.md): Get the time that a player has been connected for. - [NetStats_MessagesReceived](../functions/NetStats_MessagesReceived.md): Get the number of network messages the server has received from the player. - [NetStats_BytesReceived](../functions/NetStats_BytesReceived.md): Get the amount of information (in bytes) that the server has received from the player. - [NetStats_BytesSent](../functions/NetStats_BytesSent.md): Get the amount of information (in bytes) that the server has sent to the player. - [NetStats_MessagesRecvPerSecond](../functions/NetStats_MessagesRecvPerSecond.md): Get the number of network messages the server has received from the player in the last second. - [NetStats_PacketLossPercent](../functions/NetStats_PacketLossPercent.md): Get a player's packet loss percent. - [NetStats_ConnectionStatus](../functions/NetStats_ConnectionStatus.md): Get a player's connection status. - [NetStats_GetIpPort](../functions/NetStats_GetIpPort.md): Get a player's IP and port.
openmultiplayer/web/docs/translations/th/scripting/functions/NetStats_MessagesSent.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/NetStats_MessagesSent.md", "repo_id": "openmultiplayer", "token_count": 735 }
432
--- title: PlayerTextDrawSetPreviewModel description: Sets a player textdraw 2D preview sprite of a specified model ID. tags: ["player", "textdraw", "playertextdraw"] --- ## คำอธิบาย Sets a player textdraw 2D preview sprite of a specified model ID. | Name | Description | | ---------- | ------------------------------------------------- | | playerid | The PlayerTextDraw player ID. | | text | The textdraw id that will display the 3D preview. | | modelindex | The GTA SA or SA:MP model ID to display. | ## ส่งคืน 1: The function was executed successfully. If an invalid model is passed 'success' is reported, but the model will appear as a yellow/black question mark. 0: The function failed to execute. Player and/or textdraw do not exist. ## ตัวอย่าง ```c new PlayerText:textdraw; public OnPlayerConnect(playerid) { textdraw = CreatePlayerTextDraw(playerid, 320.0, 240.0, "_"); PlayerTextDrawFont(playerid, textdraw, TEXT_DRAW_FONT_MODEL_PREVIEW); PlayerTextDrawUseBox(playerid, textdraw, true); PlayerTextDrawBoxColor(playerid, textdraw, 0x000000FF); PlayerTextDrawTextSize(playerid, textdraw, 40.0, 40.0); PlayerTextDrawSetPreviewModel(playerid, textdraw, 411); // Show an Infernus (model 411) //PlayerTextDrawSetPreviewModel(playerid, textdraw, 0); //Display model 0 (CJ Skin) //PlayerTextDrawSetPreviewModel(playerid, textdraw, 18646); //Display model 18646 (police light object) PlayerTextDrawShow(playerid, textdraw); return 1; } ``` ## บันทึก :::warning The textdraw MUST use the font type `TEXT_DRAW_FONT_MODEL_PREVIEW` in order for this function to have effect. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [PlayerTextDrawSetPreviewRot](PlayerTextDrawSetPreviewRot): Set rotation of a 3D player textdraw preview. - [PlayerTextDrawSetPreviewVehCol](PlayerTextDrawSetPreviewVehCol): Set the colours of a vehicle in a 3D player textdraw preview. - [PlayerTextDrawFont](PlayerTextDrawFont): Set the font of a player-textdraw. ## Related Callbacks - [OnPlayerClickPlayerTextDraw](../callbacks/OnPlayerClickPlayerTextDraw): Called when a player clicks on a player-textdraw.
openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawSetPreviewModel.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawSetPreviewModel.md", "repo_id": "openmultiplayer", "token_count": 817 }
433
--- title: RepairVehicle description: Fully repairs a vehicle, including visual damage (bumps, dents, scratches, popped tires etc. tags: ["vehicle"] --- ## คำอธิบาย Fully repairs a vehicle, including visual damage (bumps, dents, scratches, popped tires etc.). | Name | Description | | --------- | -------------------------------- | | vehicleid | The ID of the vehicle to repair. | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. This means the vehicle specified does not exist. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp("/repair", cmdtext)) { if (!IsPlayerInAnyVehicle(playerid)) return SendClientMessage(playerid, 0xFFFFFFFF, "You are not in a vehicle!"); RepairVehicle(GetPlayerVehicleID(playerid)); SendClientMessage(playerid, 0xFFFFFFFF, "Your vehicle has been repaired!"); return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetVehicleHealth](../functions/SetVehicleHealth.md): Set the health of a vehicle. - [GetVehicleHealth](../functions/GetVehicleHealth.md): Check the health of a vehicle.
openmultiplayer/web/docs/translations/th/scripting/functions/RepairVehicle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/RepairVehicle.md", "repo_id": "openmultiplayer", "token_count": 470 }
434
--- title: SetActorPos description: Set the position of an actor. tags: [] --- :::warning ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้! ::: ## คำอธิบาย Set the position of an actor. | Name | Description | | ------- | -------------------------------------------------------------------- | | actorid | The ID of the actor to set the position of. Returned by CreateActor. | | X | The X coordinate to position the actor at. | | Y | The Y coordinate to position the actor at. | | Z | The Z coordinate to position the actor at. | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. The actor specified does not exist. ## ตัวอย่าง ```c new MyActor; public OnGameModeInit() { MyActor = CreateActor(...); return 1; } // Somewhere else SetActorPos(MyActor, 1.0, 2.0, 3.0); ``` ## บันทึก :::tip When creating an actor with CreateActor, you specify it's position. You do not need to use this function unless you want to change its position later. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetActorPos: Get the position of an actor. - CreateActor: Create an actor (static NPC).
openmultiplayer/web/docs/translations/th/scripting/functions/SetActorPos.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetActorPos.md", "repo_id": "openmultiplayer", "token_count": 693 }
435
--- title: SetPVarString description: Saves a string into a player variable. tags: ["pvar"] --- ## คำอธิบาย Saves a string into a player variable. | Name | Description | | ------------ | ------------------------------------------------------- | | playerid | The ID of the player whose player variable will be set. | | varname | The name of the player variable. | | string_value | The string you want to save in the player variable. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c public OnPlayerConnect(playerid) { new h,m,s,str[50]; gettime(h,m,s); // get the time format(str,50,"Connected: %d:%d:%d",h,m,s); // create the string with the connect time SetPVarString(playerid,"timeconnected",str); // save the string into a player variable return 1; } ``` ## บันทึก :::tip Variables aren't reset until after OnPlayerDisconnect is called, so the values are still accessible in OnPlayerDisconnect. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPVarInt: Set an integer for a player variable. - GetPVarInt: Get the previously set integer from a player variable. - GetPVarString: Get the previously set string from a player variable. - SetPVarFloat: Set a float for a player variable. - GetPVarFloat: Get the previously set float from a player variable. - DeletePVar: Delete a player variable.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPVarString.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPVarString.md", "repo_id": "openmultiplayer", "token_count": 582 }
436
--- title: SetPlayerMapIcon description: Place an icon/marker on a player's map. tags: ["player"] --- ## คำอธิบาย Place an icon/marker on a player's map. Can be used to mark locations such as banks and hospitals to players. | Name | Description | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | playerid | The ID of the player to set the map icon for. | | iconid | The player's icon ID, ranging from 0 to 99. This means there is a maximum of 100 map icons. ID can be used in [RemovePlayerMapIcon](/docs/scripting/functions/RemovePlayerMapIcon). | | Float:x | The X coordinate to place the map icon at. | | Float:y | The Y coordinate to place the map icon at. | | Float:z | The Z coordinate to place the map icon at. | | markertype | The [icon](/docs/scripting/resources/mapicons) to set. | | color | The color of the icon, as an integer or hex in RGBA color format. This should only be used with the square icon (ID: 0). | | style | The [style](/docs/scripting/resources/mapiconstyles) of icon. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. Player is not connected. ## ตัวอย่าง ```c public OnPlayerConnect( playerid ) { // This example demonstrates how to create a dollar-icon on top of a 24/7 located // in Las Venturas. This way new players know where to go with their money! SetPlayerMapIcon(playerid, 12, 2204.9468, 1986.2877, 16.7380, 52, 0, MAPICON_LOCAL); } ``` ## บันทึก :::tip If you use an invalid marker type, it will create ID 1 (White Square). If you use an icon ID that is already in use, it will replace the current map icon using that ID. ::: :::warning You can only have 100 map icons! Marker type 1 (![](/images/mapIcons/icon1.gif)), 2 (![](/images/mapIcons/icon2.gif)), 4 (![](/images/mapIcons/icon4.gif)), and 56 (![](/images/mapIcons/icon56.gif)) will cause your game to crash if you have map legends enabled while viewing the map. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [RemovePlayerMapIcon](/docs/scripting/functions/RemovePlayerMapIcon): Remove a map icon for a player. - [SetPlayerMarkerForPlayer](/docs/scripting/functions/SetPlayerMarkerForPlayer): Set a player's marker.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerMapIcon.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerMapIcon.md", "repo_id": "openmultiplayer", "token_count": 1805 }
437
--- title: SetPlayerTeam description: Set the team of a player. tags: ["player"] --- ## คำอธิบาย Set the team of a player. | Name | Description | | -------- | ------------------------------------------------------------------------------ | | playerid | The ID of the player you want to set the team of. | | teamid | The team to put the player in. Use NO_TEAM to remove the player from any team. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c public OnPlayerSpawn(playerid) { // Set a player's team to 4 when they spawn SetPlayerTeam(playerid, 4); return 1; } ``` ## บันทึก :::tip - Players can not damage/kill players on the same team unless they use a knife to slit their throat. - Players are also unable to damage vehicles driven by a player from the same team. This can be enabled with EnableVehicleFriendlyFire. - 255 (or `NO_TEAM`) is the default team to be able to shoot other players, not 0. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetPlayerTeam: Check what team a player is on. - SetTeamCount: Set the number of teams available. - EnableVehicleFriendlyFire: Enable friendly fire for team vehicles.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerTeam.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerTeam.md", "repo_id": "openmultiplayer", "token_count": 524 }
438
--- title: ShowPlayerNameTagForPlayer description: This functions allows you to toggle the drawing of player nametags, healthbars and armor bars which display above their head. tags: ["player"] --- ## คำอธิบาย This functions allows you to toggle the drawing of player nametags, healthbars and armor bars which display above their head. For use of a similar function like this on a global level, ShowNameTags function. | Name | Description | | ------------ | ------------------------------------------------ | | playerid | Player who will see the results of this function | | showplayerid | Player whose name tag will be shown or hidden | | show | 1-show name tag, 0-hide name tag | ## ส่งคืน ImportantNote ShowNameTags must be set to 1 to be able to show name tags with ShowPlayerNameTagForPlayer, that means that in order to be effective you need to ShowPlayerNameTagForPlayer(forplayerid, playerid, 0) ahead of time(OnPlayerStreamIn is a good spot). ## ตัวอย่าง ```c //The player who typed /nameoff will not be able to see any other players nametag. if (strcmp("/nameoff", cmdtext, true) == 0) { for(new i = GetPlayerPoolSize(); i != -1; --i) ShowPlayerNameTagForPlayer(playerid, i, false); GameTextForPlayer(playerid, "~W~Nametags ~R~off", 5000, 5); return 1; } ``` ## บันทึก :::warning ShowNameTags must be set to 1 to be able to show name tags with ShowPlayerNameTagForPlayer, that means that in order to be effective you need to ShowPlayerNameTagForPlayer(forplayerid, playerid, 0) ahead of time(OnPlayerStreamIn is a good spot). ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - ShowNameTags: Set nametags on or off. - DisableNameTagLOS: Disable nametag Line-Of-Sight checking. - SetPlayerMarkerForPlayer: Set a player's marker.
openmultiplayer/web/docs/translations/th/scripting/functions/ShowPlayerNameTagForPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ShowPlayerNameTagForPlayer.md", "repo_id": "openmultiplayer", "token_count": 679 }
439
--- title: TextDrawHideForPlayer description: Hides a textdraw for a specific player. tags: ["player", "textdraw"] --- ## คำอธิบาย Hides a textdraw for a specific player. | Name | Description | | -------- | ----------------------------------------------------------- | | playerid | The ID of the player that the textdraw should be hidden for | | text | The ID of the textdraw to hide | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new Text:Textdraw[MAX_PLAYERS]; public OnPlayerConnect(playerid) { Textdraw[playerid] = TextDrawCreate( ... ); return 1; } public OnPlayerDisconnect(playerid, reason) { TextDrawDestroy(Textdraw[playerid]); return 1; } public OnPlayerSpawn(playerid) { TextDrawShowForPlayer(playerid, Textdraw[playerid]); return 1; } public OnPlayerDeath(playerid, reason) { TextDrawHideForPlayer(playerid, Textdraw[playerid]); return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players. - [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player. - [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players.
openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawHideForPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawHideForPlayer.md", "repo_id": "openmultiplayer", "token_count": 567 }
440
--- title: TogglePlayerControllable description: Toggles whether a player can control their character or not. tags: ["player"] --- ## คำอธิบาย Toggles whether a player can control their character or not. The player will also be unable to move their camera. | Name | Description | | -------- | ----------------------------------------------------------- | | playerid | The ID of the player to toggle the controllability of | | toggle | 0 to make them uncontrollable, 1 to make them controllable. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. The player specified does not exist. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { // Freezes a player when they types /freezeme if (strcmp(cmdtext, "/freezeme", true) == 0) { TogglePlayerControllable(playerid,0); return 1; } // Unfreezes a player when they types /unfreezeme if (strcmp(cmdtext, "/unfreezeme", true) == 0) { TogglePlayerControllable(playerid,1); return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน
openmultiplayer/web/docs/translations/th/scripting/functions/TogglePlayerControllable.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TogglePlayerControllable.md", "repo_id": "openmultiplayer", "token_count": 516 }
441
--- title: db_field_name description: Returns the name of a field at a particular index. tags: ["sqlite"] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Returns the name of a field at a particular index. | Name | Description | | ----------------- | ------------------------------------------------------ | | DBResult:dbresult | The result to get the data from; returned by db_query. | | field | The index of the field to get the name of. | | result[] | The result. | | maxlength | The max length of the field. | ## ส่งคืน Returns 1, if the function was successful, otherwise 0 if DBResult:dbresult is a NULL reference or the column index not available. ## ตัวอย่าง ```c // Callback public OnPlayerCommandText(playerid, cmdtext[]) { // If "cmdtext" equals "/getfieldnames" if (!strcmp(cmdtext, "/getfieldnames", true, 14)) { // Declare "db_result", "i", and "columns" new DBResult:db_result = db_query(db_handle, "SELECT * FROM `join_log`"), i, columns = db_num_fields(db_result), info[30]; // Iterate from 0 to "columns-1" for(; i < columns; i++) { // Store the name of the i indexed column name into "info" db_field_name(db_result, i, info, sizeof info); // Print "info" printf("Field name: %s", info); } // Frees the result db_free_result(db_result); // Returns 1 return 1; } // Returns 0 return 0; } ``` ## บันทึก :::warning Using an invalid handle will crash your server! Get a valid handle by using db_query. But it's protected against NULL references. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - db_open: Open a connection to an SQLite database - db_close: Close the connection to an SQLite database - db_query: Query an SQLite database - db_free_result: Free result memory from a db_query - db_num_rows: Get the number of rows in a result - db_next_row: Move to the next row - db_num_fields: Get the number of fields in a result - db_field_name: Returns the name of a field at a particular index - db_get_field: Get content of field with specified ID from current result row - db_get_field_assoc: Get content of field with specified name from current result row - db_get_field_int: Get content of field as an integer with specified ID from current result row - db_get_field_assoc_int: Get content of field as an integer with specified name from current result row - db_get_field_float: Get content of field as a float with specified ID from current result row - db_get_field_assoc_float: Get content of field as a float with specified name from current result row - db_get_mem_handle: Get memory handle for an SQLite database that was opened with db_open. - db_get_result_mem_handle: Get memory handle for an SQLite query that was executed with db_query. - db_debug_openfiles - db_debug_openresults
openmultiplayer/web/docs/translations/th/scripting/functions/db_field_name.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/db_field_name.md", "repo_id": "openmultiplayer", "token_count": 1203 }
442
--- title: existproperty description: Check if a property exist. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Check if a property exist. | 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. | ## ส่งคืน True if the property exists and false otherwise. ## ตัวอย่าง ```c if ( existproperty(0, "", 123984334) ) { //the property exists, do something } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetProperty](../functions/SetProperty): Set a property. - [GetProperty](../functions/GetProperty): Get the value of a property. - [DeleteProperty](../functions/DeleteProperty): Delete a property.
openmultiplayer/web/docs/translations/th/scripting/functions/existproperty.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/existproperty.md", "repo_id": "openmultiplayer", "token_count": 466 }
443
--- title: floatpower description: Raises the given value to the power of the exponent. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Raises the given value to the power of the exponent. | Name | Description | | -------- | ------------------------------------------------------------------------- | | value | The value to raise to a power, as a floating-point number. | | exponent | The exponent is also a floating-point number. It may be zero or negative. | ## ส่งคืน The result of 'value' to the power of 'exponent'. ## ตัวอย่าง ```c printf("2 to the power of 8 is %f", floatpower(2.0, 8.0)); // Result: 256.0 ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [floatsqroot](../functions/floatsqroot): Calculate the square root of a floating point value. - [floatlog](../functions/floatlog): Get the logarithm of the float value.
openmultiplayer/web/docs/translations/th/scripting/functions/floatpower.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatpower.md", "repo_id": "openmultiplayer", "token_count": 419 }
444
--- title: fwrite description: Write text into a file. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Write text into a file. | Name | Description | | ------ | ------------------------------------------------------- | | handle | The handle of the file to write to (returned by fopen). | | string | The string of text to write in to the file. | ## ส่งคืน The length of the written string as an integer. ## ตัวอย่าง ```c // Open "file.txt" in "write only" mode new File:handle = fopen("file.txt", io_write); // Check, if file is open if (handle) { // Success // Write "I just wrote here!" into this file fwrite(handle, "I just wrote here!"); // Close the file fclose(handle); } else { // Error print("Failed to open file \"file.txt\"."); } // Open "file.txt" in "read and write" mode new File:handle = fopen("file.txt"), // Initialize "buf" buf[128]; // Check, if file is open if (handle) { // Success // Read the whole file while(fread(handle, buf)) print(buf); // Set the file pointer to the first byte fseek(handle, _, seek_begin); // Write "I just wrote here!" into this file fwrite(handle, "I just wrote here!"); // Close the file fclose(handle); } else { // Error print("The file \"file.txt\" does not exists, or can't be opened."); } // Open "file.txt" in "append only" mode new File:handle = fopen("file.txt", io_append); // Check, if file is open if (handle) { // Success // Append "This is a text.\r\n" fwrite(handle, "This is a test.\r\n"); // Close the file fclose(handle); } else { // Error print("Failed to open file \"file.txt\"."); } ``` ## บันทึก :::tip This functions writes to the file in UTF-8, which does not support some localized language symbols. ::: :::warning Using an invalid handle will crash your server! Get a valid handle by using fopen or ftemp. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [fopen](../functions/fopen): Open a file. - [fclose](../functions/fclose): Close 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/fwrite.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fwrite.md", "repo_id": "openmultiplayer", "token_count": 1127 }
445
--- title: uudecode description: Decode an UU-encoded string. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Decode an UU-encoded string. | Name | Description | | -------------- | --------------------------------------------- | | dest[] | The destination for the decoded string array. | | const source[] | The UU-encoded source string. | | maxlength | The maximum length of dest that can be used. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c uudecode(normalString, encodedString); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน
openmultiplayer/web/docs/translations/th/scripting/functions/uudecode.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/uudecode.md", "repo_id": "openmultiplayer", "token_count": 336 }
446
--- title: Camera Modes --- A list of possible camera modes to be used with [GetPlayerCameraMode](../functions/GetPlayerCameraMode). :::note Note that there might still be more usable IDs hidden away in the game and some IDs are used for more than one situation. ::: - `3` - Train/tram camera. - `4` - Follow ped (normal behind player camera). - `7` - Sniper aiming. - `8` - Rocket Launcher aiming. - `15` - Fixed camera (non-moving) - used for Pay 'n' Spray, chase camera, tune shops, entering buildings, buying food etc. - `16` - Vehicle front camera, bike side camera. - `18` - Normal car (+skimmer+helicopter+airplane), several variable distances. - `22` - Normal boat camera. - `46` - Camera weapon aiming. - `51` - Heat-seeking Rocket Launcher aiming. - `53` - Aiming any other weapon - `55` - Vehicle passenger drive-by camera. - `56` - Chase camera: helicopter/bird view. - `57` - Chase camera: ground camera, zooms in very quickly. (Similar to 56, but on the ground.) - `58` - Chase camera: horizontal flyby past vehicle. - `59` - Chase camera (for air vehicles only): ground camera, looking up to the air vehicle. - `62` - Chase camera (for air vehicles only): vertical flyby past air vehicle. - `63` - Chase camera (for air vehicles only): horizontal flyby past air vehicle (similar to 58 and 62). - `64` - Chase camera (for air vehicles only): camera focused on pilot, similar to pressing LOOK_BEHIND key on foot, but in air vehicle.
openmultiplayer/web/docs/translations/th/scripting/resources/cameramode.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/cameramode.md", "repo_id": "openmultiplayer", "token_count": 406 }
447
--- title: Record Types description: Record types to be used with [StartRecordingPlayerData]()../functions/StartRecordingPlayerData.md) tags: ["player"] sidebar_label: Record Types --- Record types to be used with [StartRecordingPlayerData](../functions/StartRecordingPlayerData.md) | Type | Value | | ---------------------------- | ----- | | PLAYER_RECORDING_TYPE_NONE | (0) | | PLAYER_RECORDING_TYPE_DRIVER | (1) | | PLAYER_RECORDING_TYPE_ONFOOT | (2) |
openmultiplayer/web/docs/translations/th/scripting/resources/recordtypes.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/recordtypes.md", "repo_id": "openmultiplayer", "token_count": 180 }
448
--- title: Vehicle Information Types description: Vehicle Information Type Constants --- | Vehicle Information Type | Description | | --------------------------------- | ----------------------------------------------------------------- | | VEHICLE_MODEL_INFO_SIZE | Vehicle size | | VEHICLE_MODEL_INFO_FRONTSEAT | Position of the front seat\* | | VEHICLE_MODEL_INFO_REARSEAT | Position of the rear seat\* | | VEHICLE_MODEL_INFO_PETROLCAP | Position of the fuel cap\* | | VEHICLE_MODEL_INFO_WHEELSFRONT | Position of the front wheels\* | | VEHICLE_MODEL_INFO_WHEELSREAR | Position of the rear wheels\* | | VEHICLE_MODEL_INFO_WHEELSMID | Position of the middle wheels (applies to vehicles with 3 axes)\* | | VEHICLE_MODEL_INFO_FRONT_BUMPER_Z | Height of the front bumper | | VEHICLE_MODEL_INFO_REAR_BUMPER_Z | Height of the rear bumper | \* = These values are calculated from the center of the vehicle. ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [GetVehicleModelInfo](/docs/scripting/functions/GetVehicleModelInfo): Retrieve information about a specific vehicle model such as the size or position of seats.
openmultiplayer/web/docs/translations/th/scripting/resources/vehicleinformationtypes.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/vehicleinformationtypes.md", "repo_id": "openmultiplayer", "token_count": 790 }
449
--- title: OnPlayerClickMap description: Bu callback oyuncu haritada bir yer işaretlediğinde çağrılır. tags: ["player"] --- ## Açıklama Bu callback oyuncu haritada bir yer işaretlediğinde çağrılır. | Ad | Açıklama | | -------- | --------------------------------------------------------------- | | playerid | Oyuncunun id'si | | Float:fX | İşaretlediği yerin X koordinatı. | | Float:fY | İşaretlediği yerin Y koordinatı. | | Float:fZ | İşaretlediği yerin Z koordinatı. (kullanışsız - notu inceleyin) | ## Çalışınca Vereceği Sonuçlar 1 - Diğer filterscriptlerin bu callbacki çalıştırmasını engeller. 0 - Diğer filterscriptler içinde aranması için pas geçilir. Her zaman öncelikle oyun modunda çağrılır. ## Örnekler ```c public OnPlayerClickMap(playerid, Float:fX, Float:fY, Float:fZ) { SetPlayerPosFindZ(playerid, fX, fY, fZ); return 1; } ``` ## Notlar :::tip Bu callback sadece haritada bir yer işaretlemek için tıkladığında çağrılır, tuşa basarak işaretlediğinde çağrılmaz. Eğer oyuncu işaretlediği yerden uzaksa Z koordinatı 0 (geçersiz) olarak döndürülür, bunu çözmek için ColAndreas veya MapAndreas pluginini kullanın. ::: ## Bağlı Fonksiyonlar
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerClickMap.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerClickMap.md", "repo_id": "openmultiplayer", "token_count": 722 }
450
--- title: OnPlayerGiveDamage description: This callback is called when a player gives damage to another player. tags: ["player"] --- ## Açıklama Bu callback, bir oyuncu başka bir oyuncuya hasar verdiğinde çağırılır. | İsim | Açıklama | |-----------------|---------------------------------------------------------| | playerid | Hasar veren oyuncunun ID'si. | | damagedid | Hasar alan oyuncunun ID'si. | | Float:amount | Hasar olan oyuncunun aldığı hasar miktarı. | | WEAPON:weaponid | Hasar alan oyuncunun hasar alma nedeni. | | bodypart | Hasar alan oyuncuda hasarın isabet ettiği vücut bölümü. | ## Çalışınca Vereceği Sonuçlar 1 - Callback diğer filterscriptlerde çağırılmayacak. 0 - Callbackin diğer filterscriptlerde çağırılmasına olanak tanır. Filterscriptlerde her zaman ilk çağırılan callbacktir, yani 1 değerini döndürmek diğer filterscriptlerin bunu görmesini engeller. ## Örnekler ```c public OnPlayerGiveDamage(playerid, damagedid, Float:amount, WEAPON:weaponid, bodypart) { new string[128], victim[MAX_PLAYER_NAME], attacker[MAX_PLAYER_NAME]; new weaponname[24]; GetPlayerName(playerid, attacker, sizeof (attacker)); GetPlayerName(damagedid, victim, sizeof (victim)); GetWeaponName(weaponid, weaponname, sizeof (weaponname)); format(string, sizeof(string), "%s, %s isimli oyuncuya %.0f hasar verdi, silah: %s, vücut bölümü: %d", attacker, victim, amount, weaponname, bodypart); SendClientMessageToAll(0xFFFFFFFF, string); return 1; } ``` ## Notlar :::tip Bu fonksiyonun bazı durumlarda yanlış olabileceğini unutmayın. Eğer bir oyuncunun başka bir oyuncudan hasar almasını engellemek istiyorsanız SetPlayerTeam kullanın. Herhangi bir ateş kaynağından gelen hasarlarda(örnek: molotov, 18) weaponid değeri 37 (flame thrower) olarak döndürülür. Herhangi bir patlama kaynağından gelen hasarlarda (örnek: roketatar, el bombası) weapondid değeri 51 olarak geri döndürülür. Yalnızca playerid bu callbacki çağırabilir. amount değeri her zaman silahın verebileceği maksimum değeri geri döndürür, oyuncunun canı silahın verdiği hasardan az olsa dahi amount değerinde maksimum silah hasarı görülür. Örnek: Oyuncunun 25 canı var ve Desert Eagle 46.2 hasar veriyor, Desert Eagle ile ateş edildiğinde 25 değil 46.2 değeri amount olarak geri döndürülür. :::
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerGiveDamage.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerGiveDamage.md", "repo_id": "openmultiplayer", "token_count": 1091 }
451
--- title: OnPlayerStreamOut description: Bu fonksiyon, bir oyuncu başka bir oyuncunun istemcisinden stream alanından çıktığında çağrılır. tags: ["player"] --- ## Açıklama Bu fonksiyon, bir oyuncu başka bir oyuncunun istemcisinden stream alanından çıktığında çağrılır. | Parametre | Açıklama | | ----------- | ----------------------------------------------- | | playerid | Diğer oyuncuyu canlı olarak görülen oyuncu. | | forplayerid | Diğer oyuncuyu canlı olarak gören oyuncu. | ## Çalışınca Vereceği Sonuçlar Filterscript komutlarında her zaman ilk olarak çağrılır. ## Örnekler ```c public OnPlayerStreamOut(playerid, forplayerid) { new string[80]; format(string, sizeof(string), "Streamer bölgenizden %d ID'li oyuncu kaldırıldı.", playerid); SendClientMessage(forplayerid, 0xFF0000FF, string); return 1; } ``` ## Notlar <TipNPCCallbacks />
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerStreamOut.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerStreamOut.md", "repo_id": "openmultiplayer", "token_count": 429 }
452
--- title: OnVehicleStreamIn description: Called when a vehicle is streamed to a player's client. tags: ["vehicle"] --- ## Açıklama Bir araç, oyuncunun işlem alanına girdiğinde çağırılıyor. | İsim | Açıklama | | ----------- | ------------------------------------------------------ | | vehicleid | Oyuncunun işlem aracına giren aracın ID'si. | | forplayerid | İşlem alanına araç giren oyuncunun ID'si. | ## Çalışınca Vereceği Sonuçlar Her zaman ilk olarak filterscriptlerde çağırılır. ## Örnekler ```c public OnVehicleStreamIn(vehicleid, forplayerid) { new string[32]; format(string, sizeof(string), "Şuanda ID'si %d olan aracı görebiliyorsun.", vehicleid); SendClientMessage(forplayerid, 0xFFFFFFFF, string); return 1; } ``` ## Notlar <TipNPCCallbacks /> ## Bağlantılı Fonksiyonlar
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleStreamIn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleStreamIn.md", "repo_id": "openmultiplayer", "token_count": 418 }
453
--- title: ApplyActorAnimation description: Aktörlere animasyon yaptırma. tags: [] --- <VersionWarnTR version='SA-MP 0.3.7' /> ## Açıklama Bu fonksiyon aktörlere animasyon uygulatmak için kullanılır. | Parametre | Açıklama | | ---------- | ----------------------------------------------------------------------------------------------------------------------- | | actorid | Animasyonun uygulanacağı aktörün ID'si | | animlib[] | Uygulanacak animasyonun kütüphanesi | | animname[] | Uygulanacak animasyonun ismi | | fDelta | Animasyon oynatma hızı (4.1 tavsiye edilir) | | loop | Döngü (Eğer 1 seçilirse animasyon sürekli oynatılır. Eğer 0 seçilirse animasyon bir defa oynatılır.) | | lockx | Eğer 0 seçilirse aktör animasyon bittikten sonra başlamadan önceki koordinatlarına döner | | locky | Üsttekinin aynısı ancak Y ekseni için geçerlidir | | freeze | Eğer 1 seçilirse animasyon sonunda aktör dondurulur, hareket edemez. 0 ise tam tersidir | | time | Milisaniye cinsinden animasyon süresi. Eğer 0 seçilirse sonsuz kez animasyon oynatılır | ## Çalışınca Vereceği Sonuçlar 1: Fonksiyon başarıyla çalıştı. 0: Fonksiyon çalışamadı. Hatalı aktör ID'si. ## Örnekler ```c new gMyActor; public OnGameModeInit() { gMyActor = CreateActor(179, 316.1, -134.0, 999.6, 90.0); // Ammunation'daki satıcıdan yaratıyoruz ApplyActorAnimation(gMyActor, "DEALER", "shop_pay", 4.1, 0, 0, 0, 0, 0); // Animasyonu oynatıyoruz return 1; } ``` ## Notlar :::tip Animasyon kütüphanesini aktör için önceden yüklemelisiniz(preload). Aksi taktirde fonksiyon tekrar çağırılana kadar animasyon aktöre işlemez. ::: ## Bağlantılı Fonksiyonlar - [ClearActorAnimations](ClearActorAnimations): Aktöre uygulanmış animasyonları kaldırın.
openmultiplayer/web/docs/translations/tr/scripting/functions/ApplyActorAnimation.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/ApplyActorAnimation.md", "repo_id": "openmultiplayer", "token_count": 1445 }
454
--- title: ChangeVehiclePaintjob description: Aracın kaplamasını değiştirme. (düz renkler için bkz. ChangeVehicleColor). tags: ["vehicle"] --- ## Açıklama Aracın kaplamasını değiştirme. (düz renkler için bkz. ChangeVehicleColor). | Parametre | Açıklama | | ---------- | ------------------------------------------------------------ | | vehicleid | Kaplaması değişecek aracın ID'si. | | paintjobid | Uygulanacak kaplama ID'si. Kaplama kaldırmak için 3'ü girin. | ## Çalışınca Vereceği Sonuçlar Bu fonksiyon belirtilen araç ID'si oluşturulmamış olsa bile her zaman 1'i (başarılı) döndürür. :::warning Eğer aracın rengi siyahsa kaplama gözükmeyebilir. Aracı beyaza boyamak daha iyi olabilir, yapmak için ChangeVehicleColor(vehicleid,1,1); kullanılabilir. ::: ## Örnekler ```c new rand = random(3); // 0, 1 veya 2 olacaktır (tümü geçerlidir) ChangeVehicleColor(GetPlayerVehicleID(playerid),1,1); // kaplamanın daha iyi gözükmesi için aracın beyaz renkte olduğundan emin olduk. ChangeVehiclePaintjob(GetPlayerVehicleID(playerid), rand); // Oyuncunun bulunduğu aracı rastgele çıkan sayıya eşit olan kaplama ID'sine boyadık. ``` ## Bağlantılı Fonksiyonlar - [ChangeVehicleColor](ChangeVehicleColor): Aracın rengini değiştirme. - [OnVehiclePaintjob](../callbacks/OnVehiclePaintjob): Bu fonksiyon, araç kaplaması değiştiğinde çağrılır.
openmultiplayer/web/docs/translations/tr/scripting/functions/ChangeVehiclePaintjob.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/ChangeVehiclePaintjob.md", "repo_id": "openmultiplayer", "token_count": 693 }
455
--- title: GetPlayerCameraTargetActor description: Oyuncunun baktığı aktörün (herhangi bir aktörün) ID'sini çekme. tags: ["player", "camera", "actor"] --- <VersionWarnTR version='SA-MP 0.3.7' /> ## Açıklama Oyuncunun baktığı aktörün (herhangi bir aktörün) ID'sini çekme. | Parametre | Açıklama | | -------- | ------------------------------------------------ | | playerid | Herhangi bir aktöre bakan oyuncunun ID'si. | ## Çalışınca Vereceği Sonuçlar Oyunncunun baktığı aktörün ID'si. ## Örnekler ```c new bool:ActorHandsup[MAX_ACTORS]; public OnPlayerConnect(playerid) { EnablePlayerCameraTarget(playerid, 1); // Oyuncu girdiğinde kamera hedefi etkin hale gelir (1:aktif, 0:kapalı). return 1; } public OnPlayerUpdate(playerid) { // Oyuncunun hangi aktöre baktığını opsiyonel şekilde değişken olarak tanıttık. new playerTargetActor = GetPlayerCameraTargetActor(playerid); // Oyuncu baktığı şey geçersiz aktör ID'si değilse. if (playerTargetActor != INVALID_ACTOR_ID) { // Oyuncunun elinde olan silahı opsiyonel şekilde değişken olarak tanıttık. new playerWeapon = GetPlayerWeapon(playerid); // Oyuncunun bastığı tuşları kontrol ediyoruz, böylece nişan alıp almadığını kontrol ediyoruz. new KEY:keys, updown, leftright; GetPlayerKeys(playerid, keys, updown, leftright); // Oyuncunun hedef aldığı aktör eğer ELLERİNİ KALDIRMADIYSA, elindeki silah'ın GTA:SA ID'si 22 üzeri ve 42'den aşağıysa ve AİM tuşuna basıyorsa if (!ActorHandsup[playerTargetActor] && playerWeapon >= 22 && playerWeapon <= 42 && keys & KEY_AIM) { // Aktör ellerini kaldırma animasyonunu uygular. ApplyActorAnimation(playerTargetActor, "SHOP", "SHP_HandsUp_Scr",4.1,0,0,0,1,0); // Hedef alınan aktör'ün ellerini kaldırma değişkeni true yani aktif/doğru hale gelir. ActorHandsup[playerTargetActor] = true; } } return 1; } ``` ## Notlar :::tip Bu fonksiyon oyuncunun aktöre bakıp bakmadığı kontrol eder. Eğer tam anlamıyla oyuncunun nişan alıp almadığını kontrol etmek için GetPlayerTargetActor fonksiyonunu kullanmanız gerekir. ::: :::warning Bu fonksiyon, bant genişliğinden tasarruf etmek için varsayılan olarak devre dışı bırakılmıştır. Kullanılmadan önce OnPlayerConnect üzerinden EnablePlayerCameraTarget fonksiyonunu (her) oyuncu için aktif hale getirilmesi gerekiyor. ::: ## Bağlantılı Fonksiyonlar - [GetPlayerTargetActor](GetPlayerTargetActor): Oyuncunun silah ile hedef aldığı oyuncuyu kontrol eder. - [GetPlayerCameraTargetPlayer](GetPlayerCameratargetPlayer): Oyuncunun kamerası ile baktığı oyuncuyu kontrol eder. - [GetPlayerCameraTargetVehicle](GetPlayerCameraTargetVehicle): Oyuncunun kamerası ile baktığı aracı kontrol eder. - [GetPlayerCameraTargetObject](GetPlayerCameraTargetObject): Oyuncunun kamerası ile baktığı objeyi kontrol eder. - [GetPlayerCameraFrontVector](GetPlayerCaemraFrontVector): Oyuncu kamerasının ön vektörünü alır.
openmultiplayer/web/docs/translations/tr/scripting/functions/GetPlayerCameraTargetActor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/GetPlayerCameraTargetActor.md", "repo_id": "openmultiplayer", "token_count": 1404 }
456
# SA-MP 维基(Wiki) 和 open.mp 文档 欢迎来到由open.mp团队和更加广泛的SA-MP社区共同维护的SA-MP维基! 本站旨在为SA-MP和open.mp提供一个易于访问、易于提交的文档资源。 ## SA-MP 维基已经消逝 不幸的是,SA-MP维基在2020年9月下旬关闭——尽管它的大部分内容可以在公共互联网档案中找到。 正因此,我们需要社会各界的帮助,把旧的维基内容搬到它的新家园,这儿! 如有兴趣,请查看[本页](/docs/meta/Contributing)获取更多信息。 如果你没有使用GitHub或转换HTML的经验, 别担心!你可以反馈问题 (通过 [Discord](https://discord.gg/samp),[论坛](https://forum.open.mp) 或 社交媒体) 来帮助我们。最重要的是:“传播”!因此,请务必收藏本站,并且分享给更多需要SAMP维基的各位朋友。 我们欢迎大家对文档的改进作出贡献,也欢迎大家提供一些常见任务的教程和指南,比如构建简单的游戏模式或是介绍常用的库和插件的使用。如果您有兴趣投稿,请访问[GitHub页面](https://github.com/openmultiplayer/web)。
openmultiplayer/web/docs/translations/zh-cn/index.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/index.md", "repo_id": "openmultiplayer", "token_count": 794 }
457
--- title: OnNPCExitVehicle description: 当NPC离开车辆时调用此回调。 tags: [] --- ## 描述 当 NPC 离开车辆时调用此回调。 ## 相关案例 ```c public OnNPCExitVehicle() { print("NPC离开了车辆"); return 1; } ``` ## 相关回调 - [OnNPCEnterVehicle](../callbacks/OnNPCEnterVehicle): 当 NPC 进入车辆时被调用。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCExitVehicle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCExitVehicle.md", "repo_id": "openmultiplayer", "token_count": 215 }
458
--- title: OnPlayerEnterRaceCheckpoint description: 当玩家进入一个比赛检查点时,这个回调函数被调用。 tags: ["player", "checkpoint", "racecheckpoint"] --- ## 描述 当玩家进入一个比赛检查点时,这个回调函数被调用。 | 参数名 | 描述 | | -------- | --------------------------- | | playerid | 进入比赛检查点的玩家的 ID。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerEnterRaceCheckpoint(playerid) { printf("玩家 %d 进入了一个比赛检查点!", playerid); return 1; } ``` ## 要点 <TipNPCCallbacksCN /> ## 相关函数 - [SetPlayerCheckpoint](../functions/SetPlayerCheckpoint): 为玩家创造一个检查点。 - [DisablePlayerCheckpoint](../functions/DisablePlayerCheckpoint): 禁用玩家当前的检查点。 - [IsPlayerInCheckpoint](../functions/IsPlayerInRaceCheckpoint): 检查玩家是否处于检查点。 - [SetPlayerRaceCheckpoint](../functions/SetPlayerRaceCheckpoint): 为玩家创造一个比赛检查点。 - [DisablePlayerRaceCheckpoint](../functions/DisablePlayerRaceCheckpoint): 禁用玩家当前的比赛检查点。 - [IsPlayerInRaceCheckpoint](../functions/IsPlayerInRaceCheckpoint): 检查玩家是否处于比赛检查点。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerEnterRaceCheckpoint.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerEnterRaceCheckpoint.md", "repo_id": "openmultiplayer", "token_count": 681 }
459
--- title: OnPlayerSelectObject description: 当玩家在使用SelectObject之后选择一个物体时,这个回调会被调用。 tags: ["player"] --- ## 描述 当玩家在使用 SelectObject 之后选择一个物体时,这个回调会被调用。 | 参数名 | 描述 | | -------- | -------------------------------------------- | | playerid | 选择玩家的玩家 ID | | type | [选择的类型](../resources/selectobjecttypes) | | objectid | 所选物体的 ID | | modelid | 所选模型的 ID | | Float:fX | 选择玩家的 X 轴位置 | | Float:fY | 选择玩家的 Y 轴位置 | | Float:fZ | 选择玩家的 Z 轴位置 | ## 返回值 1 - 将阻止其他脚本接收此回调。 0 - 指示此回调将传递给下一个脚本。 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerSelectObject(playerid, type, objectid, modelid, Float:fX, Float:fY, Float:fZ) { printf("玩家 %d 选择了物体 %d", playerid, objectid); if (type == SELECT_OBJECT_GLOBAL_OBJECT) { EditObject(playerid, objectid); } else { EditPlayerObject(playerid, objectid); } SendClientMessage(playerid, 0xFFFFFFFF, "现在可以编辑物体了!"); return 1; } ``` ## 相关函数 - [SelectObject](../functions/SelectObject): 选择一个物体。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerSelectObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerSelectObject.md", "repo_id": "openmultiplayer", "token_count": 915 }
460
--- title: OnVehicleDeath description: 如果载具被摧毁,不管是爆炸还是沉入水中,都会调用这个回调函数。 tags: ["vehicle"] --- ## 描述 如果载具被摧毁,不管是爆炸还是沉入水中,都会调用这个回调函数。 | 参数名 | 描述 | | --------- | ------------------------------------------------------------------------------------- | | vehicleid | 被毁载具的 ID。 | | killerid | 报告(同步)车辆破坏的玩家的 ID(名称误导)。通常是司机或乘客(如果有的话)或最接近的玩家。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnVehicleDeath(vehicleid, killerid) { new string[64]; format(string, sizeof(string), "载具 %i 被摧毁。报告的玩家 %i.", vehicleid, killerid); SendClientMessageToAll(0xFFFFFFFF, string); return 1; } ``` ## 要点 :::tip 当载具进入水中时,这个回调也会被调用,但载具可以通过传送或驾驶(如果只是部分淹没)免于破坏。 回调将不会被第二次调用,并且载具可能在司机离开时或较短时间后消失。 ::: ## 相关函数 - [SetVehicleHealth](../functions/SetVehicleHealth): 设置载具的健康度。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleDeath.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleDeath.md", "repo_id": "openmultiplayer", "token_count": 870 }
461
--- title: AddStaticVehicleEx description: 在游戏模式中新增一个静态的载具(模型是为玩家预加载的)。 tags: ["vehicle"] --- ## 描述 在游戏模式中新增一个静态的载具(模型是为玩家预加载的)。与 AddStaticVehicle 的区别只有一个: 当载具无人驾驶时,允许设置重生时间。 | 参数名 | 说明 | | ------------------------------------- | --------------------------------------------------------------------------------------- | --- | | modelid | 载具的模型 ID。 | | Float:spawn_X | 载具的 X 坐标。 | | Float:spawn_Y | 载具的 Y 坐标。 | | Float:spawn_Z | 载具的 Z 坐标。 | | Float:z_angle | 载具方向-角度。 | | [color1](../resources/vehiclecolorid) | 主要颜色 ID,-1 表示随机。 | | [color2](../resources/vehiclecolorid) | 次要颜色 ID,-1 表示随机。 | | | respawn_delay | 直到载具在没有司机的情况下重生的延迟,以秒为单位。 | | addsiren | 在 0.3.7 中添加;在早期版本中不起作用。具有默认值 0。使载具有警报器,前提是载具有喇叭。 | ## 返回值 创建的载具的 ID(1 ~ MAX_VEHICLES)。 如果未能创建载具(达到数量限制或无效的载具模型 ID),则返回 INVALID_VEHICLE_ID(65535)。 ## 案例 ```c public OnGameModeInit() { // 新增一架九头蛇(520),司机离开15秒后重生 AddStaticVehicleEx (520, 2109.1763, 1503.0453, 32.2887, 82.2873, -1, -1, 15); return 1; } ``` ## 相关函数 - [AddStaticVehicle](AddStaticVehicle): 新增一辆静态载具。 - [CreateVehicle](CreateVehicle): 创建一辆载具。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddStaticVehicleEx.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddStaticVehicleEx.md", "repo_id": "openmultiplayer", "token_count": 1724 }
462
--- title: CreatePlayer3DTextLabel description: 只为某个特定的玩家创建一个三维文本标签。 tags: ["player", "3dtextlabel"] --- ## 描述 只为某个特定的玩家创建一个三维文本标签。 | 参数名 | 说明 | | --------------- | ----------------------------------------------------------------- | | playerid | 新创建的三维文本标签想给哪个玩家 ID 看到。 | | text[] | 用于显示的文本内容。 | | color | 文本内容颜色。 | | x | X 坐标 (如果用于附加则为偏移量) | | y | Y 坐标 (如果用于附加则为偏移量) | | z | Z 坐标 (如果用于附加则为偏移量) | | DrawDistance | 你能够看到三维文本标签的距离 | | attachedplayer | 你想把三维文本标签附加在哪个玩家身上。(不附加: INVALID_PLAYER_ID) | | attachedvehicle | 你想把三维文本标签附加在哪个载具上。 (不附加: INVALID_VEHICLE_ID) | | testLOS | 0/1 控制在视线范围内能否透过物体看到 | ## 返回值 新创建的玩家三维文本标签的 ID,如果达到限制(MAX_3DTEXT_PLAYER),则为 INVALID_3DTEXT_ID。 ## 案例 ```c if (strcmp(cmd, "/playerlabel", true) == 0) { new PlayerText3D: playerTextId, Float: X, Float: Y, Float: Z; GetPlayerPos(playerid, X, Y, Z); playerTextId = CreatePlayer3DTextLabel(playerid, "你好\n我就在你当前的坐标上", 0x008080FF, X, Y, Z, 40.0); return 1; } ``` ## 要点 :::tip 处于观察模式时,绘制距离似乎小了很多。 ::: :::warning 如果 text[] 参数是空的,服务端或位于文本标签旁的玩家客户端可能会崩溃! ::: ## 相关函数 - [Create3DTextLabel](Create3DTextLabel): 创建一个三维文本标签。 - [Delete3DTextLabel](Delete3DTextLabel): 删除一个三维文本标签。 - [Attach3DTextLabelToPlayer](Attach3DTextLabelToPlayer): 将三维文本标签附加到玩家身上。 - [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): 将一个三维文本标签附加到载具。 - [Update3DTextLabelText](Update3DTextLabelText): 改变三维文本标签的文本内容和颜色。 - [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): 删除一个为玩家创建的三维文本标签。 - [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): 改变玩家的三维文本标签的文本内容和颜色。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/CreatePlayer3DTextLabel.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/CreatePlayer3DTextLabel.md", "repo_id": "openmultiplayer", "token_count": 1767 }
463
--- title: SetPlayerCameraPos description: 设置玩家的视角到指定位置。 tags: ["player"] --- ## 描述 设置玩家的视角到指定位置。 | 参数名 | 说明 | | -------- | ------------- | | playerid | 玩家 ID。 | | Float:x | 视角的 X 坐标 | | Float:y | 视角的 Y 坐标 | | Float:z | 视角的 Z 坐标 | ## 返回值 1:函数执行成功。 0:函数执行失败。指定的玩家不存在。 ## 案例 ```c SetPlayerCameraPos(playerid, 652.23, 457.21, 10.84); ``` ## 要点 :::tip 通常还需要结合 SetPlayerCameraLookAt 函数才能正常工作。 使用 SetCameraBehindPlayer 来重置视角到玩家后面。 ::: :::warning 在启用旁观者模式后,不能直接使用视角函数。 ::: ## 相关函数 - [SetPlayerCameraLookAt](SetPlayerCameraLookAt): 设置玩家的视角所看的方向。 - [SetCameraBehindPlayer](SetCameraBehindPlayer): 重置视角到玩家后面。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/SetPlayerCameraPos.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/SetPlayerCameraPos.md", "repo_id": "openmultiplayer", "token_count": 550 }
464
--- title: 一些不錯的東西 description: 對製作腳本有幫助的工具、函數庫和插件的列表。 --- ## 工具 - **[Community Compiler](https://github.com/pawn-lang/compiler/)** - 一個更好的編譯器,改進和修復了許多地方,非常推薦取代原本的pawn編譯器。 - **[sampctl](http://sampctl.com/)** - 一個軟件包管理器,用於快速安裝函數庫,以及執行伺服器。 - **[Plugin Runner](https://github.com/Zeex/samp-plugin-runner/)** - 一個輕巧簡便的插件執行器,適合用來對腳本和插件進行除錯,只需要開啟命令管理器並且輸入簡單指令即可開啟伺服器。 - **[Plugin Boilerplate](https://github.com/Southclaws/samp-plugin-boilerplate/)** - 簡化插件製作流程的模板。 - **[SA:MP Plugin Template Library](https://github.com/katursis/samp-ptl/)** - 使用這個模板函數庫,可以輕鬆快速地創建自己的插件。 - **[SA-MP Fiddle](https://fiddle.sa-mp.dev/)** - 一個測試用的平台,可以用於測試腳本、進行除錯、分享代碼。 - **[Pawn Syntax - Sublime](https://packagecontrol.io/packages/Pawn%20syntax/)** - Sublime Text 的自動完成擴充套件,非常有幫助。 - **[Pawn Syntax - Visual Marketplace](https://marketplace.visualstudio.com/items?itemName=southclaws.vscode-pawn/)** - Visual Studio Code 的自動完成擴充套件,非常有幫助。 - **[SA-MP Zone Editor](https://bitbucket.org/Grimrandomer/samp-zone-editor/downloads/)** - 一個地盤區域的編輯器。 - **[SA-MP Map Editor](https://github.com/openmultiplayer/archive/raw/master/tools/Map%20Editor.zip)** - 一個貼近大眾的地圖編輯器。 ## 函數庫 - **[samp-stdlib](https://github.com/pawn-lang/samp-stdlib/)** - 改良的原版函數庫。 修復錯誤、增加說明且更加完整。 - **[fixes.inc](https://github.com/pawn-lang/sa-mp-fixes/)** - 修復大量samp伺服器原有的bug,可以直接使用。 - **[YSI-Includes](https://github.com/pawn-lang/YSI-Includes/)** - 開發最久、最多功能、測試充足的函數庫,提供大量的新功能來製作腳本。 - **[foreach](https://github.com/Open-GTO/foreach)** - 獨立的 foreach 函數庫 (非 y_iterate版本)。 - **[amx_assembly](https://github.com/Zeex/amx_assembly/)** - Pawn底層等級的語言運用。 - **[md-sort](https://github.com/oscar-broman/md-sort/)** - 可以對pawn的多維數組進行排序。該函數庫通過修改數組的內部指針而不是複製資料來實現。 - **[indirection](https://github.com/Y-Less/indirection/)** - 可以間接呼叫函數指針,並且更有效率且更安全,甚至可以取代CallLocalFunction等類似的函數。 - **[code-parse.inc](https://github.com/Y-Less/code-parse.inc/)** - 可以分析自定義的代碼,並在編譯時可以取得詳細。 - **[strlib.inc](https://github.com/oscar-broman/strlib/)** - 字串相關的函數庫。 - **[Extended Vehicle Information](https://github.com/Vince0789/sa-mp-extended-vehicle-information/)** - 使用SQLite且含有大量單人模式之交通工具旗標。 - **[sqlitei](https://github.com/oscar-broman/sqlitei/)** - 更高層次的SA-MP SQLite函數API。 - **[weapon-config](https://github.com/oscar-broman/samp-weapon-config/)** - 更加一致且反應靈敏度較高的傷害系統,並且含有許多新功能。 - **[samp-geoip](https://github.com/Southclaws/SAMP-geoip/)** - IP地理位置 GeoIP 的函數庫。 - **[progress2.inc](https://github.com/Southclaws/progress2/)** - 讓時間、血量、油量等自製內容以進度條的方式呈現。 - **[weapon-data.inc](https://github.com/Southclaws/samp-weapon-dat/)** - 經過改良的武器數值自定義函數庫。 - **[MV_Youtube.inc](https://github.com/MichaelBelgium/MV_Youtube)** - 轉換 Youtube 影片至音頻的API函數庫。 - **[MySQL Prepared Statements](https://github.com/PatrickGTR/MySQL-Prepared-Statements/)** - 用於PAWN MySQL插件的預編譯語句仿真。 - **[samp-server-weapons](https://github.com/Brunoo16/samp-server-weapons/)** - 由伺服器控制的武器。 - **[actor_robbery](https://github.com/PatrickGTR/actor_robbery/)** - 受GTA V商店搶劫啟發。 actor_robbery.inc 可以模擬這個功能! - **[samp-aviation](https://github.com/Southclaws/samp-aviation/)** - 讓飛機可以更貼近現實的自動駕駛。 - **[samp-logger](https://github.com/Southclaws/samp-logger)** - 結構化的簡易日誌工具,提供簡單的函數進行日誌紀錄和除錯。 - **[TDW Recursion Scanner](https://github.com/tdworg/samp-include-rscan)** - 一個能夠找到程式碼中遞迴的函數庫。 - **[easyDialog](https://github.com/Awsomedude/easyDialog)** - 提供簡化Dialog的函數庫。 - **[mdialog](https://github.com/Open-GTO/mdialog)** - 現代化的Dialog系統,類似於easyDialog。 - **[Model Sizes Plus](https://github.com/Crayder/Model-Sizes-Plus)** - 舊版本modelsizes的升級版,更加精確。 - **[physics.inc](https://github.com/uPeppe/physics.inc)** - 模擬2D和3D物理系統(真實運動、碰撞等)。 - **[samp-async-dialogs](https://github.com/AGraber/samp-async-dialogs)** - 使用PawnPlus任務進行非同步的Dialog處理。 - **[speedcap.inc](https://github.com/openmultiplayer/archive/blob/master/includes/speedcap.inc)** - 控制車輛速度的函數庫。 - **[SA:MP Command Guess](https://github.com/Kirima2nd/samp-command-guess)** - 使用Levenshtein距離函數的指令猜測器。 - **[vending](https://github.com/wuzi/vending)** - SA-MP伺服器端自動販賣機。 - **[strlib](https://github.com/oscar-broman/strlib)** - 一個有用的字符串函數庫。 - **[mathutil](https://github.com/ScavengeSurvive/mathutil)** - 一個有用的數學函數庫。 - **[rotations.inc](https://github.com/sampctl/rotations.inc)** - 由Nero_3D的rotations.inc整理的有用的旋轉函數庫。 - **[SA-MP Distance Functions](https://github.com/Y-Less/samp-distance)** - 有用的距離檢測函數庫。 - **[New SA-MP callbacks](https://github.com/emmet-jones/New-SA-MP-callbacks)** - 有用的新回調函數庫。 - **[Alternative Dialogs](https://github.com/NexiusTailer/Alternative-Dialogs)** - 具有新設計的Textdraw Dialog。 - **[eSelection](https://github.com/TommyB123/eSelection)** - 在SA-MP遊戲模式中添加創建動態模型選擇菜單的功能。 - **[mSelection](https://github.com/alextwothousand/mSelection)** - 與eSelection類似,但樣式不同。 ## 命令處理 - **[I-ZCMD](https://github.com/YashasSamaga/I-ZCMD/)** - ZCMD的改良版本。 - **[Pawn.CMD](https://github.com/katursis/Pawn.CMD/)** - 性能最強的命令處理系統。 - **[y_commands](https://github.com/pawn-lang/YSI-Includes/blob/5.x/YSI_Visual/y_commands.md)** - YSI Includes中的指令處理器。 ## 插件 - **[JIT](https://github.com/Zeex/samp-plugin-jit/)** - 一款即時編譯器插件,對於穩定的腳本,可以提升相當大的執行性能。 - **[crashdetect](https://github.com/Zeex/samp-plugin-crashdetect/)** - 相當好用的插件,可以在測試時查找錯誤,直接得到錯誤相關訊息,對於除錯有相當大的幫助。 - **[Profiler](https://github.com/Zeex/samp-plugin-profiler/)** - SA-MP伺服器性能分析插件。 - **[sscanf](https://github.com/Y-Less/sscanf/)** - 可以將字符串轉換為多個不同類型的值,如整數、浮點數、玩家等。 - **[MySQL Plugin](https://github.com/pBlueG/SA-MP-MySQL/)** - 建立SA-MP伺服器到MySQL資料庫的連接。 - **[Streamer Plugin](https://github.com/samp-incognito/samp-streamer-plugin/)** - 繞過SA-MP的許多限制,如物體和撿取物品。 - **[nativechecker](https://github.com/openmultiplayer/archive/raw/master/plugins/nativechecker.zip)** - 檢查伺服器啟動時的原生函數。 - **[FCNPC](https://github.com/ziggi/FCNPC/)** - 一個為SA-MP伺服器添加許多新功能的插件,提供了更強大的NPC。 - **[FileManager](https://github.com/JaTochNietDan/SA-MP-FileManager/)** - 允許您從根目錄管理文件和文件夾(不僅限於腳本文件伺服器目錄)。 - **[Pawn.Raknet](https://github.com/katursis/Pawn.RakNet/)** - 允許您分析RakNet資料流量。 - **[samp-precise-timers](https://github.com/bmisiak/samp-precise-timers/)** - 使用Rust編寫的一個提供精確計時器的SA-MP插件。 - **[PawnPlus](https://github.com/IllidanS4/PawnPlus/)** - 通過添加新的構造、資料類型和編程技術,擴展了Pawn腳本語言的功能。 - **[PAWN memory access](https://github.com/BigETI/pawn-memory/)** - 允許在PAWN中從堆中分配和釋放記憶體。 - **[Native Fallback](https://github.com/IllidanS4/NativeFallback/)** - SA-MP插件,為沒有註冊原生函數提供後備實現。 - **[YSF](https://github.com/IllidanS4/YSF/)** - 一個插件,主要用於通過記憶體編輯和hook來提取伺服器的最大可能性。 - **[SKY](https://github.com/oscar-broman/SKY/)** - 此插件提供了讓Pawn腳本執行強大事務的底層函數。 - **[Pawn.Regex](https://github.com/katursis/Pawn.Regex/)** - 在Pawn中添加了正則表達式的支持。 - **[pawn-scraper](https://github.com/Sreyas-Sreelal/pawn-scraper/)** - 一個功能強大的爬蟲插件,提供了在pawn中使用html_parsers和css選擇器的接口。 - **[TOTP](https://github.com/philip1337/samp-plugin-totp)** - 允許在sa-mp遊戲模式中使用TOTP身份驗證。 - **[DNS Plugin](https://github.com/samp-incognito/samp-dns-plugin)** - 提供DNS查找和反向DNS查找功能的插件。 - **[MapAndreas](https://github.com/Southclaws/samp-plugin-mapandreas)** - 允許載入不同的高度地圖並檢查x,y坐標的最小高度。 - **[ColAndreas](https://github.com/Pottus/ColAndreas)** - 創建San Andreas世界的模擬,使用Bullet Physics庫。 - **[PathFinder](https://bitbucket.org/Pamdex/pathfinder/src/master)** - 允許在San Andreas地圖上從A點到B點計算路線。 - **[Custom Query Flood Check](https://github.com/spmn/samp-custom-query-flood-check)** - 編寫自定義保護措施以防止查詢洪水攻擊。 - **[sampml](https://github.com/YashasSamaga/sampml)** - 簡化的機器學習工具包和相關的SAMP項目(Aimbot檢測)。 - **[TgConnector](https://github.com/Sreyas-Sreelal/tgconnector)** - 一個telegram連接器插件,可幫助通過SA-MP與telegram機器人互動。 - **[Discord connector](https://github.com/maddinat0r/samp-discord-connector)** - 允許您從PAWN腳本中控制Discord機器人。 - **[TSConnector](https://github.com/maddinat0r/samp-tsconnector)** - 允許您從PAWN腳本中控制Teamspeak3服務器。 - **[IRC Plugin](https://github.com/samp-incognito/samp-irc-plugin)** - 允許通過SA-MP服務器創建和管理IRC機器人。 - **[pawn-requests](https://github.com/Southclaws/pawn-requests)** - 提供與支持純文本和JSON資料類型的HTTP(S)API交互的API。 - **[pawn-redis](https://github.com/Southclaws/pawn-redis)** - 提供快速的記憶體資料庫和其他程序之間的異步消息通道的訪問權限。 - **[Chrono](https://github.com/Southclaws/pawn-chrono)** - 用於處理日期和時間的現代Pawn庫。 - **[rustext](https://github.com/ziggi/rustext)** - 修復俄語文本插件,適用於SA-MP:GameText,TextDraw和Menu。 - **[Advanced SA NickName](https://github.com/KrYpToDeN/Advanced-SA-NickName)** - 支持在暱稱中使用任何符號。 - **[SAMPSON](https://github.com/Hual/SAMPSON)** - 一個用於SA-MP的JSON插件。 ## 用戶端-伺服器插件 - **[SA-MP+](https://github.com/Hual/SA-MP-Plus)** - 用戶端修改版,使用SA-MP的插件SDK來與伺服器交互並增加新功能。 - **[CHandling](https://github.com/dotSILENT/chandling)** - 修改游戲的預設行為,為每輛車分配車輛處理能力。 - **[SAMPVOICE](https://github.com/CyberMor/sampvoice)** - 在SA:MP伺服器上使用Pawn語言實現語音通信系統。 - **[KeyListener](https://github.com/CyberMor/keylistener)** - 用戶端-伺服器插件,可追蹤任何按鍵的按下情況。 - **[SAMP CEF](https://github.com/ZOTTCE/samp-cef)** - SA:MP的用戶端和伺服器插件,用於嵌入CEF。 - **[SAMP_AC_v2](https://github.com/Whitetigerswt/SAMP_AC_v2)** - SA:MP用戶端反作弊程式。 ## 加密用插件 - **[whirlpool](https://github.com/Southclaws/samp-whirlpool)** - 一個用於SA:MP的Whirlpool加密插件。 - **[bcrypt](https://github.com/Sreyas-Sreelal/samp-bcrypt/)** - 為SAMP製作的Bcrypt加密插件。 - **[samp-crypto](https://github.com/alextwothousand/samp-crypto)** - 提供SA:MP加密功能的函數庫,例如Argon2、Scrypt和Bcrypt。 - **[SHA512](https://github.com/openmultiplayer/archive/raw/master/plugins/SHA512.zip)** - 為SAMP製作的SHA512加密插件。 ## GDK/SDKs 現在,你可以使用open.mp來製作pawn以外的程式碼,不需要使用任何插件,詳細請查看[這篇文章](https://www.open.mp/blog/release-candidate-1) - **[sampsdk](https://github.com/Zeex/samp-plugin-sdk/)** - 開發插件所需的最小程式碼。 - **[sampgdk](https://github.com/Zeex/sampgdk/)** - C/C++ 語言支援,用於製作SA:MP的遊戲模式。 - **[SampSharp](https://github.com/ikkentim/SampSharp/)** - C# 語言支援,用於製作SA:MP的遊戲模式。 - **[.NET Plugin](https://github.com/Seregamil/.NET-plugin/)** - C# 語言支援,用於製作SA:MP的插件。 - **[sampgo](https://github.com/sampgo/sampgo/)** - Go 語言支援,用於製作SA:MP的遊戲模式/插件。 - **[samp-node](https://github.com/AmyrAhmady/samp-node/)** - Javascript/Typescript 語言支援,用於製作SA:MP的遊戲模式。 - **[Shoebill Project](https://github.com/Shoebill/ShoebillPlugin/)** - Java 語言支援,用於製作SA:MP的遊戲模式。 - **[pySAMP](https://github.com/habecker/PySAMP/)** - Python 語言支援,用於製作SA:MP的遊戲模式。 - **[samp-rs](https://github.com/ZOTTCE/samp-rs/)** - Rust 語言支援,用於製作SA:MP的插件。 - **[Yet Another Lua Plugin](https://github.com/IllidanS4/YALP/)** - Lua 語言支援,用於製作SA:MP的遊戲模式。 - **[SAMPHP](https://github.com/Lapayo/SAMPHP/)** - PHP 語言支援,用於製作SA:MP的遊戲模式。 - **[SA-MP S[D]K](https://github.com/Hual/SA-MP-S-D-K/)** - D 語言支援,用於製作SA:MP的遊戲模式。 - **[Kamp](https://github.com/Double-O-Seven/kamp/)** - Kotlin 語言支援,用於製作SA:MP的遊戲模式。 ## 遊戲模式 - **[Example Gamemode](https://github.com/openmultiplayer/example-gamemodes)** - 與open.mp兼容的gamemode腳本專案庫。 - **[ScavengeSurvive](https://github.com/Southclaws/ScavengeSurvive)** - 最基礎的PvP生存遊戲腳本。 - **[gta-open](https://github.com/PatrickGTR/gta-open)** - 以洛杉磯為基礎的警匪互抢模式。 - **[SF-CnR](https://github.com/zeelorenc/sf-cnr)** - San Fierro Cops And Robbers,一個SA:MP的警匪模式。 - **[Next Generation Roleplay](https://github.com/NextGenerationGamingLLC/SA-MP-Development)** - 下一代遊戲LLC SA:MP遊戲模式。 - **[SC-RP](https://github.com/seanny/SC-RP)** - 一個带有MySQL支持的角色扮演遊戲模式。 ## 副腳本 - **[MapFix](https://github.com/NexiusTailer/MapFix)** - 修復GTA San Andreas地圖的紋理錯誤。 - **[SA:MP Animbrowse](https://github.com/Southclaws/samp-animbrowse)** - SA:MP的動畫瀏覽工具。 - **[IsPlayerUsingAndroid](https://github.com/Fairuz-Afdhal/IsPlayerUsingAndroid)** - 檢查玩家是否使用Android系統。 - **[TextDraw-Editor](https://github.com/Nickk888SAMP/TextDraw-Editor)** - TextDraw編輯器,具有一些豐富的功能。 - **[Ultimate Creator](https://github.com/NexiusTailer/Ultimate-Creator)** - 具有豐富功能的高級地圖編輯器。 - **[Fusez's Map Editor](https://github.com/fusez/Map-Editor-V3)** - SA:MP的地圖編輯器。 - **[Texture Studio](https://github.com/Pottus/Texture-Studio)** - 這是一個遊戲中的地圖編輯器,可以對15個材質進行紋理,並設置對象的顏色。
openmultiplayer/web/docs/translations/zh-tw/awesome.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-tw/awesome.md", "repo_id": "openmultiplayer", "token_count": 8598 }
465
--- title: SA-MP Android (Mobile Version) date: "2021-01-30T12:46:46" author: Potassium --- Stavovi i mišljenja open.mp tima o SA-MPu za Android Zdravo svima, Samo smo hteli da napišemo brzi post na blogu o našim pogledima na SA-MP za Android, jer smo dobijali mnogo komentara o tome na našim YouTube video zapisima i na Discordu. Kao što smo naveli u našem YouTube videu, ne podržavamo trenutnu verziju SA-MP za Android. Ova aplikacija je kreirana korištenjem izvornog koda koji je ukraden od SA-MP tima, što aplikaciju čini ilegalnom. Ne odobravamo krađu koda drugih ljudi i ne odobravamo upotrebu ukradenog koda. Takođe se ne družimo sa ilegalnim aktivnostima. Vidimo da GTA SA multiplayer za mobilne uređaje ima veliku zajednicu i želimo dobrodošlicu ovoj zajednici u open.mp. Trenutno razgovaramo o tome kako možemo kreirati vlastiti multiplayer mod za SA mobile, kako bi to bilo legalno i pošteno! :) To znači da je vrlo moguće da će u budućnosti postojati open.mp za mobilne uređaje, pa vas molimo da nas podržite dok to shvatimo! Pozivamo mobilnu zajednicu da se pridruži našem službenom Discordu sa preko 7000 članova, kreirali smo kanal za vas na #samp-android i radujemo se što ćemo čuti vaša mišljenja i mišljenja! Vidimo se tamo! https://discord.gg/samp
openmultiplayer/web/frontend/content/bs/blog/samp-mobile.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/bs/blog/samp-mobile.mdx", "repo_id": "openmultiplayer", "token_count": 568 }
466
--- title: Forum e Wiki offline description: Ti stai chiedendo perché il SA-MP Forum e la Wiki sono offline? Leggi qui per informazioni e chiarimenti. --- # Perché il Forum e la Wiki sono offline? Il 25 Settembre 2020, i certificati per forum.sa-mp.com e wiki.sa-mp.com sono entrambi scaduti. Molti utenti l'hanno notato ed hanno sollevato la questione sul Discord. Sebbene il sito fosse ancora accessibile bypassando la sicurezza HTTPS, era evidente che qualcosa di più grande stesse per andare per il verso sbagliato. Il giorno dopo, molti utenti hanno trovato entrambi i siti totalmente offline con errori di database sulle relative finestre dei browser. ![https://i.imgur.com/hJLmVTo.png](https://i.imgur.com/hJLmVTo.png) Quest'errore è piuttosto comune, di solito indica un backup del database. Ma dato il problema con il certificato SSL, sembrava indicativo di qualcos'altro. Più tardi quel giorno, entrambi i siti andarono completamente offline, senza neanche mostrare una pagina di errore. ![https://i.imgur.com/GjzURlq.png](https://i.imgur.com/GjzURlq.png) ## Che cosa significa? Ci sono varie teorie all'interno della community di SA-MP ma nessun avviso ufficiale su cos'è avvenuto. Da quel che sappiamo, tuttavia, è ragionevole pensare al peggio. Il Forum e la Wiki probabilmente non torneranno. Sarebbe grandioso il contrario. ## Alternative Per ora, il contenuto della wiki è ancora accessibile presso [le copie di Archive.org](http://web-old.archive.org/web/20200314132548/https://wiki.sa-mp.com/wiki/Main_Page). Ovviamente non si tratta di un'ottima soluzione a lungo termine. Queste pagine impiegano molto tempo per caricare e causano lo stress del servizio di Archive.org (che è già sotto-finanziato e costituisce una parte molto importante della storia di internet) [La Wiki di SA-MP recuperata](/docs) costituisce un'ottima alternativa. Utilizza Markdown ed è hostata tramite GitHub e Vercel. Necessitiamo che gli utenti contribuiscano il più possibile per aiutare a trasferire tutte le pagine della wiki rimasta presso la nuova wiki. Puoi trovare più informazioni qui: https://github.com/openmultiplayer/wiki/issues/27
openmultiplayer/web/frontend/content/it/missing-sites.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/it/missing-sites.mdx", "repo_id": "openmultiplayer", "token_count": 782 }
467
<h1>FAQ - Intrebari Frecvente</h1> <hr /> <h2>Ce este open.mp?</h2> open.mp (Open Multiplayer, OMP) este un mod multiplayer substitut pentru San Andreas, initiat ca si raspuns la regretabila crestere a numarului de probleme cu actualizarile si administrarea SA:MP. Versiunea din urma lansarii oficiale va inlocui complet partea de server. Jucatorii existenti de SA:MP vor putea sa se conecteze la server fara efort. In viitor, un client open.mp va fi disponibil, care va permite lansarea unor noi actualizari. <hr /> <h2>Este acesta un fork?</h2> Nu. Este o rescriere completa, care va fi avantajata de decenii de studiu si experienta. In trecut au existat incercari de a crea Fork-uri ale SA:MP-ului, dar credem ca acestea au avut doua probleme majore: <ol> <li> Se bazau pe codul SA:MP care era folosit fara permisiune. Autorii acestor moduri nu aveau niciun drept legal pentru acel cod, si deci au fost tot timpul cu un pas inapoi, moral dar si legal. Noi refuzam sa folosim acel cod. Asta va lungi timpul de productie, dar se va dovedi a fi cea mai buna decizie. </li> <li> Au incercat sa reinventeze roata. Fie inlocuind motorul de scripting, fie eliminand functionalitati si adaugand altele, fie modificand functionalitati si creand incompatibilitati. Asta previne serverele cu mult cod si multi jucatori de a migra, pentru ca ar fi nevoiti sa schimbe putin, daca nu chiar tot codul - un pas incredibil de costisitor. Suntem ferm motivati sa adaugam functionalitai, sa modificam altele, cu timpul, dar avem si scopul de a suporta orice server deja existent, permitandu-le sa foloseasca acelasi cod, fara modificari. </li> </ol> <hr /> <h2>De ce facem asta?</h2> Desi au fost nenumarate incercari de a avansa productia SA:MP, sub forma de sugestii si oferte de ajutor din partea echipei de beta testeri; alaturi de o comunitate care cerea orice actualizare posibila; niciun progres nu a fost facut. Acest refuz a fost considerat la inceput doar o lipsa de interes din partea liderului modului respectiv, ceea ce nu era o problema, dar nu ar fi existat niciun progres. In loc sa ofere acess pentru productie celor care erau interesati sa ajute, fondatorul incerca sa lase modul sa dispara odata cu lipsa lui de interes, rezolvand doar problemele foarte majore. Unii spun ca asta s-a intamplat din cauza scaderii de venituri, dar nu exista vreo dovada pentru asta. Desi inca exista interes urias din partea comunitatii strans unite, el credea ca modul va mai trai doar 1-2 ani, si ca acea comunitate care a muncit atat de mult pentru a impinge SA:MP pana in pozitia in care este acum, nu merita un astfel de efort. <br /> Noi suntem de alta parere. <hr /> <h2>Ce parere aveti de Kalcor/SA:MP/Altceva?</h2> In primul rand, noi ne aflam aici deoarece iubim SA:MP-ul - si pe această cale ii datoram multumiri lui Kalcor pentru crearea sa. El a facut o multime de lucruri pentru mod de-a lungul anilor si toata aceasta contributie nu ar trebui uitata sau ignorata. Deciziile care au dus la crearea open.mp au fost luate datorita dezacordului nostru cu anumite decizii recente, si in ciuda repetatelor noastre tentative de a ghida mod-ul intr-o directie diferita, nu s-a putut vedea nicio rezolvare in acest sens. Astfel, am fost fortati sa luam nefericita decizie de a incerca sa continuam dezvoltarea SA:MP-ului in acelasi spirit, doar ca fara Kalcor. Nu este o decizie luata impotriva lui, personal, si nici nu ar trebui vazuta ca un atac la persoana lui. Nu vom tolera nicio jignire la adresa altor persoane, chiar daca acestea ar tine partea cauzei open.mp; Ar trebui sa putem avea o dezbatere rezonabila, fara a recurge la atacuri ad-hominem. <hr /> <h2>Nu se ajunge la dezbinarea comunitatii?</h2> Nu aceasta este intentia noastra. Ideal ar fi fost sa nu se produca nicio separare, dar despartirea unora si salvarea lor, este mai buna decat prabusirea intregii comunitati. Ba din contra, inca de la anuntarea lansarii acestui mod, un numar mare de comunitati non-engleze s-au reunit cu comunitatea engleza. Aceste comunitati au fost din ce in ce mai marginalizate in trecut, fiind cu totul date la o parte, asa ca prin reincluderea lor s-a produs reunificarea comunitatilor. Multor oameni le-a fost interzis accesul pe forumul oficial al SA:MP-ului (si in unele cazuri, le-a fost sters tot istoricul postarilor), chiar daca insusi Kalcor a precizat faptul ca forumul oficial nu inseamna SA:MP, fiind doar o parte a sa. Multi jucatori sau detinatori de servere nu au postat vreodata acolo, sau nici macar nu au cont; asa ca, posibilitatea recomunicarii cu acesti oameni unifica si mai multe parti ale comunitatii. <hr /> <h2>Avand in vedere ca se numeste "Open" Multiplayer, codul va fi open-source?</h2> In mod normal acesta ar fi planul. Deocamdata incercam sa facem productia "open" sub forma de comunicare si transparenta (care prin definitie duce spre progres), si vom avansa catre a face codul open-source cand vom avea posibilitatea, odata ce lucrurile se linistesc si totul este stabil. <hr /> <h2>Cand va fi lansarea?</h2> Este o intrebare veche de ani de zile, pusa dintotdeauna. Din pacate, are un raspuns la fel de vechi: Cand este gata. Pur si simplu, nu exista nicio cale de a afla de cat de mult timp are nevoie un astfel de proiect. S-a lucrat in liniste la el de ceva vreme si a avut parte deja de cateva fluctuatii la nivelul de activitate, depinzand in mod direct de disponibilitatea dezvoltatorilor. Va asiguram ca este pe directia cea buna si progreseaza rapid, datorita unor decizii fundamentale de proiectare (Vom vorbi mai multe despre arhitectura ceva mai tarziu). <hr /> <h2>Cum pot ajuta?</h2> Stai cu ochii pe forum. Avem un topic exact pentru asta, si il vom actualiza odata ce vom avea nevoie de ajutor. Desi proiectul a fost dezvaluit mai devreme decat ar fi trebuit, suntem deja in drum spre a face lansarea initiala, dar asta nu inseamna ca si mai mult ajutor nu ar fi apreciat. Multumim anticipat pentru interes, si incredere in acest proiect: <br /> <a href="https://forum.open.mp/showthread.php?tid=99"> <u>Topic "Cum pot ajuta?"</u> </a> <hr /> <h2>Ce este burgershot.gg?</h2> burgershot.gg este un forum de gaming si atat. Multi oameni s-au alaturat ambelor proiecte, si unele actualizari si schimbari la Open MP sunt postate acolo, dar sunt proiecte total independente. Burgershot nu este o proprietate Open MP, si nici invers. Odata ce un website complet al Open MP va fi disponibil, cele doua proiecte vor fi complet separate (in acelasi fel in care SA:MP facea parte, in trecut, din forumul GTAForums). <hr /> <h2>Dar OpenMP ce este?</h2> Proiectul "Open Multi-Processing" este "OpenMP", noi suntem "open.mp". Doua chestii total diferite.
openmultiplayer/web/frontend/content/ro/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/ro/faq.mdx", "repo_id": "openmultiplayer", "token_count": 2522 }
468
--- title: Open.mp'ye taşıma date: "2024-03-06T14:01:00" author: Y_Less --- Uzun bir süredir oldukça açıktır ki Kalcor, SA:MP'yi sürdürme konusunda artık ilgilenmiyordu; ki bu, başlı başına sorun değil, ancak resmi kaynak kodu erişimi olan tek kişi olması, yeni güncellemeler için bir darboğaz oluşturuyordu. YSF ve fixes.inc, bu boşluğu doldurmak amacıyla oluşturuldu - sunucunun kaynak kodu erişimine ihtiyaç duymadan hataları ve tutarsızlıkları düzeltmek; birincisi eklenti olarak, diğeri ise bir include olarak. Bu projeleri mümkün olduğunca istikrarlı, kapsamlı ve kullanımı kolay hale getirmek için bazı büyük çabalar sarf edilmiş olmasına rağmen, doğal olarak sınırlarına ulaştılar ve yeni nesil düzeltmelere ihtiyaç duyuldu. İşte burada open.mp devreye giriyor. Aynı prensiplere dayanarak ve topluluk tarafından on yıllık süreçte geliştirilen bir dizi iyileştirmeyi içeren open.mp, orijinal SA:MP sunucusunun temelden yeniden yazımıdır; doğrudan önceki sürümlerinden gelen tüm düzeltmelerle birlikte, ya yönetilemez ya da açıkça imkansız olan birçok ek düzeltme içerir. Elbette bu yaklaşımın bazı kontroversiyel yönleri vardı - bazı sunucular, topluluğun çabalarından bağımsız olarak SA:MP'nin alışılmış durumlarıyla başa çıkma konusunda kendi özel yöntemlerini geliştirmişti; ancak bunlar, her geliştiricinin kendi başına geliştirmesi gereken teknikler değildir ve bu makale, mevcut kodu taşımak konusunda yardımcı olacaktır. Büyük takılmaları ele almaya çalışıyoruz, ancak gözden kaçırdığımız bir şey varsa, lütfen discord veya github üzerinden bize ulaşın ve rehberi güncellemekten mutluluk duyarız. Alternatif bir seçenek, fixes.inc'in ikizi olan bir kütüphaneyi kullanarak düzeltmeleri geri almaktır: breaks.inc: https://github.com/pawn-lang/sa-mp-fixes/blob/master/breaks.inc Bu kütüphaneyi kullanarak eski davranışlara sorunsuz bir şekilde geri dönmek için bunu yükleyebilirsiniz. ## `Etiketler` Open.mp'nin içerdiği birçok yeni etiket, işlevlere bir denge bulmaya çalışsa da, çok gerekli güncellemeler ile müdahalecilik arasında bir denge kurmaya çalışıyoruz. Bu değişikliklerin ne kadar geniş kapsamlı olabileceği nedeniyle, birçok işlemi otomatikleştirmek için bir araç geliştirdik: ## `HideMenuForPlayer` Bu işlev her zaman bir menü kimliği parametresini almıştır, ancak SA:MP'de bu kimlik kullanılmamıştır. Bu nedenle, verilen değer ne olursa olsun, oyuncunun mevcut menüsü kapatılacaktı, hatta sizin kapatmanız gereken menüye bakmıyorlarsa bile. Eski kod şu şekilde görünürdü: ```pawn gShopMenu = CreateMenu("text", 2, 100.0, 30.0, 7.0); HideMenuForPlayer(gShopMenu, playerid); ``` Bu, oyuncunun gerçekte hangi menüyü incelediğinden bağımsız olarak her zaman oyuncunun mevcut menüsünü kapatırdı. Şimdi hangi menüyü incelediklerini hatırlamanız veya sadece onu almanız gerekecek: ```pawn gShopMenu = CreateMenu("text", 2, 100.0, 30.0, 7.0); HideMenuForPlayer(GetPlayerMenu(playerid), playerid); ``` ## `SetPlayerAttachedObject` SA:MP'de bağlı nesneler oyun modu değişikliğini sağlıyordu, ancak open.mp'de bu durum geçerli değil. Eğer bir oyuncunun nesnelerini mod yeniden başladığında korumasını istiyorsanız, bunları `OnPlayerConnect` içinde yeniden eklemeniz gerekecek ```pawn enum E_ATTACHMENT_DATA { E_ATTACHMENT_DATA_MODEL, E_ATTACHMENT_DATA_BONE, E_ATTACHMENT_DATA_OFFSET_X, E_ATTACHMENT_DATA_OFFSET_Y, E_ATTACHMENT_DATA_OFFSET_Z, E_ATTACHMENT_DATA_ROT_X, E_ATTACHMENT_DATA_ROT_Y, E_ATTACHMENT_DATA_ROT_Z, E_ATTACHMENT_DATA_SCALE_X, E_ATTACHMENT_DATA_SCALE_Y, E_ATTACHMENT_DATA_SCALE_Z, E_ATTACHMENT_DATA_COLOUR_1, E_ATTACHMENT_DATA_COLOUR_2, } public OnPlayerConnect(playerid) { for (new i = 0; i != MAX_OBJECT_ATTACHMENT_SLOTS; ++i) { SetPlayerAttachedObject( playerid, i, gAttachementData[playerid][E_ATTACHMENT_DATA_MODEL], gAttachementData[playerid][E_ATTACHMENT_DATA_BONE], gAttachementData[playerid][E_ATTACHMENT_DATA_OFFSET_X], gAttachementData[playerid][E_ATTACHMENT_DATA_OFFSET_Y], gAttachementData[playerid][E_ATTACHMENT_DATA_OFFSET_Z], gAttachementData[playerid][E_ATTACHMENT_DATA_ROT_X], gAttachementData[playerid][E_ATTACHMENT_DATA_ROT_Y], gAttachementData[playerid][E_ATTACHMENT_DATA_ROT_Z], gAttachementData[playerid][E_ATTACHMENT_DATA_SCALE_X], gAttachementData[playerid][E_ATTACHMENT_DATA_SCALE_Y], gAttachementData[playerid][E_ATTACHMENT_DATA_SCALE_Z], gAttachementData[playerid][E_ATTACHMENT_DATA_COLOUR_1], gAttachementData[playerid][E_ATTACHMENT_DATA_COLOUR_2] ); } } ``` ## `ClearAnimations` `ClearAnimations`, bir oyuncunun önceki talep edilen eylemi gerçekleştirmesini durdurmak için `ApplyAnimation`'ın ikizidir. Ancak, bu bir oyuncuya araç içindeyken kullanıldığında oyuncunun araçtan çıkarılmasına neden olurdu. Bu hızlı bir işlem olduğu için faydalı bir işlevdir, ancak `ClearAnimations` işlevinin kapsamı dışındadır. Bir oyuncuyu hemen bir araçtan çıkarmak için: ```pawn RemovePlayerFromVehicle(playerid, true); ``` ## Hastane Masrafları San Andreas'ta bir oyuncu öldüğünde, otomatik olarak hastane masraflarını karşılamak için onlardan $100 kesilir. Bu özellik SA:MP'de var, fakat open.mp'den kaldırılıyor, böylece kodlar kendi paralarını yönetebilir. Birkaç kod zaten bunu düzeltmeye çalışıyor, oyuncunun ölümünden sonra veya yeniden doğduklarında oyuncuya $100 ekleyerek. Eğer bu senin kodun ise, ek düzeltmeyi sil yeterli; ancak open.mp'deki kodlar, bu işlemi gerçekleştiren kodlara da hesaplamaya çalışır. Eğer senin kodun bu özelliğe dayanıyorsa, sadece aşağıdaki kodu `OnPlayerDeath` içine ekleyin: ```pawn GivePlayerMoney(playerid, -100); ``` ## OnPlayerConnect SA:MP'de bir oyun modu başladığında veya yeniden başladığında, `OnPlayerConnect` tüm oyuncular için hemen çağrılır; ancak bir filter-scriptler içerisinde başladığında veya yeniden başladığında bu çağrılmaz. İlk hareket adından daha yakın olabilir, ancak ikinci hareket kodlarda oldukça yaygın olarak kullanıldığı için open.mp'de tutarlılık sağlamak amacıyla tüm betik türlerine genişletilmiştir. Artık bir oyuncu için veri başlatan betikler, bu kodu iki farklı konumda gerçekleştirmek zorunda değildir: ```pawn public OnFilterScriptInit() { for (new playerid = 0; playerid != MAX_PLAYERS; ++playerid) { if (IsPlayerConnected(playerid)) { InitialisePlayer(playerid); } } } public OnPlayerConnect(playerid) { InitialisePlayer(playerid); } ``` `OnFilterScriptInit` içindeki döngü şimdi kaldırılabilir: ```pawn public OnPlayerConnect(playerid) { InitialisePlayer(playerid); } ``` Eğer bir kod, kodun başladıktan sonra sunucuya katılan yeni oyuncular için kodu çalıştırmak üzere bu durumu istismar ediyorsa, ve önceki oyuncular için çalıştırmıyorsa, bu artık çalışmayacak ancak kolayca düzeltilebilir: ```pawn static bool:gAlreadyHere[MAX_PLAYERS]; public OnFilterScriptInit() { for (new playerid = 0; playerid != MAX_PLAYERS; ++playerid) { gAlreadyHere[playerid] = IsPlayerConnected(playerid); } } public OnPlayerConnect(playerid) { if (gAlreadyHere[playerid]) { gAlreadyHere[playerid] = false; } else { SendClientMessage(playerid, COLOUR_WARN, "Geciktin!"); } } ``` Bu, sadece `OnFilterScriptInit` içindeki bir döngüyü başka bir döngü ile değiştirmek gibi görünebilir, ancak mevcut oyuncuları belirli bir kodun dışında tutmak istemek, herkes için bir şey yapmak istemekten daha az yaygın bir durumdur. Bu nedenle, genel olarak bu bir net iyileşme; ve önceki belirtildiği gibi, oyun modlarında `OnPlayerConnect` çağrılmamasından çok daha az müdahaleci bir değişikliktir. ## Game texts SA:MP has six different game text styles, but several of them are basically unusable. One fades in and out constantly, one disappears after a set time regardless of the time you put, and one never disappears regardless of the time selected. However it turns out that all of these game text styles can be accurately\* reproduced using text draws. Thus fixes.inc and subsequently open.mp did so. The appearance of the game texts is the same as before, the advantage being that all styles are usable, with the downside being that they no longer fade in and out. There is currently no way to bypass this feature to get the fading back, except for using Pawn.RakNet and sending the game text messages directly: SA:MP'de altı farklı oyun metni stili bulunmaktadır, ancak bunlardan birkaçı temelde kullanılamaz durumdadır. Bir tanesi sürekli olarak belirir ve kaybolur, bir tanesi belirli bir süre sonra kaybolur, belirtilen süreyi takip etmeksizin, ve bir tanesi seçilen süreye bakılmaksızın hiç kaybolmaz. Ancak, bu oyun metni stillerinin tümü doğru bir şekilde\* metin çizimleri kullanılarak yeniden üretilebilir. Bu nedenle fixes.inc ve ardından open.mp bunu yaptı. Oyun metinlerinin görünümü öncekiyle aynıdır, avantajı ise tüm stillerin kullanılabilir olmasıdır; ancak dezavantajı ise artık belirir ve kaybolmazlar. Şu anda bu özelliği atlamak ve tekrar belirip kaybolma efektini elde etmek için doğrudan Pawn.RakNet kullanmak dışında bir yol bulunmamaktadır: ```pawn FadingGameTextForPlayer(playerid, const format[], time, style) { if (style > 6) { // Bu stillerin bir kaybolma versiyonu yok. GameTextForPlayer(playerid, format, time, style) } else { // Pawn.RakNet aracılığıyla düz bir ileti gönder } } ``` \* Ancak dikkate değer bir istisna var - yeni saat oyun metni stili. Bilinmeyen bir nedenle, saat rengi farklı kişiler için farklıdır, bu da bu stili en iyi nasıl taklit edeceğimize dair birçok geri ve ileri tartışmaya yol açtı, farklılık bulunana kadar. Tutarlılık için ikisinden birini seçmek zorunda kaldık. ## Havuz Boyutları `GetPlayerPoolSize`, `GetActorPoolSize`, ve `GetVehiclePoolSize` ilk kez kullanılmaya başlandığında biraz anlamsızdı; en yüksek bağlı ID'yi döndürerek, bağlı oyuncu sayısı ile hiçbir ilgisi olmayan bir değer. Zaten çok daha iyi döngüleme yöntemleri mevcutken ve uzun zaman sonra tanıtılmışlardı. Biraz saçma olmak, başlı başına bir fonksiyonu kaldırmak için bir neden değildir, ancak maalesef bunlar aynı zamanda bozuk ve bağlı oyuncu olmadığında yanlış veri döndürürler. Bu değerleri hem geriye dönük uyumlu hem de ileriye dönük doğru bir şekilde düzeltecek bir yol bulunmamaktadır (bana inanın, denedik). Bu gerçeklere göre, fonksiyonları basitçe kaldırmaya karar verdik. Sadece normal bir döngü veya `foreach` kullanın: ```pawn foreach (new i : Player) { } ``` Bu değişiklik tanıtıldığında yalnızca aşağıdaki döngü formunu kullanırken bazı kodlar çökebilirdi: ```pawn for (new i = 0; i != GetPlayerPoolSize(); ++i) { } ``` Ancak çevrimiçi kişiler olduğunda en yüksek değer bir gerçek oyuncudur, bu nedenle bu kod zaten yanlıştır - bir kişiyi atlar. ## Yazımlar SA:MP kodlamalarında çok tutarsız bir imla kullanımı var - bazı şeyler İngilizce, bazı şeyler Amerikan İngilizcesi kullanıyor: * `Bumper` - İngilizce * `Hood` - Amerikan İngilizcesi * `Armour` - İngilizce * `Stereo` - Amerikan İngilizcesi Bunları birleştirdik ve İngilizce imla kullanımına karar verdik. Örneğin: ```pawn TextDrawBoxColor(Text:textid, boxColor); ``` Şimdi: ```pawn TextDrawBoxColour(Text:textid, boxColour); ``` Yükseltme aracı, bunların çoğunu otomatik olarak ele alacaktır.
openmultiplayer/web/frontend/content/tr/blog/porting.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/tr/blog/porting.mdx", "repo_id": "openmultiplayer", "token_count": 5165 }
469
# اوپن ملٹی پلیئر جی ٹی اے ایس اے کے لئے ایک آنے والا ملٹی پلیئر موڈ جو موجودہ ملٹی پلیئر موڈ سان اینڈریاس ملٹی پلیئر کے ساتھ مکمل طور پر ہم آہنگ ہوگا۔ <br /> اس کے مطلب ہے کہ موجودہ ایس اے ایم پی کلائنٹ اور تمام موجودہ ایس اے ایم پی اسکرپٹس اوپن ایم پی کے ساتھ کام کریں گی، اور اس کے ساتھ ساتھ، سرور سافٹ ویر میں بہت سارے مسائل بھی ہیکس اور جگار بغیر حل کیے جائے گے۔ اگر آپ سوچ رہے ہیں کہ عوامی ریلیز کا منصوبہ کب تیار کیا گیا ہے یا آپ اس منصوبے میں حصہ ڈالنے میں کس طرح مدد کرسکتے ہیں تو برائے کرم [اس فورم](https://forum.open.mp/showthread.php?tid=99) پر تشریف لے جائے مزید معلومات کے لیے۔ # [عمومی سوالات](/faq)
openmultiplayer/web/frontend/content/ur/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/ur/index.mdx", "repo_id": "openmultiplayer", "token_count": 733 }
470
{ "name": "frontend", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "test": "eslint --ext .tsx,.ts src/" }, "dependencies": { "@babel/core": "^7.14.8", "@babel/generator": "^7.14.8", "@babel/parser": "^7.14.8", "@babel/preset-env": "^7.14.8", "@babel/preset-react": "^7.14.5", "@babel/traverse": "^7.14.8", "@chakra-ui/icons": "^1.0.15", "@chakra-ui/react": "^1.7.0", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.3.0", "@hookform/resolvers": "^2.7.1", "@mdx-js/loader": "^1.6.22", "@mdx-js/mdx": "^1.6.22", "@microflash/rehype-starry-night": "https://github.com/AmyrAhmady/rehype-starry-night", "cookie": "^0.4.1", "date-fns": "^2.22.1", "emoji-mart": "^3.0.1", "framer-motion": "^5.3.0", "fuse.js": "^6.4.6", "glob": "^7.1.7", "gray-matter": "^4.0.3", "html-react-parser": "^1.2.7", "iso-639-1": "^2.1.9", "js-cookie": "^2.2.1", "lodash": "^4.17.21", "lodash.debounce": "^4.0.8", "next": "^12.0.1", "next-mdx-remote": "^4.0.2", "next-seo": "^4.26.0", "normalize.css": "^8.0.1", "nprogress": "^0.2.0", "polished": "^4.1.3", "react": "17.0.2", "react-color": "^2.19.3", "react-dom": "17.0.2", "react-hook-form": "^7.12.2", "react-markdown": "^6.0.3", "react-nextjs-toast": "^1.2.5", "react-sortablejs": "^6.0.0", "react-twemoji": "^0.3.0", "remark-admonitions": "^1.2.1", "remark-gfm": "^3.0.1", "remark-html": "^13.0.1", "remark-parse": "^9.0.0", "rich-markdown-editor": "^11.17.2", "sortablejs": "^1.14.0", "styled-components": "^5.3.1", "swr": "^1.0.1", "tachyons": "^4.12.0", "twemoji": "^13.1.0", "unified": "^10.0.0", "zod": "^3.7.1" }, "devDependencies": { "@types/babel__core": "^7.1.15", "@types/babel__preset-env": "^7.9.2", "@types/cookie": "^0.4.1", "@types/emoji-mart": "^3.0.8", "@types/glob": "^7.1.4", "@types/lodash": "^4.14.171", "@types/lodash.debounce": "^4.0.6", "@types/node": "^16.3.3", "@types/nprogress": "^0.2.0", "@types/react": "^17.0.14", "@types/react-color": "^3.0.6", "@types/react-dom": "^17.0.9", "@types/sortablejs": "^1.10.7", "@types/twemoji": "^12.1.2", "@typescript-eslint/eslint-plugin": "^4.14.2", "@typescript-eslint/parser": "^4.14.2", "eslint": "^7.19.0", "eslint-config-next": "^11.1.0", "eslint-plugin-react": "^7.22.0", "typescript": "4.9.5", "unist-util-visit": "^3.1.0" } }
openmultiplayer/web/frontend/package.json/0
{ "file_path": "openmultiplayer/web/frontend/package.json", "repo_id": "openmultiplayer", "token_count": 1494 }
471
import { NextPage } from "next"; import withAuthRedirect from "./withAuthRedirect"; /** * Ensures a page is only displayed for users who are authenticated. * * @param WrappedComponent Page component. * @param location location to redirect to if not authenticated. */ export function withAuth<P>( WrappedComponent: NextPage<P>, location = "/login" ) { return withAuthRedirect(WrappedComponent, true, location); } /** * Ensures a page is only displayed for users who are NOT authenticated. * * @param WrappedComponent Page component. * @param location location to redirect to if user is actually authenticated. */ export function withoutAuth<P>( WrappedComponent: React.FunctionComponent<P>, location = "/dashboard" ) { return withAuthRedirect(WrappedComponent, false, location); }
openmultiplayer/web/frontend/src/auth/hoc.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/auth/hoc.tsx", "repo_id": "openmultiplayer", "token_count": 215 }
472
const DiscordIcon = ({ width = 32, height = 32, fill = "#7289DA" }) => ( <svg xmlns="http://www.w3.org/2000/svg" width={width} height={height} viewBox="0 0 245 240" > <path fill={fill} d="M104.4 103.9c-5.7 0-10.2 5-10.2 11.1s4.6 11.1 10.2 11.1c5.7 0 10.2-5 10.2-11.1.1-6.1-4.5-11.1-10.2-11.1zM140.9 103.9c-5.7 0-10.2 5-10.2 11.1s4.6 11.1 10.2 11.1c5.7 0 10.2-5 10.2-11.1s-4.5-11.1-10.2-11.1z" /> <path fill={fill} d="M189.5 20h-134C44.2 20 35 29.2 35 40.6v135.2c0 11.4 9.2 20.6 20.5 20.6h113.4l-5.3-18.5 12.8 11.9 12.1 11.2 21.5 19V40.6c0-11.4-9.2-20.6-20.5-20.6zm-38.6 130.6s-3.6-4.3-6.6-8.1c13.1-3.7 18.1-11.9 18.1-11.9-4.1 2.7-8 4.6-11.5 5.9-5 2.1-9.8 3.5-14.5 4.3-9.6 1.8-18.4 1.3-25.9-.1-5.7-1.1-10.6-2.7-14.7-4.3-2.3-.9-4.8-2-7.3-3.4-.3-.2-.6-.3-.9-.5-.2-.1-.3-.2-.4-.3-1.8-1-2.8-1.7-2.8-1.7s4.8 8 17.5 11.8c-3 3.8-6.7 8.3-6.7 8.3-22.1-.7-30.5-15.2-30.5-15.2 0-32.2 14.4-58.3 14.4-58.3 14.4-10.8 28.1-10.5 28.1-10.5l1 1.2c-18 5.2-26.3 13.1-26.3 13.1s2.2-1.2 5.9-2.9c10.7-4.7 19.2-6 22.7-6.3.6-.1 1.1-.2 1.7-.2 6.1-.8 13-1 20.2-.2 9.5 1.1 19.7 3.9 30.1 9.6 0 0-7.9-7.5-24.9-12.7l1.4-1.6s13.7-.3 28.1 10.5c0 0 14.4 26.1 14.4 58.3 0 0-8.5 14.5-30.6 15.2z" /> </svg> ); export default DiscordIcon;
openmultiplayer/web/frontend/src/components/icons/Discord.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/icons/Discord.tsx", "repo_id": "openmultiplayer", "token_count": 868 }
473
// From: https://jonsuh.com/hamburgers/ const Hamburger = ({ className = "", active, toggle, }: { className?: string; active: boolean; toggle: (_: boolean) => void; }) => ( <> <button className={[className, "hamburger", active && "is-active"].join(" ")} type="button" aria-label="Menu" aria-controls="navigation" onClick={() => toggle(!active)} > <span className="hamburger-box"> <span className="hamburger-inner"></span> </span> </button> <style jsx>{` .hamburger { padding: 15px 15px; display: inline-block; cursor: pointer; transition-property: opacity, filter; transition-duration: 0.15s; transition-timing-function: linear; font: inherit; color: inherit; text-transform: none; background-color: transparent; border: 0; margin: 0; overflow: visible; } .hamburger:hover { opacity: 0.7; } .hamburger.is-active:hover { opacity: 0.7; } .hamburger.is-active .hamburger-inner, .hamburger.is-active .hamburger-inner::before, .hamburger.is-active .hamburger-inner::after { background-color: #000; } .hamburger-box { width: 40px; height: 24px; display: inline-block; position: relative; } .hamburger-inner { display: block; top: 50%; margin-top: -2px; } .hamburger-inner, .hamburger-inner::before, .hamburger-inner::after { width: 40px; height: 4px; background-color: #000; border-radius: 4px; position: absolute; transition-property: transform; transition-duration: 0.15s; transition-timing-function: ease; } .hamburger-inner::before, .hamburger-inner::after { content: ""; display: block; } .hamburger-inner::before { top: -10px; } .hamburger-inner::after { bottom: -10px; } .hamburger .hamburger-inner::before, .hamburger .hamburger-inner::after { transition: bottom 0.08s 0s ease-out, top 0.08s 0s ease-out, opacity 0s linear; } .hamburger.is-active .hamburger-inner::before, .hamburger.is-active .hamburger-inner::after { opacity: 0; transition: bottom 0.08s ease-out, top 0.08s ease-out, opacity 0s 0.08s linear; } .hamburger.is-active .hamburger-inner::before { top: 0; } .hamburger.is-active .hamburger-inner::after { bottom: 0; } `}</style> </> ); export default Hamburger;
openmultiplayer/web/frontend/src/components/site/Hamburger.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/site/Hamburger.tsx", "repo_id": "openmultiplayer", "token_count": 1332 }
474
import Admonition from "../../../Admonition"; export default function WarningVersion({ version, name = "function", }: { version: string; name: string; }) { return ( <Admonition type="warning"> <p> {name} ini telah ditambahkan dalam {version} dan tidak bekerja pada versi dibawahnya! </p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/translations/id/version-warning.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/translations/id/version-warning.tsx", "repo_id": "openmultiplayer", "token_count": 149 }
475
/* eslint-disable react-hooks/rules-of-hooks */ import React from "react"; import { mdx, MDXProvider } from "@mdx-js/react"; import { useEffect } from "react"; import { MDX_COMPONENTS } from "./components"; import { MarkdownContent, MarkdownRenderConfig } from "./types"; import "./idle-callback-polyfill"; // Renders markdown content on the client side using the props passed to the // page component from `markdownSSR`. export const markdownCSR = (content: MarkdownContent): JSX.Element => hydrate(content, { components: MDX_COMPONENTS, }); // Stolen from Hashicorp's next-mdx-remote! export const hydrate = ( { compiledSource, renderedOutput, scope }: MarkdownContent, { components }: MarkdownRenderConfig ): JSX.Element => { // our default result is the server-rendered output // we get this in front of users as quickly as possible const [result, setResult] = React.useState<JSX.Element>( React.createElement("div", { dangerouslySetInnerHTML: { __html: renderedOutput, }, }) ); // if we're on the client side, we hydrate the mdx content inside // requestIdleCallback, since we can be fairly confident that // markdown - embedded components are not a high priority to get // to interactive compared to...anything else on the page. // // once the hydration is complete, we update the state/memo value and // react re-renders for us useEffect(() => { const handle = window.requestIdleCallback(() => { // first we set up the scope which has to include the mdx custom // create element function as well as any components we're using const fullScope = { mdx, ...components, ...scope }; const keys = Object.keys(fullScope); const values = Object.values(fullScope); // now we eval the source code using a function constructor // in order for this to work we need to have React, the mdx createElement, // and all our components in scope for the function, which is the case here // we pass the names (via keys) in as the function's args, and execute the // function with the actual values. const hydratedFn = new Function( "React", ...keys, `${compiledSource} return React.createElement(MDXContent, { });` )(React, ...values); // wrapping the content with MDXProvider will allow us to customize the standard // markdown components (such as "h1" or "a") with the "components" object const wrappedWithMdxProvider = React.createElement( MDXProvider, { components }, hydratedFn ); // finally, set the the output as the new result so that react will re-render for us // and cancel the idle callback since we don't need it anymore setResult(wrappedWithMdxProvider); window.cancelIdleCallback(handle); }); }, [compiledSource]); // if we're server-side, we can return the raw output early if (typeof window === "undefined") { return result; } return result; };
openmultiplayer/web/frontend/src/mdx-helpers/csr.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/mdx-helpers/csr.ts", "repo_id": "openmultiplayer", "token_count": 980 }
476
import { useEffect, useState } from "react"; import { NextSeo } from "next-seo"; // import { MDXRemote } from "next-mdx-remote"; // import remarkGfm from "remark-gfm"; import components from "src/components/templates"; // - // Client side // - import { hydrate } from "src/mdx-helpers/csr"; import { DocsSidebar } from "src/components/Sidebar"; import Admonition from "src/components/Admonition"; type Props = { source?: any; error?: string; data?: { [key: string]: any }; fallback?: boolean; ghUrl?: string; }; const Page = (props: Props) => { const [isMounted, setIsMounted] = useState(false); // hydrate contains hook calls, and hooks must always be called // unconditionally. Because they are called from a regular function here and // not a nested component, the unconditionality applies to the call stack of // *this* component, so the content must be hydrated regardless of whether or // not there was an error in the following if-statement. const content = props.source && hydrate(props.source, { components: components as Components }); const codeColor = useColorModeValue( "var(--chakra-colors-gray-200)", "var(--chakra-colors-gray-700)" ); const tableRowBgColor = useColorModeValue( "var(--chakra-colors-gray-50)", "var(--chakra-colors-gray-700)" ); useEffect(() => setIsMounted(true), []); if (props.error) { return ( <section className="mw7 pa3 measure-wide center"> <h1>Error!</h1> <p>{props.error}</p> </section> ); } const contributeCallToAction = props.fallback ? ( <Admonition type="warning" title="Not Translated"> <p> This page has not been translated into the language that your browser requested yet. The English content is being shown as a fallback. </p> <p> If you want to contribute a translation for this page then please click{" "} <a href={props.ghUrl}>here</a>. </p> </Admonition> ) : ( // TODO: would we want to translate this into the locale selected? <Admonition type="note" title="Help Needed"> <p> This wiki is the result of an ongoing community effort — thank you all for helping! </p> <p> If you want to provide changes to this page then please click{" "} <a href={props.ghUrl}>here</a>. </p> </Admonition> ); return ( <div className="flex flex-column flex-auto items-stretch"> <NextSeo title={props?.data?.title} description={props?.data?.description} /> <div className="flex flex-column flex-row-ns justify-center-ns"> <div className="flex flex-column flex-grow"> <Search /> {isMounted && <DocsSidebar />} </div> <section className="mw7 pa3 flex-auto"> {!props.error && contributeCallToAction} <h1>{props?.data?.title}</h1> {/* <MDXRemote {...props.source} components={components} /> */} {content} <style global jsx>{` pre, code { background: ${codeColor}; } table { border-collapse: collapse; border-spacing: 0; display: block; margin-bottom: 1rem; margin-top: 0; overflow: auto; width: 100%; } table tr { background-color: transparent; border-top: 1px solid #dadde1; } table tr:nth-child(2n) { background-color: ${tableRowBgColor}; } table td, table th { border: 1px solid #dadde1; padding: 0.75rem; } table th { background-color: inherit; color: inherit; font-weight: 700; } table td { color: inherit; } `}</style> </section> <nav>{/* TODO: Table of contents */}</nav> </div> </div> ); }; // - // Server side // - import { extname } from "path"; import { readdirSync, statSync } from "fs"; import { GetStaticPathsContext, GetStaticPathsResult, GetStaticPropsContext, GetStaticPropsResult, } from "next"; import matter from "gray-matter"; import glob from "glob"; import admonitions from "remark-admonitions"; import { concat, filter, flatten, flow, map } from "lodash/fp"; // import { serialize } from "next-mdx-remote/serialize"; import rehypeStarryNight from "@microflash/rehype-starry-night"; import { getDocsGithubUrl, readLocaleDocs } from "src/utils/content"; import Search from "src/components/Search"; import { deriveError } from "src/fetcher/fetcher"; import { renderToString } from "src/mdx-helpers/ssr"; import { Components } from "@mdx-js/react"; import { useColorModeValue } from "@chakra-ui/react"; export async function getStaticProps( context: GetStaticPropsContext<{ path: string[] }> ): Promise<GetStaticPropsResult<Props>> { const { locale } = context; const route = context?.params?.path || ["index"]; let result: { source: string; fallback: boolean }; const path = route.join("/"); try { result = await readLocaleDocs(path, locale); } catch (e) { return { props: { error: `File ${path} (${locale}) not found: ${deriveError(e).error}`, }, }; } const { content, data } = matter(result.source); // TODO: plugin for frontmatter const mdxSource = await renderToString(content, { components, mdxOptions: { remarkPlugins: [ admonitions, // remarkGfm, ], rehypePlugins: [ [rehypeStarryNight, { showHeader: false, showLines: false }], ], }, }); return { props: { source: mdxSource, data, fallback: result.fallback, ghUrl: getDocsGithubUrl(path, !result.fallback, locale), }, }; } export async function getStaticPaths( ctx: GetStaticPathsContext ): Promise<GetStaticPathsResult> { type P = { path: string[] }; type Path = { params: P; locale?: string }; // read docs from the repo root const all = glob.sync("../docs/**/*.md"); // Function to get the directory tree as a list of paths. This is recursive. const walk = (root: string): string[] => flow( // Prefix the directory item name with the root directory path map((path: string) => root + "/" + path), // Filter out non-directories. filter((path: string) => statSync(path).isDirectory()), // Mix in the paths being iterated with their children, the pipeline is // now dealing with string[][] map((path: string) => concat(path)(walk(path))), // Flatten string[][] back to string[] for yielding flatten )(readdirSync(root)); const paths: Array<Path> = flow( // Mix in the flat list of directories from the above recursive function concat(walk("../docs")), // Filter out translations directory - these are handled separately filter((v: string) => v.indexOf("translations") === -1), // Filter out category content pages filter((v: string) => !v.endsWith("_.md")), // Chop off the `../docs/` base path map((v: string) => v.replace("../docs/", "")), // Chop off the file extension map((v: string) => v.slice(0, v.length - extname(v).length)), // slices off "index" from pages so they lead to the base path map((v: string) => (v.endsWith("index") ? v.slice(0, v.length - 5) : v)), // Add the docs base path (open.mp/docs) concat([""]), // Transform the paths into Path objects for "en" locale map((v: string) => ({ params: { path: v.split("/"), }, locale: "en", })) )(all); return { paths: paths, fallback: "blocking", }; } export default Page;
openmultiplayer/web/frontend/src/pages/docs/[[...path]].tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/docs/[[...path]].tsx", "repo_id": "openmultiplayer", "token_count": 3206 }
477
/* Notes: English Grotesque is the primary brand typeface for headings 1, 2, 3 and 4. Paragraphcs should use the sans serif default stack from `body`. */ @import "./fonts.css"; @import "./starry-night.css"; body { color: #000; background: #fefefe; } /* Necessary to prevent overflow issues in flexbox. */ :not(pre) > code { background-color: var(--ifm-code-background); border-radius: var(--ifm-code-border-radius); color: var(--ifm-code-color); font-family: var(--ifm-font-family-monospace); font-size: var(--ifm-code-font-size); margin: 0; padding: var(--ifm-code-padding-vertical) var(--ifm-code-padding-horizontal); } table { border-collapse: collapse; border-spacing: 0; display: block; margin-bottom: 1rem; margin-top: 0; overflow: auto; width: 100%; } table tr { background-color: transparent; border-top: 1px solid #dadde1; } table tr:nth-child(2n) { background-color: #f5f6f7; } table td, table th { border: 1px solid #dadde1; padding: 0.75rem; } table th { background-color: inherit; color: inherit; font-weight: 700; } table td { color: inherit; } @media (prefers-color-scheme: dark) { body { color: #fff; background: var(--chakra-colors-gray-800); } } details > summary { cursor: pointer; }
openmultiplayer/web/frontend/src/styles/base.css/0
{ "file_path": "openmultiplayer/web/frontend/src/styles/base.css", "repo_id": "openmultiplayer", "token_count": 501 }
478
import ISO6391 from "iso-639-1"; const missingLanguages: Record<string, string> = { "zh-tw": "繁體中文", "zh-cn": "简体中文", "ar": "العربية", "pt-BR": "Português do Brasil" }; const getLanguageName = (short: string) => ISO6391.getNativeName(short) || missingLanguages?.[short] || short; export default getLanguageName;
openmultiplayer/web/frontend/src/utils/getLanguageName.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/utils/getLanguageName.ts", "repo_id": "openmultiplayer", "token_count": 139 }
479
package infrastructure import ( "go.uber.org/fx" "github.com/openmultiplayer/web/internal/cache" "github.com/openmultiplayer/web/internal/config" "github.com/openmultiplayer/web/internal/db" "github.com/openmultiplayer/web/internal/github" "github.com/openmultiplayer/web/internal/logger" ) func Build() fx.Option { return fx.Options( logger.Build(), cache.Build(), fx.Provide( config.New, db.New, github.New, ), ) }
openmultiplayer/web/internal/infrastructure/infrastructure.go/0
{ "file_path": "openmultiplayer/web/internal/infrastructure/infrastructure.go", "repo_id": "openmultiplayer", "token_count": 180 }
480
-- AlterTable ALTER TABLE "User" ADD COLUMN "deletedAt" TIMESTAMP(3);
openmultiplayer/web/prisma/migrations/20210821184144_user_deleted_at/migration.sql/0
{ "file_path": "openmultiplayer/web/prisma/migrations/20210821184144_user_deleted_at/migration.sql", "repo_id": "openmultiplayer", "token_count": 30 }
481
# NOTE: changing paths may require updating them in the Makefile too. node_modules modules/**/scripts frontend/js/vendor modules/**/frontend/js/vendor public/js public/minjs
overleaf/web/.eslintignore/0
{ "file_path": "overleaf/web/.eslintignore", "repo_id": "overleaf", "token_count": 53 }
482
const metrics = require('@overleaf/metrics') const AnalyticsManager = require('./AnalyticsManager') const SessionManager = require('../Authentication/SessionManager') const GeoIpLookup = require('../../infrastructure/GeoIpLookup') const Features = require('../../infrastructure/Features') module.exports = { updateEditingSession(req, res, next) { if (!Features.hasFeature('analytics')) { return res.sendStatus(202) } const userId = SessionManager.getLoggedInUserId(req.session) const { projectId } = req.params let countryCode = null if (userId) { GeoIpLookup.getDetails(req.ip, function (err, geoDetails) { if (err) { metrics.inc('analytics_geo_ip_lookup_errors') } else if (geoDetails && geoDetails.country_code) { countryCode = geoDetails.country_code } AnalyticsManager.updateEditingSession(userId, projectId, countryCode) }) } res.sendStatus(202) }, recordEvent(req, res, next) { if (!Features.hasFeature('analytics')) { return res.sendStatus(202) } const userId = SessionManager.getLoggedInUserId(req.session) || req.sessionID AnalyticsManager.recordEvent(userId, req.params.event, req.body) res.sendStatus(202) }, }
overleaf/web/app/src/Features/Analytics/AnalyticsController.js/0
{ "file_path": "overleaf/web/app/src/Features/Analytics/AnalyticsController.js", "repo_id": "overleaf", "token_count": 475 }
483
const { callbackify } = require('util') const metrics = require('@overleaf/metrics') const UserUpdater = require('../User/UserUpdater') async function optIn(userId) { await UserUpdater.promises.updateUser(userId, { $set: { betaProgram: true } }) metrics.inc('beta-program.opt-in') } async function optOut(userId) { await UserUpdater.promises.updateUser(userId, { $set: { betaProgram: false }, }) metrics.inc('beta-program.opt-out') } const BetaProgramHandler = { optIn: callbackify(optIn), optOut: callbackify(optOut), } BetaProgramHandler.promises = { optIn, optOut, } module.exports = BetaProgramHandler
overleaf/web/app/src/Features/BetaProgram/BetaProgramHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/BetaProgram/BetaProgramHandler.js", "repo_id": "overleaf", "token_count": 223 }
484
/* eslint-disable node/handle-callback-err, max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * 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 ClsiStateManager const Settings = require('@overleaf/settings') const logger = require('logger-sharelatex') const crypto = require('crypto') const ProjectEntityHandler = require('../Project/ProjectEntityHandler') // The "state" of a project is a hash of the relevant attributes in the // project object in this case we only need the rootFolder. // // The idea is that it will change if any doc or file is // created/renamed/deleted, and also if the content of any file (not // doc) changes. // // When the hash changes the full set of files on the CLSI will need to // be updated. If it doesn't change then we can overwrite changed docs // in place on the clsi, getting them from the docupdater. // // The docupdater is responsible for setting the key in redis, and // unsetting it if it removes any documents from the doc updater. const buildState = s => crypto.createHash('sha1').update(s, 'utf8').digest('hex') module.exports = ClsiStateManager = { computeHash(project, options, callback) { if (callback == null) { callback = function (err, hash) {} } return ProjectEntityHandler.getAllEntitiesFromProject( project, function (err, docs, files) { const fileList = Array.from(files || []).map( f => `${f.file._id}:${f.file.rev}:${f.file.created}:${f.path}` ) const docList = Array.from(docs || []).map( d => `${d.doc._id}:${d.path}` ) const sortedEntityList = [ ...Array.from(docList), ...Array.from(fileList), ].sort() // ignore the isAutoCompile options as it doesn't affect the // output, but include all other options e.g. draft const optionsList = (() => { const result = [] const object = options || {} for (const key in object) { const value = object[key] if (!['isAutoCompile'].includes(key)) { result.push(`option ${key}:${value}`) } } return result })() const sortedOptionsList = optionsList.sort() const hash = buildState( [ ...Array.from(sortedEntityList), ...Array.from(sortedOptionsList), ].join('\n') ) return callback(null, hash) } ) }, }
overleaf/web/app/src/Features/Compile/ClsiStateManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Compile/ClsiStateManager.js", "repo_id": "overleaf", "token_count": 1070 }
485
/* 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 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let EditorRealTimeController const Settings = require('@overleaf/settings') const Metrics = require('@overleaf/metrics') const RedisWrapper = require('../../infrastructure/RedisWrapper') const rclient = RedisWrapper.client('pubsub') const os = require('os') const crypto = require('crypto') const HOST = os.hostname() const RND = crypto.randomBytes(4).toString('hex') // generate a random key for this process let COUNT = 0 module.exports = EditorRealTimeController = { emitToRoom(room_id, message, ...payload) { // create a unique message id using a counter const message_id = `web:${HOST}:${RND}-${COUNT++}` var channel if (room_id === 'all' || !Settings.publishOnIndividualChannels) { channel = 'editor-events' } else { channel = `editor-events:${room_id}` } const blob = JSON.stringify({ room_id, message, payload, _id: message_id, }) Metrics.summary('redis.publish.editor-events', blob.length, { status: message, }) return rclient.publish(channel, blob) }, emitToAll(message, ...payload) { return this.emitToRoom('all', message, ...Array.from(payload)) }, }
overleaf/web/app/src/Features/Editor/EditorRealTimeController.js/0
{ "file_path": "overleaf/web/app/src/Features/Editor/EditorRealTimeController.js", "repo_id": "overleaf", "token_count": 556 }
486
/* eslint-disable node/handle-callback-err, max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let FileHashManager const crypto = require('crypto') const logger = require('logger-sharelatex') const fs = require('fs') const _ = require('underscore') module.exports = FileHashManager = { computeHash(filePath, callback) { if (callback == null) { callback = function (error, hashValue) {} } callback = _.once(callback) // avoid double callbacks // taken from v1/history/storage/lib/blob_hash.js const getGitBlobHeader = byteLength => `blob ${byteLength}` + '\x00' const getByteLengthOfFile = cb => fs.stat(filePath, function (err, stats) { if (err != null) { return cb(err) } return cb(null, stats.size) }) return getByteLengthOfFile(function (err, byteLength) { if (err != null) { return callback(err) } const input = fs.createReadStream(filePath) input.on('error', function (err) { logger.warn({ filePath, err }, 'error opening file in computeHash') return callback(err) }) const hash = crypto.createHash('sha1') hash.setEncoding('hex') hash.update(getGitBlobHeader(byteLength)) hash.on('readable', function () { const result = hash.read() if (result != null) { return callback(null, result.toString('hex')) } }) return input.pipe(hash) }) }, }
overleaf/web/app/src/Features/FileStore/FileHashManager.js/0
{ "file_path": "overleaf/web/app/src/Features/FileStore/FileHashManager.js", "repo_id": "overleaf", "token_count": 691 }
487
/* 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const InactiveProjectManager = require('./InactiveProjectManager') module.exports = { deactivateOldProjects(req, res) { const numberOfProjectsToArchive = parseInt( req.body.numberOfProjectsToArchive, 10 ) const { ageOfProjects } = req.body return InactiveProjectManager.deactivateOldProjects( numberOfProjectsToArchive, ageOfProjects, function (err, projectsDeactivated) { if (err != null) { return res.sendStatus(500) } else { return res.send(projectsDeactivated) } } ) }, deactivateProject(req, res) { const { project_id } = req.params return InactiveProjectManager.deactivateProject(project_id, function (err) { if (err != null) { return res.sendStatus(500) } else { return res.sendStatus(200) } }) }, }
overleaf/web/app/src/Features/InactiveData/InactiveProjectController.js/0
{ "file_path": "overleaf/web/app/src/Features/InactiveData/InactiveProjectController.js", "repo_id": "overleaf", "token_count": 478 }
488
/* eslint-disable camelcase, node/handle-callback-err, max-len, no-cond-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let MetaHandler const ProjectEntityHandler = require('../Project/ProjectEntityHandler') const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler') const packageMapping = require('./packageMapping') module.exports = MetaHandler = { labelRegex() { return /\\label{(.{0,80}?)}/g }, usepackageRegex() { return /^\\usepackage(?:\[.{0,80}?])?{(.{0,80}?)}/g }, ReqPackageRegex() { return /^\\RequirePackage(?:\[.{0,80}?])?{(.{0,80}?)}/g }, getAllMetaForProject(projectId, callback) { if (callback == null) { callback = function (err, projectMeta) {} } return DocumentUpdaterHandler.flushProjectToMongo( projectId, function (err) { if (err != null) { return callback(err) } return ProjectEntityHandler.getAllDocs(projectId, function (err, docs) { if (err != null) { return callback(err) } const projectMeta = MetaHandler.extractMetaFromProjectDocs(docs) return callback(null, projectMeta) }) } ) }, getMetaForDoc(projectId, docId, callback) { if (callback == null) { callback = function (err, docMeta) {} } return DocumentUpdaterHandler.flushDocToMongo( projectId, docId, function (err) { if (err != null) { return callback(err) } return ProjectEntityHandler.getDoc( projectId, docId, function (err, lines) { if (err != null) { return callback(err) } const docMeta = MetaHandler.extractMetaFromDoc(lines) return callback(null, docMeta) } ) } ) }, extractMetaFromDoc(lines) { let pkg const docMeta = { labels: [], packages: {} } const packages = [] const label_re = MetaHandler.labelRegex() const package_re = MetaHandler.usepackageRegex() const req_package_re = MetaHandler.ReqPackageRegex() for (const line of Array.from(lines)) { var labelMatch var clean, messy, packageMatch while ((labelMatch = label_re.exec(line))) { var label if ((label = labelMatch[1])) { docMeta.labels.push(label) } } while ((packageMatch = package_re.exec(line))) { if ((messy = packageMatch[1])) { for (pkg of Array.from(messy.split(','))) { if ((clean = pkg.trim())) { packages.push(clean) } } } } while ((packageMatch = req_package_re.exec(line))) { if ((messy = packageMatch[1])) { for (pkg of Array.from(messy.split(','))) { if ((clean = pkg.trim())) { packages.push(clean) } } } } } for (pkg of Array.from(packages)) { if (packageMapping[pkg] != null) { docMeta.packages[pkg] = packageMapping[pkg] } } return docMeta }, extractMetaFromProjectDocs(projectDocs) { const projectMeta = {} for (const _path in projectDocs) { const doc = projectDocs[_path] projectMeta[doc._id] = MetaHandler.extractMetaFromDoc(doc.lines) } return projectMeta }, }
overleaf/web/app/src/Features/Metadata/MetaHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Metadata/MetaHandler.js", "repo_id": "overleaf", "token_count": 1631 }
489
const Features = require('../../infrastructure/Features') const _ = require('lodash') const { db, ObjectId } = require('../../infrastructure/mongodb') const { callbackify } = require('util') const { Project } = require('../../models/Project') const { DeletedProject } = require('../../models/DeletedProject') const Errors = require('../Errors/Errors') const logger = require('logger-sharelatex') const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler') const TagsHandler = require('../Tags/TagsHandler') const ProjectHelper = require('./ProjectHelper') const ProjectDetailsHandler = require('./ProjectDetailsHandler') const CollaboratorsHandler = require('../Collaborators/CollaboratorsHandler') const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter') const DocstoreManager = require('../Docstore/DocstoreManager') const EditorRealTimeController = require('../Editor/EditorRealTimeController') const HistoryManager = require('../History/HistoryManager') const FilestoreHandler = require('../FileStore/FileStoreHandler') const TpdsUpdateSender = require('../ThirdPartyDataStore/TpdsUpdateSender') const moment = require('moment') const { promiseMapWithLimit } = require('../../util/promises') const EXPIRE_PROJECTS_AFTER_DAYS = 90 const PROJECT_EXPIRATION_BATCH_SIZE = 10000 module.exports = { markAsDeletedByExternalSource: callbackify(markAsDeletedByExternalSource), unmarkAsDeletedByExternalSource: callbackify(unmarkAsDeletedByExternalSource), deleteUsersProjects: callbackify(deleteUsersProjects), expireDeletedProjectsAfterDuration: callbackify( expireDeletedProjectsAfterDuration ), restoreProject: callbackify(restoreProject), archiveProject: callbackify(archiveProject), unarchiveProject: callbackify(unarchiveProject), trashProject: callbackify(trashProject), untrashProject: callbackify(untrashProject), deleteProject: callbackify(deleteProject), undeleteProject: callbackify(undeleteProject), expireDeletedProject: callbackify(expireDeletedProject), promises: { archiveProject, unarchiveProject, trashProject, untrashProject, deleteProject, undeleteProject, expireDeletedProject, markAsDeletedByExternalSource, unmarkAsDeletedByExternalSource, deleteUsersProjects, expireDeletedProjectsAfterDuration, restoreProject, }, } async function markAsDeletedByExternalSource(projectId) { logger.log( { project_id: projectId }, 'marking project as deleted by external data source' ) await Project.updateOne( { _id: projectId }, { deletedByExternalDataSource: true } ).exec() EditorRealTimeController.emitToRoom( projectId, 'projectRenamedOrDeletedByExternalSource' ) } async function unmarkAsDeletedByExternalSource(projectId) { await Project.updateOne( { _id: projectId }, { deletedByExternalDataSource: false } ).exec() } async function deleteUsersProjects(userId) { const projects = await Project.find({ owner_ref: userId }).exec() await promiseMapWithLimit(5, projects, project => deleteProject(project._id)) await CollaboratorsHandler.promises.removeUserFromAllProjects(userId) } async function expireDeletedProjectsAfterDuration() { const deletedProjects = await DeletedProject.find( { 'deleterData.deletedAt': { $lt: new Date(moment().subtract(EXPIRE_PROJECTS_AFTER_DAYS, 'days')), }, project: { $ne: null }, }, { 'deleterData.deletedProjectId': 1 } ) .limit(PROJECT_EXPIRATION_BATCH_SIZE) .read('secondary') const projectIds = _.shuffle( deletedProjects.map( deletedProject => deletedProject.deleterData.deletedProjectId ) ) for (const projectId of projectIds) { await expireDeletedProject(projectId) } } async function restoreProject(projectId) { await Project.updateOne( { _id: projectId }, { $unset: { archived: true } } ).exec() } async function archiveProject(projectId, userId) { try { const project = await Project.findOne({ _id: projectId }).exec() if (!project) { throw new Errors.NotFoundError('project not found') } const archived = ProjectHelper.calculateArchivedArray( project, userId, 'ARCHIVE' ) await Project.updateOne( { _id: projectId }, { $set: { archived: archived }, $pull: { trashed: ObjectId(userId) } } ) } catch (err) { logger.warn({ err }, 'problem archiving project') throw err } } async function unarchiveProject(projectId, userId) { try { const project = await Project.findOne({ _id: projectId }).exec() if (!project) { throw new Errors.NotFoundError('project not found') } const archived = ProjectHelper.calculateArchivedArray( project, userId, 'UNARCHIVE' ) await Project.updateOne( { _id: projectId }, { $set: { archived: archived } } ) } catch (err) { logger.warn({ err }, 'problem unarchiving project') throw err } } async function trashProject(projectId, userId) { try { const project = await Project.findOne({ _id: projectId }).exec() if (!project) { throw new Errors.NotFoundError('project not found') } const archived = ProjectHelper.calculateArchivedArray( project, userId, 'UNARCHIVE' ) await Project.updateOne( { _id: projectId }, { $addToSet: { trashed: ObjectId(userId) }, $set: { archived: archived }, } ) } catch (err) { logger.warn({ err }, 'problem trashing project') throw err } } async function untrashProject(projectId, userId) { try { const project = await Project.findOne({ _id: projectId }).exec() if (!project) { throw new Errors.NotFoundError('project not found') } await Project.updateOne( { _id: projectId }, { $pull: { trashed: ObjectId(userId) } } ) } catch (err) { logger.warn({ err }, 'problem untrashing project') throw err } } async function deleteProject(projectId, options = {}) { try { const project = await Project.findOne({ _id: projectId }).exec() if (!project) { throw new Errors.NotFoundError('project not found') } await DocumentUpdaterHandler.promises.flushProjectToMongoAndDelete( projectId ) try { // OPTIMIZATION: flush docs out of mongo await DocstoreManager.promises.archiveProject(projectId) } catch (err) { // It is OK to fail here, the docs will get hard-deleted eventually after // the grace-period for soft-deleted projects has passed. logger.warn( { projectId, err }, 'failed archiving doc via docstore as part of project soft-deletion' ) } const memberIds = await CollaboratorsGetter.promises.getMemberIds(projectId) // fire these jobs in the background for (const memberId of memberIds) { TagsHandler.promises .removeProjectFromAllTags(memberId, projectId) .catch(err => { logger.err( { err, memberId, projectId }, 'failed to remove project from tags' ) }) } const deleterData = { deletedAt: new Date(), deleterId: options.deleterUser != null ? options.deleterUser._id : undefined, deleterIpAddress: options.ipAddress, deletedProjectId: project._id, deletedProjectOwnerId: project.owner_ref, deletedProjectCollaboratorIds: project.collaberator_refs, deletedProjectReadOnlyIds: project.readOnly_refs, deletedProjectReadWriteTokenAccessIds: project.tokenAccessReadAndWrite_refs, deletedProjectOverleafId: project.overleaf ? project.overleaf.id : undefined, deletedProjectOverleafHistoryId: project.overleaf && project.overleaf.history ? project.overleaf.history.id : undefined, deletedProjectReadOnlyTokenAccessIds: project.tokenAccessReadOnly_refs, deletedProjectReadWriteToken: project.tokens.readAndWrite, deletedProjectReadOnlyToken: project.tokens.readOnly, deletedProjectLastUpdatedAt: project.lastUpdated, } Object.keys(deleterData).forEach(key => deleterData[key] === undefined ? delete deleterData[key] : '' ) await DeletedProject.updateOne( { 'deleterData.deletedProjectId': projectId }, { project, deleterData }, { upsert: true } ) await Project.deleteOne({ _id: projectId }).exec() } catch (err) { logger.warn({ err }, 'problem deleting project') throw err } logger.log({ project_id: projectId }, 'successfully deleted project') } async function undeleteProject(projectId, options = {}) { projectId = ObjectId(projectId) const deletedProject = await DeletedProject.findOne({ 'deleterData.deletedProjectId': projectId, }).exec() if (!deletedProject) { throw new Errors.NotFoundError('project_not_found') } if (!deletedProject.project) { throw new Errors.NotFoundError('project_too_old_to_restore') } const restored = new Project(deletedProject.project) if (options.userId) { restored.owner_ref = options.userId } // if we're undeleting, we want the document to show up restored.name = await ProjectDetailsHandler.promises.generateUniqueName( deletedProject.deleterData.deletedProjectOwnerId, restored.name + ' (Restored)' ) restored.archived = undefined if (restored.deletedDocs && restored.deletedDocs.length > 0) { await promiseMapWithLimit(10, restored.deletedDocs, async deletedDoc => { // back fill context of deleted docs const { _id: docId, name, deletedAt } = deletedDoc await DocstoreManager.promises.deleteDoc( projectId, docId, name, deletedAt ) }) restored.deletedDocs = [] } if (restored.deletedFiles && restored.deletedFiles.length > 0) { filterDuplicateDeletedFilesInPlace(restored) const deletedFiles = restored.deletedFiles.map(file => { // break free from the model file = file.toObject() // add projectId file.projectId = projectId return file }) await db.deletedFiles.insertMany(deletedFiles) restored.deletedFiles = [] } // we can't use Mongoose to re-insert the project, as it won't // create a new document with an _id already specified. We need to // insert it directly into the collection await db.projects.insertOne(restored) await DeletedProject.deleteOne({ _id: deletedProject._id }).exec() } async function expireDeletedProject(projectId) { try { const activeProject = await Project.findById(projectId).exec() if (activeProject) { // That project is active. The deleted project record might be there // because of an incomplete delete or undelete operation. Clean it up and // return. await DeletedProject.deleteOne({ 'deleterData.deletedProjectId': projectId, }) return } const deletedProject = await DeletedProject.findOne({ 'deleterData.deletedProjectId': projectId, }).exec() if (!deletedProject) { throw new Errors.NotFoundError( `No deleted project found for project id ${projectId}` ) } if (!deletedProject.project) { logger.warn( { projectId }, `Attempted to expire already-expired deletedProject` ) return } const historyId = deletedProject.project.overleaf && deletedProject.project.overleaf.history && deletedProject.project.overleaf.history.id await Promise.all([ DocstoreManager.promises.destroyProject(deletedProject.project._id), Features.hasFeature('history-v1') ? HistoryManager.promises.deleteProject( deletedProject.project._id, historyId ) : Promise.resolve(), FilestoreHandler.promises.deleteProject(deletedProject.project._id), TpdsUpdateSender.promises.deleteProject({ project_id: deletedProject.project._id, }), hardDeleteDeletedFiles(deletedProject.project._id), ]) await DeletedProject.updateOne( { _id: deletedProject._id, }, { $set: { 'deleterData.deleterIpAddress': null, project: null, }, } ).exec() } catch (error) { logger.warn({ projectId, error }, 'error expiring deleted project') throw error } } function filterDuplicateDeletedFilesInPlace(project) { const fileIds = new Set() project.deletedFiles = project.deletedFiles.filter(file => { const id = file._id.toString() if (fileIds.has(id)) return false fileIds.add(id) return true }) } let deletedFilesProjectIdIndexExist async function doesDeletedFilesProjectIdIndexExist() { if (typeof deletedFilesProjectIdIndexExist !== 'boolean') { // Resolve this about once. No need for locking or retry handling. deletedFilesProjectIdIndexExist = await db.deletedFiles.indexExists( 'projectId_1' ) } return deletedFilesProjectIdIndexExist } async function hardDeleteDeletedFiles(projectId) { if (!(await doesDeletedFilesProjectIdIndexExist())) { // Running the deletion command w/o index would kill mongo performance return } return db.deletedFiles.deleteMany({ projectId }) }
overleaf/web/app/src/Features/Project/ProjectDeleter.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/ProjectDeleter.js", "repo_id": "overleaf", "token_count": 4783 }
490
const OError = require('@overleaf/o-error') const { User } = require('../../models/User') const FeaturesUpdater = require('../Subscription/FeaturesUpdater') module.exports = { allocate(referalId, newUserId, referalSource, referalMedium, callback) { if (callback == null) { callback = function () {} } if (referalId == null) { return callback(null) } const query = { referal_id: referalId } return User.findOne(query, { _id: 1 }, function (error, user) { if (error != null) { return callback(error) } if (user == null || user._id == null) { return callback(null) } if (referalSource === 'bonus') { User.updateOne( query, { $push: { refered_users: newUserId, }, $inc: { refered_user_count: 1, }, }, {}, function (err) { if (err != null) { OError.tag(err, 'something went wrong allocating referal', { referalId, newUserId, }) return callback(err) } FeaturesUpdater.refreshFeatures(user._id, 'referral', callback) } ) } else { callback() } }) }, }
overleaf/web/app/src/Features/Referal/ReferalAllocator.js/0
{ "file_path": "overleaf/web/app/src/Features/Referal/ReferalAllocator.js", "repo_id": "overleaf", "token_count": 668 }
491
const { SplitTest } = require('../../models/SplitTest') const OError = require('@overleaf/o-error') const _ = require('lodash') const ALPHA_PHASE = 'alpha' const BETA_PHASE = 'beta' const RELEASE_PHASE = 'release' async function getSplitTests() { try { return await SplitTest.find().exec() } catch (error) { throw OError.tag(error, 'Failed to get split tests list') } } async function getSplitTestByName(name) { try { return await SplitTest.findOne({ name }).exec() } catch (error) { throw OError.tag(error, 'Failed to get split test', { name }) } } async function createSplitTest(name, configuration) { const stripedVariants = [] let stripeStart = 0 _checkNewVariantsConfiguration([], configuration.variants) for (const variant of configuration.variants) { stripedVariants.push({ name: variant.name, active: variant.active, rolloutPercent: variant.rolloutPercent, rolloutStripes: [ { start: stripeStart, end: stripeStart + variant.rolloutPercent, }, ], }) stripeStart += variant.rolloutPercent } const splitTest = new SplitTest({ name, versions: [ { versionNumber: 1, phase: configuration.phase, active: configuration.active, variants: stripedVariants, }, ], }) return _saveSplitTest(splitTest) } async function updateSplitTest(name, configuration) { const splitTest = await getSplitTestByName(name) if (splitTest) { const lastVersion = splitTest.getCurrentVersion().toObject() if (configuration.phase !== lastVersion.phase) { throw new OError( `Cannot update with different phase - use switchToNextPhase endpoint instead` ) } _checkNewVariantsConfiguration(lastVersion.variants, configuration.variants) const updatedVariants = _updateVariantsWithNewConfiguration( lastVersion.variants, configuration.variants ) splitTest.versions.push({ versionNumber: lastVersion.versionNumber + 1, phase: configuration.phase, active: configuration.active, variants: updatedVariants, }) return _saveSplitTest(splitTest) } else { throw new OError(`Cannot update split test '${name}': not found`) } } async function switchToNextPhase(name) { const splitTest = await getSplitTestByName(name) if (splitTest) { const lastVersionCopy = splitTest.getCurrentVersion().toObject() lastVersionCopy.versionNumber++ if (lastVersionCopy.phase === ALPHA_PHASE) { lastVersionCopy.phase = BETA_PHASE } else if (lastVersionCopy.phase === BETA_PHASE) { if (splitTest.forbidReleasePhase) { throw new OError('Switch to release phase is disabled for this test') } lastVersionCopy.phase = RELEASE_PHASE } else if (splitTest.phase === RELEASE_PHASE) { throw new OError( `Split test with ID '${name}' is already in the release phase` ) } for (const variant of lastVersionCopy.variants) { variant.rolloutPercent = 0 variant.rolloutStripes = [] } splitTest.versions.push(lastVersionCopy) return _saveSplitTest(splitTest) } else { throw new OError( `Cannot switch split test with ID '${name}' to next phase: not found` ) } } async function revertToPreviousVersion(name, versionNumber) { const splitTest = await getSplitTestByName(name) if (splitTest) { if (splitTest.versions.length <= 1) { throw new OError( `Cannot revert split test with ID '${name}' to previous version: split test must have at least 2 versions` ) } const previousVersion = splitTest.getVersion(versionNumber) if (!previousVersion) { throw new OError( `Cannot revert split test with ID '${name}' to version number ${versionNumber}: version not found` ) } const lastVersion = splitTest.getCurrentVersion() if ( lastVersion.phase === RELEASE_PHASE && previousVersion.phase !== RELEASE_PHASE ) { splitTest.forbidReleasePhase = true } const previousVersionCopy = previousVersion.toObject() previousVersionCopy.versionNumber = lastVersion.versionNumber + 1 splitTest.versions.push(previousVersionCopy) return _saveSplitTest(splitTest) } else { throw new OError( `Cannot revert split test with ID '${name}' to previous version: not found` ) } } function _checkNewVariantsConfiguration(variants, newVariantsConfiguration) { const totalRolloutPercentage = _getTotalRolloutPercentage( newVariantsConfiguration ) if (totalRolloutPercentage > 100) { throw new OError(`Total variants rollout percentage cannot exceed 100`) } for (const variant of variants) { const newVariantConfiguration = _.find(newVariantsConfiguration, { name: variant.name, }) if (!newVariantConfiguration) { throw new OError( `Variant defined in previous version as ${JSON.stringify( variant )} cannot be removed in new configuration: either set it inactive or create a new split test` ) } if (newVariantConfiguration.rolloutPercent < variant.rolloutPercent) { throw new OError( `Rollout percentage for variant defined in previous version as ${JSON.stringify( variant )} cannot be decreased: revert to a previous configuration instead` ) } } } function _updateVariantsWithNewConfiguration( variants, newVariantsConfiguration ) { let totalRolloutPercentage = _getTotalRolloutPercentage(variants) const variantsCopy = _.clone(variants) for (const newVariantConfig of newVariantsConfiguration) { const variant = _.find(variantsCopy, { name: newVariantConfig.name }) if (!variant) { variantsCopy.push({ name: newVariantConfig.name, active: newVariantConfig.active, rolloutPercent: newVariantConfig.rolloutPercent, rolloutStripes: [ { start: totalRolloutPercentage, end: totalRolloutPercentage + newVariantConfig.rolloutPercent, }, ], }) totalRolloutPercentage += newVariantConfig.rolloutPercent } else if (variant.rolloutPercent < newVariantConfig.rolloutPercent) { const newStripeSize = newVariantConfig.rolloutPercent - variant.rolloutPercent variant.active = newVariantConfig.active variant.rolloutPercent = newVariantConfig.rolloutPercent variant.rolloutStripes.push({ start: totalRolloutPercentage, end: totalRolloutPercentage + newStripeSize, }) totalRolloutPercentage += newStripeSize } } return variantsCopy } function _getTotalRolloutPercentage(variants) { return _.sumBy(variants, 'rolloutPercent') } async function _saveSplitTest(splitTest) { try { return (await splitTest.save()).toObject() } catch (error) { throw OError.tag(error, 'Failed to save split test', { splitTest: JSON.stringify(splitTest), }) } } module.exports = { getSplitTestByName, getSplitTests, createSplitTest, updateSplitTest, switchToNextPhase, revertToPreviousVersion, }
overleaf/web/app/src/Features/SplitTests/SplitTestManager.js/0
{ "file_path": "overleaf/web/app/src/Features/SplitTests/SplitTestManager.js", "repo_id": "overleaf", "token_count": 2578 }
492
/* 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: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const SubscriptionGroupHandler = require('./SubscriptionGroupHandler') const OError = require('@overleaf/o-error') const logger = require('logger-sharelatex') const SubscriptionLocator = require('./SubscriptionLocator') const SessionManager = require('../Authentication/SessionManager') const _ = require('underscore') const async = require('async') module.exports = { removeUserFromGroup(req, res, next) { const subscription = req.entity const userToRemove_id = req.params.user_id logger.log( { subscriptionId: subscription._id, userToRemove_id }, 'removing user from group subscription' ) return SubscriptionGroupHandler.removeUserFromGroup( subscription._id, userToRemove_id, function (err) { if (err != null) { OError.tag(err, 'error removing user from group', { subscriptionId: subscription._id, userToRemove_id, }) return next(err) } return res.sendStatus(200) } ) }, removeSelfFromGroup(req, res, next) { const subscriptionId = req.query.subscriptionId const userToRemove_id = SessionManager.getLoggedInUserId(req.session) return SubscriptionLocator.getSubscription( subscriptionId, function (error, subscription) { if (error != null) { return next(error) } return SubscriptionGroupHandler.removeUserFromGroup( subscription._id, userToRemove_id, function (err) { if (err != null) { logger.err( { err, userToRemove_id, subscriptionId }, 'error removing self from group' ) return res.sendStatus(500) } return res.sendStatus(200) } ) } ) }, }
overleaf/web/app/src/Features/Subscription/SubscriptionGroupController.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionGroupController.js", "repo_id": "overleaf", "token_count": 898 }
493
const { Tag } = require('../../models/Tag') const { promisifyAll } = require('../../util/promises') function getAllTags(userId, callback) { Tag.find({ user_id: userId }, callback) } function createTag(userId, name, callback) { if (!callback) { callback = function () {} } Tag.create({ user_id: userId, name }, function (err, tag) { // on duplicate key error return existing tag if (err && err.code === 11000) { return Tag.findOne({ user_id: userId, name }, callback) } callback(err, tag) }) } function renameTag(userId, tagId, name, callback) { if (!callback) { callback = function () {} } Tag.updateOne( { _id: tagId, user_id: userId, }, { $set: { name, }, }, callback ) } function deleteTag(userId, tagId, callback) { if (!callback) { callback = function () {} } Tag.deleteOne( { _id: tagId, user_id: userId, }, callback ) } // TODO: unused? function updateTagUserIds(oldUserId, newUserId, callback) { if (!callback) { callback = function () {} } const searchOps = { user_id: oldUserId } const updateOperation = { $set: { user_id: newUserId } } Tag.updateMany(searchOps, updateOperation, callback) } function removeProjectFromTag(userId, tagId, projectId, callback) { if (!callback) { callback = function () {} } const searchOps = { _id: tagId, user_id: userId, } const deleteOperation = { $pull: { project_ids: projectId } } Tag.updateOne(searchOps, deleteOperation, callback) } function addProjectToTag(userId, tagId, projectId, callback) { if (!callback) { callback = function () {} } const searchOps = { _id: tagId, user_id: userId, } const insertOperation = { $addToSet: { project_ids: projectId } } Tag.findOneAndUpdate(searchOps, insertOperation, callback) } function addProjectToTagName(userId, name, projectId, callback) { if (!callback) { callback = function () {} } const searchOps = { name, user_id: userId, } const insertOperation = { $addToSet: { project_ids: projectId } } Tag.updateOne(searchOps, insertOperation, { upsert: true }, callback) } function removeProjectFromAllTags(userId, projectId, callback) { const searchOps = { user_id: userId } const deleteOperation = { $pull: { project_ids: projectId } } Tag.updateMany(searchOps, deleteOperation, callback) } const TagsHandler = { getAllTags, createTag, renameTag, deleteTag, updateTagUserIds, removeProjectFromTag, addProjectToTag, addProjectToTagName, removeProjectFromAllTags, } TagsHandler.promises = promisifyAll(TagsHandler) module.exports = TagsHandler
overleaf/web/app/src/Features/Tags/TagsHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Tags/TagsHandler.js", "repo_id": "overleaf", "token_count": 982 }
494
const fs = require('fs') const Path = require('path') const { callbackify } = require('util') const EditorController = require('../Editor/EditorController') const Errors = require('../Errors/Errors') const FileTypeManager = require('./FileTypeManager') const SafePath = require('../Project/SafePath') const logger = require('logger-sharelatex') module.exports = { addEntity: callbackify(addEntity), importDir: callbackify(importDir), promises: { addEntity, importDir, }, } async function addDoc(userId, projectId, folderId, name, lines, replace) { if (replace) { const doc = await EditorController.promises.upsertDoc( projectId, folderId, name, lines, 'upload', userId ) return doc } else { const doc = await EditorController.promises.addDoc( projectId, folderId, name, lines, 'upload', userId ) return doc } } async function addFile(userId, projectId, folderId, name, path, replace) { if (replace) { const file = await EditorController.promises.upsertFile( projectId, folderId, name, path, null, 'upload', userId ) return file } else { const file = await EditorController.promises.addFile( projectId, folderId, name, path, null, 'upload', userId ) return file } } async function addFolder(userId, projectId, folderId, name, path, replace) { const newFolder = await EditorController.promises.addFolder( projectId, folderId, name, 'upload', userId ) await addFolderContents(userId, projectId, newFolder._id, path, replace) return newFolder } async function addFolderContents( userId, projectId, parentFolderId, folderPath, replace ) { if (!(await _isSafeOnFileSystem(folderPath))) { logger.log( { userId, projectId, parentFolderId, folderPath }, 'add folder contents is from symlink, stopping insert' ) throw new Error('path is symlink') } const entries = (await fs.promises.readdir(folderPath)) || [] for (const entry of entries) { if (await FileTypeManager.promises.shouldIgnore(entry)) { continue } await addEntity( userId, projectId, parentFolderId, entry, `${folderPath}/${entry}`, replace ) } } async function addEntity(userId, projectId, folderId, name, fsPath, replace) { if (!(await _isSafeOnFileSystem(fsPath))) { logger.log( { userId, projectId, folderId, fsPath }, 'add entry is from symlink, stopping insert' ) throw new Error('path is symlink') } if (await FileTypeManager.promises.isDirectory(fsPath)) { const newFolder = await addFolder( userId, projectId, folderId, name, fsPath, replace ) return newFolder } // Here, we cheat a little bit and provide the project path relative to the // folder, not the root of the project. This is because we don't know for sure // at this point what the final path of the folder will be. The project path // is still important for importFile() to be able to figure out if the file is // a binary file or an editable document. const projectPath = Path.join('/', name) const importInfo = await importFile(fsPath, projectPath) switch (importInfo.type) { case 'file': { const entity = await addFile( userId, projectId, folderId, name, importInfo.fsPath, replace ) if (entity != null) { entity.type = 'file' } return entity } case 'doc': { const entity = await addDoc( userId, projectId, folderId, name, importInfo.lines, replace ) if (entity != null) { entity.type = 'doc' } return entity } default: { throw new Error(`unknown import type: ${importInfo.type}`) } } } async function _isSafeOnFileSystem(path) { // Use lstat() to ensure we don't follow symlinks. Symlinks from an // untrusted source are dangerous. const stat = await fs.promises.lstat(path) return stat.isFile() || stat.isDirectory() } async function importFile(fsPath, projectPath) { const stat = await fs.promises.lstat(fsPath) if (!stat.isFile()) { throw new Error(`can't import ${fsPath}: not a regular file`) } _validateProjectPath(projectPath) const filename = Path.basename(projectPath) const { binary, encoding } = await FileTypeManager.promises.getType( filename, fsPath ) if (binary) { return new FileImport(projectPath, fsPath) } else { const content = await fs.promises.readFile(fsPath, encoding) // Handle Unix, DOS and classic Mac newlines const lines = content.split(/\r\n|\n|\r/) return new DocImport(projectPath, lines) } } async function importDir(dirPath) { const stat = await fs.promises.lstat(dirPath) if (!stat.isDirectory()) { throw new Error(`can't import ${dirPath}: not a directory`) } const entries = [] for await (const filePath of _walkDir(dirPath)) { const projectPath = Path.join('/', Path.relative(dirPath, filePath)) const importInfo = await importFile(filePath, projectPath) entries.push(importInfo) } return entries } function _validateProjectPath(path) { if (!SafePath.isAllowedLength(path) || !SafePath.isCleanPath(path)) { throw new Errors.InvalidNameError(`Invalid path: ${path}`) } } async function* _walkDir(dirPath) { const entries = await fs.promises.readdir(dirPath) for (const entry of entries) { const entryPath = Path.join(dirPath, entry) if (await FileTypeManager.promises.shouldIgnore(entryPath)) { continue } // Use lstat() to ensure we don't follow symlinks. Symlinks from an // untrusted source are dangerous. const stat = await fs.promises.lstat(entryPath) if (stat.isFile()) { yield entryPath } else if (stat.isDirectory()) { yield* _walkDir(entryPath) } } } class FileImport { constructor(projectPath, fsPath) { this.type = 'file' this.projectPath = projectPath this.fsPath = fsPath } } class DocImport { constructor(projectPath, lines) { this.type = 'doc' this.projectPath = projectPath this.lines = lines } }
overleaf/web/app/src/Features/Uploads/FileSystemImportManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Uploads/FileSystemImportManager.js", "repo_id": "overleaf", "token_count": 2428 }
495
const UserGetter = require('./UserGetter') const UserInfoManager = { getPersonalInfo(userId, callback) { UserGetter.getUser( userId, { _id: true, first_name: true, last_name: true, email: true }, callback ) }, } module.exports = UserInfoManager
overleaf/web/app/src/Features/User/UserInfoManager.js/0
{ "file_path": "overleaf/web/app/src/Features/User/UserInfoManager.js", "repo_id": "overleaf", "token_count": 109 }
496
/* 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const request = require('request') const settings = require('@overleaf/settings') const Errors = require('../Errors/Errors') const { promisifyAll } = require('../../util/promises') // TODO: check what happens when these settings aren't defined const DEFAULT_V1_PARAMS = { baseUrl: settings.apis.v1.url, auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass, }, json: true, timeout: 30 * 1000, } const v1Request = request.defaults(DEFAULT_V1_PARAMS) const DEFAULT_V1_OAUTH_PARAMS = { baseUrl: settings.apis.v1.url, json: true, timeout: 30 * 1000, } const v1OauthRequest = request.defaults(DEFAULT_V1_OAUTH_PARAMS) const V1Api = { request(options, callback) { if (callback == null) { return request(options) } return v1Request(options, (error, response, body) => V1Api._responseHandler(options, error, response, body, callback) ) }, oauthRequest(options, token, callback) { if (options.uri == null) { return callback(new Error('uri required')) } if (options.method == null) { options.method = 'GET' } options.auth = { bearer: token } return v1OauthRequest(options, (error, response, body) => V1Api._responseHandler(options, error, response, body, callback) ) }, _responseHandler(options, error, response, body, callback) { if (error != null) { return callback( new Errors.V1ConnectionError('error from V1 API').withCause(error) ) } if (response && response.statusCode >= 500) { return callback( new Errors.V1ConnectionError({ message: 'error from V1 API', info: { status: response.statusCode, body: body }, }) ) } if ( (response.statusCode >= 200 && response.statusCode < 300) || Array.from(options.expectedStatusCodes || []).includes( response.statusCode ) ) { return callback(null, response, body) } else if (response.statusCode === 403) { error = new Errors.ForbiddenError('overleaf v1 returned forbidden') error.statusCode = response.statusCode return callback(error) } else if (response.statusCode === 404) { error = new Errors.NotFoundError( `overleaf v1 returned non-success code: ${response.statusCode} ${options.method} ${options.uri}` ) error.statusCode = response.statusCode return callback(error) } else { error = new Error( `overleaf v1 returned non-success code: ${response.statusCode} ${options.method} ${options.uri}` ) error.statusCode = response.statusCode return callback(error) } }, } V1Api.promises = promisifyAll(V1Api, { multiResult: { request: ['response', 'body'], oauthRequest: ['response', 'body'], }, }) module.exports = V1Api
overleaf/web/app/src/Features/V1/V1Api.js/0
{ "file_path": "overleaf/web/app/src/Features/V1/V1Api.js", "repo_id": "overleaf", "token_count": 1207 }
497
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const ACE_VERSION = require('ace-builds/version') const version = { // Upgrade instructions: https://github.com/overleaf/write_latex/wiki/Upgrading-Ace ace: ACE_VERSION, fineuploader: '5.15.4', } module.exports = { version, lib(name) { if (version[name] != null) { return `${name}-${version[name]}` } else { return `${name}` } }, }
overleaf/web/app/src/infrastructure/PackageVersions.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/PackageVersions.js", "repo_id": "overleaf", "token_count": 231 }
498
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const DeletedFileSchema = new Schema( { name: String, projectId: Schema.ObjectId, created: { type: Date, }, linkedFileData: { type: Schema.Types.Mixed }, hash: { type: String, }, deletedAt: { type: Date }, }, { collection: 'deletedFiles' } ) exports.DeletedFile = mongoose.model('DeletedFile', DeletedFileSchema) exports.DeletedFileSchema = DeletedFileSchema
overleaf/web/app/src/models/DeletedFile.js/0
{ "file_path": "overleaf/web/app/src/models/DeletedFile.js", "repo_id": "overleaf", "token_count": 194 }
499
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const SamlCacheSchema = new Schema( { createdAt: { type: Date }, requestId: { type: String }, }, { collection: 'samlCache', } ) exports.SamlCache = mongoose.model('SamlCache', SamlCacheSchema) exports.SamlCacheSchema = SamlCacheSchema
overleaf/web/app/src/models/SamlCache.js/0
{ "file_path": "overleaf/web/app/src/models/SamlCache.js", "repo_id": "overleaf", "token_count": 128 }
500
@article{greenwade93, author = "George D. Greenwade", title = "The {C}omprehensive {T}ex {A}rchive {N}etwork ({CTAN})", year = "1993", journal = "TUGBoat", volume = "14", number = "3", pages = "342--351" }
overleaf/web/app/templates/project_files/test-example-project/sample.bib/0
{ "file_path": "overleaf/web/app/templates/project_files/test-example-project/sample.bib", "repo_id": "overleaf", "token_count": 118 }
501
extends ../layout block vars - var suppressNavbar = true - var suppressFooter = true - var suppressSkipToContent = true block content script(type="template", id="gateway-data")!= StringHelper.stringifyJsonForScript({ params: form_data }) .content.content-alt .container .row .col-md-6.col-md-offset-3 .card p.text-center #{translate('processing_your_request')} form( ng-controller="PostGatewayController", ng-init="handleGateway();" id='gateway' method='POST')
overleaf/web/app/views/general/post-gateway.pug/0
{ "file_path": "overleaf/web/app/views/general/post-gateway.pug", "repo_id": "overleaf", "token_count": 186 }
502
header.toolbar.toolbar-header.toolbar-with-labels( ng-cloak, ng-hide="state.loading" ) .toolbar-left a.btn.btn-full-height( href, ng-click="ui.leftMenuShown = true;", ) i.fa.fa-fw.fa-bars.editor-menu-icon p.toolbar-label #{translate("menu")} a.btn.btn-full-height.header-cobranding-logo-container( ng-if="::(cobranding.isProjectCobranded && cobranding.logoImgUrl)" ng-href="{{ ::cobranding.brandVariationHomeUrl }}" target="_blank" rel="noreferrer noopener" ) img.header-cobranding-logo( ng-src="{{ ::cobranding.logoImgUrl }}" alt="{{ ::cobranding.brandVariationName }}" ) a.toolbar-header-back-projects( href="/project" ) i.fa.fa-fw.fa-level-up span(ng-controller="PdfViewToggleController") a.btn.btn-full-height.btn-full-height-no-border( href, ng-show="ui.pdfLayout == 'flat'", tooltip="PDF", tooltip-placement="bottom", tooltip-append-to-body="true", ng-click="togglePdfView()", ng-class="{ 'active': ui.view == 'pdf' }" ) i.fa.fa-file-pdf-o .toolbar-center.project-name(ng-controller="ProjectNameController") span.name( ng-dblclick="!permissions.admin || startRenaming()", ng-show="!state.renaming" tooltip="{{ project.name }}", tooltip-class="project-name-tooltip" tooltip-placement="bottom", tooltip-append-to-body="true", tooltip-enable="state.overflowed" ) {{ project.name }} input.form-control( type="text" ng-model="inputs.name", ng-show="state.renaming", on-enter="finishRenaming()", ng-blur="finishRenaming()", select-name-when="state.renaming" ) a.rename( ng-if="permissions.admin", href='#', tooltip-placement="bottom", tooltip=translate('rename'), tooltip-append-to-body="true", ng-click="startRenaming()", ng-show="!state.renaming" ) i.fa.fa-pencil .toolbar-right .online-users( ng-if="onlineUsersArray.length < 4" ng-controller="OnlineUsersController" ) span.online-user( ng-repeat="user in onlineUsersArray", ng-style="{ 'background-color': 'hsl({{ getHueForUserId(user.user_id) }}, 70%, 50%)' }", popover="{{ user.name }}" popover-placement="bottom" popover-append-to-body="true" popover-trigger="mouseenter" ng-click="gotoUser(user)" ) {{ userInitial(user) }} .online-users.dropdown( dropdown ng-if="onlineUsersArray.length >= 4" ng-controller="OnlineUsersController" ) span.online-user.online-user-multi( dropdown-toggle, tooltip=translate('connected_users'), tooltip-placement="left" ) strong {{ onlineUsersArray.length }} i.fa.fa-fw.fa-users ul.dropdown-menu.pull-right li.dropdown-header #{translate('connected_users')} li(ng-repeat="user in onlineUsersArray") a(href, ng-click="gotoUser(user)") span.online-user( ng-style="{ 'background-color': 'hsl({{ getHueForUserId(user.user_id) }}, 70%, 50%)' }" ) {{ user.name.slice(0,1) }} | {{ user.name }} if !isRestrictedTokenMember a.btn.btn-full-height( href, ng-if="project.features.trackChangesVisible", ng-class="{ active: ui.reviewPanelOpen && ui.view !== 'history' }" ng-disabled="ui.view === 'history'" ng-click="toggleReviewPanel()" ) i.review-icon p.toolbar-label | #{translate("review")} a.btn.btn-full-height( href ng-click="openShareProjectModal(permissions.admin);" ng-controller="ReactShareProjectModalController" ) i.fa.fa-fw.fa-group p.toolbar-label #{translate("share")} share-project-modal( handle-hide="handleHide" show="show" is-admin="isAdmin" ) != moduleIncludes('publish:button', locals) if !isRestrictedTokenMember a.btn.btn-full-height( href, ng-click="toggleHistory();", ng-class="{ active: (ui.view == 'history') }", ) i.fa.fa-fw.fa-history p.toolbar-label #{translate("history")} a.btn.btn-full-height( href, ng-class="{ active: ui.chatOpen }", ng-click="toggleChat();", ng-controller="ChatButtonController", ng-show="!anonymous", ) i.fa.fa-fw.fa-comment( ng-class="{ 'bounce': unreadMessages > 0 }" ) span.label.label-info( ng-show="unreadMessages > 0" ) {{ unreadMessages }} p.toolbar-label #{translate("chat")}
overleaf/web/app/views/project/editor/header.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/header.pug", "repo_id": "overleaf", "token_count": 1935 }
503
extends ../../layout block content main.content.content-alt#main-content .container .row .col-md-8.col-md-offset-2 .card.project-invite-invalid .page-header.text-centered h1 #{translate("invite_not_valid")} .row.text-center .col-md-12 p | #{translate("invite_not_valid_description")}. .row.text-center.actions .col-md-12 a.btn.btn-info(href="/project") #{translate("back_to_your_projects")}
overleaf/web/app/views/project/invite/not-valid.pug/0
{ "file_path": "overleaf/web/app/views/project/invite/not-valid.pug", "repo_id": "overleaf", "token_count": 244 }
504
p i * !{translate("subject_to_additional_vat")} if (personalSubscription.recurly.activeCoupons.length > 0) i * !{translate("coupons_not_included")}: ul each coupon in personalSubscription.recurly.activeCoupons li i= coupon.description || coupon.name
overleaf/web/app/views/subscriptions/_price_exceptions.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/_price_exceptions.pug", "repo_id": "overleaf", "token_count": 102 }
505
extends ../layout include _plans_page_mixins include _plans_page_tables block vars - metadata = { viewport: true } block append meta meta(name="ol-recomendedCurrency" content=recomendedCurrency) meta(name="ol-groupPlans" data-type="json" content=groupPlans) block content main.content.content-alt#main-content .container .user-notifications ul.list-unstyled(ng-cloak) li.notification-entry .alert.alert-info .notification-body span To help you work from home throughout 2021, we're providing discounted plans and special initiatives. .notification-action a.btn.btn-sm.btn-info(href="https://www.overleaf.com/events/wfh2021" event-tracking="Event-Pages" event-tracking-trigger="click" event-tracking-ga="WFH-Offer-Click" event-tracking-label="Plans-Banner") Upgrade .content-page .plans(ng-controller="PlansController") .container(ng-cloak) .row .col-md-12 .page-header.centered.plans-header.text-centered h1.text-capitalize(ng-non-bindable) #{translate('get_instant_access_to')} #{settings.appName} .row .col-md-8.col-md-offset-2 p.text-centered #{translate("sl_benefits_plans")} +allCardsAndControls() .row.row-spaced-large.text-centered .col-xs-12 p.text-centered !{translate('also_provides_free_plan', { appName:'{{settings.appName}}' }, [{ name: 'a', attrs: { href: '/register' }}])} i.fa.fa-cc-mastercard.fa-2x(aria-hidden="true") &nbsp; span.sr-only Mastercard accepted i.fa.fa-cc-visa.fa-2x(aria-hidden="true") &nbsp; span.sr-only Visa accepted i.fa.fa-cc-amex.fa-2x(aria-hidden="true") &nbsp; span.sr-only Amex accepted i.fa.fa-cc-paypal.fa-2x(aria-hidden="true") &nbsp; span.sr-only Paypal accepted div.text-centered #{translate('change_plans_any_time')}<br/> #{translate('billed_after_x_days', {len:'{{trial_len}}'})} br div.text-centered #{translate('subject_to_additional_vat')}<br/> #{translate('select_country_vat')} .row.row-spaced-large .col-md-8.col-md-offset-2 .card.text-centered .card-header h2 #{translate('looking_multiple_licenses')} span #{translate('reduce_costs_group_licenses')} br br a.btn.btn-default( href="#groups" ng-click="openGroupPlanModal()" ) #{translate('find_out_more')} .row.row-spaced-large .col-sm-12 .page-header.plans-header.plans-subheader.text-centered h2 #{translate('compare_plan_features')} .row .col-md-6.col-md-offset-3 +plan_switch('table') .col-md-3.text-right +currency_dropdown .row(event-tracking="features-table-viewed" event-tracking-ga="subscription-funnel" event-tracking-trigger="scroll" event-tracking-send-once="true" event-tracking-label=`exp-{{plansVariant}}`) .col-sm-12(ng-if="ui.view != 'student'") +table_premium .col-sm-12(ng-if="ui.view == 'student'") +table_student include _plans_quotes include _plans_faq #bottom-cards.row.row-spaced(style="display: none;") .col-sm-12 +allCardsAndControls(true, 'bottom') .row.row-spaced-large .col-md-12 .plans-header.plans-subheader.text-centered h2.header-with-btn #{translate('still_have_questions')} button.btn.btn-default.btn-header.text-capitalize( ng-controller="ContactGeneralModal" ng-click="openModal()" ) #{translate('get_in_touch')} != moduleIncludes("contactModalGeneral", locals) .row.row-spaced include _modal_group_purchase
overleaf/web/app/views/subscriptions/plans.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/plans.pug", "repo_id": "overleaf", "token_count": 1708 }
506
extends ../layout block append meta meta(name="ol-passwordStrengthOptions" data-type="json" content=settings.passwordStrengthOptions) block content main.content.content-alt#main-content .container .row .col-md-6.col-md-offset-3.col-lg-4.col-lg-offset-4 .card .page-header h1 #{translate("reset_your_password")} form( async-form="password-reset", name="passwordResetForm", action="/user/password/set", method="POST", ng-cloak ) input(type="hidden", name="_csrf", value=csrfToken) .alert.alert-success(ng-show="passwordResetForm.response.success") | #{translate("password_has_been_reset")}. br a(href='/login') #{translate("login_here")} div(ng-show="passwordResetForm.response.error == true") div(ng-switch="passwordResetForm.response.status") .alert.alert-danger(ng-switch-when="404") | #{translate('password_reset_token_expired')} br a(href="/user/password/reset") | Request a new password reset email .alert.alert-danger(ng-switch-when="400") | #{translate('invalid_password')} .alert.alert-danger(ng-switch-when="429") | #{translate('rate_limit_hit_wait')} .alert.alert-danger(ng-switch-default) | #{translate('error_performing_request')} .form-group input.form-control#passwordField( type='password', name='password', placeholder='new password', required, autocomplete="new-password", ng-model="password", autofocus, complex-password ) span.small.text-primary(ng-show="passwordResetForm.password.$error.complexPassword", ng-bind-html="complexPasswordErrorMessage") input( type="hidden", name="passwordResetToken", value=passwordResetToken ng-non-bindable ) .actions button.btn.btn-primary( type='submit', ng-disabled="passwordResetForm.$invalid" ) #{translate("set_new_password")}
overleaf/web/app/views/user/setPassword.pug/0
{ "file_path": "overleaf/web/app/views/user/setPassword.pug", "repo_id": "overleaf", "token_count": 1021 }
507
const { merge } = require('@overleaf/settings/merge') let defaultFeatures, siteUrl // Make time interval config easier. const seconds = 1000 const minutes = 60 * seconds // These credentials are used for authenticating api requests // between services that may need to go over public channels const httpAuthUser = process.env.WEB_API_USER const httpAuthPass = process.env.WEB_API_PASSWORD const httpAuthUsers = {} if (httpAuthUser && httpAuthPass) { httpAuthUsers[httpAuthUser] = httpAuthPass } const sessionSecret = process.env.SESSION_SECRET || 'secret-please-change' const intFromEnv = function (name, defaultValue) { if ( [null, undefined].includes(defaultValue) || typeof defaultValue !== 'number' ) { throw new Error( `Bad default integer value for setting: ${name}, ${defaultValue}` ) } return parseInt(process.env[name], 10) || defaultValue } const defaultTextExtensions = [ 'tex', 'latex', 'sty', 'cls', 'bst', 'bib', 'bibtex', 'txt', 'tikz', 'mtx', 'rtex', 'md', 'asy', 'latexmkrc', 'lbx', 'bbx', 'cbx', 'm', 'lco', 'dtx', 'ins', 'ist', 'def', 'clo', 'ldf', 'rmd', 'lua', 'gv', 'mf', 'yml', 'yaml', ] const parseTextExtensions = function (extensions) { if (extensions) { return extensions.split(',').map(ext => ext.trim()) } else { return [] } } module.exports = { env: 'server-ce', limits: { httpGlobalAgentMaxSockets: 300, httpsGlobalAgentMaxSockets: 300, }, allowAnonymousReadAndWriteSharing: process.env.SHARELATEX_ALLOW_ANONYMOUS_READ_AND_WRITE_SHARING === 'true', // Databases // --------- mongo: { options: { appname: 'web', useUnifiedTopology: (process.env.MONGO_USE_UNIFIED_TOPOLOGY || 'true') === 'true', poolSize: parseInt(process.env.MONGO_POOL_SIZE, 10) || 10, serverSelectionTimeoutMS: parseInt(process.env.MONGO_SERVER_SELECTION_TIMEOUT, 10) || 60000, socketTimeoutMS: parseInt(process.env.MONGO_SOCKET_TIMEOUT, 10) || 30000, }, url: process.env.MONGO_CONNECTION_STRING || process.env.MONGO_URL || `mongodb://${process.env.MONGO_HOST || '127.0.0.1'}/sharelatex`, }, redis: { web: { host: process.env.REDIS_HOST || 'localhost', port: process.env.REDIS_PORT || '6379', password: process.env.REDIS_PASSWORD || '', maxRetriesPerRequest: parseInt( process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20' ), }, // websessions: // cluster: [ // {host: 'localhost', port: 7000} // {host: 'localhost', port: 7001} // {host: 'localhost', port: 7002} // {host: 'localhost', port: 7003} // {host: 'localhost', port: 7004} // {host: 'localhost', port: 7005} // ] // ratelimiter: // cluster: [ // {host: 'localhost', port: 7000} // {host: 'localhost', port: 7001} // {host: 'localhost', port: 7002} // {host: 'localhost', port: 7003} // {host: 'localhost', port: 7004} // {host: 'localhost', port: 7005} // ] // cooldown: // cluster: [ // {host: 'localhost', port: 7000} // {host: 'localhost', port: 7001} // {host: 'localhost', port: 7002} // {host: 'localhost', port: 7003} // {host: 'localhost', port: 7004} // {host: 'localhost', port: 7005} // ] api: { host: process.env.REDIS_HOST || 'localhost', port: process.env.REDIS_PORT || '6379', password: process.env.REDIS_PASSWORD || '', maxRetriesPerRequest: parseInt( process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20' ), }, }, // Service locations // ----------------- // Configure which ports to run each service on. Generally you // can leave these as they are unless you have some other services // running which conflict, or want to run the web process on port 80. internal: { web: { port: process.env.WEB_PORT || 3000, host: process.env.LISTEN_ADDRESS || 'localhost', }, }, // Tell each service where to find the other services. If everything // is running locally then this is easy, but they exist as separate config // options incase you want to run some services on remote hosts. apis: { web: { url: `http://${ process.env.WEB_API_HOST || process.env.WEB_HOST || 'localhost' }:${process.env.WEB_API_PORT || process.env.WEB_PORT || 3000}`, user: httpAuthUser, pass: httpAuthPass, }, documentupdater: { url: `http://${ process.env.DOCUPDATER_HOST || process.env.DOCUMENT_UPDATER_HOST || 'localhost' }:3003`, }, spelling: { url: `http://${process.env.SPELLING_HOST || 'localhost'}:3005`, host: process.env.SPELLING_HOST, }, trackchanges: { url: `http://${process.env.TRACK_CHANGES_HOST || 'localhost'}:3015`, }, docstore: { url: `http://${process.env.DOCSTORE_HOST || 'localhost'}:3016`, pubUrl: `http://${process.env.DOCSTORE_HOST || 'localhost'}:3016`, }, chat: { internal_url: `http://${process.env.CHAT_HOST || 'localhost'}:3010`, }, filestore: { url: `http://${process.env.FILESTORE_HOST || 'localhost'}:3009`, }, clsi: { url: `http://${process.env.CLSI_HOST || 'localhost'}:3013`, // url: "http://#{process.env['CLSI_LB_HOST']}:3014" backendGroupName: undefined, }, realTime: { url: `http://${process.env.REALTIME_HOST || 'localhost'}:3026`, }, contacts: { url: `http://${process.env.CONTACTS_HOST || 'localhost'}:3036`, }, notifications: { url: `http://${process.env.NOTIFICATIONS_HOST || 'localhost'}:3042`, }, // For legacy reasons, we need to populate the below objects. v1: {}, recurly: {}, }, splitTests: [], // Where your instance of ShareLaTeX can be found publically. Used in emails // that are sent out, generated links, etc. siteUrl: (siteUrl = process.env.PUBLIC_URL || 'http://localhost:3000'), lockManager: { lockTestInterval: intFromEnv('LOCK_MANAGER_LOCK_TEST_INTERVAL', 50), maxTestInterval: intFromEnv('LOCK_MANAGER_MAX_TEST_INTERVAL', 1000), maxLockWaitTime: intFromEnv('LOCK_MANAGER_MAX_LOCK_WAIT_TIME', 10000), redisLockExpiry: intFromEnv('LOCK_MANAGER_REDIS_LOCK_EXPIRY', 30), slowExecutionThreshold: intFromEnv( 'LOCK_MANAGER_SLOW_EXECUTION_THRESHOLD', 5000 ), }, // Optional separate location for websocket connections, if unset defaults to siteUrl. wsUrl: process.env.WEBSOCKET_URL, wsUrlV2: process.env.WEBSOCKET_URL_V2, wsUrlBeta: process.env.WEBSOCKET_URL_BETA, wsUrlV2Percentage: parseInt( process.env.WEBSOCKET_URL_V2_PERCENTAGE || '0', 10 ), wsRetryHandshake: parseInt(process.env.WEBSOCKET_RETRY_HANDSHAKE || '5', 10), // cookie domain // use full domain for cookies to only be accessible from that domain, // replace subdomain with dot to have them accessible on all subdomains cookieDomain: process.env.COOKIE_DOMAIN, cookieName: process.env.COOKIE_NAME || 'sharelatex.sid', // this is only used if cookies are used for clsi backend // clsiCookieKey: "clsiserver" robotsNoindex: process.env.ROBOTS_NOINDEX === 'true' || false, maxEntitiesPerProject: 2000, maxUploadSize: 50 * 1024 * 1024, // 50 MB // start failing the health check if active handles exceeds this limit maxActiveHandles: process.env.MAX_ACTIVE_HANDLES ? parseInt(process.env.MAX_ACTIVE_HANDLES, 10) : undefined, // Security // -------- security: { sessionSecret, bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS, 10) || 12, }, // number of rounds used to hash user passwords (raised to power 2) httpAuthUsers, // Default features // ---------------- // // You can select the features that are enabled by default for new // new users. defaultFeatures: (defaultFeatures = { collaborators: -1, dropbox: true, github: true, gitBridge: true, versioning: true, compileTimeout: 180, compileGroup: 'standard', references: true, templates: true, trackChanges: true, }), features: { personal: defaultFeatures, }, plans: [ { planCode: 'personal', name: 'Personal', price: 0, features: defaultFeatures, }, ], enableSubscriptions: false, enabledLinkedFileTypes: (process.env.ENABLED_LINKED_FILE_TYPES || '').split( ',' ), // i18n // ------ // i18n: { checkForHTMLInVars: process.env.I18N_CHECK_FOR_HTML_IN_VARS === 'true', escapeHTMLInVars: process.env.I18N_ESCAPE_HTML_IN_VARS === 'true', subdomainLang: { www: { lngCode: 'en', url: siteUrl }, }, defaultLng: 'en', }, // Spelling languages // ------------------ // // You must have the corresponding aspell package installed to // be able to use a language. languages: [ { code: 'en', name: 'English' }, { code: 'en_US', name: 'English (American)' }, { code: 'en_GB', name: 'English (British)' }, { code: 'en_CA', name: 'English (Canadian)' }, { code: 'af', name: 'Afrikaans' }, { code: 'ar', name: 'Arabic' }, { code: 'gl', name: 'Galician' }, { code: 'eu', name: 'Basque' }, { code: 'br', name: 'Breton' }, { code: 'bg', name: 'Bulgarian' }, { code: 'ca', name: 'Catalan' }, { code: 'hr', name: 'Croatian' }, { code: 'cs', name: 'Czech' }, { code: 'da', name: 'Danish' }, { code: 'nl', name: 'Dutch' }, { code: 'eo', name: 'Esperanto' }, { code: 'et', name: 'Estonian' }, { code: 'fo', name: 'Faroese' }, { code: 'fr', name: 'French' }, { code: 'de', name: 'German' }, { code: 'el', name: 'Greek' }, { code: 'id', name: 'Indonesian' }, { code: 'ga', name: 'Irish' }, { code: 'it', name: 'Italian' }, { code: 'kk', name: 'Kazakh' }, { code: 'ku', name: 'Kurdish' }, { code: 'lv', name: 'Latvian' }, { code: 'lt', name: 'Lithuanian' }, { code: 'nr', name: 'Ndebele' }, { code: 'ns', name: 'Northern Sotho' }, { code: 'no', name: 'Norwegian' }, { code: 'fa', name: 'Persian' }, { code: 'pl', name: 'Polish' }, { code: 'pt_BR', name: 'Portuguese (Brazilian)' }, { code: 'pt_PT', name: 'Portuguese (European)' }, { code: 'pa', name: 'Punjabi' }, { code: 'ro', name: 'Romanian' }, { code: 'ru', name: 'Russian' }, { code: 'sk', name: 'Slovak' }, { code: 'sl', name: 'Slovenian' }, { code: 'st', name: 'Southern Sotho' }, { code: 'es', name: 'Spanish' }, { code: 'sv', name: 'Swedish' }, { code: 'tl', name: 'Tagalog' }, { code: 'ts', name: 'Tsonga' }, { code: 'tn', name: 'Tswana' }, { code: 'hsb', name: 'Upper Sorbian' }, { code: 'cy', name: 'Welsh' }, { code: 'xh', name: 'Xhosa' }, ], // Password Settings // ----------- // These restrict the passwords users can use when registering // opts are from http://antelle.github.io/passfield // passwordStrengthOptions: // pattern: "aA$3" // length: // min: 6 // max: 128 // Email support // ------------- // // ShareLaTeX uses nodemailer (http://www.nodemailer.com/) to send transactional emails. // To see the range of transport and options they support, see http://www.nodemailer.com/docs/transports // email: // fromAddress: "" // replyTo: "" // lifecycle: false // # Example transport and parameter settings for Amazon SES // transport: "SES" // parameters: // AWSAccessKeyID: "" // AWSSecretKey: "" // For legacy reasons, we need to populate this object. sentry: {}, // Production Settings // ------------------- debugPugTemplates: process.env.DEBUG_PUG_TEMPLATES === 'true', precompilePugTemplatesAtBootTime: process.env .PRECOMPILE_PUG_TEMPLATES_AT_BOOT_TIME ? process.env.PRECOMPILE_PUG_TEMPLATES_AT_BOOT_TIME === 'true' : process.env.NODE_ENV === 'production', // Should javascript assets be served minified or not. Note that you will // need to run `grunt compile:minify` within the web-sharelatex directory // to generate these. useMinifiedJs: process.env.MINIFIED_JS === 'true' || false, // Should static assets be sent with a header to tell the browser to cache // them. cacheStaticAssets: false, // If you are running ShareLaTeX over https, set this to true to send the // cookie with a secure flag (recommended). secureCookie: false, // 'SameSite' cookie setting. Can be set to 'lax', 'none' or 'strict' // 'lax' is recommended, as 'strict' will prevent people linking to projects // https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 sameSiteCookie: 'lax', // If you are running ShareLaTeX behind a proxy (like Apache, Nginx, etc) // then set this to true to allow it to correctly detect the forwarded IP // address and http/https protocol information. behindProxy: false, // Expose the hostname in the `X-Served-By` response header exposeHostname: process.env.EXPOSE_HOSTNAME === 'true', // Cookie max age (in milliseconds). Set to false for a browser session. cookieSessionLength: 5 * 24 * 60 * 60 * 1000, // 5 days // When true, only allow invites to be sent to email addresses that // already have user accounts restrictInvitesToExistingAccounts: false, // Should we allow access to any page without logging in? This includes // public projects, /learn, /templates, about pages, etc. allowPublicAccess: process.env.SHARELATEX_ALLOW_PUBLIC_ACCESS === 'true', // editor should be open by default editorIsOpen: process.env.EDITOR_OPEN !== 'false', // site should be open by default siteIsOpen: process.env.SITE_OPEN !== 'false', // Use a single compile directory for all users in a project // (otherwise each user has their own directory) // disablePerUserCompiles: true // Domain the client (pdfjs) should download the compiled pdf from pdfDownloadDomain: process.env.PDF_DOWNLOAD_DOMAIN, // "http://clsi-lb:3014" // By default turn on feature flag, can be overridden per request. enablePdfCaching: process.env.ENABLE_PDF_CACHING === 'true', // Whether to disable any existing service worker on the next load of the editor resetServiceWorker: process.env.RESET_SERVICE_WORKER === 'true', // Maximum size of text documents in the real-time editing system. max_doc_length: 2 * 1024 * 1024, // 2mb // Maximum JSON size in HTTP requests // We should be able to process twice the max doc length, to allow for // - the doc content // - text ranges spanning the whole doc // // There's also overhead required for the JSON encoding and the UTF-8 encoding, // theoretically up to 3 times the max doc length. On the other hand, we don't // want to block the event loop with JSON parsing, so we try to find a // practical compromise. max_json_request_size: parseInt(process.env.MAX_JSON_REQUEST_SIZE) || 6 * 1024 * 1024, // 6 MB // Internal configs // ---------------- path: { // If we ever need to write something to disk (e.g. incoming requests // that need processing but may be too big for memory, then write // them to disk here). dumpFolder: './data/dumpFolder', uploadFolder: './data/uploads', }, // Automatic Snapshots // ------------------- automaticSnapshots: { // How long should we wait after the user last edited to // take a snapshot? waitTimeAfterLastEdit: 5 * minutes, // Even if edits are still taking place, this is maximum // time to wait before taking another snapshot. maxTimeBetweenSnapshots: 30 * minutes, }, // Smoke test // ---------- // Provide log in credentials and a project to be able to run // some basic smoke tests to check the core functionality. // smokeTest: { user: process.env.SMOKE_TEST_USER, userId: process.env.SMOKE_TEST_USER_ID, password: process.env.SMOKE_TEST_PASSWORD, projectId: process.env.SMOKE_TEST_PROJECT_ID, rateLimitSubject: process.env.SMOKE_TEST_RATE_LIMIT_SUBJECT || '127.0.0.1', stepTimeout: parseInt(process.env.SMOKE_TEST_STEP_TIMEOUT || '10000', 10), }, appName: process.env.APP_NAME || 'ShareLaTeX (Community Edition)', adminEmail: process.env.ADMIN_EMAIL || 'placeholder@example.com', adminDomains: process.env.ADMIN_DOMAINS ? JSON.parse(process.env.ADMIN_DOMAINS) : undefined, nav: { title: 'ShareLaTeX Community Edition', left_footer: [ { text: "Powered by <a href='https://www.sharelatex.com'>ShareLaTeX</a> © 2016", }, ], right_footer: [ { text: "<i class='fa fa-github-square'></i> Fork on Github!", url: 'https://github.com/sharelatex/sharelatex', }, ], showSubscriptionLink: false, header_extras: [], }, // Example: // header_extras: [{text: "Some Page", url: "http://example.com/some/page", class: "subdued"}] recaptcha: { disabled: { invite: true, login: true, passwordReset: true, register: true, }, }, customisation: {}, redirects: { '/templates/index': '/templates/', }, reloadModuleViewsOnEachRequest: process.env.NODE_ENV === 'development', rateLimit: { autoCompile: { everyone: process.env.RATE_LIMIT_AUTO_COMPILE_EVERYONE || 100, standard: process.env.RATE_LIMIT_AUTO_COMPILE_STANDARD || 25, }, }, analytics: { enabled: false, }, compileBodySizeLimitMb: process.env.COMPILE_BODY_SIZE_LIMIT_MB || 5, textExtensions: defaultTextExtensions.concat( parseTextExtensions(process.env.ADDITIONAL_TEXT_EXTENSIONS) ), validRootDocExtensions: ['tex', 'Rtex', 'ltx'], emailConfirmationDisabled: process.env.EMAIL_CONFIRMATION_DISABLED === 'true' || false, enabledServices: (process.env.ENABLED_SERVICES || 'web,api') .split(',') .map(s => s.trim()), // module options // ---------- modules: { sanitize: { options: { allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'col', 'caption', 'tbody', 'tr', 'th', 'td', 'tfoot', 'pre', 'iframe', 'img', 'figure', 'figcaption', 'span', 'source', 'video', 'del', ], allowedAttributes: { a: [ 'href', 'name', 'target', 'class', 'event-tracking', 'event-tracking-ga', 'event-tracking-label', 'event-tracking-trigger', ], div: ['class', 'id', 'style'], h1: ['class', 'id'], h2: ['class', 'id'], h3: ['class', 'id'], h4: ['class', 'id'], h5: ['class', 'id'], h6: ['class', 'id'], col: ['width'], figure: ['class', 'id', 'style'], figcaption: ['class', 'id', 'style'], i: ['aria-hidden', 'aria-label', 'class', 'id'], iframe: [ 'allowfullscreen', 'frameborder', 'height', 'src', 'style', 'width', ], img: ['alt', 'class', 'src', 'style'], source: ['src', 'type'], span: ['class', 'id', 'style'], strong: ['style'], table: ['border', 'class', 'id', 'style'], td: ['colspan', 'rowspan', 'headers', 'style'], th: [ 'abbr', 'headers', 'colspan', 'rowspan', 'scope', 'sorted', 'style', ], tr: ['class'], video: ['alt', 'class', 'controls', 'height', 'width'], }, }, }, }, overleafModuleImports: { // modules to import (an empty array for each set of modules) createFileModes: [], gitBridge: [], publishModal: [], tprLinkedFileInfo: [], tprLinkedFileRefreshError: [], }, moduleImportSequence: ['launchpad', 'server-ce-scripts', 'user-activate'], csp: { percentage: parseFloat(process.env.CSP_PERCENTAGE) || 0, enabled: process.env.CSP_ENABLED === 'true', reportOnly: process.env.CSP_REPORT_ONLY === 'true', reportPercentage: parseFloat(process.env.CSP_REPORT_PERCENTAGE) || 0, reportUri: process.env.CSP_REPORT_URI, exclude: ['app/views/project/editor', 'app/views/project/list'], }, unsupportedBrowsers: { ie: '<=11', }, } module.exports.mergeWith = function (overrides) { return merge(overrides, module.exports) }
overleaf/web/config/settings.defaults.js/0
{ "file_path": "overleaf/web/config/settings.defaults.js", "repo_id": "overleaf", "token_count": 8638 }
508
import _ from 'lodash' import App from '../base' App.directive('bookmarkableTabset', $location => ({ restrict: 'A', require: 'tabset', link(scope, el, attrs, tabset) { const _makeActive = function (hash) { if (hash && hash !== '') { const matchingTab = _.find( tabset.tabs, tab => tab.bookmarkableTabId === hash ) if (matchingTab) { matchingTab.select() return el.children()[0].scrollIntoView({ behavior: 'smooth' }) } } } scope.$applyAsync(function () { // for page load const hash = $location.hash() _makeActive(hash) // for links within page to a tab // this needs to be within applyAsync because there could be a link // within a tab to another tab const linksToTabs = document.querySelectorAll('.link-to-tab') const _clickLinkToTab = event => { const hash = event.currentTarget.getAttribute('href').split('#').pop() _makeActive(hash) } if (linksToTabs) { Array.from(linksToTabs).map(link => link.addEventListener('click', _clickLinkToTab) ) } }) }, })) App.directive('bookmarkableTab', $location => ({ restrict: 'A', require: 'tab', link(scope, el, attrs, tab) { const tabScope = el.isolateScope() const tabId = attrs.bookmarkableTab if (tabScope && tabId && tabId !== '') { tabScope.bookmarkableTabId = tabId tabScope.$watch('active', function (isActive, wasActive) { if (isActive && !wasActive && $location.hash() !== tabId) { return $location.hash(tabId) } }) } }, }))
overleaf/web/frontend/js/directives/bookmarkableTabset.js/0
{ "file_path": "overleaf/web/frontend/js/directives/bookmarkableTabset.js", "repo_id": "overleaf", "token_count": 712 }
509
import React, { useEffect } from 'react' import PropTypes from 'prop-types' import { useTranslation } from 'react-i18next' import MessageList from './message-list' import MessageInput from './message-input' import InfiniteScroll from './infinite-scroll' import ChatFallbackError from './chat-fallback-error' import Icon from '../../../shared/components/icon' import { useLayoutContext } from '../../../shared/context/layout-context' import { useUserContext } from '../../../shared/context/user-context' import withErrorBoundary from '../../../infrastructure/error-boundary' import { FetchError } from '../../../infrastructure/fetch-json' import { useChatContext } from '../context/chat-context' const ChatPane = React.memo(function ChatPane() { const { t } = useTranslation() const { chatIsOpen } = useLayoutContext({ chatIsOpen: PropTypes.bool }) const user = useUserContext({ id: PropTypes.string.isRequired, }) const { status, messages, initialMessagesLoaded, atEnd, loadInitialMessages, loadMoreMessages, reset, sendMessage, markMessagesAsRead, error, } = useChatContext() useEffect(() => { if (chatIsOpen && !initialMessagesLoaded) { loadInitialMessages() } }, [chatIsOpen, loadInitialMessages, initialMessagesLoaded]) const shouldDisplayPlaceholder = status !== 'pending' && messages.length === 0 const messageContentCount = messages.reduce( (acc, { contents }) => acc + contents.length, 0 ) if (error) { // let user try recover from fetch errors if (error instanceof FetchError) { return <ChatFallbackError reconnect={reset} /> } throw error } if (!user) { return null } return ( <aside className="chat"> <InfiniteScroll atEnd={atEnd} className="messages" fetchData={loadMoreMessages} isLoading={status === 'pending'} itemCount={messageContentCount} > <div> <h2 className="sr-only">{t('chat')}</h2> {status === 'pending' && <LoadingSpinner />} {shouldDisplayPlaceholder && <Placeholder />} <MessageList messages={messages} userId={user.id} resetUnreadMessages={markMessagesAsRead} /> </div> </InfiniteScroll> <MessageInput resetUnreadMessages={markMessagesAsRead} sendMessage={sendMessage} /> </aside> ) }) function LoadingSpinner() { const { t } = useTranslation() return ( <div className="loading"> <Icon type="fw" modifier="refresh" spin /> {` ${t('loading')}…`} </div> ) } function Placeholder() { const { t } = useTranslation() return ( <> <div className="no-messages text-center small">{t('no_messages')}</div> <div className="first-message text-center"> {t('send_first_message')} <br /> <Icon type="arrow-down" /> </div> </> ) } export default withErrorBoundary(ChatPane, ChatFallbackError)
overleaf/web/frontend/js/features/chat/components/chat-pane.js/0
{ "file_path": "overleaf/web/frontend/js/features/chat/components/chat-pane.js", "repo_id": "overleaf", "token_count": 1168 }
510
import React, { useCallback } from 'react' import PropTypes from 'prop-types' import ToolbarHeader from './toolbar-header' import { useEditorContext } from '../../../shared/context/editor-context' import { useChatContext } from '../../chat/context/chat-context' import { useLayoutContext } from '../../../shared/context/layout-context' import { useProjectContext } from '../../../shared/context/project-context' const projectContextPropTypes = { name: PropTypes.string.isRequired, } const editorContextPropTypes = { cobranding: PropTypes.object, loading: PropTypes.bool, isRestrictedTokenMember: PropTypes.bool, renameProject: PropTypes.func.isRequired, isProjectOwner: PropTypes.bool, permissionsLevel: PropTypes.string, } const layoutContextPropTypes = { chatIsOpen: PropTypes.bool, setChatIsOpen: PropTypes.func.isRequired, reviewPanelOpen: PropTypes.bool, setReviewPanelOpen: PropTypes.func.isRequired, view: PropTypes.string, setView: PropTypes.func.isRequired, setLeftMenuShown: PropTypes.func.isRequired, pdfLayout: PropTypes.string.isRequired, } const chatContextPropTypes = { markMessagesAsRead: PropTypes.func.isRequired, unreadMessageCount: PropTypes.number.isRequired, } const EditorNavigationToolbarRoot = React.memo( function EditorNavigationToolbarRoot({ onlineUsersArray, openDoc, openShareProjectModal, }) { const { name: projectName } = useProjectContext(projectContextPropTypes) const { cobranding, loading, isRestrictedTokenMember, renameProject, isProjectOwner, permissionsLevel, } = useEditorContext(editorContextPropTypes) const { chatIsOpen, setChatIsOpen, reviewPanelOpen, setReviewPanelOpen, view, setView, setLeftMenuShown, pdfLayout, } = useLayoutContext(layoutContextPropTypes) const { markMessagesAsRead, unreadMessageCount } = useChatContext( chatContextPropTypes ) const toggleChatOpen = useCallback(() => { if (!chatIsOpen) { markMessagesAsRead() } setChatIsOpen(value => !value) }, [chatIsOpen, setChatIsOpen, markMessagesAsRead]) const toggleReviewPanelOpen = useCallback( () => setReviewPanelOpen(value => !value), [setReviewPanelOpen] ) const toggleHistoryOpen = useCallback(() => { setView(view === 'history' ? 'editor' : 'history') }, [view, setView]) const togglePdfView = useCallback(() => { setView(view === 'pdf' ? 'editor' : 'pdf') }, [view, setView]) const openShareModal = useCallback(() => { openShareProjectModal(isProjectOwner) }, [openShareProjectModal, isProjectOwner]) const onShowLeftMenuClick = useCallback( () => setLeftMenuShown(value => !value), [setLeftMenuShown] ) const goToUser = useCallback( user => { if (user.doc && typeof user.row === 'number') { openDoc(user.doc, { gotoLine: user.row + 1 }) } }, [openDoc] ) // using {display: 'none'} as 1:1 migration from Angular's ng-hide. Using // `loading ? null : <ToolbarHeader/>` causes UI glitches return ( <ToolbarHeader style={loading ? { display: 'none' } : {}} cobranding={cobranding} onShowLeftMenuClick={onShowLeftMenuClick} chatIsOpen={chatIsOpen} unreadMessageCount={unreadMessageCount} toggleChatOpen={toggleChatOpen} reviewPanelOpen={reviewPanelOpen} toggleReviewPanelOpen={toggleReviewPanelOpen} historyIsOpen={view === 'history'} toggleHistoryOpen={toggleHistoryOpen} onlineUsers={onlineUsersArray} goToUser={goToUser} isRestrictedTokenMember={isRestrictedTokenMember} hasPublishPermissions={ permissionsLevel === 'owner' || permissionsLevel === 'readAndWrite' } projectName={projectName} renameProject={renameProject} hasRenamePermissions={permissionsLevel === 'owner'} openShareModal={openShareModal} pdfViewIsOpen={view === 'pdf'} pdfButtonIsVisible={pdfLayout === 'flat'} togglePdfView={togglePdfView} /> ) } ) EditorNavigationToolbarRoot.propTypes = { onlineUsersArray: PropTypes.array.isRequired, openDoc: PropTypes.func.isRequired, openShareProjectModal: PropTypes.func.isRequired, } export default EditorNavigationToolbarRoot
overleaf/web/frontend/js/features/editor-navigation-toolbar/components/editor-navigation-toolbar-root.js/0
{ "file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/editor-navigation-toolbar-root.js", "repo_id": "overleaf", "token_count": 1645 }
511
import { useTranslation } from 'react-i18next' import { Alert, Button } from 'react-bootstrap' import { useFileTreeCreateForm } from '../../contexts/file-tree-create-form' import { useFileTreeActionable } from '../../contexts/file-tree-actionable' import { useFileTreeMutable } from '../../contexts/file-tree-mutable' import PropTypes from 'prop-types' export default function FileTreeModalCreateFileFooter() { const { valid } = useFileTreeCreateForm() const { newFileCreateMode, inFlight, cancel } = useFileTreeActionable() const { fileCount } = useFileTreeMutable() return ( <FileTreeModalCreateFileFooterContent valid={valid} cancel={cancel} newFileCreateMode={newFileCreateMode} inFlight={inFlight} fileCount={fileCount} /> ) } export function FileTreeModalCreateFileFooterContent({ valid, fileCount, inFlight, newFileCreateMode, cancel, }) { const { t } = useTranslation() return ( <> {fileCount.status === 'warning' && ( <div className="modal-footer-left approaching-file-limit"> {t('project_approaching_file_limit')} ({fileCount.value}/ {fileCount.limit}) </div> )} {fileCount.status === 'error' && ( <Alert bsStyle="warning" className="at-file-limit"> {/* TODO: add parameter for fileCount.limit */} {t('project_has_too_many_files')} </Alert> )} <Button bsStyle="default" type="button" disabled={inFlight} onClick={cancel} > {t('cancel')} </Button> {newFileCreateMode !== 'upload' && ( <Button bsStyle="primary" type="submit" form="create-file" disabled={inFlight || !valid} > <span>{inFlight ? `${t('creating')}…` : t('create')}</span> </Button> )} </> ) } FileTreeModalCreateFileFooterContent.propTypes = { cancel: PropTypes.func.isRequired, fileCount: PropTypes.shape({ limit: PropTypes.number.isRequired, status: PropTypes.string.isRequired, value: PropTypes.number.isRequired, }).isRequired, inFlight: PropTypes.bool.isRequired, newFileCreateMode: PropTypes.string, valid: PropTypes.bool.isRequired, }
overleaf/web/frontend/js/features/file-tree/components/file-tree-create/file-tree-modal-create-file-footer.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/file-tree-modal-create-file-footer.js", "repo_id": "overleaf", "token_count": 923 }
512
import React, { useEffect } from 'react' import PropTypes from 'prop-types' import withErrorBoundary from '../../../infrastructure/error-boundary' import FileTreeContext from './file-tree-context' import FileTreeDraggablePreviewLayer from './file-tree-draggable-preview-layer' import FileTreeFolderList from './file-tree-folder-list' import FileTreeToolbar from './file-tree-toolbar' import FileTreeModalDelete from './modals/file-tree-modal-delete' import FileTreeModalCreateFolder from './modals/file-tree-modal-create-folder' import FileTreeModalError from './modals/file-tree-modal-error' import FileTreeContextMenu from './file-tree-context-menu' import FileTreeError from './file-tree-error' import { useFileTreeMutable } from '../contexts/file-tree-mutable' import { useDroppable } from '../contexts/file-tree-draggable' import { useFileTreeSocketListener } from '../hooks/file-tree-socket-listener' import FileTreeModalCreateFile from './modals/file-tree-modal-create-file' const FileTreeRoot = React.memo(function FileTreeRoot({ projectId, rootFolder, rootDocId, hasWritePermissions, userHasFeature, refProviders, reindexReferences, setRefProviderEnabled, setStartedFreeTrial, onSelect, onInit, isConnected, }) { const isReady = projectId && rootFolder useEffect(() => { if (isReady) onInit() }, [isReady, onInit]) if (!isReady) return null return ( <FileTreeContext projectId={projectId} hasWritePermissions={hasWritePermissions} userHasFeature={userHasFeature} refProviders={refProviders} setRefProviderEnabled={setRefProviderEnabled} setStartedFreeTrial={setStartedFreeTrial} reindexReferences={reindexReferences} rootFolder={rootFolder} rootDocId={rootDocId} onSelect={onSelect} > {isConnected ? null : <div className="disconnected-overlay" />} <FileTreeToolbar /> <FileTreeContextMenu /> <div className="file-tree-inner"> <FileTreeRootFolder /> </div> <FileTreeModalDelete /> <FileTreeModalCreateFile /> <FileTreeModalCreateFolder /> <FileTreeModalError /> </FileTreeContext> ) }) function FileTreeRootFolder() { useFileTreeSocketListener() const { fileTreeData } = useFileTreeMutable() const { isOver, dropRef } = useDroppable(fileTreeData._id) return ( <> <FileTreeDraggablePreviewLayer isOver={isOver} /> <FileTreeFolderList folders={fileTreeData.folders} docs={fileTreeData.docs} files={fileTreeData.fileRefs} classes={{ root: 'file-tree-list' }} dropRef={dropRef} isOver={isOver} > <li className="bottom-buffer" /> </FileTreeFolderList> </> ) } FileTreeRoot.propTypes = { projectId: PropTypes.string, rootFolder: PropTypes.array, rootDocId: PropTypes.string, hasWritePermissions: PropTypes.bool.isRequired, onSelect: PropTypes.func.isRequired, onInit: PropTypes.func.isRequired, isConnected: PropTypes.bool.isRequired, setRefProviderEnabled: PropTypes.func.isRequired, userHasFeature: PropTypes.func.isRequired, setStartedFreeTrial: PropTypes.func.isRequired, reindexReferences: PropTypes.func.isRequired, refProviders: PropTypes.object.isRequired, } export default withErrorBoundary(FileTreeRoot, FileTreeError)
overleaf/web/frontend/js/features/file-tree/components/file-tree-root.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-root.js", "repo_id": "overleaf", "token_count": 1204 }
513
import { useEffect, useState } from 'react' import { getJSON } from '../../../infrastructure/fetch-json' import { fileCollator } from '../util/file-collator' import useAbortController from '../../../shared/hooks/use-abort-controller' const alphabetical = (a, b) => fileCollator.compare(a.path, b.path) export function useProjectEntities(projectId) { const [loading, setLoading] = useState(false) const [data, setData] = useState(null) const [error, setError] = useState(false) const { signal } = useAbortController() useEffect(() => { if (projectId) { setLoading(true) setError(false) setData(null) getJSON(`/project/${projectId}/entities`, { signal }) .then(data => { setData(data.entities.sort(alphabetical)) }) .catch(error => setError(error)) .finally(() => setLoading(false)) } }, [projectId, signal]) return { loading, data, error } }
overleaf/web/frontend/js/features/file-tree/hooks/use-project-entities.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/hooks/use-project-entities.js", "repo_id": "overleaf", "token_count": 354 }
514
import { Button, Modal, Row, Col } from 'react-bootstrap' import PropTypes from 'prop-types' import { Trans, useTranslation } from 'react-i18next' import AccessibleModal from '../../../shared/components/accessible-modal' export default function HotkeysModal({ animation = true, handleHide, show, isMac = false, trackChangesVisible = false, }) { const { t } = useTranslation() const ctrl = isMac ? 'Cmd' : 'Ctrl' return ( <AccessibleModal bsSize="large" onHide={handleHide} show={show} animation={animation} > <Modal.Header closeButton> <Modal.Title>{t('hotkeys')}</Modal.Title> </Modal.Header> <Modal.Body className="modal-hotkeys"> <h3>{t('common')}</h3> <Row> <Col xs={4}> <Hotkey combination={`${ctrl} + F`} description={t('hotkey_find_and_replace')} /> <Hotkey combination={`${ctrl} + Enter`} description={t('hotkey_compile')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + Z`} description={t('hotkey_undo')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + Y`} description={t('hotkey_redo')} /> </Col> </Row> <h3>{t('navigation')}</h3> <Row> <Col xs={4}> <Hotkey combination={`${ctrl} + Home`} description={t('hotkey_beginning_of_document')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + End`} description={t('hotkey_end_of_document')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + L`} description={t('hotkey_go_to_line')} /> </Col> </Row> <h3>{t('editing')}</h3> <Row> <Col xs={4}> <Hotkey combination={`${ctrl} + /`} description={t('hotkey_toggle_comment')} /> <Hotkey combination={`${ctrl} + D`} description={t('hotkey_delete_current_line')} /> <Hotkey combination={`${ctrl} + A`} description={t('hotkey_select_all')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + U`} description={t('hotkey_to_uppercase')} /> <Hotkey combination={`${ctrl} + Shift + U`} description={t('hotkey_to_lowercase')} /> <Hotkey combination="Tab" description={t('hotkey_indent_selection')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + B`} description={t('hotkey_bold_text')} /> <Hotkey combination={`${ctrl} + I`} description={t('hotkey_italic_text')} /> </Col> </Row> <h3>{t('autocomplete')}</h3> <Row> <Col xs={4}> <Hotkey combination={`${ctrl} + Space`} description={t('hotkey_autocomplete_menu')} /> </Col> <Col xs={4}> <Hotkey combination="Tab / Up / Down" description={t('hotkey_select_candidate')} /> </Col> <Col xs={4}> <Hotkey combination="Enter" description={t('hotkey_insert_candidate')} /> </Col> </Row> <h3> <Trans i18nKey="autocomplete_references" components={{ code: <code /> }} /> </h3> <Row> <Col xs={4}> <Hotkey combination={`${ctrl} + Space `} description={t('hotkey_search_references')} /> </Col> </Row> {trackChangesVisible && ( <> <h3>{t('review')}</h3> <Row> <Col xs={4}> <Hotkey combination={`${ctrl} + J`} description={t('hotkey_toggle_review_panel')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + Shift + A`} description={t('hotkey_toggle_track_changes')} /> </Col> <Col xs={4}> <Hotkey combination={`${ctrl} + Shift + C`} description={t('hotkey_add_a_comment')} /> </Col> </Row> </> )} </Modal.Body> <Modal.Footer> <Button onClick={handleHide}>{t('ok')}</Button> </Modal.Footer> </AccessibleModal> ) } HotkeysModal.propTypes = { animation: PropTypes.bool, isMac: PropTypes.bool, show: PropTypes.bool.isRequired, handleHide: PropTypes.func.isRequired, trackChangesVisible: PropTypes.bool, } function Hotkey({ combination, description }) { return ( <div className="hotkey" data-test-selector="hotkey"> <span className="combination">{combination}</span> <span className="description">{description}</span> </div> ) } Hotkey.propTypes = { combination: PropTypes.string.isRequired, description: PropTypes.string.isRequired, }
overleaf/web/frontend/js/features/hotkeys-modal/components/hotkeys-modal.js/0
{ "file_path": "overleaf/web/frontend/js/features/hotkeys-modal/components/hotkeys-modal.js", "repo_id": "overleaf", "token_count": 3240 }
515
import { useState } from 'react' import PropTypes from 'prop-types' import PreviewToolbar from './preview-toolbar' import PreviewLogsPane from './preview-logs-pane' import PreviewFirstErrorPopUp from './preview-first-error-pop-up' import { useTranslation } from 'react-i18next' function PreviewPane({ compilerState, onClearCache, onRecompile, onRecompileFromScratch, onRunSyntaxCheckNow, onSetAutoCompile, onSetDraftMode, onSetSyntaxCheck, onToggleLogs, onSetFullLayout, onSetSplitLayout, onStopCompilation, outputFiles, pdfDownloadUrl, onLogEntryLocationClick, showLogs, variantWithFirstErrorPopup = true, splitLayout, }) { const { t } = useTranslation() const [lastCompileTimestamp, setLastCompileTimestamp] = useState( compilerState.lastCompileTimestamp ) const [seenLogsForCurrentCompile, setSeenLogsForCurrentCompile] = useState( false ) const [dismissedFirstErrorPopUp, setDismissedFirstErrorPopUp] = useState( false ) if (lastCompileTimestamp < compilerState.lastCompileTimestamp) { setLastCompileTimestamp(compilerState.lastCompileTimestamp) setSeenLogsForCurrentCompile(false) } if (showLogs && !seenLogsForCurrentCompile) { setSeenLogsForCurrentCompile(true) } const nErrors = compilerState.logEntries && compilerState.logEntries.errors ? compilerState.logEntries.errors.length : 0 const nWarnings = compilerState.logEntries && compilerState.logEntries.warnings ? compilerState.logEntries.warnings.length : 0 const hasCLSIErrors = compilerState.errors && Object.keys(compilerState.errors).length > 0 && compilerState.compileFailed && !compilerState.isCompiling const hasValidationIssues = compilerState.validationIssues && Object.keys(compilerState.validationIssues).length > 0 && compilerState.compileFailed && !compilerState.isCompiling const showFirstErrorPopUp = variantWithFirstErrorPopup && nErrors > 0 && !seenLogsForCurrentCompile && !dismissedFirstErrorPopUp && !compilerState.isCompiling function handleFirstErrorPopUpClose() { setDismissedFirstErrorPopUp(true) } return ( <> <PreviewToolbar compilerState={compilerState} logsState={{ nErrors, nWarnings }} showLogs={showLogs} onRecompile={onRecompile} onRecompileFromScratch={onRecompileFromScratch} onRunSyntaxCheckNow={onRunSyntaxCheckNow} onSetAutoCompile={onSetAutoCompile} onSetDraftMode={onSetDraftMode} onSetSyntaxCheck={onSetSyntaxCheck} onToggleLogs={onToggleLogs} onSetSplitLayout={onSetSplitLayout} onSetFullLayout={onSetFullLayout} onStopCompilation={onStopCompilation} outputFiles={outputFiles} pdfDownloadUrl={pdfDownloadUrl} splitLayout={splitLayout} /> <span aria-live="polite" className="sr-only"> {hasCLSIErrors ? t('compile_error_description') : ''} </span> <span aria-live="polite" className="sr-only"> {hasValidationIssues ? t('validation_issue_description') : ''} </span> <span aria-live="polite" className="sr-only"> {nErrors && !compilerState.isCompiling ? t('n_errors', { count: nErrors }) : ''} </span> <span aria-live="polite" className="sr-only"> {nWarnings && !compilerState.isCompiling ? t('n_warnings', { count: nWarnings }) : ''} </span> {showFirstErrorPopUp ? ( <PreviewFirstErrorPopUp logEntry={compilerState.logEntries.errors[0]} nErrors={nErrors} onGoToErrorLocation={onLogEntryLocationClick} onViewLogs={onToggleLogs} onClose={handleFirstErrorPopUpClose} /> ) : null} {showLogs ? ( <PreviewLogsPane logEntries={compilerState.logEntries} rawLog={compilerState.rawLog} validationIssues={compilerState.validationIssues} errors={compilerState.errors} autoCompileHasLintingError={compilerState.autoCompileHasLintingError} outputFiles={outputFiles} onLogEntryLocationClick={onLogEntryLocationClick} isClearingCache={compilerState.isClearingCache} isCompiling={compilerState.isCompiling} variantWithFirstErrorPopup={variantWithFirstErrorPopup} onClearCache={onClearCache} /> ) : null} </> ) } PreviewPane.propTypes = { compilerState: PropTypes.shape({ autoCompileHasLintingError: PropTypes.bool, isAutoCompileOn: PropTypes.bool.isRequired, isCompiling: PropTypes.bool.isRequired, isDraftModeOn: PropTypes.bool.isRequired, isSyntaxCheckOn: PropTypes.bool.isRequired, isClearingCache: PropTypes.bool.isRequired, lastCompileTimestamp: PropTypes.number, logEntries: PropTypes.object, validationIssues: PropTypes.object, errors: PropTypes.object, rawLog: PropTypes.string, compileFailed: PropTypes.bool, }), onClearCache: PropTypes.func.isRequired, onLogEntryLocationClick: PropTypes.func.isRequired, onRecompile: PropTypes.func.isRequired, onRecompileFromScratch: PropTypes.func.isRequired, onRunSyntaxCheckNow: PropTypes.func.isRequired, onSetAutoCompile: PropTypes.func.isRequired, onSetDraftMode: PropTypes.func.isRequired, onSetSyntaxCheck: PropTypes.func.isRequired, onSetSplitLayout: PropTypes.func.isRequired, onSetFullLayout: PropTypes.func.isRequired, onStopCompilation: PropTypes.func.isRequired, onToggleLogs: PropTypes.func.isRequired, outputFiles: PropTypes.array, pdfDownloadUrl: PropTypes.string, showLogs: PropTypes.bool.isRequired, variantWithFirstErrorPopup: PropTypes.bool, splitLayout: PropTypes.bool.isRequired, } export default PreviewPane
overleaf/web/frontend/js/features/preview/components/preview-pane.js/0
{ "file_path": "overleaf/web/frontend/js/features/preview/components/preview-pane.js", "repo_id": "overleaf", "token_count": 2305 }
516
import React, { createContext, useCallback, useContext, useEffect, useState, } from 'react' import PropTypes from 'prop-types' import ShareProjectModalContent from './share-project-modal-content' import { useProjectContext } from '../../../shared/context/project-context' const ShareProjectContext = createContext() ShareProjectContext.Provider.propTypes = { value: PropTypes.shape({ isAdmin: PropTypes.bool.isRequired, updateProject: PropTypes.func.isRequired, monitorRequest: PropTypes.func.isRequired, inFlight: PropTypes.bool, setInFlight: PropTypes.func, error: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), setError: PropTypes.func, }), } export function useShareProjectContext() { const context = useContext(ShareProjectContext) if (!context) { throw new Error( 'useShareProjectContext is only available inside ShareProjectProvider' ) } return context } const projectShape = { _id: PropTypes.string.isRequired, members: PropTypes.arrayOf( PropTypes.shape({ _id: PropTypes.string.isRequired, }) ), invites: PropTypes.arrayOf( PropTypes.shape({ _id: PropTypes.string.isRequired, }) ), name: PropTypes.string, features: PropTypes.shape({ collaborators: PropTypes.number, }), publicAccesLevel: PropTypes.string, tokens: PropTypes.shape({ readOnly: PropTypes.string, readAndWrite: PropTypes.string, }), owner: PropTypes.shape({ email: PropTypes.string, }), } const ShareProjectModal = React.memo(function ShareProjectModal({ handleHide, show, animation = true, isAdmin, }) { const [inFlight, setInFlight] = useState(false) const [error, setError] = useState() const project = useProjectContext(projectShape) // reset error when the modal is opened useEffect(() => { if (show) { setError(undefined) } }, [show]) // close the modal if not in flight const cancel = useCallback(() => { if (!inFlight) { handleHide() } }, [handleHide, inFlight]) // update `error` and `inFlight` while sending a request const monitorRequest = useCallback(request => { setError(undefined) setInFlight(true) const promise = request() promise.catch(error => { setError( error.data?.errorReason || error.data?.error || 'generic_something_went_wrong' ) }) promise.finally(() => { setInFlight(false) }) return promise }, []) // merge the new data with the old project data const updateProject = useCallback(data => Object.assign(project, data), [ project, ]) if (!project) { return null } return ( <ShareProjectContext.Provider value={{ isAdmin, updateProject, monitorRequest, inFlight, setInFlight, error, setError, }} > <ShareProjectModalContent animation={animation} cancel={cancel} error={error} inFlight={inFlight} show={show} /> </ShareProjectContext.Provider> ) }) ShareProjectModal.propTypes = { animation: PropTypes.bool, handleHide: PropTypes.func.isRequired, isAdmin: PropTypes.bool.isRequired, show: PropTypes.bool.isRequired, } export default ShareProjectModal
overleaf/web/frontend/js/features/share-project-modal/components/share-project-modal.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/share-project-modal.js", "repo_id": "overleaf", "token_count": 1222 }
517
import App from '../../../base' import { react2angular } from 'react2angular' import SymbolPalette from '../components/symbol-palette' App.component('symbolPalette', react2angular(SymbolPalette))
overleaf/web/frontend/js/features/symbol-palette/controllers/symbol-palette-controller.js/0
{ "file_path": "overleaf/web/frontend/js/features/symbol-palette/controllers/symbol-palette-controller.js", "repo_id": "overleaf", "token_count": 61 }
518
import './controllers/ChatButtonController' import '../../features/chat/controllers/chat-controller'
overleaf/web/frontend/js/ide/chat/index.js/0
{ "file_path": "overleaf/web/frontend/js/ide/chat/index.js", "repo_id": "overleaf", "token_count": 27 }
519
/* 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: * DS001: Remove Babel/TypeScript constructor workaround * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__ * DS205: Consider reworking code to avoid use of IIFEs * DS206: Consider reworking classes to avoid initClass * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import EventEmitter from '../../utils/EventEmitter' import ShareJs from 'libs/sharejs' import EditorWatchdogManager from '../connection/EditorWatchdogManager' let ShareJsDoc const SINGLE_USER_FLUSH_DELAY = 2000 // ms const MULTI_USER_FLUSH_DELAY = 500 // ms export default ShareJsDoc = (function () { ShareJsDoc = class ShareJsDoc extends EventEmitter { static initClass() { this.prototype.INFLIGHT_OP_TIMEOUT = 5000 // Retry sending ops after 5 seconds without an ack this.prototype.WAIT_FOR_CONNECTION_TIMEOUT = 500 this.prototype.FATAL_OP_TIMEOUT = 30000 } constructor( doc_id, docLines, version, socket, globalEditorWatchdogManager ) { super() // Dencode any binary bits of data // See http://ecmanaut.blogspot.co.uk/2006/07/encoding-decoding-utf8-in-javascript.html this.doc_id = doc_id this.socket = socket this.type = 'text' docLines = Array.from(docLines).map(line => decodeURIComponent(escape(line)) ) const snapshot = docLines.join('\n') this.track_changes = false this.connection = { send: update => { this._startInflightOpTimeout(update) if ( window.disconnectOnUpdate != null && Math.random() < window.disconnectOnUpdate ) { sl_console.log('Disconnecting on update', update) window._ide.socket.socket.disconnect() } if ( window.dropUpdates != null && Math.random() < window.dropUpdates ) { sl_console.log('Simulating a lost update', update) return } if (this.track_changes) { if (update.meta == null) { update.meta = {} } update.meta.tc = this.track_changes_id_seeds.inflight } return this.socket.emit( 'applyOtUpdate', this.doc_id, update, error => { if (error != null) { return this._handleError(error) } } ) }, state: 'ok', id: this.socket.publicId, } this._doc = new ShareJs.Doc(this.connection, this.doc_id, { type: this.type, }) this._doc.setFlushDelay(SINGLE_USER_FLUSH_DELAY) this._doc.on('change', (...args) => { return this.trigger('change', ...Array.from(args)) }) this.EditorWatchdogManager = new EditorWatchdogManager({ parent: globalEditorWatchdogManager, }) this._doc.on('acknowledge', () => { this.lastAcked = new Date() // note time of last ack from server for an op we sent this.EditorWatchdogManager.onAck() // keep track of last ack globally return this.trigger('acknowledge') }) this._doc.on('remoteop', (...args) => { // As soon as we're working with a collaborator, start sending // ops more frequently for low latency. this._doc.setFlushDelay(MULTI_USER_FLUSH_DELAY) return this.trigger('remoteop', ...Array.from(args)) }) this._doc.on('flipped_pending_to_inflight', () => { return this.trigger('flipped_pending_to_inflight') }) this._doc.on('saved', () => { return this.trigger('saved') }) this._doc.on('error', e => { return this._handleError(e) }) this._bindToDocChanges(this._doc) this.processUpdateFromServer({ open: true, v: version, snapshot, }) this._removeCarriageReturnCharFromShareJsDoc() } _removeCarriageReturnCharFromShareJsDoc() { const doc = this._doc if (doc.snapshot.indexOf('\r') === -1) { return } window._ide.pushEvent('remove-carriage-return-char', { doc_id: this.doc_id, }) let nextPos while ((nextPos = doc.snapshot.indexOf('\r')) !== -1) { sl_console.log('[ShareJsDoc] remove-carriage-return-char', nextPos) doc.del(nextPos, 1) } } submitOp(...args) { return this._doc.submitOp(...Array.from(args || [])) } // The following code puts out of order messages into a queue // so that they can be processed in order. This is a workaround // for messages being delayed by redis cluster. // FIXME: REMOVE THIS WHEN REDIS PUBSUB IS SENDING MESSAGES IN ORDER _isAheadOfExpectedVersion(message) { return this._doc.version > 0 && message.v > this._doc.version } _pushOntoQueue(message) { sl_console.log(`[processUpdate] push onto queue ${message.v}`) // set a timer so that we never leave messages in the queue indefinitely if (!this.queuedMessageTimer) { this.queuedMessageTimer = setTimeout(() => { sl_console.log(`[processUpdate] queue timeout fired for ${message.v}`) // force the message to be processed after the timeout, // it will cause an error if the missing update has not arrived this.processUpdateFromServer(message) }, this.INFLIGHT_OP_TIMEOUT) } this.queuedMessages.push(message) // keep the queue in order, lowest version first this.queuedMessages.sort(function (a, b) { return a.v - b.v }) } _clearQueue() { this.queuedMessages = [] } _processQueue() { if (this.queuedMessages.length > 0) { const nextAvailableVersion = this.queuedMessages[0].v if (nextAvailableVersion > this._doc.version) { // there are updates we still can't apply yet } else { // there's a version we can accept on the queue, apply it sl_console.log( `[processUpdate] taken from queue ${nextAvailableVersion}` ) this.processUpdateFromServerInOrder(this.queuedMessages.shift()) // clear the pending timer if the queue has now been cleared if (this.queuedMessages.length === 0 && this.queuedMessageTimer) { sl_console.log('[processUpdate] queue is empty, cleared timeout') clearTimeout(this.queuedMessageTimer) this.queuedMessageTimer = null } } } } // FIXME: This is the new method which reorders incoming updates if needed // called from Document.js processUpdateFromServerInOrder(message) { // Create an array to hold queued messages if (!this.queuedMessages) { this.queuedMessages = [] } // Is this update ahead of the next expected update? // If so, put it on a queue to be handled later. if (this._isAheadOfExpectedVersion(message)) { this._pushOntoQueue(message) return // defer processing this update for now } var error = this.processUpdateFromServer(message) if ( error instanceof Error && error.message === 'Invalid version from server' ) { // if there was an error, abandon the queued updates ahead of this one this._clearQueue() return } // Do we have any messages queued up? // find the next message if available this._processQueue() } // FIXME: This is the original method. Switch back to this when redis // issues are resolved. processUpdateFromServer(message) { try { this._doc._onMessage(message) } catch (error) { // Version mismatches are thrown as errors console.log(error) this._handleError(error) return error // return the error for queue handling } if ( __guard__(message != null ? message.meta : undefined, x => x.type) === 'external' ) { return this.trigger('externalUpdate', message) } } catchUp(updates) { return (() => { const result = [] for (let i = 0; i < updates.length; i++) { const update = updates[i] update.v = this._doc.version update.doc = this.doc_id result.push(this.processUpdateFromServer(update)) } return result })() } getSnapshot() { return this._doc.snapshot } getVersion() { return this._doc.version } getType() { return this.type } clearInflightAndPendingOps() { this._clearFatalTimeoutTimer() this._doc.inflightOp = null this._doc.inflightCallbacks = [] this._doc.pendingOp = null return (this._doc.pendingCallbacks = []) } flushPendingOps() { // This will flush any ops that are pending. // If there is an inflight op it will do nothing. return this._doc.flush() } updateConnectionState(state) { sl_console.log(`[updateConnectionState] Setting state to ${state}`) this.connection.state = state this.connection.id = this.socket.publicId this._doc.autoOpen = false this._doc._connectionStateChanged(state) return (this.lastAcked = null) // reset the last ack time when connection changes } hasBufferedOps() { return this._doc.inflightOp != null || this._doc.pendingOp != null } getInflightOp() { return this._doc.inflightOp } getPendingOp() { return this._doc.pendingOp } getRecentAck() { // check if we have received an ack recently (within a factor of two of the single user flush delay) return ( this.lastAcked != null && new Date() - this.lastAcked < 2 * SINGLE_USER_FLUSH_DELAY ) } getOpSize(op) { // compute size of an op from its components // (total number of characters inserted and deleted) let size = 0 for (const component of Array.from(op || [])) { if ((component != null ? component.i : undefined) != null) { size += component.i.length } if ((component != null ? component.d : undefined) != null) { size += component.d.length } } return size } _attachEditorWatchdogManager(editorName, editor) { // end-to-end check for edits -> acks, for this very ShareJsdoc // This will catch a broken connection and missing UX-blocker for the // user, allowing them to keep editing. this._detachEditorWatchdogManager = this.EditorWatchdogManager.attachToEditor( editorName, editor ) } _attachToEditor(editorName, editor, attachToShareJs) { this._attachEditorWatchdogManager(editorName, editor) attachToShareJs() } _maybeDetachEditorWatchdogManager() { // a failed attach attempt may lead to a missing cleanup handler if (this._detachEditorWatchdogManager) { this._detachEditorWatchdogManager() delete this._detachEditorWatchdogManager } } attachToAce(ace) { this._attachToEditor('Ace', ace, () => { this._doc.attach_ace(ace, false, window.maxDocLength) }) } detachFromAce() { this._maybeDetachEditorWatchdogManager() return typeof this._doc.detach_ace === 'function' ? this._doc.detach_ace() : undefined } attachToCM(cm) { this._attachToEditor('CM', cm, () => { this._doc.attach_cm(cm, false) }) } detachFromCM() { this._maybeDetachEditorWatchdogManager() return typeof this._doc.detach_cm === 'function' ? this._doc.detach_cm() : undefined } // If we're waiting for the project to join, try again in 0.5 seconds _startInflightOpTimeout(update) { this._startFatalTimeoutTimer(update) var retryOp = () => { // Only send the update again if inflightOp is still populated // This can be cleared when hard reloading the document in which // case we don't want to keep trying to send it. sl_console.log('[inflightOpTimeout] Trying op again') if (this._doc.inflightOp != null) { // When there is a socket.io disconnect, @_doc.inflightSubmittedIds // is updated with the socket.io client id of the current op in flight // (meta.source of the op). // @connection.id is the client id of the current socket.io session. // So we need both depending on whether the op was submitted before // one or more disconnects, or if it was submitted during the current session. update.dupIfSource = [ this.connection.id, ...Array.from(this._doc.inflightSubmittedIds), ] // We must be joined to a project for applyOtUpdate to work on the real-time // service, so don't send an op if we're not. Connection state is set to 'ok' // when we've joined the project if (this.connection.state !== 'ok') { let timer sl_console.log( '[inflightOpTimeout] Not connected, retrying in 0.5s' ) return (timer = setTimeout( retryOp, this.WAIT_FOR_CONNECTION_TIMEOUT )) } else { sl_console.log('[inflightOpTimeout] Sending') return this.connection.send(update) } } } const timer = setTimeout(retryOp, this.INFLIGHT_OP_TIMEOUT) return this._doc.inflightCallbacks.push(() => { this._clearFatalTimeoutTimer() return clearTimeout(timer) }) // 30 seconds } _startFatalTimeoutTimer(update) { // If an op doesn't get acked within FATAL_OP_TIMEOUT, something has // gone unrecoverably wrong (the op will have been retried multiple times) if (this._timeoutTimer != null) { return } return (this._timeoutTimer = setTimeout(() => { this._clearFatalTimeoutTimer() return this.trigger('op:timeout', update) }, this.FATAL_OP_TIMEOUT)) } _clearFatalTimeoutTimer() { if (this._timeoutTimer == null) { return } clearTimeout(this._timeoutTimer) return (this._timeoutTimer = null) } _handleError(error, meta) { if (meta == null) { meta = {} } return this.trigger('error', error, meta) } _bindToDocChanges(doc) { const { submitOp } = doc doc.submitOp = (...args) => { this.trigger('op:sent', ...Array.from(args)) doc.pendingCallbacks.push(() => { return this.trigger('op:acknowledged', ...Array.from(args)) }) return submitOp.apply(doc, args) } const { flush } = doc return (doc.flush = (...args) => { this.trigger('flush', doc.inflightOp, doc.pendingOp, doc.version) return flush.apply(doc, args) }) } } ShareJsDoc.initClass() return ShareJsDoc })() function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/frontend/js/ide/editor/ShareJsDoc.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/ShareJsDoc.js", "repo_id": "overleaf", "token_count": 6500 }
520
import HighlightedWordManager from './HighlightedWordManager' import 'ace/ace' const { Range } = ace.require('ace/range') class SpellCheckAdapter { constructor(editor) { this.replaceWord = this.replaceWord.bind(this) this.editor = editor this.highlightedWordManager = new HighlightedWordManager(this.editor) } getLines() { return this.editor.getValue().split('\n') } getLineCount() { return this.editor.session.getLength() } getFirstVisibleRowNum() { return this.editor.renderer.layerConfig.firstRow } getLastVisibleRowNum() { return this.editor.renderer.layerConfig.lastRow } getLinesByRows(rows) { return rows.map(rowIdx => this.editor.session.doc.getLine(rowIdx)) } getSelectionContents() { return this.editor.getSelectedText() } normalizeChangeEvent(e) { return e } getCoordsFromContextMenuEvent(e) { e.domEvent.stopPropagation() return { x: e.domEvent.clientX, y: e.domEvent.clientY, } } preventContextMenuEventDefault(e) { e.domEvent.preventDefault() } getHighlightFromCoords(coords) { const position = this.editor.renderer.screenToTextCoordinates( coords.x, coords.y ) return this.highlightedWordManager.findHighlightWithinRange({ start: position, end: position, }) } isContextMenuEventOnBottomHalf(e) { const { clientY } = e.domEvent const editorBoundingRect = e.target.container.getBoundingClientRect() const relativeYPos = (clientY - editorBoundingRect.top) / editorBoundingRect.height return relativeYPos > 0.5 } selectHighlightedWord(highlight) { const { row } = highlight.range.start const startColumn = highlight.range.start.column const endColumn = highlight.range.end.column this.editor .getSession() .getSelection() .setSelectionRange(new Range(row, startColumn, row, endColumn)) } replaceWord(highlight, newWord) { const { row } = highlight.range.start const startColumn = highlight.range.start.column const endColumn = highlight.range.end.column this.editor .getSession() .replace(new Range(row, startColumn, row, endColumn), newWord) // Bring editor back into focus after clicking on suggestion this.editor.focus() } } export default SpellCheckAdapter
overleaf/web/frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckAdapter.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckAdapter.js", "repo_id": "overleaf", "token_count": 852 }
521
/* eslint-disable camelcase, max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS206: Consider reworking classes to avoid initClass * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import moment from 'moment' import ColorManager from '../colors/ColorManager' import displayNameForUser from './util/displayNameForUser' import './controllers/HistoryListController' import './controllers/HistoryDiffController' import './directives/infiniteScroll' let HistoryManager export default HistoryManager = (function () { HistoryManager = class HistoryManager { static initClass() { this.prototype.BATCH_SIZE = 10 } constructor(ide, $scope) { this.ide = ide this.$scope = $scope this.reset() this.$scope.toggleHistory = () => { if (this.$scope.ui.view === 'history') { return this.hide() } else { return this.show() } } this.$scope.$watch('history.selection.updates', updates => { if (updates != null && updates.length > 0) { this._selectDocFromUpdates() return this.reloadDiff() } }) this.$scope.$on('entity:selected', (event, entity) => { if (this.$scope.ui.view === 'history' && entity.type === 'doc') { this.$scope.history.selection.doc = entity return this.reloadDiff() } }) } show() { this.$scope.ui.view = 'history' return this.reset() } hide() { this.$scope.ui.view = 'editor' // Make sure we run the 'open' logic for whatever is currently selected return this.$scope.$emit( 'entity:selected', this.ide.fileTreeManager.findSelectedEntity() ) } reset() { return (this.$scope.history = { updates: [], nextBeforeTimestamp: null, atEnd: false, selection: { updates: [], doc: null, range: { fromV: null, toV: null, start_ts: null, end_ts: null, }, }, diff: null, }) } autoSelectRecentUpdates() { if (this.$scope.history.updates.length === 0) { return } this.$scope.history.updates[0].selectedTo = true let indexOfLastUpdateNotByMe = 0 for (let i = 0; i < this.$scope.history.updates.length; i++) { const update = this.$scope.history.updates[i] if (this._updateContainsUserId(update, this.$scope.user.id)) { break } indexOfLastUpdateNotByMe = i } return (this.$scope.history.updates[ indexOfLastUpdateNotByMe ].selectedFrom = true) } fetchNextBatchOfUpdates() { let url = `/project/${this.ide.project_id}/updates?min_count=${this.BATCH_SIZE}` if (this.$scope.history.nextBeforeTimestamp != null) { url += `&before=${this.$scope.history.nextBeforeTimestamp}` } this.$scope.history.loading = true return this.ide.$http.get(url).then(response => { const { data } = response this._loadUpdates(data.updates) this.$scope.history.nextBeforeTimestamp = data.nextBeforeTimestamp if (data.nextBeforeTimestamp == null) { this.$scope.history.atEnd = true } return (this.$scope.history.loading = false) }) } reloadDiff() { let { diff } = this.$scope.history const { updates, doc } = this.$scope.history.selection const { fromV, toV, start_ts, end_ts, } = this._calculateRangeFromSelection() if (doc == null) { return } if ( diff != null && diff.doc === doc && diff.fromV === fromV && diff.toV === toV ) { return } this.$scope.history.diff = diff = { fromV, toV, start_ts, end_ts, doc, error: false, pathname: doc.name, } if (!doc.deleted) { diff.loading = true let url = `/project/${this.$scope.project_id}/doc/${diff.doc.id}/diff` if (diff.fromV != null && diff.toV != null) { url += `?from=${diff.fromV}&to=${diff.toV}` } return this.ide.$http .get(url) .then(response => { const { data } = response diff.loading = false const { text, highlights } = this._parseDiff(data) diff.text = text return (diff.highlights = highlights) }) .catch(function () { diff.loading = false return (diff.error = true) }) } else { diff.deleted = true diff.restoreInProgress = false diff.restoreDeletedSuccess = false return (diff.restoredDocNewId = null) } } restoreDeletedDoc(doc) { const url = `/project/${this.$scope.project_id}/doc/${doc.id}/restore` return this.ide.$http.post(url, { name: doc.name, _csrf: window.csrfToken, }) } restoreDiff(diff) { const url = `/project/${this.$scope.project_id}/doc/${diff.doc.id}/version/${diff.fromV}/restore` return this.ide.$http.post(url, { _csrf: window.csrfToken }) } _parseDiff(diff) { let row = 0 let column = 0 const highlights = [] let text = '' const iterable = diff.diff || [] for (let i = 0; i < iterable.length; i++) { var endColumn, endRow const entry = iterable[i] let content = entry.u || entry.i || entry.d if (!content) { content = '' } text += content const lines = content.split('\n') const startRow = row const startColumn = column if (lines.length > 1) { endRow = startRow + lines.length - 1 endColumn = lines[lines.length - 1].length } else { endRow = startRow endColumn = startColumn + lines[0].length } row = endRow column = endColumn const range = { start: { row: startRow, column: startColumn, }, end: { row: endRow, column: endColumn, }, } if (entry.i != null || entry.d != null) { const name = displayNameForUser(entry.meta.user) const date = moment(entry.meta.end_ts).format('Do MMM YYYY, h:mm a') if (entry.i != null) { highlights.push({ label: `Added by ${name} on ${date}`, highlight: range, hue: ColorManager.getHueForUserId( entry.meta.user != null ? entry.meta.user.id : undefined ), }) } else if (entry.d != null) { highlights.push({ label: `Deleted by ${name} on ${date}`, strikeThrough: range, hue: ColorManager.getHueForUserId( entry.meta.user != null ? entry.meta.user.id : undefined ), }) } } } return { text, highlights } } _loadUpdates(updates) { if (updates == null) { updates = [] } let previousUpdate = this.$scope.history.updates[ this.$scope.history.updates.length - 1 ] for (const update of Array.from(updates)) { update.pathnames = [] // Used for display const object = update.docs || {} for (const doc_id in object) { const doc = object[doc_id] doc.entity = this.ide.fileTreeManager.findEntityById(doc_id, { includeDeleted: true, }) update.pathnames.push(doc.entity.name) } for (const user of Array.from(update.meta.users || [])) { if (user != null) { user.hue = ColorManager.getHueForUserId(user.id) } } if ( previousUpdate == null || !moment(previousUpdate.meta.end_ts).isSame(update.meta.end_ts, 'day') ) { update.meta.first_in_day = true } update.selectedFrom = false update.selectedTo = false update.inSelection = false previousUpdate = update } const firstLoad = this.$scope.history.updates.length === 0 this.$scope.history.updates = this.$scope.history.updates.concat(updates) if (firstLoad) { return this.autoSelectRecentUpdates() } } _calculateRangeFromSelection() { let end_ts, start_ts, toV let fromV = (toV = start_ts = end_ts = null) const selected_doc_id = this.$scope.history.selection.doc != null ? this.$scope.history.selection.doc.id : undefined for (const update of Array.from( this.$scope.history.selection.updates || [] )) { for (const doc_id in update.docs) { const doc = update.docs[doc_id] if (doc_id === selected_doc_id) { if (fromV != null && toV != null) { fromV = Math.min(fromV, doc.fromV) toV = Math.max(toV, doc.toV) start_ts = Math.min(start_ts, update.meta.start_ts) end_ts = Math.max(end_ts, update.meta.end_ts) } else { ;({ fromV } = doc) ;({ toV } = doc) ;({ start_ts } = update.meta) ;({ end_ts } = update.meta) } break } } } return { fromV, toV, start_ts, end_ts } } // Set the track changes selected doc to one of the docs in the range // of currently selected updates. If we already have a selected doc // then prefer this one if present. _selectDocFromUpdates() { let doc, doc_id const affected_docs = {} for (const update of Array.from(this.$scope.history.selection.updates)) { for (doc_id in update.docs) { doc = update.docs[doc_id] affected_docs[doc_id] = doc.entity } } let selected_doc = this.$scope.history.selection.doc if (selected_doc != null && affected_docs[selected_doc.id] != null) { // Selected doc is already open } else { const doc_ids = Object.keys(affected_docs) if (doc_ids.length > 0) { const doc_id = doc_ids[0] doc = affected_docs[doc_id] selected_doc = doc } } this.$scope.history.selection.doc = selected_doc return this.ide.fileTreeManager.selectEntity(selected_doc) } _updateContainsUserId(update, user_id) { for (const user of Array.from(update.meta.users)) { if ((user != null ? user.id : undefined) === user_id) { return true } } return false } } HistoryManager.initClass() return HistoryManager })()
overleaf/web/frontend/js/ide/history/HistoryManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/HistoryManager.js", "repo_id": "overleaf", "token_count": 5237 }
522
import App from '../../../base' export default App.directive('historyDroppableArea', () => ({ scope: { historyDroppableAreaOnDrop: '&', historyDroppableAreaOnOver: '&', historyDroppableAreaOnOut: '&', }, restrict: 'A', link(scope, element, attrs) { element.droppable({ accept: e => '.history-entry-toV-handle, .history-entry-fromV-handle', drop: (e, ui) => { const draggedBoundary = ui.draggable.data('selectionBoundary').boundary ui.helper.data('wasProperlyDropped', true) scope.historyDroppableAreaOnDrop({ boundary: draggedBoundary }) }, over: (e, ui) => { const draggedBoundary = ui.draggable.data('selectionBoundary').boundary scope.historyDroppableAreaOnOver({ boundary: draggedBoundary }) }, }) }, }))
overleaf/web/frontend/js/ide/history/directives/historyDroppableArea.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/directives/historyDroppableArea.js", "repo_id": "overleaf", "token_count": 326 }
523