discourse-user-card-directory/javascripts/discourse/initializers/user-card-directory.js.es6
David Taylor cff3d510f2
FIX: Update for Discourse core changes (#3)
- Adds support for core's customizable user directory: https://meta.discourse.org/t/195263
- Adds a new theme component setting which allows the statistics to be hidden completely from the user cards
- Uses core's new group filter functionality
- Adds .discourse-compatibility so that this component can still be installed successfully on older Discourse versions
2021-07-01 17:50:38 +01:00

87 lines
2.8 KiB
JavaScript

import { withPluginApi } from "discourse/lib/plugin-api";
import discourseComputed from "discourse-common/utils/decorators";
import User from "discourse/models/user";
import EmberObject from "@ember/object";
import { ajax } from "discourse/lib/ajax";
export default {
name: "user-card-directory",
initialize(container) {
// This component provides a responsive template
// Delete the core mobile one
delete Ember.TEMPLATES["mobile/users"];
withPluginApi("0.8.7", api => {
api.modifyClass("route:users", {
resetController(controller, isExiting) {
this._super(...arguments);
if (isExiting) {
controller.set("cachedUserCardInfo", {});
}
}
});
api.modifyClass("controller:users", {
cachedUserCardInfo: null,
init(){
this.set("cachedUserCardInfo", {});
this._super(...arguments);
},
@discourseComputed("model.content.@each")
userCards(allUsers) {
if (!allUsers) return [];
const toLoad = [];
if (settings.hide_current_user && this.currentUser) {
allUsers = allUsers.filter((u) => u.id !== this.currentUser.id);
}
const userCardInfos = allUsers.map(u => {
if (this.cachedUserCardInfo[u.id]) {
return this.cachedUserCardInfo[u.id];
}
const userCardInfo = (this.cachedUserCardInfo[
u.id
] = EmberObject.create({
user: User.create(u.user),
directoryItem: u,
loading: true
}));
toLoad.push(userCardInfo);
return userCardInfo;
});
const loadMax = 50;
while (toLoad.length > 0) {
const thisBatch = toLoad.splice(0, loadMax);
const promise = ajax("/user-cards.json", {
data: { user_ids: thisBatch.map(uc => uc.user.id).join(",") }
});
thisBatch.forEach(uc => {
// Each user card expects its own promise
// Rather than making a separate AJAX request for each
// We re-use the `user-cards.json` promise, and manipulate the data
const convertedPromise = promise.then(data => {
// Find the correct user from users, and put it in the user attribute
// Use Object.assign to avoid contaminating the source object
return Object.assign({}, data, {
user: data.users.find(u => u.id === uc.user.id)
});
});
return uc.user
.findDetails({ existingRequest: convertedPromise })
.finally(() => uc.set("loading", false));
});
}
return userCardInfos;
}
});
});
}
};