REFACTOR: Remove `Discourse.Category` constants

This commit is contained in:
Robin Ward 2019-11-08 13:30:41 -05:00
parent e51efce356
commit 7ac2a55588
28 changed files with 95 additions and 78 deletions

View File

@ -6,6 +6,7 @@ import Component from "@ember/component";
import { bufferedProperty } from "discourse/mixins/buffered-content";
import { on, observes } from "discourse-common/utils/decorators";
import { popupAjaxError } from "discourse/lib/ajax-error";
import Category from "discourse/models/category";
export default Component.extend(bufferedProperty("host"), {
editToggled: false,
@ -50,7 +51,7 @@ export default Component.extend(bufferedProperty("host"), {
host
.save(props)
.then(() => {
host.set("category", Discourse.Category.findById(this.categoryId));
host.set("category", Category.findById(this.categoryId));
this.set("editToggled", false);
})
.catch(popupAjaxError);

View File

@ -1,11 +1,12 @@
import discourseComputed from "discourse-common/utils/decorators";
import Component from "@ember/component";
import Category from "discourse/models/category";
export default Component.extend({
@discourseComputed("value")
selectedCategories: {
get(value) {
return Discourse.Category.findByIds(value.split("|"));
return Category.findByIds(value.split("|"));
},
set(value) {
this.set("value", value.mapBy("id").join("|"));

View File

@ -5,6 +5,7 @@ import { observes } from "discourse-common/utils/decorators";
import { escapeExpression } from "discourse/lib/utilities";
import Group from "discourse/models/group";
import Badge from "discourse/models/badge";
import Category from "discourse/models/category";
const REGEXP_BLOCKS = /(([^" \t\n\x0B\f\r]+)?(("[^"]+")?))/g;
@ -224,7 +225,7 @@ export default Component.extend({
.replace(REGEXP_CATEGORY_PREFIX, "")
.split(":");
if (subcategories.length > 1) {
const userInput = Discourse.Category.findBySlug(
const userInput = Category.findBySlug(
subcategories[1],
subcategories[0]
);
@ -234,14 +235,14 @@ export default Component.extend({
)
this.set("searchedTerms.category", userInput);
} else if (isNaN(subcategories)) {
const userInput = Discourse.Category.findSingleBySlug(subcategories[0]);
const userInput = Category.findSingleBySlug(subcategories[0]);
if (
(!existingInput && userInput) ||
(existingInput && userInput && existingInput.id !== userInput.id)
)
this.set("searchedTerms.category", userInput);
} else {
const userInput = Discourse.Category.findById(subcategories[0]);
const userInput = Category.findById(subcategories[0]);
if (
(!existingInput && userInput) ||
(existingInput && userInput && existingInput.id !== userInput.id)

View File

@ -1,6 +1,7 @@
import discourseComputed from "discourse-common/utils/decorators";
import { sort } from "@ember/object/computed";
import Component from "@ember/component";
import Category from "discourse/models/category";
export default Component.extend({
classNameBindings: [":tag-list", "categoryClass", "tagGroupNameClass"],
@ -15,7 +16,7 @@ export default Component.extend({
@discourseComputed("categoryId")
category(categoryId) {
return categoryId && Discourse.Category.findById(categoryId);
return categoryId && Category.findById(categoryId);
},
@discourseComputed("category.fullSlug")

View File

@ -2,6 +2,7 @@ import { alias, not } from "@ember/object/computed";
import { inject } from "@ember/controller";
import Controller from "@ember/controller";
import DiscourseURL from "discourse/lib/url";
import Category from "discourse/models/category";
export default Controller.extend({
discoveryTopics: inject("discovery/topics"),
@ -25,7 +26,7 @@ export default Controller.extend({
if (category) {
url =
"/c/" +
Discourse.Category.slugFor(category) +
Category.slugFor(category) +
(this.noSubcategories ? "/none" : "") +
"/l";
}

View File

@ -8,6 +8,7 @@ import {
on,
observes
} from "discourse-common/utils/decorators";
import Category from "discourse/models/category";
export default Controller.extend(ModalFunctionality, {
selectedTab: null,
@ -106,7 +107,7 @@ export default Controller.extend(ModalFunctionality, {
slug: result.category.slug,
id: result.category.id
});
DiscourseURL.redirectTo("/c/" + Discourse.Category.slugFor(model));
DiscourseURL.redirectTo("/c/" + Category.slugFor(model));
})
.catch(error => {
this.flash(extractError(error), "error");

View File

@ -15,6 +15,7 @@ import { on, observes } from "discourse-common/utils/decorators";
import { sanitizeAsync } from "discourse/lib/text";
import { iconHTML } from "discourse-common/lib/icon-library";
import Post from "discourse/models/post";
import Category from "discourse/models/category";
function customTagArray(fieldName) {
return computed(fieldName, function() {
@ -95,10 +96,7 @@ export default Controller.extend(ModalFunctionality, {
post.set("topic.fancy_title", result.topic.fancy_title);
}
if (result.category_id) {
post.set(
"topic.category",
Discourse.Category.findById(result.category_id)
);
post.set("topic.category", Category.findById(result.category_id));
}
this.send("closeModal");
})
@ -226,7 +224,7 @@ export default Controller.extend(ModalFunctionality, {
@discourseComputed("model.category_id_changes")
previousCategory(changes) {
if (changes) {
var category = Discourse.Category.findById(changes["previous"]);
var category = Category.findById(changes["previous"]);
return categoryBadgeHTML(category, { allowUncategorized: true });
}
},
@ -234,7 +232,7 @@ export default Controller.extend(ModalFunctionality, {
@discourseComputed("model.category_id_changes")
currentCategory(changes) {
if (changes) {
var category = Discourse.Category.findById(changes["current"]);
var category = Category.findById(changes["current"]);
return categoryBadgeHTML(category, { allowUncategorized: true });
}
},

View File

@ -11,6 +11,7 @@ import {
extraNavItemProperties,
customNavItemHref
} from "discourse/models/nav-item";
import Category from "discourse/models/category";
if (extraNavItemProperties) {
extraNavItemProperties(function(text, opts) {
@ -36,7 +37,7 @@ if (customNavItemHref) {
if (category) {
path += "c/";
path += Discourse.Category.slugFor(category);
path += Category.slugFor(category);
if (navItem.get("noSubcategories")) {
path += "/none";
}

View File

@ -2,6 +2,7 @@ import { empty, alias } from "@ember/object/computed";
import Controller from "@ember/controller";
import ModalFunctionality from "discourse/mixins/modal-functionality";
import Topic from "discourse/models/topic";
import Category from "discourse/models/category";
const _buttons = [];
@ -175,7 +176,7 @@ export default Controller.extend(ModalFunctionality, {
changeCategory() {
const categoryId = parseInt(this.newCategoryId, 10) || 0;
const category = Discourse.Category.findById(categoryId);
const category = Category.findById(categoryId);
this.perform({ type: "change_category", category_id: categoryId }).then(
topics => {

View File

@ -2,6 +2,7 @@ import { get } from "@ember/object";
import { registerUnbound } from "discourse-common/lib/helpers";
import { isRTL } from "discourse/lib/text-direction";
import { iconHTML } from "discourse-common/lib/icon-library";
import Category from "discourse/models/category";
let escapeExpression = Handlebars.Utils.escapeExpression;
let _renderer = defaultCategoryLinkRenderer;
@ -78,7 +79,7 @@ function defaultCategoryLinkRenderer(category, opts) {
let restricted = get(category, "read_restricted");
let url = opts.url
? opts.url
: Discourse.getURL("/c/") + Discourse.Category.slugFor(category);
: Discourse.getURL("/c/") + Category.slugFor(category);
let href = opts.link === false ? "" : url;
let tagName = opts.link === false || opts.link === "false" ? "span" : "a";
let extraClasses = opts.extraClasses ? " " + opts.extraClasses : "";
@ -88,9 +89,7 @@ function defaultCategoryLinkRenderer(category, opts) {
let categoryDir = "";
if (!opts.hideParent) {
parentCat = Discourse.Category.findById(
get(category, "parent_category_id")
);
parentCat = Category.findById(get(category, "parent_category_id"));
}
const categoryStyle =

View File

@ -1,6 +1,7 @@
import PreloadStore from "preload-store";
import { ajax } from "discourse/lib/ajax";
import Topic from "discourse/models/topic";
import Category from "discourse/models/category";
const CategoryList = Ember.ArrayProxy.extend({
init() {
@ -12,7 +13,7 @@ const CategoryList = Ember.ArrayProxy.extend({
CategoryList.reopenClass({
categoriesFrom(store, result) {
const categories = CategoryList.create();
const list = Discourse.Category.list();
const list = Category.list();
let statPeriod = "all";
const minCategories = result.category_list.categories.length * 0.66;

View File

@ -5,6 +5,7 @@ import RestModel from "discourse/models/rest";
import { on } from "discourse-common/utils/decorators";
import PermissionType from "discourse/models/permission-type";
import { NotificationLevels } from "discourse/lib/notification-levels";
import deprecated from "discourse-common/lib/deprecated";
const Category = RestModel.extend({
permissions: null,
@ -407,4 +408,14 @@ Category.reopenClass({
}
});
Object.defineProperty(Discourse, "Category", {
get() {
deprecated(
"Import the Category object instead of using Discourse.Category",
{ since: "2.4.0", dropFrom: "2.5.0" }
);
return Category;
}
});
export default Category;

View File

@ -1,6 +1,7 @@
import discourseComputed from "discourse-common/utils/decorators";
import { toTitleCase } from "discourse/lib/formatter";
import { emojiUnescape } from "discourse/lib/text";
import Category from "discourse/models/category";
const NavItem = Discourse.Model.extend({
@discourseComputed("categoryName", "name")
@ -53,7 +54,7 @@ const NavItem = Discourse.Model.extend({
"nameLower",
split[1].toLowerCase()
);
return cat ? Discourse.Category.slugFor(cat) : null;
return cat ? Category.slugFor(cat) : null;
}
return null;
},
@ -84,7 +85,7 @@ const NavItem = Discourse.Model.extend({
let mode = "";
if (category) {
mode += "c/";
mode += Discourse.Category.slugFor(category);
mode += Category.slugFor(category);
if (noSubcategories) {
mode += "/none";
}
@ -143,7 +144,7 @@ NavItem.reopenClass({
)
return null;
if (!Discourse.Category.list() && testName === "categories") return null;
if (!Category.list() && testName === "categories") return null;
if (!Discourse.Site.currentProp("top_menu_items").includes(testName))
return null;

View File

@ -5,6 +5,7 @@ import ResultSet from "discourse/models/result-set";
import { getRegister } from "discourse-common/lib/get-owner";
import { underscore } from "@ember/string";
import { set } from "@ember/object";
import Category from "discourse/models/category";
let _identityMap;
@ -272,7 +273,7 @@ export default EmberObject.extend({
// to category. That should either respect this or be
// removed.
if (subType === "category" && type !== "topic") {
return Discourse.Category.findById(id);
return Category.findById(id);
}
if (root.meta && root.meta.types) {

View File

@ -5,6 +5,7 @@ import RestModel from "discourse/models/rest";
import Model from "discourse/models/model";
import { getOwner } from "discourse-common/lib/get-owner";
import { Promise } from "rsvp";
import Category from "discourse/models/category";
// Whether to show the category badge in topic lists
function displayCategoryInList(site, category) {
@ -136,7 +137,7 @@ TopicList.reopenClass({
// Stitch together our side loaded data
const categories = Discourse.Category.list(),
const categories = Category.list(),
users = Model.extractByKey(result.users, Discourse.User),
groups = Model.extractByKey(result.primary_groups, EmberObject);

View File

@ -7,6 +7,7 @@ import {
} from "discourse-common/utils/decorators";
import { defaultHomepage } from "discourse/lib/utilities";
import PreloadStore from "preload-store";
import Category from "discourse/models/category";
function isNew(topic) {
return (
@ -57,7 +58,7 @@ const TopicTrackingState = Discourse.Model.extend({
// fill parent_category_id we need it for counting new/unread
if (data.payload && data.payload.category_id) {
var category = Discourse.Category.findById(data.payload.category_id);
var category = Category.findById(data.payload.category_id);
if (category && category.parent_category_id) {
data.payload.parent_category_id = category.parent_category_id;
@ -133,7 +134,7 @@ const TopicTrackingState = Discourse.Model.extend({
const categoryId = data.payload && data.payload.category_id;
if (filterCategory && filterCategory.get("id") !== categoryId) {
const category = categoryId && Discourse.Category.findById(categoryId);
const category = categoryId && Category.findById(categoryId);
if (
!category ||
category.get("parentCategory.id") !== filterCategory.get("id")
@ -194,7 +195,7 @@ const TopicTrackingState = Discourse.Model.extend({
if (split.length >= 4) {
filter = split[split.length - 1];
// c/cat/subcat/l/latest
var category = Discourse.Category.findSingleBySlug(
var category = Category.findSingleBySlug(
split.splice(1, split.length - 3).join("/")
);
this.set("filterCategory", category);
@ -408,7 +409,7 @@ const TopicTrackingState = Discourse.Model.extend({
loadStates(data) {
const states = this.states;
const idMap = Discourse.Category.idMap();
const idMap = Category.idMap();
// I am taking some shortcuts here to avoid 500 gets for a large list
if (data) {

View File

@ -18,6 +18,7 @@ import {
observes,
on
} from "discourse-common/utils/decorators";
import Category from "discourse/models/category";
export function loadTopicView(topic, args) {
const data = _.merge({}, args);
@ -208,7 +209,7 @@ const Topic = RestModel.extend({
@on("init")
@observes("category_id")
_categoryIdChanged() {
this.set("category", Discourse.Category.findById(this.category_id));
this.set("category", Category.findById(this.category_id));
},
@observes("categoryName")

View File

@ -5,6 +5,7 @@ import { on } from "discourse-common/utils/decorators";
import UserActionGroup from "discourse/models/user-action-group";
import { postUrl } from "discourse/lib/utilities";
import { userPath } from "discourse/lib/url";
import Category from "discourse/models/category";
const UserActionTypes = {
likes_given: 1,
@ -31,7 +32,7 @@ const UserAction = RestModel.extend({
_attachCategory() {
const categoryId = this.category_id;
if (categoryId) {
this.set("category", Discourse.Category.findById(categoryId));
this.set("category", Category.findById(categoryId));
}
},

View File

@ -631,17 +631,14 @@ const User = RestModel.extend({
@observes("muted_category_ids")
updateMutedCategories() {
this.set(
"mutedCategories",
Discourse.Category.findByIds(this.muted_category_ids)
);
this.set("mutedCategories", Category.findByIds(this.muted_category_ids));
},
@observes("tracked_category_ids")
updateTrackedCategories() {
this.set(
"trackedCategories",
Discourse.Category.findByIds(this.tracked_category_ids)
Category.findByIds(this.tracked_category_ids)
);
},
@ -649,7 +646,7 @@ const User = RestModel.extend({
updateWatchedCategories() {
this.set(
"watchedCategories",
Discourse.Category.findByIds(this.watched_category_ids)
Category.findByIds(this.watched_category_ids)
);
},
@ -657,7 +654,7 @@ const User = RestModel.extend({
updateWatchedFirstPostCategories() {
this.set(
"watchedFirstPostCategories",
Discourse.Category.findByIds(this.watched_first_post_category_ids)
Category.findByIds(this.watched_first_post_category_ids)
);
},

View File

@ -65,7 +65,7 @@ export default (filterArg, params) => {
_setupNavigation(category) {
const noSubcategories = params && !!params.no_subcategories,
filterMode = `c/${Discourse.Category.slugFor(category)}${
filterMode = `c/${Category.slugFor(category)}${
noSubcategories ? "/none" : ""
}/l/${this.filter(category)}`;
@ -92,9 +92,9 @@ export default (filterArg, params) => {
},
_retrieveTopicList(category, transition) {
const listFilter = `c/${Discourse.Category.slugFor(
const listFilter = `c/${Category.slugFor(category)}/l/${this.filter(
category
)}/l/${this.filter(category)}`,
)}`,
findOpts = filterQueryParams(transition.to.queryParams, params),
extras = { cached: this.isPoppedState(transition) };

View File

@ -7,6 +7,7 @@ import {
} from "discourse/routes/build-topic-route";
import { queryParams } from "discourse/controllers/discovery-sortable";
import PermissionType from "discourse/models/permission-type";
import Category from "discourse/models/category";
export default DiscourseRoute.extend({
navMode: "latest",
@ -79,10 +80,7 @@ export default DiscourseRoute.extend({
let filter;
if (categorySlug) {
const category = Discourse.Category.findBySlug(
categorySlug,
parentCategorySlug
);
const category = Category.findBySlug(categorySlug, parentCategorySlug);
if (parentCategorySlug) {
filter = `tags/c/${parentCategorySlug}/${categorySlug}/${tagId}/l/${topicFilter}`;
} else if (this.noSubcategories) {

View File

@ -1,6 +1,7 @@
import { createWidget } from "discourse/widgets/widget";
import { h } from "virtual-dom";
import { number } from "discourse/lib/formatter";
import Category from "discourse/models/category";
createWidget("hamburger-category", {
tagName: "li.category-link",
@ -10,7 +11,7 @@ createWidget("hamburger-category", {
this.tagName += ".subcategory";
}
this.tagName += ".category-" + Discourse.Category.slugFor(c, "-");
this.tagName += ".category-" + Category.slugFor(c, "-");
const results = [
this.attach("category-link", { category: c, allowUncategorized: true })

View File

@ -81,7 +81,7 @@ export default ComboBoxComponent.extend({
const contentLength = (content && content.length) || 0;
return (
contentLength >= 15 ||
(this.isAsync && contentLength < Discourse.Category.list().length)
(this.isAsync && contentLength < Category.list().length)
);
},
@ -141,7 +141,7 @@ export default ComboBoxComponent.extend({
categoryURL = Discourse.getURL(this.noCategoriesUrl);
} else {
const category = Category.findById(parseInt(categoryId, 10));
const slug = Discourse.Category.slugFor(category);
const slug = Category.slugFor(category);
categoryURL = Discourse.getURL("/c/") + slug;
}
@ -164,7 +164,7 @@ export default ComboBoxComponent.extend({
return;
}
let results = Discourse.Category.search(filter);
let results = Category.search(filter);
if (!this.siteSettings.allow_uncategorized_topics) {
results = results.filter(result => {

View File

@ -87,7 +87,6 @@ JS
@@whitelisted ||= Set.new(
[
"discourse/routes/discourse",
"discourse/models/category",
"discourse/models/site",
"discourse/models/user",
"discourse/models/session",

View File

@ -7,7 +7,7 @@ QUnit.test("slugFor", assert => {
const store = createStore();
const slugFor = function(cat, val, text) {
assert.equal(Discourse.Category.slugFor(cat), val, text);
assert.equal(Category.slugFor(cat), val, text);
};
slugFor(
@ -86,35 +86,35 @@ QUnit.test("findBySlug", assert => {
}),
categoryList = [darth, luke, hurricane, newsFeed, time, bah];
sandbox.stub(Discourse.Category, "list").returns(categoryList);
sandbox.stub(Category, "list").returns(categoryList);
assert.deepEqual(
Discourse.Category.findBySlug("darth"),
Category.findBySlug("darth"),
darth,
"we can find a category"
);
assert.deepEqual(
Discourse.Category.findBySlug("luke", "darth"),
Category.findBySlug("luke", "darth"),
luke,
"we can find the other category with parent category"
);
assert.deepEqual(
Discourse.Category.findBySlug("熱帶風暴畫眉"),
Category.findBySlug("熱帶風暴畫眉"),
hurricane,
"we can find a category with CJK slug"
);
assert.deepEqual(
Discourse.Category.findBySlug("뉴스피드", "熱帶風暴畫眉"),
Category.findBySlug("뉴스피드", "熱帶風暴畫眉"),
newsFeed,
"we can find a category with CJK slug whose parent slug is also CJK"
);
assert.deepEqual(
Discourse.Category.findBySlug("时间", "darth"),
Category.findBySlug("时间", "darth"),
time,
"we can find a category with CJK slug whose parent slug is english"
);
assert.deepEqual(
Discourse.Category.findBySlug("bah", "熱帶風暴畫眉"),
Category.findBySlug("bah", "熱帶風暴畫眉"),
bah,
"we can find a category with english slug whose parent slug is CJK"
);
@ -150,35 +150,35 @@ QUnit.test("findSingleBySlug", assert => {
}),
categoryList = [darth, luke, hurricane, newsFeed, time, bah];
sandbox.stub(Discourse.Category, "list").returns(categoryList);
sandbox.stub(Category, "list").returns(categoryList);
assert.deepEqual(
Discourse.Category.findSingleBySlug("darth"),
Category.findSingleBySlug("darth"),
darth,
"we can find a category"
);
assert.deepEqual(
Discourse.Category.findSingleBySlug("darth/luke"),
Category.findSingleBySlug("darth/luke"),
luke,
"we can find the other category with parent category"
);
assert.deepEqual(
Discourse.Category.findSingleBySlug("熱帶風暴畫眉"),
Category.findSingleBySlug("熱帶風暴畫眉"),
hurricane,
"we can find a category with CJK slug"
);
assert.deepEqual(
Discourse.Category.findSingleBySlug("熱帶風暴畫眉/뉴스피드"),
Category.findSingleBySlug("熱帶風暴畫眉/뉴스피드"),
newsFeed,
"we can find a category with CJK slug whose parent slug is also CJK"
);
assert.deepEqual(
Discourse.Category.findSingleBySlug("darth/时间"),
Category.findSingleBySlug("darth/时间"),
time,
"we can find a category with CJK slug whose parent slug is english"
);
assert.deepEqual(
Discourse.Category.findSingleBySlug("熱帶風暴畫眉/bah"),
Category.findSingleBySlug("熱帶風暴畫眉/bah"),
bah,
"we can find a category with english slug whose parent slug is CJK"
);
@ -191,13 +191,10 @@ QUnit.test("findByIds", assert => {
2: store.createRecord("category", { id: 2 })
};
sandbox.stub(Discourse.Category, "idMap").returns(categories);
assert.deepEqual(
Discourse.Category.findByIds([1, 2, 3]),
_.values(categories)
);
sandbox.stub(Category, "idMap").returns(categories);
assert.deepEqual(Category.findByIds([1, 2, 3]), _.values(categories));
assert.deepEqual(Discourse.Category.findByIds(), []);
assert.deepEqual(Category.findByIds(), []);
});
QUnit.test("search with category name", assert => {

View File

@ -1,11 +1,12 @@
import { run } from "@ember/runloop";
import createStore from "helpers/create-store";
import NavItem from "discourse/models/nav-item";
import Category from "discourse/models/category";
QUnit.module("NavItem", {
beforeEach() {
run(function() {
const asianCategory = Discourse.Category.create({
const asianCategory = Category.create({
name: "确实是这样",
id: 343434
});

View File

@ -1,10 +1,10 @@
import EmberObject from "@ember/object";
import { IMAGE_VERSION as v } from "pretty-text/emoji/version";
import Category from "discourse/models/category";
import Topic from "discourse/models/topic";
QUnit.module("model:topic");
import Topic from "discourse/models/topic";
QUnit.test("defaults", assert => {
const topic = Topic.create({ id: 1234 });
@ -84,7 +84,7 @@ QUnit.test("has suggestedTopics", assert => {
QUnit.test("category relationship", assert => {
// It finds the category by id
const category = Discourse.Category.list()[0];
const category = Category.list()[0];
const topic = Topic.create({ id: 1111, category_id: category.get("id") });
assert.equal(topic.get("category"), category);
@ -92,7 +92,7 @@ QUnit.test("category relationship", assert => {
QUnit.test("updateFromJson", assert => {
const topic = Topic.create({ id: 1234 });
const category = Discourse.Category.list()[0];
const category = Category.list()[0];
topic.updateFromJson({
post_stream: [1, 2, 3],

View File

@ -1,5 +1,6 @@
import TopicTrackingState from "discourse/models/topic-tracking-state";
import createStore from "helpers/create-store";
import Category from "discourse/models/category";
QUnit.module("model:topic-tracking-state");
@ -37,7 +38,7 @@ QUnit.test("subscribe to category", function(assert) {
}),
categoryList = [darth, luke];
sandbox.stub(Discourse.Category, "list").returns(categoryList);
sandbox.stub(Category, "list").returns(categoryList);
const state = TopicTrackingState.create();