1
0
mirror of https://github.com/flarum/core.git synced 2025-07-15 13:56:23 +02:00

Merge remote-tracking branch 'extensions_likes/REWRITE'

This commit is contained in:
Alexander Skvortsov
2022-03-11 18:01:17 -05:00
40 changed files with 3276 additions and 0 deletions

View File

@ -0,0 +1,19 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2
[*.{diff,md}]
trim_trailing_whitespace = false
[*.{php,xml,json}]
indent_size = 4

18
extensions/likes/.gitattributes vendored Normal file
View File

@ -0,0 +1,18 @@
.gitattributes export-ignore
.gitignore export-ignore
.gitmodules export-ignore
.github export-ignore
.travis export-ignore
.travis.yml export-ignore
.editorconfig export-ignore
.styleci.yml export-ignore
phpunit.xml export-ignore
tests export-ignore
js/dist/* -diff
js/dist/* linguist-generated
js/dist-typings/* linguist-generated
js/yarn.lock -diff
* text=auto eol=lf

View File

@ -0,0 +1,15 @@
name: Likes PHP
on: [workflow_dispatch, push, pull_request]
# The reusable workflow definitions will be moved to the `flarum/framework` repo soon.
# This will break your current script.
# When this happens, run `flarum-cli audit infra --fix` to update your infrastructure.
jobs:
run:
uses: flarum/.github/.github/workflows/REUSABLE_backend.yml@main
with:
enable_backend_testing: false
backend_directory: .

View File

@ -0,0 +1,21 @@
name: Likes JS
on: [workflow_dispatch, push, pull_request]
# The reusable workflow definitions will be moved to the `flarum/framework` repo soon.
# This will break your current script.
# When this happens, run `flarum-cli audit infra --fix` to update your infrastructure.
jobs:
run:
uses: flarum/.github/.github/workflows/REUSABLE_frontend.yml@main
with:
enable_bundlewatch: false
enable_prettier: true
enable_typescript: false
frontend_directory: ./js
main_git_branch: master
secrets:
bundlewatch_github_token: ${{ secrets.BUNDLEWATCH_GITHUB_TOKEN }}

12
extensions/likes/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
/vendor
composer.lock
composer.phar
.DS_Store
Thumbs.db
tests/.phpunit.result.cache
/tests/integration/tmp
.vagrant
.idea/*
.vscode
js/coverage-ts

View File

@ -0,0 +1,14 @@
preset: recommended
enabled:
- logical_not_operators_with_successor_space
disabled:
- align_double_arrow
- blank_line_after_opening_tag
- multiline_array_trailing_comma
- new_with_braces
- phpdoc_align
- phpdoc_order
- phpdoc_separation
- phpdoc_types

View File

@ -0,0 +1,62 @@
# Changelog
## [1.2.0](https://github.com/flarum/likes/compare/v1.1.0...v1.2.0)
No changes.
## [1.1.0](https://github.com/flarum/likes/compare/v1.0.0...v1.1.0)
### Changed
- Add missing dot to `liked_by_text` translation (https://github.com/flarum/likes/pulls/29)
## [1.0.0](https://github.com/flarum/likes/compare/v0.1.0-beta.16...v1.0.0)
### Added
- Creation time stored for likes in the database (https://github.com/flarum/likes/pull/28)
### Changed
- Compatibility with Flarum v1.0.0.
## [0.1.0-beta.16](https://github.com/flarum/likes/compare/v0.1.0-beta.15...v0.1.0-beta.16)
### Changed
- Updated admin category from discussion to feature (https://github.com/flarum/likes/pull/26)
- Moved locale files from translation pack to extension (https://github.com/flarum/likes/pull/23)
## [0.1.0-beta.15](https://github.com/flarum/likes/compare/v0.1.0-beta.14...v0.1.0-beta.15)
### Changed
- Updated composer.json and admin javascript for new admin area.
- Updated to use newest extenders.
## [0.1.0-beta.14](https://github.com/flarum/likes/compare/v0.1.0-beta.13...v0.1.0-beta.14)
### Changed
- Updated mithril to version 2
- Load language strings correctly on en-/disable
- Updated JS dependencies
## [0.1.0-beta.13](https://github.com/flarum/likes/compare/v0.1.0-beta.12...v0.1.0-beta.13)
### Changed
- Updated JS dependencies
- Stop using deprecated core events, use extenders instead
## [0.1.0-beta.12](https://github.com/flarum/likes/compare/v0.1.0-beta.9...v0.1.0-beta.12)
### Fixed
- Fix notifications being sent to deleted users ([726ddfe](https://github.com/flarum/likes/commit/726ddfe1b45f2752f6179848a7128e520b1860fc))
## [0.1.0-beta.9](https://github.com/flarum/likes/compare/v0.1.0-beta.8.1...v0.1.0-beta.9)
### Changed
- Replace event subscribers (that resolve services too early) with listeners ([0b3fbc5](https://github.com/flarum/likes/commit/0b3fbc5813a5b52e8b81aaf557dcf1ec37d1481a))
- Compatibility with Laravel 5.7 ([c2281d1](https://github.com/flarum/likes/commit/c2281d14f6e9268c6eb306781ffb43d74095cc9e))
## [0.1.0-beta.8.1](https://github.com/flarum/likes/compare/v0.1.0-beta.8...v0.1.0-beta.8.1)
### Fixed
- Fix dropping foreign keys in `down` migrations ([4e92f20](https://github.com/flarum/likes/commit/4e92f20d7a18efc08bb24e0767014e4ba689c805))
- Truncate notification excerpts ([55524aa](https://github.com/flarum/likes/commit/55524aa2e87951c858bf20d960e1f4f9a86a103f))
- Prevent possible crash on discussion view ([84bcc0e](https://github.com/flarum/likes/commit/84bcc0e283295b6109d4bc1449d8ba06b156ca01))

22
extensions/likes/LICENSE Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2019-2021 Stichting Flarum (Flarum Foundation)
Copyright (c) 2014-2019 Toby Zerner (toby.zerner@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,60 @@
{
"name": "flarum/likes",
"description": "Allow users to like posts.",
"type": "flarum-extension",
"keywords": [
"discussion"
],
"license": "MIT",
"support": {
"issues": "https://github.com/flarum/core/issues",
"source": "https://github.com/flarum/likes",
"forum": "https://discuss.flarum.org"
},
"homepage": "https://flarum.org",
"funding": [
{
"type": "website",
"url": "https://flarum.org/donate/"
}
],
"require": {
"flarum/core": "^1.2"
},
"autoload": {
"psr-4": {
"Flarum\\Likes\\": "src/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
},
"flarum-extension": {
"title": "Likes",
"category": "feature",
"icon": {
"name": "far fa-thumbs-up",
"backgroundColor": "#3A649D",
"color": "#fff"
}
},
"flarum-cli": {
"modules": {
"admin": true,
"forum": true,
"js": true,
"jsCommon": false,
"css": true,
"gitConf": true,
"githubActions": true,
"prettier": true,
"typescript": false,
"bundlewatch": false,
"backendTesting": false,
"editorConfig": true,
"styleci": true
}
}
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Api\Controller;
use Flarum\Api\Serializer\BasicUserSerializer;
use Flarum\Api\Serializer\PostSerializer;
use Flarum\Extend;
use Flarum\Likes\Event\PostWasLiked;
use Flarum\Likes\Event\PostWasUnliked;
use Flarum\Likes\Listener;
use Flarum\Likes\Notification\PostLikedBlueprint;
use Flarum\Post\Event\Deleted;
use Flarum\Post\Event\Saving;
use Flarum\Post\Post;
use Flarum\User\User;
return [
(new Extend\Frontend('forum'))
->js(__DIR__.'/js/dist/forum.js')
->css(__DIR__.'/less/forum.less'),
(new Extend\Frontend('admin'))
->js(__DIR__.'/js/dist/admin.js'),
(new Extend\Model(Post::class))
->belongsToMany('likes', User::class, 'post_likes', 'post_id', 'user_id'),
new Extend\Locales(__DIR__.'/locale'),
(new Extend\Notification())
->type(PostLikedBlueprint::class, PostSerializer::class, ['alert']),
(new Extend\ApiSerializer(PostSerializer::class))
->hasMany('likes', BasicUserSerializer::class)
->attribute('canLike', function (PostSerializer $serializer, $model) {
return (bool) $serializer->getActor()->can('like', $model);
}),
(new Extend\ApiController(Controller\ShowDiscussionController::class))
->addInclude('posts.likes'),
(new Extend\ApiController(Controller\ListPostsController::class))
->addInclude('likes'),
(new Extend\ApiController(Controller\ShowPostController::class))
->addInclude('likes'),
(new Extend\ApiController(Controller\CreatePostController::class))
->addInclude('likes'),
(new Extend\ApiController(Controller\UpdatePostController::class))
->addInclude('likes'),
(new Extend\Event())
->listen(PostWasLiked::class, Listener\SendNotificationWhenPostIsLiked::class)
->listen(PostWasUnliked::class, Listener\SendNotificationWhenPostIsUnliked::class)
->listen(Deleted::class, [Listener\SaveLikesToDatabase::class, 'whenPostIsDeleted'])
->listen(Saving::class, [Listener\SaveLikesToDatabase::class, 'whenPostIsSaving']),
];

9
extensions/likes/js/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
node_modules

View File

@ -0,0 +1 @@
export * from './src/admin';

2
extensions/likes/js/dist/admin.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
(()=>{var e={n:r=>{var o=r&&r.__esModule?()=>r.default:()=>r;return e.d(o,{a:o}),o},d:(r,o)=>{for(var t in o)e.o(o,t)&&!e.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:o[t]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},r={};(()=>{"use strict";e.r(r);const o=flarum.core.compat["admin/app"];var t=e.n(o);t().initializers.add("flarum-likes",(function(){t().extensionData.for("flarum-likes").registerPermission({icon:"far fa-thumbs-up",label:t().translator.trans("flarum-likes.admin.permissions.like_posts_label"),permission:"discussion.likePosts"},"reply")}))})(),module.exports=r})();
//# sourceMappingURL=admin.js.map

1
extensions/likes/js/dist/admin.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"admin.js","mappings":"MACA,IAAIA,EAAsB,CCA1BA,EAAyBC,IACxB,IAAIC,EAASD,GAAUA,EAAOE,WAC7B,IAAOF,EAAiB,QACxB,IAAM,EAEP,OADAD,EAAoBI,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,GCLRF,EAAwB,CAACM,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXP,EAAoBS,EAAEF,EAAYC,KAASR,EAAoBS,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3ER,EAAwB,CAACc,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFf,EAAyBM,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,M,+BCLvD,MAAM,EAA+BC,OAAOC,KAAKC,OAAO,a,aCExDC,IAAAA,aAAAA,IAAqB,gBAAgB,WACnCA,IAAAA,cAAAA,IAAsB,gBAAgBC,mBACpC,CACEC,KAAM,mBACNC,MAAOH,IAAAA,WAAAA,MAAqB,mDAC5BI,WAAY,wBAEd,a","sources":["webpack://@flarum/likes/webpack/bootstrap","webpack://@flarum/likes/webpack/runtime/compat get default export","webpack://@flarum/likes/webpack/runtime/define property getters","webpack://@flarum/likes/webpack/runtime/hasOwnProperty shorthand","webpack://@flarum/likes/webpack/runtime/make namespace object","webpack://@flarum/likes/external root \"flarum.core.compat['admin/app']\"","webpack://@flarum/likes/./src/admin/index.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['admin/app'];","import app from 'flarum/admin/app';\n\napp.initializers.add('flarum-likes', () => {\n app.extensionData.for('flarum-likes').registerPermission(\n {\n icon: 'far fa-thumbs-up',\n label: app.translator.trans('flarum-likes.admin.permissions.like_posts_label'),\n permission: 'discussion.likePosts',\n },\n 'reply'\n );\n});\n"],"names":["__webpack_require__","module","getter","__esModule","d","a","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","flarum","core","compat","app","registerPermission","icon","label","permission"],"sourceRoot":""}

2
extensions/likes/js/dist/forum.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
(()=>{var t={n:o=>{var n=o&&o.__esModule?()=>o.default:()=>o;return t.d(n,{a:n}),n},d:(o,n)=>{for(var e in n)t.o(n,e)&&!t.o(o,e)&&Object.defineProperty(o,e,{enumerable:!0,get:n[e]})},o:(t,o)=>Object.prototype.hasOwnProperty.call(t,o),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};(()=>{"use strict";t.r(o);const n=flarum.core.compat["common/extend"],e=flarum.core.compat["forum/app"];var r=t.n(e);const s=flarum.core.compat["common/models/Post"];var a=t.n(s);const i=flarum.core.compat["common/Model"];var c=t.n(i);const u=flarum.core.compat["forum/components/NotificationGrid"];var l=t.n(u);const f=flarum.core.compat["common/components/Button"];var p=t.n(f);const d=flarum.core.compat["forum/components/CommentPost"];var k=t.n(d);const h=flarum.core.compat["common/components/Link"];var v=t.n(h);const y=flarum.core.compat["common/helpers/punctuateSeries"];var _=t.n(y);const b=flarum.core.compat["common/helpers/username"];var g=t.n(b);const P=flarum.core.compat["common/helpers/icon"];var L=t.n(P);function M(t,o){return M=Object.setPrototypeOf||function(t,o){return t.__proto__=o,t},M(t,o)}function x(t,o){t.prototype=Object.create(o.prototype),t.prototype.constructor=t,M(t,o)}const j=flarum.core.compat["common/components/Modal"];var O=t.n(j);const N=flarum.core.compat["common/helpers/avatar"];var S=t.n(N),B=function(t){function o(){return t.apply(this,arguments)||this}x(o,t);var n=o.prototype;return n.className=function(){return"PostLikesModal Modal--small"},n.title=function(){return r().translator.trans("flarum-likes.forum.post_likes.title")},n.content=function(){return m("div",{className:"Modal-body"},m("ul",{className:"PostLikesModal-list"},this.attrs.post.likes().map((function(t){return m("li",null,m(v(),{href:r().route.user(t)},S()(t)," ",g()(t)))}))))},o}(O());const T=flarum.core.compat["forum/components/Notification"];var w=t.n(T);const C=flarum.core.compat["common/utils/string"];var I=function(t){function o(){return t.apply(this,arguments)||this}x(o,t);var n=o.prototype;return n.icon=function(){return"far fa-thumbs-up"},n.href=function(){return r().route.post(this.attrs.notification.subject())},n.content=function(){var t=this.attrs.notification.fromUser();return r().translator.trans("flarum-likes.forum.notifications.post_liked_text",{user:t,count:1})},n.excerpt=function(){return(0,C.truncate)(this.attrs.notification.subject().contentPlain(),200)},o}(w());r().initializers.add("flarum-likes",(function(){r().notificationComponents.postLiked=I,a().prototype.canLike=c().attribute("canLike"),a().prototype.likes=c().hasMany("likes"),(0,n.extend)(k().prototype,"actionItems",(function(t){var o=this.attrs.post;if(!o.isHidden()&&o.canLike()){var n=o.likes(),e=r().session.user&&n&&n.some((function(t){return t===r().session.user}));t.add("like",p().component({className:"Button Button--link",onclick:function(){e=!e,o.save({isLiked:e});var t=o.data.relationships.likes.data;t.some((function(o,n){if(o.id===r().session.user.id())return t.splice(n,1),!0})),e&&t.unshift({type:"users",id:r().session.user.id()})}},r().translator.trans(e?"flarum-likes.forum.post.unlike_link":"flarum-likes.forum.post.like_link")))}})),(0,n.extend)(k().prototype,"footerItems",(function(t){var o=this.attrs.post,n=o.likes();if(n&&n.length){var e=n.length>4,s=n.sort((function(t){return t===r().session.user?-1:1})).slice(0,e?3:4).map((function(t){return m(v(),{href:r().route.user(t)},t===r().session.user?r().translator.trans("flarum-likes.forum.post.you_text"):g()(t))}));if(e){var a=n.length-s.length;s.push(m("a",{href:"#",onclick:function(t){t.preventDefault(),r().modal.show(B,{post:o})}},r().translator.trans("flarum-likes.forum.post.others_link",{count:a})))}t.add("liked",m("div",{className:"Post-likedBy"},L()("far fa-thumbs-up"),r().translator.trans("flarum-likes.forum.post.liked_by"+(n[0]===r().session.user?"_self":"")+"_text",{count:s.length,users:_()(s)})))}})),(0,n.extend)(l().prototype,"notificationTypes",(function(t){t.add("postLiked",{name:"postLiked",icon:"far fa-thumbs-up",label:r().translator.trans("flarum-likes.forum.settings.notify_post_liked_label")})}))}))})(),module.exports=o})();
//# sourceMappingURL=forum.js.map

1
extensions/likes/js/dist/forum.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
export * from './src/forum';

View File

@ -0,0 +1,19 @@
{
"private": true,
"name": "@flarum/likes",
"prettier": "@flarum/prettier-config",
"devDependencies": {
"prettier": "^2.5.1",
"flarum-webpack-config": "^2.0.0",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"@flarum/prettier-config": "^1.0.0"
},
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production",
"format": "prettier --write src",
"format-check": "prettier --check src",
"analyze": "cross-env ANALYZER=true yarn build"
}
}

View File

@ -0,0 +1,12 @@
import app from 'flarum/admin/app';
app.initializers.add('flarum-likes', () => {
app.extensionData.for('flarum-likes').registerPermission(
{
icon: 'far fa-thumbs-up',
label: app.translator.trans('flarum-likes.admin.permissions.like_posts_label'),
permission: 'discussion.likePosts',
},
'reply'
);
});

View File

@ -0,0 +1,46 @@
import { extend } from 'flarum/common/extend';
import app from 'flarum/forum/app';
import Button from 'flarum/common/components/Button';
import CommentPost from 'flarum/forum/components/CommentPost';
export default function () {
extend(CommentPost.prototype, 'actionItems', function (items) {
const post = this.attrs.post;
if (post.isHidden() || !post.canLike()) return;
const likes = post.likes();
let isLiked = app.session.user && likes && likes.some((user) => user === app.session.user);
items.add(
'like',
Button.component(
{
className: 'Button Button--link',
onclick: () => {
isLiked = !isLiked;
post.save({ isLiked });
// We've saved the fact that we do or don't like the post, but in order
// to provide instantaneous feedback to the user, we'll need to add or
// remove the like from the relationship data manually.
const data = post.data.relationships.likes.data;
data.some((like, i) => {
if (like.id === app.session.user.id()) {
data.splice(i, 1);
return true;
}
});
if (isLiked) {
data.unshift({ type: 'users', id: app.session.user.id() });
}
},
},
app.translator.trans(isLiked ? 'flarum-likes.forum.post.unlike_link' : 'flarum-likes.forum.post.like_link')
)
);
});
}

View File

@ -0,0 +1,64 @@
import { extend } from 'flarum/common/extend';
import app from 'flarum/forum/app';
import CommentPost from 'flarum/forum/components/CommentPost';
import Link from 'flarum/common/components/Link';
import punctuateSeries from 'flarum/common/helpers/punctuateSeries';
import username from 'flarum/common/helpers/username';
import icon from 'flarum/common/helpers/icon';
import PostLikesModal from './components/PostLikesModal';
export default function () {
extend(CommentPost.prototype, 'footerItems', function (items) {
const post = this.attrs.post;
const likes = post.likes();
if (likes && likes.length) {
const limit = 4;
const overLimit = likes.length > limit;
// Construct a list of names of users who have liked this post. Make sure the
// current user is first in the list, and cap a maximum of 4 items.
const names = likes
.sort((a) => (a === app.session.user ? -1 : 1))
.slice(0, overLimit ? limit - 1 : limit)
.map((user) => {
return (
<Link href={app.route.user(user)}>
{user === app.session.user ? app.translator.trans('flarum-likes.forum.post.you_text') : username(user)}
</Link>
);
});
// If there are more users that we've run out of room to display, add a "x
// others" name to the end of the list. Clicking on it will display a modal
// with a full list of names.
if (overLimit) {
const count = likes.length - names.length;
names.push(
<a
href="#"
onclick={(e) => {
e.preventDefault();
app.modal.show(PostLikesModal, { post });
}}
>
{app.translator.trans('flarum-likes.forum.post.others_link', { count })}
</a>
);
}
items.add(
'liked',
<div className="Post-likedBy">
{icon('far fa-thumbs-up')}
{app.translator.trans('flarum-likes.forum.post.liked_by' + (likes[0] === app.session.user ? '_self' : '') + '_text', {
count: names.length,
users: punctuateSeries(names),
})}
</div>
);
}
});
}

View File

@ -0,0 +1,24 @@
import app from 'flarum/forum/app';
import Notification from 'flarum/forum/components/Notification';
import { truncate } from 'flarum/common/utils/string';
export default class PostLikedNotification extends Notification {
icon() {
return 'far fa-thumbs-up';
}
href() {
return app.route.post(this.attrs.notification.subject());
}
content() {
const notification = this.attrs.notification;
const user = notification.fromUser();
return app.translator.trans('flarum-likes.forum.notifications.post_liked_text', { user, count: 1 });
}
excerpt() {
return truncate(this.attrs.notification.subject().contentPlain(), 200);
}
}

View File

@ -0,0 +1,31 @@
import app from 'flarum/forum/app';
import Modal from 'flarum/common/components/Modal';
import Link from 'flarum/common/components/Link';
import avatar from 'flarum/common/helpers/avatar';
import username from 'flarum/common/helpers/username';
export default class PostLikesModal extends Modal {
className() {
return 'PostLikesModal Modal--small';
}
title() {
return app.translator.trans('flarum-likes.forum.post_likes.title');
}
content() {
return (
<div className="Modal-body">
<ul className="PostLikesModal-list">
{this.attrs.post.likes().map((user) => (
<li>
<Link href={app.route.user(user)}>
{avatar(user)} {username(user)}
</Link>
</li>
))}
</ul>
</div>
);
}
}

View File

@ -0,0 +1,27 @@
import { extend } from 'flarum/common/extend';
import app from 'flarum/forum/app';
import Post from 'flarum/common/models/Post';
import Model from 'flarum/common/Model';
import NotificationGrid from 'flarum/forum/components/NotificationGrid';
import addLikeAction from './addLikeAction';
import addLikesList from './addLikesList';
import PostLikedNotification from './components/PostLikedNotification';
app.initializers.add('flarum-likes', () => {
app.notificationComponents.postLiked = PostLikedNotification;
Post.prototype.canLike = Model.attribute('canLike');
Post.prototype.likes = Model.hasMany('likes');
addLikeAction();
addLikesList();
extend(NotificationGrid.prototype, 'notificationTypes', function (items) {
items.add('postLiked', {
name: 'postLiked',
icon: 'far fa-thumbs-up',
label: app.translator.trans('flarum-likes.forum.settings.notify_post_liked_label'),
});
});
});

View File

@ -0,0 +1 @@
module.exports = require('flarum-webpack-config')();

File diff suppressed because it is too large Load Diff

View File

View File

@ -0,0 +1,23 @@
.PostLikesModal-list {
list-style: none;
padding: 0;
margin: 0;
a {
color: @text-color;
font-size: 15px;
font-weight: bold;
display: block;
margin-bottom: 10px;
text-decoration: none;
&:hover .username {
text-decoration: underline;
}
}
.Avatar {
.Avatar--size(32px);
vertical-align: middle;
margin-right: 5px;
}
}

View File

@ -0,0 +1,37 @@
flarum-likes:
##
# UNIQUE KEYS - The following keys are used in only one location each.
##
# Translations in this namespace are used by the admin interface.
admin:
# These translations are used in the Permissions page of the admin interface.
permissions:
like_posts_label: Like posts
# Translations in this namespace are used by the forum user interface.
forum:
# These translations are used by the Notifications dropdown, a.k.a. "the bell".
notifications:
others_text: => core.ref.some_others
post_liked_text: "{username} liked your post" # Can be pluralized to agree with the number of users!
# These translations are displayed beneath individual posts.
post:
like_link: Like
liked_by_self_text: "{users} like this." # Can be pluralized to agree with the number of users!
liked_by_text: "{count, plural, one {{users} likes this} other {{users} like this}}."
others_link: => core.ref.some_others
unlike_link: Unlike
you_text: => core.ref.you
# These translations are used by the Users Who Like This modal dialog.
post_likes:
title: Users Who Like This
# These translations are used in the Settings page.
settings:
notify_post_liked_label: Someone likes one of my posts

View File

@ -0,0 +1,20 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Database\Migration;
use Illuminate\Database\Schema\Blueprint;
return Migration::createTable(
'posts_likes',
function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->primary(['post_id', 'user_id']);
}
);

View File

@ -0,0 +1,15 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Database\Migration;
use Flarum\Group\Group;
return Migration::addPermissions([
'discussion.likePosts' => Group::MEMBER_ID
]);

View File

@ -0,0 +1,12 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Database\Migration;
return Migration::renameTable('posts_likes', 'post_likes');

View File

@ -0,0 +1,39 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
// Delete rows with non-existent entities so that we will be able to create
// foreign keys without any issues.
$schema->getConnection()
->table('post_likes')
->whereNotExists(function ($query) {
$query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id');
})
->orWhereNotExists(function ($query) {
$query->selectRaw(1)->from('users')->whereColumn('id', 'user_id');
})
->delete();
$schema->table('post_likes', function (Blueprint $table) {
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
},
'down' => function (Builder $schema) {
$schema->table('post_likes', function (Blueprint $table) {
$table->dropForeign(['post_id']);
$table->dropForeign(['user_id']);
});
}
];

View File

@ -0,0 +1,18 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Database\Migration;
return Migration::addColumns('post_likes', [
'created_at' => [
'timestamp',
'null' => false,
'useCurrent' => true,
],
]);

View File

@ -0,0 +1,36 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Likes\Event;
use Flarum\Post\Post;
use Flarum\User\User;
class PostWasLiked
{
/**
* @var Post
*/
public $post;
/**
* @var User
*/
public $user;
/**
* @param Post $post
* @param User $user
*/
public function __construct(Post $post, User $user)
{
$this->post = $post;
$this->user = $user;
}
}

