diff --git a/.devcontainer/Sonarr.code-workspace b/.devcontainer/Sonarr.code-workspace deleted file mode 100644 index a46158e44..000000000 --- a/.devcontainer/Sonarr.code-workspace +++ /dev/null @@ -1,13 +0,0 @@ -// This file is used to open the backend and frontend in the same workspace, which is necessary as -// the frontend has vscode settings that are distinct from the backend -{ - "folders": [ - { - "path": ".." - }, - { - "path": "../frontend" - } - ], - "settings": {} -} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 629a2aa21..000000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,19 +0,0 @@ -// For format details, see https://aka.ms/devcontainer.json. For config options, see the -// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet -{ - "name": "Sonarr", - "image": "mcr.microsoft.com/devcontainers/dotnet:1-6.0", - "features": { - "ghcr.io/devcontainers/features/node:1": { - "nodeGypDependencies": true, - "version": "16", - "nvmVersion": "latest" - } - }, - "forwardPorts": [8989], - "customizations": { - "vscode": { - "extensions": ["esbenp.prettier-vscode"] - } - } -} diff --git a/.editorconfig b/.editorconfig index 6d6c3a13f..5e19cc2d6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,274 +2,14 @@ # editorconfig.org root = true -# NOTE: Requires **VS2019 16.3** or later - -# Stylecop.ruleset -# Description: Rules for Sonarr - -# Code files -[*.cs] +[*.{cs}] charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 4 -# Sort using and Import directives with System.* appearing first -dotnet_sort_system_directives_first = true - -# Avoid "this." and "Me." if not necessary -dotnet_style_qualification_for_field = false:refactoring -dotnet_style_qualification_for_property = false:refactoring -dotnet_style_qualification_for_method = false:refactoring -dotnet_style_qualification_for_event = false:refactoring - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_switch_labels = true -csharp_indent_labels = flush_left - -dotnet_style_qualification_for_field = false:suggestion -dotnet_style_qualification_for_property = false:suggestion -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_event = false:suggestion -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# Prefer "var" everywhere -csharp_style_var_for_built_in_types = true -csharp_style_var_when_type_is_apparent = true -csharp_style_var_elsewhere = true -# Prefer "out" variables to be declared inline -csharp_style_inlined_variable_declaration = true - -# Using directive is unnecessary. -dotnet_diagnostic.IDE0005.severity = error -# Use var instead of explicit type -dotnet_diagnostic.IDE0007.severity = error -# Inline variable declaration -dotnet_diagnostic.IDE0018.severity = error - -# Stylecop Rules -dotnet_diagnostic.SA0001.severity = none -dotnet_diagnostic.SA1025.severity = none -dotnet_diagnostic.SA1101.severity = none -dotnet_diagnostic.SA1116.severity = none -dotnet_diagnostic.SA1118.severity = none -dotnet_diagnostic.SA1122.severity = none -dotnet_diagnostic.SA1201.severity = suggestion -dotnet_diagnostic.SA1202.severity = suggestion -dotnet_diagnostic.SA1204.severity = suggestion -dotnet_diagnostic.SA1300.severity = none -dotnet_diagnostic.SA1303.severity = none -dotnet_diagnostic.SA1304.severity = none -dotnet_diagnostic.SA1306.severity = none -dotnet_diagnostic.SA1309.severity = none -dotnet_diagnostic.SA1310.severity = none -dotnet_diagnostic.SA1401.severity = none -dotnet_diagnostic.SA1402.severity = none -dotnet_diagnostic.SA1404.severity = suggestion -dotnet_diagnostic.SA1405.severity = suggestion -dotnet_diagnostic.SA1406.severity = suggestion -dotnet_diagnostic.SA1410.severity = suggestion -dotnet_diagnostic.SA1411.severity = suggestion -dotnet_diagnostic.SA1413.severity = none -dotnet_diagnostic.SA1512.severity = none -dotnet_diagnostic.SA1516.severity = none -dotnet_diagnostic.SA1600.severity = none -dotnet_diagnostic.SA1601.severity = none -dotnet_diagnostic.SA1602.severity = none -dotnet_diagnostic.SA1604.severity = none -dotnet_diagnostic.SA1605.severity = none -dotnet_diagnostic.SA1606.severity = none -dotnet_diagnostic.SA1607.severity = none -dotnet_diagnostic.SA1608.severity = none -dotnet_diagnostic.SA1610.severity = none -dotnet_diagnostic.SA1611.severity = none -dotnet_diagnostic.SA1612.severity = none -dotnet_diagnostic.SA1613.severity = none -dotnet_diagnostic.SA1614.severity = none -dotnet_diagnostic.SA1615.severity = none -dotnet_diagnostic.SA1616.severity = none -dotnet_diagnostic.SA1617.severity = none -dotnet_diagnostic.SA1618.severity = none -dotnet_diagnostic.SA1619.severity = none -dotnet_diagnostic.SA1620.severity = none -dotnet_diagnostic.SA1621.severity = none -dotnet_diagnostic.SA1622.severity = none -dotnet_diagnostic.SA1623.severity = none -dotnet_diagnostic.SA1624.severity = none -dotnet_diagnostic.SA1625.severity = none -dotnet_diagnostic.SA1626.severity = none -dotnet_diagnostic.SA1627.severity = none -dotnet_diagnostic.SA1629.severity = none -dotnet_diagnostic.SA1633.severity = none -dotnet_diagnostic.SA1634.severity = none -dotnet_diagnostic.SA1635.severity = none -dotnet_diagnostic.SA1636.severity = none -dotnet_diagnostic.SA1637.severity = none -dotnet_diagnostic.SA1638.severity = none -dotnet_diagnostic.SA1640.severity = none -dotnet_diagnostic.SA1641.severity = none -dotnet_diagnostic.SA1642.severity = none -dotnet_diagnostic.SA1643.severity = none -dotnet_diagnostic.SA1648.severity = none -dotnet_diagnostic.SA1649.severity = none -dotnet_diagnostic.SA1651.severity = none -dotnet_diagnostic.SX1309.severity = warning - -# Microsoft Analyzers that fail and need to be sorted thru -dotnet_diagnostic.ASP0000.severity = suggestion -dotnet_diagnostic.CA1000.severity = suggestion -dotnet_diagnostic.CA1001.severity = suggestion -dotnet_diagnostic.CA1002.severity = suggestion -dotnet_diagnostic.CA1003.severity = suggestion -dotnet_diagnostic.CA1008.severity = suggestion -dotnet_diagnostic.CA1010.severity = suggestion -dotnet_diagnostic.CA1012.severity = suggestion -dotnet_diagnostic.CA1014.severity = suggestion -dotnet_diagnostic.CA1016.severity = suggestion -dotnet_diagnostic.CA1017.severity = suggestion -dotnet_diagnostic.CA1018.severity = suggestion -dotnet_diagnostic.CA1019.severity = suggestion -dotnet_diagnostic.CA1021.severity = suggestion -dotnet_diagnostic.CA1024.severity = suggestion -dotnet_diagnostic.CA1027.severity = suggestion -dotnet_diagnostic.CA1028.severity = suggestion -dotnet_diagnostic.CA1030.severity = suggestion -dotnet_diagnostic.CA1031.severity = suggestion -dotnet_diagnostic.CA1032.severity = suggestion -dotnet_diagnostic.CA1033.severity = suggestion -dotnet_diagnostic.CA1034.severity = suggestion -dotnet_diagnostic.CA1036.severity = suggestion -dotnet_diagnostic.CA1040.severity = suggestion -dotnet_diagnostic.CA1041.severity = suggestion -dotnet_diagnostic.CA1043.severity = suggestion -dotnet_diagnostic.CA1044.severity = suggestion -dotnet_diagnostic.CA1050.severity = suggestion -dotnet_diagnostic.CA1051.severity = suggestion -dotnet_diagnostic.CA1052.severity = suggestion -dotnet_diagnostic.CA1054.severity = suggestion -dotnet_diagnostic.CA1055.severity = suggestion -dotnet_diagnostic.CA1056.severity = suggestion -dotnet_diagnostic.CA1058.severity = suggestion -dotnet_diagnostic.CA1060.severity = suggestion -dotnet_diagnostic.CA1061.severity = suggestion -dotnet_diagnostic.CA1062.severity = suggestion -dotnet_diagnostic.CA1063.severity = suggestion -dotnet_diagnostic.CA1064.severity = suggestion -dotnet_diagnostic.CA1065.severity = suggestion -dotnet_diagnostic.CA1066.severity = suggestion -dotnet_diagnostic.CA1067.severity = suggestion -dotnet_diagnostic.CA1068.severity = suggestion -dotnet_diagnostic.CA1069.severity = suggestion -dotnet_diagnostic.CA1200.severity = suggestion -dotnet_diagnostic.CA1303.severity = suggestion -dotnet_diagnostic.CA1304.severity = suggestion -dotnet_diagnostic.CA1305.severity = suggestion -dotnet_diagnostic.CA1307.severity = suggestion -dotnet_diagnostic.CA1308.severity = suggestion -dotnet_diagnostic.CA1309.severity = suggestion -dotnet_diagnostic.CA1310.severity = suggestion -dotnet_diagnostic.CA1401.severity = suggestion -dotnet_diagnostic.CA1416.severity = suggestion -dotnet_diagnostic.CA1419.severity = suggestion -dotnet_diagnostic.CA1507.severity = suggestion -dotnet_diagnostic.CA1508.severity = suggestion -dotnet_diagnostic.CA1707.severity = suggestion -dotnet_diagnostic.CA1708.severity = suggestion -dotnet_diagnostic.CA1710.severity = suggestion -dotnet_diagnostic.CA1711.severity = suggestion -dotnet_diagnostic.CA1712.severity = suggestion -dotnet_diagnostic.CA1714.severity = suggestion -dotnet_diagnostic.CA1715.severity = suggestion -dotnet_diagnostic.CA1716.severity = suggestion -dotnet_diagnostic.CA1717.severity = suggestion -dotnet_diagnostic.CA1720.severity = suggestion -dotnet_diagnostic.CA1721.severity = suggestion -dotnet_diagnostic.CA1724.severity = suggestion -dotnet_diagnostic.CA1725.severity = suggestion -dotnet_diagnostic.CA1806.severity = suggestion -dotnet_diagnostic.CA1810.severity = suggestion -dotnet_diagnostic.CA1812.severity = suggestion -dotnet_diagnostic.CA1813.severity = suggestion -dotnet_diagnostic.CA1814.severity = suggestion -dotnet_diagnostic.CA1815.severity = suggestion -dotnet_diagnostic.CA1816.severity = suggestion -dotnet_diagnostic.CA1819.severity = suggestion -dotnet_diagnostic.CA1822.severity = suggestion -dotnet_diagnostic.CA1823.severity = suggestion -dotnet_diagnostic.CA1824.severity = suggestion -dotnet_diagnostic.CA1825.severity = suggestion -dotnet_diagnostic.CA2000.severity = suggestion -dotnet_diagnostic.CA2002.severity = suggestion -dotnet_diagnostic.CA2007.severity = suggestion -dotnet_diagnostic.CA2008.severity = suggestion -dotnet_diagnostic.CA2012.severity = suggestion -dotnet_diagnostic.CA2013.severity = suggestion -dotnet_diagnostic.CA2100.severity = suggestion -dotnet_diagnostic.CA2101.severity = suggestion -dotnet_diagnostic.CA2119.severity = suggestion -dotnet_diagnostic.CA2153.severity = suggestion -dotnet_diagnostic.CA2200.severity = suggestion -dotnet_diagnostic.CA2201.severity = suggestion -dotnet_diagnostic.CA2207.severity = suggestion -dotnet_diagnostic.CA2208.severity = suggestion -dotnet_diagnostic.CA2211.severity = suggestion -dotnet_diagnostic.CA2213.severity = suggestion -dotnet_diagnostic.CA2214.severity = suggestion -dotnet_diagnostic.CA2215.severity = suggestion -dotnet_diagnostic.CA2216.severity = suggestion -dotnet_diagnostic.CA2219.severity = suggestion -dotnet_diagnostic.CA2225.severity = suggestion -dotnet_diagnostic.CA2226.severity = suggestion -dotnet_diagnostic.CA2227.severity = suggestion -dotnet_diagnostic.CA2229.severity = suggestion -dotnet_diagnostic.CA2231.severity = suggestion -dotnet_diagnostic.CA2234.severity = suggestion -dotnet_diagnostic.CA2235.severity = suggestion -dotnet_diagnostic.CA2237.severity = suggestion -dotnet_diagnostic.CA2241.severity = suggestion -dotnet_diagnostic.CA2242.severity = suggestion -dotnet_diagnostic.CA2243.severity = suggestion -dotnet_diagnostic.CA2244.severity = suggestion -dotnet_diagnostic.CA2245.severity = suggestion -dotnet_diagnostic.CA2246.severity = suggestion -dotnet_diagnostic.CA2249.severity = suggestion -dotnet_diagnostic.CA2251.severity = suggestion -dotnet_diagnostic.CA3061.severity = suggestion -dotnet_diagnostic.CA3075.severity = suggestion -dotnet_diagnostic.CA3076.severity = suggestion -dotnet_diagnostic.CA3077.severity = suggestion -dotnet_diagnostic.CA3147.severity = suggestion -dotnet_diagnostic.CA5350.severity = suggestion -dotnet_diagnostic.CA5351.severity = suggestion -dotnet_diagnostic.CA5359.severity = suggestion -dotnet_diagnostic.CA5360.severity = suggestion -dotnet_diagnostic.CA5363.severity = suggestion -dotnet_diagnostic.CA5364.severity = suggestion -dotnet_diagnostic.CA5365.severity = suggestion -dotnet_diagnostic.CA5366.severity = suggestion -dotnet_diagnostic.CA5368.severity = suggestion -dotnet_diagnostic.CA5369.severity = suggestion -dotnet_diagnostic.CA5370.severity = suggestion -dotnet_diagnostic.CA5371.severity = suggestion -dotnet_diagnostic.CA5372.severity = suggestion -dotnet_diagnostic.CA5373.severity = suggestion -dotnet_diagnostic.CA5374.severity = suggestion -dotnet_diagnostic.CA5379.severity = suggestion -dotnet_diagnostic.CA5384.severity = suggestion -dotnet_diagnostic.CA5385.severity = suggestion -dotnet_diagnostic.CA5392.severity = suggestion -dotnet_diagnostic.CA5394.severity = suggestion -dotnet_diagnostic.CA5397.severity = suggestion - -dotnet_diagnostic.SYSLIB0006.severity = none - -[*.{js,html,hbs,less,css,ts,tsx}] +[*.{js,html,js,hbs,less,css}] charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true diff --git a/.esprintrc b/.esprintrc new file mode 100644 index 000000000..9330e00d1 --- /dev/null +++ b/.esprintrc @@ -0,0 +1,9 @@ +{ + "paths": [ + "frontend/src/**/*.js" + ], + "ignored": [ + "**/node_modules/**/*" + ], + "port": 5004 +} diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 4e4eedb66..9f557d227 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,13 +1,13 @@ name: Bug Report -description: 'Only bug reports for v4 will be accepted, older versions are no longer receiving bug fixes and support issues will be closed immediately.' +description: 'Support Requests will be closed immediately, if you are not 100% certain this is a bug please go to our Reddit, Discord, Forums, or IRC first. Exceptions do not mean you found a bug!' labels: ['needs-triage'] body: - type: checkboxes attributes: label: Is there an existing issue for this? - description: Please search to see if an open or closed issue already exists for the bug you encountered. If a bug exists and it is closed as complete it may not yet be in a stable release. + description: Please search to see if an issue already exists for the bug you encountered. options: - - label: I have searched the existing open and closed issues + - label: I have searched the existing issues required: true - type: textarea attributes: @@ -37,19 +37,17 @@ body: label: Environment description: | examples: - - **OS**: Ubuntu 22.04 - - **Sonarr**: Sonarr 4.0.0.766 + - **OS**: Ubuntu 20.04 + - **Sonarr**: Sonarr 3.0.6.1265 - **Docker Install**: Yes - **Using Reverse Proxy**: No - **Browser**: Firefox 90 (If UI related) - - **Database**: Sqlite 3.41.2 value: | - OS: - - Sonarr: - - Docker Install: - - Using Reverse Proxy: - - Browser: - - Database: + - Sonarr: + - Docker Install: + - Using Reverse Proxy: + - Browser: render: markdown validations: required: true @@ -62,20 +60,13 @@ body: - Other (This issue will be closed) validations: required: true -- type: textarea - attributes: - label: Trace Logs? - description: | - Trace Logs (https://wiki.servarr.com/sonarr/troubleshooting#logging-and-log-files) - ***Generally speaking, all bug reports must have trace logs provided.*** - *** Info Logs are not trace logs. If the logs do not say trace and are not from a file like `*.trace.*.txt` they are not trace logs.*** - validations: - required: true - type: textarea attributes: label: Anything else? description: | - Links? Screenshots? References? Anything that will give us more context about the issue you are encountering! + Trace Logs (https://wiki.servarr.com/sonarr/troubleshooting#logging-and-log-files) + Links? References? Anything that will give us more context about the issue you are encountering! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. validations: - required: false + required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index cd224373c..52a8192b9 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -5,9 +5,9 @@ body: - type: checkboxes attributes: label: Is there an existing issue for this? - description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a feature request exists and it is closed as complete it may not yet be in a stable release. + description: Please search to see if an issue already exists for the feature you are requesting. options: - - label: I have searched the existing open and closed issues + - label: I have searched the existing issues required: true - type: textarea attributes: @@ -32,6 +32,7 @@ body: label: Anything else? description: | Links? References? Mockups? Anything that will give us more context about the feature you are encountering! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. validations: - required: false + required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 25b1761f9..d8f748ad9 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,15 +1,14 @@ +#### Database Migration +YES | NO + #### Description A few sentences describing the overall goals of the pull request's commits. - - -#### Screenshots for UI Changes - - -#### Database Migration -YES - ### +#### Todos +- [ ] Tests +- [ ] Wiki Updates #### Issues Fixed or Closed by this PR -* Closes # +* diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md new file mode 100644 index 000000000..7adf10efb --- /dev/null +++ b/.github/SUPPORT.md @@ -0,0 +1,7 @@ +## Support + +There are a number of frequently asked questions that have been answered in our [FAQ](https://wiki.servarr.com/sonarr/faq) + +The [wiki](https://wiki.servarr.com/sonarr) contains other information and guides + +Please use one of the support channels: [forums](https://forums.sonarr.tv/), [subreddit](https://www.reddit.com/r/sonarr/), [discord ](https://discord.gg/M6BvZn5), or [IRC](https://web.libera.chat/?channels=#sonarr)for support/questions. \ No newline at end of file diff --git a/.github/actions/archive/action.yml b/.github/actions/archive/action.yml deleted file mode 100644 index 83e8a8ea9..000000000 --- a/.github/actions/archive/action.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: Archive -description: Archive binaries for deployment - -inputs: - os: - description: 'OS that the packaging is running on' - required: true - artifact: - description: 'Binary artifact' - required: true - archive_type: - description: 'File type to use for the final package' - required: true - branch: - description: 'Git branch used for this build' - required: true - major_version: - description: 'Sonarr major version' - required: true - version: - description: 'Sonarr version' - required: true - -runs: - using: 'composite' - steps: - - name: Archive Artifact - uses: thedoctor0/zip-release@0.7.5 - diff --git a/.github/actions/package/action.yml b/.github/actions/package/action.yml deleted file mode 100644 index 99c4d4ff1..000000000 --- a/.github/actions/package/action.yml +++ /dev/null @@ -1,78 +0,0 @@ -name: Package -description: Packages binaries for deployment - -inputs: - platform: - description: 'Binary platform' - required: true - framework: - description: '.net framework' - required: true - artifact: - description: 'Binary artifact' - required: true - branch: - description: 'Git branch used for this build' - required: true - major_version: - description: 'Sonarr major version' - required: true - version: - description: 'Sonarr version' - required: true - -runs: - using: 'composite' - steps: - - name: Download Artifact - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.artifact }} - path: _output - - - name: Download UI Artifact - uses: actions/download-artifact@v4 - with: - name: build_ui - path: _output/UI - - - name: Configure Environment Variables - shell: bash - run: | - echo "FRAMEWORK=${{ inputs.framework }}" >> "$GITHUB_ENV" - echo "BRANCH=${{ inputs.branch }}" >> "$GITHUB_ENV" - echo "SONARR_MAJOR_VERSION=${{ inputs.major_version }}" >> "$GITHUB_ENV" - echo "SONARR_VERSION=${{ inputs.version }}" >> "$GITHUB_ENV" - - - name: Create Packages - shell: bash - run: $GITHUB_ACTION_PATH/package.sh - - - name: Create Windows Installer (x64) - if: ${{ inputs.platform == 'windows' }} - working-directory: distribution/windows/setup - shell: cmd - run: | - SET RUNTIME=win-x64 - - build.bat - - - name: Create Windows Installer (x86) - if: ${{ inputs.platform == 'windows' }} - working-directory: distribution/windows/setup - shell: cmd - run: | - SET RUNTIME=win-x86 - - build.bat - - - name: Upload Artifact - uses: actions/upload-artifact@v4 - with: - name: release_${{ inputs.platform }} - compression-level: 0 - if-no-files-found: error - path: | - _artifacts/*.exe - _artifacts/*.tar.gz - _artifacts/*.zip diff --git a/.github/actions/package/package.sh b/.github/actions/package/package.sh deleted file mode 100755 index 8dce60585..000000000 --- a/.github/actions/package/package.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/bash - -outputFolder=_output -artifactsFolder=_artifacts -uiFolder="$outputFolder/UI" -framework="${FRAMEWORK:=net6.0}" - -rm -rf $artifactsFolder -mkdir $artifactsFolder - -for runtime in _output/* -do - name="${runtime##*/}" - folderName="$runtime/$framework" - sonarrFolder="$folderName/Sonarr" - archiveName="Sonarr.$BRANCH.$SONARR_VERSION.$name" - - if [[ "$name" == 'UI' ]]; then - continue - fi - - echo "Creating package for $name" - - echo "Copying UI" - cp -r $uiFolder $sonarrFolder - - echo "Setting permissions" - find $sonarrFolder -name "ffprobe" -exec chmod a+x {} \; - find $sonarrFolder -name "Sonarr" -exec chmod a+x {} \; - find $sonarrFolder -name "Sonarr.Update" -exec chmod a+x {} \; - - if [[ "$name" == *"osx"* ]]; then - echo "Creating macOS package" - - packageName="$name-app" - packageFolder="$outputFolder/$packageName" - - rm -rf $packageFolder - mkdir $packageFolder - - cp -r distribution/macOS/Sonarr.app $packageFolder - mkdir -p $packageFolder/Sonarr.app/Contents/MacOS - - echo "Copying Binaries" - cp -r $sonarrFolder/* $packageFolder/Sonarr.app/Contents/MacOS - - echo "Removing Update Folder" - rm -r $packageFolder/Sonarr.app/Contents/MacOS/Sonarr.Update - - echo "Packaging macOS app Artifact" - (cd $packageFolder; zip -rq "../../$artifactsFolder/$archiveName-app.zip" ./Sonarr.app) - fi - - echo "Packaging Artifact" - if [[ "$name" == *"linux"* ]] || [[ "$name" == *"osx"* ]] || [[ "$name" == *"freebsd"* ]]; then - tar -zcf "./$artifactsFolder/$archiveName.tar.gz" -C $folderName Sonarr - fi - - if [[ "$name" == *"win"* ]]; then - if [ "$RUNNER_OS" = "Windows" ] - then - (cd $folderName; 7z a -tzip "../../../$artifactsFolder/$archiveName.zip" ./Sonarr) - else - (cd $folderName; zip -rq "../../../$artifactsFolder/$archiveName.zip" ./Sonarr) - fi - fi -done diff --git a/.github/actions/publish-test-artifact/action.yml b/.github/actions/publish-test-artifact/action.yml deleted file mode 100644 index af3642043..000000000 --- a/.github/actions/publish-test-artifact/action.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Publish Test Artifact -description: Publishes a test artifact - -inputs: - framework: - description: '.net framework' - required: true - runtime: - description: '.net runtime' - required: true - -runs: - using: 'composite' - steps: - - uses: actions/upload-artifact@v4 - with: - name: tests-${{ inputs.runtime }} - path: _tests/${{ inputs.framework }}/${{ inputs.runtime }}/publish/**/* diff --git a/.github/actions/test/action.yml b/.github/actions/test/action.yml deleted file mode 100644 index bd62f4830..000000000 --- a/.github/actions/test/action.yml +++ /dev/null @@ -1,87 +0,0 @@ -name: Test -description: Runs unit/integration tests - -inputs: - use_postgres: - description: 'Whether postgres should be used for the database' - os: - description: 'OS that the tests are running on' - required: true - artifact: - description: 'Test binary artifact' - required: true - pattern: - description: 'Pattern for DLLs' - required: true - filter: - description: 'Filter for tests' - required: true - integration_tests: - description: 'True if running integration tests' - binary_artifact: - description: 'Binary artifact for integration tests' - binary_path: - description: 'Path witin binary artifact for integration tests' - -runs: - using: 'composite' - steps: - - name: Setup .NET - uses: actions/setup-dotnet@v4 - - - name: Setup Postgres - if: ${{ inputs.use_postgres }} - uses: ikalnytskyi/action-setup-postgres@v4 - - - name: Setup Test Variables - shell: bash - run: | - echo "RESULTS_NAME=${{ inputs.integration_tests && 'integation-' || 'unit-' }}${{ inputs.artifact }}${{ inputs.use_postgres && '-postgres' }}" >> "$GITHUB_ENV" - - - name: Setup Postgres Environment Variables - if: ${{ inputs.use_postgres }} - shell: bash - run: | - echo "Sonarr__Postgres__Host=localhost" >> "$GITHUB_ENV" - echo "Sonarr__Postgres__Port=5432" >> "$GITHUB_ENV" - echo "Sonarr__Postgres__User=postgres" >> "$GITHUB_ENV" - echo "Sonarr__Postgres__Password=postgres" >> "$GITHUB_ENV" - - - name: Download Artifact - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.artifact }} - path: _tests - - - name: Download Binary Artifact - if: ${{ inputs.integration_tests }} - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.binary_artifact }} - path: _output - - - name: Set up binary artifact - if: ${{ inputs.binary_path != '' }} - shell: bash - run: mv ./_output/${{inputs.binary_path}} _tests/bin - - - name: Make executable - if: startsWith(inputs.os, 'windows') != true - shell: bash - run: chmod +x ./_tests/Sonarr.Test.Dummy && chmod +x ./_tests/ffprobe - - - name: Make Sonarr binary executable - if: ${{ inputs.integration_tests && !startsWith(inputs.os, 'windows') }} - shell: bash - run: chmod +x ./_tests/bin/Sonarr - - - name: Run tests - shell: bash - run: dotnet test ./_tests/Sonarr.*.Test.dll --filter "${{ inputs.filter }}" --logger "trx;LogFileName=${{ env.RESULTS_NAME }}.trx" --logger "GitHubActions;summary.includePassedTests=true;summary.includeSkippedTests=true" - - - name: Upload Test Results - if: ${{ !cancelled() }} - uses: actions/upload-artifact@v4 - with: - name: results-${{ env.RESULTS_NAME }} - path: TestResults/*.trx diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index f33a02cd1..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,12 +0,0 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for more information: -# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates -# https://containers.dev/guide/dependabot - -version: 2 -updates: - - package-ecosystem: "devcontainers" - directory: "/" - schedule: - interval: weekly diff --git a/.github/labeler.yml b/.github/labeler.yml deleted file mode 100644 index fdd66d11a..000000000 --- a/.github/labeler.yml +++ /dev/null @@ -1,23 +0,0 @@ -'connection': - - changed-files: - - any-glob-to-any-file: src/NzbDrone.Core/Notifications/**/* - -'db-migration': - - changed-files: - - any-glob-to-any-file: src/NzbDrone.Core/Datastore/Migration/* - -'download-client': - - changed-files: - - any-glob-to-any-file: src/NzbDrone.Core/Download/Clients/**/* - -'indexer': - - changed-files: - - any-glob-to-any-file: src/NzbDrone.Core/Indexers/**/* - -'parsing': - - changed-files: - - any-glob-to-any-file: src/NzbDrone.Core/Parser/**/* - -'ui-only': - - changed-files: - - any-glob-to-all-files: frontend/**/* diff --git a/.github/release.yml b/.github/release.yml deleted file mode 100644 index 87eb8f2fe..000000000 --- a/.github/release.yml +++ /dev/null @@ -1,9 +0,0 @@ - changelog: - exclude: - authors: - - Weblate - - SonarrBot - categories: - - title: Changes - labels: - - '*' diff --git a/.github/workflows/api_docs.yml b/.github/workflows/api_docs.yml deleted file mode 100644 index dfd8ce0e2..000000000 --- a/.github/workflows/api_docs.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: 'API Docs' - -on: - workflow_dispatch: - schedule: - - cron: '0 0 * * 1' - push: - branches: - - develop - paths: - - ".github/workflows/api_docs.yml" - - "docs.sh" - - "src/Sonarr.Api.*/**" - - "src/Sonarr.Http/**" - - "src/**/*.csproj" - - "src/*" - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - api_docs: - runs-on: ubuntu-latest - if: github.repository == 'Sonarr/Sonarr' - permissions: - contents: write - steps: - - uses: actions/checkout@v4 - - - name: Setup dotnet - uses: actions/setup-dotnet@v4 - id: setup-dotnet - - - name: Create openapi.json - run: ./docs.sh Linux - - - name: Commit API Docs Change - continue-on-error: true - run: | - git config --global user.email "development@sonarr.tv" - git config --global user.name "Sonarr" - git checkout -b api-docs - git add src - if git status | grep -q modified - then - git commit -am 'Automated API Docs update' -m "ignore-downstream" - git push -f --set-upstream origin api-docs - curl -X POST -H "Authorization: Bearer ${{ secrets.OPENAPI_PAT }}" -H "Accept: application/vnd.github+json" https://api.github.com/repos/sonarr/sonarr/pulls -d '{"head":"api-docs","base":"develop","title":"Update API docs"}' - else - echo "No changes since last run" - fi diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 52f9d5678..000000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,257 +0,0 @@ -name: Build - -on: - push: - branches: - - develop - - main - paths-ignore: - - "src/Sonarr.Api.*/openapi.json" - pull_request: - branches: - - develop - paths-ignore: - - "src/NzbDrone.Core/Localization/Core/**" - - "src/Sonarr.Api.*/openapi.json" - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -env: - FRAMEWORK: net6.0 - RAW_BRANCH_NAME: ${{ github.head_ref || github.ref_name }} - SONARR_MAJOR_VERSION: 4 - VERSION: 4.0.14 - -jobs: - backend: - runs-on: windows-latest - outputs: - framework: ${{ steps.variables.outputs.framework }} - major_version: ${{ steps.variables.outputs.major_version }} - version: ${{ steps.variables.outputs.version }} - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - - - name: Setup Environment Variables - id: variables - shell: bash - run: | - # Add 800 to the build number because GitHub won't let us pick an arbitrary starting point - SONARR_VERSION="${{ env.VERSION }}.$((${{ github.run_number }}+800))" - DOTNET_VERSION=$(jq -r '.sdk.version' global.json) - - echo "SDK_PATH=${{ env.DOTNET_ROOT }}/sdk/${DOTNET_VERSION}" >> "$GITHUB_ENV" - echo "SONARR_VERSION=$SONARR_VERSION" >> "$GITHUB_ENV" - echo "BRANCH=${RAW_BRANCH_NAME//\//-}" >> "$GITHUB_ENV" - - echo "framework=${{ env.FRAMEWORK }}" >> "$GITHUB_OUTPUT" - echo "major_version=${{ env.SONARR_MAJOR_VERSION }}" >> "$GITHUB_OUTPUT" - echo "version=$SONARR_VERSION" >> "$GITHUB_OUTPUT" - - - name: Enable Extra Platforms In SDK - shell: bash - run: ./build.sh --enable-extra-platforms-in-sdk - - - name: Build Backend - shell: bash - run: ./build.sh --backend --enable-extra-platforms --packages - - # Test Artifacts - - - name: Publish win-x64 Test Artifact - uses: ./.github/actions/publish-test-artifact - with: - framework: ${{ env.FRAMEWORK }} - runtime: win-x64 - - - name: Publish linux-x64 Test Artifact - uses: ./.github/actions/publish-test-artifact - with: - framework: ${{ env.FRAMEWORK }} - runtime: linux-x64 - - - name: Publish osx-arm64 Test Artifact - uses: ./.github/actions/publish-test-artifact - with: - framework: ${{ env.FRAMEWORK }} - runtime: osx-arm64 - - # Build Artifacts (grouped by OS) - - - name: Publish FreeBSD Artifact - uses: actions/upload-artifact@v4 - with: - name: build_freebsd - path: _artifacts/freebsd-*/**/* - - name: Publish Linux Artifact - uses: actions/upload-artifact@v4 - with: - name: build_linux - path: _artifacts/linux-*/**/* - - name: Publish macOS Artifact - uses: actions/upload-artifact@v4 - with: - name: build_macos - path: _artifacts/osx-*/**/* - - name: Publish Windows Artifact - uses: actions/upload-artifact@v4 - with: - name: build_windows - path: _artifacts/win-*/**/* - - frontend: - runs-on: ubuntu-latest - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Volta - uses: volta-cli/action@v4 - - - name: Yarn Install - run: yarn install - - - name: Lint - run: yarn lint - - - name: Stylelint - run: yarn stylelint -f github - - - name: Build - run: yarn build --env production - - - name: Publish UI Artifact - uses: actions/upload-artifact@v4 - with: - name: build_ui - path: _output/UI/**/* - - unit_test: - needs: backend - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - include: - - os: ubuntu-latest - artifact: tests-linux-x64 - filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory!=IntegrationTest&TestCategory!=AutomationTest - - os: macos-latest - artifact: tests-osx-arm64 - filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory!=IntegrationTest&TestCategory!=AutomationTest - - os: windows-latest - artifact: tests-win-x64 - filter: TestCategory!=ManualTest&TestCategory!=LINUX&TestCategory!=IntegrationTest&TestCategory!=AutomationTest - runs-on: ${{ matrix.os }} - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Test - uses: ./.github/actions/test - with: - os: ${{ matrix.os }} - artifact: ${{ matrix.artifact }} - pattern: Sonarr.*.Test.dll - filter: ${{ matrix.filter }} - - unit_test_postgres: - needs: backend - runs-on: ubuntu-latest - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Test - uses: ./.github/actions/test - with: - os: ubuntu-latest - artifact: tests-linux-x64 - pattern: Sonarr.*.Test.dll - filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory!=IntegrationTest&TestCategory!=AutomationTest - use_postgres: true - - integration_test: - needs: backend - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - include: - - os: ubuntu-latest - artifact: tests-linux-x64 - filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory=IntegrationTest - binary_artifact: build_linux - binary_path: linux-x64/${{ needs.backend.outputs.framework }}/Sonarr - - os: macos-latest - artifact: tests-osx-arm64 - filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory=IntegrationTest - binary_artifact: build_macos - binary_path: osx-arm64/${{ needs.backend.outputs.framework }}/Sonarr - - os: windows-latest - artifact: tests-win-x64 - filter: TestCategory!=ManualTest&TestCategory!=LINUX&TestCategory=IntegrationTest - binary_artifact: build_windows - binary_path: win-x64/${{ needs.backend.outputs.framework }}/Sonarr - runs-on: ${{ matrix.os }} - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Test - uses: ./.github/actions/test - with: - os: ${{ matrix.os }} - artifact: ${{ matrix.artifact }} - pattern: Sonarr.*.Test.dll - filter: ${{ matrix.filter }} - integration_tests: true - binary_artifact: ${{ matrix.binary_artifact }} - binary_path: ${{ matrix.binary_path }} - - deploy: - if: ${{ github.ref_name == 'develop' || github.ref_name == 'main' }} - needs: [backend, frontend, unit_test, unit_test_postgres, integration_test] - secrets: inherit - uses: ./.github/workflows/deploy.yml - with: - framework: ${{ needs.backend.outputs.framework }} - branch: ${{ github.ref_name }} - major_version: ${{ needs.backend.outputs.major_version }} - version: ${{ needs.backend.outputs.version }} - - notify: - name: Discord Notification - needs: - [ - backend, - frontend, - unit_test, - unit_test_postgres, - integration_test, - deploy, - ] - if: ${{ !cancelled() && (github.ref_name == 'develop' || github.ref_name == 'main') }} - env: - STATUS: ${{ contains(needs.*.result, 'failure') && 'failure' || 'success' }} - runs-on: ubuntu-latest - - steps: - - name: Notify - uses: tsickert/discord-webhook@v6.0.0 - with: - webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }} - username: "GitHub Actions" - avatar-url: "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" - embed-title: "${{ github.workflow }}: ${{ env.STATUS == 'success' && 'Success' || 'Failure' }}" - embed-url: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" - embed-description: | - **Branch** ${{ github.ref }} - **Build** ${{ needs.backend.outputs.version }} - embed-color: ${{ env.STATUS == 'success' && '3066993' || '15158332' }} diff --git a/.github/workflows/conflict_labeler.yml b/.github/workflows/conflict_labeler.yml deleted file mode 100644 index e9afb71a3..000000000 --- a/.github/workflows/conflict_labeler.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Merge Conflict Labeler - -on: - push: - branches: - - develop - pull_request_target: - branches: - - develop - types: [synchronize] - -jobs: - label: - name: Labeling - runs-on: ubuntu-latest - if: ${{ github.repository == 'Sonarr/Sonarr' }} - permissions: - contents: read - pull-requests: write - steps: - - name: Apply label - uses: eps1lon/actions-label-merge-conflict@v3 - with: - dirtyLabel: 'merge-conflict' - repoToken: '${{ secrets.GITHUB_TOKEN }}' - \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 4fa5b54ee..000000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,160 +0,0 @@ -name: Deploy - -on: - workflow_call: - inputs: - framework: - description: '.net framework' - type: string - required: true - branch: - description: 'Git branch used for this build' - type: string - required: true - major_version: - description: 'Sonarr major version' - type: string - required: true - version: - description: 'Sonarr version' - type: string - required: true - secrets: - SERVICES_API_KEY: - required: true - -jobs: - package: - strategy: - matrix: - platform: [freebsd, linux, macos, windows] - include: - - platform: freebsd - os: ubuntu-latest - - platform: linux - os: ubuntu-latest - - platform: macos - os: ubuntu-latest - - platform: windows - os: windows-latest - - runs-on: ${{ matrix.os }} - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Package - uses: ./.github/actions/package - with: - framework: ${{ inputs.framework }} - platform: ${{ matrix.platform }} - artifact: build_${{ matrix.platform }} - branch: ${{ inputs.branch }} - major_version: ${{ inputs.major_version }} - version: ${{ inputs.version }} - - release: - needs: package - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Check out - uses: actions/checkout@v4 - - - name: Download release artifacts - uses: actions/download-artifact@v4 - with: - path: _artifacts - pattern: release_* - merge-multiple: true - - - name: Get Previous Release - id: previous-release - uses: cardinalby/git-get-release-action@v1 - env: - GITHUB_TOKEN: ${{ github.token }} - with: - latest: true - prerelease: ${{ inputs.branch != 'main' }} - - - name: Generate Release Notes - id: generate-release-notes - uses: actions/github-script@v7 - with: - github-token: ${{ github.token }} - result-encoding: string - script: | - const { data } = await github.rest.repos.generateReleaseNotes({ - owner: context.repo.owner, - repo: context.repo.repo, - tag_name: 'v${{ inputs.version }}', - target_commitish: '${{ github.sha }}', - previous_tag_name: '${{ steps.previous-release.outputs.tag_name }}', - }) - return data.body - - - name: Create release - uses: ncipollo/release-action@v1 - with: - artifacts: _artifacts/Sonarr.* - commit: ${{ github.sha }} - generateReleaseNotes: false - body: ${{ steps.generate-release-notes.outputs.result }} - name: ${{ inputs.version }} - prerelease: ${{ inputs.branch != 'main' }} - skipIfReleaseExists: true - tag: v${{ inputs.version }} - - - name: Publish to Services - shell: bash - working-directory: _artifacts - run: | - branch=${{ inputs.branch }} - version=${{ inputs.version }} - lastCommit=${{ github.sha }} - - hashes="[" - - addHash() { - path=$1 - os=$2 - arch=$3 - type=$4 - - local hash=$(sha256sum *.$version.$path | awk '{ print $1; }') - echo "{ \""Os\"": \""$os\"", \""Arch\"": \""$arch\"", \""Type\"": \""$type\"", \""Hash\"": \""$hash\"" }" - } - - hashes="$hashes $(addHash "linux-arm.tar.gz" "linux" "arm" "archive")" - hashes="$hashes, $(addHash "linux-arm64.tar.gz" "linux" "arm64" "archive")" - hashes="$hashes, $(addHash "linux-x64.tar.gz" "linux" "x64" "archive")" - # hashes="$hashes, $(addHash "linux-x86.tar.gz" "linux" "x86" "archive")" - - # hashes="$hashes, $(addHash "linux-musl-arm.tar.gz" "linuxmusl" "arm" "archive")" - hashes="$hashes, $(addHash "linux-musl-arm64.tar.gz" "linuxmusl" "arm64" "archive")" - hashes="$hashes, $(addHash "linux-musl-x64.tar.gz" "linuxmusl" "x64" "archive")" - - hashes="$hashes, $(addHash "osx-arm64.tar.gz" "osx" "arm64" "archive")" - hashes="$hashes, $(addHash "osx-x64.tar.gz" "osx" "x64" "archive")" - - hashes="$hashes, $(addHash "osx-arm64-app.zip" "osx" "arm64" "installer")" - hashes="$hashes, $(addHash "osx-x64-app.zip" "osx" "x64" "installer")" - - hashes="$hashes, $(addHash "win-x64.zip" "windows" "x64" "archive")" - hashes="$hashes, $(addHash "win-x86.zip" "windows" "x86" "archive")" - - hashes="$hashes, $(addHash "win-x64-installer.exe" "windows" "x64" "installer")" - hashes="$hashes, $(addHash "win-x86-installer.exe" "windows" "x86" "installer")" - - hashes="$hashes, $(addHash "freebsd-x64.tar.gz" "freebsd" "x64" "archive")" - - hashes="$hashes ]" - - json="{\""branch\"":\""$branch\"", \""version\"":\""$version\"", \""lastCommit\"":\""$lastCommit\"", \""hashes\"":$hashes, \""gitHubRelease\"":true}" - url="https://services.sonarr.tv/v1/update" - - echo "Publishing update $version ($branch) to: $url" - echo "$json" - - curl -H "Content-Type: application/json" -H "X-Api-Key: ${{ secrets.SERVICES_API_KEY }}" -X POST -d "$json" --fail-with-body $url diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml deleted file mode 100644 index df54c0fff..000000000 --- a/.github/workflows/labeler.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: "Pull Request Labeler" -on: - - pull_request_target - -jobs: - triage: - permissions: - contents: read - pull-requests: write - runs-on: ubuntu-latest - if: github.repository == 'Sonarr/Sonarr' - steps: - - uses: actions/labeler@v5 diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml index d775234db..0435b1c71 100644 --- a/.github/workflows/lock.yml +++ b/.github/workflows/lock.yml @@ -8,15 +8,14 @@ on: jobs: lock: runs-on: ubuntu-latest - if: github.repository == 'Sonarr/Sonarr' steps: - - uses: dessant/lock-threads@v5 + - uses: dessant/lock-threads@v2 with: github-token: ${{ github.token }} - issue-inactive-days: '90' - exclude-issue-created-before: '' - exclude-any-issue-labels: 'one-day-maybe' - add-issue-labels: '' - issue-comment: '' + issue-lock-inactive-days: '90' + issue-exclude-created-before: '' + issue-exclude-labels: 'one-day-maybe' + issue-lock-labels: '' + issue-lock-comment: '' issue-lock-reason: 'resolved' process-only: '' diff --git a/.github/workflows/support-requests.yml b/.github/workflows/support-requests.yml deleted file mode 100644 index adf5a8c4a..000000000 --- a/.github/workflows/support-requests.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: 'Support Requests' - -on: - issues: - types: [labeled, unlabeled, reopened] - -permissions: - issues: write - -jobs: - action: - runs-on: ubuntu-latest - if: github.repository == 'Sonarr/Sonarr' - steps: - - uses: dessant/support-requests@v4 - with: - github-token: ${{ github.token }} - support-label: 'support' - issue-comment: > - :wave: @{issue-author}, we use the issue tracker exclusively - for bug reports and feature requests. However, this issue appears - to be a support request. Please use one of the support channels: - [forums](https://forums.sonarr.tv/), [subreddit](https://www.reddit.com/r/sonarr/), - [discord](https://discord.gg/Ex7FmFK), or [IRC](https://web.libera.chat/?channels=#sonarr) - for support/questions. - close-issue: true - issue-close-reason: 'not planned' - lock-issue: false - issue-lock-reason: 'off-topic' diff --git a/.gitignore b/.gitignore index d17209556..e0931490a 100644 --- a/.gitignore +++ b/.gitignore @@ -84,6 +84,7 @@ TestResults [Tt]est[Rr]esult* *.Cache ClientBin +[Ss]tyle[Cc]op.* ~$* *.dbmdl Generated_Code #added for RIA/Silverlight projects @@ -116,52 +117,28 @@ src/UI/.idea/* *log.txt node_modules/ _output* -_artifacts _rawPackage/ _dotTrace* _tests* _publish* _temp* *.Result.xml -coverage*.xml -coverage*.json setup/Output/ *.~is -.mono + +UI/ #VS outout folders bin obj output/* -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ -**/Properties/launchSettings.json - -# Packages -Sonarr_*/ -Sonarr_*.zip -Sonarr_*.gz -gecko.zip -geckodriver.exe #OS X metadata files ._* .DS_Store _start -_temp_*/**/* - -# Windows thumbnail cache files -Thumbs.db src/.idea/ /distribution/windows/setup/output/* - -# API doc generation -.config/ - -# Ignore Jetbrains IntelliJ Workspace Directories -.idea/ diff --git a/.vscode/extensions.json b/.vscode/extensions.json deleted file mode 100644 index 7a36fefe1..000000000 --- a/.vscode/extensions.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "recommendations": [ - "esbenp.prettier-vscode", - "ms-dotnettools.csdevkit", - "ms-vscode-remote.remote-containers" - ] -} diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 6ea80f418..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md - "name": "Run Sonarr", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build dotnet", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/_output/net6.0/Sonarr", - "args": [], - "cwd": "${workspaceFolder}", - // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console - "console": "integratedTerminal", - "stopAtEntry": false - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach" - } - ] -} diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 44aeb4060..000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "typescript.tsdk": "node_modules\\typescript\\lib" -} diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index cfd41d42f..000000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "label": "build dotnet", - "command": "dotnet", - "type": "process", - "args": [ - "msbuild", - "-restore", - "${workspaceFolder}/src/Sonarr.sln", - "-p:GenerateFullPaths=true", - "-p:Configuration=Debug", - "-p:Platform=Posix", - "-consoleloggerparameters:NoSummary;ForceNoAlign" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "publish", - "command": "dotnet", - "type": "process", - "args": [ - "publish", - "${workspaceFolder}/src/Sonarr.sln", - "-property:GenerateFullPaths=true", - "-consoleloggerparameters:NoSummary;ForceNoAlign" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "watch", - "command": "dotnet", - "type": "process", - "args": [ - "watch", - "run", - "--project", - "${workspaceFolder}/src/Sonarr.sln" - ], - "problemMatcher": "$msCompile" - } - ] -} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9eedd495b..f2746fd26 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ We're always looking for people to help make Sonarr even better, there are a number of ways to contribute. ## Documentation ## -Setup guides, [FAQ](https://wiki.servarr.com/sonarr/faq), the more information we have on the [wiki](https://wiki.servarr.com/sonarr) the better. +Setup guides, [FAQ](https://wiki.servarr.com/Sonarr_FAQ), the more information we have on the [wiki](https://wiki.servarr.com/Sonarr) the better. ## Development ## @@ -17,7 +17,7 @@ Setup guides, [FAQ](https://wiki.servarr.com/sonarr/faq), the more information w ### Getting started ### 1. Fork Sonarr -2. Clone the repository into your development machine. [*info*](https://docs.github.com/en/get-started/quickstart/fork-a-repo) +2. Clone the repository into your development machine. [*info*](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository-from-github) 3. Install the required Node Packages `yarn install` 4. Start webpack to monitor your dev environment for any frontend changes that need post processing using `yarn start` command. 5. Build the project in Visual Studio, Setting startup project to `Sonarr.Console` and framework to `x86` @@ -29,14 +29,14 @@ Setup guides, [FAQ](https://wiki.servarr.com/sonarr/faq), the more information w - Rebase from Sonarr's `develop` branch, don't merge - Make meaningful commits, or squash them - Feel free to make a pull request before work is complete, this will let us see where its at and make comments/suggest improvements -- Reach out to us on our [forums](https://forums.sonarr.tv/), [subreddit](https://www.reddit.com/r/sonarr/), [discord](https://discord.gg/Ex7FmFK), or [IRC](https://web.libera.chat/?channels=#sonarr) if you have any questions +- Reach out to us on our [forums](https://forums.sonarr.tv/), [subreddit](https://www.reddit.com/r/sonarr/), [discord](https://discord.gg/Ex7FmFK), or [IRC](http://webchat.freenode.net/?channels=#sonarr) if you have any questions - Add tests (unit/integration) - Commit with *nix line endings for consistency (We checkout Windows and commit *nix) - One feature/bug fix per pull request to keep things clean and easy to understand - Use 4 spaces instead of tabs, this should be the default for VS 2019 and WebStorm ### Pull Requesting ### -- Only make pull requests to develop (currently `develop`), never `main`, if you make a PR to master we'll comment on it and close it +- Only make pull requests to develop (currently phantom-develop), never master, if you make a PR to master we'll comment on it and close it - You're probably going to get some comments or questions from us, they will be to ensure consistency and maintainability - We'll try to respond to pull requests as soon as possible, if its been a day or two, please reach out to us, we may have missed it - Each PR should come from its own [feature branch](http://martinfowler.com/bliki/FeatureBranch.html) not develop in your fork, it should have a meaningful branch name (what is being added/fixed) diff --git a/Logo/Jetbrains/dottrace.svg b/Logo/Jetbrains/dottrace.svg new file mode 100644 index 000000000..b879517cd --- /dev/null +++ b/Logo/Jetbrains/dottrace.svg @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Logo/Jetbrains/jetbrains.svg b/Logo/Jetbrains/jetbrains.svg new file mode 100644 index 000000000..75d4d2177 --- /dev/null +++ b/Logo/Jetbrains/jetbrains.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Logo/Jetbrains/resharper.svg b/Logo/Jetbrains/resharper.svg new file mode 100644 index 000000000..24c987a78 --- /dev/null +++ b/Logo/Jetbrains/resharper.svg @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Logo/Jetbrains/teamcity.svg b/Logo/Jetbrains/teamcity.svg new file mode 100644 index 000000000..ca14b3dc1 --- /dev/null +++ b/Logo/Jetbrains/teamcity.svg @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index d43366f93..fa28c3905 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,4 @@ -# Sonarr Sonarr - -[![Translated](https://translate.servarr.com/widget/servarr/sonarr/svg-badge.svg)](https://translate.servarr.com/engage/servarr/) -[![Backers on Open Collective](https://opencollective.com/Sonarr/backers/badge.svg)](#backers) -[![Sponsors on Open Collective](https://opencollective.com/Sonarr/sponsors/badge.svg)](#sponsors) -[![Mega Sponsors on Open Collective](https://opencollective.com/Sonarr/megasponsors/badge.svg)](#mega-sponsors) +# Sonarr Sonarr Sonarr is a PVR for Usenet and BitTorrent users. It can monitor multiple RSS feeds for new episodes of your favorite shows and will grab, sort and rename them. It can also be configured to automatically upgrade the quality of files already downloaded when a better quality format becomes available. @@ -12,11 +7,10 @@ Sonarr is a PVR for Usenet and BitTorrent users. It can monitor multiple RSS fee - [Download/Installation](https://sonarr.tv/#downloads-v3) - [FAQ](https://wiki.servarr.com/sonarr/faq) - [Wiki](https://wiki.servarr.com/Sonarr) -- [v4 Beta API Documentation](https://sonarr.tv/docs/api) +- [(WIP) API Documentation](https://github.com/Sonarr/Sonarr/wiki/API) - [Donate](https://sonarr.tv/donate) ## Support - Note: GitHub Issues are for Bugs and Feature Requests Only - [Forums](https://forums.sonarr.tv/) @@ -26,6 +20,8 @@ Note: GitHub Issues are for Bugs and Feature Requests Only - [Reddit](https://www.reddit.com/r/sonarr) - [Wiki](https://wiki.servarr.com/sonarr) + + ## Features ### Current Features @@ -33,7 +29,7 @@ Note: GitHub Issues are for Bugs and Feature Requests Only - Support for major platforms: Windows, Linux, macOS, Raspberry Pi, etc. - Automatically detects new episodes - Can scan your existing library and download any missing episodes -- Can watch for better quality of the episodes you already have and do an automatic upgrade. _eg. from DVD to Blu-Ray_ +- Can watch for better quality of the episodes you already have and do an automatic upgrade. *eg. from DVD to Blu-Ray* - Automatic failed download handling will try another release if one fails - Manual search so you can pick any release or to see why a release was not downloaded automatically - Fully configurable episode renaming @@ -45,41 +41,35 @@ Note: GitHub Issues are for Bugs and Feature Requests Only ## Contributing ### Development - This project exists thanks to all the people who contribute. [Contribute](CONTRIBUTING.md). - ### Supporters -This project would not be possible without the support of our users and software providers. +This project would not be possible without the support of our users and software providers. [**Become a sponsor or backer**](https://opencollective.com/sonarr) to help us out! -#### Mega Sponsors - -[![Sponsors](https://opencollective.com/sonarr/tiers/mega-sponsor.svg?width=890)](https://opencollective.com/sonarr/contribute/mega-sponsor-21443/checkout) - #### Sponsors -[![Flexible Sponsors](https://opencollective.com/sonarr/sponsors.svg?width=890)](https://opencollective.com/sonarr/contribute/sponsor-21457/checkout) +[![Sponsors](https://opencollective.com/sonarr/tiers/sponsor.svg)](https://opencollective.com/sonarr/contribute/sponsor-21443/checkout) + +#### Flexible Sponsors + +[![Flexible Sponsors](https://opencollective.com/sonarr/tiers/flexible-sponsor.svg?avatarHeight=54)](https://opencollective.com/sonarr/contribute/flexible-sponsor-21457/checkout) #### Backers -[![Backers](https://opencollective.com/sonarr/backers.svg?width=890)](https://opencollective.com/sonarr/contribute/backer-21442/checkout) +[![Backers](https://opencollective.com/sonarr/tiers/backer.svg?avatarHeight=48)](https://opencollective.com/sonarr/contribute/backer-21442/checkout) #### JetBrains -Thank you to [JetBrains](http://www.jetbrains.com/) for providing us with free licenses to their great tools +Thank you to [JetBrains JetBrains](http://www.jetbrains.com/) for providing us with free licenses to their great tools -[TeamCity](http://www.jetbrains.com/teamcity/) - -[ReSharper](http://www.jetbrains.com/resharper/) - -[dotTrace](http://www.jetbrains.com/dottrace/) - -[Rider](http://www.jetbrains.com/rider/) +* [TeamCity TeamCity](http://www.jetbrains.com/teamcity/) +* [ReSharper ReSharper](http://www.jetbrains.com/resharper/) +* [dotTrace dotTrace](http://www.jetbrains.com/dottrace/) ### Licenses -- [GNU GPL v3](http://www.gnu.org/licenses/gpl.html) -- Copyright 2010-2024 +- [GNU GPL v3](http://www.gnu.org/licenses/gpl.html) +- Copyright 2010-2021 diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index a534ff2fb..000000000 --- a/SECURITY.md +++ /dev/null @@ -1,9 +0,0 @@ -# Security Policy - -## Reporting a Vulnerability - -Please report (suspected) security vulnerabilities on Discord (preferred) to -either markus101 -#2148 or Taloth#7357 or via email: security@sonarr.tv. You will receive a response from -us within 72 hours. If the issue is confirmed, we will release a patch as soon -as possible depending on complexity/severity. diff --git a/build.sh b/build.sh index ee59d2f61..22275fa11 100755 --- a/build.sh +++ b/build.sh @@ -1,59 +1,122 @@ -#! /usr/bin/env bash -set -e +#! /bin/bash +msBuildVersion='15.0' +outputFolder='./_output' +outputFolderWindows='./_output_windows' +outputFolderLinux='./_output_linux' +outputFolderMacOS='./_output_macos' +outputFolderMacOSApp='./_output_macos_app' +testPackageFolder='./_tests' +testPackageFolderWindows='./_tests_windows' +testPackageFolderLinux='./_tests_linux' +sourceFolder='./src' +slnFile=$sourceFolder/Sonarr.sln +updateSubFolder=Sonarr.Update -outputFolder='_output' -testPackageFolder='_tests' -artifactsFolder="_artifacts"; -framework="${FRAMEWORK:=net6.0}" +nuget='tools/nuget/nuget.exe'; +vswhere='tools/vswhere/vswhere.exe'; + +. ./version.sh + +CheckExitCode() +{ + "$@" + local status=$? + if [ $status -ne 0 ]; then + echo "error with $1" >&2 + exit 1 + fi + return $status +} ProgressStart() { - echo "::group::$1" - echo "Start '$1'" + echo "##teamcity[blockOpened name='$1']" + echo "##teamcity[progressStart '$1']" } ProgressEnd() { - echo "Finish '$1'" - echo "::endgroup::" + echo "##teamcity[progressFinish '$1']" + echo "##teamcity[blockClosed name='$1']" } UpdateVersionNumber() { - if [ "$SONARR_VERSION" != "" ]; then - echo "Updating version info to: $SONARR_VERSION" - sed -i'' -e "s/[0-9.*]\+<\/AssemblyVersion>/$SONARR_VERSION<\/AssemblyVersion>/g" src/Directory.Build.props - sed -i'' -e "s/[\$()A-Za-z-]\+<\/AssemblyConfiguration>/${BRANCH}<\/AssemblyConfiguration>/g" src/Directory.Build.props - sed -i'' -e "s/10.0.0.0<\/string>/$SONARR_VERSION<\/string>/g" distribution/macOS/Sonarr.app/Contents/Info.plist + if [ "$BUILD_NUMBER" != "" ]; then + echo "Updating Version Info" + verMajorMinorRevision=`echo "$buildVersion" | cut -d. -f1,2,3` + verBuild=`echo "${BUILD_NUMBER}" | cut -d. -f4` + BUILD_NUMBER=$verMajorMinorRevision.$verBuild + echo "##teamcity[buildNumber '$BUILD_NUMBER']" + sed -i "s/[0-9.*]\+<\/AssemblyVersion>/$BUILD_NUMBER<\/AssemblyVersion>/g" ./src/Directory.Build.props + sed -i "s/[\$()A-Za-z-]\+<\/AssemblyConfiguration>/${BRANCH:-dev}<\/AssemblyConfiguration>/g" ./src/Directory.Build.props fi } -EnableExtraPlatformsInSDK() +CreateReleaseInfo() { - BUNDLEDVERSIONS="${SDK_PATH}/Microsoft.NETCoreSdk.BundledVersions.props" - if grep -q freebsd-x64 "$BUNDLEDVERSIONS"; then - echo "Extra platforms already enabled" - else - echo "Enabling extra platform support" - sed -i.ORI 's/osx-x64/osx-x64;freebsd-x64/' "$BUNDLEDVERSIONS" + if [ "$BUILD_NUMBER" != "" ]; then + echo "Create Release Info" + echo -e "# Do Not Edit\nReleaseVersion=$BUILD_NUMBER\nBranch=${BRANCH:-dev}" > $outputFolder/release_info fi } -EnableExtraPlatforms() +CleanFolder() { - if grep -qv freebsd-x64 src/Directory.Build.props; then - sed -i'' -e "s^\(.*\)^\1;freebsd-x64^g" src/Directory.Build.props + local path=$1 + local keepConfigFiles=$2 + + find $path -name "*.transform" -exec rm "{}" \; + + if [ $keepConfigFiles != true ] ; then + find $path -name "*.dll.config" -exec rm "{}" \; fi + + echo "Removing FluentValidation.Resources files" + find $path -name "FluentValidation.resources.dll" -exec rm "{}" \; + find $path -name "App.config" -exec rm "{}" \; + + echo "Removing vshost files" + find $path -name "*.vshost.exe" -exec rm "{}" \; + + echo "Removing dylib files" + find $path -name "*.dylib" -exec rm "{}" \; + + echo "Removing Empty folders" + find $path -depth -empty -type d -exec rm -r "{}" \; +} + +BuildWithMSBuild() +{ + msBuildPath=`$vswhere -latest -products \* -requires Microsoft.Component.MSBuild -find MSBuild\\\\\*\*\\\\Bin\\\\MSBuild.exe` + msBuildPath=${msBuildPath/C:\\/\/c\/} + msBuildPath=${msBuildPath//\\/\/} + msBuildDir=$(dirname "$msBuildPath") + + echo $msBuildDir + + export PATH=$msBuildDir:$PATH + CheckExitCode MSBuild.exe $slnFile //p:Configuration=Release //p:Platform=x86 //t:Clean //m + $nuget restore $slnFile + CheckExitCode MSBuild.exe $slnFile //p:Configuration=Release //p:Platform=x86 //t:Build //m //p:AllowedReferenceRelatedFileExtensions=.pdb +} + +BuildWithXbuild() +{ + export MONO_IOMAP=case + CheckExitCode msbuild /t:Clean $slnFile + mono $nuget restore $slnFile + CheckExitCode msbuild /p:Configuration=Release /p:Platform=x86 /t:Build /p:AllowedReferenceRelatedFileExtensions=.pdb $slnFile } LintUI() { ProgressStart 'ESLint' - yarn lint + CheckExitCode yarn lint ProgressEnd 'ESLint' ProgressStart 'Stylelint' - yarn stylelint + CheckExitCode yarn stylelint ProgressEnd 'Stylelint' } @@ -64,392 +127,331 @@ Build() rm -rf $outputFolder rm -rf $testPackageFolder - slnFile=src/Sonarr.sln - - if [ $os = "windows" ]; then - platform=Windows + if [ $runtime = "dotnet" ] ; then + BuildWithMSBuild else - platform=Posix + BuildWithXbuild fi - dotnet clean $slnFile -c Debug - dotnet clean $slnFile -c Release + CleanFolder $outputFolder false - if [[ -z "$RID" || -z "$FRAMEWORK" ]]; - then - dotnet msbuild -restore $slnFile -p:Configuration=Release -p:Platform=$platform -t:PublishAllRids - else - dotnet msbuild -restore $slnFile -p:Configuration=Release -p:Platform=$platform -p:RuntimeIdentifiers=$RID -t:PublishAllRids - fi + echo "Removing Mono.Posix.dll" + rm $outputFolder/Mono.Posix.dll ProgressEnd 'Build' } -YarnInstall() -{ - ProgressStart 'yarn install' - yarn install --frozen-lockfile --network-timeout 120000 - ProgressEnd 'yarn install' -} - RunWebpack() { + ProgressStart 'yarn install' + yarn install + ProgressEnd 'yarn install' + + LintUI + ProgressStart 'Running webpack' - yarn run build --env production + CheckExitCode yarn run build --env production ProgressEnd 'Running webpack' } -PackageFiles() +CreateMdbs() { - local folder="$1" - local framework="$2" - local runtime="$3" - - rm -rf $folder - mkdir -p $folder - cp -r $outputFolder/$framework/$runtime/publish/* $folder - cp -r $outputFolder/Sonarr.Update/$framework/$runtime/publish $folder/Sonarr.Update - - if [ "$FRONTEND" = "YES" ]; - then - cp -r $outputFolder/UI $folder + local path=$1 + if [ $runtime = "dotnet" ] ; then + local pdbFiles=( $(find $path -name "*.pdb") ) + for filename in "${pdbFiles[@]}" + do + if [ -e ${filename%.pdb}.dll ] ; then + tools/pdb2mdb/pdb2mdb.exe ${filename%.pdb}.dll + fi + if [ -e ${filename%.pdb}.exe ] ; then + tools/pdb2mdb/pdb2mdb.exe ${filename%.pdb}.exe + fi + done fi - - echo "Adding LICENSE" - cp LICENSE.md $folder } -PackageLinux() +PatchMono() { - local framework="$1" - local runtime="$2" + local path=$1 - ProgressStart "Creating $runtime Package for $framework" + # Below we deal with some mono incompatibilities with windows-only dotnet core/standard libs + # See: https://github.com/mono/mono/blob/master/tools/nuget-hash-extractor/download.sh + # That list defines assemblies that are prohibited from being loaded from the appdir, instead loading from mono GAC. - local folder=$artifactsFolder/$runtime/$framework/Sonarr + # We have debian dependencies to get these installed or facades from mono 5.10+ + for assembly in System.IO.Compression System.Runtime.InteropServices.RuntimeInformation System.Net.Http System.Globalization.Extensions System.Text.Encoding.CodePages System.Threading.Overlapped + do + if [ -e $path/$assembly.dll ]; then + if [ -e $sourceFolder/Libraries/Mono/$assembly.dll ]; then + echo "Copy Mono-specific facade $assembly.dll (uses win32 interop)" + cp $sourceFolder/Libraries/Mono/$assembly.dll $path/$assembly.dll + else + echo "Remove $assembly.dll (uses win32 interop)" + rm $path/$assembly.dll + fi + + fi + done - PackageFiles "$folder" "$framework" "$runtime" + # Copy more stable version of Vectors for mono <5.12 + if [ -e $path/System.Numerics.Vectors.dll ]; then + packageDir="$HOME/.nuget/packages/system.numerics.vectors/4.5.0" + + if [ ! -d "$HOME/.nuget/packages/system.numerics.vectors/4.5.0" ]; then + # May reside in the NuGetFallback folder, which is harder to find + # Download somewhere to get the real cache populated + if [ $runtime = "dotnet" ] ; then + $nuget install System.Numerics.Vectors -Version 4.5.0 -Output ./_temp/System.Numerics.Vectors + else + mono $nuget install System.Numerics.Vectors -Version 4.5.0 -Output ./_temp/System.Numerics.Vectors + fi + rm -rf ./_temp/System.Numerics.Vectors + fi + # Copy the netstandard2.0 version rather than net46 + cp "$packageDir/lib/netstandard2.0/System.Numerics.Vectors.dll" $path/ + fi +} + +PackageMono() +{ + ProgressStart 'Creating Mono Package' + + rm -rf $outputFolderLinux + + echo "Copying Binaries" + cp -r $outputFolder $outputFolderLinux + + echo "Creating MDBs" + CreateMdbs $outputFolderLinux + + echo "Removing PDBs" + find $outputFolderLinux -name "*.pdb" -exec rm "{}" \; echo "Removing Service helpers" - rm -f $folder/ServiceUninstall.* - rm -f $folder/ServiceInstall.* + rm -f $outputFolderLinux/ServiceUninstall.* + rm -f $outputFolderLinux/ServiceInstall.* + + echo "Removing native windows binaries Sqlite, MediaInfo" + rm -f $outputFolderLinux/sqlite3.* + rm -f $outputFolderLinux/MediaInfo.* + + PatchMono $outputFolderLinux + + echo "Adding Sonarr.Core.dll.config (for dllmap)" + cp $sourceFolder/NzbDrone.Core/Sonarr.Core.dll.config $outputFolderLinux + + # Remove Http binding redirect by renaming it + # We don't need this anymore once our minimum mono version is 5.10 + sed -i "s/System.Net.Http/System.Net.Http.Mono/g" $outputFolderLinux/Sonarr.Console.exe.config + + echo "Renaming Sonarr.Console.exe to Sonarr.exe" + rm $outputFolderLinux/Sonarr.exe* + for file in $outputFolderLinux/Sonarr.Console.exe*; do + mv "$file" "${file//.Console/}" + done echo "Removing Sonarr.Windows" - rm $folder/Sonarr.Windows.* + rm $outputFolderLinux/Sonarr.Windows.* echo "Adding Sonarr.Mono to UpdatePackage" - cp $folder/Sonarr.Mono.* $folder/Sonarr.Update - if [ "$framework" = "$framework" ]; then - cp $folder/Mono.Posix.NETStandard.* $folder/Sonarr.Update - cp $folder/libMonoPosixHelper.* $folder/Sonarr.Update - fi + cp $outputFolderLinux/Sonarr.Mono.* $outputFolderLinux/$updateSubFolder/ - ProgressEnd "Creating $runtime Package for $framework" + ProgressEnd 'Creating Mono Package' } PackageMacOS() { - local framework="$1" - local runtime="$2" + ProgressStart 'Creating MacOS Package' - ProgressStart "Creating $runtime Package for $framework" + rm -rf $outputFolderMacOS + mkdir $outputFolderMacOS + + echo "Copying Binaries" + cp -r $outputFolderLinux/* $outputFolderMacOS - local folder=$artifactsFolder/$runtime/$framework/Sonarr + echo "Adding Sonarr Launcher" + cp ./distribution/osx/Launcher/dist/Launcher $outputFolderMacOS/ + mv $outputFolderMacOS/Sonarr.exe $outputFolderMacOS/Sonarr.exe.bak + mv $outputFolderMacOS/Launcher $outputFolderMacOS/Sonarr + mv $outputFolderMacOS/Sonarr.exe.bak $outputFolderMacOS/Sonarr.exe + chmod +x $outputFolderMacOS/Sonarr - PackageFiles "$folder" "$framework" "$runtime" + echo "Adding Sonarr.Update Launcher" + cp ./distribution/osx/Launcher/dist/Launcher $outputFolderMacOS/Sonarr.Update/ + mv $outputFolderMacOS/Sonarr.Update/Sonarr.Update.exe $outputFolderMacOS/Sonarr.Update/Sonarr.Update.exe.bak + mv $outputFolderMacOS/Sonarr.Update/Launcher $outputFolderMacOS/Sonarr.Update/Sonarr.Update + mv $outputFolderMacOS/Sonarr.Update/Sonarr.Update.exe.bak $outputFolderMacOS/Sonarr.Update/Sonarr.Update.exe + chmod +x $outputFolderMacOS/Sonarr.Update/Sonarr.Update - echo "Removing Service helpers" - rm -f $folder/ServiceUninstall.* - rm -f $folder/ServiceInstall.* + echo "Adding sqlite dylibs" + cp $sourceFolder/Libraries/Sqlite/*.dylib $outputFolderMacOS - echo "Removing Sonarr.Windows" - rm $folder/Sonarr.Windows.* + echo "Adding MediaInfo dylib" + cp $sourceFolder/Libraries/MediaInfo/*.dylib $outputFolderMacOS - echo "Adding Sonarr.Mono to UpdatePackage" - cp $folder/Sonarr.Mono.* $folder/Sonarr.Update - if [ "$framework" = "$framework" ]; then - cp $folder/Mono.Posix.NETStandard.* $folder/Sonarr.Update - cp $folder/libMonoPosixHelper.* $folder/Sonarr.Update - fi - - ProgressEnd "Creating $runtime Package for $framework" + ProgressEnd 'Creating MacOS Package' } PackageMacOSApp() { - local framework="$1" - local runtime="$2" + ProgressStart 'Creating macOS App Package' - ProgressStart "Creating $runtime App Package for $framework" + rm -rf $outputFolderMacOSApp + mkdir $outputFolderMacOSApp + cp -r ./distribution/osx/Sonarr.app $outputFolderMacOSApp + mkdir -p $outputFolderMacOSApp/Sonarr.app/Contents/MacOS - local folder=$artifactsFolder/$runtime-app/$framework - - rm -rf $folder - mkdir -p $folder - cp -r distribution/macOS/Sonarr.app $folder - mkdir -p $folder/Sonarr.app/Contents/MacOS + echo "Adding Sonarr Launcher" + cp ./distribution/osx/Launcher/dist/Launcher $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/ + mv $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/Launcher $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/Sonarr + chmod +x $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/Sonarr echo "Copying Binaries" - cp -r $artifactsFolder/$runtime/$framework/Sonarr/* $folder/Sonarr.app/Contents/MacOS + mkdir -p $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/bin + cp -r $outputFolderLinux/* $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/bin/ + + echo "Adding sqlite dylibs" + cp $sourceFolder/Libraries/Sqlite/*.dylib $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/bin/ + + echo "Adding MediaInfo dylib" + cp $sourceFolder/Libraries/MediaInfo/*.dylib $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/bin/ echo "Removing Update Folder" - rm -r $folder/Sonarr.app/Contents/MacOS/Sonarr.Update + rm -r $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/bin/Sonarr.Update + echo "# Do Not Edit\nPackageVersion=${BUILD_NUMBER}\nPackageAuthor=[Team Sonarr](https://sonarr.tv)\nReleaseVersion=${BUILD_NUMBER}\nUpdateMethod=$PackageUpdater\nBranch=${Branch:-master}" > $outputFolderMacOSApp/Sonarr.app/Contents/MacOS/package_info - ProgressEnd "Creating $runtime App Package for $framework" + ProgressEnd 'Creating macOS App Package' +} + +PackageTestsMono() +{ + ProgressStart 'Creating Mono Test Package' + + rm -rf $testPackageFolderLinux + + echo "Copying Binaries" + cp -r $testPackageFolder $testPackageFolderLinux + + if [ $runtime = "dotnet" ] ; then + $nuget install NUnit.ConsoleRunner -Version 3.10.0 -Output $testPackageFolderLinux + else + mono $nuget install NUnit.ConsoleRunner -Version 3.10.0 -Output $testPackageFolderLinux + fi + + echo "Creating MDBs" + CreateMdbs $testPackageFolderLinux + + echo "Removing PDBs" + find $testPackageFolderLinux -name "*.pdb" -exec rm "{}" \; + + PatchMono $testPackageFolderLinux + + echo "Adding Sonarr.Core.dll.config (for dllmap)" + cp $sourceFolder/NzbDrone.Core/Sonarr.Core.dll.config $testPackageFolderLinux + + # Remove Http binding redirect by renaming it + # We don't need this anymore once our minimum mono version is 5.10 + sed -i "s/System.Net.Http/System.Net.Http.Mono/g" $testPackageFolderLinux/Sonarr.Common.Test.dll.config + + cp ./test.sh $testPackageFolderLinux/ + dos2unix $testPackageFolderLinux/test.sh + + echo "Removing Sonarr.Windows" + rm $testPackageFolderLinux/Sonarr.Windows.* + + rm -f $testPackageFolderLinux/*.log.config + + CleanFolder $testPackageFolderLinux true + + ProgressEnd 'Creating Linux Test Package' +} + +PackageTestsWindows() +{ + ProgressStart 'Creating Windows Test Package' + + rm -rf $testPackageFolderWindows + + echo "Copying Binaries" + cp -r $testPackageFolder $testPackageFolderWindows + + if [ $runtime = "dotnet" ] ; then + $nuget install NUnit.ConsoleRunner -Version 3.10.0 -Output $testPackageFolderWindows + else + mono $nuget install NUnit.ConsoleRunner -Version 3.10.0 -Output $testPackageFolderWindows + fi + + cp ./test.sh $testPackageFolderWindows + + echo "Removing Sonarr.Mono" + rm -f $testPackageFolderWindows/Sonarr.Mono.* + + rm -f $testPackageFolderWindows/*.log.config + + CleanFolder $testPackageFolderWindows true + + ProgressEnd 'Creating Windows Test Package' } PackageWindows() { - local framework="$1" - local runtime="$2" + ProgressStart 'Creating Windows Package' - ProgressStart "Creating Windows Package for $framework" - - local folder=$artifactsFolder/$runtime/$framework/Sonarr - - PackageFiles "$folder" "$framework" "$runtime" - cp -r $outputFolder/$framework-windows/$runtime/publish/* $folder + rm -rf $outputFolderWindows + + echo "Copying Binaries" + cp -r $outputFolder $outputFolderWindows echo "Removing Sonarr.Mono" - rm -f $folder/Sonarr.Mono.* - rm -f $folder/Mono.Posix.NETStandard.* - rm -f $folder/libMonoPosixHelper.* + rm -f $outputFolderWindows/Sonarr.Mono.* echo "Adding Sonarr.Windows to UpdatePackage" - cp $folder/Sonarr.Windows.* $folder/Sonarr.Update + cp $outputFolderWindows/Sonarr.Windows.* $outputFolderWindows/$updateSubFolder/ - ProgressEnd "Creating Windows Package for $framework" + ProgressEnd 'Creating Windows Package' } -Package() +PublishArtifacts() { - local framework="$1" - local runtime="$2" - local SPLIT - - IFS='-' read -ra SPLIT <<< "$runtime" - - case "${SPLIT[0]}" in - linux|freebsd*) - PackageLinux "$framework" "$runtime" - ;; - win) - PackageWindows "$framework" "$runtime" - ;; - osx) - PackageMacOS "$framework" "$runtime" - ;; - esac -} - -PackageTests() -{ - local framework="$1" - local runtime="$2" - - ProgressStart "Creating $runtime Test Package for $framework" - - cp test.sh "$testPackageFolder/$framework/$runtime/publish" - - rm -f $testPackageFolder/$framework/$runtime/*.log.config - - ProgressEnd "Creating $runtime Test Package for $framework" -} - -UploadTestArtifacts() -{ - local framework="$1" - - ProgressStart 'Publishing Test Artifacts' - - # Tests - for dir in $testPackageFolder/$framework/* - do - local runtime=$(basename "$dir") - echo "##teamcity[publishArtifacts '$testPackageFolder/$framework/$runtime/publish/** => tests.$runtime.zip']" - done - - ProgressEnd 'Publishing Test Artifacts' -} - -UploadArtifacts() -{ - local framework="$1" - ProgressStart 'Publishing Artifacts' + # Tests + echo "##teamcity[publishArtifacts '$testPackageFolderWindows/** => tests.windows.zip']" + echo "##teamcity[publishArtifacts '$testPackageFolderLinux/** => tests.linux.zip']" + # Releases - for dir in $artifactsFolder/* - do - local runtime=$(basename "$dir") - - echo "##teamcity[publishArtifacts '$artifactsFolder/$runtime/$framework/** => Sonarr.$BRANCH.$SONARR_VERSION.$runtime.zip']" - done - - # Debian Package / Windows installer / macOS app + echo "##teamcity[publishArtifacts '$outputFolderWindows/** => Sonarr.$BRANCH.$BUILD_NUMBER.windows.zip!Sonarr']" + echo "##teamcity[publishArtifacts '$outputFolderLinux/** => Sonarr.$BRANCH.$BUILD_NUMBER.linux.tar.gz!Sonarr']" + echo "##teamcity[publishArtifacts '$outputFolderMacOS/** => Sonarr.$BRANCH.$BUILD_NUMBER.macos.tar.gz!Sonarr']" + echo "##teamcity[publishArtifacts '$outputFolderMacOSApp/** => Sonarr.$BRANCH.$BUILD_NUMBER.macos.zip']" + + # Debian Package echo "##teamcity[publishArtifacts 'distribution/** => distribution.zip']" - + ProgressEnd 'Publishing Artifacts' } -UploadUIArtifacts() -{ - local framework="$1" - - ProgressStart 'Publishing UI Artifacts' - - # UI folder - echo "##teamcity[publishArtifacts '$outputFolder/UI/** => UI.zip']" - - ProgressEnd 'Publishing UI Artifacts' -} - # Use mono or .net depending on OS case "$(uname -s)" in CYGWIN*|MINGW32*|MINGW64*|MSYS*) # on windows, use dotnet - os="windows" + runtime="dotnet" ;; *) # otherwise use mono - os="posix" + runtime="mono" ;; esac -POSITIONAL=() - -if [ $# -eq 0 ]; then - echo "No arguments provided, building everything" - BACKEND=YES - FRONTEND=YES - PACKAGES=YES - LINT=YES - ENABLE_EXTRA_PLATFORMS=NO - ENABLE_EXTRA_PLATFORMS_IN_SDK=NO -fi - -while [[ $# -gt 0 ]] -do -key="$1" - -case $key in - --backend) - BACKEND=YES - shift # past argument - ;; - --enable-bsd|--enable-extra-platforms) - ENABLE_EXTRA_PLATFORMS=YES - shift # past argument - ;; - --enable-extra-platforms-in-sdk) - ENABLE_EXTRA_PLATFORMS_IN_SDK=YES - shift # past argument - ;; - -r|--runtime) - RID="$2" - shift # past argument - shift # past value - ;; - -f|--framework) - FRAMEWORK="$2" - shift # past argument - shift # past value - ;; - --frontend) - FRONTEND=YES - shift # past argument - ;; - --packages) - PACKAGES=YES - shift # past argument - ;; - --lint) - LINT=YES - shift # past argument - ;; - --all) - BACKEND=YES - FRONTEND=YES - PACKAGES=YES - LINT=YES - shift # past argument - ;; - *) # unknown option - POSITIONAL+=("$1") # save it in an array for later - shift # past argument - ;; -esac -done -set -- "${POSITIONAL[@]}" # restore positional parameters - -if [ "$ENABLE_EXTRA_PLATFORMS_IN_SDK" = "YES" ]; -then - EnableExtraPlatformsInSDK -fi - -if [ "$BACKEND" = "YES" ]; -then - UpdateVersionNumber - if [ "$ENABLE_EXTRA_PLATFORMS" = "YES" ]; - then - EnableExtraPlatforms - fi - - Build - - if [[ -z "$RID" || -z "$FRAMEWORK" ]]; - then - PackageTests "$framework" "win-x64" - PackageTests "$framework" "win-x86" - PackageTests "$framework" "linux-x64" - PackageTests "$framework" "linux-musl-x64" - PackageTests "$framework" "osx-x64" - if [ "$ENABLE_EXTRA_PLATFORMS" = "YES" ]; - then - PackageTests "$framework" "freebsd-x64" - fi - else - PackageTests "$FRAMEWORK" "$RID" - fi - - UploadTestArtifacts "$framework" -fi - -if [ "$FRONTEND" = "YES" ]; -then - YarnInstall - - if [ "$LINT" = "YES" ]; - then - LintUI - fi - - RunWebpack - UploadUIArtifacts -fi - -if [ "$PACKAGES" = "YES" ]; -then - UpdateVersionNumber - - if [[ -z "$RID" || -z "$FRAMEWORK" ]]; - then - Package "$framework" "win-x64" - Package "$framework" "win-x86" - Package "$framework" "linux-x64" - Package "$framework" "linux-musl-x64" - Package "$framework" "linux-arm64" - Package "$framework" "linux-musl-arm64" - Package "$framework" "linux-arm" - Package "$framework" "osx-x64" - Package "$framework" "osx-arm64" - if [ "$ENABLE_EXTRA_PLATFORMS" = "YES" ]; - then - Package "$framework" "freebsd-x64" - fi - else - Package "$FRAMEWORK" "$RID" - fi - - UploadArtifacts "$framework" -fi +UpdateVersionNumber +Build +CreateReleaseInfo +RunWebpack +PackageMono +PackageMacOS +PackageMacOSApp +PackageTestsMono +PackageTestsWindows +PackageWindows +PublishArtifacts diff --git a/distribution/debian.sh b/distribution/debian.sh new file mode 100644 index 000000000..21ce857e7 --- /dev/null +++ b/distribution/debian.sh @@ -0,0 +1,64 @@ +fromdos ./debian/* +chmod ugo-x ./debian/* +cp -r ./debian ./debian_backup + +BuildVersion=${dependent_build_number:-3.10.0.999} +BuildBranch=${dependent_build_branch:-master} +BootstrapVersion=`echo "$BuildVersion" | cut -d. -f1,2,3` +BootstrapUpdater="BuiltIn" +PackageUpdater="apt" + +echo Version: "$BuildVersion" Branch: "$BuildBranch" + +rm -r ./sonarr_bin/Sonarr.Update +chmod -R ugo-x,ugo+rwX,go-w ./sonarr_bin/* + +echo Updating changelog for $BuildVersion +sed -i "s:{version}:$BuildVersion:g; s:{branch}:$BuildBranch:g;" debian/changelog +sed -i "s:{version}:$BuildVersion:g; s:{updater}:$PackageUpdater:g" debian/preinst debian/postinst debian/postrm +sed -i '/#BEGIN BUILTIN UPDATER/,/#END BUILTIN UPDATER/d' debian/preinst debian/postinst debian/postrm +echo "# Do Not Edit\nPackageVersion=$BuildVersion\nPackageAuthor=[Team Sonarr](https://sonarr.tv)\nReleaseVersion=$BuildVersion\nUpdateMethod=$PackageUpdater\nBranch=$BuildBranch" > package_info + +echo Running debuild for $BuildVersion +if [ -z "${TEST_OUTPUT}" ]; then + debuild -b +else + debuild -us -uc -b +fi + +# Restore debian directory to the original files +rm -rf ./debian +mv ./debian_backup ./debian + +echo Updating changelog for $BootstrapVersion +sed -i "s:{version}:$BootstrapVersion:g; s:{branch}:$BuildBranch:g;" debian/changelog +sed -i "s:{version}:$BuildVersion:g; s:{updater}:$BootstrapUpdater:g" debian/preinst debian/postinst debian/postrm +sed -i '/#BEGIN BUILTIN UPDATER/d; /#END BUILTIN UPDATER/d' debian/preinst debian/postinst debian/postrm +echo "# Do Not Edit\nPackageVersion=$BootstrapVersion\nPackageAuthor=[Team Sonarr](https://sonarr.tv)\nReleaseVersion=$BuildVersion\nUpdateMethod=$BootstrapUpdater\nBranch=$BuildBranch" > package_info + +echo Running debuild for $BootstrapVersion +if [ -z "${TEST_OUTPUT}" ]; then + debuild -b +else + debuild -us -uc -b +fi + +echo Moving stuff around +mv ../sonarr_*.deb ./ +mv ../sonarr_*.changes ./ +rm ../sonarr_*.build + +if [ -z "${TEST_OUTPUT}" ]; then + echo Signing Package + dpkg-sig -k 884589CE --sign builder "sonarr_${BuildVersion}_all.deb" + dpkg-sig -k 884589CE --sign builder "sonarr_${BootstrapVersion}_all.deb" + + echo running alien + alien -r -v ./*.deb +else + echo "Exporting packages to ${TEST_OUTPUT}" + dpkg -e "sonarr_${BuildVersion}_all.deb" ${TEST_OUTPUT}/sonarr-build + dpkg -e "sonarr_${BootstrapVersion}_all.deb" ${TEST_OUTPUT}/sonarr-release + + cp *.deb ${TEST_OUTPUT}/ +fi diff --git a/distribution/debian/.editorconfig b/distribution/debian/.editorconfig new file mode 100644 index 000000000..ed7f9d309 --- /dev/null +++ b/distribution/debian/.editorconfig @@ -0,0 +1,6 @@ +[*] +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 2 diff --git a/distribution/debian/changelog b/distribution/debian/changelog new file mode 100644 index 000000000..e5c3c5745 --- /dev/null +++ b/distribution/debian/changelog @@ -0,0 +1,5 @@ +sonarr ({version}) {branch}; urgency=low + + * Automatic Release. + + -- Sonarr Sun, 28 Jan 2018 00:00:00 -0700 diff --git a/distribution/debian/compat b/distribution/debian/compat new file mode 100644 index 000000000..f599e28b8 --- /dev/null +++ b/distribution/debian/compat @@ -0,0 +1 @@ +10 diff --git a/distribution/debian/config b/distribution/debian/config new file mode 100644 index 000000000..fb68205ff --- /dev/null +++ b/distribution/debian/config @@ -0,0 +1,17 @@ +#!/bin/sh -e + +. /usr/share/debconf/confmodule + +db_beginblock +db_input high sonarr/owning_user || true +db_input high sonarr/owning_group || true +db_endblock +db_go + +db_beginblock +db_input low sonarr/owning_umask || true +db_input low sonarr/config_directory || true +db_endblock +db_go + +exit 0 diff --git a/distribution/debian/control b/distribution/debian/control new file mode 100644 index 000000000..1ddefd5dd --- /dev/null +++ b/distribution/debian/control @@ -0,0 +1,22 @@ +Section: web +Priority: optional +Maintainer: Sonarr +Source: sonarr +Homepage: https://sonarr.tv +Vcs-Git: git@github.com:Sonarr/Sonarr.git +Vcs-Browser: https://github.com/Sonarr/Sonarr +Build-Depends: debhelper (>= 9), + dh-systemd (>= 1.5), + mono-devel (>= 5.18), + libmono-cil-dev (>= 5.18), + cli-common-dev (>= 0.9+xamarin5) + +Package: sonarr +Architecture: all +Provides: nzbdrone +Conflicts: nzbdrone +Replaces: nzbdrone +Depends: adduser, libsqlite3-0 (>= 3.7), libmediainfo0v5 (>= 0.7.52) | libmediainfo0 (>= 0.7.52), mono-runtime (>= 5.18), ca-certificates-mono, libmono-system-net-http4.0-cil (>= 4.0.0~alpha1), ${cli:Depends}, ${misc:Depends} +Recommends: libmediainfo0v5 (>= 18.03) | libmediainfo0 (>= 18.03) +Suggests: sqlite3 (>= 3.7), mediainfo (>= 0.7.52) +Description: Internet PVR diff --git a/distribution/debian/copyright b/distribution/debian/copyright new file mode 100644 index 000000000..8d2f3f1d3 --- /dev/null +++ b/distribution/debian/copyright @@ -0,0 +1,24 @@ +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: sonarr +Source: https://github.com/Sonarr/Sonarr + +Files: * +Copyright: 2010-2016 Sonarr + +License: GPL-3.0+ + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + . + This package is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + . + You should have received a copy of the GNU General Public License + along with this program. If not, see . + . + On Debian systems, the complete text of the GNU General + Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". diff --git a/distribution/debian/files b/distribution/debian/files new file mode 100644 index 000000000..01702ddbb --- /dev/null +++ b/distribution/debian/files @@ -0,0 +1 @@ +sonarr_3.0.0.0_all.deb web optional diff --git a/distribution/debian/install b/distribution/debian/install new file mode 100644 index 000000000..b3cf8bedb --- /dev/null +++ b/distribution/debian/install @@ -0,0 +1,2 @@ +sonarr_bin/* usr/lib/sonarr/bin +package_info usr/lib/sonarr diff --git a/distribution/debian/install.sh b/distribution/debian/install.sh deleted file mode 100644 index 803d7cf51..000000000 --- a/distribution/debian/install.sh +++ /dev/null @@ -1,182 +0,0 @@ -#!/bin/bash -### Description: Sonarr .NET Debian install -### Originally written for Radarr by: DoctorArr - doctorarr@the-rowlands.co.uk on 2021-10-01 v1.0 -### Updates for servarr suite made by Bakerboy448, DoctorArr, brightghost, aeramor and VP-EN -### Version v1.0.0 2023-12-29 - StevieTV - adapted from servarr script for Sonarr installs -### Version V1.0.1 2024-01-02 - StevieTV - remove UTF8-BOM -### Version V1.0.2 2024-01-03 - markus101 - Get user input from /dev/tty -### Version V1.0.3 2024-01-06 - StevieTV - exit script when it is ran from install directory - -### Boilerplate Warning -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -#LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -#OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -#WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -scriptversion="1.0.3" -scriptdate="2024-01-06" - -set -euo pipefail - -echo "Running Sonarr Install Script - Version [$scriptversion] as of [$scriptdate]" - -# Am I root?, need root! - -if [ "$EUID" -ne 0 ]; then - echo "Please run as root." - exit -fi - -app="sonarr" -app_port="8989" -app_prereq="curl sqlite3 wget" -app_umask="0002" -branch="main" - -# Constants -### Update these variables as required for your specific instance -installdir="/opt" # {Update me if needed} Install Location -bindir="${installdir}/${app^}" # Full Path to Install Location -datadir="/var/lib/$app/" # {Update me if needed} AppData directory to use -app_bin=${app^} # Binary Name of the app - -# This script should not be ran from installdir, otherwise later in the script the extracted files will be removed before they can be moved to installdir. -if [ "$installdir" == "$(dirname -- "$( readlink -f -- "$0"; )")" ] || [ "$bindir" == "$(dirname -- "$( readlink -f -- "$0"; )")" ]; then - echo "You should not run this script from the intended install directory. The script will exit. Please re-run it from another directory" - exit -fi - -# Prompt User -read -r -p "What user should ${app^} run as? (Default: $app): " app_uid < /dev/tty -app_uid=$(echo "$app_uid" | tr -d ' ') -app_uid=${app_uid:-$app} -# Prompt Group -read -r -p "What group should ${app^} run as? (Default: media): " app_guid < /dev/tty -app_guid=$(echo "$app_guid" | tr -d ' ') -app_guid=${app_guid:-media} - -echo "This will install [${app^}] to [$bindir] and use [$datadir] for the AppData Directory" -echo "${app^} will run as the user [$app_uid] and group [$app_guid]. By continuing, you've confirmed that the selected user and group will have READ and WRITE access to your Media Library and Download Client Completed Download directories" -read -n 1 -r -s -p $'Press enter to continue or ctrl+c to exit...\n' < /dev/tty - -# Create User / Group as needed -if [ "$app_guid" != "$app_uid" ]; then - if ! getent group "$app_guid" >/dev/null; then - groupadd "$app_guid" - fi -fi -if ! getent passwd "$app_uid" >/dev/null; then - adduser --system --no-create-home --ingroup "$app_guid" "$app_uid" - echo "Created and added User [$app_uid] to Group [$app_guid]" -fi -if ! getent group "$app_guid" | grep -qw "$app_uid"; then - echo "User [$app_uid] did not exist in Group [$app_guid]" - usermod -a -G "$app_guid" "$app_uid" - echo "Added User [$app_uid] to Group [$app_guid]" -fi - -# Stop the App if running -if service --status-all | grep -Fq "$app"; then - systemctl stop "$app" - systemctl disable "$app".service - echo "Stopped existing $app" -fi - -# Create Appdata Directory - -# AppData -mkdir -p "$datadir" -chown -R "$app_uid":"$app_guid" "$datadir" -chmod 775 "$datadir" -echo "Directories created" -# Download and install the App - -# prerequisite packages -echo "" -echo "Installing pre-requisite Packages" -# shellcheck disable=SC2086 -apt update && apt install -y $app_prereq -echo "" -ARCH=$(dpkg --print-architecture) -# get arch -dlbase="https://services.sonarr.tv/v1/download/$branch/latest?version=4&os=linux" -case "$ARCH" in -"amd64") DLURL="${dlbase}&arch=x64" ;; -"armhf") DLURL="${dlbase}&arch=arm" ;; -"arm64") DLURL="${dlbase}&arch=arm64" ;; -*) - echo "Arch not supported" - exit 1 - ;; -esac -echo "" -echo "Removing previous tarballs" -# -f to Force so we fail if it doesn't exist -rm -f "${app^}".*.tar.gz -echo "" -echo "Downloading..." -wget --content-disposition "$DLURL" -tar -xvzf "${app^}".*.tar.gz -echo "" -echo "Installation files downloaded and extracted" - -# remove existing installs -echo "Removing existing installation" -rm -rf "$bindir" -echo "Installing..." -mv "${app^}" $installdir -chown "$app_uid":"$app_guid" -R "$bindir" -chmod 775 "$bindir" -rm -rf "${app^}.*.tar.gz" -# Ensure we check for an update in case user installs older version or different branch -touch "$datadir"/update_required -chown "$app_uid":"$app_guid" "$datadir"/update_required -echo "App Installed" -# Configure Autostart - -# Remove any previous app .service -echo "Removing old service file" -rm -rf /etc/systemd/system/"$app".service - -# Create app .service with correct user startup -echo "Creating service file" -cat </dev/null -[Unit] -Description=${app^} Daemon -After=syslog.target network.target -[Service] -User=$app_uid -Group=$app_guid -UMask=$app_umask -Type=simple -ExecStart=$bindir/$app_bin -nobrowser -data=$datadir -TimeoutStopSec=20 -KillMode=process -Restart=on-failure -[Install] -WantedBy=multi-user.target -EOF - -# Start the App -echo "Service file created. Attempting to start the app" -systemctl -q daemon-reload -systemctl enable --now -q "$app" - -# Finish Update/Installation -host=$(hostname -I) -ip_local=$(grep -oP '^\S*' <<<"$host") -echo "" -echo "Install complete" -sleep 10 -STATUS="$(systemctl is-active "$app")" -if [ "${STATUS}" = "active" ]; then - echo "Browse to http://$ip_local:$app_port for the ${app^} GUI" -else - echo "${app^} failed to start" -fi - -# Exit -exit 0 diff --git a/distribution/debian/postinst b/distribution/debian/postinst new file mode 100644 index 000000000..df3c8fd42 --- /dev/null +++ b/distribution/debian/postinst @@ -0,0 +1,111 @@ +#!/bin/sh +set -e + +BUILD_VERSION={version} +UPDATER={updater} + +. /usr/share/debconf/confmodule +db_get sonarr/owning_user +USER="$RET" +db_get sonarr/owning_group +GROUP="$RET" +db_get sonarr/owning_umask +UMASK="$RET" +db_get sonarr/config_directory +CONFDIR="$RET" + +# Add User and Group +if ! getent group "$GROUP" >/dev/null; then + groupadd "$GROUP" +fi +if ! getent passwd "$USER" >/dev/null; then + adduser --system --no-create-home --ingroup "$GROUP" "$USER" +fi + +if [ $1 = "configure" ]; then + # Migrate old Sonarr v3 alpha data dir from /var/opt/sonarr or user home + if [ -d "/var/opt/sonarr" ] && [ "$CONFDIR" != "/var/opt/sonarr" ] && [ ! -d "$CONFDIR" ]; then + varoptRoot="/var/opt/sonarr" + varoptAppData="$varoptRoot/.config/Sonarr" + sonarrUserHome=`getent passwd $USER | cut -d ':' -f 6` + sonarrAppData="$sonarrUserHome/.config/Sonarr" + if [ -f "$varoptRoot/sonarr.db" ]; then + # Handle /var/opt/sonarr/sonarr.db + mv "$varoptRoot" "$CONFDIR" + elif [ -f "$varoptAppData/sonarr.db" ]; then + # Handle /var/opt/sonarr/.config/Sonarr/sonarr.db + mv "$varoptAppData" "$CONFDIR" + rm -rf "$varoptRoot" + elif [ -f "$sonarrAppData/sonarr.db" ]; then + # Handle ~/.config/Sonarr/sonarr.db + mv "$sonarrAppData" "$CONFDIR" + rm -rf "$sonarrAppData" + else + mv "$varoptRoot" "$CONFDIR" + fi + chown -R $USER:$GROUP "$CONFDIR" + chmod -R 775 "$CONFDIR" + fi + + # Migrate old NzbDrone data dir + if [ -d "/usr/lib/sonarr/nzbdrone-appdata" ] && [ ! -d "$CONFDIR" ]; then + NZBDRONE_DATA=`readlink /usr/lib/sonarr/nzbdrone-appdata` + if [ -f "$NZBDRONE_DATA/config.xml" ] && [ -f "$NZBDRONE_DATA/nzbdrone.db" ]; then + echo "Found NzbDrone database in $NZBDRONE_DATA, copying to $CONFDIR." + mkdir -p "$CONFDIR" + cp $NZBDRONE_DATA/config.xml $NZBDRONE_DATA/nzbdrone.db* "$CONFDIR/" + chown -R $USER:$GROUP "$CONFDIR" + chmod -R 775 "$CONFDIR" + else + echo "Missing NzbDrone database in $NZBDRONE_DATA, skipping migration." + fi + rm /usr/lib/sonarr/nzbdrone-appdata + fi +fi + +# Create data directory +if [ ! -d "$CONFDIR" ]; then + mkdir -p "$CONFDIR" +fi + +# Set permissions on data directory (always do this instead only on creation in case user was changed via dpkg-reconfigure) +chown -R $USER:$GROUP "$CONFDIR" + +#BEGIN BUILTIN UPDATER +# Apply patch if present +if [ "$UPDATER" = "BuiltIn" ] && [ -f /usr/lib/sonarr/bin_patch/release_info ]; then + # It shouldn't be possible to get a wrong bin_patch, but let's check anyway and throw it away if it's wrong + currentVersion=`cat /usr/lib/sonarr/bin_patch/release_info | grep 'ReleaseVersion=' | cut -d= -f 2` + currentRelease=`echo "$currentVersion" | cut -d. -f1,2,3` + currentBuild=`echo "$currentVersion" | cut -d. -f4` + targetVersion=$BUILD_VERSION + targetRelease=`echo "$targetVersion" | cut -d. -f1,2,3` + targetBuild=`echo "$targetVersion" | cut -d. -f4` + + if [ "$currentRelease" = "$targetRelease" ] && [ "$currentBuild" -gt "$targetBuild" ]; then + echo "Applying $currentVersion from BuiltIn updater instead of downgrading to $targetVersion" + rm -rf /usr/lib/sonarr/bin + mv /usr/lib/sonarr/bin_patch /usr/lib/sonarr/bin + else + rm -rf /usr/lib/sonarr/bin_patch + fi +fi +#END BUILTIN UPDATER + +# Set permissions on /usr/lib/sonarr +chown -R $USER:$GROUP /usr/lib/sonarr + +# Update sonarr.service file +sed -i "s:User=\w*:User=$USER:g; s:Group=\w*:Group=$GROUP:g; s:UMask=[0-9]*:UMask=$UMASK:g; s:-data=.*$:-data=$CONFDIR:g" /lib/systemd/system/sonarr.service + +#BEGIN BUILTIN UPDATER +if [ "$UPDATER" = "BuiltIn" ]; then + # If we upgraded, signal Sonarr to do an update check on startup instead of scheduled. + touch $CONFDIR/update_required + chown $USER:$GROUP $CONFDIR/update_required +fi +#END BUILTIN UPDATER + +#DEBHELPER# + +exit 0 diff --git a/distribution/debian/postrm b/distribution/debian/postrm new file mode 100644 index 000000000..d13374776 --- /dev/null +++ b/distribution/debian/postrm @@ -0,0 +1,36 @@ +#!/bin/sh +set -e + +BUILD_VERSION={version} +UPDATER={updater} + +if [ $1 = "abort-install" ]; then + # preinst was aborted, possibly due to NzbDrone still running. + # Nothing to do here + : +fi + +# The bin directory is expected to be empty, unless the BuiltIn updater added files. +if [ $1 = "remove" ] && [ -d /usr/lib/sonarr/bin ]; then + rm -rf /usr/lib/sonarr/bin +fi + +#BEGIN BUILTIN UPDATER +# Remove any existing patch if still present +if [ $1 = "remove" ] && [ -d /usr/lib/sonarr/bin_patch ]; then + rm -rf /usr/lib/sonarr/bin_patch +fi +#END BUILTIN UPDATER + +# Purge the entire sonarr configuration directory. +# TODO: Maybe move a minimal backup to tmp? +if [ $1 = "purge" ] && [ -e /usr/share/debconf/confmodule ]; then + . /usr/share/debconf/confmodule + db_get sonarr/config_directory + CONFDIR="$RET" + if [ -d "$CONFDIR" ]; then + rm -rf "$CONFDIR" + fi +fi + +#DEBHELPER# diff --git a/distribution/debian/preinst b/distribution/debian/preinst new file mode 100644 index 000000000..a07a6310c --- /dev/null +++ b/distribution/debian/preinst @@ -0,0 +1,91 @@ +#!/bin/sh +set -e + +BUILD_VERSION={version} +UPDATER={updater} + +# Deal with existing nzbdrone installs +# +# Existing nzbdrone packages do not have startup scripts and the process might still be running. +# If the user manually installed nzbdrone then the process might still be running too. +if [ $1 = "install" ]; then + psNzbDrone=`ps ax -o'user:20,pid,ppid,unit,args' | grep mono.*NzbDrone\\\\.exe || true` + if [ ! -z "$psNzbDrone" ]; then + # Get the user and optional systemd unit + psNzbDroneUser=`echo "$psNzbDrone" | tr -s ' ' | cut -d ' ' -f 1` + psNzbDroneUnit=`echo "$psNzbDrone" | tr -s ' ' | cut -d ' ' -f 4` + # Get the appdata from the cmdline or get it from the user dir + droneAppData=`echo "$psNzbDrone" | tr ' ' '\n' | grep -- "-data=" | cut -d= -f 2` + if [ "$droneAppData" = "" ]; then + droneUserHome=`getent passwd $psNzbDroneUser | cut -d ':' -f 6` + droneAppData="$droneUserHome/.config/NzbDrone" + fi + + if [ "$psNzbDroneUnit" != "-" ] && [ -d /run/systemd/system ]; then + if [ "$psNzbDroneUnit" = "sonarr.service" ]; then + # Conflicts with our new sonarr.service so we have to remove it + echo "NzbDrone systemd startup detected at $psNzbDroneUnit, stopping and removing..." + deb-systemd-invoke stop $psNzbDroneUnit >/dev/null + if [ -f "/etc/systemd/system/$psNzbDroneUnit" ]; then + rm /etc/systemd/system/$psNzbDroneUnit + fi + if [ -f "/usr/lib/systemd/system/$psNzbDroneUnit" ]; then + rm /usr/lib/systemd/system/$psNzbDroneUnit + fi + deb-systemd-helper purge $psNzbDroneUnit >/dev/null + deb-systemd-helper unmask $psNzbDroneUnit >/dev/null + systemctl --system daemon-reload >/dev/null || true + else + # Just disable it, so the user can revisit the settings later + echo "NzbDrone systemd startup detected at $psNzbDroneUnit, stopping and disabling..." + deb-systemd-invoke stop $psNzbDroneUnit >/dev/null + deb-systemd-invoke mask $psNzbDroneUnit >/dev/null + fi + else + # We don't support auto migration for other startup methods, so bail. + # This leaves the sonarr package in an incomplete state. + echo "ps: $psNzbDrone" + echo "Error: An existing Sonarr v2 (NzbDrone) process is running. Remove the NzbDrone auto-startup prior to installing sonarr." + exit 1 + fi + + # We don't have the debconf configuration yet so we can't migrate the data. + # Instead we symlink so postinst knows where it's at. + if [ -f "/usr/lib/sonarr/nzbdrone-appdata" ]; then + rm "/usr/lib/sonarr/nzbdrone-appdata" + else + mkdir -p "/usr/lib/sonarr" + fi + ln -s $droneAppData /usr/lib/sonarr/nzbdrone-appdata + fi +fi + +#BEGIN BUILTIN UPDATER +# Check for supported upgrade paths +if [ $1 = "upgrade" ] && [ "$UPDATER" = "BuiltIn" ] && [ -f /usr/lib/sonarr/bin/release_info ]; then + # If we allow the Built-In updater to upgrade from 3.0.1.123 to 3.0.2.500 and now apt is catching up to 3.0.2.425 + # then we need to deal with that 500->425 'downgrade'. + # We do that by preserving the binaries and using those instead for postinst. + + currentVersion=`cat /usr/lib/sonarr/bin/release_info | grep 'ReleaseVersion=' | cut -d= -f 2` + currentRelease=`echo "$currentVersion" | cut -d. -f1,2,3` + currentBuild=`echo "$currentVersion" | cut -d. -f4` + targetVersion=$BUILD_VERSION + targetRelease=`echo "$targetVersion" | cut -d. -f1,2,3` + targetBuild=`echo "$targetVersion" | cut -d. -f4` + + if [ -d /usr/lib/sonarr/bin_patch ]; then + rm -rf /usr/lib/sonarr/bin_patch + fi + + # Check if the existing version is already an upgrade for the included build + if [ "$currentRelease" = "$targetRelease" ] && [ "$currentBuild" -gt "$targetBuild" ]; then + echo "Preserving $currentVersion from BuiltIn updater instead of downgrading to $targetVersion" + cp -r /usr/lib/sonarr/bin /usr/lib/sonarr/bin_patch + fi +fi +#END BUILTIN UPDATER + +#DEBHELPER# + +exit 0 diff --git a/distribution/debian/rules b/distribution/debian/rules new file mode 100644 index 000000000..e775b54f7 --- /dev/null +++ b/distribution/debian/rules @@ -0,0 +1,21 @@ +#!/usr/bin/make -f + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +EXCLUDE_MODULEREFS = crypt32 httpapi __Internal ole32.dll libmonosgen-2.0 + +%: + dh $@ --with=systemd --with=cli + +# No init script, only systemd +override_dh_installinit: + true + +# Sonarr likes debug symbols for logging +override_dh_clistrip: + +override_dh_makeclilibs: + +override_dh_clideps: + dh_clideps -d -r $(patsubst %,--exclude-moduleref=%,$(EXCLUDE_MODULEREFS)) diff --git a/distribution/debian/sonarr.clideps-override b/distribution/debian/sonarr.clideps-override new file mode 100644 index 000000000..6ede15fed --- /dev/null +++ b/distribution/debian/sonarr.clideps-override @@ -0,0 +1,3 @@ +ignores msbuild +ignores libmediainfo0v5 +ignores libc6 diff --git a/distribution/debian/sonarr.service b/distribution/debian/sonarr.service index cd106de3d..939509157 100644 --- a/distribution/debian/sonarr.service +++ b/distribution/debian/sonarr.service @@ -11,7 +11,7 @@ Group=sonarr UMask=002 Type=simple -ExecStart=/opt/Sonarr/Sonarr -nobrowser -data=/var/lib/sonarr +ExecStart=/usr/bin/mono --debug /usr/lib/sonarr/bin/Sonarr.exe -nobrowser -data=/var/lib/sonarr TimeoutStopSec=20 KillMode=process Restart=on-failure diff --git a/distribution/debian/templates b/distribution/debian/templates new file mode 100644 index 000000000..40c7746f1 --- /dev/null +++ b/distribution/debian/templates @@ -0,0 +1,27 @@ +Template: sonarr/owning_user +Type: string +Default: sonarr +Description: Sonarr user: + Specify the user that is used to run Sonarr. The user will be created if it does not already exist. + The default 'sonarr' should work fine for most users. You can specify the user group next. + +Template: sonarr/owning_group +Type: string +Default: sonarr +Description: Sonarr group: + Specify the group that is used to run Sonarr. The group will be created if it does not already exist. + If the user doesn't already exist then this group will be used as the user's primary group. + Any media files created by Sonarr will be writeable by this group. + It's advisable to keep the group the same between download client, Sonarr and media centers. + +Template: sonarr/owning_umask +Type: string +Default: 0002 +Description: Sonarr umask: + Specifies the umask of the files created by Sonarr. 0002 means the files will be created with 664 as permissions. + +Template: sonarr/config_directory +Type: string +Default: /var/lib/sonarr +Description: Config directory: + Specify the directory where Sonarr stores the internal database and metadata. Media content will be stored elsewhere. diff --git a/distribution/osx/Launcher/LICENSE.LGPL.md b/distribution/osx/Launcher/LICENSE.LGPL.md new file mode 100644 index 000000000..c5bf65e21 --- /dev/null +++ b/distribution/osx/Launcher/LICENSE.LGPL.md @@ -0,0 +1,459 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + \ No newline at end of file diff --git a/distribution/osx/Launcher/README.md b/distribution/osx/Launcher/README.md new file mode 100644 index 000000000..5345e871d --- /dev/null +++ b/distribution/osx/Launcher/README.md @@ -0,0 +1,28 @@ +Code reused from duplicati, licensed under LGPL 2.1 +Modified for Sonarr by Taloth Saldono + +see here for the original source: https://github.com/duplicati/duplicati/tree/679981d29f8a6e445d3c1e6d41e72a673ffaa653/Installer/OSX + +License +------- + +Sonarr as a whole is licensed under GPL 3.0 as specified in the git repository root. + +But to preserve the original intent of the duplicati project, the modified versions of the sources in this folder are dual licensed under LGPL 2.1 and GPL 3.0. +Note: This exception can be freely removed in any copy of Sonarr sources as per LGPL/GPL licensing terms. + +A copy of the LGPL 2.1 license is included in the LICENSE.LGPL.md file. + +Purpose +------- + +The Launcher is a bootstrap/shim application that checks if the appropriate version of mono is installed and subsequently use it to execute Sonarr. +By using a separate application, instead of a shell script, this allows the user to assign certain operating system permissions to Sonarr specifically. + +Compiling the Launcher +---------------------- + +You need an OSX installation with xcode +Then run compile.sh in a terminal + +The generated dist/Launcher can be renamed to Sonarr and Sonarr.Update to serve as shims to run Sonarr.exe and Sonarr.Update.exe respectively. diff --git a/distribution/osx/Launcher/dist/Launcher b/distribution/osx/Launcher/dist/Launcher new file mode 100755 index 000000000..be72543ea Binary files /dev/null and b/distribution/osx/Launcher/dist/Launcher differ diff --git a/distribution/osx/Launcher/src/Launcher.m b/distribution/osx/Launcher/src/Launcher.m new file mode 100644 index 000000000..5af282665 --- /dev/null +++ b/distribution/osx/Launcher/src/Launcher.m @@ -0,0 +1,32 @@ +#import "run-with-mono.h" +#import "PFMoveApplication.h" + +int const MONO_VERSION_MAJOR = 5; +int const MONO_VERSION_MINOR = 20; + +int main() { + @autoreleasepool { + // Use our own executable name so the same compiled binary to be used for forks + NSString * const FileName = NSProcessInfo.processInfo.arguments[0].lastPathComponent; + + // Sonarr.Update.exe + NSString * const ASSEMBLY = [NSString stringWithFormat:@"%@.exe", FileName]; + + // Sonarr Update + NSString * const APP_NAME = [FileName stringByReplacingOccurrencesOfString:@"." withString:@" "]; + + // -sonarrupdate + NSString * const PROCESS_NAME = [NSString stringWithFormat:@"-%@", [FileName stringByReplacingOccurrencesOfString:@"." withString:@""].lowercaseString]; + + @try + { + PFMoveToApplicationsFolderIfNecessary(); + } + @catch (NSException * ex) + { + NSLog(@"Translocation/Quarantine check failed, starting normally. Reason: %@", ex.reason); + } + + return [RunWithMono runAssemblyWithMono:APP_NAME procnamesuffix:PROCESS_NAME assembly:ASSEMBLY major:MONO_VERSION_MAJOR minor:MONO_VERSION_MINOR]; + } +} diff --git a/distribution/osx/Launcher/src/PFMoveApplication.h b/distribution/osx/Launcher/src/PFMoveApplication.h new file mode 100644 index 000000000..c86a21a9b --- /dev/null +++ b/distribution/osx/Launcher/src/PFMoveApplication.h @@ -0,0 +1,32 @@ +// +// PFMoveApplication.h, version 1.24 +// LetsMove +// +// Created by Andy Kim at Potion Factory LLC on 9/17/09 +// +// The contents of this file are dedicated to the public domain. + +#ifdef __cplusplus +extern "C" { +#endif + +#import + +/** + Moves the running application to ~/Applications or /Applications if the former does not exist. + After the move, it relaunches app from the new location. + DOES NOT work for sandboxed applications. + + Call from \c NSApplication's delegate method \c -applicationWillFinishLaunching: method. */ +void PFMoveToApplicationsFolderIfNecessary(void); + +/** + Check whether an app move is currently in progress. + Returns YES if LetsMove is currently in-progress trying to move the app to the Applications folder, or NO otherwise. + This can be used to work around a crash with apps that terminate after last window is closed. + See https://github.com/potionfactory/LetsMove/issues/64 for details. */ +BOOL PFMoveIsInProgress(void); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/distribution/osx/Launcher/src/PFMoveApplication.m b/distribution/osx/Launcher/src/PFMoveApplication.m new file mode 100644 index 000000000..35effaec4 --- /dev/null +++ b/distribution/osx/Launcher/src/PFMoveApplication.m @@ -0,0 +1,565 @@ +// +// PFMoveApplication.m, version 1.24 +// LetsMove +// +// Created by Andy Kim at Potion Factory LLC on 9/17/09 +// +// The contents of this file are dedicated to the public domain. + +#import "PFMoveApplication.h" + +#import +#import +#import +#import + +@interface LetsMove : NSObject +@end + +@implementation LetsMove ++ (NSBundle *)bundle { + return [NSBundle bundleForClass:self]; +} +@end + +// Strings +// These are macros to be able to use custom i18n tools +#define _I10NS(nsstr) NSLocalizedStringFromTableInBundle(nsstr, @"MoveApplication", [LetsMove bundle], nil) +#define kStrMoveApplicationCouldNotMove _I10NS(@"Could not move to Applications folder") +#define kStrMoveApplicationQuestionTitle _I10NS(@"Move to Applications folder?") +#define kStrMoveApplicationQuestionTitleHome _I10NS(@"Move to Applications folder in your Home folder?") +#define kStrMoveApplicationQuestionMessage _I10NS(@"I can move myself to the Applications folder if you'd like.") +#define kStrMoveApplicationButtonMove _I10NS(@"Move to Applications Folder") +#define kStrMoveApplicationButtonDoNotMove _I10NS(@"Do Not Move") +#define kStrMoveApplicationQuestionInfoWillRequirePasswd _I10NS(@"Note that this will require an administrator password.") +#define kStrMoveApplicationQuestionInfoInDownloadsFolder _I10NS(@"This will keep your Downloads folder uncluttered.") + +// Needs to be defined for compiling under 10.5 SDK +#ifndef NSAppKitVersionNumber10_5 + #define NSAppKitVersionNumber10_5 949 +#endif + +// By default, we use a small control/font for the suppression button. +// If you prefer to use the system default (to match your other alerts), +// set this to 0. +#define PFUseSmallAlertSuppressCheckbox 1 + + +static NSString *AlertSuppressKey = @"moveToApplicationsFolderAlertSuppress"; +static BOOL MoveInProgress = NO; + +// Helper functions +static NSString *PreferredInstallLocation(BOOL *isUserDirectory); +static BOOL IsInApplicationsFolder(NSString *path); +static BOOL IsInDownloadsFolder(NSString *path); +static BOOL IsApplicationAtPathRunning(NSString *path); +static BOOL IsApplicationAtPathNested(NSString *path); +static NSString *ContainingDiskImageDevice(NSString *path); +static BOOL Trash(NSString *path); +static BOOL DeleteOrTrash(NSString *path); +static BOOL AuthorizedInstall(NSString *srcPath, NSString *dstPath, BOOL *canceled); +static BOOL CopyBundle(NSString *srcPath, NSString *dstPath); +static NSString *ShellQuotedString(NSString *string); +static void Relaunch(NSString *destinationPath); + +// Main worker function +void PFMoveToApplicationsFolderIfNecessary(void) { + + // Make sure to do our work on the main thread. + // Apparently Electron apps need this for things to work properly. + if (![NSThread isMainThread]) { + dispatch_async(dispatch_get_main_queue(), ^{ + PFMoveToApplicationsFolderIfNecessary(); + }); + return; + } + + // Skip if user suppressed the alert before + if ([[NSUserDefaults standardUserDefaults] boolForKey:AlertSuppressKey]) return; + + // Path of the bundle + NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; + + // Check if the bundle is embedded in another application + BOOL isNestedApplication = IsApplicationAtPathNested(bundlePath); + + // Skip if the application is already in some Applications folder, + // unless it's inside another app's bundle. + if (IsInApplicationsFolder(bundlePath) && !isNestedApplication) return; + + // OK, looks like we'll need to do a move - set the status variable appropriately + MoveInProgress = YES; + + // File Manager + NSFileManager *fm = [NSFileManager defaultManager]; + + // Are we on a disk image? + NSString *diskImageDevice = ContainingDiskImageDevice(bundlePath); + + // Since we are good to go, get the preferred installation directory. + BOOL installToUserApplications = NO; + NSString *applicationsDirectory = PreferredInstallLocation(&installToUserApplications); + NSString *bundleName = [bundlePath lastPathComponent]; + NSString *destinationPath = [applicationsDirectory stringByAppendingPathComponent:bundleName]; + + // Check if we need admin password to write to the Applications directory + BOOL needAuthorization = ([fm isWritableFileAtPath:applicationsDirectory] == NO); + + // Check if the destination bundle is already there but not writable + needAuthorization |= ([fm fileExistsAtPath:destinationPath] && ![fm isWritableFileAtPath:destinationPath]); + + // Setup the alert + NSAlert *alert = [[[NSAlert alloc] init] autorelease]; + { + NSString *informativeText = nil; + + [alert setMessageText:(installToUserApplications ? kStrMoveApplicationQuestionTitleHome : kStrMoveApplicationQuestionTitle)]; + + informativeText = kStrMoveApplicationQuestionMessage; + + if (needAuthorization) { + informativeText = [informativeText stringByAppendingString:@" "]; + informativeText = [informativeText stringByAppendingString:kStrMoveApplicationQuestionInfoWillRequirePasswd]; + } + else if (IsInDownloadsFolder(bundlePath)) { + // Don't mention this stuff if we need authentication. The informative text is long enough as it is in that case. + informativeText = [informativeText stringByAppendingString:@" "]; + informativeText = [informativeText stringByAppendingString:kStrMoveApplicationQuestionInfoInDownloadsFolder]; + } + + [alert setInformativeText:informativeText]; + + // Add accept button + [alert addButtonWithTitle:kStrMoveApplicationButtonMove]; + + // Add deny button + NSButton *cancelButton = [alert addButtonWithTitle:kStrMoveApplicationButtonDoNotMove]; + [cancelButton setKeyEquivalent:[NSString stringWithFormat:@"%C", 0x1b]]; // Escape key + + // Setup suppression button + [alert setShowsSuppressionButton:YES]; + + if (PFUseSmallAlertSuppressCheckbox) { + NSCell *cell = [[alert suppressionButton] cell]; + [cell setControlSize:NSSmallControlSize]; + [cell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]]; + } + } + + // Activate app -- work-around for focus issues related to "scary file from internet" OS dialog. + if (![NSApp isActive]) { + [NSApp activateIgnoringOtherApps:YES]; + } + + if ([alert runModal] == NSAlertFirstButtonReturn) { + NSLog(@"INFO -- Moving myself to the Applications folder"); + + // Move + if (needAuthorization) { + BOOL authorizationCanceled; + + if (!AuthorizedInstall(bundlePath, destinationPath, &authorizationCanceled)) { + if (authorizationCanceled) { + NSLog(@"INFO -- Not moving because user canceled authorization"); + MoveInProgress = NO; + return; + } + else { + NSLog(@"ERROR -- Could not copy myself to /Applications with authorization"); + goto fail; + } + } + } + else { + // If a copy already exists in the Applications folder, put it in the Trash + if ([fm fileExistsAtPath:destinationPath]) { + // But first, make sure that it's not running + if (IsApplicationAtPathRunning(destinationPath)) { + // Give the running app focus and terminate myself + NSLog(@"INFO -- Switching to an already running version"); + [[NSTask launchedTaskWithLaunchPath:@"/usr/bin/open" arguments:[NSArray arrayWithObject:destinationPath]] waitUntilExit]; + MoveInProgress = NO; + exit(0); + } + else { + if (!Trash([applicationsDirectory stringByAppendingPathComponent:bundleName])) + goto fail; + } + } + + if (!CopyBundle(bundlePath, destinationPath)) { + NSLog(@"ERROR -- Could not copy myself to %@", destinationPath); + goto fail; + } + } + + // Trash the original app. It's okay if this fails. + // NOTE: This final delete does not work if the source bundle is in a network mounted volume. + // Calling rm or file manager's delete method doesn't work either. It's unlikely to happen + // but it'd be great if someone could fix this. + if (!isNestedApplication && diskImageDevice == nil && !DeleteOrTrash(bundlePath)) { + NSLog(@"WARNING -- Could not delete application after moving it to Applications folder"); + } + + // Relaunch. + Relaunch(destinationPath); + + // Launched from within a disk image? -- unmount (if no files are open after 5 seconds, + // otherwise leave it mounted). + if (diskImageDevice && !isNestedApplication) { + NSString *script = [NSString stringWithFormat:@"(/bin/sleep 5 && /usr/bin/hdiutil detach %@) &", ShellQuotedString(diskImageDevice)]; + [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:[NSArray arrayWithObjects:@"-c", script, nil]]; + } + + MoveInProgress = NO; + exit(0); + } + // Save the alert suppress preference if checked + else if ([[alert suppressionButton] state] == NSOnState) { + [[NSUserDefaults standardUserDefaults] setBool:YES forKey:AlertSuppressKey]; + } + + MoveInProgress = NO; + return; + +fail: + { + // Show failure message + alert = [[[NSAlert alloc] init] autorelease]; + [alert setMessageText:kStrMoveApplicationCouldNotMove]; + [alert runModal]; + MoveInProgress = NO; + } +} + +BOOL PFMoveIsInProgress() { + return MoveInProgress; +} + +#pragma mark - +#pragma mark Helper Functions + +static NSString *PreferredInstallLocation(BOOL *isUserDirectory) { + // Return the preferred install location. + // Assume that if the user has a ~/Applications folder, they'd prefer their + // applications to go there. + + NSFileManager *fm = [NSFileManager defaultManager]; + + /* + NSArray *userApplicationsDirs = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES); + + if ([userApplicationsDirs count] > 0) { + NSString *userApplicationsDir = [userApplicationsDirs objectAtIndex:0]; + BOOL isDirectory; + + if ([fm fileExistsAtPath:userApplicationsDir isDirectory:&isDirectory] && isDirectory) { + // User Applications directory exists. Get the directory contents. + NSArray *contents = [fm contentsOfDirectoryAtPath:userApplicationsDir error:NULL]; + + // Check if there is at least one ".app" inside the directory. + for (NSString *contentsPath in contents) { + if ([[contentsPath pathExtension] isEqualToString:@"app"]) { + if (isUserDirectory) *isUserDirectory = YES; + return [userApplicationsDir stringByResolvingSymlinksInPath]; + } + } + } + } + */ + + // No user Applications directory in use. Return the machine local Applications directory + if (isUserDirectory) *isUserDirectory = NO; + + return [[NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSLocalDomainMask, YES) lastObject] stringByResolvingSymlinksInPath]; +} + +static BOOL IsInApplicationsFolder(NSString *path) { + // Check all the normal Application directories + NSArray *applicationDirs = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSAllDomainsMask, YES); + for (NSString *appDir in applicationDirs) { + if ([path hasPrefix:appDir]) return YES; + } + + // Also, handle the case that the user has some other Application directory (perhaps on a separate data partition). + if ([[path pathComponents] containsObject:@"Applications"]) return YES; + + return NO; +} + +static BOOL IsInDownloadsFolder(NSString *path) { + NSArray *downloadDirs = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSAllDomainsMask, YES); + for (NSString *downloadsDirPath in downloadDirs) { + if ([path hasPrefix:downloadsDirPath]) return YES; + } + + return NO; +} + +static BOOL IsApplicationAtPathRunning(NSString *bundlePath) { + bundlePath = [bundlePath stringByStandardizingPath]; + +#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5 + // Use the new API on 10.6 or higher to determine if the app is already running + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) { + for (NSRunningApplication *runningApplication in [[NSWorkspace sharedWorkspace] runningApplications]) { + NSString *runningAppBundlePath = [[[runningApplication bundleURL] path] stringByStandardizingPath]; + if ([runningAppBundlePath isEqualToString:bundlePath]) { + return YES; + } + } + return NO; + } +#endif + // Use the shell to determine if the app is already running on systems 10.5 or lower + NSString *script = [NSString stringWithFormat:@"/bin/ps ax -o comm | /usr/bin/grep %@/ | /usr/bin/grep -v grep >/dev/null", ShellQuotedString(bundlePath)]; + NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:[NSArray arrayWithObjects:@"-c", script, nil]]; + [task waitUntilExit]; + + // If the task terminated with status 0, it means that the final grep produced 1 or more lines of output. + // Which means that the app is already running + return [task terminationStatus] == 0; +} + +static BOOL IsApplicationAtPathNested(NSString *path) { + NSString *containingPath = [path stringByDeletingLastPathComponent]; + + NSArray *components = [containingPath pathComponents]; + for (NSString *component in components) { + if ([[component pathExtension] isEqualToString:@"app"]) { + return YES; + } + } + + return NO; +} + +static NSString *ContainingDiskImageDevice(NSString *path) { + NSString *containingPath = [path stringByDeletingLastPathComponent]; + + struct statfs fs; + if (statfs([containingPath fileSystemRepresentation], &fs) || (fs.f_flags & MNT_ROOTFS)) + return nil; + + NSString *device = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fs.f_mntfromname length:strlen(fs.f_mntfromname)]; + + NSTask *hdiutil = [[[NSTask alloc] init] autorelease]; + [hdiutil setLaunchPath:@"/usr/bin/hdiutil"]; + [hdiutil setArguments:[NSArray arrayWithObjects:@"info", @"-plist", nil]]; + [hdiutil setStandardOutput:[NSPipe pipe]]; + [hdiutil launch]; + [hdiutil waitUntilExit]; + + NSData *data = [[[hdiutil standardOutput] fileHandleForReading] readDataToEndOfFile]; + NSDictionary *info = nil; +#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5 + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) { + info = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:NULL]; + } + else { +#endif +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10 + info = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL]; +#endif +#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5 + } +#endif + + if (![info isKindOfClass:[NSDictionary class]]) return nil; + + NSArray *images = (NSArray *)[info objectForKey:@"images"]; + if (![images isKindOfClass:[NSArray class]]) return nil; + + for (NSDictionary *image in images) { + if (![image isKindOfClass:[NSDictionary class]]) return nil; + + id systemEntities = [image objectForKey:@"system-entities"]; + if (![systemEntities isKindOfClass:[NSArray class]]) return nil; + + for (NSDictionary *systemEntity in systemEntities) { + if (![systemEntity isKindOfClass:[NSDictionary class]]) return nil; + + NSString *devEntry = [systemEntity objectForKey:@"dev-entry"]; + if (![devEntry isKindOfClass:[NSString class]]) return nil; + + if ([devEntry isEqualToString:device]) + return device; + } + } + + return nil; +} + +static BOOL Trash(NSString *path) { + BOOL result = NO; +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8 + if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_8) { + result = [[NSFileManager defaultManager] trashItemAtURL:[NSURL fileURLWithPath:path] resultingItemURL:NULL error:NULL]; + } +#endif +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_11 + if (!result) { + result = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation + source:[path stringByDeletingLastPathComponent] + destination:@"" + files:[NSArray arrayWithObject:[path lastPathComponent]] + tag:NULL]; + } +#endif + + // As a last resort try trashing with AppleScript. + // This allows us to trash the app in macOS Sierra even when the app is running inside + // an app translocation image. + if (!result) { + NSAppleScript *appleScript = [[[NSAppleScript alloc] initWithSource: + [NSString stringWithFormat:@"\ + set theFile to POSIX file \"%@\" \n\ + tell application \"Finder\" \n\ + move theFile to trash \n\ + end tell", path]] autorelease]; + NSDictionary *errorDict = nil; + NSAppleEventDescriptor *scriptResult = [appleScript executeAndReturnError:&errorDict]; + if (scriptResult == nil) { + NSLog(@"Trash AppleScript error: %@", errorDict); + } + result = (scriptResult != nil); + } + + if (!result) { + NSLog(@"ERROR -- Could not trash '%@'", path); + } + + return result; +} + +static BOOL DeleteOrTrash(NSString *path) { + NSError *error; + + if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error]) { + return YES; + } + else { + // Don't log warning if on Sierra and running inside App Translocation path + if ([path rangeOfString:@"/AppTranslocation/"].location == NSNotFound) + NSLog(@"WARNING -- Could not delete '%@': %@", path, [error localizedDescription]); + + return Trash(path); + } +} + +static BOOL AuthorizedInstall(NSString *srcPath, NSString *dstPath, BOOL *canceled) { + if (canceled) *canceled = NO; + + // Make sure that the destination path is an app bundle. We're essentially running 'sudo rm -rf' + // so we really don't want to fuck this up. + if (![[dstPath pathExtension] isEqualToString:@"app"]) return NO; + + // Do some more checks + if ([[dstPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) return NO; + if ([[srcPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) return NO; + + int pid, status; + AuthorizationRef myAuthorizationRef; + + // Get the authorization + OSStatus err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &myAuthorizationRef); + if (err != errAuthorizationSuccess) return NO; + + AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0}; + AuthorizationRights myRights = {1, &myItems}; + AuthorizationFlags myFlags = (AuthorizationFlags)(kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize); + + err = AuthorizationCopyRights(myAuthorizationRef, &myRights, NULL, myFlags, NULL); + if (err != errAuthorizationSuccess) { + if (err == errAuthorizationCanceled && canceled) + *canceled = YES; + goto fail; + } + + static OSStatus (*security_AuthorizationExecuteWithPrivileges)(AuthorizationRef authorization, const char *pathToTool, + AuthorizationFlags options, char * const *arguments, + FILE **communicationsPipe) = NULL; + if (!security_AuthorizationExecuteWithPrivileges) { + // On 10.7, AuthorizationExecuteWithPrivileges is deprecated. We want to still use it since there's no + // good alternative (without requiring code signing). We'll look up the function through dyld and fail + // if it is no longer accessible. If Apple removes the function entirely this will fail gracefully. If + // they keep the function and throw some sort of exception, this won't fail gracefully, but that's a + // risk we'll have to take for now. + security_AuthorizationExecuteWithPrivileges = (OSStatus (*)(AuthorizationRef, const char*, + AuthorizationFlags, char* const*, + FILE **)) dlsym(RTLD_DEFAULT, "AuthorizationExecuteWithPrivileges"); + } + if (!security_AuthorizationExecuteWithPrivileges) goto fail; + + // Delete the destination + { + char *args[] = {"-rf", (char *)[dstPath fileSystemRepresentation], NULL}; + err = security_AuthorizationExecuteWithPrivileges(myAuthorizationRef, "/bin/rm", kAuthorizationFlagDefaults, args, NULL); + if (err != errAuthorizationSuccess) goto fail; + + // Wait until it's done + pid = wait(&status); + if (pid == -1 || !WIFEXITED(status)) goto fail; // We don't care about exit status as the destination most likely does not exist + } + + // Copy + { + char *args[] = {"-pR", (char *)[srcPath fileSystemRepresentation], (char *)[dstPath fileSystemRepresentation], NULL}; + err = security_AuthorizationExecuteWithPrivileges(myAuthorizationRef, "/bin/cp", kAuthorizationFlagDefaults, args, NULL); + if (err != errAuthorizationSuccess) goto fail; + + // Wait until it's done + pid = wait(&status); + if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) goto fail; + } + + AuthorizationFree(myAuthorizationRef, kAuthorizationFlagDefaults); + return YES; + +fail: + AuthorizationFree(myAuthorizationRef, kAuthorizationFlagDefaults); + return NO; +} + +static BOOL CopyBundle(NSString *srcPath, NSString *dstPath) { + NSFileManager *fm = [NSFileManager defaultManager]; + NSError *error = nil; + + if ([fm copyItemAtPath:srcPath toPath:dstPath error:&error]) { + return YES; + } + else { + NSLog(@"ERROR -- Could not copy '%@' to '%@' (%@)", srcPath, dstPath, error); + return NO; + } +} + +static NSString *ShellQuotedString(NSString *string) { + return [NSString stringWithFormat:@"'%@'", [string stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]]; +} + +static void Relaunch(NSString *destinationPath) { + // The shell script waits until the original app process terminates. + // This is done so that the relaunched app opens as the front-most app. + int pid = [[NSProcessInfo processInfo] processIdentifier]; + + // Command run just before running open /final/path + NSString *preOpenCmd = @""; + + NSString *quotedDestinationPath = ShellQuotedString(destinationPath); + + // OS X >=10.5: + // Before we launch the new app, clear xattr:com.apple.quarantine to avoid + // duplicate "scary file from the internet" dialog. + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) { + // Add the -r flag on 10.6 + preOpenCmd = [NSString stringWithFormat:@"/usr/bin/xattr -d -r com.apple.quarantine %@", quotedDestinationPath]; + } + else { + preOpenCmd = [NSString stringWithFormat:@"/usr/bin/xattr -d com.apple.quarantine %@", quotedDestinationPath]; + } + + NSString *script = [NSString stringWithFormat:@"(while /bin/kill -0 %d >&/dev/null; do /bin/sleep 0.1; done; %@; /usr/bin/open %@) &", pid, preOpenCmd, quotedDestinationPath]; + + [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:[NSArray arrayWithObjects:@"-c", script, nil]]; +} \ No newline at end of file diff --git a/distribution/osx/Launcher/src/compile.sh b/distribution/osx/Launcher/src/compile.sh new file mode 100644 index 000000000..e8947aff9 --- /dev/null +++ b/distribution/osx/Launcher/src/compile.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# -fobjc-arc: enables ARC +# -fmodules: enables modules so you can import with `@import AppKit;` +# -mmacosx-version-min=10.6: support older OS X versions, this might increase the binary size + +if [ ! -d "../dist" ]; then mkdir ../dist; fi + +clang PFMoveApplication.m -fno-objc-arc -fmodules -mmacosx-version-min=10.6 -c -o PFMoveApplication.o +clang run-with-mono.m Launcher.m PFMoveApplication.o -fobjc-arc -fmodules -mmacosx-version-min=10.6 -o ../dist/Launcher +rm PFMoveApplication.o + +if [ "$1" == "install" ] && [ "$2" != "" ]; then + echo "Installing to $2" + cp ../dist/Launcher $2 + chmod +x $2 +fi diff --git a/distribution/osx/Launcher/src/run-with-mono.h b/distribution/osx/Launcher/src/run-with-mono.h new file mode 100644 index 000000000..c95536103 --- /dev/null +++ b/distribution/osx/Launcher/src/run-with-mono.h @@ -0,0 +1,11 @@ +@import Foundation; +@import AppKit; + +@interface RunWithMono : NSObject { +} + ++ (void) openDownloadLink:(NSButton*)button; ++ (bool) showDownloadMonoDialog:(NSString *)appName major:(int)major minor:(int)minor; ++ (int) runAssemblyWithMono:(NSString *)appName procnamesuffix:(NSString *)procnamesuffix assembly:(NSString *)assembly major:(int) major minor:(int) minor; + +@end \ No newline at end of file diff --git a/distribution/osx/Launcher/src/run-with-mono.m b/distribution/osx/Launcher/src/run-with-mono.m new file mode 100644 index 000000000..2979fcc53 --- /dev/null +++ b/distribution/osx/Launcher/src/run-with-mono.m @@ -0,0 +1,258 @@ +#import "run-with-mono.h" + +@import Foundation; +@import AppKit; + +NSString * const VERSION_TITLE = @"Cannot launch %@"; +NSString * const VERSION_MSG = @"%@ requires the Mono Framework version %d.%d or later."; +NSString * const DOWNLOAD_URL = @"http://www.mono-project.com/download/stable/#download-mac"; + +// Helper method to see if the user has requested debug output +bool D() { + NSString* v = [[[NSProcessInfo processInfo]environment]objectForKey:@"DEBUG"]; + if (v == nil || v.length == 0 || [v isEqual:@"0"] || [v isEqual:@"false"] || [v isEqual:@"f"]) + return false; + return true; +} + +// Wrapper method to invoke commandline operations and return the string output +NSString *runCommand(NSString *program, NSArray *arguments) { + NSPipe *pipe = [NSPipe pipe]; + NSFileHandle *file = pipe.fileHandleForReading; + + NSTask *task = [[NSTask alloc] init]; + task.launchPath = program; + task.arguments = arguments; + task.standardOutput = pipe; + + [task launch]; + + NSData *data = [file readDataToEndOfFile]; + [file closeFile]; + [task waitUntilExit]; + + NSString *cmdOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; + if (cmdOutput == nil || cmdOutput.length == 0) + return nil; + + return [cmdOutput stringByTrimmingCharactersInSet: + [NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} + +// Checks if the Mono version is greater than or equal to the desired version +bool isValidMono(NSString *mono, int major, int minor) { + NSFileManager *fileManager = [NSFileManager defaultManager]; + + if (mono == nil) + return false; + + if (![fileManager fileExistsAtPath:mono] || ![fileManager isExecutableFileAtPath:mono]) + return false; + + NSString *versionInfo = runCommand(mono, @[@"--version"]); + + NSRange rg = [versionInfo rangeOfString:@"Mono JIT compiler version \\d+\\.\\d+" options:NSRegularExpressionSearch]; + if (rg.location != NSNotFound) { + versionInfo = [versionInfo substringWithRange:rg]; + if (D()) NSLog(@"Matched version: %@", versionInfo); + rg = [versionInfo rangeOfString:@"\\d+\\.\\d+" options:NSRegularExpressionSearch]; + if (rg.location != NSNotFound) { + versionInfo = [versionInfo substringWithRange:rg]; + if (D()) NSLog(@"Matched version: %@", versionInfo); + + NSArray *versionComponents = [versionInfo componentsSeparatedByString:@"."]; + if ([versionComponents[0] intValue] < major) + return false; + if ([versionComponents[0] intValue] == major && [versionComponents[1] intValue] < minor) + return false; + + return true; + } + } + + return false; +} + +// Attempts to locate a mono with a valid version +NSString *findMono(int major, int minor) { + NSFileManager *fileManager = [NSFileManager defaultManager]; + + NSString *currentMono = runCommand(@"/usr/bin/which", @[@"mono"]); + if (D()) NSLog(@"which mono: %@", currentMono); + + if (isValidMono(currentMono, major, minor)) { + if (D()) NSLog(@"Found mono with: %@", currentMono); + return currentMono; + } + + NSArray *probepaths = @[@"/usr/local/bin/mono", @"/Library/Frameworks/Mono.framework/Versions/Current/bin/mono", @"/opt/local/bin/mono"]; + for(NSString* probepath in probepaths) { + if (D()) NSLog(@"Trying mono with: %@", probepath); + if (isValidMono(probepath, major, minor)) { + if (D()) NSLog(@"Found mono with: %@", probepath); + return probepath; + } + } + + if (D()) NSLog(@"Failed to find Mono, returning: %@", nil); + return nil; +} + +// Check Bundle for quarantine +void checkBundle() { + + NSString * const bundlePath = [[NSBundle mainBundle] bundlePath]; + NSString * const attributes = runCommand(@"/usr/bin/xattr", @[@"-l", bundlePath]); + if (D()) NSLog(@"Attributes: %@", attributes); + if ([attributes containsString:@"com.apple.quarantine:"]) { + runCommand(@"/usr/bin/xattr", @[@"-dr", @"com.apple.quarantine", bundlePath]); + NSLog(@"Removed quarantine attribute from bundle"); + } +} + + +@implementation RunWithMono + ++ (void) openDownloadLink:(NSButton*)button { + if (D()) NSLog(@"Clicked Download"); + runCommand(@"/usr/bin/open", @[DOWNLOAD_URL]); +} + +// Shows the download dialog, prompting to download Mono ++ (bool) showDownloadMonoDialog:(NSString *)appName major:(int)major minor:(int)minor { + NSAlert *alert = [[NSAlert alloc] init]; + + [alert setInformativeText:[NSString stringWithFormat:VERSION_MSG, appName, major, minor]]; + [alert setMessageText:[NSString stringWithFormat:VERSION_TITLE, appName]]; + [alert addButtonWithTitle:@"Cancel"]; + [alert addButtonWithTitle:@"Retry"]; + [alert addButtonWithTitle:@"Download"]; + + NSButton *downloadButton = [[alert buttons] objectAtIndex:2]; + + [downloadButton setTarget:self]; + [downloadButton setAction:@selector(openDownloadLink:)]; + + NSModalResponse btn = [alert runModal]; + if (btn == NSAlertFirstButtonReturn) { + if (D()) NSLog(@"Clicked Cancel"); + return true; + } + else if (btn == NSAlertSecondButtonReturn) { + if (D()) NSLog(@"Clicked Retry"); + return false; + } + + return true; +} + +// Top-level method, finds Mono with an appropriate version and launches the assembly ++ (int) runAssemblyWithMono: (NSString *)appName procnamesuffix:(NSString *)procnamesuffix assembly:(NSString *)assembly major:(int) major minor:(int) minor { + NSFileManager *fileManager = [NSFileManager defaultManager]; + + NSString *assemblyPath; + bool found = false; + + NSString *localPath = NSProcessInfo.processInfo.arguments[0].stringByDeletingLastPathComponent; + NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; + NSArray *paths = @[ + localPath, + [NSString pathWithComponents:@[localPath, @"bin"]], + resourcePath, + [NSString pathWithComponents:@[resourcePath, @"bin"]] + ]; + for (NSString* entryFolder in paths) { + if (D()) NSLog(@"Checking folder: %@", entryFolder); + + assemblyPath = [NSString pathWithComponents:@[entryFolder, assembly]]; + + if ([fileManager fileExistsAtPath:assemblyPath]) { + found = true; + break; + } + } + + if (!found) { + NSLog(@"Assembly file not found"); + return 1; + } + + if (D()) NSLog(@"assemblyPath: %@", assemblyPath); + + checkBundle(); + + NSString *currentMono = findMono(major, minor); + + while (currentMono == nil) { + NSLog(@"No valid mono found!"); + bool close = [self showDownloadMonoDialog:appName major:major minor:minor]; + if (close) + return 1; + currentMono = findMono(major, minor); + } + + // Setup dylib fallback loading + NSMutableArray * dylibPath = [NSMutableArray arrayWithObject:assemblyPath.stringByDeletingLastPathComponent]; + + // Update the PATH to use the specified mono version + if ([currentMono hasPrefix:@"/"]) + { + NSString * curMonoBinDir = currentMono.stringByDeletingLastPathComponent; + NSString * curMonoDir = curMonoBinDir.stringByDeletingLastPathComponent; + NSString * curMonoLibDir = [NSString pathWithComponents:@[curMonoDir, @"lib"]]; + + NSString * curEnvPath = [NSString stringWithUTF8String:getenv("PATH")]; + NSString * newEnvPath = [NSString stringWithFormat:@"%@:%@", curMonoBinDir, curEnvPath]; + setenv("PATH", newEnvPath.UTF8String, 1); + + [dylibPath addObject:curMonoLibDir]; + + NSLog(@"Added %@ to PATH", curMonoBinDir); + } + + // Setup libsqlite? + /* if [[ -f '/opt/local/lib/libsqlite3.0.dylib' ]]; then + export DYLD_FALLBACK_LIBRARY_PATH="/opt/local/lib:$DYLD_FALLBACK_LIBRARY_PATH" + fi + */ + + [dylibPath addObjectsFromArray:@[@"$HOME/lib", @"/usr/local/lib", @"/lib", @"/usr/lib"]]; + + setenv("DYLD_FALLBACK_LIBRARY_PATH", [dylibPath componentsJoinedByString:@":"].UTF8String, 1); + + if (D()) NSLog(@"Running %@ --debug %@", currentMono, assemblyPath); + + // Copy commandline arguments + NSMutableArray* arguments = [[NSMutableArray alloc] init]; + // Disabled suffix for now coz it's confusing and not preserved on in-app restart + [arguments addObject:currentMono]; + //[arguments addObject:[currentMono stringByAppendingString:procnamesuffix]]; + [arguments addObject:@"--debug"]; + [arguments addObjectsFromArray:[[NSProcessInfo processInfo] arguments]]; + + // replace the executable-path with the assembly path + [arguments replaceObjectAtIndex:2 withObject:assemblyPath]; + + // Try switch to mono using execv + char * cPath = strdup([currentMono UTF8String]); + char ** cArgs; + char ** pArgNext = cArgs = malloc(sizeof(*cArgs) * ([arguments count] + 1)); + for (NSString *s in arguments) { + *pArgNext++ = strdup([s UTF8String]); + } + *pArgNext = NULL; + int ret = execv(cPath, cArgs); + if (ret != 0) + NSLog(@"Failed execv with errno @d", errno); + // execv failed, cleanup + pArgNext = cArgs; + for (NSString *s in arguments) { + free(*pArgNext++); + } + free(cArgs); + free(cPath); + + return -1; +} + +@end \ No newline at end of file diff --git a/distribution/macOS/Sonarr.app/Contents/Info.plist b/distribution/osx/Sonarr.app/Contents/Info.plist similarity index 95% rename from distribution/macOS/Sonarr.app/Contents/Info.plist rename to distribution/osx/Sonarr.app/Contents/Info.plist index 4a6973050..91fe06105 100644 --- a/distribution/macOS/Sonarr.app/Contents/Info.plist +++ b/distribution/osx/Sonarr.app/Contents/Info.plist @@ -23,11 +23,11 @@ CFBundlePackageType APPL CFBundleShortVersionString - 4.0 + 3.0 CFBundleSignature xmmd CFBundleVersion - 4.0 + 3.0 NSAppleScriptEnabled YES diff --git a/distribution/macOS/Sonarr.app/Contents/Resources/sonarr.icns b/distribution/osx/Sonarr.app/Contents/Resources/sonarr.icns similarity index 100% rename from distribution/macOS/Sonarr.app/Contents/Resources/sonarr.icns rename to distribution/osx/Sonarr.app/Contents/Resources/sonarr.icns diff --git a/distribution/osx/Sonarr.old.sh b/distribution/osx/Sonarr.old.sh new file mode 100644 index 000000000..33c3230b5 --- /dev/null +++ b/distribution/osx/Sonarr.old.sh @@ -0,0 +1,62 @@ +#!/bin/sh + +#get the bundle's MacOS directory full path +DIR=$(cd "$(dirname "$0")"; pwd) + +#change these values to match your app +EXE_PATH="$DIR/Sonarr.exe" +APPNAME="Sonarr" + +#set up environment +if [[ -x '/opt/local/bin/mono' ]]; then + # Macports and mono-supplied installer path + export PATH="/opt/local/bin:$PATH" +elif [[ -x '/usr/local/bin/mono' ]]; then + # Homebrew-supplied path to mono + export PATH="/usr/local/bin:$PATH" +fi + +export DYLD_FALLBACK_LIBRARY_PATH="$DIR" + +if [ -e /Library/Frameworks/Mono.framework ]; then + MONO_FRAMEWORK_PATH=/Library/Frameworks/Mono.framework/Versions/Current + export PATH="$MONO_FRAMEWORK_PATH/bin:$PATH" + export DYLD_FALLBACK_LIBRARY_PATH="$DYLD_FALLBACK_LIBRARY_PATH:$MONO_FRAMEWORK_PATH/lib" +fi + +if [[ -f '/opt/local/lib/libsqlite3.0.dylib' ]]; then + export DYLD_FALLBACK_LIBRARY_PATH="/opt/local/lib:$DYLD_FALLBACK_LIBRARY_PATH" +fi + +export DYLD_FALLBACK_LIBRARY_PATH="$DYLD_FALLBACK_LIBRARY_PATH:$HOME/lib:/usr/local/lib:/lib:/usr/lib" + +#mono version check +REQUIRED_MAJOR=4 +REQUIRED_MINOR=6 + +VERSION_TITLE="Cannot launch $APPNAME" +VERSION_MSG="$APPNAME requires Mono Runtime Environment(MRE) $REQUIRED_MAJOR.$REQUIRED_MINOR or later." +DOWNLOAD_URL="http://www.mono-project.com/download/#download-mac" + +MONO_VERSION="$(mono --version | grep 'Mono JIT compiler version ' | cut -f5 -d\ )" +# if [[ -o DEBUG ]]; then osascript -e "display dialog \"MONO_VERSION: $MONO_VERSION\""; fi + + +MONO_VERSION_MAJOR="$(echo $MONO_VERSION | cut -f1 -d.)" +MONO_VERSION_MINOR="$(echo $MONO_VERSION | cut -f2 -d.)" +if [ -z "$MONO_VERSION" ] \ + || [ $MONO_VERSION_MAJOR -lt $REQUIRED_MAJOR ] \ + || [ $MONO_VERSION_MAJOR -eq $REQUIRED_MAJOR -a $MONO_VERSION_MINOR -lt $REQUIRED_MINOR ] +then + osascript \ + -e "set question to display dialog \"$VERSION_MSG\" with title \"$VERSION_TITLE\" buttons {\"Cancel\", \"Download...\"} default button 2" \ + -e "if button returned of question is equal to \"Download...\" then open location \"$DOWNLOAD_URL\"" + echo "$VERSION_TITLE" + echo "$VERSION_MSG" + exit 1 +fi + +MONO_EXEC="exec mono --debug" + +#run app using mono +$MONO_EXEC "$EXE_PATH" diff --git a/distribution/windows/setup/build.bat b/distribution/windows/setup/build.bat index 6c205089e..dfeba4491 100644 --- a/distribution/windows/setup/build.bat +++ b/distribution/windows/setup/build.bat @@ -1,7 +1,7 @@ -@REM SET SONARR_MAJOR_VERSION=4 -@REM SET SONARR_VERSION=4.0.0.5 -@REM SET BRANCH=develop -@REM SET FRAMEWORK=net6.0 -@REM SET RUNTIME=win-x64 - +REM SET BUILD_NUMBER=1 +REM SET BRANCH=develop +echo ##teamcity[progressStart 'Building setup file'] inno\ISCC.exe sonarr.iss +echo ##teamcity[progressFinish 'Building setup file'] + +echo ##teamcity[publishArtifacts 'distribution\windows\setup\output\*.exe'] diff --git a/distribution/windows/setup/sonarr.iss b/distribution/windows/setup/sonarr.iss index 8401bdea9..5fc1e53ae 100644 --- a/distribution/windows/setup/sonarr.iss +++ b/distribution/windows/setup/sonarr.iss @@ -6,20 +6,17 @@ #define AppURL "https://sonarr.tv/" #define ForumsURL "https://forums.sonarr.tv/" #define AppExeName "Sonarr.exe" -#define BuildNumber "4.0" -#define BuildNumber GetEnv('SONARR_VERSION') -#define MajorVersion GetEnv('SONARR_MAJOR_VERSION') +#define BuildNumber "3.0" +#define BuildNumber GetEnv('BUILD_NUMBER') #define BranchName GetEnv('BRANCH') -#define Framework GetEnv('FRAMEWORK') -#define Runtime GetEnv('RUNTIME') [Setup] -; NOTE: The value of AppId uniquely identifies this appl ication. +; NOTE: The value of AppId uniquely identifies this application. ; Do not use the same AppId value in installers for other applications. ; (To generate a new GUID, click Tools | Generate GUID inside the IDE.) AppId={{56C1065D-3523-4025-B76D-6F73F67F7F71} AppName={#AppName} -AppVersion={#MajorVersion} +AppVersion=3.0 AppPublisher={#AppPublisher} AppPublisherURL={#AppURL} AppSupportURL={#ForumsURL} @@ -29,7 +26,7 @@ DefaultDirName={commonappdata}\Sonarr\bin DisableDirPage=yes DefaultGroupName={#AppName} DisableProgramGroupPage=yes -OutputBaseFilename=Sonarr.{#BranchName}.{#BuildNumber}.{#Runtime}-installer +OutputBaseFilename=Sonarr.{#BranchName}.{#BuildNumber}.windows SolidCompression=yes AppCopyright=Creative Commons 3.0 License AllowUNCPath=False @@ -38,10 +35,9 @@ DisableReadyPage=True CompressionThreads=2 Compression=lzma2/normal AppContact={#ForumsURL} -VersionInfoVersion={#MajorVersion} +VersionInfoVersion={#BuildNumber} SetupLogging=yes -OutputDir="..\..\..\_artifacts" -AppverName={#AppName} +OutputDir=output [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" @@ -53,8 +49,8 @@ Name: "startupShortcut"; Description: "Create shortcut in Startup folder (Starts Name: "none"; Description: "Do not start automatically"; GroupDescription: "Start automatically"; Flags: exclusive unchecked [Files] -Source: "..\..\..\_output\{#Runtime}\{#Framework}\Sonarr\Sonarr.exe"; DestDir: "{app}"; Flags: ignoreversion -Source: "..\..\..\_output\{#Runtime}\{#Framework}\Sonarr\*"; Excludes: "Sonarr.Update"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs +Source: "..\..\..\_output_windows\Sonarr.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\..\..\_output_windows\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs ; NOTE: Don't use "Flags: ignoreversion" on any shared system files [Icons] @@ -84,3 +80,26 @@ begin Exec('net', 'stop nzbdrone', '', 0, ewWaitUntilTerminated, ResultCode) Exec('sc', 'delete nzbdrone', '', 0, ewWaitUntilTerminated, ResultCode) end; + +function Framework472IsNotInstalled(): Boolean; +var + bSuccess: Boolean; + regVersion: Cardinal; +begin + Result := True; +bSuccess := RegQueryDWordValue(HKLM, 'Software\Microsoft\NET Framework Setup\NDP\v4\Full', 'Release', regVersion); + if (True = bSuccess) and (regVersion >= 461808) then begin + Result := False; + end; +end; + +function InitializeSetup(): Boolean; +begin + if Framework472IsNotInstalled() then begin + MsgBox('Sonarr requires Microsoft .NET Framework 4.7.2 or higher.'#13#13 + 'Please use Windows Update to install this version'#13 + 'or download it from https://dotnet.microsoft.com/download/dotnet-framework.', mbInformation, MB_OK); + result := false; + end else + result := true; +end; diff --git a/docs.sh b/docs.sh deleted file mode 100755 index 386f5df68..000000000 --- a/docs.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -set -e - -FRAMEWORK="net6.0" -PLATFORM=$1 - -if [ "$PLATFORM" = "Windows" ]; then - RUNTIME="win-x64" -elif [ "$PLATFORM" = "Linux" ]; then - RUNTIME="linux-x64" -elif [ "$PLATFORM" = "Mac" ]; then - RUNTIME="osx-x64" -else - echo "Platform must be provided as first argument: Windows, Linux or Mac" - exit 1 -fi - -outputFolder='_output' -testPackageFolder='_tests' - -rm -rf $outputFolder -rm -rf $testPackageFolder - -slnFile=src/Sonarr.sln - -platform=Posix - -if [ "$PLATFORM" = "Windows" ]; then - application=Sonarr.Console.dll -else - application=Sonarr.dll -fi - -dotnet clean $slnFile -c Debug -dotnet clean $slnFile -c Release - -dotnet msbuild -restore $slnFile -p:Configuration=Debug -p:Platform=$platform -p:RuntimeIdentifiers=$RUNTIME -t:PublishAllRids - -dotnet new tool-manifest -dotnet tool install --version 6.6.2 Swashbuckle.AspNetCore.Cli - -dotnet tool run swagger tofile --output ./src/Sonarr.Api.V3/openapi.json "$outputFolder/$FRAMEWORK/$RUNTIME/$application" v3 & - -sleep 45 - -kill %1 - -exit 0 diff --git a/frontend/.csscomb.json b/frontend/.csscomb.json new file mode 100644 index 000000000..a82e49732 --- /dev/null +++ b/frontend/.csscomb.json @@ -0,0 +1,25 @@ +{ + "remove-empty-rulesets": true, + "always-semicolon": true, + "color-case": "lower", + "block-indent": " ", + "color-shorthand": false, + "element-case": "lower", + "eof-newline": true, + "leading-zero": true, + "quotes": "double", + "sort-order-fallback": "abc", + "space-before-colon": "", + "space-after-colon": " ", + "space-before-combinator": " ", + "space-after-combinator": " ", + "space-between-declarations": "\n", + "space-before-opening-brace": " ", + "space-after-opening-brace": "\n", + "space-after-selector-delimiter": " ", + "space-before-selector-delimiter": "", + "space-before-closing-brace": "\n", + "strip-spaces": true, + "tab-size": true, + "unitless-zero": false +} diff --git a/frontend/.esformatter b/frontend/.esformatter new file mode 100644 index 000000000..600bb0751 --- /dev/null +++ b/frontend/.esformatter @@ -0,0 +1,335 @@ +{ + "indent": { + "value": " ", + "FunctionExpression": 1, + "ArrayExpression": 1, + "ObjectExpression": 1 + }, + "lineBreak": { + "value": "\n", + + "before": { + "ArrayPatternClosing": 0, + "ArrayPatternComma": 0, + "ArrayPatternOpening": 0, + "ArrowFunctionExpressionArrow": 0, + "ArrowFunctionExpressionClosingBrace": ">=1", + "ArrowFunctionExpressionOpeningBrace": 0, + "AssignmentExpression": ">=1", + "AssignmentOperator": 0, + "BlockStatement": 0, + "BreakKeyword": ">=1", + "CallExpression": -1, + "CallExpressionClosingParentheses": -1, + "CallExpressionOpeningParentheses": 0, + "CatchClosingBrace": ">=1", + "CatchKeyword": 0, + "CatchOpeningBrace": 0, + "ClassDeclaration": ">=1", + "ClassDeclarationClosingBrace": ">=1", + "ClassDeclarationOpeningBrace": 0, + "ConditionalExpression": ">=1", + "DeleteOperator": ">=1", + "DoWhileStatement": ">=1", + "DoWhileStatementClosingBrace": ">=1", + "DoWhileStatementOpeningBrace": 0, + "ElseIfStatement": 0, + "ElseIfStatementClosingBrace": ">=1", + "ElseIfStatementOpeningBrace": 0, + "ElseStatement": 0, + "ElseStatementClosingBrace": ">=1", + "ElseStatementOpeningBrace": 0, + "EmptyStatement": -1, + "EndOfFile": -1, + "FinallyClosingBrace": ">=1", + "FinallyKeyword": -1, + "FinallyOpeningBrace": 0, + "ForInStatement": ">=1", + "ForInStatementClosingBrace": ">=1", + "ForInStatementExpressionClosing": 0, + "ForInStatementExpressionOpening": 0, + "ForInStatementOpeningBrace": 0, + "ForStatement": ">=1", + "ForStatementClosingBrace": ">=1", + "ForStatementExpressionClosing": "<2", + "ForStatementExpressionOpening": 0, + "ForStatementOpeningBrace": 0, + "FunctionDeclaration": ">=1", + "FunctionDeclarationClosingBrace": ">=1", + "FunctionDeclarationOpeningBrace": 0, + "FunctionExpression": 0, + "FunctionExpressionClosingBrace": 1, + "FunctionExpressionOpeningBrace":0, + "IIFEClosingParentheses": 0, + "IfStatement": ">=1", + "IfStatementClosingBrace": ">=1", + "IfStatementOpeningBrace": 0, + "LogicalExpression": -1, + "MemberExpressionClosing": 0, + "MemberExpressionOpening": 0, + "MemberExpressionPeriod": -1, + "MethodDefinition": ">=1", + "ObjectExpressionClosingBrace": "<=1", + "ObjectPatternClosingBrace": 0, + "ObjectPatternComma": 0, + "ObjectPatternOpeningBrace": 0, + "ParameterDefault": 0, + "Property": "<=2", + "PropertyValue": 0, + "ReturnStatement": -1, + "SwitchClosingBrace": ">=1", + "SwitchOpeningBrace": 0, + "ThisExpression": -1, + "ThrowStatement": ">=1", + "TryClosingBrace": ">=1", + "TryKeyword": -1, + "TryOpeningBrace": 0, + "VariableDeclaration": ">=1", + "VariableDeclarationSemiColon": 0, + "VariableDeclarationWithoutInit": ">=1", + "VariableName": ">=1", + "VariableValue": 0, + "WhileStatement": ">=1", + "WhileStatementClosingBrace": ">=1", + "WhileStatementOpeningBrace": 0 + }, + + "after": { + "ArrayPatternClosing": 0, + "ArrayPatternComma": 0, + "ArrayPatternOpening": 0, + "ArrowFunctionExpressionArrow": 0, + "ArrowFunctionExpressionClosingBrace": -1, + "ArrowFunctionExpressionOpeningBrace": ">=1", + "AssignmentExpression": ">=1", + "AssignmentOperator": 0, + "BlockStatement": 0, + "BreakKeyword": -1, + "CallExpression": -1, + "CallExpressionClosingParentheses": -1, + "CallExpressionOpeningParentheses": -1, + "CatchClosingBrace": ">=0", + "CatchKeyword": 0, + "CatchOpeningBrace": ">=1", + "ClassDeclaration": ">=1", + "ClassDeclarationClosingBrace": ">=1", + "ClassDeclarationOpeningBrace": ">=1", + "ConditionalExpression": ">=1", + "DeleteOperator": ">=1", + "DoWhileStatement": ">=1", + "DoWhileStatementClosingBrace": 0, + "DoWhileStatementOpeningBrace": ">=1", + "ElseIfStatement": ">=1", + "ElseIfStatementClosingBrace": ">=1", + "ElseIfStatementOpeningBrace": ">=1", + "ElseStatement": ">=1", + "ElseStatementClosingBrace": ">=1", + "ElseStatementOpeningBrace": ">=1", + "EmptyStatement": -1, + "FinallyClosingBrace": ">=1", + "FinallyKeyword": -1, + "FinallyOpeningBrace": ">=1", + "ForInStatement": ">=1", + "ForInStatementClosingBrace": ">=1", + "ForInStatementExpressionClosing": -1, + "ForInStatementExpressionOpening": "<2", + "ForInStatementOpeningBrace": ">=1", + "ForStatement": ">=1", + "ForStatementClosingBrace": ">=1", + "ForStatementExpressionClosing": -1, + "ForStatementExpressionOpening": "<2", + "ForStatementOpeningBrace": ">=1", + "FunctionDeclaration": ">=1", + "FunctionDeclarationClosingBrace": ">=1", + "FunctionDeclarationOpeningBrace": ">=1", + "FunctionExpression": 0, + "FunctionExpressionClosingBrace": -1, + "FunctionExpressionOpeningBrace": 1, + "IIFEOpeningParentheses": 0, + "IfStatement": ">=1", + "IfStatementClosingBrace": ">=1", + "IfStatementOpeningBrace": ">=1", + "LogicalExpression": -1, + "MemberExpressionClosing": 0, + "MemberExpressionOpening": 0, + "MemberExpressionPeriod": 0, + "MethodDefinition": ">=1", + "ObjectExpressionOpeningBrace": "<=1", + "ObjectPatternClosingBrace": 0, + "ObjectPatternComma": 0, + "ObjectPatternOpeningBrace": 0, + "ParameterDefault": 0, + "Property": -1, + "PropertyName": 0, + "ReturnStatement": -1, + "SwitchCaseColon": ">=1", + "SwitchClosingBrace": ">=1", + "SwitchOpeningBrace": ">=1", + "ThisExpression": 0, + "ThrowStatement": ">=1", + "TryClosingBrace": 0, + "TryKeyword": -1, + "TryOpeningBrace": ">=1", + "VariableDeclaration": ">=1", + "VariableDeclarationSemiColon": ">=1", + "VariableValue": -1, + "WhileStatement": ">=1", + "WhileStatementClosingBrace": ">=1", + "WhileStatementOpeningBrace": ">=1" + } + }, + "whiteSpace": { + "value": " ", + "removeTrailing": 1, + "before": { + "ArgumentComma": 0, + "ArgumentList": 0, + "ArgumentListArrayExpression": 0, + "ArgumentListFunctionExpression": 1, + "ArgumentListObjectExpression": 0, + "ArrayExpressionClosing": 0, + "ArrayExpressionComma": 0, + "ArrayExpressionOpening": 1, + "AssignmentOperator": 1, + "BinaryExpression": 0, + "BinaryExpressionOperator": 1, + "BlockComment": 1, + "CallExpression": 1, + "CatchClosingBrace": 1, + "CatchKeyword": 1, + "CatchOpeningBrace": 1, + "CatchParameterList": 0, + "CommaOperator": 0, + "ConditionalExpressionAlternate": 1, + "ConditionalExpressionConsequent": 1, + "DoWhileStatementClosingBrace": 1, + "DoWhileStatementConditional": 1, + "DoWhileStatementOpeningBrace": 1, + "ElseIfStatementClosingBrace": 1, + "ElseIfStatementOpeningBrace": 1, + "ElseStatementClosingBrace": 1, + "ElseStatementOpeningBrace": 1, + "EmptyStatement": 0, + "ExpressionClosingParentheses": 0, + "FinallyClosingBrace": 1, + "FinallyKeyword": -1, + "FinallyOpeningBrace": 1, + "ForInStatement": 1, + "ForInStatementClosingBrace": 1, + "ForInStatementExpressionClosing": 0, + "ForInStatementExpressionOpening": 1, + "ForInStatementOpeningBrace": 1, + "ForStatement": 1, + "ForStatementClosingBrace": 1, + "ForStatementExpressionClosing": 0, + "ForStatementExpressionOpening": 1, + "ForStatementOpeningBrace": 1, + "ForStatementSemicolon": 0, + "FunctionDeclarationClosingBrace": 1, + "FunctionDeclarationOpeningBrace": 1, + "FunctionExpressionClosingBrace": 1, + "FunctionExpressionOpeningBrace": 1, + "IfStatementClosingBrace": 1, + "IfStatementConditionalClosing": 0, + "IfStatementConditionalOpening": 1, + "IfStatementOpeningBrace": 1, + "LineComment": 1, + "LogicalExpressionOperator": 1, + "MemberExpressionClosing": 0, + "ObjectExpressionClosingBrace": 1, + "ParameterComma": 0, + "ParameterList": 0, + "Property": 1, + "PropertyName": 1, + "PropertyValue": 1, + "SwitchDiscriminantClosing": 0, + "SwitchDiscriminantOpening": 1, + "ThrowKeyword": 1, + "TryClosingBrace": 1, + "TryKeyword": -1, + "TryOpeningBrace": 1, + "UnaryExpressionOperator": 0, + "VariableName": 1, + "VariableValue": 1, + "WhileStatementClosingBrace": 1, + "WhileStatementConditionalClosing": 0, + "WhileStatementConditionalOpening": 1, + "WhileStatementOpeningBrace": 1 + }, + "after": { + "ArgumentComma": 1, + "ArgumentList": 0, + "ArgumentListArrayExpression": 1, + "ArgumentListFunctionExpression": 1, + "ArgumentListObjectExpression": 0, + "ArrayExpressionClosing": 0, + "ArrayExpressionComma": 1, + "ArrayExpressionOpening": 0, + "AssignmentOperator": 1, + "BinaryExpression": 0, + "BinaryExpressionOperator": 1, + "BlockComment": 1, + "CallExpression": 0, + "CatchClosingBrace": 1, + "CatchKeyword": 1, + "CatchOpeningBrace": 1, + "CatchParameterList": 0, + "CommaOperator": 1, + "ConditionalExpressionConsequent": 1, + "ConditionalExpressionTest": 1, + "DoWhileStatementBody": 1, + "DoWhileStatementClosingBrace": 1, + "DoWhileStatementOpeningBrace": 1, + "ElseIfStatementClosingBrace": 1, + "ElseIfStatementOpeningBrace": 1, + "ElseStatementClosingBrace": 1, + "ElseStatementOpeningBrace": 1, + "EmptyStatement": 0, + "ExpressionOpeningParentheses": 0, + "FinallyClosingBrace": 1, + "FinallyKeyword": -1, + "FinallyOpeningBrace": 1, + "ForInStatement": 1, + "ForInStatementClosingBrace": 1, + "ForInStatementExpressionClosing": 1, + "ForInStatementExpressionOpening": 0, + "ForInStatementOpeningBrace": 1, + "ForStatement": 1, + "ForStatementClosingBrace": 1, + "ForStatementExpressionClosing": 1, + "ForStatementExpressionOpening": 0, + "ForStatementOpeningBrace": 1, + "ForStatementSemicolon": 1, + "FunctionDeclarationClosingBrace": 0, + "FunctionDeclarationOpeningBrace": 0, + "FunctionExpressionClosingBrace": 0, + "FunctionExpressionOpeningBrace": 0, + "FunctionName": 0, + "FunctionReservedWord": 0, + "IfStatementClosingBrace": 1, + "IfStatementConditionalClosing": 0, + "IfStatementConditionalOpening": 0, + "IfStatementOpeningBrace": 1, + "LogicalExpressionOperator": 1, + "MemberExpressionOpening": 0, + "ObjectExpressionClosingBrace": 0, + "ObjectExpressionOpeningBrace": 1, + "ParameterComma": 1, + "ParameterList": 0, + "PropertyName": 0, + "PropertyValue": 0, + "SwitchDiscriminantClosing": 1, + "SwitchDiscriminantOpening": 0, + "ThrowKeyword": 1, + "TryClosingBrace": 1, + "TryKeyword": -1, + "TryOpeningBrace": 1, + "UnaryExpressionOperator": 0, + "VariableName": 1, + "WhileStatementClosingBrace": 1, + "WhileStatementConditionalClosing": 1, + "WhileStatementConditionalOpening": 0, + "WhileStatementOpeningBrace": 1 + } + } +} diff --git a/frontend/.eslintignore b/frontend/.eslintignore index e6d49ec4d..d4b43f836 100644 --- a/frontend/.eslintignore +++ b/frontend/.eslintignore @@ -1,2 +1 @@ **/JsLibraries/** -**/*.css.d.ts diff --git a/frontend/.eslintrc b/frontend/.eslintrc new file mode 100644 index 000000000..8593e9f61 --- /dev/null +++ b/frontend/.eslintrc @@ -0,0 +1,293 @@ +{ + "parser": "babel-eslint", + + "env": { + "browser": true, + "commonjs": true, + "node": true, + "es6": true + }, + + "globals": { + "expect": false, + "chai": false, + "sinon": false + }, + + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module", + "ecmaFeatures": { + "modules": true, + "impliedStrict": true + } + }, + + "plugins": [ + "filenames", + "react" + ], + + "settings": { + "react": { + "version": "detect" + } + }, + + "rules": { + "filenames/match-exported": ["error"], + + # ECMAScript 6 + + "arrow-body-style": [0], + "arrow-parens": ["error", "always"], + "arrow-spacing": ["error", { "before": true, "after": true }], + "constructor-super": "error", + "generator-star-spacing": "off", + "no-class-assign": "error", + "no-confusing-arrow": "error", + "no-const-assign": "error", + "no-dupe-class-members": "error", + "no-duplicate-imports": "error", + "no-new-symbol": "error", + "no-this-before-super": "error", + "no-useless-escape": "error", + "no-useless-computed-key": "error", + "no-useless-constructor": "error", + "no-var": "warn", + "object-shorthand": ["error", "properties"], + "prefer-arrow-callback": "error", + "prefer-const": "warn", + "prefer-reflect": "off", + "prefer-rest-params": "off", + "prefer-spread": "warn", + "prefer-template": "error", + "require-yield": "off", + "template-curly-spacing": ["error", "never"], + "yield-star-spacing": "off", + + # Possible Errors + + "comma-dangle": "error", + "no-cond-assign": "error", + "no-console": "off", + "no-constant-condition": "warn", + "no-control-regex": "error", + "no-debugger": "off", + "no-dupe-args": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-empty": "warn", + "no-empty-character-class": "error", + "no-ex-assign": "error", + "no-extra-boolean-cast": "error", + "no-extra-parens": ["error", "functions"], + "no-extra-semi": "error", + "no-func-assign": "error", + "no-inner-declarations": "error", + "no-invalid-regexp": "error", + "no-irregular-whitespace": "error", + "no-negated-in-lhs": "error", + "no-obj-calls": "error", + "no-regex-spaces": "error", + "no-sparse-arrays": "error", + "no-unexpected-multiline": "error", + "no-unreachable": "warn", + "no-unsafe-finally": "error", + "use-isnan": "error", + "valid-jsdoc": "off", + "valid-typeof": "error", + + # Best Practices + + "accessor-pairs": "off", + "array-callback-return": "warn", + "block-scoped-var": "warn", + "consistent-return": "off", + "curly": "error", + "default-case": "error", + "dot-location": ["error", "property"], + "dot-notation": "error", + "eqeqeq": ["error", "smart"], + "guard-for-in": "error", + "no-alert": "warn", + "no-caller": "error", + "no-case-declarations": "error", + "no-div-regex": "error", + "no-else-return": "error", + "no-empty-function": ["error", {"allow": ["arrowFunctions"]}], + "no-empty-pattern": "error", + "no-eval": "error", + "no-extend-native": "error", + "no-extra-bind": "error", + "no-fallthrough": "error", + "no-floating-decimal": "error", + "no-implicit-coercion": ["error", { + "boolean": false, + "number": true, + "string": true, + "allow": [/* "!!", "~", "*", "+" */] + }], + "no-implicit-globals": "error", + "no-implied-eval": "error", + "no-invalid-this": "off", + "no-iterator": "error", + "no-labels": "error", + "no-lone-blocks": "error", + "no-loop-func": "error", + "no-magic-numbers": ["off", {"ignoreArrayIndexes": true, "ignore": [0, 1] }], + "no-multi-spaces": "error", + "no-multi-str": "error", + "no-native-reassign": ["error", {"exceptions": ["console"]}], + "no-new": "off", + "no-new-func": "error", + "no-new-wrappers": "error", + "no-octal": "error", + "no-octal-escape": "error", + "no-param-reassign": "off", + "no-process-env": "off", + "no-proto": "error", + "no-redeclare": "error", + "no-return-assign": "warn", + "no-script-url": "error", + "no-self-assign": "error", + "no-self-compare": "error", + "no-sequences": "error", + "no-throw-literal": "error", + "no-unmodified-loop-condition": "error", + "no-unused-expressions": "error", + "no-unused-labels": "error", + "no-useless-call": "error", + "no-useless-concat": "error", + "no-void": "error", + "no-warning-comments": "off", + "no-with": "error", + "radix": ["error", "as-needed"], + "vars-on-top": "off", + "wrap-iife": ["error", "inside"], + "yoda": "error", + + # Strict Mode + + "strict": ["error", "never"], + + # Variables + + "init-declarations": ["error", "always"], + "no-catch-shadow": "error", + "no-delete-var": "error", + "no-label-var": "error", + "no-restricted-globals": "off", + "no-shadow": "error", + "no-shadow-restricted-names": "error", + "no-undef": "error", + "no-undef-init": "off", + "no-undefined": "off", + "no-unused-vars": ["error", { "args": "none", "ignoreRestSiblings": true }], + "no-use-before-define": "error", + + # Node.js and CommonJS + + "callback-return": "warn", + "global-require": "error", + "handle-callback-err": "warn", + "no-mixed-requires": "error", + "no-new-require": "error", + "no-path-concat": "error", + "no-process-exit": "error", + + # Stylistic Issues + + "array-bracket-spacing": ["error", "never"], + "block-spacing": ["error", "always"], + "brace-style": ["error", "1tbs", { "allowSingleLine": false }], + "camelcase": "off", + "comma-spacing": ["error", {"before": false, "after": true}], + "comma-style": ["error", "last"], + "computed-property-spacing": ["error", "never"], + "consistent-this": ["error", "self"], + "eol-last": "error", + "func-names": "off", + "func-style": ["error", "declaration"], + "indent": ["error", 2, {"SwitchCase": 1}], + "key-spacing": ["error", {"beforeColon": false, "afterColon": true}], + "keyword-spacing": ["error", { "before": true, "after": true}], + "lines-around-comment": ["error", { "beforeBlockComment": true, "afterBlockComment": false }], + "max-depth": ["error", {"maximum": 5}], + "max-nested-callbacks": ["error", 4], + "max-statements": "off", + "max-statements-per-line": ["error", { "max": 1 }], + "new-cap": ["error", {"capIsNewExceptions": ["$.Deferred", "DragDropContext", "DragLayer", "DragSource", "DropTarget"]}], + "new-parens": "error", + "newline-after-var": "off", + "newline-before-return": "off", + "newline-per-chained-call": "off", + "no-array-constructor": "error", + "no-bitwise": "error", + "no-continue": "error", + "no-inline-comments": "off", + "no-lonely-if": "warn", + "no-mixed-spaces-and-tabs": "error", + "no-multiple-empty-lines": ["error", { "max": 1 }], + "no-negated-condition": "warn", + "no-nested-ternary": "error", + "no-new-object": "error", + "no-plusplus": "off", + "no-restricted-syntax": "off", + "no-spaced-func": "error", + "no-ternary": "off", + "no-trailing-spaces": "error", + "no-underscore-dangle": ["error", { "allowAfterThis": true }], + "no-unneeded-ternary": "error", + "no-whitespace-before-property": "error", + "object-curly-spacing": ["error", "always"], + "one-var": ["error", "never"], + "one-var-declaration-per-line": ["error", "always"], + "operator-assignment": ["off", "never"], + "operator-linebreak": ["error", "after"], + "quote-props": ["error", "as-needed"], + "quotes": ["error", "single"], + "require-jsdoc": "off", + "semi": "error", + "semi-spacing": ["error", { "before": false, "after": true }], + "sort-vars": "off", + "space-before-blocks": ["error", "always"], + "space-before-function-paren": ["error", "never"], + "space-in-parens": "off", + "space-infix-ops": "off", + "space-unary-ops": "off", + "spaced-comment": "error", + "wrap-regex": "error", + + # React + + "react/jsx-boolean-value": [2, "always"], + "react/jsx-uses-vars": 2, + "react/jsx-closing-bracket-location": 2, + "react/jsx-tag-spacing": ["error"], + "react/jsx-curly-spacing": [2, "never"], + "react/jsx-equals-spacing": [2, "never"], + "react/jsx-indent-props": [2, 2], + "react/jsx-indent": [2, 2], + "react/jsx-key": 2, + "react/jsx-no-bind": [2, { "allowArrowFunctions": true }], + "react/jsx-no-duplicate-props": [2, { "ignoreCase": true }], + "react/jsx-max-props-per-line": [2, { "maximum": 2 }], + "react/jsx-handler-names": [2, { "eventHandlerPrefix": "(on|dispatch)", "eventHandlerPropPrefix": "on" }], + "react/jsx-no-undef": 2, + "react/jsx-pascal-case": 2, + "react/jsx-uses-react": 2, + // Explicitly disabled in case we want to enable them again + "react/no-did-mount-set-state": 0, + "react/no-did-update-set-state": 0, + "react/no-direct-mutation-state": 2, + "react/no-multi-comp": [2, { "ignoreStateless": true }], + "react/no-unknown-property": 2, + "react/prefer-es6-class": 2, + "react/prop-types": 2, + "react/react-in-jsx-scope": 2, + "react/self-closing-comp": 2, + "react/sort-comp": 2, + "react/jsx-wrap-multilines": 2 + } +} diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.js deleted file mode 100644 index e14b9125d..000000000 --- a/frontend/.eslintrc.js +++ /dev/null @@ -1,435 +0,0 @@ -// eslint-disable-next-line @typescript-eslint/no-var-requires -const fs = require('fs'); -// eslint-disable-next-line @typescript-eslint/no-var-requires -const path = require('path'); -// eslint-disable-next-line @typescript-eslint/no-var-requires -const typescriptEslintRecommended = require('@typescript-eslint/eslint-plugin').configs.recommended; - -const frontendFolder = __dirname; - -const dirs = fs - .readdirSync(path.join(frontendFolder, 'src'), { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) - .map((dirent) => dirent.name) - .join('|'); - -module.exports = { - root: true, - - parser: '@babel/eslint-parser', - - env: { - browser: true, - commonjs: true, - node: true, - es6: true - }, - - globals: { - expect: false, - chai: false, - sinon: false, - JSX: true - }, - - parserOptions: { - ecmaVersion: 6, - sourceType: 'module', - babelOptions: { - configFile: `${frontendFolder}/babel.config.js` - }, - ecmaFeatures: { - modules: true, - impliedStrict: true - } - }, - - plugins: [ - 'filenames', - 'react', - 'react-hooks', - 'simple-import-sort', - 'import', - '@typescript-eslint', - 'prettier' - ], - - settings: { - react: { - version: 'detect' - } - }, - - rules: { - 'filenames/match-exported': ['error'], - - // ECMAScript 6 - - 'arrow-body-style': [0], - 'arrow-parens': ['error', 'always'], - 'arrow-spacing': ['error', { before: true, after: true }], - 'constructor-super': 'error', - 'generator-star-spacing': 'off', - 'no-class-assign': 'error', - 'no-confusing-arrow': 'error', - 'no-const-assign': 'error', - 'no-dupe-class-members': 'error', - 'no-duplicate-imports': 'error', - 'no-new-symbol': 'error', - 'no-this-before-super': 'error', - 'no-useless-escape': 'error', - 'no-useless-computed-key': 'error', - 'no-useless-constructor': 'error', - 'no-var': 'warn', - 'object-shorthand': ['error', 'properties'], - 'prefer-arrow-callback': 'error', - 'prefer-const': 'warn', - 'prefer-reflect': 'off', - 'prefer-rest-params': 'off', - 'prefer-spread': 'warn', - 'prefer-template': 'error', - 'require-yield': 'off', - 'template-curly-spacing': ['error', 'never'], - 'yield-star-spacing': 'off', - - // Possible Errors - - 'comma-dangle': 'error', - 'no-cond-assign': 'error', - 'no-console': 'off', - 'no-constant-condition': 'warn', - 'no-control-regex': 'error', - 'no-debugger': 'off', - 'no-dupe-args': 'error', - 'no-dupe-keys': 'error', - 'no-duplicate-case': 'error', - 'no-empty': 'warn', - 'no-empty-character-class': 'error', - 'no-ex-assign': 'error', - 'no-extra-boolean-cast': 'error', - 'no-extra-parens': ['error', 'functions'], - 'no-extra-semi': 'error', - 'no-func-assign': 'error', - 'no-inner-declarations': 'error', - 'no-invalid-regexp': 'error', - 'no-irregular-whitespace': 'error', - 'no-negated-in-lhs': 'error', - 'no-obj-calls': 'error', - 'no-regex-spaces': 'error', - 'no-sparse-arrays': 'error', - 'no-unexpected-multiline': 'error', - 'no-unreachable': 'warn', - 'no-unsafe-finally': 'error', - 'use-isnan': 'error', - 'valid-jsdoc': 'off', - 'valid-typeof': 'error', - - // Best Practices - - 'accessor-pairs': 'off', - 'array-callback-return': 'warn', - 'block-scoped-var': 'warn', - 'consistent-return': 'off', - curly: 'error', - 'default-case': 'error', - 'dot-location': ['error', 'property'], - 'dot-notation': 'error', - eqeqeq: ['error', 'smart'], - 'guard-for-in': 'error', - 'no-alert': 'warn', - 'no-caller': 'error', - 'no-case-declarations': 'error', - 'no-div-regex': 'error', - 'no-else-return': 'error', - 'no-empty-function': ['error', { allow: ['arrowFunctions'] }], - 'no-empty-pattern': 'error', - 'no-eval': 'error', - 'no-extend-native': 'error', - 'no-extra-bind': 'error', - 'no-fallthrough': 'error', - 'no-floating-decimal': 'error', - 'no-implicit-coercion': ['error', { - boolean: false, - number: true, - string: true, - allow: [/* "!!", "~", "*", "+" */] - }], - 'no-implicit-globals': 'error', - 'no-implied-eval': 'error', - 'no-invalid-this': 'off', - 'no-iterator': 'error', - 'no-labels': 'error', - 'no-lone-blocks': 'error', - 'no-loop-func': 'error', - 'no-magic-numbers': ['off', { ignoreArrayIndexes: true, ignore: [0, 1] }], - 'no-multi-spaces': 'error', - 'no-multi-str': 'error', - 'no-native-reassign': ['error', { exceptions: ['console'] }], - 'no-new': 'off', - 'no-new-func': 'error', - 'no-new-wrappers': 'error', - 'no-octal': 'error', - 'no-octal-escape': 'error', - 'no-param-reassign': 'off', - 'no-process-env': 'off', - 'no-proto': 'error', - 'no-redeclare': 'error', - 'no-return-assign': 'warn', - 'no-script-url': 'error', - 'no-self-assign': 'error', - 'no-self-compare': 'error', - 'no-sequences': 'error', - 'no-throw-literal': 'error', - 'no-unmodified-loop-condition': 'error', - 'no-unused-expressions': 'error', - 'no-unused-labels': 'error', - 'no-useless-call': 'error', - 'no-useless-concat': 'error', - 'no-void': 'error', - 'no-warning-comments': 'off', - 'no-with': 'error', - radix: ['error', 'as-needed'], - 'vars-on-top': 'off', - 'wrap-iife': ['error', 'inside'], - yoda: 'error', - - // Strict Mode - - strict: ['error', 'never'], - - // Variables - - 'init-declarations': ['error', 'always'], - 'no-catch-shadow': 'error', - 'no-delete-var': 'error', - 'no-label-var': 'error', - 'no-restricted-globals': 'off', - 'no-shadow': 'error', - 'no-shadow-restricted-names': 'error', - 'no-undef': 'error', - 'no-undef-init': 'off', - 'no-undefined': 'off', - 'no-unused-vars': ['error', { args: 'none', ignoreRestSiblings: true }], - - // Node.js and CommonJS - - 'callback-return': 'warn', - 'global-require': 'error', - 'handle-callback-err': 'warn', - 'no-mixed-requires': 'error', - 'no-new-require': 'error', - 'no-path-concat': 'error', - 'no-process-exit': 'error', - - // Stylistic Issues - - 'array-bracket-spacing': ['error', 'never'], - 'block-spacing': ['error', 'always'], - 'brace-style': ['error', '1tbs', { allowSingleLine: false }], - camelcase: 'off', - 'comma-spacing': ['error', { before: false, after: true }], - 'comma-style': ['error', 'last'], - 'computed-property-spacing': ['error', 'never'], - 'consistent-this': ['error', 'self'], - 'eol-last': 'error', - 'func-names': 'off', - 'func-style': ['error', 'declaration', { allowArrowFunctions: true }], - indent: ['error', 2, { SwitchCase: 1 }], - 'key-spacing': ['error', { beforeColon: false, afterColon: true }], - 'keyword-spacing': ['error', { before: true, after: true }], - 'lines-around-comment': ['error', { beforeBlockComment: true, afterBlockComment: false }], - 'max-depth': ['error', { maximum: 5 }], - 'max-nested-callbacks': ['error', 4], - 'max-statements': 'off', - 'max-statements-per-line': ['error', { max: 1 }], - 'new-cap': ['error', { capIsNewExceptions: ['$.Deferred', 'DragDropContext', 'DragLayer', 'DragSource', 'DropTarget'] }], - 'new-parens': 'error', - 'newline-after-var': 'off', - 'newline-before-return': 'off', - 'newline-per-chained-call': 'off', - 'no-array-constructor': 'error', - 'no-bitwise': 'error', - 'no-continue': 'error', - 'no-inline-comments': 'off', - 'no-lonely-if': 'warn', - 'no-mixed-spaces-and-tabs': 'error', - 'no-multiple-empty-lines': ['error', { max: 1 }], - 'no-negated-condition': 'warn', - 'no-nested-ternary': 'error', - 'no-new-object': 'error', - 'no-plusplus': 'off', - 'no-restricted-syntax': 'off', - 'no-spaced-func': 'error', - 'no-ternary': 'off', - 'no-trailing-spaces': 'error', - 'no-underscore-dangle': ['error', { allowAfterThis: true }], - 'no-unneeded-ternary': 'error', - 'no-whitespace-before-property': 'error', - 'object-curly-spacing': ['error', 'always'], - 'one-var': ['error', 'never'], - 'one-var-declaration-per-line': ['error', 'always'], - 'operator-assignment': ['off', 'never'], - 'operator-linebreak': ['error', 'after'], - 'quote-props': ['error', 'as-needed'], - quotes: ['error', 'single'], - 'require-jsdoc': 'off', - semi: 'error', - 'semi-spacing': ['error', { before: false, after: true }], - 'sort-vars': 'off', - 'space-before-blocks': ['error', 'always'], - 'space-before-function-paren': ['error', 'never'], - 'space-in-parens': 'off', - 'space-infix-ops': 'off', - 'space-unary-ops': 'off', - 'spaced-comment': 'error', - 'wrap-regex': 'error', - - // ImportSort - - 'simple-import-sort/imports': 'error', - 'import/newline-after-import': 'error', - - // React - - 'react/jsx-boolean-value': [2, 'always'], - 'react/jsx-uses-vars': 2, - 'react/jsx-closing-bracket-location': 2, - 'react/jsx-tag-spacing': ['error'], - 'react/jsx-curly-spacing': [2, 'never'], - 'react/jsx-equals-spacing': [2, 'never'], - 'react/jsx-indent-props': [2, 2], - 'react/jsx-indent': [2, 2, { indentLogicalExpressions: true }], - 'react/jsx-key': 2, - 'react/jsx-no-bind': [2, { allowArrowFunctions: true }], - 'react/jsx-no-duplicate-props': [2, { ignoreCase: true }], - 'react/jsx-max-props-per-line': [2, { maximum: 2 }], - 'react/jsx-handler-names': [2, { eventHandlerPrefix: '(on|dispatch)', eventHandlerPropPrefix: 'on' }], - 'react/jsx-no-undef': 2, - 'react/jsx-pascal-case': 2, - 'react/jsx-uses-react': 2, - // Explicitly disabled in case we want to enable them again - 'react/no-did-mount-set-state': 0, - 'react/no-did-update-set-state': 0, - 'react/no-direct-mutation-state': 2, - 'react/no-multi-comp': [2, { ignoreStateless: true }], - 'react/no-unknown-property': 2, - 'react/prefer-es6-class': 2, - 'react/prop-types': 2, - 'react/react-in-jsx-scope': 2, - 'react/self-closing-comp': 2, - 'react/sort-comp': 2, - 'react/jsx-wrap-multilines': 2, - 'react-hooks/rules-of-hooks': 'error', - 'react-hooks/exhaustive-deps': 'error' - }, - overrides: [ - { - files: [ - '*.js' - ], - rules: { - 'simple-import-sort/imports': [ - 'error', - { - groups: [ - // Packages - // Absolute Paths - // Relative Paths - // Css - ['^@?\\w', `^(${dirs})(/.*|$)`, '^\\.', '^\\..*css$'] - ] - } - ] - } - }, - { - files: [ - '*.ts', - '*.tsx' - ], - - parser: '@typescript-eslint/parser', - parserOptions: { - project: './tsconfig.json' - }, - - extends: [ - 'prettier' - ], - - rules: Object.assign(typescriptEslintRecommended.rules, { - '@typescript-eslint/no-unused-vars': [ - 'error', - { - args: 'after-used', - argsIgnorePattern: '^_', - caughtErrorsIgnorePattern: '^_', - destructuredArrayIgnorePattern: '^_', - varsIgnorePattern: '^_', - ignoreRestSiblings: true - - } - ], - '@typescript-eslint/explicit-function-return-type': 'off', - 'no-shadow': 'off', - 'prettier/prettier': 'error', - 'simple-import-sort/imports': [ - 'error', - { - groups: [ - // Packages - // Absolute Paths - // Relative Paths - // Css - ['^@?\\w', `^(${dirs})(/.*|$)`, '^\\.', '^\\..*css$'] - ] - } - ], - - // React Hooks - 'react-hooks/rules-of-hooks': 'error', - 'react-hooks/exhaustive-deps': 'error', - - // React - 'react/function-component-definition': 'error', - 'react/hook-use-state': 'error', - 'react/jsx-boolean-value': ['error', 'always'], - 'react/jsx-curly-brace-presence': [ - 'error', - { props: 'never', children: 'never' } - ], - 'react/jsx-fragments': 'error', - 'react/jsx-handler-names': [ - 'error', - { - eventHandlerPrefix: 'on', - eventHandlerPropPrefix: 'on' - } - ], - 'react/jsx-no-bind': ['error', { ignoreRefs: true }], - 'react/jsx-no-useless-fragment': ['error', { allowExpressions: true }], - 'react/jsx-pascal-case': ['error', { allowAllCaps: true }], - 'react/jsx-sort-props': [ - 'error', - { - callbacksLast: true, - noSortAlphabetically: true, - reservedFirst: true - } - ], - 'react/prop-types': 'off', - 'react/self-closing-comp': 'error' - }) - }, - { - files: [ - '*.css.d.ts' - ], - rules: { - 'filenames/match-exported': 'off', - 'init-declarations': 'off', - 'prettier/prettier': 'off' - } - } - ] -}; diff --git a/frontend/.jsbeautifyrc b/frontend/.jsbeautifyrc new file mode 100644 index 000000000..50aa6aa29 --- /dev/null +++ b/frontend/.jsbeautifyrc @@ -0,0 +1,12 @@ +{ + "js": { + "indent_size": 2, + "indent_char": " ", + "indent_level": 2, + "indent_with_tabs": false, + "preserve_newlines": true, + "brace_style": "collapse", + "max_preserve_newlines": 2, + "jslint_happy": true + } +} \ No newline at end of file diff --git a/frontend/.prettierignore b/frontend/.prettierignore deleted file mode 100644 index 3e6367c54..000000000 --- a/frontend/.prettierignore +++ /dev/null @@ -1,10 +0,0 @@ -# Ignore everything recursively -* - -# But not the .ts files -!*.ts* - -*css.d.ts - -# Check subdirectories too -!*/ diff --git a/frontend/.prettierrc.json b/frontend/.prettierrc.json deleted file mode 100644 index 2f91ee691..000000000 --- a/frontend/.prettierrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "arrowParens": "always", - "endOfLine": "auto", - "singleQuote": true, - "trailingComma": "es5" -} diff --git a/frontend/.stylelintrc b/frontend/.stylelintrc index f19357a4c..92a583d89 100644 --- a/frontend/.stylelintrc +++ b/frontend/.stylelintrc @@ -1,12 +1,12 @@ { - "plugins": [ - "stylelint-order" - ], - "ignoreFiles": [ - "frontend/src/Styles/scaffolding.css", - "**/*.js" - ], - "rules": { +"plugins": [ + "stylelint-order" +], +"ignoreFiles": [ + "frontend/src/Styles/scaffolding.css", + "**/*.js" +], +"rules": { "at-rule-empty-line-before": [ "always", { @@ -15,46 +15,96 @@ ] } ], + "at-rule-name-case": "lower", + "at-rule-name-newline-after": "always-multi-line", + "at-rule-name-space-after": "always", "at-rule-no-unknown": [ true, { "ignoreAtRules": [ "/^add\\-mixin$/", "/^define\\-mixin$/" - ] + ] } ], "at-rule-no-vendor-prefix": true, + "at-rule-semicolon-newline-after": "always", + "at-rule-semicolon-space-before": "never", + "block-closing-brace-empty-line-before": "never", + "block-closing-brace-newline-after": "always", + "block-closing-brace-newline-before": "always", + "block-closing-brace-space-after": "always-single-line", + "block-closing-brace-space-before": "always-single-line", "block-no-empty": true, + "block-opening-brace-newline-after": "always", + "block-opening-brace-newline-before": "never-single-line", + "block-opening-brace-space-after": "always-single-line", + "block-opening-brace-space-before": "always", + "color-hex-case": "lower", "color-hex-length": "short", "color-named": "never", "color-no-invalid-hex": true, "comment-whitespace-inside": "always", + "declaration-bang-space-after": "never", + "declaration-bang-space-before": "always", "declaration-block-no-duplicate-properties": [ true, { "ignoreProperties": [ - "composes" + "composes" ] } ], "declaration-block-no-redundant-longhand-properties": true, "declaration-block-no-shorthand-property-overrides": true, + "declaration-block-semicolon-newline-after": "always", + "declaration-block-semicolon-newline-before": "never-multi-line", + "declaration-block-semicolon-space-before": "never", "declaration-block-single-line-max-declarations": 1, + "declaration-block-trailing-semicolon": "always", + "declaration-colon-space-after": "always", + "declaration-colon-space-before": "never", "font-family-name-quotes": "always-unless-keyword", "function-calc-no-unspaced-operator": true, + "function-comma-newline-after": "never-multi-line", + "function-comma-newline-before": "never-multi-line", + "function-comma-space-after": "always", + "function-comma-space-before": "never", "function-linear-gradient-no-nonstandard-direction": true, "function-name-case": "lower", + "function-parentheses-newline-inside": "never-multi-line", + "function-parentheses-space-inside": "never", "function-url-quotes": "always", "function-url-scheme-disallowed-list": [ "data" ], + "function-whitespace-after": "always", + "indentation": 2, "keyframe-declaration-no-important": true, "length-zero-no-unit": true, + "max-empty-lines": 1, + "max-line-length": [ + 100, + { + "ignore": [ + "non-comments" + ] + } + ], "max-nesting-depth": 2, + "media-feature-colon-space-after": "always", + "media-feature-colon-space-before": "never", + "media-feature-name-case": "lower", "media-feature-name-no-vendor-prefix": true, + "media-feature-range-operator-space-after": "always", + "media-feature-range-operator-space-before": "always", "no-empty-source": true, + "no-eol-whitespace": true, + "no-extra-semicolons": true, "no-invalid-double-slash-comments": true, + "no-missing-end-of-source-newline": true, + "number-leading-zero": "always", + "number-no-trailing-zeros": true, "order/order": [ "custom-properties", "dollar-variables", @@ -82,7 +132,6 @@ "right", "bottom", "left", - "inset", "z-index", "display", "visibility", @@ -294,33 +343,54 @@ ] } ], + "property-case": "lower", "property-no-vendor-prefix": true, "rule-empty-line-before": [ "always", { "except": [ - "first-nested" + "first-nested" ], "ignore": [ - "after-comment" + "after-comment" ] } ], + "selector-attribute-brackets-space-inside": "never", + "selector-attribute-operator-space-after": "never", + "selector-attribute-operator-space-before": "never", "selector-attribute-quotes": "never", "selector-class-pattern": "^[A-Za-z0-9]+$", + "selector-combinator-space-after": "always", + "selector-combinator-space-before": "always", + "selector-descendant-combinator-no-non-space": true, + "selector-list-comma-newline-after": "always", + "selector-list-comma-newline-before": "never-multi-line", + "selector-list-comma-space-before": "never", "selector-max-attribute": 0, "selector-max-class": 3, "selector-max-compound-selectors": 3, + "selector-max-empty-lines": 0, "selector-max-id": 0, "selector-max-universal": 0, + "selector-pseudo-class-case": "lower", + "selector-pseudo-class-parentheses-space-inside": "never", + "selector-pseudo-element-case": "lower", "selector-pseudo-element-colon-notation": "double", "selector-pseudo-element-no-unknown": true, "selector-type-case": "lower", "selector-type-no-unknown": true, "shorthand-property-no-redundant-values": true, "string-no-newline": true, + "string-quotes": "single", "time-min-milliseconds": 100, + "unit-case": "lower", "unit-no-unknown": true, + "value-list-comma-newline-after": "never-multi-line", + "value-list-comma-newline-before": "never-multi-line", + "value-list-comma-space-after": "always", + "value-list-comma-space-before": "never", + "value-list-max-empty-lines": 0, "value-no-vendor-prefix": true } -} \ No newline at end of file +} diff --git a/frontend/.vscode/extensions.json b/frontend/.vscode/extensions.json deleted file mode 100644 index 0e005a3cd..000000000 --- a/frontend/.vscode/extensions.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "recommendations": [ - "stylelint.vscode-stylelint", - "dbaeumer.vscode-eslint", - "esbenp.prettier-vscode" - ] -} \ No newline at end of file diff --git a/frontend/.vscode/settings.json b/frontend/.vscode/settings.json deleted file mode 100644 index 8da95337f..000000000 --- a/frontend/.vscode/settings.json +++ /dev/null @@ -1,23 +0,0 @@ -// Place your settings in this file to overwrite default and user settings. -{ - "files.insertFinalNewline": true, - - "files.exclude": { - "**/node_modules": true, - "**/*.d.css": true - }, - - "editor.formatOnSave": false, - "editor.codeActionsOnSave": { - "source.fixAll": "explicit" - }, - - "typescript.preferences.quoteStyle": "single", - - "eslint.validate": [ - "javascript", - "javascriptreact", - "typescript", - "typescriptreact" - ], -} diff --git a/frontend/babel.config.js b/frontend/babel.config.js index ade9f24a2..fe855af63 100644 --- a/frontend/babel.config.js +++ b/frontend/babel.config.js @@ -2,25 +2,22 @@ const loose = true; module.exports = { plugins: [ - '@babel/plugin-transform-logical-assignment-operators', - // Stage 1 '@babel/plugin-proposal-export-default-from', - ['@babel/plugin-transform-optional-chaining', { loose }], - ['@babel/plugin-transform-nullish-coalescing-operator', { loose }], + ['@babel/plugin-proposal-optional-chaining', { loose }], + ['@babel/plugin-proposal-nullish-coalescing-operator', { loose }], // Stage 2 - '@babel/plugin-transform-export-namespace-from', + '@babel/plugin-proposal-export-namespace-from', // Stage 3 - ['@babel/plugin-transform-class-properties', { loose }], + ['@babel/plugin-proposal-class-properties', { loose }], '@babel/plugin-syntax-dynamic-import' ], env: { development: { presets: [ - ['@babel/preset-react', { development: true }], - '@babel/preset-typescript' + ['@babel/preset-react', { development: true }] ], plugins: [ 'babel-plugin-inline-classnames' @@ -28,8 +25,7 @@ module.exports = { }, production: { presets: [ - '@babel/preset-react', - '@babel/preset-typescript' + '@babel/preset-react' ], plugins: [ 'babel-plugin-transform-react-remove-prop-types' diff --git a/frontend/build/webpack.config.js b/frontend/build/webpack.config.js index 0d0364950..1167916f3 100644 --- a/frontend/build/webpack.config.js +++ b/frontend/build/webpack.config.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-var-requires */ const path = require('path'); const webpack = require('webpack'); const FileManagerPlugin = require('filemanager-webpack-plugin'); @@ -6,7 +5,6 @@ const HtmlWebpackPlugin = require('html-webpack-plugin'); const LiveReloadPlugin = require('webpack-livereload-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const TerserPlugin = require('terser-webpack-plugin'); -const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); module.exports = (env) => { const uiFolder = 'UI'; @@ -26,7 +24,6 @@ module.exports = (env) => { const config = { mode: isProduction ? 'production' : 'development', devtool: isProduction ? 'source-map' : 'eval-source-map', - target: 'web', stats: { children: false @@ -37,53 +34,40 @@ module.exports = (env) => { }, entry: { - index: 'index.ts' + index: 'index.js' }, resolve: { - extensions: [ - '.ts', - '.tsx', - '.js' - ], modules: [ srcFolder, path.join(srcFolder, 'Shims'), 'node_modules' ], alias: { - jquery: 'jquery/dist/jquery.min' - }, - fallback: { - buffer: false, - http: false, - https: false, - url: false, - util: false, - net: false + jquery: 'jquery/src/jquery' } }, output: { path: distFolder, publicPath: '/', - filename: isProduction ? '[name]-[contenthash].js' : '[name].js', + filename: '[name].js', sourceMapFilename: '[file].map' }, optimization: { moduleIds: 'deterministic', - chunkIds: isProduction ? 'deterministic' : 'named' + chunkIds: 'named', + splitChunks: { + chunks: 'initial', + name: 'vendors' + } }, performance: { hints: false }, - experiments: { - topLevelAwait: true - }, - plugins: [ new webpack.DefinePlugin({ __DEV__: !isProduction, @@ -91,15 +75,13 @@ module.exports = (env) => { }), new MiniCssExtractPlugin({ - filename: 'Content/styles.css', - chunkFilename: isProduction ? 'Content/[id]-[chunkhash].css' : 'Content/[id].css' + filename: 'Content/styles.css' }), new HtmlWebpackPlugin({ template: 'frontend/src/index.ejs', filename: 'index.html', - publicPath: '/', - inject: false + publicPath: '/' }), new FileManagerPlugin({ @@ -134,20 +116,12 @@ module.exports = (env) => { { source: 'frontend/src/Content/robots.txt', destination: path.join(distFolder, 'Content/robots.txt') - }, - - // manifest.json and browserconfig.xml - { - source: 'frontend/src/Content/*.(json|xml)', - destination: path.join(distFolder, 'Content') } ] } } }), - new ForkTsCheckerWebpackPlugin(), - new LiveReloadPlugin() ], @@ -171,7 +145,7 @@ module.exports = (env) => { } }, { - test: [/\.jsx?$/, /\.tsx?$/], + test: /\.js?$/, exclude: /(node_modules|JsLibraries)/, use: [ { @@ -187,7 +161,7 @@ module.exports = (env) => { loose: true, debug: false, useBuiltIns: 'entry', - corejs: '3.39' + corejs: 3 } ] ] @@ -202,13 +176,12 @@ module.exports = (env) => { exclude: /(node_modules|globals.css)/, use: [ { loader: MiniCssExtractPlugin.loader }, - { loader: 'css-modules-typescript-loader' }, { loader: 'css-loader', options: { importLoaders: 1, modules: { - localIdentName: isProduction ? '[name]/[local]/[hash:base64:5]' : '[name]/[local]' + localIdentName: '[name]/[local]/[hash:base64:5]' } } }, @@ -271,19 +244,18 @@ module.exports = (env) => { config.resolve.alias['react-dom$'] = 'react-dom/profiling'; config.resolve.alias['scheduler/tracing'] = 'scheduler/tracing-profiling'; - config.optimization = { - minimize: true, - minimizer: [ - new TerserPlugin({ - terserOptions: { - sourceMap: true, // Must be set to true if using source-maps in production - mangle: false, - keep_classnames: true, - keep_fnames: true - } - }) - ] - }; + config.optimization.minimizer = [ + new TerserPlugin({ + cache: true, + parallel: true, + sourceMap: true, // Must be set to true if using source-maps in production + terserOptions: { + mangle: false, + keep_classnames: true, + keep_fnames: true + } + }) + ]; } return config; diff --git a/frontend/build/webpack/css-variables-loader.js b/frontend/build/webpack/css-variables-loader.js index 717d7d323..5683c98be 100644 --- a/frontend/build/webpack/css-variables-loader.js +++ b/frontend/build/webpack/css-variables-loader.js @@ -1,4 +1,3 @@ -// eslint-disable-next-line filenames/match-exported const loaderUtils = require('loader-utils'); module.exports = function cssVariablesLoader(source) { diff --git a/frontend/jsconfig.json b/frontend/jsconfig.json new file mode 100644 index 000000000..b12d0a2d4 --- /dev/null +++ b/frontend/jsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "es6", + "checkJs": false, + "baseUrl": "src", + "jsx": "react", + "module": "commonjs", + "moduleResolution": "node", + "paths": { + "*": [ + "*" + ] + } + }, + "include": [ + "./src/**/*" + ], + "exclude": [ + ] +} \ No newline at end of file diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js index 89db00f8c..7b5bc5976 100644 --- a/frontend/postcss.config.js +++ b/frontend/postcss.config.js @@ -1,6 +1,7 @@ const reload = require('require-nocache')(module); const cssVarsFiles = [ + './src/Styles/Variables/colors', './src/Styles/Variables/dimensions', './src/Styles/Variables/fonts', './src/Styles/Variables/animations', @@ -16,7 +17,6 @@ const mixinsFiles = [ module.exports = { plugins: [ - 'autoprefixer', ['postcss-mixins', { mixinsFiles }], diff --git a/frontend/src/.vscode/settings.json b/frontend/src/.vscode/settings.json new file mode 100644 index 000000000..0fb2bf460 --- /dev/null +++ b/frontend/src/.vscode/settings.json @@ -0,0 +1,4 @@ +// Place your settings in this file to overwrite default and user settings. +{ + "files.insertFinalNewline": true +} \ No newline at end of file diff --git a/frontend/src/Activity/Blocklist/Blocklist.js b/frontend/src/Activity/Blocklist/Blocklist.js new file mode 100644 index 000000000..4ab40faec --- /dev/null +++ b/frontend/src/Activity/Blocklist/Blocklist.js @@ -0,0 +1,232 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import getRemovedItems from 'Utilities/Object/getRemovedItems'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import getSelectedIds from 'Utilities/Table/getSelectedIds'; +import removeOldSelectedState from 'Utilities/Table/removeOldSelectedState'; +import selectAll from 'Utilities/Table/selectAll'; +import toggleSelected from 'Utilities/Table/toggleSelected'; +import { align, icons, kinds } from 'Helpers/Props'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import ConfirmModal from 'Components/Modal/ConfirmModal'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; +import TablePager from 'Components/Table/TablePager'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import BlocklistRowConnector from './BlocklistRowConnector'; + +class Blocklist extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + allSelected: false, + allUnselected: false, + lastToggled: null, + selectedState: {}, + isConfirmRemoveModalOpen: false, + items: props.items + }; + } + + componentDidUpdate(prevProps) { + const { + items + } = this.props; + + if (hasDifferentItems(prevProps.items, items)) { + this.setState((state) => { + return { + ...removeOldSelectedState(state, getRemovedItems(prevProps.items, items)), + items + }; + }); + + return; + } + } + + // + // Control + + getSelectedIds = () => { + return getSelectedIds(this.state.selectedState); + } + + // + // Listeners + + onSelectAllChange = ({ value }) => { + this.setState(selectAll(this.state.selectedState, value)); + } + + onSelectedChange = ({ id, value, shiftKey = false }) => { + this.setState((state) => { + return toggleSelected(state, this.props.items, id, value, shiftKey); + }); + } + + onRemoveSelectedPress = () => { + this.setState({ isConfirmRemoveModalOpen: true }); + } + + onRemoveSelectedConfirmed = () => { + this.props.onRemoveSelected(this.getSelectedIds()); + this.setState({ isConfirmRemoveModalOpen: false }); + } + + onConfirmRemoveModalClose = () => { + this.setState({ isConfirmRemoveModalOpen: false }); + } + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + items, + columns, + totalRecords, + isRemoving, + isClearingBlocklistExecuting, + onClearBlocklistPress, + ...otherProps + } = this.props; + + const { + allSelected, + allUnselected, + selectedState, + isConfirmRemoveModalOpen + } = this.state; + + const selectedIds = this.getSelectedIds(); + + return ( + + + + + + + + + + + + + + + + + { + isFetching && !isPopulated && + + } + + { + !isFetching && !!error && +
Unable to load blocklist
+ } + + { + isPopulated && !error && !items.length && +
+ No history blocklist +
+ } + + { + isPopulated && !error && !!items.length && +
+ + + { + items.map((item) => { + return ( + + ); + }) + } + +
+ + +
+ } +
+ + +
+ ); + } +} + +Blocklist.propTypes = { + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + columns: PropTypes.arrayOf(PropTypes.object).isRequired, + totalRecords: PropTypes.number, + isRemoving: PropTypes.bool.isRequired, + isClearingBlocklistExecuting: PropTypes.bool.isRequired, + onRemoveSelected: PropTypes.func.isRequired, + onClearBlocklistPress: PropTypes.func.isRequired +}; + +export default Blocklist; diff --git a/frontend/src/Activity/Blocklist/Blocklist.tsx b/frontend/src/Activity/Blocklist/Blocklist.tsx deleted file mode 100644 index 4163bc9ca..000000000 --- a/frontend/src/Activity/Blocklist/Blocklist.tsx +++ /dev/null @@ -1,329 +0,0 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import { SelectProvider } from 'App/SelectContext'; -import AppState from 'App/State/AppState'; -import * as commandNames from 'Commands/commandNames'; -import Alert from 'Components/Alert'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import FilterMenu from 'Components/Menu/FilterMenu'; -import ConfirmModal from 'Components/Modal/ConfirmModal'; -import PageContent from 'Components/Page/PageContent'; -import PageContentBody from 'Components/Page/PageContentBody'; -import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; -import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; -import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; -import Table from 'Components/Table/Table'; -import TableBody from 'Components/Table/TableBody'; -import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; -import TablePager from 'Components/Table/TablePager'; -import usePaging from 'Components/Table/usePaging'; -import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import useSelectState from 'Helpers/Hooks/useSelectState'; -import { align, icons, kinds } from 'Helpers/Props'; -import { - clearBlocklist, - fetchBlocklist, - gotoBlocklistPage, - removeBlocklistItems, - setBlocklistFilter, - setBlocklistSort, - setBlocklistTableOption, -} from 'Store/Actions/blocklistActions'; -import { executeCommand } from 'Store/Actions/commandActions'; -import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; -import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; -import { CheckInputChanged } from 'typings/inputs'; -import { SelectStateInputProps } from 'typings/props'; -import { TableOptionsChangePayload } from 'typings/Table'; -import { - registerPagePopulator, - unregisterPagePopulator, -} from 'Utilities/pagePopulator'; -import translate from 'Utilities/String/translate'; -import getSelectedIds from 'Utilities/Table/getSelectedIds'; -import BlocklistFilterModal from './BlocklistFilterModal'; -import BlocklistRow from './BlocklistRow'; - -function Blocklist() { - const requestCurrentPage = useCurrentPage(); - - const { - isFetching, - isPopulated, - error, - items, - columns, - selectedFilterKey, - filters, - sortKey, - sortDirection, - page, - pageSize, - totalPages, - totalRecords, - isRemoving, - } = useSelector((state: AppState) => state.blocklist); - - const customFilters = useSelector(createCustomFiltersSelector('blocklist')); - const isClearingBlocklistExecuting = useSelector( - createCommandExecutingSelector(commandNames.CLEAR_BLOCKLIST) - ); - const dispatch = useDispatch(); - - const [isConfirmRemoveModalOpen, setIsConfirmRemoveModalOpen] = - useState(false); - const [isConfirmClearModalOpen, setIsConfirmClearModalOpen] = useState(false); - - const [selectState, setSelectState] = useSelectState(); - const { allSelected, allUnselected, selectedState } = selectState; - - const selectedIds = useMemo(() => { - return getSelectedIds(selectedState); - }, [selectedState]); - - const wasClearingBlocklistExecuting = usePrevious( - isClearingBlocklistExecuting - ); - - const handleSelectAllChange = useCallback( - ({ value }: CheckInputChanged) => { - setSelectState({ type: value ? 'selectAll' : 'unselectAll', items }); - }, - [items, setSelectState] - ); - - const handleSelectedChange = useCallback( - ({ id, value, shiftKey = false }: SelectStateInputProps) => { - setSelectState({ - type: 'toggleSelected', - items, - id, - isSelected: value, - shiftKey, - }); - }, - [items, setSelectState] - ); - - const handleRemoveSelectedPress = useCallback(() => { - setIsConfirmRemoveModalOpen(true); - }, [setIsConfirmRemoveModalOpen]); - - const handleRemoveSelectedConfirmed = useCallback(() => { - dispatch(removeBlocklistItems({ ids: selectedIds })); - setIsConfirmRemoveModalOpen(false); - }, [selectedIds, setIsConfirmRemoveModalOpen, dispatch]); - - const handleConfirmRemoveModalClose = useCallback(() => { - setIsConfirmRemoveModalOpen(false); - }, [setIsConfirmRemoveModalOpen]); - - const handleClearBlocklistPress = useCallback(() => { - setIsConfirmClearModalOpen(true); - }, [setIsConfirmClearModalOpen]); - - const handleClearBlocklistConfirmed = useCallback(() => { - dispatch(executeCommand({ name: commandNames.CLEAR_BLOCKLIST })); - setIsConfirmClearModalOpen(false); - }, [setIsConfirmClearModalOpen, dispatch]); - - const handleConfirmClearModalClose = useCallback(() => { - setIsConfirmClearModalOpen(false); - }, [setIsConfirmClearModalOpen]); - - const { - handleFirstPagePress, - handlePreviousPagePress, - handleNextPagePress, - handleLastPagePress, - handlePageSelect, - } = usePaging({ - page, - totalPages, - gotoPage: gotoBlocklistPage, - }); - - const handleFilterSelect = useCallback( - (selectedFilterKey: string) => { - dispatch(setBlocklistFilter({ selectedFilterKey })); - }, - [dispatch] - ); - - const handleSortPress = useCallback( - (sortKey: string) => { - dispatch(setBlocklistSort({ sortKey })); - }, - [dispatch] - ); - - const handleTableOptionChange = useCallback( - (payload: TableOptionsChangePayload) => { - dispatch(setBlocklistTableOption(payload)); - - if (payload.pageSize) { - dispatch(gotoBlocklistPage({ page: 1 })); - } - }, - [dispatch] - ); - - useEffect(() => { - if (requestCurrentPage) { - dispatch(fetchBlocklist()); - } else { - dispatch(gotoBlocklistPage({ page: 1 })); - } - - return () => { - dispatch(clearBlocklist()); - }; - }, [requestCurrentPage, dispatch]); - - useEffect(() => { - const repopulate = () => { - dispatch(fetchBlocklist()); - }; - - registerPagePopulator(repopulate); - - return () => { - unregisterPagePopulator(repopulate); - }; - }, [dispatch]); - - useEffect(() => { - if (wasClearingBlocklistExecuting && !isClearingBlocklistExecuting) { - dispatch(gotoBlocklistPage({ page: 1 })); - } - }, [isClearingBlocklistExecuting, wasClearingBlocklistExecuting, dispatch]); - - return ( - - - - - - - - - - - - - - - - - - - - {isFetching && !isPopulated ? : null} - - {!isFetching && !!error ? ( - {translate('BlocklistLoadError')} - ) : null} - - {isPopulated && !error && !items.length ? ( - - {selectedFilterKey === 'all' - ? translate('NoBlocklistItems') - : translate('BlocklistFilterHasNoItems')} - - ) : null} - - {isPopulated && !error && !!items.length ? ( -
- - - {items.map((item) => { - return ( - - ); - })} - -
- -
- ) : null} -
- - - - -
-
- ); -} - -export default Blocklist; diff --git a/frontend/src/Activity/Blocklist/BlocklistConnector.js b/frontend/src/Activity/Blocklist/BlocklistConnector.js new file mode 100644 index 000000000..4ae4059e5 --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistConnector.js @@ -0,0 +1,160 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator'; +import withCurrentPage from 'Components/withCurrentPage'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import * as blocklistActions from 'Store/Actions/blocklistActions'; +import { executeCommand } from 'Store/Actions/commandActions'; +import * as commandNames from 'Commands/commandNames'; +import Blocklist from './Blocklist'; + +function createMapStateToProps() { + return createSelector( + (state) => state.blocklist, + createCommandExecutingSelector(commandNames.CLEAR_BLOCKLIST), + (blocklist, isClearingBlocklistExecuting) => { + return { + isClearingBlocklistExecuting, + ...blocklist + }; + } + ); +} + +const mapDispatchToProps = { + ...blocklistActions, + executeCommand +}; + +class BlocklistConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + const { + useCurrentPage, + fetchBlocklist, + gotoBlocklistFirstPage + } = this.props; + + registerPagePopulator(this.repopulate); + + if (useCurrentPage) { + fetchBlocklist(); + } else { + gotoBlocklistFirstPage(); + } + } + + componentDidUpdate(prevProps) { + if (prevProps.isClearingBlocklistExecuting && !this.props.isClearingBlocklistExecuting) { + this.props.gotoBlocklistFirstPage(); + } + } + + componentWillUnmount() { + this.props.clearBlocklist(); + unregisterPagePopulator(this.repopulate); + } + + // + // Control + + repopulate = () => { + this.props.fetchBlocklist(); + } + // + // Listeners + + onFirstPagePress = () => { + this.props.gotoBlocklistFirstPage(); + } + + onPreviousPagePress = () => { + this.props.gotoBlocklistPreviousPage(); + } + + onNextPagePress = () => { + this.props.gotoBlocklistNextPage(); + } + + onLastPagePress = () => { + this.props.gotoBlocklistLastPage(); + } + + onPageSelect = (page) => { + this.props.gotoBlocklistPage({ page }); + } + + onRemoveSelected = (ids) => { + this.props.removeBlocklistItems({ ids }); + } + + onSortPress = (sortKey) => { + this.props.setBlocklistSort({ sortKey }); + } + + onTableOptionChange = (payload) => { + this.props.setBlocklistTableOption(payload); + + if (payload.pageSize) { + this.props.gotoBlocklistFirstPage(); + } + } + + onClearBlocklistPress = () => { + this.props.executeCommand({ name: commandNames.CLEAR_BLOCKLIST }); + } + + onTableOptionChange = (payload) => { + this.props.setBlocklistTableOption(payload); + + if (payload.pageSize) { + this.props.gotoBlocklistFirstPage(); + } + } + + // + // Render + + render() { + return ( + + ); + } +} + +BlocklistConnector.propTypes = { + useCurrentPage: PropTypes.bool.isRequired, + isClearingBlocklistExecuting: PropTypes.bool.isRequired, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + fetchBlocklist: PropTypes.func.isRequired, + gotoBlocklistFirstPage: PropTypes.func.isRequired, + gotoBlocklistPreviousPage: PropTypes.func.isRequired, + gotoBlocklistNextPage: PropTypes.func.isRequired, + gotoBlocklistLastPage: PropTypes.func.isRequired, + gotoBlocklistPage: PropTypes.func.isRequired, + removeBlocklistItems: PropTypes.func.isRequired, + setBlocklistSort: PropTypes.func.isRequired, + setBlocklistTableOption: PropTypes.func.isRequired, + clearBlocklist: PropTypes.func.isRequired, + executeCommand: PropTypes.func.isRequired +}; + +export default withCurrentPage( + connect(createMapStateToProps, mapDispatchToProps)(BlocklistConnector) +); diff --git a/frontend/src/Activity/Blocklist/BlocklistDetailsModal.js b/frontend/src/Activity/Blocklist/BlocklistDetailsModal.js new file mode 100644 index 000000000..5317f2fdf --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistDetailsModal.js @@ -0,0 +1,89 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Button from 'Components/Link/Button'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import Modal from 'Components/Modal/Modal'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; + +class BlocklistDetailsModal extends Component { + + // + // Render + + render() { + const { + isOpen, + sourceTitle, + protocol, + indexer, + message, + onModalClose + } = this.props; + + return ( + + + + Details + + + + + + + + + { + !!message && + + } + + { + !!message && + + } + + + + + + + + + ); + } +} + +BlocklistDetailsModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + sourceTitle: PropTypes.string.isRequired, + protocol: PropTypes.string.isRequired, + indexer: PropTypes.string, + message: PropTypes.string, + onModalClose: PropTypes.func.isRequired +}; + +export default BlocklistDetailsModal; diff --git a/frontend/src/Activity/Blocklist/BlocklistDetailsModal.tsx b/frontend/src/Activity/Blocklist/BlocklistDetailsModal.tsx deleted file mode 100644 index ec026ae92..000000000 --- a/frontend/src/Activity/Blocklist/BlocklistDetailsModal.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import React from 'react'; -import DescriptionList from 'Components/DescriptionList/DescriptionList'; -import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; -import Button from 'Components/Link/Button'; -import Modal from 'Components/Modal/Modal'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import DownloadProtocol from 'DownloadClient/DownloadProtocol'; -import translate from 'Utilities/String/translate'; - -interface BlocklistDetailsModalProps { - isOpen: boolean; - sourceTitle: string; - protocol: DownloadProtocol; - indexer?: string; - message?: string; - onModalClose: () => void; -} - -function BlocklistDetailsModal(props: BlocklistDetailsModalProps) { - const { isOpen, sourceTitle, protocol, indexer, message, onModalClose } = - props; - - return ( - - - Details - - - - - - - - {message ? ( - - ) : null} - - {message ? ( - - ) : null} - - - - - - - - - ); -} - -export default BlocklistDetailsModal; diff --git a/frontend/src/Activity/Blocklist/BlocklistFilterModal.tsx b/frontend/src/Activity/Blocklist/BlocklistFilterModal.tsx deleted file mode 100644 index ea80458f1..000000000 --- a/frontend/src/Activity/Blocklist/BlocklistFilterModal.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import React, { useCallback } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import FilterModal from 'Components/Filter/FilterModal'; -import { setBlocklistFilter } from 'Store/Actions/blocklistActions'; - -function createBlocklistSelector() { - return createSelector( - (state: AppState) => state.blocklist.items, - (blocklistItems) => { - return blocklistItems; - } - ); -} - -function createFilterBuilderPropsSelector() { - return createSelector( - (state: AppState) => state.blocklist.filterBuilderProps, - (filterBuilderProps) => { - return filterBuilderProps; - } - ); -} - -interface BlocklistFilterModalProps { - isOpen: boolean; -} - -export default function BlocklistFilterModal(props: BlocklistFilterModalProps) { - const sectionItems = useSelector(createBlocklistSelector()); - const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); - const customFilterType = 'blocklist'; - - const dispatch = useDispatch(); - - const dispatchSetFilter = useCallback( - (payload: unknown) => { - dispatch(setBlocklistFilter(payload)); - }, - [dispatch] - ); - - return ( - - ); -} diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.css b/frontend/src/Activity/Blocklist/BlocklistRow.css index aa008a6ce..c7d31a886 100644 --- a/frontend/src/Activity/Blocklist/BlocklistRow.css +++ b/frontend/src/Activity/Blocklist/BlocklistRow.css @@ -1,4 +1,4 @@ -.languages, +.language, .quality { composes: cell from '~Components/Table/Cells/TableRowCell.css'; diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.css.d.ts b/frontend/src/Activity/Blocklist/BlocklistRow.css.d.ts deleted file mode 100644 index cc16b7e9e..000000000 --- a/frontend/src/Activity/Blocklist/BlocklistRow.css.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'actions': string; - 'indexer': string; - 'languages': string; - 'quality': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.js b/frontend/src/Activity/Blocklist/BlocklistRow.js new file mode 100644 index 000000000..3563e7230 --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistRow.js @@ -0,0 +1,198 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { icons, kinds } from 'Helpers/Props'; +import IconButton from 'Components/Link/IconButton'; +import TableSelectCell from 'Components/Table/Cells/TableSelectCell'; +import RelativeDateCellConnector from 'Components/Table/Cells/RelativeDateCellConnector'; +import TableRow from 'Components/Table/TableRow'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import EpisodeLanguage from 'Episode/EpisodeLanguage'; +import EpisodeQuality from 'Episode/EpisodeQuality'; +import SeriesTitleLink from 'Series/SeriesTitleLink'; +import BlocklistDetailsModal from './BlocklistDetailsModal'; +import styles from './BlocklistRow.css'; + +class BlocklistRow extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isDetailsModalOpen: false + }; + } + + // + // Listeners + + onDetailsPress = () => { + this.setState({ isDetailsModalOpen: true }); + } + + onDetailsModalClose = () => { + this.setState({ isDetailsModalOpen: false }); + } + + // + // Render + + render() { + const { + id, + series, + sourceTitle, + language, + quality, + date, + protocol, + indexer, + message, + isSelected, + columns, + onSelectedChange, + onRemovePress + } = this.props; + + return ( + + + + { + columns.map((column) => { + const { + name, + isVisible + } = column; + + if (!isVisible) { + return null; + } + + if (name === 'series.sortTitle') { + return ( + + + + ); + } + + if (name === 'sourceTitle') { + return ( + + {sourceTitle} + + ); + } + + if (name === 'language') { + return ( + + + + ); + } + + if (name === 'quality') { + return ( + + + + ); + } + + if (name === 'date') { + return ( + + ); + } + + if (name === 'indexer') { + return ( + + {indexer} + + ); + } + + if (name === 'actions') { + return ( + + + + + + ); + } + + return null; + }) + } + + + + ); + } + +} + +BlocklistRow.propTypes = { + id: PropTypes.number.isRequired, + series: PropTypes.object.isRequired, + sourceTitle: PropTypes.string.isRequired, + language: PropTypes.object.isRequired, + quality: PropTypes.object.isRequired, + date: PropTypes.string.isRequired, + protocol: PropTypes.string.isRequired, + indexer: PropTypes.string, + message: PropTypes.string, + isSelected: PropTypes.bool.isRequired, + columns: PropTypes.arrayOf(PropTypes.object).isRequired, + onSelectedChange: PropTypes.func.isRequired, + onRemovePress: PropTypes.func.isRequired +}; + +export default BlocklistRow; diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.tsx b/frontend/src/Activity/Blocklist/BlocklistRow.tsx deleted file mode 100644 index c7410320d..000000000 --- a/frontend/src/Activity/Blocklist/BlocklistRow.tsx +++ /dev/null @@ -1,163 +0,0 @@ -import React, { useCallback, useState } from 'react'; -import { useDispatch } from 'react-redux'; -import IconButton from 'Components/Link/IconButton'; -import RelativeDateCell from 'Components/Table/Cells/RelativeDateCell'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import TableSelectCell from 'Components/Table/Cells/TableSelectCell'; -import Column from 'Components/Table/Column'; -import TableRow from 'Components/Table/TableRow'; -import EpisodeFormats from 'Episode/EpisodeFormats'; -import EpisodeLanguages from 'Episode/EpisodeLanguages'; -import EpisodeQuality from 'Episode/EpisodeQuality'; -import { icons, kinds } from 'Helpers/Props'; -import SeriesTitleLink from 'Series/SeriesTitleLink'; -import useSeries from 'Series/useSeries'; -import { removeBlocklistItem } from 'Store/Actions/blocklistActions'; -import Blocklist from 'typings/Blocklist'; -import { SelectStateInputProps } from 'typings/props'; -import translate from 'Utilities/String/translate'; -import BlocklistDetailsModal from './BlocklistDetailsModal'; -import styles from './BlocklistRow.css'; - -interface BlocklistRowProps extends Blocklist { - isSelected: boolean; - columns: Column[]; - onSelectedChange: (options: SelectStateInputProps) => void; -} - -function BlocklistRow(props: BlocklistRowProps) { - const { - id, - seriesId, - sourceTitle, - languages, - quality, - customFormats, - date, - protocol, - indexer, - message, - isSelected, - columns, - onSelectedChange, - } = props; - - const series = useSeries(seriesId); - const dispatch = useDispatch(); - const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); - - const handleDetailsPress = useCallback(() => { - setIsDetailsModalOpen(true); - }, [setIsDetailsModalOpen]); - - const handleDetailsModalClose = useCallback(() => { - setIsDetailsModalOpen(false); - }, [setIsDetailsModalOpen]); - - const handleRemovePress = useCallback(() => { - dispatch(removeBlocklistItem({ id })); - }, [id, dispatch]); - - if (!series) { - return null; - } - - return ( - - - - {columns.map((column) => { - const { name, isVisible } = column; - - if (!isVisible) { - return null; - } - - if (name === 'series.sortTitle') { - return ( - - - - ); - } - - if (name === 'sourceTitle') { - return {sourceTitle}; - } - - if (name === 'languages') { - return ( - - - - ); - } - - if (name === 'quality') { - return ( - - - - ); - } - - if (name === 'customFormats') { - return ( - - - - ); - } - - if (name === 'date') { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore ts(2739) - return ; - } - - if (name === 'indexer') { - return ( - - {indexer} - - ); - } - - if (name === 'actions') { - return ( - - - - - - ); - } - - return null; - })} - - - - ); -} - -export default BlocklistRow; diff --git a/frontend/src/Activity/Blocklist/BlocklistRowConnector.js b/frontend/src/Activity/Blocklist/BlocklistRowConnector.js new file mode 100644 index 000000000..f0b93cd25 --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistRowConnector.js @@ -0,0 +1,26 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { removeBlocklistItem } from 'Store/Actions/blocklistActions'; +import createSeriesSelector from 'Store/Selectors/createSeriesSelector'; +import BlocklistRow from './BlocklistRow'; + +function createMapStateToProps() { + return createSelector( + createSeriesSelector(), + (series) => { + return { + series + }; + } + ); +} + +function createMapDispatchToProps(dispatch, props) { + return { + onRemovePress() { + dispatch(removeBlocklistItem({ id: props.id })); + } + }; +} + +export default connect(createMapStateToProps, createMapDispatchToProps)(BlocklistRow); diff --git a/frontend/src/Activity/History/Details/HistoryDetails.css.d.ts b/frontend/src/Activity/History/Details/HistoryDetails.css.d.ts deleted file mode 100644 index ff7055b0f..000000000 --- a/frontend/src/Activity/History/Details/HistoryDetails.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'description': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/History/Details/HistoryDetails.js b/frontend/src/Activity/History/Details/HistoryDetails.js new file mode 100644 index 000000000..a1be61bb1 --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetails.js @@ -0,0 +1,320 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import formatAge from 'Utilities/Number/formatAge'; +import formatDateTime from 'Utilities/Date/formatDateTime'; +import formatPreferredWordScore from 'Utilities/Number/formatPreferredWordScore'; +import Link from 'Components/Link/Link'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import DescriptionListItemTitle from 'Components/DescriptionList/DescriptionListItemTitle'; +import DescriptionListItemDescription from 'Components/DescriptionList/DescriptionListItemDescription'; +import styles from './HistoryDetails.css'; + +function HistoryDetails(props) { + const { + eventType, + sourceTitle, + data, + shortDateFormat, + timeFormat + } = props; + + if (eventType === 'grabbed') { + const { + indexer, + releaseGroup, + preferredWordScore, + nzbInfoUrl, + downloadClient, + downloadId, + age, + ageHours, + ageMinutes, + publishedDate + } = data; + + return ( + + + + { + indexer ? + : + null + } + + { + releaseGroup ? + : + null + } + + { + preferredWordScore && preferredWordScore !== '0' ? + : + null + } + + { + nzbInfoUrl ? + + + Info URL + + + + {nzbInfoUrl} + + : + null + } + + { + downloadClient ? + : + null + } + + { + downloadId ? + : + null + } + + { + age || ageHours || ageMinutes ? + : + null + } + + { + publishedDate ? + : + null + } + + ); + } + + if (eventType === 'downloadFailed') { + const { + message + } = data; + + return ( + + + + { + message ? + : + null + } + + ); + } + + if (eventType === 'downloadFolderImported') { + const { + preferredWordScore, + droppedPath, + importedPath + } = data; + + return ( + + + + { + droppedPath ? + : + null + } + + { + importedPath ? + : + null + } + + { + preferredWordScore && preferredWordScore !== '0' ? + : + null + } + + ); + } + + if (eventType === 'episodeFileDeleted') { + const { + reason, + preferredWordScore + } = data; + + let reasonMessage = ''; + + switch (reason) { + case 'Manual': + reasonMessage = 'File was deleted by via UI'; + break; + case 'MissingFromDisk': + reasonMessage = 'Sonarr was unable to find the file on disk so it was removed'; + break; + case 'Upgrade': + reasonMessage = 'File was deleted to import an upgrade'; + break; + default: + reasonMessage = ''; + } + + return ( + + + + + + { + preferredWordScore && preferredWordScore !== '0' ? + : + null + } + + ); + } + + if (eventType === 'episodeFileRenamed') { + const { + sourcePath, + sourceRelativePath, + path, + relativePath + } = data; + + return ( + + + + + + + + + + ); + } + + if (eventType === 'downloadIgnored') { + const { + message + } = data; + + return ( + + + + { + message ? + : + null + } + + ); + } + + return ( + + + + ); +} + +HistoryDetails.propTypes = { + eventType: PropTypes.string.isRequired, + sourceTitle: PropTypes.string.isRequired, + data: PropTypes.object.isRequired, + shortDateFormat: PropTypes.string.isRequired, + timeFormat: PropTypes.string.isRequired +}; + +export default HistoryDetails; diff --git a/frontend/src/Activity/History/Details/HistoryDetails.tsx b/frontend/src/Activity/History/Details/HistoryDetails.tsx deleted file mode 100644 index f460ec433..000000000 --- a/frontend/src/Activity/History/Details/HistoryDetails.tsx +++ /dev/null @@ -1,321 +0,0 @@ -import React from 'react'; -import { useSelector } from 'react-redux'; -import DescriptionList from 'Components/DescriptionList/DescriptionList'; -import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; -import DescriptionListItemDescription from 'Components/DescriptionList/DescriptionListItemDescription'; -import DescriptionListItemTitle from 'Components/DescriptionList/DescriptionListItemTitle'; -import Link from 'Components/Link/Link'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import { - DownloadFailedHistory, - DownloadFolderImportedHistory, - DownloadIgnoredHistory, - EpisodeFileDeletedHistory, - EpisodeFileRenamedHistory, - GrabbedHistoryData, - HistoryData, - HistoryEventType, -} from 'typings/History'; -import formatDateTime from 'Utilities/Date/formatDateTime'; -import formatAge from 'Utilities/Number/formatAge'; -import formatCustomFormatScore from 'Utilities/Number/formatCustomFormatScore'; -import translate from 'Utilities/String/translate'; -import styles from './HistoryDetails.css'; - -interface HistoryDetailsProps { - eventType: HistoryEventType; - sourceTitle: string; - data: HistoryData; - downloadId?: string; -} - -function HistoryDetails(props: HistoryDetailsProps) { - const { eventType, sourceTitle, data, downloadId } = props; - - const { shortDateFormat, timeFormat } = useSelector( - createUISettingsSelector() - ); - - if (eventType === 'grabbed') { - const { - indexer, - releaseGroup, - seriesMatchType, - releaseSource, - customFormatScore, - nzbInfoUrl, - downloadClient, - downloadClientName, - age, - ageHours, - ageMinutes, - publishedDate, - } = data as GrabbedHistoryData; - - const downloadClientNameInfo = downloadClientName ?? downloadClient; - - let releaseSourceMessage = ''; - - switch (releaseSource) { - case 'Unknown': - releaseSourceMessage = translate('Unknown'); - break; - case 'Rss': - releaseSourceMessage = translate('Rss'); - break; - case 'Search': - releaseSourceMessage = translate('Search'); - break; - case 'UserInvokedSearch': - releaseSourceMessage = translate('UserInvokedSearch'); - break; - case 'InteractiveSearch': - releaseSourceMessage = translate('InteractiveSearch'); - break; - case 'ReleasePush': - releaseSourceMessage = translate('ReleasePush'); - break; - default: - releaseSourceMessage = ''; - } - - return ( - - - - {indexer ? ( - - ) : null} - - {releaseGroup ? ( - - ) : null} - - {customFormatScore && customFormatScore !== '0' ? ( - - ) : null} - - {seriesMatchType ? ( - - ) : null} - - {releaseSource ? ( - - ) : null} - - {nzbInfoUrl ? ( - - - {translate('InfoUrl')} - - - - {nzbInfoUrl} - - - ) : null} - - {downloadClientNameInfo ? ( - - ) : null} - - {downloadId ? ( - - ) : null} - - {age || ageHours || ageMinutes ? ( - - ) : null} - - {publishedDate ? ( - - ) : null} - - ); - } - - if (eventType === 'downloadFailed') { - const { message } = data as DownloadFailedHistory; - - return ( - - - - {downloadId ? ( - - ) : null} - - {message ? ( - - ) : null} - - ); - } - - if (eventType === 'downloadFolderImported') { - const { customFormatScore, droppedPath, importedPath } = - data as DownloadFolderImportedHistory; - - return ( - - - - {droppedPath ? ( - - ) : null} - - {importedPath ? ( - - ) : null} - - {customFormatScore && customFormatScore !== '0' ? ( - - ) : null} - - ); - } - - if (eventType === 'episodeFileDeleted') { - const { reason, customFormatScore } = data as EpisodeFileDeletedHistory; - - let reasonMessage = ''; - - switch (reason) { - case 'Manual': - reasonMessage = translate('DeletedReasonManual'); - break; - case 'MissingFromDisk': - reasonMessage = translate('DeletedReasonEpisodeMissingFromDisk'); - break; - case 'Upgrade': - reasonMessage = translate('DeletedReasonUpgrade'); - break; - default: - reasonMessage = ''; - } - - return ( - - - - - - {customFormatScore && customFormatScore !== '0' ? ( - - ) : null} - - ); - } - - if (eventType === 'episodeFileRenamed') { - const { sourcePath, sourceRelativePath, path, relativePath } = - data as EpisodeFileRenamedHistory; - - return ( - - - - - - - - - - ); - } - - if (eventType === 'downloadIgnored') { - const { message } = data as DownloadIgnoredHistory; - - return ( - - - - {downloadId ? ( - - ) : null} - - {message ? ( - - ) : null} - - ); - } - - return ( - - - - ); -} - -export default HistoryDetails; diff --git a/frontend/src/Activity/History/Details/HistoryDetailsConnector.js b/frontend/src/Activity/History/Details/HistoryDetailsConnector.js new file mode 100644 index 000000000..0848c7905 --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetailsConnector.js @@ -0,0 +1,19 @@ +import _ from 'lodash'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import HistoryDetails from './HistoryDetails'; + +function createMapStateToProps() { + return createSelector( + createUISettingsSelector(), + (uiSettings) => { + return _.pick(uiSettings, [ + 'shortDateFormat', + 'timeFormat' + ]); + } + ); +} + +export default connect(createMapStateToProps)(HistoryDetails); diff --git a/frontend/src/Activity/History/Details/HistoryDetailsModal.css.d.ts b/frontend/src/Activity/History/Details/HistoryDetailsModal.css.d.ts deleted file mode 100644 index a8cc499e2..000000000 --- a/frontend/src/Activity/History/Details/HistoryDetailsModal.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'markAsFailedButton': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/History/Details/HistoryDetailsModal.js b/frontend/src/Activity/History/Details/HistoryDetailsModal.js new file mode 100644 index 000000000..6b660e10b --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetailsModal.js @@ -0,0 +1,106 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { kinds } from 'Helpers/Props'; +import Button from 'Components/Link/Button'; +import SpinnerButton from 'Components/Link/SpinnerButton'; +import Modal from 'Components/Modal/Modal'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; +import HistoryDetails from './HistoryDetails'; +import styles from './HistoryDetailsModal.css'; + +function getHeaderTitle(eventType) { + switch (eventType) { + case 'grabbed': + return 'Grabbed'; + case 'downloadFailed': + return 'Download Failed'; + case 'downloadFolderImported': + return 'Episode Imported'; + case 'episodeFileDeleted': + return 'Episode File Deleted'; + case 'episodeFileRenamed': + return 'Episode File Renamed'; + case 'downloadIgnored': + return 'Download Ignored'; + default: + return 'Unknown'; + } +} + +function HistoryDetailsModal(props) { + const { + isOpen, + eventType, + sourceTitle, + data, + isMarkingAsFailed, + shortDateFormat, + timeFormat, + onMarkAsFailedPress, + onModalClose + } = props; + + return ( + + + + {getHeaderTitle(eventType)} + + + + + + + + { + eventType === 'grabbed' && + + Mark as Failed + + } + + + + + + ); +} + +HistoryDetailsModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + eventType: PropTypes.string.isRequired, + sourceTitle: PropTypes.string.isRequired, + data: PropTypes.object.isRequired, + isMarkingAsFailed: PropTypes.bool.isRequired, + shortDateFormat: PropTypes.string.isRequired, + timeFormat: PropTypes.string.isRequired, + onMarkAsFailedPress: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +HistoryDetailsModal.defaultProps = { + isMarkingAsFailed: false +}; + +export default HistoryDetailsModal; diff --git a/frontend/src/Activity/History/Details/HistoryDetailsModal.tsx b/frontend/src/Activity/History/Details/HistoryDetailsModal.tsx deleted file mode 100644 index 8134a9736..000000000 --- a/frontend/src/Activity/History/Details/HistoryDetailsModal.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import React from 'react'; -import Button from 'Components/Link/Button'; -import SpinnerButton from 'Components/Link/SpinnerButton'; -import Modal from 'Components/Modal/Modal'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import { kinds } from 'Helpers/Props'; -import { HistoryData, HistoryEventType } from 'typings/History'; -import translate from 'Utilities/String/translate'; -import HistoryDetails from './HistoryDetails'; -import styles from './HistoryDetailsModal.css'; - -function getHeaderTitle(eventType: HistoryEventType) { - switch (eventType) { - case 'grabbed': - return translate('Grabbed'); - case 'downloadFailed': - return translate('DownloadFailed'); - case 'downloadFolderImported': - return translate('EpisodeImported'); - case 'episodeFileDeleted': - return translate('EpisodeFileDeleted'); - case 'episodeFileRenamed': - return translate('EpisodeFileRenamed'); - case 'downloadIgnored': - return translate('DownloadIgnored'); - default: - return translate('Unknown'); - } -} - -interface HistoryDetailsModalProps { - isOpen: boolean; - eventType: HistoryEventType; - sourceTitle: string; - data: HistoryData; - downloadId?: string; - isMarkingAsFailed: boolean; - onMarkAsFailedPress: () => void; - onModalClose: () => void; -} - -function HistoryDetailsModal(props: HistoryDetailsModalProps) { - const { - isOpen, - eventType, - sourceTitle, - data, - downloadId, - isMarkingAsFailed = false, - onMarkAsFailedPress, - onModalClose, - } = props; - - return ( - - - {getHeaderTitle(eventType)} - - - - - - - {eventType === 'grabbed' && ( - - {translate('MarkAsFailed')} - - )} - - - - - - ); -} - -export default HistoryDetailsModal; diff --git a/frontend/src/Activity/History/History.js b/frontend/src/Activity/History/History.js new file mode 100644 index 000000000..34ccb7008 --- /dev/null +++ b/frontend/src/Activity/History/History.js @@ -0,0 +1,172 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { align, icons } from 'Helpers/Props'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; +import TablePager from 'Components/Table/TablePager'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import FilterMenu from 'Components/Menu/FilterMenu'; +import HistoryRowConnector from './HistoryRowConnector'; + +class History extends Component { + + // + // Lifecycle + + shouldComponentUpdate(nextProps) { + // Don't update when fetching has completed if items have changed, + // before episodes start fetching or when episodes start fetching. + + if ( + ( + this.props.isFetching && + nextProps.isPopulated && + hasDifferentItems(this.props.items, nextProps.items) + ) || + (!this.props.isEpisodesFetching && nextProps.isEpisodesFetching) + ) { + return false; + } + + return true; + } + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + items, + columns, + selectedFilterKey, + filters, + totalRecords, + isEpisodesFetching, + isEpisodesPopulated, + episodesError, + onFilterSelect, + onFirstPagePress, + ...otherProps + } = this.props; + + const isFetchingAny = isFetching || isEpisodesFetching; + const isAllPopulated = isPopulated && (isEpisodesPopulated || !items.length); + const hasError = error || episodesError; + + return ( + + + + + + + + + + + + + + + + + { + isFetchingAny && !isAllPopulated && + + } + + { + !isFetchingAny && hasError && +
Unable to load history
+ } + + { + // If history isPopulated and it's empty show no history found and don't + // wait for the episodes to populate because they are never coming. + + isPopulated && !hasError && !items.length && +
+ No history found +
+ } + + { + isAllPopulated && !hasError && !!items.length && +
+ + + { + items.map((item) => { + return ( + + ); + }) + } + +
+ + +
+ } +
+
+ ); + } +} + +History.propTypes = { + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + columns: PropTypes.arrayOf(PropTypes.object).isRequired, + selectedFilterKey: PropTypes.string.isRequired, + filters: PropTypes.arrayOf(PropTypes.object).isRequired, + totalRecords: PropTypes.number, + isEpisodesFetching: PropTypes.bool.isRequired, + isEpisodesPopulated: PropTypes.bool.isRequired, + episodesError: PropTypes.object, + onFilterSelect: PropTypes.func.isRequired, + onFirstPagePress: PropTypes.func.isRequired +}; + +export default History; diff --git a/frontend/src/Activity/History/History.tsx b/frontend/src/Activity/History/History.tsx deleted file mode 100644 index 9f00a1ab3..000000000 --- a/frontend/src/Activity/History/History.tsx +++ /dev/null @@ -1,231 +0,0 @@ -import React, { useCallback, useEffect } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import Alert from 'Components/Alert'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import FilterMenu from 'Components/Menu/FilterMenu'; -import PageContent from 'Components/Page/PageContent'; -import PageContentBody from 'Components/Page/PageContentBody'; -import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; -import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; -import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; -import Table from 'Components/Table/Table'; -import TableBody from 'Components/Table/TableBody'; -import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; -import TablePager from 'Components/Table/TablePager'; -import usePaging from 'Components/Table/usePaging'; -import createEpisodesFetchingSelector from 'Episode/createEpisodesFetchingSelector'; -import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; -import { align, icons, kinds } from 'Helpers/Props'; -import { clearEpisodes, fetchEpisodes } from 'Store/Actions/episodeActions'; -import { clearEpisodeFiles } from 'Store/Actions/episodeFileActions'; -import { - clearHistory, - fetchHistory, - gotoHistoryPage, - setHistoryFilter, - setHistorySort, - setHistoryTableOption, -} from 'Store/Actions/historyActions'; -import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; -import HistoryItem from 'typings/History'; -import { TableOptionsChangePayload } from 'typings/Table'; -import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; -import { - registerPagePopulator, - unregisterPagePopulator, -} from 'Utilities/pagePopulator'; -import translate from 'Utilities/String/translate'; -import HistoryFilterModal from './HistoryFilterModal'; -import HistoryRow from './HistoryRow'; - -function History() { - const requestCurrentPage = useCurrentPage(); - - const { - isFetching, - isPopulated, - error, - items, - columns, - selectedFilterKey, - filters, - sortKey, - sortDirection, - page, - pageSize, - totalPages, - totalRecords, - } = useSelector((state: AppState) => state.history); - - const { isEpisodesFetching, isEpisodesPopulated, episodesError } = - useSelector(createEpisodesFetchingSelector()); - const customFilters = useSelector(createCustomFiltersSelector('history')); - const dispatch = useDispatch(); - - const isFetchingAny = isFetching || isEpisodesFetching; - const isAllPopulated = isPopulated && (isEpisodesPopulated || !items.length); - const hasError = error || episodesError; - - const { - handleFirstPagePress, - handlePreviousPagePress, - handleNextPagePress, - handleLastPagePress, - handlePageSelect, - } = usePaging({ - page, - totalPages, - gotoPage: gotoHistoryPage, - }); - - const handleFilterSelect = useCallback( - (selectedFilterKey: string) => { - dispatch(setHistoryFilter({ selectedFilterKey })); - }, - [dispatch] - ); - - const handleSortPress = useCallback( - (sortKey: string) => { - dispatch(setHistorySort({ sortKey })); - }, - [dispatch] - ); - - const handleTableOptionChange = useCallback( - (payload: TableOptionsChangePayload) => { - dispatch(setHistoryTableOption(payload)); - - if (payload.pageSize) { - dispatch(gotoHistoryPage({ page: 1 })); - } - }, - [dispatch] - ); - - useEffect(() => { - if (requestCurrentPage) { - dispatch(fetchHistory()); - } else { - dispatch(gotoHistoryPage({ page: 1 })); - } - - return () => { - dispatch(clearHistory()); - dispatch(clearEpisodes()); - dispatch(clearEpisodeFiles()); - }; - }, [requestCurrentPage, dispatch]); - - useEffect(() => { - const episodeIds = selectUniqueIds(items, 'episodeId'); - - if (episodeIds.length) { - dispatch(fetchEpisodes({ episodeIds })); - } else { - dispatch(clearEpisodes()); - } - }, [items, dispatch]); - - useEffect(() => { - const repopulate = () => { - dispatch(fetchHistory()); - }; - - registerPagePopulator(repopulate); - - return () => { - unregisterPagePopulator(repopulate); - }; - }, [dispatch]); - - return ( - - - - - - - - - - - - - - - - - {isFetchingAny && !isAllPopulated ? : null} - - {!isFetchingAny && hasError ? ( - {translate('HistoryLoadError')} - ) : null} - - { - // If history isPopulated and it's empty show no history found and don't - // wait for the episodes to populate because they are never coming. - - isPopulated && !hasError && !items.length ? ( - {translate('NoHistoryFound')} - ) : null - } - - {isAllPopulated && !hasError && items.length ? ( -
- - - {items.map((item) => { - return ( - - ); - })} - -
- - -
- ) : null} -
-
- ); -} - -export default History; diff --git a/frontend/src/Activity/History/HistoryConnector.js b/frontend/src/Activity/History/HistoryConnector.js new file mode 100644 index 000000000..3bf224871 --- /dev/null +++ b/frontend/src/Activity/History/HistoryConnector.js @@ -0,0 +1,162 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; +import withCurrentPage from 'Components/withCurrentPage'; +import * as historyActions from 'Store/Actions/historyActions'; +import { fetchEpisodes, clearEpisodes } from 'Store/Actions/episodeActions'; +import { clearEpisodeFiles } from 'Store/Actions/episodeFileActions'; +import History from './History'; + +function createMapStateToProps() { + return createSelector( + (state) => state.history, + (state) => state.episodes, + (history, episodes) => { + return { + isEpisodesFetching: episodes.isFetching, + isEpisodesPopulated: episodes.isPopulated, + episodesError: episodes.error, + ...history + }; + } + ); +} + +const mapDispatchToProps = { + ...historyActions, + fetchEpisodes, + clearEpisodes, + clearEpisodeFiles +}; + +class HistoryConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + const { + useCurrentPage, + fetchHistory, + gotoHistoryFirstPage + } = this.props; + + registerPagePopulator(this.repopulate); + + if (useCurrentPage) { + fetchHistory(); + } else { + gotoHistoryFirstPage(); + } + } + + componentDidUpdate(prevProps) { + if (hasDifferentItems(prevProps.items, this.props.items)) { + const episodeIds = selectUniqueIds(this.props.items, 'episodeId'); + + if (episodeIds.length) { + this.props.fetchEpisodes({ episodeIds }); + } else { + this.props.clearEpisodes(); + } + } + } + + componentWillUnmount() { + unregisterPagePopulator(this.repopulate); + this.props.clearHistory(); + this.props.clearEpisodes(); + this.props.clearEpisodeFiles(); + } + + // + // Control + + repopulate = () => { + this.props.fetchHistory(); + } + + // + // Listeners + + onFirstPagePress = () => { + this.props.gotoHistoryFirstPage(); + } + + onPreviousPagePress = () => { + this.props.gotoHistoryPreviousPage(); + } + + onNextPagePress = () => { + this.props.gotoHistoryNextPage(); + } + + onLastPagePress = () => { + this.props.gotoHistoryLastPage(); + } + + onPageSelect = (page) => { + this.props.gotoHistoryPage({ page }); + } + + onSortPress = (sortKey) => { + this.props.setHistorySort({ sortKey }); + } + + onFilterSelect = (selectedFilterKey) => { + this.props.setHistoryFilter({ selectedFilterKey }); + } + + onTableOptionChange = (payload) => { + this.props.setHistoryTableOption(payload); + + if (payload.pageSize) { + this.props.gotoHistoryFirstPage(); + } + } + + // + // Render + + render() { + return ( + + ); + } +} + +HistoryConnector.propTypes = { + useCurrentPage: PropTypes.bool.isRequired, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + fetchHistory: PropTypes.func.isRequired, + gotoHistoryFirstPage: PropTypes.func.isRequired, + gotoHistoryPreviousPage: PropTypes.func.isRequired, + gotoHistoryNextPage: PropTypes.func.isRequired, + gotoHistoryLastPage: PropTypes.func.isRequired, + gotoHistoryPage: PropTypes.func.isRequired, + setHistorySort: PropTypes.func.isRequired, + setHistoryFilter: PropTypes.func.isRequired, + setHistoryTableOption: PropTypes.func.isRequired, + clearHistory: PropTypes.func.isRequired, + fetchEpisodes: PropTypes.func.isRequired, + clearEpisodes: PropTypes.func.isRequired, + clearEpisodeFiles: PropTypes.func.isRequired +}; + +export default withCurrentPage( + connect(createMapStateToProps, mapDispatchToProps)(HistoryConnector) +); diff --git a/frontend/src/Activity/History/HistoryEventTypeCell.css.d.ts b/frontend/src/Activity/History/HistoryEventTypeCell.css.d.ts deleted file mode 100644 index c748f6f97..000000000 --- a/frontend/src/Activity/History/HistoryEventTypeCell.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'cell': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/History/HistoryEventTypeCell.js b/frontend/src/Activity/History/HistoryEventTypeCell.js new file mode 100644 index 000000000..b6591e0b0 --- /dev/null +++ b/frontend/src/Activity/History/HistoryEventTypeCell.js @@ -0,0 +1,86 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { icons, kinds } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import styles from './HistoryEventTypeCell.css'; + +function getIconName(eventType) { + switch (eventType) { + case 'grabbed': + return icons.DOWNLOADING; + case 'seriesFolderImported': + return icons.DRIVE; + case 'downloadFolderImported': + return icons.DOWNLOADED; + case 'downloadFailed': + return icons.DOWNLOADING; + case 'episodeFileDeleted': + return icons.DELETE; + case 'episodeFileRenamed': + return icons.ORGANIZE; + case 'downloadIgnored': + return icons.IGNORE; + default: + return icons.UNKNOWN; + } +} + +function getIconKind(eventType) { + switch (eventType) { + case 'downloadFailed': + return kinds.DANGER; + default: + return kinds.DEFAULT; + } +} + +function getTooltip(eventType, data) { + switch (eventType) { + case 'grabbed': + return `Episode grabbed from ${data.indexer} and sent to ${data.downloadClient}`; + case 'seriesFolderImported': + return 'Episode imported from series folder'; + case 'downloadFolderImported': + return 'Episode downloaded successfully and picked up from download client'; + case 'downloadFailed': + return 'Episode download failed'; + case 'episodeFileDeleted': + return 'Episode file deleted'; + case 'episodeFileRenamed': + return 'Episode file renamed'; + case 'downloadIgnored': + return 'Episode Download Ignored'; + default: + return 'Unknown event'; + } +} + +function HistoryEventTypeCell({ eventType, data }) { + const iconName = getIconName(eventType); + const iconKind = getIconKind(eventType); + const tooltip = getTooltip(eventType, data); + + return ( + + + + ); +} + +HistoryEventTypeCell.propTypes = { + eventType: PropTypes.string.isRequired, + data: PropTypes.object +}; + +HistoryEventTypeCell.defaultProps = { + data: {} +}; + +export default HistoryEventTypeCell; diff --git a/frontend/src/Activity/History/HistoryEventTypeCell.tsx b/frontend/src/Activity/History/HistoryEventTypeCell.tsx deleted file mode 100644 index adedf08c0..000000000 --- a/frontend/src/Activity/History/HistoryEventTypeCell.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import React from 'react'; -import Icon from 'Components/Icon'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import { icons, kinds } from 'Helpers/Props'; -import { - EpisodeFileDeletedHistory, - GrabbedHistoryData, - HistoryData, - HistoryEventType, -} from 'typings/History'; -import translate from 'Utilities/String/translate'; -import styles from './HistoryEventTypeCell.css'; - -function getIconName(eventType: HistoryEventType, data: HistoryData) { - switch (eventType) { - case 'grabbed': - return icons.DOWNLOADING; - case 'seriesFolderImported': - return icons.DRIVE; - case 'downloadFolderImported': - return icons.DOWNLOADED; - case 'downloadFailed': - return icons.DOWNLOADING; - case 'episodeFileDeleted': - return (data as EpisodeFileDeletedHistory).reason === 'MissingFromDisk' - ? icons.FILE_MISSING - : icons.DELETE; - case 'episodeFileRenamed': - return icons.ORGANIZE; - case 'downloadIgnored': - return icons.IGNORE; - default: - return icons.UNKNOWN; - } -} - -function getIconKind(eventType: HistoryEventType) { - switch (eventType) { - case 'downloadFailed': - return kinds.DANGER; - default: - return kinds.DEFAULT; - } -} - -function getTooltip(eventType: HistoryEventType, data: HistoryData) { - switch (eventType) { - case 'grabbed': - return translate('EpisodeGrabbedTooltip', { - indexer: (data as GrabbedHistoryData).indexer, - downloadClient: (data as GrabbedHistoryData).downloadClient, - }); - case 'seriesFolderImported': - return translate('SeriesFolderImportedTooltip'); - case 'downloadFolderImported': - return translate('EpisodeImportedTooltip'); - case 'downloadFailed': - return translate('DownloadFailedEpisodeTooltip'); - case 'episodeFileDeleted': - return (data as EpisodeFileDeletedHistory).reason === 'MissingFromDisk' - ? translate('EpisodeFileMissingTooltip') - : translate('EpisodeFileDeletedTooltip'); - case 'episodeFileRenamed': - return translate('EpisodeFileRenamedTooltip'); - case 'downloadIgnored': - return translate('DownloadIgnoredEpisodeTooltip'); - default: - return translate('UnknownEventTooltip'); - } -} - -interface HistoryEventTypeCellProps { - eventType: HistoryEventType; - data: HistoryData; -} - -function HistoryEventTypeCell({ eventType, data }: HistoryEventTypeCellProps) { - const iconName = getIconName(eventType, data); - const iconKind = getIconKind(eventType); - const tooltip = getTooltip(eventType, data); - - return ( - - - - ); -} - -export default HistoryEventTypeCell; diff --git a/frontend/src/Activity/History/HistoryFilterModal.tsx b/frontend/src/Activity/History/HistoryFilterModal.tsx deleted file mode 100644 index f4ad2e57c..000000000 --- a/frontend/src/Activity/History/HistoryFilterModal.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import React, { useCallback } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import FilterModal from 'Components/Filter/FilterModal'; -import { setHistoryFilter } from 'Store/Actions/historyActions'; - -function createHistorySelector() { - return createSelector( - (state: AppState) => state.history.items, - (queueItems) => { - return queueItems; - } - ); -} - -function createFilterBuilderPropsSelector() { - return createSelector( - (state: AppState) => state.history.filterBuilderProps, - (filterBuilderProps) => { - return filterBuilderProps; - } - ); -} - -interface HistoryFilterModalProps { - isOpen: boolean; -} - -export default function HistoryFilterModal(props: HistoryFilterModalProps) { - const sectionItems = useSelector(createHistorySelector()); - const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); - const customFilterType = 'history'; - - const dispatch = useDispatch(); - - const dispatchSetFilter = useCallback( - (payload: unknown) => { - dispatch(setHistoryFilter(payload)); - }, - [dispatch] - ); - - return ( - - ); -} diff --git a/frontend/src/Activity/History/HistoryRow.css b/frontend/src/Activity/History/HistoryRow.css index 039804b63..07a392d71 100644 --- a/frontend/src/Activity/History/HistoryRow.css +++ b/frontend/src/Activity/History/HistoryRow.css @@ -10,7 +10,7 @@ width: 80px; } -.customFormatScore { +.preferredWordScore { composes: cell from '~Components/Table/Cells/TableRowCell.css'; width: 55px; diff --git a/frontend/src/Activity/History/HistoryRow.css.d.ts b/frontend/src/Activity/History/HistoryRow.css.d.ts deleted file mode 100644 index e1f54bc96..000000000 --- a/frontend/src/Activity/History/HistoryRow.css.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'customFormatScore': string; - 'details': string; - 'downloadClient': string; - 'indexer': string; - 'releaseGroup': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/History/HistoryRow.js b/frontend/src/Activity/History/HistoryRow.js new file mode 100644 index 000000000..7b892be6a --- /dev/null +++ b/frontend/src/Activity/History/HistoryRow.js @@ -0,0 +1,275 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import formatPreferredWordScore from 'Utilities/Number/formatPreferredWordScore'; +import { icons } from 'Helpers/Props'; +import IconButton from 'Components/Link/IconButton'; +import RelativeDateCellConnector from 'Components/Table/Cells/RelativeDateCellConnector'; +import TableRow from 'Components/Table/TableRow'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import episodeEntities from 'Episode/episodeEntities'; +import SeasonEpisodeNumber from 'Episode/SeasonEpisodeNumber'; +import EpisodeTitleLink from 'Episode/EpisodeTitleLink'; +import EpisodeLanguage from 'Episode/EpisodeLanguage'; +import EpisodeQuality from 'Episode/EpisodeQuality'; +import SeriesTitleLink from 'Series/SeriesTitleLink'; +import HistoryEventTypeCell from './HistoryEventTypeCell'; +import HistoryDetailsModal from './Details/HistoryDetailsModal'; +import styles from './HistoryRow.css'; + +class HistoryRow extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isDetailsModalOpen: false + }; + } + + componentDidUpdate(prevProps) { + if ( + prevProps.isMarkingAsFailed && + !this.props.isMarkingAsFailed && + !this.props.markAsFailedError + ) { + this.setState({ isDetailsModalOpen: false }); + } + } + + // + // Listeners + + onDetailsPress = () => { + this.setState({ isDetailsModalOpen: true }); + } + + onDetailsModalClose = () => { + this.setState({ isDetailsModalOpen: false }); + } + + // + // Render + + render() { + const { + episodeId, + series, + episode, + language, + languageCutoffNotMet, + quality, + qualityCutoffNotMet, + eventType, + sourceTitle, + date, + data, + isMarkingAsFailed, + columns, + shortDateFormat, + timeFormat, + onMarkAsFailedPress + } = this.props; + + if (!episode) { + return null; + } + + return ( + + { + columns.map((column) => { + const { + name, + isVisible + } = column; + + if (!isVisible) { + return null; + } + + if (name === 'eventType') { + return ( + + ); + } + + if (name === 'series.sortTitle') { + return ( + + + + ); + } + + if (name === 'episode') { + return ( + + + + ); + } + + if (name === 'episodeTitle') { + return ( + + + + ); + } + + if (name === 'language') { + return ( + + + + ); + } + + if (name === 'quality') { + return ( + + + + ); + } + + if (name === 'date') { + return ( + + ); + } + + if (name === 'downloadClient') { + return ( + + {data.downloadClient} + + ); + } + + if (name === 'indexer') { + return ( + + {data.indexer} + + ); + } + + if (name === 'preferredWordScore') { + return ( + + {formatPreferredWordScore(data.preferredWordScore)} + + ); + } + + if (name === 'releaseGroup') { + return ( + + {data.releaseGroup} + + ); + } + + if (name === 'details') { + return ( + + + + ); + } + + return null; + }) + } + + + + ); + } + +} + +HistoryRow.propTypes = { + episodeId: PropTypes.number, + series: PropTypes.object.isRequired, + episode: PropTypes.object, + language: PropTypes.object.isRequired, + languageCutoffNotMet: PropTypes.bool.isRequired, + quality: PropTypes.object.isRequired, + qualityCutoffNotMet: PropTypes.bool.isRequired, + eventType: PropTypes.string.isRequired, + sourceTitle: PropTypes.string.isRequired, + date: PropTypes.string.isRequired, + data: PropTypes.object.isRequired, + isMarkingAsFailed: PropTypes.bool, + markAsFailedError: PropTypes.object, + columns: PropTypes.arrayOf(PropTypes.object).isRequired, + shortDateFormat: PropTypes.string.isRequired, + timeFormat: PropTypes.string.isRequired, + onMarkAsFailedPress: PropTypes.func.isRequired +}; + +export default HistoryRow; diff --git a/frontend/src/Activity/History/HistoryRow.tsx b/frontend/src/Activity/History/HistoryRow.tsx deleted file mode 100644 index d1ba279dc..000000000 --- a/frontend/src/Activity/History/HistoryRow.tsx +++ /dev/null @@ -1,270 +0,0 @@ -import React, { useCallback, useEffect, useState } from 'react'; -import { useDispatch } from 'react-redux'; -import IconButton from 'Components/Link/IconButton'; -import RelativeDateCell from 'Components/Table/Cells/RelativeDateCell'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import Column from 'Components/Table/Column'; -import TableRow from 'Components/Table/TableRow'; -import Tooltip from 'Components/Tooltip/Tooltip'; -import episodeEntities from 'Episode/episodeEntities'; -import EpisodeFormats from 'Episode/EpisodeFormats'; -import EpisodeLanguages from 'Episode/EpisodeLanguages'; -import EpisodeQuality from 'Episode/EpisodeQuality'; -import EpisodeTitleLink from 'Episode/EpisodeTitleLink'; -import SeasonEpisodeNumber from 'Episode/SeasonEpisodeNumber'; -import useEpisode from 'Episode/useEpisode'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { icons, tooltipPositions } from 'Helpers/Props'; -import Language from 'Language/Language'; -import { QualityModel } from 'Quality/Quality'; -import SeriesTitleLink from 'Series/SeriesTitleLink'; -import useSeries from 'Series/useSeries'; -import { fetchHistory, markAsFailed } from 'Store/Actions/historyActions'; -import CustomFormat from 'typings/CustomFormat'; -import { HistoryData, HistoryEventType } from 'typings/History'; -import formatCustomFormatScore from 'Utilities/Number/formatCustomFormatScore'; -import HistoryDetailsModal from './Details/HistoryDetailsModal'; -import HistoryEventTypeCell from './HistoryEventTypeCell'; -import styles from './HistoryRow.css'; - -interface HistoryRowProps { - id: number; - episodeId: number; - seriesId: number; - languages: Language[]; - quality: QualityModel; - customFormats?: CustomFormat[]; - customFormatScore: number; - qualityCutoffNotMet: boolean; - eventType: HistoryEventType; - sourceTitle: string; - date: string; - data: HistoryData; - downloadId?: string; - isMarkingAsFailed?: boolean; - markAsFailedError?: object; - columns: Column[]; -} - -function HistoryRow(props: HistoryRowProps) { - const { - id, - episodeId, - seriesId, - languages, - quality, - customFormats = [], - customFormatScore, - qualityCutoffNotMet, - eventType, - sourceTitle, - date, - data, - downloadId, - isMarkingAsFailed = false, - markAsFailedError, - columns, - } = props; - - const wasMarkingAsFailed = usePrevious(isMarkingAsFailed); - const dispatch = useDispatch(); - const series = useSeries(seriesId); - const episode = useEpisode(episodeId, 'episodes'); - - const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); - - const handleDetailsPress = useCallback(() => { - setIsDetailsModalOpen(true); - }, [setIsDetailsModalOpen]); - - const handleDetailsModalClose = useCallback(() => { - setIsDetailsModalOpen(false); - }, [setIsDetailsModalOpen]); - - const handleMarkAsFailedPress = useCallback(() => { - dispatch(markAsFailed({ id })); - }, [id, dispatch]); - - useEffect(() => { - if (wasMarkingAsFailed && !isMarkingAsFailed && !markAsFailedError) { - setIsDetailsModalOpen(false); - dispatch(fetchHistory()); - } - }, [ - wasMarkingAsFailed, - isMarkingAsFailed, - markAsFailedError, - setIsDetailsModalOpen, - dispatch, - ]); - - if (!series || !episode) { - return null; - } - - return ( - - {columns.map((column) => { - const { name, isVisible } = column; - - if (!isVisible) { - return null; - } - - if (name === 'eventType') { - return ( - - ); - } - - if (name === 'series.sortTitle') { - return ( - - - - ); - } - - if (name === 'episode') { - return ( - - - - ); - } - - if (name === 'episodes.title') { - return ( - - - - ); - } - - if (name === 'languages') { - return ( - - - - ); - } - - if (name === 'quality') { - return ( - - - - ); - } - - if (name === 'customFormats') { - return ( - - - - ); - } - - if (name === 'date') { - return ; - } - - if (name === 'downloadClient') { - const downloadClientName = - 'downloadClientName' in data ? data.downloadClientName : null; - const downloadClient = - 'downloadClient' in data ? data.downloadClient : null; - - return ( - - {downloadClientName ?? downloadClient ?? ''} - - ); - } - - if (name === 'indexer') { - return ( - - {'indexer' in data ? data.indexer : ''} - - ); - } - - if (name === 'customFormatScore') { - return ( - - } - position={tooltipPositions.BOTTOM} - /> - - ); - } - - if (name === 'releaseGroup') { - return ( - - {'releaseGroup' in data ? data.releaseGroup : ''} - - ); - } - - if (name === 'sourceTitle') { - return {sourceTitle}; - } - - if (name === 'details') { - return ( - - - - ); - } - - return null; - })} - - - - ); -} - -export default HistoryRow; diff --git a/frontend/src/Activity/History/HistoryRowConnector.js b/frontend/src/Activity/History/HistoryRowConnector.js new file mode 100644 index 000000000..271000193 --- /dev/null +++ b/frontend/src/Activity/History/HistoryRowConnector.js @@ -0,0 +1,76 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { fetchHistory, markAsFailed } from 'Store/Actions/historyActions'; +import createSeriesSelector from 'Store/Selectors/createSeriesSelector'; +import createEpisodeSelector from 'Store/Selectors/createEpisodeSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import HistoryRow from './HistoryRow'; + +function createMapStateToProps() { + return createSelector( + createSeriesSelector(), + createEpisodeSelector(), + createUISettingsSelector(), + (series, episode, uiSettings) => { + return { + series, + episode, + shortDateFormat: uiSettings.shortDateFormat, + timeFormat: uiSettings.timeFormat + }; + } + ); +} + +const mapDispatchToProps = { + fetchHistory, + markAsFailed +}; + +class HistoryRowConnector extends Component { + + // + // Lifecycle + + componentDidUpdate(prevProps) { + if ( + prevProps.isMarkingAsFailed && + !this.props.isMarkingAsFailed && + !this.props.markAsFailedError + ) { + this.props.fetchHistory(); + } + } + + // + // Listeners + + onMarkAsFailedPress = () => { + this.props.markAsFailed({ id: this.props.id }); + } + + // + // Render + + render() { + return ( + + ); + } + +} + +HistoryRowConnector.propTypes = { + id: PropTypes.number.isRequired, + isMarkingAsFailed: PropTypes.bool, + markAsFailedError: PropTypes.object, + fetchHistory: PropTypes.func.isRequired, + markAsFailed: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(HistoryRowConnector); diff --git a/frontend/src/Activity/Queue/ProtocolLabel.css b/frontend/src/Activity/Queue/ProtocolLabel.css index c94e383b1..259fd5c65 100644 --- a/frontend/src/Activity/Queue/ProtocolLabel.css +++ b/frontend/src/Activity/Queue/ProtocolLabel.css @@ -1,17 +1,13 @@ .torrent { composes: label from '~Components/Label.css'; - border-color: var(--torrentColor); - background-color: var(--torrentColor); + border-color: $torrentColor; + background-color: $torrentColor; } .usenet { composes: label from '~Components/Label.css'; - border-color: var(--usenetColor); - background-color: var(--usenetColor); -} - -.unknown { - composes: label from '~Components/Label.css'; + border-color: $usenetColor; + background-color: $usenetColor; } diff --git a/frontend/src/Activity/Queue/ProtocolLabel.css.d.ts b/frontend/src/Activity/Queue/ProtocolLabel.css.d.ts deleted file mode 100644 index ba0cb260d..000000000 --- a/frontend/src/Activity/Queue/ProtocolLabel.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'torrent': string; - 'unknown': string; - 'usenet': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/ProtocolLabel.js b/frontend/src/Activity/Queue/ProtocolLabel.js new file mode 100644 index 000000000..e8a08943c --- /dev/null +++ b/frontend/src/Activity/Queue/ProtocolLabel.js @@ -0,0 +1,20 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Label from 'Components/Label'; +import styles from './ProtocolLabel.css'; + +function ProtocolLabel({ protocol }) { + const protocolName = protocol === 'usenet' ? 'nzb' : protocol; + + return ( + + ); +} + +ProtocolLabel.propTypes = { + protocol: PropTypes.string.isRequired +}; + +export default ProtocolLabel; diff --git a/frontend/src/Activity/Queue/ProtocolLabel.tsx b/frontend/src/Activity/Queue/ProtocolLabel.tsx deleted file mode 100644 index c1824452a..000000000 --- a/frontend/src/Activity/Queue/ProtocolLabel.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import React from 'react'; -import Label from 'Components/Label'; -import DownloadProtocol from 'DownloadClient/DownloadProtocol'; -import styles from './ProtocolLabel.css'; - -interface ProtocolLabelProps { - protocol: DownloadProtocol; -} - -function ProtocolLabel({ protocol }: ProtocolLabelProps) { - const protocolName = protocol === 'usenet' ? 'nzb' : protocol; - - return ; -} - -export default ProtocolLabel; diff --git a/frontend/src/Activity/Queue/Queue.js b/frontend/src/Activity/Queue/Queue.js new file mode 100644 index 000000000..7d16d75a0 --- /dev/null +++ b/frontend/src/Activity/Queue/Queue.js @@ -0,0 +1,319 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import getRemovedItems from 'Utilities/Object/getRemovedItems'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import getSelectedIds from 'Utilities/Table/getSelectedIds'; +import removeOldSelectedState from 'Utilities/Table/removeOldSelectedState'; +import selectAll from 'Utilities/Table/selectAll'; +import toggleSelected from 'Utilities/Table/toggleSelected'; +import { align, icons } from 'Helpers/Props'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import TablePager from 'Components/Table/TablePager'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator'; +import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; +import RemoveQueueItemsModal from './RemoveQueueItemsModal'; +import QueueOptionsConnector from './QueueOptionsConnector'; +import QueueRowConnector from './QueueRowConnector'; + +class Queue extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._shouldBlockRefresh = false; + + this.state = { + allSelected: false, + allUnselected: false, + lastToggled: null, + selectedState: {}, + isPendingSelected: false, + isConfirmRemoveModalOpen: false, + items: props.items + }; + } + + shouldComponentUpdate() { + if (this._shouldBlockRefresh) { + return false; + } + + return true; + } + + componentDidUpdate(prevProps) { + const { + items, + isEpisodesFetching + } = this.props; + + if ( + (!isEpisodesFetching && prevProps.isEpisodesFetching) || + (hasDifferentItems(prevProps.items, items) && !items.some((e) => e.episodeId)) + ) { + this.setState((state) => { + return { + ...removeOldSelectedState(state, getRemovedItems(prevProps.items, items)), + items + }; + }); + + return; + } + + const selectedIds = this.getSelectedIds(); + const isPendingSelected = _.some(this.props.items, (item) => { + return selectedIds.indexOf(item.id) > -1 && item.status === 'delay'; + }); + + if (isPendingSelected !== this.state.isPendingSelected) { + this.setState({ isPendingSelected }); + } + } + + // + // Control + + getSelectedIds = () => { + return getSelectedIds(this.state.selectedState); + } + + // + // Listeners + + onQueueRowModalOpenOrClose = (isOpen) => { + this._shouldBlockRefresh = isOpen; + } + + onSelectAllChange = ({ value }) => { + this.setState(selectAll(this.state.selectedState, value)); + } + + onSelectedChange = ({ id, value, shiftKey = false }) => { + this.setState((state) => { + return toggleSelected(state, this.props.items, id, value, shiftKey); + }); + } + + onGrabSelectedPress = () => { + this.props.onGrabSelectedPress(this.getSelectedIds()); + } + + onRemoveSelectedPress = () => { + this.setState({ isConfirmRemoveModalOpen: true }, () => { + this._shouldBlockRefresh = true; + }); + } + + onRemoveSelectedConfirmed = (payload) => { + this._shouldBlockRefresh = false; + this.props.onRemoveSelectedPress({ ids: this.getSelectedIds(), ...payload }); + this.setState({ isConfirmRemoveModalOpen: false }); + } + + onConfirmRemoveModalClose = () => { + this._shouldBlockRefresh = false; + this.setState({ isConfirmRemoveModalOpen: false }); + } + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + isEpisodesFetching, + isEpisodesPopulated, + episodesError, + columns, + totalRecords, + isGrabbing, + isRemoving, + isRefreshMonitoredDownloadsExecuting, + onRefreshPress, + ...otherProps + } = this.props; + + const { + allSelected, + allUnselected, + selectedState, + isConfirmRemoveModalOpen, + isPendingSelected, + items + } = this.state; + + const isRefreshing = isFetching || isEpisodesFetching || isRefreshMonitoredDownloadsExecuting; + const isAllPopulated = isPopulated && (isEpisodesPopulated || !items.length || items.every((e) => !e.episodeId)); + const hasError = error || episodesError; + const selectedIds = this.getSelectedIds(); + const selectedCount = selectedIds.length; + const disableSelectedActions = selectedCount === 0; + + return ( + + + + + + + + + + + + + + + + + + + + + { + isRefreshing && !isAllPopulated && + + } + + { + !isRefreshing && hasError && +
+ Failed to load Queue +
+ } + + { + isAllPopulated && !hasError && !items.length && +
+ Queue is empty +
+ } + + { + isAllPopulated && !hasError && !!items.length && +
+ + + { + items.map((item) => { + return ( + + ); + }) + } + +
+ + +
+ } +
+ + { + const item = items.find((i) => i.id === id); + + return !!(item && item.seriesId && item.episodeId); + }) + )} + allPending={isConfirmRemoveModalOpen && ( + selectedIds.every((id) => { + const item = items.find((i) => i.id === id); + + if (!item) { + return false; + } + + return item.status === 'delay' || item.status === 'downloadClientUnavailable'; + }) + )} + onRemovePress={this.onRemoveSelectedConfirmed} + onModalClose={this.onConfirmRemoveModalClose} + /> +
+ ); + } +} + +Queue.propTypes = { + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + isEpisodesFetching: PropTypes.bool.isRequired, + isEpisodesPopulated: PropTypes.bool.isRequired, + episodesError: PropTypes.object, + columns: PropTypes.arrayOf(PropTypes.object).isRequired, + totalRecords: PropTypes.number, + isGrabbing: PropTypes.bool.isRequired, + isRemoving: PropTypes.bool.isRequired, + isRefreshMonitoredDownloadsExecuting: PropTypes.bool.isRequired, + onRefreshPress: PropTypes.func.isRequired, + onGrabSelectedPress: PropTypes.func.isRequired, + onRemoveSelectedPress: PropTypes.func.isRequired +}; + +export default Queue; diff --git a/frontend/src/Activity/Queue/Queue.tsx b/frontend/src/Activity/Queue/Queue.tsx deleted file mode 100644 index bd063e69a..000000000 --- a/frontend/src/Activity/Queue/Queue.tsx +++ /dev/null @@ -1,415 +0,0 @@ -import React, { - ReactElement, - useCallback, - useEffect, - useMemo, - useRef, - useState, -} from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import * as commandNames from 'Commands/commandNames'; -import Alert from 'Components/Alert'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import FilterMenu from 'Components/Menu/FilterMenu'; -import PageContent from 'Components/Page/PageContent'; -import PageContentBody from 'Components/Page/PageContentBody'; -import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; -import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; -import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; -import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator'; -import Table from 'Components/Table/Table'; -import TableBody from 'Components/Table/TableBody'; -import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; -import TablePager from 'Components/Table/TablePager'; -import usePaging from 'Components/Table/usePaging'; -import createEpisodesFetchingSelector from 'Episode/createEpisodesFetchingSelector'; -import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; -import useSelectState from 'Helpers/Hooks/useSelectState'; -import { align, icons, kinds } from 'Helpers/Props'; -import { executeCommand } from 'Store/Actions/commandActions'; -import { clearEpisodes, fetchEpisodes } from 'Store/Actions/episodeActions'; -import { - clearQueue, - fetchQueue, - gotoQueuePage, - grabQueueItems, - removeQueueItems, - setQueueFilter, - setQueueSort, - setQueueTableOption, -} from 'Store/Actions/queueActions'; -import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; -import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; -import { CheckInputChanged } from 'typings/inputs'; -import { SelectStateInputProps } from 'typings/props'; -import QueueItem from 'typings/Queue'; -import { TableOptionsChangePayload } from 'typings/Table'; -import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; -import { - registerPagePopulator, - unregisterPagePopulator, -} from 'Utilities/pagePopulator'; -import translate from 'Utilities/String/translate'; -import getSelectedIds from 'Utilities/Table/getSelectedIds'; -import QueueFilterModal from './QueueFilterModal'; -import QueueOptions from './QueueOptions'; -import QueueRow from './QueueRow'; -import RemoveQueueItemModal, { RemovePressProps } from './RemoveQueueItemModal'; -import createQueueStatusSelector from './Status/createQueueStatusSelector'; - -function Queue() { - const requestCurrentPage = useCurrentPage(); - const dispatch = useDispatch(); - - const { - isFetching, - isPopulated, - error, - items, - columns, - selectedFilterKey, - filters, - sortKey, - sortDirection, - page, - pageSize, - totalPages, - totalRecords, - isGrabbing, - isRemoving, - } = useSelector((state: AppState) => state.queue.paged); - - const { count } = useSelector(createQueueStatusSelector()); - const { isEpisodesFetching, isEpisodesPopulated, episodesError } = - useSelector(createEpisodesFetchingSelector()); - const customFilters = useSelector(createCustomFiltersSelector('queue')); - - const isRefreshMonitoredDownloadsExecuting = useSelector( - createCommandExecutingSelector(commandNames.REFRESH_MONITORED_DOWNLOADS) - ); - - const shouldBlockRefresh = useRef(false); - const currentQueue = useRef(null); - - const [selectState, setSelectState] = useSelectState(); - const { allSelected, allUnselected, selectedState } = selectState; - - const selectedIds = useMemo(() => { - return getSelectedIds(selectedState); - }, [selectedState]); - - const isPendingSelected = useMemo(() => { - return items.some((item) => { - return selectedIds.indexOf(item.id) > -1 && item.status === 'delay'; - }); - }, [items, selectedIds]); - - const [isConfirmRemoveModalOpen, setIsConfirmRemoveModalOpen] = - useState(false); - - const isRefreshing = - isFetching || isEpisodesFetching || isRefreshMonitoredDownloadsExecuting; - const isAllPopulated = - isPopulated && - (isEpisodesPopulated || !items.length || items.every((e) => !e.episodeId)); - const hasError = error || episodesError; - const selectedCount = selectedIds.length; - const disableSelectedActions = selectedCount === 0; - - const handleSelectAllChange = useCallback( - ({ value }: CheckInputChanged) => { - setSelectState({ type: value ? 'selectAll' : 'unselectAll', items }); - }, - [items, setSelectState] - ); - - const handleSelectedChange = useCallback( - ({ id, value, shiftKey = false }: SelectStateInputProps) => { - setSelectState({ - type: 'toggleSelected', - items, - id, - isSelected: value, - shiftKey, - }); - }, - [items, setSelectState] - ); - - const handleRefreshPress = useCallback(() => { - dispatch( - executeCommand({ - name: commandNames.REFRESH_MONITORED_DOWNLOADS, - }) - ); - }, [dispatch]); - - const handleQueueRowModalOpenOrClose = useCallback((isOpen: boolean) => { - shouldBlockRefresh.current = isOpen; - }, []); - - const handleGrabSelectedPress = useCallback(() => { - dispatch(grabQueueItems({ ids: selectedIds })); - }, [selectedIds, dispatch]); - - const handleRemoveSelectedPress = useCallback(() => { - shouldBlockRefresh.current = true; - setIsConfirmRemoveModalOpen(true); - }, [setIsConfirmRemoveModalOpen]); - - const handleRemoveSelectedConfirmed = useCallback( - (payload: RemovePressProps) => { - shouldBlockRefresh.current = false; - dispatch(removeQueueItems({ ids: selectedIds, ...payload })); - setIsConfirmRemoveModalOpen(false); - }, - [selectedIds, setIsConfirmRemoveModalOpen, dispatch] - ); - - const handleConfirmRemoveModalClose = useCallback(() => { - shouldBlockRefresh.current = false; - setIsConfirmRemoveModalOpen(false); - }, [setIsConfirmRemoveModalOpen]); - - const { - handleFirstPagePress, - handlePreviousPagePress, - handleNextPagePress, - handleLastPagePress, - handlePageSelect, - } = usePaging({ - page, - totalPages, - gotoPage: gotoQueuePage, - }); - - const handleFilterSelect = useCallback( - (selectedFilterKey: string) => { - dispatch(setQueueFilter({ selectedFilterKey })); - }, - [dispatch] - ); - - const handleSortPress = useCallback( - (sortKey: string) => { - dispatch(setQueueSort({ sortKey })); - }, - [dispatch] - ); - - const handleTableOptionChange = useCallback( - (payload: TableOptionsChangePayload) => { - dispatch(setQueueTableOption(payload)); - - if (payload.pageSize) { - dispatch(gotoQueuePage({ page: 1 })); - } - }, - [dispatch] - ); - - useEffect(() => { - if (requestCurrentPage) { - dispatch(fetchQueue()); - } else { - dispatch(gotoQueuePage({ page: 1 })); - } - - return () => { - dispatch(clearQueue()); - }; - }, [requestCurrentPage, dispatch]); - - useEffect(() => { - const episodeIds = selectUniqueIds( - items, - 'episodeId' - ); - - if (episodeIds.length) { - dispatch(fetchEpisodes({ episodeIds })); - } else { - dispatch(clearEpisodes()); - } - }, [items, dispatch]); - - useEffect(() => { - const repopulate = () => { - dispatch(fetchQueue()); - }; - - registerPagePopulator(repopulate); - - return () => { - unregisterPagePopulator(repopulate); - }; - }, [dispatch]); - - if (!shouldBlockRefresh.current) { - currentQueue.current = ( - - {isRefreshing && !isAllPopulated ? : null} - - {!isRefreshing && hasError ? ( - {translate('QueueLoadError')} - ) : null} - - {isAllPopulated && !hasError && !items.length ? ( - - {selectedFilterKey !== 'all' && count > 0 - ? translate('QueueFilterHasNoItems') - : translate('QueueIsEmpty')} - - ) : null} - - {isAllPopulated && !hasError && !!items.length ? ( -
- - - {items.map((item) => { - return ( - - ); - })} - -
- - -
- ) : null} -
- ); - } - - return ( - - - - - - - - - - - - - - - - - - - - - - {currentQueue.current} - - { - const item = items.find((i) => i.id === id); - - return !!(item && item.downloadClientHasPostImportCategory); - }) - } - canIgnore={ - isConfirmRemoveModalOpen && - selectedIds.every((id) => { - const item = items.find((i) => i.id === id); - - return !!(item && item.seriesId && item.episodeId); - }) - } - isPending={ - isConfirmRemoveModalOpen && - selectedIds.every((id) => { - const item = items.find((i) => i.id === id); - - if (!item) { - return false; - } - - return ( - item.status === 'delay' || - item.status === 'downloadClientUnavailable' - ); - }) - } - onRemovePress={handleRemoveSelectedConfirmed} - onModalClose={handleConfirmRemoveModalClose} - /> - - ); -} - -export default Queue; diff --git a/frontend/src/Activity/Queue/QueueConnector.js b/frontend/src/Activity/Queue/QueueConnector.js new file mode 100644 index 000000000..ceb864f89 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueConnector.js @@ -0,0 +1,192 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; +import withCurrentPage from 'Components/withCurrentPage'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import { executeCommand } from 'Store/Actions/commandActions'; +import * as queueActions from 'Store/Actions/queueActions'; +import { fetchEpisodes, clearEpisodes } from 'Store/Actions/episodeActions'; +import * as commandNames from 'Commands/commandNames'; +import Queue from './Queue'; + +function createMapStateToProps() { + return createSelector( + (state) => state.episodes, + (state) => state.queue.options, + (state) => state.queue.paged, + createCommandExecutingSelector(commandNames.REFRESH_MONITORED_DOWNLOADS), + (episodes, options, queue, isRefreshMonitoredDownloadsExecuting) => { + return { + isEpisodesFetching: episodes.isFetching, + isEpisodesPopulated: episodes.isPopulated, + episodesError: episodes.error, + isRefreshMonitoredDownloadsExecuting, + ...options, + ...queue + }; + } + ); +} + +const mapDispatchToProps = { + ...queueActions, + fetchEpisodes, + clearEpisodes, + executeCommand +}; + +class QueueConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + const { + useCurrentPage, + fetchQueue, + fetchQueueStatus, + gotoQueueFirstPage + } = this.props; + + registerPagePopulator(this.repopulate); + + if (useCurrentPage) { + fetchQueue(); + } else { + gotoQueueFirstPage(); + } + + fetchQueueStatus(); + } + + componentDidUpdate(prevProps) { + if (hasDifferentItems(prevProps.items, this.props.items)) { + const episodeIds = selectUniqueIds(this.props.items, 'episodeId'); + + if (episodeIds.length) { + this.props.fetchEpisodes({ episodeIds }); + } else { + this.props.clearEpisodes(); + } + } + + if ( + this.props.includeUnknownSeriesItems !== + prevProps.includeUnknownSeriesItems + ) { + this.repopulate(); + } + } + + componentWillUnmount() { + unregisterPagePopulator(this.repopulate); + this.props.clearQueue(); + this.props.clearEpisodes(); + } + + // + // Control + + repopulate = () => { + this.props.fetchQueue(); + } + + // + // Listeners + + onFirstPagePress = () => { + this.props.gotoQueueFirstPage(); + } + + onPreviousPagePress = () => { + this.props.gotoQueuePreviousPage(); + } + + onNextPagePress = () => { + this.props.gotoQueueNextPage(); + } + + onLastPagePress = () => { + this.props.gotoQueueLastPage(); + } + + onPageSelect = (page) => { + this.props.gotoQueuePage({ page }); + } + + onSortPress = (sortKey) => { + this.props.setQueueSort({ sortKey }); + } + + onTableOptionChange = (payload) => { + this.props.setQueueTableOption(payload); + + if (payload.pageSize) { + this.props.gotoQueueFirstPage(); + } + } + + onRefreshPress = () => { + this.props.executeCommand({ + name: commandNames.REFRESH_MONITORED_DOWNLOADS + }); + } + + onGrabSelectedPress = (ids) => { + this.props.grabQueueItems({ ids }); + } + + onRemoveSelectedPress = (payload) => { + this.props.removeQueueItems(payload); + } + + // + // Render + + render() { + return ( + + ); + } +} + +QueueConnector.propTypes = { + includeUnknownSeriesItems: PropTypes.bool.isRequired, + useCurrentPage: PropTypes.bool.isRequired, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + fetchQueue: PropTypes.func.isRequired, + fetchQueueStatus: PropTypes.func.isRequired, + gotoQueueFirstPage: PropTypes.func.isRequired, + gotoQueuePreviousPage: PropTypes.func.isRequired, + gotoQueueNextPage: PropTypes.func.isRequired, + gotoQueueLastPage: PropTypes.func.isRequired, + gotoQueuePage: PropTypes.func.isRequired, + setQueueSort: PropTypes.func.isRequired, + setQueueTableOption: PropTypes.func.isRequired, + clearQueue: PropTypes.func.isRequired, + grabQueueItems: PropTypes.func.isRequired, + removeQueueItems: PropTypes.func.isRequired, + fetchEpisodes: PropTypes.func.isRequired, + clearEpisodes: PropTypes.func.isRequired, + executeCommand: PropTypes.func.isRequired +}; + +export default withCurrentPage( + connect(createMapStateToProps, mapDispatchToProps)(QueueConnector) +); diff --git a/frontend/src/Activity/Queue/QueueDetails.css b/frontend/src/Activity/Queue/QueueDetails.css deleted file mode 100644 index b7caba649..000000000 --- a/frontend/src/Activity/Queue/QueueDetails.css +++ /dev/null @@ -1,5 +0,0 @@ -.progressBarContainer { - display: flex; - justify-content: center; - width: 100%; -} diff --git a/frontend/src/Activity/Queue/QueueDetails.css.d.ts b/frontend/src/Activity/Queue/QueueDetails.css.d.ts deleted file mode 100644 index 4f2287015..000000000 --- a/frontend/src/Activity/Queue/QueueDetails.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'progressBarContainer': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueDetails.js b/frontend/src/Activity/Queue/QueueDetails.js new file mode 100644 index 000000000..5279971a3 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueDetails.js @@ -0,0 +1,127 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React from 'react'; +import { icons, kinds } from 'Helpers/Props'; +import Icon from 'Components/Icon'; + +function QueueDetails(props) { + const { + title, + size, + sizeleft, + estimatedCompletionTime, + status, + trackedDownloadState, + trackedDownloadStatus, + errorMessage, + progressBar + } = props; + + const progress = (100 - sizeleft / size * 100); + + if (status === 'pending') { + return ( + + ); + } + + if (status === 'completed') { + if (errorMessage) { + return ( + + ); + } + + if (trackedDownloadStatus === 'warning') { + return ( + + ); + } + + if (trackedDownloadState === 'importPending') { + return ( + + ); + } + + if (trackedDownloadState === 'importing') { + return ( + + ); + } + } + + if (errorMessage) { + return ( + + ); + } + + if (status === 'failed') { + return ( + + ); + } + + if (status === 'warning') { + return ( + + ); + } + + if (progress < 5) { + return ( + + ); + } + + return progressBar; +} + +QueueDetails.propTypes = { + title: PropTypes.string.isRequired, + size: PropTypes.number.isRequired, + sizeleft: PropTypes.number.isRequired, + estimatedCompletionTime: PropTypes.string, + status: PropTypes.string.isRequired, + trackedDownloadState: PropTypes.string.isRequired, + trackedDownloadStatus: PropTypes.string.isRequired, + errorMessage: PropTypes.string, + progressBar: PropTypes.node.isRequired +}; + +export default QueueDetails; diff --git a/frontend/src/Activity/Queue/QueueDetails.tsx b/frontend/src/Activity/Queue/QueueDetails.tsx deleted file mode 100644 index be70ceead..000000000 --- a/frontend/src/Activity/Queue/QueueDetails.tsx +++ /dev/null @@ -1,82 +0,0 @@ -import React from 'react'; -import Icon from 'Components/Icon'; -import Popover from 'Components/Tooltip/Popover'; -import { icons, tooltipPositions } from 'Helpers/Props'; -import { - QueueTrackedDownloadState, - QueueTrackedDownloadStatus, - StatusMessage, -} from 'typings/Queue'; -import translate from 'Utilities/String/translate'; -import QueueStatus from './QueueStatus'; -import styles from './QueueDetails.css'; - -interface QueueDetailsProps { - title: string; - size: number; - sizeleft: number; - estimatedCompletionTime?: string; - status: string; - trackedDownloadState?: QueueTrackedDownloadState; - trackedDownloadStatus?: QueueTrackedDownloadStatus; - statusMessages?: StatusMessage[]; - errorMessage?: string; - progressBar: React.ReactNode; -} - -function QueueDetails(props: QueueDetailsProps) { - const { - title, - size, - sizeleft, - status, - trackedDownloadState = 'downloading', - trackedDownloadStatus = 'ok', - statusMessages, - errorMessage, - progressBar, - } = props; - - const progress = 100 - (sizeleft / size) * 100; - const isDownloading = status === 'downloading'; - const isPaused = status === 'paused'; - const hasWarning = trackedDownloadStatus === 'warning'; - const hasError = trackedDownloadStatus === 'error'; - - if ((isDownloading || isPaused) && !hasWarning && !hasError) { - const state = isPaused ? translate('Paused') : translate('Downloading'); - - if (progress < 5) { - return ( - - ); - } - - return ( - {title}} - position={tooltipPositions.LEFT} - /> - ); - } - - return ( - - ); -} - -export default QueueDetails; diff --git a/frontend/src/Activity/Queue/QueueFilterModal.tsx b/frontend/src/Activity/Queue/QueueFilterModal.tsx deleted file mode 100644 index 3fce6c166..000000000 --- a/frontend/src/Activity/Queue/QueueFilterModal.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import React, { useCallback } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import FilterModal from 'Components/Filter/FilterModal'; -import { setQueueFilter } from 'Store/Actions/queueActions'; - -function createQueueSelector() { - return createSelector( - (state: AppState) => state.queue.paged.items, - (queueItems) => { - return queueItems; - } - ); -} - -function createFilterBuilderPropsSelector() { - return createSelector( - (state: AppState) => state.queue.paged.filterBuilderProps, - (filterBuilderProps) => { - return filterBuilderProps; - } - ); -} - -interface QueueFilterModalProps { - isOpen: boolean; -} - -export default function QueueFilterModal(props: QueueFilterModalProps) { - const sectionItems = useSelector(createQueueSelector()); - const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); - const customFilterType = 'queue'; - - const dispatch = useDispatch(); - - const dispatchSetFilter = useCallback( - (payload: unknown) => { - dispatch(setQueueFilter(payload)); - }, - [dispatch] - ); - - return ( - - ); -} diff --git a/frontend/src/Activity/Queue/QueueOptions.js b/frontend/src/Activity/Queue/QueueOptions.js new file mode 100644 index 000000000..900cf85cb --- /dev/null +++ b/frontend/src/Activity/Queue/QueueOptions.js @@ -0,0 +1,77 @@ +import PropTypes from 'prop-types'; +import React, { Component, Fragment } from 'react'; +import { inputTypes } from 'Helpers/Props'; +import FormGroup from 'Components/Form/FormGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import FormInputGroup from 'Components/Form/FormInputGroup'; + +class QueueOptions extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + includeUnknownSeriesItems: props.includeUnknownSeriesItems + }; + } + + componentDidUpdate(prevProps) { + const { + includeUnknownSeriesItems + } = this.props; + + if (includeUnknownSeriesItems !== prevProps.includeUnknownSeriesItems) { + this.setState({ + includeUnknownSeriesItems + }); + } + } + + // + // Listeners + + onOptionChange = ({ name, value }) => { + this.setState({ + [name]: value + }, () => { + this.props.onOptionChange({ + [name]: value + }); + }); + } + + // + // Render + + render() { + const { + includeUnknownSeriesItems + } = this.state; + + return ( + + + Show Unknown Series Items + + + + + ); + } +} + +QueueOptions.propTypes = { + includeUnknownSeriesItems: PropTypes.bool.isRequired, + onOptionChange: PropTypes.func.isRequired +}; + +export default QueueOptions; diff --git a/frontend/src/Activity/Queue/QueueOptions.tsx b/frontend/src/Activity/Queue/QueueOptions.tsx deleted file mode 100644 index 17a6ac1fe..000000000 --- a/frontend/src/Activity/Queue/QueueOptions.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import React, { useCallback } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import FormGroup from 'Components/Form/FormGroup'; -import FormInputGroup from 'Components/Form/FormInputGroup'; -import FormLabel from 'Components/Form/FormLabel'; -import { inputTypes } from 'Helpers/Props'; -import { gotoQueuePage, setQueueOption } from 'Store/Actions/queueActions'; -import { CheckInputChanged } from 'typings/inputs'; -import translate from 'Utilities/String/translate'; - -function QueueOptions() { - const dispatch = useDispatch(); - const { includeUnknownSeriesItems } = useSelector( - (state: AppState) => state.queue.options - ); - - const handleOptionChange = useCallback( - ({ name, value }: CheckInputChanged) => { - dispatch( - setQueueOption({ - [name]: value, - }) - ); - - if (name === 'includeUnknownSeriesItems') { - dispatch(gotoQueuePage({ page: 1 })); - } - }, - [dispatch] - ); - - return ( - - {translate('ShowUnknownSeriesItems')} - - - - ); -} - -export default QueueOptions; diff --git a/frontend/src/Activity/Queue/QueueOptionsConnector.js b/frontend/src/Activity/Queue/QueueOptionsConnector.js new file mode 100644 index 000000000..b2c99511c --- /dev/null +++ b/frontend/src/Activity/Queue/QueueOptionsConnector.js @@ -0,0 +1,19 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { setQueueOption } from 'Store/Actions/queueActions'; +import QueueOptions from './QueueOptions'; + +function createMapStateToProps() { + return createSelector( + (state) => state.queue.options, + (options) => { + return options; + } + ); +} + +const mapDispatchToProps = { + onOptionChange: setQueueOption +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(QueueOptions); diff --git a/frontend/src/Activity/Queue/QueueRow.css b/frontend/src/Activity/Queue/QueueRow.css index 459cdad8e..ee0483f96 100644 --- a/frontend/src/Activity/Queue/QueueRow.css +++ b/frontend/src/Activity/Queue/QueueRow.css @@ -16,15 +16,8 @@ width: 150px; } -.customFormatScore { - composes: cell from '~Components/Table/Cells/TableRowCell.css'; - - width: 55px; -} - .actions { composes: cell from '~Components/Table/Cells/TableRowCell.css'; width: 70px; - text-align: right; } diff --git a/frontend/src/Activity/Queue/QueueRow.css.d.ts b/frontend/src/Activity/Queue/QueueRow.css.d.ts deleted file mode 100644 index 13d67ea3a..000000000 --- a/frontend/src/Activity/Queue/QueueRow.css.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'actions': string; - 'customFormatScore': string; - 'progress': string; - 'protocol': string; - 'quality': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueRow.js b/frontend/src/Activity/Queue/QueueRow.js new file mode 100644 index 000000000..8e6a0ac2f --- /dev/null +++ b/frontend/src/Activity/Queue/QueueRow.js @@ -0,0 +1,430 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { icons, kinds } from 'Helpers/Props'; +import IconButton from 'Components/Link/IconButton'; +import SpinnerIconButton from 'Components/Link/SpinnerIconButton'; +import ProgressBar from 'Components/ProgressBar'; +import TableRow from 'Components/Table/TableRow'; +import RelativeDateCellConnector from 'Components/Table/Cells/RelativeDateCellConnector'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import TableSelectCell from 'Components/Table/Cells/TableSelectCell'; +import ProtocolLabel from 'Activity/Queue/ProtocolLabel'; +import EpisodeTitleLink from 'Episode/EpisodeTitleLink'; +import EpisodeLanguage from 'Episode/EpisodeLanguage'; +import EpisodeQuality from 'Episode/EpisodeQuality'; +import SeasonEpisodeNumber from 'Episode/SeasonEpisodeNumber'; +import InteractiveImportModal from 'InteractiveImport/InteractiveImportModal'; +import SeriesTitleLink from 'Series/SeriesTitleLink'; +import QueueStatusCell from './QueueStatusCell'; +import TimeleftCell from './TimeleftCell'; +import RemoveQueueItemModal from './RemoveQueueItemModal'; +import styles from './QueueRow.css'; +import formatBytes from 'Utilities/Number/formatBytes'; + +class QueueRow extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isRemoveQueueItemModalOpen: false, + isInteractiveImportModalOpen: false + }; + } + + // + // Listeners + + onRemoveQueueItemPress = () => { + this.setState({ isRemoveQueueItemModalOpen: true }); + } + + onRemoveQueueItemModalConfirmed = (blocklist) => { + const { + onRemoveQueueItemPress, + onQueueRowModalOpenOrClose + } = this.props; + + onQueueRowModalOpenOrClose(false); + onRemoveQueueItemPress(blocklist); + + this.setState({ isRemoveQueueItemModalOpen: false }); + } + + onRemoveQueueItemModalClose = () => { + this.props.onQueueRowModalOpenOrClose(false); + + this.setState({ isRemoveQueueItemModalOpen: false }); + } + + onInteractiveImportPress = () => { + this.props.onQueueRowModalOpenOrClose(true); + + this.setState({ isInteractiveImportModalOpen: true }); + } + + onInteractiveImportModalClose = () => { + this.props.onQueueRowModalOpenOrClose(false); + + this.setState({ isInteractiveImportModalOpen: false }); + } + + // + // Render + + render() { + const { + id, + downloadId, + title, + status, + trackedDownloadStatus, + trackedDownloadState, + statusMessages, + errorMessage, + series, + episode, + language, + quality, + protocol, + indexer, + outputPath, + downloadClient, + estimatedCompletionTime, + timeleft, + size, + sizeleft, + showRelativeDates, + shortDateFormat, + timeFormat, + isGrabbing, + grabError, + isRemoving, + isSelected, + columns, + onSelectedChange, + onGrabPress + } = this.props; + + const { + isRemoveQueueItemModalOpen, + isInteractiveImportModalOpen + } = this.state; + + const progress = 100 - (sizeleft / size * 100); + const showInteractiveImport = status === 'completed' && trackedDownloadStatus === 'warning'; + const isPending = status === 'delay' || status === 'downloadClientUnavailable'; + + return ( + + + + { + columns.map((column) => { + const { + name, + isVisible + } = column; + + if (!isVisible) { + return null; + } + + if (name === 'status') { + return ( + + ); + } + + if (name === 'series.sortTitle') { + return ( + + { + series ? + : + title + } + + ); + } + + if (name === 'episode') { + return ( + + { + episode ? + : + '-' + } + + ); + } + + if (name === 'episode.title') { + return ( + + { + episode ? + : + '-' + } + + ); + } + + if (name === 'episode.airDateUtc') { + if (episode) { + return ( + + ); + } + + return ( + + - + + ); + } + + if (name === 'language') { + return ( + + + + ); + } + + if (name === 'quality') { + return ( + + { + quality ? + : + null + } + + ); + } + + if (name === 'protocol') { + return ( + + + + ); + } + + if (name === 'indexer') { + return ( + + {indexer} + + ); + } + + if (name === 'downloadClient') { + return ( + + {downloadClient} + + ); + } + + if (name === 'title') { + return ( + + {title} + + ); + } + + if (name === 'size') { + return ( + {formatBytes(size)} + ); + } + + if (name === 'outputPath') { + return ( + + {outputPath} + + ); + } + + if (name === 'estimatedCompletionTime') { + return ( + + ); + } + + if (name === 'progress') { + return ( + + { + !!progress && + + } + + ); + } + + if (name === 'actions') { + return ( + + { + showInteractiveImport && + + } + + { + isPending && + + } + + + + ); + } + + return null; + }) + } + + + + + + ); + } + +} + +QueueRow.propTypes = { + id: PropTypes.number.isRequired, + downloadId: PropTypes.string, + title: PropTypes.string.isRequired, + status: PropTypes.string.isRequired, + trackedDownloadStatus: PropTypes.string, + trackedDownloadState: PropTypes.string, + statusMessages: PropTypes.arrayOf(PropTypes.object), + errorMessage: PropTypes.string, + series: PropTypes.object, + episode: PropTypes.object, + language: PropTypes.object.isRequired, + quality: PropTypes.object.isRequired, + protocol: PropTypes.string.isRequired, + indexer: PropTypes.string, + outputPath: PropTypes.string, + downloadClient: PropTypes.string, + estimatedCompletionTime: PropTypes.string, + timeleft: PropTypes.string, + size: PropTypes.number, + sizeleft: PropTypes.number, + showRelativeDates: PropTypes.bool.isRequired, + shortDateFormat: PropTypes.string.isRequired, + timeFormat: PropTypes.string.isRequired, + isGrabbing: PropTypes.bool.isRequired, + grabError: PropTypes.object, + isRemoving: PropTypes.bool.isRequired, + isSelected: PropTypes.bool, + columns: PropTypes.arrayOf(PropTypes.object).isRequired, + onSelectedChange: PropTypes.func.isRequired, + onGrabPress: PropTypes.func.isRequired, + onRemoveQueueItemPress: PropTypes.func.isRequired, + onQueueRowModalOpenOrClose: PropTypes.func.isRequired +}; + +QueueRow.defaultProps = { + isGrabbing: false, + isRemoving: false +}; + +export default QueueRow; diff --git a/frontend/src/Activity/Queue/QueueRow.tsx b/frontend/src/Activity/Queue/QueueRow.tsx deleted file mode 100644 index 25f5cb410..000000000 --- a/frontend/src/Activity/Queue/QueueRow.tsx +++ /dev/null @@ -1,411 +0,0 @@ -import React, { useCallback, useState } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import ProtocolLabel from 'Activity/Queue/ProtocolLabel'; -import { Error } from 'App/State/AppSectionState'; -import IconButton from 'Components/Link/IconButton'; -import SpinnerIconButton from 'Components/Link/SpinnerIconButton'; -import ProgressBar from 'Components/ProgressBar'; -import RelativeDateCell from 'Components/Table/Cells/RelativeDateCell'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import TableSelectCell from 'Components/Table/Cells/TableSelectCell'; -import Column from 'Components/Table/Column'; -import TableRow from 'Components/Table/TableRow'; -import Tooltip from 'Components/Tooltip/Tooltip'; -import DownloadProtocol from 'DownloadClient/DownloadProtocol'; -import EpisodeFormats from 'Episode/EpisodeFormats'; -import EpisodeLanguages from 'Episode/EpisodeLanguages'; -import EpisodeQuality from 'Episode/EpisodeQuality'; -import EpisodeTitleLink from 'Episode/EpisodeTitleLink'; -import SeasonEpisodeNumber from 'Episode/SeasonEpisodeNumber'; -import useEpisode from 'Episode/useEpisode'; -import { icons, kinds, tooltipPositions } from 'Helpers/Props'; -import InteractiveImportModal from 'InteractiveImport/InteractiveImportModal'; -import Language from 'Language/Language'; -import { QualityModel } from 'Quality/Quality'; -import SeriesTitleLink from 'Series/SeriesTitleLink'; -import useSeries from 'Series/useSeries'; -import { grabQueueItem, removeQueueItem } from 'Store/Actions/queueActions'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import CustomFormat from 'typings/CustomFormat'; -import { SelectStateInputProps } from 'typings/props'; -import { - QueueTrackedDownloadState, - QueueTrackedDownloadStatus, - StatusMessage, -} from 'typings/Queue'; -import formatBytes from 'Utilities/Number/formatBytes'; -import formatCustomFormatScore from 'Utilities/Number/formatCustomFormatScore'; -import translate from 'Utilities/String/translate'; -import QueueStatusCell from './QueueStatusCell'; -import RemoveQueueItemModal, { RemovePressProps } from './RemoveQueueItemModal'; -import TimeleftCell from './TimeleftCell'; -import styles from './QueueRow.css'; - -interface QueueRowProps { - id: number; - seriesId?: number; - episodeId?: number; - downloadId?: string; - title: string; - status: string; - trackedDownloadStatus?: QueueTrackedDownloadStatus; - trackedDownloadState?: QueueTrackedDownloadState; - statusMessages?: StatusMessage[]; - errorMessage?: string; - languages: Language[]; - quality: QualityModel; - customFormats?: CustomFormat[]; - customFormatScore: number; - protocol: DownloadProtocol; - indexer?: string; - outputPath?: string; - downloadClient?: string; - downloadClientHasPostImportCategory?: boolean; - estimatedCompletionTime?: string; - added?: string; - timeleft?: string; - size: number; - sizeleft: number; - isGrabbing?: boolean; - grabError?: Error; - isRemoving?: boolean; - isSelected?: boolean; - columns: Column[]; - onSelectedChange: (options: SelectStateInputProps) => void; - onQueueRowModalOpenOrClose: (isOpen: boolean) => void; -} - -function QueueRow(props: QueueRowProps) { - const { - id, - seriesId, - episodeId, - downloadId, - title, - status, - trackedDownloadStatus, - trackedDownloadState, - statusMessages, - errorMessage, - languages, - quality, - customFormats = [], - customFormatScore, - protocol, - indexer, - outputPath, - downloadClient, - downloadClientHasPostImportCategory, - estimatedCompletionTime, - added, - timeleft, - size, - sizeleft, - isGrabbing = false, - grabError, - isRemoving = false, - isSelected, - columns, - onSelectedChange, - onQueueRowModalOpenOrClose, - } = props; - - const dispatch = useDispatch(); - const series = useSeries(seriesId); - const episode = useEpisode(episodeId, 'episodes'); - const { showRelativeDates, shortDateFormat, timeFormat } = useSelector( - createUISettingsSelector() - ); - - const [isRemoveQueueItemModalOpen, setIsRemoveQueueItemModalOpen] = - useState(false); - - const [isInteractiveImportModalOpen, setIsInteractiveImportModalOpen] = - useState(false); - - const handleGrabPress = useCallback(() => { - dispatch(grabQueueItem({ id })); - }, [id, dispatch]); - - const handleInteractiveImportPress = useCallback(() => { - onQueueRowModalOpenOrClose(true); - setIsInteractiveImportModalOpen(true); - }, [setIsInteractiveImportModalOpen, onQueueRowModalOpenOrClose]); - - const handleInteractiveImportModalClose = useCallback(() => { - onQueueRowModalOpenOrClose(false); - setIsInteractiveImportModalOpen(false); - }, [setIsInteractiveImportModalOpen, onQueueRowModalOpenOrClose]); - - const handleRemoveQueueItemPress = useCallback(() => { - onQueueRowModalOpenOrClose(true); - setIsRemoveQueueItemModalOpen(true); - }, [setIsRemoveQueueItemModalOpen, onQueueRowModalOpenOrClose]); - - const handleRemoveQueueItemModalConfirmed = useCallback( - (payload: RemovePressProps) => { - onQueueRowModalOpenOrClose(false); - dispatch(removeQueueItem({ id, ...payload })); - setIsRemoveQueueItemModalOpen(false); - }, - [id, setIsRemoveQueueItemModalOpen, onQueueRowModalOpenOrClose, dispatch] - ); - - const handleRemoveQueueItemModalClose = useCallback(() => { - onQueueRowModalOpenOrClose(false); - setIsRemoveQueueItemModalOpen(false); - }, [setIsRemoveQueueItemModalOpen, onQueueRowModalOpenOrClose]); - - const progress = 100 - (sizeleft / size) * 100; - const showInteractiveImport = - status === 'completed' && trackedDownloadStatus === 'warning'; - const isPending = - status === 'delay' || status === 'downloadClientUnavailable'; - - return ( - - - - {columns.map((column) => { - const { name, isVisible } = column; - - if (!isVisible) { - return null; - } - - if (name === 'status') { - return ( - - ); - } - - if (name === 'series.sortTitle') { - return ( - - {series ? ( - - ) : ( - title - )} - - ); - } - - if (name === 'episode') { - return ( - - {episode ? ( - - ) : ( - '-' - )} - - ); - } - - if (name === 'episodes.title') { - return ( - - {series && episode ? ( - - ) : ( - '-' - )} - - ); - } - - if (name === 'episodes.airDateUtc') { - if (episode) { - return ; - } - - return -; - } - - if (name === 'languages') { - return ( - - - - ); - } - - if (name === 'quality') { - return ( - - {quality ? : null} - - ); - } - - if (name === 'customFormats') { - return ( - - - - ); - } - - if (name === 'customFormatScore') { - return ( - - } - position={tooltipPositions.BOTTOM} - /> - - ); - } - - if (name === 'protocol') { - return ( - - - - ); - } - - if (name === 'indexer') { - return {indexer}; - } - - if (name === 'downloadClient') { - return {downloadClient}; - } - - if (name === 'title') { - return {title}; - } - - if (name === 'size') { - return {formatBytes(size)}; - } - - if (name === 'outputPath') { - return {outputPath}; - } - - if (name === 'estimatedCompletionTime') { - return ( - - ); - } - - if (name === 'progress') { - return ( - - {!!progress && ( - - )} - - ); - } - - if (name === 'added') { - return ; - } - - if (name === 'actions') { - return ( - - {showInteractiveImport ? ( - - ) : null} - - {isPending ? ( - - ) : null} - - - - ); - } - - return null; - })} - - - - - - ); -} - -export default QueueRow; diff --git a/frontend/src/Activity/Queue/QueueRowConnector.js b/frontend/src/Activity/Queue/QueueRowConnector.js new file mode 100644 index 000000000..3203fe425 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueRowConnector.js @@ -0,0 +1,70 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { grabQueueItem, removeQueueItem } from 'Store/Actions/queueActions'; +import createSeriesSelector from 'Store/Selectors/createSeriesSelector'; +import createEpisodeSelector from 'Store/Selectors/createEpisodeSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import QueueRow from './QueueRow'; + +function createMapStateToProps() { + return createSelector( + createSeriesSelector(), + createEpisodeSelector(), + createUISettingsSelector(), + (series, episode, uiSettings) => { + const result = { + showRelativeDates: uiSettings.showRelativeDates, + shortDateFormat: uiSettings.shortDateFormat, + timeFormat: uiSettings.timeFormat + }; + + result.series = series; + result.episode = episode; + + return result; + } + ); +} + +const mapDispatchToProps = { + grabQueueItem, + removeQueueItem +}; + +class QueueRowConnector extends Component { + + // + // Listeners + + onGrabPress = () => { + this.props.grabQueueItem({ id: this.props.id }); + } + + onRemoveQueueItemPress = (payload) => { + this.props.removeQueueItem({ id: this.props.id, ...payload }); + } + + // + // Render + + render() { + return ( + + ); + } +} + +QueueRowConnector.propTypes = { + id: PropTypes.number.isRequired, + episode: PropTypes.object, + grabQueueItem: PropTypes.func.isRequired, + removeQueueItem: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(QueueRowConnector); diff --git a/frontend/src/Activity/Queue/QueueStatus.css b/frontend/src/Activity/Queue/QueueStatus.css deleted file mode 100644 index 566231656..000000000 --- a/frontend/src/Activity/Queue/QueueStatus.css +++ /dev/null @@ -1,3 +0,0 @@ -.noMessages { - margin-bottom: 10px; -} diff --git a/frontend/src/Activity/Queue/QueueStatus.css.d.ts b/frontend/src/Activity/Queue/QueueStatus.css.d.ts deleted file mode 100644 index 0911f2376..000000000 --- a/frontend/src/Activity/Queue/QueueStatus.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'noMessages': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueStatus.tsx b/frontend/src/Activity/Queue/QueueStatus.tsx deleted file mode 100644 index 31a28f35c..000000000 --- a/frontend/src/Activity/Queue/QueueStatus.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import React from 'react'; -import Icon, { IconProps } from 'Components/Icon'; -import Popover from 'Components/Tooltip/Popover'; -import { icons, kinds } from 'Helpers/Props'; -import { TooltipPosition } from 'Helpers/Props/tooltipPositions'; -import { - QueueTrackedDownloadState, - QueueTrackedDownloadStatus, - StatusMessage, -} from 'typings/Queue'; -import translate from 'Utilities/String/translate'; -import styles from './QueueStatus.css'; - -function getDetailedPopoverBody(statusMessages: StatusMessage[]) { - return ( -
- {statusMessages.map(({ title, messages }) => { - return ( -
- {title} -
    - {messages.map((message) => { - return
  • {message}
  • ; - })} -
-
- ); - })} -
- ); -} - -interface QueueStatusProps { - sourceTitle: string; - status: string; - trackedDownloadStatus?: QueueTrackedDownloadStatus; - trackedDownloadState?: QueueTrackedDownloadState; - statusMessages?: StatusMessage[]; - errorMessage?: string; - position: TooltipPosition; - canFlip?: boolean; -} - -function QueueStatus(props: QueueStatusProps) { - const { - sourceTitle, - status, - trackedDownloadStatus = 'ok', - trackedDownloadState = 'downloading', - statusMessages = [], - errorMessage, - position, - canFlip = false, - } = props; - - const hasWarning = trackedDownloadStatus === 'warning'; - const hasError = trackedDownloadStatus === 'error'; - - // status === 'downloading' - let iconName = icons.DOWNLOADING; - let iconKind: IconProps['kind'] = kinds.DEFAULT; - let title = translate('Downloading'); - - if (status === 'paused') { - iconName = icons.PAUSED; - title = translate('Paused'); - } - - if (status === 'queued') { - iconName = icons.QUEUED; - title = translate('Queued'); - } - - if (status === 'completed') { - iconName = icons.DOWNLOADED; - title = translate('Downloaded'); - - if (trackedDownloadState === 'importBlocked') { - title += ` - ${translate('UnableToImportAutomatically')}`; - iconKind = kinds.WARNING; - } - - if (trackedDownloadState === 'importPending') { - title += ` - ${translate('WaitingToImport')}`; - iconKind = kinds.PURPLE; - } - - if (trackedDownloadState === 'importing') { - title += ` - ${translate('Importing')}`; - iconKind = kinds.PURPLE; - } - - if (trackedDownloadState === 'failedPending') { - title += ` - ${translate('WaitingToProcess')}`; - iconKind = kinds.DANGER; - } - } - - if (hasWarning) { - iconKind = kinds.WARNING; - } - - if (status === 'delay') { - iconName = icons.PENDING; - title = translate('Pending'); - } - - if (status === 'downloadClientUnavailable') { - iconName = icons.PENDING; - iconKind = kinds.WARNING; - title = translate('PendingDownloadClientUnavailable'); - } - - if (status === 'failed') { - iconName = icons.DOWNLOADING; - iconKind = kinds.DANGER; - title = translate('DownloadFailed'); - } - - if (status === 'warning') { - iconName = icons.DOWNLOADING; - iconKind = kinds.WARNING; - const warningMessage = - errorMessage || translate('CheckDownloadClientForDetails'); - title = translate('DownloadWarning', { warningMessage }); - } - - if (hasError) { - if (status === 'completed') { - iconName = icons.DOWNLOAD; - iconKind = kinds.DANGER; - title = translate('ImportFailed', { sourceTitle }); - } else { - iconName = icons.DOWNLOADING; - iconKind = kinds.DANGER; - title = translate('DownloadFailed'); - } - } - - return ( - } - title={title} - body={ - hasWarning || hasError - ? getDetailedPopoverBody(statusMessages) - : sourceTitle - } - position={position} - canFlip={canFlip} - /> - ); -} - -export default QueueStatus; diff --git a/frontend/src/Activity/Queue/QueueStatusCell.css.d.ts b/frontend/src/Activity/Queue/QueueStatusCell.css.d.ts deleted file mode 100644 index aefdc03b9..000000000 --- a/frontend/src/Activity/Queue/QueueStatusCell.css.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'noMessages': string; - 'status': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueStatusCell.js b/frontend/src/Activity/Queue/QueueStatusCell.js new file mode 100644 index 000000000..32fa1d0a4 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatusCell.js @@ -0,0 +1,158 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { icons, kinds, tooltipPositions } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import Popover from 'Components/Tooltip/Popover'; +import styles from './QueueStatusCell.css'; + +function getDetailedPopoverBody(statusMessages) { + return ( +
+ { + statusMessages.map(({ title, messages }) => { + return ( +
+ {title} +
    + { + messages.map((message) => { + return ( +
  • + {message} +
  • + ); + }) + } +
+
+ ); + }) + } +
+ ); +} + +function QueueStatusCell(props) { + const { + sourceTitle, + status, + trackedDownloadStatus, + trackedDownloadState, + statusMessages, + errorMessage + } = props; + + const hasWarning = trackedDownloadStatus === 'warning'; + const hasError = trackedDownloadStatus === 'error'; + + // status === 'downloading' + let iconName = icons.DOWNLOADING; + let iconKind = kinds.DEFAULT; + let title = 'Downloading'; + + if (status === 'paused') { + iconName = icons.PAUSED; + title = 'Paused'; + } + + if (status === 'queued') { + iconName = icons.QUEUED; + title = 'Queued'; + } + + if (status === 'completed') { + iconName = icons.DOWNLOADED; + title = 'Downloaded'; + + if (trackedDownloadState === 'importPending') { + title += ' - Waiting to Import'; + iconKind = kinds.PURPLE; + } + + if (trackedDownloadState === 'importing') { + title += ' - Importing'; + iconKind = kinds.PURPLE; + } + + if (trackedDownloadState === 'failedPending') { + title += ' - Waiting to Process'; + iconKind = kinds.DANGER; + } + } + + if (hasWarning) { + iconKind = kinds.WARNING; + } + + if (status === 'delay') { + iconName = icons.PENDING; + title = 'Pending'; + } + + if (status === 'downloadClientUnavailable') { + iconName = icons.PENDING; + iconKind = kinds.WARNING; + title = 'Pending - Download client is unavailable'; + } + + if (status === 'failed') { + iconName = icons.DOWNLOADING; + iconKind = kinds.DANGER; + title = 'Download failed'; + } + + if (status === 'warning') { + iconName = icons.DOWNLOADING; + iconKind = kinds.WARNING; + title = `Download warning: ${errorMessage || 'check download client for more details'}`; + } + + if (hasError) { + if (status === 'completed') { + iconName = icons.DOWNLOAD; + iconKind = kinds.DANGER; + title = `Import failed: ${sourceTitle}`; + } else { + iconName = icons.DOWNLOADING; + iconKind = kinds.DANGER; + title = 'Download failed'; + } + } + + return ( + + + } + title={title} + body={hasWarning || hasError ? getDetailedPopoverBody(statusMessages) : sourceTitle} + position={tooltipPositions.RIGHT} + canFlip={false} + /> + + ); +} + +QueueStatusCell.propTypes = { + sourceTitle: PropTypes.string.isRequired, + status: PropTypes.string.isRequired, + trackedDownloadStatus: PropTypes.string.isRequired, + trackedDownloadState: PropTypes.string.isRequired, + statusMessages: PropTypes.arrayOf(PropTypes.object), + errorMessage: PropTypes.string +}; + +QueueStatusCell.defaultProps = { + trackedDownloadStatus: 'Ok', + trackedDownloadState: 'Downloading' +}; + +export default QueueStatusCell; diff --git a/frontend/src/Activity/Queue/QueueStatusCell.tsx b/frontend/src/Activity/Queue/QueueStatusCell.tsx deleted file mode 100644 index 634e33164..000000000 --- a/frontend/src/Activity/Queue/QueueStatusCell.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import React from 'react'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import { - QueueTrackedDownloadState, - QueueTrackedDownloadStatus, - StatusMessage, -} from 'typings/Queue'; -import QueueStatus from './QueueStatus'; -import styles from './QueueStatusCell.css'; - -interface QueueStatusCellProps { - sourceTitle: string; - status: string; - trackedDownloadStatus?: QueueTrackedDownloadStatus; - trackedDownloadState?: QueueTrackedDownloadState; - statusMessages?: StatusMessage[]; - errorMessage?: string; -} - -function QueueStatusCell(props: QueueStatusCellProps) { - const { - sourceTitle, - status, - trackedDownloadStatus = 'ok', - trackedDownloadState = 'downloading', - statusMessages, - errorMessage, - } = props; - - return ( - - - - ); -} - -export default QueueStatusCell; diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.css.d.ts b/frontend/src/Activity/Queue/RemoveQueueItemModal.css.d.ts deleted file mode 100644 index 65c237dff..000000000 --- a/frontend/src/Activity/Queue/RemoveQueueItemModal.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'message': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.js b/frontend/src/Activity/Queue/RemoveQueueItemModal.js new file mode 100644 index 000000000..c2e71a48d --- /dev/null +++ b/frontend/src/Activity/Queue/RemoveQueueItemModal.js @@ -0,0 +1,150 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { inputTypes, kinds, sizes } from 'Helpers/Props'; +import Button from 'Components/Link/Button'; +import Modal from 'Components/Modal/Modal'; +import FormGroup from 'Components/Form/FormGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; + +class RemoveQueueItemModal extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + remove: true, + blocklist: false + }; + } + + // + // Control + + resetState = function() { + this.setState({ + remove: true, + blocklist: false + }); + } + + // + // Listeners + + onRemoveChange = ({ value }) => { + this.setState({ remove: value }); + } + + onBlocklistChange = ({ value }) => { + this.setState({ blocklist: value }); + } + + onRemoveConfirmed = () => { + const state = this.state; + + this.resetState(); + this.props.onRemovePress(state); + } + + onModalClose = () => { + this.resetState(); + this.props.onModalClose(); + } + + // + // Render + + render() { + const { + isOpen, + sourceTitle, + canIgnore, + isPending + } = this.props; + + const { remove, blocklist } = this.state; + + return ( + + + + Remove - {sourceTitle} + + + +
+ Are you sure you want to remove '{sourceTitle}' from the queue? +
+ + { + isPending ? + null : + + Remove From Download Client + + + + } + + + Add Release To Blocklist + + + + +
+ + + + + + +
+
+ ); + } +} + +RemoveQueueItemModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + sourceTitle: PropTypes.string.isRequired, + canIgnore: PropTypes.bool.isRequired, + isPending: PropTypes.bool.isRequired, + onRemovePress: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default RemoveQueueItemModal; diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.tsx b/frontend/src/Activity/Queue/RemoveQueueItemModal.tsx deleted file mode 100644 index 461fa57ad..000000000 --- a/frontend/src/Activity/Queue/RemoveQueueItemModal.tsx +++ /dev/null @@ -1,231 +0,0 @@ -import React, { useCallback, useMemo, useState } from 'react'; -import FormGroup from 'Components/Form/FormGroup'; -import FormInputGroup from 'Components/Form/FormInputGroup'; -import FormLabel from 'Components/Form/FormLabel'; -import Button from 'Components/Link/Button'; -import Modal from 'Components/Modal/Modal'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import { inputTypes, kinds, sizes } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; -import styles from './RemoveQueueItemModal.css'; - -export interface RemovePressProps { - remove: boolean; - changeCategory: boolean; - blocklist: boolean; - skipRedownload: boolean; -} - -interface RemoveQueueItemModalProps { - isOpen: boolean; - sourceTitle?: string; - canChangeCategory: boolean; - canIgnore: boolean; - isPending: boolean; - selectedCount?: number; - onRemovePress(props: RemovePressProps): void; - onModalClose: () => void; -} - -type RemovalMethod = 'removeFromClient' | 'changeCategory' | 'ignore'; -type BlocklistMethod = - | 'doNotBlocklist' - | 'blocklistAndSearch' - | 'blocklistOnly'; - -function RemoveQueueItemModal(props: RemoveQueueItemModalProps) { - const { - isOpen, - sourceTitle = '', - canIgnore, - canChangeCategory, - isPending, - selectedCount, - onRemovePress, - onModalClose, - } = props; - - const multipleSelected = selectedCount && selectedCount > 1; - - const [removalMethod, setRemovalMethod] = - useState('removeFromClient'); - const [blocklistMethod, setBlocklistMethod] = - useState('doNotBlocklist'); - - const { title, message } = useMemo(() => { - if (!selectedCount) { - return { - title: translate('RemoveQueueItem', { sourceTitle }), - message: translate('RemoveQueueItemConfirmation', { sourceTitle }), - }; - } - - if (selectedCount === 1) { - return { - title: translate('RemoveSelectedItem'), - message: translate('RemoveSelectedItemQueueMessageText'), - }; - } - - return { - title: translate('RemoveSelectedItems'), - message: translate('RemoveSelectedItemsQueueMessageText', { - selectedCount, - }), - }; - }, [sourceTitle, selectedCount]); - - const removalMethodOptions = useMemo(() => { - return [ - { - key: 'removeFromClient', - value: translate('RemoveFromDownloadClient'), - hint: multipleSelected - ? translate('RemoveMultipleFromDownloadClientHint') - : translate('RemoveFromDownloadClientHint'), - }, - { - key: 'changeCategory', - value: translate('ChangeCategory'), - isDisabled: !canChangeCategory, - hint: multipleSelected - ? translate('ChangeCategoryMultipleHint') - : translate('ChangeCategoryHint'), - }, - { - key: 'ignore', - value: multipleSelected - ? translate('IgnoreDownloads') - : translate('IgnoreDownload'), - isDisabled: !canIgnore, - hint: multipleSelected - ? translate('IgnoreDownloadsHint') - : translate('IgnoreDownloadHint'), - }, - ]; - }, [canChangeCategory, canIgnore, multipleSelected]); - - const blocklistMethodOptions = useMemo(() => { - return [ - { - key: 'doNotBlocklist', - value: translate('DoNotBlocklist'), - hint: translate('DoNotBlocklistHint'), - }, - { - key: 'blocklistAndSearch', - value: translate('BlocklistAndSearch'), - isDisabled: isPending, - hint: multipleSelected - ? translate('BlocklistAndSearchMultipleHint') - : translate('BlocklistAndSearchHint'), - }, - { - key: 'blocklistOnly', - value: translate('BlocklistOnly'), - hint: multipleSelected - ? translate('BlocklistMultipleOnlyHint') - : translate('BlocklistOnlyHint'), - }, - ]; - }, [isPending, multipleSelected]); - - const handleRemovalMethodChange = useCallback( - ({ value }: { value: RemovalMethod }) => { - setRemovalMethod(value); - }, - [setRemovalMethod] - ); - - const handleBlocklistMethodChange = useCallback( - ({ value }: { value: BlocklistMethod }) => { - setBlocklistMethod(value); - }, - [setBlocklistMethod] - ); - - const handleConfirmRemove = useCallback(() => { - onRemovePress({ - remove: removalMethod === 'removeFromClient', - changeCategory: removalMethod === 'changeCategory', - blocklist: blocklistMethod !== 'doNotBlocklist', - skipRedownload: blocklistMethod === 'blocklistOnly', - }); - - setRemovalMethod('removeFromClient'); - setBlocklistMethod('doNotBlocklist'); - }, [ - removalMethod, - blocklistMethod, - setRemovalMethod, - setBlocklistMethod, - onRemovePress, - ]); - - const handleModalClose = useCallback(() => { - setRemovalMethod('removeFromClient'); - setBlocklistMethod('doNotBlocklist'); - - onModalClose(); - }, [setRemovalMethod, setBlocklistMethod, onModalClose]); - - return ( - - - {title} - - -
{message}
- - {isPending ? null : ( - - {translate('RemoveQueueItemRemovalMethod')} - - - - )} - - - - {multipleSelected - ? translate('BlocklistReleases') - : translate('BlocklistRelease')} - - - - -
- - - - - - -
-
- ); -} - -export default RemoveQueueItemModal; diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.css b/frontend/src/Activity/Queue/RemoveQueueItemsModal.css similarity index 100% rename from frontend/src/Activity/Queue/RemoveQueueItemModal.css rename to frontend/src/Activity/Queue/RemoveQueueItemsModal.css diff --git a/frontend/src/Activity/Queue/RemoveQueueItemsModal.js b/frontend/src/Activity/Queue/RemoveQueueItemsModal.js new file mode 100644 index 000000000..b80427ffe --- /dev/null +++ b/frontend/src/Activity/Queue/RemoveQueueItemsModal.js @@ -0,0 +1,153 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { inputTypes, kinds, sizes } from 'Helpers/Props'; +import Button from 'Components/Link/Button'; +import Modal from 'Components/Modal/Modal'; +import FormGroup from 'Components/Form/FormGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; +import styles from './RemoveQueueItemsModal.css'; + +class RemoveQueueItemsModal extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + remove: true, + blocklist: false + }; + } + + // + // Control + + resetState = function() { + this.setState({ + remove: true, + blocklist: false + }); + } + + // + // Listeners + + onRemoveChange = ({ value }) => { + this.setState({ remove: value }); + } + + onBlocklistChange = ({ value }) => { + this.setState({ blocklist: value }); + } + + onRemoveConfirmed = () => { + const state = this.state; + + this.resetState(); + this.props.onRemovePress(state); + } + + onModalClose = () => { + this.resetState(); + this.props.onModalClose(); + } + + // + // Render + + render() { + const { + isOpen, + selectedCount, + canIgnore, + allPending + } = this.props; + + const { remove, blocklist } = this.state; + + return ( + + + + Remove Selected Item{selectedCount > 1 ? 's' : ''} + + + +
+ Are you sure you want to remove {selectedCount} item{selectedCount > 1 ? 's' : ''} from the queue? +
+ + { + allPending ? + null : + + Remove From Download Client + + + + } + + + + Add Release{selectedCount > 1 ? 's' : ''} To Blocklist + + + + + +
+ + + + + + +
+
+ ); + } +} + +RemoveQueueItemsModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + selectedCount: PropTypes.number.isRequired, + canIgnore: PropTypes.bool.isRequired, + allPending: PropTypes.bool.isRequired, + onRemovePress: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default RemoveQueueItemsModal; diff --git a/frontend/src/Activity/Queue/Status/QueueStatus.tsx b/frontend/src/Activity/Queue/Status/QueueStatus.tsx deleted file mode 100644 index 894434e07..000000000 --- a/frontend/src/Activity/Queue/Status/QueueStatus.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import React, { useEffect } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import PageSidebarStatus from 'Components/Page/Sidebar/PageSidebarStatus'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { fetchQueueStatus } from 'Store/Actions/queueActions'; -import createQueueStatusSelector from './createQueueStatusSelector'; - -function QueueStatus() { - const dispatch = useDispatch(); - const { isConnected, isReconnecting } = useSelector( - (state: AppState) => state.app - ); - const { isPopulated, count, errors, warnings } = useSelector( - createQueueStatusSelector() - ); - - const wasReconnecting = usePrevious(isReconnecting); - - useEffect(() => { - if (!isPopulated) { - dispatch(fetchQueueStatus()); - } - }, [isPopulated, dispatch]); - - useEffect(() => { - if (isConnected && wasReconnecting) { - dispatch(fetchQueueStatus()); - } - }, [isConnected, wasReconnecting, dispatch]); - - return ( - - ); -} - -export default QueueStatus; diff --git a/frontend/src/Activity/Queue/Status/QueueStatusConnector.js b/frontend/src/Activity/Queue/Status/QueueStatusConnector.js new file mode 100644 index 000000000..3d7d11566 --- /dev/null +++ b/frontend/src/Activity/Queue/Status/QueueStatusConnector.js @@ -0,0 +1,76 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { fetchQueueStatus } from 'Store/Actions/queueActions'; +import PageSidebarStatus from 'Components/Page/Sidebar/PageSidebarStatus'; + +function createMapStateToProps() { + return createSelector( + (state) => state.app, + (state) => state.queue.status, + (state) => state.queue.options.includeUnknownSeriesItems, + (app, status, includeUnknownSeriesItems) => { + const { + errors, + warnings, + unknownErrors, + unknownWarnings, + count, + totalCount + } = status.item; + + return { + isConnected: app.isConnected, + isReconnecting: app.isReconnecting, + isPopulated: status.isPopulated, + ...status.item, + count: includeUnknownSeriesItems ? totalCount : count, + errors: includeUnknownSeriesItems ? errors || unknownErrors : errors, + warnings: includeUnknownSeriesItems ? warnings || unknownWarnings : warnings + }; + } + ); +} + +const mapDispatchToProps = { + fetchQueueStatus +}; + +class QueueStatusConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + if (!this.props.isPopulated) { + this.props.fetchQueueStatus(); + } + } + + componentDidUpdate(prevProps) { + if (this.props.isConnected && prevProps.isReconnecting) { + this.props.fetchQueueStatus(); + } + } + + // + // Render + + render() { + return ( + + ); + } +} + +QueueStatusConnector.propTypes = { + isConnected: PropTypes.bool.isRequired, + isReconnecting: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + fetchQueueStatus: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(QueueStatusConnector); diff --git a/frontend/src/Activity/Queue/Status/createQueueStatusSelector.ts b/frontend/src/Activity/Queue/Status/createQueueStatusSelector.ts deleted file mode 100644 index 4fd37b28c..000000000 --- a/frontend/src/Activity/Queue/Status/createQueueStatusSelector.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; - -function createQueueStatusSelector() { - return createSelector( - (state: AppState) => state.queue.status.isPopulated, - (state: AppState) => state.queue.status.item, - (state: AppState) => state.queue.options.includeUnknownSeriesItems, - (isPopulated, status, includeUnknownSeriesItems) => { - const { - errors, - warnings, - unknownErrors, - unknownWarnings, - count, - totalCount, - } = status; - - return { - ...status, - isPopulated, - count: includeUnknownSeriesItems ? totalCount : count, - errors: includeUnknownSeriesItems ? errors || unknownErrors : errors, - warnings: includeUnknownSeriesItems - ? warnings || unknownWarnings - : warnings, - }; - } - ); -} - -export default createQueueStatusSelector; diff --git a/frontend/src/Activity/Queue/TimeleftCell.css.d.ts b/frontend/src/Activity/Queue/TimeleftCell.css.d.ts deleted file mode 100644 index f5c9402d1..000000000 --- a/frontend/src/Activity/Queue/TimeleftCell.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'timeleft': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Activity/Queue/TimeleftCell.js b/frontend/src/Activity/Queue/TimeleftCell.js new file mode 100644 index 000000000..f4356224b --- /dev/null +++ b/frontend/src/Activity/Queue/TimeleftCell.js @@ -0,0 +1,82 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import formatTime from 'Utilities/Date/formatTime'; +import formatTimeSpan from 'Utilities/Date/formatTimeSpan'; +import getRelativeDate from 'Utilities/Date/getRelativeDate'; +import formatBytes from 'Utilities/Number/formatBytes'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import styles from './TimeleftCell.css'; + +function TimeleftCell(props) { + const { + estimatedCompletionTime, + timeleft, + status, + size, + sizeleft, + showRelativeDates, + shortDateFormat, + timeFormat + } = props; + + if (status === 'delay') { + const date = getRelativeDate(estimatedCompletionTime, shortDateFormat, showRelativeDates); + const time = formatTime(estimatedCompletionTime, timeFormat, { includeMinuteZero: true }); + + return ( + + - + + ); + } + + if (status === 'downloadClientUnavailable') { + const date = getRelativeDate(estimatedCompletionTime, shortDateFormat, showRelativeDates); + const time = formatTime(estimatedCompletionTime, timeFormat, { includeMinuteZero: true }); + + return ( + + - + + ); + } + + if (!timeleft || status === 'completed' || status === 'failed') { + return ( + + - + + ); + } + + const totalSize = formatBytes(size); + const remainingSize = formatBytes(sizeleft); + + return ( + + {formatTimeSpan(timeleft)} + + ); +} + +TimeleftCell.propTypes = { + estimatedCompletionTime: PropTypes.string, + timeleft: PropTypes.string, + status: PropTypes.string.isRequired, + size: PropTypes.number.isRequired, + sizeleft: PropTypes.number.isRequired, + showRelativeDates: PropTypes.bool.isRequired, + shortDateFormat: PropTypes.string.isRequired, + timeFormat: PropTypes.string.isRequired +}; + +export default TimeleftCell; diff --git a/frontend/src/Activity/Queue/TimeleftCell.tsx b/frontend/src/Activity/Queue/TimeleftCell.tsx deleted file mode 100644 index 917a6ad0d..000000000 --- a/frontend/src/Activity/Queue/TimeleftCell.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import React from 'react'; -import Icon from 'Components/Icon'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import Tooltip from 'Components/Tooltip/Tooltip'; -import { icons, kinds, tooltipPositions } from 'Helpers/Props'; -import formatTime from 'Utilities/Date/formatTime'; -import formatTimeSpan from 'Utilities/Date/formatTimeSpan'; -import getRelativeDate from 'Utilities/Date/getRelativeDate'; -import formatBytes from 'Utilities/Number/formatBytes'; -import translate from 'Utilities/String/translate'; -import styles from './TimeleftCell.css'; - -interface TimeleftCellProps { - estimatedCompletionTime?: string; - timeleft?: string; - status: string; - size: number; - sizeleft: number; - showRelativeDates: boolean; - shortDateFormat: string; - timeFormat: string; -} - -function TimeleftCell(props: TimeleftCellProps) { - const { - estimatedCompletionTime, - timeleft, - status, - size, - sizeleft, - showRelativeDates, - shortDateFormat, - timeFormat, - } = props; - - if (status === 'delay') { - const date = getRelativeDate({ - date: estimatedCompletionTime, - shortDateFormat, - showRelativeDates, - }); - const time = formatTime(estimatedCompletionTime, timeFormat, { - includeMinuteZero: true, - }); - - return ( - - } - tooltip={translate('DelayingDownloadUntil', { date, time })} - kind={kinds.INVERSE} - position={tooltipPositions.TOP} - /> - - ); - } - - if (status === 'downloadClientUnavailable') { - const date = getRelativeDate({ - date: estimatedCompletionTime, - shortDateFormat, - showRelativeDates, - }); - const time = formatTime(estimatedCompletionTime, timeFormat, { - includeMinuteZero: true, - }); - - return ( - - } - tooltip={translate('RetryingDownloadOn', { date, time })} - kind={kinds.INVERSE} - position={tooltipPositions.TOP} - /> - - ); - } - - if (!timeleft || status === 'completed' || status === 'failed') { - return -; - } - - const totalSize = formatBytes(size); - const remainingSize = formatBytes(sizeleft); - - return ( - - {formatTimeSpan(timeleft)} - - ); -} - -export default TimeleftCell; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css index d41571320..fa28540cd 100644 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css @@ -6,12 +6,12 @@ .searchIconContainer { width: 58px; height: 46px; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-right: none; border-radius: 4px; border-top-right-radius: 0; border-bottom-right-radius: 0; - background-color: var(--searchIconContainerBackgroundColor); + background-color: #edf1f2; text-align: center; line-height: 46px; } @@ -25,7 +25,7 @@ } .clearLookupButton { - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-left: none; border-top-right-radius: 4px; border-bottom-right-radius: 4px; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css.d.ts b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css.d.ts deleted file mode 100644 index 176938a16..000000000 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'clearLookupButton': string; - 'helpText': string; - 'message': string; - 'noResults': string; - 'noSeriesText': string; - 'searchContainer': string; - 'searchIconContainer': string; - 'searchInput': string; - 'searchResults': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js index 18cbffddb..bb19ff311 100644 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js @@ -1,16 +1,14 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import Alert from 'Components/Alert'; -import TextInput from 'Components/Form/TextInput'; -import Icon from 'Components/Icon'; +import getErrorMessage from 'Utilities/Object/getErrorMessage'; +import { icons, kinds } from 'Helpers/Props'; import Button from 'Components/Link/Button'; import Link from 'Components/Link/Link'; +import Icon from 'Components/Icon'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import TextInput from 'Components/Form/TextInput'; import PageContent from 'Components/Page/PageContent'; import PageContentBody from 'Components/Page/PageContentBody'; -import { icons, kinds } from 'Helpers/Props'; -import getErrorMessage from 'Utilities/Object/getErrorMessage'; -import translate from 'Utilities/String/translate'; import AddNewSeriesSearchResultConnector from './AddNewSeriesSearchResultConnector'; import styles from './AddNewSeries.css'; @@ -68,12 +66,12 @@ class AddNewSeries extends Component { this.props.onClearSeriesLookup(); } }); - }; + } onClearSeriesLookupPress = () => { this.setState({ term: '' }); this.props.onClearSeriesLookup(); - }; + } // // Render @@ -89,7 +87,7 @@ class AddNewSeries extends Component { const isFetching = this.state.isFetching; return ( - +
@@ -128,10 +126,9 @@ class AddNewSeries extends Component { !isFetching && !!error ?
- {translate('AddNewSeriesError')} + Failed to load search results, please try again.
- - {getErrorMessage(error)} +
{getErrorMessage(error)}
: null } @@ -154,11 +151,11 @@ class AddNewSeries extends Component { { !isFetching && !error && !items.length && !!term &&
-
{translate('CouldNotFindResults', { term })}
-
{translate('SearchByTvdbId')}
+
Couldn't find any results for '{term}'
+
You can also search using TVDB ID of a show. eg. tvdb:71663
- {translate('WhyCantIFindMyShow')} + Why can't I find my show?
@@ -169,9 +166,9 @@ class AddNewSeries extends Component { null :
- {translate('AddNewSeriesHelpText')} + It's easy to add a new series, just start typing the name the series you want to add.
-
{translate('SearchByTvdbId')}
+
You can also search using TVDB ID of a show. eg. tvdb:71663
} @@ -179,14 +176,14 @@ class AddNewSeries extends Component { !term && !hasExistingSeries ?
- {translate('NoSeriesHaveBeenAdded')} + You haven't added any series yet, do you want to import some or all of your series first?
: diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js index a80a94fca..03283c256 100644 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js @@ -2,9 +2,9 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; -import { clearAddSeries, lookupSeries } from 'Store/Actions/addSeriesActions'; -import { fetchRootFolders } from 'Store/Actions/rootFolderActions'; import parseUrl from 'Utilities/String/parseUrl'; +import { lookupSeries, clearAddSeries } from 'Store/Actions/addSeriesActions'; +import { fetchRootFolders } from 'Store/Actions/rootFolderActions'; import AddNewSeries from './AddNewSeries'; function createMapStateToProps() { @@ -68,11 +68,11 @@ class AddNewSeriesConnector extends Component { this.props.lookupSeries({ term }); }, 300); } - }; + } onClearSeriesLookup = () => { this.props.clearAddSeries(); - }; + } // // Render diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css index 5da3d9b96..1ece5b8e9 100644 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css @@ -4,7 +4,7 @@ .year { margin-left: 5px; - color: var(--disabledColor); + color: $disabledColor; } .poster { @@ -57,6 +57,12 @@ composes: button from '~Components/Link/SpinnerButton.css'; } +.hideLanguageProfile { + composes: group from '~Components/Form/FormGroup.css'; + + display: none; +} + @media only screen and (max-width: $breakpointSmall) { .modalFooter { display: block; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css.d.ts b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css.d.ts deleted file mode 100644 index 554ff6ff3..000000000 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'addButton': string; - 'container': string; - 'info': string; - 'labelIcon': string; - 'modalFooter': string; - 'overview': string; - 'poster': string; - 'searchInput': string; - 'searchInputContainer': string; - 'searchLabel': string; - 'searchLabelContainer': string; - 'year': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js index 285c00ecb..36a76a2a8 100644 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js @@ -1,23 +1,22 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import SeriesMonitoringOptionsPopoverContent from 'AddSeries/SeriesMonitoringOptionsPopoverContent'; -import SeriesTypePopoverContent from 'AddSeries/SeriesTypePopoverContent'; -import CheckInput from 'Components/Form/CheckInput'; -import Form from 'Components/Form/Form'; -import FormGroup from 'Components/Form/FormGroup'; -import FormInputGroup from 'Components/Form/FormInputGroup'; -import FormLabel from 'Components/Form/FormLabel'; +import { icons, kinds, inputTypes, tooltipPositions } from 'Helpers/Props'; import Icon from 'Components/Icon'; import SpinnerButton from 'Components/Link/SpinnerButton'; -import ModalBody from 'Components/Modal/ModalBody'; +import Form from 'Components/Form/Form'; +import FormGroup from 'Components/Form/FormGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import CheckInput from 'Components/Form/CheckInput'; import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; import Popover from 'Components/Tooltip/Popover'; -import { icons, inputTypes, kinds, tooltipPositions } from 'Helpers/Props'; import SeriesPoster from 'Series/SeriesPoster'; import * as seriesTypes from 'Utilities/Series/seriesTypes'; -import translate from 'Utilities/String/translate'; +import SeriesMonitoringOptionsPopoverContent from 'AddSeries/SeriesMonitoringOptionsPopoverContent'; +import SeriesTypePopoverContent from 'AddSeries/SeriesTypePopoverContent'; import styles from './AddNewSeriesModalContent.css'; class AddNewSeriesModalContent extends Component { @@ -46,7 +45,11 @@ class AddNewSeriesModalContent extends Component { onQualityProfileIdChange = ({ value }) => { this.props.onInputChange({ name: 'qualityProfileId', value: parseInt(value) }); - }; + } + + onLanguageProfileIdChange = ({ value }) => { + this.props.onInputChange({ name: 'languageProfileId', value: parseInt(value) }); + } onAddSeriesPress = () => { const { @@ -56,7 +59,7 @@ class AddNewSeriesModalContent extends Component { this.props.onAddSeriesPress( seriesType ); - }; + } // // Render @@ -71,12 +74,14 @@ class AddNewSeriesModalContent extends Component { rootFolderPath, monitor, qualityProfileId, + languageProfileId, seriesType, seasonFolder, searchForMissingEpisodes, searchForCutoffUnmetEpisodes, folder, tags, + showLanguageProfile, isSmallScreen, isWindows, onModalClose, @@ -120,7 +125,7 @@ class AddNewSeriesModalContent extends Component {
- {translate('RootFolder')} + Root Folder @@ -141,7 +146,7 @@ class AddNewSeriesModalContent extends Component { - {translate('Monitor')} + Monitor } - title={translate('MonitoringOptions')} + title="Monitoring Options" body={} position={tooltipPositions.RIGHT} /> @@ -165,7 +170,7 @@ class AddNewSeriesModalContent extends Component { - {translate('QualityProfile')} + Quality Profile + + Language Profile + + + + - {translate('SeriesType')} + Series Type } - title={translate('SeriesTypes')} + title="Series Types" body={} position={tooltipPositions.RIGHT} /> @@ -198,12 +214,11 @@ class AddNewSeriesModalContent extends Component { onChange={onInputChange} {...seriesType} value={this.state.seriesType} - helpText={translate('SeriesTypesHelpText')} /> - {translate('SeasonFolder')} + Season Folder - {translate('Tags')} + Tags - { - originalLanguage?.name ? - : - null - } - { network ? : - null - } - - { - genres.length > 0 ? - : null } @@ -209,7 +168,7 @@ class AddNewSeriesSearchResult extends Component { kind={kinds.DANGER} size={sizes.LARGE} > - {translate('Ended')} + Ended : null } @@ -220,7 +179,7 @@ class AddNewSeriesSearchResult extends Component { kind={kinds.INFO} size={sizes.LARGE} > - {translate('Upcoming')} + Upcoming : null } @@ -229,8 +188,6 @@ class AddNewSeriesSearchResult extends Component {
{overview}
- -
@@ -256,8 +213,6 @@ AddNewSeriesSearchResult.propTypes = { titleSlug: PropTypes.string.isRequired, year: PropTypes.number.isRequired, network: PropTypes.string, - originalLanguage: PropTypes.object, - genres: PropTypes.arrayOf(PropTypes.string), status: PropTypes.string.isRequired, overview: PropTypes.string, statistics: PropTypes.object.isRequired, @@ -269,8 +224,4 @@ AddNewSeriesSearchResult.propTypes = { isSmallScreen: PropTypes.bool.isRequired }; -AddNewSeriesSearchResult.defaultProps = { - genres: [] -}; - export default AddNewSeriesSearchResult; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js index c1207c9ef..5ba942270 100644 --- a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js @@ -1,7 +1,7 @@ import { connect } from 'react-redux'; import { createSelector } from 'reselect'; -import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; import createExistingSeriesSelector from 'Store/Selectors/createExistingSeriesSelector'; +import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; import AddNewSeriesSearchResult from './AddNewSeriesSearchResult'; function createMapStateToProps() { diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js index eecdf8495..f6ba9836b 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js @@ -1,16 +1,13 @@ -import { reduce } from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import Alert from 'Components/Alert'; +import getSelectedIds from 'Utilities/Table/getSelectedIds'; +import selectAll from 'Utilities/Table/selectAll'; +import toggleSelected from 'Utilities/Table/toggleSelected'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; import PageContent from 'Components/Page/PageContent'; import PageContentBody from 'Components/Page/PageContentBody'; -import { kinds } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; -import selectAll from 'Utilities/Table/selectAll'; -import toggleSelected from 'Utilities/Table/toggleSelected'; -import ImportSeriesFooterConnector from './ImportSeriesFooterConnector'; import ImportSeriesTableConnector from './ImportSeriesTableConnector'; +import ImportSeriesFooterConnector from './ImportSeriesFooterConnector'; class ImportSeries extends Component { @@ -20,8 +17,6 @@ class ImportSeries extends Component { constructor(props, context) { super(props, context); - this.scrollerRef = React.createRef(); - this.state = { allSelected: false, allUnselected: false, @@ -30,33 +25,30 @@ class ImportSeries extends Component { }; } + // + // Control + + setScrollerRef = (ref) => { + this.setState({ scroller: ref }); + } + // // Listeners getSelectedIds = () => { - return reduce( - this.state.selectedState, - (result, value, id) => { - if (value) { - result.push(id); - } - - return result; - }, - [] - ); - }; + return getSelectedIds(this.state.selectedState, { parseIds: false }); + } onSelectAllChange = ({ value }) => { // Only select non-dupes this.setState(selectAll(this.state.selectedState, value)); - }; + } onSelectedChange = ({ id, value, shiftKey = false }) => { this.setState((state) => { return toggleSelected(state, this.props.items, id, value, shiftKey); }); - }; + } onRemoveSelectedStateItem = (id) => { this.setState((state) => { @@ -68,15 +60,19 @@ class ImportSeries extends Component { selectedState }; }); - }; + } onInputChange = ({ name, value }) => { this.props.onInputChange(this.getSelectedIds(), name, value); - }; + } onImportPress = () => { this.props.onImportPress(this.getSelectedIds()); - }; + } + + onScroll = ({ scrollTop }) => { + this.setState({ scrollTop }); + } // // Render @@ -88,27 +84,30 @@ class ImportSeries extends Component { rootFoldersFetching, rootFoldersPopulated, rootFoldersError, - unmappedFolders + unmappedFolders, + showLanguageProfile } = this.props; const { allSelected, allUnselected, - selectedState + selectedState, + scroller } = this.state; return ( - - + + { rootFoldersFetching ? : null } { !rootFoldersFetching && !!rootFoldersError ? - - {translate('RootFoldersLoadError')} - : +
Unable to load root folders
: null } @@ -117,9 +116,9 @@ class ImportSeries extends Component { !rootFoldersFetching && rootFoldersPopulated && !unmappedFolders.length ? - - {translate('AllSeriesInRootFolderHaveBeenImported', { path })} - : +
+ All series in {path} have been imported +
: null } @@ -128,14 +127,15 @@ class ImportSeries extends Component { !rootFoldersFetching && rootFoldersPopulated && !!unmappedFolders.length && - this.scrollerRef.current ? + scroller ? : @@ -168,6 +169,7 @@ ImportSeries.propTypes = { rootFoldersError: PropTypes.object, unmappedFolders: PropTypes.arrayOf(PropTypes.object), items: PropTypes.arrayOf(PropTypes.object), + showLanguageProfile: PropTypes.bool.isRequired, onInputChange: PropTypes.func.isRequired, onImportPress: PropTypes.func.isRequired }; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js index 50436ba88..71619acfa 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js @@ -3,10 +3,10 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; -import createRouteMatchShape from 'Helpers/Props/Shapes/createRouteMatchShape'; -import { setAddSeriesDefault } from 'Store/Actions/addSeriesActions'; -import { clearImportSeries, importSeries, setImportSeriesValue } from 'Store/Actions/importSeriesActions'; +import { setImportSeriesValue, importSeries, clearImportSeries } from 'Store/Actions/importSeriesActions'; import { fetchRootFolders } from 'Store/Actions/rootFolderActions'; +import { setAddSeriesDefault } from 'Store/Actions/addSeriesActions'; +import createRouteMatchShape from 'Helpers/Props/Shapes/createRouteMatchShape'; import ImportSeries from './ImportSeries'; function createMapStateToProps() { @@ -16,12 +16,14 @@ function createMapStateToProps() { (state) => state.addSeries, (state) => state.importSeries, (state) => state.settings.qualityProfiles, + (state) => state.settings.languageProfiles, ( match, rootFolders, addSeries, importSeriesState, - qualityProfiles + qualityProfiles, + languageProfiles ) => { const { isFetching: rootFoldersFetching, @@ -38,7 +40,10 @@ function createMapStateToProps() { rootFoldersPopulated, rootFoldersError, qualityProfiles: qualityProfiles.items, - defaultQualityProfileId: addSeries.defaults.qualityProfileId + languageProfiles: languageProfiles.items, + showLanguageProfile: languageProfiles.items.length > 1, + defaultQualityProfileId: addSeries.defaults.qualityProfileId, + defaultLanguageProfileId: addSeries.defaults.languageProfileId }; if (items.length) { @@ -73,7 +78,9 @@ class ImportSeriesConnector extends Component { const { rootFolderId, qualityProfiles, + languageProfiles, defaultQualityProfileId, + defaultLanguageProfileId, dispatchFetchRootFolders, dispatchSetAddSeriesDefault } = this.props; @@ -91,6 +98,14 @@ class ImportSeriesConnector extends Component { setDefaultPayload.qualityProfileId = qualityProfiles[0].id; } + if ( + !defaultLanguageProfileId || + !languageProfiles.some((p) => p.id === defaultLanguageProfileId) + ) { + setDefaults = true; + setDefaultPayload.languageProfileId = languageProfiles[0].id; + } + if (setDefaults) { dispatchSetAddSeriesDefault(setDefaultPayload); } @@ -112,11 +127,11 @@ class ImportSeriesConnector extends Component { [name]: value }); }); - }; + } onImportPress = (ids) => { this.props.dispatchImportSeries({ ids }); - }; + } // // Render @@ -142,7 +157,9 @@ ImportSeriesConnector.propTypes = { rootFoldersFetching: PropTypes.bool.isRequired, rootFoldersPopulated: PropTypes.bool.isRequired, qualityProfiles: PropTypes.arrayOf(PropTypes.object).isRequired, + languageProfiles: PropTypes.arrayOf(PropTypes.object).isRequired, defaultQualityProfileId: PropTypes.number.isRequired, + defaultLanguageProfileId: PropTypes.number.isRequired, dispatchSetImportSeriesValue: PropTypes.func.isRequired, dispatchImportSeries: PropTypes.func.isRequired, dispatchClearImportSeries: PropTypes.func.isRequired, diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css index d0c6e98ae..9bfb5a493 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css @@ -4,7 +4,7 @@ } .label { - margin-bottom: 10px; + margin-bottom: 3px; font-weight: bold; } @@ -35,17 +35,3 @@ .importError { margin-left: 10px; } - -@media only screen and (max-width: $breakpointSmall) { - .inputContainer { - margin-top: 10px; - - &:first-child { - margin-top: 0; - } - } - - .importButtonContainer { - margin-top: 10px; - } -} diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css.d.ts deleted file mode 100644 index d107ffc8d..000000000 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'importButton': string; - 'importButtonContainer': string; - 'importError': string; - 'inputContainer': string; - 'label': string; - 'loading': string; - 'loadingButton': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js index a2e4cffff..14adccb00 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js @@ -1,16 +1,15 @@ import _ from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import CheckInput from 'Components/Form/CheckInput'; -import FormInputGroup from 'Components/Form/FormInputGroup'; +import { icons, inputTypes, kinds, tooltipPositions } from 'Helpers/Props'; import Icon from 'Components/Icon'; import Button from 'Components/Link/Button'; import SpinnerButton from 'Components/Link/SpinnerButton'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import CheckInput from 'Components/Form/CheckInput'; +import FormInputGroup from 'Components/Form/FormInputGroup'; import PageContentFooter from 'Components/Page/PageContentFooter'; import Popover from 'Components/Tooltip/Popover'; -import { icons, inputTypes, kinds, tooltipPositions } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; import styles from './ImportSeriesFooter.css'; const MIXED = 'mixed'; @@ -26,6 +25,7 @@ class ImportSeriesFooter extends Component { const { defaultMonitor, defaultQualityProfileId, + defaultLanguageProfileId, defaultSeasonFolder, defaultSeriesType } = props; @@ -33,6 +33,7 @@ class ImportSeriesFooter extends Component { this.state = { monitor: defaultMonitor, qualityProfileId: defaultQualityProfileId, + languageProfileId: defaultLanguageProfileId, seriesType: defaultSeriesType, seasonFolder: defaultSeasonFolder }; @@ -42,10 +43,12 @@ class ImportSeriesFooter extends Component { const { defaultMonitor, defaultQualityProfileId, + defaultLanguageProfileId, defaultSeriesType, defaultSeasonFolder, isMonitorMixed, isQualityProfileIdMixed, + isLanguageProfileIdMixed, isSeriesTypeMixed, isSeasonFolderMixed } = this.props; @@ -53,6 +56,7 @@ class ImportSeriesFooter extends Component { const { monitor, qualityProfileId, + languageProfileId, seriesType, seasonFolder } = this.state; @@ -71,6 +75,12 @@ class ImportSeriesFooter extends Component { newState.qualityProfileId = defaultQualityProfileId; } + if (isLanguageProfileIdMixed && languageProfileId !== MIXED) { + newState.languageProfileId = MIXED; + } else if (!isLanguageProfileIdMixed && languageProfileId !== defaultLanguageProfileId) { + newState.languageProfileId = defaultLanguageProfileId; + } + if (isSeriesTypeMixed && seriesType !== MIXED) { newState.seriesType = MIXED; } else if (!isSeriesTypeMixed && seriesType !== defaultSeriesType) { @@ -94,7 +104,7 @@ class ImportSeriesFooter extends Component { onInputChange = ({ name, value }) => { this.setState({ [name]: value }); this.props.onInputChange({ name, value }); - }; + } // // Render @@ -106,8 +116,10 @@ class ImportSeriesFooter extends Component { isLookingUpSeries, isMonitorMixed, isQualityProfileIdMixed, + isLanguageProfileIdMixed, isSeriesTypeMixed, hasUnsearchedItems, + showLanguageProfile, importError, onImportPress, onLookupPress, @@ -117,6 +129,7 @@ class ImportSeriesFooter extends Component { const { monitor, qualityProfileId, + languageProfileId, seriesType, seasonFolder } = this.state; @@ -125,7 +138,7 @@ class ImportSeriesFooter extends Component {
- {translate('Monitor')} + Monitor
- {translate('QualityProfile')} + Quality Profile
+ { + showLanguageProfile && +
+
+ Language Profile +
+ + +
+ } +
- {translate('SeriesType')} + Series Type
- {translate('SeasonFolder')} + Season Folder
- {translate('ImportCountSeries', { selectedCount })} + Import {selectedCount} Series { @@ -204,7 +235,7 @@ class ImportSeriesFooter extends Component { kind={kinds.WARNING} onPress={onCancelLookupPress} > - {translate('CancelProcessing')} + Cancel Processing : null } @@ -216,7 +247,7 @@ class ImportSeriesFooter extends Component { kind={kinds.SUCCESS} onPress={onLookupPress} > - {translate('StartProcessing')} + Start Processing : null } @@ -232,7 +263,7 @@ class ImportSeriesFooter extends Component { { isLookingUpSeries ? - translate('ProcessingFolders') : + 'Processing Folders' : null } @@ -246,23 +277,17 @@ class ImportSeriesFooter extends Component { kind={kinds.WARNING} /> } - title={translate('ImportErrors')} + title="Import Errors" body={
    { - Array.isArray(importError.responseJSON) ? - importError.responseJSON.map((error, index) => { - return ( -
  • - {error.errorMessage} -
  • - ); - }) : -
  • - { - JSON.stringify(importError.responseJSON) - } -
  • + importError.responseJSON.map((error, index) => { + return ( +
  • + {error.errorMessage} +
  • + ); + }) }
} @@ -283,13 +308,16 @@ ImportSeriesFooter.propTypes = { isLookingUpSeries: PropTypes.bool.isRequired, defaultMonitor: PropTypes.string.isRequired, defaultQualityProfileId: PropTypes.number, + defaultLanguageProfileId: PropTypes.number, defaultSeriesType: PropTypes.string.isRequired, defaultSeasonFolder: PropTypes.bool.isRequired, isMonitorMixed: PropTypes.bool.isRequired, isQualityProfileIdMixed: PropTypes.bool.isRequired, + isLanguageProfileIdMixed: PropTypes.bool.isRequired, isSeriesTypeMixed: PropTypes.bool.isRequired, isSeasonFolderMixed: PropTypes.bool.isRequired, hasUnsearchedItems: PropTypes.bool.isRequired, + showLanguageProfile: PropTypes.bool.isRequired, importError: PropTypes.object, onInputChange: PropTypes.func.isRequired, onImportPress: PropTypes.func.isRequired, diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js index 12a90aae7..d8f4739fa 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; -import { cancelLookupSeries, lookupUnsearchedSeries } from 'Store/Actions/importSeriesActions'; +import { lookupUnsearchedSeries, cancelLookupSeries } from 'Store/Actions/importSeriesActions'; import ImportSeriesFooter from './ImportSeriesFooter'; function isMixed(items, selectedIds, defaultValue, key) { @@ -19,6 +19,7 @@ function createMapStateToProps() { const { monitor: defaultMonitor, qualityProfileId: defaultQualityProfileId, + languageProfileId: defaultLanguageProfileId, seriesType: defaultSeriesType, seasonFolder: defaultSeasonFolder } = addSeries.defaults; @@ -32,6 +33,7 @@ function createMapStateToProps() { const isMonitorMixed = isMixed(items, selectedIds, defaultMonitor, 'monitor'); const isQualityProfileIdMixed = isMixed(items, selectedIds, defaultQualityProfileId, 'qualityProfileId'); + const isLanguageProfileIdMixed = isMixed(items, selectedIds, defaultLanguageProfileId, 'languageProfileId'); const isSeriesTypeMixed = isMixed(items, selectedIds, defaultSeriesType, 'seriesType'); const isSeasonFolderMixed = isMixed(items, selectedIds, defaultSeasonFolder, 'seasonFolder'); const hasUnsearchedItems = !isLookingUpSeries && items.some((item) => !item.isPopulated); @@ -42,10 +44,12 @@ function createMapStateToProps() { isImporting, defaultMonitor, defaultQualityProfileId, + defaultLanguageProfileId, defaultSeriesType, defaultSeasonFolder, isMonitorMixed, isQualityProfileIdMixed, + isLanguageProfileIdMixed, isSeriesTypeMixed, isSeasonFolderMixed, importError, diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css index df5214bdd..00284e107 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css @@ -11,7 +11,8 @@ min-width: 185px; } -.qualityProfile { +.qualityProfile, +.languageProfile { composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; flex: 0 1 250px; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css.d.ts deleted file mode 100644 index ecf1347f5..000000000 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'detailsIcon': string; - 'folder': string; - 'monitor': string; - 'qualityProfile': string; - 'seasonFolder': string; - 'series': string; - 'seriesType': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js index 6f44b9754..fe60a4d5d 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js @@ -1,18 +1,18 @@ import PropTypes from 'prop-types'; import React from 'react'; -import SeriesMonitoringOptionsPopoverContent from 'AddSeries/SeriesMonitoringOptionsPopoverContent'; -import SeriesTypePopoverContent from 'AddSeries/SeriesTypePopoverContent'; +import { icons, tooltipPositions } from 'Helpers/Props'; import Icon from 'Components/Icon'; +import Popover from 'Components/Tooltip/Popover'; import VirtualTableHeader from 'Components/Table/VirtualTableHeader'; import VirtualTableHeaderCell from 'Components/Table/VirtualTableHeaderCell'; import VirtualTableSelectAllHeaderCell from 'Components/Table/VirtualTableSelectAllHeaderCell'; -import Popover from 'Components/Tooltip/Popover'; -import { icons, tooltipPositions } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; +import SeriesMonitoringOptionsPopoverContent from 'AddSeries/SeriesMonitoringOptionsPopoverContent'; +import SeriesTypePopoverContent from 'AddSeries/SeriesTypePopoverContent'; import styles from './ImportSeriesHeader.css'; function ImportSeriesHeader(props) { const { + showLanguageProfile, allSelected, allUnselected, onSelectAllChange @@ -30,14 +30,14 @@ function ImportSeriesHeader(props) { className={styles.folder} name="folder" > - {translate('Folder')} + Folder - {translate('Monitor')} + Monitor } - title={translate('MonitoringOptions')} + title="Monitoring Options" body={} position={tooltipPositions.RIGHT} /> @@ -56,14 +56,24 @@ function ImportSeriesHeader(props) { className={styles.qualityProfile} name="qualityProfileId" > - {translate('QualityProfile')} + Quality Profile + { + showLanguageProfile && + + Language Profile + + } + - {translate('SeriesType')} + Series Type } - title={translate('SeriesType')} + title="Series Type" body={} position={tooltipPositions.RIGHT} /> @@ -82,20 +92,21 @@ function ImportSeriesHeader(props) { className={styles.seasonFolder} name="seasonFolder" > - {translate('SeasonFolder')} + Season Folder - {translate('Series')} + Series ); } ImportSeriesHeader.propTypes = { + showLanguageProfile: PropTypes.bool.isRequired, allSelected: PropTypes.bool.isRequired, allUnselected: PropTypes.bool.isRequired, onSelectAllChange: PropTypes.func.isRequired diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css index c75b47dba..fc9af049a 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css @@ -16,7 +16,8 @@ min-width: 185px; } -.qualityProfile { +.qualityProfile, +.languageProfile { composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; flex: 0 1 250px; @@ -43,3 +44,9 @@ flex: 0 1 400px; min-width: 300px; } + +.hideLanguageProfile { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + display: none; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css.d.ts deleted file mode 100644 index 4339b9d05..000000000 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'folder': string; - 'monitor': string; - 'qualityProfile': string; - 'seasonFolder': string; - 'selectInput': string; - 'series': string; - 'seriesType': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js index 7777c768f..293277ffd 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js @@ -1,22 +1,23 @@ import PropTypes from 'prop-types'; import React from 'react'; +import { inputTypes } from 'Helpers/Props'; import FormInputGroup from 'Components/Form/FormInputGroup'; import VirtualTableRowCell from 'Components/Table/Cells/VirtualTableRowCell'; import VirtualTableSelectCell from 'Components/Table/Cells/VirtualTableSelectCell'; -import { inputTypes } from 'Helpers/Props'; import ImportSeriesSelectSeriesConnector from './SelectSeries/ImportSeriesSelectSeriesConnector'; import styles from './ImportSeriesRow.css'; function ImportSeriesRow(props) { const { id, - relativePath, monitor, qualityProfileId, + languageProfileId, seasonFolder, seriesType, selectedSeries, isExistingSeries, + showLanguageProfile, isSelected, onSelectedChange, onInputChange @@ -33,7 +34,7 @@ function ImportSeriesRow(props) { /> - {relativePath} + {id} @@ -54,6 +55,17 @@ function ImportSeriesRow(props) { /> + + + + { const id = unmappedFolder.name; - onSeriesLookup(id, unmappedFolder.path, unmappedFolder.relativePath); + onSeriesLookup(id, unmappedFolder.path); onSetImportSeriesValue({ id, @@ -104,6 +106,7 @@ class ImportSeriesTable extends Component { rootFolderId, items, selectedState, + showLanguageProfile, onSelectedChange } = this.props; @@ -117,13 +120,14 @@ class ImportSeriesTable extends Component { ); - }; + } // // Render @@ -135,6 +139,7 @@ class ImportSeriesTable extends Component { allUnselected, isSmallScreen, scroller, + showLanguageProfile, selectedState, onSelectAllChange } = this.props; @@ -153,6 +158,7 @@ class ImportSeriesTable extends Component { rowRenderer={this.rowRenderer} header={ onPress(tvdbId), [tvdbId, onPress]); + // + // Listeners - return ( -
+ onPress = () => { + this.props.onPress(this.props.tvdbId); + } + + // + // Render + + render() { + const { + title, + year, + network, + isExistingSeries + } = this.props; + + return ( - - - - -
- ); + ); + } } ImportSeriesSearchResult.propTypes = { diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css index 89b03301b..6bdfd093e 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css @@ -6,10 +6,10 @@ padding: 6px 16px; width: 100%; height: 35px; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-radius: 4px; - background-color: var(--inputBackgroundColor); - box-shadow: inset 0 1px 1px var(--inputBoxShadowColor); + background-color: $white; + box-shadow: inset 0 1px 1px $inputBoxShadowColor; } .loading { @@ -33,15 +33,15 @@ .contentContainer { z-index: $popperZIndex; margin-top: 4px; - /* 400px container width with 8px padding on each side */ + /* 400px container witdh with 8px padding on each side */ width: 384px; } .content { padding: 4px; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-radius: 4px; - background-color: var(--inputBackgroundColor); + background-color: $white; } .searchContainer { @@ -50,12 +50,12 @@ .searchIconContainer { width: 58px; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-right: none; border-radius: 4px; border-top-right-radius: 0; border-bottom-right-radius: 0; - background-color: var(--searchIconContainerBackgroundColor); + background-color: #edf1f2; text-align: center; line-height: 33px; } diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css.d.ts deleted file mode 100644 index d5aa6bc94..000000000 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'button': string; - 'content': string; - 'contentContainer': string; - 'dropdownArrowContainer': string; - 'existing': string; - 'loading': string; - 'results': string; - 'searchContainer': string; - 'searchIconContainer': string; - 'searchInput': string; - 'warningIcon': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js index 1257be9b1..c51a97a5e 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js @@ -1,15 +1,14 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Manager, Popper, Reference } from 'react-popper'; -import FormInputButton from 'Components/Form/FormInputButton'; -import TextInput from 'Components/Form/TextInput'; +import getUniqueElememtId from 'Utilities/getUniqueElementId'; +import { icons, kinds } from 'Helpers/Props'; import Icon from 'Components/Icon'; +import Portal from 'Components/Portal'; +import FormInputButton from 'Components/Form/FormInputButton'; import Link from 'Components/Link/Link'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import Portal from 'Components/Portal'; -import { icons, kinds } from 'Helpers/Props'; -import getUniqueElementId from 'Utilities/getUniqueElementId'; -import translate from 'Utilities/String/translate'; +import TextInput from 'Components/Form/TextInput'; import ImportSeriesSearchResultConnector from './ImportSeriesSearchResultConnector'; import ImportSeriesTitle from './ImportSeriesTitle'; import styles from './ImportSeriesSelectSeries.css'; @@ -24,8 +23,8 @@ class ImportSeriesSelectSeries extends Component { this._seriesLookupTimeout = null; this._scheduleUpdate = null; - this._buttonId = getUniqueElementId(); - this._contentId = getUniqueElementId(); + this._buttonId = getUniqueElememtId(); + this._contentId = getUniqueElememtId(); this.state = { term: props.id, @@ -69,7 +68,7 @@ class ImportSeriesSelectSeries extends Component { this.setState({ isOpen: false }); this._removeListener(); } - }; + } onPress = () => { if (this.state.isOpen) { @@ -79,7 +78,7 @@ class ImportSeriesSelectSeries extends Component { } this.setState({ isOpen: !this.state.isOpen }); - }; + } onSearchInputChange = ({ value }) => { if (this._seriesLookupTimeout) { @@ -91,17 +90,17 @@ class ImportSeriesSelectSeries extends Component { this.props.onSearchInputChange(value); }, 200); }); - }; + } onRefreshPress = () => { this.props.onSearchInputChange(this.state.term); - }; + } onSeriesSelect = (tvdbId) => { this.setState({ isOpen: false }); this.props.onSeriesSelect(tvdbId); - }; + } // // Render @@ -175,7 +174,7 @@ class ImportSeriesSelectSeries extends Component { kind={kinds.WARNING} /> - {translate('NoMatchFound')} + No match found!
: null } @@ -190,7 +189,7 @@ class ImportSeriesSelectSeries extends Component { kind={kinds.WARNING} /> - {translate('SearchFailedError')} + Search failed, please try again later. : null } diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js index 935c95f4e..0222d88e4 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js @@ -36,7 +36,7 @@ class ImportSeriesSelectSeriesConnector extends Component { term, topOfQueue: true }); - }; + } onSeriesSelect = (tvdbId) => { const { @@ -58,7 +58,7 @@ class ImportSeriesSelectSeriesConnector extends Component { value: selectedSeries.seriesType }); } - }; + } // // Render diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css index ed00effa7..222623179 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css @@ -12,7 +12,7 @@ .year { margin-right: 5px; margin-left: 5px; - color: var(--disabledColor); + color: $disabledColor; } .existing { diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css.d.ts deleted file mode 100644 index 1816cf49e..000000000 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'existing': string; - 'title': string; - 'titleContainer': string; - 'year': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js index c7ea7b961..5dfabe6f4 100644 --- a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js @@ -1,8 +1,7 @@ import PropTypes from 'prop-types'; import React from 'react'; -import Label from 'Components/Label'; import { kinds } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; +import Label from 'Components/Label'; import styles from './ImportSeriesTitle.css'; function ImportSeriesTitle(props) { @@ -21,27 +20,24 @@ function ImportSeriesTitle(props) { { !title.contains(year) && - year > 0 ? + year > 0 && ({year}) - : - null + } { - network ? - : - null + !!network && + } { - isExistingSeries ? + isExistingSeries && : - null + Existing + } ); diff --git a/frontend/src/AddSeries/ImportSeries/ImportSeries.js b/frontend/src/AddSeries/ImportSeries/ImportSeries.js index 8f9fed325..15362a7d0 100644 --- a/frontend/src/AddSeries/ImportSeries/ImportSeries.js +++ b/frontend/src/AddSeries/ImportSeries/ImportSeries.js @@ -1,8 +1,8 @@ import React, { Component } from 'react'; import { Route } from 'react-router-dom'; -import ImportSeriesConnector from 'AddSeries/ImportSeries/Import/ImportSeriesConnector'; -import ImportSeriesSelectFolderConnector from 'AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector'; import Switch from 'Components/Router/Switch'; +import ImportSeriesSelectFolderConnector from 'AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector'; +import ImportSeriesConnector from 'AddSeries/ImportSeries/Import/ImportSeriesConnector'; class ImportSeries extends Component { diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css.d.ts b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css.d.ts deleted file mode 100644 index e9d3bbc92..000000000 --- a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'addErrorAlert': string; - 'code': string; - 'header': string; - 'importButtonIcon': string; - 'recentFolders': string; - 'startImport': string; - 'tip': string; - 'tips': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js index 24fcff3dc..e88bd345e 100644 --- a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js +++ b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js @@ -1,17 +1,15 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import Alert from 'Components/Alert'; -import FieldSet from 'Components/FieldSet'; -import FileBrowserModal from 'Components/FileBrowser/FileBrowserModal'; -import Icon from 'Components/Icon'; +import { icons, kinds, sizes } from 'Helpers/Props'; import Button from 'Components/Link/Button'; +import Alert from 'Components/Alert'; +import Icon from 'Components/Icon'; +import FieldSet from 'Components/FieldSet'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import InlineMarkdown from 'Components/Markdown/InlineMarkdown'; +import FileBrowserModal from 'Components/FileBrowser/FileBrowserModal'; import PageContent from 'Components/Page/PageContent'; import PageContentBody from 'Components/Page/PageContentBody'; -import { icons, kinds, sizes } from 'Helpers/Props'; import RootFolders from 'RootFolder/RootFolders'; -import translate from 'Utilities/String/translate'; import styles from './ImportSeriesSelectFolder.css'; class ImportSeriesSelectFolder extends Component { @@ -32,15 +30,15 @@ class ImportSeriesSelectFolder extends Component { onAddNewRootFolderPress = () => { this.setState({ isAddNewRootFolderModalOpen: true }); - }; + } onNewRootFolderSelect = ({ value }) => { this.props.onNewRootFolderSelect(value); - }; + } onAddRootFolderModalClose = () => { this.setState({ isAddNewRootFolderModalOpen: false }); - }; + } // // Render @@ -57,11 +55,9 @@ class ImportSeriesSelectFolder extends Component { } = this.props; const hasRootFolders = items.length > 0; - const goodFolderExample = (isWindows) ? 'C:\\tv shows' : '/tv shows'; - const badFolderExample = (isWindows) ? 'C:\\tv shows\\the simpsons' : '/tv shows/the simpsons'; return ( - + { isFetching && !isPopulated ? @@ -71,7 +67,7 @@ class ImportSeriesSelectFolder extends Component { { !isFetching && error ? - {translate('RootFoldersLoadError')} : +
Unable to load root folders
: null } @@ -79,20 +75,20 @@ class ImportSeriesSelectFolder extends Component { !error && isPopulated &&
- {translate('LibraryImportSeriesHeader')} + Import series you already have
- {translate('LibraryImportTips')} + Some tips to ensure the import goes smoothly:
  • - + Make sure that your files include the quality in their filenames. eg. episode.s02e15.bluray.mkv
  • - + Point Sonarr to the folder containing all of your tv shows, not a specific one. eg. "{isWindows ? 'C:\\tv shows' : '/tv shows'}" and not "{isWindows ? 'C:\\tv shows\\the simpsons' : '/tv shows/the simpsons'}" Additionally, each series must be in its own folder within the root/library folder.
  • - {translate('LibraryImportTipsDontUseDownloadsFolder')} + Do not use for importing downloads from your download client, this is only for existing organized libraries, not unsorted files.
@@ -100,7 +96,7 @@ class ImportSeriesSelectFolder extends Component { { hasRootFolders ?
-
+
- {translate('AddRootFolderError')} + Unable to add root folder
    { - Array.isArray(saveError.responseJSON) ? - saveError.responseJSON.map((e, index) => { - return ( -
  • - {e.errorMessage} -
  • - ); - }) : -
  • - { - JSON.stringify(saveError.responseJSON) - } -
  • + saveError.responseJSON.map((e, index) => { + return ( +
  • + {e.errorMessage} +
  • + ); + }) }
: @@ -153,8 +143,8 @@ class ImportSeriesSelectFolder extends Component { /> { hasRootFolders ? - translate('ChooseAnotherFolder') : - translate('StartImport') + 'Choose another folder' : + 'Start Import' }
diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js index 1df231f4e..5ef79ec4e 100644 --- a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js +++ b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js @@ -1,17 +1,16 @@ -import { push } from 'connected-react-router'; import _ from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; -import { addRootFolder, fetchRootFolders } from 'Store/Actions/rootFolderActions'; -import createRootFoldersSelector from 'Store/Selectors/createRootFoldersSelector'; +import { push } from 'connected-react-router'; import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector'; +import { fetchRootFolders, addRootFolder } from 'Store/Actions/rootFolderActions'; import ImportSeriesSelectFolder from './ImportSeriesSelectFolder'; function createMapStateToProps() { return createSelector( - createRootFoldersSelector(), + (state) => state.rootFolders, createSystemStatusSelector(), (rootFolders, systemStatus) => { return { @@ -58,7 +57,7 @@ class ImportSeriesSelectFolderConnector extends Component { onNewRootFolderSelect = (path) => { this.props.addRootFolder({ path }); - }; + } // // Render diff --git a/frontend/src/AddSeries/SeriesMonitorNewItemsOptionsPopoverContent.js b/frontend/src/AddSeries/SeriesMonitorNewItemsOptionsPopoverContent.js deleted file mode 100644 index c70ec0dec..000000000 --- a/frontend/src/AddSeries/SeriesMonitorNewItemsOptionsPopoverContent.js +++ /dev/null @@ -1,22 +0,0 @@ -import React from 'react'; -import DescriptionList from 'Components/DescriptionList/DescriptionList'; -import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; -import translate from 'Utilities/String/translate'; - -function SeriesMonitorNewItemsOptionsPopoverContent() { - return ( - - - - - - ); -} - -export default SeriesMonitorNewItemsOptionsPopoverContent; diff --git a/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js b/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js index 21289fcb8..e889fbb09 100644 --- a/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js +++ b/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js @@ -1,64 +1,43 @@ import React from 'react'; import DescriptionList from 'Components/DescriptionList/DescriptionList'; import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; -import translate from 'Utilities/String/translate'; function SeriesMonitoringOptionsPopoverContent() { return ( - - - - - - - - ); diff --git a/frontend/src/AddSeries/SeriesTypePopoverContent.js b/frontend/src/AddSeries/SeriesTypePopoverContent.js index 9771bd8db..e57d49a9e 100644 --- a/frontend/src/AddSeries/SeriesTypePopoverContent.js +++ b/frontend/src/AddSeries/SeriesTypePopoverContent.js @@ -1,24 +1,23 @@ import React from 'react'; import DescriptionList from 'Components/DescriptionList/DescriptionList'; import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; -import translate from 'Utilities/String/translate'; function SeriesTypePopoverContent() { return ( ); diff --git a/frontend/src/App/App.js b/frontend/src/App/App.js new file mode 100644 index 000000000..2baaf9fe9 --- /dev/null +++ b/frontend/src/App/App.js @@ -0,0 +1,28 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import DocumentTitle from 'react-document-title'; +import { Provider } from 'react-redux'; +import { ConnectedRouter } from 'connected-react-router'; +import PageConnector from 'Components/Page/PageConnector'; +import AppRoutes from './AppRoutes'; + +function App({ store, history }) { + return ( + + + + + + + + + + ); +} + +App.propTypes = { + store: PropTypes.object.isRequired, + history: PropTypes.object.isRequired +}; + +export default App; diff --git a/frontend/src/App/App.tsx b/frontend/src/App/App.tsx deleted file mode 100644 index b71199bb3..000000000 --- a/frontend/src/App/App.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { ConnectedRouter, ConnectedRouterProps } from 'connected-react-router'; -import React from 'react'; -import DocumentTitle from 'react-document-title'; -import { Provider } from 'react-redux'; -import { Store } from 'redux'; -import PageConnector from 'Components/Page/PageConnector'; -import ApplyTheme from './ApplyTheme'; -import AppRoutes from './AppRoutes'; - -interface AppProps { - store: Store; - history: ConnectedRouterProps['history']; -} - -const queryClient = new QueryClient(); - -function App({ store, history }: AppProps) { - return ( - - - - - - - - - - - - - ); -} - -export default App; diff --git a/frontend/src/App/AppRoutes.js b/frontend/src/App/AppRoutes.js new file mode 100644 index 000000000..102681071 --- /dev/null +++ b/frontend/src/App/AppRoutes.js @@ -0,0 +1,254 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { Route, Redirect } from 'react-router-dom'; +import getPathWithUrlBase from 'Utilities/getPathWithUrlBase'; +import NotFound from 'Components/NotFound'; +import Switch from 'Components/Router/Switch'; +import SeriesIndexConnector from 'Series/Index/SeriesIndexConnector'; +import AddNewSeriesConnector from 'AddSeries/AddNewSeries/AddNewSeriesConnector'; +import ImportSeries from 'AddSeries/ImportSeries/ImportSeries'; +import SeriesEditorConnector from 'Series/Editor/SeriesEditorConnector'; +import SeasonPassConnector from 'SeasonPass/SeasonPassConnector'; +import SeriesDetailsPageConnector from 'Series/Details/SeriesDetailsPageConnector'; +import CalendarPageConnector from 'Calendar/CalendarPageConnector'; +import HistoryConnector from 'Activity/History/HistoryConnector'; +import QueueConnector from 'Activity/Queue/QueueConnector'; +import BlocklistConnector from 'Activity/Blocklist/BlocklistConnector'; +import MissingConnector from 'Wanted/Missing/MissingConnector'; +import CutoffUnmetConnector from 'Wanted/CutoffUnmet/CutoffUnmetConnector'; +import Settings from 'Settings/Settings'; +import MediaManagementConnector from 'Settings/MediaManagement/MediaManagementConnector'; +import Profiles from 'Settings/Profiles/Profiles'; +import Quality from 'Settings/Quality/Quality'; +import IndexerSettingsConnector from 'Settings/Indexers/IndexerSettingsConnector'; +import ImportListSettingsConnector from 'Settings/ImportLists/ImportListSettingsConnector'; +import DownloadClientSettingsConnector from 'Settings/DownloadClients/DownloadClientSettingsConnector'; +import NotificationSettings from 'Settings/Notifications/NotificationSettings'; +import MetadataSettings from 'Settings/Metadata/MetadataSettings'; +import TagSettings from 'Settings/Tags/TagSettings'; +import GeneralSettingsConnector from 'Settings/General/GeneralSettingsConnector'; +import UISettingsConnector from 'Settings/UI/UISettingsConnector'; +import Status from 'System/Status/Status'; +import Tasks from 'System/Tasks/Tasks'; +import BackupsConnector from 'System/Backup/BackupsConnector'; +import UpdatesConnector from 'System/Updates/UpdatesConnector'; +import LogsTableConnector from 'System/Events/LogsTableConnector'; +import Logs from 'System/Logs/Logs'; + +function AppRoutes(props) { + const { + app + } = props; + + return ( + + {/* + Series + */} + + + + { + window.Sonarr.urlBase && + { + return ( + + ); + }} + /> + } + + + + + + + + + + + + {/* + Calendar + */} + + + + {/* + Activity + */} + + + + + + + + {/* + Wanted + */} + + + + + + {/* + Settings + */} + + + + + + + + + + + + + + + + + + + + + + + + + + {/* + System + */} + + + + + + + + + + + + + + {/* + Not Found + */} + + + + ); +} + +AppRoutes.propTypes = { + app: PropTypes.func.isRequired +}; + +export default AppRoutes; diff --git a/frontend/src/App/AppRoutes.tsx b/frontend/src/App/AppRoutes.tsx deleted file mode 100644 index fbe4a15bb..000000000 --- a/frontend/src/App/AppRoutes.tsx +++ /dev/null @@ -1,167 +0,0 @@ -import React from 'react'; -import { Redirect, Route } from 'react-router-dom'; -import Blocklist from 'Activity/Blocklist/Blocklist'; -import History from 'Activity/History/History'; -import Queue from 'Activity/Queue/Queue'; -import AddNewSeriesConnector from 'AddSeries/AddNewSeries/AddNewSeriesConnector'; -import ImportSeries from 'AddSeries/ImportSeries/ImportSeries'; -import CalendarPage from 'Calendar/CalendarPage'; -import NotFound from 'Components/NotFound'; -import Switch from 'Components/Router/Switch'; -import SeriesDetailsPageConnector from 'Series/Details/SeriesDetailsPageConnector'; -import SeriesIndex from 'Series/Index/SeriesIndex'; -import CustomFormatSettingsPage from 'Settings/CustomFormats/CustomFormatSettingsPage'; -import DownloadClientSettingsConnector from 'Settings/DownloadClients/DownloadClientSettingsConnector'; -import GeneralSettingsConnector from 'Settings/General/GeneralSettingsConnector'; -import ImportListSettingsConnector from 'Settings/ImportLists/ImportListSettingsConnector'; -import IndexerSettingsConnector from 'Settings/Indexers/IndexerSettingsConnector'; -import MediaManagementConnector from 'Settings/MediaManagement/MediaManagementConnector'; -import MetadataSettings from 'Settings/Metadata/MetadataSettings'; -import MetadataSourceSettings from 'Settings/MetadataSource/MetadataSourceSettings'; -import NotificationSettings from 'Settings/Notifications/NotificationSettings'; -import Profiles from 'Settings/Profiles/Profiles'; -import QualityConnector from 'Settings/Quality/QualityConnector'; -import Settings from 'Settings/Settings'; -import TagSettings from 'Settings/Tags/TagSettings'; -import UISettingsConnector from 'Settings/UI/UISettingsConnector'; -import BackupsConnector from 'System/Backup/BackupsConnector'; -import LogsTableConnector from 'System/Events/LogsTableConnector'; -import Logs from 'System/Logs/Logs'; -import Status from 'System/Status/Status'; -import Tasks from 'System/Tasks/Tasks'; -import Updates from 'System/Updates/Updates'; -import getPathWithUrlBase from 'Utilities/getPathWithUrlBase'; -import CutoffUnmetConnector from 'Wanted/CutoffUnmet/CutoffUnmetConnector'; -import MissingConnector from 'Wanted/Missing/MissingConnector'; - -function RedirectWithUrlBase() { - return ; -} - -function AppRoutes() { - return ( - - {/* - Series - */} - - - - {window.Sonarr.urlBase && ( - - )} - - - - - - - - - - - - {/* - Calendar - */} - - - - {/* - Activity - */} - - - - - - - - {/* - Wanted - */} - - - - - - {/* - Settings - */} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {/* - System - */} - - - - - - - - - - - - - - {/* - Not Found - */} - - - - ); -} - -export default AppRoutes; diff --git a/frontend/src/App/AppUpdatedModal.js b/frontend/src/App/AppUpdatedModal.js new file mode 100644 index 000000000..abc7f8832 --- /dev/null +++ b/frontend/src/App/AppUpdatedModal.js @@ -0,0 +1,30 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import AppUpdatedModalContentConnector from './AppUpdatedModalContentConnector'; + +function AppUpdatedModal(props) { + const { + isOpen, + onModalClose + } = props; + + return ( + + + + ); +} + +AppUpdatedModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default AppUpdatedModal; diff --git a/frontend/src/App/AppUpdatedModal.tsx b/frontend/src/App/AppUpdatedModal.tsx deleted file mode 100644 index 696d36fb2..000000000 --- a/frontend/src/App/AppUpdatedModal.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import React, { useCallback } from 'react'; -import Modal from 'Components/Modal/Modal'; -import AppUpdatedModalContent from './AppUpdatedModalContent'; - -interface AppUpdatedModalProps { - isOpen: boolean; - onModalClose: (...args: unknown[]) => unknown; -} - -function AppUpdatedModal(props: AppUpdatedModalProps) { - const { isOpen, onModalClose } = props; - - const handleModalClose = useCallback(() => { - location.reload(); - }, []); - - return ( - - - - ); -} - -export default AppUpdatedModal; diff --git a/frontend/src/App/AppUpdatedModalConnector.js b/frontend/src/App/AppUpdatedModalConnector.js new file mode 100644 index 000000000..a21afbc5a --- /dev/null +++ b/frontend/src/App/AppUpdatedModalConnector.js @@ -0,0 +1,12 @@ +import { connect } from 'react-redux'; +import AppUpdatedModal from './AppUpdatedModal'; + +function createMapDispatchToProps(dispatch, props) { + return { + onModalClose() { + location.reload(); + } + }; +} + +export default connect(null, createMapDispatchToProps)(AppUpdatedModal); diff --git a/frontend/src/App/AppUpdatedModalContent.css b/frontend/src/App/AppUpdatedModalContent.css index 0df4183a6..37b89c9be 100644 --- a/frontend/src/App/AppUpdatedModalContent.css +++ b/frontend/src/App/AppUpdatedModalContent.css @@ -1,7 +1,6 @@ .version { margin: 0 3px; font-weight: bold; - font-family: var(--defaultFontFamily); } .maintenance { diff --git a/frontend/src/App/AppUpdatedModalContent.css.d.ts b/frontend/src/App/AppUpdatedModalContent.css.d.ts deleted file mode 100644 index 70ddbf6a1..000000000 --- a/frontend/src/App/AppUpdatedModalContent.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'changes': string; - 'maintenance': string; - 'version': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/App/AppUpdatedModalContent.js b/frontend/src/App/AppUpdatedModalContent.js new file mode 100644 index 000000000..562467288 --- /dev/null +++ b/frontend/src/App/AppUpdatedModalContent.js @@ -0,0 +1,137 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { kinds } from 'Helpers/Props'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Button from 'Components/Link/Button'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; +import UpdateChanges from 'System/Updates/UpdateChanges'; +import styles from './AppUpdatedModalContent.css'; + +function mergeUpdates(items, version, prevVersion) { + let installedIndex = items.findIndex((u) => u.version === version); + let installedPreviouslyIndex = items.findIndex((u) => u.version === prevVersion); + + if (installedIndex === -1) { + installedIndex = 0; + } + + if (installedPreviouslyIndex === -1) { + installedPreviouslyIndex = items.length; + } else if (installedPreviouslyIndex === installedIndex && items.length) { + installedPreviouslyIndex += 1; + } + + const appliedUpdates = items.slice(installedIndex, installedPreviouslyIndex); + + if (!appliedUpdates.length) { + return null; + } + + const appliedChanges = { new: [], fixed: [] }; + appliedUpdates.forEach((u) => { + if (u.changes) { + appliedChanges.new.push(... u.changes.new); + appliedChanges.fixed.push(... u.changes.fixed); + } + }); + + const mergedUpdate = Object.assign({}, appliedUpdates[0], { changes: appliedChanges }); + + if (!appliedChanges.new.length && !appliedChanges.fixed.length) { + mergedUpdate.changes = null; + } + + return mergedUpdate; +} + +function AppUpdatedModalContent(props) { + const { + version, + prevVersion, + isPopulated, + error, + items, + onSeeChangesPress, + onModalClose + } = props; + + const update = mergeUpdates(items, version, prevVersion); + + return ( + + + Sonarr Updated + + + +
+ Sonarr has been updated to version {version}, in order to get the latest changes you'll need to reload Sonarr. +
+ + { + isPopulated && !error && !!update && +
+ { + !update.changes && +
Maintenance release
+ } + + { + !!update.changes && +
+
+ What's new? +
+ + + + +
+ } +
+ } + + { + !isPopulated && !error && + + } +
+ + + + + + +
+ ); +} + +AppUpdatedModalContent.propTypes = { + version: PropTypes.string.isRequired, + prevVersion: PropTypes.string, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + onSeeChangesPress: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default AppUpdatedModalContent; diff --git a/frontend/src/App/AppUpdatedModalContent.tsx b/frontend/src/App/AppUpdatedModalContent.tsx deleted file mode 100644 index 6553d6270..000000000 --- a/frontend/src/App/AppUpdatedModalContent.tsx +++ /dev/null @@ -1,145 +0,0 @@ -import React, { useCallback, useEffect } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import Button from 'Components/Link/Button'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import InlineMarkdown from 'Components/Markdown/InlineMarkdown'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { kinds } from 'Helpers/Props'; -import { fetchUpdates } from 'Store/Actions/systemActions'; -import UpdateChanges from 'System/Updates/UpdateChanges'; -import Update from 'typings/Update'; -import translate from 'Utilities/String/translate'; -import AppState from './State/AppState'; -import styles from './AppUpdatedModalContent.css'; - -function mergeUpdates(items: Update[], version: string, prevVersion?: string) { - let installedIndex = items.findIndex((u) => u.version === version); - let installedPreviouslyIndex = items.findIndex( - (u) => u.version === prevVersion - ); - - if (installedIndex === -1) { - installedIndex = 0; - } - - if (installedPreviouslyIndex === -1) { - installedPreviouslyIndex = items.length; - } else if (installedPreviouslyIndex === installedIndex && items.length) { - installedPreviouslyIndex += 1; - } - - const appliedUpdates = items.slice(installedIndex, installedPreviouslyIndex); - - if (!appliedUpdates.length) { - return null; - } - - const appliedChanges: Update['changes'] = { new: [], fixed: [] }; - - appliedUpdates.forEach((u: Update) => { - if (u.changes) { - appliedChanges.new.push(...u.changes.new); - appliedChanges.fixed.push(...u.changes.fixed); - } - }); - - const mergedUpdate: Update = Object.assign({}, appliedUpdates[0], { - changes: appliedChanges, - }); - - if (!appliedChanges.new.length && !appliedChanges.fixed.length) { - mergedUpdate.changes = null; - } - - return mergedUpdate; -} - -interface AppUpdatedModalContentProps { - onModalClose: () => void; -} - -function AppUpdatedModalContent(props: AppUpdatedModalContentProps) { - const dispatch = useDispatch(); - const { version, prevVersion } = useSelector((state: AppState) => state.app); - const { isPopulated, error, items } = useSelector( - (state: AppState) => state.system.updates - ); - const previousVersion = usePrevious(version); - - const { onModalClose } = props; - - const update = mergeUpdates(items, version, prevVersion); - - const handleSeeChangesPress = useCallback(() => { - window.location.href = `${window.Sonarr.urlBase}/system/updates`; - }, []); - - useEffect(() => { - dispatch(fetchUpdates()); - }, [dispatch]); - - useEffect(() => { - if (version !== previousVersion) { - dispatch(fetchUpdates()); - } - }, [version, previousVersion, dispatch]); - - return ( - - {translate('AppUpdated')} - - -
- -
- - {isPopulated && !error && !!update ? ( -
- {update.changes ? ( -
- {translate('MaintenanceRelease')} -
- ) : null} - - {update.changes ? ( -
-
{translate('WhatsNew')}
- - - - -
- ) : null} -
- ) : null} - - {!isPopulated && !error ? : null} -
- - - - - - -
- ); -} - -export default AppUpdatedModalContent; diff --git a/frontend/src/App/AppUpdatedModalContentConnector.js b/frontend/src/App/AppUpdatedModalContentConnector.js new file mode 100644 index 000000000..4100ee674 --- /dev/null +++ b/frontend/src/App/AppUpdatedModalContentConnector.js @@ -0,0 +1,78 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { fetchUpdates } from 'Store/Actions/systemActions'; +import AppUpdatedModalContent from './AppUpdatedModalContent'; + +function createMapStateToProps() { + return createSelector( + (state) => state.app.version, + (state) => state.app.prevVersion, + (state) => state.system.updates, + (version, prevVersion, updates) => { + const { + isPopulated, + error, + items + } = updates; + + return { + version, + prevVersion, + isPopulated, + error, + items + }; + } + ); +} + +function createMapDispatchToProps(dispatch, props) { + return { + dispatchFetchUpdates() { + dispatch(fetchUpdates()); + }, + + onSeeChangesPress() { + window.location = `${window.Sonarr.urlBase}/system/updates`; + } + }; +} + +class AppUpdatedModalContentConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + this.props.dispatchFetchUpdates(); + } + + componentDidUpdate(prevProps) { + if (prevProps.version !== this.props.version) { + this.props.dispatchFetchUpdates(); + } + } + + // + // Render + + render() { + const { + dispatchFetchUpdates, + ...otherProps + } = this.props; + + return ( + + ); + } +} + +AppUpdatedModalContentConnector.propTypes = { + version: PropTypes.string.isRequired, + dispatchFetchUpdates: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, createMapDispatchToProps)(AppUpdatedModalContentConnector); diff --git a/frontend/src/App/ApplyTheme.tsx b/frontend/src/App/ApplyTheme.tsx deleted file mode 100644 index ce598f2dc..000000000 --- a/frontend/src/App/ApplyTheme.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useCallback, useEffect } from 'react'; -import { useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import themes from 'Styles/Themes'; -import AppState from './State/AppState'; - -function createThemeSelector() { - return createSelector( - (state: AppState) => state.settings.ui.item.theme || window.Sonarr.theme, - (theme) => { - return theme; - } - ); -} - -function ApplyTheme() { - const theme = useSelector(createThemeSelector()); - - const updateCSSVariables = useCallback(() => { - Object.entries(themes[theme]).forEach(([key, value]) => { - document.documentElement.style.setProperty(`--${key}`, value); - }); - }, [theme]); - - // On Component Mount and Component Update - useEffect(() => { - updateCSSVariables(); - }, [updateCSSVariables, theme]); - - return null; -} - -export default ApplyTheme; diff --git a/frontend/src/App/ColorImpairedContext.ts b/frontend/src/App/ColorImpairedContext.js similarity index 100% rename from frontend/src/App/ColorImpairedContext.ts rename to frontend/src/App/ColorImpairedContext.js diff --git a/frontend/src/App/ConnectionLostModal.css.d.ts b/frontend/src/App/ConnectionLostModal.css.d.ts deleted file mode 100644 index 027f2a9a3..000000000 --- a/frontend/src/App/ConnectionLostModal.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'automatic': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/App/ConnectionLostModal.js b/frontend/src/App/ConnectionLostModal.js new file mode 100644 index 000000000..b54f81d50 --- /dev/null +++ b/frontend/src/App/ConnectionLostModal.js @@ -0,0 +1,55 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { kinds } from 'Helpers/Props'; +import Button from 'Components/Link/Button'; +import Modal from 'Components/Modal/Modal'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; +import styles from './ConnectionLostModal.css'; + +function ConnectionLostModal(props) { + const { + isOpen, + onModalClose + } = props; + + return ( + + + + Connection Lost + + + +
+ Sonarr has lost it's connection to the backend and will need to be reloaded to restore functionality. +
+ +
+ Sonarr will try to connect automatically, or you can click reload below. +
+
+ + + +
+
+ ); +} + +ConnectionLostModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default ConnectionLostModal; diff --git a/frontend/src/App/ConnectionLostModal.tsx b/frontend/src/App/ConnectionLostModal.tsx deleted file mode 100644 index f08f2c0e2..000000000 --- a/frontend/src/App/ConnectionLostModal.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import React, { useCallback } from 'react'; -import Button from 'Components/Link/Button'; -import Modal from 'Components/Modal/Modal'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import { kinds } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; -import styles from './ConnectionLostModal.css'; - -interface ConnectionLostModalProps { - isOpen: boolean; -} - -function ConnectionLostModal(props: ConnectionLostModalProps) { - const { isOpen } = props; - - const handleModalClose = useCallback(() => { - location.reload(); - }, []); - - return ( - - - {translate('ConnectionLost')} - - -
{translate('ConnectionLostToBackend')}
- -
- {translate('ConnectionLostReconnect')} -
-
- - - -
-
- ); -} - -export default ConnectionLostModal; diff --git a/frontend/src/App/ConnectionLostModalConnector.js b/frontend/src/App/ConnectionLostModalConnector.js new file mode 100644 index 000000000..8ab8e3cd0 --- /dev/null +++ b/frontend/src/App/ConnectionLostModalConnector.js @@ -0,0 +1,12 @@ +import { connect } from 'react-redux'; +import ConnectionLostModal from './ConnectionLostModal'; + +function createMapDispatchToProps(dispatch, props) { + return { + onModalClose() { + location.reload(); + } + }; +} + +export default connect(undefined, createMapDispatchToProps)(ConnectionLostModal); diff --git a/frontend/src/App/ModelBase.ts b/frontend/src/App/ModelBase.ts deleted file mode 100644 index 187b12fb2..000000000 --- a/frontend/src/App/ModelBase.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface ModelBase { - id: number; -} - -export default ModelBase; diff --git a/frontend/src/App/SelectContext.tsx b/frontend/src/App/SelectContext.tsx deleted file mode 100644 index 66be388ce..000000000 --- a/frontend/src/App/SelectContext.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import { cloneDeep } from 'lodash'; -import React, { useCallback, useEffect } from 'react'; -import useSelectState, { SelectState } from 'Helpers/Hooks/useSelectState'; -import ModelBase from './ModelBase'; - -export type SelectContextAction = - | { type: 'reset' } - | { type: 'selectAll' } - | { type: 'unselectAll' } - | { - type: 'toggleSelected'; - id: number; - isSelected: boolean; - shiftKey: boolean; - } - | { - type: 'removeItem'; - id: number; - } - | { - type: 'updateItems'; - items: ModelBase[]; - }; - -export type SelectDispatch = (action: SelectContextAction) => void; - -interface SelectProviderOptions { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - children: any; - items: Array; -} - -const SelectContext = React.createContext< - [SelectState, SelectDispatch] | undefined ->(cloneDeep(undefined)); - -export function SelectProvider( - props: SelectProviderOptions -) { - const { items } = props; - const [state, dispatch] = useSelectState(); - - const dispatchWrapper = useCallback( - (action: SelectContextAction) => { - switch (action.type) { - case 'reset': - case 'removeItem': - dispatch(action); - break; - - default: - dispatch({ - ...action, - items, - }); - break; - } - }, - [items, dispatch] - ); - - const value: [SelectState, SelectDispatch] = [state, dispatchWrapper]; - - useEffect(() => { - dispatch({ type: 'updateItems', items }); - }, [items, dispatch]); - - return ( - - {props.children} - - ); -} - -export function useSelect() { - const context = React.useContext(SelectContext); - - if (context === undefined) { - throw new Error('useSelect must be used within a SelectProvider'); - } - - return context; -} diff --git a/frontend/src/App/State/AppSectionState.ts b/frontend/src/App/State/AppSectionState.ts deleted file mode 100644 index 4e9dbe7a0..000000000 --- a/frontend/src/App/State/AppSectionState.ts +++ /dev/null @@ -1,85 +0,0 @@ -import Column from 'Components/Table/Column'; -import { SortDirection } from 'Helpers/Props/sortDirections'; -import { ValidationFailure } from 'typings/pending'; -import { FilterBuilderProp, PropertyFilter } from './AppState'; - -export interface Error { - status?: number; - responseJSON: - | { - message: string | undefined; - } - | ValidationFailure[] - | undefined; -} - -export interface AppSectionDeleteState { - isDeleting: boolean; - deleteError: Error; -} - -export interface AppSectionSaveState { - isSaving: boolean; - saveError: Error; -} - -export interface PagedAppSectionState { - page: number; - pageSize: number; - totalPages: number; - totalRecords?: number; -} -export interface TableAppSectionState { - columns: Column[]; -} - -export interface AppSectionFilterState { - selectedFilterKey: string; - filters: PropertyFilter[]; - filterBuilderProps: FilterBuilderProp[]; -} - -export interface AppSectionSchemaState { - isSchemaFetching: boolean; - isSchemaPopulated: boolean; - schemaError: Error; - schema: { - items: T[]; - }; -} - -export interface AppSectionItemSchemaState { - isSchemaFetching: boolean; - isSchemaPopulated: boolean; - schemaError: Error; - schema: T; -} - -export interface AppSectionItemState { - isFetching: boolean; - isPopulated: boolean; - error: Error; - pendingChanges: Partial; - item: T; -} - -export interface AppSectionProviderState - extends AppSectionDeleteState, - AppSectionSaveState { - isFetching: boolean; - isPopulated: boolean; - error: Error; - items: T[]; - pendingChanges: Partial; -} - -interface AppSectionState { - isFetching: boolean; - isPopulated: boolean; - error: Error; - items: T[]; - sortKey: string; - sortDirection: SortDirection; -} - -export default AppSectionState; diff --git a/frontend/src/App/State/AppState.ts b/frontend/src/App/State/AppState.ts deleted file mode 100644 index 84bd5d0b4..000000000 --- a/frontend/src/App/State/AppState.ts +++ /dev/null @@ -1,95 +0,0 @@ -import BlocklistAppState from './BlocklistAppState'; -import CalendarAppState from './CalendarAppState'; -import CaptchaAppState from './CaptchaAppState'; -import CommandAppState from './CommandAppState'; -import EpisodeFilesAppState from './EpisodeFilesAppState'; -import EpisodesAppState from './EpisodesAppState'; -import HistoryAppState from './HistoryAppState'; -import InteractiveImportAppState from './InteractiveImportAppState'; -import OAuthAppState from './OAuthAppState'; -import ParseAppState from './ParseAppState'; -import PathsAppState from './PathsAppState'; -import ProviderOptionsAppState from './ProviderOptionsAppState'; -import QueueAppState from './QueueAppState'; -import ReleasesAppState from './ReleasesAppState'; -import RootFolderAppState from './RootFolderAppState'; -import SeriesAppState, { SeriesIndexAppState } from './SeriesAppState'; -import SettingsAppState from './SettingsAppState'; -import SystemAppState from './SystemAppState'; -import TagsAppState from './TagsAppState'; -import WantedAppState from './WantedAppState'; - -interface FilterBuilderPropOption { - id: string; - name: string; -} - -export interface FilterBuilderProp { - name: string; - label: string; - type: string; - valueType?: string; - optionsSelector?: (items: T[]) => FilterBuilderPropOption[]; -} - -export interface PropertyFilter { - key: string; - value: boolean | string | number | string[] | number[]; - type: string; -} - -export interface Filter { - key: string; - label: string; - filters: PropertyFilter[]; -} - -export interface CustomFilter { - id: number; - type: string; - label: string; - filters: PropertyFilter[]; -} - -export interface AppSectionState { - isConnected: boolean; - isReconnecting: boolean; - isSidebarVisible: boolean; - version: string; - prevVersion?: string; - dimensions: { - isSmallScreen: boolean; - isLargeScreen: boolean; - width: number; - height: number; - }; -} - -interface AppState { - app: AppSectionState; - blocklist: BlocklistAppState; - calendar: CalendarAppState; - captcha: CaptchaAppState; - commands: CommandAppState; - episodeFiles: EpisodeFilesAppState; - episodeHistory: HistoryAppState; - episodes: EpisodesAppState; - episodesSelection: EpisodesAppState; - history: HistoryAppState; - interactiveImport: InteractiveImportAppState; - oAuth: OAuthAppState; - parse: ParseAppState; - paths: PathsAppState; - providerOptions: ProviderOptionsAppState; - queue: QueueAppState; - releases: ReleasesAppState; - rootFolders: RootFolderAppState; - series: SeriesAppState; - seriesIndex: SeriesIndexAppState; - settings: SettingsAppState; - system: SystemAppState; - tags: TagsAppState; - wanted: WantedAppState; -} - -export default AppState; diff --git a/frontend/src/App/State/BlocklistAppState.ts b/frontend/src/App/State/BlocklistAppState.ts deleted file mode 100644 index 004a30732..000000000 --- a/frontend/src/App/State/BlocklistAppState.ts +++ /dev/null @@ -1,16 +0,0 @@ -import Blocklist from 'typings/Blocklist'; -import AppSectionState, { - AppSectionFilterState, - PagedAppSectionState, - TableAppSectionState, -} from './AppSectionState'; - -interface BlocklistAppState - extends AppSectionState, - AppSectionFilterState, - PagedAppSectionState, - TableAppSectionState { - isRemoving: boolean; -} - -export default BlocklistAppState; diff --git a/frontend/src/App/State/CalendarAppState.ts b/frontend/src/App/State/CalendarAppState.ts deleted file mode 100644 index 75c8b5e50..000000000 --- a/frontend/src/App/State/CalendarAppState.ts +++ /dev/null @@ -1,29 +0,0 @@ -import moment from 'moment'; -import AppSectionState, { - AppSectionFilterState, -} from 'App/State/AppSectionState'; -import { CalendarView } from 'Calendar/calendarViews'; -import { CalendarItem } from 'typings/Calendar'; - -interface CalendarOptions { - showEpisodeInformation: boolean; - showFinaleIcon: boolean; - showSpecialIcon: boolean; - showCutoffUnmetIcon: boolean; - collapseMultipleEpisodes: boolean; - fullColorEvents: boolean; -} - -interface CalendarAppState - extends AppSectionState, - AppSectionFilterState { - searchMissingCommandId: number | null; - start: moment.Moment; - end: moment.Moment; - dates: string[]; - time: string; - view: CalendarView; - options: CalendarOptions; -} - -export default CalendarAppState; diff --git a/frontend/src/App/State/CaptchaAppState.ts b/frontend/src/App/State/CaptchaAppState.ts deleted file mode 100644 index 7252937eb..000000000 --- a/frontend/src/App/State/CaptchaAppState.ts +++ /dev/null @@ -1,11 +0,0 @@ -interface CaptchaAppState { - refreshing: false; - token: string; - siteKey: unknown; - secretToken: unknown; - ray: unknown; - stoken: unknown; - responseUrl: unknown; -} - -export default CaptchaAppState; diff --git a/frontend/src/App/State/ClientSideCollectionAppState.ts b/frontend/src/App/State/ClientSideCollectionAppState.ts deleted file mode 100644 index f4110ef73..000000000 --- a/frontend/src/App/State/ClientSideCollectionAppState.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { CustomFilter } from './AppState'; - -interface ClientSideCollectionAppState { - totalItems: number; - customFilters: CustomFilter[]; -} - -export default ClientSideCollectionAppState; diff --git a/frontend/src/App/State/CommandAppState.ts b/frontend/src/App/State/CommandAppState.ts deleted file mode 100644 index 1bde37371..000000000 --- a/frontend/src/App/State/CommandAppState.ts +++ /dev/null @@ -1,6 +0,0 @@ -import AppSectionState from 'App/State/AppSectionState'; -import Command from 'Commands/Command'; - -export type CommandAppState = AppSectionState; - -export default CommandAppState; diff --git a/frontend/src/App/State/CustomFiltersAppState.ts b/frontend/src/App/State/CustomFiltersAppState.ts deleted file mode 100644 index 6ac4820c7..000000000 --- a/frontend/src/App/State/CustomFiltersAppState.ts +++ /dev/null @@ -1,10 +0,0 @@ -import AppSectionState, { - AppSectionDeleteState, -} from 'App/State/AppSectionState'; -import { CustomFilter } from './AppState'; - -interface CustomFiltersAppState - extends AppSectionState, - AppSectionDeleteState {} - -export default CustomFiltersAppState; diff --git a/frontend/src/App/State/EpisodeFilesAppState.ts b/frontend/src/App/State/EpisodeFilesAppState.ts deleted file mode 100644 index 5e6e94a06..000000000 --- a/frontend/src/App/State/EpisodeFilesAppState.ts +++ /dev/null @@ -1,10 +0,0 @@ -import AppSectionState, { - AppSectionDeleteState, -} from 'App/State/AppSectionState'; -import { EpisodeFile } from 'EpisodeFile/EpisodeFile'; - -interface EpisodeFilesAppState - extends AppSectionState, - AppSectionDeleteState {} - -export default EpisodeFilesAppState; diff --git a/frontend/src/App/State/EpisodesAppState.ts b/frontend/src/App/State/EpisodesAppState.ts deleted file mode 100644 index 4234c0bcb..000000000 --- a/frontend/src/App/State/EpisodesAppState.ts +++ /dev/null @@ -1,6 +0,0 @@ -import AppSectionState from 'App/State/AppSectionState'; -import Episode from 'Episode/Episode'; - -type EpisodesAppState = AppSectionState; - -export default EpisodesAppState; diff --git a/frontend/src/App/State/HistoryAppState.ts b/frontend/src/App/State/HistoryAppState.ts deleted file mode 100644 index 632b82179..000000000 --- a/frontend/src/App/State/HistoryAppState.ts +++ /dev/null @@ -1,14 +0,0 @@ -import AppSectionState, { - AppSectionFilterState, - PagedAppSectionState, - TableAppSectionState, -} from 'App/State/AppSectionState'; -import History from 'typings/History'; - -interface HistoryAppState - extends AppSectionState, - AppSectionFilterState, - PagedAppSectionState, - TableAppSectionState {} - -export default HistoryAppState; diff --git a/frontend/src/App/State/InteractiveImportAppState.ts b/frontend/src/App/State/InteractiveImportAppState.ts deleted file mode 100644 index 84fd9f4c1..000000000 --- a/frontend/src/App/State/InteractiveImportAppState.ts +++ /dev/null @@ -1,21 +0,0 @@ -import AppSectionState from 'App/State/AppSectionState'; -import ImportMode from 'InteractiveImport/ImportMode'; -import InteractiveImport from 'InteractiveImport/InteractiveImport'; - -interface FavoriteFolder { - folder: string; -} - -interface RecentFolder { - folder: string; - lastUsed: string; -} - -interface InteractiveImportAppState extends AppSectionState { - originalItems: InteractiveImport[]; - importMode: ImportMode; - favoriteFolders: FavoriteFolder[]; - recentFolders: RecentFolder[]; -} - -export default InteractiveImportAppState; diff --git a/frontend/src/App/State/MetadataAppState.ts b/frontend/src/App/State/MetadataAppState.ts deleted file mode 100644 index 495f109d8..000000000 --- a/frontend/src/App/State/MetadataAppState.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { AppSectionProviderState } from 'App/State/AppSectionState'; -import Metadata from 'typings/Metadata'; - -type MetadataAppState = AppSectionProviderState; - -export default MetadataAppState; diff --git a/frontend/src/App/State/OAuthAppState.ts b/frontend/src/App/State/OAuthAppState.ts deleted file mode 100644 index 619767929..000000000 --- a/frontend/src/App/State/OAuthAppState.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Error } from './AppSectionState'; - -interface OAuthAppState { - authorizing: boolean; - result: Record | null; - error: Error; -} - -export default OAuthAppState; diff --git a/frontend/src/App/State/ParseAppState.ts b/frontend/src/App/State/ParseAppState.ts deleted file mode 100644 index 67fb4cc63..000000000 --- a/frontend/src/App/State/ParseAppState.ts +++ /dev/null @@ -1,54 +0,0 @@ -import ModelBase from 'App/ModelBase'; -import { AppSectionItemState } from 'App/State/AppSectionState'; -import Episode from 'Episode/Episode'; -import Language from 'Language/Language'; -import { QualityModel } from 'Quality/Quality'; -import Series from 'Series/Series'; -import CustomFormat from 'typings/CustomFormat'; - -export interface SeriesTitleInfo { - title: string; - titleWithoutYear: string; - year: number; - allTitles: string[]; -} - -export interface ParsedEpisodeInfo { - releaseTitle: string; - seriesTitle: string; - seriesTitleInfo: SeriesTitleInfo; - quality: QualityModel; - seasonNumber: number; - episodeNumbers: number[]; - absoluteEpisodeNumbers: number[]; - specialAbsoluteEpisodeNumbers: number[]; - languages: Language[]; - fullSeason: boolean; - isPartialSeason: boolean; - isMultiSeason: boolean; - isSeasonExtra: boolean; - special: boolean; - releaseHash: string; - seasonPart: number; - releaseGroup?: string; - releaseTokens: string; - airDate?: string; - isDaily: boolean; - isAbsoluteNumbering: boolean; - isPossibleSpecialEpisode: boolean; - isPossibleSceneSeasonSpecial: boolean; -} - -export interface ParseModel extends ModelBase { - title: string; - parsedEpisodeInfo: ParsedEpisodeInfo; - series?: Series; - episodes: Episode[]; - languages?: Language[]; - customFormats?: CustomFormat[]; - customFormatScore?: number; -} - -type ParseAppState = AppSectionItemState; - -export default ParseAppState; diff --git a/frontend/src/App/State/PathsAppState.ts b/frontend/src/App/State/PathsAppState.ts deleted file mode 100644 index 068a48dc0..000000000 --- a/frontend/src/App/State/PathsAppState.ts +++ /dev/null @@ -1,29 +0,0 @@ -interface BasePath { - name: string; - path: string; - size: number; - lastModified: string; -} - -interface File extends BasePath { - type: 'file'; -} - -interface Folder extends BasePath { - type: 'folder'; -} - -export type PathType = 'file' | 'folder' | 'drive' | 'computer' | 'parent'; -export type Path = File | Folder; - -interface PathsAppState { - currentPath: string; - isFetching: boolean; - isPopulated: boolean; - error: Error; - directories: Folder[]; - files: File[]; - parent: string | null; -} - -export default PathsAppState; diff --git a/frontend/src/App/State/ProviderOptionsAppState.ts b/frontend/src/App/State/ProviderOptionsAppState.ts deleted file mode 100644 index 7fb5df02b..000000000 --- a/frontend/src/App/State/ProviderOptionsAppState.ts +++ /dev/null @@ -1,22 +0,0 @@ -import AppSectionState from 'App/State/AppSectionState'; -import Field, { FieldSelectOption } from 'typings/Field'; - -export interface ProviderOptions { - fields?: Field[]; -} - -interface ProviderOptionsDevice { - id: string; - name: string; -} - -interface ProviderOptionsAppState { - devices: AppSectionState; - servers: AppSectionState>; - newznabCategories: AppSectionState>; - getProfiles: AppSectionState>; - getTags: AppSectionState>; - getRootFolders: AppSectionState>; -} - -export default ProviderOptionsAppState; diff --git a/frontend/src/App/State/QueueAppState.ts b/frontend/src/App/State/QueueAppState.ts deleted file mode 100644 index 954d649a2..000000000 --- a/frontend/src/App/State/QueueAppState.ts +++ /dev/null @@ -1,44 +0,0 @@ -import Queue from 'typings/Queue'; -import AppSectionState, { - AppSectionFilterState, - AppSectionItemState, - Error, - PagedAppSectionState, - TableAppSectionState, -} from './AppSectionState'; - -export interface QueueStatus { - totalCount: number; - count: number; - unknownCount: number; - errors: boolean; - warnings: boolean; - unknownErrors: boolean; - unknownWarnings: boolean; -} - -export interface QueueDetailsAppState extends AppSectionState { - params: unknown; -} - -export interface QueuePagedAppState - extends AppSectionState, - AppSectionFilterState, - PagedAppSectionState, - TableAppSectionState { - isGrabbing: boolean; - grabError: Error; - isRemoving: boolean; - removeError: Error; -} - -interface QueueAppState { - status: AppSectionItemState; - details: QueueDetailsAppState; - paged: QueuePagedAppState; - options: { - includeUnknownSeriesItems: boolean; - }; -} - -export default QueueAppState; diff --git a/frontend/src/App/State/ReleasesAppState.ts b/frontend/src/App/State/ReleasesAppState.ts deleted file mode 100644 index 350f6eac8..000000000 --- a/frontend/src/App/State/ReleasesAppState.ts +++ /dev/null @@ -1,10 +0,0 @@ -import AppSectionState, { - AppSectionFilterState, -} from 'App/State/AppSectionState'; -import Release from 'typings/Release'; - -interface ReleasesAppState - extends AppSectionState, - AppSectionFilterState {} - -export default ReleasesAppState; diff --git a/frontend/src/App/State/RootFolderAppState.ts b/frontend/src/App/State/RootFolderAppState.ts deleted file mode 100644 index 9e636c95f..000000000 --- a/frontend/src/App/State/RootFolderAppState.ts +++ /dev/null @@ -1,12 +0,0 @@ -import AppSectionState, { - AppSectionDeleteState, - AppSectionSaveState, -} from 'App/State/AppSectionState'; -import RootFolder from 'typings/RootFolder'; - -interface RootFolderAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState {} - -export default RootFolderAppState; diff --git a/frontend/src/App/State/SeriesAppState.ts b/frontend/src/App/State/SeriesAppState.ts deleted file mode 100644 index 5da5987dd..000000000 --- a/frontend/src/App/State/SeriesAppState.ts +++ /dev/null @@ -1,66 +0,0 @@ -import AppSectionState, { - AppSectionDeleteState, - AppSectionSaveState, -} from 'App/State/AppSectionState'; -import Column from 'Components/Table/Column'; -import { SortDirection } from 'Helpers/Props/sortDirections'; -import Series from 'Series/Series'; -import { Filter, FilterBuilderProp } from './AppState'; - -export interface SeriesIndexAppState { - sortKey: string; - sortDirection: SortDirection; - secondarySortKey: string; - secondarySortDirection: SortDirection; - view: string; - - posterOptions: { - detailedProgressBar: boolean; - size: string; - showTitle: boolean; - showMonitored: boolean; - showQualityProfile: boolean; - showTags: boolean; - showSearchAction: boolean; - }; - - overviewOptions: { - detailedProgressBar: boolean; - size: string; - showMonitored: boolean; - showNetwork: boolean; - showQualityProfile: boolean; - showPreviousAiring: boolean; - showAdded: boolean; - showSeasonCount: boolean; - showPath: boolean; - showSizeOnDisk: boolean; - showTags: boolean; - showSearchAction: boolean; - }; - - tableOptions: { - showBanners: boolean; - showSearchAction: boolean; - }; - - selectedFilterKey: string; - filterBuilderProps: FilterBuilderProp[]; - filters: Filter[]; - columns: Column[]; -} - -interface SeriesAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState { - itemMap: Record; - - deleteOptions: { - addImportListExclusion: boolean; - }; - - pendingChanges: Partial; -} - -export default SeriesAppState; diff --git a/frontend/src/App/State/SettingsAppState.ts b/frontend/src/App/State/SettingsAppState.ts deleted file mode 100644 index b8e6f4954..000000000 --- a/frontend/src/App/State/SettingsAppState.ts +++ /dev/null @@ -1,109 +0,0 @@ -import AppSectionState, { - AppSectionDeleteState, - AppSectionItemSchemaState, - AppSectionItemState, - AppSectionSaveState, - PagedAppSectionState, -} from 'App/State/AppSectionState'; -import Language from 'Language/Language'; -import CustomFormat from 'typings/CustomFormat'; -import DownloadClient from 'typings/DownloadClient'; -import ImportList from 'typings/ImportList'; -import ImportListExclusion from 'typings/ImportListExclusion'; -import ImportListOptionsSettings from 'typings/ImportListOptionsSettings'; -import Indexer from 'typings/Indexer'; -import IndexerFlag from 'typings/IndexerFlag'; -import Notification from 'typings/Notification'; -import QualityProfile from 'typings/QualityProfile'; -import General from 'typings/Settings/General'; -import NamingConfig from 'typings/Settings/NamingConfig'; -import NamingExample from 'typings/Settings/NamingExample'; -import ReleaseProfile from 'typings/Settings/ReleaseProfile'; -import UiSettings from 'typings/Settings/UiSettings'; -import MetadataAppState from './MetadataAppState'; - -export interface DownloadClientAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState { - isTestingAll: boolean; -} - -export interface GeneralAppState - extends AppSectionItemState, - AppSectionSaveState {} - -export interface NamingAppState - extends AppSectionItemState, - AppSectionSaveState {} - -export type NamingExamplesAppState = AppSectionItemState; - -export interface ImportListAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState {} - -export interface IndexerAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState { - isTestingAll: boolean; -} - -export interface NotificationAppState - extends AppSectionState, - AppSectionDeleteState {} - -export interface QualityProfilesAppState - extends AppSectionState, - AppSectionItemSchemaState {} - -export interface ReleaseProfilesAppState - extends AppSectionState, - AppSectionSaveState { - pendingChanges: Partial; -} - -export interface CustomFormatAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState {} - -export interface ImportListOptionsSettingsAppState - extends AppSectionItemState, - AppSectionSaveState {} - -export interface ImportListExclusionsSettingsAppState - extends AppSectionState, - AppSectionSaveState, - PagedAppSectionState, - AppSectionDeleteState { - pendingChanges: Partial; -} - -export type IndexerFlagSettingsAppState = AppSectionState; -export type LanguageSettingsAppState = AppSectionState; -export type UiSettingsAppState = AppSectionItemState; - -interface SettingsAppState { - advancedSettings: boolean; - customFormats: CustomFormatAppState; - downloadClients: DownloadClientAppState; - general: GeneralAppState; - importListExclusions: ImportListExclusionsSettingsAppState; - importListOptions: ImportListOptionsSettingsAppState; - importLists: ImportListAppState; - indexerFlags: IndexerFlagSettingsAppState; - indexers: IndexerAppState; - languages: LanguageSettingsAppState; - metadata: MetadataAppState; - naming: NamingAppState; - namingExamples: NamingExamplesAppState; - notifications: NotificationAppState; - qualityProfiles: QualityProfilesAppState; - releaseProfiles: ReleaseProfilesAppState; - ui: UiSettingsAppState; -} - -export default SettingsAppState; diff --git a/frontend/src/App/State/SystemAppState.ts b/frontend/src/App/State/SystemAppState.ts deleted file mode 100644 index 1161f0e1e..000000000 --- a/frontend/src/App/State/SystemAppState.ts +++ /dev/null @@ -1,22 +0,0 @@ -import DiskSpace from 'typings/DiskSpace'; -import Health from 'typings/Health'; -import SystemStatus from 'typings/SystemStatus'; -import Task from 'typings/Task'; -import Update from 'typings/Update'; -import AppSectionState, { AppSectionItemState } from './AppSectionState'; - -export type DiskSpaceAppState = AppSectionState; -export type HealthAppState = AppSectionState; -export type SystemStatusAppState = AppSectionItemState; -export type TaskAppState = AppSectionState; -export type UpdateAppState = AppSectionState; - -interface SystemAppState { - diskSpace: DiskSpaceAppState; - health: HealthAppState; - status: SystemStatusAppState; - tasks: TaskAppState; - updates: UpdateAppState; -} - -export default SystemAppState; diff --git a/frontend/src/App/State/TagsAppState.ts b/frontend/src/App/State/TagsAppState.ts deleted file mode 100644 index 914df9044..000000000 --- a/frontend/src/App/State/TagsAppState.ts +++ /dev/null @@ -1,32 +0,0 @@ -import ModelBase from 'App/ModelBase'; -import AppSectionState, { - AppSectionDeleteState, - AppSectionSaveState, -} from 'App/State/AppSectionState'; - -export interface Tag extends ModelBase { - label: string; -} - -export interface TagDetail extends ModelBase { - label: string; - autoTagIds: number[]; - delayProfileIds: number[]; - downloadClientIds: []; - importListIds: number[]; - indexerIds: number[]; - notificationIds: number[]; - restrictionIds: number[]; - seriesIds: number[]; -} - -export interface TagDetailAppState - extends AppSectionState, - AppSectionDeleteState, - AppSectionSaveState {} - -interface TagsAppState extends AppSectionState, AppSectionDeleteState { - details: TagDetailAppState; -} - -export default TagsAppState; diff --git a/frontend/src/App/State/WantedAppState.ts b/frontend/src/App/State/WantedAppState.ts deleted file mode 100644 index b543d3879..000000000 --- a/frontend/src/App/State/WantedAppState.ts +++ /dev/null @@ -1,13 +0,0 @@ -import AppSectionState from 'App/State/AppSectionState'; -import Episode from 'Episode/Episode'; - -type WantedCutoffUnmetAppState = AppSectionState; - -type WantedMissingAppState = AppSectionState; - -interface WantedAppState { - cutoffUnmet: WantedCutoffUnmetAppState; - missing: WantedMissingAppState; -} - -export default WantedAppState; diff --git a/frontend/src/Calendar/Agenda/Agenda.css.d.ts b/frontend/src/Calendar/Agenda/Agenda.css.d.ts deleted file mode 100644 index 44421cc99..000000000 --- a/frontend/src/Calendar/Agenda/Agenda.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'agenda': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Agenda/Agenda.js b/frontend/src/Calendar/Agenda/Agenda.js new file mode 100644 index 000000000..89472301d --- /dev/null +++ b/frontend/src/Calendar/Agenda/Agenda.js @@ -0,0 +1,38 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React from 'react'; +import AgendaEventConnector from './AgendaEventConnector'; +import styles from './Agenda.css'; + +function Agenda(props) { + const { + items + } = props; + + return ( +
+ { + items.map((item, index) => { + const momentDate = moment(item.airDateUtc); + const showDate = index === 0 || + !moment(items[index - 1].airDateUtc).isSame(momentDate, 'day'); + + return ( + + ); + }) + } +
+ ); +} + +Agenda.propTypes = { + items: PropTypes.arrayOf(PropTypes.object).isRequired +}; + +export default Agenda; diff --git a/frontend/src/Calendar/Agenda/Agenda.tsx b/frontend/src/Calendar/Agenda/Agenda.tsx deleted file mode 100644 index fdef40466..000000000 --- a/frontend/src/Calendar/Agenda/Agenda.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import moment from 'moment'; -import React from 'react'; -import { useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import AgendaEvent from './AgendaEvent'; -import styles from './Agenda.css'; - -function Agenda() { - const { items } = useSelector((state: AppState) => state.calendar); - - return ( -
- {items.map((item, index) => { - const momentDate = moment(item.airDateUtc); - const showDate = - index === 0 || - !moment(items[index - 1].airDateUtc).isSame(momentDate, 'day'); - - return ; - })} -
- ); -} - -export default Agenda; diff --git a/frontend/src/Calendar/Agenda/AgendaConnector.js b/frontend/src/Calendar/Agenda/AgendaConnector.js new file mode 100644 index 000000000..b6f238873 --- /dev/null +++ b/frontend/src/Calendar/Agenda/AgendaConnector.js @@ -0,0 +1,14 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import Agenda from './Agenda'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar, + (calendar) => { + return calendar; + } + ); +} + +export default connect(createMapStateToProps)(Agenda); diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.css b/frontend/src/Calendar/Agenda/AgendaEvent.css index 7ad9ccf6a..38b4f50f3 100644 --- a/frontend/src/Calendar/Agenda/AgendaEvent.css +++ b/frontend/src/Calendar/Agenda/AgendaEvent.css @@ -1,27 +1,12 @@ .event { - position: relative; - padding: 5px; - border-bottom: 1px solid var(--borderColor); -} - -.underlay { - @add-mixin cover; - - &:hover { - background-color: var(--tableRowHoverBackgroundColor); - } -} - -.overlay { - @add-mixin linkOverlay; - - position: relative; display: flex; overflow-x: hidden; + padding: 5px; + border-bottom: 1px solid $borderColor; font-size: $defaultFontSize; - &:global(.colorImpaired) { - border-left-width: 5px; + &:hover { + background-color: $tableRowHoverBackgroundColor; } } @@ -71,8 +56,6 @@ .statusIcon { margin-left: 3px; - cursor: default; - pointer-events: all; } /* @@ -103,12 +86,8 @@ composes: premiere from '~Calendar/Events/CalendarEvent.css'; } -.unaired { - composes: unaired from '~Calendar/Events/CalendarEvent.css'; -} - @media only screen and (max-width: $breakpointSmall) { - .overlay { + .event { flex-direction: column; } diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.css.d.ts b/frontend/src/Calendar/Agenda/AgendaEvent.css.d.ts deleted file mode 100644 index 288e11824..000000000 --- a/frontend/src/Calendar/Agenda/AgendaEvent.css.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'absoluteEpisodeNumber': string; - 'date': string; - 'downloaded': string; - 'downloading': string; - 'episodeSeparator': string; - 'episodeTitle': string; - 'event': string; - 'eventWrapper': string; - 'missing': string; - 'onAir': string; - 'overlay': string; - 'premiere': string; - 'seasonEpisodeNumber': string; - 'seriesTitle': string; - 'statusIcon': string; - 'time': string; - 'unaired': string; - 'underlay': string; - 'unmonitored': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.js b/frontend/src/Calendar/Agenda/AgendaEvent.js new file mode 100644 index 000000000..3d5aa36fb --- /dev/null +++ b/frontend/src/Calendar/Agenda/AgendaEvent.js @@ -0,0 +1,253 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import formatTime from 'Utilities/Date/formatTime'; +import padNumber from 'Utilities/Number/padNumber'; +import { icons, kinds } from 'Helpers/Props'; +import getStatusStyle from 'Calendar/getStatusStyle'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import episodeEntities from 'Episode/episodeEntities'; +import EpisodeDetailsModal from 'Episode/EpisodeDetailsModal'; +import CalendarEventQueueDetails from 'Calendar/Events/CalendarEventQueueDetails'; +import styles from './AgendaEvent.css'; + +class AgendaEvent extends Component { + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isDetailsModalOpen: false + }; + } + + // + // Listeners + + onPress = () => { + this.setState({ isDetailsModalOpen: true }); + } + + onDetailsModalClose = () => { + this.setState({ isDetailsModalOpen: false }); + } + + // + // Render + + render() { + const { + id, + series, + episodeFile, + title, + seasonNumber, + episodeNumber, + absoluteEpisodeNumber, + airDateUtc, + monitored, + hasFile, + grabbed, + queueItem, + showDate, + showEpisodeInformation, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + timeFormat, + longDateFormat, + colorImpairedMode + } = this.props; + + const startTime = moment(airDateUtc); + const endTime = moment(airDateUtc).add(series.runtime, 'minutes'); + const downloading = !!(queueItem || grabbed); + const isMonitored = series.monitored && monitored; + const statusStyle = getStatusStyle(hasFile, downloading, startTime, endTime, isMonitored); + const missingAbsoluteNumber = series.seriesType === 'anime' && seasonNumber > 0 && !absoluteEpisodeNumber; + const season = series.seasons.find((s) => s.seasonNumber === seasonNumber); + const seasonStatistics = season.statistics || {}; + + return ( +
+ +
+ { + showDate && + startTime.format(longDateFormat) + } +
+ +
+
+ {formatTime(airDateUtc, timeFormat)} - {formatTime(endTime.toISOString(), timeFormat, { includeMinuteZero: true })} +
+ +
+ {series.title} +
+ + { + showEpisodeInformation && +
+ {seasonNumber}x{padNumber(episodeNumber, 2)} + + { + series.seriesType === 'anime' && absoluteEpisodeNumber && + ({absoluteEpisodeNumber}) + } + +
-
+
+ } + +
+ { + showEpisodeInformation && + title + } +
+ + { + missingAbsoluteNumber && + + } + + { + !!queueItem && + + + + } + + { + !queueItem && grabbed && + + } + + { + showCutoffUnmetIcon && + !!episodeFile && + episodeFile.qualityCutoffNotMet && + + } + + { + showCutoffUnmetIcon && + !!episodeFile && + episodeFile.languageCutoffNotMet && + !episodeFile.qualityCutoffNotMet && + + } + + { + episodeNumber === 1 && seasonNumber > 0 && + + } + + { + showFinaleIcon && + episodeNumber !== 1 && + seasonNumber > 0 && + episodeNumber === seasonStatistics.totalEpisodeCount && + + } + + { + showSpecialIcon && + (episodeNumber === 0 || seasonNumber === 0) && + + } +
+ + + +
+ ); + } +} + +AgendaEvent.propTypes = { + id: PropTypes.number.isRequired, + series: PropTypes.object.isRequired, + episodeFile: PropTypes.object, + title: PropTypes.string.isRequired, + seasonNumber: PropTypes.number.isRequired, + episodeNumber: PropTypes.number.isRequired, + absoluteEpisodeNumber: PropTypes.number, + airDateUtc: PropTypes.string.isRequired, + monitored: PropTypes.bool.isRequired, + hasFile: PropTypes.bool.isRequired, + grabbed: PropTypes.bool, + queueItem: PropTypes.object, + showDate: PropTypes.bool.isRequired, + showEpisodeInformation: PropTypes.bool.isRequired, + showFinaleIcon: PropTypes.bool.isRequired, + showSpecialIcon: PropTypes.bool.isRequired, + showCutoffUnmetIcon: PropTypes.bool.isRequired, + timeFormat: PropTypes.string.isRequired, + longDateFormat: PropTypes.string.isRequired, + colorImpairedMode: PropTypes.bool.isRequired +}; + +export default AgendaEvent; diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.tsx b/frontend/src/Calendar/Agenda/AgendaEvent.tsx deleted file mode 100644 index 2fd2d7c54..000000000 --- a/frontend/src/Calendar/Agenda/AgendaEvent.tsx +++ /dev/null @@ -1,227 +0,0 @@ -import classNames from 'classnames'; -import moment from 'moment'; -import React, { useCallback, useState } from 'react'; -import { useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import CalendarEventQueueDetails from 'Calendar/Events/CalendarEventQueueDetails'; -import getStatusStyle from 'Calendar/getStatusStyle'; -import Icon from 'Components/Icon'; -import Link from 'Components/Link/Link'; -import EpisodeDetailsModal from 'Episode/EpisodeDetailsModal'; -import episodeEntities from 'Episode/episodeEntities'; -import getFinaleTypeName from 'Episode/getFinaleTypeName'; -import useEpisodeFile from 'EpisodeFile/useEpisodeFile'; -import { icons, kinds } from 'Helpers/Props'; -import useSeries from 'Series/useSeries'; -import { createQueueItemSelectorForHook } from 'Store/Selectors/createQueueItemSelector'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import formatTime from 'Utilities/Date/formatTime'; -import padNumber from 'Utilities/Number/padNumber'; -import translate from 'Utilities/String/translate'; -import styles from './AgendaEvent.css'; - -interface AgendaEventProps { - id: number; - seriesId: number; - episodeFileId: number; - title: string; - seasonNumber: number; - episodeNumber: number; - absoluteEpisodeNumber?: number; - airDateUtc: string; - monitored: boolean; - unverifiedSceneNumbering?: boolean; - finaleType?: string; - hasFile: boolean; - grabbed?: boolean; - showDate: boolean; -} - -function AgendaEvent(props: AgendaEventProps) { - const { - id, - seriesId, - episodeFileId, - title, - seasonNumber, - episodeNumber, - absoluteEpisodeNumber, - airDateUtc, - monitored, - unverifiedSceneNumbering, - finaleType, - hasFile, - grabbed, - showDate, - } = props; - - const series = useSeries(seriesId)!; - const episodeFile = useEpisodeFile(episodeFileId); - const queueItem = useSelector(createQueueItemSelectorForHook(id)); - const { timeFormat, longDateFormat, enableColorImpairedMode } = useSelector( - createUISettingsSelector() - ); - - const { - showEpisodeInformation, - showFinaleIcon, - showSpecialIcon, - showCutoffUnmetIcon, - } = useSelector((state: AppState) => state.calendar.options); - - const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); - - const startTime = moment(airDateUtc); - const endTime = moment(airDateUtc).add(series.runtime, 'minutes'); - const downloading = !!(queueItem || grabbed); - const isMonitored = series.monitored && monitored; - const statusStyle = getStatusStyle( - hasFile, - downloading, - startTime, - endTime, - isMonitored - ); - const missingAbsoluteNumber = - series.seriesType === 'anime' && seasonNumber > 0 && !absoluteEpisodeNumber; - - const handlePress = useCallback(() => { - setIsDetailsModalOpen(true); - }, []); - - const handleDetailsModalClose = useCallback(() => { - setIsDetailsModalOpen(false); - }, []); - - return ( -
- - -
-
- {showDate && startTime.format(longDateFormat)} -
- -
-
- {formatTime(airDateUtc, timeFormat)} -{' '} - {formatTime(endTime.toISOString(), timeFormat, { - includeMinuteZero: true, - })} -
- -
{series.title}
- - {showEpisodeInformation ? ( -
- {seasonNumber}x{padNumber(episodeNumber, 2)} - {series.seriesType === 'anime' && absoluteEpisodeNumber && ( - - ({absoluteEpisodeNumber}) - - )} -
-
-
- ) : null} - -
- {showEpisodeInformation ? title : null} -
- - {missingAbsoluteNumber ? ( - - ) : null} - - {unverifiedSceneNumbering && !missingAbsoluteNumber ? ( - - ) : null} - - {queueItem ? ( - - - - ) : null} - - {!queueItem && grabbed ? ( - - ) : null} - - {showCutoffUnmetIcon && - episodeFile && - episodeFile.qualityCutoffNotMet ? ( - - ) : null} - - {episodeNumber === 1 && seasonNumber > 0 && ( - - )} - - {showFinaleIcon && finaleType ? ( - - ) : null} - - {showSpecialIcon && (episodeNumber === 0 || seasonNumber === 0) ? ( - - ) : null} -
-
- - -
- ); -} - -export default AgendaEvent; diff --git a/frontend/src/Calendar/Agenda/AgendaEventConnector.js b/frontend/src/Calendar/Agenda/AgendaEventConnector.js new file mode 100644 index 000000000..e1d996225 --- /dev/null +++ b/frontend/src/Calendar/Agenda/AgendaEventConnector.js @@ -0,0 +1,30 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createEpisodeFileSelector from 'Store/Selectors/createEpisodeFileSelector'; +import createSeriesSelector from 'Store/Selectors/createSeriesSelector'; +import createQueueItemSelector from 'Store/Selectors/createQueueItemSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import AgendaEvent from './AgendaEvent'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar.options, + createSeriesSelector(), + createEpisodeFileSelector(), + createQueueItemSelector(), + createUISettingsSelector(), + (calendarOptions, series, episodeFile, queueItem, uiSettings) => { + return { + series, + episodeFile, + queueItem, + ...calendarOptions, + timeFormat: uiSettings.timeFormat, + longDateFormat: uiSettings.longDateFormat, + colorImpairedMode: uiSettings.enableColorImpairedMode + }; + } + ); +} + +export default connect(createMapStateToProps)(AgendaEvent); diff --git a/frontend/src/Calendar/Calendar.css.d.ts b/frontend/src/Calendar/Calendar.css.d.ts deleted file mode 100644 index 503034402..000000000 --- a/frontend/src/Calendar/Calendar.css.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'calendar': string; - 'calendarContent': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Calendar.js b/frontend/src/Calendar/Calendar.js new file mode 100644 index 000000000..6ceb1f3bb --- /dev/null +++ b/frontend/src/Calendar/Calendar.js @@ -0,0 +1,64 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import * as calendarViews from './calendarViews'; +import CalendarHeaderConnector from './Header/CalendarHeaderConnector'; +import DaysOfWeekConnector from './Day/DaysOfWeekConnector'; +import CalendarDaysConnector from './Day/CalendarDaysConnector'; +import AgendaConnector from './Agenda/AgendaConnector'; +import styles from './Calendar.css'; + +class Calendar extends Component { + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + view + } = this.props; + + return ( +
+ { + isFetching && !isPopulated && + + } + + { + !isFetching && !!error && +
Unable to load the calendar
+ } + + { + !error && isPopulated && view === calendarViews.AGENDA && +
+ + +
+ } + + { + !error && isPopulated && view !== calendarViews.AGENDA && +
+ + + +
+ } +
+ ); + } +} + +Calendar.propTypes = { + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + view: PropTypes.string.isRequired +}; + +export default Calendar; diff --git a/frontend/src/Calendar/Calendar.tsx b/frontend/src/Calendar/Calendar.tsx deleted file mode 100644 index caa337cf0..000000000 --- a/frontend/src/Calendar/Calendar.tsx +++ /dev/null @@ -1,170 +0,0 @@ -import React, { useCallback, useEffect, useRef } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import * as commandNames from 'Commands/commandNames'; -import Alert from 'Components/Alert'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import Episode from 'Episode/Episode'; -import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { kinds } from 'Helpers/Props'; -import { - clearCalendar, - fetchCalendar, - gotoCalendarToday, -} from 'Store/Actions/calendarActions'; -import { - clearEpisodeFiles, - fetchEpisodeFiles, -} from 'Store/Actions/episodeFileActions'; -import { - clearQueueDetails, - fetchQueueDetails, -} from 'Store/Actions/queueActions'; -import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; -import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; -import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; -import { - registerPagePopulator, - unregisterPagePopulator, -} from 'Utilities/pagePopulator'; -import translate from 'Utilities/String/translate'; -import Agenda from './Agenda/Agenda'; -import CalendarDays from './Day/CalendarDays'; -import DaysOfWeek from './Day/DaysOfWeek'; -import CalendarHeader from './Header/CalendarHeader'; -import styles from './Calendar.css'; - -const UPDATE_DELAY = 3600000; // 1 hour - -function Calendar() { - const dispatch = useDispatch(); - const requestCurrentPage = useCurrentPage(); - const updateTimeout = useRef>(); - - const { isFetching, isPopulated, error, items, time, view } = useSelector( - (state: AppState) => state.calendar - ); - - const isRefreshingSeries = useSelector( - createCommandExecutingSelector(commandNames.REFRESH_SERIES) - ); - - const firstDayOfWeek = useSelector( - (state: AppState) => state.settings.ui.item.firstDayOfWeek - ); - - const wasRefreshingSeries = usePrevious(isRefreshingSeries); - const previousFirstDayOfWeek = usePrevious(firstDayOfWeek); - const previousItems = usePrevious(items); - - const handleScheduleUpdate = useCallback(() => { - clearTimeout(updateTimeout.current); - - function updateCalendar() { - dispatch(gotoCalendarToday()); - updateTimeout.current = setTimeout(updateCalendar, UPDATE_DELAY); - } - - updateTimeout.current = setTimeout(updateCalendar, UPDATE_DELAY); - }, [dispatch]); - - useEffect(() => { - handleScheduleUpdate(); - - return () => { - dispatch(clearCalendar()); - dispatch(clearQueueDetails()); - dispatch(clearEpisodeFiles()); - clearTimeout(updateTimeout.current); - }; - }, [dispatch, handleScheduleUpdate]); - - useEffect(() => { - if (requestCurrentPage) { - dispatch(fetchCalendar()); - } else { - dispatch(gotoCalendarToday()); - } - }, [requestCurrentPage, dispatch]); - - useEffect(() => { - const repopulate = () => { - dispatch(fetchQueueDetails({ time, view })); - dispatch(fetchCalendar({ time, view })); - }; - - registerPagePopulator(repopulate, [ - 'episodeFileUpdated', - 'episodeFileDeleted', - ]); - - return () => { - unregisterPagePopulator(repopulate); - }; - }, [time, view, dispatch]); - - useEffect(() => { - handleScheduleUpdate(); - }, [time, handleScheduleUpdate]); - - useEffect(() => { - if ( - previousFirstDayOfWeek != null && - firstDayOfWeek !== previousFirstDayOfWeek - ) { - dispatch(fetchCalendar({ time, view })); - } - }, [time, view, firstDayOfWeek, previousFirstDayOfWeek, dispatch]); - - useEffect(() => { - if (wasRefreshingSeries && !isRefreshingSeries) { - dispatch(fetchCalendar({ time, view })); - } - }, [time, view, isRefreshingSeries, wasRefreshingSeries, dispatch]); - - useEffect(() => { - if (!previousItems || hasDifferentItems(items, previousItems)) { - const episodeIds = selectUniqueIds(items, 'id'); - const episodeFileIds = selectUniqueIds( - items, - 'episodeFileId' - ); - - if (items.length) { - dispatch(fetchQueueDetails({ episodeIds })); - } - - if (episodeFileIds.length) { - dispatch(fetchEpisodeFiles({ episodeFileIds })); - } - } - }, [items, previousItems, dispatch]); - - return ( -
- {isFetching && !isPopulated ? : null} - - {!isFetching && error ? ( - {translate('CalendarLoadError')} - ) : null} - - {!error && isPopulated && view === 'agenda' ? ( -
- - -
- ) : null} - - {!error && isPopulated && view !== 'agenda' ? ( -
- - - -
- ) : null} -
- ); -} - -export default Calendar; diff --git a/frontend/src/Calendar/CalendarConnector.js b/frontend/src/Calendar/CalendarConnector.js new file mode 100644 index 000000000..636026c56 --- /dev/null +++ b/frontend/src/Calendar/CalendarConnector.js @@ -0,0 +1,196 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; +import * as calendarActions from 'Store/Actions/calendarActions'; +import { fetchEpisodeFiles, clearEpisodeFiles } from 'Store/Actions/episodeFileActions'; +import { fetchQueueDetails, clearQueueDetails } from 'Store/Actions/queueActions'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import * as commandNames from 'Commands/commandNames'; +import Calendar from './Calendar'; + +const UPDATE_DELAY = 3600000; // 1 hour + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar, + (state) => state.settings.ui.item.firstDayOfWeek, + createCommandExecutingSelector(commandNames.REFRESH_SERIES), + (calendar, firstDayOfWeek, isRefreshingSeries) => { + return { + ...calendar, + isRefreshingSeries, + firstDayOfWeek + }; + } + ); +} + +const mapDispatchToProps = { + ...calendarActions, + fetchEpisodeFiles, + clearEpisodeFiles, + fetchQueueDetails, + clearQueueDetails +}; + +class CalendarConnector extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.updateTimeoutId = null; + } + + componentDidMount() { + const { + useCurrentPage, + fetchCalendar, + gotoCalendarToday + } = this.props; + + registerPagePopulator(this.repopulate); + + if (useCurrentPage) { + fetchCalendar(); + } else { + gotoCalendarToday(); + } + + this.scheduleUpdate(); + } + + componentDidUpdate(prevProps) { + const { + items, + time, + view, + isRefreshingSeries, + firstDayOfWeek + } = this.props; + + if (hasDifferentItems(prevProps.items, items)) { + const episodeIds = selectUniqueIds(items, 'id'); + const episodeFileIds = selectUniqueIds(items, 'episodeFileId'); + + if (items.length) { + this.props.fetchQueueDetails({ episodeIds }); + } + + if (episodeFileIds.length) { + this.props.fetchEpisodeFiles({ episodeFileIds }); + } + } + + if (prevProps.time !== time) { + this.scheduleUpdate(); + } + + if (prevProps.firstDayOfWeek !== firstDayOfWeek) { + this.props.fetchCalendar({ time, view }); + } + + if (prevProps.isRefreshingSeries && !isRefreshingSeries) { + this.props.fetchCalendar({ time, view }); + } + } + + componentWillUnmount() { + unregisterPagePopulator(this.repopulate); + this.props.clearCalendar(); + this.props.clearQueueDetails(); + this.props.clearEpisodeFiles(); + this.clearUpdateTimeout(); + } + + // + // Control + + repopulate = () => { + const { + time, + view + } = this.props; + + this.props.fetchQueueDetails({ time, view }); + this.props.fetchCalendar({ time, view }); + } + + scheduleUpdate = () => { + this.clearUpdateTimeout(); + + this.updateTimeoutId = setTimeout(this.updateCalendar, UPDATE_DELAY); + } + + clearUpdateTimeout = () => { + if (this.updateTimeoutId) { + clearTimeout(this.updateTimeoutId); + } + } + + updateCalendar = () => { + this.props.gotoCalendarToday(); + this.scheduleUpdate(); + } + + // + // Listeners + + onCalendarViewChange = (view) => { + this.props.setCalendarView({ view }); + } + + onTodayPress = () => { + this.props.gotoCalendarToday(); + } + + onPreviousPress = () => { + this.props.gotoCalendarPreviousRange(); + } + + onNextPress = () => { + this.props.gotoCalendarNextRange(); + } + + // + // Render + + render() { + return ( + + ); + } +} + +CalendarConnector.propTypes = { + useCurrentPage: PropTypes.bool.isRequired, + time: PropTypes.string, + view: PropTypes.string.isRequired, + firstDayOfWeek: PropTypes.number.isRequired, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + isRefreshingSeries: PropTypes.bool.isRequired, + setCalendarView: PropTypes.func.isRequired, + gotoCalendarToday: PropTypes.func.isRequired, + gotoCalendarPreviousRange: PropTypes.func.isRequired, + gotoCalendarNextRange: PropTypes.func.isRequired, + clearCalendar: PropTypes.func.isRequired, + fetchCalendar: PropTypes.func.isRequired, + fetchEpisodeFiles: PropTypes.func.isRequired, + clearEpisodeFiles: PropTypes.func.isRequired, + fetchQueueDetails: PropTypes.func.isRequired, + clearQueueDetails: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(CalendarConnector); diff --git a/frontend/src/Calendar/CalendarFilterModal.tsx b/frontend/src/Calendar/CalendarFilterModal.tsx deleted file mode 100644 index e26b2928b..000000000 --- a/frontend/src/Calendar/CalendarFilterModal.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import React, { useCallback } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import FilterModal from 'Components/Filter/FilterModal'; -import { setCalendarFilter } from 'Store/Actions/calendarActions'; - -function createCalendarSelector() { - return createSelector( - (state: AppState) => state.calendar.items, - (calendar) => { - return calendar; - } - ); -} - -function createFilterBuilderPropsSelector() { - return createSelector( - (state: AppState) => state.calendar.filterBuilderProps, - (filterBuilderProps) => { - return filterBuilderProps; - } - ); -} - -interface CalendarFilterModalProps { - isOpen: boolean; -} - -export default function CalendarFilterModal(props: CalendarFilterModalProps) { - const sectionItems = useSelector(createCalendarSelector()); - const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); - const customFilterType = 'calendar'; - - const dispatch = useDispatch(); - - const dispatchSetFilter = useCallback( - (payload: unknown) => { - dispatch(setCalendarFilter(payload)); - }, - [dispatch] - ); - - return ( - - ); -} diff --git a/frontend/src/Calendar/CalendarPage.css.d.ts b/frontend/src/Calendar/CalendarPage.css.d.ts deleted file mode 100644 index 30befba55..000000000 --- a/frontend/src/Calendar/CalendarPage.css.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'calendarInnerPageBody': string; - 'calendarPageBody': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/CalendarPage.js b/frontend/src/Calendar/CalendarPage.js new file mode 100644 index 000000000..5e4f1c6db --- /dev/null +++ b/frontend/src/Calendar/CalendarPage.js @@ -0,0 +1,192 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { align, icons } from 'Helpers/Props'; +import PageContent from 'Components/Page/PageContent'; +import Measure from 'Components/Measure'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import FilterMenu from 'Components/Menu/FilterMenu'; +import NoSeries from 'Series/NoSeries'; +import CalendarLinkModal from './iCal/CalendarLinkModal'; +import CalendarOptionsModal from './Options/CalendarOptionsModal'; +import LegendConnector from './Legend/LegendConnector'; +import CalendarConnector from './CalendarConnector'; +import styles from './CalendarPage.css'; + +const MINIMUM_DAY_WIDTH = 120; + +class CalendarPage extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isCalendarLinkModalOpen: false, + isOptionsModalOpen: false, + width: 0 + }; + } + + // + // Listeners + + onMeasure = ({ width }) => { + this.setState({ width }); + const days = Math.max(3, Math.min(7, Math.floor(width / MINIMUM_DAY_WIDTH))); + + this.props.onDaysCountChange(days); + } + + onGetCalendarLinkPress = () => { + this.setState({ isCalendarLinkModalOpen: true }); + } + + onGetCalendarLinkModalClose = () => { + this.setState({ isCalendarLinkModalOpen: false }); + } + + onOptionsPress = () => { + this.setState({ isOptionsModalOpen: true }); + } + + onOptionsModalClose = () => { + this.setState({ isOptionsModalOpen: false }); + } + + onSearchMissingPress = () => { + const { + missingEpisodeIds, + onSearchMissingPress + } = this.props; + + onSearchMissingPress(missingEpisodeIds); + } + + // + // Render + + render() { + const { + selectedFilterKey, + filters, + hasSeries, + missingEpisodeIds, + isRssSyncExecuting, + isSearchingForMissing, + useCurrentPage, + onRssSyncPress, + onFilterSelect + } = this.props; + + const { + isCalendarLinkModalOpen, + isOptionsModalOpen + } = this.state; + + const isMeasured = this.state.width > 0; + const PageComponent = hasSeries ? CalendarConnector : NoSeries; + + return ( + + + + + + + + + + + + + + + + + + + + + + { + isMeasured ? + : +
+ } + + + { + hasSeries && + + } + + + + + + + ); + } +} + +CalendarPage.propTypes = { + selectedFilterKey: PropTypes.string.isRequired, + filters: PropTypes.arrayOf(PropTypes.object).isRequired, + hasSeries: PropTypes.bool.isRequired, + missingEpisodeIds: PropTypes.arrayOf(PropTypes.number).isRequired, + isRssSyncExecuting: PropTypes.bool.isRequired, + isSearchingForMissing: PropTypes.bool.isRequired, + useCurrentPage: PropTypes.bool.isRequired, + onSearchMissingPress: PropTypes.func.isRequired, + onDaysCountChange: PropTypes.func.isRequired, + onRssSyncPress: PropTypes.func.isRequired, + onFilterSelect: PropTypes.func.isRequired +}; + +export default CalendarPage; diff --git a/frontend/src/Calendar/CalendarPage.tsx b/frontend/src/Calendar/CalendarPage.tsx deleted file mode 100644 index f408b6a60..000000000 --- a/frontend/src/Calendar/CalendarPage.tsx +++ /dev/null @@ -1,226 +0,0 @@ -import moment from 'moment'; -import React, { useCallback, useState } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import * as commandNames from 'Commands/commandNames'; -import Measure from 'Components/Measure'; -import FilterMenu from 'Components/Menu/FilterMenu'; -import PageContent from 'Components/Page/PageContent'; -import PageContentBody from 'Components/Page/PageContentBody'; -import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; -import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; -import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; -import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator'; -import { align, icons } from 'Helpers/Props'; -import NoSeries from 'Series/NoSeries'; -import { - searchMissing, - setCalendarDaysCount, - setCalendarFilter, -} from 'Store/Actions/calendarActions'; -import { executeCommand } from 'Store/Actions/commandActions'; -import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; -import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; -import createCommandsSelector from 'Store/Selectors/createCommandsSelector'; -import createSeriesCountSelector from 'Store/Selectors/createSeriesCountSelector'; -import { isCommandExecuting } from 'Utilities/Command'; -import isBefore from 'Utilities/Date/isBefore'; -import translate from 'Utilities/String/translate'; -import Calendar from './Calendar'; -import CalendarFilterModal from './CalendarFilterModal'; -import CalendarLinkModal from './iCal/CalendarLinkModal'; -import Legend from './Legend/Legend'; -import CalendarOptionsModal from './Options/CalendarOptionsModal'; -import styles from './CalendarPage.css'; - -const MINIMUM_DAY_WIDTH = 120; - -function createMissingEpisodeIdsSelector() { - return createSelector( - (state: AppState) => state.calendar.start, - (state: AppState) => state.calendar.end, - (state: AppState) => state.calendar.items, - (state: AppState) => state.queue.details.items, - (start, end, episodes, queueDetails) => { - return episodes.reduce((acc, episode) => { - const airDateUtc = episode.airDateUtc; - - if ( - !episode.episodeFileId && - moment(airDateUtc).isAfter(start) && - moment(airDateUtc).isBefore(end) && - isBefore(episode.airDateUtc) && - !queueDetails.some( - (details) => !!details.episode && details.episode.id === episode.id - ) - ) { - acc.push(episode.id); - } - - return acc; - }, []); - } - ); -} - -function createIsSearchingSelector() { - return createSelector( - (state: AppState) => state.calendar.searchMissingCommandId, - createCommandsSelector(), - (searchMissingCommandId, commands) => { - if (searchMissingCommandId == null) { - return false; - } - - return isCommandExecuting( - commands.find((command) => { - return command.id === searchMissingCommandId; - }) - ); - } - ); -} - -function CalendarPage() { - const dispatch = useDispatch(); - - const { selectedFilterKey, filters } = useSelector( - (state: AppState) => state.calendar - ); - const missingEpisodeIds = useSelector(createMissingEpisodeIdsSelector()); - const isSearchingForMissing = useSelector(createIsSearchingSelector()); - const isRssSyncExecuting = useSelector( - createCommandExecutingSelector(commandNames.RSS_SYNC) - ); - const customFilters = useSelector(createCustomFiltersSelector('calendar')); - const hasSeries = !!useSelector(createSeriesCountSelector()); - - const [isCalendarLinkModalOpen, setIsCalendarLinkModalOpen] = useState(false); - const [isOptionsModalOpen, setIsOptionsModalOpen] = useState(false); - const [width, setWidth] = useState(0); - - const isMeasured = width > 0; - const PageComponent = hasSeries ? Calendar : NoSeries; - - const handleMeasure = useCallback( - ({ width: newWidth }: { width: number }) => { - setWidth(newWidth); - - const dayCount = Math.max( - 3, - Math.min(7, Math.floor(newWidth / MINIMUM_DAY_WIDTH)) - ); - - dispatch(setCalendarDaysCount({ dayCount })); - }, - [dispatch] - ); - - const handleGetCalendarLinkPress = useCallback(() => { - setIsCalendarLinkModalOpen(true); - }, []); - - const handleGetCalendarLinkModalClose = useCallback(() => { - setIsCalendarLinkModalOpen(false); - }, []); - - const handleOptionsPress = useCallback(() => { - setIsOptionsModalOpen(true); - }, []); - - const handleOptionsModalClose = useCallback(() => { - setIsOptionsModalOpen(false); - }, []); - - const handleRssSyncPress = useCallback(() => { - dispatch( - executeCommand({ - name: commandNames.RSS_SYNC, - }) - ); - }, [dispatch]); - - const handleSearchMissingPress = useCallback(() => { - dispatch(searchMissing({ episodeIds: missingEpisodeIds })); - }, [missingEpisodeIds, dispatch]); - - const handleFilterSelect = useCallback( - (key: string) => { - dispatch(setCalendarFilter({ selectedFilterKey: key })); - }, - [dispatch] - ); - - return ( - - - - - - - - - - - - - - - - - - - - - - {isMeasured ? :
} - - - {hasSeries && } - - - - - - - ); -} - -export default CalendarPage; diff --git a/frontend/src/Calendar/CalendarPageConnector.js b/frontend/src/Calendar/CalendarPageConnector.js new file mode 100644 index 000000000..e039b2824 --- /dev/null +++ b/frontend/src/Calendar/CalendarPageConnector.js @@ -0,0 +1,113 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import moment from 'moment'; +import { isCommandExecuting } from 'Utilities/Command'; +import isBefore from 'Utilities/Date/isBefore'; +import * as commandNames from 'Commands/commandNames'; +import withCurrentPage from 'Components/withCurrentPage'; +import { executeCommand } from 'Store/Actions/commandActions'; +import { searchMissing, setCalendarDaysCount, setCalendarFilter } from 'Store/Actions/calendarActions'; +import createSeriesCountSelector from 'Store/Selectors/createSeriesCountSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import createCommandsSelector from 'Store/Selectors/createCommandsSelector'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import CalendarPage from './CalendarPage'; + +function createMissingEpisodeIdsSelector() { + return createSelector( + (state) => state.calendar.start, + (state) => state.calendar.end, + (state) => state.calendar.items, + (state) => state.queue.details.items, + (start, end, episodes, queueDetails) => { + return episodes.reduce((acc, episode) => { + const airDateUtc = episode.airDateUtc; + + if ( + !episode.episodeFileId && + moment(airDateUtc).isAfter(start) && + moment(airDateUtc).isBefore(end) && + isBefore(episode.airDateUtc) && + !queueDetails.some((details) => !!details.episode && details.episode.id === episode.id) + ) { + acc.push(episode.id); + } + + return acc; + }, []); + } + ); +} + +function createIsSearchingSelector() { + return createSelector( + (state) => state.calendar.searchMissingCommandId, + createCommandsSelector(), + (searchMissingCommandId, commands) => { + if (searchMissingCommandId == null) { + return false; + } + + return isCommandExecuting(commands.find((command) => { + return command.id === searchMissingCommandId; + })); + } + ); +} + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar.selectedFilterKey, + (state) => state.calendar.filters, + createSeriesCountSelector(), + createUISettingsSelector(), + createMissingEpisodeIdsSelector(), + createCommandExecutingSelector(commandNames.RSS_SYNC), + createIsSearchingSelector(), + ( + selectedFilterKey, + filters, + seriesCount, + uiSettings, + missingEpisodeIds, + isRssSyncExecuting, + isSearchingForMissing + ) => { + return { + selectedFilterKey, + filters, + colorImpairedMode: uiSettings.enableColorImpairedMode, + hasSeries: !!seriesCount, + missingEpisodeIds, + isRssSyncExecuting, + isSearchingForMissing + }; + } + ); +} + +function createMapDispatchToProps(dispatch, props) { + return { + onRssSyncPress() { + dispatch(executeCommand({ + name: commandNames.RSS_SYNC + })); + }, + + onSearchMissingPress(episodeIds) { + dispatch(searchMissing({ episodeIds })); + }, + + onDaysCountChange(dayCount) { + dispatch(setCalendarDaysCount({ dayCount })); + }, + + onFilterSelect(selectedFilterKey) { + dispatch(setCalendarFilter({ selectedFilterKey })); + } + }; +} + +export default withCurrentPage( + connect(createMapStateToProps, createMapDispatchToProps)(CalendarPage) +); diff --git a/frontend/src/Calendar/Day/CalendarDay.css b/frontend/src/Calendar/Day/CalendarDay.css index 22d1b1ccf..79eb67ae7 100644 --- a/frontend/src/Calendar/Day/CalendarDay.css +++ b/frontend/src/Calendar/Day/CalendarDay.css @@ -2,8 +2,8 @@ flex: 1 0 14.28%; overflow: hidden; min-height: 70px; - border-bottom: 1px solid var(--calendarBorderColor); - border-left: 1px solid var(--calendarBorderColor); + border-bottom: 1px solid $calendarBorderColor; + border-left: 1px solid $calendarBorderColor; } .isSingleDay { @@ -12,14 +12,14 @@ .dayOfMonth { padding-right: 5px; - border-bottom: 1px solid var(--calendarBorderColor); + border-bottom: 1px solid $calendarBorderColor; text-align: right; } .isToday { - background-color: var(--calendarTodayBackgroundColor); + background-color: $calendarTodayBackgroundColor; } .isDifferentMonth { - color: var(--disabledColor); + color: $disabledColor; } diff --git a/frontend/src/Calendar/Day/CalendarDay.css.d.ts b/frontend/src/Calendar/Day/CalendarDay.css.d.ts deleted file mode 100644 index f32def3dd..000000000 --- a/frontend/src/Calendar/Day/CalendarDay.css.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'day': string; - 'dayOfMonth': string; - 'isDifferentMonth': string; - 'isSingleDay': string; - 'isToday': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Day/CalendarDay.js b/frontend/src/Calendar/Day/CalendarDay.js new file mode 100644 index 000000000..faa45b28b --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDay.js @@ -0,0 +1,74 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React from 'react'; +import classNames from 'classnames'; +import * as calendarViews from 'Calendar/calendarViews'; +import CalendarEventConnector from 'Calendar/Events/CalendarEventConnector'; +import CalendarEventGroupConnector from 'Calendar/Events/CalendarEventGroupConnector'; +import styles from './CalendarDay.css'; + +function CalendarDay(props) { + const { + date, + time, + isTodaysDate, + events, + view, + onEventModalOpenToggle + } = props; + + return ( +
+ { + view === calendarViews.MONTH && +
+ {moment(date).date()} +
+ } +
+ { + events.map((event) => { + if (event.isGroup) { + return ( + + ); + } + + return ( + + ); + }) + } +
+
+ ); +} + +CalendarDay.propTypes = { + date: PropTypes.string.isRequired, + time: PropTypes.string.isRequired, + isTodaysDate: PropTypes.bool.isRequired, + events: PropTypes.arrayOf(PropTypes.object).isRequired, + view: PropTypes.string.isRequired, + onEventModalOpenToggle: PropTypes.func.isRequired +}; + +export default CalendarDay; diff --git a/frontend/src/Calendar/Day/CalendarDay.tsx b/frontend/src/Calendar/Day/CalendarDay.tsx deleted file mode 100644 index a619109ca..000000000 --- a/frontend/src/Calendar/Day/CalendarDay.tsx +++ /dev/null @@ -1,159 +0,0 @@ -import classNames from 'classnames'; -import moment from 'moment'; -import React from 'react'; -import { useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import * as calendarViews from 'Calendar/calendarViews'; -import CalendarEvent from 'Calendar/Events/CalendarEvent'; -import CalendarEventGroup from 'Calendar/Events/CalendarEventGroup'; -import { - CalendarEvent as CalendarEventModel, - CalendarEventGroup as CalendarEventGroupModel, - CalendarItem, -} from 'typings/Calendar'; -import styles from './CalendarDay.css'; - -function sort(items: (CalendarEventModel | CalendarEventGroupModel)[]) { - return items.sort((a, b) => { - const aDate = a.isGroup - ? moment(a.events[0].airDateUtc).unix() - : moment(a.airDateUtc).unix(); - - const bDate = b.isGroup - ? moment(b.events[0].airDateUtc).unix() - : moment(b.airDateUtc).unix(); - - return aDate - bDate; - }); -} - -function createCalendarEventsConnector(date: string) { - return createSelector( - (state: AppState) => state.calendar.items, - (state: AppState) => state.calendar.options.collapseMultipleEpisodes, - (items, collapseMultipleEpisodes) => { - const momentDate = moment(date); - - const filtered = items.filter((item) => { - return momentDate.isSame(moment(item.airDateUtc), 'day'); - }); - - if (!collapseMultipleEpisodes) { - return sort( - filtered.map((item) => ({ - isGroup: false, - ...item, - })) - ); - } - - const groupedObject = Object.groupBy( - filtered, - (item: CalendarItem) => `${item.seriesId}-${item.seasonNumber}` - ); - - const grouped = Object.entries(groupedObject).reduce< - (CalendarEventModel | CalendarEventGroupModel)[] - >((acc, [, events]) => { - if (!events) { - return acc; - } - - if (events.length === 1) { - acc.push({ - isGroup: false, - ...events[0], - }); - } else { - acc.push({ - isGroup: true, - seriesId: events[0].seriesId, - seasonNumber: events[0].seasonNumber, - episodeIds: events.map((event) => event.id), - events: events.sort( - (a, b) => - moment(a.airDateUtc).unix() - moment(b.airDateUtc).unix() - ), - }); - } - - return acc; - }, []); - - return sort(grouped); - } - ); -} - -interface CalendarDayProps { - date: string; - isTodaysDate: boolean; - onEventModalOpenToggle(isOpen: boolean): unknown; -} - -function CalendarDay({ - date, - isTodaysDate, - onEventModalOpenToggle, -}: CalendarDayProps) { - const { time, view } = useSelector((state: AppState) => state.calendar); - const events = useSelector(createCalendarEventsConnector(date)); - - const ref = React.useRef(null); - - React.useEffect(() => { - if (isTodaysDate && view === calendarViews.MONTH && ref.current) { - ref.current.scrollIntoView(); - } - }, [time, isTodaysDate, view]); - - return ( -
- {view === calendarViews.MONTH && ( -
- {moment(date).date()} -
- )} -
- {events.map((event) => { - if (event.isGroup) { - return ( - - ); - } - - return ( - - ); - })} -
-
- ); -} - -export default CalendarDay; diff --git a/frontend/src/Calendar/Day/CalendarDayConnector.js b/frontend/src/Calendar/Day/CalendarDayConnector.js new file mode 100644 index 000000000..8fd6cc5a1 --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDayConnector.js @@ -0,0 +1,91 @@ +import _ from 'lodash'; +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import CalendarDay from './CalendarDay'; + +function sort(items) { + return _.sortBy(items, (item) => { + if (item.isGroup) { + return moment(item.events[0].airDateUtc).unix(); + } + + return moment(item.airDateUtc).unix(); + }); +} + +function createCalendarEventsConnector() { + return createSelector( + (state, { date }) => date, + (state) => state.calendar.items, + (state) => state.calendar.options.collapseMultipleEpisodes, + (date, items, collapseMultipleEpisodes) => { + const filtered = _.filter(items, (item) => { + return moment(date).isSame(moment(item.airDateUtc), 'day'); + }); + + if (!collapseMultipleEpisodes) { + return sort(filtered); + } + + const groupedObject = _.groupBy(filtered, (item) => `${item.seriesId}-${item.seasonNumber}`); + const grouped = []; + + Object.keys(groupedObject).forEach((key) => { + const events = groupedObject[key]; + + if (events.length === 1) { + grouped.push(events[0]); + } else { + grouped.push({ + isGroup: true, + seriesId: events[0].seriesId, + seasonNumber: events[0].seasonNumber, + episodeIds: events.map((event) => event.id), + events: _.sortBy(events, (item) => moment(item.airDateUtc).unix()) + }); + } + }); + + const sorted = sort(grouped); + + return sorted; + } + ); +} + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar, + createCalendarEventsConnector(), + (calendar, events) => { + return { + time: calendar.time, + view: calendar.view, + events + }; + } + ); +} + +class CalendarDayConnector extends Component { + + // + // Render + + render() { + return ( + + ); + } +} + +CalendarDayConnector.propTypes = { + date: PropTypes.string.isRequired +}; + +export default connect(createMapStateToProps)(CalendarDayConnector); diff --git a/frontend/src/Calendar/Day/CalendarDays.css b/frontend/src/Calendar/Day/CalendarDays.css index 507dd0ede..b6dd2100c 100644 --- a/frontend/src/Calendar/Day/CalendarDays.css +++ b/frontend/src/Calendar/Day/CalendarDays.css @@ -1,6 +1,6 @@ .days { display: flex; - border-right: 1px solid var(--calendarBorderColor); + border-right: 1px solid $calendarBorderColor; } .day, diff --git a/frontend/src/Calendar/Day/CalendarDays.css.d.ts b/frontend/src/Calendar/Day/CalendarDays.css.d.ts deleted file mode 100644 index ae3e7aebc..000000000 --- a/frontend/src/Calendar/Day/CalendarDays.css.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'day': string; - 'days': string; - 'forecast': string; - 'month': string; - 'week': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Day/CalendarDays.js b/frontend/src/Calendar/Day/CalendarDays.js new file mode 100644 index 000000000..0a1a36172 --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDays.js @@ -0,0 +1,164 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import isToday from 'Utilities/Date/isToday'; +import * as calendarViews from 'Calendar/calendarViews'; +import CalendarDayConnector from './CalendarDayConnector'; +import styles from './CalendarDays.css'; + +class CalendarDays extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._touchStart = null; + + this.state = { + todaysDate: moment().startOf('day').toISOString(), + isEventModalOpen: false + }; + + this.updateTimeoutId = null; + } + + // Lifecycle + + componentDidMount() { + const view = this.props.view; + + if (view === calendarViews.MONTH) { + this.scheduleUpdate(); + } + + window.addEventListener('touchstart', this.onTouchStart); + window.addEventListener('touchend', this.onTouchEnd); + window.addEventListener('touchcancel', this.onTouchCancel); + window.addEventListener('touchmove', this.onTouchMove); + } + + componentWillUnmount() { + this.clearUpdateTimeout(); + + window.removeEventListener('touchstart', this.onTouchStart); + window.removeEventListener('touchend', this.onTouchEnd); + window.removeEventListener('touchcancel', this.onTouchCancel); + window.removeEventListener('touchmove', this.onTouchMove); + } + + // + // Control + + scheduleUpdate = () => { + this.clearUpdateTimeout(); + const todaysDate = moment().startOf('day'); + const diff = moment().diff(todaysDate.clone().add(1, 'day')); + + this.setState({ todaysDate: todaysDate.toISOString() }); + + this.updateTimeoutId = setTimeout(this.scheduleUpdate, diff); + } + + clearUpdateTimeout = () => { + if (this.updateTimeoutId) { + clearTimeout(this.updateTimeoutId); + } + } + + // + // Listeners + + onEventModalOpenToggle = (isEventModalOpen) => { + this.setState({ isEventModalOpen }); + } + + onTouchStart = (event) => { + const touches = event.touches; + const touchStart = touches[0].pageX; + + if (touches.length !== 1) { + return; + } + + if ( + touchStart < 50 || + this.props.isSidebarVisible || + this.state.isEventModalOpen + ) { + return; + } + + this._touchStart = touchStart; + } + + onTouchEnd = (event) => { + const touches = event.changedTouches; + const currentTouch = touches[0].pageX; + + if (!this._touchStart) { + return; + } + + if (currentTouch > this._touchStart && currentTouch - this._touchStart > 100) { + this.props.onNavigatePrevious(); + } else if (currentTouch < this._touchStart && this._touchStart - currentTouch > 100) { + this.props.onNavigateNext(); + } + + this._touchStart = null; + } + + onTouchCancel = (event) => { + this._touchStart = null; + } + + onTouchMove = (event) => { + if (!this._touchStart) { + return; + } + } + + // + // Render + + render() { + const { + dates, + view + } = this.props; + + return ( +
+ { + dates.map((date) => { + return ( + + ); + }) + } +
+ ); + } +} + +CalendarDays.propTypes = { + dates: PropTypes.arrayOf(PropTypes.string).isRequired, + view: PropTypes.string.isRequired, + isSidebarVisible: PropTypes.bool.isRequired, + onNavigatePrevious: PropTypes.func.isRequired, + onNavigateNext: PropTypes.func.isRequired +}; + +export default CalendarDays; diff --git a/frontend/src/Calendar/Day/CalendarDays.tsx b/frontend/src/Calendar/Day/CalendarDays.tsx deleted file mode 100644 index 149dc1455..000000000 --- a/frontend/src/Calendar/Day/CalendarDays.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import classNames from 'classnames'; -import moment from 'moment'; -import React, { useCallback, useEffect, useRef, useState } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import * as calendarViews from 'Calendar/calendarViews'; -import { - gotoCalendarNextRange, - gotoCalendarPreviousRange, -} from 'Store/Actions/calendarActions'; -import CalendarDay from './CalendarDay'; -import styles from './CalendarDays.css'; - -function CalendarDays() { - const dispatch = useDispatch(); - const { dates, view } = useSelector((state: AppState) => state.calendar); - const isSidebarVisible = useSelector( - (state: AppState) => state.app.isSidebarVisible - ); - - const updateTimeout = useRef>(); - const touchStart = useRef(null); - const isEventModalOpen = useRef(false); - const [todaysDate, setTodaysDate] = useState( - moment().startOf('day').toISOString() - ); - - const handleEventModalOpenToggle = useCallback((isOpen: boolean) => { - isEventModalOpen.current = isOpen; - }, []); - - const scheduleUpdate = useCallback(() => { - clearTimeout(updateTimeout.current); - - const todaysDate = moment().startOf('day'); - const diff = moment().diff(todaysDate.clone().add(1, 'day')); - - setTodaysDate(todaysDate.toISOString()); - - updateTimeout.current = setTimeout(scheduleUpdate, diff); - }, []); - - const handleTouchStart = useCallback( - (event: TouchEvent) => { - const touches = event.touches; - const currentTouch = touches[0].pageX; - - if (touches.length !== 1) { - return; - } - - if (currentTouch < 50 || isSidebarVisible || isEventModalOpen.current) { - return; - } - - touchStart.current = currentTouch; - }, - [isSidebarVisible] - ); - - const handleTouchEnd = useCallback( - (event: TouchEvent) => { - const touches = event.changedTouches; - const currentTouch = touches[0].pageX; - - if (!touchStart.current) { - return; - } - - if ( - currentTouch > touchStart.current && - currentTouch - touchStart.current > 100 - ) { - dispatch(gotoCalendarPreviousRange()); - } else if ( - currentTouch < touchStart.current && - touchStart.current - currentTouch > 100 - ) { - dispatch(gotoCalendarNextRange()); - } - - touchStart.current = null; - }, - [dispatch] - ); - - const handleTouchCancel = useCallback(() => { - touchStart.current = null; - }, []); - - const handleTouchMove = useCallback(() => { - if (!touchStart.current) { - return; - } - }, []); - - useEffect(() => { - if (view === calendarViews.MONTH) { - scheduleUpdate(); - } - }, [view, scheduleUpdate]); - - useEffect(() => { - window.addEventListener('touchstart', handleTouchStart); - window.addEventListener('touchend', handleTouchEnd); - window.addEventListener('touchcancel', handleTouchCancel); - window.addEventListener('touchmove', handleTouchMove); - - return () => { - window.removeEventListener('touchstart', handleTouchStart); - window.removeEventListener('touchend', handleTouchEnd); - window.removeEventListener('touchcancel', handleTouchCancel); - window.removeEventListener('touchmove', handleTouchMove); - }; - }, [handleTouchStart, handleTouchEnd, handleTouchCancel, handleTouchMove]); - - return ( -
- {dates.map((date) => { - return ( - - ); - })} -
- ); -} - -export default CalendarDays; diff --git a/frontend/src/Calendar/Day/CalendarDaysConnector.js b/frontend/src/Calendar/Day/CalendarDaysConnector.js new file mode 100644 index 000000000..3dea906a7 --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDaysConnector.js @@ -0,0 +1,25 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { gotoCalendarPreviousRange, gotoCalendarNextRange } from 'Store/Actions/calendarActions'; +import CalendarDays from './CalendarDays'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar, + (state) => state.app.isSidebarVisible, + (calendar, isSidebarVisible) => { + return { + dates: calendar.dates, + view: calendar.view, + isSidebarVisible + }; + } + ); +} + +const mapDispatchToProps = { + onNavigatePrevious: gotoCalendarPreviousRange, + onNavigateNext: gotoCalendarNextRange +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(CalendarDays); diff --git a/frontend/src/Calendar/Day/DayOfWeek.css b/frontend/src/Calendar/Day/DayOfWeek.css index 2d31a30be..8c3552e55 100644 --- a/frontend/src/Calendar/Day/DayOfWeek.css +++ b/frontend/src/Calendar/Day/DayOfWeek.css @@ -1,6 +1,6 @@ .dayOfWeek { flex: 1 0 14.28%; - background-color: var(--calendarBackgroundColor); + background-color: #e4eaec; text-align: center; } @@ -9,5 +9,5 @@ } .isToday { - background-color: var(--calendarTodayBackgroundColor); + background-color: $calendarTodayBackgroundColor; } diff --git a/frontend/src/Calendar/Day/DayOfWeek.css.d.ts b/frontend/src/Calendar/Day/DayOfWeek.css.d.ts deleted file mode 100644 index a377e4a8e..000000000 --- a/frontend/src/Calendar/Day/DayOfWeek.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'dayOfWeek': string; - 'isSingleDay': string; - 'isToday': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Day/DayOfWeek.js b/frontend/src/Calendar/Day/DayOfWeek.js new file mode 100644 index 000000000..d97671522 --- /dev/null +++ b/frontend/src/Calendar/Day/DayOfWeek.js @@ -0,0 +1,56 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import getRelativeDate from 'Utilities/Date/getRelativeDate'; +import * as calendarViews from 'Calendar/calendarViews'; +import styles from './DayOfWeek.css'; + +class DayOfWeek extends Component { + + // + // Render + + render() { + const { + date, + view, + isTodaysDate, + calendarWeekColumnHeader, + shortDateFormat, + showRelativeDates + } = this.props; + + const highlightToday = view !== calendarViews.MONTH && isTodaysDate; + const momentDate = moment(date); + let formatedDate = momentDate.format('dddd'); + + if (view === calendarViews.WEEK) { + formatedDate = momentDate.format(calendarWeekColumnHeader); + } else if (view === calendarViews.FORECAST) { + formatedDate = getRelativeDate(date, shortDateFormat, showRelativeDates); + } + + return ( +
+ {formatedDate} +
+ ); + } +} + +DayOfWeek.propTypes = { + date: PropTypes.string.isRequired, + view: PropTypes.string.isRequired, + isTodaysDate: PropTypes.bool.isRequired, + calendarWeekColumnHeader: PropTypes.string.isRequired, + shortDateFormat: PropTypes.string.isRequired, + showRelativeDates: PropTypes.bool.isRequired +}; + +export default DayOfWeek; diff --git a/frontend/src/Calendar/Day/DayOfWeek.tsx b/frontend/src/Calendar/Day/DayOfWeek.tsx deleted file mode 100644 index c8b493b7c..000000000 --- a/frontend/src/Calendar/Day/DayOfWeek.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import classNames from 'classnames'; -import moment from 'moment'; -import React from 'react'; -import * as calendarViews from 'Calendar/calendarViews'; -import getRelativeDate from 'Utilities/Date/getRelativeDate'; -import styles from './DayOfWeek.css'; - -interface DayOfWeekProps { - date: string; - view: string; - isTodaysDate: boolean; - calendarWeekColumnHeader: string; - shortDateFormat: string; - showRelativeDates: boolean; -} - -function DayOfWeek(props: DayOfWeekProps) { - const { - date, - view, - isTodaysDate, - calendarWeekColumnHeader, - shortDateFormat, - showRelativeDates, - } = props; - - const highlightToday = view !== calendarViews.MONTH && isTodaysDate; - const momentDate = moment(date); - let formatedDate = momentDate.format('dddd'); - - if (view === calendarViews.WEEK) { - formatedDate = momentDate.format(calendarWeekColumnHeader); - } else if (view === calendarViews.FORECAST) { - formatedDate = getRelativeDate({ - date, - shortDateFormat, - showRelativeDates, - }); - } - - return ( -
- {formatedDate} -
- ); -} - -export default DayOfWeek; diff --git a/frontend/src/Calendar/Day/DaysOfWeek.css.d.ts b/frontend/src/Calendar/Day/DaysOfWeek.css.d.ts deleted file mode 100644 index 5bc224b68..000000000 --- a/frontend/src/Calendar/Day/DaysOfWeek.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'daysOfWeek': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Day/DaysOfWeek.js b/frontend/src/Calendar/Day/DaysOfWeek.js new file mode 100644 index 000000000..a67777f7c --- /dev/null +++ b/frontend/src/Calendar/Day/DaysOfWeek.js @@ -0,0 +1,97 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import DayOfWeek from './DayOfWeek'; +import * as calendarViews from 'Calendar/calendarViews'; +import styles from './DaysOfWeek.css'; + +class DaysOfWeek extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + todaysDate: moment().startOf('day').toISOString() + }; + + this.updateTimeoutId = null; + } + + // Lifecycle + + componentDidMount() { + const view = this.props.view; + + if (view !== calendarViews.AGENDA || view !== calendarViews.MONTH) { + this.scheduleUpdate(); + } + } + + componentWillUnmount() { + this.clearUpdateTimeout(); + } + + // + // Control + + scheduleUpdate = () => { + this.clearUpdateTimeout(); + const todaysDate = moment().startOf('day'); + const diff = todaysDate.clone().add(1, 'day').diff(moment()); + + this.setState({ + todaysDate: todaysDate.toISOString() + }); + + this.updateTimeoutId = setTimeout(this.scheduleUpdate, diff); + } + + clearUpdateTimeout = () => { + if (this.updateTimeoutId) { + clearTimeout(this.updateTimeoutId); + } + } + + // + // Render + + render() { + const { + dates, + view, + ...otherProps + } = this.props; + + if (view === calendarViews.AGENDA) { + return null; + } + + return ( +
+ { + dates.map((date) => { + return ( + + ); + }) + } +
+ ); + } +} + +DaysOfWeek.propTypes = { + dates: PropTypes.arrayOf(PropTypes.string), + view: PropTypes.string.isRequired +}; + +export default DaysOfWeek; diff --git a/frontend/src/Calendar/Day/DaysOfWeek.tsx b/frontend/src/Calendar/Day/DaysOfWeek.tsx deleted file mode 100644 index 64bc886cc..000000000 --- a/frontend/src/Calendar/Day/DaysOfWeek.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import moment from 'moment'; -import React, { useCallback, useEffect, useRef, useState } from 'react'; -import { useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import * as calendarViews from 'Calendar/calendarViews'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import DayOfWeek from './DayOfWeek'; -import styles from './DaysOfWeek.css'; - -function DaysOfWeek() { - const { dates, view } = useSelector((state: AppState) => state.calendar); - const { calendarWeekColumnHeader, shortDateFormat, showRelativeDates } = - useSelector(createUISettingsSelector()); - - const updateTimeout = useRef>(); - const [todaysDate, setTodaysDate] = useState( - moment().startOf('day').toISOString() - ); - - const scheduleUpdate = useCallback(() => { - clearTimeout(updateTimeout.current); - - const todaysDate = moment().startOf('day'); - const diff = moment().diff(todaysDate.clone().add(1, 'day')); - - setTodaysDate(todaysDate.toISOString()); - - updateTimeout.current = setTimeout(scheduleUpdate, diff); - }, []); - - useEffect(() => { - if (view !== calendarViews.AGENDA && view !== calendarViews.MONTH) { - scheduleUpdate(); - } - }, [view, scheduleUpdate]); - - if (view === calendarViews.AGENDA) { - return null; - } - - return ( -
- {dates.map((date) => { - return ( - - ); - })} -
- ); -} - -export default DaysOfWeek; diff --git a/frontend/src/Calendar/Day/DaysOfWeekConnector.js b/frontend/src/Calendar/Day/DaysOfWeekConnector.js new file mode 100644 index 000000000..7f5cdef19 --- /dev/null +++ b/frontend/src/Calendar/Day/DaysOfWeekConnector.js @@ -0,0 +1,22 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import DaysOfWeek from './DaysOfWeek'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar, + createUISettingsSelector(), + (calendar, UiSettings) => { + return { + dates: calendar.dates.slice(0, 7), + view: calendar.view, + calendarWeekColumnHeader: UiSettings.calendarWeekColumnHeader, + shortDateFormat: UiSettings.shortDateFormat, + showRelativeDates: UiSettings.showRelativeDates + }; + } + ); +} + +export default connect(createMapStateToProps)(DaysOfWeek); diff --git a/frontend/src/Calendar/Events/CalendarEvent.css b/frontend/src/Calendar/Events/CalendarEvent.css index 679b4cc51..fb7a39855 100644 --- a/frontend/src/Calendar/Events/CalendarEvent.css +++ b/frontend/src/Calendar/Events/CalendarEvent.css @@ -1,22 +1,11 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); .event { - position: relative; + overflow-x: hidden; margin: 4px 2px; padding: 5px; - border-bottom: 1px solid var(--calendarBorderColor); - border-left: 4px solid var(--calendarBorderColor); -} - -.underlay { - @add-mixin cover; -} - -.overlay { - @add-mixin linkOverlay; - - position: relative; - overflow-x: hidden; + border-bottom: 1px solid $borderColor; + border-left: 4px solid $borderColor; font-size: 12px; &:global(.colorImpaired) { @@ -30,7 +19,7 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); } .episodeInfo { - color: var(--calendarTextDim); + color: $calendarTextDim; } .seriesTitle, @@ -41,7 +30,7 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); } .seriesTitle { - color: var(--calendarTextDimAlternate); + color: #3a3f51; font-size: $defaultFontSize; } @@ -52,20 +41,14 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); .statusContainer { display: flex; align-items: center; - - &:global(.fullColor) { - filter: var(--calendarFullColorFilter) - } } .statusIcon { margin-left: 3px; - cursor: default; - pointer-events: all; } .airTime { - color: var(--calendarTextDim); + color: $calendarTextDim; } /* @@ -73,19 +56,19 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); */ .downloaded { - border-left-color: var(--successColor) !important; + border-left-color: $successColor !important; &:global(.fullColor) { background-color: rgba(39, 194, 76, 0.4) !important; } &:global(.colorImpaired) { - border-left-color: color(#27c24c saturation(+15%)) !important; + border-left-color: color($successColor, saturation(+15%)) !important; } } .downloading { - border-left-color: var(--purple) !important; + border-left-color: $purple !important; &:global(.fullColor) { background-color: rgba(122, 67, 182, 0.4) !important; @@ -93,14 +76,14 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); } .unmonitored { - border-left-color: var(--gray) !important; + border-left-color: $gray !important; &:global(.fullColor) { background-color: rgba(173, 173, 173, 0.5) !important; } &:global(.colorImpaired) { - background: repeating-linear-gradient(45deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + background: repeating-linear-gradient(45deg, $colorImpairedGradientDark, $colorImpairedGradientDark 5px, $colorImpairedGradient 5px, $colorImpairedGradient 10px); } &:global(.fullColor.colorImpaired) { @@ -109,14 +92,14 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); } .onAir { - border-left-color: var(--warningColor) !important; + border-left-color: $warningColor !important; &:global(.fullColor) { background-color: rgba(255, 165, 0, 0.6) !important; } &:global(.colorImpaired) { - background: repeating-linear-gradient(90deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + background: repeating-linear-gradient(90deg, $colorImpairedGradientDark, $colorImpairedGradientDark 5px, $colorImpairedGradient 5px, $colorImpairedGradient 10px); } &:global(.fullColor.colorImpaired) { @@ -125,15 +108,15 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); } .missing { - border-left-color: var(--dangerColor) !important; + border-left-color: $dangerColor !important; &:global(.fullColor) { background-color: rgba(240, 80, 80, 0.6) !important; } &:global(.colorImpaired) { - border-left-color: color(#f05050 saturation(+15%)) !important; - background: repeating-linear-gradient(90deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + border-left-color: color($dangerColor saturation(+15%)) !important; + background: repeating-linear-gradient(90deg, $colorImpairedGradientDark, $colorImpairedGradientDark 5px, $colorImpairedGradient 5px, $colorImpairedGradient 10px); } &:global(.fullColor.colorImpaired) { @@ -142,14 +125,14 @@ $fullColorGradient: rgba(244, 245, 246, 0.2); } .unaired { - border-left-color: var(--primaryColor) !important; + border-left-color: $primaryColor !important; &:global(.fullColor) { background-color: rgba(93, 156, 236, 0.4) !important; } &:global(.colorImpaired) { - background: repeating-linear-gradient(90deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + background: repeating-linear-gradient(90deg, $colorImpairedGradientDark, $colorImpairedGradientDark 5px, $colorImpairedGradient 5px, $colorImpairedGradient 10px); } &:global(.fullColor.colorImpaired) { diff --git a/frontend/src/Calendar/Events/CalendarEvent.css.d.ts b/frontend/src/Calendar/Events/CalendarEvent.css.d.ts deleted file mode 100644 index f099df211..000000000 --- a/frontend/src/Calendar/Events/CalendarEvent.css.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'absoluteEpisodeNumber': string; - 'airTime': string; - 'downloaded': string; - 'downloading': string; - 'episodeInfo': string; - 'episodeTitle': string; - 'event': string; - 'info': string; - 'missing': string; - 'onAir': string; - 'overlay': string; - 'seriesTitle': string; - 'statusContainer': string; - 'statusIcon': string; - 'unaired': string; - 'underlay': string; - 'unmonitored': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Events/CalendarEvent.js b/frontend/src/Calendar/Events/CalendarEvent.js new file mode 100644 index 000000000..00e91aa8c --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEvent.js @@ -0,0 +1,260 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component, Fragment } from 'react'; +import classNames from 'classnames'; +import { icons, kinds } from 'Helpers/Props'; +import formatTime from 'Utilities/Date/formatTime'; +import padNumber from 'Utilities/Number/padNumber'; +import getStatusStyle from 'Calendar/getStatusStyle'; +import episodeEntities from 'Episode/episodeEntities'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import EpisodeDetailsModal from 'Episode/EpisodeDetailsModal'; +import CalendarEventQueueDetails from './CalendarEventQueueDetails'; +import styles from './CalendarEvent.css'; + +class CalendarEvent extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isDetailsModalOpen: false + }; + } + + // + // Listeners + + onPress = () => { + this.setState({ isDetailsModalOpen: true }, () => { + this.props.onEventModalOpenToggle(true); + }); + } + + onDetailsModalClose = () => { + this.setState({ isDetailsModalOpen: false }, () => { + this.props.onEventModalOpenToggle(false); + }); + } + + // + // Render + + render() { + const { + id, + series, + episodeFile, + title, + seasonNumber, + episodeNumber, + absoluteEpisodeNumber, + airDateUtc, + monitored, + hasFile, + grabbed, + queueItem, + showEpisodeInformation, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + fullColorEvents, + timeFormat, + colorImpairedMode + } = this.props; + + if (!series) { + return null; + } + + const startTime = moment(airDateUtc); + const endTime = moment(airDateUtc).add(series.runtime, 'minutes'); + const isDownloading = !!(queueItem || grabbed); + const isMonitored = series.monitored && monitored; + const statusStyle = getStatusStyle(hasFile, isDownloading, startTime, endTime, isMonitored); + const missingAbsoluteNumber = series.seriesType === 'anime' && seasonNumber > 0 && !absoluteEpisodeNumber; + const season = series.seasons.find((s) => s.seasonNumber === seasonNumber); + const seasonStatistics = season.statistics || {}; + + return ( + + +
+
+ {series.title} +
+ +
+ { + missingAbsoluteNumber ? + : + null + } + + { + queueItem ? + + + : + null + } + + { + !queueItem && grabbed ? + : + null + } + + { + showCutoffUnmetIcon && + !!episodeFile && + episodeFile.qualityCutoffNotMet ? + : + null + } + + { + showCutoffUnmetIcon && + !!episodeFile && + episodeFile.languageCutoffNotMet && + !episodeFile.qualityCutoffNotMet ? + : + null + } + + { + episodeNumber === 1 && seasonNumber > 0 ? + : + null + } + + { + showFinaleIcon && + episodeNumber !== 1 && + seasonNumber > 0 && + episodeNumber === seasonStatistics.totalEpisodeCount ? + : + null + } + + { + showSpecialIcon && + (episodeNumber === 0 || seasonNumber === 0) ? + : + null + } +
+
+ + { + showEpisodeInformation ? +
+
+ {title} +
+ +
+ {seasonNumber}x{padNumber(episodeNumber, 2)} + + { + series.seriesType === 'anime' && absoluteEpisodeNumber ? + ({absoluteEpisodeNumber}) : null + } +
+
: + null + } + +
+ {formatTime(airDateUtc, timeFormat)} - {formatTime(endTime.toISOString(), timeFormat, { includeMinuteZero: true })} +
+ + + +
+ ); + } +} + +CalendarEvent.propTypes = { + id: PropTypes.number.isRequired, + series: PropTypes.object.isRequired, + episodeFile: PropTypes.object, + title: PropTypes.string.isRequired, + seasonNumber: PropTypes.number.isRequired, + episodeNumber: PropTypes.number.isRequired, + absoluteEpisodeNumber: PropTypes.number, + airDateUtc: PropTypes.string.isRequired, + monitored: PropTypes.bool.isRequired, + hasFile: PropTypes.bool.isRequired, + grabbed: PropTypes.bool, + queueItem: PropTypes.object, + showEpisodeInformation: PropTypes.bool.isRequired, + showFinaleIcon: PropTypes.bool.isRequired, + showSpecialIcon: PropTypes.bool.isRequired, + showCutoffUnmetIcon: PropTypes.bool.isRequired, + fullColorEvents: PropTypes.bool.isRequired, + timeFormat: PropTypes.string.isRequired, + colorImpairedMode: PropTypes.bool.isRequired, + onEventModalOpenToggle: PropTypes.func.isRequired +}; + +export default CalendarEvent; diff --git a/frontend/src/Calendar/Events/CalendarEvent.tsx b/frontend/src/Calendar/Events/CalendarEvent.tsx deleted file mode 100644 index 079256a0e..000000000 --- a/frontend/src/Calendar/Events/CalendarEvent.tsx +++ /dev/null @@ -1,240 +0,0 @@ -import classNames from 'classnames'; -import moment from 'moment'; -import React, { useCallback, useState } from 'react'; -import { useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import getStatusStyle from 'Calendar/getStatusStyle'; -import Icon from 'Components/Icon'; -import Link from 'Components/Link/Link'; -import EpisodeDetailsModal from 'Episode/EpisodeDetailsModal'; -import episodeEntities from 'Episode/episodeEntities'; -import getFinaleTypeName from 'Episode/getFinaleTypeName'; -import useEpisodeFile from 'EpisodeFile/useEpisodeFile'; -import { icons, kinds } from 'Helpers/Props'; -import useSeries from 'Series/useSeries'; -import { createQueueItemSelectorForHook } from 'Store/Selectors/createQueueItemSelector'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import formatTime from 'Utilities/Date/formatTime'; -import padNumber from 'Utilities/Number/padNumber'; -import translate from 'Utilities/String/translate'; -import CalendarEventQueueDetails from './CalendarEventQueueDetails'; -import styles from './CalendarEvent.css'; - -interface CalendarEventProps { - id: number; - episodeId: number; - seriesId: number; - episodeFileId?: number; - title: string; - seasonNumber: number; - episodeNumber: number; - absoluteEpisodeNumber?: number; - airDateUtc: string; - monitored: boolean; - unverifiedSceneNumbering?: boolean; - finaleType?: string; - hasFile: boolean; - grabbed?: boolean; - onEventModalOpenToggle: (isOpen: boolean) => void; -} - -function CalendarEvent(props: CalendarEventProps) { - const { - id, - seriesId, - episodeFileId, - title, - seasonNumber, - episodeNumber, - absoluteEpisodeNumber, - airDateUtc, - monitored, - unverifiedSceneNumbering, - finaleType, - hasFile, - grabbed, - onEventModalOpenToggle, - } = props; - - const series = useSeries(seriesId); - const episodeFile = useEpisodeFile(episodeFileId); - const queueItem = useSelector(createQueueItemSelectorForHook(id)); - - const { timeFormat, enableColorImpairedMode } = useSelector( - createUISettingsSelector() - ); - - const { - showEpisodeInformation, - showFinaleIcon, - showSpecialIcon, - showCutoffUnmetIcon, - fullColorEvents, - } = useSelector((state: AppState) => state.calendar.options); - - const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); - - const handlePress = useCallback(() => { - setIsDetailsModalOpen(true); - onEventModalOpenToggle(true); - }, [onEventModalOpenToggle]); - - const handleDetailsModalClose = useCallback(() => { - setIsDetailsModalOpen(false); - onEventModalOpenToggle(false); - }, [onEventModalOpenToggle]); - - if (!series) { - return null; - } - - const startTime = moment(airDateUtc); - const endTime = moment(airDateUtc).add(series.runtime, 'minutes'); - const isDownloading = !!(queueItem || grabbed); - const isMonitored = series.monitored && monitored; - const statusStyle = getStatusStyle( - hasFile, - isDownloading, - startTime, - endTime, - isMonitored - ); - const missingAbsoluteNumber = - series.seriesType === 'anime' && seasonNumber > 0 && !absoluteEpisodeNumber; - - return ( -
- - -
-
-
{series.title}
- -
- {missingAbsoluteNumber ? ( - - ) : null} - - {unverifiedSceneNumbering && !missingAbsoluteNumber ? ( - - ) : null} - - {queueItem ? ( - - - - ) : null} - - {!queueItem && grabbed ? ( - - ) : null} - - {showCutoffUnmetIcon && - !!episodeFile && - episodeFile.qualityCutoffNotMet ? ( - - ) : null} - - {episodeNumber === 1 && seasonNumber > 0 ? ( - - ) : null} - - {showFinaleIcon && finaleType ? ( - - ) : null} - - {showSpecialIcon && (episodeNumber === 0 || seasonNumber === 0) ? ( - - ) : null} -
-
- - {showEpisodeInformation ? ( -
-
{title}
- -
- {seasonNumber}x{padNumber(episodeNumber, 2)} - {series.seriesType === 'anime' && absoluteEpisodeNumber ? ( - - ({absoluteEpisodeNumber}) - - ) : null} -
-
- ) : null} - -
- {formatTime(airDateUtc, timeFormat)} -{' '} - {formatTime(endTime.toISOString(), timeFormat, { - includeMinuteZero: true, - })} -
-
- - -
- ); -} - -export default CalendarEvent; diff --git a/frontend/src/Calendar/Events/CalendarEventConnector.js b/frontend/src/Calendar/Events/CalendarEventConnector.js new file mode 100644 index 000000000..f3b663dae --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventConnector.js @@ -0,0 +1,29 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createEpisodeFileSelector from 'Store/Selectors/createEpisodeFileSelector'; +import createSeriesSelector from 'Store/Selectors/createSeriesSelector'; +import createQueueItemSelector from 'Store/Selectors/createQueueItemSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import CalendarEvent from './CalendarEvent'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar.options, + createSeriesSelector(), + createEpisodeFileSelector(), + createQueueItemSelector(), + createUISettingsSelector(), + (calendarOptions, series, episodeFile, queueItem, uiSettings) => { + return { + series, + episodeFile, + queueItem, + ...calendarOptions, + timeFormat: uiSettings.timeFormat, + colorImpairedMode: uiSettings.enableColorImpairedMode + }; + } + ); +} + +export default connect(createMapStateToProps)(CalendarEvent); diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.css b/frontend/src/Calendar/Events/CalendarEventGroup.css index 990d994ec..e5be0fd92 100644 --- a/frontend/src/Calendar/Events/CalendarEventGroup.css +++ b/frontend/src/Calendar/Events/CalendarEventGroup.css @@ -2,8 +2,8 @@ overflow-x: hidden; margin: 4px 2px; padding: 5px; - border-bottom: 1px solid var(--borderColor); - border-left: 4px solid var(--borderColor); + border-bottom: 1px solid $borderColor; + border-left: 4px solid $borderColor; font-size: 12px; } @@ -16,18 +16,18 @@ @add-mixin truncate; flex: 1 0 1px; margin-right: 10px; - color: var(--calendarTextDimAlternate); + color: #3a3f51; font-size: $defaultFontSize; } .airTime { flex: 1 0 1px; - color: var(--calendarTextDim); + color: $calendarTextDim; } .episodeInfo { margin-left: 10px; - color: var(--calendarTextDim); + color: $calendarTextDim; } .absoluteEpisodeNumber { @@ -43,7 +43,6 @@ .expandContainer, .collapseContainer { display: flex; - align-items: center; justify-content: center; } @@ -51,15 +50,6 @@ margin-bottom: 5px; } -.statusContainer { - display: flex; - align-items: center; - - &:global(.fullColor) { - filter: var(--calendarFullColorFilter) - } -} - .statusIcon { margin-left: 3px; } diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.css.d.ts b/frontend/src/Calendar/Events/CalendarEventGroup.css.d.ts deleted file mode 100644 index c527feff1..000000000 --- a/frontend/src/Calendar/Events/CalendarEventGroup.css.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'absoluteEpisodeNumber': string; - 'airTime': string; - 'airingInfo': string; - 'collapseContainer': string; - 'downloaded': string; - 'downloading': string; - 'episodeInfo': string; - 'eventGroup': string; - 'expandContainer': string; - 'expandContainerInline': string; - 'info': string; - 'missing': string; - 'onAir': string; - 'premiere': string; - 'seriesTitle': string; - 'statusContainer': string; - 'statusIcon': string; - 'unaired': string; - 'unmonitored': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.js b/frontend/src/Calendar/Events/CalendarEventGroup.js new file mode 100644 index 000000000..320ae8cc6 --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventGroup.js @@ -0,0 +1,249 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import formatTime from 'Utilities/Date/formatTime'; +import padNumber from 'Utilities/Number/padNumber'; +import { icons, kinds } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import getStatusStyle from 'Calendar/getStatusStyle'; +import CalendarEventConnector from 'Calendar/Events/CalendarEventConnector'; +import styles from './CalendarEventGroup.css'; + +function getEventsInfo(events) { + let files = 0; + let queued = 0; + let monitored = 0; + let absoluteEpisodeNumbers = 0; + + events.forEach((event) => { + if (event.episodeFileId) { + files++; + } + + if (event.queued) { + queued++; + } + + if (event.monitored) { + monitored++; + } + + if (event.absoluteEpisodeNumber) { + absoluteEpisodeNumbers++; + } + }); + + return { + allDownloaded: files === events.length, + anyQueued: queued > 0, + anyMonitored: monitored > 0, + allAbsoluteEpisodeNumbers: absoluteEpisodeNumbers === events.length + }; +} + +class CalendarEventGroup extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isExpanded: false + }; + } + + // + // Listeners + + onExpandPress = () => { + this.setState({ isExpanded: !this.state.isExpanded }); + } + + // + // Render + + render() { + const { + series, + events, + isDownloading, + showEpisodeInformation, + showFinaleIcon, + timeFormat, + fullColorEvents, + colorImpairedMode, + onEventModalOpenToggle + } = this.props; + + const { isExpanded } = this.state; + const { + allDownloaded, + anyQueued, + anyMonitored, + allAbsoluteEpisodeNumbers + } = getEventsInfo(events); + const anyDownloading = isDownloading || anyQueued; + const firstEpisode = events[0]; + const lastEpisode = events[events.length -1]; + const airDateUtc = firstEpisode.airDateUtc; + const startTime = moment(airDateUtc); + const endTime = moment(lastEpisode.airDateUtc).add(series.runtime, 'minutes'); + const seasonNumber = firstEpisode.seasonNumber; + const statusStyle = getStatusStyle(allDownloaded, anyDownloading, startTime, endTime, anyMonitored); + const isMissingAbsoluteNumber = series.seriesType === 'anime' && seasonNumber > 0 && !allAbsoluteEpisodeNumbers; + + if (isExpanded) { + return ( +
+ { + events.map((event) => { + if (event.isGroup) { + return null; + } + + return ( + + ); + }) + } + + + + +
+ ); + } + + return ( +
+
+
+ {series.title} +
+ + { + isMissingAbsoluteNumber && + + } + + { + anyDownloading && + + } + + { + firstEpisode.episodeNumber === 1 && seasonNumber > 0 && + + } + + { + showFinaleIcon && + lastEpisode.episodeNumber !== 1 && + seasonNumber > 0 && + lastEpisode.episodeNumber === series.seasons.find((season) => season.seasonNumber === seasonNumber).statistics.totalEpisodeCount && + + } +
+ +
+
+ {formatTime(airDateUtc, timeFormat)} - {formatTime(endTime.toISOString(), timeFormat, { includeMinuteZero: true })} +
+ + { + showEpisodeInformation ? +
+ {seasonNumber}x{padNumber(firstEpisode.episodeNumber, 2)}-{padNumber(lastEpisode.episodeNumber, 2)} + + { + series.seriesType === 'anime' && + firstEpisode.absoluteEpisodeNumber && + lastEpisode.absoluteEpisodeNumber && + + ({firstEpisode.absoluteEpisodeNumber}-{lastEpisode.absoluteEpisodeNumber}) + + } +
: + + + + } +
+ + { + showEpisodeInformation && + + + + } +
+ ); + } +} + +CalendarEventGroup.propTypes = { + series: PropTypes.object.isRequired, + events: PropTypes.arrayOf(PropTypes.object).isRequired, + isDownloading: PropTypes.bool.isRequired, + showEpisodeInformation: PropTypes.bool.isRequired, + showFinaleIcon: PropTypes.bool.isRequired, + fullColorEvents: PropTypes.bool.isRequired, + timeFormat: PropTypes.string.isRequired, + colorImpairedMode: PropTypes.bool.isRequired, + onEventModalOpenToggle: PropTypes.func.isRequired +}; + +export default CalendarEventGroup; diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.tsx b/frontend/src/Calendar/Events/CalendarEventGroup.tsx deleted file mode 100644 index 1ee981cfd..000000000 --- a/frontend/src/Calendar/Events/CalendarEventGroup.tsx +++ /dev/null @@ -1,253 +0,0 @@ -import classNames from 'classnames'; -import moment from 'moment'; -import React, { useCallback, useMemo, useState } from 'react'; -import { useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import getStatusStyle from 'Calendar/getStatusStyle'; -import Icon from 'Components/Icon'; -import Link from 'Components/Link/Link'; -import getFinaleTypeName from 'Episode/getFinaleTypeName'; -import { icons, kinds } from 'Helpers/Props'; -import useSeries from 'Series/useSeries'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import { CalendarItem } from 'typings/Calendar'; -import formatTime from 'Utilities/Date/formatTime'; -import padNumber from 'Utilities/Number/padNumber'; -import translate from 'Utilities/String/translate'; -import CalendarEvent from './CalendarEvent'; -import styles from './CalendarEventGroup.css'; - -function createIsDownloadingSelector(episodeIds: number[]) { - return createSelector( - (state: AppState) => state.queue.details, - (details) => { - return details.items.some((item) => { - return !!(item.episodeId && episodeIds.includes(item.episodeId)); - }); - } - ); -} - -interface CalendarEventGroupProps { - episodeIds: number[]; - seriesId: number; - events: CalendarItem[]; - onEventModalOpenToggle: (isOpen: boolean) => void; -} - -function CalendarEventGroup({ - episodeIds, - seriesId, - events, - onEventModalOpenToggle, -}: CalendarEventGroupProps) { - const isDownloading = useSelector(createIsDownloadingSelector(episodeIds)); - const series = useSeries(seriesId)!; - - const { timeFormat, enableColorImpairedMode } = useSelector( - createUISettingsSelector() - ); - - const { showEpisodeInformation, showFinaleIcon, fullColorEvents } = - useSelector((state: AppState) => state.calendar.options); - - const [isExpanded, setIsExpanded] = useState(false); - - const firstEpisode = events[0]; - const lastEpisode = events[events.length - 1]; - const airDateUtc = firstEpisode.airDateUtc; - const startTime = moment(airDateUtc); - const endTime = moment(lastEpisode.airDateUtc).add(series.runtime, 'minutes'); - const seasonNumber = firstEpisode.seasonNumber; - - const { allDownloaded, anyQueued, anyMonitored, allAbsoluteEpisodeNumbers } = - useMemo(() => { - let files = 0; - let queued = 0; - let monitored = 0; - let absoluteEpisodeNumbers = 0; - - events.forEach((event) => { - if (event.episodeFileId) { - files++; - } - - if (event.queued) { - queued++; - } - - if (series.monitored && event.monitored) { - monitored++; - } - - if (event.absoluteEpisodeNumber) { - absoluteEpisodeNumbers++; - } - }); - - return { - allDownloaded: files === events.length, - anyQueued: queued > 0, - anyMonitored: monitored > 0, - allAbsoluteEpisodeNumbers: absoluteEpisodeNumbers === events.length, - }; - }, [series, events]); - - const anyDownloading = isDownloading || anyQueued; - - const statusStyle = getStatusStyle( - allDownloaded, - anyDownloading, - startTime, - endTime, - anyMonitored - ); - const isMissingAbsoluteNumber = - series.seriesType === 'anime' && - seasonNumber > 0 && - !allAbsoluteEpisodeNumbers; - - const handleExpandPress = useCallback(() => { - setIsExpanded((state) => !state); - }, []); - - if (isExpanded) { - return ( -
- {events.map((event) => { - return ( - - ); - })} - - - - -
- ); - } - - return ( -
-
-
{series.title}
- -
- {isMissingAbsoluteNumber ? ( - - ) : null} - - {anyDownloading ? ( - - ) : null} - - {firstEpisode.episodeNumber === 1 && seasonNumber > 0 ? ( - - ) : null} - - {showFinaleIcon && lastEpisode.finaleType ? ( - - ) : null} -
-
- -
-
- {formatTime(airDateUtc, timeFormat)} -{' '} - {formatTime(endTime.toISOString(), timeFormat, { - includeMinuteZero: true, - })} -
- - {showEpisodeInformation ? ( -
- {seasonNumber}x{padNumber(firstEpisode.episodeNumber, 2)}- - {padNumber(lastEpisode.episodeNumber, 2)} - {series.seriesType === 'anime' && - firstEpisode.absoluteEpisodeNumber && - lastEpisode.absoluteEpisodeNumber ? ( - - ({firstEpisode.absoluteEpisodeNumber}- - {lastEpisode.absoluteEpisodeNumber}) - - ) : null} -
- ) : ( - - - - )} -
- - {showEpisodeInformation ? ( - -   - -   - - ) : null} -
- ); -} - -export default CalendarEventGroup; diff --git a/frontend/src/Calendar/Events/CalendarEventGroupConnector.js b/frontend/src/Calendar/Events/CalendarEventGroupConnector.js new file mode 100644 index 000000000..dbd967784 --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventGroupConnector.js @@ -0,0 +1,37 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createSeriesSelector from 'Store/Selectors/createSeriesSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import CalendarEventGroup from './CalendarEventGroup'; + +function createIsDownloadingSelector() { + return createSelector( + (state, { episodeIds }) => episodeIds, + (state) => state.queue.details, + (episodeIds, details) => { + return details.items.some((item) => { + return item.episode && episodeIds.includes(item.episode.id); + }); + } + ); +} + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar.options, + createSeriesSelector(), + createIsDownloadingSelector(), + createUISettingsSelector(), + (calendarOptions, series, isDownloading, uiSettings) => { + return { + series, + isDownloading, + ...calendarOptions, + timeFormat: uiSettings.timeFormat, + colorImpairedMode: uiSettings.enableColorImpairedMode + }; + } + ); +} + +export default connect(createMapStateToProps)(CalendarEventGroup); diff --git a/frontend/src/Calendar/Events/CalendarEventQueueDetails.js b/frontend/src/Calendar/Events/CalendarEventQueueDetails.js new file mode 100644 index 000000000..7440b9d67 --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventQueueDetails.js @@ -0,0 +1,56 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import colors from 'Styles/Variables/colors'; +import CircularProgressBar from 'Components/CircularProgressBar'; +import QueueDetails from 'Activity/Queue/QueueDetails'; + +function CalendarEventQueueDetails(props) { + const { + title, + size, + sizeleft, + estimatedCompletionTime, + status, + trackedDownloadState, + trackedDownloadStatus, + errorMessage + } = props; + + const progress = size ? (100 - sizeleft / size * 100) : 0; + + return ( + + +
+ } + /> + ); +} + +CalendarEventQueueDetails.propTypes = { + title: PropTypes.string.isRequired, + size: PropTypes.number.isRequired, + sizeleft: PropTypes.number.isRequired, + estimatedCompletionTime: PropTypes.string, + status: PropTypes.string.isRequired, + trackedDownloadState: PropTypes.string.isRequired, + trackedDownloadStatus: PropTypes.string.isRequired, + errorMessage: PropTypes.string +}; + +export default CalendarEventQueueDetails; diff --git a/frontend/src/Calendar/Events/CalendarEventQueueDetails.tsx b/frontend/src/Calendar/Events/CalendarEventQueueDetails.tsx deleted file mode 100644 index 2372bc78e..000000000 --- a/frontend/src/Calendar/Events/CalendarEventQueueDetails.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import React from 'react'; -import QueueDetails from 'Activity/Queue/QueueDetails'; -import CircularProgressBar from 'Components/CircularProgressBar'; -import { - QueueTrackedDownloadState, - QueueTrackedDownloadStatus, - StatusMessage, -} from 'typings/Queue'; - -interface CalendarEventQueueDetailsProps { - title: string; - size: number; - sizeleft: number; - estimatedCompletionTime?: string; - status: string; - trackedDownloadState: QueueTrackedDownloadState; - trackedDownloadStatus: QueueTrackedDownloadStatus; - statusMessages?: StatusMessage[]; - errorMessage?: string; -} - -function CalendarEventQueueDetails({ - title, - size, - sizeleft, - estimatedCompletionTime, - status, - trackedDownloadState, - trackedDownloadStatus, - statusMessages, - errorMessage, -}: CalendarEventQueueDetailsProps) { - const progress = size ? 100 - (sizeleft / size) * 100 : 0; - - return ( - - } - /> - ); -} - -export default CalendarEventQueueDetails; diff --git a/frontend/src/Calendar/Header/CalendarHeader.css.d.ts b/frontend/src/Calendar/Header/CalendarHeader.css.d.ts deleted file mode 100644 index 700b53652..000000000 --- a/frontend/src/Calendar/Header/CalendarHeader.css.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'header': string; - 'loading': string; - 'navigationButtons': string; - 'titleDesktop': string; - 'titleMobile': string; - 'todayButton': string; - 'viewButtonsContainer': string; - 'viewMenu': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Header/CalendarHeader.js b/frontend/src/Calendar/Header/CalendarHeader.js new file mode 100644 index 000000000..9e65df87b --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeader.js @@ -0,0 +1,267 @@ +import moment from 'moment'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { align, icons } from 'Helpers/Props'; +import Button from 'Components/Link/Button'; +import Icon from 'Components/Icon'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Menu from 'Components/Menu/Menu'; +import MenuButton from 'Components/Menu/MenuButton'; +import MenuContent from 'Components/Menu/MenuContent'; +import ViewMenuItem from 'Components/Menu/ViewMenuItem'; +import * as calendarViews from 'Calendar/calendarViews'; +import CalendarHeaderViewButton from './CalendarHeaderViewButton'; +import styles from './CalendarHeader.css'; + +function getTitle(time, start, end, view, longDateFormat) { + const timeMoment = moment(time); + const startMoment = moment(start); + const endMoment = moment(end); + + if (view === 'day') { + return timeMoment.format(longDateFormat); + } else if (view === 'month') { + return timeMoment.format('MMMM YYYY'); + } else if (view === 'agenda') { + return 'Agenda'; + } + + let startFormat = 'MMM D YYYY'; + let endFormat = 'MMM D YYYY'; + + if (startMoment.isSame(endMoment, 'month')) { + startFormat = 'MMM D'; + endFormat = 'D YYYY'; + } else if (startMoment.isSame(endMoment, 'year')) { + startFormat = 'MMM D'; + endFormat = 'MMM D YYYY'; + } + + return `${startMoment.format(startFormat)} \u2014 ${endMoment.format(endFormat)}`; +} + +// TODO Convert to a stateful Component so we can track view internally when changed + +class CalendarHeader extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + view: props.view + }; + } + + componentDidUpdate(prevProps) { + const view = this.props.view; + + if (prevProps.view !== view) { + this.setState({ view }); + } + } + + // + // Listeners + + onViewChange = (view) => { + this.setState({ view }, () => { + this.props.onViewChange(view); + }); + } + + // + // Render + + render() { + const { + isFetching, + time, + start, + end, + longDateFormat, + isSmallScreen, + collapseViewButtons, + onTodayPress, + onPreviousPress, + onNextPress + } = this.props; + + const view = this.state.view; + + const title = getTitle(time, start, end, view, longDateFormat); + + return ( +
+ { + isSmallScreen && +
+ {title} +
+ } + +
+
+ + + + + +
+ + { + !isSmallScreen && +
+ {title} +
+ } + +
+ { + isFetching && + + } + + { + collapseViewButtons ? + + + + + + + { + isSmallScreen ? + null : + + Month + + } + + + Week + + + + Forecast + + + + Day + + + + Agenda + + + : + +
+ + + + + + + + + +
+ } +
+
+
+ ); + } +} + +CalendarHeader.propTypes = { + isFetching: PropTypes.bool.isRequired, + time: PropTypes.string.isRequired, + start: PropTypes.string.isRequired, + end: PropTypes.string.isRequired, + view: PropTypes.oneOf(calendarViews.all).isRequired, + isSmallScreen: PropTypes.bool.isRequired, + collapseViewButtons: PropTypes.bool.isRequired, + longDateFormat: PropTypes.string.isRequired, + onViewChange: PropTypes.func.isRequired, + onTodayPress: PropTypes.func.isRequired, + onPreviousPress: PropTypes.func.isRequired, + onNextPress: PropTypes.func.isRequired +}; + +export default CalendarHeader; diff --git a/frontend/src/Calendar/Header/CalendarHeader.tsx b/frontend/src/Calendar/Header/CalendarHeader.tsx deleted file mode 100644 index 2faaca25e..000000000 --- a/frontend/src/Calendar/Header/CalendarHeader.tsx +++ /dev/null @@ -1,221 +0,0 @@ -import moment from 'moment'; -import React, { useCallback, useMemo } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import { CalendarView } from 'Calendar/calendarViews'; -import Icon from 'Components/Icon'; -import Button from 'Components/Link/Button'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import Menu from 'Components/Menu/Menu'; -import MenuButton from 'Components/Menu/MenuButton'; -import MenuContent from 'Components/Menu/MenuContent'; -import ViewMenuItem from 'Components/Menu/ViewMenuItem'; -import { align, icons } from 'Helpers/Props'; -import { - gotoCalendarNextRange, - gotoCalendarPreviousRange, - gotoCalendarToday, - setCalendarView, -} from 'Store/Actions/calendarActions'; -import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import translate from 'Utilities/String/translate'; -import CalendarHeaderViewButton from './CalendarHeaderViewButton'; -import styles from './CalendarHeader.css'; - -function CalendarHeader() { - const dispatch = useDispatch(); - - const { isFetching, view, time, start, end } = useSelector( - (state: AppState) => state.calendar - ); - - const { isSmallScreen, isLargeScreen } = useSelector( - createDimensionsSelector() - ); - - const { longDateFormat } = useSelector(createUISettingsSelector()); - - const handleViewChange = useCallback( - (newView: CalendarView) => { - dispatch(setCalendarView({ view: newView })); - }, - [dispatch] - ); - - const handleTodayPress = useCallback(() => { - dispatch(gotoCalendarToday()); - }, [dispatch]); - - const handlePreviousPress = useCallback(() => { - dispatch(gotoCalendarPreviousRange()); - }, [dispatch]); - - const handleNextPress = useCallback(() => { - dispatch(gotoCalendarNextRange()); - }, [dispatch]); - - const title = useMemo(() => { - const timeMoment = moment(time); - const startMoment = moment(start); - const endMoment = moment(end); - - if (view === 'day') { - return timeMoment.format(longDateFormat); - } else if (view === 'month') { - return timeMoment.format('MMMM YYYY'); - } else if (view === 'agenda') { - return translate('Agenda'); - } - - let startFormat = 'MMM D YYYY'; - let endFormat = 'MMM D YYYY'; - - if (startMoment.isSame(endMoment, 'month')) { - startFormat = 'MMM D'; - endFormat = 'D YYYY'; - } else if (startMoment.isSame(endMoment, 'year')) { - startFormat = 'MMM D'; - endFormat = 'MMM D YYYY'; - } - - return `${startMoment.format(startFormat)} \u2014 ${endMoment.format( - endFormat - )}`; - }, [time, start, end, view, longDateFormat]); - - return ( -
- {isSmallScreen ?
{title}
: null} - -
-
- - - - - -
- - {isSmallScreen ? null : ( -
{title}
- )} - -
- {isFetching ? ( - - ) : null} - - {isLargeScreen ? ( - - - - - - - {isSmallScreen ? null : ( - - {translate('Month')} - - )} - - - {translate('Week')} - - - - {translate('Forecast')} - - - - {translate('Day')} - - - - {translate('Agenda')} - - - - ) : ( - <> - - - - - - - - - - - )} -
-
-
- ); -} - -export default CalendarHeader; diff --git a/frontend/src/Calendar/Header/CalendarHeaderConnector.js b/frontend/src/Calendar/Header/CalendarHeaderConnector.js new file mode 100644 index 000000000..b73730ed9 --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeaderConnector.js @@ -0,0 +1,85 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import { setCalendarView, gotoCalendarToday, gotoCalendarPreviousRange, gotoCalendarNextRange } from 'Store/Actions/calendarActions'; +import CalendarHeader from './CalendarHeader'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar, + createDimensionsSelector(), + createUISettingsSelector(), + (calendar, dimensions, uiSettings) => { + const result = _.pick(calendar, [ + 'isFetching', + 'view', + 'time', + 'start', + 'end' + ]); + + result.isSmallScreen = dimensions.isSmallScreen; + result.collapseViewButtons = dimensions.isLargeScreen; + result.longDateFormat = uiSettings.longDateFormat; + + return result; + } + ); +} + +const mapDispatchToProps = { + setCalendarView, + gotoCalendarToday, + gotoCalendarPreviousRange, + gotoCalendarNextRange +}; + +class CalendarHeaderConnector extends Component { + + // + // Listeners + + onViewChange = (view) => { + this.props.setCalendarView({ view }); + } + + onTodayPress = () => { + this.props.gotoCalendarToday(); + } + + onPreviousPress = () => { + this.props.gotoCalendarPreviousRange(); + } + + onNextPress = () => { + this.props.gotoCalendarNextRange(); + } + + // + // Render + + render() { + return ( + + ); + } +} + +CalendarHeaderConnector.propTypes = { + setCalendarView: PropTypes.func.isRequired, + gotoCalendarToday: PropTypes.func.isRequired, + gotoCalendarPreviousRange: PropTypes.func.isRequired, + gotoCalendarNextRange: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(CalendarHeaderConnector); diff --git a/frontend/src/Calendar/Header/CalendarHeaderViewButton.js b/frontend/src/Calendar/Header/CalendarHeaderViewButton.js new file mode 100644 index 000000000..8dd5ae9f0 --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeaderViewButton.js @@ -0,0 +1,45 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import titleCase from 'Utilities/String/titleCase'; +import Button from 'Components/Link/Button'; +import * as calendarViews from 'Calendar/calendarViews'; +// import styles from './CalendarHeaderViewButton.css'; + +class CalendarHeaderViewButton extends Component { + + // + // Listeners + + onPress = () => { + this.props.onPress(this.props.view); + } + + // + // Render + + render() { + const { + view, + selectedView, + ...otherProps + } = this.props; + + return ( + + ); + } +} + +CalendarHeaderViewButton.propTypes = { + view: PropTypes.oneOf(calendarViews.all).isRequired, + selectedView: PropTypes.oneOf(calendarViews.all).isRequired, + onPress: PropTypes.func.isRequired +}; + +export default CalendarHeaderViewButton; diff --git a/frontend/src/Calendar/Header/CalendarHeaderViewButton.tsx b/frontend/src/Calendar/Header/CalendarHeaderViewButton.tsx deleted file mode 100644 index c9366f9ef..000000000 --- a/frontend/src/Calendar/Header/CalendarHeaderViewButton.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import React, { useCallback } from 'react'; -import { CalendarView } from 'Calendar/calendarViews'; -import Button, { ButtonProps } from 'Components/Link/Button'; -import titleCase from 'Utilities/String/titleCase'; - -interface CalendarHeaderViewButtonProps - extends Omit { - view: CalendarView; - selectedView: CalendarView; - onPress: (view: CalendarView) => void; -} - -function CalendarHeaderViewButton({ - view, - selectedView, - onPress, - ...otherProps -}: CalendarHeaderViewButtonProps) { - const handlePress = useCallback(() => { - onPress(view); - }, [view, onPress]); - - return ( - - ); -} - -export default CalendarHeaderViewButton; diff --git a/frontend/src/Calendar/Legend/Legend.css.d.ts b/frontend/src/Calendar/Legend/Legend.css.d.ts deleted file mode 100644 index 19c0339b4..000000000 --- a/frontend/src/Calendar/Legend/Legend.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'legend': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Legend/Legend.js b/frontend/src/Calendar/Legend/Legend.js new file mode 100644 index 000000000..0945f7b3e --- /dev/null +++ b/frontend/src/Calendar/Legend/Legend.js @@ -0,0 +1,144 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { icons, kinds } from 'Helpers/Props'; +import LegendItem from './LegendItem'; +import LegendIconItem from './LegendIconItem'; +import styles from './Legend.css'; + +function Legend(props) { + const { + view, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + fullColorEvents, + colorImpairedMode + } = props; + + const iconsToShow = []; + const isAgendaView = view === 'agenda'; + + if (showFinaleIcon) { + iconsToShow.push( + + ); + } + + if (showSpecialIcon) { + iconsToShow.push( + + ); + } + + if (showCutoffUnmetIcon) { + iconsToShow.push( + + ); + } + + return ( +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + {iconsToShow[0]} +
+ + { + iconsToShow.length > 1 && +
+ {iconsToShow[1]} + {iconsToShow[2]} +
+ } +
+ ); +} + +Legend.propTypes = { + view: PropTypes.string.isRequired, + showFinaleIcon: PropTypes.bool.isRequired, + showSpecialIcon: PropTypes.bool.isRequired, + showCutoffUnmetIcon: PropTypes.bool.isRequired, + fullColorEvents: PropTypes.bool.isRequired, + colorImpairedMode: PropTypes.bool.isRequired +}; + +export default Legend; diff --git a/frontend/src/Calendar/Legend/Legend.tsx b/frontend/src/Calendar/Legend/Legend.tsx deleted file mode 100644 index b9887f856..000000000 --- a/frontend/src/Calendar/Legend/Legend.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import React from 'react'; -import { useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import { icons, kinds } from 'Helpers/Props'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import translate from 'Utilities/String/translate'; -import LegendIconItem from './LegendIconItem'; -import LegendItem from './LegendItem'; -import styles from './Legend.css'; - -function Legend() { - const view = useSelector((state: AppState) => state.calendar.view); - const { - showFinaleIcon, - showSpecialIcon, - showCutoffUnmetIcon, - fullColorEvents, - } = useSelector((state: AppState) => state.calendar.options); - const { enableColorImpairedMode } = useSelector(createUISettingsSelector()); - - const iconsToShow = []; - const isAgendaView = view === 'agenda'; - - if (showFinaleIcon) { - iconsToShow.push( - - ); - - iconsToShow.push( - - ); - } - - if (showSpecialIcon) { - iconsToShow.push( - - ); - } - - if (showCutoffUnmetIcon) { - iconsToShow.push( - - ); - } - - return ( -
-
- - - -
- -
- - - -
- -
- - - -
- -
- - - {iconsToShow[0]} -
- - {iconsToShow.length > 1 ? ( -
- {iconsToShow[1]} - {iconsToShow[2]} -
- ) : null} - {iconsToShow.length > 3 ?
{iconsToShow[3]}
: null} -
- ); -} - -export default Legend; diff --git a/frontend/src/Calendar/Legend/LegendConnector.js b/frontend/src/Calendar/Legend/LegendConnector.js new file mode 100644 index 000000000..889b7a002 --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendConnector.js @@ -0,0 +1,21 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import Legend from './Legend'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar.options, + (state) => state.calendar.view, + createUISettingsSelector(), + (calendarOptions, view, uiSettings) => { + return { + ...calendarOptions, + view, + colorImpairedMode: uiSettings.enableColorImpairedMode + }; + } + ); +} + +export default connect(createMapStateToProps)(Legend); diff --git a/frontend/src/Calendar/Legend/LegendIconItem.css b/frontend/src/Calendar/Legend/LegendIconItem.css index c6c12027d..01db0ba5a 100644 --- a/frontend/src/Calendar/Legend/LegendIconItem.css +++ b/frontend/src/Calendar/Legend/LegendIconItem.css @@ -7,8 +7,4 @@ .icon { margin-right: 5px; - - &:global(.fullColorEvents) { - filter: var(--calendarFullColorFilter) - } } diff --git a/frontend/src/Calendar/Legend/LegendIconItem.css.d.ts b/frontend/src/Calendar/Legend/LegendIconItem.css.d.ts deleted file mode 100644 index 5d618d24b..000000000 --- a/frontend/src/Calendar/Legend/LegendIconItem.css.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'icon': string; - 'legendIconItem': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Legend/LegendIconItem.js b/frontend/src/Calendar/Legend/LegendIconItem.js new file mode 100644 index 000000000..5ce5f725b --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendIconItem.js @@ -0,0 +1,44 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Icon from 'Components/Icon'; +import styles from './LegendIconItem.css'; + +function LegendIconItem(props) { + const { + name, + icon, + kind, + darken, + tooltip + } = props; + + return ( +
+ + + {name} +
+ ); +} + +LegendIconItem.propTypes = { + name: PropTypes.string.isRequired, + icon: PropTypes.object.isRequired, + kind: PropTypes.string.isRequired, + darken: PropTypes.bool.isRequired, + tooltip: PropTypes.string.isRequired +}; + +LegendIconItem.defaultProps = { + darken: false +}; + +export default LegendIconItem; diff --git a/frontend/src/Calendar/Legend/LegendIconItem.tsx b/frontend/src/Calendar/Legend/LegendIconItem.tsx deleted file mode 100644 index 88a758c44..000000000 --- a/frontend/src/Calendar/Legend/LegendIconItem.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { FontAwesomeIconProps } from '@fortawesome/react-fontawesome'; -import classNames from 'classnames'; -import React from 'react'; -import Icon, { IconProps } from 'Components/Icon'; -import styles from './LegendIconItem.css'; - -interface LegendIconItemProps extends Pick { - name: string; - fullColorEvents: boolean; - icon: FontAwesomeIconProps['icon']; - tooltip: string; -} - -function LegendIconItem(props: LegendIconItemProps) { - const { name, fullColorEvents, icon, kind, tooltip } = props; - - return ( -
- - - {name} -
- ); -} - -export default LegendIconItem; diff --git a/frontend/src/Calendar/Legend/LegendItem.css.d.ts b/frontend/src/Calendar/Legend/LegendItem.css.d.ts deleted file mode 100644 index 155e029c6..000000000 --- a/frontend/src/Calendar/Legend/LegendItem.css.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'downloaded': string; - 'downloading': string; - 'legendItem': string; - 'missing': string; - 'onAir': string; - 'premiere': string; - 'unaired': string; - 'unmonitored': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Calendar/Legend/LegendItem.js b/frontend/src/Calendar/Legend/LegendItem.js new file mode 100644 index 000000000..a63cbf527 --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendItem.js @@ -0,0 +1,41 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import classNames from 'classnames'; +import titleCase from 'Utilities/String/titleCase'; +import styles from './LegendItem.css'; + +function LegendItem(props) { + const { + name, + status, + tooltip, + isAgendaView, + fullColorEvents, + colorImpairedMode + } = props; + + return ( +
+ {name ? name : titleCase(status)} +
+ ); +} + +LegendItem.propTypes = { + name: PropTypes.string, + status: PropTypes.string.isRequired, + tooltip: PropTypes.string.isRequired, + isAgendaView: PropTypes.bool.isRequired, + fullColorEvents: PropTypes.bool.isRequired, + colorImpairedMode: PropTypes.bool.isRequired +}; + +export default LegendItem; diff --git a/frontend/src/Calendar/Legend/LegendItem.tsx b/frontend/src/Calendar/Legend/LegendItem.tsx deleted file mode 100644 index 40466ab9d..000000000 --- a/frontend/src/Calendar/Legend/LegendItem.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import classNames from 'classnames'; -import React from 'react'; -import { CalendarStatus } from 'typings/Calendar'; -import titleCase from 'Utilities/String/titleCase'; -import styles from './LegendItem.css'; - -interface LegendItemProps { - name?: string; - status: CalendarStatus; - tooltip: string; - isAgendaView: boolean; - fullColorEvents: boolean; - colorImpairedMode: boolean; -} - -function LegendItem(props: LegendItemProps) { - const { - name, - status, - tooltip, - isAgendaView, - fullColorEvents, - colorImpairedMode, - } = props; - - return ( -
- {name ? name : titleCase(status)} -
- ); -} - -export default LegendItem; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModal.js b/frontend/src/Calendar/Options/CalendarOptionsModal.js new file mode 100644 index 000000000..b68c83f30 --- /dev/null +++ b/frontend/src/Calendar/Options/CalendarOptionsModal.js @@ -0,0 +1,29 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import CalendarOptionsModalContentConnector from './CalendarOptionsModalContentConnector'; + +function CalendarOptionsModal(props) { + const { + isOpen, + onModalClose + } = props; + + return ( + + + + ); +} + +CalendarOptionsModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default CalendarOptionsModal; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModal.tsx b/frontend/src/Calendar/Options/CalendarOptionsModal.tsx deleted file mode 100644 index ae782a684..000000000 --- a/frontend/src/Calendar/Options/CalendarOptionsModal.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import React from 'react'; -import Modal from 'Components/Modal/Modal'; -import CalendarOptionsModalContent from './CalendarOptionsModalContent'; - -interface CalendarOptionsModalProps { - isOpen: boolean; - onModalClose: () => void; -} - -function CalendarOptionsModal({ - isOpen, - onModalClose, -}: CalendarOptionsModalProps) { - return ( - - - - ); -} - -export default CalendarOptionsModal; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModalContent.js b/frontend/src/Calendar/Options/CalendarOptionsModalContent.js new file mode 100644 index 000000000..0b34219a0 --- /dev/null +++ b/frontend/src/Calendar/Options/CalendarOptionsModalContent.js @@ -0,0 +1,275 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { inputTypes } from 'Helpers/Props'; +import FieldSet from 'Components/FieldSet'; +import Button from 'Components/Link/Button'; +import Form from 'Components/Form/Form'; +import FormGroup from 'Components/Form/FormGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; +import { firstDayOfWeekOptions, weekColumnOptions, timeFormatOptions } from 'Settings/UI/UISettings'; + +class CalendarOptionsModalContent extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + const { + firstDayOfWeek, + calendarWeekColumnHeader, + timeFormat, + enableColorImpairedMode, + fullColorEvents + } = props; + + this.state = { + firstDayOfWeek, + calendarWeekColumnHeader, + timeFormat, + enableColorImpairedMode, + fullColorEvents + }; + } + + componentDidUpdate(prevProps) { + const { + firstDayOfWeek, + calendarWeekColumnHeader, + timeFormat, + enableColorImpairedMode + } = this.props; + + if ( + prevProps.firstDayOfWeek !== firstDayOfWeek || + prevProps.calendarWeekColumnHeader !== calendarWeekColumnHeader || + prevProps.timeFormat !== timeFormat || + prevProps.enableColorImpairedMode !== enableColorImpairedMode + ) { + this.setState({ + firstDayOfWeek, + calendarWeekColumnHeader, + timeFormat, + enableColorImpairedMode + }); + } + } + + // + // Listeners + + onOptionInputChange = ({ name, value }) => { + const { + dispatchSetCalendarOption + } = this.props; + + dispatchSetCalendarOption({ [name]: value }); + } + + onGlobalInputChange = ({ name, value }) => { + const { + dispatchSaveUISettings + } = this.props; + + const setting = { [name]: value }; + + this.setState(setting, () => { + dispatchSaveUISettings(setting); + }); + } + + onLinkFocus = (event) => { + event.target.select(); + } + + // + // Render + + render() { + const { + collapseMultipleEpisodes, + showEpisodeInformation, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + fullColorEvents, + onModalClose + } = this.props; + + const { + firstDayOfWeek, + calendarWeekColumnHeader, + timeFormat, + enableColorImpairedMode + } = this.state; + + return ( + + + Calendar Options + + + +
+ + + Collapse Multiple Episodes + + + + + + Show Episode Information + + + + + + Icon for Finales + + + + + + Icon for Specials + + + + + + Icon for Cutoff Unmet + + + + + + Full Color Events + + + + +
+ +
+
+ + First Day of Week + + + + + + Week Column Header + + + + + + Time Format + + + + + + Enable Color-Impaired Mode + + + +
+
+
+ + + + +
+ ); + } +} + +CalendarOptionsModalContent.propTypes = { + collapseMultipleEpisodes: PropTypes.bool.isRequired, + showEpisodeInformation: PropTypes.bool.isRequired, + showFinaleIcon: PropTypes.bool.isRequired, + showSpecialIcon: PropTypes.bool.isRequired, + showCutoffUnmetIcon: PropTypes.bool.isRequired, + firstDayOfWeek: PropTypes.number.isRequired, + calendarWeekColumnHeader: PropTypes.string.isRequired, + timeFormat: PropTypes.string.isRequired, + enableColorImpairedMode: PropTypes.bool.isRequired, + fullColorEvents: PropTypes.bool.isRequired, + dispatchSetCalendarOption: PropTypes.func.isRequired, + dispatchSaveUISettings: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default CalendarOptionsModalContent; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModalContent.tsx b/frontend/src/Calendar/Options/CalendarOptionsModalContent.tsx deleted file mode 100644 index 4f974dda3..000000000 --- a/frontend/src/Calendar/Options/CalendarOptionsModalContent.tsx +++ /dev/null @@ -1,228 +0,0 @@ -import React, { useCallback, useEffect, useState } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import FieldSet from 'Components/FieldSet'; -import Form from 'Components/Form/Form'; -import FormGroup from 'Components/Form/FormGroup'; -import FormInputGroup from 'Components/Form/FormInputGroup'; -import FormLabel from 'Components/Form/FormLabel'; -import Button from 'Components/Link/Button'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import { inputTypes } from 'Helpers/Props'; -import { - firstDayOfWeekOptions, - timeFormatOptions, - weekColumnOptions, -} from 'Settings/UI/UISettings'; -import { setCalendarOption } from 'Store/Actions/calendarActions'; -import { saveUISettings } from 'Store/Actions/settingsActions'; -import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; -import { InputChanged } from 'typings/inputs'; -import UiSettings from 'typings/Settings/UiSettings'; -import translate from 'Utilities/String/translate'; - -interface CalendarOptionsModalContentProps { - onModalClose: () => void; -} - -function CalendarOptionsModalContent({ - onModalClose, -}: CalendarOptionsModalContentProps) { - const dispatch = useDispatch(); - - const { - collapseMultipleEpisodes, - showEpisodeInformation, - showFinaleIcon, - showSpecialIcon, - showCutoffUnmetIcon, - fullColorEvents, - } = useSelector((state: AppState) => state.calendar.options); - - const uiSettings = useSelector(createUISettingsSelector()); - - const [state, setState] = useState>({ - firstDayOfWeek: uiSettings.firstDayOfWeek, - calendarWeekColumnHeader: uiSettings.calendarWeekColumnHeader, - timeFormat: uiSettings.timeFormat, - enableColorImpairedMode: uiSettings.enableColorImpairedMode, - }); - - const { - firstDayOfWeek, - calendarWeekColumnHeader, - timeFormat, - enableColorImpairedMode, - } = state; - - const handleOptionInputChange = useCallback( - ({ name, value }: InputChanged) => { - dispatch(setCalendarOption({ [name]: value })); - }, - [dispatch] - ); - - const handleGlobalInputChange = useCallback( - ({ name, value }: InputChanged) => { - setState((prevState) => ({ ...prevState, [name]: value })); - - dispatch(saveUISettings({ [name]: value })); - }, - [dispatch] - ); - - useEffect(() => { - setState({ - firstDayOfWeek: uiSettings.firstDayOfWeek, - calendarWeekColumnHeader: uiSettings.calendarWeekColumnHeader, - timeFormat: uiSettings.timeFormat, - enableColorImpairedMode: uiSettings.enableColorImpairedMode, - }); - }, [uiSettings]); - - return ( - - {translate('CalendarOptions')} - - -
-
- - {translate('CollapseMultipleEpisodes')} - - - - - - {translate('ShowEpisodeInformation')} - - - - - - {translate('IconForFinales')} - - - - - - {translate('IconForSpecials')} - - - - - - {translate('IconForCutoffUnmet')} - - - - - - {translate('FullColorEvents')} - - - -
-
- -
-
- - {translate('FirstDayOfWeek')} - - - - - - {translate('WeekColumnHeader')} - - - - - - {translate('TimeFormat')} - - - - - - {translate('EnableColorImpairedMode')} - - - -
-
-
- - - - -
- ); -} - -export default CalendarOptionsModalContent; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModalContentConnector.js b/frontend/src/Calendar/Options/CalendarOptionsModalContentConnector.js new file mode 100644 index 000000000..eb979f74e --- /dev/null +++ b/frontend/src/Calendar/Options/CalendarOptionsModalContentConnector.js @@ -0,0 +1,25 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { setCalendarOption } from 'Store/Actions/calendarActions'; +import CalendarOptionsModalContent from './CalendarOptionsModalContent'; +import { saveUISettings } from 'Store/Actions/settingsActions'; + +function createMapStateToProps() { + return createSelector( + (state) => state.calendar.options, + (state) => state.settings.ui.item, + (options, uiSettings) => { + return { + ...options, + ...uiSettings + }; + } + ); +} + +const mapDispatchToProps = { + dispatchSetCalendarOption: setCalendarOption, + dispatchSaveUISettings: saveUISettings +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(CalendarOptionsModalContent); diff --git a/frontend/src/Calendar/calendarViews.js b/frontend/src/Calendar/calendarViews.js new file mode 100644 index 000000000..929958b66 --- /dev/null +++ b/frontend/src/Calendar/calendarViews.js @@ -0,0 +1,7 @@ +export const DAY = 'day'; +export const WEEK = 'week'; +export const MONTH = 'month'; +export const FORECAST = 'forecast'; +export const AGENDA = 'agenda'; + +export const all = [DAY, WEEK, MONTH, FORECAST, AGENDA]; diff --git a/frontend/src/Calendar/calendarViews.ts b/frontend/src/Calendar/calendarViews.ts deleted file mode 100644 index 4f5549dbd..000000000 --- a/frontend/src/Calendar/calendarViews.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const DAY = 'day'; -export const WEEK = 'week'; -export const MONTH = 'month'; -export const FORECAST = 'forecast'; -export const AGENDA = 'agenda'; - -export const all = [DAY, WEEK, MONTH, FORECAST, AGENDA]; - -export type CalendarView = 'agenda' | 'day' | 'forecast' | 'month' | 'week'; diff --git a/frontend/src/Calendar/getStatusStyle.js b/frontend/src/Calendar/getStatusStyle.js new file mode 100644 index 000000000..b149a8aab --- /dev/null +++ b/frontend/src/Calendar/getStatusStyle.js @@ -0,0 +1,30 @@ +/* eslint max-params: 0 */ +import moment from 'moment'; + +function getStatusStyle(hasFile, downloading, startTime, endTime, isMonitored) { + const currentTime = moment(); + + if (hasFile) { + return 'downloaded'; + } + + if (downloading) { + return 'downloading'; + } + + if (!isMonitored) { + return 'unmonitored'; + } + + if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) { + return 'onAir'; + } + + if (endTime.isBefore(currentTime) && !hasFile) { + return 'missing'; + } + + return 'unaired'; +} + +export default getStatusStyle; diff --git a/frontend/src/Calendar/getStatusStyle.ts b/frontend/src/Calendar/getStatusStyle.ts deleted file mode 100644 index 678e6c2a1..000000000 --- a/frontend/src/Calendar/getStatusStyle.ts +++ /dev/null @@ -1,36 +0,0 @@ -import moment from 'moment'; -import { CalendarStatus } from 'typings/Calendar'; - -function getStatusStyle( - hasFile: boolean, - downloading: boolean, - startTime: moment.Moment, - endTime: moment.Moment, - isMonitored: boolean -): CalendarStatus { - const currentTime = moment(); - - if (hasFile) { - return 'downloaded'; - } - - if (downloading) { - return 'downloading'; - } - - if (!isMonitored) { - return 'unmonitored'; - } - - if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) { - return 'onAir'; - } - - if (endTime.isBefore(currentTime) && !hasFile) { - return 'missing'; - } - - return 'unaired'; -} - -export default getStatusStyle; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModal.js b/frontend/src/Calendar/iCal/CalendarLinkModal.js new file mode 100644 index 000000000..8cc487c16 --- /dev/null +++ b/frontend/src/Calendar/iCal/CalendarLinkModal.js @@ -0,0 +1,29 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import CalendarLinkModalContentConnector from './CalendarLinkModalContentConnector'; + +function CalendarLinkModal(props) { + const { + isOpen, + onModalClose + } = props; + + return ( + + + + ); +} + +CalendarLinkModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default CalendarLinkModal; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModal.tsx b/frontend/src/Calendar/iCal/CalendarLinkModal.tsx deleted file mode 100644 index f0eecbd4a..000000000 --- a/frontend/src/Calendar/iCal/CalendarLinkModal.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import React from 'react'; -import Modal from 'Components/Modal/Modal'; -import CalendarLinkModalContent from './CalendarLinkModalContent'; - -interface CalendarLinkModalProps { - isOpen: boolean; - onModalClose: () => void; -} - -function CalendarLinkModal(props: CalendarLinkModalProps) { - const { isOpen, onModalClose } = props; - - return ( - - - - ); -} - -export default CalendarLinkModal; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModalContent.js b/frontend/src/Calendar/iCal/CalendarLinkModalContent.js new file mode 100644 index 000000000..e965b862d --- /dev/null +++ b/frontend/src/Calendar/iCal/CalendarLinkModalContent.js @@ -0,0 +1,221 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { icons, inputTypes, kinds, sizes } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import Button from 'Components/Link/Button'; +import ClipboardButton from 'Components/Link/ClipboardButton'; +import Form from 'Components/Form/Form'; +import FormGroup from 'Components/Form/FormGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import FormInputButton from 'Components/Form/FormInputButton'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; + +function getUrls(state) { + const { + unmonitored, + premieresOnly, + asAllDay, + tags + } = state; + + let icalUrl = `${window.location.host}${window.Sonarr.urlBase}/feed/calendar/Sonarr.ics?`; + + if (unmonitored) { + icalUrl += 'unmonitored=true&'; + } + + if (premieresOnly) { + icalUrl += 'premieresOnly=true&'; + } + + if (asAllDay) { + icalUrl += 'asAllDay=true&'; + } + + if (tags.length) { + icalUrl += `tags=${tags.toString()}&`; + } + + icalUrl += `apikey=${window.Sonarr.apiKey}`; + + const iCalHttpUrl = `${window.location.protocol}//${icalUrl}`; + const iCalWebCalUrl = `webcal://${icalUrl}`; + + return { + iCalHttpUrl, + iCalWebCalUrl + }; +} + +class CalendarLinkModalContent extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + const defaultState = { + unmonitored: false, + premieresOnly: false, + asAllDay: false, + tags: [] + }; + + const urls = getUrls(defaultState); + + this.state = { + ...defaultState, + ...urls + }; + } + + // + // Listeners + + onInputChange = ({ name, value }) => { + const state = { + ...this.state, + [name]: value + }; + + const urls = getUrls(state); + + this.setState({ + [name]: value, + ...urls + }); + } + + onLinkFocus = (event) => { + event.target.select(); + } + + // + // Render + + render() { + const { + onModalClose + } = this.props; + + const { + unmonitored, + premieresOnly, + asAllDay, + tags, + iCalHttpUrl, + iCalWebCalUrl + } = this.state; + + return ( + + + Sonarr Calendar Feed + + + +
+ + Include Unmonitored + + + + + + Season Premieres Only + + + + + + Show as All-Day Events + + + + + + Tags + + + + + + iCal Feed + + , + + + + + ]} + onChange={this.onInputChange} + onFocus={this.onLinkFocus} + /> + +
+
+ + + + +
+ ); + } +} + +CalendarLinkModalContent.propTypes = { + tagList: PropTypes.arrayOf(PropTypes.object).isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default CalendarLinkModalContent; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModalContent.tsx b/frontend/src/Calendar/iCal/CalendarLinkModalContent.tsx deleted file mode 100644 index aa90db301..000000000 --- a/frontend/src/Calendar/iCal/CalendarLinkModalContent.tsx +++ /dev/null @@ -1,166 +0,0 @@ -import React, { FocusEvent, useCallback, useMemo, useState } from 'react'; -import Form from 'Components/Form/Form'; -import FormGroup from 'Components/Form/FormGroup'; -import FormInputButton from 'Components/Form/FormInputButton'; -import FormInputGroup from 'Components/Form/FormInputGroup'; -import FormLabel from 'Components/Form/FormLabel'; -import Icon from 'Components/Icon'; -import Button from 'Components/Link/Button'; -import ClipboardButton from 'Components/Link/ClipboardButton'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import { icons, inputTypes, kinds, sizes } from 'Helpers/Props'; -import { InputChanged } from 'typings/inputs'; -import translate from 'Utilities/String/translate'; - -interface CalendarLinkModalContentProps { - onModalClose: () => void; -} - -function CalendarLinkModalContent({ - onModalClose, -}: CalendarLinkModalContentProps) { - const [state, setState] = useState({ - unmonitored: false, - premieresOnly: false, - asAllDay: false, - tags: [], - }); - - const { unmonitored, premieresOnly, asAllDay, tags } = state; - - const handleInputChange = useCallback(({ name, value }: InputChanged) => { - setState((prevState) => ({ ...prevState, [name]: value })); - }, []); - - const handleLinkFocus = useCallback( - (event: FocusEvent) => { - event.target.select(); - }, - [] - ); - - const { iCalHttpUrl, iCalWebCalUrl } = useMemo(() => { - let icalUrl = `${window.location.host}${window.Sonarr.urlBase}/feed/v3/calendar/Sonarr.ics?`; - - if (unmonitored) { - icalUrl += 'unmonitored=true&'; - } - - if (premieresOnly) { - icalUrl += 'premieresOnly=true&'; - } - - if (asAllDay) { - icalUrl += 'asAllDay=true&'; - } - - if (tags.length) { - icalUrl += `tags=${tags.toString()}&`; - } - - icalUrl += `apikey=${encodeURIComponent(window.Sonarr.apiKey)}`; - - return { - iCalHttpUrl: `${window.location.protocol}//${icalUrl}`, - iCalWebCalUrl: `webcal://${icalUrl}`, - }; - }, [unmonitored, premieresOnly, asAllDay, tags]); - - return ( - - {translate('CalendarFeed')} - - -
- - {translate('IncludeUnmonitored')} - - - - - - {translate('SeasonPremieresOnly')} - - - - - - {translate('ICalShowAsAllDayEvents')} - - - - - - {translate('Tags')} - - - - - - {translate('ICalFeed')} - - , - - - - , - ]} - onChange={handleInputChange} - onFocus={handleLinkFocus} - /> - -
-
- - - - -
- ); -} - -export default CalendarLinkModalContent; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModalContentConnector.js b/frontend/src/Calendar/iCal/CalendarLinkModalContentConnector.js new file mode 100644 index 000000000..e10c5c3f9 --- /dev/null +++ b/frontend/src/Calendar/iCal/CalendarLinkModalContentConnector.js @@ -0,0 +1,17 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createTagsSelector from 'Store/Selectors/createTagsSelector'; +import CalendarLinkModalContent from './CalendarLinkModalContent'; + +function createMapStateToProps() { + return createSelector( + createTagsSelector(), + (tagList) => { + return { + tagList + }; + } + ); +} + +export default connect(createMapStateToProps)(CalendarLinkModalContent); diff --git a/frontend/src/Commands/Command.ts b/frontend/src/Commands/Command.ts deleted file mode 100644 index cd875d56b..000000000 --- a/frontend/src/Commands/Command.ts +++ /dev/null @@ -1,52 +0,0 @@ -import ModelBase from 'App/ModelBase'; - -export type CommandStatus = - | 'queued' - | 'started' - | 'completed' - | 'failed' - | 'aborted' - | 'cancelled' - | 'orphaned'; - -export type CommandResult = 'unknown' | 'successful' | 'unsuccessful'; - -export interface CommandBody { - sendUpdatesToClient: boolean; - updateScheduledTask: boolean; - completionMessage: string; - requiresDiskAccess: boolean; - isExclusive: boolean; - isLongRunning: boolean; - name: string; - lastExecutionTime: string; - lastStartTime: string; - trigger: string; - suppressMessages: boolean; - seriesId?: number; - seriesIds?: number[]; - seasonNumber?: number; - episodeIds?: number[]; - [key: string]: string | number | boolean | number[] | undefined; -} - -interface Command extends ModelBase { - name: string; - commandName: string; - message: string; - body: CommandBody; - priority: string; - status: CommandStatus; - result: CommandResult; - queued: string; - started: string; - ended: string; - duration: string; - trigger: string; - stateChangeTime: string; - sendUpdatesToClient: boolean; - updateScheduledTask: boolean; - lastExecutionTime: string; -} - -export default Command; diff --git a/frontend/src/Commands/commandNames.js b/frontend/src/Commands/commandNames.js index 13ac9d62c..9945fd8f8 100644 --- a/frontend/src/Commands/commandNames.js +++ b/frontend/src/Commands/commandNames.js @@ -6,7 +6,7 @@ export const CLEAR_LOGS = 'ClearLog'; export const CUTOFF_UNMET_EPISODE_SEARCH = 'CutoffUnmetEpisodeSearch'; export const DELETE_LOG_FILES = 'DeleteLogFiles'; export const DELETE_UPDATE_LOG_FILES = 'DeleteUpdateLogFiles'; -export const DOWNLOADED_EPISODES_SCAN = 'DownloadedEpisodesScan'; +export const DOWNLOADED_EPSIODES_SCAN = 'DownloadedEpisodesScan'; export const EPISODE_SEARCH = 'EpisodeSearch'; export const INTERACTIVE_IMPORT = 'ManualImport'; export const MISSING_EPISODE_SEARCH = 'MissingEpisodeSearch'; @@ -15,7 +15,6 @@ export const REFRESH_SERIES = 'RefreshSeries'; export const RENAME_FILES = 'RenameFiles'; export const RENAME_SERIES = 'RenameSeries'; export const RESET_API_KEY = 'ResetApiKey'; -export const RESET_QUALITY_DEFINITIONS = 'ResetQualityDefinitions'; export const RSS_SYNC = 'RssSync'; export const SEASON_SEARCH = 'SeasonSearch'; export const SERIES_SEARCH = 'SeriesSearch'; diff --git a/frontend/src/Components/Alert.css b/frontend/src/Components/Alert.css index 135d1ee2b..312fbb4f2 100644 --- a/frontend/src/Components/Alert.css +++ b/frontend/src/Components/Alert.css @@ -7,25 +7,25 @@ } .danger { - border-color: var(--alertDangerBorderColor); - background-color: var(--alertDangerBackgroundColor); - color: var(--alertDangerColor); + border-color: $alertDangerBorderColor; + background-color: $alertDangerBackgroundColor; + color: $alertDangerColor; } .info { - border-color: var(--alertInfoBorderColor); - background-color: var(--alertInfoBackgroundColor); - color: var(--alertInfoColor); + border-color: $alertInfoBorderColor; + background-color: $alertInfoBackgroundColor; + color: $alertInfoColor; } .success { - border-color: var(--alertSuccessBorderColor); - background-color: var(--alertSuccessBackgroundColor); - color: var(--alertSuccessColor); + border-color: $alertSuccessBorderColor; + background-color: $alertSuccessBackgroundColor; + color: $alertSuccessColor; } .warning { - border-color: var(--alertWarningBorderColor); - background-color: var(--alertWarningBackgroundColor); - color: var(--alertWarningColor); + border-color: $alertWarningBorderColor; + background-color: $alertWarningBackgroundColor; + color: $alertWarningColor; } diff --git a/frontend/src/Components/Alert.css.d.ts b/frontend/src/Components/Alert.css.d.ts deleted file mode 100644 index daffec2e6..000000000 --- a/frontend/src/Components/Alert.css.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'alert': string; - 'danger': string; - 'info': string; - 'success': string; - 'warning': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Alert.js b/frontend/src/Components/Alert.js new file mode 100644 index 000000000..dc19a418c --- /dev/null +++ b/frontend/src/Components/Alert.js @@ -0,0 +1,32 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import classNames from 'classnames'; +import { kinds } from 'Helpers/Props'; +import styles from './Alert.css'; + +function Alert({ className, kind, children, ...otherProps }) { + return ( +
+ {children} +
+ ); +} + +Alert.propTypes = { + className: PropTypes.string.isRequired, + kind: PropTypes.oneOf(kinds.all).isRequired, + children: PropTypes.node.isRequired +}; + +Alert.defaultProps = { + className: styles.alert, + kind: kinds.INFO +}; + +export default Alert; diff --git a/frontend/src/Components/Alert.tsx b/frontend/src/Components/Alert.tsx deleted file mode 100644 index 92c89e741..000000000 --- a/frontend/src/Components/Alert.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import classNames from 'classnames'; -import React from 'react'; -import { Kind } from 'Helpers/Props/kinds'; -import styles from './Alert.css'; - -interface AlertProps { - className?: string; - kind?: Extract; - children: React.ReactNode; -} - -function Alert(props: AlertProps) { - const { className = styles.alert, kind = 'info', children } = props; - - return
{children}
; -} - -export default Alert; diff --git a/frontend/src/Components/Card.css b/frontend/src/Components/Card.css index 49a9abd76..b54bbcdf4 100644 --- a/frontend/src/Components/Card.css +++ b/frontend/src/Components/Card.css @@ -3,9 +3,9 @@ margin: 10px; padding: 10px; border-radius: 3px; - background-color: var(--cardBackgroundColor); - box-shadow: 0 0 10px 1px var(--cardShadowColor); - color: var(--defaultColor); + background-color: $white; + box-shadow: 0 0 10px 1px $cardShadowColor; + color: $defaultColor; } .underlay { diff --git a/frontend/src/Components/Card.css.d.ts b/frontend/src/Components/Card.css.d.ts deleted file mode 100644 index fb3ea792e..000000000 --- a/frontend/src/Components/Card.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'card': string; - 'overlay': string; - 'underlay': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Card.js b/frontend/src/Components/Card.js new file mode 100644 index 000000000..c5a4d164c --- /dev/null +++ b/frontend/src/Components/Card.js @@ -0,0 +1,60 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Link from 'Components/Link/Link'; +import styles from './Card.css'; + +class Card extends Component { + + // + // Render + + render() { + const { + className, + overlayClassName, + overlayContent, + children, + onPress + } = this.props; + + if (overlayContent) { + return ( +
+ + +
+ {children} +
+
+ ); + } + + return ( + + {children} + + ); + } +} + +Card.propTypes = { + className: PropTypes.string.isRequired, + overlayClassName: PropTypes.string.isRequired, + overlayContent: PropTypes.bool.isRequired, + children: PropTypes.node.isRequired, + onPress: PropTypes.func.isRequired +}; + +Card.defaultProps = { + className: styles.card, + overlayClassName: styles.overlay, + overlayContent: false +}; + +export default Card; diff --git a/frontend/src/Components/Card.tsx b/frontend/src/Components/Card.tsx deleted file mode 100644 index 24588c841..000000000 --- a/frontend/src/Components/Card.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import React from 'react'; -import Link, { LinkProps } from 'Components/Link/Link'; -import styles from './Card.css'; - -interface CardProps extends Pick { - // TODO: Consider using different properties for classname depending if it's overlaying content or not - className?: string; - overlayClassName?: string; - overlayContent?: boolean; - children: React.ReactNode; -} - -function Card(props: CardProps) { - const { - className = styles.card, - overlayClassName = styles.overlay, - overlayContent = false, - children, - onPress, - } = props; - - if (overlayContent) { - return ( -
- - -
{children}
-
- ); - } - - return ( - - {children} - - ); -} - -export default Card; diff --git a/frontend/src/Components/CircularProgressBar.css.d.ts b/frontend/src/Components/CircularProgressBar.css.d.ts deleted file mode 100644 index 45179620c..000000000 --- a/frontend/src/Components/CircularProgressBar.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'circularProgressBar': string; - 'circularProgressBarContainer': string; - 'circularProgressBarText': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/CircularProgressBar.js b/frontend/src/Components/CircularProgressBar.js new file mode 100644 index 000000000..95c84f59a --- /dev/null +++ b/frontend/src/Components/CircularProgressBar.js @@ -0,0 +1,139 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import colors from 'Styles/Variables/colors'; +import styles from './CircularProgressBar.css'; + +class CircularProgressBar extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + progress: 0 + }; + } + + componentDidMount() { + this._progressStep(); + } + + componentDidUpdate(prevProps) { + const progress = this.props.progress; + + if (prevProps.progress !== progress) { + this._cancelProgressStep(); + this._progressStep(); + } + } + + componentWillUnmount() { + this._cancelProgressStep(); + } + + // + // Control + + _progressStep() { + this.requestAnimationFrame = window.requestAnimationFrame(() => { + this.setState({ + progress: this.state.progress + 1 + }, () => { + if (this.state.progress < this.props.progress) { + this._progressStep(); + } + }); + }); + } + + _cancelProgressStep() { + if (this.requestAnimationFrame) { + window.cancelAnimationFrame(this.requestAnimationFrame); + } + } + + // + // Render + + render() { + const { + className, + containerClassName, + size, + strokeWidth, + strokeColor, + showProgressText + } = this.props; + + const progress = this.state.progress; + + const center = size / 2; + const radius = center - strokeWidth; + const circumference = Math.PI * (radius * 2); + const sizeInPixels = `${size}px`; + const strokeDashoffset = ((100 - progress) / 100) * circumference; + const progressText = `${Math.round(progress)}%`; + + return ( +
+ + + + + { + showProgressText && +
+ {progressText} +
+ } +
+ ); + } +} + +CircularProgressBar.propTypes = { + className: PropTypes.string, + containerClassName: PropTypes.string, + size: PropTypes.number, + progress: PropTypes.number.isRequired, + strokeWidth: PropTypes.number, + strokeColor: PropTypes.string, + showProgressText: PropTypes.bool +}; + +CircularProgressBar.defaultProps = { + className: styles.circularProgressBar, + containerClassName: styles.circularProgressBarContainer, + size: 60, + strokeWidth: 5, + strokeColor: colors.sonarrBlue, + showProgressText: false +}; + +export default CircularProgressBar; diff --git a/frontend/src/Components/CircularProgressBar.tsx b/frontend/src/Components/CircularProgressBar.tsx deleted file mode 100644 index b14f5fc6a..000000000 --- a/frontend/src/Components/CircularProgressBar.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import React, { useCallback, useEffect, useState } from 'react'; -import styles from './CircularProgressBar.css'; - -interface CircularProgressBarProps { - className?: string; - containerClassName?: string; - size?: number; - progress: number; - strokeWidth?: number; - strokeColor?: string; - showProgressText?: boolean; -} - -function CircularProgressBar({ - className = styles.circularProgressBar, - containerClassName = styles.circularProgressBarContainer, - size = 60, - strokeWidth = 5, - strokeColor = '#35c5f4', - showProgressText = false, - progress, -}: CircularProgressBarProps) { - const [currentProgress, setCurrentProgress] = useState(0); - const raf = React.useRef(0); - const center = size / 2; - const radius = center - strokeWidth; - const circumference = Math.PI * (radius * 2); - const sizeInPixels = `${size}px`; - const strokeDashoffset = ((100 - currentProgress) / 100) * circumference; - const progressText = `${Math.round(currentProgress)}%`; - - const handleAnimation = useCallback( - (p: number) => { - setCurrentProgress((prevProgress) => { - if (prevProgress < p) { - return prevProgress + Math.min(1, p - prevProgress); - } - - return prevProgress; - }); - }, - [setCurrentProgress] - ); - - useEffect(() => { - if (progress > currentProgress) { - cancelAnimationFrame(raf.current); - - raf.current = requestAnimationFrame(() => handleAnimation(progress)); - } - }, [progress, currentProgress, handleAnimation]); - - useEffect( - () => { - return () => cancelAnimationFrame(raf.current); - }, - // We only want to run this effect once - // eslint-disable-next-line react-hooks/exhaustive-deps - [] - ); - - return ( -
- - - - - {showProgressText && ( -
{progressText}
- )} -
- ); -} - -export default CircularProgressBar; diff --git a/frontend/src/Components/DescriptionList/DescriptionList.css.d.ts b/frontend/src/Components/DescriptionList/DescriptionList.css.d.ts deleted file mode 100644 index 34c1578a4..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionList.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'descriptionList': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/DescriptionList/DescriptionList.js b/frontend/src/Components/DescriptionList/DescriptionList.js new file mode 100644 index 000000000..be2c87c55 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionList.js @@ -0,0 +1,33 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import styles from './DescriptionList.css'; + +class DescriptionList extends Component { + + // + // Render + + render() { + const { + className, + children + } = this.props; + + return ( +
+ {children} +
+ ); + } +} + +DescriptionList.propTypes = { + className: PropTypes.string.isRequired, + children: PropTypes.node +}; + +DescriptionList.defaultProps = { + className: styles.descriptionList +}; + +export default DescriptionList; diff --git a/frontend/src/Components/DescriptionList/DescriptionList.tsx b/frontend/src/Components/DescriptionList/DescriptionList.tsx deleted file mode 100644 index 6deee77e5..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionList.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from 'react'; -import styles from './DescriptionList.css'; - -interface DescriptionListProps { - className?: string; - children?: React.ReactNode; -} - -function DescriptionList(props: DescriptionListProps) { - const { className = styles.descriptionList, children } = props; - - return
{children}
; -} - -export default DescriptionList; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItem.js b/frontend/src/Components/DescriptionList/DescriptionListItem.js new file mode 100644 index 000000000..4ba70bf33 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItem.js @@ -0,0 +1,44 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import DescriptionListItemTitle from './DescriptionListItemTitle'; +import DescriptionListItemDescription from './DescriptionListItemDescription'; + +class DescriptionListItem extends Component { + + // + // Render + + render() { + const { + titleClassName, + descriptionClassName, + title, + data + } = this.props; + + return ( + + + {title} + + + + {data} + + + ); + } +} + +DescriptionListItem.propTypes = { + titleClassName: PropTypes.string, + descriptionClassName: PropTypes.string, + title: PropTypes.string, + data: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.node]) +}; + +export default DescriptionListItem; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItem.tsx b/frontend/src/Components/DescriptionList/DescriptionListItem.tsx deleted file mode 100644 index 13a7efdd0..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionListItem.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react'; -import DescriptionListItemDescription, { - DescriptionListItemDescriptionProps, -} from './DescriptionListItemDescription'; -import DescriptionListItemTitle, { - DescriptionListItemTitleProps, -} from './DescriptionListItemTitle'; - -interface DescriptionListItemProps { - className?: string; - titleClassName?: DescriptionListItemTitleProps['className']; - descriptionClassName?: DescriptionListItemDescriptionProps['className']; - title?: DescriptionListItemTitleProps['children']; - data?: DescriptionListItemDescriptionProps['children']; -} - -function DescriptionListItem(props: DescriptionListItemProps) { - const { className, titleClassName, descriptionClassName, title, data } = - props; - - return ( -
- - {title} - - - - {data} - -
- ); -} - -export default DescriptionListItem; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css index 786123fb7..b23415a76 100644 --- a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css +++ b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css @@ -1,7 +1,9 @@ +.description { + line-height: $lineHeight; +} + .description { margin-left: 0; - line-height: $lineHeight; - overflow-wrap: break-word; } @media (min-width: 768px) { diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css.d.ts b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css.d.ts deleted file mode 100644 index ff7055b0f..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'description': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.js b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.js new file mode 100644 index 000000000..4ef3c015e --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.js @@ -0,0 +1,27 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import styles from './DescriptionListItemDescription.css'; + +function DescriptionListItemDescription(props) { + const { + className, + children + } = props; + + return ( +
+ {children} +
+ ); +} + +DescriptionListItemDescription.propTypes = { + className: PropTypes.string.isRequired, + children: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.node]) +}; + +DescriptionListItemDescription.defaultProps = { + className: styles.description +}; + +export default DescriptionListItemDescription; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.tsx b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.tsx deleted file mode 100644 index e08c117dc..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import React, { ReactNode } from 'react'; -import styles from './DescriptionListItemDescription.css'; - -export interface DescriptionListItemDescriptionProps { - className?: string; - children?: ReactNode; -} - -function DescriptionListItemDescription( - props: DescriptionListItemDescriptionProps -) { - const { className = styles.description, children } = props; - - return
{children}
; -} - -export default DescriptionListItemDescription; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css.d.ts b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css.d.ts deleted file mode 100644 index 86bceec06..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'title': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.js b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.js new file mode 100644 index 000000000..e1632c1cf --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.js @@ -0,0 +1,27 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import styles from './DescriptionListItemTitle.css'; + +function DescriptionListItemTitle(props) { + const { + className, + children + } = props; + + return ( +
+ {children} +
+ ); +} + +DescriptionListItemTitle.propTypes = { + className: PropTypes.string.isRequired, + children: PropTypes.string +}; + +DescriptionListItemTitle.defaultProps = { + className: styles.title +}; + +export default DescriptionListItemTitle; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.tsx b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.tsx deleted file mode 100644 index 59ea6955c..000000000 --- a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React, { ReactNode } from 'react'; -import styles from './DescriptionListItemTitle.css'; - -export interface DescriptionListItemTitleProps { - className?: string; - children?: ReactNode; -} - -function DescriptionListItemTitle(props: DescriptionListItemTitleProps) { - const { className = styles.title, children } = props; - - return
{children}
; -} - -export default DescriptionListItemTitle; diff --git a/frontend/src/Components/DragPreviewLayer.css.d.ts b/frontend/src/Components/DragPreviewLayer.css.d.ts deleted file mode 100644 index 6944a829d..000000000 --- a/frontend/src/Components/DragPreviewLayer.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'dragLayer': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/DragPreviewLayer.js b/frontend/src/Components/DragPreviewLayer.js new file mode 100644 index 000000000..a111df70e --- /dev/null +++ b/frontend/src/Components/DragPreviewLayer.js @@ -0,0 +1,22 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import styles from './DragPreviewLayer.css'; + +function DragPreviewLayer({ children, ...otherProps }) { + return ( +
+ {children} +
+ ); +} + +DragPreviewLayer.propTypes = { + children: PropTypes.node, + className: PropTypes.string +}; + +DragPreviewLayer.defaultProps = { + className: styles.dragLayer +}; + +export default DragPreviewLayer; diff --git a/frontend/src/Components/DragPreviewLayer.tsx b/frontend/src/Components/DragPreviewLayer.tsx deleted file mode 100644 index 2e578504b..000000000 --- a/frontend/src/Components/DragPreviewLayer.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import React from 'react'; -import styles from './DragPreviewLayer.css'; - -interface DragPreviewLayerProps { - className?: string; - children?: React.ReactNode; -} - -function DragPreviewLayer({ - className = styles.dragLayer, - children, - ...otherProps -}: DragPreviewLayerProps) { - return ( -
- {children} -
- ); -} - -export default DragPreviewLayer; diff --git a/frontend/src/Components/Error/ErrorBoundary.js b/frontend/src/Components/Error/ErrorBoundary.js new file mode 100644 index 000000000..87fb2498a --- /dev/null +++ b/frontend/src/Components/Error/ErrorBoundary.js @@ -0,0 +1,62 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import * as sentry from '@sentry/browser'; + +class ErrorBoundary extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + error: null, + info: null + }; + } + + componentDidCatch(error, info) { + this.setState({ + error, + info + }); + + sentry.captureException(error); + } + + // + // Render + + render() { + const { + children, + errorComponent: ErrorComponent, + ...otherProps + } = this.props; + + const { + error, + info + } = this.state; + + if (error) { + return ( + + ); + } + + return children; + } +} + +ErrorBoundary.propTypes = { + children: PropTypes.node.isRequired, + errorComponent: PropTypes.elementType.isRequired +}; + +export default ErrorBoundary; diff --git a/frontend/src/Components/Error/ErrorBoundary.tsx b/frontend/src/Components/Error/ErrorBoundary.tsx deleted file mode 100644 index 6b27f7a09..000000000 --- a/frontend/src/Components/Error/ErrorBoundary.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import * as sentry from '@sentry/browser'; -import React, { Component, ErrorInfo } from 'react'; - -interface ErrorBoundaryProps { - children: React.ReactNode; - errorComponent: React.ElementType; -} - -interface ErrorBoundaryState { - error: Error | null; - info: ErrorInfo | null; -} - -// Class component until componentDidCatch is supported in functional components -class ErrorBoundary extends Component { - constructor(props: ErrorBoundaryProps) { - super(props); - - this.state = { - error: null, - info: null, - }; - } - - componentDidCatch(error: Error, info: ErrorInfo) { - this.setState({ - error, - info, - }); - - sentry.captureException(error); - } - - render() { - const { children, errorComponent: ErrorComponent } = this.props; - const { error, info } = this.state; - - if (error) { - return ; - } - - return children; - } -} - -export default ErrorBoundary; diff --git a/frontend/src/Components/Error/ErrorBoundaryError.css b/frontend/src/Components/Error/ErrorBoundaryError.css index 3e7a04302..b6d1f917e 100644 --- a/frontend/src/Components/Error/ErrorBoundaryError.css +++ b/frontend/src/Components/Error/ErrorBoundaryError.css @@ -25,10 +25,6 @@ white-space: pre-wrap; } -.version { - margin-top: 20px; -} - @media only screen and (max-width: $breakpointMedium) { .image { height: 250px; diff --git a/frontend/src/Components/Error/ErrorBoundaryError.css.d.ts b/frontend/src/Components/Error/ErrorBoundaryError.css.d.ts deleted file mode 100644 index e19fd804d..000000000 --- a/frontend/src/Components/Error/ErrorBoundaryError.css.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'container': string; - 'details': string; - 'image': string; - 'imageContainer': string; - 'message': string; - 'version': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Error/ErrorBoundaryError.js b/frontend/src/Components/Error/ErrorBoundaryError.js new file mode 100644 index 000000000..e0181db96 --- /dev/null +++ b/frontend/src/Components/Error/ErrorBoundaryError.js @@ -0,0 +1,60 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import styles from './ErrorBoundaryError.css'; + +function ErrorBoundaryError(props) { + const { + className, + messageClassName, + detailsClassName, + message, + error, + info + } = props; + + return ( +
+
+ {message} +
+ +
+ +
+ +
+ { + error && +
+ {error.toString()} +
+ } + +
+ {info.componentStack} +
+
+
+ ); +} + +ErrorBoundaryError.propTypes = { + className: PropTypes.string.isRequired, + messageClassName: PropTypes.string.isRequired, + detailsClassName: PropTypes.string.isRequired, + message: PropTypes.string.isRequired, + error: PropTypes.object.isRequired, + info: PropTypes.object.isRequired +}; + +ErrorBoundaryError.defaultProps = { + className: styles.container, + messageClassName: styles.message, + detailsClassName: styles.details, + message: 'There was an error loading this content' +}; + +export default ErrorBoundaryError; diff --git a/frontend/src/Components/Error/ErrorBoundaryError.tsx b/frontend/src/Components/Error/ErrorBoundaryError.tsx deleted file mode 100644 index 870b28058..000000000 --- a/frontend/src/Components/Error/ErrorBoundaryError.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import React, { useEffect, useState } from 'react'; -import StackTrace from 'stacktrace-js'; -import translate from 'Utilities/String/translate'; -import styles from './ErrorBoundaryError.css'; - -interface ErrorBoundaryErrorProps { - className: string; - messageClassName: string; - detailsClassName: string; - message: string; - error: Error; - info: { - componentStack: string; - }; -} - -function ErrorBoundaryError(props: ErrorBoundaryErrorProps) { - const { - className = styles.container, - messageClassName = styles.message, - detailsClassName = styles.details, - message = translate('ErrorLoadingContent'), - error, - info, - } = props; - - const [detailedError, setDetailedError] = useState< - StackTrace.StackFrame[] | null - >(null); - - useEffect(() => { - if (error) { - StackTrace.fromError(error).then((de) => { - setDetailedError(de); - }); - } else { - setDetailedError(null); - } - }, [error, setDetailedError]); - - return ( -
-
{message}
- -
- -
- -
- {error ?
{error.message}
: null} - - {detailedError ? ( - detailedError.map((d, index) => { - return ( -
- {` at ${d.functionName} (${d.fileName}:${d.lineNumber}:${d.columnNumber})`} -
- ); - }) - ) : ( -
{info.componentStack}
- )} - -
Version: {window.Sonarr.version}
-
-
- ); -} - -export default ErrorBoundaryError; diff --git a/frontend/src/Components/FieldSet.css b/frontend/src/Components/FieldSet.css index 9ea0dbab1..6da64f0e0 100644 --- a/frontend/src/Components/FieldSet.css +++ b/frontend/src/Components/FieldSet.css @@ -13,7 +13,7 @@ width: 100%; border: 0; border-bottom: 1px solid #e5e5e5; - color: var(--textColor); + color: #3a3f51; font-size: 21px; line-height: inherit; diff --git a/frontend/src/Components/FieldSet.css.d.ts b/frontend/src/Components/FieldSet.css.d.ts deleted file mode 100644 index 74e99779a..000000000 --- a/frontend/src/Components/FieldSet.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'fieldSet': string; - 'legend': string; - 'small': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/FieldSet.js b/frontend/src/Components/FieldSet.js new file mode 100644 index 000000000..d5f411fbe --- /dev/null +++ b/frontend/src/Components/FieldSet.js @@ -0,0 +1,41 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import { sizes } from 'Helpers/Props'; +import styles from './FieldSet.css'; + +class FieldSet extends Component { + + // + // Render + + render() { + const { + size, + legend, + children + } = this.props; + + return ( +
+ + {legend} + + {children} +
+ ); + } + +} + +FieldSet.propTypes = { + size: PropTypes.oneOf(sizes.all).isRequired, + legend: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), + children: PropTypes.node +}; + +FieldSet.defaultProps = { + size: sizes.MEDIUM +}; + +export default FieldSet; diff --git a/frontend/src/Components/FieldSet.tsx b/frontend/src/Components/FieldSet.tsx deleted file mode 100644 index c2ff03a7f..000000000 --- a/frontend/src/Components/FieldSet.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import classNames from 'classnames'; -import React, { ComponentProps } from 'react'; -import { sizes } from 'Helpers/Props'; -import { Size } from 'Helpers/Props/sizes'; -import styles from './FieldSet.css'; - -interface FieldSetProps { - size?: Size; - legend?: ComponentProps<'legend'>['children']; - children?: React.ReactNode; -} - -function FieldSet({ size = sizes.MEDIUM, legend, children }: FieldSetProps) { - return ( -
- - {legend} - - {children} -
- ); -} - -export default FieldSet; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModal.css.d.ts b/frontend/src/Components/FileBrowser/FileBrowserModal.css.d.ts deleted file mode 100644 index 5d00cca7e..000000000 --- a/frontend/src/Components/FileBrowser/FileBrowserModal.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'modal': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModal.js b/frontend/src/Components/FileBrowser/FileBrowserModal.js new file mode 100644 index 000000000..6b58dbb8c --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModal.js @@ -0,0 +1,39 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Modal from 'Components/Modal/Modal'; +import FileBrowserModalContentConnector from './FileBrowserModalContentConnector'; +import styles from './FileBrowserModal.css'; + +class FileBrowserModal extends Component { + + // + // Render + + render() { + const { + isOpen, + onModalClose, + ...otherProps + } = this.props; + + return ( + + + + ); + } +} + +FileBrowserModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default FileBrowserModal; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModal.tsx b/frontend/src/Components/FileBrowser/FileBrowserModal.tsx deleted file mode 100644 index 0925890de..000000000 --- a/frontend/src/Components/FileBrowser/FileBrowserModal.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import React from 'react'; -import Modal from 'Components/Modal/Modal'; -import FileBrowserModalContent, { - FileBrowserModalContentProps, -} from './FileBrowserModalContent'; -import styles from './FileBrowserModal.css'; - -interface FileBrowserModalProps extends FileBrowserModalContentProps { - isOpen: boolean; - onModalClose: () => void; -} - -function FileBrowserModal(props: FileBrowserModalProps) { - const { isOpen, onModalClose, ...otherProps } = props; - - return ( - - - - ); -} - -export default FileBrowserModal; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.css b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css index db31d6f86..7ddb9e806 100644 --- a/frontend/src/Components/FileBrowser/FileBrowserModalContent.css +++ b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css @@ -13,7 +13,7 @@ } .faqLink { - color: var(--alertWarningColor); + color: $alertWarningColor; font-weight: bold; } diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.css.d.ts b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css.d.ts deleted file mode 100644 index e83c13075..000000000 --- a/frontend/src/Components/FileBrowser/FileBrowserModalContent.css.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'faqLink': string; - 'loading': string; - 'mappedDrivesWarning': string; - 'modalBody': string; - 'pathInput': string; - 'scroller': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.js b/frontend/src/Components/FileBrowser/FileBrowserModalContent.js new file mode 100644 index 000000000..49a18974b --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModalContent.js @@ -0,0 +1,257 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import ReactDOM from 'react-dom'; +import { kinds, scrollDirections } from 'Helpers/Props'; +import Alert from 'Components/Alert'; +import Button from 'Components/Link/Button'; +import Link from 'Components/Link/Link'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import ModalContent from 'Components/Modal/ModalContent'; +import ModalHeader from 'Components/Modal/ModalHeader'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; +import Scroller from 'Components/Scroller/Scroller'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import PathInput from 'Components/Form/PathInput'; +import FileBrowserRow from './FileBrowserRow'; +import styles from './FileBrowserModalContent.css'; + +const columns = [ + { + name: 'type', + label: 'Type', + isVisible: true + }, + { + name: 'name', + label: 'Name', + isVisible: true + } +]; + +class FileBrowserModalContent extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._scrollerNode = null; + + this.state = { + isFileBrowserModalOpen: false, + currentPath: props.value + }; + } + + componentDidUpdate(prevProps, prevState) { + const { + currentPath + } = this.props; + + if ( + currentPath !== this.state.currentPath && + currentPath !== prevState.currentPath + ) { + this.setState({ currentPath }); + this._scrollerNode.scrollTop = 0; + } + } + + // + // Control + + setScrollerRef = (ref) => { + if (ref) { + this._scrollerNode = ReactDOM.findDOMNode(ref); + } else { + this._scrollerNode = null; + } + } + + // + // Listeners + + onPathInputChange = ({ value }) => { + this.setState({ currentPath: value }); + } + + onRowPress = (path) => { + this.props.onFetchPaths(path); + } + + onOkPress = () => { + this.props.onChange({ + name: this.props.name, + value: this.state.currentPath + }); + + this.props.onClearPaths(); + this.props.onModalClose(); + } + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + parent, + directories, + files, + isWindowsService, + onModalClose, + ...otherProps + } = this.props; + + const emptyParent = parent === ''; + + return ( + + + File Browser + + + + { + isWindowsService && + + Mapped network drives are not available when running as a Windows Service, see the FAQ for more information. + + } + + + + + { + !!error && +
Error loading contents
+ } + + { + isPopulated && !error && + + + { + emptyParent && + + } + + { + !emptyParent && parent && + + } + + { + directories.map((directory) => { + return ( + + ); + }) + } + + { + files.map((file) => { + return ( + + ); + }) + } + +
+ } +
+
+ + + { + isFetching && + + } + + + + + +
+ ); + } +} + +FileBrowserModalContent.propTypes = { + name: PropTypes.string.isRequired, + value: PropTypes.string.isRequired, + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + parent: PropTypes.string, + currentPath: PropTypes.string.isRequired, + directories: PropTypes.arrayOf(PropTypes.object).isRequired, + files: PropTypes.arrayOf(PropTypes.object).isRequired, + isWindowsService: PropTypes.bool.isRequired, + onFetchPaths: PropTypes.func.isRequired, + onClearPaths: PropTypes.func.isRequired, + onChange: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default FileBrowserModalContent; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.tsx b/frontend/src/Components/FileBrowser/FileBrowserModalContent.tsx deleted file mode 100644 index 41338cb39..000000000 --- a/frontend/src/Components/FileBrowser/FileBrowserModalContent.tsx +++ /dev/null @@ -1,237 +0,0 @@ -import React, { useCallback, useEffect, useRef, useState } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; -import Alert from 'Components/Alert'; -import { PathInputInternal } from 'Components/Form/PathInput'; -import Button from 'Components/Link/Button'; -import LoadingIndicator from 'Components/Loading/LoadingIndicator'; -import InlineMarkdown from 'Components/Markdown/InlineMarkdown'; -import ModalBody from 'Components/Modal/ModalBody'; -import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; -import ModalHeader from 'Components/Modal/ModalHeader'; -import Scroller from 'Components/Scroller/Scroller'; -import Column from 'Components/Table/Column'; -import Table from 'Components/Table/Table'; -import TableBody from 'Components/Table/TableBody'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { kinds, scrollDirections } from 'Helpers/Props'; -import { clearPaths, fetchPaths } from 'Store/Actions/pathActions'; -import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector'; -import { InputChanged } from 'typings/inputs'; -import translate from 'Utilities/String/translate'; -import createPathsSelector from './createPathsSelector'; -import FileBrowserRow from './FileBrowserRow'; -import styles from './FileBrowserModalContent.css'; - -const columns: Column[] = [ - { - name: 'type', - label: () => translate('Type'), - isVisible: true, - }, - { - name: 'name', - label: () => translate('Name'), - isVisible: true, - }, -]; - -const handleClearPaths = () => {}; - -export interface FileBrowserModalContentProps { - name: string; - value: string; - includeFiles?: boolean; - onChange: (args: InputChanged) => unknown; - onModalClose: () => void; -} - -function FileBrowserModalContent(props: FileBrowserModalContentProps) { - const { name, value, includeFiles = true, onChange, onModalClose } = props; - - const dispatch = useDispatch(); - - const { isWindows, mode } = useSelector(createSystemStatusSelector()); - const { isFetching, isPopulated, error, parent, directories, files, paths } = - useSelector(createPathsSelector()); - - const [currentPath, setCurrentPath] = useState(value); - const scrollerRef = useRef(null); - const previousValue = usePrevious(value); - - const emptyParent = parent === ''; - const isWindowsService = isWindows && mode === 'service'; - - const handlePathInputChange = useCallback( - ({ value }: InputChanged) => { - setCurrentPath(value); - }, - [] - ); - - const handleRowPress = useCallback( - (path: string) => { - setCurrentPath(path); - - dispatch( - fetchPaths({ - path, - allowFoldersWithoutTrailingSlashes: true, - includeFiles, - }) - ); - }, - [includeFiles, dispatch, setCurrentPath] - ); - - const handleOkPress = useCallback(() => { - onChange({ - name, - value: currentPath, - }); - - dispatch(clearPaths()); - onModalClose(); - }, [name, currentPath, dispatch, onChange, onModalClose]); - - const handleFetchPaths = useCallback( - (path: string) => { - dispatch( - fetchPaths({ - path, - allowFoldersWithoutTrailingSlashes: true, - includeFiles, - }) - ); - }, - [includeFiles, dispatch] - ); - - useEffect(() => { - if (value !== previousValue && value !== currentPath) { - setCurrentPath(value); - } - }, [value, previousValue, currentPath, setCurrentPath]); - - useEffect( - () => { - dispatch( - fetchPaths({ - path: currentPath, - allowFoldersWithoutTrailingSlashes: true, - includeFiles, - }) - ); - - return () => { - dispatch(clearPaths()); - }; - }, - // This should only run once when the component mounts, - // so we don't need to include the other dependencies. - // eslint-disable-next-line react-hooks/exhaustive-deps - [dispatch] - ); - - return ( - - {translate('FileBrowser')} - - - {isWindowsService ? ( - - - - ) : null} - - - - - {error ?
{translate('ErrorLoadingContents')}
: null} - - {isPopulated && !error ? ( - - - {emptyParent ? ( - - ) : null} - - {!emptyParent && parent ? ( - - ) : null} - - {directories.map((directory) => { - return ( - - ); - })} - - {files.map((file) => { - return ( - - ); - })} - -
- ) : null} -
-
- - - {isFetching ? ( - - ) : null} - - - - - -
- ); -} - -export default FileBrowserModalContent; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContentConnector.js b/frontend/src/Components/FileBrowser/FileBrowserModalContentConnector.js new file mode 100644 index 000000000..da5ae2ab8 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModalContentConnector.js @@ -0,0 +1,119 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { fetchPaths, clearPaths } from 'Store/Actions/pathActions'; +import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector'; +import FileBrowserModalContent from './FileBrowserModalContent'; + +function createMapStateToProps() { + return createSelector( + (state) => state.paths, + createSystemStatusSelector(), + (paths, systemStatus) => { + const { + isFetching, + isPopulated, + error, + parent, + currentPath, + directories, + files + } = paths; + + const filteredPaths = _.filter([...directories, ...files], ({ path }) => { + return path.toLowerCase().startsWith(currentPath.toLowerCase()); + }); + + return { + isFetching, + isPopulated, + error, + parent, + currentPath, + directories, + files, + paths: filteredPaths, + isWindowsService: systemStatus.isWindows && systemStatus.mode === 'service' + }; + } + ); +} + +const mapDispatchToProps = { + dispatchFetchPaths: fetchPaths, + dispatchClearPaths: clearPaths +}; + +class FileBrowserModalContentConnector extends Component { + + // Lifecycle + + componentDidMount() { + const { + value, + includeFiles, + dispatchFetchPaths + } = this.props; + + dispatchFetchPaths({ + path: value, + allowFoldersWithoutTrailingSlashes: true, + includeFiles + }); + } + + // + // Listeners + + onFetchPaths = (path) => { + const { + includeFiles, + dispatchFetchPaths + } = this.props; + + dispatchFetchPaths({ + path, + allowFoldersWithoutTrailingSlashes: true, + includeFiles + }); + } + + onClearPaths = () => { + // this.props.dispatchClearPaths(); + } + + onModalClose = () => { + this.props.dispatchClearPaths(); + this.props.onModalClose(); + } + + // + // Render + + render() { + return ( + + ); + } +} + +FileBrowserModalContentConnector.propTypes = { + value: PropTypes.string, + includeFiles: PropTypes.bool.isRequired, + dispatchFetchPaths: PropTypes.func.isRequired, + dispatchClearPaths: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +FileBrowserModalContentConnector.defaultProps = { + includeFiles: false +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(FileBrowserModalContentConnector); diff --git a/frontend/src/Components/FileBrowser/FileBrowserRow.css.d.ts b/frontend/src/Components/FileBrowser/FileBrowserRow.css.d.ts deleted file mode 100644 index 127d00928..000000000 --- a/frontend/src/Components/FileBrowser/FileBrowserRow.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'type': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/FileBrowser/FileBrowserRow.js b/frontend/src/Components/FileBrowser/FileBrowserRow.js new file mode 100644 index 000000000..42ac30405 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserRow.js @@ -0,0 +1,62 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { icons } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import TableRowButton from 'Components/Table/TableRowButton'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import styles from './FileBrowserRow.css'; + +function getIconName(type) { + switch (type) { + case 'computer': + return icons.COMPUTER; + case 'drive': + return icons.DRIVE; + case 'file': + return icons.FILE; + case 'parent': + return icons.PARENT; + default: + return icons.FOLDER; + } +} + +class FileBrowserRow extends Component { + + // + // Listeners + + onPress = () => { + this.props.onPress(this.props.path); + } + + // + // Render + + render() { + const { + type, + name + } = this.props; + + return ( + + + + + + {name} + + ); + } + +} + +FileBrowserRow.propTypes = { + type: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + path: PropTypes.string.isRequired, + onPress: PropTypes.func.isRequired +}; + +export default FileBrowserRow; diff --git a/frontend/src/Components/FileBrowser/FileBrowserRow.tsx b/frontend/src/Components/FileBrowser/FileBrowserRow.tsx deleted file mode 100644 index fe47f1664..000000000 --- a/frontend/src/Components/FileBrowser/FileBrowserRow.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import React, { useCallback } from 'react'; -import { PathType } from 'App/State/PathsAppState'; -import Icon from 'Components/Icon'; -import TableRowCell from 'Components/Table/Cells/TableRowCell'; -import TableRowButton from 'Components/Table/TableRowButton'; -import { icons } from 'Helpers/Props'; -import styles from './FileBrowserRow.css'; - -function getIconName(type: PathType) { - switch (type) { - case 'computer': - return icons.COMPUTER; - case 'drive': - return icons.DRIVE; - case 'file': - return icons.FILE; - case 'parent': - return icons.PARENT; - default: - return icons.FOLDER; - } -} - -interface FileBrowserRowProps { - type: PathType; - name: string; - path: string; - onPress: (path: string) => void; -} - -function FileBrowserRow(props: FileBrowserRowProps) { - const { type, name, path, onPress } = props; - - const handlePress = useCallback(() => { - onPress(path); - }, [path, onPress]); - - return ( - - - - - - {name} - - ); -} - -export default FileBrowserRow; diff --git a/frontend/src/Components/FileBrowser/createPathsSelector.ts b/frontend/src/Components/FileBrowser/createPathsSelector.ts deleted file mode 100644 index 5da830bd5..000000000 --- a/frontend/src/Components/FileBrowser/createPathsSelector.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; - -function createPathsSelector() { - return createSelector( - (state: AppState) => state.paths, - (paths) => { - const { - isFetching, - isPopulated, - error, - parent, - currentPath, - directories, - files, - } = paths; - - const filteredPaths = [...directories, ...files].filter(({ path }) => { - return path.toLowerCase().startsWith(currentPath.toLowerCase()); - }); - - return { - isFetching, - isPopulated, - error, - parent, - currentPath, - directories, - files, - paths: filteredPaths, - }; - } - ); -} - -export default createPathsSelector; diff --git a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css.d.ts b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css.d.ts deleted file mode 100644 index d391a1f30..000000000 --- a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'container': string; - 'numberInput': string; - 'selectInput': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js index 0193cf44f..73fa30149 100644 --- a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js +++ b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js @@ -1,10 +1,10 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import isString from 'Utilities/String/isString'; +import { IN_LAST, NOT_IN_LAST, IN_NEXT, NOT_IN_NEXT } from 'Helpers/Props/filterTypes'; import NumberInput from 'Components/Form/NumberInput'; import SelectInput from 'Components/Form/SelectInput'; import TextInput from 'Components/Form/TextInput'; -import { IN_LAST, IN_NEXT, NOT_IN_LAST, NOT_IN_NEXT } from 'Helpers/Props/filterTypes'; -import isString from 'Utilities/String/isString'; import { NAME } from './FilterBuilderRowValue'; import styles from './DateFilterBuilderRowValue.css'; @@ -102,7 +102,7 @@ class DateFilterBuilderRowValue extends Component { name: NAME, value: newValue }); - }; + } onTimeChange = ({ value }) => { const { @@ -117,7 +117,7 @@ class DateFilterBuilderRowValue extends Component { value: filterValue.value } }); - }; + } // // Render @@ -160,7 +160,6 @@ class DateFilterBuilderRowValue extends Component { diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css.d.ts b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css.d.ts deleted file mode 100644 index 033d2edca..000000000 --- a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'label': string; - 'labelContainer': string; - 'labelInputContainer': string; - 'rows': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js index 0c4a31657..165457cde 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js +++ b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js @@ -1,15 +1,13 @@ -import { maxBy } from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import { inputTypes } from 'Helpers/Props'; import FormInputGroup from 'Components/Form/FormInputGroup'; import Button from 'Components/Link/Button'; import SpinnerErrorButton from 'Components/Link/SpinnerErrorButton'; -import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; -import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; -import { inputTypes } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; +import ModalBody from 'Components/Modal/ModalBody'; +import ModalFooter from 'Components/Modal/ModalFooter'; import FilterBuilderRow from './FilterBuilderRow'; import styles from './FilterBuilderModalContent.css'; @@ -51,7 +49,7 @@ class FilterBuilderModalContent extends Component { if (id) { dispatchSetFilter({ selectedFilterKey: id }); } else { - const last = maxBy(customFilters, 'id'); + const last = customFilters[customFilters.length -1]; dispatchSetFilter({ selectedFilterKey: last.id }); } @@ -64,7 +62,7 @@ class FilterBuilderModalContent extends Component { onLabelChange = ({ value }) => { this.setState({ label: value }); - }; + } onFilterChange = (index, filter) => { const filters = [...this.state.filters]; @@ -73,7 +71,7 @@ class FilterBuilderModalContent extends Component { this.setState({ filters }); - }; + } onAddFilterPress = () => { const filters = [...this.state.filters]; @@ -82,7 +80,7 @@ class FilterBuilderModalContent extends Component { this.setState({ filters }); - }; + } onRemoveFilterPress = (index) => { const filters = [...this.state.filters]; @@ -91,7 +89,7 @@ class FilterBuilderModalContent extends Component { this.setState({ filters }); - }; + } onSaveFilterPress = () => { const { @@ -109,7 +107,7 @@ class FilterBuilderModalContent extends Component { this.setState({ labelErrors: [ { - message: translate('LabelIsRequired') + message: 'Label is required' } ] }); @@ -123,7 +121,7 @@ class FilterBuilderModalContent extends Component { label, filters }); - }; + } // // Render @@ -147,13 +145,13 @@ class FilterBuilderModalContent extends Component { return ( - {translate('CustomFilter')} + Custom Filter
- {translate('Label')} + Label
@@ -167,9 +165,7 @@ class FilterBuilderModalContent extends Component {
-
- {translate('Filters')} -
+
Filters
{ @@ -196,7 +192,7 @@ class FilterBuilderModalContent extends Component { - {translate('Save')} + Save diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js b/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js index 17633172b..c94db9925 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js +++ b/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js @@ -1,6 +1,6 @@ import { connect } from 'react-redux'; import { createSelector } from 'reselect'; -import { deleteCustomFilter, saveCustomFilter } from 'Store/Actions/customFilterActions'; +import { saveCustomFilter, deleteCustomFilter } from 'Store/Actions/customFilterActions'; import FilterBuilderModalContent from './FilterBuilderModalContent'; function createMapStateToProps() { diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRow.css b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css index bcfc3b04e..c5471b253 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRow.css +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css @@ -3,7 +3,7 @@ margin-bottom: 5px; &:hover { - background-color: var(--tableRowHoverBackgroundColor); + background-color: $tableRowHoverBackgroundColor; } } diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRow.css.d.ts b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css.d.ts deleted file mode 100644 index aba698af4..000000000 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRow.css.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'actionsContainer': string; - 'filterRow': string; - 'inputContainer': string; - 'valueInputContainer': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRow.js b/frontend/src/Components/Filter/Builder/FilterBuilderRow.js index 0b00c0f03..3b2ba0a53 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRow.js +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRow.js @@ -1,21 +1,16 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import { filterBuilderTypes, filterBuilderValueTypes, icons } from 'Helpers/Props'; import SelectInput from 'Components/Form/SelectInput'; import IconButton from 'Components/Link/IconButton'; -import { filterBuilderTypes, filterBuilderValueTypes, icons } from 'Helpers/Props'; -import sortByProp from 'Utilities/Array/sortByProp'; import BoolFilterBuilderRowValue from './BoolFilterBuilderRowValue'; import DateFilterBuilderRowValue from './DateFilterBuilderRowValue'; import FilterBuilderRowValueConnector from './FilterBuilderRowValueConnector'; -import HistoryEventTypeFilterBuilderRowValue from './HistoryEventTypeFilterBuilderRowValue'; import IndexerFilterBuilderRowValueConnector from './IndexerFilterBuilderRowValueConnector'; -import LanguageFilterBuilderRowValue from './LanguageFilterBuilderRowValue'; +import LanguageProfileFilterBuilderRowValueConnector from './LanguageProfileFilterBuilderRowValueConnector'; import ProtocolFilterBuilderRowValue from './ProtocolFilterBuilderRowValue'; import QualityFilterBuilderRowValueConnector from './QualityFilterBuilderRowValueConnector'; -import QualityProfileFilterBuilderRowValue from './QualityProfileFilterBuilderRowValue'; -import QueueStatusFilterBuilderRowValue from './QueueStatusFilterBuilderRowValue'; -import SeasonsMonitoredStatusFilterBuilderRowValue from './SeasonsMonitoredStatusFilterBuilderRowValue'; -import SeriesFilterBuilderRowValue from './SeriesFilterBuilderRowValue'; +import QualityProfileFilterBuilderRowValueConnector from './QualityProfileFilterBuilderRowValueConnector'; import SeriesStatusFilterBuilderRowValue from './SeriesStatusFilterBuilderRowValue'; import SeriesTypeFilterBuilderRowValue from './SeriesTypeFilterBuilderRowValue'; import TagFilterBuilderRowValueConnector from './TagFilterBuilderRowValueConnector'; @@ -63,14 +58,11 @@ function getRowValueConnector(selectedFilterBuilderProp) { case filterBuilderValueTypes.DATE: return DateFilterBuilderRowValue; - case filterBuilderValueTypes.HISTORY_EVENT_TYPE: - return HistoryEventTypeFilterBuilderRowValue; - case filterBuilderValueTypes.INDEXER: return IndexerFilterBuilderRowValueConnector; - case filterBuilderValueTypes.LANGUAGE: - return LanguageFilterBuilderRowValue; + case filterBuilderValueTypes.LANGUAGE_PROFILE: + return LanguageProfileFilterBuilderRowValueConnector; case filterBuilderValueTypes.PROTOCOL: return ProtocolFilterBuilderRowValue; @@ -79,16 +71,7 @@ function getRowValueConnector(selectedFilterBuilderProp) { return QualityFilterBuilderRowValueConnector; case filterBuilderValueTypes.QUALITY_PROFILE: - return QualityProfileFilterBuilderRowValue; - - case filterBuilderValueTypes.QUEUE_STATUS: - return QueueStatusFilterBuilderRowValue; - - case filterBuilderValueTypes.SEASONS_MONITORED_STATUS: - return SeasonsMonitoredStatusFilterBuilderRowValue; - - case filterBuilderValueTypes.SERIES: - return SeriesFilterBuilderRowValue; + return QualityProfileFilterBuilderRowValueConnector; case filterBuilderValueTypes.SERIES_STATUS: return SeriesStatusFilterBuilderRowValue; @@ -171,7 +154,7 @@ class FilterBuilderRow extends Component { this.selectedFilterBuilderProp = selectedFilterBuilderProp; onFilterChange(index, filter); - }; + } onFilterChange = ({ name, value }) => { const { @@ -191,7 +174,7 @@ class FilterBuilderRow extends Component { filter[name] = value; onFilterChange(index, filter); - }; + } onAddPress = () => { const { @@ -200,7 +183,7 @@ class FilterBuilderRow extends Component { } = this.props; onAddPress(index); - }; + } onRemovePress = () => { const { @@ -209,7 +192,7 @@ class FilterBuilderRow extends Component { } = this.props; onRemovePress(index); - }; + } // // Render @@ -227,13 +210,11 @@ class FilterBuilderRow extends Component { const selectedFilterBuilderProp = this.selectedFilterBuilderProp; const keyOptions = filterBuilderProps.map((availablePropFilter) => { - const { name, label } = availablePropFilter; - return { - key: name, - value: typeof label === 'function' ? label() : label + key: availablePropFilter.name, + value: availablePropFilter.label }; - }).sort(sortByProp('value')); + }); const ValueComponent = getRowValueConnector(selectedFilterBuilderProp); diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js index 217626c90..d53c07607 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js @@ -1,10 +1,10 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import TagInput from 'Components/Form/Tag/TagInput'; -import { filterBuilderTypes, filterBuilderValueTypes, kinds } from 'Helpers/Props'; -import tagShape from 'Helpers/Props/Shapes/tagShape'; import convertToBytes from 'Utilities/Number/convertToBytes'; import formatBytes from 'Utilities/Number/formatBytes'; +import { kinds, filterBuilderTypes, filterBuilderValueTypes } from 'Helpers/Props'; +import tagShape from 'Helpers/Props/Shapes/tagShape'; +import TagInput from 'Components/Form/TagInput'; import FilterBuilderRowValueTag from './FilterBuilderRowValueTag'; export const NAME = 'value'; @@ -84,7 +84,7 @@ class FilterBuilderRowValue extends Component { name: NAME, value: [...filterValue, value] }); - }; + } onTagDelete = ({ index }) => { const { @@ -98,7 +98,7 @@ class FilterBuilderRowValue extends Component { name: NAME, value }); - }; + } // // Render diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js index d1419327a..821d098e0 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js @@ -1,9 +1,9 @@ import _ from 'lodash'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; +import sortByName from 'Utilities/Array/sortByName'; import { filterBuilderTypes } from 'Helpers/Props'; import * as filterTypes from 'Helpers/Props/filterTypes'; -import sortByProp from 'Utilities/Array/sortByProp'; import FilterBuilderRowValue from './FilterBuilderRowValue'; function createTagListSelector() { @@ -38,7 +38,7 @@ function createTagListSelector() { } return acc; - }, []).sort(sortByProp('name')); + }, []).sort(sortByName); } return _.uniqBy(items, 'id'); diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueProps.ts b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueProps.ts deleted file mode 100644 index 5bf9e5785..000000000 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueProps.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { FilterBuilderProp } from 'App/State/AppState'; - -interface FilterBuilderRowOnChangeProps { - name: string; - value: unknown[]; -} - -interface FilterBuilderRowValueProps { - filterType?: string; - filterValue: string | number | object | string[] | number[] | object[]; - selectedFilterBuilderProp: FilterBuilderProp; - sectionItem: unknown[]; - onChange: (payload: FilterBuilderRowOnChangeProps) => void; -} - -export default FilterBuilderRowValueProps; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css index 807f383dd..86ef9e73a 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css @@ -17,6 +17,6 @@ .or { margin: 0 3px; - color: var(--themeDarkColor); + color: $themeDarkColor; line-height: 31px; } diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css.d.ts b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css.d.ts deleted file mode 100644 index 80bcf1464..000000000 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'isLastTag': string; - 'label': string; - 'or': string; - 'tag': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js index 063a97346..9166666de 100644 --- a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js @@ -1,8 +1,7 @@ import PropTypes from 'prop-types'; import React from 'react'; -import TagInputTag from 'Components/Form/Tag/TagInputTag'; import { kinds } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; +import TagInputTag from 'Components/Form/TagInputTag'; import styles from './FilterBuilderRowValueTag.css'; function FilterBuilderRowValueTag(props) { @@ -19,7 +18,7 @@ function FilterBuilderRowValueTag(props) { props.isLastTag ? null :
- {translate('Or')} + or
}
diff --git a/frontend/src/Components/Filter/Builder/HistoryEventTypeFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/HistoryEventTypeFilterBuilderRowValue.tsx deleted file mode 100644 index 4ecddf646..000000000 --- a/frontend/src/Components/Filter/Builder/HistoryEventTypeFilterBuilderRowValue.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import React from 'react'; -import translate from 'Utilities/String/translate'; -import FilterBuilderRowValue from './FilterBuilderRowValue'; -import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; - -const EVENT_TYPE_OPTIONS = [ - { - id: 1, - get name() { - return translate('Grabbed'); - }, - }, - { - id: 3, - get name() { - return translate('Imported'); - }, - }, - { - id: 4, - get name() { - return translate('Failed'); - }, - }, - { - id: 5, - get name() { - return translate('Deleted'); - }, - }, - { - id: 6, - get name() { - return translate('Renamed'); - }, - }, - { - id: 7, - get name() { - return translate('Ignored'); - }, - }, -]; - -function HistoryEventTypeFilterBuilderRowValue( - props: FilterBuilderRowValueProps -) { - return ; -} - -export default HistoryEventTypeFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js index e834b79a3..0132ae641 100644 --- a/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js +++ b/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js @@ -47,7 +47,7 @@ class IndexerFilterBuilderRowValueConnector extends Component { if (!this.props.isPopulated) { this.props.dispatchFetchIndexers(); } - }; + } // // Render diff --git a/frontend/src/Components/Filter/Builder/LanguageFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/LanguageFilterBuilderRowValue.tsx deleted file mode 100644 index e828fd848..000000000 --- a/frontend/src/Components/Filter/Builder/LanguageFilterBuilderRowValue.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import React from 'react'; -import { useSelector } from 'react-redux'; -import createLanguagesSelector from 'Store/Selectors/createLanguagesSelector'; -import FilterBuilderRowValue from './FilterBuilderRowValue'; -import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; - -function LanguageFilterBuilderRowValue(props: FilterBuilderRowValueProps) { - const { items } = useSelector(createLanguagesSelector()); - - return ; -} - -export default LanguageFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/LanguageProfileFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/LanguageProfileFilterBuilderRowValueConnector.js new file mode 100644 index 000000000..31b1e952a --- /dev/null +++ b/frontend/src/Components/Filter/Builder/LanguageProfileFilterBuilderRowValueConnector.js @@ -0,0 +1,28 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createMapStateToProps() { + return createSelector( + (state) => state.settings.languageProfiles, + (languageProfiles) => { + const tagList = languageProfiles.items.map((languageProfile) => { + const { + id, + name + } = languageProfile; + + return { + id, + name + }; + }); + + return { + tagList + }; + } + ); +} + +export default connect(createMapStateToProps)(FilterBuilderRowValue); diff --git a/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js index fd6e466d4..d0443bf19 100644 --- a/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js +++ b/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js @@ -2,9 +2,9 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; +import getQualities from 'Utilities/Quality/getQualities'; import tagShape from 'Helpers/Props/Shapes/tagShape'; import { fetchQualityProfileSchema } from 'Store/Actions/settingsActions'; -import getQualities from 'Utilities/Quality/getQualities'; import FilterBuilderRowValue from './FilterBuilderRowValue'; function createMapStateToProps() { @@ -43,7 +43,7 @@ class QualityFilterBuilderRowValueConnector extends Component { if (!this.props.isPopulated) { this.props.dispatchFetchQualityProfileSchema(); } - }; + } // // Render diff --git a/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValue.tsx deleted file mode 100644 index 50036cb90..000000000 --- a/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValue.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import React from 'react'; -import { useSelector } from 'react-redux'; -import { createSelector } from 'reselect'; -import AppState from 'App/State/AppState'; -import FilterBuilderRowValueProps from 'Components/Filter/Builder/FilterBuilderRowValueProps'; -import sortByProp from 'Utilities/Array/sortByProp'; -import FilterBuilderRowValue from './FilterBuilderRowValue'; - -function createQualityProfilesSelector() { - return createSelector( - (state: AppState) => state.settings.qualityProfiles.items, - (qualityProfiles) => { - return qualityProfiles; - } - ); -} - -function QualityProfileFilterBuilderRowValue( - props: FilterBuilderRowValueProps -) { - const qualityProfiles = useSelector(createQualityProfilesSelector()); - - const tagList = qualityProfiles - .map(({ id, name }) => ({ id, name })) - .sort(sortByProp('name')); - - return ; -} - -export default QualityProfileFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValueConnector.js new file mode 100644 index 000000000..4a8b82283 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValueConnector.js @@ -0,0 +1,28 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createMapStateToProps() { + return createSelector( + (state) => state.settings.qualityProfiles, + (qualityProfiles) => { + const tagList = qualityProfiles.items.map((qualityProfile) => { + const { + id, + name + } = qualityProfile; + + return { + id, + name + }; + }); + + return { + tagList + }; + } + ); +} + +export default connect(createMapStateToProps)(FilterBuilderRowValue); diff --git a/frontend/src/Components/Filter/Builder/QueueStatusFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/QueueStatusFilterBuilderRowValue.tsx deleted file mode 100644 index 1127493a5..000000000 --- a/frontend/src/Components/Filter/Builder/QueueStatusFilterBuilderRowValue.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import React from 'react'; -import translate from 'Utilities/String/translate'; -import FilterBuilderRowValue from './FilterBuilderRowValue'; -import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; - -const statusTagList = [ - { - id: 'queued', - get name() { - return translate('Queued'); - }, - }, - { - id: 'paused', - get name() { - return translate('Paused'); - }, - }, - { - id: 'downloading', - get name() { - return translate('Downloading'); - }, - }, - { - id: 'completed', - get name() { - return translate('Completed'); - }, - }, - { - id: 'failed', - get name() { - return translate('Failed'); - }, - }, - { - id: 'warning', - get name() { - return translate('Warning'); - }, - }, - { - id: 'delay', - get name() { - return translate('Delay'); - }, - }, - { - id: 'downloadClientUnavailable', - get name() { - return translate('DownloadClientUnavailable'); - }, - }, - { - id: 'fallback', - get name() { - return translate('Fallback'); - }, - }, -]; - -function QueueStatusFilterBuilderRowValue(props: FilterBuilderRowValueProps) { - return ; -} - -export default QueueStatusFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeasonsMonitoredStatusFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/SeasonsMonitoredStatusFilterBuilderRowValue.js deleted file mode 100644 index b84260e3c..000000000 --- a/frontend/src/Components/Filter/Builder/SeasonsMonitoredStatusFilterBuilderRowValue.js +++ /dev/null @@ -1,35 +0,0 @@ -import React from 'react'; -import translate from 'Utilities/String/translate'; -import FilterBuilderRowValue from './FilterBuilderRowValue'; - -const seasonsMonitoredStatusList = [ - { - id: 'all', - get name() { - return translate('SeasonsMonitoredAll'); - } - }, - { - id: 'partial', - get name() { - return translate('SeasonsMonitoredPartial'); - } - }, - { - id: 'none', - get name() { - return translate('SeasonsMonitoredNone'); - } - } -]; - -function SeasonsMonitoredStatusFilterBuilderRowValue(props) { - return ( - - ); -} - -export default SeasonsMonitoredStatusFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeriesFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/SeriesFilterBuilderRowValue.tsx deleted file mode 100644 index 88b34509a..000000000 --- a/frontend/src/Components/Filter/Builder/SeriesFilterBuilderRowValue.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import React from 'react'; -import { useSelector } from 'react-redux'; -import Series from 'Series/Series'; -import createAllSeriesSelector from 'Store/Selectors/createAllSeriesSelector'; -import sortByProp from 'Utilities/Array/sortByProp'; -import FilterBuilderRowValue from './FilterBuilderRowValue'; -import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; - -function SeriesFilterBuilderRowValue(props: FilterBuilderRowValueProps) { - const allSeries: Series[] = useSelector(createAllSeriesSelector()); - - const tagList = allSeries - .map((series) => ({ id: series.id, name: series.title })) - .sort(sortByProp('name')); - - return ; -} - -export default SeriesFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js index e017f72e7..b52cb4899 100644 --- a/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js +++ b/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js @@ -1,38 +1,16 @@ import React from 'react'; -import translate from 'Utilities/String/translate'; import FilterBuilderRowValue from './FilterBuilderRowValue'; -const statusTagList = [ - { - id: 'continuing', - get name() { - return translate('Continuing'); - } - }, - { - id: 'upcoming', - get name() { - return translate('Upcoming'); - } - }, - { - id: 'ended', - get name() { - return translate('Ended'); - } - }, - { - id: 'deleted', - get name() { - return translate('Deleted'); - } - } +const seriesStatusList = [ + { id: 'continuing', name: 'Continuing' }, + { id: 'upcoming', name: 'Upcoming' }, + { id: 'ended', name: 'Ended' } ]; function SeriesStatusFilterBuilderRowValue(props) { return ( ); diff --git a/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js index 2e62e558d..263c9e9da 100644 --- a/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js +++ b/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js @@ -1,26 +1,10 @@ import React from 'react'; -import translate from 'Utilities/String/translate'; import FilterBuilderRowValue from './FilterBuilderRowValue'; const seriesTypeList = [ - { - id: 'anime', - get name() { - return translate('Anime'); - } - }, - { - id: 'daily', - get name() { - return translate('Daily'); - } - }, - { - id: 'standard', - get name() { - return translate('Standard'); - } - } + { id: 'anime', name: 'Anime' }, + { id: 'daily', name: 'Daily' }, + { id: 'standard', name: 'Standard' } ]; function SeriesTypeFilterBuilderRowValue(props) { diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFilter.css b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css index e2b8c72bf..7acb69dc7 100644 --- a/frontend/src/Components/Filter/CustomFilters/CustomFilter.css +++ b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css @@ -4,7 +4,7 @@ padding: 5px; &:hover { - background-color: var(--tableRowHoverBackgroundColor); + background-color: $tableRowHoverBackgroundColor; } } diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFilter.css.d.ts b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css.d.ts deleted file mode 100644 index af5bfa967..000000000 --- a/frontend/src/Components/Filter/CustomFilters/CustomFilter.css.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'actions': string; - 'customFilter': string; - 'label': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFilter.js b/frontend/src/Components/Filter/CustomFilters/CustomFilter.js index 9f378d5a2..c9c326d78 100644 --- a/frontend/src/Components/Filter/CustomFilters/CustomFilter.js +++ b/frontend/src/Components/Filter/CustomFilters/CustomFilter.js @@ -1,9 +1,8 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import { icons } from 'Helpers/Props'; import IconButton from 'Components/Link/IconButton'; import SpinnerIconButton from 'Components/Link/SpinnerIconButton'; -import { icons } from 'Helpers/Props'; -import translate from 'Utilities/String/translate'; import styles from './CustomFilter.css'; class CustomFilter extends Component { @@ -37,8 +36,8 @@ class CustomFilter extends Component { dispatchSetFilter } = this.props; - // Assume that delete and then unmounting means the deletion was successful. - // Moving this check to an ancestor would be more accurate, but would have + // Assume that delete and then unmounting means the delete was successful. + // Moving this check to a ancestor would be more accurate, but would have // more boilerplate. if (this.state.isDeleting && id === selectedFilterKey) { dispatchSetFilter({ selectedFilterKey: 'all' }); @@ -55,7 +54,7 @@ class CustomFilter extends Component { } = this.props; onEditPress(id); - }; + } onRemovePress = () => { const { @@ -67,7 +66,7 @@ class CustomFilter extends Component { dispatchDeleteCustomFilter({ id }); }); - }; + } // // Render @@ -90,7 +89,7 @@ class CustomFilter extends Component { /> - {translate('CustomFilters')} + Custom Filters { - customFilters - .sort((a, b) => sortByProp(a, b, 'label')) - .map((customFilter) => { - return ( - - ); - }) + customFilters.map((customFilter) => { + return ( + + ); + }) }
@@ -62,7 +58,7 @@ function CustomFiltersModalContent(props) {
diff --git a/frontend/src/Components/Filter/FilterModal.js b/frontend/src/Components/Filter/FilterModal.js index d52362d7b..729f380e7 100644 --- a/frontend/src/Components/Filter/FilterModal.js +++ b/frontend/src/Components/Filter/FilterModal.js @@ -25,14 +25,14 @@ class FilterModal extends Component { this.setState({ filterBuilder: true }); - }; + } onEditCustomFilter = (id) => { this.setState({ filterBuilder: true, id }); - }; + } onCancelPress = () => { if (this.state.filterBuilder) { @@ -43,7 +43,7 @@ class FilterModal extends Component { } else { this.onModalClose(); } - }; + } onModalClose = () => { this.setState({ @@ -52,7 +52,7 @@ class FilterModal extends Component { }, () => { this.props.onModalClose(); }); - }; + } // // Render diff --git a/frontend/src/Components/Form/AutoCompleteInput.js b/frontend/src/Components/Form/AutoCompleteInput.js new file mode 100644 index 000000000..e19700d08 --- /dev/null +++ b/frontend/src/Components/Form/AutoCompleteInput.js @@ -0,0 +1,98 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import jdu from 'jdu'; +import AutoSuggestInput from './AutoSuggestInput'; + +class AutoCompleteInput extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + suggestions: [] + }; + } + + // + // Control + + getSuggestionValue(item) { + return item; + } + + renderSuggestion(item) { + return item; + } + + // + // Listeners + + onInputChange = (event, { newValue }) => { + this.props.onChange({ + name: this.props.name, + value: newValue + }); + } + + onInputBlur = () => { + this.setState({ suggestions: [] }); + } + + onSuggestionsFetchRequested = ({ value }) => { + const { values } = this.props; + const lowerCaseValue = jdu.replace(value).toLowerCase(); + + const filteredValues = values.filter((v) => { + return jdu.replace(v).toLowerCase().contains(lowerCaseValue); + }); + + this.setState({ suggestions: filteredValues }); + } + + onSuggestionsClearRequested = () => { + this.setState({ suggestions: [] }); + } + + // + // Render + + render() { + const { + name, + value, + ...otherProps + } = this.props; + + const { suggestions } = this.state; + + return ( + + ); + } +} + +AutoCompleteInput.propTypes = { + name: PropTypes.string.isRequired, + value: PropTypes.string, + values: PropTypes.arrayOf(PropTypes.string).isRequired, + onChange: PropTypes.func.isRequired +}; + +AutoCompleteInput.defaultProps = { + value: '' +}; + +export default AutoCompleteInput; diff --git a/frontend/src/Components/Form/AutoCompleteInput.tsx b/frontend/src/Components/Form/AutoCompleteInput.tsx deleted file mode 100644 index 7ba114125..000000000 --- a/frontend/src/Components/Form/AutoCompleteInput.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import jdu from 'jdu'; -import React, { SyntheticEvent, useCallback, useState } from 'react'; -import { - ChangeEvent, - SuggestionsFetchRequestedParams, -} from 'react-autosuggest'; -import { InputChanged } from 'typings/inputs'; -import AutoSuggestInput from './AutoSuggestInput'; - -interface AutoCompleteInputProps { - name: string; - value?: string; - values: string[]; - onChange: (change: InputChanged) => unknown; -} - -function AutoCompleteInput({ - name, - value = '', - values, - onChange, - ...otherProps -}: AutoCompleteInputProps) { - const [suggestions, setSuggestions] = useState([]); - - const getSuggestionValue = useCallback((item: string) => { - return item; - }, []); - - const renderSuggestion = useCallback((item: string) => { - return item; - }, []); - - const handleInputChange = useCallback( - (_event: SyntheticEvent, { newValue }: ChangeEvent) => { - onChange({ - name, - value: newValue, - }); - }, - [name, onChange] - ); - - const handleInputBlur = useCallback(() => { - setSuggestions([]); - }, [setSuggestions]); - - const handleSuggestionsFetchRequested = useCallback( - ({ value: newValue }: SuggestionsFetchRequestedParams) => { - const lowerCaseValue = jdu.replace(newValue).toLowerCase(); - - const filteredValues = values.filter((v) => { - return jdu.replace(v).toLowerCase().includes(lowerCaseValue); - }); - - setSuggestions(filteredValues); - }, - [values, setSuggestions] - ); - - const handleSuggestionsClearRequested = useCallback(() => { - setSuggestions([]); - }, [setSuggestions]); - - return ( - - ); -} - -export default AutoCompleteInput; diff --git a/frontend/src/Components/Form/AutoSuggestInput.css b/frontend/src/Components/Form/AutoSuggestInput.css index 7dc416960..0f3279cb9 100644 --- a/frontend/src/Components/Form/AutoSuggestInput.css +++ b/frontend/src/Components/Form/AutoSuggestInput.css @@ -27,10 +27,10 @@ overflow-y: auto; max-height: 200px; width: 100%; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-radius: 4px; - background-color: var(--inputBackgroundColor); - box-shadow: inset 0 1px 1px var(--inputBoxShadowColor); + background-color: $white; + box-shadow: inset 0 1px 1px $inputBoxShadowColor; } } @@ -46,5 +46,5 @@ } .suggestionHighlighted { - background-color: var(--menuItemHoverBackgroundColor); + background-color: $menuItemHoverBackgroundColor; } diff --git a/frontend/src/Components/Form/AutoSuggestInput.css.d.ts b/frontend/src/Components/Form/AutoSuggestInput.css.d.ts deleted file mode 100644 index 2b8f51924..000000000 --- a/frontend/src/Components/Form/AutoSuggestInput.css.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'hasError': string; - 'hasWarning': string; - 'input': string; - 'inputContainer': string; - 'suggestion': string; - 'suggestionHighlighted': string; - 'suggestionsContainer': string; - 'suggestionsContainerOpen': string; - 'suggestionsList': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Form/AutoSuggestInput.js b/frontend/src/Components/Form/AutoSuggestInput.js new file mode 100644 index 000000000..dd5833ee0 --- /dev/null +++ b/frontend/src/Components/Form/AutoSuggestInput.js @@ -0,0 +1,257 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Autosuggest from 'react-autosuggest'; +import { Manager, Popper, Reference } from 'react-popper'; +import classNames from 'classnames'; +import Portal from 'Components/Portal'; +import styles from './AutoSuggestInput.css'; + +class AutoSuggestInput extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._scheduleUpdate = null; + } + + componentDidUpdate(prevProps) { + if ( + this._scheduleUpdate && + prevProps.suggestions !== this.props.suggestions + ) { + this._scheduleUpdate(); + } + } + + // + // Control + + renderInputComponent = (inputProps) => { + const { renderInputComponent } = this.props; + + return ( + + {({ ref }) => { + if (renderInputComponent) { + return renderInputComponent(inputProps, ref); + } + + return ( +
+ +
+ ); + }} +
+ ); + } + + renderSuggestionsContainer = ({ containerProps, children }) => { + return ( + + + {({ ref: popperRef, style, scheduleUpdate }) => { + this._scheduleUpdate = scheduleUpdate; + + return ( +
+
+ {children} +
+
+ ); + }} +
+
+ ); + } + + // + // Listeners + + onComputeMaxHeight = (data) => { + const { + top, + bottom, + width + } = data.offsets.reference; + + const windowHeight = window.innerHeight; + + if ((/^botton/).test(data.placement)) { + data.styles.maxHeight = windowHeight - bottom; + } else { + data.styles.maxHeight = top; + } + + data.styles.width = width; + + return data; + } + + onInputChange = (event, { newValue }) => { + this.props.onChange({ + name: this.props.name, + value: newValue + }); + } + + onInputKeyDown = (event) => { + const { + name, + value, + suggestions, + onChange + } = this.props; + + if ( + event.key === 'Tab' && + suggestions.length && + suggestions[0] !== this.props.value + ) { + event.preventDefault(); + + if (value) { + onChange({ + name, + value: suggestions[0] + }); + } + } + } + + // + // Render + + render() { + const { + forwardedRef, + className, + inputContainerClassName, + name, + value, + placeholder, + suggestions, + hasError, + hasWarning, + getSuggestionValue, + renderSuggestion, + onInputChange, + onInputKeyDown, + onInputFocus, + onInputBlur, + onSuggestionsFetchRequested, + onSuggestionsClearRequested, + onSuggestionSelected, + ...otherProps + } = this.props; + + const inputProps = { + className: classNames( + className, + hasError && styles.hasError, + hasWarning && styles.hasWarning + ), + name, + value, + placeholder, + autoComplete: 'off', + spellCheck: false, + onChange: onInputChange || this.onInputChange, + onKeyDown: onInputKeyDown || this.onInputKeyDown, + onFocus: onInputFocus, + onBlur: onInputBlur + }; + + const theme = { + container: inputContainerClassName, + containerOpen: styles.suggestionsContainerOpen, + suggestionsContainer: styles.suggestionsContainer, + suggestionsList: styles.suggestionsList, + suggestion: styles.suggestion, + suggestionHighlighted: styles.suggestionHighlighted + }; + + return ( + + + + ); + } +} + +AutoSuggestInput.propTypes = { + forwardedRef: PropTypes.func, + className: PropTypes.string.isRequired, + inputContainerClassName: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), + placeholder: PropTypes.string, + suggestions: PropTypes.array.isRequired, + hasError: PropTypes.bool, + hasWarning: PropTypes.bool, + enforceMaxHeight: PropTypes.bool.isRequired, + minHeight: PropTypes.number.isRequired, + maxHeight: PropTypes.number.isRequired, + getSuggestionValue: PropTypes.func.isRequired, + renderInputComponent: PropTypes.elementType, + renderSuggestion: PropTypes.func.isRequired, + onInputChange: PropTypes.func, + onInputKeyDown: PropTypes.func, + onInputFocus: PropTypes.func, + onInputBlur: PropTypes.func.isRequired, + onSuggestionsFetchRequested: PropTypes.func.isRequired, + onSuggestionsClearRequested: PropTypes.func.isRequired, + onSuggestionSelected: PropTypes.func, + onChange: PropTypes.func.isRequired +}; + +AutoSuggestInput.defaultProps = { + className: styles.input, + inputContainerClassName: styles.inputContainer, + enforceMaxHeight: true, + minHeight: 50, + maxHeight: 200 +}; + +export default AutoSuggestInput; diff --git a/frontend/src/Components/Form/AutoSuggestInput.tsx b/frontend/src/Components/Form/AutoSuggestInput.tsx deleted file mode 100644 index b3a7c31b0..000000000 --- a/frontend/src/Components/Form/AutoSuggestInput.tsx +++ /dev/null @@ -1,259 +0,0 @@ -import classNames from 'classnames'; -import React, { - FocusEvent, - FormEvent, - KeyboardEvent, - KeyboardEventHandler, - MutableRefObject, - ReactNode, - Ref, - SyntheticEvent, - useCallback, - useEffect, - useRef, -} from 'react'; -import Autosuggest, { - AutosuggestPropsBase, - BlurEvent, - ChangeEvent, - RenderInputComponentProps, - RenderSuggestionsContainerParams, -} from 'react-autosuggest'; -import { Manager, Popper, Reference } from 'react-popper'; -import Portal from 'Components/Portal'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { InputChanged } from 'typings/inputs'; -import styles from './AutoSuggestInput.css'; - -interface AutoSuggestInputProps - extends Omit, 'renderInputComponent' | 'inputProps'> { - forwardedRef?: MutableRefObject | null>; - className?: string; - inputContainerClassName?: string; - name: string; - value?: string; - placeholder?: string; - suggestions: T[]; - hasError?: boolean; - hasWarning?: boolean; - enforceMaxHeight?: boolean; - minHeight?: number; - maxHeight?: number; - renderInputComponent?: ( - inputProps: RenderInputComponentProps, - ref: Ref - ) => ReactNode; - onInputChange: ( - event: FormEvent, - params: ChangeEvent - ) => unknown; - onInputKeyDown?: KeyboardEventHandler; - onInputFocus?: (event: SyntheticEvent) => unknown; - onInputBlur: ( - event: FocusEvent, - params?: BlurEvent - ) => unknown; - onChange?: (change: InputChanged) => unknown; -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function AutoSuggestInput(props: AutoSuggestInputProps) { - const { - // TODO: forwaredRef should be replaces with React.forwardRef - forwardedRef, - className = styles.input, - inputContainerClassName = styles.inputContainer, - name, - value = '', - placeholder, - suggestions, - enforceMaxHeight = true, - hasError, - hasWarning, - minHeight = 50, - maxHeight = 200, - getSuggestionValue, - renderSuggestion, - renderInputComponent, - onInputChange, - onInputKeyDown, - onInputFocus, - onInputBlur, - onSuggestionsFetchRequested, - onSuggestionsClearRequested, - onSuggestionSelected, - onChange, - ...otherProps - } = props; - - const updater = useRef<(() => void) | null>(null); - const previousSuggestions = usePrevious(suggestions); - - const handleComputeMaxHeight = useCallback( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (data: any) => { - const { top, bottom, width } = data.offsets.reference; - - if (enforceMaxHeight) { - data.styles.maxHeight = maxHeight; - } else { - const windowHeight = window.innerHeight; - - if (/^botton/.test(data.placement)) { - data.styles.maxHeight = windowHeight - bottom; - } else { - data.styles.maxHeight = top; - } - } - - data.styles.width = width; - - return data; - }, - [enforceMaxHeight, maxHeight] - ); - - const createRenderInputComponent = useCallback( - (inputProps: RenderInputComponentProps) => { - return ( - - {({ ref }) => { - if (renderInputComponent) { - return renderInputComponent(inputProps, ref); - } - - return ( -
- -
- ); - }} -
- ); - }, - [renderInputComponent] - ); - - const renderSuggestionsContainer = useCallback( - ({ containerProps, children }: RenderSuggestionsContainerParams) => { - return ( - - - {({ ref: popperRef, style, scheduleUpdate }) => { - updater.current = scheduleUpdate; - - return ( -
-
- {children} -
-
- ); - }} -
-
- ); - }, - [minHeight, handleComputeMaxHeight] - ); - - const handleInputKeyDown = useCallback( - (event: KeyboardEvent) => { - if ( - event.key === 'Tab' && - suggestions.length && - suggestions[0] !== value - ) { - event.preventDefault(); - - if (value) { - onSuggestionSelected?.(event, { - suggestion: suggestions[0], - suggestionValue: value, - suggestionIndex: 0, - sectionIndex: null, - method: 'enter', - }); - } - } - }, - [value, suggestions, onSuggestionSelected] - ); - - const inputProps = { - className: classNames( - className, - hasError && styles.hasError, - hasWarning && styles.hasWarning - ), - name, - value, - placeholder, - autoComplete: 'off', - spellCheck: false, - onChange: onInputChange, - onKeyDown: onInputKeyDown || handleInputKeyDown, - onFocus: onInputFocus, - onBlur: onInputBlur, - }; - - const theme = { - container: inputContainerClassName, - containerOpen: styles.suggestionsContainerOpen, - suggestionsContainer: styles.suggestionsContainer, - suggestionsList: styles.suggestionsList, - suggestion: styles.suggestion, - suggestionHighlighted: styles.suggestionHighlighted, - }; - - useEffect(() => { - if (updater.current && suggestions !== previousSuggestions) { - updater.current(); - } - }, [suggestions, previousSuggestions]); - - return ( - - - - ); -} - -export default AutoSuggestInput; diff --git a/frontend/src/Components/Form/CaptchaInput.css.d.ts b/frontend/src/Components/Form/CaptchaInput.css.d.ts deleted file mode 100644 index b6844144e..000000000 --- a/frontend/src/Components/Form/CaptchaInput.css.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'captchaInputWrapper': string; - 'hasButton': string; - 'hasError': string; - 'hasWarning': string; - 'input': string; - 'recaptchaWrapper': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Form/CaptchaInput.js b/frontend/src/Components/Form/CaptchaInput.js new file mode 100644 index 000000000..e1a5df458 --- /dev/null +++ b/frontend/src/Components/Form/CaptchaInput.js @@ -0,0 +1,84 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import ReCAPTCHA from 'react-google-recaptcha'; +import classNames from 'classnames'; +import { icons } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import FormInputButton from './FormInputButton'; +import TextInput from './TextInput'; +import styles from './CaptchaInput.css'; + +function CaptchaInput(props) { + const { + className, + name, + value, + hasError, + hasWarning, + refreshing, + siteKey, + secretToken, + onChange, + onRefreshPress, + onCaptchaChange + } = props; + + return ( +
+
+ + + + + +
+ + { + !!siteKey && !!secretToken && +
+ +
+ } +
+ ); +} + +CaptchaInput.propTypes = { + className: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + value: PropTypes.string.isRequired, + hasError: PropTypes.bool, + hasWarning: PropTypes.bool, + refreshing: PropTypes.bool.isRequired, + siteKey: PropTypes.string, + secretToken: PropTypes.string, + onChange: PropTypes.func.isRequired, + onRefreshPress: PropTypes.func.isRequired, + onCaptchaChange: PropTypes.func.isRequired +}; + +CaptchaInput.defaultProps = { + className: styles.input, + value: '' +}; + +export default CaptchaInput; diff --git a/frontend/src/Components/Form/CaptchaInput.tsx b/frontend/src/Components/Form/CaptchaInput.tsx deleted file mode 100644 index d5a3f11f7..000000000 --- a/frontend/src/Components/Form/CaptchaInput.tsx +++ /dev/null @@ -1,118 +0,0 @@ -import classNames from 'classnames'; -import React, { useCallback, useEffect } from 'react'; -import ReCAPTCHA from 'react-google-recaptcha'; -import { useDispatch, useSelector } from 'react-redux'; -import AppState from 'App/State/AppState'; -import Icon from 'Components/Icon'; -import usePrevious from 'Helpers/Hooks/usePrevious'; -import { icons } from 'Helpers/Props'; -import { - getCaptchaCookie, - refreshCaptcha, - resetCaptcha, -} from 'Store/Actions/captchaActions'; -import { InputChanged } from 'typings/inputs'; -import FormInputButton from './FormInputButton'; -import TextInput from './TextInput'; -import styles from './CaptchaInput.css'; - -interface CaptchaInputProps { - className?: string; - name: string; - value?: string; - provider: string; - providerData: object; - hasError?: boolean; - hasWarning?: boolean; - refreshing: boolean; - siteKey?: string; - secretToken?: string; - onChange: (change: InputChanged) => unknown; -} - -function CaptchaInput({ - className = styles.input, - name, - value = '', - provider, - providerData, - hasError, - hasWarning, - refreshing, - siteKey, - secretToken, - onChange, -}: CaptchaInputProps) { - const { token } = useSelector((state: AppState) => state.captcha); - const dispatch = useDispatch(); - const previousToken = usePrevious(token); - - const handleCaptchaChange = useCallback( - (token: string | null) => { - // If the captcha has expired `captchaResponse` will be null. - // In the event it's null don't try to get the captchaCookie. - // TODO: Should we clear the cookie? or reset the captcha? - - if (!token) { - return; - } - - dispatch( - getCaptchaCookie({ - provider, - providerData, - captchaResponse: token, - }) - ); - }, - [provider, providerData, dispatch] - ); - - const handleRefreshPress = useCallback(() => { - dispatch(refreshCaptcha({ provider, providerData })); - }, [provider, providerData, dispatch]); - - useEffect(() => { - if (token && token !== previousToken) { - onChange({ name, value: token }); - } - }, [name, token, previousToken, onChange]); - - useEffect(() => { - dispatch(resetCaptcha()); - }, [dispatch]); - - return ( -
-
- - - - - -
- - {siteKey && secretToken ? ( -
- -
- ) : null} -
- ); -} - -export default CaptchaInput; diff --git a/frontend/src/Components/Form/CaptchaInputConnector.js b/frontend/src/Components/Form/CaptchaInputConnector.js new file mode 100644 index 000000000..17b875c88 --- /dev/null +++ b/frontend/src/Components/Form/CaptchaInputConnector.js @@ -0,0 +1,98 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { refreshCaptcha, getCaptchaCookie, resetCaptcha } from 'Store/Actions/captchaActions'; +import CaptchaInput from './CaptchaInput'; + +function createMapStateToProps() { + return createSelector( + (state) => state.captcha, + (captcha) => { + return captcha; + } + ); +} + +const mapDispatchToProps = { + refreshCaptcha, + getCaptchaCookie, + resetCaptcha +}; + +class CaptchaInputConnector extends Component { + + // + // Lifecycle + + componentDidUpdate(prevProps) { + const { + name, + token, + onChange + } = this.props; + + if (token && token !== prevProps.token) { + onChange({ name, value: token }); + } + } + + componentWillUnmount = () => { + this.props.resetCaptcha(); + } + + // + // Listeners + + onRefreshPress = () => { + const { + provider, + providerData + } = this.props; + + this.props.refreshCaptcha({ provider, providerData }); + } + + onCaptchaChange = (captchaResponse) => { + // If the captcha has expired `captchaResponse` will be null. + // In the event it's null don't try to get the captchaCookie. + // TODO: Should we clear the cookie? or reset the captcha? + + if (!captchaResponse) { + return; + } + + const { + provider, + providerData + } = this.props; + + this.props.getCaptchaCookie({ provider, providerData, captchaResponse }); + } + + // + // Render + + render() { + return ( + + ); + } +} + +CaptchaInputConnector.propTypes = { + provider: PropTypes.string.isRequired, + providerData: PropTypes.object.isRequired, + name: PropTypes.string.isRequired, + token: PropTypes.string, + onChange: PropTypes.func.isRequired, + refreshCaptcha: PropTypes.func.isRequired, + getCaptchaCookie: PropTypes.func.isRequired, + resetCaptcha: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(CaptchaInputConnector); diff --git a/frontend/src/Components/Form/CheckInput.css b/frontend/src/Components/Form/CheckInput.css index 171121482..e0b05eca3 100644 --- a/frontend/src/Components/Form/CheckInput.css +++ b/frontend/src/Components/Form/CheckInput.css @@ -32,21 +32,21 @@ height: 20px; border: 1px solid #ccc; border-radius: 2px; - background-color: var(--white); - color: var(--white); + background-color: $white; + color: $white; text-align: center; line-height: 20px; } .checkbox:focus + .input { outline: 0; - border-color: var(--inputFocusBorderColor); - box-shadow: inset 0 1px 1px var(--inputBoxShadowColor), 0 0 8px var(--inputFocusBoxShadowColor); + border-color: $inputFocusBorderColor; + box-shadow: inset 0 1px 1px $inputBoxShadowColor, 0 0 8px $inputFocusBoxShadowColor; } .dangerIsChecked { - border-color: var(--dangerColor); - background-color: var(--dangerColor); + border-color: $dangerColor; + background-color: $dangerColor; &.isDisabled { opacity: 0.7; @@ -54,8 +54,8 @@ } .primaryIsChecked { - border-color: var(--primaryColor); - background-color: var(--primaryColor); + border-color: $primaryColor; + background-color: $primaryColor; &.isDisabled { opacity: 0.7; @@ -63,8 +63,8 @@ } .successIsChecked { - border-color: var(--successColor); - background-color: var(--successColor); + border-color: $successColor; + background-color: $successColor; &.isDisabled { opacity: 0.7; @@ -72,8 +72,8 @@ } .warningIsChecked { - border-color: var(--warningColor); - background-color: var(--warningColor); + border-color: $warningColor; + background-color: $warningColor; &.isDisabled { opacity: 0.7; @@ -82,15 +82,15 @@ .isNotChecked { &.isDisabled { - border-color: var(--disabledCheckInputColor); - background-color: var(--disabledCheckInputColor); + border-color: $disabledCheckInputColor; + background-color: $disabledCheckInputColor; opacity: 0.7; } } .isIndeterminate { - border-color: var(--gray); - background-color: var(--gray); + border-color: $gray; + background-color: $gray; } .helpText { diff --git a/frontend/src/Components/Form/CheckInput.css.d.ts b/frontend/src/Components/Form/CheckInput.css.d.ts deleted file mode 100644 index bba6b63bb..000000000 --- a/frontend/src/Components/Form/CheckInput.css.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'checkbox': string; - 'container': string; - 'dangerIsChecked': string; - 'helpText': string; - 'input': string; - 'isDisabled': string; - 'isIndeterminate': string; - 'isNotChecked': string; - 'label': string; - 'primaryIsChecked': string; - 'successIsChecked': string; - 'warningIsChecked': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Form/CheckInput.js b/frontend/src/Components/Form/CheckInput.js new file mode 100644 index 000000000..134290111 --- /dev/null +++ b/frontend/src/Components/Form/CheckInput.js @@ -0,0 +1,191 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import { icons, kinds } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import FormInputHelpText from './FormInputHelpText'; +import styles from './CheckInput.css'; + +class CheckInput extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._checkbox = null; + } + + componentDidMount() { + this.setIndeterminate(); + } + + componentDidUpdate() { + this.setIndeterminate(); + } + + // + // Control + + setIndeterminate() { + if (!this._checkbox) { + return; + } + + const { + value, + uncheckedValue, + checkedValue + } = this.props; + + this._checkbox.indeterminate = value !== uncheckedValue && value !== checkedValue; + } + + toggleChecked = (checked, shiftKey) => { + const { + name, + value, + checkedValue, + uncheckedValue + } = this.props; + + const newValue = checked ? checkedValue : uncheckedValue; + + if (value !== newValue) { + this.props.onChange({ + name, + value: newValue, + shiftKey + }); + } + } + + // + // Listeners + + setRef = (ref) => { + this._checkbox = ref; + } + + onClick = (event) => { + if (this.props.isDisabled) { + return; + } + + const shiftKey = event.nativeEvent.shiftKey; + const checked = !this._checkbox.checked; + + event.preventDefault(); + this.toggleChecked(checked, shiftKey); + } + + onChange = (event) => { + const checked = event.target.checked; + const shiftKey = event.nativeEvent.shiftKey; + + this.toggleChecked(checked, shiftKey); + } + + // + // Render + + render() { + const { + className, + containerClassName, + name, + value, + checkedValue, + uncheckedValue, + helpText, + helpTextWarning, + isDisabled, + kind + } = this.props; + + const isChecked = value === checkedValue; + const isUnchecked = value === uncheckedValue; + const isIndeterminate = !isChecked && !isUnchecked; + const isCheckClass = `${kind}IsChecked`; + + return ( +
+ +
+ ); + } +} + +CheckInput.propTypes = { + className: PropTypes.string.isRequired, + containerClassName: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + checkedValue: PropTypes.bool, + uncheckedValue: PropTypes.bool, + value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]), + helpText: PropTypes.string, + helpTextWarning: PropTypes.string, + isDisabled: PropTypes.bool, + kind: PropTypes.oneOf(kinds.all).isRequired, + onChange: PropTypes.func.isRequired +}; + +CheckInput.defaultProps = { + className: styles.input, + containerClassName: styles.container, + checkedValue: true, + uncheckedValue: false, + kind: kinds.PRIMARY +}; + +export default CheckInput; diff --git a/frontend/src/Components/Form/CheckInput.tsx b/frontend/src/Components/Form/CheckInput.tsx deleted file mode 100644 index b7080cfdd..000000000 --- a/frontend/src/Components/Form/CheckInput.tsx +++ /dev/null @@ -1,141 +0,0 @@ -import classNames from 'classnames'; -import React, { SyntheticEvent, useCallback, useEffect, useRef } from 'react'; -import Icon from 'Components/Icon'; -import { icons } from 'Helpers/Props'; -import { Kind } from 'Helpers/Props/kinds'; -import { CheckInputChanged } from 'typings/inputs'; -import FormInputHelpText from './FormInputHelpText'; -import styles from './CheckInput.css'; - -interface ChangeEvent extends SyntheticEvent { - target: EventTarget & T; -} - -interface CheckInputProps { - className?: string; - containerClassName?: string; - name: string; - checkedValue?: boolean; - uncheckedValue?: boolean; - value?: string | boolean; - helpText?: string; - helpTextWarning?: string; - isDisabled?: boolean; - kind?: Extract; - onChange: (changes: CheckInputChanged) => void; -} - -function CheckInput(props: CheckInputProps) { - const { - className = styles.input, - containerClassName = styles.container, - name, - value, - checkedValue = true, - uncheckedValue = false, - helpText, - helpTextWarning, - isDisabled, - kind = 'primary', - onChange, - } = props; - - const inputRef = useRef(null); - - const isChecked = value === checkedValue; - const isUnchecked = value === uncheckedValue; - const isIndeterminate = !isChecked && !isUnchecked; - const isCheckClass: keyof typeof styles = `${kind}IsChecked`; - - const toggleChecked = useCallback( - (checked: boolean, shiftKey: boolean) => { - const newValue = checked ? checkedValue : uncheckedValue; - - if (value !== newValue) { - onChange({ - name, - value: newValue, - shiftKey, - }); - } - }, - [name, value, checkedValue, uncheckedValue, onChange] - ); - - const handleClick = useCallback( - (event: SyntheticEvent) => { - if (isDisabled) { - return; - } - - const shiftKey = event.nativeEvent.shiftKey; - const checked = !(inputRef.current?.checked ?? false); - - event.preventDefault(); - toggleChecked(checked, shiftKey); - }, - [isDisabled, toggleChecked] - ); - - const handleChange = useCallback( - (event: ChangeEvent) => { - const checked = event.target.checked; - const shiftKey = event.nativeEvent.shiftKey; - - toggleChecked(checked, shiftKey); - }, - [toggleChecked] - ); - - useEffect(() => { - if (!inputRef.current) { - return; - } - - inputRef.current.indeterminate = - value !== uncheckedValue && value !== checkedValue; - }, [value, uncheckedValue, checkedValue]); - - return ( -
- -
- ); -} - -export default CheckInput; diff --git a/frontend/src/Components/Form/DeviceInput.css b/frontend/src/Components/Form/DeviceInput.css new file mode 100644 index 000000000..7abe83db5 --- /dev/null +++ b/frontend/src/Components/Form/DeviceInput.css @@ -0,0 +1,8 @@ +.deviceInputWrapper { + display: flex; +} + +.input { + composes: input from '~./TagInput.css'; + composes: hasButton from '~Components/Form/Input.css'; +} diff --git a/frontend/src/Components/Form/DeviceInput.js b/frontend/src/Components/Form/DeviceInput.js new file mode 100644 index 000000000..f77c7cf29 --- /dev/null +++ b/frontend/src/Components/Form/DeviceInput.js @@ -0,0 +1,106 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { icons } from 'Helpers/Props'; +import tagShape from 'Helpers/Props/Shapes/tagShape'; +import Icon from 'Components/Icon'; +import FormInputButton from './FormInputButton'; +import TagInput from './TagInput'; +import styles from './DeviceInput.css'; + +class DeviceInput extends Component { + + onTagAdd = (device) => { + const { + name, + value, + onChange + } = this.props; + + // New tags won't have an ID, only a name. + const deviceId = device.id || device.name; + + onChange({ + name, + value: [...value, deviceId] + }); + } + + onTagDelete = ({ index }) => { + const { + name, + value, + onChange + } = this.props; + + const newValue = value.slice(); + newValue.splice(index, 1); + + onChange({ + name, + value: newValue + }); + } + + // + // Render + + render() { + const { + className, + name, + items, + selectedDevices, + hasError, + hasWarning, + isFetching, + onRefreshPress + } = this.props; + + return ( +
+ + + + + +
+ ); + } +} + +DeviceInput.propTypes = { + className: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + value: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])).isRequired, + items: PropTypes.arrayOf(PropTypes.shape(tagShape)).isRequired, + selectedDevices: PropTypes.arrayOf(PropTypes.shape(tagShape)).isRequired, + hasError: PropTypes.bool, + hasWarning: PropTypes.bool, + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + onChange: PropTypes.func.isRequired, + onRefreshPress: PropTypes.func.isRequired +}; + +DeviceInput.defaultProps = { + className: styles.deviceInputWrapper, + inputClassName: styles.input +}; + +export default DeviceInput; diff --git a/frontend/src/Components/Form/DeviceInputConnector.js b/frontend/src/Components/Form/DeviceInputConnector.js new file mode 100644 index 000000000..0b0a87959 --- /dev/null +++ b/frontend/src/Components/Form/DeviceInputConnector.js @@ -0,0 +1,104 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { fetchOptions, clearOptions, defaultState } from 'Store/Actions/providerOptionActions'; +import DeviceInput from './DeviceInput'; + +function createMapStateToProps() { + return createSelector( + (state, { value }) => value, + (state) => state.providerOptions.devices || defaultState, + (value, devices) => { + + return { + ...devices, + selectedDevices: value.map((valueDevice) => { + // Disable equality ESLint rule so we don't need to worry about + // a type mismatch between the value items and the device ID. + // eslint-disable-next-line eqeqeq + const device = devices.items.find((d) => d.id == valueDevice); + + if (device) { + return { + id: device.id, + name: `${device.name} (${device.id})` + }; + } + + return { + id: valueDevice, + name: `Unknown (${valueDevice})` + }; + }) + }; + } + ); +} + +const mapDispatchToProps = { + dispatchFetchOptions: fetchOptions, + dispatchClearOptions: clearOptions +}; + +class DeviceInputConnector extends Component { + + // + // Lifecycle + + componentDidMount = () => { + this._populate(); + } + + componentWillUnmount = () => { + this.props.dispatchClearOptions({ section: 'devices' }); + } + + // + // Control + + _populate() { + const { + provider, + providerData, + dispatchFetchOptions + } = this.props; + + dispatchFetchOptions({ + section: 'devices', + action: 'getDevices', + provider, + providerData + }); + } + + // + // Listeners + + onRefreshPress = () => { + this._populate(); + } + + // + // Render + + render() { + return ( + + ); + } +} + +DeviceInputConnector.propTypes = { + provider: PropTypes.string.isRequired, + providerData: PropTypes.object.isRequired, + name: PropTypes.string.isRequired, + onChange: PropTypes.func.isRequired, + dispatchFetchOptions: PropTypes.func.isRequired, + dispatchClearOptions: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(DeviceInputConnector); diff --git a/frontend/src/Components/Form/Select/EnhancedSelectInput.css b/frontend/src/Components/Form/EnhancedSelectInput.css similarity index 76% rename from frontend/src/Components/Form/Select/EnhancedSelectInput.css rename to frontend/src/Components/Form/EnhancedSelectInput.css index 735d63573..f971f6517 100644 --- a/frontend/src/Components/Form/Select/EnhancedSelectInput.css +++ b/frontend/src/Components/Form/EnhancedSelectInput.css @@ -19,7 +19,7 @@ .isDisabled { opacity: 0.7; - cursor: not-allowed !important; + cursor: not-allowed; } .dropdownArrowContainer { @@ -39,7 +39,7 @@ .dropdownArrowContainerDisabled { composes: dropdownArrowContainer; - color: var(--disabledInputColor); + color: $disabledInputColor; } .optionsContainer { @@ -50,9 +50,9 @@ .options { composes: scroller from '~Components/Scroller/Scroller.css'; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-radius: 4px; - background-color: var(--inputBackgroundColor); + background-color: $white; } .optionsModal { @@ -73,18 +73,12 @@ padding: 10px 0; } -.optionsInnerModalBody { - composes: innerModalBody from '~Components/Modal/ModalBody.css'; - - padding: 0; -} - .optionsModalScroller { composes: scroller from '~Components/Scroller/Scroller.css'; - border: 1px solid var(--inputBorderColor); + border: 1px solid $inputBorderColor; border-radius: 4px; - background-color: var(--inputBackgroundColor); + background-color: $white; } .loading { @@ -96,7 +90,7 @@ display: flex; justify-content: flex-end; height: 40px; - border-bottom: 1px solid var(--borderColor); + border-bottom: 1px solid $borderColor; } .mobileCloseButton { @@ -106,6 +100,6 @@ line-height: 40px; &:hover { - color: var(--modalCloseButtonHoverColor); + color: $modalCloseButtonHoverColor; } } diff --git a/frontend/src/Components/Form/EnhancedSelectInput.js b/frontend/src/Components/Form/EnhancedSelectInput.js new file mode 100644 index 000000000..8f1faab89 --- /dev/null +++ b/frontend/src/Components/Form/EnhancedSelectInput.js @@ -0,0 +1,596 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { Manager, Popper, Reference } from 'react-popper'; +import classNames from 'classnames'; +import getUniqueElememtId from 'Utilities/getUniqueElementId'; +import { isMobile as isMobileUtil } from 'Utilities/mobile'; +import * as keyCodes from 'Utilities/Constants/keyCodes'; +import { icons, sizes, scrollDirections } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import Portal from 'Components/Portal'; +import Link from 'Components/Link/Link'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Measure from 'Components/Measure'; +import Modal from 'Components/Modal/Modal'; +import ModalBody from 'Components/Modal/ModalBody'; +import Scroller from 'Components/Scroller/Scroller'; +import TextInput from './TextInput'; +import HintedSelectInputSelectedValue from './HintedSelectInputSelectedValue'; +import HintedSelectInputOption from './HintedSelectInputOption'; +import styles from './EnhancedSelectInput.css'; + +function isArrowKey(keyCode) { + return keyCode === keyCodes.UP_ARROW || keyCode === keyCodes.DOWN_ARROW; +} + +function getSelectedOption(selectedIndex, values) { + return values[selectedIndex]; +} + +function findIndex(startingIndex, direction, values) { + let indexToTest = startingIndex + direction; + + while (indexToTest !== startingIndex) { + if (indexToTest < 0) { + indexToTest = values.length - 1; + } else if (indexToTest >= values.length) { + indexToTest = 0; + } + + if (getSelectedOption(indexToTest, values).isDisabled) { + indexToTest = indexToTest + direction; + } else { + return indexToTest; + } + } +} + +function previousIndex(selectedIndex, values) { + return findIndex(selectedIndex, -1, values); +} + +function nextIndex(selectedIndex, values) { + return findIndex(selectedIndex, 1, values); +} + +function getSelectedIndex(props) { + const { + value, + values + } = props; + + if (Array.isArray(value)) { + return values.findIndex((v) => { + return value.size && v.key === value[0]; + }); + } + + return values.findIndex((v) => { + return v.key === value; + }); +} + +function isSelectedItem(index, props) { + const { + value, + values + } = props; + + if (Array.isArray(value)) { + return value.includes(values[index].key); + } + + return values[index].key === value; +} + +function getKey(selectedIndex, values) { + return values[selectedIndex].key; +} + +class EnhancedSelectInput extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._scheduleUpdate = null; + this._buttonId = getUniqueElememtId(); + this._optionsId = getUniqueElememtId(); + + this.state = { + isOpen: false, + selectedIndex: getSelectedIndex(props), + width: 0, + isMobile: isMobileUtil() + }; + } + + componentDidUpdate(prevProps) { + if (this._scheduleUpdate) { + this._scheduleUpdate(); + } + + if (!Array.isArray(this.props.value) && prevProps.value !== this.props.value) { + this.setState({ + selectedIndex: getSelectedIndex(this.props) + }); + } + } + + // + // Control + + _addListener() { + window.addEventListener('click', this.onWindowClick); + } + + _removeListener() { + window.removeEventListener('click', this.onWindowClick); + } + + // + // Listeners + + onComputeMaxHeight = (data) => { + const { + top, + bottom + } = data.offsets.reference; + + const windowHeight = window.innerHeight; + + if ((/^botton/).test(data.placement)) { + data.styles.maxHeight = windowHeight - bottom; + } else { + data.styles.maxHeight = top; + } + + return data; + } + + onWindowClick = (event) => { + const button = document.getElementById(this._buttonId); + const options = document.getElementById(this._optionsId); + + if (!button || !event.target.isConnected || this.state.isMobile) { + return; + } + + if ( + !button.contains(event.target) && + options && + !options.contains(event.target) && + this.state.isOpen + ) { + this.setState({ isOpen: false }); + this._removeListener(); + } + } + + onFocus = () => { + if (this.state.isOpen) { + this._removeListener(); + this.setState({ isOpen: false }); + } + } + + onBlur = () => { + if (!this.props.isEditable) { + // Calling setState without this check prevents the click event from being properly handled on Chrome (it is on firefox) + const origIndex = getSelectedIndex(this.props); + + if (origIndex !== this.state.selectedIndex) { + this.setState({ selectedIndex: origIndex }); + } + } + } + + onKeyDown = (event) => { + const { + values + } = this.props; + + const { + isOpen, + selectedIndex + } = this.state; + + const keyCode = event.keyCode; + const newState = {}; + + if (!isOpen) { + if (isArrowKey(keyCode)) { + event.preventDefault(); + newState.isOpen = true; + } + + if ( + selectedIndex == null || selectedIndex === -1 || + getSelectedOption(selectedIndex, values).isDisabled + ) { + if (keyCode === keyCodes.UP_ARROW) { + newState.selectedIndex = previousIndex(0, values); + } else if (keyCode === keyCodes.DOWN_ARROW) { + newState.selectedIndex = nextIndex(values.length - 1, values); + } + } + + this.setState(newState); + return; + } + + if (keyCode === keyCodes.UP_ARROW) { + event.preventDefault(); + newState.selectedIndex = previousIndex(selectedIndex, values); + } + + if (keyCode === keyCodes.DOWN_ARROW) { + event.preventDefault(); + newState.selectedIndex = nextIndex(selectedIndex, values); + } + + if (keyCode === keyCodes.ENTER) { + event.preventDefault(); + newState.isOpen = false; + this.onSelect(getKey(selectedIndex, values)); + } + + if (keyCode === keyCodes.TAB) { + newState.isOpen = false; + this.onSelect(getKey(selectedIndex, values)); + } + + if (keyCode === keyCodes.ESCAPE) { + event.preventDefault(); + event.stopPropagation(); + newState.isOpen = false; + newState.selectedIndex = getSelectedIndex(this.props); + } + + if (!_.isEmpty(newState)) { + this.setState(newState); + } + } + + onPress = () => { + if (this.state.isOpen) { + this._removeListener(); + } else { + this._addListener(); + } + + if (!this.state.isOpen && this.props.onOpen) { + this.props.onOpen(); + } + + this.setState({ isOpen: !this.state.isOpen }); + } + + onSelect = (value) => { + if (Array.isArray(this.props.value)) { + let newValue = null; + const index = this.props.value.indexOf(value); + if (index === -1) { + newValue = this.props.values.map((v) => v.key).filter((v) => (v === value) || this.props.value.includes(v)); + } else { + newValue = [...this.props.value]; + newValue.splice(index, 1); + } + this.props.onChange({ + name: this.props.name, + value: newValue + }); + } else { + this.setState({ isOpen: false }); + + this.props.onChange({ + name: this.props.name, + value + }); + } + } + + onMeasure = ({ width }) => { + this.setState({ width }); + } + + onOptionsModalClose = () => { + this.setState({ isOpen: false }); + } + + // + // Render + + render() { + const { + className, + disabledClassName, + name, + value, + values, + isDisabled, + isEditable, + isFetching, + hasError, + hasWarning, + valueOptions, + selectedValueOptions, + selectedValueComponent: SelectedValueComponent, + optionComponent: OptionComponent, + onChange + } = this.props; + + const { + selectedIndex, + width, + isOpen, + isMobile + } = this.state; + + const isMultiSelect = Array.isArray(value); + const selectedOption = getSelectedOption(selectedIndex, values); + + return ( +
+ + + {({ ref }) => ( +
+ + { + isEditable ? +
+ + + { + isFetching && + + } + + { + !isFetching && + + } + +
: + + + {selectedOption ? selectedOption.value : null} + + +
+ + { + isFetching && + + } + + { + !isFetching && + + } +
+ + } +
+
+ )} +
+ + + {({ ref, style, scheduleUpdate }) => { + this._scheduleUpdate = scheduleUpdate; + + return ( +
+ { + isOpen && !isMobile ? + + { + values.map((v, index) => { + const hasParent = v.parentKey !== undefined; + const depth = hasParent ? 1 : 0; + const parentSelected = hasParent && value.includes(v.parentKey); + return ( + + {v.value} + + ); + }) + } + : + null + } +
+ ); + } + } +
+
+
+ + { + isMobile && + + + +
+ + + +
+ + { + values.map((v, index) => { + const hasParent = v.parentKey !== undefined; + const depth = hasParent ? 1 : 0; + const parentSelected = hasParent && value.includes(v.parentKey); + return ( + + {v.value} + + ); + }) + } +
+
+
+ } +
+ ); + } +} + +EnhancedSelectInput.propTypes = { + className: PropTypes.string, + disabledClassName: PropTypes.string, + name: PropTypes.string.isRequired, + value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.arrayOf(PropTypes.number)]).isRequired, + values: PropTypes.arrayOf(PropTypes.object).isRequired, + isDisabled: PropTypes.bool.isRequired, + isFetching: PropTypes.bool.isRequired, + isEditable: PropTypes.bool.isRequired, + hasError: PropTypes.bool, + hasWarning: PropTypes.bool, + valueOptions: PropTypes.object.isRequired, + selectedValueOptions: PropTypes.object.isRequired, + selectedValueComponent: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired, + optionComponent: PropTypes.elementType, + onOpen: PropTypes.func, + onChange: PropTypes.func.isRequired +}; + +EnhancedSelectInput.defaultProps = { + className: styles.enhancedSelect, + disabledClassName: styles.isDisabled, + isDisabled: false, + isFetching: false, + isEditable: false, + valueOptions: {}, + selectedValueOptions: {}, + selectedValueComponent: HintedSelectInputSelectedValue, + optionComponent: HintedSelectInputOption +}; + +export default EnhancedSelectInput; diff --git a/frontend/src/Components/Form/EnhancedSelectInputConnector.js b/frontend/src/Components/Form/EnhancedSelectInputConnector.js new file mode 100644 index 000000000..01a7038b9 --- /dev/null +++ b/frontend/src/Components/Form/EnhancedSelectInputConnector.js @@ -0,0 +1,159 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { fetchOptions, clearOptions, defaultState } from 'Store/Actions/providerOptionActions'; +import EnhancedSelectInput from './EnhancedSelectInput'; + +const importantFieldNames = [ + 'baseUrl', + 'apiPath', + 'apiKey' +]; + +function getProviderDataKey(providerData) { + if (!providerData || !providerData.fields) { + return null; + } + + const fields = providerData.fields + .filter((f) => importantFieldNames.includes(f.name)) + .map((f) => f.value); + + return fields; +} + +function getSelectOptions(items) { + if (!items) { + return []; + } + + return items.map((option) => { + return { + key: option.value, + value: option.name, + hint: option.hint, + parentKey: option.parentValue + }; + }); +} + +function createMapStateToProps() { + return createSelector( + (state, { selectOptionsProviderAction }) => state.providerOptions[selectOptionsProviderAction] || defaultState, + (options) => { + if (options) { + return { + isFetching: options.isFetching, + values: getSelectOptions(options.items) + }; + } + } + ); +} + +const mapDispatchToProps = { + dispatchFetchOptions: fetchOptions, + dispatchClearOptions: clearOptions +}; + +class EnhancedSelectInputConnector extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + refetchRequired: false + }; + } + + componentDidMount = () => { + this._populate(); + } + + componentDidUpdate = (prevProps) => { + const prevKey = getProviderDataKey(prevProps.providerData); + const nextKey = getProviderDataKey(this.props.providerData); + + if (!_.isEqual(prevKey, nextKey)) { + this.setState({ refetchRequired: true }); + } + } + + componentWillUnmount = () => { + this._cleanup(); + } + + // + // Listeners + + onOpen = () => { + if (this.state.refetchRequired) { + this._populate(); + } + } + + // + // Control + + _populate() { + const { + provider, + providerData, + selectOptionsProviderAction, + dispatchFetchOptions + } = this.props; + + if (selectOptionsProviderAction) { + this.setState({ refetchRequired: false }); + dispatchFetchOptions({ + section: selectOptionsProviderAction, + action: selectOptionsProviderAction, + provider, + providerData + }); + } + } + + _cleanup() { + const { + selectOptionsProviderAction, + dispatchClearOptions + } = this.props; + + if (selectOptionsProviderAction) { + dispatchClearOptions({ section: selectOptionsProviderAction }); + } + } + + // + // Render + + render() { + return ( + + ); + } +} + +EnhancedSelectInputConnector.propTypes = { + provider: PropTypes.string.isRequired, + providerData: PropTypes.object.isRequired, + name: PropTypes.string.isRequired, + value: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])).isRequired, + values: PropTypes.arrayOf(PropTypes.object).isRequired, + selectOptionsProviderAction: PropTypes.string, + onChange: PropTypes.func.isRequired, + isFetching: PropTypes.bool.isRequired, + dispatchFetchOptions: PropTypes.func.isRequired, + dispatchClearOptions: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(EnhancedSelectInputConnector); diff --git a/frontend/src/Components/Form/EnhancedSelectInputOption.css b/frontend/src/Components/Form/EnhancedSelectInputOption.css new file mode 100644 index 000000000..f6b6136ae --- /dev/null +++ b/frontend/src/Components/Form/EnhancedSelectInputOption.css @@ -0,0 +1,61 @@ +.option { + display: flex; + align-items: center; + justify-content: space-between; + padding: 5px 10px; + width: 100%; + cursor: default; + + &:hover { + background-color: #f8f8f8; + } +} + +.optionCheck { + composes: container from '~./CheckInput.css'; + + flex: 0 0 0; +} + +.optionCheckInput { + composes: input from '~./CheckInput.css'; + + margin-top: 0; +} + +.isSelected { + background-color: #e2e2e2; + + &:hover { + background-color: #e2e2e2; + } + + &.isMobile { + background-color: inherit; + + .iconContainer { + color: $primaryColor; + } + } +} + +.isDisabled { + background-color: #aaa; +} + +.isHidden { + display: none; +} + +.isMobile { + height: 50px; + border-bottom: 1px solid $borderColor; + + &:last-child { + border: none; + } + + &:hover { + background-color: unset; + } +} diff --git a/frontend/src/Components/Form/EnhancedSelectInputOption.js b/frontend/src/Components/Form/EnhancedSelectInputOption.js new file mode 100644 index 000000000..d4fad3b24 --- /dev/null +++ b/frontend/src/Components/Form/EnhancedSelectInputOption.js @@ -0,0 +1,113 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import classNames from 'classnames'; +import { icons } from 'Helpers/Props'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import CheckInput from './CheckInput'; +import styles from './EnhancedSelectInputOption.css'; + +class EnhancedSelectInputOption extends Component { + + // + // Listeners + + onPress = (e) => { + e.preventDefault(); + + const { + id, + onSelect + } = this.props; + + onSelect(id); + } + + onCheckPress = () => { + // CheckInput requires a handler. Swallow the change event because onPress will already handle it via event propagation. + } + + // + // Render + + render() { + const { + className, + id, + depth, + isSelected, + isDisabled, + isHidden, + isMultiSelect, + isMobile, + children + } = this.props; + + return ( + + + { + depth !== 0 && +
+ } + + { + isMultiSelect && + + } + + {children} + + { + isMobile && +
+ +
+ } + + ); + } +} + +EnhancedSelectInputOption.propTypes = { + className: PropTypes.string.isRequired, + id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, + depth: PropTypes.number.isRequired, + isSelected: PropTypes.bool.isRequired, + isDisabled: PropTypes.bool.isRequired, + isHidden: PropTypes.bool.isRequired, + isMultiSelect: PropTypes.bool.isRequired, + isMobile: PropTypes.bool.isRequired, + children: PropTypes.node.isRequired, + onSelect: PropTypes.func.isRequired +}; + +EnhancedSelectInputOption.defaultProps = { + className: styles.option, + depth: 0, + isDisabled: false, + isHidden: false, + isMultiSelect: false +}; + +export default EnhancedSelectInputOption; diff --git a/frontend/src/Components/Form/EnhancedSelectInputSelectedValue.css b/frontend/src/Components/Form/EnhancedSelectInputSelectedValue.css new file mode 100644 index 000000000..6b8b73af9 --- /dev/null +++ b/frontend/src/Components/Form/EnhancedSelectInputSelectedValue.css @@ -0,0 +1,7 @@ +.selectedValue { + flex: 1 1 auto; +} + +.isDisabled { + color: $disabledInputColor; +} diff --git a/frontend/src/Components/Form/EnhancedSelectInputSelectedValue.js b/frontend/src/Components/Form/EnhancedSelectInputSelectedValue.js new file mode 100644 index 000000000..c40ee93c1 --- /dev/null +++ b/frontend/src/Components/Form/EnhancedSelectInputSelectedValue.js @@ -0,0 +1,35 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import classNames from 'classnames'; +import styles from './EnhancedSelectInputSelectedValue.css'; + +function EnhancedSelectInputSelectedValue(props) { + const { + className, + children, + isDisabled + } = props; + + return ( +
+ {children} +
+ ); +} + +EnhancedSelectInputSelectedValue.propTypes = { + className: PropTypes.string.isRequired, + children: PropTypes.node, + isDisabled: PropTypes.bool.isRequired +}; + +EnhancedSelectInputSelectedValue.defaultProps = { + className: styles.selectedValue, + isDisabled: false +}; + +export default EnhancedSelectInputSelectedValue; diff --git a/frontend/src/Components/Form/Form.css.d.ts b/frontend/src/Components/Form/Form.css.d.ts deleted file mode 100644 index 178f2fec1..000000000 --- a/frontend/src/Components/Form/Form.css.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'validationFailures': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Form/Form.js b/frontend/src/Components/Form/Form.js new file mode 100644 index 000000000..c2c67eddf --- /dev/null +++ b/frontend/src/Components/Form/Form.js @@ -0,0 +1,58 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import { kinds } from 'Helpers/Props'; +import Alert from 'Components/Alert'; +import styles from './Form.css'; + +function Form({ children, validationErrors, validationWarnings, ...otherProps }) { + return ( +
+ { + validationErrors.length || validationWarnings.length ? +
+ { + validationErrors.map((error, index) => { + return ( + + {error.errorMessage} + + ); + }) + } + + { + validationWarnings.map((warning, index) => { + return ( + + {warning.errorMessage} + + ); + }) + } +
: + null + } + + {children} +
+ ); +} + +Form.propTypes = { + children: PropTypes.node.isRequired, + validationErrors: PropTypes.arrayOf(PropTypes.object).isRequired, + validationWarnings: PropTypes.arrayOf(PropTypes.object).isRequired +}; + +Form.defaultProps = { + validationErrors: [], + validationWarnings: [] +}; + +export default Form; diff --git a/frontend/src/Components/Form/Form.tsx b/frontend/src/Components/Form/Form.tsx deleted file mode 100644 index d522019e7..000000000 --- a/frontend/src/Components/Form/Form.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import React, { ReactNode } from 'react'; -import Alert from 'Components/Alert'; -import { kinds } from 'Helpers/Props'; -import { ValidationError, ValidationWarning } from 'typings/pending'; -import styles from './Form.css'; - -export interface FormProps { - children: ReactNode; - validationErrors?: ValidationError[]; - validationWarnings?: ValidationWarning[]; -} - -function Form({ - children, - validationErrors = [], - validationWarnings = [], -}: FormProps) { - return ( -
- {validationErrors.length || validationWarnings.length ? ( -
- {validationErrors.map((error, index) => { - return ( - - {error.errorMessage} - - ); - })} - - {validationWarnings.map((warning, index) => { - return ( - - {warning.errorMessage} - - ); - })} -
- ) : null} - - {children} -
- ); -} - -export default Form; diff --git a/frontend/src/Components/Form/FormGroup.css.d.ts b/frontend/src/Components/Form/FormGroup.css.d.ts deleted file mode 100644 index 86145f643..000000000 --- a/frontend/src/Components/Form/FormGroup.css.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'extraSmall': string; - 'group': string; - 'large': string; - 'medium': string; - 'small': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Form/FormGroup.js b/frontend/src/Components/Form/FormGroup.js new file mode 100644 index 000000000..d2e04c350 --- /dev/null +++ b/frontend/src/Components/Form/FormGroup.js @@ -0,0 +1,56 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import classNames from 'classnames'; +import { map } from 'Helpers/elementChildren'; +import { sizes } from 'Helpers/Props'; +import styles from './FormGroup.css'; + +function FormGroup(props) { + const { + className, + children, + size, + advancedSettings, + isAdvanced, + ...otherProps + } = props; + + if (!advancedSettings && isAdvanced) { + return null; + } + + const childProps = isAdvanced ? { isAdvanced } : {}; + + return ( +
+ { + map(children, (child) => { + return React.cloneElement(child, childProps); + }) + } +
+ ); +} + +FormGroup.propTypes = { + className: PropTypes.string.isRequired, + children: PropTypes.node.isRequired, + size: PropTypes.oneOf(sizes.all).isRequired, + advancedSettings: PropTypes.bool.isRequired, + isAdvanced: PropTypes.bool.isRequired +}; + +FormGroup.defaultProps = { + className: styles.group, + size: sizes.SMALL, + advancedSettings: false, + isAdvanced: false +}; + +export default FormGroup; diff --git a/frontend/src/Components/Form/FormGroup.tsx b/frontend/src/Components/Form/FormGroup.tsx deleted file mode 100644 index 1dd879897..000000000 --- a/frontend/src/Components/Form/FormGroup.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import classNames from 'classnames'; -import React, { Children, ComponentPropsWithoutRef, ReactNode } from 'react'; -import { Size } from 'Helpers/Props/sizes'; -import styles from './FormGroup.css'; - -interface FormGroupProps extends ComponentPropsWithoutRef<'div'> { - className?: string; - children: ReactNode; - size?: Extract; - advancedSettings?: boolean; - isAdvanced?: boolean; -} - -function FormGroup(props: FormGroupProps) { - const { - className = styles.group, - children, - size = 'small', - advancedSettings = false, - isAdvanced = false, - ...otherProps - } = props; - - if (!advancedSettings && isAdvanced) { - return null; - } - - const childProps = isAdvanced ? { isAdvanced } : {}; - - return ( -
- {Children.map(children, (child) => { - if (!React.isValidElement(child)) { - return child; - } - - return React.cloneElement(child, childProps); - })} -
- ); -} - -export default FormGroup; diff --git a/frontend/src/Components/Form/FormInputButton.css.d.ts b/frontend/src/Components/Form/FormInputButton.css.d.ts deleted file mode 100644 index d469cdfe3..000000000 --- a/frontend/src/Components/Form/FormInputButton.css.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// This file is automatically generated. -// Please do not change this file! -interface CssExports { - 'button': string; - 'middleButton': string; -} -export const cssExports: CssExports; -export default cssExports; diff --git a/frontend/src/Components/Form/FormInputButton.js b/frontend/src/Components/Form/FormInputButton.js new file mode 100644 index 000000000..4b6491663 --- /dev/null +++ b/frontend/src/Components/Form/FormInputButton.js @@ -0,0 +1,54 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import classNames from 'classnames'; +import Button from 'Components/Link/Button'; +import SpinnerButton from 'Components/Link/SpinnerButton'; +import { kinds } from 'Helpers/Props'; +import styles from './FormInputButton.css'; + +function FormInputButton(props) { + const { + className, + canSpin, + isLastButton, + ...otherProps + } = props; + + if (canSpin) { + return ( + + ); + } + + return ( +