Skip to content

Commit

Permalink
Conditionally include scripts (forem#21330)
Browse files Browse the repository at this point in the history
* Conditionally include scripts

* Adjust js loading

* Remove console log

* Adjust js loading
  • Loading branch information
benhalpern authored Oct 15, 2024
1 parent 5511dfb commit 31a0b0e
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 76 deletions.
15 changes: 13 additions & 2 deletions app/javascript/packs/Search.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import { h, render } from 'preact';
import { SearchFormSync } from '../Search/SearchFormSync';

document.addEventListener('DOMContentLoaded', () => {
if (document.readyState === "interactive" || document.readyState === "complete") {
// DOMContentLoaded has already been triggered
const root = document.getElementById('header-search');

render(<SearchFormSync />, root);
window.InstantClick.on('change', () => {
render(<SearchFormSync />, root);
});
});
} else {
// Add event listener for DOMContentLoaded
document.addEventListener("DOMContentLoaded", function () {
const root = document.getElementById('header-search');

render(<SearchFormSync />, root);
window.InstantClick.on('change', () => {
render(<SearchFormSync />, root);
});
});
}
20 changes: 20 additions & 0 deletions app/javascript/packs/application.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,26 @@ document.ready.then(() => {
'js-hamburger-trigger',
)[0];
hamburgerTrigger.addEventListener('click', getNavigation);

// Dynamically loading the script.js.
// We don't currently have dynamic insert working, so using this
// method instead.
const hoverElement = document.querySelector("#search-input");

const scriptElement = document.querySelector('meta[name="search-script"]');
if (scriptElement) {
hoverElement.addEventListener("mouseenter", function() {
const scriptPath = scriptElement.getAttribute("content");

// Check if the script is already added to the head
if (scriptPath && !document.querySelector(`script[src="${scriptPath}"]`)) {
const script = document.createElement("script");
script.src = scriptPath;
script.defer = true; // Optional, if you want it to load in deferred mode
document.head.appendChild(script);
}
}, { once: true }); // Ensures the hover event only triggers once
}
});

trackCreateAccountClicks('authentication-hamburger-actions');
Expand Down
8 changes: 8 additions & 0 deletions app/javascript/packs/articleAnimations.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const animatedImages = document.querySelectorAll('[data-animated="true"]');
if (animatedImages.length > 0) {
import('@utilities/animatedImageUtils').then(
({ initializePausableAnimatedImages }) => {
initializePausableAnimatedImages(animatedImages);
},
);
}
72 changes: 0 additions & 72 deletions app/javascript/packs/articlePage.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { h, render } from 'preact';
import { Snackbar, addSnackbarItem } from '../Snackbar';
import { addFullScreenModeControl } from '../utilities/codeFullscreenModeSwitcher';
import { initializeDropdown } from '../utilities/dropdownUtils';
import { setupBillboardInteractivity } from '../utilities/billboardInteractivity';
import { embedGists } from '../utilities/gist';
import { initializeUserSubscriptionLiquidTagContent } from '../liquidTags/userSubscriptionLiquidTag';
import { trackCommentClicks } from '@utilities/ahoy/trackEvents';
import { isNativeAndroid, copyToClipboard } from '@utilities/runtime';

// Open in new tab backfill
Expand Down Expand Up @@ -34,15 +30,6 @@ function backfillLinkTarget() {
});
}

const animatedImages = document.querySelectorAll('[data-animated="true"]');
if (animatedImages.length > 0) {
import('@utilities/animatedImageUtils').then(
({ initializePausableAnimatedImages }) => {
initializePausableAnimatedImages(animatedImages);
},
);
}

const fullscreenActionElements = document.getElementsByClassName(
'js-fullscreen-code-action',
);
Expand All @@ -51,15 +38,6 @@ if (fullscreenActionElements) {
addFullScreenModeControl(fullscreenActionElements);
}

// The Snackbar for the article page
const snackZone = document.getElementById('snack-zone');
if (snackZone) {
render(<Snackbar lifespan={3} />, snackZone);
}

// eslint-disable-next-line no-restricted-globals
top.addSnackbarItem = addSnackbarItem;

const multiReactionDrawerTrigger = document.getElementById(
'reaction-drawer-trigger',
);
Expand Down Expand Up @@ -134,60 +112,10 @@ document
.getElementById('copy-post-url-button')
?.addEventListener('click', copyArticleLink);

