From a8b458dcc9286cc4aaca840e35545afe8a97488f Mon Sep 17 00:00:00 2001 From: ItsSelis Date: Sat, 25 Jun 2022 18:55:15 +0200 Subject: [PATCH] Added prettierx --- .vscode/extensions.json | 3 +- .vscode/settings.json | 39 +- tgui/.eslintrc.yml | 55 +- tgui/.prettierignore | 19 + tgui/.prettierrc.yml | 5 +- tgui/.yarn/sdks/eslint/lib/api.js | 6 +- tgui/.yarn/sdks/prettier/index.js | 20 + tgui/.yarn/sdks/prettier/package.json | 6 + tgui/.yarn/sdks/typescript/lib/tsserver.js | 90 +- .../sdks/typescript/lib/tsserverlibrary.js | 90 +- tgui/babel.config.js | 5 +- tgui/bin/tgui_.ps1 | 5 + tgui/global.d.ts | 25 +- tgui/jest.config.js | 9 +- tgui/package.json | 9 +- tgui/packages/common/collections.spec.ts | 18 +- tgui/packages/common/collections.ts | 84 +- tgui/packages/common/color.js | 17 +- tgui/packages/common/events.js | 7 +- tgui/packages/common/fp.js | 34 +- tgui/packages/common/math.ts | 8 +- tgui/packages/common/perf.js | 5 +- tgui/packages/common/react.ts | 6 +- tgui/packages/common/redux.js | 53 +- tgui/packages/common/storage.js | 26 +- tgui/packages/common/string.babel-plugin.cjs | 8 +- tgui/packages/common/string.js | 108 +- tgui/packages/common/timer.js | 4 +- tgui/packages/common/types.ts | 3 +- tgui/packages/common/uuid.js | 4 +- tgui/packages/common/vector.js | 10 +- tgui/packages/tgfont/dist/tgfont.css | 47 +- tgui/packages/tgfont/icons/ATTRIBUTIONS.md | 2 + tgui/packages/tgfont/mkdist.cjs | 3 +- tgui/packages/tgui-bench/entrypoint.tsx | 3 +- tgui/packages/tgui-bench/index.js | 6 +- tgui/packages/tgui-bench/lib/benchmark.d.ts | 12 +- tgui/packages/tgui-bench/lib/benchmark.js | 761 ++++++----- .../packages/tgui-bench/tests/Button.test.tsx | 24 +- .../tgui-bench/tests/DisposalBin.test.tsx | 8 +- tgui/packages/tgui-bench/tests/Flex.test.tsx | 4 +- tgui/packages/tgui-bench/tests/Stack.test.tsx | 4 +- .../tgui-bench/tests/Tooltip.test.tsx | 4 +- tgui/packages/tgui-dev-server/dreamseeker.js | 16 +- tgui/packages/tgui-dev-server/link/client.cjs | 30 +- tgui/packages/tgui-dev-server/link/retrace.js | 20 +- tgui/packages/tgui-dev-server/link/server.js | 31 +- tgui/packages/tgui-dev-server/logging.js | 22 +- tgui/packages/tgui-dev-server/reloader.js | 20 +- tgui/packages/tgui-dev-server/util.js | 3 +- tgui/packages/tgui-dev-server/webpack.js | 6 +- tgui/packages/tgui-dev-server/winreg.js | 7 +- tgui/packages/tgui-polyfill/00-html5shiv.js | 146 +- tgui/packages/tgui-polyfill/01-ie8.js | 905 ++++++------- tgui/packages/tgui-polyfill/02-dom4.js | 796 ++++++----- tgui/packages/tgui-polyfill/03-css-om.js | 3 +- tgui/packages/tgui-polyfill/10-misc.js | 36 +- tgui/packages/tgui/assets.js | 8 +- tgui/packages/tgui/backend.ts | 104 +- .../tgui/components/AnimatedNumber.js | 6 +- tgui/packages/tgui/components/Autofocus.tsx | 2 +- tgui/packages/tgui/components/Blink.js | 15 +- tgui/packages/tgui/components/BlockQuote.js | 11 +- tgui/packages/tgui/components/Box.tsx | 72 +- tgui/packages/tgui/components/Button.js | 80 +- tgui/packages/tgui/components/ByondUi.js | 37 +- tgui/packages/tgui/components/Chart.js | 13 +- tgui/packages/tgui/components/Collapsible.js | 20 +- tgui/packages/tgui/components/ColorBox.js | 19 +- tgui/packages/tgui/components/Dimmer.js | 13 +- tgui/packages/tgui/components/Divider.js | 14 +- .../tgui/components/DraggableControl.js | 118 +- tgui/packages/tgui/components/Dropdown.js | 33 +- tgui/packages/tgui/components/Flex.tsx | 26 +- tgui/packages/tgui/components/Grid.js | 11 +- tgui/packages/tgui/components/Icon.js | 47 +- .../packages/tgui/components/InfinitePlane.js | 98 +- tgui/packages/tgui/components/Input.js | 46 +- tgui/packages/tgui/components/KeyListener.tsx | 14 +- tgui/packages/tgui/components/Knob.js | 60 +- .../tgui/components/LabeledControls.js | 40 +- tgui/packages/tgui/components/LabeledList.tsx | 39 +- tgui/packages/tgui/components/Modal.js | 15 +- tgui/packages/tgui/components/NanoMap.js | 126 +- tgui/packages/tgui/components/NoticeBox.js | 15 +- tgui/packages/tgui/components/NumberInput.js | 102 +- tgui/packages/tgui/components/Popper.tsx | 13 +- tgui/packages/tgui/components/ProgressBar.js | 26 +- .../tgui/components/RestrictedInput.js | 7 +- tgui/packages/tgui/components/RoundGauge.js | 87 +- tgui/packages/tgui/components/Section.tsx | 20 +- tgui/packages/tgui/components/Slider.js | 66 +- tgui/packages/tgui/components/Stack.tsx | 29 +- tgui/packages/tgui/components/Table.js | 50 +- tgui/packages/tgui/components/Tabs.js | 53 +- tgui/packages/tgui/components/TextArea.js | 40 +- tgui/packages/tgui/components/TimeDisplay.js | 8 +- tgui/packages/tgui/components/Tooltip.tsx | 27 +- .../tgui/components/TrackOutsideClicks.tsx | 14 +- tgui/packages/tgui/constants.js | 147 +-- tgui/packages/tgui/debug/KitchenSink.js | 22 +- tgui/packages/tgui/debug/hooks.js | 2 +- tgui/packages/tgui/debug/middleware.js | 29 +- tgui/packages/tgui/debug/selectors.js | 2 +- tgui/packages/tgui/drag.js | 99 +- tgui/packages/tgui/events.js | 39 +- tgui/packages/tgui/format.js | 79 +- tgui/packages/tgui/hotkeys.ts | 14 +- tgui/packages/tgui/http.ts | 21 +- tgui/packages/tgui/index.js | 7 +- tgui/packages/tgui/interfaces/AICard.js | 86 +- tgui/packages/tgui/interfaces/APC.js | 167 ++- .../tgui/interfaces/AccountsTerminal.js | 145 +- .../tgui/interfaces/AdminShuttleController.js | 47 +- tgui/packages/tgui/interfaces/AgentCard.js | 36 +- tgui/packages/tgui/interfaces/AiAirlock.js | 107 +- tgui/packages/tgui/interfaces/AiRestorer.js | 55 +- .../packages/tgui/interfaces/AiSupermatter.js | 42 +- tgui/packages/tgui/interfaces/AirAlarm.js | 168 +-- tgui/packages/tgui/interfaces/AlertModal.tsx | 36 +- tgui/packages/tgui/interfaces/AlgaeFarm.js | 63 +- .../tgui/interfaces/AppearanceChanger.js | 228 ++-- tgui/packages/tgui/interfaces/ArcadeBattle.js | 32 +- .../tgui/interfaces/AreaScrubberControl.js | 81 +- .../tgui/interfaces/AssemblyInfrared.js | 27 +- tgui/packages/tgui/interfaces/AssemblyProx.js | 45 +- .../packages/tgui/interfaces/AssemblyTimer.js | 31 +- .../tgui/interfaces/AtmosAlertConsole.js | 27 +- tgui/packages/tgui/interfaces/AtmosControl.js | 46 +- tgui/packages/tgui/interfaces/AtmosFilter.js | 41 +- tgui/packages/tgui/interfaces/AtmosMixer.js | 48 +- tgui/packages/tgui/interfaces/Autolathe.js | 88 +- tgui/packages/tgui/interfaces/Batteryrack.js | 74 +- .../packages/tgui/interfaces/BeaconLocator.js | 47 +- tgui/packages/tgui/interfaces/Biogenerator.js | 113 +- tgui/packages/tgui/interfaces/BodyDesigner.js | 243 ++-- tgui/packages/tgui/interfaces/BodyScanner.js | 398 +++--- tgui/packages/tgui/interfaces/BombTester.js | 101 +- tgui/packages/tgui/interfaces/BotanyEditor.js | 58 +- .../tgui/interfaces/BotanyIsolator.js | 97 +- tgui/packages/tgui/interfaces/BrigTimer.js | 40 +- .../packages/tgui/interfaces/CameraConsole.js | 75 +- tgui/packages/tgui/interfaces/Canister.js | 99 +- tgui/packages/tgui/interfaces/Canvas.js | 36 +- .../tgui/interfaces/CasinoPrizeDispenser.js | 101 +- .../tgui/interfaces/CharacterDirectory.js | 141 +- .../packages/tgui/interfaces/ChemDispenser.js | 110 +- tgui/packages/tgui/interfaces/ChemMaster.js | 431 +++--- tgui/packages/tgui/interfaces/ClawMachine.js | 56 +- tgui/packages/tgui/interfaces/Cleanbot.js | 92 +- .../tgui/interfaces/CloningConsole.js | 276 ++-- tgui/packages/tgui/interfaces/ColorMate.js | 43 +- .../tgui/interfaces/CommunicationsConsole.js | 182 ++- tgui/packages/tgui/interfaces/Communicator.js | 701 ++++------ .../tgui/interfaces/ComputerFabricator.js | 282 ++-- .../tgui/interfaces/CookingAppliance.js | 43 +- tgui/packages/tgui/interfaces/CrewManifest.js | 73 +- tgui/packages/tgui/interfaces/CrewMonitor.js | 135 +- tgui/packages/tgui/interfaces/Cryo.js | 134 +- tgui/packages/tgui/interfaces/CryoStorage.js | 72 +- .../packages/tgui/interfaces/CryoStorageVr.js | 38 +- tgui/packages/tgui/interfaces/DNAForensics.js | 57 +- tgui/packages/tgui/interfaces/DNAModifier.js | 394 +++--- .../tgui/interfaces/DestinationTagger.js | 18 +- .../tgui/interfaces/DiseaseSplicer.js | 107 +- .../packages/tgui/interfaces/DishIncubator.js | 90 +- tgui/packages/tgui/interfaces/DisposalBin.js | 55 +- tgui/packages/tgui/interfaces/DroneConsole.js | 69 +- .../tgui/interfaces/EmbeddedController.js | 364 ++--- tgui/packages/tgui/interfaces/ExonetNode.js | 45 +- .../tgui/interfaces/ExosuitFabricator.js | 650 +++------ tgui/packages/tgui/interfaces/Farmbot.js | 64 +- tgui/packages/tgui/interfaces/Fax.js | 70 +- tgui/packages/tgui/interfaces/FileCabinet.js | 19 +- tgui/packages/tgui/interfaces/Floorbot.js | 77 +- tgui/packages/tgui/interfaces/GasPump.js | 53 +- .../tgui/interfaces/GasTemperatureSystem.js | 34 +- .../tgui/interfaces/GeneralAtmoControl.js | 185 +-- .../tgui/interfaces/GeneralRecords.js | 148 +-- tgui/packages/tgui/interfaces/Gps.js | 84 +- .../tgui/interfaces/GravityGenerator.js | 44 +- tgui/packages/tgui/interfaces/GuestPass.js | 83 +- .../tgui/interfaces/GyrotronControl.js | 66 +- tgui/packages/tgui/interfaces/Holodeck.js | 38 +- tgui/packages/tgui/interfaces/ICAssembly.js | 55 +- tgui/packages/tgui/interfaces/ICCircuit.js | 104 +- tgui/packages/tgui/interfaces/ICDetailer.js | 34 +- tgui/packages/tgui/interfaces/ICPrinter.js | 55 +- tgui/packages/tgui/interfaces/IDCard.js | 59 +- .../tgui/interfaces/IdentificationComputer.js | 105 +- .../tgui/interfaces/InventoryPanel.js | 46 +- .../tgui/interfaces/InventoryPanelHuman.js | 107 +- .../tgui/interfaces/IsolationCentrifuge.js | 50 +- tgui/packages/tgui/interfaces/JanitorCart.js | 87 +- tgui/packages/tgui/interfaces/Jukebox.js | 130 +- tgui/packages/tgui/interfaces/LawManager.js | 219 ++- .../tgui/interfaces/ListInputModal.tsx | 39 +- tgui/packages/tgui/interfaces/LookingGlass.js | 36 +- .../tgui/interfaces/MechaControlConsole.js | 163 ++- tgui/packages/tgui/interfaces/Medbot.js | 87 +- .../tgui/interfaces/MedicalRecords.js | 259 ++-- .../tgui/interfaces/MessageMonitor.js | 330 ++--- tgui/packages/tgui/interfaces/Microwave.js | 109 +- .../interfaces/MiningOreProcessingConsole.js | 186 ++- .../tgui/interfaces/MiningStackingConsole.js | 36 +- tgui/packages/tgui/interfaces/MiningVendor.js | 95 +- tgui/packages/tgui/interfaces/MuleBot.js | 127 +- tgui/packages/tgui/interfaces/NIF.js | 180 ++- tgui/packages/tgui/interfaces/NTNetRelay.js | 59 +- tgui/packages/tgui/interfaces/Newscaster.js | 477 +++---- tgui/packages/tgui/interfaces/NoticeBoard.js | 42 +- .../tgui/interfaces/NtosAccessDecrypter.js | 89 +- tgui/packages/tgui/interfaces/NtosArcade.js | 45 +- .../tgui/interfaces/NtosAtmosControl.js | 7 +- .../tgui/interfaces/NtosCameraConsole.js | 7 +- .../interfaces/NtosCommunicationsConsole.js | 8 +- .../tgui/interfaces/NtosConfiguration.js | 59 +- .../tgui/interfaces/NtosCrewMonitor.js | 7 +- .../tgui/interfaces/NtosDigitalWarrant.js | 147 +-- .../interfaces/NtosEmailAdministration.js | 104 +- .../tgui/interfaces/NtosEmailClient.js | 328 ++--- .../tgui/interfaces/NtosFileManager.js | 149 +-- .../interfaces/NtosIdentificationComputer.js | 6 +- tgui/packages/tgui/interfaces/NtosMain.js | 71 +- tgui/packages/tgui/interfaces/NtosNetChat.js | 139 +- tgui/packages/tgui/interfaces/NtosNetDos.js | 66 +- .../tgui/interfaces/NtosNetDownloader.js | 86 +- .../tgui/interfaces/NtosNetMonitor.js | 129 +- .../tgui/interfaces/NtosNetTransfer.js | 146 +- .../tgui/interfaces/NtosNewsBrowser.js | 118 +- .../tgui/interfaces/NtosOvermapNavigation.js | 5 +- .../tgui/interfaces/NtosPowerMonitor.js | 5 +- tgui/packages/tgui/interfaces/NtosRCON.js | 5 +- .../tgui/interfaces/NtosRevelation.js | 32 +- .../tgui/interfaces/NtosShutoffMonitor.js | 11 +- .../interfaces/NtosStationAlertConsole.js | 5 +- .../tgui/interfaces/NtosSupermatterMonitor.js | 7 +- tgui/packages/tgui/interfaces/NtosUAV.js | 79 +- .../tgui/interfaces/NtosWordProcessor.js | 139 +- .../tgui/interfaces/NumberInputModal.tsx | 11 +- tgui/packages/tgui/interfaces/OmniFilter.js | 141 +- tgui/packages/tgui/interfaces/OmniMixer.js | 135 +- .../tgui/interfaces/OperatingComputer.js | 133 +- .../tgui/interfaces/OvermapDisperser.js | 83 +- .../tgui/interfaces/OvermapEngines.js | 78 +- tgui/packages/tgui/interfaces/OvermapFull.js | 18 +- tgui/packages/tgui/interfaces/OvermapHelm.js | 123 +- .../tgui/interfaces/OvermapNavigation.js | 39 +- .../tgui/interfaces/OvermapShieldGenerator.js | 172 ++- .../tgui/interfaces/OvermapShipSensors.js | 97 +- .../tgui/interfaces/ParticleAccelerator.js | 40 +- tgui/packages/tgui/interfaces/PartsLathe.js | 106 +- .../tgui/interfaces/PathogenicIsolator.js | 209 ++- tgui/packages/tgui/interfaces/Pda.js | 103 +- .../tgui/interfaces/PersonalCrafting.js | 91 +- tgui/packages/tgui/interfaces/Photocopier.js | 73 +- .../packages/tgui/interfaces/PipeDispenser.js | 58 +- .../packages/tgui/interfaces/PlantAnalyzer.js | 78 +- tgui/packages/tgui/interfaces/PlayerNotes.js | 54 +- .../tgui/interfaces/PlayerNotesInfo.js | 38 +- .../tgui/interfaces/PointDefenseControl.js | 60 +- .../tgui/interfaces/PortableGenerator.js | 53 +- tgui/packages/tgui/interfaces/PortablePump.js | 56 +- .../tgui/interfaces/PortableScrubber.js | 13 +- .../tgui/interfaces/PortableTurret.js | 36 +- tgui/packages/tgui/interfaces/PowerMonitor.js | 191 +-- .../tgui/interfaces/PressureRegulator.js | 54 +- .../tgui/interfaces/PrisonerManagement.js | 69 +- tgui/packages/tgui/interfaces/RCON.js | 201 +-- tgui/packages/tgui/interfaces/RIGSuit.js | 279 ++-- tgui/packages/tgui/interfaces/Radio.js | 107 +- .../tgui/interfaces/RapidPipeDispenser.js | 126 +- .../tgui/interfaces/RequestConsole.js | 232 ++-- .../tgui/interfaces/ResearchConsole.js | 805 +++++------- .../interfaces/ResearchServerController.js | 183 ++- .../tgui/interfaces/ResleevingConsole.js | 406 ++---- .../packages/tgui/interfaces/ResleevingPod.js | 86 +- .../tgui/interfaces/RoboticsControlConsole.js | 98 +- tgui/packages/tgui/interfaces/RogueZones.js | 73 +- .../tgui/interfaces/RustCoreMonitor.js | 72 +- .../tgui/interfaces/RustFuelControl.js | 42 +- tgui/packages/tgui/interfaces/Secbot.js | 72 +- tgui/packages/tgui/interfaces/SecureSafe.js | 56 +- .../tgui/interfaces/SecurityRecords.js | 167 +-- tgui/packages/tgui/interfaces/SeedStorage.js | 33 +- .../tgui/interfaces/ShieldCapacitor.js | 42 +- .../tgui/interfaces/ShieldGenerator.js | 97 +- .../tgui/interfaces/ShutoffMonitor.js | 49 +- .../tgui/interfaces/ShuttleControl.js | 389 +++--- tgui/packages/tgui/interfaces/Signaler.js | 54 +- tgui/packages/tgui/interfaces/Sleeper.js | 181 +-- tgui/packages/tgui/interfaces/SmartVend.js | 66 +- tgui/packages/tgui/interfaces/Smes.js | 134 +- tgui/packages/tgui/interfaces/SolarControl.js | 46 +- tgui/packages/tgui/interfaces/SpaceHeater.js | 34 +- tgui/packages/tgui/interfaces/Stack.js | 99 +- .../tgui/interfaces/StationAlertConsole.js | 45 +- .../tgui/interfaces/StationBlueprints.js | 13 +- .../packages/tgui/interfaces/StockExchange.js | 232 ++-- tgui/packages/tgui/interfaces/SuitCycler.js | 123 +- .../tgui/interfaces/SuitStorageUnit.js | 200 ++- .../tgui/interfaces/SupermatterMonitor.js | 73 +- .../packages/tgui/interfaces/SupplyConsole.js | 357 +++-- tgui/packages/tgui/interfaces/TEGenerator.js | 86 +- tgui/packages/tgui/interfaces/Tank.js | 66 +- .../packages/tgui/interfaces/TankDispenser.js | 19 +- .../tgui/interfaces/TelecommsLogBrowser.js | 201 +-- .../interfaces/TelecommsMachineBrowser.js | 97 +- .../tgui/interfaces/TelecommsMultitoolMenu.js | 123 +- tgui/packages/tgui/interfaces/Teleporter.js | 44 +- .../tgui/interfaces/TelesciConsole.js | 82 +- .../tgui/interfaces/TextInputModal.tsx | 34 +- tgui/packages/tgui/interfaces/TimeClock.js | 126 +- .../packages/tgui/interfaces/TransferValve.js | 50 +- .../tgui/interfaces/TurbineControl.js | 66 +- tgui/packages/tgui/interfaces/Turbolift.js | 58 +- tgui/packages/tgui/interfaces/Uplink.js | 267 ++-- tgui/packages/tgui/interfaces/Vending.js | 110 +- tgui/packages/tgui/interfaces/VolumePanel.js | 20 +- tgui/packages/tgui/interfaces/VorePanel.js | 992 +++++++------- tgui/packages/tgui/interfaces/Wires.js | 52 +- .../interfaces/XenoarchArtifactAnalyzer.js | 28 +- .../interfaces/XenoarchArtifactHarvester.js | 123 +- .../tgui/interfaces/XenoarchDepthScanner.js | 94 +- .../XenoarchHandheldPowerUtilizer.js | 61 +- .../tgui/interfaces/XenoarchReplicator.js | 13 +- .../tgui/interfaces/XenoarchSpectrometer.js | 100 +- .../tgui/interfaces/XenoarchSuspension.js | 53 +- .../tgui/interfaces/common/AtmosControls.js | 166 +-- .../tgui/interfaces/common/BeakerContents.js | 23 +- .../tgui/interfaces/common/ComplexModal.js | 60 +- .../interfaces/common/FullscreenNotice.js | 5 +- .../tgui/interfaces/common/InputButtons.tsx | 18 +- .../common/InterfaceLockNoticeBox.js | 10 +- .../tgui/interfaces/common/Loader.tsx | 6 +- .../tgui/interfaces/common/LoginInfo.js | 5 +- .../tgui/interfaces/common/LoginScreen.js | 44 +- .../packages/tgui/interfaces/common/Mining.js | 17 +- .../tgui/interfaces/common/Overmap.js | 83 +- .../tgui/interfaces/common/PortableAtmos.js | 46 +- .../tgui/interfaces/common/RankIcon.js | 15 +- .../tgui/interfaces/common/TemporaryNotice.js | 13 +- tgui/packages/tgui/interfaces/pAIAtmos.js | 32 +- .../packages/tgui/interfaces/pAIDirectives.js | 49 +- tgui/packages/tgui/interfaces/pAIDoorjack.js | 57 +- tgui/packages/tgui/interfaces/pAIInterface.js | 33 +- .../packages/tgui/interfaces/pAIMedrecords.js | 72 +- .../packages/tgui/interfaces/pAISecrecords.js | 68 +- .../tgui/interfaces/pda/pda_atmos_scan.js | 30 +- .../tgui/interfaces/pda/pda_janitor.js | 44 +- .../tgui/interfaces/pda/pda_main_menu.js | 44 +- .../tgui/interfaces/pda/pda_manifest.js | 4 +- .../tgui/interfaces/pda/pda_medical.js | 103 +- .../tgui/interfaces/pda/pda_messenger.js | 193 +-- tgui/packages/tgui/interfaces/pda/pda_news.js | 97 +- .../tgui/interfaces/pda/pda_notekeeper.js | 17 +- .../packages/tgui/interfaces/pda/pda_power.js | 4 +- .../tgui/interfaces/pda/pda_security.js | 89 +- .../tgui/interfaces/pda/pda_status_display.js | 30 +- .../tgui/interfaces/pda/pda_supply.js | 60 +- tgui/packages/tgui/layouts/Layout.js | 30 +- tgui/packages/tgui/layouts/NtosWindow.js | 51 +- tgui/packages/tgui/layouts/Pane.js | 41 +- tgui/packages/tgui/layouts/Window.js | 120 +- tgui/packages/tgui/links.js | 5 +- tgui/packages/tgui/logging.js | 30 +- tgui/packages/tgui/public/tgui.bundle.js | 35 - tgui/packages/tgui/renderer.ts | 75 +- tgui/packages/tgui/routes.js | 25 +- tgui/packages/tgui/store.js | 36 +- tgui/packages/tgui/stories/Blink.stories.js | 4 +- tgui/packages/tgui/stories/Box.stories.js | 32 +- tgui/packages/tgui/stories/Button.stories.js | 36 +- tgui/packages/tgui/stories/ByondUi.stories.js | 47 +- .../tgui/stories/Collapsible.stories.js | 6 +- tgui/packages/tgui/stories/Flex.stories.js | 52 +- tgui/packages/tgui/stories/Input.stories.js | 41 +- tgui/packages/tgui/stories/Popper.stories.js | 70 +- .../tgui/stories/ProgressBar.stories.js | 13 +- tgui/packages/tgui/stories/Storage.stories.js | 18 +- tgui/packages/tgui/stories/Tabs.stories.js | 98 +- tgui/packages/tgui/stories/Themes.stories.js | 5 +- tgui/packages/tgui/stories/Tooltip.stories.js | 18 +- tgui/packages/tgui/stories/common.js | 10 +- .../tgui/styles/atomic/debug-layout.scss | 8 +- tgui/packages/tgui/styles/atomic/links.scss | 6 +- tgui/packages/tgui/styles/base.scss | 6 +- tgui/packages/tgui/styles/colors.scss | 18 +- .../tgui/styles/components/Button.scss | 16 +- .../tgui/styles/components/Dropdown.scss | 2 +- .../packages/tgui/styles/components/Icon.scss | 1 - .../packages/tgui/styles/components/Knob.scss | 4 +- .../tgui/styles/components/LabeledList.scss | 2 +- .../tgui/styles/components/NoticeBox.scss | 18 +- .../tgui/styles/components/RoundGauge.scss | 16 +- .../tgui/styles/components/Section.scss | 2 +- tgui/packages/tgui/styles/functions.scss | 30 +- .../tgui/styles/interfaces/CrewManifest.scss | 2 +- .../tgui/styles/interfaces/IDCard.scss | 2 +- .../tgui/styles/interfaces/InputModal.scss | 29 +- .../tgui/styles/interfaces/ListInput.scss | 29 +- .../tgui/styles/interfaces/NuclearBomb.scss | 8 +- .../packages/tgui/styles/interfaces/Safe.scss | 12 +- .../styles/interfaces/TinderMessaging.scss | 11 +- .../tgui/styles/interfaces/Turbolift.scss | 7 +- tgui/packages/tgui/styles/layouts/Layout.scss | 30 +- .../tgui/styles/layouts/TitleBar.scss | 2 +- tgui/packages/tgui/styles/layouts/Window.scss | 4 +- tgui/packages/tgui/styles/reset.scss | 17 +- .../packages/tgui/styles/themes/abductor.scss | 41 +- .../packages/tgui/styles/themes/abstract.scss | 2 +- .../tgui/styles/themes/cardtable.scss | 29 +- .../tgui/styles/themes/hackerman.scss | 21 +- .../tgui/styles/themes/malfunction.scss | 41 +- tgui/packages/tgui/styles/themes/neutral.scss | 56 +- tgui/packages/tgui/styles/themes/ntos.scss | 23 +- tgui/packages/tgui/styles/themes/paper.scss | 46 +- .../tgui/styles/themes/pda-retro.scss | 37 +- tgui/packages/tgui/styles/themes/retro.scss | 27 +- .../tgui/styles/themes/syndicate.scss | 41 +- tgui/packages/tgui/styles/themes/wizard.scss | 75 +- tgui/public/tgui.bundle.js | 2 +- tgui/webpack.config.js | 3 +- tgui/yarn.lock | 1169 ++++++++++++++++- 424 files changed, 14661 insertions(+), 20149 deletions(-) create mode 100644 tgui/.prettierignore create mode 100644 tgui/.yarn/sdks/prettier/index.js create mode 100644 tgui/.yarn/sdks/prettier/package.json delete mode 100644 tgui/packages/tgui/public/tgui.bundle.js diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 19a0ceb7dec..4b96db2f5a0 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -9,6 +9,7 @@ "dbaeumer.vscode-eslint", "editorconfig.editorconfig", "donkie.vscode-tgstation-test-adapter", - "icrawl.discord-vscode" + "icrawl.discord-vscode", + "esbenp.prettier-vscode" ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 64cfc2bb26d..5f92ba8db6b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,7 @@ { "eslint.nodePath": "./tgui/.yarn/sdks", - "eslint.workingDirectories": [ - "./tgui" - ], + "eslint.workingDirectories": ["./tgui"], + "prettier.prettierPath": "./tgui/.yarn/sdks/prettier/index.js", "typescript.tsdk": "./tgui/.yarn/sdks/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true, "search.exclude": { @@ -13,24 +12,38 @@ "*.dmi": "imagePreview.previewEditor" }, "files.eol": "\n", + "files.encoding": "utf8", + "files.associations": { + "*.{dme,dmf,dmm,dm}": "dm", + }, "gitlens.advanced.blame.customArguments": [ "-w" ], "tgstationTestExplorer.project.resultsType": "json", "[javascript]": { - "editor.rulers": [ - 120 - ] + "editor.rulers": [120], + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true + }, + "[javascriptreact]": { + "editor.rulers": [120], + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true }, "[typescript]": { - "editor.rulers": [ - 120 - ] + "editor.rulers": [120], + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true + }, + "[typescriptreact]": { + "editor.rulers": [120], + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true }, "[scss]": { - "editor.rulers": [ - 120 - ] + "editor.rulers": [120], + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true }, "tgstationTestExplorer.project.DMEName": "tgmc.dme" -} \ No newline at end of file +} diff --git a/tgui/.eslintrc.yml b/tgui/.eslintrc.yml index 31d1b345d47..7fd4b2914c1 100644 --- a/tgui/.eslintrc.yml +++ b/tgui/.eslintrc.yml @@ -1,4 +1,5 @@ root: true +extends: prettier parser: '@typescript-eslint/parser' parserOptions: ecmaVersion: 2020 @@ -349,15 +350,15 @@ rules: ## Enforce the location of arrow function bodies # implicit-arrow-linebreak: error ## Enforce consistent indentation - indent: [error, 2, { SwitchCase: 1 }] + # indent: [warn, 2, { SwitchCase: 1 }] ## Enforce the consistent use of either double or single quotes in JSX ## attributes - jsx-quotes: [error, prefer-double] + # jsx-quotes: [warn, prefer-double] ## Enforce consistent spacing between keys and values in object literal ## properties - key-spacing: [error, { beforeColon: false, afterColon: true }] + # key-spacing: [warn, { beforeColon: false, afterColon: true }] ## Enforce consistent spacing before and after keywords - keyword-spacing: [error, { before: true, after: true }] + # keyword-spacing: [warn, { before: true, after: true }] ## Enforce position of line comments # line-comment-position: error ## Enforce consistent linebreak style @@ -369,15 +370,15 @@ rules: ## Enforce a maximum depth that blocks can be nested # max-depth: error ## Enforce a maximum line length - max-len: [error, { - code: 120, - ## Ignore imports - ignorePattern: '^(import\s.+\sfrom\s|.*require\()', - ignoreUrls: true, - ignoreRegExpLiterals: true, - ignoreStrings: true, - ignoreTemplateLiterals: true, - }] + # max-len: [warn, { + # code: 120, + # ## Ignore imports + # ignorePattern: '^(import\s.+\sfrom\s|.*require\()', + # ignoreUrls: true, + # ignoreRegExpLiterals: true, + # ignoreStrings: true, + # ignoreTemplateLiterals: true, + # }] ## Enforce a maximum number of lines per file # max-lines: error ## Enforce a maximum number of line of code in a function @@ -414,7 +415,7 @@ rules: ## Disallow mixed binary operators # no-mixed-operators: error ## Disallow mixed spaces and tabs for indentation - no-mixed-spaces-and-tabs: error + no-mixed-spaces-and-tabs: warn ## Disallow use of chained assignment expressions # no-multi-assign: error ## Disallow multiple empty lines @@ -440,7 +441,7 @@ rules: ## Disallow ternary operators when simpler alternatives exist # no-unneeded-ternary: error ## Disallow whitespace before properties - no-whitespace-before-property: error + # no-whitespace-before-property: warn ## Enforce the location of single-line statements # nonblock-statement-body-position: error ## Enforce consistent line breaks inside braces @@ -457,7 +458,7 @@ rules: ## Require or disallow assignment operator shorthand where possible # operator-assignment: error ## Enforce consistent linebreak style for operators - operator-linebreak: [error, before] + # operator-linebreak: [warn, before] ## Require or disallow padding within blocks # padded-blocks: error ## Require or disallow padding lines between statements @@ -482,11 +483,11 @@ rules: ## Enforce consistent spacing before blocks space-before-blocks: [error, always] ## Enforce consistent spacing before function definition opening parenthesis - space-before-function-paren: [error, { - anonymous: always, - named: never, - asyncArrow: always, - }] + # space-before-function-paren: [warn, { + # anonymous: always, + # named: never, + # asyncArrow: always, + # }] ## Enforce consistent spacing inside parentheses space-in-parens: [error, never] ## Require spacing around infix operators @@ -695,7 +696,7 @@ rules: react/jsx-closing-tag-location: error ## Enforce or disallow newlines inside of curly braces in JSX attributes and ## expressions (fixable) - react/jsx-curly-newline: error + # react/jsx-curly-newline: warn ## Enforce or disallow spaces inside of curly braces in JSX attributes and ## expressions (fixable) react/jsx-curly-spacing: error @@ -708,13 +709,13 @@ rules: ## Enforce event handler naming conventions in JSX react/jsx-handler-names: error ## Validate JSX indentation (fixable) - react/jsx-indent: [error, 2, { - checkAttributes: true, - }] + # react/jsx-indent: [warn, 2, { + # checkAttributes: true, + # }] ## Validate props indentation in JSX (fixable) - react/jsx-indent-props: [error, 2] + # react/jsx-indent-props: [warn, 2] ## Validate JSX has key prop when in array or iterator - react/jsx-key: error + # react/jsx-key: warn ## Validate JSX maximum depth react/jsx-max-depth: [error, { max: 10 }] ## Generous ## Limit maximum of props on a single line in JSX (fixable) diff --git a/tgui/.prettierignore b/tgui/.prettierignore new file mode 100644 index 00000000000..2522dec056c --- /dev/null +++ b/tgui/.prettierignore @@ -0,0 +1,19 @@ +## NPM +/**/node_modules + +## Yarn +/.yarn +/yarn.lock +/.pnp.* + +/docs +/public +/packages/tgui-polyfill +/packages/tgfont/static +**/*.json +**/*.yml +**/*.md + +## Build artifacts +/public/.tmp/**/* +/public/*.map diff --git a/tgui/.prettierrc.yml b/tgui/.prettierrc.yml index b64bef0cd05..5dbf435cf14 100644 --- a/tgui/.prettierrc.yml +++ b/tgui/.prettierrc.yml @@ -1,8 +1,10 @@ arrowParens: always -bracketSpacing: true +breakLongMethodChains: true endOfLine: lf +importFormatting: oneline jsxBracketSameLine: true jsxSingleQuote: false +offsetTernaryExpressions: true printWidth: 120 proseWrap: preserve quoteProps: preserve @@ -10,3 +12,4 @@ semi: true singleQuote: true tabWidth: 2 trailingComma: es5 +useTabs: false diff --git a/tgui/.yarn/sdks/eslint/lib/api.js b/tgui/.yarn/sdks/eslint/lib/api.js index 97a052442a8..fc728d952bb 100644 --- a/tgui/.yarn/sdks/eslint/lib/api.js +++ b/tgui/.yarn/sdks/eslint/lib/api.js @@ -11,10 +11,10 @@ const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { - // Setup the environment to be able to require eslint/lib/api.js + // Setup the environment to be able to require eslint require(absPnpApiPath).setup(); } } -// Defer to the real eslint/lib/api.js your application uses -module.exports = absRequire(`eslint/lib/api.js`); +// Defer to the real eslint your application uses +module.exports = absRequire(`eslint`); diff --git a/tgui/.yarn/sdks/prettier/index.js b/tgui/.yarn/sdks/prettier/index.js new file mode 100644 index 00000000000..f6882d80972 --- /dev/null +++ b/tgui/.yarn/sdks/prettier/index.js @@ -0,0 +1,20 @@ +#!/usr/bin/env node + +const {existsSync} = require(`fs`); +const {createRequire, createRequireFromPath} = require(`module`); +const {resolve} = require(`path`); + +const relPnpApiPath = "../../../.pnp.cjs"; + +const absPnpApiPath = resolve(__dirname, relPnpApiPath); +const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); + +if (existsSync(absPnpApiPath)) { + if (!process.versions.pnp) { + // Setup the environment to be able to require prettier/index.js + require(absPnpApiPath).setup(); + } +} + +// Defer to the real prettier/index.js your application uses +module.exports = absRequire(`prettier/index.js`); diff --git a/tgui/.yarn/sdks/prettier/package.json b/tgui/.yarn/sdks/prettier/package.json new file mode 100644 index 00000000000..0cbd71ff32d --- /dev/null +++ b/tgui/.yarn/sdks/prettier/package.json @@ -0,0 +1,6 @@ +{ + "name": "prettier", + "version": "0.19.0-sdk", + "main": "./index.js", + "type": "commonjs" +} diff --git a/tgui/.yarn/sdks/typescript/lib/tsserver.js b/tgui/.yarn/sdks/typescript/lib/tsserver.js index 4d90f3879d0..9f9f4d6f469 100644 --- a/tgui/.yarn/sdks/typescript/lib/tsserver.js +++ b/tgui/.yarn/sdks/typescript/lib/tsserver.js @@ -18,6 +18,7 @@ const moduleWrapper = tsserver => { const pnpApi = require(`pnpapi`); const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); + const isPortal = str => str.startsWith("portal:/"); const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { @@ -30,7 +31,7 @@ const moduleWrapper = tsserver => { function toEditorPath(str) { // We add the `zip:` prefix to both `.zip/` paths and virtual paths - if (isAbsolute(str) && !str.match(/^\^zip:/) && (str.match(/\.zip\//) || isVirtual(str))) { + if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { // We also take the opportunity to turn virtual paths into physical ones; // this makes it much easier to work with workspaces that list peer // dependencies, since otherwise Ctrl+Click would bring us to the virtual @@ -44,7 +45,7 @@ const moduleWrapper = tsserver => { const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; if (resolved) { const locator = pnpApi.findPackageLocator(resolved); - if (locator && dependencyTreeRoots.has(`${locator.name}@${locator.reference}`)) { + if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { str = resolved; } } @@ -60,10 +61,34 @@ const moduleWrapper = tsserver => { // // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 // - case `vscode`: { + // 2021-10-08: VSCode changed the format in 1.61. + // Before | ^zip:/c:/foo/bar.zip/package.json + // After | ^/zip//c:/foo/bar.zip/package.json + // + // 2022-04-06: VSCode changed the format in 1.66. + // Before | ^/zip//c:/foo/bar.zip/package.json + // After | ^/zip/c:/foo/bar.zip/package.json + // + // 2022-05-06: VSCode changed the format in 1.68 + // Before | ^/zip/c:/foo/bar.zip/package.json + // After | ^/zip//c:/foo/bar.zip/package.json + // + case `vscode <1.61`: { str = `^zip:${str}`; } break; + case `vscode <1.66`: { + str = `^/zip/${str}`; + } break; + + case `vscode <1.68`: { + str = `^/zip${str}`; + } break; + + case `vscode`: { + str = `^/zip/${str}`; + } break; + // To make "go to definition" work, // We have to resolve the actual file system path from virtual path // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) @@ -77,7 +102,7 @@ const moduleWrapper = tsserver => { // everything else is up to neovim case `neovim`: { str = normalize(resolved).replace(/\.zip\//, `.zip::`); - str = `zipfile:${str}`; + str = `zipfile://${str}`; } break; default: { @@ -91,9 +116,28 @@ const moduleWrapper = tsserver => { } function fromEditorPath(str) { - return process.platform === `win32` - ? str.replace(/^\^?zip:\//, ``) - : str.replace(/^\^?zip:/, ``); + switch (hostInfo) { + case `coc-nvim`: { + str = str.replace(/\.zip::/, `.zip/`); + // The path for coc-nvim is in format of //zipfile://.yarn/... + // So in order to convert it back, we use .* to match all the thing + // before `zipfile:` + return process.platform === `win32` + ? str.replace(/^.*zipfile:\//, ``) + : str.replace(/^.*zipfile:/, ``); + } break; + + case `neovim`: { + str = str.replace(/\.zip::/, `.zip/`); + // The path for neovim is in format of zipfile:////.yarn/... + return str.replace(/^zipfile:\/\//, ``); + } break; + + case `vscode`: + default: { + return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`) + } break; + } } // Force enable 'allowLocalPluginLoads' @@ -119,8 +163,9 @@ const moduleWrapper = tsserver => { let hostInfo = `unknown`; Object.assign(Session.prototype, { - onMessage(/** @type {string} */ message) { - const parsedMessage = JSON.parse(message) + onMessage(/** @type {string | object} */ message) { + const isStringMessage = typeof message === 'string'; + const parsedMessage = isStringMessage ? JSON.parse(message) : message; if ( parsedMessage != null && @@ -129,11 +174,32 @@ const moduleWrapper = tsserver => { typeof parsedMessage.arguments.hostInfo === `string` ) { hostInfo = parsedMessage.arguments.hostInfo; + if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { + const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match( + // The RegExp from https://semver.org/ but without the caret at the start + /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ + ) ?? []).map(Number) + + if (major === 1) { + if (minor < 61) { + hostInfo += ` <1.61`; + } else if (minor < 66) { + hostInfo += ` <1.66`; + } else if (minor < 68) { + hostInfo += ` <1.68`; + } + } + } } - return originalOnMessage.call(this, JSON.stringify(parsedMessage, (key, value) => { - return typeof value === `string` ? fromEditorPath(value) : value; - })); + const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { + return typeof value === 'string' ? fromEditorPath(value) : value; + }); + + return originalOnMessage.call( + this, + isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) + ); }, send(/** @type {any} */ msg) { diff --git a/tgui/.yarn/sdks/typescript/lib/tsserverlibrary.js b/tgui/.yarn/sdks/typescript/lib/tsserverlibrary.js index c3de4ff5d70..878b11946a4 100644 --- a/tgui/.yarn/sdks/typescript/lib/tsserverlibrary.js +++ b/tgui/.yarn/sdks/typescript/lib/tsserverlibrary.js @@ -18,6 +18,7 @@ const moduleWrapper = tsserver => { const pnpApi = require(`pnpapi`); const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); + const isPortal = str => str.startsWith("portal:/"); const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { @@ -30,7 +31,7 @@ const moduleWrapper = tsserver => { function toEditorPath(str) { // We add the `zip:` prefix to both `.zip/` paths and virtual paths - if (isAbsolute(str) && !str.match(/^\^zip:/) && (str.match(/\.zip\//) || isVirtual(str))) { + if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { // We also take the opportunity to turn virtual paths into physical ones; // this makes it much easier to work with workspaces that list peer // dependencies, since otherwise Ctrl+Click would bring us to the virtual @@ -44,7 +45,7 @@ const moduleWrapper = tsserver => { const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; if (resolved) { const locator = pnpApi.findPackageLocator(resolved); - if (locator && dependencyTreeRoots.has(`${locator.name}@${locator.reference}`)) { + if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { str = resolved; } } @@ -60,10 +61,34 @@ const moduleWrapper = tsserver => { // // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 // - case `vscode`: { + // 2021-10-08: VSCode changed the format in 1.61. + // Before | ^zip:/c:/foo/bar.zip/package.json + // After | ^/zip//c:/foo/bar.zip/package.json + // + // 2022-04-06: VSCode changed the format in 1.66. + // Before | ^/zip//c:/foo/bar.zip/package.json + // After | ^/zip/c:/foo/bar.zip/package.json + // + // 2022-05-06: VSCode changed the format in 1.68 + // Before | ^/zip/c:/foo/bar.zip/package.json + // After | ^/zip//c:/foo/bar.zip/package.json + // + case `vscode <1.61`: { str = `^zip:${str}`; } break; + case `vscode <1.66`: { + str = `^/zip/${str}`; + } break; + + case `vscode <1.68`: { + str = `^/zip${str}`; + } break; + + case `vscode`: { + str = `^/zip/${str}`; + } break; + // To make "go to definition" work, // We have to resolve the actual file system path from virtual path // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) @@ -77,7 +102,7 @@ const moduleWrapper = tsserver => { // everything else is up to neovim case `neovim`: { str = normalize(resolved).replace(/\.zip\//, `.zip::`); - str = `zipfile:${str}`; + str = `zipfile://${str}`; } break; default: { @@ -91,9 +116,28 @@ const moduleWrapper = tsserver => { } function fromEditorPath(str) { - return process.platform === `win32` - ? str.replace(/^\^?zip:\//, ``) - : str.replace(/^\^?zip:/, ``); + switch (hostInfo) { + case `coc-nvim`: { + str = str.replace(/\.zip::/, `.zip/`); + // The path for coc-nvim is in format of //zipfile://.yarn/... + // So in order to convert it back, we use .* to match all the thing + // before `zipfile:` + return process.platform === `win32` + ? str.replace(/^.*zipfile:\//, ``) + : str.replace(/^.*zipfile:/, ``); + } break; + + case `neovim`: { + str = str.replace(/\.zip::/, `.zip/`); + // The path for neovim is in format of zipfile:////.yarn/... + return str.replace(/^zipfile:\/\//, ``); + } break; + + case `vscode`: + default: { + return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`) + } break; + } } // Force enable 'allowLocalPluginLoads' @@ -119,8 +163,9 @@ const moduleWrapper = tsserver => { let hostInfo = `unknown`; Object.assign(Session.prototype, { - onMessage(/** @type {string} */ message) { - const parsedMessage = JSON.parse(message) + onMessage(/** @type {string | object} */ message) { + const isStringMessage = typeof message === 'string'; + const parsedMessage = isStringMessage ? JSON.parse(message) : message; if ( parsedMessage != null && @@ -129,11 +174,32 @@ const moduleWrapper = tsserver => { typeof parsedMessage.arguments.hostInfo === `string` ) { hostInfo = parsedMessage.arguments.hostInfo; + if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { + const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match( + // The RegExp from https://semver.org/ but without the caret at the start + /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ + ) ?? []).map(Number) + + if (major === 1) { + if (minor < 61) { + hostInfo += ` <1.61`; + } else if (minor < 66) { + hostInfo += ` <1.66`; + } else if (minor < 68) { + hostInfo += ` <1.68`; + } + } + } } - return originalOnMessage.call(this, JSON.stringify(parsedMessage, (key, value) => { - return typeof value === `string` ? fromEditorPath(value) : value; - })); + const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { + return typeof value === 'string' ? fromEditorPath(value) : value; + }); + + return originalOnMessage.call( + this, + isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) + ); }, send(/** @type {any} */ msg) { diff --git a/tgui/babel.config.js b/tgui/babel.config.js index d8ddb75721d..e702c9a7119 100644 --- a/tgui/babel.config.js +++ b/tgui/babel.config.js @@ -4,8 +4,9 @@ * @license MIT */ -const createBabelConfig = options => { +const createBabelConfig = (options) => { const { presets = [], plugins = [], removeConsole } = options; + // prettier-ignore return { presets: [ [require.resolve('@babel/preset-typescript'), { @@ -34,7 +35,7 @@ const createBabelConfig = options => { }; }; -module.exports = api => { +module.exports = (api) => { api.cache(true); const mode = process.env.NODE_ENV; return createBabelConfig({ mode }); diff --git a/tgui/bin/tgui_.ps1 b/tgui/bin/tgui_.ps1 index a1909fe70ef..e6f378405fd 100644 --- a/tgui/bin/tgui_.ps1 +++ b/tgui/bin/tgui_.ps1 @@ -54,6 +54,10 @@ function task-bench { yarn tgui:bench @Args } +function task-prettier { + yarn tgui:prettier @Args +} + ## Run a linter through all packages function task-lint { yarn run tsc @@ -148,6 +152,7 @@ if ($Args.Length -gt 0) { ## Make a production webpack build if ($Args.Length -eq 0) { task-install + task-prettier task-lint task-webpack --mode=production exit 0 diff --git a/tgui/global.d.ts b/tgui/global.d.ts index 0f69e371539..348cb9c5165 100644 --- a/tgui/global.d.ts +++ b/tgui/global.d.ts @@ -27,12 +27,11 @@ type TguiMessage = { [key: string]: any; }; - type ByondType = { /** - * ID of the Byond window this script is running on. - * Can be used as a parameter to winget/winset. - */ + * ID of the Byond window this script is running on. + * Can be used as a parameter to winget/winset. + */ windowId: string; /** @@ -41,8 +40,8 @@ type ByondType = { IS_BYOND: boolean; /** - * Version of Trident engine of Internet Explorer. Null if N/A. - */ + * Version of Trident engine of Internet Explorer. Null if N/A. + */ TRIDENT: number | null; /** @@ -145,20 +144,20 @@ type ByondType = { parseJson(text: string): any; /** - * Sends a message to `/datum/tgui_window` which hosts this window instance. - */ + * Sends a message to `/datum/tgui_window` which hosts this window instance. + */ sendMessage(type: string, payload?: any): void; sendMessage(message: TguiMessage): void; /** - * Subscribe to incoming messages that were sent from `/datum/tgui_window`. - */ + * Subscribe to incoming messages that were sent from `/datum/tgui_window`. + */ subscribe(listener: (type: string, payload: any) => void): void; /** - * Subscribe to incoming messages *of some specific type* - * that were sent from `/datum/tgui_window`. - */ + * Subscribe to incoming messages *of some specific type* + * that were sent from `/datum/tgui_window`. + */ subscribeTo(type: string, listener: (payload: any) => void): void; /** diff --git a/tgui/jest.config.js b/tgui/jest.config.js index e654f0089b8..de06e1c229a 100644 --- a/tgui/jest.config.js +++ b/tgui/jest.config.js @@ -1,12 +1,7 @@ module.exports = { roots: ['/packages'], - testMatch: [ - '/packages/**/__tests__/*.{js,ts,tsx}', - '/packages/**/*.{spec,test}.{js,ts,tsx}', - ], - testPathIgnorePatterns: [ - '/packages/tgui-bench', - ], + testMatch: ['/packages/**/__tests__/*.{js,ts,tsx}', '/packages/**/*.{spec,test}.{js,ts,tsx}'], + testPathIgnorePatterns: ['/packages/tgui-bench'], testEnvironment: 'jsdom', testRunner: require.resolve('jest-circus/runner'), transform: { diff --git a/tgui/package.json b/tgui/package.json index 7fc6d67cd29..602af0324c0 100644 --- a/tgui/package.json +++ b/tgui/package.json @@ -7,16 +7,17 @@ "packages/*" ], "scripts": { - "tgui:build": "webpack", "tgui:analyze": "webpack --analyze", + "tgui:bench": "webpack --env TGUI_BENCH=1 && node packages/tgui-bench/index.js", + "tgui:build": "webpack", "tgui:dev": "node --experimental-modules packages/tgui-dev-server/index.js", "tgui:lint": "eslint packages --ext .js,.cjs,.ts,.tsx", + "tgui:prettier": "prettierx --check .", "tgui:sonar": "eslint packages --ext .js,.cjs,.ts,.tsx -c .eslintrc-harder.yml", - "tgui:tsc": "tsc", "tgui:test": "jest --watch", "tgui:test-simple": "CI=true jest --color", "tgui:test-ci": "CI=true jest --color --collect-coverage", - "tgui:bench": "webpack --env TGUI_BENCH=1 && node packages/tgui-bench/index.js" + "tgui:tsc": "tsc" }, "dependencies": { "@babel/core": "^7.18.0", @@ -38,6 +39,7 @@ "common": "workspace:*", "css-loader": "^6.7.1", "eslint": "^8.16.0", + "eslint-config-prettier": "^8.5.0", "eslint-plugin-radar": "^0.2.1", "eslint-plugin-react": "^7.30.0", "eslint-plugin-unused-imports": "^2.0.0", @@ -48,6 +50,7 @@ "jest-environment-jsdom": "^28.1.0", "jsdom": "^19.0.0", "mini-css-extract-plugin": "^2.6.0", + "prettier": "npm:prettierx@0.19.0", "sass": "^1.52.1", "sass-loader": "^13.0.0", "style-loader": "^3.3.1", diff --git a/tgui/packages/common/collections.spec.ts b/tgui/packages/common/collections.spec.ts index 58eff7f354c..ef35a95cb3e 100644 --- a/tgui/packages/common/collections.spec.ts +++ b/tgui/packages/common/collections.spec.ts @@ -1,20 +1,20 @@ -import { range, zip } from "./collections"; +import { range, zip } from './collections'; // Type assertions, these will lint if the types are wrong. -const _zip1: [string, number] = zip(["a"], [1])[0]; +const _zip1: [string, number] = zip(['a'], [1])[0]; -describe("range", () => { - test("range(0, 5)", () => { +describe('range', () => { + test('range(0, 5)', () => { expect(range(0, 5)).toEqual([0, 1, 2, 3, 4]); }); }); -describe("zip", () => { +describe('zip', () => { test("zip(['a', 'b', 'c'], [1, 2, 3, 4])", () => { - expect(zip(["a", "b", "c"], [1, 2, 3, 4])).toEqual([ - ["a", 1], - ["b", 2], - ["c", 3], + expect(zip(['a', 'b', 'c'], [1, 2, 3, 4])).toEqual([ + ['a', 1], + ['b', 2], + ['c', 3], ]); }); }); diff --git a/tgui/packages/common/collections.ts b/tgui/packages/common/collections.ts index f0a8bfeba31..623d534a3fb 100644 --- a/tgui/packages/common/collections.ts +++ b/tgui/packages/common/collections.ts @@ -14,40 +14,31 @@ * * @returns {any[]} */ -export const filter = (iterateeFn: ( - input: T, - index: number, - collection: T[], -) => boolean) => - (collection: T[]): T[] => { - if (collection === null || collection === undefined) { - return collection; - } - if (Array.isArray(collection)) { - const result: T[] = []; - for (let i = 0; i < collection.length; i++) { - const item = collection[i]; - if (iterateeFn(item, i, collection)) { - result.push(item); - } +export const filter = + (iterateeFn: (input: T, index: number, collection: T[]) => boolean) => + (collection: T[]): T[] => { + if (collection === null || collection === undefined) { + return collection; + } + if (Array.isArray(collection)) { + const result: T[] = []; + for (let i = 0; i < collection.length; i++) { + const item = collection[i]; + if (iterateeFn(item, i, collection)) { + result.push(item); } - return result; } - throw new Error(`filter() can't iterate on type ${typeof collection}`); - }; + return result; + } + throw new Error(`filter() can't iterate on type ${typeof collection}`); + }; type MapFunction = { - (iterateeFn: ( - value: T, - index: number, - collection: T[], - ) => U): (collection: T[]) => U[]; + (iterateeFn: (value: T, index: number, collection: T[]) => U): (collection: T[]) => U[]; - (iterateeFn: ( - value: T, - index: K, - collection: Record, - ) => U): (collection: Record) => U[]; + (iterateeFn: (value: T, index: K, collection: Record) => U): ( + collection: Record + ) => U[]; }; /** @@ -58,7 +49,8 @@ type MapFunction = { * If collection is 'null' or 'undefined', it will be returned "as is" * without emitting any errors (which can be useful in some cases). */ -export const map: MapFunction = (iterateeFn) => +export const map: MapFunction = + (iterateeFn) => (collection: T[]): U[] => { if (collection === null || collection === undefined) { return collection; @@ -102,22 +94,22 @@ const COMPARATOR = (objA, objB) => { * * @returns {any[]} */ -export const sortBy = ( - ...iterateeFns: ((input: T) => unknown)[] -) => (array: T[]): T[] => { +export const sortBy = + (...iterateeFns: ((input: T) => unknown)[]) => + (array: T[]): T[] => { if (!Array.isArray(array)) { return array; } let length = array.length; // Iterate over the array to collect criteria to sort it by let mappedArray: { - criteria: unknown[], - value: T, + criteria: unknown[]; + value: T; }[] = []; for (let i = 0; i < length; i++) { const value = array[i]; mappedArray.push({ - criteria: iterateeFns.map(fn => fn(value)), + criteria: iterateeFns.map((fn) => fn(value)), value, }); } @@ -144,15 +136,14 @@ export const range = (start: number, end: number): number[] => /** * A fast implementation of reduce. */ -export const reduce = (reducerFn, initialValue) => array => { +export const reduce = (reducerFn, initialValue) => (array) => { const length = array.length; let i; let result; if (initialValue === undefined) { i = 1; result = array[0]; - } - else { + } else { i = 0; result = initialValue; } @@ -173,15 +164,14 @@ export const reduce = (reducerFn, initialValue) => array => { * is determined by the order they occur in the array. The iteratee is * invoked with one argument: value. */ -export const uniqBy = ( - iterateeFn?: (value: T) => unknown -) => (array: T[]): T[] => { +export const uniqBy = + (iterateeFn?: (value: T) => unknown) => + (array: T[]): T[] => { const { length } = array; const result: T[] = []; const seen: unknown[] = iterateeFn ? [] : result; let index = -1; - outer: - while (++index < length) { + outer: while (++index < length) { let value: T | 0 = array[index]; const computed = iterateeFn ? iterateeFn(value) : value; if (computed === computed) { @@ -195,8 +185,7 @@ export const uniqBy = ( seen.push(computed); } result.push(value); - } - else if (!seen.includes(computed)) { + } else if (!seen.includes(computed)) { if (seen !== result) { seen.push(computed); } @@ -242,7 +231,8 @@ export const zip = (...arrays: T): Zip => { * specify how grouped values should be combined. The iteratee is * invoked with the elements of each group. */ -export const zipWith = (iterateeFn: (...values: T[]) => U) => +export const zipWith = + (iterateeFn: (...values: T[]) => U) => (...arrays: T[][]): U[] => { return map((values: T[]) => iterateeFn(...values))(zip(...arrays)); }; diff --git a/tgui/packages/common/color.js b/tgui/packages/common/color.js index 510579bc266..21727424767 100644 --- a/tgui/packages/common/color.js +++ b/tgui/packages/common/color.js @@ -22,23 +22,14 @@ export class Color { /** * Creates a color from the CSS hex color notation. */ -Color.fromHex = hex => ( - new Color( - parseInt(hex.substr(1, 2), 16), - parseInt(hex.substr(3, 2), 16), - parseInt(hex.substr(5, 2), 16)) -); +Color.fromHex = (hex) => + new Color(parseInt(hex.substr(1, 2), 16), parseInt(hex.substr(3, 2), 16), parseInt(hex.substr(5, 2), 16)); /** * Linear interpolation of two colors. */ -Color.lerp = (c1, c2, n) => ( - new Color( - (c2.r - c1.r) * n + c1.r, - (c2.g - c1.g) * n + c1.g, - (c2.b - c1.b) * n + c1.b, - (c2.a - c1.a) * n + c1.a) -); +Color.lerp = (c1, c2, n) => + new Color((c2.r - c1.r) * n + c1.r, (c2.g - c1.g) * n + c1.g, (c2.b - c1.b) * n + c1.b, (c2.a - c1.a) * n + c1.a); /** * Loops up the color in the provided list of colors diff --git a/tgui/packages/common/events.js b/tgui/packages/common/events.js index 6d590a34453..7eeff511aa5 100644 --- a/tgui/packages/common/events.js +++ b/tgui/packages/common/events.js @@ -19,10 +19,9 @@ export class EventEmitter { if (!listeners) { throw new Error(`There is no listeners for "${name}"`); } - this.listeners[name] = listeners - .filter(existingListener => { - return existingListener !== listener; - }); + this.listeners[name] = listeners.filter((existingListener) => { + return existingListener !== listener; + }); } emit(name, ...params) { diff --git a/tgui/packages/common/fp.js b/tgui/packages/common/fp.js index 7aa00a00f3e..990c7c53c51 100644 --- a/tgui/packages/common/fp.js +++ b/tgui/packages/common/fp.js @@ -9,19 +9,20 @@ * functions, where each successive invocation is supplied the return * value of the previous. */ -export const flow = (...funcs) => (input, ...rest) => { - let output = input; - for (let func of funcs) { - // Recurse into the array of functions - if (Array.isArray(func)) { - output = flow(...func)(output, ...rest); +export const flow = + (...funcs) => + (input, ...rest) => { + let output = input; + for (let func of funcs) { + // Recurse into the array of functions + if (Array.isArray(func)) { + output = flow(...func)(output, ...rest); + } else if (func) { + output = func(output, ...rest); + } } - else if (func) { - output = func(output, ...rest); - } - } - return output; -}; + return output; + }; /** * Composes single-argument functions from right to left. @@ -37,11 +38,14 @@ export const flow = (...funcs) => (input, ...rest) => { */ export const compose = (...funcs) => { if (funcs.length === 0) { - return arg => arg; + return (arg) => arg; } if (funcs.length === 1) { return funcs[0]; } - return funcs.reduce((a, b) => (value, ...rest) => - a(b(value, ...rest), ...rest)); + return funcs.reduce( + (a, b) => + (value, ...rest) => + a(b(value, ...rest), ...rest) + ); }; diff --git a/tgui/packages/common/math.ts b/tgui/packages/common/math.ts index 97e6b60b2ed..9dc1d655693 100644 --- a/tgui/packages/common/math.ts +++ b/tgui/packages/common/math.ts @@ -14,7 +14,7 @@ export const clamp = (value, min, max) => { /** * Limits a number between 0 and 1. */ -export const clamp01 = value => { +export const clamp01 = (value) => { return value < 0 ? 0 : value > 1 ? 1 : value; }; @@ -69,9 +69,7 @@ export const toFixed = (value, fractionDigits = 0) => { * Range is an array of two numbers, for example: [0, 15]. */ export const inRange = (value, range) => { - return range - && value >= range[0] - && value <= range[1]; + return range && value >= range[0] && value <= range[1]; }; /** @@ -92,7 +90,7 @@ export const keyOfMatchingRange = (value, ranges) => { /** * Get number of digits following the decimal point in a number */ -export const numberOfDecimalDigits = value => { +export const numberOfDecimalDigits = (value) => { if (Math.floor(value) !== value) { return value.toString().split('.')[1].length || 0; } diff --git a/tgui/packages/common/perf.js b/tgui/packages/common/perf.js index 8414971f93b..5b9e377f7cb 100644 --- a/tgui/packages/common/perf.js +++ b/tgui/packages/common/perf.js @@ -48,10 +48,9 @@ const measure = (markerNameA, markerNameB) => { } }; -const formatDuration = duration => { +const formatDuration = (duration) => { const durationInFrames = duration / FRAME_DURATION; - return duration.toFixed(duration < 10 ? 1 : 0) + 'ms ' - + '(' + durationInFrames.toFixed(2) + ' frames)'; + return duration.toFixed(duration < 10 ? 1 : 0) + 'ms ' + '(' + durationInFrames.toFixed(2) + ' frames)'; }; export const perf = { diff --git a/tgui/packages/common/react.ts b/tgui/packages/common/react.ts index c8a08f04934..6789bb4edc6 100644 --- a/tgui/packages/common/react.ts +++ b/tgui/packages/common/react.ts @@ -24,7 +24,7 @@ export const classes = (classNames: (string | BooleanLike)[]) => { */ export const normalizeChildren = (children: T | T[]) => { if (Array.isArray(children)) { - return children.flat().filter(value => value) as T[]; + return children.flat().filter((value) => value) as T[]; } if (typeof children === 'object') { return [children]; @@ -64,9 +64,7 @@ export const pureComponentHooks = { * A helper to determine whether the object is renderable by React. */ export const canRender = (value: unknown) => { - return value !== undefined - && value !== null - && typeof value !== 'boolean'; + return value !== undefined && value !== null && typeof value !== 'boolean'; }; /** diff --git a/tgui/packages/common/redux.js b/tgui/packages/common/redux.js index ebed11f166b..8718dccc0cd 100644 --- a/tgui/packages/common/redux.js +++ b/tgui/packages/common/redux.js @@ -20,11 +20,11 @@ export const createStore = (reducer, enhancer) => { const getState = () => currentState; - const subscribe = listener => { + const subscribe = (listener) => { listeners.push(listener); }; - const dispatch = action => { + const dispatch = (action) => { currentState = reducer(currentState, action); for (let i = 0; i < listeners.length; i++) { listeners[i](); @@ -49,27 +49,27 @@ export const createStore = (reducer, enhancer) => { * actions. */ export const applyMiddleware = (...middlewares) => { - return createStore => (reducer, ...args) => { - const store = createStore(reducer, ...args); + return (createStore) => + (reducer, ...args) => { + const store = createStore(reducer, ...args); - let dispatch = () => { - throw new Error( - 'Dispatching while constructing your middleware is not allowed.'); + let dispatch = () => { + throw new Error('Dispatching while constructing your middleware is not allowed.'); + }; + + const storeApi = { + getState: store.getState, + dispatch: (action, ...args) => dispatch(action, ...args), + }; + + const chain = middlewares.map((middleware) => middleware(storeApi)); + dispatch = compose(...chain)(store.dispatch); + + return { + ...store, + dispatch, + }; }; - - const storeApi = { - getState: store.getState, - dispatch: (action, ...args) => dispatch(action, ...args), - }; - - const chain = middlewares.map(middleware => middleware(storeApi)); - dispatch = compose(...chain)(store.dispatch); - - return { - ...store, - dispatch, - }; - }; }; /** @@ -80,7 +80,7 @@ export const applyMiddleware = (...middlewares) => { * in the state that are not present in the reducers object. This function * is also more flexible than the redux counterpart. */ -export const combineReducers = reducersObj => { +export const combineReducers = (reducersObj) => { const keys = Object.keys(reducersObj); let hasChanged = false; return (prevState = {}, action) => { @@ -94,9 +94,7 @@ export const combineReducers = reducersObj => { nextState[key] = nextDomainState; } } - return hasChanged - ? nextState - : prevState; + return hasChanged ? nextState : prevState; }; }; @@ -136,15 +134,14 @@ export const createAction = (type, prepare = null) => { }; actionCreator.toString = () => '' + type; actionCreator.type = type; - actionCreator.match = action => action.type === type; + actionCreator.match = (action) => action.type === type; return actionCreator; }; - // Implementation specific // -------------------------------------------------------- -export const useDispatch = context => { +export const useDispatch = (context) => { return context.store.dispatch; }; diff --git a/tgui/packages/common/storage.js b/tgui/packages/common/storage.js index 83dc6d99c1c..5d9da981322 100644 --- a/tgui/packages/common/storage.js +++ b/tgui/packages/common/storage.js @@ -17,11 +17,10 @@ const INDEXED_DB_STORE_NAME = 'storage-v1'; const READ_ONLY = 'readonly'; const READ_WRITE = 'readwrite'; -const testGeneric = testFn => () => { +const testGeneric = (testFn) => () => { try { return Boolean(testFn()); - } - catch { + } catch { return false; } }; @@ -29,14 +28,11 @@ const testGeneric = testFn => () => { // Localstorage can sometimes throw an error, even if DOM storage is not // disabled in IE11 settings. // See: https://superuser.com/questions/1080011 -const testLocalStorage = testGeneric(() => ( - window.localStorage && window.localStorage.getItem -)); +const testLocalStorage = testGeneric(() => window.localStorage && window.localStorage.getItem); -const testIndexedDb = testGeneric(() => ( - (window.indexedDB || window.msIndexedDB) - && (window.IDBTransaction || window.msIDBTransaction) -)); +const testIndexedDb = testGeneric( + () => (window.indexedDB || window.msIndexedDB) && (window.IDBTransaction || window.msIDBTransaction) +); class MemoryBackend { constructor() { @@ -96,8 +92,7 @@ class IndexedDbBackend { req.onupgradeneeded = () => { try { req.result.createObjectStore(INDEXED_DB_STORE_NAME); - } - catch (err) { + } catch (err) { reject(new Error('Failed to upgrade IDB: ' + req.error)); } }; @@ -109,9 +104,7 @@ class IndexedDbBackend { } getStore(mode) { - return this.dbPromise.then(db => db - .transaction(INDEXED_DB_STORE_NAME, mode) - .objectStore(INDEXED_DB_STORE_NAME)); + return this.dbPromise.then((db) => db.transaction(INDEXED_DB_STORE_NAME, mode).objectStore(INDEXED_DB_STORE_NAME)); } async get(key) { @@ -161,8 +154,7 @@ class StorageProxy { const backend = new IndexedDbBackend(); await backend.dbPromise; return backend; - } - catch {} + } catch {} } if (testLocalStorage()) { return new LocalStorageBackend(); diff --git a/tgui/packages/common/string.babel-plugin.cjs b/tgui/packages/common/string.babel-plugin.cjs index 68295aefcf8..97ca67c6ea4 100644 --- a/tgui/packages/common/string.babel-plugin.cjs +++ b/tgui/packages/common/string.babel-plugin.cjs @@ -19,7 +19,7 @@ /** * Removes excess whitespace and indentation from the string. */ -const multiline = str => { +const multiline = (str) => { const lines = str.split('\n'); // Determine base indentation let minIndent; @@ -40,15 +40,15 @@ const multiline = str => { // Remove this base indentation and trim the resulting string // from both ends. return lines - .map(line => line.substr(minIndent).trimRight()) + .map((line) => line.substr(minIndent).trimRight()) .join('\n') .trim(); }; -const StringPlugin = ref => { +const StringPlugin = (ref) => { return { visitor: { - TaggedTemplateExpression: path => { + TaggedTemplateExpression: (path) => { if (path.node.tag.name === 'multiline') { const { quasi } = path.node; if (quasi.expressions.length > 0) { diff --git a/tgui/packages/common/string.js b/tgui/packages/common/string.js index 4278a1fb3e0..d80caf8da1e 100644 --- a/tgui/packages/common/string.js +++ b/tgui/packages/common/string.js @@ -7,7 +7,7 @@ /** * Removes excess whitespace and indentation from the string. */ -export const multiline = str => { +export const multiline = (str) => { if (Array.isArray(str)) { // Small stub to allow usage as a template tag return multiline(str.join('')); @@ -32,7 +32,7 @@ export const multiline = str => { // Remove this base indentation and trim the resulting string // from both ends. return lines - .map(line => line.substr(minIndent).trimRight()) + .map((line) => line.substr(minIndent).trimRight()) .join('\n') .trim(); }; @@ -44,12 +44,17 @@ export const multiline = str => { * * Example: createGlobPattern('*@domain')('user@domain') === true */ -export const createGlobPattern = pattern => { - const escapeString = str => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); - const regex = new RegExp('^' - + pattern.split(/\*+/).map(escapeString).join('.*') - + '$'); - return str => regex.test(str); +export const createGlobPattern = (pattern) => { + const escapeString = (str) => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); + const regex = new RegExp( + '^' + + pattern + .split(/\*+/) + .map(escapeString) + .join('.*') + + '$' + ); + return (str) => regex.test(str); }; /** @@ -64,7 +69,7 @@ export const createGlobPattern = pattern => { */ export const createSearch = (searchText, stringifier) => { const preparedSearchText = searchText.toLowerCase().trim(); - return obj => { + return (obj) => { if (!preparedSearchText) { return true; } @@ -72,17 +77,15 @@ export const createSearch = (searchText, stringifier) => { if (!str) { return false; } - return str - .toLowerCase() - .includes(preparedSearchText); + return str.toLowerCase().includes(preparedSearchText); }; }; -export const isUppercase = chr => { +export const isUppercase = (chr) => { return chr.toUpperCase() === chr; }; -export const capitalize = str => { +export const capitalize = (str) => { // Handle array if (Array.isArray(str)) { return str.map(capitalize); @@ -95,7 +98,7 @@ export const capitalize = str => { return chr.toUpperCase() + str.slice(1).toLowerCase(); }; -export const toTitleCase = str => { +export const toTitleCase = (str) => { // Handle array if (Array.isArray(str)) { return str.map(toTitleCase); @@ -107,19 +110,38 @@ export const toTitleCase = str => { // Handle string const WORDS_UPPER = ['Id', 'Tv', 'Rcd']; // VOREStation Edit const WORDS_LOWER = [ - 'A', 'An', 'And', 'As', 'At', 'But', 'By', 'For', 'For', 'From', 'In', - 'Into', 'Near', 'Nor', 'Of', 'On', 'Onto', 'Or', 'The', 'To', 'With', + 'A', + 'An', + 'And', + 'As', + 'At', + 'But', + 'By', + 'For', + 'For', + 'From', + 'In', + 'Into', + 'Near', + 'Nor', + 'Of', + 'On', + 'Onto', + 'Or', + 'The', + 'To', + 'With', ]; - let currentStr = str.replace(/([^\W_]+[^\s-]*) */g, str => { + let currentStr = str.replace(/([^\W_]+[^\s-]*) */g, (str) => { return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase(); }); for (let word of WORDS_LOWER) { const regex = new RegExp('\\s' + word + '\\s', 'g'); - currentStr = currentStr.replace(regex, str => str.toLowerCase()); + currentStr = currentStr.replace(regex, (str) => str.toLowerCase()); } for (let word of WORDS_UPPER) { const regex = new RegExp('\\b' + word + '\\b', 'g'); - currentStr = currentStr.replace(regex, str => str.toUpperCase()); + currentStr = currentStr.replace(regex, (str) => str.toUpperCase()); } return currentStr; }; @@ -130,7 +152,7 @@ export const toTitleCase = str => { * @param {String} str Encoded HTML string * @return {String} Decoded HTML string */ -export const decodeHtmlEntities = str => { +export const decodeHtmlEntities = (str) => { if (!str) { return str; } @@ -142,31 +164,33 @@ export const decodeHtmlEntities = str => { quot: '"', lt: '<', gt: '>', - apos: '\'', + apos: "'", trade: 'â„¢', }; - return str - // Newline tags - .replace(/
/gi, '\n') - .replace(/<\/?[a-z0-9-_]+[^>]*>/gi, '') - // Basic entities - .replace(translate_re, (match, entity) => translate[entity]) - // Decimal entities - .replace(/&#?([0-9]+);/gi, (match, numStr) => { - const num = parseInt(numStr, 10); - return String.fromCharCode(num); - }) - // Hex entities - .replace(/&#x?([0-9a-f]+);/gi, (match, numStr) => { - const num = parseInt(numStr, 16); - return String.fromCharCode(num); - }); + return ( + str + // Newline tags + .replace(/
/gi, '\n') + .replace(/<\/?[a-z0-9-_]+[^>]*>/gi, '') + // Basic entities + .replace(translate_re, (match, entity) => translate[entity]) + // Decimal entities + .replace(/&#?([0-9]+);/gi, (match, numStr) => { + const num = parseInt(numStr, 10); + return String.fromCharCode(num); + }) + // Hex entities + .replace(/&#x?([0-9a-f]+);/gi, (match, numStr) => { + const num = parseInt(numStr, 16); + return String.fromCharCode(num); + }) + ); }; /** * Converts an object into a query string, */ -export const buildQueryString = obj => Object.keys(obj) - .map(key => encodeURIComponent(key) - + '=' + encodeURIComponent(obj[key])) - .join('&'); +export const buildQueryString = (obj) => + Object.keys(obj) + .map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])) + .join('&'); diff --git a/tgui/packages/common/timer.js b/tgui/packages/common/timer.js index 1177071b9c6..4f42c37e4a0 100644 --- a/tgui/packages/common/timer.js +++ b/tgui/packages/common/timer.js @@ -33,6 +33,4 @@ export const debounce = (fn, time, immediate = false) => { * * @param {number} time */ -export const sleep = time => ( - new Promise(resolve => setTimeout(resolve, time)) -); +export const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time)); diff --git a/tgui/packages/common/types.ts b/tgui/packages/common/types.ts index a92ac122d9f..aab2213da78 100644 --- a/tgui/packages/common/types.ts +++ b/tgui/packages/common/types.ts @@ -1,5 +1,4 @@ /** * Returns the arguments of a function F as an array. */ -export type ArgumentsOf - = F extends (...args: infer A) => unknown ? A : never; +export type ArgumentsOf = F extends (...args: infer A) => unknown ? A : never; diff --git a/tgui/packages/common/uuid.js b/tgui/packages/common/uuid.js index 7721af64949..f2eb4bb98f4 100644 --- a/tgui/packages/common/uuid.js +++ b/tgui/packages/common/uuid.js @@ -11,9 +11,9 @@ */ export const createUuid = () => { let d = new Date().getTime(); - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); - return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); + return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16); }); }; diff --git a/tgui/packages/common/vector.js b/tgui/packages/common/vector.js index c3ac350a4e8..b1f85f7429d 100644 --- a/tgui/packages/common/vector.js +++ b/tgui/packages/common/vector.js @@ -32,17 +32,17 @@ export const vecDivide = (...vecs) => { }; export const vecScale = (vec, n) => { - return map(x => x * n)(vec); + return map((x) => x * n)(vec); }; -export const vecInverse = vec => { - return map(x => -x)(vec); +export const vecInverse = (vec) => { + return map((x) => -x)(vec); }; -export const vecLength = vec => { +export const vecLength = (vec) => { return Math.sqrt(reduce(ADD)(zipWith(MUL)(vec, vec))); }; -export const vecNormalize = vec => { +export const vecNormalize = (vec) => { return vecDivide(vec, vecLength(vec)); }; diff --git a/tgui/packages/tgfont/dist/tgfont.css b/tgui/packages/tgfont/dist/tgfont.css index ad732b8fc06..24f875594b8 100644 --- a/tgui/packages/tgfont/dist/tgfont.css +++ b/tgui/packages/tgfont/dist/tgfont.css @@ -1,50 +1,51 @@ @font-face { - font-family: "tgfont"; - src: url("./tgfont.woff2?45c3c7acc69dd413375d77898d24e41e") format("woff2"), -url("./tgfont.eot?45c3c7acc69dd413375d77898d24e41e#iefix") format("embedded-opentype"); + font-family: 'tgfont'; + src: url('./tgfont.woff2?45c3c7acc69dd413375d77898d24e41e') format('woff2'), + url('./tgfont.eot?45c3c7acc69dd413375d77898d24e41e#iefix') format('embedded-opentype'); } -i[class^="tg-"]:before, i[class*=" tg-"]:before { - font-family: tgfont !important; - font-style: normal; - font-weight: normal !important; - font-variant: normal; - text-transform: none; - line-height: 1; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; +i[class^='tg-']:before, +i[class*=' tg-']:before { + font-family: tgfont !important; + font-style: normal; + font-weight: normal !important; + font-variant: normal; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } .tg-air-tank-slash:before { - content: "\f101"; + content: '\f101'; } .tg-air-tank:before { - content: "\f102"; + content: '\f102'; } .tg-bad-touch:before { - content: "\f103"; + content: '\f103'; } .tg-image-minus:before { - content: "\f104"; + content: '\f104'; } .tg-image-plus:before { - content: "\f105"; + content: '\f105'; } .tg-nanotrasen-logo:before { - content: "\f106"; + content: '\f106'; } .tg-non-binary:before { - content: "\f107"; + content: '\f107'; } .tg-prosthetic-leg:before { - content: "\f108"; + content: '\f108'; } .tg-sound-minus:before { - content: "\f109"; + content: '\f109'; } .tg-sound-plus:before { - content: "\f10a"; + content: '\f10a'; } .tg-syndicate-logo:before { - content: "\f10b"; + content: '\f10b'; } diff --git a/tgui/packages/tgfont/icons/ATTRIBUTIONS.md b/tgui/packages/tgfont/icons/ATTRIBUTIONS.md index 2f218388d36..0491b90e726 100644 --- a/tgui/packages/tgfont/icons/ATTRIBUTIONS.md +++ b/tgui/packages/tgfont/icons/ATTRIBUTIONS.md @@ -1,6 +1,8 @@ bad-touch.svg contains: + - hug by Phạm Thanh Lộc from the Noun Project - Fight by Rudez Studio from the Noun Project prosthetic-leg.svg contains: + - prosthetic leg by Gan Khoon Lay from the Noun Project diff --git a/tgui/packages/tgfont/mkdist.cjs b/tgui/packages/tgfont/mkdist.cjs index 5c628becf99..85634bd265d 100644 --- a/tgui/packages/tgfont/mkdist.cjs +++ b/tgui/packages/tgfont/mkdist.cjs @@ -10,5 +10,4 @@ process.chdir(__dirname); // Silently make a dist folder try { require('fs').mkdirSync('dist'); -} -catch (err) {} +} catch (err) {} diff --git a/tgui/packages/tgui-bench/entrypoint.tsx b/tgui/packages/tgui-bench/entrypoint.tsx index d41d667894a..a6eb7a91d6d 100644 --- a/tgui/packages/tgui-bench/entrypoint.tsx +++ b/tgui/packages/tgui-bench/entrypoint.tsx @@ -62,8 +62,7 @@ const setupApp = async () => { } suite.run(); }); - } - catch (error) { + } catch (error) { sendMessage({ type: 'error', error }); } } diff --git a/tgui/packages/tgui-bench/index.js b/tgui/packages/tgui-bench/index.js index e29ad9a5c20..b10e0a3e0b6 100644 --- a/tgui/packages/tgui-bench/index.js +++ b/tgui/packages/tgui-bench/index.js @@ -27,8 +27,7 @@ const setup = async () => { assets += `\n`; const publicDir = path.resolve(__dirname, '../../public'); - const page = fs.readFileSync(path.join(publicDir, 'tgui.html'), 'utf-8') - .replace('\n', assets); + const page = fs.readFileSync(path.join(publicDir, 'tgui.html'), 'utf-8').replace('\n', assets); server.register(require('@fastify/static'), { root: publicDir, @@ -67,8 +66,7 @@ const setup = async () => { try { await server.listen(3002, '0.0.0.0'); - } - catch (err) { + } catch (err) { console.error(err); process.exit(1); } diff --git a/tgui/packages/tgui-bench/lib/benchmark.d.ts b/tgui/packages/tgui-bench/lib/benchmark.d.ts index 7f3310005f7..6ddad41fd82 100644 --- a/tgui/packages/tgui-bench/lib/benchmark.d.ts +++ b/tgui/packages/tgui-bench/lib/benchmark.d.ts @@ -11,11 +11,7 @@ declare class Benchmark { static filter(arr: T[], filter: string, thisArg?: any): T[]; static formatNumber(num: number): string; static join(obj: Object, separator1?: string, separator2?: string): string; - static invoke( - benches: Benchmark[], - name: string | Object, - ...args: any[] - ): any[]; + static invoke(benches: Benchmark[], name: string | Object, ...args: any[]): any[]; static runInContext(context: Object): Function; static each(obj: Object | any[], callback: Function, thisArg?: any): void; @@ -24,11 +20,7 @@ declare class Benchmark { static has(obj: Object, path: any[] | string): boolean; static indexOf(arr: T[], value: T, fromIndex?: number): number; static map(arr: T[], callback: (value: T) => K, thisArg?: any): K[]; - static reduce( - arr: T[], - callback: (accumulator: K, value: T) => K, - thisArg?: any - ): K; + static reduce(arr: T[], callback: (accumulator: K, value: T) => K, thisArg?: any): K; static options: Benchmark.Options; static platform: Benchmark.Platform; diff --git a/tgui/packages/tgui-bench/lib/benchmark.js b/tgui/packages/tgui-bench/lib/benchmark.js index 1e76cec7087..1e4b8aa760a 100644 --- a/tgui/packages/tgui-bench/lib/benchmark.js +++ b/tgui/packages/tgui-bench/lib/benchmark.js @@ -7,7 +7,7 @@ * Manually stripped from useless junk by /tg/station13 maintainers. * Available under MIT license */ -module.exports = (function() { +module.exports = function () { 'use strict'; /** Used as a safe reference for `undefined` in pre ES5 environments. */ @@ -16,7 +16,7 @@ module.exports = (function() { /** Used to determine if values are of the language type Object. */ var objectTypes = { 'function': true, - 'object': true + 'object': true, }; /** Used as a reference to the global object. */ @@ -36,9 +36,24 @@ module.exports = (function() { /** Used to assign default `context` object properties. */ var contextProps = [ - 'Array', 'Date', 'Function', 'Math', 'Object', 'RegExp', 'String', '_', - 'clearTimeout', 'chrome', 'chromium', 'document', 'navigator', 'phantom', - 'platform', 'process', 'runtime', 'setTimeout' + 'Array', + 'Date', + 'Function', + 'Math', + 'Object', + 'RegExp', + 'String', + '_', + 'clearTimeout', + 'chrome', + 'chromium', + 'document', + 'navigator', + 'phantom', + 'platform', + 'process', + 'runtime', + 'setTimeout', ]; /** Used to avoid hz of Infinity. */ @@ -47,7 +62,7 @@ module.exports = (function() { '2': 512, '3': 64, '4': 8, - '5': 0 + '5': 0, }; /** @@ -55,12 +70,37 @@ module.exports = (function() { * For more info see http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm. */ var tTable = { - '1': 12.706, '2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447, - '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179, - '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101, - '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064, - '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042, - 'infinity': 1.96 + '1': 12.706, + '2': 4.303, + '3': 3.182, + '4': 2.776, + '5': 2.571, + '6': 2.447, + '7': 2.365, + '8': 2.306, + '9': 2.262, + '10': 2.228, + '11': 2.201, + '12': 2.179, + '13': 2.16, + '14': 2.145, + '15': 2.131, + '16': 2.12, + '17': 2.11, + '18': 2.101, + '19': 2.093, + '20': 2.086, + '21': 2.08, + '22': 2.074, + '23': 2.069, + '24': 2.064, + '25': 2.06, + '26': 2.056, + '27': 2.052, + '28': 2.048, + '29': 2.045, + '30': 2.042, + 'infinity': 1.96, }; /** @@ -68,11 +108,11 @@ module.exports = (function() { * For more info see http://www.saburchill.com/IBbiology/stats/003.html. */ var uTable = { - '5': [0, 1, 2], - '6': [1, 2, 3, 5], - '7': [1, 3, 5, 6, 8], - '8': [2, 4, 6, 8, 10, 13], - '9': [2, 4, 7, 10, 12, 15, 17], + '5': [0, 1, 2], + '6': [1, 2, 3, 5], + '7': [1, 3, 5, 6, 8], + '8': [2, 4, 6, 8, 10, 13], + '9': [2, 4, 7, 10, 12, 15, 17], '10': [3, 5, 8, 11, 14, 17, 20, 23], '11': [3, 6, 9, 13, 16, 19, 23, 26, 30], '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37], @@ -89,11 +129,24 @@ module.exports = (function() { '23': [9, 17, 24, 32, 40, 48, 56, 64, 73, 81, 89, 98, 106, 115, 123, 132, 140, 149, 157, 166, 175], '24': [10, 17, 25, 33, 42, 50, 59, 67, 76, 85, 94, 102, 111, 120, 129, 138, 147, 156, 165, 174, 183, 192], '25': [10, 18, 27, 35, 44, 53, 62, 71, 80, 89, 98, 107, 117, 126, 135, 145, 154, 163, 173, 182, 192, 201, 211], - '26': [11, 19, 28, 37, 46, 55, 64, 74, 83, 93, 102, 112, 122, 132, 141, 151, 161, 171, 181, 191, 200, 210, 220, 230], - '27': [11, 20, 29, 38, 48, 57, 67, 77, 87, 97, 107, 118, 125, 138, 147, 158, 168, 178, 188, 199, 209, 219, 230, 240, 250], - '28': [12, 21, 30, 40, 50, 60, 70, 80, 90, 101, 111, 122, 132, 143, 154, 164, 175, 186, 196, 207, 218, 228, 239, 250, 261, 272], - '29': [13, 22, 32, 42, 52, 62, 73, 83, 94, 105, 116, 127, 138, 149, 160, 171, 182, 193, 204, 215, 226, 238, 249, 260, 271, 282, 294], - '30': [13, 23, 33, 43, 54, 65, 76, 87, 98, 109, 120, 131, 143, 154, 166, 177, 189, 200, 212, 223, 235, 247, 258, 270, 282, 293, 305, 317] + '26': [ + 11, 19, 28, 37, 46, 55, 64, 74, 83, 93, 102, 112, 122, 132, 141, 151, 161, 171, 181, 191, 200, 210, 220, 230, + ], + '27': [ + 11, 20, 29, 38, 48, 57, 67, 77, 87, 97, 107, 118, 125, 138, 147, 158, 168, 178, 188, 199, 209, 219, 230, 240, 250, + ], + '28': [ + 12, 21, 30, 40, 50, 60, 70, 80, 90, 101, 111, 122, 132, 143, 154, 164, 175, 186, 196, 207, 218, 228, 239, 250, + 261, 272, + ], + '29': [ + 13, 22, 32, 42, 52, 62, 73, 83, 94, 105, 116, 127, 138, 149, 160, 171, 182, 193, 204, 215, 226, 238, 249, 260, + 271, 282, 294, + ], + '30': [ + 13, 23, 33, 43, 54, 65, 76, 87, 98, 109, 120, 131, 143, 154, 166, 177, 189, 200, 212, 223, 235, 247, 258, 270, + 282, 293, 305, 317, + ], }; /*--------------------------------------------------------------------------*/ @@ -108,7 +161,7 @@ module.exports = (function() { */ function runInContext(context) { // Exit early if unable to acquire lodash. - var _ = context && context._ || require('lodash') || root._; + var _ = (context && context._) || require('lodash') || root._; if (!_) { Benchmark.runInContext = runInContext; return Benchmark; @@ -121,32 +174,32 @@ module.exports = (function() { /** Native constructor references. */ var Array = context.Array, - Date = context.Date, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String; + Date = context.Date, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String; /** Used for `Array` and `Object` method references. */ var arrayRef = [], - objectProto = Object.prototype; + objectProto = Object.prototype; /** Native method shortcuts. */ var abs = Math.abs, - clearTimeout = context.clearTimeout, - floor = Math.floor, - log = Math.log, - max = Math.max, - min = Math.min, - pow = Math.pow, - push = arrayRef.push, - setTimeout = context.setTimeout, - shift = arrayRef.shift, - slice = arrayRef.slice, - sqrt = Math.sqrt, - toString = objectProto.toString, - unshift = arrayRef.unshift; + clearTimeout = context.clearTimeout, + floor = Math.floor, + log = Math.log, + max = Math.max, + min = Math.min, + pow = Math.pow, + push = arrayRef.push, + setTimeout = context.setTimeout, + shift = arrayRef.shift, + slice = arrayRef.slice, + sqrt = Math.sqrt, + toString = objectProto.toString, + unshift = arrayRef.unshift; /** Detect DOM document object. */ var doc = isHostType(context, 'document') && context.document; @@ -172,8 +225,7 @@ module.exports = (function() { */ var support = {}; - (function() { - + (function () { /** * Detect if running in a browser environment. * @@ -202,15 +254,22 @@ module.exports = (function() { // See http://webk.it/11609 for more details. // Firefox 3.6 and Opera 9.25 strip grouping parentheses from `Function#toString` results. // See http://bugzil.la/559438 for more details. - support.decompilation = Function( - ('return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')') - // Avoid issues with code added by Istanbul. - .replace(/__cov__[^;]+;/g, '') - )()(0).x === '1'; - } catch(e) { + support.decompilation = + Function( + ( + 'return (' + + function (x) { + return { 'x': '' + (1 + x) + '', 'y': 0 }; + } + + ')' + ) + // Avoid issues with code added by Istanbul. + .replace(/__cov__[^;]+;/g, '') + )()(0).x === '1'; + } catch (e) { support.decompilation = false; } - }()); + })(); /** * Timer object used by `clock()` and `Deferred#resolve`. @@ -219,7 +278,6 @@ module.exports = (function() { * @type Object */ var timer = { - /** * The timer namespace object or constructor. * @@ -245,7 +303,7 @@ module.exports = (function() { * @memberOf timer * @param {Object} deferred The deferred instance. */ - 'stop': null // Lazy defined in `clock()`. + 'stop': null, // Lazy defined in `clock()`. }; /*------------------------------------------------------------------------*/ @@ -342,19 +400,16 @@ module.exports = (function() { if (_.isPlainObject(name)) { // 1 argument (options). options = name; - } - else if (_.isFunction(name)) { + } else if (_.isFunction(name)) { // 2 arguments (fn, options). options = fn; fn = name; - } - else if (_.isPlainObject(fn)) { + } else if (_.isPlainObject(fn)) { // 2 arguments (name, options). options = fn; fn = null; bench.name = name; - } - else { + } else { // 3 arguments (name, fn [, options]). bench.name = name; } @@ -395,7 +450,7 @@ module.exports = (function() { if (type instanceof Event) { return type; } - return (event instanceof Event) + return event instanceof Event ? _.assign(event, { 'timeStamp': _.now() }, typeof type == 'string' ? { 'type': type } : type) : new Event(type); } @@ -470,11 +525,9 @@ module.exports = (function() { * @param {*} value The value to clone. * @returns {*} The cloned value. */ - var cloneDeep = _.partial(_.cloneDeepWith, _, function(value) { + var cloneDeep = _.partial(_.cloneDeepWith, _, function (value) { // Only clone primitives, arrays, and plain objects. - return (_.isObject(value) && !_.isArray(value) && !_.isPlainObject(value)) - ? value - : undefined; + return _.isObject(value) && !_.isArray(value) && !_.isPlainObject(value) ? value : undefined; }); /** @@ -487,10 +540,10 @@ module.exports = (function() { */ function createFunction() { // Lazy define. - createFunction = function(args, body) { + createFunction = function (args, body) { var result, - anchor = freeDefine ? freeDefine.amd : Benchmark, - prop = uid + 'createFunction'; + anchor = freeDefine ? freeDefine.amd : Benchmark, + prop = uid + 'createFunction'; runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); result = anchor[prop]; @@ -499,7 +552,8 @@ module.exports = (function() { }; // Fix JaegerMonkey bug. // For more information see http://bugzil.la/639720. - createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function; + createFunction = + support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function; return createFunction.apply(null, arguments); } @@ -533,8 +587,7 @@ module.exports = (function() { * @returns {string} The argument name. */ function getFirstArgument(fn) { - return (!_.has(fn, 'toString') && - (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || ''; + return (!_.has(fn, 'toString') && (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || ''; } /** @@ -545,9 +598,11 @@ module.exports = (function() { * @returns {number} The mean. */ function getMean(sample) { - return (_.reduce(sample, function(sum, x) { - return sum + x; - }) / sample.length) || 0; + return ( + _.reduce(sample, function (sum, x) { + return sum + x; + }) / sample.length || 0 + ); } /** @@ -569,9 +624,7 @@ module.exports = (function() { result = (result || '').replace(/^\s+|\s+$/g, ''); // Detect strings containing only the "use strict" directive. - return /^(?:\/\*+[\w\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result) - ? '' - : result; + return /^(?:\/\*+[\w\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result) ? '' : result; } /** @@ -623,11 +676,11 @@ module.exports = (function() { */ function runScript(code) { var anchor = freeDefine ? define.amd : Benchmark, - script = doc.createElement('script'), - sibling = doc.getElementsByTagName('script')[0], - parent = sibling.parentNode, - prop = uid + 'runScript', - prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; + script = doc.createElement('script'), + sibling = doc.getElementsByTagName('script')[0], + parent = sibling.parentNode, + prop = uid + 'runScript', + prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; // Firefox 2.0.0.2 cannot use script injection as intended because it executes // asynchronously, but that's OK because script injection is only used to avoid @@ -636,8 +689,10 @@ module.exports = (function() { // Remove the inserted script *before* running the code to avoid differences // in the expected script element count/order of the document. script.appendChild(doc.createTextNode(prefix + code)); - anchor[prop] = function() { destroyElement(script); }; - } catch(e) { + anchor[prop] = function () { + destroyElement(script); + }; + } catch (e) { parent = parent.cloneNode(false); sibling = null; script.text = code; @@ -656,11 +711,11 @@ module.exports = (function() { function setOptions(object, options) { options = object.options = _.assign({}, cloneDeep(object.constructor.options), cloneDeep(options)); - _.forOwn(options, function(value, key) { + _.forOwn(options, function (value, key) { if (value != null) { // Add event listeners. if (/^on[A-Z]/.test(key)) { - _.each(key.split(' '), function(key) { + _.each(key.split(' '), function (key) { object.on(key.slice(2).toLowerCase(), value); }); } else if (!_.has(object, key)) { @@ -679,22 +734,22 @@ module.exports = (function() { */ function resolve() { var deferred = this, - clone = deferred.benchmark, - bench = clone._original; + clone = deferred.benchmark, + bench = clone._original; if (bench.aborted) { // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete. deferred.teardown(); clone.running = false; cycle(deferred); - } - else if (++deferred.cycles < clone.count) { + } else if (++deferred.cycles < clone.count) { clone.compiled.call(deferred, context, timer); - } - else { + } else { timer.stop(deferred); deferred.teardown(); - delay(clone, function() { cycle(deferred); }); + delay(clone, function () { + cycle(deferred); + }); } } @@ -727,18 +782,18 @@ module.exports = (function() { function filter(array, callback) { if (callback === 'successful') { // Callback to exclude those that are errored, unrun, or have hz of Infinity. - callback = function(bench) { + callback = function (bench) { return bench.cycles && _.isFinite(bench.hz) && !bench.error; }; - } - else if (callback === 'fastest' || callback === 'slowest') { + } else if (callback === 'fastest' || callback === 'slowest') { // Get successful, sort by period + margin of error, and filter fastest/slowest. - var result = filter(array, 'successful').sort(function(a, b) { - a = a.stats; b = b.stats; + var result = filter(array, 'successful').sort(function (a, b) { + a = a.stats; + b = b.stats; return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback === 'fastest' ? 1 : -1); }); - return _.filter(result, function(bench) { + return _.filter(result, function (bench) { return result[0].compare(bench) == 0; }); } @@ -755,8 +810,7 @@ module.exports = (function() { */ function formatNumber(number) { number = String(number).split('.'); - return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') + - (number[1] ? '.' + number[1] : ''); + return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') + (number[1] ? '.' + number[1] : ''); } /** @@ -800,19 +854,19 @@ module.exports = (function() { */ function invoke(benches, name) { var args, - bench, - queued, - index = -1, - eventProps = { 'currentTarget': benches }, - options = { 'onStart': _.noop, 'onCycle': _.noop, 'onComplete': _.noop }, - result = _.toArray(benches); + bench, + queued, + index = -1, + eventProps = { 'currentTarget': benches }, + options = { 'onStart': _.noop, 'onCycle': _.noop, 'onComplete': _.noop }, + result = _.toArray(benches); /** * Invokes the method of the current object and if synchronous, fetches the next. */ function execute() { var listeners, - async = isAsync(bench); + async = isAsync(bench); if (async) { // Use `getNext` as the first listener. @@ -831,8 +885,8 @@ module.exports = (function() { */ function getNext(event) { var cycleEvent, - last = bench, - async = isAsync(last); + last = bench, + async = isAsync(last); if (async) { last.off('complete', getNext); @@ -849,12 +903,10 @@ module.exports = (function() { bench = queued ? benches[0] : result[index]; if (isAsync(bench)) { delay(bench, execute); - } - else if (async) { + } else if (async) { // Resume execution if previously asynchronous but now synchronous. while (execute()) {} - } - else { + } else { // Continue synchronous execution. return true; } @@ -879,8 +931,11 @@ module.exports = (function() { function isAsync(object) { // Avoid using `instanceof` here because of IE memory leak issues with host objects. var async = args[0] && args[0].async; - return name == 'run' && (object instanceof Benchmark) && - ((async == null ? object.options.async : async) && support.timeout || object.defer); + return ( + name == 'run' && + object instanceof Benchmark && + (((async == null ? object.options.async : async) && support.timeout) || object.defer) + ); } /** @@ -894,9 +949,7 @@ module.exports = (function() { shift.call(benches); } // If we reached the last index then return `false`. - return (queued ? benches.length : index < result.length) - ? index - : (index = false); + return (queued ? benches.length : index < result.length) ? index : (index = false); } // Juggle arguments. if (_.isString(name)) { @@ -906,7 +959,7 @@ module.exports = (function() { // 2 arguments (array, options). options = _.assign(options, name); name = options.name; - args = _.isArray(args = 'args' in options ? options.args : []) ? args : [args]; + args = _.isArray((args = 'args' in options ? options.args : [])) ? args : [args]; queued = options.queued; } // Start iterating over the array. @@ -918,7 +971,7 @@ module.exports = (function() { options.onStart.call(benches, Event(eventProps)); // End early if the suite was aborted in an "onStart" listener. - if (name == 'run' && (benches instanceof Suite) && benches.aborted) { + if (name == 'run' && benches instanceof Suite && benches.aborted) { // Emit "cycle" event. eventProps.type = 'cycle'; options.onCycle.call(benches, Event(eventProps)); @@ -950,11 +1003,11 @@ module.exports = (function() { */ function join(object, separator1, separator2) { var result = [], - length = (object = Object(object)).length, - arrayLike = length === length >>> 0; + length = (object = Object(object)).length, + arrayLike = length === length >>> 0; separator2 || (separator2 = ': '); - _.each(object, function(value, key) { + _.each(object, function (value, key) { result.push(arrayLike ? value : key + separator2 + value); }); return result.join(separator1 || ','); @@ -971,8 +1024,8 @@ module.exports = (function() { */ function abortSuite() { var event, - suite = this, - resetting = calledBy.resetSuite; + suite = this, + resetting = calledBy.resetSuite; if (suite.running) { event = Event('abort'); @@ -1031,10 +1084,10 @@ module.exports = (function() { */ function add(name, fn, options) { var suite = this, - bench = new Benchmark(name, fn, options), - event = Event({ 'type': 'add', 'target': bench }); + bench = new Benchmark(name, fn, options), + event = Event({ 'type': 'add', 'target': bench }); - if (suite.emit(event), !event.cancelled) { + if ((suite.emit(event), !event.cancelled)) { suite.push(bench); } return suite; @@ -1050,14 +1103,12 @@ module.exports = (function() { */ function cloneSuite(options) { var suite = this, - result = new suite.constructor(_.assign({}, suite.options, options)); + result = new suite.constructor(_.assign({}, suite.options, options)); // Copy own properties. - _.forOwn(suite, function(value, key) { + _.forOwn(suite, function (value, key) { if (!_.has(result, key)) { - result[key] = value && _.isFunction(value.clone) - ? value.clone() - : cloneDeep(value); + result[key] = value && _.isFunction(value.clone) ? value.clone() : cloneDeep(value); } }); return result; @@ -1073,7 +1124,7 @@ module.exports = (function() { */ function filterSuite(callback) { var suite = this, - result = new suite.constructor(suite.options); + result = new suite.constructor(suite.options); result.push.apply(result, filter(suite, callback)); return result; @@ -1088,8 +1139,8 @@ module.exports = (function() { */ function resetSuite() { var event, - suite = this, - aborting = calledBy.abortSuite; + suite = this, + aborting = calledBy.abortSuite; if (suite.running && !aborting) { // No worries, `resetSuite()` is called within `abortSuite()`. @@ -1098,8 +1149,7 @@ module.exports = (function() { delete calledBy.resetSuite; } // Reset if the state has changed. - else if ((suite.aborted || suite.running) && - (suite.emit(event = Event('reset')), !event.cancelled)) { + else if ((suite.aborted || suite.running) && (suite.emit((event = Event('reset'))), !event.cancelled)) { suite.aborted = suite.running = false; if (!aborting) { invoke(suite, 'reset'); @@ -1134,10 +1184,10 @@ module.exports = (function() { 'name': 'run', 'args': options, 'queued': options.queued, - 'onStart': function(event) { + 'onStart': function (event) { suite.emit(event); }, - 'onCycle': function(event) { + 'onCycle': function (event) { var bench = event.target; if (bench.error) { suite.emit({ 'type': 'error', 'target': bench }); @@ -1145,10 +1195,10 @@ module.exports = (function() { suite.emit(event); event.aborted = suite.aborted; }, - 'onComplete': function(event) { + 'onComplete': function (event) { suite.running = false; suite.emit(event); - } + }, }); return suite; } @@ -1165,17 +1215,17 @@ module.exports = (function() { */ function emit(type) { var listeners, - object = this, - event = Event(type), - events = object.events, - args = (arguments[0] = event, arguments); + object = this, + event = Event(type), + events = object.events, + args = ((arguments[0] = event), arguments); event.currentTarget || (event.currentTarget = object); event.target || (event.target = object); delete event.result; if (events && (listeners = _.has(events, event.type) && events[event.type])) { - _.each(listeners.slice(), function(listener) { + _.each(listeners.slice(), function (listener) { if ((event.result = listener.apply(object, args)) === false) { event.cancelled = true; } @@ -1195,7 +1245,7 @@ module.exports = (function() { */ function listeners(type) { var object = this, - events = object.events || (object.events = {}); + events = object.events || (object.events = {}); return _.has(events, type) ? events[type] : (events[type] = []); } @@ -1228,12 +1278,12 @@ module.exports = (function() { */ function off(type, listener) { var object = this, - events = object.events; + events = object.events; if (!events) { return object; } - _.each(type ? type.split(' ') : events, function(listeners, type) { + _.each(type ? type.split(' ') : events, function (listeners, type) { var index; if (typeof listeners == 'string') { type = listeners; @@ -1270,13 +1320,10 @@ module.exports = (function() { */ function on(type, listener) { var object = this, - events = object.events || (object.events = {}); + events = object.events || (object.events = {}); - _.each(type.split(' '), function(type) { - (_.has(events, type) - ? events[type] - : (events[type] = []) - ).push(listener); + _.each(type.split(' '), function (type) { + (_.has(events, type) ? events[type] : (events[type] = [])).push(listener); }); return object; } @@ -1291,8 +1338,8 @@ module.exports = (function() { */ function abort() { var event, - bench = this, - resetting = calledBy.reset; + bench = this, + resetting = calledBy.reset; if (bench.running) { event = Event('abort'); @@ -1330,13 +1377,13 @@ module.exports = (function() { */ function clone(options) { var bench = this, - result = new bench.constructor(_.assign({}, bench, options)); + result = new bench.constructor(_.assign({}, bench, options)); // Correct the `options` object. result.options = _.assign({}, cloneDeep(bench.options), cloneDeep(options)); // Copy own custom properties. - _.forOwn(bench, function(value, key) { + _.forOwn(bench, function (value, key) { if (!_.has(result, key)) { result[key] = cloneDeep(value); } @@ -1360,31 +1407,39 @@ module.exports = (function() { return 0; } var critical, - zStat, - sample1 = bench.stats.sample, - sample2 = other.stats.sample, - size1 = sample1.length, - size2 = sample2.length, - maxSize = max(size1, size2), - minSize = min(size1, size2), - u1 = getU(sample1, sample2), - u2 = getU(sample2, sample1), - u = min(u1, u2); + zStat, + sample1 = bench.stats.sample, + sample2 = other.stats.sample, + size1 = sample1.length, + size2 = sample2.length, + maxSize = max(size1, size2), + minSize = min(size1, size2), + u1 = getU(sample1, sample2), + u2 = getU(sample2, sample1), + u = min(u1, u2); function getScore(xA, sampleB) { - return _.reduce(sampleB, function(total, xB) { - return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); - }, 0); + return _.reduce( + sampleB, + function (total, xB) { + return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); + }, + 0 + ); } function getU(sampleA, sampleB) { - return _.reduce(sampleA, function(total, xA) { - return total + getScore(xA, sampleB); - }, 0); + return _.reduce( + sampleA, + function (total, xA) { + return total + getScore(xA, sampleB); + }, + 0 + ); } function getZ(u) { - return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); + return (u - (size1 * size2) / 2) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); } // Reject the null hypothesis the two samples come from the // same population (i.e. have the same median) if... @@ -1415,22 +1470,22 @@ module.exports = (function() { return bench; } var event, - index = 0, - changes = [], - queue = []; + index = 0, + changes = [], + queue = []; // A non-recursive solution to check if properties have changed. // For more information see http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4. var data = { 'destination': bench, - 'source': _.assign({}, cloneDeep(bench.constructor.prototype), cloneDeep(bench.options)) + 'source': _.assign({}, cloneDeep(bench.constructor.prototype), cloneDeep(bench.options)), }; do { - _.forOwn(data.source, function(value, key) { + _.forOwn(data.source, function (value, key) { var changed, - destination = data.destination, - currValue = destination[key]; + destination = data.destination, + currValue = destination[key]; // Skip pseudo private properties like `_timerId` which could be a // Java object in environments like RingoJS. @@ -1464,12 +1519,11 @@ module.exports = (function() { changes.push({ 'destination': destination, 'key': key, 'value': value }); } }); - } - while ((data = queue[index++])); + } while ((data = queue[index++])); // If changed emit the `reset` event and if it isn't cancelled reset the benchmark. - if (changes.length && (bench.emit(event = Event('reset')), !event.cancelled)) { - _.each(changes, function(data) { + if (changes.length && (bench.emit((event = Event('reset'))), !event.cancelled)) { + _.each(changes, function (data) { data.destination[data.key] = data.value; }); } @@ -1485,13 +1539,13 @@ module.exports = (function() { */ function toStringBench() { var bench = this, - error = bench.error, - hz = bench.hz, - id = bench.id, - stats = bench.stats, - size = stats.sample.length, - pm = '\xb1', - result = bench.name || (_.isNaN(id) ? id : ''); + error = bench.error, + hz = bench.hz, + id = bench.id, + stats = bench.stats, + size = stats.sample.length, + pm = '\xb1', + result = bench.name || (_.isNaN(id) ? id : ''); if (error) { var errorStr; @@ -1504,10 +1558,18 @@ module.exports = (function() { errorStr = join(_.assign({ 'name': error.name, 'message': error.message }, error)); } result += ': ' + errorStr; - } - else { - result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm + - stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)'; + } else { + result += + ' x ' + + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + + ' ops/sec ' + + pm + + stats.rme.toFixed(2) + + '% (' + + size + + ' run' + + (size == 1 ? '' : 's') + + ' sampled)'; } return result; } @@ -1523,11 +1585,11 @@ module.exports = (function() { */ function clock() { var options = Benchmark.options, - templateData = {}, - timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }]; + templateData = {}, + timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }]; // Lazy define for hi-res timers. - clock = function(clone) { + clock = function (clone) { var deferred; if (clone instanceof Deferred) { @@ -1535,12 +1597,12 @@ module.exports = (function() { clone = deferred.benchmark; } var bench = clone._original, - stringable = isStringable(bench.fn), - count = bench.count = clone.count, - decompilable = stringable || (support.decompilation && (clone.setup !== _.noop || clone.teardown !== _.noop)), - id = bench.id, - name = bench.name || (typeof id == 'number' ? '' : id), - result = 0; + stringable = isStringable(bench.fn), + count = (bench.count = clone.count), + decompilable = stringable || (support.decompilation && (clone.setup !== _.noop || clone.teardown !== _.noop)), + id = bench.id, + name = bench.name || (typeof id == 'number' ? '' : id), + result = 0; // Init `minTime` if needed. clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime); @@ -1550,50 +1612,47 @@ module.exports = (function() { // to avoid potential engine optimizations enabled over the life of the test. var funcBody = deferred ? 'var d#=this,${fnArg}=d#,m#=d#.benchmark._original,f#=m#.fn,su#=m#.setup,td#=m#.teardown;' + - // When `deferred.cycles` is `0` then... - 'if(!d#.cycles){' + - // set `deferred.fn`, - 'd#.fn=function(){var ${fnArg}=d#;if(typeof f#=="function"){try{${fn}\n}catch(e#){f#(d#)}}else{${fn}\n}};' + - // set `deferred.teardown`, - 'd#.teardown=function(){d#.cycles=0;if(typeof td#=="function"){try{${teardown}\n}catch(e#){td#()}}else{${teardown}\n}};' + - // execute the benchmark's `setup`, - 'if(typeof su#=="function"){try{${setup}\n}catch(e#){su#()}}else{${setup}\n};' + - // start timer, - 't#.start(d#);' + - // and then execute `deferred.fn` and return a dummy object. - '}d#.fn();return{uid:"${uid}"}' - + // When `deferred.cycles` is `0` then... + 'if(!d#.cycles){' + + // set `deferred.fn`, + 'd#.fn=function(){var ${fnArg}=d#;if(typeof f#=="function"){try{${fn}\n}catch(e#){f#(d#)}}else{${fn}\n}};' + + // set `deferred.teardown`, + 'd#.teardown=function(){d#.cycles=0;if(typeof td#=="function"){try{${teardown}\n}catch(e#){td#()}}else{${teardown}\n}};' + + // execute the benchmark's `setup`, + 'if(typeof su#=="function"){try{${setup}\n}catch(e#){su#()}}else{${setup}\n};' + + // start timer, + 't#.start(d#);' + + // and then execute `deferred.fn` and return a dummy object. + '}d#.fn();return{uid:"${uid}"}' : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count,n#=t#.ns;${setup}\n${begin};' + - 'while(i#--){${fn}\n}${end};${teardown}\nreturn{elapsed:r#,uid:"${uid}"}'; + 'while(i#--){${fn}\n}${end};${teardown}\nreturn{elapsed:r#,uid:"${uid}"}'; - var compiled = bench.compiled = clone.compiled = createCompiled(bench, decompilable, deferred, funcBody), - isEmpty = !(templateData.fn || stringable); + var compiled = (bench.compiled = clone.compiled = createCompiled(bench, decompilable, deferred, funcBody)), + isEmpty = !(templateData.fn || stringable); try { if (isEmpty) { // Firefox may remove dead code from `Function#toString` results. // For more information see http://bugzil.la/536085. throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.'); - } - else if (!deferred) { + } else if (!deferred) { // Pretest to determine if compiled code exits early, usually by a // rogue `return` statement, by checking for a return object with the uid. bench.count = 1; compiled = decompilable && (compiled.call(bench, context, timer) || {}).uid == templateData.uid && compiled; bench.count = count; } - } catch(e) { + } catch (e) { compiled = null; clone.error = e || new Error(String(e)); bench.count = count; } // Fallback when a test exits early or errors during pretest. if (!compiled && !deferred && !isEmpty) { - funcBody = ( - stringable || (decompilable && !clone.error) + funcBody = + (stringable || (decompilable && !clone.error) ? 'function f#(){${fn}\n}var r#,s#,m#=this,i#=m#.count' - : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count' - ) + + : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count') + ',n#=t#.ns;${setup}\n${begin};m#.f#=f#;while(i#--){m#.f#()}${end};' + 'delete m#.f#;${teardown}\nreturn{elapsed:r#}'; @@ -1605,8 +1664,7 @@ module.exports = (function() { compiled.call(bench, context, timer); bench.count = count; delete clone.error; - } - catch(e) { + } catch (e) { bench.count = count; if (!clone.error) { clone.error = e || new Error(String(e)); @@ -1628,7 +1686,7 @@ module.exports = (function() { */ function createCompiled(bench, decompilable, deferred, body) { var fn = bench.fn, - fnArg = deferred ? getFirstArgument(fn) || 'deferred' : ''; + fnArg = deferred ? getFirstArgument(fn) || 'deferred' : ''; templateData.uid = uid + uidCounter++; @@ -1636,39 +1694,36 @@ module.exports = (function() { 'setup': decompilable ? getSource(bench.setup) : interpolate('m#.setup()'), 'fn': decompilable ? getSource(fn) : interpolate('m#.fn(' + fnArg + ')'), 'fnArg': fnArg, - 'teardown': decompilable ? getSource(bench.teardown) : interpolate('m#.teardown()') + 'teardown': decompilable ? getSource(bench.teardown) : interpolate('m#.teardown()'), }); // Use API of chosen timer. if (timer.unit == 'ns') { _.assign(templateData, { 'begin': interpolate('s#=n#()'), - 'end': interpolate('r#=n#(s#);r#=r#[0]+(r#[1]/1e9)') + 'end': interpolate('r#=n#(s#);r#=r#[0]+(r#[1]/1e9)'), }); - } - else if (timer.unit == 'us') { + } else if (timer.unit == 'us') { if (timer.ns.stop) { _.assign(templateData, { 'begin': interpolate('s#=n#.start()'), - 'end': interpolate('r#=n#.microseconds()/1e6') + 'end': interpolate('r#=n#.microseconds()/1e6'), }); } else { _.assign(templateData, { 'begin': interpolate('s#=n#()'), - 'end': interpolate('r#=(n#()-s#)/1e6') + 'end': interpolate('r#=(n#()-s#)/1e6'), }); } - } - else if (timer.ns.now) { + } else if (timer.ns.now) { _.assign(templateData, { 'begin': interpolate('s#=n#.now()'), - 'end': interpolate('r#=(n#.now()-s#)/1e3') + 'end': interpolate('r#=(n#.now()-s#)/1e3'), }); - } - else { + } else { _.assign(templateData, { 'begin': interpolate('s#=new n#().getTime()'), - 'end': interpolate('r#=(new n#().getTime()-s#)/1e3') + 'end': interpolate('r#=(new n#().getTime()-s#)/1e3'), }); } // Define `timer` methods. @@ -1686,7 +1741,7 @@ module.exports = (function() { return createFunction( interpolate('window,t#'), 'var global = window, clearTimeout = global.clearTimeout, setTimeout = global.setTimeout;\n' + - interpolate(body) + interpolate(body) ); } @@ -1695,11 +1750,11 @@ module.exports = (function() { */ function getRes(unit) { var measured, - begin, - count = 30, - divisor = 1e3, - ns = timer.ns, - sample = []; + begin, + count = 30, + divisor = 1e3, + ns = timer.ns, + sample = []; // Get average smallest measurable time. while (count--) { @@ -1712,18 +1767,15 @@ module.exports = (function() { begin = ns(); while (!(measured = ns() - begin)) {} } - } - else if (unit == 'ns') { + } else if (unit == 'ns') { divisor = 1e9; - begin = (begin = ns())[0] + (begin[1] / divisor); - while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) {} + begin = (begin = ns())[0] + begin[1] / divisor; + while (!(measured = (measured = ns())[0] + measured[1] / divisor - begin)) {} divisor = 1; - } - else if (ns.now) { + } else if (ns.now) { begin = ns.now(); while (!(measured = ns.now() - begin)) {} - } - else { + } else { begin = new ns().getTime(); while (!(measured = new ns().getTime() - begin)) {} } @@ -1753,10 +1805,10 @@ module.exports = (function() { // enable benchmarking via the --enable-benchmarking command // line switch in at least Chrome 7 to use chrome.Interval try { - if ((timer.ns = new (context.chrome || context.chromium).Interval)) { + if ((timer.ns = new (context.chrome || context.chromium).Interval())) { timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); } - } catch(e) {} + } catch (e) {} // Detect Node.js's nanosecond resolution timer available in Node.js >= 0.8. if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') { @@ -1788,25 +1840,27 @@ module.exports = (function() { options || (options = {}); var async = options.async, - elapsed = 0, - initCount = bench.initCount, - minSamples = bench.minSamples, - queue = [], - sample = bench.stats.sample; + elapsed = 0, + initCount = bench.initCount, + minSamples = bench.minSamples, + queue = [], + sample = bench.stats.sample; /** * Adds a clone to the queue. */ function enqueue() { - queue.push(bench.clone({ - '_original': bench, - 'events': { - 'abort': [update], - 'cycle': [update], - 'error': [update], - 'start': [update] - } - })); + queue.push( + bench.clone({ + '_original': bench, + 'events': { + 'abort': [update], + 'cycle': [update], + 'error': [update], + 'start': [update], + }, + }) + ); } /** @@ -1814,14 +1868,13 @@ module.exports = (function() { */ function update(event) { var clone = this, - type = event.type; + type = event.type; if (bench.running) { if (type == 'start') { // Note: `clone.minTime` prop is inited in `clock()`. clone.count = bench.initCount; - } - else { + } else { if (type == 'error') { bench.error = clone.error; } @@ -1845,20 +1898,22 @@ module.exports = (function() { */ function evaluate(event) { var critical, - df, - mean, - moe, - rme, - sd, - sem, - variance, - clone = event.target, - done = bench.aborted, - now = _.now(), - size = sample.push(clone.times.period), - maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, - times = bench.times, - varOf = function(sum, x) { return sum + pow(x - mean, 2); }; + df, + mean, + moe, + rme, + sd, + sem, + variance, + clone = event.target, + done = bench.aborted, + now = _.now(), + size = sample.push(clone.times.period), + maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, + times = bench.times, + varOf = function (sum, x) { + return sum + pow(x - mean, 2); + }; // Exit early for aborted or unclockable tests. if (done || clone.hz == Infinity) { @@ -1889,7 +1944,7 @@ module.exports = (function() { 'moe': moe, 'rme': rme, 'sem': sem, - 'variance': variance + 'variance': variance, }); // Abort the cycle loop when the minimum sample size has been collected @@ -1925,7 +1980,9 @@ module.exports = (function() { 'args': { 'async': async }, 'queued': true, 'onCycle': evaluate, - 'onComplete': function() { bench.emit('complete'); } + 'onComplete': function () { + bench.emit('complete'); + }, }); } @@ -1947,15 +2004,15 @@ module.exports = (function() { clone = clone.benchmark; } var clocked, - cycles, - divisor, - event, - minTime, - period, - async = options.async, - bench = clone._original, - count = clone.count, - times = clone.times; + cycles, + divisor, + event, + minTime, + period, + async = options.async, + bench = clone._original, + count = clone.count, + times = clone.times; // Continue, if not aborted between cycles. if (clone.running) { @@ -2015,12 +2072,13 @@ module.exports = (function() { if (deferred) { clone.compiled.call(deferred, context, timer); } else if (async) { - delay(clone, function() { cycle(clone, options); }); + delay(clone, function () { + cycle(clone, options); + }); } else { cycle(clone); } - } - else { + } else { // Fix TraceMonkey bug associated with clock fallbacks. // For more information see http://bugzil.la/509069. if (support.browser) { @@ -2049,7 +2107,7 @@ module.exports = (function() { */ function run(options) { var bench = this, - event = Event('start'); + event = Event('start'); // Set `running` to `false` so `reset()` won't call `abort()`. bench.running = false; @@ -2061,7 +2119,9 @@ module.exports = (function() { bench.emit(event); if (!event.cancelled) { - options = { 'async': ((options = options && options.async) == null ? bench.async : options) && support.timeout }; + options = { + 'async': ((options = options && options.async) == null ? bench.async : options) && support.timeout, + }; // For clones created within `compute()`. if (bench._original) { @@ -2088,7 +2148,6 @@ module.exports = (function() { // making it non-writable in the process, unless it is the first property // assigned by for-in loop of `_.assign()`. _.assign(Benchmark, { - /** * The default options copied by benchmark instances. * @@ -2097,7 +2156,6 @@ module.exports = (function() { * @type Object */ 'options': { - /** * A flag to indicate that benchmark cycles will execute asynchronously * by default. @@ -2219,7 +2277,7 @@ module.exports = (function() { * @memberOf Benchmark.options * @type Function */ - 'onStart': undefined + 'onStart': undefined, }, /** @@ -2230,19 +2288,20 @@ module.exports = (function() { * @memberOf Benchmark * @type Object */ - 'platform': context.platform || require('platform') || ({ - 'description': context.navigator && context.navigator.userAgent || null, - 'layout': null, - 'product': null, - 'name': null, - 'manufacturer': null, - 'os': null, - 'prerelease': null, - 'version': null, - 'toString': function() { - return this.description || ''; - } - }), + 'platform': context.platform || + require('platform') || { + 'description': (context.navigator && context.navigator.userAgent) || null, + 'layout': null, + 'product': null, + 'name': null, + 'manufacturer': null, + 'os': null, + 'prerelease': null, + 'version': null, + 'toString': function () { + return this.description || ''; + }, + }, /** * The semantic version number. @@ -2251,7 +2310,7 @@ module.exports = (function() { * @memberOf Benchmark * @type string */ - 'version': '2.1.2' + 'version': '2.1.2', }); _.assign(Benchmark, { @@ -2260,18 +2319,17 @@ module.exports = (function() { 'invoke': invoke, 'join': join, 'runInContext': runInContext, - 'support': support + 'support': support, }); // Add lodash methods to Benchmark. - _.each(['each', 'forEach', 'forOwn', 'has', 'indexOf', 'map', 'reduce'], function(methodName) { + _.each(['each', 'forEach', 'forOwn', 'has', 'indexOf', 'map', 'reduce'], function (methodName) { Benchmark[methodName] = _[methodName]; }); /*------------------------------------------------------------------------*/ _.assign(Benchmark.prototype, { - /** * The number of times a test was executed. * @@ -2414,7 +2472,6 @@ module.exports = (function() { * @type Object */ 'stats': { - /** * The margin of error. * @@ -2469,7 +2526,7 @@ module.exports = (function() { * @memberOf Benchmark#stats * @type number */ - 'variance': 0 + 'variance': 0, }, /** @@ -2479,7 +2536,6 @@ module.exports = (function() { * @type Object */ 'times': { - /** * The time taken to complete the last cycle (secs). * @@ -2510,8 +2566,8 @@ module.exports = (function() { * @memberOf Benchmark#times * @type number */ - 'timeStamp': 0 - } + 'timeStamp': 0, + }, }); _.assign(Benchmark.prototype, { @@ -2524,13 +2580,12 @@ module.exports = (function() { 'on': on, 'reset': reset, 'run': run, - 'toString': toStringBench + 'toString': toStringBench, }); /*------------------------------------------------------------------------*/ _.assign(Deferred.prototype, { - /** * The deferred benchmark instance. * @@ -2561,17 +2616,16 @@ module.exports = (function() { * @memberOf Benchmark.Deferred * @type number */ - 'timeStamp': 0 + 'timeStamp': 0, }); _.assign(Deferred.prototype, { - 'resolve': resolve + 'resolve': resolve, }); /*------------------------------------------------------------------------*/ _.assign(Event.prototype, { - /** * A flag to indicate if the emitters listener iteration is aborted. * @@ -2626,7 +2680,7 @@ module.exports = (function() { * @memberOf Benchmark.Event * @type string */ - 'type': '' + 'type': '', }); /*------------------------------------------------------------------------*/ @@ -2639,20 +2693,18 @@ module.exports = (function() { * @type Object */ Suite.options = { - /** * The name of the suite. * * @memberOf Benchmark.Suite.options * @type string */ - 'name': undefined + 'name': undefined, }; /*------------------------------------------------------------------------*/ _.assign(Suite.prototype, { - /** * The number of benchmarks in the suite. * @@ -2675,7 +2727,7 @@ module.exports = (function() { * @memberOf Benchmark.Suite * @type boolean */ - 'running': false + 'running': false, }); _.assign(Suite.prototype, { @@ -2697,7 +2749,7 @@ module.exports = (function() { 'slice': slice, 'sort': arrayRef.sort, 'splice': arrayRef.splice, - 'unshift': unshift + 'unshift': unshift, }); /*------------------------------------------------------------------------*/ @@ -2706,15 +2758,15 @@ module.exports = (function() { _.assign(Benchmark, { 'Deferred': Deferred, 'Event': Event, - 'Suite': Suite + 'Suite': Suite, }); /*------------------------------------------------------------------------*/ // Add lodash methods as Suite methods. - _.each(['each', 'forEach', 'indexOf', 'map', 'reduce'], function(methodName) { + _.each(['each', 'forEach', 'indexOf', 'map', 'reduce'], function (methodName) { var func = _[methodName]; - Suite.prototype[methodName] = function() { + Suite.prototype[methodName] = function () { var args = [this]; push.apply(args, arguments); return func.apply(_, args); @@ -2723,12 +2775,12 @@ module.exports = (function() { // Avoid array-like object bugs with `Array#shift` and `Array#splice` // in Firefox < 10 and IE < 9. - _.each(['pop', 'shift', 'splice'], function(methodName) { + _.each(['pop', 'shift', 'splice'], function (methodName) { var func = arrayRef[methodName]; - Suite.prototype[methodName] = function() { + Suite.prototype[methodName] = function () { var value = this, - result = func.apply(value, arguments); + result = func.apply(value, arguments); if (value.length === 0) { delete value[0]; @@ -2739,7 +2791,7 @@ module.exports = (function() { // Avoid buggy `Array#unshift` in IE < 8 which doesn't return the new // length of the array. - Suite.prototype.unshift = function() { + Suite.prototype.unshift = function () { var value = this; unshift.apply(value, arguments); return value.length; @@ -2755,5 +2807,4 @@ module.exports = (function() { window.Benchmark = Benchmark; return Benchmark; - -}.call(this)); +}.call(this); diff --git a/tgui/packages/tgui-bench/tests/Button.test.tsx b/tgui/packages/tgui-bench/tests/Button.test.tsx index e3472cbbbfa..67e156e366a 100644 --- a/tgui/packages/tgui-bench/tests/Button.test.tsx +++ b/tgui/packages/tgui-bench/tests/Button.test.tsx @@ -7,40 +7,24 @@ const render = createRenderer(); const handleClick = () => undefined; export const SingleButton = () => { - const node = ( - - ); + const node = ; render(node); }; export const SingleButtonWithCallback = () => { - const node = ( - - ); + const node = ; render(node); }; export const SingleButtonWithLinkEvent = () => { - const node = ( - - ); + const node = ; render(node); }; export const ListOfButtons = () => { const nodes: JSX.Element[] = []; for (let i = 0; i < 100; i++) { - const node = ( - - ); + const node = ; nodes.push(node); } render(
{nodes}
); diff --git a/tgui/packages/tgui-bench/tests/DisposalBin.test.tsx b/tgui/packages/tgui-bench/tests/DisposalBin.test.tsx index 99367d2016c..a7cbe55dd61 100644 --- a/tgui/packages/tgui-bench/tests/DisposalBin.test.tsx +++ b/tgui/packages/tgui-bench/tests/DisposalBin.test.tsx @@ -6,9 +6,11 @@ import { configureStore, StoreProvider } from 'tgui/store'; const store = configureStore({ sideEffets: false }); const renderUi = createRenderer((dataJson: string) => { - store.dispatch(backendUpdate({ - data: Byond.parseJson(dataJson), - })); + store.dispatch( + backendUpdate({ + data: Byond.parseJson(dataJson), + }) + ); return ( diff --git a/tgui/packages/tgui-bench/tests/Flex.test.tsx b/tgui/packages/tgui-bench/tests/Flex.test.tsx index e81ebc6f611..66c039a1908 100644 --- a/tgui/packages/tgui-bench/tests/Flex.test.tsx +++ b/tgui/packages/tgui-bench/tests/Flex.test.tsx @@ -6,9 +6,7 @@ const render = createRenderer(); export const Default = () => { const node = ( - - Text {Math.random()} - + Text {Math.random()} Text {Math.random()} diff --git a/tgui/packages/tgui-bench/tests/Stack.test.tsx b/tgui/packages/tgui-bench/tests/Stack.test.tsx index 952dba20294..ce7f5599e72 100644 --- a/tgui/packages/tgui-bench/tests/Stack.test.tsx +++ b/tgui/packages/tgui-bench/tests/Stack.test.tsx @@ -6,9 +6,7 @@ const render = createRenderer(); export const Default = () => { const node = ( - - Text {Math.random()} - + Text {Math.random()} Text {Math.random()} diff --git a/tgui/packages/tgui-bench/tests/Tooltip.test.tsx b/tgui/packages/tgui-bench/tests/Tooltip.test.tsx index b953fc911d2..ea43a61f0b4 100644 --- a/tgui/packages/tgui-bench/tests/Tooltip.test.tsx +++ b/tgui/packages/tgui-bench/tests/Tooltip.test.tsx @@ -1,5 +1,5 @@ -import { Box, Tooltip } from "tgui/components"; -import { createRenderer } from "tgui/renderer"; +import { Box, Tooltip } from 'tgui/components'; +import { createRenderer } from 'tgui/renderer'; const render = createRenderer(); diff --git a/tgui/packages/tgui-dev-server/dreamseeker.js b/tgui/packages/tgui-dev-server/dreamseeker.js index 3d4149cf256..0081d91a7e7 100644 --- a/tgui/packages/tgui-dev-server/dreamseeker.js +++ b/tgui/packages/tgui-dev-server/dreamseeker.js @@ -25,8 +25,7 @@ export class DreamSeeker { topic(params = {}) { const query = Object.keys(params) - .map(key => encodeURIComponent(key) - + '=' + encodeURIComponent(params[key])) + .map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(params[key])) .join('&'); return this.client.get('/dummy?' + query); } @@ -36,7 +35,7 @@ export class DreamSeeker { * @param {number[]} pids * @returns {DreamSeeker[]} */ -DreamSeeker.getInstancesByPids = async pids => { +DreamSeeker.getInstancesByPids = async (pids) => { if (process.platform !== 'win32') { return []; } @@ -46,8 +45,7 @@ DreamSeeker.getInstancesByPids = async pids => { const instance = instanceByPid.get(pid); if (instance) { instances.push(instance); - } - else { + } else { pidsToResolve.push(pid); } } @@ -83,12 +81,10 @@ DreamSeeker.getInstancesByPids = async pids => { instances.push(instance); instanceByPid.set(pid, instance); } - } - catch (err) { + } catch (err) { if (err.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') { logger.error(err.message, err.code); - } - else { + } else { logger.error(err); } return []; @@ -97,4 +93,4 @@ DreamSeeker.getInstancesByPids = async pids => { return instances; }; -const plural = (word, n) => n !== 1 ? word + 's' : word; +const plural = (word, n) => (n !== 1 ? word + 's' : word); diff --git a/tgui/packages/tgui-dev-server/link/client.cjs b/tgui/packages/tgui-dev-server/link/client.cjs index fe75314acd3..47cd6398b02 100644 --- a/tgui/packages/tgui-dev-server/link/client.cjs +++ b/tgui/packages/tgui-dev-server/link/client.cjs @@ -23,7 +23,7 @@ const ensureConnection = () => { socket.send(msg); } }; - socket.onmessage = event => { + socket.onmessage = (event) => { const msg = JSON.parse(event.data); for (let subscriber of subscribers) { subscriber(msg); @@ -37,14 +37,14 @@ if (process.env.NODE_ENV !== 'production') { window.onunload = () => socket && socket.close(); } -const subscribe = fn => subscribers.push(fn); +const subscribe = (fn) => subscribers.push(fn); /** * A json serializer which handles circular references and other junk. */ -const serializeObject = obj => { +const serializeObject = (obj) => { let refs = []; - const primitiveReviver = value => { + const primitiveReviver = (value) => { if (typeof value === 'number' && !Number.isFinite(value)) { return { __number__: String(value), @@ -68,9 +68,7 @@ const serializeObject = obj => { } refs.push(value); // Error object - const isError = value instanceof Error || ( - value.code && value.message && value.message.includes('Error') - ); + const isError = value instanceof Error || (value.code && value.message && value.message.includes('Error')); if (isError) { return { __error__: true, @@ -91,7 +89,7 @@ const serializeObject = obj => { return json; }; -const sendMessage = msg => { +const sendMessage = (msg) => { if (process.env.NODE_ENV !== 'production') { const json = serializeObject(msg); // Send message using WebSocket @@ -99,8 +97,7 @@ const sendMessage = msg => { ensureConnection(); if (socket.readyState === WebSocket.OPEN) { socket.send(json); - } - else { + } else { // Keep only 100 latest messages in the queue if (queue.length > 100) { queue.shift(); @@ -130,19 +127,16 @@ const sendLogEntry = (level, ns, ...args) => { args, }, }); - } - catch (err) {} + } catch (err) {} } }; const setupHotReloading = () => { - if (process.env.NODE_ENV !== 'production' - && process.env.WEBPACK_HMR_ENABLED - && window.WebSocket) { + if (process.env.NODE_ENV !== 'production' && process.env.WEBPACK_HMR_ENABLED && window.WebSocket) { if (module.hot) { ensureConnection(); sendLogEntry(0, null, 'setting up hot reloading'); - subscribe(msg => { + subscribe((msg) => { const { type } = msg; sendLogEntry(0, null, 'received', type); if (type === 'hotUpdate') { @@ -157,10 +151,10 @@ const setupHotReloading = () => { ignoreDeclined: true, ignoreErrored: true, }) - .then(modules => { + .then((modules) => { sendLogEntry(0, null, 'outdated modules', modules); }) - .catch(err => { + .catch((err) => { sendLogEntry(0, null, 'reload error', err); }); } diff --git a/tgui/packages/tgui-dev-server/link/retrace.js b/tgui/packages/tgui-dev-server/link/retrace.js index c10ba9cb173..60819861b90 100644 --- a/tgui/packages/tgui-dev-server/link/retrace.js +++ b/tgui/packages/tgui-dev-server/link/retrace.js @@ -18,7 +18,7 @@ const logger = createLogger('retrace'); const { SourceMapConsumer } = SourceMap; const sourceMaps = []; -export const loadSourceMaps = async bundleDir => { +export const loadSourceMaps = async (bundleDir) => { // Destroy and garbage collect consumers while (sourceMaps.length !== 0) { const { consumer } = sourceMaps.shift(); @@ -29,30 +29,28 @@ export const loadSourceMaps = async bundleDir => { for (let path of paths) { try { const file = basename(path).replace('.map', ''); - const consumer = await new SourceMapConsumer( - JSON.parse(fs.readFileSync(path, 'utf8'))); + const consumer = await new SourceMapConsumer(JSON.parse(fs.readFileSync(path, 'utf8'))); sourceMaps.push({ file, consumer }); - } - catch (err) { + } catch (err) { logger.error(err); } } logger.log(`loaded ${sourceMaps.length} source maps`); }; -export const retrace = stack => { +export const retrace = (stack) => { if (typeof stack !== 'string') { logger.log('ERROR: Stack is not a string!', stack); return stack; } const header = stack.split(/\n\s.*at/)[0]; const mappedStack = parseStackTrace(stack) - .map(frame => { + .map((frame) => { if (!frame.file) { return frame; } // Find the correct source map - const sourceMap = sourceMaps.find(sourceMap => { + const sourceMap = sourceMaps.find((sourceMap) => { return frame.file.includes(sourceMap.file); }); if (!sourceMap) { @@ -72,15 +70,13 @@ export const retrace = stack => { column: mappedFrame.column, }; }) - .map(frame => { + .map((frame) => { // Stringify the frame const { file, methodName, lineNumber } = frame; if (!file) { return ` at ${methodName}`; } - const compactPath = file - .replace(/^webpack:\/\/\/?/, './') - .replace(/.*node_modules\//, ''); + const compactPath = file.replace(/^webpack:\/\/\/?/, './').replace(/.*node_modules\//, ''); return ` at ${methodName} (${compactPath}:${lineNumber})`; }) .join('\n'); diff --git a/tgui/packages/tgui-dev-server/link/server.js b/tgui/packages/tgui-dev-server/link/server.js index 87a8a5911bc..70109d162ee 100644 --- a/tgui/packages/tgui-dev-server/link/server.js +++ b/tgui/packages/tgui-dev-server/link/server.js @@ -32,9 +32,9 @@ class LinkServer { setupWebSocketLink() { const port = 3000; this.wss = new WebSocket.Server({ port }); - this.wss.on('connection', ws => { + this.wss.on('connection', (ws) => { logger.log('client connected'); - ws.on('message', json => { + ws.on('message', (json) => { const msg = deserializeObject(json); this.handleLinkMessage(ws, msg); }); @@ -51,7 +51,7 @@ class LinkServer { this.httpServer = http.createServer((req, res) => { if (req.method === 'POST') { let body = ''; - req.on('data', chunk => { + req.on('data', (chunk) => { body += chunk.toString(); }); req.on('end', () => { @@ -76,16 +76,19 @@ class LinkServer { if (level <= 0 && !DEBUG) { return; } - directLog(ns, ...args.map(arg => { - if (typeof arg === 'object') { - return inspect(arg, { - depth: Infinity, - colors: true, - compact: 8, - }); - } - return arg; - })); + directLog( + ns, + ...args.map((arg) => { + if (typeof arg === 'object') { + return inspect(arg, { + depth: Infinity, + colors: true, + compact: 8, + }); + } + return arg; + }) + ); return; } if (type === 'relay') { @@ -117,7 +120,7 @@ class LinkServer { } } -const deserializeObject = str => { +const deserializeObject = (str) => { return JSON.parse(str, (key, value) => { if (typeof value === 'object' && value !== null) { if (value.__undefined__) { diff --git a/tgui/packages/tgui-dev-server/logging.js b/tgui/packages/tgui-dev-server/logging.js index 0dc222ae3d7..ff8aba8776e 100644 --- a/tgui/packages/tgui-dev-server/logging.js +++ b/tgui/packages/tgui-dev-server/logging.js @@ -11,8 +11,7 @@ const isNode = process && process.release && process.release.name === 'node'; let isChrome = false; try { isChrome = window.navigator.userAgent.toLowerCase().includes('chrome'); -} -catch {} +} catch {} // Timestamping function const getTimestamp = () => { @@ -32,9 +31,7 @@ const getPrefix = (() => { bright: '\x1b[37;1m', reset: '\x1b[0m', }; - return ns => [ - `${ESC.dimmed}${getTimestamp()} ${ESC.bright}${ns}${ESC.reset}`, - ]; + return (ns) => [`${ESC.dimmed}${getTimestamp()} ${ESC.bright}${ns}${ESC.reset}`]; } if (isChrome) { // Styles @@ -42,21 +39,15 @@ const getPrefix = (() => { dimmed: 'color: #888', bright: 'font-weight: bold', }; - return ns => [ - `%c${getTimestamp()}%c ${ns}`, - styles.dimmed, - styles.bright, - ]; + return (ns) => [`%c${getTimestamp()}%c ${ns}`, styles.dimmed, styles.bright]; } - return ns => [ - `${getTimestamp()} ${ns}`, - ]; + return (ns) => [`${getTimestamp()} ${ns}`]; })(); /** * Creates a logger object. */ -export const createLogger = ns => ({ +export const createLogger = (ns) => ({ log: (...args) => console.log(...getPrefix(ns), ...args), trace: (...args) => console.trace(...getPrefix(ns), ...args), debug: (...args) => console.debug(...getPrefix(ns), ...args), @@ -68,5 +59,4 @@ export const createLogger = ns => ({ /** * Explicitly log with chosen namespace. */ -export const directLog = (ns, ...args) => - console.log(...getPrefix(ns), ...args); +export const directLog = (ns, ...args) => console.log(...getPrefix(ns), ...args); diff --git a/tgui/packages/tgui-dev-server/reloader.js b/tgui/packages/tgui-dev-server/reloader.js index 5722cee644b..4e3c8fc0ecf 100644 --- a/tgui/packages/tgui-dev-server/reloader.js +++ b/tgui/packages/tgui-dev-server/reloader.js @@ -50,14 +50,9 @@ export const findCacheRoot = async () => { // Query the Windows Registry if (process.platform === 'win32') { logger.log('querying windows registry'); - let userpath = await regQuery( - 'HKCU\\Software\\Dantom\\BYOND', - 'userpath'); + let userpath = await regQuery('HKCU\\Software\\Dantom\\BYOND', 'userpath'); if (userpath) { - cacheRoot = userpath - .replace(/\\$/, '') - .replace(/\\/g, '/') - + '/cache'; + cacheRoot = userpath.replace(/\\$/, '').replace(/\\/g, '/') + '/cache'; onCacheRootFound(cacheRoot); return cacheRoot; } @@ -65,13 +60,13 @@ export const findCacheRoot = async () => { logger.log('found no cache directories'); }; -const onCacheRootFound = cacheRoot => { +const onCacheRootFound = (cacheRoot) => { logger.log(`found cache at '${cacheRoot}'`); // Plant a dummy fs.closeSync(fs.openSync(cacheRoot + '/dummy', 'w')); }; -export const reloadByondCache = async bundleDir => { +export const reloadByondCache = async (bundleDir) => { const cacheRoot = await findCacheRoot(); if (!cacheRoot) { return; @@ -83,9 +78,7 @@ export const reloadByondCache = async bundleDir => { return; } // Get dreamseeker instances - const pids = cacheDirs.map(cacheDir => ( - parseInt(cacheDir.split('/cache/tmp').pop(), 10) - )); + const pids = cacheDirs.map((cacheDir) => parseInt(cacheDir.split('/cache/tmp').pop(), 10)); const dssPromise = DreamSeeker.getInstancesByPids(pids); // Copy assets const assets = await resolveGlob(bundleDir, './*.+(bundle|chunk|hot-update).*'); @@ -102,8 +95,7 @@ export const reloadByondCache = async bundleDir => { fs.writeFileSync(destination, fs.readFileSync(asset)); } logger.log(`copied ${assets.length} files to '${cacheDir}'`); - } - catch (err) { + } catch (err) { logger.error(`failed copying to '${cacheDir}'`); logger.error(err); } diff --git a/tgui/packages/tgui-dev-server/util.js b/tgui/packages/tgui-dev-server/util.js index 0fc255ed674..9d07b96c71a 100644 --- a/tgui/packages/tgui-dev-server/util.js +++ b/tgui/packages/tgui-dev-server/util.js @@ -25,8 +25,7 @@ export const resolveGlob = (...sections) => { try { fs.statSync(path); safePaths.push(path); - } - catch {} + } catch {} } return safePaths; }; diff --git a/tgui/packages/tgui-dev-server/webpack.js b/tgui/packages/tgui-dev-server/webpack.js index 8cba68afcba..139610b79ce 100644 --- a/tgui/packages/tgui-dev-server/webpack.js +++ b/tgui/packages/tgui-dev-server/webpack.js @@ -18,7 +18,7 @@ const logger = createLogger('webpack'); * @param {any} config * @return {WebpackCompiler} */ -export const createCompiler = async options => { +export const createCompiler = async (options) => { const compiler = new WebpackCompiler(); await compiler.setup(options); return compiler; @@ -57,7 +57,7 @@ class WebpackCompiler { logger.log('compiling'); }); // Start reloading when it's finished - compiler.hooks.done.tap('tgui-dev-server', async stats => { + compiler.hooks.done.tap('tgui-dev-server', async (stats) => { // Load source maps await loadSourceMaps(this.bundleDir); // Reload cache @@ -77,7 +77,7 @@ class WebpackCompiler { stats .toString(this.config.devServer.stats) .split('\n') - .forEach(line => logger.log(line)); + .forEach((line) => logger.log(line)); }); } } diff --git a/tgui/packages/tgui-dev-server/winreg.js b/tgui/packages/tgui-dev-server/winreg.js index 669e2aad55d..b61fddc1a25 100644 --- a/tgui/packages/tgui-dev-server/winreg.js +++ b/tgui/packages/tgui-dev-server/winreg.js @@ -30,17 +30,14 @@ export const regQuery = async (path, key) => { logger.error('could not find the end of the line'); return null; } - const indexOfValue = stdout.indexOf( - ' ', - indexOfKey + keyPattern.length); + const indexOfValue = stdout.indexOf(' ', indexOfKey + keyPattern.length); if (indexOfValue === -1) { logger.error('could not find the start of the key value'); return null; } const value = stdout.substring(indexOfValue + 4, indexOfEol); return value; - } - catch (err) { + } catch (err) { logger.error(err); return null; } diff --git a/tgui/packages/tgui-polyfill/00-html5shiv.js b/tgui/packages/tgui-polyfill/00-html5shiv.js index c2f2060a1db..fcde92e6f7a 100644 --- a/tgui/packages/tgui-polyfill/00-html5shiv.js +++ b/tgui/packages/tgui-polyfill/00-html5shiv.js @@ -5,8 +5,8 @@ */ /* eslint-disable */ -(function(window, document) { -/*jshint evil:true */ +(function (window, document) { + /*jshint evil:true */ /** version */ var version = '3.7.3'; @@ -17,7 +17,8 @@ var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; /** Not all elements can be cloned in IE **/ - var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; + var saveClones = + /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; /** Detect whether the browser supports default html5 styles */ var supportsHtml5Styles; @@ -34,30 +35,31 @@ /** Detect whether the browser supports unknown elements */ var supportsUnknownElements; - (function() { + (function () { try { - var a = document.createElement('a'); - a.innerHTML = ''; - //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles - supportsHtml5Styles = ('hidden' in a); + var a = document.createElement('a'); + a.innerHTML = ''; + //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles + supportsHtml5Styles = 'hidden' in a; - supportsUnknownElements = a.childNodes.length == 1 || (function() { + supportsUnknownElements = + a.childNodes.length == 1 || + (function () { // assign a false positive if unable to shiv - (document.createElement)('a'); + document.createElement('a'); var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); - }()); - } catch(e) { + })(); + } catch (e) { // assign a false positive if detection fails => unable to shiv supportsHtml5Styles = true; supportsUnknownElements = true; } - - }()); + })(); /*--------------------------------------------------------------------------*/ @@ -70,7 +72,7 @@ */ function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), - parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; + parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x'; return parent.insertBefore(p.lastChild, parent.firstChild); @@ -94,17 +96,17 @@ */ function addElements(newElements, ownerDocument) { var elements = html5.elements; - if(typeof elements != 'string'){ + if (typeof elements != 'string') { elements = elements.join(' '); } - if(typeof newElements != 'string'){ + if (typeof newElements != 'string') { newElements = newElements.join(' '); } - html5.elements = elements +' '+ newElements; + html5.elements = elements + ' ' + newElements; shivDocument(ownerDocument); } - /** + /** * Returns the data associated to the given document * @private * @param {Document} ownerDocument The document. @@ -113,10 +115,10 @@ function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { - data = {}; - expanID++; - ownerDocument[expando] = expanID; - expandoData[expanID] = data; + data = {}; + expanID++; + ownerDocument[expando] = expanID; + expandoData[expanID] = data; } return data; } @@ -128,24 +130,24 @@ * @param {Document|DocumentFragment} ownerDocument The context document. * @returns {Object} The shived element. */ - function createElement(nodeName, ownerDocument, data){ + function createElement(nodeName, ownerDocument, data) { if (!ownerDocument) { - ownerDocument = document; + ownerDocument = document; } - if(supportsUnknownElements){ - return ownerDocument.createElement(nodeName); + if (supportsUnknownElements) { + return ownerDocument.createElement(nodeName); } if (!data) { - data = getExpandoData(ownerDocument); + data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { - node = data.cache[nodeName].cloneNode(); + node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { - node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); + node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { - node = data.createElem(nodeName); + node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because @@ -164,20 +166,20 @@ * @param {Document} ownerDocument The context document. * @returns {Object} The shived DocumentFragment. */ - function createDocumentFragment(ownerDocument, data){ + function createDocumentFragment(ownerDocument, data) { if (!ownerDocument) { - ownerDocument = document; + ownerDocument = document; } - if(supportsUnknownElements){ - return ownerDocument.createDocumentFragment(); + if (supportsUnknownElements) { + return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), - i = 0, - elems = getElements(), - l = elems.length; - for(;i>> 0); + var dataScope = 'data-scope-' + ((Math.random() * 1e9) >>> 0); var proto = Element.prototype; var querySelector = proto.querySelector; var querySelectorAll = proto.querySelectorAll; @@ -732,80 +684,76 @@ node.setAttribute(dataScope, null); var result = method.call( node, - String(css).replace( - /(^|,\s*)(:scope([ >]|$))/g, - function ($0, $1, $2, $3) { - return $1 + '[' + dataScope + ']' + ($3 || ' '); - } - ) + String(css).replace(/(^|,\s*)(:scope([ >]|$))/g, function ($0, $1, $2, $3) { + return $1 + '[' + dataScope + ']' + ($3 || ' '); + }) ); node.removeAttribute(dataScope); return result; } - }()); + })(); } -}(window)); -(function (global){'use strict'; +})(window); +(function (global) { + 'use strict'; // a WeakMap fallback for DOM nodes only used as key - var DOMMap = global.WeakMap || (function () { + var DOMMap = + global.WeakMap || + (function () { + var counter = 0, + dispatched = false, + drop = false, + value; - var - counter = 0, - dispatched = false, - drop = false, - value - ; - - function dispatch(key, ce, shouldDrop) { - drop = shouldDrop; - dispatched = false; - value = undefined; - key.dispatchEvent(ce); - } - - function Handler(value) { - this.value = value; - } - - Handler.prototype.handleEvent = function handleEvent(e) { - dispatched = true; - if (drop) { - e.currentTarget.removeEventListener(e.type, this, false); - } else { - value = this.value; - } - }; - - function DOMMap() { - counter++; // make id clashing highly improbable - this.__ce__ = new Event(('@DOMMap:' + counter) + Math.random()); - } - - DOMMap.prototype = { - 'constructor': DOMMap, - 'delete': function del(key) { - return dispatch(key, this.__ce__, true), dispatched; - }, - 'get': function get(key) { - dispatch(key, this.__ce__, false); - var v = value; + function dispatch(key, ce, shouldDrop) { + drop = shouldDrop; + dispatched = false; value = undefined; - return v; - }, - 'has': function has(key) { - return dispatch(key, this.__ce__, false), dispatched; - }, - 'set': function set(key, value) { - dispatch(key, this.__ce__, true); - key.addEventListener(this.__ce__.type, new Handler(value), false); - return this; - }, - }; + key.dispatchEvent(ce); + } - return DOMMap; + function Handler(value) { + this.value = value; + } - }()); + Handler.prototype.handleEvent = function handleEvent(e) { + dispatched = true; + if (drop) { + e.currentTarget.removeEventListener(e.type, this, false); + } else { + value = this.value; + } + }; + + function DOMMap() { + counter++; // make id clashing highly improbable + this.__ce__ = new Event('@DOMMap:' + counter + Math.random()); + } + + DOMMap.prototype = { + 'constructor': DOMMap, + 'delete': function del(key) { + return dispatch(key, this.__ce__, true), dispatched; + }, + 'get': function get(key) { + dispatch(key, this.__ce__, false); + var v = value; + value = undefined; + return v; + }, + 'has': function has(key) { + return dispatch(key, this.__ce__, false), dispatched; + }, + 'set': function set(key, value) { + dispatch(key, this.__ce__, true); + key.addEventListener(this.__ce__.type, new Handler(value), false); + return this; + }, + }; + + return DOMMap; + })(); function Dict() {} Dict.prototype = (Object.create || Object)(null); @@ -815,11 +763,7 @@ function createEventListener(type, callback, options) { function eventListener(e) { if (eventListener.once) { - e.currentTarget.removeEventListener( - e.type, - callback, - eventListener - ); + e.currentTarget.removeEventListener(e.type, callback, eventListener); eventListener.removed = true; } if (eventListener.passive) { @@ -847,38 +791,36 @@ createEventListener.preventDefault = function preventDefault() {}; - var - Event = global.CustomEvent, + var Event = global.CustomEvent, dE = global.dispatchEvent, aEL = global.addEventListener, rEL = global.removeEventListener, counter = 0, - increment = function () { counter++; }, - indexOf = [].indexOf || function indexOf(value){ - var length = this.length; - while(length--) { - if (this[length] === value) { - break; + increment = function () { + counter++; + }, + indexOf = + [].indexOf || + function indexOf(value) { + var length = this.length; + while (length--) { + if (this[length] === value) { + break; + } } - } - return length; - }, + return length; + }, getListenerKey = function (options) { - return ''.concat( - options.capture ? '1' : '0', - options.passive ? '1' : '0', - options.once ? '1' : '0' - ); + return ''.concat(options.capture ? '1' : '0', options.passive ? '1' : '0', options.once ? '1' : '0'); }, - augment - ; + augment; try { - aEL('_', increment, {once: true}); + aEL('_', increment, { once: true }); dE(new Event('_')); dE(new Event('_')); - rEL('_', increment, {once: true}); - } catch(o_O) {} + rEL('_', increment, { once: true }); + } catch (o_O) {} if (counter !== 1) { (function () { @@ -886,21 +828,22 @@ function createAEL(aEL) { return function addEventListener(type, handler, options) { if (options && typeof options !== 'boolean') { - var - info = dm.get(this), + var info = dm.get(this), key = getListenerKey(options), - i, tmp, wrap - ; + i, + tmp, + wrap; if (!info) dm.set(this, (info = new Dict())); - if (!(type in info)) info[type] = { - handler: [], - wrap: [] - }; + if (!(type in info)) + info[type] = { + handler: [], + wrap: [], + }; tmp = info[type]; i = indexOf.call(tmp.handler, handler); if (i < 0) { i = tmp.handler.push(handler) - 1; - tmp.wrap[i] = (wrap = new Dict()); + tmp.wrap[i] = wrap = new Dict(); } else { wrap = tmp.wrap[i]; } @@ -916,11 +859,12 @@ function createREL(rEL) { return function removeEventListener(type, handler, options) { if (options && typeof options !== 'boolean') { - var - info = dm.get(this), - key, i, tmp, wrap - ; - if (info && (type in info)) { + var info = dm.get(this), + key, + i, + tmp, + wrap; + if (info && type in info) { tmp = info[type]; i = indexOf.call(tmp.handler, handler); if (-1 < i) { @@ -960,11 +904,9 @@ augment(global.Text); augment(global.Element || global.HTMLElement); augment(global.HTMLDocument); - augment(global.Window || {prototype:global}); + augment(global.Window || { prototype: global }); augment(global.XMLHttpRequest); } - - }()); + })(); } - -}(window)); +})(window); diff --git a/tgui/packages/tgui-polyfill/03-css-om.js b/tgui/packages/tgui-polyfill/03-css-om.js index 757d14f9285..534265e6f77 100644 --- a/tgui/packages/tgui-polyfill/03-css-om.js +++ b/tgui/packages/tgui-polyfill/03-css-om.js @@ -9,7 +9,7 @@ */ /* eslint-disable */ -(function(Proto) { +(function (Proto) { 'use strict'; if (typeof Proto.setAttribute !== 'undefined') { @@ -40,5 +40,4 @@ return value; }; } - })(CSSStyleDeclaration.prototype); diff --git a/tgui/packages/tgui-polyfill/10-misc.js b/tgui/packages/tgui-polyfill/10-misc.js index 5a1849e1355..f2d69f288cf 100644 --- a/tgui/packages/tgui-polyfill/10-misc.js +++ b/tgui/packages/tgui-polyfill/10-misc.js @@ -9,23 +9,24 @@ 'use strict'; // Necessary polyfill to make Webpack code splitting work on IE8 - if (!Function.prototype.bind) (function () { - var slice = Array.prototype.slice; - Function.prototype.bind = function () { - var thatFunc = this, thatArg = arguments[0]; - var args = slice.call(arguments, 1); - if (typeof thatFunc !== 'function') { - // closest thing possible to the ECMAScript 5 - // internal IsCallable function - throw new TypeError('Function.prototype.bind - ' + - 'what is trying to be bound is not callable'); - } - return function () { - var funcArgs = args.concat(slice.call(arguments)) - return thatFunc.apply(thatArg, funcArgs); + if (!Function.prototype.bind) + (function () { + var slice = Array.prototype.slice; + Function.prototype.bind = function () { + var thatFunc = this, + thatArg = arguments[0]; + var args = slice.call(arguments, 1); + if (typeof thatFunc !== 'function') { + // closest thing possible to the ECMAScript 5 + // internal IsCallable function + throw new TypeError('Function.prototype.bind - ' + 'what is trying to be bound is not callable'); + } + return function () { + var funcArgs = args.concat(slice.call(arguments)); + return thatFunc.apply(thatArg, funcArgs); + }; }; - }; - })(); + })(); if (!Array.prototype['forEach']) { Array.prototype.forEach = function (callback, thisArg) { @@ -35,7 +36,7 @@ var T, k; var O = Object(this); var len = O.length >>> 0; - if (typeof callback !== "function") { + if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { @@ -57,5 +58,4 @@ if (!window.Int32Array) { window.Int32Array = Array; } - })(); diff --git a/tgui/packages/tgui/assets.js b/tgui/packages/tgui/assets.js index db6dd635c01..f41181e078f 100644 --- a/tgui/packages/tgui/assets.js +++ b/tgui/packages/tgui/assets.js @@ -7,11 +7,9 @@ const EXCLUDED_PATTERNS = [/v4shim/i]; const loadedMappings = {}; -export const resolveAsset = name => ( - loadedMappings[name] || name -); +export const resolveAsset = (name) => loadedMappings[name] || name; -export const assetMiddleware = store => next => action => { +export const assetMiddleware = (store) => (next) => (action) => { const { type, payload } = action; if (type === 'asset/stylesheet') { Byond.loadCss(payload); @@ -20,7 +18,7 @@ export const assetMiddleware = store => next => action => { if (type === 'asset/mappings') { for (let name of Object.keys(payload)) { // Skip anything that matches excluded patterns - if (EXCLUDED_PATTERNS.some(regex => regex.test(name))) { + if (EXCLUDED_PATTERNS.some((regex) => regex.test(name))) { continue; } const url = payload[name]; diff --git a/tgui/packages/tgui/backend.ts b/tgui/packages/tgui/backend.ts index 2b3499bfac5..8e483ebfe1f 100644 --- a/tgui/packages/tgui/backend.ts +++ b/tgui/packages/tgui/backend.ts @@ -62,8 +62,7 @@ export const backendReducer = (state = initialState, action) => { const value = payload.shared[key]; if (value === '') { shared[key] = undefined; - } - else { + } else { shared[key] = JSON.parse(value); } } @@ -115,11 +114,11 @@ export const backendReducer = (state = initialState, action) => { return state; }; -export const backendMiddleware = store => { +export const backendMiddleware = (store) => { let fancyState; let suspendInterval; - return next => action => { + return (next) => (action) => { const { suspended } = selectBackend(store.getState()); const { type, payload } = action; @@ -196,8 +195,7 @@ export const backendMiddleware = store => { }); perf.mark('resume/finish'); if (process.env.NODE_ENV !== 'production') { - logger.log('visible in', - perf.measure('render/finish', 'resume/finish')); + logger.log('visible in', perf.measure('render/finish', 'resume/finish')); } }); } @@ -212,9 +210,7 @@ export const backendMiddleware = store => { */ export const sendAct = (action: string, payload: object = {}) => { // Validate that payload is an object - const isObject = typeof payload === 'object' - && payload !== null - && !Array.isArray(payload); + const isObject = typeof payload === 'object' && payload !== null && !Array.isArray(payload); if (!isObject) { logger.error(`Payload for act() must be an object, got this:`, payload); return; @@ -224,38 +220,36 @@ export const sendAct = (action: string, payload: object = {}) => { type BackendState = { config: { - title: string, - status: number, - interface: string, - refreshing: boolean, + title: string; + status: number; + interface: string; + refreshing: boolean; window: { - key: string, - size: [number, number], - fancy: boolean, - locked: boolean, - }, + key: string; + size: [number, number]; + fancy: boolean; + locked: boolean; + }; client: { - ckey: string, - address: string, - computer_id: string, - }, + ckey: string; + address: string; + computer_id: string; + }; user: { - name: string, - observer: number, - }, - }, - data: TData, - shared: Record, - suspending: boolean, - suspended: boolean, + name: string; + observer: number; + }; + }; + data: TData; + shared: Record; + suspending: boolean; + suspended: boolean; }; /** * Selects a backend-related slice of Redux state */ -export const selectBackend = (state: any): BackendState => ( - state.backend || {} -); +export const selectBackend = (state: any): BackendState => state.backend || {}; /** * Get data from tgui backend. @@ -289,28 +283,20 @@ type StateWithSetter = [T, (nextState: T) => void]; * @param key Key which uniquely identifies this state in Redux store. * @param initialState Initializes your global variable with this value. */ -export const useLocalState = ( - context: any, - key: string, - initialState: T, -): StateWithSetter => { +export const useLocalState = (context: any, key: string, initialState: T): StateWithSetter => { const { store } = context; const state = selectBackend(store.getState()); const sharedStates = state.shared ?? {}; - const sharedState = (key in sharedStates) - ? sharedStates[key] - : initialState; + const sharedState = key in sharedStates ? sharedStates[key] : initialState; return [ sharedState, - nextState => { - store.dispatch(backendSetSharedState({ - key, - nextState: ( - typeof nextState === 'function' - ? nextState(sharedState) - : nextState - ), - })); + (nextState) => { + store.dispatch( + backendSetSharedState({ + key, + nextState: typeof nextState === 'function' ? nextState(sharedState) : nextState, + }) + ); }, ]; }; @@ -329,28 +315,18 @@ export const useLocalState = ( * @param key Key which uniquely identifies this state in Redux store. * @param initialState Initializes your global variable with this value. */ -export const useSharedState = ( - context: any, - key: string, - initialState: T, -): StateWithSetter => { +export const useSharedState = (context: any, key: string, initialState: T): StateWithSetter => { const { store } = context; const state = selectBackend(store.getState()); const sharedStates = state.shared ?? {}; - const sharedState = (key in sharedStates) - ? sharedStates[key] - : initialState; + const sharedState = key in sharedStates ? sharedStates[key] : initialState; return [ sharedState, - nextState => { + (nextState) => { Byond.sendMessage({ type: 'setSharedState', key, - value: JSON.stringify( - typeof nextState === 'function' - ? nextState(sharedState) - : nextState - ) || '', + value: JSON.stringify(typeof nextState === 'function' ? nextState(sharedState) : nextState) || '', }); }, ]; diff --git a/tgui/packages/tgui/components/AnimatedNumber.js b/tgui/packages/tgui/components/AnimatedNumber.js index 05b89c96d02..0258609e585 100644 --- a/tgui/packages/tgui/components/AnimatedNumber.js +++ b/tgui/packages/tgui/components/AnimatedNumber.js @@ -10,10 +10,8 @@ import { Component } from 'inferno'; const FPS = 20; const Q = 0.5; -const isSafeNumber = value => { - return typeof value === 'number' - && Number.isFinite(value) - && !Number.isNaN(value); +const isSafeNumber = (value) => { + return typeof value === 'number' && Number.isFinite(value) && !Number.isNaN(value); }; export class AnimatedNumber extends Component { diff --git a/tgui/packages/tgui/components/Autofocus.tsx b/tgui/packages/tgui/components/Autofocus.tsx index f5ae00650aa..28945dd7aa4 100644 --- a/tgui/packages/tgui/components/Autofocus.tsx +++ b/tgui/packages/tgui/components/Autofocus.tsx @@ -1,4 +1,4 @@ -import { Component, createRef } from "inferno"; +import { Component, createRef } from 'inferno'; export class Autofocus extends Component { ref = createRef(); diff --git a/tgui/packages/tgui/components/Blink.js b/tgui/packages/tgui/components/Blink.js index 1f1fd908318..f81ecef8b45 100644 --- a/tgui/packages/tgui/components/Blink.js +++ b/tgui/packages/tgui/components/Blink.js @@ -12,10 +12,7 @@ export class Blink extends Component { } createTimer() { - const { - interval = DEFAULT_BLINKING_INTERVAL, - time = DEFAULT_BLINKING_TIME, - } = this.props; + const { interval = DEFAULT_BLINKING_INTERVAL, time = DEFAULT_BLINKING_TIME } = this.props; clearInterval(this.interval); clearTimeout(this.timer); @@ -42,8 +39,7 @@ export class Blink extends Component { } componentDidUpdate(prevProps) { - if (prevProps.interval !== this.props.interval - || prevProps.time !== this.props.time) { + if (prevProps.interval !== this.props.interval || prevProps.time !== this.props.time) { this.createTimer(); } } @@ -55,9 +51,10 @@ export class Blink extends Component { render(props) { return ( - + {props.children} ); diff --git a/tgui/packages/tgui/components/BlockQuote.js b/tgui/packages/tgui/components/BlockQuote.js index 62a05215728..8c0f53a46a1 100644 --- a/tgui/packages/tgui/components/BlockQuote.js +++ b/tgui/packages/tgui/components/BlockQuote.js @@ -7,14 +7,7 @@ import { classes } from 'common/react'; import { Box } from './Box'; -export const BlockQuote = props => { +export const BlockQuote = (props) => { const { className, ...rest } = props; - return ( - - ); + return ; }; diff --git a/tgui/packages/tgui/components/Box.tsx b/tgui/packages/tgui/components/Box.tsx index bcd8447c8b2..441ec43cacd 100644 --- a/tgui/packages/tgui/components/Box.tsx +++ b/tgui/packages/tgui/components/Box.tsx @@ -60,17 +60,17 @@ export interface BoxProps { backgroundColor?: string | BooleanLike; // VOREStation Addition Start // Flex props - order?: string | BooleanLike, - flexDirection?: string | BooleanLike, - flexGrow?: string | BooleanLike, - flexShrink?: string | BooleanLike, - flexWrap?: string | BooleanLike, - flexFlow?: string | BooleanLike, - flexBasis?: string | BooleanLike, - flex?: string | BooleanLike, - alignItems?: string | BooleanLike, - justifyContent?: string | BooleanLike, - alignSelf?: string | BooleanLike, + order?: string | BooleanLike; + flexDirection?: string | BooleanLike; + flexGrow?: string | BooleanLike; + flexShrink?: string | BooleanLike; + flexWrap?: string | BooleanLike; + flexFlow?: string | BooleanLike; + flexBasis?: string | BooleanLike; + flex?: string | BooleanLike; + alignItems?: string | BooleanLike; + justifyContent?: string | BooleanLike; + alignSelf?: string | BooleanLike; // VOREStation Addition End fillPositionedParent?: boolean; } @@ -109,10 +109,10 @@ export const halfUnit = (value: unknown): string | undefined => { const isColorCode = (str: unknown) => !isColorClass(str); const isColorClass = (str: unknown): boolean => { - return typeof str === "string" && CSS_COLORS.includes(str); + return typeof str === 'string' && CSS_COLORS.includes(str); }; -const mapRawPropTo = attrName => (style, value) => { +const mapRawPropTo = (attrName) => (style, value) => { if (typeof value === 'number' || typeof value === 'string') { style[attrName] = value; } @@ -138,7 +138,7 @@ const mapDirectionalUnitPropTo = (attrName, unit, dirs) => (style, value) => { } }; -const mapColorPropTo = attrName => (style, value) => { +const mapColorPropTo = (attrName) => (style, value) => { if (isColorCode(value)) { style[attrName] = value; } @@ -165,8 +165,7 @@ const styleMapperByPropName = { lineHeight: (style, value) => { if (typeof value === 'number') { style['line-height'] = value; - } - else if (typeof value === 'string') { + } else if (typeof value === 'string') { style['line-height'] = unit(value); } }, @@ -182,29 +181,17 @@ const styleMapperByPropName = { nowrap: mapBooleanPropTo('white-space', 'nowrap'), preserveWhitespace: mapBooleanPropTo('white-space', 'pre-wrap'), // Margins - m: mapDirectionalUnitPropTo('margin', halfUnit, [ - 'top', 'bottom', 'left', 'right', - ]), - mx: mapDirectionalUnitPropTo('margin', halfUnit, [ - 'left', 'right', - ]), - my: mapDirectionalUnitPropTo('margin', halfUnit, [ - 'top', 'bottom', - ]), + m: mapDirectionalUnitPropTo('margin', halfUnit, ['top', 'bottom', 'left', 'right']), + mx: mapDirectionalUnitPropTo('margin', halfUnit, ['left', 'right']), + my: mapDirectionalUnitPropTo('margin', halfUnit, ['top', 'bottom']), mt: mapUnitPropTo('margin-top', halfUnit), mb: mapUnitPropTo('margin-bottom', halfUnit), ml: mapUnitPropTo('margin-left', halfUnit), mr: mapUnitPropTo('margin-right', halfUnit), // Margins - p: mapDirectionalUnitPropTo('padding', halfUnit, [ - 'top', 'bottom', 'left', 'right', - ]), - px: mapDirectionalUnitPropTo('padding', halfUnit, [ - 'left', 'right', - ]), - py: mapDirectionalUnitPropTo('padding', halfUnit, [ - 'top', 'bottom', - ]), + p: mapDirectionalUnitPropTo('padding', halfUnit, ['top', 'bottom', 'left', 'right']), + px: mapDirectionalUnitPropTo('padding', halfUnit, ['left', 'right']), + py: mapDirectionalUnitPropTo('padding', halfUnit, ['top', 'bottom']), pt: mapUnitPropTo('padding-top', halfUnit), pb: mapUnitPropTo('padding-bottom', halfUnit), pl: mapUnitPropTo('padding-left', halfUnit), @@ -256,8 +243,7 @@ export const computeBoxProps = (props: BoxProps) => { const mapPropToStyle = styleMapperByPropName[propName]; if (mapPropToStyle) { mapPropToStyle(computedStyles, propValue); - } - else { + } else { computedProps[propName] = propValue; } } @@ -289,19 +275,13 @@ export const computeBoxClassName = (props: BoxProps) => { }; export const Box: SFC = (props: BoxProps) => { - const { - as = 'div', - className, - children, - ...rest - } = props; + const { as = 'div', className, children, ...rest } = props; // Render props if (typeof children === 'function') { return children(computeBoxProps(props)); } - const computedClassName = typeof className === 'string' - ? className + ' ' + computeBoxClassName(rest) - : computeBoxClassName(rest); + const computedClassName = + typeof className === 'string' ? className + ' ' + computeBoxClassName(rest) : computeBoxClassName(rest); const computedProps = computeBoxProps(rest); // Render a wrapper element return createVNode( @@ -311,7 +291,7 @@ export const Box: SFC = (props: BoxProps) => { children, ChildFlags.UnknownChildren, computedProps, - undefined, + undefined ); }; diff --git a/tgui/packages/tgui/components/Button.js b/tgui/packages/tgui/components/Button.js index 58c3dc76970..05abfc39ee1 100644 --- a/tgui/packages/tgui/components/Button.js +++ b/tgui/packages/tgui/components/Button.js @@ -14,7 +14,7 @@ import { Tooltip } from './Tooltip'; const logger = createLogger('Button'); -export const Button = props => { +export const Button = (props) => { const { className, fluid, @@ -42,12 +42,13 @@ export const Button = props => { // A warning about the lowercase onclick if (onclick) { logger.warn( - `Lowercase 'onclick' is not supported on Button and lowercase` - + ` prop names are discouraged in general. Please use a camelCase` - + `'onClick' instead and read: ` - + `https://infernojs.org/docs/guides/event-handling`); + `Lowercase 'onclick' is not supported on Button and lowercase` + + ` prop names are discouraged in general. Please use a camelCase` + + `'onClick' instead and read: ` + + `https://infernojs.org/docs/guides/event-handling` + ); } - rest.onClick = e => { + rest.onClick = (e) => { if (!disabled && onClick) { onClick(e); } @@ -68,14 +69,12 @@ export const Button = props => { circular && 'Button--circular', compact && 'Button--compact', iconPosition && 'Button--iconPosition--' + iconPosition, - (color && typeof color === 'string') - ? 'Button--color--' + color - : 'Button--color--default', + color && typeof color === 'string' ? 'Button--color--' + color : 'Button--color--default', className, computeBoxClassName(rest), ])} tabIndex={!disabled && '0'} - onKeyDown={e => { + onKeyDown={(e) => { if (props.captureKeys === false) { return; } @@ -96,16 +95,12 @@ export const Button = props => { } }} {...computeBoxProps(rest)}> - {(icon && iconPosition !== 'right') && ( - + {icon && iconPosition !== 'right' && ( + )} {content} {children} - {(icon && iconPosition === 'right') && ( + {icon && iconPosition === 'right' && ( { Button.defaultHooks = pureComponentHooks; -export const ButtonCheckbox = props => { +export const ButtonCheckbox = (props) => { const { checked, ...rest } = props; - return ( - - {buttons && ( -
- {buttons} -
- )} + {buttons &&
{buttons}
} - {open && ( - - {children} - - )} + {open && {children}}
); } diff --git a/tgui/packages/tgui/components/ColorBox.js b/tgui/packages/tgui/components/ColorBox.js index 10306cf4654..641e5fa751e 100644 --- a/tgui/packages/tgui/components/ColorBox.js +++ b/tgui/packages/tgui/components/ColorBox.js @@ -7,25 +7,12 @@ import { classes, pureComponentHooks } from 'common/react'; import { computeBoxClassName, computeBoxProps } from './Box'; -export const ColorBox = props => { - const { - content, - children, - className, - color, - backgroundColor, - ...rest - } = props; +export const ColorBox = (props) => { + const { content, children, className, color, backgroundColor, ...rest } = props; rest.color = content ? null : 'transparent'; rest.backgroundColor = color || backgroundColor; return ( -
+
{content || '.'}
); diff --git a/tgui/packages/tgui/components/Dimmer.js b/tgui/packages/tgui/components/Dimmer.js index d97c3626a3e..85e046ca0db 100644 --- a/tgui/packages/tgui/components/Dimmer.js +++ b/tgui/packages/tgui/components/Dimmer.js @@ -7,18 +7,11 @@ import { classes } from 'common/react'; import { Box } from './Box'; -export const Dimmer = props => { +export const Dimmer = (props) => { const { className, children, ...rest } = props; return ( - -
- {children} -
+ +
{children}
); }; diff --git a/tgui/packages/tgui/components/Divider.js b/tgui/packages/tgui/components/Divider.js index b5338428263..8cbf9b77d7d 100644 --- a/tgui/packages/tgui/components/Divider.js +++ b/tgui/packages/tgui/components/Divider.js @@ -6,19 +6,15 @@ import { classes } from 'common/react'; -export const Divider = props => { - const { - vertical, - hidden, - } = props; +export const Divider = (props) => { + const { vertical, hidden } = props; return ( - )); + ); } // VOREStation addition end return ops.length ? ops : 'No Options Found'; @@ -93,24 +92,20 @@ export class Dropdown extends Component { placeholder, // VOREStation Addition ...boxProps } = props; - const { - className, - ...rest - } = boxProps; + const { className, ...rest } = boxProps; const adjustedOpen = over ? !this.state.open : this.state.open; const menu = this.state.open ? (
{ this.menuRef = menu; }} + ref={(menu) => { + this.menuRef = menu; + }} tabIndex="-1" style={{ 'width': width, }} - className={classes([ - noscroll && 'Dropdown__menu-noscroll' || 'Dropdown__menu', - over && 'Dropdown__over', - ])}> + className={classes([(noscroll && 'Dropdown__menu-noscroll') || 'Dropdown__menu', over && 'Dropdown__over'])}> {this.buildMenu()}
) : null; @@ -133,15 +128,9 @@ export class Dropdown extends Component { } this.setOpen(!this.state.open); }}> - {icon && ( - - )} + {icon && } - {displayText ? displayText : (this.state.selected || placeholder) /* VOREStation Edit */ } + {displayText ? displayText : this.state.selected || placeholder /* VOREStation Edit */} {!!nochevron || ( diff --git a/tgui/packages/tgui/components/Flex.tsx b/tgui/packages/tgui/components/Flex.tsx index 95379ea587e..915047bd9c7 100644 --- a/tgui/packages/tgui/components/Flex.tsx +++ b/tgui/packages/tgui/components/Flex.tsx @@ -50,17 +50,9 @@ export const computeFlexProps = (props: FlexProps) => { }); }; -export const Flex = props => { +export const Flex = (props) => { const { className, ...rest } = props; - return ( -
- ); + return
; }; Flex.defaultHooks = pureComponentHooks; @@ -74,11 +66,7 @@ export type FlexItemProps = BoxProps & { }; export const computeFlexItemClassName = (props: FlexItemProps) => { - return classes([ - 'Flex__item', - Byond.IS_LTE_IE10 && 'Flex__item--iefix', - computeBoxClassName(props), - ]); + return classes(['Flex__item', Byond.IS_LTE_IE10 && 'Flex__item--iefix', computeBoxClassName(props)]); }; export const computeFlexItemProps = (props: FlexItemProps) => { @@ -107,15 +95,11 @@ export const computeFlexItemProps = (props: FlexItemProps) => { }); }; -const FlexItem = props => { +const FlexItem = (props) => { const { className, ...rest } = props; return (
); diff --git a/tgui/packages/tgui/components/Grid.js b/tgui/packages/tgui/components/Grid.js index 3269b672006..7ad3fd1dfdb 100644 --- a/tgui/packages/tgui/components/Grid.js +++ b/tgui/packages/tgui/components/Grid.js @@ -8,13 +8,11 @@ import { Table } from './Table'; import { pureComponentHooks } from 'common/react'; /** @deprecated */ -export const Grid = props => { +export const Grid = (props) => { const { children, ...rest } = props; return ( - - {children} - + {children}
); }; @@ -22,7 +20,7 @@ export const Grid = props => { Grid.defaultHooks = pureComponentHooks; /** @deprecated */ -export const GridColumn = props => { +export const GridColumn = (props) => { const { size = 1, style, ...rest } = props; return ( { width: size + '%', ...style, }} - {...rest} /> + {...rest} + /> ); }; diff --git a/tgui/packages/tgui/components/Icon.js b/tgui/packages/tgui/components/Icon.js index 98a40bf5d94..ef02b1059d2 100644 --- a/tgui/packages/tgui/components/Icon.js +++ b/tgui/packages/tgui/components/Icon.js @@ -11,22 +11,14 @@ import { computeBoxClassName, computeBoxProps } from './Box'; const FA_OUTLINE_REGEX = /-o$/; -export const Icon = props => { - const { - name, - size, - spin, - className, - rotation, - inverse, - ...rest - } = props; +export const Icon = (props) => { + const { name, size, spin, className, rotation, inverse, ...rest } = props; if (size) { if (!rest.style) { rest.style = {}; } - rest.style['font-size'] = (size * 100) + '%'; + rest.style['font-size'] = size * 100 + '%'; } if (typeof rotation === 'number') { if (!rest.style) { @@ -37,44 +29,25 @@ export const Icon = props => { const boxProps = computeBoxProps(rest); - let iconClass = ""; - if (name.startsWith("tg-")) { + let iconClass = ''; + if (name.startsWith('tg-')) { // tgfont icon iconClass = name; } else { // font awesome icon const faRegular = FA_OUTLINE_REGEX.test(name); const faName = name.replace(FA_OUTLINE_REGEX, ''); - iconClass = (faRegular ? 'far ' : 'fas ') + 'fa-'+ faName + (spin ? " fa-spin" : ""); + iconClass = (faRegular ? 'far ' : 'fas ') + 'fa-' + faName + (spin ? ' fa-spin' : ''); } - return ( - - ); + return ; }; Icon.defaultHooks = pureComponentHooks; -export const IconStack = props => { - const { - className, - children, - ...rest - } = props; +export const IconStack = (props) => { + const { className, children, ...rest } = props; return ( - + {children} ); diff --git a/tgui/packages/tgui/components/InfinitePlane.js b/tgui/packages/tgui/components/InfinitePlane.js index 55273137bbe..a14c4781560 100644 --- a/tgui/packages/tgui/components/InfinitePlane.js +++ b/tgui/packages/tgui/components/InfinitePlane.js @@ -1,7 +1,7 @@ -import { computeBoxProps } from "./Box"; -import { Stack } from "./Stack"; -import { ProgressBar } from "./ProgressBar"; -import { Button } from "./Button"; +import { computeBoxProps } from './Box'; +import { Stack } from './Stack'; +import { ProgressBar } from './ProgressBar'; +import { Button } from './Button'; import { Component } from 'inferno'; const ZOOM_MIN_VAL = 0.5; @@ -33,19 +33,19 @@ export class InfinitePlane extends Component { } componentDidMount() { - window.addEventListener("mouseup", this.onMouseUp); + window.addEventListener('mouseup', this.onMouseUp); - window.addEventListener("mousedown", this.doOffsetMouse); - window.addEventListener("mousemove", this.doOffsetMouse); - window.addEventListener("mouseup", this.doOffsetMouse); + window.addEventListener('mousedown', this.doOffsetMouse); + window.addEventListener('mousemove', this.doOffsetMouse); + window.addEventListener('mouseup', this.doOffsetMouse); } componentWillUnmount() { - window.removeEventListener("mouseup", this.onMouseUp); + window.removeEventListener('mouseup', this.onMouseUp); - window.removeEventListener("mousedown", this.doOffsetMouse); - window.removeEventListener("mousemove", this.doOffsetMouse); - window.removeEventListener("mouseup", this.doOffsetMouse); + window.removeEventListener('mousedown', this.doOffsetMouse); + window.removeEventListener('mousemove', this.doOffsetMouse); + window.removeEventListener('mouseup', this.doOffsetMouse); } doOffsetMouse(event) { @@ -82,17 +82,8 @@ export class InfinitePlane extends Component { } render() { - const { - children, - backgroundImage, - imageWidth, - ...rest - } = this.props; - const { - left, - top, - zoom, - } = this.state; + const { children, backgroundImage, imageWidth, ...rest } = this.props; + const { left, top, zoom } = this.state; return (
+ })}>
+ 'position': 'fixed', + 'transform': `translate(${left}px, ${top}px) scale(${zoom})`, + 'transform-origin': 'top left', + 'height': '100%', + 'width': '100%', + }}> {children}
- +
diff --git a/tgui/packages/tgui/components/LabeledControls.js b/tgui/packages/tgui/components/LabeledControls.js index b4f069192c5..2da7efe928d 100644 --- a/tgui/packages/tgui/components/LabeledControls.js +++ b/tgui/packages/tgui/components/LabeledControls.js @@ -6,47 +6,23 @@ import { Flex } from './Flex'; -export const LabeledControls = props => { - const { - children, - wrap, - ...rest - } = props; +export const LabeledControls = (props) => { + const { children, wrap, ...rest } = props; return ( - + {children} ); }; -const LabeledControlsItem = props => { - const { - label, - children, - mx = 1, - ...rest - } = props; +const LabeledControlsItem = (props) => { + const { label, children, mx = 1, ...rest } = props; return ( - + - - {children} - - - {label} - + {children} + {label} ); diff --git a/tgui/packages/tgui/components/LabeledList.tsx b/tgui/packages/tgui/components/LabeledList.tsx index 2b52eae5eae..0a06916ee0a 100644 --- a/tgui/packages/tgui/components/LabeledList.tsx +++ b/tgui/packages/tgui/components/LabeledList.tsx @@ -15,11 +15,7 @@ type LabeledListProps = { export const LabeledList = (props: LabeledListProps) => { const { children } = props; - return ( - - {children} -
- ); + return {children}
; }; LabeledList.defaultHooks = pureComponentHooks; @@ -31,9 +27,9 @@ type LabeledListItemProps = { color?: string | BooleanLike; textAlign?: string | BooleanLike; verticalAlign?: string | BooleanLike; // VOREStation Addition - buttons?: InfernoNode, + buttons?: InfernoNode; /** @deprecated */ - content?: any, + content?: any; children?: InfernoNode; }; @@ -51,19 +47,12 @@ const LabeledListItem = (props: LabeledListItemProps) => { ...rest // VOREStation Addition } = props; return ( - + + className={classes(['LabeledList__cell', 'LabeledList__label'])}> {label ? label + ':' : null} { color={color} textAlign={textAlign} verticalAlign={verticalAlign} // VOREStation Addition - className={classes([ - 'LabeledList__cell', - 'LabeledList__content', - ])} + className={classes(['LabeledList__cell', 'LabeledList__content'])} colSpan={buttons ? undefined : 2} - {...rest} /* VOREStation Addition*/> + {...rest} /* VOREStation Addition*/ + > {content} {children} - {buttons && ( - - {buttons} - - )} + {buttons && {buttons}} ); }; @@ -96,9 +79,7 @@ type LabeledListDividerProps = { }; const LabeledListDivider = (props: LabeledListDividerProps) => { - const padding = props.size - ? unit(Math.max(0, props.size - 1)) - : 0; + const padding = props.size ? unit(Math.max(0, props.size - 1)) : 0; return ( { +export const Modal = (props) => { const { className, children, @@ -18,7 +18,7 @@ export const Modal = props => { // VOREStation Addition Start let handleKeyDown; if (onEnter) { - handleKeyDown = e => { + handleKeyDown = (e) => { let key = e.which || e.keyCode; if (key === 13) { onEnter(e); @@ -27,15 +27,8 @@ export const Modal = props => { } // VOREStation Addition End return ( - -
+ +
{children}
diff --git a/tgui/packages/tgui/components/NanoMap.js b/tgui/packages/tgui/components/NanoMap.js index 888e590d1dd..6bb4c495929 100644 --- a/tgui/packages/tgui/components/NanoMap.js +++ b/tgui/packages/tgui/components/NanoMap.js @@ -1,10 +1,14 @@ import { Component } from 'inferno'; import { Box, Button, Icon, Tooltip, LabeledList, Slider } from '.'; -import { useBackend } from "../backend"; +import { useBackend } from '../backend'; -const pauseEvent = e => { - if (e.stopPropagation) { e.stopPropagation(); } - if (e.preventDefault) { e.preventDefault(); } +const pauseEvent = (e) => { + if (e.stopPropagation) { + e.stopPropagation(); + } + if (e.preventDefault) { + e.preventDefault(); + } e.cancelBubble = true; e.returnValue = false; return false; @@ -17,8 +21,8 @@ export class NanoMap extends Component { super(props); // Auto center based on window size - const Xcenter = (window.innerWidth / 2) - 256; - const Ycenter = (window.innerHeight / 2) - 256; + const Xcenter = window.innerWidth / 2 - 256; + const Ycenter = window.innerHeight / 2 - 256; this.state = { offsetX: Xcenter, @@ -31,7 +35,7 @@ export class NanoMap extends Component { }; // Dragging - this.handleDragStart = e => { + this.handleDragStart = (e) => { this.ref = e.target; this.setState({ dragging: false, @@ -43,8 +47,8 @@ export class NanoMap extends Component { pauseEvent(e); }; - this.handleDragMove = e => { - this.setState(prevState => { + this.handleDragMove = (e) => { + this.setState((prevState) => { const state = { ...prevState }; const newOffsetX = e.screenX - state.originX; const newOffsetY = e.screenY - state.originY; @@ -61,7 +65,7 @@ export class NanoMap extends Component { pauseEvent(e); }; - this.handleDragEnd = e => { + this.handleDragEnd = (e) => { this.setState({ dragging: false, originX: null, @@ -72,30 +76,38 @@ export class NanoMap extends Component { pauseEvent(e); }; - this.handleOnClick = e => { - let byondX = (e.offsetX/this.state.zoom)/zoomScale; - let byondY = 1-(e.offsetY/this.state.zoom)/zoomScale; // Byond origin is bottom left, this is top left - + this.handleOnClick = (e) => { + let byondX = e.offsetX / this.state.zoom / zoomScale; + let byondY = 1 - e.offsetY / this.state.zoom / zoomScale; // Byond origin is bottom left, this is top left + e.byondX = byondX; e.byondY = byondY; - if (typeof(this.props.onClick) === "function") { + if (typeof this.props.onClick === 'function') { this.props.onClick(e); } }; - + this.handleZoom = (_e, value) => { - this.setState(state => { + this.setState((state) => { const newZoom = Math.min(Math.max(value, 1), 8); let zoomDiff = (newZoom - state.zoom) * 1.5; state.zoom = newZoom; let newOffsetX = state.offsetX - 262 * zoomDiff; - if (newOffsetX < -500) { newOffsetX = -500; } - if (newOffsetX > 500) { newOffsetX = 500; } - + if (newOffsetX < -500) { + newOffsetX = -500; + } + if (newOffsetX > 500) { + newOffsetX = 500; + } + let newOffsetY = state.offsetY - 256 * zoomDiff; - if (newOffsetY < -200) { newOffsetY = -200; } - if (newOffsetY > 200) { newOffsetY = 200; } + if (newOffsetY < -200) { + newOffsetY = -200; + } + if (newOffsetY > 200) { + newOffsetY = 200; + } state.offsetX = newOffsetX; state.offsetY = newOffsetY; @@ -105,41 +117,34 @@ export class NanoMap extends Component { return state; }); }; - } render() { const { config } = useBackend(this.context); const { dragging, offsetX, offsetY, zoom = 1 } = this.state; const { children } = this.props; - - const mapUrl = config.map + "_nanomap_z" + config.mapZLevel + ".png"; + + const mapUrl = config.map + '_nanomap_z' + config.mapZLevel + '.png'; // (x * zoom), x Needs to be double the turf- map size. (for virgo, 140x140) - const mapSize = (zoomScale * zoom) + 'px'; + const mapSize = zoomScale * zoom + 'px'; const newStyle = { width: mapSize, height: mapSize, - "margin-top": offsetY + "px", - "margin-left": offsetX + "px", - "overflow": "hidden", - "position": "relative", - "background-image": "url(" + mapUrl + ")", - "background-size": "cover", - "background-repeat": "no-repeat", - "text-align": "center", - "cursor": dragging ? "move" : "auto", + 'margin-top': offsetY + 'px', + 'margin-left': offsetX + 'px', + 'overflow': 'hidden', + 'position': 'relative', + 'background-image': 'url(' + mapUrl + ')', + 'background-size': 'cover', + 'background-repeat': 'no-repeat', + 'text-align': 'center', + 'cursor': dragging ? 'move' : 'auto', }; return ( - - - {children} - + + {children} @@ -148,39 +153,27 @@ export class NanoMap extends Component { } const NanoMapMarker = (props, context) => { - const { - x, - y, - zoom = 1, - icon, - tooltip, - color, - onClick, - } = props; + const { x, y, zoom = 1, icon, tooltip, color, onClick } = props; - const handleOnClick = e => { + const handleOnClick = (e) => { pauseEvent(e); if (onClick) { onClick(e); } }; - const rx = ((x * 2 * zoom) - zoom) - 3; - const ry = ((y * 2 * zoom) - zoom) - 3; + const rx = x * 2 * zoom - zoom - 3; + const ry = y * 2 * zoom - zoom - 3; return (
- +
@@ -199,7 +192,7 @@ const NanoMapZoomer = (props, context) => { minValue="1" maxValue="8" stepPixelSize="10" - format={v => v + "x"} + format={(v) => v + 'x'} value={props.zoom} onDrag={(e, v) => props.onZoom(e, v)} /> @@ -207,14 +200,15 @@ const NanoMapZoomer = (props, context) => { {data.map_levels .sort((a, b) => Number(a) - Number(b)) - .map(level => ( + .map((level) => (