Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion app/controllers/topics_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class TopicsController < ApiController
only: %i[create update destroy import_users import_articles
generate_timepoints incremental_topic_build
generate_article_analytics start_data_generation
remove_article]
remove_article add_article]

def index
if current_editor && params[:owned]
Expand Down Expand Up @@ -158,6 +158,42 @@ def remove_article
render :show
end

def add_article
topic = find_editable_topic
raw_title = params[:title].to_s.strip
if raw_title.blank?
return render(json: { error: 'Article title is required' }, status: :unprocessable_entity)
end

page_info = WikiActionApi.new(topic.wiki).get_page_info(title: raw_title)
if page_info.nil? || page_info['pageid'].blank?
return render(json: { error: "No article named \"#{raw_title}\" found on " \
"#{topic.wiki.language}.#{topic.wiki.project}.org" },
status: :unprocessable_entity)
end

canonical_title = page_info['title']
article = topic.add_article_to_active_bag!(title: canonical_title,
pageid: page_info['pageid'])
if article.nil?
return render(json: { error: "\"#{canonical_title}\" is already in this topic" },
status: :unprocessable_entity)
end

begin
ArticleAnalyticsService.new(topic).generate_for_article(article)
rescue StandardError => e
Rails.logger.error('[TopicsController#add_article] analytics failed for ' \
"#{canonical_title}: #{e.class}: #{e.message}")
topic.remove_article_from_active_bag!(title: canonical_title)
return render(json: { error: 'Failed to fetch article analytics from Wikipedia. Please try again.' },
status: :bad_gateway)
end

@topic = topic.reload
render :show
end

protected

def find_editable_topic
Expand Down
231 changes: 231 additions & 0 deletions app/frontend/components/add-article-modal.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
import React, {
useState,
useEffect,
useMemo,
useRef,
RefObject,
ChangeEvent,
KeyboardEvent,
} from "react";
import { debounce } from "lodash";
import { BsPlusLg } from "react-icons/bs";
import { IoClose } from "react-icons/io5";
import LoadingOval from "./loading-oval.component";
import SuggestionsList, {
SuggestionsListHandle,
} from "./suggestions-list.component";
import useOutsideClick from "../hooks/useOutsideClick";
import { parseWikiUrlTitle } from "../utils/search-utils";
import { Suggestion } from "../types/search-tool.type";

interface AddArticleModalProps {
wiki?: { language: string; project: string };
onAdd: (title: string) => Promise<unknown>;
adding?: boolean;
onClose: () => void;
}

const AddArticleModal: React.FC<AddArticleModalProps> = ({
wiki,
onAdd,
adding,
onClose,
}) => {
const [query, setQuery] = useState<string>("");
const [submittedTitle, setSubmittedTitle] = useState<string>("");
const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
const [showSuggestions, setShowSuggestions] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [activeSuggestion, setActiveSuggestion] = useState<number>(-1);

const suggestionsRef = useOutsideClick(() => setShowSuggestions(false));
const suggestionsListRef = useRef<SuggestionsListHandle>(null);

const language = wiki?.language ?? "en";
const project = wiki?.project ?? "wikipedia";
const wikiDomain = `${language}.${project}.org`;

useEffect(() => {
suggestionsListRef.current?.scrollToSuggestion(activeSuggestion);
}, [activeSuggestion]);

const debouncedFetchSuggestions = useMemo(
() =>
debounce(async (search: string) => {
setIsLoading(true);
try {
const response = await fetch(
`https://${wikiDomain}/w/api.php?action=query&list=prefixsearch&pssearch=${encodeURIComponent(
search,
)}&pslimit=8&format=json&formatversion=2&origin=*`,
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
const next: Suggestion[] = (data.query?.prefixsearch ?? []).map(
(page: { title: string; pageid: number }) => ({
label: page.title,
description: "",
id: String(page.pageid),
}),
);
setSuggestions(next);
setShowSuggestions(true);
setActiveSuggestion(-1);
} catch (error) {
console.error("Error fetching article suggestions:", error);
setShowSuggestions(false);
} finally {
setIsLoading(false);
}
}, 300),
[wikiDomain],
);

const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setQuery(value);
if (!value.trim() || parseWikiUrlTitle(value)) {
debouncedFetchSuggestions.cancel();
setShowSuggestions(false);
return;
}
debouncedFetchSuggestions(value.trim());
};

const submitTitle = (title: string) => {
if (!title || adding) return;
debouncedFetchSuggestions.cancel();
setShowSuggestions(false);
setSubmittedTitle(title);
onAdd(title)
.then(() => onClose())
.catch(() => {});
};

const handleSuggestionClick = (suggestion: Suggestion) => {
setQuery(suggestion.label);
debouncedFetchSuggestions.cancel();
setShowSuggestions(false);
};

const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (!showSuggestions) return;

switch (e.key) {
case "ArrowDown":
setActiveSuggestion((prev) =>
prev === suggestions.length - 1 ? 0 : prev + 1,
);
break;
case "ArrowUp":
setActiveSuggestion((prev) =>
prev === 0 ? suggestions.length - 1 : prev - 1,
);
break;
case "Enter":
if (activeSuggestion >= 0 && activeSuggestion < suggestions.length) {
e.preventDefault();
handleSuggestionClick(suggestions[activeSuggestion]);
}
break;
case "Escape":
setShowSuggestions(false);
break;
}
};

