AgPerry's picture
Add files using upload-large-folder tool
2fcdd6d verified
Raw History Blame Contribute Delete
29.3 kB
// IMDb offline clone - authored local interactions. No remote requests.
(function () {
"use strict";
var PREFERRED_SERVICES_KEY = "websitebench.imdb.preferredServices.v1";
var RECENTLY_VIEWED_KEY = "websitebench.imdb.recentlyViewed.v1";
function readLocalArray(key) {
try {
var value = JSON.parse(window.localStorage.getItem(key) || "[]");
return Array.isArray(value) ? value : [];
} catch (_error) {
return [];
}
}
function writeLocalArray(key, value) {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (_error) {
// Storage may be unavailable in a restricted browser; the page remains usable.
}
}
function normalizeRecentEntries(entries) {
var prefixes = { title: "/title/", person: "/name/", video: "/video/" };
var idPatterns = {
title: /^tt\d{7,8}$/,
person: /^nm\d{7}$/,
video: /^local-feature-(?:0[1-9]|1[0-6])$/
};
var posterPrefixes = ["/static/assets/", "/media-assets/posters/", "/media-assets/people/"];
var seen = new Set();
var normalized = [];
entries.some(function (item) {
if (!item || !prefixes[item.kind] || typeof item.id !== "string" ||
!idPatterns[item.kind].test(item.id) || typeof item.title !== "string" ||
!item.title.trim() || item.title.length > 300 || typeof item.poster !== "string" ||
item.poster.indexOf("?") !== -1 || item.poster.indexOf("#") !== -1 ||
item.poster.indexOf("\\") !== -1 || item.poster.indexOf("//") === 0 ||
!posterPrefixes.some(function (prefix) { return item.poster.indexOf(prefix) === 0; })) {
return false;
}
var decodedPoster;
try {
decodedPoster = decodeURIComponent(item.poster);
} catch (_error) {
return false;
}
if (decodedPoster.split("/").some(function (segment) {
return segment === "." || segment === "..";
})) {
return false;
}
var identity = item.kind + ":" + item.id;
if (seen.has(identity)) {
return false;
}
seen.add(identity);
normalized.push({
kind: item.kind,
id: item.id,
title: item.title.trim(),
href: prefixes[item.kind] + item.id + "/",
poster: item.poster
});
return normalized.length === 20;
});
return normalized;
}
function onReady(callback) {
if (document.readyState !== "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
onReady(function () {
// IMDb navigation drawer.
var navToggle = document.querySelector(".nav-toggle");
var headerMenu = document.getElementById("header-menu");
var drawerClose = document.querySelector(".drawer-close");
var drawerScrim = document.querySelector(".drawer-scrim");
var drawerReturnFocus = null;
function setDrawer(open) {
if (!navToggle || !headerMenu) {
return;
}
navToggle.setAttribute("aria-expanded", String(open));
headerMenu.setAttribute("aria-hidden", String(!open));
headerMenu.classList.toggle("is-open", open);
document.body.classList.toggle("drawer-open", open);
if (drawerScrim) {
drawerScrim.hidden = !open;
}
if (open && drawerClose) {
drawerReturnFocus = document.activeElement;
drawerClose.focus();
} else if (!open && drawerReturnFocus && drawerReturnFocus.focus) {
drawerReturnFocus.focus();
}
}
if (navToggle && headerMenu) {
navToggle.addEventListener("click", function () {
var expanded = navToggle.getAttribute("aria-expanded") === "true";
setDrawer(!expanded);
});
}
if (drawerClose) {
drawerClose.addEventListener("click", function () { setDrawer(false); });
}
if (drawerScrim) {
drawerScrim.addEventListener("click", function () { setDrawer(false); });
}
document.querySelectorAll(".drawer-group-toggle").forEach(function (toggle) {
toggle.addEventListener("click", function () {
var panel = document.getElementById(toggle.getAttribute("aria-controls"));
if (!panel) {
return;
}
var expanded = toggle.getAttribute("aria-expanded") === "true";
toggle.setAttribute("aria-expanded", String(!expanded));
panel.hidden = expanded;
});
});
var languageToggle = document.querySelector(".drawer-language");
var languageOptions = document.getElementById("drawer-language-options");
if (languageToggle && languageOptions) {
languageToggle.addEventListener("click", function () {
var expanded = languageToggle.getAttribute("aria-expanded") === "true";
languageToggle.setAttribute("aria-expanded", String(!expanded));
languageOptions.hidden = expanded;
});
}
function dialogFocusableElements(dialogRoot) {
return Array.prototype.slice.call(dialogRoot.querySelectorAll(
"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])"
)).filter(function (element) {
return !element.hidden && element.getClientRects().length > 0;
});
}
function setDialogBackgroundInert(dialogRoot, inert) {
Array.prototype.slice.call(document.body.children).forEach(function (element) {
if (element === dialogRoot) { return; }
if (inert) {
if (!element.inert) {
element.inert = true;
element.dataset.dialogInertOwner = dialogRoot.id;
}
} else if (element.dataset.dialogInertOwner === dialogRoot.id) {
element.inert = false;
delete element.dataset.dialogInertOwner;
}
});
}
function trapDialogTab(event, dialogRoot) {
if (event.key !== "Tab" || !dialogRoot || dialogRoot.hidden) { return; }
var focusable = dialogFocusableElements(dialogRoot);
if (!focusable.length) {
event.preventDefault();
return;
}
var first = focusable[0];
var last = focusable[focusable.length - 1];
if (!dialogRoot.contains(document.activeElement)) {
event.preventDefault();
first.focus();
} else if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
// The header account affordance opens an accessible same-page dialog;
// its sign-in link remains the exact current return URL without JS.
var accountDialog = document.getElementById("account-dialog");
var accountReturnFocus = null;
function closeAccountDialog() {
if (!accountDialog || accountDialog.hidden) { return; }
accountDialog.hidden = true;
setDialogBackgroundInert(accountDialog, false);
if (accountReturnFocus && accountReturnFocus.focus) { accountReturnFocus.focus(); }
}
document.querySelectorAll("[data-account-open]").forEach(function (opener) {
opener.addEventListener("click", function (event) {
if (!accountDialog) { return; }
event.preventDefault();
closeLanguageDialog();
accountReturnFocus = opener;
accountDialog.hidden = false;
setDialogBackgroundInert(accountDialog, true);
accountDialog.querySelector("[data-account-close]").focus();
});
});
if (accountDialog) {
accountDialog.querySelector("[data-account-close]").addEventListener("click", closeAccountDialog);
accountDialog.addEventListener("click", function (event) {
if (event.target === accountDialog) { closeAccountDialog(); }
});
accountDialog.addEventListener("keydown", function (event) {
trapDialogTab(event, accountDialog);
});
}
// Desktop language control mirrors the drawer's explicit single-language
// state. The button opens a dialog and the choice confirms local state.
var languageDialog = document.getElementById("language-dialog");
var languageReturnFocus = null;
function closeLanguageDialog() {
if (!languageDialog || languageDialog.hidden) { return; }
languageDialog.hidden = true;
setDialogBackgroundInert(languageDialog, false);
if (languageReturnFocus && languageReturnFocus.focus) { languageReturnFocus.focus(); }
}
document.querySelectorAll("[data-language-open]").forEach(function (opener) {
opener.addEventListener("click", function () {
if (!languageDialog) { return; }
closeAccountDialog();
languageReturnFocus = opener;
languageDialog.hidden = false;
setDialogBackgroundInert(languageDialog, true);
languageDialog.querySelector("[data-language-close]").focus();
});
});
if (languageDialog) {
languageDialog.querySelector("[data-language-close]").addEventListener("click", closeLanguageDialog);
languageDialog.querySelector("[data-language-choice]").addEventListener("click", function (event) {
event.currentTarget.setAttribute("aria-pressed", "true");
languageDialog.querySelector("[data-language-status]").textContent = "English (United States) remains selected.";
});
languageDialog.addEventListener("click", function (event) {
if (event.target === languageDialog) { closeLanguageDialog(); }
});
languageDialog.addEventListener("keydown", function (event) {
trapDialogTab(event, languageDialog);
});
}
// The reserved sponsored area contains no fabricated ad. Its close button
// produces an explicit DOM state change and removes the reserved height.
var adSlot = document.querySelector("[data-ad-slot]");
var adClose = document.querySelector("[data-ad-close]");
if (adSlot && adClose) {
adClose.addEventListener("click", function () {
adSlot.dataset.state = "closed";
adSlot.hidden = true;
});
}
// Homepage featured-trailer carousel. Every visible arrow changes content.
var slides = Array.prototype.slice.call(document.querySelectorAll("[data-hero-slide]"));
var heroIndex = 0;
function showHero(index) {
if (!slides.length) {
return;
}
heroIndex = (index + slides.length) % slides.length;
slides.forEach(function (slide, slideIndex) {
slide.hidden = slideIndex !== heroIndex;
});
var carousel = document.querySelector("[data-hero-carousel]");
if (carousel) { carousel.dataset.activeSlide = String(heroIndex); }
document.querySelectorAll("[data-show-slide]").forEach(function (target) {
target.setAttribute(
"aria-pressed",
String(Number(target.getAttribute("data-show-slide")) === heroIndex)
);
});
}
var previousHero = document.querySelector("[data-hero-prev]");
var nextHero = document.querySelector("[data-hero-next]");
if (previousHero) {
previousHero.addEventListener("click", function () { showHero(heroIndex - 1); });
}
if (nextHero) {
nextHero.addEventListener("click", function () { showHero(heroIndex + 1); });
}
document.querySelectorAll("[data-show-slide]").forEach(function (link) {
link.addEventListener("click", function () {
showHero(Number(link.getAttribute("data-show-slide")));
});
});
// Streaming service tabs are client-side view filters.
var preferredAtLoad = readLocalArray(PREFERRED_SERVICES_KEY);
var serviceTabs = Array.prototype.slice.call(document.querySelectorAll(".service-tab"));
if (preferredAtLoad.length && serviceTabs.length) {
var preferredTab = serviceTabs.find(function (tab) {
return tab.dataset.serviceId === preferredAtLoad[0];
});
if (preferredTab) {
serviceTabs.forEach(function (tab) {
var selected = tab === preferredTab;
tab.classList.toggle("is-selected", selected);
tab.setAttribute("aria-selected", String(selected));
});
}
}
serviceTabs.forEach(function (tab) {
tab.addEventListener("click", function () {
document.querySelectorAll(".service-tab").forEach(function (other) {
var selected = other === tab;
other.classList.toggle("is-selected", selected);
other.setAttribute("aria-selected", String(selected));
});
var heading = document.querySelector(".streaming-panel h3");
var copy = document.querySelector(".streaming-panel p");
if (heading) {
heading.textContent = "Catalog picks for " + tab.textContent.trim();
}
if (copy) {
copy.textContent = "Browse titles carrying the " + tab.textContent.trim() + " provider label in the included directory.";
}
var panel = document.getElementById("streaming-panel");
if (panel) { panel.dataset.activeService = tab.dataset.serviceId; }
});
});
// Preferred services are browser-local and apply immediately.
var preferences = document.querySelector("[data-preferred-services]");
if (preferences) {
var choices = Array.prototype.slice.call(
preferences.querySelectorAll("input[type='checkbox']")
);
var preferenceStatus = preferences.querySelector("[data-preferences-status]");
function showPreferredServices() {
var selected = choices.filter(function (choice) { return choice.checked; })
.map(function (choice) { return choice.value; });
writeLocalArray(PREFERRED_SERVICES_KEY, selected);
preferenceStatus.textContent = selected.length
? selected.length + " preferred service" + (selected.length === 1 ? "" : "s") + " saved."
: "No preferred services selected.";
}
choices.forEach(function (choice) {
choice.checked = preferredAtLoad.indexOf(choice.value) !== -1;
choice.addEventListener("change", showPreferredServices);
});
preferenceStatus.textContent = preferredAtLoad.length
? preferredAtLoad.length + " preferred service" + (preferredAtLoad.length === 1 ? "" : "s") + " saved."
: "No preferred services selected.";
}
// Record only public entity surfaces: title, person, and video.
var storedRecentEntries = readLocalArray(RECENTLY_VIEWED_KEY);
var recentEntries = normalizeRecentEntries(storedRecentEntries);
if (JSON.stringify(recentEntries) !== JSON.stringify(storedRecentEntries)) {
writeLocalArray(RECENTLY_VIEWED_KEY, recentEntries);
}
var recentEntry = document.querySelector("[data-recent-entry]");
if (recentEntry) {
var kind = recentEntry.dataset.recentKind;
if (kind === "title" || kind === "person" || kind === "video") {
var entry = {
kind: kind,
id: recentEntry.dataset.recentId,
title: recentEntry.dataset.recentTitle,
href: recentEntry.dataset.recentHref,
poster: recentEntry.dataset.recentPoster
};
recentEntries = normalizeRecentEntries([entry].concat(recentEntries));
writeLocalArray(RECENTLY_VIEWED_KEY, recentEntries);
}
}
var recentContainer = document.querySelector("[data-recently-viewed]");
if (recentContainer && recentEntries.length) {
recentContainer.replaceChildren();
var recentList = document.createElement("div");
recentList.className = "recent-list";
recentEntries.forEach(function (item) {
if (!item || !(item.kind === "title" || item.kind === "person" || item.kind === "video")) {
return;
}
var link = document.createElement("a");
link.href = item.href;
link.className = "recent-card";
var image = document.createElement("img");
image.src = item.poster;
image.alt = "";
var label = document.createElement("span");
label.textContent = item.title;
link.append(image, label);
recentList.appendChild(link);
});
recentContainer.appendChild(recentList);
}
// Popular is the default. Preferences prioritize matching services;
// Watchlist/recent titles are excluded, with Top Rated as no-match fallback.
var recommendationRoot = document.querySelector("[data-recommendations]");
if (recommendationRoot) {
var recommendationCards = Array.prototype.slice.call(
recommendationRoot.querySelectorAll("[data-recommendation-card]")
);
var watchlistIds = new Set(
(recommendationRoot.dataset.watchlistTitleIds || "").split(",").filter(Boolean)
);
var recentTitleIds = new Set(
recentEntries.filter(function (item) { return item && item.kind === "title"; })
.map(function (item) { return item.id; })
);
var eligible = function (card) {
return !watchlistIds.has(card.dataset.titleId) && !recentTitleIds.has(card.dataset.titleId);
};
var popularCards = recommendationCards.filter(function (card) {
return card.dataset.source === "popular" && eligible(card);
});
var topCards = recommendationCards.filter(function (card) {
return card.dataset.source === "top" && eligible(card);
});
var preferred = readLocalArray(PREFERRED_SERVICES_KEY);
var selectedCards = popularCards;
var statusText = "Popular titles";
if (preferred.length) {
var matching = popularCards.filter(function (card) {
var services = (card.dataset.services || "").split(",");
return preferred.some(function (service) { return services.indexOf(service) !== -1; });
});
if (matching.length) {
var matchingIds = new Set(matching.map(function (card) { return card.dataset.titleId; }));
selectedCards = matching.concat(popularCards.filter(function (card) {
return !matchingIds.has(card.dataset.titleId);
}));
statusText = "Preferred services first";
} else {
selectedCards = topCards;
statusText = "Top Rated fallback";
}
}
var visibleCards = selectedCards.slice(0, 24);
var shown = new Set(visibleCards);
recommendationCards.forEach(function (card) { card.hidden = !shown.has(card); });
var recommendationGrid = recommendationRoot.querySelector("[data-recommendation-grid]");
if (recommendationGrid) {
visibleCards.forEach(function (card) { recommendationGrid.appendChild(card); });
}
recommendationRoot.querySelector("[data-recommendation-status]").textContent = statusText;
recommendationRoot.querySelector("[data-recommendation-empty]").hidden = shown.size !== 0;
}
// Watchlist chevron dropdown menu.
var chevron = document.querySelector(".watchlist-chevron");
var menu = document.getElementById("watchlist-menu");
function closeMenu() {
if (menu && chevron) {
menu.hidden = true;
chevron.setAttribute("aria-expanded", "false");
}
}
if (chevron && menu) {
chevron.addEventListener("click", function (event) {
event.stopPropagation();
var open = !menu.hidden;
menu.hidden = open;
chevron.setAttribute("aria-expanded", String(!open));
});
document.addEventListener("click", function (event) {
if (!menu.hidden && !menu.contains(event.target)) {
closeMenu();
}
});
}
// Rating dialog open/close with Escape support.
var dialog = document.getElementById("rate-dialog");
var openers = document.querySelectorAll("[data-open-dialog='rate-dialog']");
function closeDialog() {
if (dialog) {
dialog.hidden = true;
}
}
openers.forEach(function (opener) {
opener.addEventListener("click", function () {
if (dialog) {
dialog.hidden = false;
var firstStar = dialog.querySelector("input[name='rating']");
if (firstStar) {
firstStar.focus();
}
}
});
});
if (dialog) {
var closeButton = dialog.querySelector(".dialog-close");
if (closeButton) {
closeButton.addEventListener("click", closeDialog);
}
dialog.addEventListener("click", function (event) {
if (event.target === dialog) {
closeDialog();
}
});
// Star fill preview on selection.
var options = Array.prototype.slice.call(
dialog.querySelectorAll(".star-option")
);
options.forEach(function (option, index) {
var input = option.querySelector("input");
if (!input) {
return;
}
input.addEventListener("change", function () {
options.forEach(function (other, otherIndex) {
other.classList.toggle("filled", otherIndex <= index);
});
});
});
}
// Overlay Escape handling closes any open overlay.
document.addEventListener("keydown", function (event) {
if (event.key === "Escape") {
closeDialog();
closeMenu();
setDrawer(false);
closeAccountDialog();
closeLanguageDialog();
}
});
// Character counters on the create-list form.
document.querySelectorAll("[data-counter]").forEach(function (field) {
var counter = document.getElementById(field.getAttribute("data-counter"));
var max = field.getAttribute("maxlength") || "255";
if (!counter) {
return;
}
field.addEventListener("input", function () {
counter.textContent = field.value.length + " of " + max + " characters";
});
});
// Same-origin search suggestions with combobox keyboard semantics.
var searchForm = document.querySelector("[data-search-form]");
if (searchForm) {
var searchInput = searchForm.querySelector("input[name='q']");
var suggestionBox = document.getElementById("search-suggestions");
var clearSearch = searchForm.querySelector(".search-clear");
var searchTimer = null;
var selectedIndex = -1;
var suggestionLinks = [];
function closeSuggestions() {
suggestionBox.hidden = true;
searchInput.setAttribute("aria-expanded", "false");
searchInput.removeAttribute("aria-activedescendant");
selectedIndex = -1;
}
function selectSuggestion(index) {
suggestionLinks.forEach(function (link, itemIndex) {
var selected = itemIndex === index;
link.setAttribute("aria-selected", String(selected));
link.classList.toggle("is-selected", selected);
});
selectedIndex = index;
if (index >= 0 && suggestionLinks[index]) {
searchInput.setAttribute("aria-activedescendant", suggestionLinks[index].id);
suggestionLinks[index].scrollIntoView({ block: "nearest" });
}
}
function renderSuggestions(payload) {
suggestionBox.replaceChildren();
suggestionLinks = [];
if (!payload.suggestions.length) {
var empty = document.createElement("p");
empty.className = "suggestion-empty";
empty.textContent = "No suggestions found";
suggestionBox.appendChild(empty);
} else {
payload.suggestions.forEach(function (suggestion, index) {
var link = document.createElement("a");
link.id = "search-suggestion-" + index;
link.href = suggestion.url;
link.role = "option";
link.setAttribute("aria-selected", "false");
var label = document.createElement("strong");
label.textContent = suggestion.label;
var meta = document.createElement("span");
meta.textContent = suggestion.kind === "person" ? "Person" : suggestion.year;
link.append(label, meta);
suggestionBox.appendChild(link);
suggestionLinks.push(link);
});
}
suggestionBox.hidden = false;
searchInput.setAttribute("aria-expanded", "true");
}
function loadSuggestions() {
var query = searchInput.value.trim();
clearSearch.hidden = !query;
if (query.length < 2) {
closeSuggestions();
return;
}
fetch("/find/suggest/?q=" + encodeURIComponent(query), {
headers: { Accept: "application/json" }
})
.then(function (response) {
if (!response.ok) { throw new Error("suggestion request failed"); }
return response.json();
})
.then(renderSuggestions)
.catch(function () {
suggestionBox.textContent = "Suggestions are temporarily unavailable.";
suggestionBox.hidden = false;
searchInput.setAttribute("aria-expanded", "true");
});
}
searchInput.addEventListener("input", function () {
window.clearTimeout(searchTimer);
searchTimer = window.setTimeout(loadSuggestions, 140);
});
searchInput.addEventListener("keydown", function (event) {
if (event.key === "ArrowDown" && suggestionLinks.length) {
event.preventDefault();
selectSuggestion((selectedIndex + 1) % suggestionLinks.length);
} else if (event.key === "ArrowUp" && suggestionLinks.length) {
event.preventDefault();
selectSuggestion(
selectedIndex <= 0 ? suggestionLinks.length - 1 : selectedIndex - 1
);
} else if (event.key === "Enter" && selectedIndex >= 0) {
event.preventDefault();
window.location.assign(suggestionLinks[selectedIndex].href);
} else if (event.key === "Escape") {
closeSuggestions();
}
});
clearSearch.addEventListener("click", function () {
searchInput.value = "";
clearSearch.hidden = true;
closeSuggestions();
searchInput.focus();
});
document.addEventListener("click", function (event) {
if (!searchForm.contains(event.target)) { closeSuggestions(); }
});
clearSearch.hidden = !searchInput.value;
}
// Prevent repeat writes while a POST is being submitted.
document.querySelectorAll("form[data-submit-state]").forEach(function (form) {
form.addEventListener("submit", function () {
var button = form.querySelector("button[type='submit']");
if (button) {
button.disabled = true;
button.setAttribute("aria-busy", "true");
button.dataset.originalLabel = button.textContent;
button.textContent = "Working…";
}
});
});
document.querySelectorAll("form[data-confirm]").forEach(function (form) {
form.addEventListener("submit", function (event) {
if (!window.confirm(form.getAttribute("data-confirm"))) {
event.preventDefault();
}
});
});
// Same-dialog local image and native-video viewer.
var galleryDialog = document.querySelector("[data-gallery-dialog]");
if (galleryDialog) {
var galleryImage = galleryDialog.querySelector("[data-gallery-image]");
var galleryVideo = galleryDialog.querySelector("[data-gallery-video]");
var galleryVideoSource = galleryDialog.querySelector("[data-gallery-video-source]");
var galleryVideoTrack = galleryDialog.querySelector("[data-gallery-video-track]");
var galleryVideoPage = galleryDialog.querySelector("[data-gallery-video-page]");
var galleryCaption = galleryDialog.querySelector("[data-gallery-caption]");
function closeGallery() {
galleryDialog.hidden = true;
if (galleryVideo) { galleryVideo.pause(); }
}
document.querySelectorAll("[data-gallery-open]").forEach(function (button) {
button.addEventListener("click", function () {
var image = button.querySelector("img");
var isVideo = button.dataset.galleryType === "video";
galleryImage.hidden = isVideo;
galleryVideo.hidden = !isVideo;
galleryVideoPage.hidden = !isVideo;
if (isVideo) {
galleryVideo.poster = button.dataset.galleryPoster;
galleryVideoSource.src = button.dataset.gallerySrc;
galleryVideoTrack.src = button.dataset.galleryCaptions;
galleryVideoPage.href = button.dataset.galleryVideoHref;
galleryVideo.load();
} else {
galleryVideo.pause();
galleryImage.src = button.dataset.gallerySrc || image.src;
galleryImage.alt = image.alt;
}
galleryCaption.textContent = button.dataset.galleryCaption || image.alt;
galleryDialog.hidden = false;
galleryDialog.querySelector("[data-gallery-close]").focus();
});
});
galleryDialog.querySelector("[data-gallery-close]").addEventListener("click", closeGallery);
galleryDialog.addEventListener("click", function (event) {
if (event.target === galleryDialog) { closeGallery(); }
});
document.addEventListener("keydown", function (event) {
if (event.key === "Escape") { closeGallery(); }
});
}
});
})();