// Comment Subscription
getCsrfToken().then(async () => {
const { user = null, userStatus } = document.body.dataset;
const root = document.getElementById('comment-subscription');
const isLoggedIn = userStatus === 'logged-in';

if (!root) {
return;
}
try {
const {
getCommentSubscriptionStatus,
setCommentSubscriptionStatus,
CommentSubscription,
} = await import('../CommentSubscription');

const { articleId } = document.getElementById('article-body').dataset;

let subscriptionType = 'not_subscribed';

if (isLoggedIn && user !== null) {
({ config: subscriptionType } = await getCommentSubscriptionStatus(
articleId,
));
}

const subscriptionRequestHandler = async (type) => {
const message = await setCommentSubscriptionStatus(articleId, type);

addSnackbarItem({ message, addCloseButton: true });
};

render(
<CommentSubscription
subscriptionType={subscriptionType}
positionType="static"
onSubscribe={subscriptionRequestHandler}
onUnsubscribe={subscriptionRequestHandler}
isLoggedIn={isLoggedIn}
/>,
root,
);
} catch (e) {
root.innerHTML =
'<p className="color-accent-danger">Unable to load Comment Subscription component.<br />Try refreshing the page.</p>';
}
});

const targetNode = document.querySelector('#comments');
targetNode && embedGists(targetNode);

setupBillboardInteractivity();
initializeUserSubscriptionLiquidTagContent();
focusOnComments();
// Temporary Ahoy Stats for comment section clicks on controls
trackCommentClicks('comments');
backfillLinkTarget();
63 changes: 63 additions & 0 deletions app/javascript/packs/articleSignedIn.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { h, render } from 'preact';
import { Snackbar, addSnackbarItem } from '../Snackbar';
import { initializeUserSubscriptionLiquidTagContent } from '../liquidTags/userSubscriptionLiquidTag';

// The Snackbar for the article page
const snackZone = document.getElementById('snack-zone');
if (snackZone) {
render(<Snackbar lifespan={3} />, snackZone);
}

// eslint-disable-next-line no-restricted-globals
top.addSnackbarItem = addSnackbarItem;


// Comment Subscription
getCsrfToken().then(async () => {
const { user = null, userStatus } = document.body.dataset;
const root = document.getElementById('comment-subscription');
const isLoggedIn = userStatus === 'logged-in';

if (!root) {
return;
}
try {
const {
getCommentSubscriptionStatus,
setCommentSubscriptionStatus,
CommentSubscription,
} = await import('../CommentSubscription');

const { articleId } = document.getElementById('article-body').dataset;

let subscriptionType = 'not_subscribed';

if (isLoggedIn && user !== null) {
({ config: subscriptionType } = await getCommentSubscriptionStatus(
articleId,
));
}

const subscriptionRequestHandler = async (type) => {
const message = await setCommentSubscriptionStatus(articleId, type);

addSnackbarItem({ message, addCloseButton: true });
};

render(
<CommentSubscription
subscriptionType={subscriptionType}
positionType="static"
onSubscribe={subscriptionRequestHandler}
onUnsubscribe={subscriptionRequestHandler}
isLoggedIn={isLoggedIn}
/>,
root,
);
} catch (e) {
root.innerHTML =
'<p className="color-accent-danger">Unable to load Comment Subscription component.<br />Try refreshing the page.</p>';
}
});

initializeUserSubscriptionLiquidTagContent();
6 changes: 5 additions & 1 deletion app/views/articles/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@
.html-variant-wrapper { display: none}
</style>

<% if @article.processed_html.include?("data-animated") %>
<%= javascript_include_tag "articleAnimations", defer: true %>
<% end %>
<%= render "shared/webcomponents_loader_script" %>
<% if user_signed_in? %>
<%= javascript_include_tag "webShare", "articlePage", "articleModerationTools", "commentDropdowns", defer: true %>
<%= javascript_include_tag "webShare", "articlePage", "articleSignedIn", "articleModerationTools", "commentDropdowns", defer: true %>
<% else %>
<%= javascript_include_tag "webShare", "articlePage", "commentDropdowns", defer: true %>
<% end %>
Expand Down
9 changes: 8 additions & 1 deletion app/views/layouts/application.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,14 @@
<meta name="head-cached-at" content="<%= Time.current.to_i %>">
<meta name="environment" content="<%= Rails.env %>">
<%= render "layouts/styles", qualifier: "main" %>
<%= javascript_include_tag "base", "application", "baseInitializers", "Search", "baseTracking", defer: true %>
<%= javascript_include_tag "base", "application", "baseInitializers", "baseTracking", defer: true %>
<%# This Rails.env.test? introduces some test-specific behavior, but that is much easier to verify without the specific loading code. We should ensure search still works as expected manually as well. %>
<% if controller_name == "articles_search" || Rails.env.test? %>
<%= javascript_include_tag "Search", defer: true %>
<% else %>
<meta name="search-script" content="<%= asset_path 'Search.js' %>">
<% end %>
<% if Settings::UserExperience.show_mobile_app_banner %>
<%= javascript_include_tag "runtimeBanner", defer: true %>
<% end %>
Expand Down
2 changes: 2 additions & 0 deletions config/environments/development.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@
config.logger = ActiveSupport::TaggedLogging.new(logger)
end

config.logger = ActiveSupport::Logger.new("log/development.log", 1, 3.megabytes)

config.after_initialize do
# See <https://github.com/flyerhzm/bullet#configuration> for other Bullet config options
Bullet.enable = true
Expand Down

0 comments on commit 31a0b0e

Please sign in to comment.