discourse/lib/mobile_detection.rb
Sérgio Saquetim 95a95a492b
DEV: Deprecate Site.mobileView/desktopView during initialization (#34122)
This commit introduces deprecation warnings for accessing Site.mobileView or
Site.desktopView during application initialization to prevent
layout-related errors and improve code reliability.

The changes include:

* Added deprecation warnings for Site.mobileView and Site.desktopView
access during the initialization phase.
* Updated multiple plugins and components to avoid these deprecated
calls during startup.
* Refactored initialization logic across discourse-ai, discourse-chat,
discourse-calendar, discourse-reactions, discourse-assign,
discourse-subscriptions, and discourse-user-notes plugins
* Improved error prevention by discouraging early access to
view-dependent properties before the application is fully initialized
* Enhanced code maintainability by establishing clearer boundaries
between initialization and runtime phases

This deprecation helps prevent subtle bugs that can occur when
components try to determine the view type before the application context
is properly established, leading to more robust plugin initialization
patterns.
2025-08-25 16:49:52 -03:00

42 lines
1.2 KiB
Ruby

# frozen_string_literal: true
module MobileDetection
# if the criteria for mobile_device? changes, update the code for `mobileDevice` in
# `javascripts/discourse/app/lib/mobile.js`
def self.mobile_device?(user_agent)
user_agent =~ /Mobile/ && !(user_agent =~ /iPad/)
end
# we need this as a reusable chunk that is called from the cache
def self.resolve_mobile_view!(user_agent, params, session)
return false unless SiteSetting.enable_mobile_theme
session[:mobile_view] = params[:mobile_view] if params && params.has_key?(:mobile_view)
session[:mobile_view] = nil if params && params.has_key?(:mobile_view) &&
params[:mobile_view] == "auto"
if session && session[:mobile_view]
session[:mobile_view] == "1"
else
mobile_device?(user_agent)
end
end
MODERN_MOBILE_REGEX =
%r{
\(.*iPhone\ OS\ 1[5-9].*\)|
\(.*iPad.*OS\ 1[5-9].*\)|
Chrome\/8[89]|
Chrome\/9[0-9]|
Chrome\/1[0-9][0-9]|
Firefox\/8[5-9]|
Firefox\/9[0-9]|
Firefox\/1[0-9][0-9]
}x
USER_AGENT_MAX_LENGTH = 400
def self.modern_mobile_device?(user_agent)
user_agent[0...USER_AGENT_MAX_LENGTH].match?(MODERN_MOBILE_REGEX)
end
end