View File

@ -0,0 +1,36 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Likes\Event;
use Flarum\Post\Post;
use Flarum\User\User;
class PostWasUnliked
{
/**
* @var Post
*/
public $post;
/**
* @var User
*/
public $user;
/**
* @param Post $post
* @param User $user
*/
public function __construct(Post $post, User $user)
{
$this->post = $post;
$this->user = $user;
}
}

View File

@ -0,0 +1,54 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Likes\Listener;
use Flarum\Likes\Event\PostWasLiked;
use Flarum\Likes\Event\PostWasUnliked;
use Flarum\Post\Event\Deleted;
use Flarum\Post\Event\Saving;
class SaveLikesToDatabase
{
/**
* @param Saving $event
*/
public static function whenPostIsSaving(Saving $event)
{
$post = $event->post;
$data = $event->data;
if ($post->exists && isset($data['attributes']['isLiked'])) {
$actor = $event->actor;
$liked = (bool) $data['attributes']['isLiked'];
$actor->assertCan('like', $post);
$currentlyLiked = $post->likes()->where('user_id', $actor->id)->exists();
if ($liked && ! $currentlyLiked) {
$post->likes()->attach($actor->id);
$post->raise(new PostWasLiked($post, $actor));
} elseif ($currentlyLiked) {
$post->likes()->detach($actor->id);
$post->raise(new PostWasUnliked($post, $actor));
}
}
}
/**
* @param Deleted $event
*/
public static function whenPostIsDeleted(Deleted $event)
{
$event->post->likes()->detach();
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Likes\Listener;
use Flarum\Likes\Event\PostWasLiked;
use Flarum\Likes\Notification\PostLikedBlueprint;
use Flarum\Notification\NotificationSyncer;
class SendNotificationWhenPostIsLiked
{
/**
* @var NotificationSyncer
*/
protected $notifications;
/**
* @param NotificationSyncer $notifications
*/
public function __construct(NotificationSyncer $notifications)
{
$this->notifications = $notifications;
}
public function handle(PostWasLiked $event)
{
if ($event->post->user && $event->post->user->id != $event->user->id) {
$this->notifications->sync(
new PostLikedBlueprint($event->post, $event->user),
[$event->post->user]
);
}
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Likes\Listener;
use Flarum\Likes\Event\PostWasUnliked;
use Flarum\Likes\Notification\PostLikedBlueprint;
use Flarum\Notification\NotificationSyncer;
class SendNotificationWhenPostIsUnliked
{
/**
* @var NotificationSyncer
*/
protected $notifications;
/**
* @param NotificationSyncer $notifications
*/
public function __construct(NotificationSyncer $notifications)
{
$this->notifications = $notifications;
}
public function handle(PostWasUnliked $event)
{
if ($event->post->user && $event->post->user->id != $event->user->id) {
$this->notifications->sync(
new PostLikedBlueprint($event->post, $event->user),
[]
);
}
}
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Likes\Notification;
use Flarum\Notification\Blueprint\BlueprintInterface;
use Flarum\Post\Post;
use Flarum\User\User;
class PostLikedBlueprint implements BlueprintInterface
{
/**
* @var Post
*/
public $post;
/**
* @var User
*/
public $user;
/**
* @param Post $post
* @param User $user
*/
public function __construct(Post $post, User $user)
{
$this->post = $post;
$this->user = $user;
}
/**
* {@inheritdoc}
*/
public function getSubject()
{
return $this->post;
}
/**
* {@inheritdoc}
*/
public function getFromUser()
{
return $this->user;
}
/**
* {@inheritdoc}
*/
public function getData()
{
}
/**
* {@inheritdoc}
*/
public static function getType()
{
return 'postLiked';
}
/**
* {@inheritdoc}
*/
public static function getSubjectModel()
{
return Post::class;
}
}