diff --git a/.annotaterb.yml b/.annotaterb.yml new file mode 100644 index 00000000000000..df8e92b24776a0 --- /dev/null +++ b/.annotaterb.yml @@ -0,0 +1,59 @@ +--- +:position: before +:position_in_additional_file_patterns: before +:position_in_class: before +:position_in_factory: before +:position_in_fixture: before +:position_in_routes: before +:position_in_serializer: before +:position_in_test: before +:classified_sort: true +:exclude_controllers: true +:exclude_factories: true +:exclude_fixtures: true +:exclude_helpers: true +:exclude_scaffolds: true +:exclude_serializers: true +:exclude_sti_subclasses: true +:exclude_tests: true +:force: false +:format_markdown: false +:format_rdoc: false +:format_yard: false +:frozen: false +:ignore_model_sub_dir: false +:ignore_unknown_models: false +:include_version: false +:show_complete_foreign_keys: false +:show_foreign_keys: false +:show_indexes: false +:simple_indexes: false +:sort: false +:timestamp: false +:trace: false +:with_comment: true +:with_column_comments: true +:with_table_comments: true +:active_admin: false +:command: +:debug: false +:hide_default_column_types: '' +:hide_limit_column_types: 'integer,boolean' +:ignore_columns: +:ignore_routes: +:models: true +:routes: false +:skip_on_db_migrate: false +:target_action: :do_annotations +:wrapper: +:wrapper_close: +:wrapper_open: +:classes_default_to_s: [] +:additional_file_patterns: [] +:model_dir: + - app/models +:require: [] +:root_dir: + - '' + +:show_check_constraints: false diff --git a/.devcontainer/compose.yaml b/.devcontainer/compose.yaml index 5c7263c87467d9..705d26e0ab28a0 100644 --- a/.devcontainer/compose.yaml +++ b/.devcontainer/compose.yaml @@ -69,7 +69,7 @@ services: hard: -1 libretranslate: - image: libretranslate/libretranslate:v1.6.1 + image: libretranslate/libretranslate:v1.6.2 restart: unless-stopped volumes: - lt-data:/home/libretranslate/.local diff --git a/.github/ISSUE_TEMPLATE/1.web_bug_report.yml b/.github/ISSUE_TEMPLATE/1.web_bug_report.yml index f897a7d7da434e..36b18a1287e548 100644 --- a/.github/ISSUE_TEMPLATE/1.web_bug_report.yml +++ b/.github/ISSUE_TEMPLATE/1.web_bug_report.yml @@ -1,7 +1,6 @@ name: Bug Report (Web Interface) description: There is a problem using Mastodon's web interface. -labels: ['status/to triage', 'area/web interface'] -type: Bug +labels: [bug, 'status/to triage', 'area/web interface'] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/2.server_bug_report.yml b/.github/ISSUE_TEMPLATE/2.server_bug_report.yml index a66f5c1076d504..0552e985f7b96a 100644 --- a/.github/ISSUE_TEMPLATE/2.server_bug_report.yml +++ b/.github/ISSUE_TEMPLATE/2.server_bug_report.yml @@ -1,8 +1,7 @@ name: Bug Report (server / API) description: | There is a problem with the HTTP server, REST API, ActivityPub interaction, etc. -labels: ['status/to triage'] -type: 'Bug' +labels: [bug, 'status/to triage'] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/3.troubleshooting.yml b/.github/ISSUE_TEMPLATE/3.troubleshooting.yml index eeb74b160b1040..7c6914bd7b1c81 100644 --- a/.github/ISSUE_TEMPLATE/3.troubleshooting.yml +++ b/.github/ISSUE_TEMPLATE/3.troubleshooting.yml @@ -1,8 +1,7 @@ name: Deployment troubleshooting description: | You are a server administrator and you are encountering a technical issue during installation, upgrade or operations of Mastodon. -labels: ['status/to triage'] -type: 'Troubleshooting' +labels: [bug, 'status/to triage'] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/4.feature_request.yml b/.github/ISSUE_TEMPLATE/4.feature_request.yml index 7146b4f8a3e436..2cabcf61e08ecc 100644 --- a/.github/ISSUE_TEMPLATE/4.feature_request.yml +++ b/.github/ISSUE_TEMPLATE/4.feature_request.yml @@ -1,6 +1,6 @@ name: Feature Request description: I have a suggestion -type: Suggestion +labels: [suggestion] body: - type: markdown attributes: diff --git a/.github/workflows/build-container-image.yml b/.github/workflows/build-container-image.yml index 03a0f5bf37b81b..6204319a6379fa 100644 --- a/.github/workflows/build-container-image.yml +++ b/.github/workflows/build-container-image.yml @@ -92,6 +92,7 @@ jobs: build-args: | MASTODON_VERSION_PRERELEASE=${{ inputs.version_prerelease }} MASTODON_VERSION_METADATA=${{ inputs.version_metadata }} + SOURCE_COMMIT=${{ github.sha }} platforms: ${{ inputs.platforms }} provenance: false builder: ${{ steps.buildx.outputs.name || steps.buildx-native.outputs.name }} diff --git a/.github/workflows/bundler-audit.yml b/.github/workflows/bundler-audit.yml index 2341d6e67f6241..fa28d28f740c45 100644 --- a/.github/workflows/bundler-audit.yml +++ b/.github/workflows/bundler-audit.yml @@ -36,4 +36,4 @@ jobs: bundler-cache: true - name: Run bundler-audit - run: bundle exec bundler-audit check --update + run: bin/bundler-audit check --update diff --git a/.github/workflows/check-i18n.yml b/.github/workflows/check-i18n.yml index 5a1c0519665873..4f87f0fe5f5928 100644 --- a/.github/workflows/check-i18n.yml +++ b/.github/workflows/check-i18n.yml @@ -18,7 +18,7 @@ permissions: jobs: check-i18n: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -35,18 +35,18 @@ jobs: git diff --exit-code - name: Check locale file normalization - run: bundle exec i18n-tasks check-normalized + run: bin/i18n-tasks check-normalized - name: Check for unused strings - run: bundle exec i18n-tasks unused + run: bin/i18n-tasks unused - name: Check for missing strings in English YML run: | - bundle exec i18n-tasks add-missing -l en + bin/i18n-tasks add-missing -l en git diff --exit-code - name: Check for wrong string interpolations - run: bundle exec i18n-tasks check-consistent-interpolations + run: bin/i18n-tasks check-consistent-interpolations - name: Check that all required locale files exist - run: bundle exec rake repo:check_locales_files + run: bin/rake repo:check_locales_files diff --git a/.github/workflows/crowdin-download-stable.yml b/.github/workflows/crowdin-download-stable.yml index 18911d49c2ff25..3d888f179ee9c2 100644 --- a/.github/workflows/crowdin-download-stable.yml +++ b/.github/workflows/crowdin-download-stable.yml @@ -47,7 +47,7 @@ jobs: uses: ./.github/actions/setup-ruby - name: Run i18n normalize task - run: bundle exec i18n-tasks normalize + run: bin/i18n-tasks normalize # Create or update the pull request - name: Create Pull Request diff --git a/.github/workflows/crowdin-download.yml b/.github/workflows/crowdin-download.yml index 02d8a949dec541..781fd5080ffaf5 100644 --- a/.github/workflows/crowdin-download.yml +++ b/.github/workflows/crowdin-download.yml @@ -49,7 +49,7 @@ jobs: uses: ./.github/actions/setup-ruby - name: Run i18n normalize task - run: bundle exec i18n-tasks normalize + run: bin/i18n-tasks normalize # Create or update the pull request - name: Create Pull Request diff --git a/.github/workflows/lint-haml.yml b/.github/workflows/lint-haml.yml index a1a9e99c902bfb..499be2010adc99 100644 --- a/.github/workflows/lint-haml.yml +++ b/.github/workflows/lint-haml.yml @@ -43,4 +43,4 @@ jobs: - name: Run haml-lint run: | echo "::add-matcher::.github/workflows/haml-lint-problem-matcher.json" - bundle exec haml-lint --reporter github + bin/haml-lint --reporter github diff --git a/.github/workflows/test-ruby.yml b/.github/workflows/test-ruby.yml index c05c8333b2048c..770cd72a1baea5 100644 --- a/.github/workflows/test-ruby.yml +++ b/.github/workflows/test-ruby.yml @@ -124,7 +124,6 @@ jobs: fail-fast: false matrix: ruby-version: - - '3.1' - '3.2' - '.ruby-version' steps: @@ -226,7 +225,6 @@ jobs: fail-fast: false matrix: ruby-version: - - '3.1' - '3.2' - '.ruby-version' steps: @@ -305,7 +303,6 @@ jobs: fail-fast: false matrix: ruby-version: - - '3.1' - '3.2' - '.ruby-version' @@ -422,7 +419,6 @@ jobs: fail-fast: false matrix: ruby-version: - - '3.1' - '3.2' - '.ruby-version' search-image: diff --git a/.nvmrc b/.nvmrc index 10fef252a9f178..8b84b727be4119 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -20.18 +22.11 diff --git a/.rubocop.yml b/.rubocop.yml index 965f56f3e703e6..ebeed6ea4900ca 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -8,7 +8,7 @@ AllCops: - lib/mastodon/migration_helpers.rb ExtraDetails: true NewCops: enable - TargetRubyVersion: 3.1 # Oldest supported ruby version + TargetRubyVersion: 3.2 # Oldest supported ruby version inherit_from: - .rubocop/layout.yml diff --git a/.ruby-version b/.ruby-version index fa7adc7ac72a28..9c25013dbb862f 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.3.5 +3.3.6 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fc5291d7226b5..240f6d15326ecf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,48 @@ All notable changes to this project will be documented in this file. +## [4.3.1] - 2024-10-21 + +### Added + +- Add more explicit explanations about author attribution and `fediverse:creator` (#32383 by @ClearlyClaire) +- Add ability to group follow notifications in WebUI, can be disabled in the column settings (#32520 by @renchap) +- Add back a 6 hours mute duration option (#32522 by @renchap) +- Add note about not changing ActiveRecord encryption secrets once they are set (#32413, #32476, #32512, and #32537 by @ClearlyClaire and @mjankowski) + +### Changed + +- Change translation feature to translate to selected regional variant (e.g. pt-BR) if available (#32428 by @c960657) + +### Removed + +- Remove ability to get embed code for remote posts (#32578 by @ClearlyClaire)\ + Getting the embed code is only reliable for local posts.\ + It never worked for non-Mastodon servers, and stopped working correctly with the changes made in 4.3.0.\ + We have therefore decided to remove the menu entry while we investigate solutions. + +### Fixed + +- Fix follow recommendation moderation page default language when using regional variant (#32580 by @ClearlyClaire) +- Fix column-settings spacing in local timeline in advanced view (#32567 by @lindwurm) +- Fix broken i18n in text welcome mailer tags area (#32571 by @mjankowski) +- Fix missing or incorrect cache-control headers for Streaming server (#32551 by @ThisIsMissEm) +- Fix only the first paragraph being displayed in some notifications (#32348 by @ClearlyClaire) +- Fix reblog icons on account media view (#32506 by @tribela) +- Fix Content-Security-Policy not allowing OpenStack SWIFT object storage URI (#32439 by @kenkiku1021) +- Fix back arrow pointing to the incorrect direction in RTL languages (#32485 by @renchap) +- Fix streaming server using `REDIS_USERNAME` instead of `REDIS_USER` (#32493 by @ThisIsMissEm) +- Fix follow recommendation carrousel scrolling on RTL layouts (#32462 and #32505 by @ClearlyClaire) +- Fix follow recommendation suppressions not applying immediately (#32392 by @ClearlyClaire) +- Fix language of push notifications (#32415 by @ClearlyClaire) +- Fix mute duration not being shown in list of muted accounts in web UI (#32388 by @ClearlyClaire) +- Fix “Mark every notification as read” not updating the read marker if scrolled down (#32385 by @ClearlyClaire) +- Fix “Mention” appearing for otherwise filtered posts (#32356 by @ClearlyClaire) +- Fix notification requests from suspended accounts still being listed (#32354 by @ClearlyClaire) +- Fix list edition modal styling (#32358 and #32367 by @ClearlyClaire and @vmstan) +- Fix 4 columns barely not fitting on 1920px screen (#32361 by @ClearlyClaire) +- Fix icon alignment in applications list (#32293 by @mjankowski) + ## [4.3.0] - 2024-10-08 The following changelog entries focus on changes visible to users, administrators, client developers or federated software developers, but there has also been a lot of code modernization, refactoring, and tooling work, in particular by @mjankowski. @@ -26,7 +68,7 @@ The following changelog entries focus on changes visible to users, administrator - `GET /api/v2/notifications`: https://docs.joinmastodon.org/methods/grouped_notifications/#get-grouped - `GET /api/v2/notifications/:group_key`: https://docs.joinmastodon.org/methods/grouped_notifications/#get-notification-group - `GET /api/v2/notifications/:group_key/accounts`: https://docs.joinmastodon.org/methods/grouped_notifications/#get-group-accounts - - `POST /api/v2/notifications/:group_key/dimsiss`: https://docs.joinmastodon.org/methods/grouped_notifications/#dismiss-group + - `POST /api/v2/notifications/:group_key/dismiss`: https://docs.joinmastodon.org/methods/grouped_notifications/#dismiss-group - `GET /api/v2/notifications/:unread_count`: https://docs.joinmastodon.org/methods/grouped_notifications/#unread-group-count - **Add notification policies, filtered notifications and notification requests** (#29366, #29529, #29433, #29565, #29567, #29572, #29575, #29588, #29646, #29652, #29658, #29666, #29693, #29699, #29737, #29706, #29570, #29752, #29810, #29826, #30114, #30251, #30559, #29868, #31008, #31011, #30996, #31149, #31220, #31222, #31225, #31242, #31262, #31250, #31273, #31310, #31316, #31322, #31329, #31324, #31331, #31343, #31342, #31309, #31358, #31378, #31406, #31256, #31456, #31419, #31457, #31508, #31540, #31541, #31723, #32062 and #32281 by @ClearlyClaire, @Gargron, @TheEssem, @mgmn, @oneiros, and @renchap)\ The old “Block notifications from non-followers”, “Block notifications from people you don't follow” and “Block direct messages from people you don't follow” notification settings have been replaced by a new set of settings found directly in the notification column.\ diff --git a/Dockerfile b/Dockerfile index a5e35025ae2f6f..d80a4e1555ff8a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.12 # This file is designed for production server deployment, not local development work # For a containerized local dev environment, see: https://github.com/mastodon/mastodon/blob/main/README.md#docker @@ -12,10 +12,10 @@ ARG BUILDPLATFORM=${BUILDPLATFORM} # Ruby image to use for base image, change with [--build-arg RUBY_VERSION="3.3.x"] # renovate: datasource=docker depName=docker.io/ruby -ARG RUBY_VERSION="3.3.5" +ARG RUBY_VERSION="3.3.6" # # Node version to use in base image, change with [--build-arg NODE_MAJOR_VERSION="20"] # renovate: datasource=node-version depName=node -ARG NODE_MAJOR_VERSION="20" +ARG NODE_MAJOR_VERSION="22" # Debian image to use for base image, change with [--build-arg DEBIAN_VERSION="bookworm"] ARG DEBIAN_VERSION="bookworm" # Node image to use for base image based on combined variables (ex: 20-bookworm-slim) @@ -29,6 +29,8 @@ FROM docker.io/ruby:${RUBY_VERSION}-slim-${DEBIAN_VERSION} AS ruby ARG MASTODON_VERSION_PRERELEASE="" # Append build metadata or fork information to version.rb [--build-arg MASTODON_VERSION_METADATA="pr-123456"] ARG MASTODON_VERSION_METADATA="" +# Will be available as Mastodon::Version.source_commit +ARG SOURCE_COMMIT="" # Allow Ruby on Rails to serve static files # See: https://docs.joinmastodon.org/admin/config/#rails_serve_static_files @@ -45,30 +47,31 @@ ARG GID="991" # Apply Mastodon build options based on options above ENV \ -# Apply Mastodon version information + # Apply Mastodon version information MASTODON_VERSION_PRERELEASE="${MASTODON_VERSION_PRERELEASE}" \ MASTODON_VERSION_METADATA="${MASTODON_VERSION_METADATA}" \ -# Apply Mastodon static files and YJIT options + SOURCE_COMMIT="${SOURCE_COMMIT}" \ + # Apply Mastodon static files and YJIT options RAILS_SERVE_STATIC_FILES=${RAILS_SERVE_STATIC_FILES} \ RUBY_YJIT_ENABLE=${RUBY_YJIT_ENABLE} \ -# Apply timezone + # Apply timezone TZ=${TZ} ENV \ -# Configure the IP to bind Mastodon to when serving traffic + # Configure the IP to bind Mastodon to when serving traffic BIND="0.0.0.0" \ -# Use production settings for Yarn, Node and related nodejs based tools + # Use production settings for Yarn, Node and related nodejs based tools NODE_ENV="production" \ -# Use production settings for Ruby on Rails + # Use production settings for Ruby on Rails RAILS_ENV="production" \ -# Add Ruby and Mastodon installation to the PATH + # Add Ruby and Mastodon installation to the PATH DEBIAN_FRONTEND="noninteractive" \ PATH="${PATH}:/opt/ruby/bin:/opt/mastodon/bin" \ -# Optimize jemalloc 5.x performance + # Optimize jemalloc 5.x performance MALLOC_CONF="narenas:2,background_thread:true,thp:never,dirty_decay_ms:1000,muzzy_decay_ms:0" \ -# Enable libvips, should not be changed + # Enable libvips, should not be changed MASTODON_USE_LIBVIPS=true \ -# Sidekiq will touch tmp/sidekiq_process_has_started_and_will_begin_processing_jobs to indicate it is ready. This can be used for a readiness check in Kubernetes + # Sidekiq will touch tmp/sidekiq_process_has_started_and_will_begin_processing_jobs to indicate it is ready. This can be used for a readiness check in Kubernetes MASTODON_SIDEKIQ_READY_FILENAME=sidekiq_process_has_started_and_will_begin_processing_jobs # Set default shell used for running commands @@ -79,14 +82,14 @@ ARG TARGETPLATFORM RUN echo "Target platform is $TARGETPLATFORM" RUN \ -# Remove automatic apt cache Docker cleanup scripts + # Remove automatic apt cache Docker cleanup scripts rm -f /etc/apt/apt.conf.d/docker-clean; \ -# Sets timezone + # Sets timezone echo "${TZ}" > /etc/localtime; \ -# Creates mastodon user/group and sets home directory + # Creates mastodon user/group and sets home directory groupadd -g "${GID}" mastodon; \ useradd -l -u "${UID}" -g "${GID}" -m -d /opt/mastodon mastodon; \ -# Creates /mastodon symlink to /opt/mastodon + # Creates /mastodon symlink to /opt/mastodon ln -s /opt/mastodon /mastodon; # Set /opt/mastodon as working directory @@ -94,28 +97,28 @@ WORKDIR /opt/mastodon # hadolint ignore=DL3008,DL3005 RUN \ -# Mount Apt cache and lib directories from Docker buildx caches ---mount=type=cache,id=apt-cache-${TARGETPLATFORM},target=/var/cache/apt,sharing=locked \ ---mount=type=cache,id=apt-lib-${TARGETPLATFORM},target=/var/lib/apt,sharing=locked \ -# Apt update & upgrade to check for security updates to Debian image + # Mount Apt cache and lib directories from Docker buildx caches + --mount=type=cache,id=apt-cache-${TARGETPLATFORM},target=/var/cache/apt,sharing=locked \ + --mount=type=cache,id=apt-lib-${TARGETPLATFORM},target=/var/lib/apt,sharing=locked \ + # Apt update & upgrade to check for security updates to Debian image apt-get update; \ apt-get dist-upgrade -yq; \ -# Install jemalloc, curl and other necessary components + # Install jemalloc, curl and other necessary components apt-get install -y --no-install-recommends \ - curl \ - file \ - libjemalloc2 \ - patchelf \ - procps \ - tini \ - tzdata \ - wget \ + curl \ + file \ + libjemalloc2 \ + patchelf \ + procps \ + tini \ + tzdata \ + wget \ ; \ -# Patch Ruby to use jemalloc + # Patch Ruby to use jemalloc patchelf --add-needed libjemalloc.so.2 /usr/local/bin/ruby; \ -# Discard patchelf after use + # Discard patchelf after use apt-get purge -y \ - patchelf \ + patchelf \ ; # Create temporary build layer from base image @@ -132,56 +135,56 @@ ARG TARGETPLATFORM # hadolint ignore=DL3008 RUN \ -# Mount Apt cache and lib directories from Docker buildx caches ---mount=type=cache,id=apt-cache-${TARGETPLATFORM},target=/var/cache/apt,sharing=locked \ ---mount=type=cache,id=apt-lib-${TARGETPLATFORM},target=/var/lib/apt,sharing=locked \ -# Install build tools and bundler dependencies from APT + # Mount Apt cache and lib directories from Docker buildx caches + --mount=type=cache,id=apt-cache-${TARGETPLATFORM},target=/var/cache/apt,sharing=locked \ + --mount=type=cache,id=apt-lib-${TARGETPLATFORM},target=/var/lib/apt,sharing=locked \ + # Install build tools and bundler dependencies from APT apt-get install -y --no-install-recommends \ - autoconf \ - automake \ - build-essential \ - cmake \ - git \ - libgdbm-dev \ - libglib2.0-dev \ - libgmp-dev \ - libicu-dev \ - libidn-dev \ - libpq-dev \ - libssl-dev \ - libtool \ - meson \ - nasm \ - pkg-config \ - shared-mime-info \ - xz-utils \ - # libvips components - libcgif-dev \ - libexif-dev \ - libexpat1-dev \ - libgirepository1.0-dev \ - libheif-dev \ - libimagequant-dev \ - libjpeg62-turbo-dev \ - liblcms2-dev \ - liborc-dev \ - libspng-dev \ - libtiff-dev \ - libwebp-dev \ + autoconf \ + automake \ + build-essential \ + cmake \ + git \ + libgdbm-dev \ + libglib2.0-dev \ + libgmp-dev \ + libicu-dev \ + libidn-dev \ + libpq-dev \ + libssl-dev \ + libtool \ + meson \ + nasm \ + pkg-config \ + shared-mime-info \ + xz-utils \ + # libvips components + libcgif-dev \ + libexif-dev \ + libexpat1-dev \ + libgirepository1.0-dev \ + libheif-dev \ + libimagequant-dev \ + libjpeg62-turbo-dev \ + liblcms2-dev \ + liborc-dev \ + libspng-dev \ + libtiff-dev \ + libwebp-dev \ # ffmpeg components - libdav1d-dev \ - liblzma-dev \ - libmp3lame-dev \ - libopus-dev \ - libsnappy-dev \ - libvorbis-dev \ - libvpx-dev \ - libx264-dev \ - libx265-dev \ + libdav1d-dev \ + liblzma-dev \ + libmp3lame-dev \ + libopus-dev \ + libsnappy-dev \ + libvorbis-dev \ + libvpx-dev \ + libx264-dev \ + libx265-dev \ ; RUN \ -# Configure Corepack + # Configure Corepack rm /usr/local/bin/yarn*; \ corepack enable; \ corepack prepare --activate; @@ -191,7 +194,7 @@ FROM build AS libvips # libvips version to compile, change with [--build-arg VIPS_VERSION="8.15.2"] # renovate: datasource=github-releases depName=libvips packageName=libvips/libvips -ARG VIPS_VERSION=8.15.3 +ARG VIPS_VERSION=8.16.0 # libvips download URL, change with [--build-arg VIPS_URL="https://github.com/libvips/libvips/releases/download"] ARG VIPS_URL=https://github.com/libvips/libvips/releases/download @@ -228,28 +231,28 @@ WORKDIR /usr/local/ffmpeg/src/ffmpeg-${FFMPEG_VERSION} # Configure and compile ffmpeg RUN \ ./configure \ - --prefix=/usr/local/ffmpeg \ - --toolchain=hardened \ - --disable-debug \ - --disable-devices \ - --disable-doc \ - --disable-ffplay \ - --disable-network \ - --disable-static \ - --enable-ffmpeg \ - --enable-ffprobe \ - --enable-gpl \ - --enable-libdav1d \ - --enable-libmp3lame \ - --enable-libopus \ - --enable-libsnappy \ - --enable-libvorbis \ - --enable-libvpx \ - --enable-libwebp \ - --enable-libx264 \ - --enable-libx265 \ - --enable-shared \ - --enable-version3 \ + --prefix=/usr/local/ffmpeg \ + --toolchain=hardened \ + --disable-debug \ + --disable-devices \ + --disable-doc \ + --disable-ffplay \ + --disable-network \ + --disable-static \ + --enable-ffmpeg \ + --enable-ffprobe \ + --enable-gpl \ + --enable-libdav1d \ + --enable-libmp3lame \ + --enable-libopus \ + --enable-libsnappy \ + --enable-libvorbis \ + --enable-libvpx \ + --enable-libwebp \ + --enable-libx264 \ + --enable-libx265 \ + --enable-shared \ + --enable-version3 \ ; \ make -j$(nproc); \ make install; @@ -263,17 +266,17 @@ ARG TARGETPLATFORM COPY Gemfile* /opt/mastodon/ RUN \ -# Mount Ruby Gem caches ---mount=type=cache,id=gem-cache-${TARGETPLATFORM},target=/usr/local/bundle/cache/,sharing=locked \ -# Configure bundle to prevent changes to Gemfile and Gemfile.lock + # Mount Ruby Gem caches + --mount=type=cache,id=gem-cache-${TARGETPLATFORM},target=/usr/local/bundle/cache/,sharing=locked \ + # Configure bundle to prevent changes to Gemfile and Gemfile.lock bundle config set --global frozen "true"; \ -# Configure bundle to not cache downloaded Gems + # Configure bundle to not cache downloaded Gems bundle config set --global cache_all "false"; \ -# Configure bundle to only process production Gems + # Configure bundle to only process production Gems bundle config set --local without "development test"; \ -# Configure bundle to not warn about root user + # Configure bundle to not warn about root user bundle config set silence_root_warning "true"; \ -# Download and install required Gems + # Download and install required Gems bundle install -j"$(nproc)"; # Create temporary node specific build layer from build layer @@ -288,9 +291,9 @@ COPY .yarn /opt/mastodon/.yarn # hadolint ignore=DL3008 RUN \ ---mount=type=cache,id=corepack-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/corepack,sharing=locked \ ---mount=type=cache,id=yarn-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/yarn,sharing=locked \ -# Install Node packages + --mount=type=cache,id=corepack-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/corepack,sharing=locked \ + --mount=type=cache,id=yarn-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/yarn,sharing=locked \ + # Install Node packages yarn workspaces focus --production @mastodon/mastodon; # Create temporary assets build layer from build layer @@ -311,10 +314,10 @@ ARG TARGETPLATFORM RUN \ ldconfig; \ -# Use Ruby on Rails to create Mastodon assets + # Use Ruby on Rails to create Mastodon assets SECRET_KEY_BASE_DUMMY=1 \ bundle exec rails assets:precompile; \ -# Cleanup temporary files + # Cleanup temporary files rm -fr /opt/mastodon/tmp; # Prep final Mastodon Ruby layer @@ -324,49 +327,49 @@ ARG TARGETPLATFORM # hadolint ignore=DL3008 RUN \ -# Mount Apt cache and lib directories from Docker buildx caches ---mount=type=cache,id=apt-cache-${TARGETPLATFORM},target=/var/cache/apt,sharing=locked \ ---mount=type=cache,id=apt-lib-${TARGETPLATFORM},target=/var/lib/apt,sharing=locked \ -# Mount Corepack and Yarn caches from Docker buildx caches ---mount=type=cache,id=corepack-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/corepack,sharing=locked \ ---mount=type=cache,id=yarn-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/yarn,sharing=locked \ -# Apt update install non-dev versions of necessary components + # Mount Apt cache and lib directories from Docker buildx caches + --mount=type=cache,id=apt-cache-${TARGETPLATFORM},target=/var/cache/apt,sharing=locked \ + --mount=type=cache,id=apt-lib-${TARGETPLATFORM},target=/var/lib/apt,sharing=locked \ + # Mount Corepack and Yarn caches from Docker buildx caches + --mount=type=cache,id=corepack-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/corepack,sharing=locked \ + --mount=type=cache,id=yarn-cache-${TARGETPLATFORM},target=/usr/local/share/.cache/yarn,sharing=locked \ + # Apt update install non-dev versions of necessary components apt-get install -y --no-install-recommends \ - libexpat1 \ - libglib2.0-0 \ - libicu72 \ - libidn12 \ - libpq5 \ - libreadline8 \ - libssl3 \ - libyaml-0-2 \ + libexpat1 \ + libglib2.0-0 \ + libicu72 \ + libidn12 \ + libpq5 \ + libreadline8 \ + libssl3 \ + libyaml-0-2 \ # libvips components - libcgif0 \ - libexif12 \ - libheif1 \ - libimagequant0 \ - libjpeg62-turbo \ - liblcms2-2 \ - liborc-0.4-0 \ - libspng0 \ - libtiff6 \ - libwebp7 \ - libwebpdemux2 \ - libwebpmux3 \ + libcgif0 \ + libexif12 \ + libheif1 \ + libimagequant0 \ + libjpeg62-turbo \ + liblcms2-2 \ + liborc-0.4-0 \ + libspng0 \ + libtiff6 \ + libwebp7 \ + libwebpdemux2 \ + libwebpmux3 \ # ffmpeg components - libdav1d6 \ - libmp3lame0 \ - libopencore-amrnb0 \ - libopencore-amrwb0 \ - libopus0 \ - libsnappy1v5 \ - libtheora0 \ - libvorbis0a \ - libvorbisenc2 \ - libvorbisfile3 \ - libvpx7 \ - libx264-164 \ - libx265-199 \ + libdav1d6 \ + libmp3lame0 \ + libopencore-amrnb0 \ + libopencore-amrwb0 \ + libopus0 \ + libsnappy1v5 \ + libtheora0 \ + libvorbis0a \ + libvorbisenc2 \ + libvorbisfile3 \ + libvpx7 \ + libx264-164 \ + libx265-199 \ ; # Copy Mastodon sources into final layer @@ -386,7 +389,7 @@ COPY --from=ffmpeg /usr/local/ffmpeg/lib /usr/local/lib RUN \ ldconfig; \ -# Smoketest media processors + # Smoketest media processors vips -v; \ ffmpeg -version; \ ffprobe -version; @@ -396,10 +399,10 @@ RUN \ bundle exec bootsnap precompile --gemfile app/ lib/; RUN \ -# Pre-create and chown system volume to Mastodon user + # Pre-create and chown system volume to Mastodon user mkdir -p /opt/mastodon/public/system; \ chown mastodon:mastodon /opt/mastodon/public/system; \ -# Set Mastodon user as owner of tmp folder + # Set Mastodon user as owner of tmp folder chown -R mastodon:mastodon /opt/mastodon/tmp; # Set the running user for resulting container diff --git a/Gemfile b/Gemfile index bcb19421ab9afe..6abb075c1ce613 100644 --- a/Gemfile +++ b/Gemfile @@ -1,12 +1,12 @@ # frozen_string_literal: true source 'https://rubygems.org' -ruby '>= 3.1.0' +ruby '>= 3.2.0' gem 'propshaft' gem 'puma', '~> 6.3' gem 'rack', '~> 2.2.7' -gem 'rails', '~> 7.1.1' +gem 'rails', '~> 7.2.0' gem 'thor', '~> 1.2' gem 'dotenv' @@ -16,16 +16,16 @@ gem 'pghero' gem 'aws-sdk-s3', '~> 1.123', require: false gem 'blurhash', '~> 0.1' -gem 'fog-core', '<= 2.5.0' +gem 'fog-core', '<= 2.6.0' gem 'fog-openstack', '~> 1.0', require: false +gem 'jd-paperclip-azure', '~> 3.0', require: false gem 'kt-paperclip', '~> 7.2' -gem 'md-paperclip-azure', '~> 2.2', require: false gem 'ruby-vips', '~> 2.2', require: false gem 'active_model_serializers', '~> 0.10' gem 'addressable', '~> 2.8' gem 'bootsnap', '~> 1.18.0', require: false -gem 'browser', '< 6' # https://github.com/fnando/browser/issues/543 +gem 'browser' gem 'charlock_holmes', '~> 0.7.7' gem 'chewy', '~> 7.3' gem 'devise', '~> 4.9' @@ -47,13 +47,14 @@ gem 'color_diff', '~> 0.1' gem 'csv', '~> 3.2' gem 'discard', '~> 1.2' gem 'doorkeeper', '~> 5.6' +gem 'faraday-httpclient' gem 'fast_blank', '~> 1.0' gem 'fastimage' gem 'hiredis', '~> 0.6' gem 'htmlentities', '~> 4.3' gem 'http', '~> 5.2.0' gem 'http_accept_language', '~> 2.1' -gem 'httplog', '~> 1.7.0' +gem 'httplog', '~> 1.7.0', require: false gem 'i18n' gem 'idn-ruby', require: 'idn' gem 'inline_svg' @@ -61,7 +62,8 @@ gem 'irb', '~> 1.8' gem 'kaminari', '~> 1.2' gem 'link_header', '~> 0.0' gem 'mario-redis-lock', '~> 1.2', require: 'redis_lock' -gem 'mime-types', '~> 3.5.0', require: 'mime/types/columnar' +gem 'mime-types', '~> 3.6.0', require: 'mime/types/columnar' +gem 'mutex_m' gem 'nokogiri', '~> 1.15' gem 'oj', '~> 3.14' gem 'ox', '~> 2.14' @@ -111,8 +113,8 @@ group :opentelemetry do gem 'opentelemetry-instrumentation-http_client', '~> 0.22.3', require: false gem 'opentelemetry-instrumentation-net_http', '~> 0.22.4', require: false gem 'opentelemetry-instrumentation-pg', '~> 0.29.0', require: false - gem 'opentelemetry-instrumentation-rack', '~> 0.24.1', require: false - gem 'opentelemetry-instrumentation-rails', '~> 0.31.0', require: false + gem 'opentelemetry-instrumentation-rack', '~> 0.25.0', require: false + gem 'opentelemetry-instrumentation-rails', '~> 0.33.0', require: false gem 'opentelemetry-instrumentation-redis', '~> 0.25.3', require: false gem 'opentelemetry-instrumentation-sidekiq', '~> 0.25.2', require: false gem 'opentelemetry-sdk', '~> 1.4', require: false @@ -170,7 +172,7 @@ group :development do gem 'rubocop-rspec_rails', require: false # Annotates modules with schema - gem 'annotate', '~> 3.2' + gem 'annotaterb', '~> 4.13' # Enhanced error message pages for development gem 'better_errors', '~> 2.9' @@ -220,7 +222,7 @@ gem 'concurrent-ruby', require: false gem 'connection_pool', require: false gem 'xorcist', '~> 1.1' -gem 'net-http', '~> 0.4.0' +gem 'net-http', '~> 0.5.0' gem 'rubyzip', '~> 2.3' gem 'hcaptcha', '~> 7.1' diff --git a/Gemfile.lock b/Gemfile.lock index d1ee8e0fa8eacd..1cf4930faab89a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -10,122 +10,111 @@ GIT GEM remote: https://rubygems.org/ specs: - actioncable (7.1.4.1) - actionpack (= 7.1.4.1) - activesupport (= 7.1.4.1) + actioncable (7.2.2.1) + actionpack (= 7.2.2.1) + activesupport (= 7.2.2.1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) zeitwerk (~> 2.6) - actionmailbox (7.1.4.1) - actionpack (= 7.1.4.1) - activejob (= 7.1.4.1) - activerecord (= 7.1.4.1) - activestorage (= 7.1.4.1) - activesupport (= 7.1.4.1) - mail (>= 2.7.1) - net-imap - net-pop - net-smtp - actionmailer (7.1.4.1) - actionpack (= 7.1.4.1) - actionview (= 7.1.4.1) - activejob (= 7.1.4.1) - activesupport (= 7.1.4.1) - mail (~> 2.5, >= 2.5.4) - net-imap - net-pop - net-smtp + actionmailbox (7.2.2.1) + actionpack (= 7.2.2.1) + activejob (= 7.2.2.1) + activerecord (= 7.2.2.1) + activestorage (= 7.2.2.1) + activesupport (= 7.2.2.1) + mail (>= 2.8.0) + actionmailer (7.2.2.1) + actionpack (= 7.2.2.1) + actionview (= 7.2.2.1) + activejob (= 7.2.2.1) + activesupport (= 7.2.2.1) + mail (>= 2.8.0) rails-dom-testing (~> 2.2) - actionpack (7.1.4.1) - actionview (= 7.1.4.1) - activesupport (= 7.1.4.1) + actionpack (7.2.2.1) + actionview (= 7.2.2.1) + activesupport (= 7.2.2.1) nokogiri (>= 1.8.5) racc - rack (>= 2.2.4) + rack (>= 2.2.4, < 3.2) rack-session (>= 1.0.1) rack-test (>= 0.6.3) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) - actiontext (7.1.4.1) - actionpack (= 7.1.4.1) - activerecord (= 7.1.4.1) - activestorage (= 7.1.4.1) - activesupport (= 7.1.4.1) + useragent (~> 0.16) + actiontext (7.2.2.1) + actionpack (= 7.2.2.1) + activerecord (= 7.2.2.1) + activestorage (= 7.2.2.1) + activesupport (= 7.2.2.1) globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (7.1.4.1) - activesupport (= 7.1.4.1) + actionview (7.2.2.1) + activesupport (= 7.2.2.1) builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) - active_model_serializers (0.10.14) + active_model_serializers (0.10.15) actionpack (>= 4.1) activemodel (>= 4.1) case_transform (>= 0.2) jsonapi-renderer (>= 0.1.1.beta1, < 0.3) - activejob (7.1.4.1) - activesupport (= 7.1.4.1) + activejob (7.2.2.1) + activesupport (= 7.2.2.1) globalid (>= 0.3.6) - activemodel (7.1.4.1) - activesupport (= 7.1.4.1) - activerecord (7.1.4.1) - activemodel (= 7.1.4.1) - activesupport (= 7.1.4.1) + activemodel (7.2.2.1) + activesupport (= 7.2.2.1) + activerecord (7.2.2.1) + activemodel (= 7.2.2.1) + activesupport (= 7.2.2.1) timeout (>= 0.4.0) - activestorage (7.1.4.1) - actionpack (= 7.1.4.1) - activejob (= 7.1.4.1) - activerecord (= 7.1.4.1) - activesupport (= 7.1.4.1) + activestorage (7.2.2.1) + actionpack (= 7.2.2.1) + activejob (= 7.2.2.1) + activerecord (= 7.2.2.1) + activesupport (= 7.2.2.1) marcel (~> 1.0) - activesupport (7.1.4.1) + activesupport (7.2.2.1) base64 + benchmark (>= 0.3) bigdecimal - concurrent-ruby (~> 1.0, >= 1.0.2) + concurrent-ruby (~> 1.0, >= 1.3.1) connection_pool (>= 2.2.5) drb i18n (>= 1.6, < 2) + logger (>= 1.4.2) minitest (>= 5.1) - mutex_m - tzinfo (~> 2.0) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) addressable (2.8.7) public_suffix (>= 2.0.2, < 7.0) aes_key_wrap (1.1.0) android_key_attestation (0.3.0) - annotate (3.2.0) - activerecord (>= 3.2, < 8.0) - rake (>= 10.4, < 14.0) + annotaterb (4.13.0) ast (2.4.2) attr_required (1.0.2) - awrence (1.2.1) aws-eventstream (1.3.0) - aws-partitions (1.983.0) - aws-sdk-core (3.209.1) + aws-partitions (1.1015.0) + aws-sdk-core (3.214.0) aws-eventstream (~> 1, >= 1.3.0) - aws-partitions (~> 1, >= 1.651.0) + aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) jmespath (~> 1, >= 1.6.1) - aws-sdk-kms (1.94.0) - aws-sdk-core (~> 3, >= 3.207.0) + aws-sdk-kms (1.96.0) + aws-sdk-core (~> 3, >= 3.210.0) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.167.0) - aws-sdk-core (~> 3, >= 3.207.0) + aws-sdk-s3 (1.175.0) + aws-sdk-core (~> 3, >= 3.210.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) - aws-sigv4 (1.10.0) + aws-sigv4 (1.10.1) aws-eventstream (~> 1, >= 1.0.2) - azure-storage-blob (2.0.3) - azure-storage-common (~> 2.0) - nokogiri (~> 1, >= 1.10.8) - azure-storage-common (2.0.4) - faraday (~> 1.0) - faraday_middleware (~> 1.0, >= 1.0.0.rc1) - net-http-persistent (~> 4.0) - nokogiri (~> 1, >= 1.10.8) + azure-blob (0.5.3) + rexml base64 (0.2.0) bcp47_spec (0.2.1) bcrypt (3.1.20) + benchmark (0.4.0) better_errors (2.10.1) erubi (>= 1.0.0) rack (>= 0.9.0) @@ -137,9 +126,9 @@ GEM blurhash (0.1.8) bootsnap (1.18.4) msgpack (~> 1.2) - brakeman (6.2.1) + brakeman (6.2.2) racc - browser (5.3.1) + browser (6.1.0) brpoplpush-redis_script (0.1.3) concurrent-ruby (~> 1.0, >= 1.0.5) redis (>= 1.0, < 6) @@ -179,14 +168,14 @@ GEM bigdecimal rexml crass (1.0.6) - css_parser (1.19.0) + css_parser (1.19.1) addressable csv (3.3.0) database_cleaner-active_record (2.2.0) activerecord (>= 5.a) database_cleaner-core (~> 2.0.0) database_cleaner-core (2.0.1) - date (3.3.4) + date (3.4.0) debug (1.9.2) irb (~> 1.10) reline (>= 0.3.8) @@ -197,20 +186,20 @@ GEM railties (>= 4.1.0) responders warden (~> 1.2.3) - devise-two-factor (6.0.0) - activesupport (~> 7.0) + devise-two-factor (6.1.0) + activesupport (>= 7.0, < 8.1) devise (~> 4.0) - railties (~> 7.0) + railties (>= 7.0, < 8.1) rotp (~> 6.0) devise_pam_authenticatable2 (9.2.0) devise (>= 4.0.0) rpam2 (~> 4.0) diff-lcs (1.5.1) - discard (1.3.0) - activerecord (>= 4.2, < 8) + discard (1.4.0) + activerecord (>= 4.2, < 9.0) docile (1.4.1) domain_name (0.6.20240107) - doorkeeper (5.7.1) + doorkeeper (5.8.0) railties (>= 5) dotenv (3.1.4) drb (2.2.1) @@ -231,38 +220,21 @@ GEM erubi (1.13.0) et-orbi (1.2.11) tzinfo - excon (0.111.0) + excon (0.112.0) fabrication (2.31.0) - faker (3.4.2) + faker (3.5.1) i18n (>= 1.8.11, < 2) - faraday (1.10.3) - faraday-em_http (~> 1.0) - faraday-em_synchrony (~> 1.0) - faraday-excon (~> 1.1) - faraday-httpclient (~> 1.0) - faraday-multipart (~> 1.0) - faraday-net_http (~> 1.0) - faraday-net_http_persistent (~> 1.0) - faraday-patron (~> 1.0) - faraday-rack (~> 1.0) - faraday-retry (~> 1.0) - ruby2_keywords (>= 0.0.4) - faraday-em_http (1.0.0) - faraday-em_synchrony (1.0.0) - faraday-excon (1.1.0) - faraday-httpclient (1.0.1) - faraday-multipart (1.0.4) - multipart-post (~> 2) - faraday-net_http (1.0.2) - faraday-net_http_persistent (1.2.0) - faraday-patron (1.0.0) - faraday-rack (1.0.0) - faraday-retry (1.0.3) - faraday_middleware (1.2.0) - faraday (~> 1.0) + faraday (2.12.0) + faraday-net_http (>= 2.0, < 3.4) + json + logger + faraday-httpclient (2.0.1) + httpclient (>= 2.2) + faraday-net_http (3.3.0) + net-http fast_blank (1.0.1) fastimage (2.3.1) - ffi (1.16.3) + ffi (1.17.0) ffi-compiler (1.3.2) ffi (>= 1.15.5) rake @@ -350,8 +322,12 @@ GEM irb (1.14.1) rdoc (>= 4.0.0) reline (>= 0.4.2) + jd-paperclip-azure (3.0.0) + addressable (~> 2.5) + azure-blob (~> 0.5.2) + hashie (~> 5.0) jmespath (1.6.2) - json (2.7.2) + json (2.8.1) json-canonicalization (1.0.0) json-jwt (1.15.3.1) activesupport (>= 4.2) @@ -366,13 +342,15 @@ GEM rack (>= 2.2, < 4) rdf (~> 3.3) rexml (~> 3.2) - json-ld-preloaded (3.3.0) + json-ld-preloaded (3.3.1) json-ld (~> 3.3) rdf (~> 3.3) - json-schema (5.0.1) + json-schema (5.1.1) addressable (~> 2.8) + bigdecimal (~> 3.1) jsonapi-renderer (0.2.2) - jwt (2.7.1) + jwt (2.9.3) + base64 kaminari (1.2.2) activesupport (>= 4.1.0) kaminari-actionview (= 1.2.2) @@ -406,13 +384,13 @@ GEM llhttp-ffi (0.5.0) ffi-compiler (~> 1.0) rake (~> 13.0) - logger (1.6.1) + logger (1.6.3) lograge (0.14.0) actionpack (>= 4) activesupport (>= 4) railties (>= 4) request_store (~> 1.0) - loofah (2.22.0) + loofah (2.23.1) crass (~> 1.0.2) nokogiri (>= 1.12.0) mail (2.8.1) @@ -424,26 +402,20 @@ GEM mario-redis-lock (1.2.1) redis (>= 3.0.5) matrix (0.4.2) - md-paperclip-azure (2.2.0) - addressable (~> 2.5) - azure-storage-blob (~> 2.0.1) - hashie (~> 5.0) memory_profiler (1.1.0) - mime-types (3.5.2) + mime-types (3.6.0) + logger mime-types-data (~> 3.2015) - mime-types-data (3.2024.0820) + mime-types-data (3.2024.1105) mini_mime (1.1.5) - mini_portile2 (2.8.7) - minitest (5.25.1) - msgpack (1.7.2) + mini_portile2 (2.8.8) + minitest (5.25.4) + msgpack (1.7.5) multi_json (1.15.0) - multipart-post (2.4.1) - mutex_m (0.2.0) - net-http (0.4.1) + mutex_m (0.3.0) + net-http (0.5.0) uri - net-http-persistent (4.0.2) - connection_pool (~> 2.2) - net-imap (0.4.15) + net-imap (0.5.1) date net-protocol net-ldap (0.19.0) @@ -453,11 +425,11 @@ GEM timeout net-smtp (0.5.0) net-protocol - nio4r (2.7.3) - nokogiri (1.16.7) + nio4r (2.7.4) + nokogiri (1.17.2) mini_portile2 (~> 2.8.2) racc (~> 1.4) - oj (3.16.6) + oj (3.16.7) bigdecimal (>= 3.0) ostruct (>= 0.2) omniauth (2.1.2) @@ -501,27 +473,27 @@ GEM opentelemetry-common (~> 0.20) opentelemetry-sdk (~> 1.2) opentelemetry-semantic_conventions - opentelemetry-helpers-sql-obfuscation (0.2.0) + opentelemetry-helpers-sql-obfuscation (0.2.1) opentelemetry-common (~> 0.21) - opentelemetry-instrumentation-action_mailer (0.1.0) + opentelemetry-instrumentation-action_mailer (0.2.0) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-active_support (~> 0.1) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-action_pack (0.9.0) + opentelemetry-instrumentation-action_pack (0.10.0) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) opentelemetry-instrumentation-rack (~> 0.21) - opentelemetry-instrumentation-action_view (0.7.2) + opentelemetry-instrumentation-action_view (0.7.3) opentelemetry-api (~> 1.0) - opentelemetry-instrumentation-active_support (~> 0.1) + opentelemetry-instrumentation-active_support (~> 0.6) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-active_job (0.7.7) + opentelemetry-instrumentation-active_job (0.7.8) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) opentelemetry-instrumentation-active_model_serializers (0.20.2) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-active_record (0.7.3) + opentelemetry-instrumentation-active_record (0.8.1) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) opentelemetry-instrumentation-active_support (0.6.0) @@ -534,35 +506,35 @@ GEM opentelemetry-instrumentation-concurrent_ruby (0.21.4) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-excon (0.22.4) + opentelemetry-instrumentation-excon (0.22.5) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-faraday (0.24.6) + opentelemetry-instrumentation-faraday (0.24.7) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-http (0.23.4) + opentelemetry-instrumentation-http (0.23.5) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-http_client (0.22.7) + opentelemetry-instrumentation-http_client (0.22.8) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-net_http (0.22.7) + opentelemetry-instrumentation-net_http (0.22.8) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-pg (0.29.0) + opentelemetry-instrumentation-pg (0.29.1) opentelemetry-api (~> 1.0) opentelemetry-helpers-sql-obfuscation opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-rack (0.24.6) + opentelemetry-instrumentation-rack (0.25.0) opentelemetry-api (~> 1.0) opentelemetry-instrumentation-base (~> 0.22.1) - opentelemetry-instrumentation-rails (0.31.2) + opentelemetry-instrumentation-rails (0.33.1) opentelemetry-api (~> 1.0) - opentelemetry-instrumentation-action_mailer (~> 0.1.0) - opentelemetry-instrumentation-action_pack (~> 0.9.0) + opentelemetry-instrumentation-action_mailer (~> 0.2.0) + opentelemetry-instrumentation-action_pack (~> 0.10.0) opentelemetry-instrumentation-action_view (~> 0.7.0) opentelemetry-instrumentation-active_job (~> 0.7.0) - opentelemetry-instrumentation-active_record (~> 0.7.0) + opentelemetry-instrumentation-active_record (~> 0.8.0) opentelemetry-instrumentation-active_support (~> 0.6.0) opentelemetry-instrumentation-base (~> 0.22.1) opentelemetry-instrumentation-redis (0.25.7) @@ -581,16 +553,16 @@ GEM opentelemetry-semantic_conventions (1.10.1) opentelemetry-api (~> 1.0) orm_adapter (0.5.0) - ostruct (0.6.0) + ostruct (0.6.1) ox (2.14.18) parallel (1.26.3) - parser (3.3.5.0) + parser (3.3.6.0) ast (~> 2.4.1) racc parslet (2.0.0) pastel (0.8.0) tty-color (~> 0.5) - pg (1.5.8) + pg (1.5.9) pghero (3.6.1) activerecord (>= 6.1) premailer (1.27.0) @@ -606,10 +578,10 @@ GEM activesupport (>= 7.0.0) rack railties (>= 7.0.0) - psych (5.1.2) + psych (5.2.0) stringio public_suffix (6.0.1) - puma (6.4.3) + puma (6.5.0) nio4r (~> 2.0) pundit (2.4.0) activesupport (>= 3.0.0) @@ -638,20 +610,20 @@ GEM rackup (1.0.0) rack (< 3) webrick - rails (7.1.4.1) - actioncable (= 7.1.4.1) - actionmailbox (= 7.1.4.1) - actionmailer (= 7.1.4.1) - actionpack (= 7.1.4.1) - actiontext (= 7.1.4.1) - actionview (= 7.1.4.1) - activejob (= 7.1.4.1) - activemodel (= 7.1.4.1) - activerecord (= 7.1.4.1) - activestorage (= 7.1.4.1) - activesupport (= 7.1.4.1) + rails (7.2.2.1) + actioncable (= 7.2.2.1) + actionmailbox (= 7.2.2.1) + actionmailer (= 7.2.2.1) + actionpack (= 7.2.2.1) + actiontext (= 7.2.2.1) + actionview (= 7.2.2.1) + activejob (= 7.2.2.1) + activemodel (= 7.2.2.1) + activerecord (= 7.2.2.1) + activestorage (= 7.2.2.1) + activesupport (= 7.2.2.1) bundler (>= 1.15.0) - railties (= 7.1.4.1) + railties (= 7.2.2.1) rails-controller-testing (1.0.5) actionpack (>= 5.0.1.rc1) actionview (>= 5.0.1.rc1) @@ -660,16 +632,16 @@ GEM activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.6.0) + rails-html-sanitizer (1.6.2) loofah (~> 2.21) - nokogiri (~> 1.14) - rails-i18n (7.0.9) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + rails-i18n (7.0.10) i18n (>= 0.7, < 2) railties (>= 6.0.0, < 8) - railties (7.1.4.1) - actionpack (= 7.1.4.1) - activesupport (= 7.1.4.1) - irb + railties (7.2.2.1) + actionpack (= 7.2.2.1) + activesupport (= 7.2.2.1) + irb (~> 1.13) rackup (>= 1.0.0) rake (>= 12.2) thor (~> 1.0, >= 1.2.2) @@ -691,16 +663,16 @@ GEM redlock (1.3.2) redis (>= 3.0.0, < 6.0) regexp_parser (2.9.2) - reline (0.5.10) + reline (0.5.11) io-console (~> 0.5) request_store (1.6.0) rack (>= 1.4) responders (3.1.1) actionpack (>= 5.2) railties (>= 5.2) - rexml (3.3.8) + rexml (3.3.9) rotp (6.3.0) - rouge (4.3.0) + rouge (4.5.1) rpam2 (4.0.2) rqrcode (2.2.0) chunky_png (~> 1.0) @@ -710,17 +682,17 @@ GEM rspec-core (~> 3.13.0) rspec-expectations (~> 3.13.0) rspec-mocks (~> 3.13.0) - rspec-core (3.13.1) + rspec-core (3.13.2) rspec-support (~> 3.13.0) - rspec-expectations (3.13.2) + rspec-expectations (3.13.3) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) rspec-github (2.4.0) rspec-core (~> 3.0) - rspec-mocks (3.13.1) + rspec-mocks (3.13.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-rails (7.0.1) + rspec-rails (7.1.0) actionpack (>= 7.0) activesupport (>= 7.0) railties (>= 7.0) @@ -751,17 +723,17 @@ GEM rubocop-performance (1.22.1) rubocop (>= 1.48.1, < 2.0) rubocop-ast (>= 1.31.1, < 2.0) - rubocop-rails (2.26.2) + rubocop-rails (2.27.0) activesupport (>= 4.2.0) rack (>= 1.1) rubocop (>= 1.52.0, < 2.0) rubocop-ast (>= 1.31.1, < 2.0) - rubocop-rspec (3.1.0) + rubocop-rspec (3.2.0) rubocop (~> 1.61) rubocop-rspec_rails (2.30.0) rubocop (~> 1.61) rubocop-rspec (~> 3, >= 3.0.1) - ruby-prof (1.7.0) + ruby-prof (1.7.1) ruby-progressbar (1.13.0) ruby-saml (1.17.0) nokogiri (>= 1.13.10) @@ -769,7 +741,6 @@ GEM ruby-vips (2.2.2) ffi (~> 1.12) logger - ruby2_keywords (0.0.5) rubyzip (2.3.2) rufus-scheduler (3.9.1) fugit (~> 1.1, >= 1.1.6) @@ -781,7 +752,8 @@ GEM scenic (1.8.0) activerecord (>= 4.0.0) railties (>= 4.0.0) - selenium-webdriver (4.25.0) + securerandom (0.4.1) + selenium-webdriver (4.27.0) base64 (~> 0.2) logger (~> 1.4) rexml (~> 3.2, >= 3.2.5) @@ -821,8 +793,8 @@ GEM stackprof (0.2.26) stoplight (4.1.0) redlock (~> 1.0) - stringio (3.1.1) - strong_migrations (2.0.1) + stringio (3.1.2) + strong_migrations (2.1.0) activerecord (>= 6.1) swd (1.3.0) activesupport (>= 3) @@ -837,7 +809,7 @@ GEM test-prof (1.4.2) thor (1.3.2) tilt (2.4.0) - timeout (0.4.1) + timeout (0.4.2) tpm-key_attestation (0.12.1) bindata (~> 2.4) openssl (> 2.0) @@ -864,6 +836,7 @@ GEM unf_ext (0.0.9.1) unicode-display_width (2.6.0) uri (0.13.1) + useragent (0.16.11) validate_email (0.1.6) activemodel (>= 3.0) mail (>= 2.2.5) @@ -872,9 +845,8 @@ GEM public_suffix warden (1.2.9) rack (>= 2.0.9) - webauthn (3.1.0) + webauthn (3.2.2) android_key_attestation (~> 0.3.0) - awrence (~> 1.1) bindata (~> 2.4) cbor (~> 0.5.9) cose (~> 1.1) @@ -893,7 +865,7 @@ GEM rack-proxy (>= 0.6.1) railties (>= 5.2) semantic_range (>= 2.3.0) - webrick (1.8.2) + webrick (1.9.0) websocket (1.2.11) websocket-driver (0.7.6) websocket-extensions (>= 0.1.0) @@ -902,7 +874,7 @@ GEM xorcist (1.1.3) xpath (3.2.0) nokogiri (~> 1.8) - zeitwerk (2.6.18) + zeitwerk (2.7.1) PLATFORMS ruby @@ -910,14 +882,14 @@ PLATFORMS DEPENDENCIES active_model_serializers (~> 0.10) addressable (~> 2.8) - annotate (~> 3.2) + annotaterb (~> 4.13) aws-sdk-s3 (~> 1.123) better_errors (~> 2.9) binding_of_caller (~> 1.0) blurhash (~> 0.1) bootsnap (~> 1.18.0) brakeman (~> 6.0) - browser (< 6) + browser bundler-audit (~> 0.9) capybara (~> 3.39) charlock_holmes (~> 0.7.7) @@ -939,10 +911,11 @@ DEPENDENCIES email_spec fabrication (~> 2.30) faker (~> 3.2) + faraday-httpclient fast_blank (~> 1.0) fastimage flatware-rspec - fog-core (<= 2.5.0) + fog-core (<= 2.6.0) fog-openstack (~> 1.0) haml-rails (~> 2.0) haml_lint @@ -957,6 +930,7 @@ DEPENDENCIES idn-ruby inline_svg irb (~> 1.8) + jd-paperclip-azure (~> 3.0) json-ld json-ld-preloaded (~> 3.2) json-schema (~> 5.0) @@ -968,10 +942,10 @@ DEPENDENCIES lograge (~> 0.12) mail (~> 2.8) mario-redis-lock (~> 1.2) - md-paperclip-azure (~> 2.2) memory_profiler - mime-types (~> 3.5.0) - net-http (~> 0.4.0) + mime-types (~> 3.6.0) + mutex_m + net-http (~> 0.5.0) net-ldap (~> 0.18) nokogiri (~> 1.15) oj (~> 3.14) @@ -991,8 +965,8 @@ DEPENDENCIES opentelemetry-instrumentation-http_client (~> 0.22.3) opentelemetry-instrumentation-net_http (~> 0.22.4) opentelemetry-instrumentation-pg (~> 0.29.0) - opentelemetry-instrumentation-rack (~> 0.24.1) - opentelemetry-instrumentation-rails (~> 0.31.0) + opentelemetry-instrumentation-rack (~> 0.25.0) + opentelemetry-instrumentation-rails (~> 0.33.0) opentelemetry-instrumentation-redis (~> 0.25.3) opentelemetry-instrumentation-sidekiq (~> 0.25.2) opentelemetry-sdk (~> 1.4) @@ -1009,7 +983,7 @@ DEPENDENCIES rack-attack (~> 6.6) rack-cors (~> 2.0) rack-test (~> 2.1) - rails (~> 7.1.1) + rails (~> 7.2.0) rails-controller-testing (~> 1.0) rails-i18n (~> 7.0) rdf-normalize (~> 0.5) @@ -1057,7 +1031,7 @@ DEPENDENCIES xorcist (~> 1.1) RUBY VERSION - ruby 3.3.4p94 + ruby 3.3.6p108 BUNDLED WITH - 2.5.18 + 2.5.23 diff --git a/README.md b/README.md index 0fdc8d378ce510..b0ef1b0d527b16 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ Mastodon acts as an OAuth2 provider, so 3rd party apps can use the REST and Stre - **PostgreSQL** 12+ - **Redis** 4+ -- **Ruby** 3.1+ +- **Ruby** 3.2+ - **Node.js** 18+ The repository includes deployment configurations for **Docker and docker-compose** as well as specific platforms like **Heroku**, and **Scalingo**. For Helm charts, reference the [mastodon/chart repository](https://github.com/mastodon/chart). The [**standalone** installation guide](https://docs.joinmastodon.org/admin/install/) is available in the documentation. diff --git a/Rakefile b/Rakefile index e51cf0e17e838a..488c551fee2cd1 100644 --- a/Rakefile +++ b/Rakefile @@ -3,6 +3,6 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('config/application', __dir__) +require_relative 'config/application' Rails.application.load_tasks diff --git a/app/controllers/activitypub/outboxes_controller.rb b/app/controllers/activitypub/outboxes_controller.rb index b8baf64e1a59a8..0c995edbf87277 100644 --- a/app/controllers/activitypub/outboxes_controller.rb +++ b/app/controllers/activitypub/outboxes_controller.rb @@ -41,11 +41,11 @@ def outbox_presenter end end - def outbox_url(**kwargs) + def outbox_url(**) if params[:account_username].present? - account_outbox_url(@account, **kwargs) + account_outbox_url(@account, **) else - instance_actor_outbox_url(**kwargs) + instance_actor_outbox_url(**) end end diff --git a/app/controllers/admin/email_domain_blocks_controller.rb b/app/controllers/admin/email_domain_blocks_controller.rb index faa0a061a6ddd1..9501ebd63a0e5b 100644 --- a/app/controllers/admin/email_domain_blocks_controller.rb +++ b/app/controllers/admin/email_domain_blocks_controller.rb @@ -5,7 +5,7 @@ class EmailDomainBlocksController < BaseController def index authorize :email_domain_block, :index? - @email_domain_blocks = EmailDomainBlock.where(parent_id: nil).includes(:children).order(id: :desc).page(params[:page]) + @email_domain_blocks = EmailDomainBlock.parents.includes(:children).order(id: :desc).page(params[:page]) @form = Form::EmailDomainBlockBatch.new end @@ -58,10 +58,7 @@ def create private def set_resolved_records - Resolv::DNS.open do |dns| - dns.timeouts = 5 - @resolved_records = dns.getresources(@email_domain_block.domain, Resolv::DNS::Resource::IN::MX).to_a - end + @resolved_records = DomainResource.new(@email_domain_block.domain).mx end def resource_params diff --git a/app/controllers/admin/instances_controller.rb b/app/controllers/admin/instances_controller.rb index d7f88a71f3698f..a48c4773ed5dd4 100644 --- a/app/controllers/admin/instances_controller.rb +++ b/app/controllers/admin/instances_controller.rb @@ -5,6 +5,8 @@ class InstancesController < BaseController before_action :set_instances, only: :index before_action :set_instance, except: :index + LOGS_LIMIT = 5 + def index authorize :instance, :index? preload_delivery_failures! @@ -13,7 +15,7 @@ def index def show authorize :instance, :show? @time_period = (6.days.ago.to_date...Time.now.utc.to_date) - @action_logs = Admin::ActionLogFilter.new(target_domain: @instance.domain).results.limit(5) + @action_logs = Admin::ActionLogFilter.new(target_domain: @instance.domain).results.limit(LOGS_LIMIT) end def destroy diff --git a/app/controllers/admin/invites_controller.rb b/app/controllers/admin/invites_controller.rb index dabfe97655f933..614e2a32d000f3 100644 --- a/app/controllers/admin/invites_controller.rb +++ b/app/controllers/admin/invites_controller.rb @@ -32,7 +32,7 @@ def destroy def deactivate_all authorize :invite, :deactivate_all? - Invite.available.in_batches.update_all(expires_at: Time.now.utc) + Invite.available.in_batches.touch_all(:expires_at) redirect_to admin_invites_path end diff --git a/app/controllers/admin/relays_controller.rb b/app/controllers/admin/relays_controller.rb index c893802159b753..f05255adb6d59f 100644 --- a/app/controllers/admin/relays_controller.rb +++ b/app/controllers/admin/relays_controller.rb @@ -21,6 +21,7 @@ def create @relay = Relay.new(resource_params) if @relay.save + log_action :create, @relay @relay.enable! redirect_to admin_relays_path else @@ -31,18 +32,21 @@ def create def destroy authorize :relay, :update? @relay.destroy + log_action :destroy, @relay redirect_to admin_relays_path end def enable authorize :relay, :update? @relay.enable! + log_action :enable, @relay redirect_to admin_relays_path end def disable authorize :relay, :update? @relay.disable! + log_action :disable, @relay redirect_to admin_relays_path end diff --git a/app/controllers/admin/statuses_controller.rb b/app/controllers/admin/statuses_controller.rb index e53b22dca3210c..40d1a481b281c1 100644 --- a/app/controllers/admin/statuses_controller.rb +++ b/app/controllers/admin/statuses_controller.rb @@ -16,6 +16,8 @@ def index def show authorize [:admin, @status], :show? + + @status_batch_action = Admin::StatusBatchAction.new end def batch diff --git a/app/controllers/admin/trends/links_controller.rb b/app/controllers/admin/trends/links_controller.rb index 83d68eba63c321..65eca11c7f3cde 100644 --- a/app/controllers/admin/trends/links_controller.rb +++ b/app/controllers/admin/trends/links_controller.rb @@ -4,7 +4,7 @@ class Admin::Trends::LinksController < Admin::BaseController def index authorize :preview_card, :review? - @locales = PreviewCardTrend.pluck('distinct language') + @locales = PreviewCardTrend.locales @preview_cards = filtered_preview_cards.page(params[:page]) @form = Trends::PreviewCardBatch.new end diff --git a/app/controllers/admin/trends/statuses_controller.rb b/app/controllers/admin/trends/statuses_controller.rb index 3d8b53ea8a0444..682fe70bb561d8 100644 --- a/app/controllers/admin/trends/statuses_controller.rb +++ b/app/controllers/admin/trends/statuses_controller.rb @@ -4,7 +4,7 @@ class Admin::Trends::StatusesController < Admin::BaseController def index authorize [:admin, :status], :review? - @locales = StatusTrend.pluck('distinct language') + @locales = StatusTrend.locales @statuses = filtered_statuses.page(params[:page]) @form = Trends::StatusBatch.new end diff --git a/app/controllers/api/v1/accounts/familiar_followers_controller.rb b/app/controllers/api/v1/accounts/familiar_followers_controller.rb index a49eb2eb274672..81f0a9ed0f9df9 100644 --- a/app/controllers/api/v1/accounts/familiar_followers_controller.rb +++ b/app/controllers/api/v1/accounts/familiar_followers_controller.rb @@ -12,7 +12,7 @@ def index private def set_accounts - @accounts = Account.without_suspended.where(id: account_ids).select('id, hide_collections') + @accounts = Account.without_suspended.where(id: account_ids).select(:id, :hide_collections) end def familiar_followers diff --git a/app/controllers/api/v1/accounts_controller.rb b/app/controllers/api/v1/accounts_controller.rb index 28acaeea051834..f7d3de7f946c58 100644 --- a/app/controllers/api/v1/accounts_controller.rb +++ b/app/controllers/api/v1/accounts_controller.rb @@ -106,8 +106,8 @@ def check_following_self render json: { error: I18n.t('accounts.self_follow_error') }, status: 403 if current_user.account.id == @account.id end - def relationships(**options) - AccountRelationshipsPresenter.new([@account], current_user.account_id, **options) + def relationships(**) + AccountRelationshipsPresenter.new([@account], current_user.account_id, **) end def account_ids diff --git a/app/controllers/api/v1/annual_reports_controller.rb b/app/controllers/api/v1/annual_reports_controller.rb index 9bc8e68ac2430b..b1aee288dd8595 100644 --- a/app/controllers/api/v1/annual_reports_controller.rb +++ b/app/controllers/api/v1/annual_reports_controller.rb @@ -17,6 +17,17 @@ def index relationships: @relationships end + def show + with_read_replica do + @presenter = AnnualReportsPresenter.new([@annual_report]) + @relationships = StatusRelationshipsPresenter.new(@presenter.statuses, current_account.id) + end + + render json: @presenter, + serializer: REST::AnnualReportsSerializer, + relationships: @relationships + end + def read @annual_report.view! render_empty diff --git a/app/controllers/api/v1/featured_tags/suggestions_controller.rb b/app/controllers/api/v1/featured_tags/suggestions_controller.rb index 9c72e4380d887f..d533b1af7b0846 100644 --- a/app/controllers/api/v1/featured_tags/suggestions_controller.rb +++ b/app/controllers/api/v1/featured_tags/suggestions_controller.rb @@ -5,6 +5,8 @@ class Api::V1::FeaturedTags::SuggestionsController < Api::BaseController before_action :require_user! before_action :set_recently_used_tags, only: :index + RECENT_TAGS_LIMIT = 10 + def index render json: @recently_used_tags, each_serializer: REST::TagSerializer, relationships: TagRelationshipsPresenter.new(@recently_used_tags, current_user&.account_id) end @@ -12,6 +14,6 @@ def index private def set_recently_used_tags - @recently_used_tags = Tag.suggestions_for_account(current_account).limit(10) + @recently_used_tags = Tag.suggestions_for_account(current_account).limit(RECENT_TAGS_LIMIT) end end diff --git a/app/controllers/api/v1/follow_requests_controller.rb b/app/controllers/api/v1/follow_requests_controller.rb index 29a09fceefe82e..4b44cfe531d26f 100644 --- a/app/controllers/api/v1/follow_requests_controller.rb +++ b/app/controllers/api/v1/follow_requests_controller.rb @@ -28,8 +28,8 @@ def account @account ||= Account.find(params[:id]) end - def relationships(**options) - AccountRelationshipsPresenter.new([account], current_user.account_id, **options) + def relationships(**) + AccountRelationshipsPresenter.new([account], current_user.account_id, **) end def load_accounts diff --git a/app/controllers/api/v1/lists/accounts_controller.rb b/app/controllers/api/v1/lists/accounts_controller.rb index b1c0e609d04baf..616159f05f7b7f 100644 --- a/app/controllers/api/v1/lists/accounts_controller.rb +++ b/app/controllers/api/v1/lists/accounts_controller.rb @@ -15,17 +15,12 @@ def show end def create - ApplicationRecord.transaction do - list_accounts.each do |account| - @list.accounts << account - end - end - + AddAccountsToListService.new.call(@list, Account.find(account_ids)) render_empty end def destroy - ListAccount.where(list: @list, account_id: account_ids).destroy_all + RemoveAccountsFromListService.new.call(@list, Account.where(id: account_ids)) render_empty end @@ -43,10 +38,6 @@ def load_accounts end end - def list_accounts - Account.find(account_ids) - end - def account_ids Array(resource_params[:account_ids]) end diff --git a/app/controllers/api/web/push_subscriptions_controller.rb b/app/controllers/api/web/push_subscriptions_controller.rb index 167d16fc4d838c..f5159614278a0b 100644 --- a/app/controllers/api/web/push_subscriptions_controller.rb +++ b/app/controllers/api/web/push_subscriptions_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Api::Web::PushSubscriptionsController < Api::Web::BaseController - before_action :require_user! + before_action :require_user!, except: :destroy before_action :set_push_subscription, only: :update before_action :destroy_previous_subscriptions, only: :create, if: :prior_subscriptions? after_action :update_session_with_subscription, only: :create @@ -17,6 +17,13 @@ def update render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer end + def destroy + push_subscription = ::Web::PushSubscription.find_by_token_for(:unsubscribe, params[:id]) + push_subscription&.destroy + + head 200 + end + private def active_session diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 9ed35c523faee7..199daf8c2a426f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -25,7 +25,6 @@ class ApplicationController < ActionController::Base helper_method :use_seamless_external_login? helper_method :sso_account_settings helper_method :limited_federation_mode? - helper_method :body_class_string helper_method :skip_csrf_meta_tags? rescue_from ActionController::ParameterMissing, Paperclip::AdapterRegistry::NoHandlerError, with: :bad_request @@ -155,10 +154,6 @@ def current_session @current_session = SessionActivation.find_by(session_id: cookies.signed['_session_id']) if cookies.signed['_session_id'].present? end - def body_class_string - @body_classes || '' - end - def respond_with_error(code) respond_to do |format| format.any { render "errors/#{code}", layout: 'error', status: code, formats: [:html] } diff --git a/app/controllers/concerns/auth/captcha_concern.rb b/app/controllers/concerns/auth/captcha_concern.rb index cfd93978cea576..c01da212499f04 100644 --- a/app/controllers/concerns/auth/captcha_concern.rb +++ b/app/controllers/concerns/auth/captcha_concern.rb @@ -10,7 +10,7 @@ module Auth::CaptchaConcern end def captcha_available? - ENV['HCAPTCHA_SECRET_KEY'].present? && ENV['HCAPTCHA_SITE_KEY'].present? + Rails.configuration.x.captcha.secret_key.present? && Rails.configuration.x.captcha.site_key.present? end def captcha_enabled? diff --git a/app/controllers/concerns/cache_concern.rb b/app/controllers/concerns/cache_concern.rb index 1823b5b8edacf9..b1b09f2aab0342 100644 --- a/app/controllers/concerns/cache_concern.rb +++ b/app/controllers/concerns/cache_concern.rb @@ -28,7 +28,7 @@ def enforce_cache_control! def render_with_cache(**options) raise ArgumentError, 'Only JSON render calls are supported' unless options.key?(:json) || block_given? - key = options.delete(:key) || [[params[:controller], params[:action]].join('/'), options[:json].respond_to?(:cache_key) ? options[:json].cache_key : nil, options[:fields].nil? ? nil : options[:fields].join(',')].compact.join(':') + key = options.delete(:key) || [[params[:controller], params[:action]].join('/'), options[:json].respond_to?(:cache_key) ? options[:json].cache_key : nil, options[:fields]&.join(',')].compact.join(':') expires_in = options.delete(:expires_in) || 3.minutes body = Rails.cache.read(key, raw: true) diff --git a/app/controllers/concerns/web_app_controller_concern.rb b/app/controllers/concerns/web_app_controller_concern.rb index 3447bb0d5cc5d9..5588913b157365 100644 --- a/app/controllers/concerns/web_app_controller_concern.rb +++ b/app/controllers/concerns/web_app_controller_concern.rb @@ -7,7 +7,6 @@ module WebAppControllerConcern vary_by 'Accept, Accept-Language, Cookie' before_action :redirect_unauthenticated_to_permalinks! - before_action :set_app_body_class content_security_policy do |p| policy = ContentSecurityPolicy.new @@ -24,10 +23,6 @@ def skip_csrf_meta_tags? !(ENV['ONE_CLICK_SSO_LOGIN'] == 'true' && ENV['OMNIAUTH_ONLY'] == 'true' && Devise.omniauth_providers.length == 1) && current_user.nil? end - def set_app_body_class - @body_classes = 'app-body' - end - def redirect_unauthenticated_to_permalinks! return if user_signed_in? # NOTE: Different from upstream because we allow moved users to log in diff --git a/app/controllers/oauth/authorized_applications_controller.rb b/app/controllers/oauth/authorized_applications_controller.rb index 267409a9ce4ef6..9e541e5e3c1c78 100644 --- a/app/controllers/oauth/authorized_applications_controller.rb +++ b/app/controllers/oauth/authorized_applications_controller.rb @@ -35,12 +35,6 @@ def set_cache_headers end def set_last_used_at_by_app - @last_used_at_by_app = Doorkeeper::AccessToken - .select('DISTINCT ON (application_id) application_id, last_used_at') - .where(resource_owner_id: current_resource_owner.id) - .where.not(last_used_at: nil) - .order(application_id: :desc, last_used_at: :desc) - .pluck(:application_id, :last_used_at) - .to_h + @last_used_at_by_app = current_resource_owner.applications_last_used end end diff --git a/app/controllers/oauth/userinfo_controller.rb b/app/controllers/oauth/userinfo_controller.rb new file mode 100644 index 00000000000000..e268b70dcc0609 --- /dev/null +++ b/app/controllers/oauth/userinfo_controller.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +class Oauth::UserinfoController < Api::BaseController + before_action -> { doorkeeper_authorize! :profile }, only: [:show] + before_action :require_user! + + def show + @account = current_account + render json: @account, serializer: OauthUserinfoSerializer + end +end diff --git a/app/controllers/settings/featured_tags_controller.rb b/app/controllers/settings/featured_tags_controller.rb index 90c112e21960e7..7e29dd1d2987e2 100644 --- a/app/controllers/settings/featured_tags_controller.rb +++ b/app/controllers/settings/featured_tags_controller.rb @@ -5,6 +5,8 @@ class Settings::FeaturedTagsController < Settings::BaseController before_action :set_featured_tag, except: [:index, :create] before_action :set_recently_used_tags, only: :index + RECENT_TAGS_LIMIT = 10 + def index @featured_tag = FeaturedTag.new end @@ -38,7 +40,7 @@ def set_featured_tags end def set_recently_used_tags - @recently_used_tags = Tag.suggestions_for_account(current_account).limit(10) + @recently_used_tags = Tag.suggestions_for_account(current_account).limit(RECENT_TAGS_LIMIT) end def featured_tag_params diff --git a/app/controllers/settings/imports_controller.rb b/app/controllers/settings/imports_controller.rb index 569aa07c533ece..5346a448a3912f 100644 --- a/app/controllers/settings/imports_controller.rb +++ b/app/controllers/settings/imports_controller.rb @@ -24,6 +24,8 @@ class Settings::ImportsController < Settings::BaseController lists: false, }.freeze + RECENT_IMPORTS_LIMIT = 10 + def index @import = Form::Import.new(current_account: current_account) end @@ -96,6 +98,6 @@ def set_bulk_import end def set_recent_imports - @recent_imports = current_account.bulk_imports.reorder(id: :desc).limit(10) + @recent_imports = current_account.bulk_imports.reorder(id: :desc).limit(RECENT_IMPORTS_LIMIT) end end diff --git a/app/helpers/admin/account_moderation_notes_helper.rb b/app/helpers/admin/account_moderation_notes_helper.rb index 2a3d954a35447f..7c931c11570f33 100644 --- a/app/helpers/admin/account_moderation_notes_helper.rb +++ b/app/helpers/admin/account_moderation_notes_helper.rb @@ -12,12 +12,12 @@ def admin_account_link_to(account, path: nil) ) end - def admin_account_inline_link_to(account) + def admin_account_inline_link_to(account, path: nil) return if account.nil? link_to( account_inline_text(account), - admin_account_path(account.id), + path || admin_account_path(account.id), class: class_names('inline-name-tag', suspended: suspended_account?(account)), title: account.acct ) diff --git a/app/helpers/admin/action_logs_helper.rb b/app/helpers/admin/action_logs_helper.rb index 51e28d8b4e9234..859f92468762ac 100644 --- a/app/helpers/admin/action_logs_helper.rb +++ b/app/helpers/admin/action_logs_helper.rb @@ -33,6 +33,8 @@ def log_target(log) else I18n.t('admin.action_logs.deleted_account') end + when 'Relay' + link_to log.human_identifier, admin_relays_path end end diff --git a/app/helpers/admin/settings_helper.rb b/app/helpers/admin/settings_helper.rb index 6937331e1a6df9..9b950d5a6370f4 100644 --- a/app/helpers/admin/settings_helper.rb +++ b/app/helpers/admin/settings_helper.rb @@ -2,7 +2,7 @@ module Admin::SettingsHelper def captcha_available? - ENV['HCAPTCHA_SECRET_KEY'].present? && ENV['HCAPTCHA_SITE_KEY'].present? + Rails.configuration.x.captcha.secret_key.present? && Rails.configuration.x.captcha.site_key.present? end def login_activity_title(activity) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 7665c0011a24d6..05221cfb447cda 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -79,7 +79,7 @@ def locale_direction def html_title safe_join( - [content_for(:page_title).to_s.chomp, title] + [content_for(:page_title), title] .compact_blank, ' - ' ) @@ -120,18 +120,6 @@ def check_icon inline_svg_tag 'check.svg' end - def visibility_icon(status) - if status.public_visibility? - material_symbol('globe', title: I18n.t('statuses.visibilities.public')) - elsif status.unlisted_visibility? - material_symbol('lock_open', title: I18n.t('statuses.visibilities.unlisted')) - elsif status.private_visibility? || status.limited_visibility? - material_symbol('lock', title: I18n.t('statuses.visibilities.private')) - elsif status.direct_visibility? - material_symbol('alternate_email', title: I18n.t('statuses.visibilities.direct')) - end - end - def interrelationships_icon(relationships, account_id) if relationships.following[account_id] && relationships.followed_by[account_id] material_symbol('sync_alt', title: I18n.t('relationships.mutual'), class: 'active passive') @@ -155,7 +143,7 @@ def opengraph(property, content) end def body_classes - output = body_class_string.split + output = [] output << content_for(:body_classes) output << "flavour-#{current_flavour.parameterize}" output << "skin-#{current_skin.parameterize}" @@ -256,12 +244,12 @@ def preload_locale_pack preload_pack_asset "locales/#{current_flavour}/#{I18n.locale}-json.js" if supported_locales.include?(I18n.locale.to_s) end - def flavoured_javascript_pack_tag(pack_name, **options) - javascript_pack_tag("flavours/#{current_flavour}/#{pack_name}", **options) + def flavoured_javascript_pack_tag(pack_name, **) + javascript_pack_tag("flavours/#{current_flavour}/#{pack_name}", **) end - def flavoured_stylesheet_pack_tag(pack_name, **options) - stylesheet_pack_tag("flavours/#{current_flavour}/#{pack_name}", **options) + def flavoured_stylesheet_pack_tag(pack_name, **) + stylesheet_pack_tag("flavours/#{current_flavour}/#{pack_name}", **) end def preload_signed_in_js_packs diff --git a/app/helpers/formatting_helper.rb b/app/helpers/formatting_helper.rb index bc3d07a6bb01af..b842aa1dc71267 100644 --- a/app/helpers/formatting_helper.rb +++ b/app/helpers/formatting_helper.rb @@ -27,7 +27,14 @@ def extract_status_plain_text(status) module_function :extract_status_plain_text def status_content_format(status) - html_aware_format(status.text, status.local?, preloaded_accounts: [status.account] + (status.respond_to?(:active_mentions) ? status.active_mentions.map(&:account) : []), content_type: status.content_type) + MastodonOTELTracer.in_span('HtmlAwareFormatter rendering') do |span| + span.add_attributes( + 'app.formatter.content.type' => 'status', + 'app.formatter.content.origin' => status.local? ? 'local' : 'remote' + ) + + html_aware_format(status.text, status.local?, preloaded_accounts: [status.account] + (status.respond_to?(:active_mentions) ? status.active_mentions.map(&:account) : []), content_type: status.content_type) + end end def rss_status_content_format(status) @@ -39,7 +46,14 @@ def rss_status_content_format(status) end def account_bio_format(account) - html_aware_format(account.note, account.local?) + MastodonOTELTracer.in_span('HtmlAwareFormatter rendering') do |span| + span.add_attributes( + 'app.formatter.content.type' => 'account_bio', + 'app.formatter.content.origin' => account.local? ? 'local' : 'remote' + ) + + html_aware_format(account.note, account.local?) + end end def account_field_value_format(field, with_rel_me: true) diff --git a/app/helpers/languages_helper.rb b/app/helpers/languages_helper.rb index 394202e39ad78a..0a8ebcde549cdc 100644 --- a/app/helpers/languages_helper.rb +++ b/app/helpers/languages_helper.rb @@ -162,7 +162,7 @@ module LanguagesHelper th: ['Thai', 'ไทย'].freeze, ti: ['Tigrinya', 'ትግርኛ'].freeze, tk: ['Turkmen', 'Türkmen'].freeze, - tl: ['Tagalog', 'Wikang Tagalog'].freeze, + tl: ['Tagalog', 'Tagalog'].freeze, tn: ['Tswana', 'Setswana'].freeze, to: ['Tonga', 'faka Tonga'].freeze, tr: ['Turkish', 'Türkçe'].freeze, diff --git a/app/helpers/media_component_helper.rb b/app/helpers/media_component_helper.rb index 60ccdd08359038..269566528aab86 100644 --- a/app/helpers/media_component_helper.rb +++ b/app/helpers/media_component_helper.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module MediaComponentHelper - def render_video_component(status, **options) + def render_video_component(status, **) video = status.ordered_media_attachments.first meta = video.file.meta || {} @@ -18,14 +18,14 @@ def render_video_component(status, **options) media: [ serialize_media_attachment(video), ].as_json, - }.merge(**options) + }.merge(**) react_component :video, component_params do render partial: 'statuses/attachment_list', locals: { attachments: status.ordered_media_attachments } end end - def render_audio_component(status, **options) + def render_audio_component(status, **) audio = status.ordered_media_attachments.first meta = audio.file.meta || {} @@ -38,19 +38,19 @@ def render_audio_component(status, **options) foregroundColor: meta.dig('colors', 'foreground'), accentColor: meta.dig('colors', 'accent'), duration: meta.dig('original', 'duration'), - }.merge(**options) + }.merge(**) react_component :audio, component_params do render partial: 'statuses/attachment_list', locals: { attachments: status.ordered_media_attachments } end end - def render_media_gallery_component(status, **options) + def render_media_gallery_component(status, **) component_params = { sensitive: sensitive_viewer?(status, current_account), autoplay: prefers_autoplay?, media: status.ordered_media_attachments.map { |a| serialize_media_attachment(a).as_json }, - }.merge(**options) + }.merge(**) react_component :media_gallery, component_params do render partial: 'statuses/attachment_list', locals: { attachments: status.ordered_media_attachments } diff --git a/app/helpers/registration_helper.rb b/app/helpers/registration_helper.rb index ef5462ac887413..002d167c05833a 100644 --- a/app/helpers/registration_helper.rb +++ b/app/helpers/registration_helper.rb @@ -16,6 +16,6 @@ def omniauth_only? end def ip_blocked?(remote_ip) - IpBlock.where(severity: :sign_up_block).exists?(['ip >>= ?', remote_ip.to_s]) + IpBlock.severity_sign_up_block.containing(remote_ip.to_s).exists? end end diff --git a/app/helpers/routing_helper.rb b/app/helpers/routing_helper.rb index 15d988f64d2ef2..22efc5f0924e44 100644 --- a/app/helpers/routing_helper.rb +++ b/app/helpers/routing_helper.rb @@ -14,8 +14,8 @@ def default_url_options end end - def full_asset_url(source, **options) - source = ActionController::Base.helpers.asset_url(source, **options) unless use_storage? + def full_asset_url(source, **) + source = ActionController::Base.helpers.asset_url(source, **) unless use_storage? URI.join(asset_host, source).to_s end @@ -24,12 +24,12 @@ def asset_host Rails.configuration.action_controller.asset_host || root_url end - def frontend_asset_path(source, **options) - asset_pack_path("media/#{source}", **options) + def frontend_asset_path(source, **) + asset_pack_path("media/#{source}", **) end - def frontend_asset_url(source, **options) - full_asset_url(frontend_asset_path(source, **options)) + def frontend_asset_url(source, **) + full_asset_url(frontend_asset_path(source, **)) end def use_storage? diff --git a/app/helpers/self_destruct_helper.rb b/app/helpers/self_destruct_helper.rb index 78557c25e522f2..f1927b1e043d40 100644 --- a/app/helpers/self_destruct_helper.rb +++ b/app/helpers/self_destruct_helper.rb @@ -1,9 +1,11 @@ # frozen_string_literal: true module SelfDestructHelper + VERIFY_PURPOSE = 'self-destruct' + def self.self_destruct? - value = ENV.fetch('SELF_DESTRUCT', nil) - value.present? && Rails.application.message_verifier('self-destruct').verify(value) == ENV['LOCAL_DOMAIN'] + value = Rails.configuration.x.mastodon.self_destruct_value + value.present? && Rails.application.message_verifier(VERIFY_PURPOSE).verify(value) == ENV['LOCAL_DOMAIN'] rescue ActiveSupport::MessageVerifier::InvalidSignature false end diff --git a/app/helpers/statuses_helper.rb b/app/helpers/statuses_helper.rb index 9bbb03fd820230..16b9d3fb531b21 100644 --- a/app/helpers/statuses_helper.rb +++ b/app/helpers/statuses_helper.rb @@ -1,9 +1,6 @@ # frozen_string_literal: true module StatusesHelper - EMBEDDED_CONTROLLER = 'statuses' - EMBEDDED_ACTION = 'embed' - VISIBLITY_ICONS = { public: 'globe', unlisted: 'lock_open', @@ -60,18 +57,10 @@ def status_description(status) components.compact_blank.join("\n\n") end - def stream_link_target - embedded_view? ? '_blank' : nil - end - def visibility_icon(status) VISIBLITY_ICONS[status.visibility.to_sym] end - def embedded_view? - params[:controller] == EMBEDDED_CONTROLLER && params[:action] == EMBEDDED_ACTION - end - def prefers_autoplay? ActiveModel::Type::Boolean.new.cast(params[:autoplay]) || current_user&.setting_auto_play_gif end diff --git a/app/javascript/entrypoints/public.tsx b/app/javascript/entrypoints/public.tsx index d33e00d5da88ce..9e8ff9caa15812 100644 --- a/app/javascript/entrypoints/public.tsx +++ b/app/javascript/entrypoints/public.tsx @@ -230,62 +230,6 @@ function loaded() { } }, ); - - Rails.delegate( - document, - 'button.status__content__spoiler-link', - 'click', - function () { - if (!(this instanceof HTMLButtonElement)) return; - - const statusEl = this.parentNode?.parentNode; - - if ( - !( - statusEl instanceof HTMLDivElement && - statusEl.classList.contains('.status__content') - ) - ) - return; - - if (statusEl.dataset.spoiler === 'expanded') { - statusEl.dataset.spoiler = 'folded'; - this.textContent = new IntlMessageFormat( - localeData['status.show_more'] ?? 'Show more', - locale, - ).format() as string; - } else { - statusEl.dataset.spoiler = 'expanded'; - this.textContent = new IntlMessageFormat( - localeData['status.show_less'] ?? 'Show less', - locale, - ).format() as string; - } - }, - ); - - document - .querySelectorAll('button.status__content__spoiler-link') - .forEach((spoilerLink) => { - const statusEl = spoilerLink.parentNode?.parentNode; - - if ( - !( - statusEl instanceof HTMLDivElement && - statusEl.classList.contains('.status__content') - ) - ) - return; - - const message = - statusEl.dataset.spoiler === 'expanded' - ? (localeData['status.show_less'] ?? 'Show less') - : (localeData['status.show_more'] ?? 'Show more'); - spoilerLink.textContent = new IntlMessageFormat( - message, - locale, - ).format() as string; - }); } Rails.delegate( @@ -327,31 +271,24 @@ Rails.delegate(document, '.input-copy button', 'click', ({ target }) => { if (!input) return; - const oldReadOnly = input.readOnly; - - input.readOnly = false; - input.focus(); - input.select(); - input.setSelectionRange(0, input.value.length); - - try { - if (document.execCommand('copy')) { - input.blur(); - + navigator.clipboard + .writeText(input.value) + .then(() => { const parent = target.parentElement; - if (!parent) return; - parent.classList.add('copied'); + if (parent) { + parent.classList.add('copied'); - setTimeout(() => { - parent.classList.remove('copied'); - }, 700); - } - } catch (err) { - console.error(err); - } + setTimeout(() => { + parent.classList.remove('copied'); + }, 700); + } - input.readOnly = oldReadOnly; + return true; + }) + .catch((error: unknown) => { + console.error(error); + }); }); const toggleSidebar = () => { @@ -446,6 +383,24 @@ Rails.delegate(document, '#registration_new_user,#new_user', 'submit', () => { }); }); +Rails.delegate(document, '.rules-list button', 'click', ({ target }) => { + if (!(target instanceof HTMLElement)) { + return; + } + + const button = target.closest('button'); + + if (!button) { + return; + } + + if (button.ariaExpanded === 'true') { + button.ariaExpanded = 'false'; + } else { + button.ariaExpanded = 'true'; + } +}); + function main() { ready(loaded).catch((error: unknown) => { console.error(error); diff --git a/app/javascript/flavours/glitch/actions/accounts.js b/app/javascript/flavours/glitch/actions/accounts.js index e8f81048a6d476..513b9e24a9a994 100644 --- a/app/javascript/flavours/glitch/actions/accounts.js +++ b/app/javascript/flavours/glitch/actions/accounts.js @@ -74,19 +74,6 @@ export const FOLLOW_REQUEST_AUTHORIZE_FAIL = 'FOLLOW_REQUEST_AUTHORIZE_FAIL'; export const FOLLOW_REQUEST_REJECT_REQUEST = 'FOLLOW_REQUEST_REJECT_REQUEST'; export const FOLLOW_REQUEST_REJECT_FAIL = 'FOLLOW_REQUEST_REJECT_FAIL'; -export const PINNED_ACCOUNTS_FETCH_REQUEST = 'PINNED_ACCOUNTS_FETCH_REQUEST'; -export const PINNED_ACCOUNTS_FETCH_SUCCESS = 'PINNED_ACCOUNTS_FETCH_SUCCESS'; -export const PINNED_ACCOUNTS_FETCH_FAIL = 'PINNED_ACCOUNTS_FETCH_FAIL'; - -export const PINNED_ACCOUNTS_SUGGESTIONS_FETCH_REQUEST = 'PINNED_ACCOUNTS_SUGGESTIONS_FETCH_REQUEST'; -export const PINNED_ACCOUNTS_SUGGESTIONS_FETCH_SUCCESS = 'PINNED_ACCOUNTS_SUGGESTIONS_FETCH_SUCCESS'; -export const PINNED_ACCOUNTS_SUGGESTIONS_FETCH_FAIL = 'PINNED_ACCOUNTS_SUGGESTIONS_FETCH_FAIL'; - -export const PINNED_ACCOUNTS_EDITOR_SUGGESTIONS_CLEAR = 'PINNED_ACCOUNTS_EDITOR_SUGGESTIONS_CLEAR'; -export const PINNED_ACCOUNTS_EDITOR_SUGGESTIONS_CHANGE = 'PINNED_ACCOUNTS_EDITOR_SUGGESTIONS_CHANGE'; - -export const PINNED_ACCOUNTS_EDITOR_RESET = 'PINNED_ACCOUNTS_EDITOR_RESET'; - export const ACCOUNT_REVEAL = 'ACCOUNT_REVEAL'; export * from './accounts_typed'; @@ -686,38 +673,6 @@ export function unpinAccountFail(error) { }; } -export function fetchPinnedAccounts() { - return (dispatch) => { - dispatch(fetchPinnedAccountsRequest()); - - api().get('/api/v1/endorsements', { params: { limit: 0 } }).then(response => { - dispatch(importFetchedAccounts(response.data)); - dispatch(fetchPinnedAccountsSuccess(response.data)); - }).catch(err => dispatch(fetchPinnedAccountsFail(err))); - }; -} - -export function fetchPinnedAccountsRequest() { - return { - type: PINNED_ACCOUNTS_FETCH_REQUEST, - }; -} - -export function fetchPinnedAccountsSuccess(accounts, next) { - return { - type: PINNED_ACCOUNTS_FETCH_SUCCESS, - accounts, - next, - }; -} - -export function fetchPinnedAccountsFail(error) { - return { - type: PINNED_ACCOUNTS_FETCH_FAIL, - error, - }; -} - export const updateAccount = ({ displayName, note, avatar, header, discoverable, indexable }) => (dispatch) => { const data = new FormData(); @@ -736,68 +691,9 @@ export const updateAccount = ({ displayName, note, avatar, header, discoverable, export const navigateToProfile = (accountId) => { return (_dispatch, getState) => { const acct = getState().accounts.getIn([accountId, 'acct']); - + if (acct) { browserHistory.push(`/@${acct}`); } }; }; - -export function fetchPinnedAccountsSuggestions(q) { - return (dispatch) => { - dispatch(fetchPinnedAccountsSuggestionsRequest()); - - const params = { - q, - resolve: false, - limit: 4, - following: true, - }; - - api().get('/api/v1/accounts/search', { params }).then(response => { - dispatch(importFetchedAccounts(response.data)); - dispatch(fetchPinnedAccountsSuggestionsSuccess(q, response.data)); - }).catch(err => dispatch(fetchPinnedAccountsSuggestionsFail(err))); - }; -} - -export function fetchPinnedAccountsSuggestionsRequest() { - return { - type: PINNED_ACCOUNTS_SUGGESTIONS_FETCH_REQUEST, - }; -} - -export function fetchPinnedAccountsSuggestionsSuccess(query, accounts) { - return { - type: PINNED_ACCOUNTS_SUGGESTIONS_FETCH_SUCCESS, - query, - accounts, - }; -} - -export function fetchPinnedAccountsSuggestionsFail(error) { - return { - type: PINNED_ACCOUNTS_SUGGESTIONS_FETCH_FAIL, - error, - }; -} - -export function clearPinnedAccountsSuggestions() { - return { - type: PINNED_ACCOUNTS_EDITOR_SUGGESTIONS_CLEAR, - }; -} - -export function changePinnedAccountsSuggestions(value) { - return { - type: PINNED_ACCOUNTS_EDITOR_SUGGESTIONS_CHANGE, - value, - }; -} - -export function resetPinnedAccountsEditor() { - return { - type: PINNED_ACCOUNTS_EDITOR_RESET, - }; -} - diff --git a/app/javascript/flavours/glitch/actions/lists.js b/app/javascript/flavours/glitch/actions/lists.js index 9956059387efc2..f9abc2e769c5a0 100644 --- a/app/javascript/flavours/glitch/actions/lists.js +++ b/app/javascript/flavours/glitch/actions/lists.js @@ -1,8 +1,5 @@ import api from '../api'; -import { showAlertForError } from './alerts'; -import { importFetchedAccounts } from './importer'; - export const LIST_FETCH_REQUEST = 'LIST_FETCH_REQUEST'; export const LIST_FETCH_SUCCESS = 'LIST_FETCH_SUCCESS'; export const LIST_FETCH_FAIL = 'LIST_FETCH_FAIL'; @@ -11,45 +8,10 @@ export const LISTS_FETCH_REQUEST = 'LISTS_FETCH_REQUEST'; export const LISTS_FETCH_SUCCESS = 'LISTS_FETCH_SUCCESS'; export const LISTS_FETCH_FAIL = 'LISTS_FETCH_FAIL'; -export const LIST_EDITOR_TITLE_CHANGE = 'LIST_EDITOR_TITLE_CHANGE'; -export const LIST_EDITOR_RESET = 'LIST_EDITOR_RESET'; -export const LIST_EDITOR_SETUP = 'LIST_EDITOR_SETUP'; - -export const LIST_CREATE_REQUEST = 'LIST_CREATE_REQUEST'; -export const LIST_CREATE_SUCCESS = 'LIST_CREATE_SUCCESS'; -export const LIST_CREATE_FAIL = 'LIST_CREATE_FAIL'; - -export const LIST_UPDATE_REQUEST = 'LIST_UPDATE_REQUEST'; -export const LIST_UPDATE_SUCCESS = 'LIST_UPDATE_SUCCESS'; -export const LIST_UPDATE_FAIL = 'LIST_UPDATE_FAIL'; - export const LIST_DELETE_REQUEST = 'LIST_DELETE_REQUEST'; export const LIST_DELETE_SUCCESS = 'LIST_DELETE_SUCCESS'; export const LIST_DELETE_FAIL = 'LIST_DELETE_FAIL'; -export const LIST_ACCOUNTS_FETCH_REQUEST = 'LIST_ACCOUNTS_FETCH_REQUEST'; -export const LIST_ACCOUNTS_FETCH_SUCCESS = 'LIST_ACCOUNTS_FETCH_SUCCESS'; -export const LIST_ACCOUNTS_FETCH_FAIL = 'LIST_ACCOUNTS_FETCH_FAIL'; - -export const LIST_EDITOR_SUGGESTIONS_CHANGE = 'LIST_EDITOR_SUGGESTIONS_CHANGE'; -export const LIST_EDITOR_SUGGESTIONS_READY = 'LIST_EDITOR_SUGGESTIONS_READY'; -export const LIST_EDITOR_SUGGESTIONS_CLEAR = 'LIST_EDITOR_SUGGESTIONS_CLEAR'; - -export const LIST_EDITOR_ADD_REQUEST = 'LIST_EDITOR_ADD_REQUEST'; -export const LIST_EDITOR_ADD_SUCCESS = 'LIST_EDITOR_ADD_SUCCESS'; -export const LIST_EDITOR_ADD_FAIL = 'LIST_EDITOR_ADD_FAIL'; - -export const LIST_EDITOR_REMOVE_REQUEST = 'LIST_EDITOR_REMOVE_REQUEST'; -export const LIST_EDITOR_REMOVE_SUCCESS = 'LIST_EDITOR_REMOVE_SUCCESS'; -export const LIST_EDITOR_REMOVE_FAIL = 'LIST_EDITOR_REMOVE_FAIL'; - -export const LIST_ADDER_RESET = 'LIST_ADDER_RESET'; -export const LIST_ADDER_SETUP = 'LIST_ADDER_SETUP'; - -export const LIST_ADDER_LISTS_FETCH_REQUEST = 'LIST_ADDER_LISTS_FETCH_REQUEST'; -export const LIST_ADDER_LISTS_FETCH_SUCCESS = 'LIST_ADDER_LISTS_FETCH_SUCCESS'; -export const LIST_ADDER_LISTS_FETCH_FAIL = 'LIST_ADDER_LISTS_FETCH_FAIL'; - export const fetchList = id => (dispatch, getState) => { if (getState().getIn(['lists', id])) { return; @@ -100,89 +62,6 @@ export const fetchListsFail = error => ({ error, }); -export const submitListEditor = shouldReset => (dispatch, getState) => { - const listId = getState().getIn(['listEditor', 'listId']); - const title = getState().getIn(['listEditor', 'title']); - - if (listId === null) { - dispatch(createList(title, shouldReset)); - } else { - dispatch(updateList(listId, title, shouldReset)); - } -}; - -export const setupListEditor = listId => (dispatch, getState) => { - dispatch({ - type: LIST_EDITOR_SETUP, - list: getState().getIn(['lists', listId]), - }); - - dispatch(fetchListAccounts(listId)); -}; - -export const changeListEditorTitle = value => ({ - type: LIST_EDITOR_TITLE_CHANGE, - value, -}); - -export const createList = (title, shouldReset) => (dispatch) => { - dispatch(createListRequest()); - - api().post('/api/v1/lists', { title }).then(({ data }) => { - dispatch(createListSuccess(data)); - - if (shouldReset) { - dispatch(resetListEditor()); - } - }).catch(err => dispatch(createListFail(err))); -}; - -export const createListRequest = () => ({ - type: LIST_CREATE_REQUEST, -}); - -export const createListSuccess = list => ({ - type: LIST_CREATE_SUCCESS, - list, -}); - -export const createListFail = error => ({ - type: LIST_CREATE_FAIL, - error, -}); - -export const updateList = (id, title, shouldReset, isExclusive, replies_policy) => (dispatch) => { - dispatch(updateListRequest(id)); - - api().put(`/api/v1/lists/${id}`, { title, replies_policy, exclusive: typeof isExclusive === 'undefined' ? undefined : !!isExclusive }).then(({ data }) => { - dispatch(updateListSuccess(data)); - - if (shouldReset) { - dispatch(resetListEditor()); - } - }).catch(err => dispatch(updateListFail(id, err))); -}; - -export const updateListRequest = id => ({ - type: LIST_UPDATE_REQUEST, - id, -}); - -export const updateListSuccess = list => ({ - type: LIST_UPDATE_SUCCESS, - list, -}); - -export const updateListFail = (id, error) => ({ - type: LIST_UPDATE_FAIL, - id, - error, -}); - -export const resetListEditor = () => ({ - type: LIST_EDITOR_RESET, -}); - export const deleteList = id => (dispatch) => { dispatch(deleteListRequest(id)); @@ -206,167 +85,3 @@ export const deleteListFail = (id, error) => ({ id, error, }); - -export const fetchListAccounts = listId => (dispatch) => { - dispatch(fetchListAccountsRequest(listId)); - - api().get(`/api/v1/lists/${listId}/accounts`, { params: { limit: 0 } }).then(({ data }) => { - dispatch(importFetchedAccounts(data)); - dispatch(fetchListAccountsSuccess(listId, data)); - }).catch(err => dispatch(fetchListAccountsFail(listId, err))); -}; - -export const fetchListAccountsRequest = id => ({ - type: LIST_ACCOUNTS_FETCH_REQUEST, - id, -}); - -export const fetchListAccountsSuccess = (id, accounts, next) => ({ - type: LIST_ACCOUNTS_FETCH_SUCCESS, - id, - accounts, - next, -}); - -export const fetchListAccountsFail = (id, error) => ({ - type: LIST_ACCOUNTS_FETCH_FAIL, - id, - error, -}); - -export const fetchListSuggestions = q => (dispatch) => { - const params = { - q, - resolve: false, - limit: 4, - following: true, - }; - - api().get('/api/v1/accounts/search', { params }).then(({ data }) => { - dispatch(importFetchedAccounts(data)); - dispatch(fetchListSuggestionsReady(q, data)); - }).catch(error => dispatch(showAlertForError(error))); -}; - -export const fetchListSuggestionsReady = (query, accounts) => ({ - type: LIST_EDITOR_SUGGESTIONS_READY, - query, - accounts, -}); - -export const clearListSuggestions = () => ({ - type: LIST_EDITOR_SUGGESTIONS_CLEAR, -}); - -export const changeListSuggestions = value => ({ - type: LIST_EDITOR_SUGGESTIONS_CHANGE, - value, -}); - -export const addToListEditor = accountId => (dispatch, getState) => { - dispatch(addToList(getState().getIn(['listEditor', 'listId']), accountId)); -}; - -export const addToList = (listId, accountId) => (dispatch) => { - dispatch(addToListRequest(listId, accountId)); - - api().post(`/api/v1/lists/${listId}/accounts`, { account_ids: [accountId] }) - .then(() => dispatch(addToListSuccess(listId, accountId))) - .catch(err => dispatch(addToListFail(listId, accountId, err))); -}; - -export const addToListRequest = (listId, accountId) => ({ - type: LIST_EDITOR_ADD_REQUEST, - listId, - accountId, -}); - -export const addToListSuccess = (listId, accountId) => ({ - type: LIST_EDITOR_ADD_SUCCESS, - listId, - accountId, -}); - -export const addToListFail = (listId, accountId, error) => ({ - type: LIST_EDITOR_ADD_FAIL, - listId, - accountId, - error, -}); - -export const removeFromListEditor = accountId => (dispatch, getState) => { - dispatch(removeFromList(getState().getIn(['listEditor', 'listId']), accountId)); -}; - -export const removeFromList = (listId, accountId) => (dispatch) => { - dispatch(removeFromListRequest(listId, accountId)); - - api().delete(`/api/v1/lists/${listId}/accounts`, { params: { account_ids: [accountId] } }) - .then(() => dispatch(removeFromListSuccess(listId, accountId))) - .catch(err => dispatch(removeFromListFail(listId, accountId, err))); -}; - -export const removeFromListRequest = (listId, accountId) => ({ - type: LIST_EDITOR_REMOVE_REQUEST, - listId, - accountId, -}); - -export const removeFromListSuccess = (listId, accountId) => ({ - type: LIST_EDITOR_REMOVE_SUCCESS, - listId, - accountId, -}); - -export const removeFromListFail = (listId, accountId, error) => ({ - type: LIST_EDITOR_REMOVE_FAIL, - listId, - accountId, - error, -}); - -export const resetListAdder = () => ({ - type: LIST_ADDER_RESET, -}); - -export const setupListAdder = accountId => (dispatch, getState) => { - dispatch({ - type: LIST_ADDER_SETUP, - account: getState().getIn(['accounts', accountId]), - }); - dispatch(fetchLists()); - dispatch(fetchAccountLists(accountId)); -}; - -export const fetchAccountLists = accountId => (dispatch) => { - dispatch(fetchAccountListsRequest(accountId)); - - api().get(`/api/v1/accounts/${accountId}/lists`) - .then(({ data }) => dispatch(fetchAccountListsSuccess(accountId, data))) - .catch(err => dispatch(fetchAccountListsFail(accountId, err))); -}; - -export const fetchAccountListsRequest = id => ({ - type:LIST_ADDER_LISTS_FETCH_REQUEST, - id, -}); - -export const fetchAccountListsSuccess = (id, lists) => ({ - type: LIST_ADDER_LISTS_FETCH_SUCCESS, - id, - lists, -}); - -export const fetchAccountListsFail = (id, err) => ({ - type: LIST_ADDER_LISTS_FETCH_FAIL, - id, - err, -}); - -export const addToListAdder = listId => (dispatch, getState) => { - dispatch(addToList(listId, getState().getIn(['listAdder', 'accountId']))); -}; - -export const removeFromListAdder = listId => (dispatch, getState) => { - dispatch(removeFromList(listId, getState().getIn(['listAdder', 'accountId']))); -}; diff --git a/app/javascript/flavours/glitch/actions/lists_typed.ts b/app/javascript/flavours/glitch/actions/lists_typed.ts new file mode 100644 index 00000000000000..8f5dc0ffa3b9b6 --- /dev/null +++ b/app/javascript/flavours/glitch/actions/lists_typed.ts @@ -0,0 +1,13 @@ +import { apiCreate, apiUpdate } from 'flavours/glitch/api/lists'; +import type { List } from 'flavours/glitch/models/list'; +import { createDataLoadingThunk } from 'flavours/glitch/store/typed_functions'; + +export const createList = createDataLoadingThunk( + 'list/create', + (list: Partial) => apiCreate(list), +); + +export const updateList = createDataLoadingThunk( + 'list/update', + (list: Partial) => apiUpdate(list), +); diff --git a/app/javascript/flavours/glitch/actions/notification_groups.ts b/app/javascript/flavours/glitch/actions/notification_groups.ts index f85dfac9335e72..184f8d720bddb9 100644 --- a/app/javascript/flavours/glitch/actions/notification_groups.ts +++ b/app/javascript/flavours/glitch/actions/notification_groups.ts @@ -141,6 +141,9 @@ export const pollRecentNotifications = createDataLoadingThunk( return { notifications }; }, + { + useLoadingBar: false, + }, ); export const processNewNotificationForGroups = createAppAsyncThunk( diff --git a/app/javascript/flavours/glitch/actions/suggestions.js b/app/javascript/flavours/glitch/actions/suggestions.js deleted file mode 100644 index 258ffa901de5d1..00000000000000 --- a/app/javascript/flavours/glitch/actions/suggestions.js +++ /dev/null @@ -1,58 +0,0 @@ -import api from '../api'; - -import { fetchRelationships } from './accounts'; -import { importFetchedAccounts } from './importer'; - -export const SUGGESTIONS_FETCH_REQUEST = 'SUGGESTIONS_FETCH_REQUEST'; -export const SUGGESTIONS_FETCH_SUCCESS = 'SUGGESTIONS_FETCH_SUCCESS'; -export const SUGGESTIONS_FETCH_FAIL = 'SUGGESTIONS_FETCH_FAIL'; - -export const SUGGESTIONS_DISMISS = 'SUGGESTIONS_DISMISS'; - -export function fetchSuggestions(withRelationships = false) { - return (dispatch) => { - dispatch(fetchSuggestionsRequest()); - - api().get('/api/v2/suggestions', { params: { limit: 20 } }).then(response => { - dispatch(importFetchedAccounts(response.data.map(x => x.account))); - dispatch(fetchSuggestionsSuccess(response.data)); - - if (withRelationships) { - dispatch(fetchRelationships(response.data.map(item => item.account.id))); - } - }).catch(error => dispatch(fetchSuggestionsFail(error))); - }; -} - -export function fetchSuggestionsRequest() { - return { - type: SUGGESTIONS_FETCH_REQUEST, - skipLoading: true, - }; -} - -export function fetchSuggestionsSuccess(suggestions) { - return { - type: SUGGESTIONS_FETCH_SUCCESS, - suggestions, - skipLoading: true, - }; -} - -export function fetchSuggestionsFail(error) { - return { - type: SUGGESTIONS_FETCH_FAIL, - error, - skipLoading: true, - skipAlert: true, - }; -} - -export const dismissSuggestion = accountId => (dispatch) => { - dispatch({ - type: SUGGESTIONS_DISMISS, - id: accountId, - }); - - api().delete(`/api/v1/suggestions/${accountId}`).catch(() => {}); -}; diff --git a/app/javascript/flavours/glitch/actions/suggestions.ts b/app/javascript/flavours/glitch/actions/suggestions.ts new file mode 100644 index 00000000000000..45e151caa0e70d --- /dev/null +++ b/app/javascript/flavours/glitch/actions/suggestions.ts @@ -0,0 +1,24 @@ +import { + apiGetSuggestions, + apiDeleteSuggestion, +} from 'flavours/glitch/api/suggestions'; +import { createDataLoadingThunk } from 'flavours/glitch/store/typed_functions'; + +import { fetchRelationships } from './accounts'; +import { importFetchedAccounts } from './importer'; + +export const fetchSuggestions = createDataLoadingThunk( + 'suggestions/fetch', + () => apiGetSuggestions(20), + (data, { dispatch }) => { + dispatch(importFetchedAccounts(data.map((x) => x.account))); + dispatch(fetchRelationships(data.map((x) => x.account.id))); + + return data; + }, +); + +export const dismissSuggestion = createDataLoadingThunk( + 'suggestions/dismiss', + ({ accountId }: { accountId: string }) => apiDeleteSuggestion(accountId), +); diff --git a/app/javascript/flavours/glitch/api.ts b/app/javascript/flavours/glitch/api.ts index 51cbe0b6954e09..f0663ded409f65 100644 --- a/app/javascript/flavours/glitch/api.ts +++ b/app/javascript/flavours/glitch/api.ts @@ -68,6 +68,7 @@ export async function apiRequest( method: Method, url: string, args: { + signal?: AbortSignal; params?: RequestParamsOrData; data?: RequestParamsOrData; timeout?: number; diff --git a/app/javascript/flavours/glitch/api/lists.ts b/app/javascript/flavours/glitch/api/lists.ts new file mode 100644 index 00000000000000..64a0af01f521e3 --- /dev/null +++ b/app/javascript/flavours/glitch/api/lists.ts @@ -0,0 +1,32 @@ +import { + apiRequestPost, + apiRequestPut, + apiRequestGet, + apiRequestDelete, +} from 'flavours/glitch/api'; +import type { ApiAccountJSON } from 'flavours/glitch/api_types/accounts'; +import type { ApiListJSON } from 'flavours/glitch/api_types/lists'; + +export const apiCreate = (list: Partial) => + apiRequestPost('v1/lists', list); + +export const apiUpdate = (list: Partial) => + apiRequestPut(`v1/lists/${list.id}`, list); + +export const apiGetAccounts = (listId: string) => + apiRequestGet(`v1/lists/${listId}/accounts`, { + limit: 0, + }); + +export const apiGetAccountLists = (accountId: string) => + apiRequestGet(`v1/accounts/${accountId}/lists`); + +export const apiAddAccountToList = (listId: string, accountId: string) => + apiRequestPost(`v1/lists/${listId}/accounts`, { + account_ids: [accountId], + }); + +export const apiRemoveAccountFromList = (listId: string, accountId: string) => + apiRequestDelete(`v1/lists/${listId}/accounts`, { + account_ids: [accountId], + }); diff --git a/app/javascript/flavours/glitch/api/suggestions.ts b/app/javascript/flavours/glitch/api/suggestions.ts new file mode 100644 index 00000000000000..425f02d541f60d --- /dev/null +++ b/app/javascript/flavours/glitch/api/suggestions.ts @@ -0,0 +1,8 @@ +import { apiRequestGet, apiRequestDelete } from 'flavours/glitch/api'; +import type { ApiSuggestionJSON } from 'flavours/glitch/api_types/suggestions'; + +export const apiGetSuggestions = (limit: number) => + apiRequestGet('v2/suggestions', { limit }); + +export const apiDeleteSuggestion = (accountId: string) => + apiRequestDelete(`v1/suggestions/${accountId}`); diff --git a/app/javascript/flavours/glitch/api_types/lists.ts b/app/javascript/flavours/glitch/api_types/lists.ts new file mode 100644 index 00000000000000..6984cf9b191336 --- /dev/null +++ b/app/javascript/flavours/glitch/api_types/lists.ts @@ -0,0 +1,10 @@ +// See app/serializers/rest/list_serializer.rb + +export type RepliesPolicyType = 'list' | 'followed' | 'none'; + +export interface ApiListJSON { + id: string; + title: string; + exclusive: boolean; + replies_policy: RepliesPolicyType; +} diff --git a/app/javascript/flavours/glitch/api_types/notifications.ts b/app/javascript/flavours/glitch/api_types/notifications.ts index 17c2ede32bd86e..d173083dbd2143 100644 --- a/app/javascript/flavours/glitch/api_types/notifications.ts +++ b/app/javascript/flavours/glitch/api_types/notifications.ts @@ -20,6 +20,7 @@ export const allNotificationTypes = [ 'admin.report', 'moderation_warning', 'severed_relationships', + 'annual_report', ]; export type NotificationWithStatusType = @@ -37,7 +38,8 @@ export type NotificationType = | 'moderation_warning' | 'severed_relationships' | 'admin.sign_up' - | 'admin.report'; + | 'admin.report' + | 'annual_report'; export interface BaseNotificationJSON { id: string; @@ -130,6 +132,15 @@ interface AccountRelationshipSeveranceNotificationJSON event: ApiAccountRelationshipSeveranceEventJSON; } +export interface ApiAnnualReportEventJSON { + year: string; +} + +interface AnnualReportNotificationGroupJSON extends BaseNotificationGroupJSON { + type: 'annual_report'; + annual_report: ApiAnnualReportEventJSON; +} + export type ApiNotificationJSON = | SimpleNotificationJSON | ReportNotificationJSON @@ -142,7 +153,8 @@ export type ApiNotificationGroupJSON = | ReportNotificationGroupJSON | AccountRelationshipSeveranceNotificationGroupJSON | NotificationGroupWithStatusJSON - | ModerationWarningNotificationGroupJSON; + | ModerationWarningNotificationGroupJSON + | AnnualReportNotificationGroupJSON; export interface ApiNotificationGroupsResultJSON { accounts: ApiAccountJSON[]; diff --git a/app/javascript/flavours/glitch/api_types/suggestions.ts b/app/javascript/flavours/glitch/api_types/suggestions.ts new file mode 100644 index 00000000000000..70d0ed8e7d43de --- /dev/null +++ b/app/javascript/flavours/glitch/api_types/suggestions.ts @@ -0,0 +1,13 @@ +import type { ApiAccountJSON } from 'flavours/glitch/api_types/accounts'; + +export type ApiSuggestionSourceJSON = + | 'featured' + | 'most_followed' + | 'most_interactions' + | 'similar_to_recently_followed' + | 'friends_of_friends'; + +export interface ApiSuggestionJSON { + sources: [ApiSuggestionSourceJSON, ...ApiSuggestionSourceJSON[]]; + account: ApiAccountJSON; +} diff --git a/app/javascript/flavours/glitch/components/account.jsx b/app/javascript/flavours/glitch/components/account.jsx index 29ffc60c6bacd5..cfc232805b0502 100644 --- a/app/javascript/flavours/glitch/components/account.jsx +++ b/app/javascript/flavours/glitch/components/account.jsx @@ -9,6 +9,7 @@ import ImmutablePropTypes from 'react-immutable-proptypes'; import MoreHorizIcon from '@/material-icons/400-24px/more_horiz.svg?react'; import { EmptyAccount } from 'flavours/glitch/components/empty_account'; +import { FollowButton } from 'flavours/glitch/components/follow_button'; import { ShortNumber } from 'flavours/glitch/components/short_number'; import { VerifiedBadge } from 'flavours/glitch/components/verified_badge'; @@ -23,9 +24,6 @@ import { Permalink } from './permalink'; import { RelativeTimestamp } from './relative_timestamp'; const messages = defineMessages({ - follow: { id: 'account.follow', defaultMessage: 'Follow' }, - unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, - cancel_follow_request: { id: 'account.cancel_follow_request', defaultMessage: 'Withdraw follow request' }, unblock: { id: 'account.unblock_short', defaultMessage: 'Unblock' }, unmute: { id: 'account.unmute_short', defaultMessage: 'Unmute' }, mute_notifications: { id: 'account.mute_notifications_short', defaultMessage: 'Mute notifications' }, @@ -35,13 +33,9 @@ const messages = defineMessages({ more: { id: 'status.more', defaultMessage: 'More' }, }); -const Account = ({ size = 46, account, onFollow, onBlock, onMute, onMuteNotifications, hidden, minimal, defaultAction, withBio }) => { +const Account = ({ size = 46, account, onBlock, onMute, onMuteNotifications, hidden, minimal, defaultAction, withBio }) => { const intl = useIntl(); - const handleFollow = useCallback(() => { - onFollow(account); - }, [onFollow, account]); - const handleBlock = useCallback(() => { onBlock(account); }, [onBlock, account]); @@ -74,13 +68,12 @@ const Account = ({ size = 46, account, onFollow, onBlock, onMute, onMuteNotifica let buttons; if (account.get('id') !== me && account.get('relationship', null) !== null) { - const following = account.getIn(['relationship', 'following']); const requested = account.getIn(['relationship', 'requested']); const blocking = account.getIn(['relationship', 'blocking']); const muting = account.getIn(['relationship', 'muting']); if (requested) { - buttons = + )} + + ); +}; diff --git a/app/javascript/flavours/glitch/components/content_warning.tsx b/app/javascript/flavours/glitch/components/content_warning.tsx index 82f9ca83ed4907..982365b0392308 100644 --- a/app/javascript/flavours/glitch/components/content_warning.tsx +++ b/app/javascript/flavours/glitch/components/content_warning.tsx @@ -1,6 +1,4 @@ -/* Significantly rewritten from upstream to keep the old design for now */ - -import { FormattedMessage } from 'react-intl'; +import { StatusBanner, BannerVariant } from './status_banner'; export const ContentWarning: React.FC<{ text: string; @@ -8,20 +6,12 @@ export const ContentWarning: React.FC<{ onClick?: () => void; icons?: React.ReactNode[]; }> = ({ text, expanded, onClick, icons }) => ( -