return (
<div
className="AddArticleModal"
onClick={(e) => {
if (e.target === e.currentTarget && !adding) onClose();
}}
>
<div className="Panel">
<div className="Header">
<div className="TitleGroup">
<BsPlusLg size={18} className="HeaderIcon" />
<h3 className="Title">Add article to topic</h3>
</div>
<button
type="button"
className="Close"
onClick={onClose}
disabled={adding}
aria-label="Close add article"
>
<IoClose size={24} />
</button>
</div>
<div className="Body">
<p className="Intro">
Search {wikiDomain} by article title, or paste a full article URL
(e.g. https://{wikiDomain}/wiki/...).
</p>
<ul className="HowTo">
<li>
Adding fetches the article&apos;s statistics from Wikipedia.
Popular articles with many editors and incoming links can take
longer to fetch.
</li>
<li>
Once added, the article appears in the chart and the aggregate
stats update right away.
</li>
</ul>
{adding ? (
<div className="FetchingState" role="status">
<LoadingOval visible height="44" width="44" />
<div className="FetchingText">
<strong>Adding &ldquo;{submittedTitle}&rdquo;&hellip;</strong>
<span>Fetching article statistics from Wikipedia.</span>
</div>
</div>
) : (
<form
className="AddArticleForm"
onSubmit={(e) => {
e.preventDefault();
submitTitle(parseWikiUrlTitle(query) ?? query.trim());
}}
>
<input
type="text"
className="AddArticleInput"
value={query}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder="Article title or URL"
aria-label="Article title or URL"
autoFocus
/>
<button type="submit" className="AddBtn" disabled={!query.trim()}>
Add
</button>
{showSuggestions && (
<div
className="AddArticleSuggestions"
ref={suggestionsRef as RefObject<HTMLDivElement>}
>
<SuggestionsList
ref={suggestionsListRef}
suggestions={suggestions}
activeSuggestion={activeSuggestion}
setActiveSuggestion={setActiveSuggestion}
handleSuggestionClick={handleSuggestionClick}
isLoading={isLoading}
LoadingOval={LoadingOval}
/>
</div>
)}
</form>
)}
</div>
</div>
</div>
);
};

export default AddArticleModal;
19 changes: 10 additions & 9 deletions app/frontend/components/advanced-filter-panel.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,22 @@ import {
CENTRALITY_MIN,
CENTRALITY_MAX,
} from "../utils/bubble-chart-permalink";
import { RAW_ASSESSMENT_COLORS } from "../utils/bubble-chart-utils";

const gradeGroups = [
{ id: "fa", label: "Featured", grades: ["FA", "FL"], dot: "#9CBDFF" },
{ id: "ga", label: "GA", grades: ["GA"], dot: "#66FF66" },
{ id: "aclass", label: "A-Class", grades: ["A"], dot: "#66FFFF" },
{ id: "bclass", label: "B-Class", grades: ["B"], dot: "#B2FF66" },
{ id: "cclass", label: "C-Class", grades: ["C"], dot: "#FFFF66" },
{ id: "start", label: "Start", grades: ["Start"], dot: "#FFAA66" },
{ id: "stub", label: "Stub", grades: ["Stub"], dot: "#FFA4A4" },
{ id: "list", label: "List", grades: ["List"], dot: "#C7B1FF" },
{ id: "fa", label: "Featured", grades: ["FA", "FL"], dot: RAW_ASSESSMENT_COLORS.FA },
{ id: "ga", label: "GA", grades: ["GA"], dot: RAW_ASSESSMENT_COLORS.GA },
{ id: "aclass", label: "A-Class", grades: ["A"], dot: RAW_ASSESSMENT_COLORS.A },
{ id: "bclass", label: "B-Class", grades: ["B"], dot: RAW_ASSESSMENT_COLORS.B },
{ id: "cclass", label: "C-Class", grades: ["C"], dot: RAW_ASSESSMENT_COLORS.C },
{ id: "start", label: "Start", grades: ["Start"], dot: RAW_ASSESSMENT_COLORS.Start },
{ id: "stub", label: "Stub", grades: ["Stub"], dot: RAW_ASSESSMENT_COLORS.Stub },
{ id: "list", label: "List", grades: ["List"], dot: RAW_ASSESSMENT_COLORS.List },
{
id: "unassessed",
label: "Unassessed",
grades: ["Unassessed"],
dot: "#9E9E9E",
dot: RAW_ASSESSMENT_COLORS.Unassessed,
},
];

Expand Down
59 changes: 59 additions & 0 deletions app/frontend/components/chart-aggregate-stats.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from "react";

export interface ChartAggregateStatsProps {
stats: {
totalArticles: number;
millionVisits: number | null;
averageTotalViews: number | null;
averageArticleSize: number | null;
startDateLabel: string | null;
};
}

const ChartAggregateStats: React.FC<ChartAggregateStatsProps> = ({ stats }) => {
return (
<div className="Stats">
<div className="StatCell">
<span className="StatValue">
{stats.totalArticles.toLocaleString()}
</span>
<span className="StatLabel">Total articles</span>
</div>

<div className="StatCell">
<span className="StatValue">
{stats.millionVisits !== null
? stats.millionVisits.toLocaleString("en-US", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
: "—"}
</span>
<span className="StatLabel">
Million visits
{stats.startDateLabel ? ` (since ${stats.startDateLabel})` : ""}
</span>
</div>

<div className="StatCell">
<span className="StatValue">
{stats.averageTotalViews !== null
? stats.averageTotalViews.toLocaleString()
: "—"}
</span>
<span className="StatLabel">Average total views per article</span>
</div>

<div className="StatCell">
<span className="StatValue">
{stats.averageArticleSize !== null
? stats.averageArticleSize.toLocaleString()
: "—"}
</span>
<span className="StatLabel">Average article size (bytes)</span>
</div>
</div>
);
};

export default ChartAggregateStats;
Loading
Loading