- {' '} - -

+ + {icons} +

+ ); diff --git a/app/javascript/flavours/glitch/components/filter_warning.tsx b/app/javascript/flavours/glitch/components/filter_warning.tsx index 4305e43038df9f..5eaaac4ba38686 100644 --- a/app/javascript/flavours/glitch/components/filter_warning.tsx +++ b/app/javascript/flavours/glitch/components/filter_warning.tsx @@ -10,13 +10,16 @@ export const FilterWarning: React.FC<{

{chunks}, + }} />

diff --git a/app/javascript/flavours/glitch/components/follow_button.tsx b/app/javascript/flavours/glitch/components/follow_button.tsx index a27872c1aac8dc..4b32f8d1481509 100644 --- a/app/javascript/flavours/glitch/components/follow_button.tsx +++ b/app/javascript/flavours/glitch/components/follow_button.tsx @@ -99,7 +99,12 @@ export const FollowButton: React.FC<{ return ( } + {!showResults && } {!showResults && <> · } {showResults && !this.props.disabled && <> · } {votesCount} diff --git a/app/javascript/flavours/glitch/components/scrollable_list.jsx b/app/javascript/flavours/glitch/components/scrollable_list.jsx index 82d32185e187cf..c7108c28e12254 100644 --- a/app/javascript/flavours/glitch/components/scrollable_list.jsx +++ b/app/javascript/flavours/glitch/components/scrollable_list.jsx @@ -80,6 +80,7 @@ class ScrollableList extends PureComponent { children: PropTypes.node, bindToDocument: PropTypes.bool, preventScroll: PropTypes.bool, + footer: PropTypes.node, }; static defaultProps = { @@ -324,7 +325,7 @@ class ScrollableList extends PureComponent { }; render () { - const { children, scrollKey, trackScroll, showLoading, isLoading, hasMore, numPending, prepend, alwaysPrepend, append, emptyMessage, onLoadMore } = this.props; + const { children, scrollKey, trackScroll, showLoading, isLoading, hasMore, numPending, prepend, alwaysPrepend, append, footer, emptyMessage, onLoadMore } = this.props; const { fullscreen } = this.state; const childrenCount = Children.count(children); @@ -342,11 +343,13 @@ class ScrollableList extends PureComponent {
+ + {footer} ); } else if (isLoading || childrenCount > 0 || hasMore || !emptyMessage) { scrollableArea = ( -
+
{prepend} @@ -375,6 +378,8 @@ class ScrollableList extends PureComponent { {!hasMore && append}
+ + {footer}
); } else { @@ -385,6 +390,8 @@ class ScrollableList extends PureComponent {
{emptyMessage}
+ + {footer}
); } diff --git a/app/javascript/flavours/glitch/components/short_number.tsx b/app/javascript/flavours/glitch/components/short_number.tsx index a0b523aaadc920..37201a5e1d7126 100644 --- a/app/javascript/flavours/glitch/components/short_number.tsx +++ b/app/javascript/flavours/glitch/components/short_number.tsx @@ -1,4 +1,5 @@ import { memo } from 'react'; +import type { JSX } from 'react'; import { FormattedMessage, FormattedNumber } from 'react-intl'; diff --git a/app/javascript/flavours/glitch/components/status.jsx b/app/javascript/flavours/glitch/components/status.jsx index d31a2be790f430..b68fb9013d954f 100644 --- a/app/javascript/flavours/glitch/components/status.jsx +++ b/app/javascript/flavours/glitch/components/status.jsx @@ -373,26 +373,29 @@ class Status extends ImmutablePureComponent { const { isCollapsed } = this.state; if (!history) return; - if (e.button === 0 && !(e.ctrlKey || e.altKey || e.metaKey)) { - if (isCollapsed) this.setCollapsed(false); - else if (e.shiftKey) { - this.setCollapsed(true); - document.getSelection().removeAllRanges(); - } else if (this.props.onClick) { - this.props.onClick(); - return; - } else { - if (destination === undefined) { - destination = `/@${ - status.getIn(['reblog', 'account', 'acct'], status.getIn(['account', 'acct'])) - }/${ - status.getIn(['reblog', 'id'], status.get('id')) - }`; - } - history.push(destination); + if (e.button !== 0 || e.ctrlKey || e.altKey || e.metaKey) { + return; + } + + if (isCollapsed) this.setCollapsed(false); + else if (e.shiftKey) { + this.setCollapsed(true); + document.getSelection().removeAllRanges(); + } else if (this.props.onClick) { + this.props.onClick(); + return; + } else { + if (destination === undefined) { + destination = `/@${ + status.getIn(['reblog', 'account', 'acct'], status.getIn(['account', 'acct'])) + }/${ + status.getIn(['reblog', 'id'], status.get('id')) + }`; } - e.preventDefault(); + history.push(destination); } + + e.preventDefault(); }; handleToggleMediaVisibility = () => { @@ -542,7 +545,6 @@ class Status extends ImmutablePureComponent { ...other } = this.props; const { isCollapsed } = this.state; - let background = null; let attachments = null; // Depending on user settings, some media are considered as parts of the @@ -584,22 +586,23 @@ class Status extends ImmutablePureComponent { let prepend, rebloggedByText; + const connectUp = previousId && previousId === status.get('in_reply_to_id'); + const connectToRoot = rootId && rootId === status.get('in_reply_to_id'); + const connectReply = nextInReplyToId && nextInReplyToId === status.get('id'); + const matchedFilters = status.get('matched_filters'); + if (hidden) { return (
{status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])} - {status.get('content')} + {status.get('spoiler_text').length > 0 && ({status.get('spoiler_text')})} + {isExpanded && {status.get('content')}}
); } - const connectUp = previousId && previousId === status.get('in_reply_to_id'); - const connectToRoot = rootId && rootId === status.get('in_reply_to_id'); - const connectReply = nextInReplyToId && nextInReplyToId === status.get('id'); - const matchedFilters = status.get('matched_filters'); - if (this.state.forceFilter === undefined ? matchedFilters : this.state.forceFilter) { const minHandlers = this.props.muted ? {} : { moveUp: this.handleHotkeyMoveUp, @@ -619,21 +622,10 @@ class Status extends ImmutablePureComponent { ); } - // If user backgrounds for collapsed statuses are enabled, then we - // initialize our background accordingly. This will only be rendered if - // the status is collapsed. - if (settings.getIn(['collapsed', 'backgrounds', 'user_backgrounds'])) { - background = status.getIn(['account', 'header']); - } - // This handles our media attachments. // If a media file is of unknwon type or if the status is muted // (notification), we show a list of links instead of embedded media. - // After we have generated our appropriate media element and stored it in - // `media`, we snatch the thumbnail to use as our `background` if media - // backgrounds for collapsed statuses are enabled. - attachments = status.get('media_attachments'); if (pictureInPicture.get('inUse')) { @@ -649,7 +641,7 @@ class Status extends ImmutablePureComponent { media={status.get('media_attachments')} />, ); - } else if (['image', 'gifv'].includes(status.getIn(['media_attachments', 0, 'type'])) || status.get('media_attachments').size > 1) { + } else if (['image', 'gifv', 'unknown'].includes(status.getIn(['media_attachments', 0, 'type'])) || status.get('media_attachments').size > 1) { media.push( {Component => ( @@ -726,10 +718,6 @@ class Status extends ImmutablePureComponent { ); mediaIcons.push('video-camera'); } - - if (!status.get('sensitive') && !(status.get('spoiler_text').length > 0) && settings.getIn(['collapsed', 'backgrounds', 'preview_images'])) { - background = attachments.getIn([0, 'preview_url']); - } } else if (status.get('card') && settings.get('inline_preview_cards') && !this.props.muted) { media.push( ); + contentMedia.push(); contentMediaIcons.push('tasks'); } @@ -800,14 +788,14 @@ class Status extends ImmutablePureComponent { {!skipPrepend && prepend}
{(connectReply || connectUp || connectToRoot) &&
} {(!muted || !isCollapsed) && ( -
+ /* eslint-disable-next-line jsx-a11y/no-static-element-interactions */ +
void; }> = ({ children, variant, expanded, onClick }) => ( -
+ ) : variant === BannerVariant.Warning ? ( + ) : ( )} -
+ ); diff --git a/app/javascript/flavours/glitch/components/status_content.jsx b/app/javascript/flavours/glitch/components/status_content.jsx index 7dd5dba69be0c9..22e3a62364ad35 100644 --- a/app/javascript/flavours/glitch/components/status_content.jsx +++ b/app/javascript/flavours/glitch/components/status_content.jsx @@ -396,7 +396,7 @@ class StatusContent extends PureComponent { )).reduce((aggregate, item) => [...aggregate, item, ' '], []); let spoilerIcons = []; - if (hidden && mediaIcons) { + if (mediaIcons) { const mediaComponents = { 'link': LinkIcon, 'picture-o': ImageIcon, diff --git a/app/javascript/flavours/glitch/components/status_header.jsx b/app/javascript/flavours/glitch/components/status_header.jsx index 5eeed3d41dcdae..dffffe4fb8512e 100644 --- a/app/javascript/flavours/glitch/components/status_header.jsx +++ b/app/javascript/flavours/glitch/components/status_header.jsx @@ -18,15 +18,10 @@ export default class StatusHeader extends PureComponent { parseClick: PropTypes.func.isRequired, }; - // Handles clicks on account name/image - handleClick = (acct, e) => { - const { parseClick } = this.props; - parseClick(e, `/@${acct}`); - }; - handleAccountClick = (e) => { - const { status } = this.props; - this.handleClick(status.getIn(['account', 'acct']), e); + const { status, parseClick } = this.props; + parseClick(e, `/@${status.getIn(['account', 'acct'])}`); + e.stopPropagation(); }; // Rendering. diff --git a/app/javascript/flavours/glitch/containers/dropdown_menu_container.js b/app/javascript/flavours/glitch/containers/dropdown_menu_container.js index 75501967424645..93f5a574b2ff57 100644 --- a/app/javascript/flavours/glitch/containers/dropdown_menu_container.js +++ b/app/javascript/flavours/glitch/containers/dropdown_menu_container.js @@ -13,6 +13,13 @@ const mapStateToProps = state => ({ openedViaKeyboard: state.dropdownMenu.keyboard, }); +/** + * @param {any} dispatch + * @param {Object} root0 + * @param {any} [root0.status] + * @param {any} root0.items + * @param {any} [root0.scrollKey] + */ const mapDispatchToProps = (dispatch, { status, items, scrollKey }) => ({ onOpen(id, onItemClick, keyboard) { dispatch(isUserTouching() ? openModal({ diff --git a/app/javascript/flavours/glitch/containers/poll_container.js b/app/javascript/flavours/glitch/containers/poll_container.js index e25dd061486282..710bed45c540df 100644 --- a/app/javascript/flavours/glitch/containers/poll_container.js +++ b/app/javascript/flavours/glitch/containers/poll_container.js @@ -2,6 +2,7 @@ import { connect } from 'react-redux'; import { debounce } from 'lodash'; +import { openModal } from 'flavours/glitch/actions/modal'; import { fetchPoll, vote } from 'flavours/glitch/actions/polls'; import Poll from 'flavours/glitch/components/poll'; @@ -17,6 +18,17 @@ const mapDispatchToProps = (dispatch, { pollId }) => ({ onVote (choices) { dispatch(vote(pollId, choices)); }, + + onInteractionModal (type, status) { + dispatch(openModal({ + modalType: 'INTERACTION', + modalProps: { + type, + accountId: status.getIn(['account', 'id']), + url: status.get('uri'), + }, + })); + } }); const mapStateToProps = (state, { pollId }) => ({ diff --git a/app/javascript/flavours/glitch/entrypoints/public.tsx b/app/javascript/flavours/glitch/entrypoints/public.tsx index 41c0e343968757..245495744149fc 100644 --- a/app/javascript/flavours/glitch/entrypoints/public.tsx +++ b/app/javascript/flavours/glitch/entrypoints/public.tsx @@ -230,62 +230,6 @@ function loaded() { } }, ); - - Rails.delegate( - document, - 'button.status__content__spoiler-link', - 'click', - function () { - if (!(this instanceof HTMLButtonElement)) return; - - const statusEl = this.parentNode?.parentNode; - - if ( - !( - statusEl instanceof HTMLDivElement && - statusEl.classList.contains('.status__content') - ) - ) - return; - - if (statusEl.dataset.spoiler === 'expanded') { - statusEl.dataset.spoiler = 'folded'; - this.textContent = new IntlMessageFormat( - localeData['status.show_more'] ?? 'Show more', - locale, - ).format() as string; - } else { - statusEl.dataset.spoiler = 'expanded'; - this.textContent = new IntlMessageFormat( - localeData['status.show_less'] ?? 'Show less', - locale, - ).format() as string; - } - }, - ); - - document - .querySelectorAll('button.status__content__spoiler-link') - .forEach((spoilerLink) => { - const statusEl = spoilerLink.parentNode?.parentNode; - - if ( - !( - statusEl instanceof HTMLDivElement && - statusEl.classList.contains('.status__content') - ) - ) - return; - - const message = - statusEl.dataset.spoiler === 'expanded' - ? (localeData['status.show_less'] ?? 'Show less') - : (localeData['status.show_more'] ?? 'Show more'); - spoilerLink.textContent = new IntlMessageFormat( - message, - locale, - ).format() as string; - }); } Rails.delegate( @@ -327,31 +271,24 @@ Rails.delegate(document, '.input-copy button', 'click', ({ target }) => { if (!input) return; - const oldReadOnly = input.readOnly; - - input.readOnly = false; - input.focus(); - input.select(); - input.setSelectionRange(0, input.value.length); - - try { - if (document.execCommand('copy')) { - input.blur(); - + navigator.clipboard + .writeText(input.value) + .then(() => { const parent = target.parentElement; - if (!parent) return; - parent.classList.add('copied'); + if (parent) { + parent.classList.add('copied'); - setTimeout(() => { - parent.classList.remove('copied'); - }, 700); - } - } catch (err) { - console.error(err); - } + setTimeout(() => { + parent.classList.remove('copied'); + }, 700); + } - input.readOnly = oldReadOnly; + return true; + }) + .catch((error: unknown) => { + console.error(error); + }); }); const toggleSidebar = () => { @@ -446,6 +383,24 @@ Rails.delegate(document, '#registration_new_user,#new_user', 'submit', () => { }); }); +Rails.delegate(document, '.rules-list button', 'click', ({ target }) => { + if (!(target instanceof HTMLElement)) { + return; + } + + const button = target.closest('button'); + + if (!button) { + return; + } + + if (button.ariaExpanded === 'true') { + button.ariaExpanded = 'false'; + } else { + button.ariaExpanded = 'true'; + } +}); + function main() { ready(loaded).catch((error: unknown) => { console.error(error); diff --git a/app/javascript/flavours/glitch/features/annual_report/archetype.tsx b/app/javascript/flavours/glitch/features/annual_report/archetype.tsx new file mode 100644 index 00000000000000..604f401039e1bb --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/archetype.tsx @@ -0,0 +1,69 @@ +import { FormattedMessage } from 'react-intl'; + +import booster from '@/images/archetypes/booster.png'; +import lurker from '@/images/archetypes/lurker.png'; +import oracle from '@/images/archetypes/oracle.png'; +import pollster from '@/images/archetypes/pollster.png'; +import replier from '@/images/archetypes/replier.png'; +import type { Archetype as ArchetypeData } from 'flavours/glitch/models/annual_report'; + +export const Archetype: React.FC<{ + data: ArchetypeData; +}> = ({ data }) => { + let illustration, label; + + switch (data) { + case 'booster': + illustration = booster; + label = ( + + ); + break; + case 'replier': + illustration = replier; + label = ( + + ); + break; + case 'pollster': + illustration = pollster; + label = ( + + ); + break; + case 'lurker': + illustration = lurker; + label = ( + + ); + break; + case 'oracle': + illustration = oracle; + label = ( + + ); + break; + } + + return ( +
+
{label}
+ +
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/followers.tsx b/app/javascript/flavours/glitch/features/annual_report/followers.tsx new file mode 100644 index 00000000000000..e5238705d797f0 --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/followers.tsx @@ -0,0 +1,69 @@ +import { FormattedMessage, FormattedNumber } from 'react-intl'; + +import { Sparklines, SparklinesCurve } from 'react-sparklines'; + +import { ShortNumber } from 'flavours/glitch/components/short_number'; +import type { TimeSeriesMonth } from 'flavours/glitch/models/annual_report'; + +export const Followers: React.FC<{ + data: TimeSeriesMonth[]; + total?: number; +}> = ({ data, total }) => { + const change = data.reduce((sum, item) => sum + item.followers, 0); + + const cumulativeGraph = data.reduce( + (newData, item) => [ + ...newData, + item.followers + (newData[newData.length - 1] ?? 0), + ], + [0], + ); + + return ( +
+ + + + + + + + + + + + + +
+
+ {change > -1 ? '+' : '-'} + +
+ +
+ + + +
+ }} + /> +
+
+
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/highlighted_post.tsx b/app/javascript/flavours/glitch/features/annual_report/highlighted_post.tsx new file mode 100644 index 00000000000000..e66752b53eb9dc --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/highlighted_post.tsx @@ -0,0 +1,109 @@ +/* eslint-disable @typescript-eslint/no-unsafe-return, + @typescript-eslint/no-explicit-any, + @typescript-eslint/no-unsafe-assignment */ + +import { useCallback } from 'react'; + +import { FormattedMessage } from 'react-intl'; + +import { toggleStatusSpoilers } from 'flavours/glitch/actions/statuses'; +import { DetailedStatus } from 'flavours/glitch/features/status/components/detailed_status'; +import { me } from 'flavours/glitch/initial_state'; +import type { TopStatuses } from 'flavours/glitch/models/annual_report'; +import { + makeGetStatus, + makeGetPictureInPicture, +} from 'flavours/glitch/selectors'; +import { useAppSelector, useAppDispatch } from 'flavours/glitch/store'; + +const getStatus = makeGetStatus() as unknown as (arg0: any, arg1: any) => any; +const getPictureInPicture = makeGetPictureInPicture() as unknown as ( + arg0: any, + arg1: any, +) => any; + +export const HighlightedPost: React.FC<{ + data: TopStatuses; +}> = ({ data }) => { + let statusId, label; + + if (data.by_reblogs) { + statusId = data.by_reblogs; + label = ( + + ); + } else if (data.by_favourites) { + statusId = data.by_favourites; + label = ( + + ); + } else { + statusId = data.by_replies; + label = ( + + ); + } + + const dispatch = useAppDispatch(); + const domain = useAppSelector((state) => state.meta.get('domain')); + const status = useAppSelector((state) => + statusId ? getStatus(state, { id: statusId }) : undefined, + ); + const pictureInPicture = useAppSelector((state) => + statusId ? getPictureInPicture(state, { id: statusId }) : undefined, + ); + const account = useAppSelector((state) => + me ? state.accounts.get(me) : undefined, + ); + + const handleToggleHidden = useCallback(() => { + dispatch(toggleStatusSpoilers(statusId)); + }, [dispatch, statusId]); + + if (!status) { + return ( +
+ ); + } + + const displayName = ( + + + + ), + }} + /> + + {label} + + ); + + return ( +
+ +
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/index.tsx b/app/javascript/flavours/glitch/features/annual_report/index.tsx new file mode 100644 index 00000000000000..0c737934b4bea1 --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/index.tsx @@ -0,0 +1,99 @@ +import { useState, useEffect } from 'react'; + +import { FormattedMessage } from 'react-intl'; + +import { + importFetchedStatuses, + importFetchedAccounts, +} from 'flavours/glitch/actions/importer'; +import { apiRequestGet, apiRequestPost } from 'flavours/glitch/api'; +import { LoadingIndicator } from 'flavours/glitch/components/loading_indicator'; +import { me } from 'flavours/glitch/initial_state'; +import type { Account } from 'flavours/glitch/models/account'; +import type { AnnualReport as AnnualReportData } from 'flavours/glitch/models/annual_report'; +import type { Status } from 'flavours/glitch/models/status'; +import { useAppSelector, useAppDispatch } from 'flavours/glitch/store'; + +import { Archetype } from './archetype'; +import { Followers } from './followers'; +import { HighlightedPost } from './highlighted_post'; +import { MostUsedHashtag } from './most_used_hashtag'; +import { NewPosts } from './new_posts'; +import { Percentile } from './percentile'; + +interface AnnualReportResponse { + annual_reports: AnnualReportData[]; + accounts: Account[]; + statuses: Status[]; +} + +export const AnnualReport: React.FC<{ + year: string; +}> = ({ year }) => { + const [response, setResponse] = useState(null); + const [loading, setLoading] = useState(false); + const currentAccount = useAppSelector((state) => + me ? state.accounts.get(me) : undefined, + ); + const dispatch = useAppDispatch(); + + useEffect(() => { + setLoading(true); + + apiRequestGet(`v1/annual_reports/${year}`) + .then((data) => { + dispatch(importFetchedStatuses(data.statuses)); + dispatch(importFetchedAccounts(data.accounts)); + + setResponse(data); + setLoading(false); + + return apiRequestPost(`v1/annual_reports/${year}/read`); + }) + .catch(() => { + setLoading(false); + }); + }, [dispatch, year, setResponse, setLoading]); + + if (loading) { + return ; + } + + const report = response?.annual_reports[0]; + + if (!report) { + return null; + } + + return ( +
+
+

+ +

+

+ +

+
+ +
+ + + + + + +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/most_used_app.tsx b/app/javascript/flavours/glitch/features/annual_report/most_used_app.tsx new file mode 100644 index 00000000000000..f78a02b296a008 --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/most_used_app.tsx @@ -0,0 +1,29 @@ +import { FormattedMessage } from 'react-intl'; + +import type { NameAndCount } from 'flavours/glitch/models/annual_report'; + +export const MostUsedApp: React.FC<{ + data: NameAndCount[]; +}> = ({ data }) => { + const app = data[0]; + + if (!app) { + return ( +
+ ); + } + + return ( +
+
+ {app.name} +
+
+ +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/most_used_hashtag.tsx b/app/javascript/flavours/glitch/features/annual_report/most_used_hashtag.tsx new file mode 100644 index 00000000000000..6bf7493960d2fb --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/most_used_hashtag.tsx @@ -0,0 +1,30 @@ +import { FormattedMessage } from 'react-intl'; + +import type { NameAndCount } from 'flavours/glitch/models/annual_report'; + +export const MostUsedHashtag: React.FC<{ + data: NameAndCount[]; +}> = ({ data }) => { + const hashtag = data[0]; + + return ( +
+
+ {hashtag ? ( + <>#{hashtag.name} + ) : ( + + )} +
+
+ +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/new_posts.tsx b/app/javascript/flavours/glitch/features/annual_report/new_posts.tsx new file mode 100644 index 00000000000000..4ca286debb68d5 --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/new_posts.tsx @@ -0,0 +1,53 @@ +import { FormattedNumber, FormattedMessage } from 'react-intl'; + +import ChatBubbleIcon from '@/material-icons/400-24px/chat_bubble.svg?react'; +import type { TimeSeriesMonth } from 'flavours/glitch/models/annual_report'; + +export const NewPosts: React.FC<{ + data: TimeSeriesMonth[]; +}> = ({ data }) => { + const posts = data.reduce((sum, item) => sum + item.statuses, 0); + + return ( +
+ + + + + + + + + + + +
+ +
+
+ +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/annual_report/percentile.tsx b/app/javascript/flavours/glitch/features/annual_report/percentile.tsx new file mode 100644 index 00000000000000..1c7b4c3b5b3fc5 --- /dev/null +++ b/app/javascript/flavours/glitch/features/annual_report/percentile.tsx @@ -0,0 +1,53 @@ +/* eslint-disable react/jsx-no-useless-fragment */ +import { FormattedMessage, FormattedNumber } from 'react-intl'; + +import type { Percentiles } from 'flavours/glitch/models/annual_report'; + +export const Percentile: React.FC<{ + data: Percentiles; +}> = ({ data }) => { + const percentile = data.statuses; + + return ( +
+ ( +
+ {str} +
+ ), + percentage: () => ( +
+ +
+ ), + bottomLabel: (str) => ( +
+
+ {str} +
+ + {percentile < 6 && ( +
+ +
+ )} +
+ ), + }} + > + {(message) => <>{message}} +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/explore/links.jsx b/app/javascript/flavours/glitch/features/explore/links.jsx index b5eb9c9d4f4f51..1d57f6c095e0b7 100644 --- a/app/javascript/flavours/glitch/features/explore/links.jsx +++ b/app/javascript/flavours/glitch/features/explore/links.jsx @@ -45,7 +45,7 @@ class Links extends PureComponent { const banner = ( - + ); diff --git a/app/javascript/flavours/glitch/features/explore/statuses.jsx b/app/javascript/flavours/glitch/features/explore/statuses.jsx index 888d75bb342a55..a76868c26d1505 100644 --- a/app/javascript/flavours/glitch/features/explore/statuses.jsx +++ b/app/javascript/flavours/glitch/features/explore/statuses.jsx @@ -58,7 +58,7 @@ class Statuses extends PureComponent { return ( } + prepend={} alwaysPrepend timelineId='explore' statusIds={statusIds} diff --git a/app/javascript/flavours/glitch/features/explore/suggestions.jsx b/app/javascript/flavours/glitch/features/explore/suggestions.jsx index 18a40c28b6c3af..a5d029fc269810 100644 --- a/app/javascript/flavours/glitch/features/explore/suggestions.jsx +++ b/app/javascript/flavours/glitch/features/explore/suggestions.jsx @@ -5,25 +5,24 @@ import { FormattedMessage } from 'react-intl'; import { withRouter } from 'react-router-dom'; -import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; -import { fetchSuggestions, dismissSuggestion } from 'flavours/glitch/actions/suggestions'; +import { fetchSuggestions } from 'flavours/glitch/actions/suggestions'; import { LoadingIndicator } from 'flavours/glitch/components/loading_indicator'; import { WithRouterPropTypes } from 'flavours/glitch/utils/react_router'; import { Card } from './components/card'; const mapStateToProps = state => ({ - suggestions: state.getIn(['suggestions', 'items']), - isLoading: state.getIn(['suggestions', 'isLoading']), + suggestions: state.suggestions.items, + isLoading: state.suggestions.isLoading, }); class Suggestions extends PureComponent { static propTypes = { isLoading: PropTypes.bool, - suggestions: ImmutablePropTypes.list, + suggestions: PropTypes.array, dispatch: PropTypes.func.isRequired, ...WithRouterPropTypes, }; @@ -32,22 +31,17 @@ class Suggestions extends PureComponent { const { dispatch, suggestions, history } = this.props; // If we're navigating back to the screen, do not trigger a reload - if (history.action === 'POP' && suggestions.size > 0) { + if (history.action === 'POP' && suggestions.length > 0) { return; } - dispatch(fetchSuggestions(true)); + dispatch(fetchSuggestions()); } - handleDismiss = (accountId) => { - const { dispatch } = this.props; - dispatch(dismissSuggestion(accountId)); - }; - render () { const { isLoading, suggestions } = this.props; - if (!isLoading && suggestions.isEmpty()) { + if (!isLoading && suggestions.length === 0) { return (
@@ -61,9 +55,9 @@ class Suggestions extends PureComponent {
{isLoading ? : suggestions.map(suggestion => ( ))}
diff --git a/app/javascript/flavours/glitch/features/explore/tags.jsx b/app/javascript/flavours/glitch/features/explore/tags.jsx index 5f88a79eb60199..27d789c5e317b5 100644 --- a/app/javascript/flavours/glitch/features/explore/tags.jsx +++ b/app/javascript/flavours/glitch/features/explore/tags.jsx @@ -44,7 +44,7 @@ class Tags extends PureComponent { const banner = ( - + ); diff --git a/app/javascript/flavours/glitch/features/firehose/index.jsx b/app/javascript/flavours/glitch/features/firehose/index.jsx index 2a6d790d52aeeb..84b87b8b2ae60a 100644 --- a/app/javascript/flavours/glitch/features/firehose/index.jsx +++ b/app/javascript/flavours/glitch/features/firehose/index.jsx @@ -159,7 +159,7 @@ const Firehose = ({ feedType, multiColumn }) => { diff --git a/app/javascript/flavours/glitch/features/follow_requests/index.jsx b/app/javascript/flavours/glitch/features/follow_requests/index.jsx index a8f40a31d0d007..7d651f2ca69c24 100644 --- a/app/javascript/flavours/glitch/features/follow_requests/index.jsx +++ b/app/javascript/flavours/glitch/features/follow_requests/index.jsx @@ -68,7 +68,7 @@ class FollowRequests extends ImmutablePureComponent { ); return ( - + { - this.props.dispatch(openModal({ - modalType: 'PINNED_ACCOUNTS_EDITOR', - })); - }; - render () { const { intl } = this.props; const { signedIn } = this.props.identity; @@ -54,7 +45,6 @@ class GettingStartedMisc extends ImmutablePureComponent { {signedIn && ()} {signedIn && ()} - {signedIn && ()} {signedIn && ()} {signedIn && ()} {signedIn && ()} diff --git a/app/javascript/flavours/glitch/features/hashtag_timeline/components/hashtag_header.jsx b/app/javascript/flavours/glitch/features/hashtag_timeline/components/hashtag_header.jsx index 47854d72be6c86..96dda2531856e7 100644 --- a/app/javascript/flavours/glitch/features/hashtag_timeline/components/hashtag_header.jsx +++ b/app/javascript/flavours/glitch/features/hashtag_timeline/components/hashtag_header.jsx @@ -4,12 +4,17 @@ import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; +import MoreHorizIcon from '@/material-icons/400-24px/more_horiz.svg?react'; import { Button } from 'flavours/glitch/components/button'; import { ShortNumber } from 'flavours/glitch/components/short_number'; +import DropdownMenuContainer from 'flavours/glitch/containers/dropdown_menu_container'; +import { withIdentity } from 'flavours/glitch/identity_context'; +import { PERMISSION_MANAGE_TAXONOMIES } from 'flavours/glitch/permissions'; const messages = defineMessages({ followHashtag: { id: 'hashtag.follow', defaultMessage: 'Follow hashtag' }, unfollowHashtag: { id: 'hashtag.unfollow', defaultMessage: 'Unfollow hashtag' }, + adminModeration: { id: 'hashtag.admin_moderation', defaultMessage: 'Open moderation interface for #{name}' }, }); const usesRenderer = (displayNumber, pluralReady) => ( @@ -45,11 +50,18 @@ const usesTodayRenderer = (displayNumber, pluralReady) => ( /> ); -export const HashtagHeader = injectIntl(({ tag, intl, disabled, onClick }) => { +export const HashtagHeader = withIdentity(injectIntl(({ tag, intl, disabled, onClick, identity }) => { if (!tag) { return null; } + const { signedIn, permissions } = identity; + const menu = []; + + if (signedIn && (permissions & PERMISSION_MANAGE_TAXONOMIES) === PERMISSION_MANAGE_TAXONOMIES ) { + menu.push({ text: intl.formatMessage(messages.adminModeration, { name: tag.get("name") }), href: `/admin/tags/${tag.get('id')}` }); + } + const [uses, people] = tag.get('history').reduce((arr, day) => [arr[0] + day.get('uses') * 1, arr[1] + day.get('accounts') * 1], [0, 0]); const dividingCircle = {' · '}; @@ -57,7 +69,10 @@ export const HashtagHeader = injectIntl(({ tag, intl, disabled, onClick }) => {

#{tag.get('name')}

-
@@ -69,7 +84,7 @@ export const HashtagHeader = injectIntl(({ tag, intl, disabled, onClick }) => {
); -}); +})); HashtagHeader.propTypes = { tag: ImmutablePropTypes.map, diff --git a/app/javascript/flavours/glitch/features/home_timeline/components/inline_follow_suggestions.jsx b/app/javascript/flavours/glitch/features/home_timeline/components/inline_follow_suggestions.jsx deleted file mode 100644 index 9734763138a8e8..00000000000000 --- a/app/javascript/flavours/glitch/features/home_timeline/components/inline_follow_suggestions.jsx +++ /dev/null @@ -1,217 +0,0 @@ -import PropTypes from 'prop-types'; -import { useEffect, useCallback, useRef, useState } from 'react'; - -import { FormattedMessage, useIntl, defineMessages } from 'react-intl'; - -import { Link } from 'react-router-dom'; - -import ImmutablePropTypes from 'react-immutable-proptypes'; -import { useDispatch, useSelector } from 'react-redux'; - -import ChevronLeftIcon from '@/material-icons/400-24px/chevron_left.svg?react'; -import ChevronRightIcon from '@/material-icons/400-24px/chevron_right.svg?react'; -import CloseIcon from '@/material-icons/400-24px/close.svg?react'; -import InfoIcon from '@/material-icons/400-24px/info.svg?react'; -import { changeSetting } from 'flavours/glitch/actions/settings'; -import { fetchSuggestions, dismissSuggestion } from 'flavours/glitch/actions/suggestions'; -import { Avatar } from 'flavours/glitch/components/avatar'; -import { DisplayName } from 'flavours/glitch/components/display_name'; -import { FollowButton } from 'flavours/glitch/components/follow_button'; -import { Icon } from 'flavours/glitch/components/icon'; -import { IconButton } from 'flavours/glitch/components/icon_button'; -import { VerifiedBadge } from 'flavours/glitch/components/verified_badge'; -import { domain } from 'flavours/glitch/initial_state'; - -const messages = defineMessages({ - follow: { id: 'account.follow', defaultMessage: 'Follow' }, - unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, - previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, - next: { id: 'lightbox.next', defaultMessage: 'Next' }, - dismiss: { id: 'follow_suggestions.dismiss', defaultMessage: "Don't show again" }, - friendsOfFriendsHint: { id: 'follow_suggestions.hints.friends_of_friends', defaultMessage: 'This profile is popular among the people you follow.' }, - similarToRecentlyFollowedHint: { id: 'follow_suggestions.hints.similar_to_recently_followed', defaultMessage: 'This profile is similar to the profiles you have most recently followed.' }, - featuredHint: { id: 'follow_suggestions.hints.featured', defaultMessage: 'This profile has been hand-picked by the {domain} team.' }, - mostFollowedHint: { id: 'follow_suggestions.hints.most_followed', defaultMessage: 'This profile is one of the most followed on {domain}.'}, - mostInteractionsHint: { id: 'follow_suggestions.hints.most_interactions', defaultMessage: 'This profile has been recently getting a lot of attention on {domain}.' }, -}); - -const Source = ({ id }) => { - const intl = useIntl(); - - let label, hint; - - switch (id) { - case 'friends_of_friends': - hint = intl.formatMessage(messages.friendsOfFriendsHint); - label = ; - break; - case 'similar_to_recently_followed': - hint = intl.formatMessage(messages.similarToRecentlyFollowedHint); - label = ; - break; - case 'featured': - hint = intl.formatMessage(messages.featuredHint, { domain }); - label = ; - break; - case 'most_followed': - hint = intl.formatMessage(messages.mostFollowedHint, { domain }); - label = ; - break; - case 'most_interactions': - hint = intl.formatMessage(messages.mostInteractionsHint, { domain }); - label = ; - break; - } - - return ( -
- - {label} -
- ); -}; - -Source.propTypes = { - id: PropTypes.oneOf(['friends_of_friends', 'similar_to_recently_followed', 'featured', 'most_followed', 'most_interactions']), -}; - -const Card = ({ id, sources }) => { - const intl = useIntl(); - const account = useSelector(state => state.getIn(['accounts', id])); - const firstVerifiedField = account.get('fields').find(item => !!item.get('verified_at')); - const dispatch = useDispatch(); - - const handleDismiss = useCallback(() => { - dispatch(dismissSuggestion(id)); - }, [id, dispatch]); - - return ( -
- - -
- -
- -
- - {firstVerifiedField ? : } -
- - -
- ); -}; - -Card.propTypes = { - id: PropTypes.string.isRequired, - sources: ImmutablePropTypes.list, -}; - -const DISMISSIBLE_ID = 'home/follow-suggestions'; - -export const InlineFollowSuggestions = ({ hidden }) => { - const intl = useIntl(); - const dispatch = useDispatch(); - const suggestions = useSelector(state => state.getIn(['suggestions', 'items'])); - const isLoading = useSelector(state => state.getIn(['suggestions', 'isLoading'])); - const dismissed = useSelector(state => state.getIn(['settings', 'dismissed_banners', DISMISSIBLE_ID])); - const bodyRef = useRef(); - const [canScrollLeft, setCanScrollLeft] = useState(false); - const [canScrollRight, setCanScrollRight] = useState(true); - - useEffect(() => { - dispatch(fetchSuggestions()); - }, [dispatch]); - - useEffect(() => { - if (!bodyRef.current) { - return; - } - - if (getComputedStyle(bodyRef.current).direction === 'rtl') { - setCanScrollLeft((bodyRef.current.clientWidth - bodyRef.current.scrollLeft) < bodyRef.current.scrollWidth); - setCanScrollRight(bodyRef.current.scrollLeft < 0); - } else { - setCanScrollLeft(bodyRef.current.scrollLeft > 0); - setCanScrollRight((bodyRef.current.scrollLeft + bodyRef.current.clientWidth) < bodyRef.current.scrollWidth); - } - }, [setCanScrollRight, setCanScrollLeft, bodyRef, suggestions]); - - const handleLeftNav = useCallback(() => { - bodyRef.current.scrollLeft -= 200; - }, [bodyRef]); - - const handleRightNav = useCallback(() => { - bodyRef.current.scrollLeft += 200; - }, [bodyRef]); - - const handleScroll = useCallback(() => { - if (!bodyRef.current) { - return; - } - - if (getComputedStyle(bodyRef.current).direction === 'rtl') { - setCanScrollLeft((bodyRef.current.clientWidth - bodyRef.current.scrollLeft) < bodyRef.current.scrollWidth); - setCanScrollRight(bodyRef.current.scrollLeft < 0); - } else { - setCanScrollLeft(bodyRef.current.scrollLeft > 0); - setCanScrollRight((bodyRef.current.scrollLeft + bodyRef.current.clientWidth) < bodyRef.current.scrollWidth); - } - }, [setCanScrollRight, setCanScrollLeft, bodyRef]); - - const handleDismiss = useCallback(() => { - dispatch(changeSetting(['dismissed_banners', DISMISSIBLE_ID], true)); - }, [dispatch]); - - if (dismissed || (!isLoading && suggestions.isEmpty())) { - return null; - } - - if (hidden) { - return ( -
- ); - } - - return ( -
-
-

- -
- - -
-
- -
-
- {suggestions.map(suggestion => ( - - ))} -
- - {canScrollLeft && ( - - )} - - {canScrollRight && ( - - )} -
-
- ); -}; - -InlineFollowSuggestions.propTypes = { - hidden: PropTypes.bool, -}; diff --git a/app/javascript/flavours/glitch/features/home_timeline/components/inline_follow_suggestions.tsx b/app/javascript/flavours/glitch/features/home_timeline/components/inline_follow_suggestions.tsx new file mode 100644 index 00000000000000..d980e698ce761e --- /dev/null +++ b/app/javascript/flavours/glitch/features/home_timeline/components/inline_follow_suggestions.tsx @@ -0,0 +1,326 @@ +import { useEffect, useCallback, useRef, useState } from 'react'; + +import { FormattedMessage, useIntl, defineMessages } from 'react-intl'; + +import { Link } from 'react-router-dom'; + +import ChevronLeftIcon from '@/material-icons/400-24px/chevron_left.svg?react'; +import ChevronRightIcon from '@/material-icons/400-24px/chevron_right.svg?react'; +import CloseIcon from '@/material-icons/400-24px/close.svg?react'; +import InfoIcon from '@/material-icons/400-24px/info.svg?react'; +import { changeSetting } from 'flavours/glitch/actions/settings'; +import { + fetchSuggestions, + dismissSuggestion, +} from 'flavours/glitch/actions/suggestions'; +import type { ApiSuggestionSourceJSON } from 'flavours/glitch/api_types/suggestions'; +import { Avatar } from 'flavours/glitch/components/avatar'; +import { DisplayName } from 'flavours/glitch/components/display_name'; +import { FollowButton } from 'flavours/glitch/components/follow_button'; +import { Icon } from 'flavours/glitch/components/icon'; +import { IconButton } from 'flavours/glitch/components/icon_button'; +import { VerifiedBadge } from 'flavours/glitch/components/verified_badge'; +import { domain } from 'flavours/glitch/initial_state'; +import { useAppDispatch, useAppSelector } from 'flavours/glitch/store'; + +const messages = defineMessages({ + follow: { id: 'account.follow', defaultMessage: 'Follow' }, + unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, + previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, + next: { id: 'lightbox.next', defaultMessage: 'Next' }, + dismiss: { + id: 'follow_suggestions.dismiss', + defaultMessage: "Don't show again", + }, + friendsOfFriendsHint: { + id: 'follow_suggestions.hints.friends_of_friends', + defaultMessage: 'This profile is popular among the people you follow.', + }, + similarToRecentlyFollowedHint: { + id: 'follow_suggestions.hints.similar_to_recently_followed', + defaultMessage: + 'This profile is similar to the profiles you have most recently followed.', + }, + featuredHint: { + id: 'follow_suggestions.hints.featured', + defaultMessage: 'This profile has been hand-picked by the {domain} team.', + }, + mostFollowedHint: { + id: 'follow_suggestions.hints.most_followed', + defaultMessage: 'This profile is one of the most followed on {domain}.', + }, + mostInteractionsHint: { + id: 'follow_suggestions.hints.most_interactions', + defaultMessage: + 'This profile has been recently getting a lot of attention on {domain}.', + }, +}); + +const Source: React.FC<{ + id: ApiSuggestionSourceJSON; +}> = ({ id }) => { + const intl = useIntl(); + + let label, hint; + + switch (id) { + case 'friends_of_friends': + hint = intl.formatMessage(messages.friendsOfFriendsHint); + label = ( + + ); + break; + case 'similar_to_recently_followed': + hint = intl.formatMessage(messages.similarToRecentlyFollowedHint); + label = ( + + ); + break; + case 'featured': + hint = intl.formatMessage(messages.featuredHint, { domain }); + label = ( + + ); + break; + case 'most_followed': + hint = intl.formatMessage(messages.mostFollowedHint, { domain }); + label = ( + + ); + break; + case 'most_interactions': + hint = intl.formatMessage(messages.mostInteractionsHint, { domain }); + label = ( + + ); + break; + } + + return ( +
+ + {label} +
+ ); +}; + +const Card: React.FC<{ + id: string; + sources: [ApiSuggestionSourceJSON, ...ApiSuggestionSourceJSON[]]; +}> = ({ id, sources }) => { + const intl = useIntl(); + const account = useAppSelector((state) => state.accounts.get(id)); + const firstVerifiedField = account?.fields.find((item) => !!item.verified_at); + const dispatch = useAppDispatch(); + + const handleDismiss = useCallback(() => { + void dispatch(dismissSuggestion({ accountId: id })); + }, [id, dispatch]); + + return ( +
+ + +
+ + + +
+ +
+ + + + {firstVerifiedField ? ( + + ) : ( + + )} +
+ + +
+ ); +}; + +const DISMISSIBLE_ID = 'home/follow-suggestions'; + +export const InlineFollowSuggestions: React.FC<{ + hidden?: boolean; +}> = ({ hidden }) => { + const intl = useIntl(); + const dispatch = useAppDispatch(); + const suggestions = useAppSelector((state) => state.suggestions.items); + const isLoading = useAppSelector((state) => state.suggestions.isLoading); + const dismissed = useAppSelector( + (state) => + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + state.settings.getIn(['dismissed_banners', DISMISSIBLE_ID]) as boolean, + ); + const bodyRef = useRef(null); + const [canScrollLeft, setCanScrollLeft] = useState(false); + const [canScrollRight, setCanScrollRight] = useState(true); + + useEffect(() => { + void dispatch(fetchSuggestions()); + }, [dispatch]); + + useEffect(() => { + if (!bodyRef.current) { + return; + } + + if (getComputedStyle(bodyRef.current).direction === 'rtl') { + setCanScrollLeft( + bodyRef.current.clientWidth - bodyRef.current.scrollLeft < + bodyRef.current.scrollWidth, + ); + setCanScrollRight(bodyRef.current.scrollLeft < 0); + } else { + setCanScrollLeft(bodyRef.current.scrollLeft > 0); + setCanScrollRight( + bodyRef.current.scrollLeft + bodyRef.current.clientWidth < + bodyRef.current.scrollWidth, + ); + } + }, [setCanScrollRight, setCanScrollLeft, suggestions]); + + const handleLeftNav = useCallback(() => { + if (!bodyRef.current) { + return; + } + + bodyRef.current.scrollLeft -= 200; + }, []); + + const handleRightNav = useCallback(() => { + if (!bodyRef.current) { + return; + } + + bodyRef.current.scrollLeft += 200; + }, []); + + const handleScroll = useCallback(() => { + if (!bodyRef.current) { + return; + } + + if (getComputedStyle(bodyRef.current).direction === 'rtl') { + setCanScrollLeft( + bodyRef.current.clientWidth - bodyRef.current.scrollLeft < + bodyRef.current.scrollWidth, + ); + setCanScrollRight(bodyRef.current.scrollLeft < 0); + } else { + setCanScrollLeft(bodyRef.current.scrollLeft > 0); + setCanScrollRight( + bodyRef.current.scrollLeft + bodyRef.current.clientWidth < + bodyRef.current.scrollWidth, + ); + } + }, [setCanScrollRight, setCanScrollLeft]); + + const handleDismiss = useCallback(() => { + dispatch(changeSetting(['dismissed_banners', DISMISSIBLE_ID], true)); + }, [dispatch]); + + if (dismissed || (!isLoading && suggestions.length === 0)) { + return null; + } + + if (hidden) { + return
; + } + + return ( +
+
+

+ +

+ +
+ + + + +
+
+ +
+
+ {suggestions.map((suggestion) => ( + + ))} +
+ + {canScrollLeft && ( + + )} + + {canScrollRight && ( + + )} +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/interaction_modal/index.jsx b/app/javascript/flavours/glitch/features/interaction_modal/index.jsx index 23244f06cab9a8..5f514124bfd461 100644 --- a/app/javascript/flavours/glitch/features/interaction_modal/index.jsx +++ b/app/javascript/flavours/glitch/features/interaction_modal/index.jsx @@ -9,6 +9,7 @@ import { connect } from 'react-redux'; import { throttle, escapeRegExp } from 'lodash'; +import InsertChartIcon from '@/material-icons/400-24px/insert_chart.svg?react'; import PersonAddIcon from '@/material-icons/400-24px/person_add.svg?react'; import RepeatIcon from '@/material-icons/400-24px/repeat.svg?react'; import ReplyIcon from '@/material-icons/400-24px/reply.svg?react'; @@ -340,7 +341,7 @@ class InteractionModal extends React.PureComponent { static propTypes = { displayNameHtml: PropTypes.string, url: PropTypes.string, - type: PropTypes.oneOf(['reply', 'reblog', 'favourite', 'follow']), + type: PropTypes.oneOf(['reply', 'reblog', 'favourite', 'follow', 'vote']), onSignupClick: PropTypes.func.isRequired, signupUrl: PropTypes.string.isRequired, }; @@ -377,6 +378,11 @@ class InteractionModal extends React.PureComponent { title = ; actionDescription = ; break; + case 'vote': + icon = ; + title = ; + actionDescription = ; + break; } let signupButton; diff --git a/app/javascript/flavours/glitch/features/list_adder/components/account.jsx b/app/javascript/flavours/glitch/features/list_adder/components/account.jsx deleted file mode 100644 index 94a90726e33342..00000000000000 --- a/app/javascript/flavours/glitch/features/list_adder/components/account.jsx +++ /dev/null @@ -1,43 +0,0 @@ -import { injectIntl } from 'react-intl'; - -import ImmutablePropTypes from 'react-immutable-proptypes'; -import ImmutablePureComponent from 'react-immutable-pure-component'; -import { connect } from 'react-redux'; - -import { Avatar } from '../../../components/avatar'; -import { DisplayName } from '../../../components/display_name'; -import { makeGetAccount } from '../../../selectors'; - -const makeMapStateToProps = () => { - const getAccount = makeGetAccount(); - - const mapStateToProps = (state, { accountId }) => ({ - account: getAccount(state, accountId), - }); - - return mapStateToProps; -}; - -class Account extends ImmutablePureComponent { - - static propTypes = { - account: ImmutablePropTypes.record.isRequired, - }; - - render () { - const { account } = this.props; - return ( -
-
-
-
- -
-
-
- ); - } - -} - -export default connect(makeMapStateToProps)(injectIntl(Account)); diff --git a/app/javascript/flavours/glitch/features/list_adder/components/list.jsx b/app/javascript/flavours/glitch/features/list_adder/components/list.jsx deleted file mode 100644 index e91c8e35bdf11f..00000000000000 --- a/app/javascript/flavours/glitch/features/list_adder/components/list.jsx +++ /dev/null @@ -1,75 +0,0 @@ -import PropTypes from 'prop-types'; - -import { defineMessages, injectIntl } from 'react-intl'; - -import ImmutablePropTypes from 'react-immutable-proptypes'; -import ImmutablePureComponent from 'react-immutable-pure-component'; -import { connect } from 'react-redux'; - -import AddIcon from '@/material-icons/400-24px/add.svg?react'; -import CloseIcon from '@/material-icons/400-24px/close.svg?react'; -import ListAltIcon from '@/material-icons/400-24px/list_alt.svg?react'; -import { Icon } from 'flavours/glitch/components/icon'; - -import { removeFromListAdder, addToListAdder } from '../../../actions/lists'; -import { IconButton } from '../../../components/icon_button'; - -const messages = defineMessages({ - remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' }, - add: { id: 'lists.account.add', defaultMessage: 'Add to list' }, -}); - -const MapStateToProps = (state, { listId, added }) => ({ - list: state.get('lists').get(listId), - added: typeof added === 'undefined' ? state.getIn(['listAdder', 'lists', 'items']).includes(listId) : added, -}); - -const mapDispatchToProps = (dispatch, { listId }) => ({ - onRemove: () => dispatch(removeFromListAdder(listId)), - onAdd: () => dispatch(addToListAdder(listId)), -}); - -class List extends ImmutablePureComponent { - - static propTypes = { - list: ImmutablePropTypes.map.isRequired, - intl: PropTypes.object.isRequired, - onRemove: PropTypes.func.isRequired, - onAdd: PropTypes.func.isRequired, - added: PropTypes.bool, - }; - - static defaultProps = { - added: false, - }; - - render () { - const { list, intl, onRemove, onAdd, added } = this.props; - - let button; - - if (added) { - button = ; - } else { - button = ; - } - - return ( -
-
-
- - {list.get('title')} -
- -
- {button} -
-
-
- ); - } - -} - -export default connect(MapStateToProps, mapDispatchToProps)(injectIntl(List)); diff --git a/app/javascript/flavours/glitch/features/list_adder/index.jsx b/app/javascript/flavours/glitch/features/list_adder/index.jsx deleted file mode 100644 index 4e7bd46bdfd993..00000000000000 --- a/app/javascript/flavours/glitch/features/list_adder/index.jsx +++ /dev/null @@ -1,76 +0,0 @@ -import PropTypes from 'prop-types'; - -import { injectIntl } from 'react-intl'; - -import { createSelector } from '@reduxjs/toolkit'; -import ImmutablePropTypes from 'react-immutable-proptypes'; -import ImmutablePureComponent from 'react-immutable-pure-component'; -import { connect } from 'react-redux'; - -import { setupListAdder, resetListAdder } from '../../actions/lists'; -import NewListForm from '../lists/components/new_list_form'; - -import Account from './components/account'; -import List from './components/list'; -// hack - -const getOrderedLists = createSelector([state => state.get('lists')], lists => { - if (!lists) { - return lists; - } - - return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); -}); - -const mapStateToProps = state => ({ - listIds: getOrderedLists(state).map(list=>list.get('id')), -}); - -const mapDispatchToProps = dispatch => ({ - onInitialize: accountId => dispatch(setupListAdder(accountId)), - onReset: () => dispatch(resetListAdder()), -}); - -class ListAdder extends ImmutablePureComponent { - - static propTypes = { - accountId: PropTypes.string.isRequired, - onClose: PropTypes.func.isRequired, - intl: PropTypes.object.isRequired, - onInitialize: PropTypes.func.isRequired, - onReset: PropTypes.func.isRequired, - listIds: ImmutablePropTypes.list.isRequired, - }; - - componentDidMount () { - const { onInitialize, accountId } = this.props; - onInitialize(accountId); - } - - componentWillUnmount () { - const { onReset } = this.props; - onReset(); - } - - render () { - const { accountId, listIds } = this.props; - - return ( -
-
- -
- - - - -
- {listIds.map(ListId => )} -
-
- ); - } - -} - -export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ListAdder)); diff --git a/app/javascript/flavours/glitch/features/list_adder/index.tsx b/app/javascript/flavours/glitch/features/list_adder/index.tsx new file mode 100644 index 00000000000000..af52349672bf6f --- /dev/null +++ b/app/javascript/flavours/glitch/features/list_adder/index.tsx @@ -0,0 +1,213 @@ +import { useEffect, useState, useCallback } from 'react'; + +import { FormattedMessage, useIntl, defineMessages } from 'react-intl'; + +import { isFulfilled } from '@reduxjs/toolkit'; + +import CloseIcon from '@/material-icons/400-24px/close.svg?react'; +import ListAltIcon from '@/material-icons/400-24px/list_alt.svg?react'; +import { fetchLists } from 'flavours/glitch/actions/lists'; +import { createList } from 'flavours/glitch/actions/lists_typed'; +import { + apiGetAccountLists, + apiAddAccountToList, + apiRemoveAccountFromList, +} from 'flavours/glitch/api/lists'; +import type { ApiListJSON } from 'flavours/glitch/api_types/lists'; +import { Button } from 'flavours/glitch/components/button'; +import { CheckBox } from 'flavours/glitch/components/check_box'; +import { Icon } from 'flavours/glitch/components/icon'; +import { IconButton } from 'flavours/glitch/components/icon_button'; +import { getOrderedLists } from 'flavours/glitch/selectors/lists'; +import { useAppDispatch, useAppSelector } from 'flavours/glitch/store'; + +const messages = defineMessages({ + newList: { + id: 'lists.new_list_name', + defaultMessage: 'New list name', + }, + createList: { + id: 'lists.create', + defaultMessage: 'Create', + }, + close: { + id: 'lightbox.close', + defaultMessage: 'Close', + }, +}); + +const ListItem: React.FC<{ + id: string; + title: string; + checked: boolean; + onChange: (id: string, checked: boolean) => void; +}> = ({ id, title, checked, onChange }) => { + const handleChange = useCallback( + (e: React.ChangeEvent) => { + onChange(id, e.target.checked); + }, + [id, onChange], + ); + + return ( + // eslint-disable-next-line jsx-a11y/label-has-associated-control + + ); +}; + +const NewListItem: React.FC<{ + onCreate: (list: ApiListJSON) => void; +}> = ({ onCreate }) => { + const intl = useIntl(); + const dispatch = useAppDispatch(); + const [title, setTitle] = useState(''); + + const handleChange = useCallback( + ({ target: { value } }: React.ChangeEvent) => { + setTitle(value); + }, + [setTitle], + ); + + const handleSubmit = useCallback(() => { + if (title.trim().length === 0) { + return; + } + + void dispatch(createList({ title })).then((result) => { + if (isFulfilled(result)) { + onCreate(result.payload); + setTitle(''); + } + + return ''; + }); + }, [setTitle, dispatch, onCreate, title]); + + return ( +
+ + +
+ - -
-
- - -
-
- - {replies_policy !== undefined && ( -
-

- -
- { ['none', 'list', 'followed'].map(policy => ( - - ))} -
-
- )}
@@ -230,4 +178,4 @@ class ListTimeline extends PureComponent { } -export default withRouter(connect(mapStateToProps)(injectIntl(ListTimeline))); +export default withRouter(connect(mapStateToProps)(ListTimeline)); diff --git a/app/javascript/flavours/glitch/features/lists/components/new_list_form.jsx b/app/javascript/flavours/glitch/features/lists/components/new_list_form.jsx deleted file mode 100644 index 04ff85c6598841..00000000000000 --- a/app/javascript/flavours/glitch/features/lists/components/new_list_form.jsx +++ /dev/null @@ -1,80 +0,0 @@ -import PropTypes from 'prop-types'; -import { PureComponent } from 'react'; - -import { defineMessages, injectIntl } from 'react-intl'; - -import { connect } from 'react-redux'; - -import { changeListEditorTitle, submitListEditor } from 'flavours/glitch/actions/lists'; -import { Button } from 'flavours/glitch/components/button'; - -const messages = defineMessages({ - label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' }, - title: { id: 'lists.new.create', defaultMessage: 'Add list' }, -}); - -const mapStateToProps = state => ({ - value: state.getIn(['listEditor', 'title']), - disabled: state.getIn(['listEditor', 'isSubmitting']), -}); - -const mapDispatchToProps = dispatch => ({ - onChange: value => dispatch(changeListEditorTitle(value)), - onSubmit: () => dispatch(submitListEditor(true)), -}); - -class NewListForm extends PureComponent { - - static propTypes = { - value: PropTypes.string.isRequired, - disabled: PropTypes.bool, - intl: PropTypes.object.isRequired, - onChange: PropTypes.func.isRequired, - onSubmit: PropTypes.func.isRequired, - }; - - handleChange = e => { - this.props.onChange(e.target.value); - }; - - handleSubmit = e => { - e.preventDefault(); - this.props.onSubmit(); - }; - - handleClick = () => { - this.props.onSubmit(); - }; - - render () { - const { value, disabled, intl } = this.props; - - const label = intl.formatMessage(messages.label); - const title = intl.formatMessage(messages.title); - - return ( -
- - -
+
+
+ ); +}; + +const ListMembers: React.FC<{ + multiColumn?: boolean; +}> = ({ multiColumn }) => { + const dispatch = useAppDispatch(); + const { id } = useParams<{ id: string }>(); + const intl = useIntl(); + + const [searching, setSearching] = useState(false); + const [accountIds, setAccountIds] = useState([]); + const [searchAccountIds, setSearchAccountIds] = useState([]); + const [loading, setLoading] = useState(true); + const [mode, setMode] = useState('remove'); + + useEffect(() => { + if (id) { + setLoading(true); + dispatch(fetchList(id)); + + void apiGetAccounts(id) + .then((data) => { + dispatch(importFetchedAccounts(data)); + setAccountIds(data.map((a) => a.id)); + setLoading(false); + return ''; + }) + .catch(() => { + setLoading(false); + }); + } + }, [dispatch, id]); + + const handleSearchClick = useCallback(() => { + setMode('add'); + }, [setMode]); + + const handleDismissSearchClick = useCallback(() => { + setMode('remove'); + setSearching(false); + }, [setMode]); + + const handleAccountToggle = useCallback( + (accountId: string) => { + const partOfList = accountIds.includes(accountId); + + if (partOfList) { + setAccountIds(accountIds.filter((id) => id !== accountId)); + } else { + setAccountIds([accountId, ...accountIds]); + } + }, + [accountIds, setAccountIds], + ); + + const searchRequestRef = useRef(null); + + const handleSearch = useDebouncedCallback( + (value: string) => { + if (searchRequestRef.current) { + searchRequestRef.current.abort(); + } + + if (value.trim().length === 0) { + setSearching(false); + return; + } + + setLoading(true); + + searchRequestRef.current = new AbortController(); + + void apiRequest('GET', 'v1/accounts/search', { + signal: searchRequestRef.current.signal, + params: { + q: value, + resolve: false, + following: true, + }, + }) + .then((data) => { + dispatch(importFetchedAccounts(data)); + setSearchAccountIds(data.map((a) => a.id)); + setLoading(false); + setSearching(true); + return ''; + }) + .catch(() => { + setSearching(true); + setLoading(false); + }); + }, + 500, + { leading: true, trailing: true }, + ); + + let displayedAccountIds: string[]; + + if (mode === 'add' && searching) { + displayedAccountIds = searchAccountIds; + } else { + displayedAccountIds = accountIds; + } + + return ( + + + + + + + {displayedAccountIds.length > 0 &&
} + +
+ + + +
+ + } + emptyMessage={ + mode === 'remove' ? ( + <> + + +
+ +
+ + + + ) : ( + + ) + } + > + {displayedAccountIds.map((accountId) => ( + + ))} + + + + {intl.formatMessage(messages.heading)} + + + + ); +}; + +// eslint-disable-next-line import/no-default-export +export default ListMembers; diff --git a/app/javascript/flavours/glitch/features/lists/new.tsx b/app/javascript/flavours/glitch/features/lists/new.tsx new file mode 100644 index 00000000000000..6832b7262867be --- /dev/null +++ b/app/javascript/flavours/glitch/features/lists/new.tsx @@ -0,0 +1,296 @@ +import { useCallback, useState, useEffect } from 'react'; + +import { defineMessages, useIntl, FormattedMessage } from 'react-intl'; + +import { Helmet } from 'react-helmet'; +import { useParams, useHistory, Link } from 'react-router-dom'; + +import { isFulfilled } from '@reduxjs/toolkit'; + +import Toggle from 'react-toggle'; + +import ListAltIcon from '@/material-icons/400-24px/list_alt.svg?react'; +import { fetchList } from 'flavours/glitch/actions/lists'; +import { createList, updateList } from 'flavours/glitch/actions/lists_typed'; +import { apiGetAccounts } from 'flavours/glitch/api/lists'; +import type { RepliesPolicyType } from 'flavours/glitch/api_types/lists'; +import Column from 'flavours/glitch/components/column'; +import { ColumnHeader } from 'flavours/glitch/components/column_header'; +import { LoadingIndicator } from 'flavours/glitch/components/loading_indicator'; +import { useAppDispatch, useAppSelector } from 'flavours/glitch/store'; + +const messages = defineMessages({ + edit: { id: 'column.edit_list', defaultMessage: 'Edit list' }, + create: { id: 'column.create_list', defaultMessage: 'Create list' }, +}); + +const MembersLink: React.FC<{ + id: string; +}> = ({ id }) => { + const [count, setCount] = useState(0); + const [avatars, setAvatars] = useState([]); + + useEffect(() => { + void apiGetAccounts(id) + .then((data) => { + setCount(data.length); + setAvatars(data.slice(0, 3).map((a) => a.avatar)); + return ''; + }) + .catch(() => { + // Nothing + }); + }, [id, setCount, setAvatars]); + + return ( + +
+ + + + +
+ +
+ {avatars.map((url) => ( + + ))} +
+ + ); +}; + +const NewList: React.FC<{ + multiColumn?: boolean; +}> = ({ multiColumn }) => { + const dispatch = useAppDispatch(); + const { id } = useParams<{ id?: string }>(); + const intl = useIntl(); + const history = useHistory(); + + const list = useAppSelector((state) => + id ? state.lists.get(id) : undefined, + ); + const [title, setTitle] = useState(''); + const [exclusive, setExclusive] = useState(false); + const [repliesPolicy, setRepliesPolicy] = useState('list'); + const [submitting, setSubmitting] = useState(false); + + useEffect(() => { + if (id) { + dispatch(fetchList(id)); + } + }, [dispatch, id]); + + useEffect(() => { + if (id && list) { + setTitle(list.title); + setExclusive(list.exclusive); + setRepliesPolicy(list.replies_policy); + } + }, [setTitle, setExclusive, setRepliesPolicy, id, list]); + + const handleTitleChange = useCallback( + ({ target: { value } }: React.ChangeEvent) => { + setTitle(value); + }, + [setTitle], + ); + + const handleExclusiveChange = useCallback( + ({ target: { checked } }: React.ChangeEvent) => { + setExclusive(checked); + }, + [setExclusive], + ); + + const handleRepliesPolicyChange = useCallback( + ({ target: { value } }: React.ChangeEvent) => { + setRepliesPolicy(value as RepliesPolicyType); + }, + [setRepliesPolicy], + ); + + const handleSubmit = useCallback(() => { + setSubmitting(true); + + if (id) { + void dispatch( + updateList({ + id, + title, + exclusive, + replies_policy: repliesPolicy, + }), + ).then(() => { + setSubmitting(false); + return ''; + }); + } else { + void dispatch( + createList({ + title, + exclusive, + replies_policy: repliesPolicy, + }), + ).then((result) => { + setSubmitting(false); + + if (isFulfilled(result)) { + history.replace(`/lists/${result.payload.id}/edit`); + history.push(`/lists/${result.payload.id}/members`); + } + + return ''; + }); + } + }, [history, dispatch, setSubmitting, id, title, exclusive, repliesPolicy]); + + return ( + + + +
+
+
+
+
+ + +
+ +
+
+
+
+ +
+
+
+ + +
+ +
+
+
+
+ + {id && ( +
+ +
+ )} + +
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */} + +
+ +
+ +
+
+
+ + + + {intl.formatMessage(id ? messages.edit : messages.create)} + + + +
+ ); +}; + +// eslint-disable-next-line import/no-default-export +export default NewList; diff --git a/app/javascript/flavours/glitch/features/local_settings/page/index.jsx b/app/javascript/flavours/glitch/features/local_settings/page/index.jsx index ea599afb6a223a..b924a4c85370a5 100644 --- a/app/javascript/flavours/glitch/features/local_settings/page/index.jsx +++ b/app/javascript/flavours/glitch/features/local_settings/page/index.jsx @@ -415,28 +415,6 @@ class LocalSettingsPage extends PureComponent { -
-

- - - - - - - -
), ({ intl, onChange, settings }) => ( diff --git a/app/javascript/flavours/glitch/features/notifications/components/filter_bar.jsx b/app/javascript/flavours/glitch/features/notifications/components/filter_bar.jsx deleted file mode 100644 index 7fabe78a949986..00000000000000 --- a/app/javascript/flavours/glitch/features/notifications/components/filter_bar.jsx +++ /dev/null @@ -1,119 +0,0 @@ -import PropTypes from 'prop-types'; -import { PureComponent } from 'react'; - -import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; - -import HomeIcon from '@/material-icons/400-24px/home-fill.svg?react'; -import InsertChartIcon from '@/material-icons/400-24px/insert_chart.svg?react'; -import PersonAddIcon from '@/material-icons/400-24px/person_add.svg?react'; -import RepeatIcon from '@/material-icons/400-24px/repeat.svg?react'; -import ReplyAllIcon from '@/material-icons/400-24px/reply_all.svg?react'; -import StarIcon from '@/material-icons/400-24px/star.svg?react'; -import { Icon } from 'flavours/glitch/components/icon'; - -const tooltips = defineMessages({ - mentions: { id: 'notifications.filter.mentions', defaultMessage: 'Mentions' }, - favourites: { id: 'notifications.filter.favourites', defaultMessage: 'Favorites' }, - boosts: { id: 'notifications.filter.boosts', defaultMessage: 'Boosts' }, - polls: { id: 'notifications.filter.polls', defaultMessage: 'Poll results' }, - follows: { id: 'notifications.filter.follows', defaultMessage: 'Follows' }, - statuses: { id: 'notifications.filter.statuses', defaultMessage: 'Updates from people you follow' }, -}); - -class FilterBar extends PureComponent { - - static propTypes = { - selectFilter: PropTypes.func.isRequired, - selectedFilter: PropTypes.string.isRequired, - advancedMode: PropTypes.bool.isRequired, - intl: PropTypes.object.isRequired, - }; - - onClick (notificationType) { - return () => this.props.selectFilter(notificationType); - } - - render () { - const { selectedFilter, advancedMode, intl } = this.props; - const renderedElement = !advancedMode ? ( -
- - -
- ) : ( -
- - - - - - - -
- ); - return renderedElement; - } - -} - -export default injectIntl(FilterBar); diff --git a/app/javascript/flavours/glitch/features/notifications/containers/filter_bar_container.js b/app/javascript/flavours/glitch/features/notifications/containers/filter_bar_container.js deleted file mode 100644 index 4e0184cef30534..00000000000000 --- a/app/javascript/flavours/glitch/features/notifications/containers/filter_bar_container.js +++ /dev/null @@ -1,17 +0,0 @@ -import { connect } from 'react-redux'; - -import { setFilter } from '../../../actions/notifications'; -import FilterBar from '../components/filter_bar'; - -const makeMapStateToProps = state => ({ - selectedFilter: state.getIn(['settings', 'notifications', 'quickFilter', 'active']), - advancedMode: state.getIn(['settings', 'notifications', 'quickFilter', 'advanced']), -}); - -const mapDispatchToProps = (dispatch) => ({ - selectFilter (newActiveFilter) { - dispatch(setFilter(newActiveFilter)); - }, -}); - -export default connect(makeMapStateToProps, mapDispatchToProps)(FilterBar); diff --git a/app/javascript/flavours/glitch/features/notifications/index.jsx b/app/javascript/flavours/glitch/features/notifications/index.jsx deleted file mode 100644 index b3b133411aa02f..00000000000000 --- a/app/javascript/flavours/glitch/features/notifications/index.jsx +++ /dev/null @@ -1,383 +0,0 @@ -import PropTypes from 'prop-types'; -import { PureComponent } from 'react'; - -import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; - -import classNames from 'classnames'; -import { Helmet } from 'react-helmet'; - -import { createSelector } from '@reduxjs/toolkit'; -import { List as ImmutableList } from 'immutable'; -import ImmutablePropTypes from 'react-immutable-proptypes'; -import { connect } from 'react-redux'; - -import { debounce } from 'lodash'; - -import DeleteForeverIcon from '@/material-icons/400-24px/delete_forever.svg?react'; -import DoneAllIcon from '@/material-icons/400-24px/done_all.svg?react'; -import NotificationsIcon from '@/material-icons/400-24px/notifications-fill.svg?react'; -import { compareId } from 'flavours/glitch/compare_id'; -import { Icon } from 'flavours/glitch/components/icon'; -import { NotSignedInIndicator } from 'flavours/glitch/components/not_signed_in_indicator'; -import { identityContextPropShape, withIdentity } from 'flavours/glitch/identity_context'; - -import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; -import { submitMarkers } from '../../actions/markers'; -import { - enterNotificationClearingMode, - expandNotifications, - scrollTopNotifications, - loadPending, - mountNotifications, - unmountNotifications, - markNotificationsAsRead, -} from '../../actions/notifications'; -import Column from '../../components/column'; -import ColumnHeader from '../../components/column_header'; -import { LoadGap } from '../../components/load_gap'; -import ScrollableList from '../../components/scrollable_list'; -import NotificationPurgeButtonsContainer from '../../containers/notification_purge_buttons_container'; - -import { - FilteredNotificationsBanner, - FilteredNotificationsIconButton, -} from './components/filtered_notifications_banner'; -import NotificationsPermissionBanner from './components/notifications_permission_banner'; -import ColumnSettingsContainer from './containers/column_settings_container'; -import FilterBarContainer from './containers/filter_bar_container'; -import NotificationContainer from './containers/notification_container'; - -const messages = defineMessages({ - title: { id: 'column.notifications', defaultMessage: 'Notifications' }, - enterNotifCleaning : { id: 'notification_purge.start', defaultMessage: 'Enter notification cleaning mode' }, - markAsRead : { id: 'notifications.mark_as_read', defaultMessage: 'Mark every notification as read' }, -}); - -const getExcludedTypes = createSelector([ - state => state.getIn(['settings', 'notifications', 'shows']), -], (shows) => { - return ImmutableList(shows.filter(item => !item).keys()); -}); - -const getNotifications = createSelector([ - state => state.getIn(['settings', 'notifications', 'quickFilter', 'show']), - state => state.getIn(['settings', 'notifications', 'quickFilter', 'active']), - getExcludedTypes, - state => state.getIn(['notifications', 'items']), -], (showFilterBar, allowedType, excludedTypes, notifications) => { - if (!showFilterBar || allowedType === 'all') { - // used if user changed the notification settings after loading the notifications from the server - // otherwise a list of notifications will come pre-filtered from the backend - // we need to turn it off for FilterBar in order not to block ourselves from seeing a specific category - return notifications.filterNot(item => item !== null && excludedTypes.includes(item.get('type'))); - } - return notifications.filter(item => item === null || allowedType === item.get('type')); -}); - -const mapStateToProps = state => ({ - showFilterBar: state.getIn(['settings', 'notifications', 'quickFilter', 'show']), - notifications: getNotifications(state), - localSettings: state.get('local_settings'), - isLoading: state.getIn(['notifications', 'isLoading'], 0) > 0, - isUnread: state.getIn(['notifications', 'unread']) > 0 || state.getIn(['notifications', 'pendingItems']).size > 0, - hasMore: state.getIn(['notifications', 'hasMore']), - numPending: state.getIn(['notifications', 'pendingItems'], ImmutableList()).size, - notifCleaningActive: state.getIn(['notifications', 'cleaningMode']), - lastReadId: state.getIn(['settings', 'notifications', 'showUnread']) ? state.getIn(['notifications', 'readMarkerId']) : '0', - canMarkAsRead: state.getIn(['settings', 'notifications', 'showUnread']) && state.getIn(['notifications', 'readMarkerId']) !== '0' && getNotifications(state).some(item => item !== null && compareId(item.get('id'), state.getIn(['notifications', 'readMarkerId'])) > 0), - needsNotificationPermission: state.getIn(['settings', 'notifications', 'alerts']).includes(true) && state.getIn(['notifications', 'browserSupport']) && state.getIn(['notifications', 'browserPermission']) === 'default' && !state.getIn(['settings', 'notifications', 'dismissPermissionBanner']), -}); - -/* glitch */ -const mapDispatchToProps = dispatch => ({ - onEnterCleaningMode(yes) { - dispatch(enterNotificationClearingMode(yes)); - }, - dispatch, -}); - -class Notifications extends PureComponent { - static propTypes = { - identity: identityContextPropShape, - columnId: PropTypes.string, - notifications: ImmutablePropTypes.list.isRequired, - showFilterBar: PropTypes.bool.isRequired, - dispatch: PropTypes.func.isRequired, - intl: PropTypes.object.isRequired, - isLoading: PropTypes.bool, - isUnread: PropTypes.bool, - multiColumn: PropTypes.bool, - hasMore: PropTypes.bool, - numPending: PropTypes.number, - localSettings: ImmutablePropTypes.map, - notifCleaningActive: PropTypes.bool, - onEnterCleaningMode: PropTypes.func, - lastReadId: PropTypes.string, - canMarkAsRead: PropTypes.bool, - needsNotificationPermission: PropTypes.bool, - }; - - static defaultProps = { - trackScroll: true, - }; - - state = { - animatingNCD: false, - }; - - componentDidMount() { - this.props.dispatch(mountNotifications()); - } - - componentWillUnmount () { - this.handleLoadOlder.cancel(); - this.handleScrollToTop.cancel(); - this.handleScroll.cancel(); - // this.props.dispatch(scrollTopNotifications(false)); - this.props.dispatch(unmountNotifications()); - } - - handleLoadGap = (maxId) => { - this.props.dispatch(expandNotifications({ maxId })); - }; - - handleLoadOlder = debounce(() => { - const last = this.props.notifications.last(); - this.props.dispatch(expandNotifications({ maxId: last && last.get('id') })); - }, 300, { leading: true }); - - handleLoadPending = () => { - this.props.dispatch(loadPending()); - }; - - handleScrollToTop = debounce(() => { - this.props.dispatch(scrollTopNotifications(true)); - }, 100); - - handleScroll = debounce(() => { - this.props.dispatch(scrollTopNotifications(false)); - }, 100); - - handlePin = () => { - const { columnId, dispatch } = this.props; - - if (columnId) { - dispatch(removeColumn(columnId)); - } else { - dispatch(addColumn('NOTIFICATIONS', {})); - } - }; - - handleMove = (dir) => { - const { columnId, dispatch } = this.props; - dispatch(moveColumn(columnId, dir)); - }; - - handleHeaderClick = () => { - this.column.scrollTop(); - }; - - setColumnRef = c => { - this.column = c; - }; - - handleMoveUp = id => { - const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) - 1; - this._selectChild(elementIndex, true); - }; - - handleMoveDown = id => { - const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) + 1; - this._selectChild(elementIndex, false); - }; - - _selectChild (index, align_top) { - const container = this.column.node; - const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); - - if (element) { - if (align_top && container.scrollTop > element.offsetTop) { - element.scrollIntoView(true); - } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { - element.scrollIntoView(false); - } - element.focus(); - } - } - - handleTransitionEndNCD = () => { - this.setState({ animatingNCD: false }); - }; - - onEnterCleaningMode = () => { - this.setState({ animatingNCD: true }); - this.props.onEnterCleaningMode(!this.props.notifCleaningActive); - }; - - handleMarkAsRead = () => { - this.props.dispatch(markNotificationsAsRead()); - this.props.dispatch(submitMarkers({ immediate: true })); - }; - - render () { - const { intl, notifications, isLoading, isUnread, columnId, multiColumn, hasMore, numPending, showFilterBar, lastReadId, canMarkAsRead, needsNotificationPermission } = this.props; - const { notifCleaningActive } = this.props; - const { animatingNCD } = this.state; - const pinned = !!columnId; - const emptyMessage = ; - const { signedIn } = this.props.identity; - - let scrollableContent = null; - - const filterBarContainer = (signedIn && showFilterBar) - ? () - : null; - - if (isLoading && this.scrollableContent) { - scrollableContent = this.scrollableContent; - } else if (notifications.size > 0 || hasMore) { - scrollableContent = notifications.map((item, index) => item === null ? ( - 0 ? notifications.getIn([index - 1, 'id']) : null} - onClick={this.handleLoadGap} - /> - ) : ( - 0} - /> - )); - } else { - scrollableContent = null; - } - - this.scrollableContent = scrollableContent; - - let scrollContainer; - - const prepend = ( - <> - {needsNotificationPermission && } - - - ); - - if (signedIn) { - scrollContainer = ( - - {scrollableContent} - - ); - } else { - scrollContainer = ; - } - - const extraButtons = [ - , - ]; - - if (canMarkAsRead) { - extraButtons.push( - , - ); - } - - const notifCleaningButtonClassName = classNames('column-header__button', { - 'active': notifCleaningActive, - }); - - const notifCleaningDrawerClassName = classNames('ncd column-header__collapsible', { - 'collapsed': !notifCleaningActive, - 'animating': animatingNCD, - }); - - const msgEnterNotifCleaning = intl.formatMessage(messages.enterNotifCleaning); - - extraButtons.push( - , - ); - - const notifCleaningDrawer = ( -
-
- {(notifCleaningActive || animatingNCD) ? () : null } -
-
- ); - - return ( - - - - - - {filterBarContainer} - - {scrollContainer} - - - {intl.formatMessage(messages.title)} - - - - ); - } - -} - -export default connect(mapStateToProps, mapDispatchToProps)(withIdentity(injectIntl(Notifications))); diff --git a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_annual_report.tsx b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_annual_report.tsx new file mode 100644 index 00000000000000..42754d1490f5f8 --- /dev/null +++ b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_annual_report.tsx @@ -0,0 +1,59 @@ +import { useCallback } from 'react'; + +import { FormattedMessage } from 'react-intl'; + +import classNames from 'classnames'; + +import CelebrationIcon from '@/material-icons/400-24px/celebration.svg?react'; +import { openModal } from 'flavours/glitch/actions/modal'; +import { Icon } from 'flavours/glitch/components/icon'; +import type { NotificationGroupAnnualReport } from 'flavours/glitch/models/notification_group'; +import { useAppDispatch } from 'flavours/glitch/store'; + +export const NotificationAnnualReport: React.FC<{ + notification: NotificationGroupAnnualReport; + unread: boolean; +}> = ({ notification: { annualReport }, unread }) => { + const dispatch = useAppDispatch(); + const year = annualReport.year; + + const handleClick = useCallback(() => { + dispatch( + openModal({ + modalType: 'ANNUAL_REPORT', + modalProps: { year }, + }), + ); + }, [dispatch, year]); + + return ( +
+
+ +
+ +
+

+ +

+ +
+
+ ); +}; diff --git a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_follow.tsx b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_follow.tsx index cabb671815a99b..068f56cd18b76f 100644 --- a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_follow.tsx +++ b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_follow.tsx @@ -1,3 +1,5 @@ +import type { JSX } from 'react'; + import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; diff --git a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group.tsx b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group.tsx index f4275179c5efe9..9bd6c27a86acd8 100644 --- a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group.tsx +++ b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group.tsx @@ -9,6 +9,7 @@ import { useAppSelector, useAppDispatch } from 'flavours/glitch/store'; import { NotificationAdminReport } from './notification_admin_report'; import { NotificationAdminSignUp } from './notification_admin_sign_up'; +import { NotificationAnnualReport } from './notification_annual_report'; import { NotificationFavourite } from './notification_favourite'; import { NotificationFollow } from './notification_follow'; import { NotificationFollowRequest } from './notification_follow_request'; @@ -143,6 +144,14 @@ export const NotificationGroup: React.FC<{ /> ); break; + case 'annual_report': + content = ( + + ); + break; default: return null; } diff --git a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group_with_status.tsx b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group_with_status.tsx index 99045fa53b2b9f..5be3791161120a 100644 --- a/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group_with_status.tsx +++ b/app/javascript/flavours/glitch/features/notifications_v2/components/notification_group_with_status.tsx @@ -1,4 +1,5 @@ import { useMemo } from 'react'; +import type { JSX } from 'react'; import classNames from 'classnames'; diff --git a/app/javascript/flavours/glitch/features/notifications_wrapper.jsx b/app/javascript/flavours/glitch/features/notifications_wrapper.jsx deleted file mode 100644 index e19aa9d07d0de7..00000000000000 --- a/app/javascript/flavours/glitch/features/notifications_wrapper.jsx +++ /dev/null @@ -1,9 +0,0 @@ -import Notifications_v2 from 'flavours/glitch/features/notifications_v2'; - -export const NotificationsWrapper = (props) => { - return ( - - ); -}; - -export default NotificationsWrapper; \ No newline at end of file diff --git a/app/javascript/flavours/glitch/features/onboarding/components/step.jsx b/app/javascript/flavours/glitch/features/onboarding/components/step.jsx deleted file mode 100644 index 32648982a3ed3b..00000000000000 --- a/app/javascript/flavours/glitch/features/onboarding/components/step.jsx +++ /dev/null @@ -1,57 +0,0 @@ -import PropTypes from 'prop-types'; - -import { Link } from 'react-router-dom'; - -import ArrowRightAltIcon from '@/material-icons/400-24px/arrow_right_alt.svg?react'; -import CheckIcon from '@/material-icons/400-24px/done.svg?react'; -import { Icon } from 'flavours/glitch/components/icon'; - -export const Step = ({ label, description, icon, iconComponent, completed, onClick, href, to }) => { - const content = ( - <> -
- -
- -
-
{label}
-

{description}

-
- -
- {completed ? : } -
- - ); - - if (href) { - return ( - - {content} - - ); - } else if (to) { - return ( - - {content} - - ); - } - - return ( - - ); -}; - -Step.propTypes = { - label: PropTypes.node, - description: PropTypes.node, - icon: PropTypes.string, - iconComponent: PropTypes.func, - completed: PropTypes.bool, - href: PropTypes.string, - to: PropTypes.string, - onClick: PropTypes.func, -}; diff --git a/app/javascript/flavours/glitch/features/onboarding/follows.jsx b/app/javascript/flavours/glitch/features/onboarding/follows.jsx deleted file mode 100644 index cfb50ec7a8d913..00000000000000 --- a/app/javascript/flavours/glitch/features/onboarding/follows.jsx +++ /dev/null @@ -1,62 +0,0 @@ -import { useEffect } from 'react'; - -import { FormattedMessage } from 'react-intl'; - -import { Link } from 'react-router-dom'; - -import { useDispatch } from 'react-redux'; - - -import { fetchSuggestions } from 'flavours/glitch/actions/suggestions'; -import { markAsPartial } from 'flavours/glitch/actions/timelines'; -import { ColumnBackButton } from 'flavours/glitch/components/column_back_button'; -import { EmptyAccount } from 'flavours/glitch/components/empty_account'; -import Account from 'flavours/glitch/containers/account_container'; -import { useAppSelector } from 'flavours/glitch/store'; - -export const Follows = () => { - const dispatch = useDispatch(); - const isLoading = useAppSelector(state => state.getIn(['suggestions', 'isLoading'])); - const suggestions = useAppSelector(state => state.getIn(['suggestions', 'items'])); - - useEffect(() => { - dispatch(fetchSuggestions(true)); - - return () => { - dispatch(markAsPartial('home')); - }; - }, [dispatch]); - - let loadedContent; - - if (isLoading) { - loadedContent = (new Array(8)).fill().map((_, i) => ); - } else if (suggestions.isEmpty()) { - loadedContent =
; - } else { - loadedContent = suggestions.map(suggestion => ); - } - - return ( - <> - - -
-
-

-

-
- -
- {loadedContent} -
- -

{chunks} }} />

- -
- -
-
- - ); -}; diff --git a/app/javascript/flavours/glitch/features/onboarding/follows.tsx b/app/javascript/flavours/glitch/features/onboarding/follows.tsx new file mode 100644 index 00000000000000..b2db43361bffdf --- /dev/null +++ b/app/javascript/flavours/glitch/features/onboarding/follows.tsx @@ -0,0 +1,191 @@ +import { useEffect, useState, useCallback, useRef } from 'react'; + +import { FormattedMessage, useIntl, defineMessages } from 'react-intl'; + +import { Helmet } from 'react-helmet'; +import { Link } from 'react-router-dom'; + +import { useDebouncedCallback } from 'use-debounce'; + +import PersonIcon from '@/material-icons/400-24px/person.svg?react'; +import { fetchRelationships } from 'flavours/glitch/actions/accounts'; +import { importFetchedAccounts } from 'flavours/glitch/actions/importer'; +import { fetchSuggestions } from 'flavours/glitch/actions/suggestions'; +import { markAsPartial } from 'flavours/glitch/actions/timelines'; +import { apiRequest } from 'flavours/glitch/api'; +import type { ApiAccountJSON } from 'flavours/glitch/api_types/accounts'; +import Column from 'flavours/glitch/components/column'; +import { ColumnHeader } from 'flavours/glitch/components/column_header'; +import { ColumnSearchHeader } from 'flavours/glitch/components/column_search_header'; +import ScrollableList from 'flavours/glitch/components/scrollable_list'; +import Account from 'flavours/glitch/containers/account_container'; +import { useAppSelector, useAppDispatch } from 'flavours/glitch/store'; + +const messages = defineMessages({ + title: { + id: 'onboarding.follows.title', + defaultMessage: 'Follow people to get started', + }, + search: { id: 'onboarding.follows.search', defaultMessage: 'Search' }, + back: { id: 'onboarding.follows.back', defaultMessage: 'Back' }, +}); + +type Mode = 'remove' | 'add'; + +export const Follows: React.FC<{ + multiColumn?: boolean; +}> = ({ multiColumn }) => { + const intl = useIntl(); + const dispatch = useAppDispatch(); + const isLoading = useAppSelector((state) => state.suggestions.isLoading); + const suggestions = useAppSelector((state) => state.suggestions.items); + const [searchAccountIds, setSearchAccountIds] = useState([]); + const [mode, setMode] = useState('remove'); + const [isLoadingSearch, setIsLoadingSearch] = useState(false); + const [isSearching, setIsSearching] = useState(false); + + useEffect(() => { + void dispatch(fetchSuggestions()); + + return () => { + dispatch(markAsPartial('home')); + }; + }, [dispatch]); + + const handleSearchClick = useCallback(() => { + setMode('add'); + }, [setMode]); + + const handleDismissSearchClick = useCallback(() => { + setMode('remove'); + setIsSearching(false); + }, [setMode, setIsSearching]); + + const searchRequestRef = useRef(null); + + const handleSearch = useDebouncedCallback( + (value: string) => { + if (searchRequestRef.current) { + searchRequestRef.current.abort(); + } + + if (value.trim().length === 0) { + setIsSearching(false); + setSearchAccountIds([]); + return; + } + + setIsSearching(true); + setIsLoadingSearch(true); + + searchRequestRef.current = new AbortController(); + + void apiRequest('GET', 'v1/accounts/search', { + signal: searchRequestRef.current.signal, + params: { + q: value, + }, + }) + .then((data) => { + dispatch(importFetchedAccounts(data)); + dispatch(fetchRelationships(data.map((a) => a.id))); + setSearchAccountIds(data.map((a) => a.id)); + setIsLoadingSearch(false); + return ''; + }) + .catch(() => { + setIsLoadingSearch(false); + }); + }, + 500, + { leading: true, trailing: true }, + ); + + let displayedAccountIds: string[]; + + if (mode === 'add' && isSearching) { + displayedAccountIds = searchAccountIds; + } else { + displayedAccountIds = suggestions.map( + (suggestion) => suggestion.account_id, + ); + } + + return ( + + + + + + + {displayedAccountIds.length > 0 &&
} + +
+ + + +
+ + } + emptyMessage={ + mode === 'remove' ? ( + + ) : ( + + ) + } + > + {displayedAccountIds.map((accountId) => ( + + ))} + + + + {intl.formatMessage(messages.title)} + + + + ); +}; + +// eslint-disable-next-line import/no-default-export +export default Follows; diff --git a/app/javascript/flavours/glitch/features/onboarding/index.jsx b/app/javascript/flavours/glitch/features/onboarding/index.jsx deleted file mode 100644 index 7922b616775090..00000000000000 --- a/app/javascript/flavours/glitch/features/onboarding/index.jsx +++ /dev/null @@ -1,88 +0,0 @@ -import { useCallback } from 'react'; - -import { FormattedMessage, useIntl, defineMessages } from 'react-intl'; - -import { Helmet } from 'react-helmet'; -import { Link, Switch, Route } from 'react-router-dom'; - -import { useDispatch } from 'react-redux'; - - -import illustration from '@/images/elephant_ui_conversation.svg'; -import AccountCircleIcon from '@/material-icons/400-24px/account_circle.svg?react'; -import ArrowRightAltIcon from '@/material-icons/400-24px/arrow_right_alt.svg?react'; -import ContentCopyIcon from '@/material-icons/400-24px/content_copy.svg?react'; -import EditNoteIcon from '@/material-icons/400-24px/edit_note.svg?react'; -import PersonAddIcon from '@/material-icons/400-24px/person_add.svg?react'; -import { focusCompose } from 'flavours/glitch/actions/compose'; -import { Icon } from 'flavours/glitch/components/icon'; -import Column from 'flavours/glitch/features/ui/components/column'; -import { me } from 'flavours/glitch/initial_state'; -import { useAppSelector } from 'flavours/glitch/store'; -import { assetHost } from 'flavours/glitch/utils/config'; - -import { Step } from './components/step'; -import { Follows } from './follows'; -import { Profile } from './profile'; -import { Share } from './share'; - -const messages = defineMessages({ - template: { id: 'onboarding.compose.template', defaultMessage: 'Hello #Mastodon!' }, -}); - -const Onboarding = () => { - const account = useAppSelector(state => state.getIn(['accounts', me])); - const dispatch = useDispatch(); - const intl = useIntl(); - - const handleComposeClick = useCallback(() => { - dispatch(focusCompose(intl.formatMessage(messages.template))); - }, [dispatch, intl]); - - return ( - - - -
-
- -

-

-
- -
- 0 && account.get('note').length > 0)} icon='address-book-o' iconComponent={AccountCircleIcon} label={} description={} /> - = 1} icon='user-plus' iconComponent={PersonAddIcon} label={} description={} /> - = 1} icon='pencil-square-o' iconComponent={EditNoteIcon} label={} description={ }} />} /> - } description={} /> -
- -

- -
- - - - - - - - - -
-
-
- - - - -
- - - - -
- ); -}; - -export default Onboarding; diff --git a/app/javascript/flavours/glitch/features/onboarding/profile.jsx b/app/javascript/flavours/glitch/features/onboarding/profile.jsx deleted file mode 100644 index 75e179ee1e69dd..00000000000000 --- a/app/javascript/flavours/glitch/features/onboarding/profile.jsx +++ /dev/null @@ -1,162 +0,0 @@ -import { useState, useMemo, useCallback, createRef } from 'react'; - -import { useIntl, defineMessages, FormattedMessage } from 'react-intl'; - -import classNames from 'classnames'; -import { useHistory } from 'react-router-dom'; - - -import { useDispatch } from 'react-redux'; - -import Toggle from 'react-toggle'; - -import AddPhotoAlternateIcon from '@/material-icons/400-24px/add_photo_alternate.svg?react'; -import EditIcon from '@/material-icons/400-24px/edit.svg?react'; -import { updateAccount } from 'flavours/glitch/actions/accounts'; -import { Button } from 'flavours/glitch/components/button'; -import { ColumnBackButton } from 'flavours/glitch/components/column_back_button'; -import { Icon } from 'flavours/glitch/components/icon'; -import { LoadingIndicator } from 'flavours/glitch/components/loading_indicator'; -import { me } from 'flavours/glitch/initial_state'; -import { useAppSelector } from 'flavours/glitch/store'; -import { unescapeHTML } from 'flavours/glitch/utils/html'; - -const messages = defineMessages({ - uploadHeader: { id: 'onboarding.profile.upload_header', defaultMessage: 'Upload profile header' }, - uploadAvatar: { id: 'onboarding.profile.upload_avatar', defaultMessage: 'Upload profile picture' }, -}); - -const nullIfMissing = path => path.endsWith('missing.png') ? null : path; - -export const Profile = () => { - const account = useAppSelector(state => state.getIn(['accounts', me])); - const [displayName, setDisplayName] = useState(account.get('display_name')); - const [note, setNote] = useState(unescapeHTML(account.get('note'))); - const [avatar, setAvatar] = useState(null); - const [header, setHeader] = useState(null); - const [discoverable, setDiscoverable] = useState(account.get('discoverable')); - const [isSaving, setIsSaving] = useState(false); - const [errors, setErrors] = useState(); - const avatarFileRef = createRef(); - const headerFileRef = createRef(); - const dispatch = useDispatch(); - const intl = useIntl(); - const history = useHistory(); - - const handleDisplayNameChange = useCallback(e => { - setDisplayName(e.target.value); - }, [setDisplayName]); - - const handleNoteChange = useCallback(e => { - setNote(e.target.value); - }, [setNote]); - - const handleDiscoverableChange = useCallback(e => { - setDiscoverable(e.target.checked); - }, [setDiscoverable]); - - const handleAvatarChange = useCallback(e => { - setAvatar(e.target?.files?.[0]); - }, [setAvatar]); - - const handleHeaderChange = useCallback(e => { - setHeader(e.target?.files?.[0]); - }, [setHeader]); - - const avatarPreview = useMemo(() => avatar ? URL.createObjectURL(avatar) : nullIfMissing(account.get('avatar')), [avatar, account]); - const headerPreview = useMemo(() => header ? URL.createObjectURL(header) : nullIfMissing(account.get('header')), [header, account]); - - const handleSubmit = useCallback(() => { - setIsSaving(true); - - dispatch(updateAccount({ - displayName, - note, - avatar, - header, - discoverable, - indexable: discoverable, - })).then(() => history.push('/start/follows')).catch(err => { - setIsSaving(false); - setErrors(err.response.data.details); - }); - }, [dispatch, displayName, note, avatar, header, discoverable, history]); - - return ( - <> - - -
-
-

-

-
- -
-
- - - -
- -
- - -
- -
-
- -
- - -
-