Compare commits

..
Author SHA1 Message Date
Anthony 5f8c812b9d seems to be working 2021-09-10 13:01:46 -04:00
305 changed files with 14041 additions and 4987 deletions

No files matched your search

+12 -2
View File
@@ -11,12 +11,15 @@ WEB_SERVER_PORT=1337
LBRY_WEB_API=https://api.na-backend.odysee.com
LBRY_WEB_STREAMING_API=https://cdn.lbryplayer.xyz
LBRY_WEB_BUFFER_API=https://collector-service.api.lbry.tv/api/v1/events/video
COMMENT_SERVER_API=https://comments.lbry.com/api/v2
COMMENT_SERVER_API=https://comments.odysee.com/api/v2
COMMENT_SERVER_NAME=Odysee
SEARCH_SERVER_API=https://lighthouse.odysee.com/search
SOCKETY_SERVER_API=wss://sockety.odysee.com/ws
THUMBNAIL_CDN_URL=https://image-processor.vanwanet.com/optimize/
WELCOME_VERSION=1.0
# STRIPE
STRIPE_PUBLIC_KEY='pk_test_NoL1JWL7i1ipfhVId5KfDZgo'
# STRIPE_PUBLIC_KEY='pk_test_NoL1JWL7i1ipfhVId5KfDZgo'
# Analytics
MATOMO_URL=https://analytics.lbry.com/
@@ -37,6 +40,9 @@ SITE_NAME=lbry.tv
SITE_DESCRIPTION=Meet LBRY, an open, free, and community-controlled content wonderland.
SITE_HELP_EMAIL=help@lbry.com
LOGO_TITLE=lbry.tv
## Social media
TWITTER_ACCOUNT=LBRYcom
BRANDED_SITE=odysee
## IMAGE ASSETS
YRBL_HAPPY_IMG_URL=https://cdn.lbryplayer.xyz/api/v3/streams/free/yrbl-happy/7aa50a7e5adaf48691935d55e45d697547392929/839d9a
@@ -46,6 +52,7 @@ YRBL_SAD_IMG_URL=https://cdn.lbryplayer.xyz/api/v3/streams/free/yrbl-sad/c2d9649
#LOGO_TEXT_LIGHT=https://cdn.lbryplayer.xyz/api/v3/streams/free/yrbl-sad/c2d9649633d974e5ffb503925e1f17d951f1bd0f/f262dd
#LOGO_TEXT_DARK=https://cdn.lbryplayer.xyz/api/v3/streams/free/yrbl-sad/c2d9649633d974e5ffb503925e1f17d951f1bd0f/f262dd
#AVATAR_DEFAULT=
#MISSING_THUMB_DEFAULT=
#FAVICON=
# LOCALE
@@ -68,6 +75,7 @@ AUTO_FOLLOW_CHANNELS=lbry://@lbry#3fda836a92faaceedfe398225fb9b2ee2ed1f01a
## FEATURES AND LIMITS
SIMPLE_SITE=false
#BRANDED_SITE
ENABLE_COMMENT_REACTIONS=true
ENABLE_FILE_REACTIONS=false
@@ -103,3 +111,5 @@ ENABLE_UI_NOTIFICATIONS=false
#IMAGES_ENABLED=true
#FILES_ENABLED=true
#MODELS_ENABLED=true
BRANDED_SITE=odysee
+1
View File
@@ -31,6 +31,7 @@ module.name_mapper='^modal\(.*\)$' -> '<PROJECT_ROOT>/ui/modal\1'
module.name_mapper='^app\(.*\)$' -> '<PROJECT_ROOT>/ui/app\1'
module.name_mapper='^native\(.*\)$' -> '<PROJECT_ROOT>/ui/native\1'
module.name_mapper='^analytics\(.*\)$' -> '<PROJECT_ROOT>/ui/analytics\1'
module.name_mapper='^recsys\(.*\)$' -> '<PROJECT_ROOT>/ui/recsys\1'
module.name_mapper='^rewards\(.*\)$' -> '<PROJECT_ROOT>/ui/rewards\1'
module.name_mapper='^i18n\(.*\)$' -> '<PROJECT_ROOT>/ui/i18n\1'
module.name_mapper='^effects\(.*\)$' -> '<PROJECT_ROOT>/ui/effects\1'
+25 -17
View File
@@ -1,15 +1,26 @@
## Fixes
Issue Number:
<!-- Tip:
- Add keywords to directly close the Issue when the PR is merged.
- Skip the keyword if the Issue contains multiple items.
- https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword
-->
## What is the current behavior?
## What is the new behavior?
## Other information
<!-- If this PR contains a breaking change, please describe the impact and solution strategy for existing applications below. -->
## PR Checklist
<!-- For the checkbox formatting to work properly, make sure there are no spaces on either side of the "x" -->
Please check all that apply to this PR using "x":
- [ ] I have checked that this PR is not a duplicate of an existing PR (open, closed or merged)
- [ ] I added a line describing my change to CHANGELOG.md
- [ ] I have checked that this PR does not introduce a breaking change
- [ ] This PR introduces breaking changes and I have provided a detailed explanation below
## PR Type
<details><summary>Toggle...</summary>
What kind of change does this PR introduce?
@@ -20,14 +31,11 @@ What kind of change does this PR introduce?
- [ ] Documentation changes
- [ ] Other - Please describe:
## Fixes
Please check all that apply to this PR using "x":
Issue Number:
- [ ] I have checked that this PR is not a duplicate of an existing PR (open, closed or merged)
- [ ] I added a line describing my change to CHANGELOG.md
- [ ] I have checked that this PR does not introduce a breaking change
- [ ] This PR introduces breaking changes and I have provided a detailed explanation below
## What is the current behavior?
## What is the new behavior?
## Other information
<!-- If this PR contains a breaking change, please describe the impact and solution strategy for existing applications below. -->
</details>
+1 -1
View File
@@ -3,7 +3,7 @@
"ui/**/*.{js,jsx,scss,json}": ["prettier --write", "git add"],
"web/**/*.{js,jsx,scss,json}": ["prettier --write", "git add"],
"ui/**/*.{js,jsx}": ["eslint", "flow focus-check --color always", "git add"],
"web/**/*.{js,jsx,scss}": ["eslint", "git add"]
"web/**/*.{js,jsx}": ["eslint", "git add"]
},
"ignore": ["node_modules", "web/dist/**/*", "dist/**/*", "package-lock.json"]
}
+32 -1
View File
@@ -3,22 +3,53 @@
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased for Desktop]
## [0.51.2] - [2021-08-20]
### Added
- Show currently active playing item on playlist _community pr!_ ([#6453](https://github.com/lbryio/lbry-desktop/pull/6453))
- Add watch later to hover action for last used playlist on popup _community pr!_ ([#6274](https://github.com/lbryio/lbry-desktop/pull/6274))
- Add confirmation on comment removal _community pr!_ ([#6563](https://github.com/lbryio/lbry-desktop/pull/6563))
- Show on content page if a file is part of a playlist already _community pr!_([#6393](https://github.com/lbryio/lbry-desktop/pull/6393))
- Add filtering to playlists ([#6905](https://github.com/lbryio/lbry-desktop/pull/6905))
- Added direct replying to notifications _community pr!_ ([#6935](https://github.com/lbryio/lbry-desktop/pull/6935))
- Added "Replay" option on autoplay countdown ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added "Loop" option on Lists ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added "Shuffle" option on Lists ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added Play Next/Previous buttons (with shortcuts SHIFT+N/SHIFT+P) ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added separate control for autoplay next on video player ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
### Changed
- Use Canonical Url for copy link ([#6500](https://github.com/lbryio/lbry-desktop/pull/6500))
- Use better icon for copy link ([#6485](https://github.com/lbryio/lbry-desktop/pull/6485))
- Comments load paginated ([#6390](https://github.com/lbryio/lbry-desktop/pull/6390))
- Improve twitter share _community pr!_ ([#6690](https://github.com/lbryio/lbry-desktop/pull/6690))
- Update lighthouse search api _community pr!_ ([#6731](https://github.com/lbryio/lbry-desktop/pull/6731))
- Update sockety api _community pr!_ ([#6747](https://github.com/lbryio/lbry-desktop/pull/6747))
- Use resolve for OG metadata instead of chainquery _community pr!_ ([#6787](https://github.com/lbryio/lbry-desktop/pull/6787))
- Improved clickability of notification links _community pr!_ ([#6711](https://github.com/lbryio/lbry-desktop/pull/6711))
- Changing the supported language from Filipino to Tagalog _community pr!_ ([#6951](https://github.com/lbryio/lbry-desktop/pull/6951))
- Don't show countdown to next item in list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Changed "View List" popup option to link, so can be opened on a new tab ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
### Fixed
- App now supports '#' and ':' for claimId separator ([#6496](https://github.com/lbryio/lbry-desktop/pull/6496))
- Fix "exact match" being applied to Recommended ([#6460](https://github.com/lbryio/lbry-desktop/pull/6460))
- Fix upload button on creator analytics _community pr!_ ([#6458](https://github.com/lbryio/lbry-desktop/pull/6458))
- Prevent sidebar shortcut activation on textarea _community pr!_ ([#6454](https://github.com/lbryio/lbry-desktop/pull/6454))
- Improve accessibility and some minor css fixes _community pr!_ ([#6470](https:/github.com/lbryio/lbry-desktop/pull/6470))
- Fix drag / drop publish issues for web users _community pr!_ ([#6466](https://github.com/lbryio/lbry-desktop/pull/6466))
- Fix yarn copyenv on windows _community pr!_ ([#6702](https://github.com/lbryio/lbry-desktop/pull/6702))
- Fix unnecessary livestream api calls in channel page _community pr!_ ([#6652](https://github.com/lbryio/lbry-desktop/pull/6652))
- Fix desktop app fails to resolve deep links _community pr!_ ([#6779](https://github.com/lbryio/lbry-desktop/pull/6779))
- Fix wrong release date on GoogleVideo metadata _community pr!_ ([#6787](https://github.com/lbryio/lbry-desktop/pull/6787))
- Fix markdown line breaking mid word _community pr!_ ([#6805](https://github.com/lbryio/lbry-desktop/pull/6805))
- Added \ and = to reserved symbol warning _community pr!_ ([#6733](https://github.com/lbryio/lbry-desktop/pull/6733))
- Don't break words in chat + fix text overflow past 3 dot menu _community pr!_ ([#6602](https://github.com/lbryio/lbry-desktop/pull/6602))
- Fix embed shows wrong OG metadata _community pr!_ ([#6815](https://github.com/lbryio/lbry-desktop/pull/6815))
- Fix OG: "Unparsable data structure - Truncated Unicode character" _community pr!_ ([#6839](https://github.com/lbryio/lbry-desktop/pull/6839))
- Fix Paid embed warning overlay redirection button now links to odysee _community pr!_ ([#6819](https://github.com/lbryio/lbry-desktop/pull/6819))
- Fix comment section redirection to create channel _community pr!_ ([#6557](https://github.com/lbryio/lbry-desktop/pull/6557))
- Clicking on the title of a floating player will take you back to the list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
## [0.51.1] - [2021-06-26]
+1 -1
View File
@@ -96,7 +96,7 @@ You can run the web version (lbry.tv), the electron app, or both at the same tim
`yarn dev:web`
- This uses webpack-dev-server and includes hot-reloading. If you want to debug the [web server we use in production](https://github.com/lbryio/lbry-desktop/blob/master/src/platforms/web/server.js) you can run `yarn dev:web-server`. This starts a server at `localhost:1337` and does not include hot reloading.
- This uses webpack-dev-server and includes hot-reloading. If you want to debug the [web server we use in production](https://github.com/lbryio/lbry-desktop/blob/master/web/index.js) you can run `yarn dev:web-server`. This starts a server at `localhost:1337` and does not include hot reloading.
#### Customize the web app
+13 -5
View File
@@ -9,10 +9,14 @@ const config = {
WEBPACK_ELECTRON_PORT: process.env.WEBPACK_ELECTRON_PORT,
WEB_SERVER_PORT: process.env.WEB_SERVER_PORT,
LBRY_WEB_API: process.env.LBRY_WEB_API, //api.na-backend.odysee.com',
LBRY_WEB_PUBLISH_API: process.env.LBRY_WEB_PUBLISH_API,
LBRY_API_URL: process.env.LBRY_API_URL, //api.lbry.com',
LBRY_WEB_STREAMING_API: process.env.LBRY_WEB_STREAMING_API, //cdn.lbryplayer.xyz',
LBRY_WEB_BUFFER_API: process.env.LBRY_WEB_BUFFER_API,
SEARCH_SERVER_API: process.env.SEARCH_SERVER_API,
COMMENT_SERVER_API: process.env.COMMENT_SERVER_API,
COMMENT_SERVER_NAME: process.env.COMMENT_SERVER_NAME,
SOCKETY_SERVER_API: process.env.SOCKETY_SERVER_API,
WELCOME_VERSION: process.env.WELCOME_VERSION,
DOMAIN: process.env.DOMAIN,
SHARE_DOMAIN_URL: process.env.SHARE_DOMAIN_URL,
@@ -22,12 +26,16 @@ const config = {
SITE_NAME: process.env.SITE_NAME,
SITE_DESCRIPTION: process.env.SITE_DESCRIPTION,
SITE_HELP_EMAIL: process.env.SITE_HELP_EMAIL,
// SOCIAL MEDIA
TWITTER_ACCOUNT: process.env.TWITTER_ACCOUNT,
// LOGO
LOGO_TITLE: process.env.LOGO_TITLE,
FAVICON: process.env.FAVICON,
LOGO_URL: process.env.LOGO_URL,
LOGO_TEXT_LIGHT_URL: process.env.LOGO_TEXT_LIGHT_URL,
LOGO_TEXT_DARK_URL: process.env.LOGO_TEXT_DARK_URL,
LOGO: process.env.LOGO,
LOGO_TEXT_LIGHT: process.env.LOGO_TEXT_LIGHT,
LOGO_TEXT_DARK: process.env.LOGO_TEXT_DARK,
AVATAR_DEFAULT: process.env.AVATAR_DEFAULT,
MISSING_THUMB_DEFAULT: process.env.MISSING_THUMB_DEFAULT,
// OG
OG_TITLE_SUFFIX: process.env.OG_TITLE_SUFFIX,
OG_HOMEPAGE_TITLE: process.env.OG_HOMEPAGE_TITLE,
@@ -40,7 +48,6 @@ const config = {
DEFAULT_LANGUAGE: process.env.DEFAULT_LANGUAGE,
AUTO_FOLLOW_CHANNELS: process.env.AUTO_FOLLOW_CHANNELS,
UNSYNCED_SETTINGS: process.env.UNSYNCED_SETTINGS,
AVATAR_DEFAULT: process.env.AVATAR_DEFAULT,
// ENABLE FEATURES
ENABLE_COMMENT_REACTIONS: process.env.ENABLE_COMMENT_REACTIONS === 'true',
@@ -65,9 +72,10 @@ const config = {
CUSTOM_HOMEPAGE: process.env.CUSTOM_HOMEPAGE === 'true',
SHOW_TAGS_INTRO: process.env.SHOW_TAGS_INTRO === 'true',
LIGHTHOUSE_DEFAULT_TYPES: process.env.LIGHTHOUSE_DEFAULT_TYPES,
BRANDED_SITE: process.env.BRANDED_SITE,
};
config.URL_LOCAL = `http://localhost:${config.WEB_SERVER_PORT}`;
config.URL_DEV = `http://localhost:${config.WEBPACK_WEB_PORT}`;
config.URL_LOCAL = `http://localhost:${config.WEB_SERVER_PORT}`;
module.exports = config;
+17 -5
View File
@@ -45,9 +45,15 @@ let daemon;
let lbryFirst;
const appState = {};
const PROTOCOL = 'lbry';
if (process.platform !== 'linux') {
app.setAsDefaultProtocolClient('lbry');
if (isDev && process.platform === 'win32') {
// Setting this is required to get this working in dev mode.
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [
path.resolve(process.argv[1]),
]);
} else {
app.setAsDefaultProtocolClient(PROTOCOL);
}
app.name = 'LBRY';
@@ -149,9 +155,15 @@ if (!gotSingleInstanceLock) {
app.on('second-instance', (event, argv) => {
// Send the url to the app to navigate first, then focus
if (rendererWindow) {
if ((process.platform === 'win32' || process.platform === 'linux') && String(argv[1]).startsWith('lbry')) {
let URI = argv[1];
// External uri (last item on argv):
const EXTERNAL_URI = (argv.length) ? argv[argv.length - 1] : '';
// Handle protocol requests for windows and linux
const platforms = (process.platform === 'win32' || process.platform === 'linux');
// Is LBRY protocol
const isProtocolURI = String(EXTERNAL_URI).startsWith(PROTOCOL + '://');
// External protocol requested:
if (platforms && isProtocolURI) {
let URI = EXTERNAL_URI;
// Keep only command line / deep linked arguments
// Windows normalizes URIs when they're passed in from other apps. On Windows, this tries to
// restore the original URI that was typed.
+58 -6
View File
@@ -14,6 +14,9 @@ declare type Comment = {
is_pinned: boolean,
support_amount: number,
replies: number, // number of direct replies (i.e. excluding nested replies).
is_moderator: boolean,
is_creator: boolean,
is_global_mod: boolean,
is_fiat?: boolean,
};
@@ -32,12 +35,13 @@ declare type CommentsState = {
byId: { [string]: Array<string> }, // ClaimID -> list of fetched comment IDs.
totalCommentsById: {}, // ClaimId -> ultimate total (including replies) in commentron.
repliesByParentId: { [string]: Array<string> }, // ParentCommentID -> list of fetched replies.
totalRepliesByParentId: {}, // ParentCommentID -> total replies in commentron.
repliesTotalPagesByParentId: {}, // ParentCommentID -> total number of reply pages for a parentId in commentron.
topLevelCommentsById: { [string]: Array<string> }, // ClaimID -> list of fetched top level comments.
topLevelTotalPagesById: { [string]: number }, // ClaimID -> total number of top-level pages in commentron. Based on COMMENT_PAGE_SIZE_TOP_LEVEL.
topLevelTotalCommentsById: { [string]: number }, // ClaimID -> total top level comments in commentron.
commentById: { [string]: Comment },
linkedCommentAncestors: { [string]: Array<string> }, // {"linkedCommentId": ["parentId", "grandParentId", ...]}
pinnedCommentsById: {}, // ClaimId -> array of pinned comment IDs
isLoading: boolean,
isLoadingByParentId: { [string]: boolean },
myComments: ?Set<string>,
@@ -56,8 +60,10 @@ declare type CommentsState = {
fetchingModerationDelegators: boolean,
blockingByUri: {},
unBlockingByUri: {},
personalTimeoutMap: { [uri: string]: { blockedAt: string, bannedFor: number, banRemaining: number } },
adminTimeoutMap: { [uri: string]: { blockedAt: string, bannedFor: number, banRemaining: number } },
moderatorTimeoutMap: { [uri: string]: { blockedAt: string, bannedFor: number, banRemaining: number } },
togglingForDelegatorMap: {[string]: Array<string>}, // {"blockedUri": ["delegatorUri1", ""delegatorUri2", ...]}
commentsDisabledChannelIds: Array<string>,
settingsByChannelId: { [string]: PerChannelSettings }, // ChannelID -> settings
fetchingSettings: boolean,
fetchingBlockedWords: boolean,
@@ -186,7 +192,43 @@ declare type SuperListResponse = {
has_hidden_comments: boolean,
};
declare type ModerationBlockParams = {};
declare type ModerationBlockParams = {
// Publisher, Moderator, or Commentron Admin
mod_channel_id: string,
mod_channel_name: string,
// Offender being blocked
blocked_channel_id: string,
blocked_channel_name: string,
// Creator that Moderator is delegated from. Used for delegated moderation
creator_channel_id?: string,
creator_channel_name?: string,
// Blocks identity from comment universally, requires Admin rights on commentron instance
block_all?: boolean,
time_out?: number,
// If true will delete all comments of the offender, requires Admin rights on commentron for universal delete
delete_all?: boolean,
// The usual signature stuff
signature: string,
signing_ts: string,
};
declare type ModerationBlockResponse = {
deleted_comment_ids: Array<string>,
banned_channel_id: string,
all_blocked: boolean,
banned_from: string,
};
declare type BlockedListArgs = {
// Publisher, Moderator or Commentron Admin
mod_channel_id: string,
mod_channel_name: string,
// Creator that Moderator is delegated from. Used for delegated moderation
creator_channel_id?: string,
creator_channel_name?: string,
signature: string,
signing_ts: string,
};
declare type ModerationAddDelegateParams = {
mod_channel_id: string,
@@ -221,10 +263,20 @@ declare type ModerationAmIParams = {
};
declare type SettingsParams = {
channel_name: string,
channel_name?: string,
channel_id: string,
signature: string,
signing_ts: string,
signature?: string,
signing_ts?: string,
};
declare type SettingsResponse = {
words?: string,
comments_enabled: boolean,
min_tip_amount_comment: number,
min_tip_amount_super_chat: number,
slow_mode_min_gap: number,
curse_jar_amount: number,
filters_enabled?: boolean,
};
declare type UpdateSettingsParams = {
+2 -1
View File
@@ -28,7 +28,7 @@ declare type SearchOptions = {
declare type SearchState = {
options: SearchOptions,
urisByQuery: {},
resultsByQuery: {},
hasReachedMaxResultsLength: {},
searching: boolean,
};
@@ -40,6 +40,7 @@ declare type SearchSuccess = {
from: number,
size: number,
uris: Array<string>,
recsys: string,
},
};
+9 -6
View File
@@ -1,6 +1,6 @@
{
"name": "lbry",
"version": "0.51.1",
"version": "0.51.2",
"description": "A browser for the LBRY network, a digital marketplace controlled by its users.",
"keywords": [
"lbry"
@@ -24,7 +24,7 @@
"compile:electron": "node --max_old_space_size=4096 ./node_modules/webpack/bin/webpack.js --config webpack.electron.config.js",
"compile:web": "yarn copyenv && cd web && node --max_old_space_size=4096 ./node_modules/webpack/bin/webpack.js --config webpack.config.js",
"compile": "cross-env NODE_ENV=production yarn compile:electron && cross-env NODE_ENV=production yarn compile:web",
"copyenv": "cp ./.env* web/",
"copyenv": "copyfiles ./.env* web/",
"dev": "yarn dev:electron",
"dev:electron": "cross-env NODE_ENV=development node ./electron/devServer.js",
"dev:web": "yarn copyenv && cd web && yarn dev",
@@ -38,7 +38,7 @@
"build:dir": "yarn build -- --dir -c.compression=store -c.mac.identity=null",
"crossenv": "./node_modules/cross-env/dist/bin/cross-env",
"lint": "eslint 'ui/**/*.{js,jsx}' && eslint 'web/**/*.{js,jsx}' && eslint 'electron/**/*.js' && flow",
"lint-fix": "eslint --fix 'ui/**/*.{js,jsx}' && eslint --fix 'web/**/*.{js,jsx}' && eslint --fix 'electron/**/*.js' && flow",
"lint-fix": "eslint --fix --quiet 'ui/**/*.{js,jsx}' && eslint --fix --quiet 'web/**/*.{js,jsx}' && eslint --fix --quiet 'electron/**/*.js'",
"format": "prettier 'src/**/*.{js,jsx,scss,json}' --write",
"flow-defs": "flow-typed install",
"precommit": "lint-staged",
@@ -54,12 +54,14 @@
"electron-notarize": "^1.0.0",
"electron-updater": "^4.2.4",
"express": "^4.17.1",
"feed": "^4.2.2",
"humanize-duration": "^3.27.0",
"if-env": "^1.0.4",
"parse-duration": "^1.0.0",
"react-datetime-picker": "^3.2.1",
"react-plastic": "^1.1.1",
"react-top-loading-bar": "^2.0.1",
"remove-markdown": "^0.3.0",
"rss": "^1.2.2",
"source-map-explorer": "^2.5.2",
"tempy": "^0.6.0",
"videojs-contrib-ads": "^6.9.0",
@@ -107,6 +109,7 @@
"concurrently": "^4.1.2",
"connected-react-router": "^6.8.0",
"copy-webpack-plugin": "^5.1.2",
"copyfiles": "^2.4.1",
"country-data": "^0.0.31",
"cross-env": "^7.0.3",
"crypto-js": "^4.0.0",
@@ -151,8 +154,8 @@
"imagesloaded": "^4.1.4",
"json-loader": "^0.5.4",
"lbry-format": "https://github.com/lbryio/lbry-format.git",
"lbry-redux": "lbryio/lbry-redux#a327385cdf71568dbd15a17f3dcf5f4b83e0966d",
"lbryinc": "lbryio/lbryinc#8f9a58bfc8312a65614fd7327661cdcc502c4e59",
"lbry-redux": "lbryio/lbry-redux#49b9db5aae8db84ec21231444bf8345d450812b2",
"lbryinc": "lbryio/lbryinc#0b4e41ef90d6347819dd3453f2f9398a5c1b4f36",
"lint-staged": "^7.0.2",
"localforage": "^1.7.1",
"lodash-es": "^4.17.14",
+120 -21
View File
@@ -155,9 +155,12 @@
"Lost passwords cannot be recovered.": "Lost passwords cannot be recovered.",
"Experimental settings": "Experimental settings",
"Autoplay media files": "Autoplay media files",
"Autoplay video and audio files when navigating to a file, as well as the next related item when a file finishes playing.": "Autoplay video and audio files when navigating to a file, as well as the next related item when a file finishes playing.",
"Application cache": "Application cache",
"Autoplay video and audio files when navigating to a file.": "Autoplay video and audio files when navigating to a file.",
"Autoplay next recommended content": "Autoplay next recommended content",
"Autoplay video and audio files as the next related item when a file finishes playing.": "Autoplay video and audio files as the next related item when a file finishes playing.",
"Clear application cache": "Clear application cache",
"Clear Cache": "Clear Cache",
"This might fix issues that you are having. Your wallet will not be affected.": "This might fix issues that you are having. Your wallet will not be affected.",
"Currency": "Currency",
"US Dollars": "US Dollars",
"There's nothing available at this location.": "There's nothing available at this location.",
@@ -209,6 +212,7 @@
"Your comment": "Your comment",
"Post --[button to submit something]--": "Post",
"Post --[noun, markdown post tab button]--": "Post",
"Livestream --[noun, livestream tab button]--": "Livestream",
"Posting...": "Posting...",
"Incompatible daemon": "Incompatible daemon",
"Incompatible daemon running": "Incompatible daemon running",
@@ -377,8 +381,6 @@
"Unfollow": "Unfollow",
"Follow @%channelName%": "Follow @%channelName%",
"Unfollow @%channelName%": "Unfollow @%channelName%",
"Item removed from %name%": "Item removed from %name%",
"Item added to %name%": "Item added to %name%",
"These LBRY Credits remain yours. It is a deposit to reserve the name and can be undone at any time.": "These LBRY Credits remain yours. It is a deposit to reserve the name and can be undone at any time.",
"Create channel": "Create channel",
"Uh oh. The flux in our Retro Encabulator must be out of whack. Try refreshing to fix it.": "Uh oh. The flux in our Retro Encabulator must be out of whack. Try refreshing to fix it.",
@@ -494,7 +496,7 @@
"Automatic dark mode": "Automatic dark mode",
"24-hour clock": "24-hour clock",
"Hide wallet balance in header": "Hide wallet balance in header",
"Max Connections": "Max Connections",
"Max connections": "Max connections",
"For users with good bandwidth, try a higher value to improve streaming and download speeds. Low bandwidth users may benefit from a lower setting. Default is 4.": "For users with good bandwidth, try a higher value to improve streaming and download speeds. Low bandwidth users may benefit from a lower setting. Default is 4.",
"Show All": "Show All",
"LBRY names cannot contain spaces or reserved symbols": "LBRY names cannot contain spaces or reserved symbols",
@@ -512,7 +514,7 @@
"Read more": "Read more",
"Multi-language support is brand new and incomplete. Switching your language may have unintended consequences, like glossolalia.": "Multi-language support is brand new and incomplete. Switching your language may have unintended consequences, like glossolalia.",
"Tailor your experience.": "Tailor your experience.",
"Save Password": "Save Password",
"Save wallet password": "Save wallet password",
"Automatically unlock your wallet on startup": "Automatically unlock your wallet on startup",
"Dark": "Dark",
"light": "light",
@@ -657,7 +659,6 @@
"Invalid claim ID %claimId%.": "Invalid claim ID %claimId%.",
"Suggested": "Suggested",
"Startup preferences": "Startup preferences",
"This will clear the application cache, and might fix issues you are having. Your wallet will not be affected. ": "This will clear the application cache, and might fix issues you are having. Your wallet will not be affected. ",
"Start minimized": "Start minimized",
"Improve view speed and help the LBRY network by allowing the app to cuddle up in your system tray.": "Improve view speed and help the LBRY network by allowing the app to cuddle up in your system tray.",
"Content Type": "Content Type",
@@ -711,7 +712,8 @@
"Failed to copy RSS URL.": "Failed to copy RSS URL.",
"Text copied": "Text copied",
"Rewards Disabled": "Rewards Disabled",
"Wallet servers are used to relay data to and from the LBRY blockchain. They also determine what content shows in trending or is blocked. %learn_more%.": "Wallet servers are used to relay data to and from the LBRY blockchain. They also determine what content shows in trending or is blocked. %learn_more%.",
"Wallet server": "Wallet server",
"Wallet servers are used to relay data to and from the LBRY blockchain. They also determine what content shows in trending or is blocked. %learn_more%": "Wallet servers are used to relay data to and from the LBRY blockchain. They also determine what content shows in trending or is blocked. %learn_more%",
"Your Tags": "Your Tags",
"All Content": "All Content",
"Accepted": "Accepted",
@@ -996,6 +998,8 @@
"Error unlocking your tip": "Error unlocking your tip",
"You deposited %lbc% as a support!": "You deposited %lbc% as a support!",
"You deposited %amount% LBRY Credits as a support!": "You deposited %amount% LBRY Credits as a support!",
"You sent $%amount% as a tip to %tipChannelName%, I'm sure they appreciate it!": "You sent $%amount% as a tip to %tipChannelName%, I'm sure they appreciate it!",
"You sent %tipAmount% LBRY Credits as a tip to %tipChannelName%, I'm sure they appreciate it!": "You sent %tipAmount% LBRY Credits as a tip to %tipChannelName%, I'm sure they appreciate it!",
"You sent %amount% LBRY Credits as a tip, Mahalo!": "You sent %amount% LBRY Credits as a tip, Mahalo!",
"You sent %amount% LBRY Credits": "You sent %amount% LBRY Credits",
"No stats found": "No stats found",
@@ -1187,6 +1191,7 @@
"Edit existing claim instead": "Edit existing claim instead",
"You already have a claim at %existing_uri%. Publishing will update (overwrite) your existing claim.": "You already have a claim at %existing_uri%. Publishing will update (overwrite) your existing claim.",
"Save": "Save",
"Saved": "Saved",
"Saving...": "Saving...",
"Downloading update": "Downloading update",
"complete": "complete",
@@ -1328,6 +1333,7 @@
"Mute": "Mute",
"Unmute": "Unmute",
"Channel muted. You will not see them again.": "Channel muted. You will not see them again.",
"Channel unmuted!": "Channel unmuted!",
"Manage notifications": "Manage notifications",
"Uploads": "Uploads",
"All uploads": "All uploads",
@@ -1419,7 +1425,9 @@
"Transcode": "Transcode",
"Estimated transaction fee:": "Estimated transaction fee:",
"Est. transaction fee:": "Est. transaction fee:",
"Publish confirmation": "Publish confirmation",
"Skip preview and confirmation": "Skip preview and confirmation",
"Show preview and confirmation dialog before publishing content.": "Show preview and confirmation dialog before publishing content.",
"Upload settings": "Upload settings",
"Currently Uploading": "Currently Uploading",
"Leave the app running until upload is complete": "Leave the app running until upload is complete",
@@ -1449,13 +1457,14 @@
"Best": "Best",
"Controversial": "Controversial",
"Show Replies": "Show Replies",
"Unable to create comment, please try again later.": "Unable to create comment, please try again later.",
"Hide replies": "Hide replies",
"Unable to comment. This channel has blocked you.": "Unable to comment. This channel has blocked you.",
"Unable to comment. Your channel has been blocked by an admin.": "Unable to comment. Your channel has been blocked by an admin.",
"Unable to comment. The content owner has disabled comments.": "Unable to comment. The content owner has disabled comments.",
"Please do not spam.": "Please do not spam.",
"Slow mode is on. Please wait up to %value% seconds before commenting again.": "Slow mode is on. Please wait up to %value% seconds before commenting again.",
"The comment contains contents that are blocked by %author%": "The comment contains contents that are blocked by %author%",
"Slow mode is on. Please wait up to %1% seconds before commenting again.": "Slow mode is on. Please wait up to %1% seconds before commenting again.",
"The comment contains contents that are blocked by %1%.": "The comment contains contents that are blocked by %1%.",
"Your user name \"%1%\" is too close to the creator's user name \"%2%\" and may cause confusion. Please use another identity.": "Your user name \"%1%\" is too close to the creator's user name \"%2%\" and may cause confusion. Please use another identity.",
"Your channel is still being setup, try again in a few moments.": "Your channel is still being setup, try again in a few moments.",
"Unable to delete this comment, please try again later.": "Unable to delete this comment, please try again later.",
"Unable to edit this comment, please try again later.": "Unable to edit this comment, please try again later.",
@@ -1609,7 +1618,7 @@
"None selected": "None selected",
"Secondary Language": "Secondary Language",
"Your other content language": "Your other content language",
"Search only in this language by default": "Search only in this language by default",
"Search only in the selected language by default": "Search only in the selected language by default",
"This link leads to an external website.": "This link leads to an external website.",
"No Content Found": "No Content Found",
"No Lists Found": "No Lists Found",
@@ -1619,7 +1628,7 @@
"No Reposts Found": "No Reposts Found",
"Publish Something": "Publish Something",
"Repost Something": "Repost Something",
"Watch on lbry.tv": "Watch on lbry.tv",
"Watch on %SITE_NAME%": "Watch on %SITE_NAME%",
"Paid content cannot be embedded.": "Paid content cannot be embedded.",
"Please wait a bit, we are still getting your account ready.": "Please wait a bit, we are still getting your account ready.",
"this channel is connected to a different account. Contact hello@lbry.com for help.": "this channel is connected to a different account. Contact hello@lbry.com for help.",
@@ -1709,6 +1718,10 @@
"Level %current_level%": "Level %current_level%",
"Creator tools": "Creator tools",
"Prevent this channel from interacting with you.": "Prevent this channel from interacting with you.",
"Choose a permanent or temporary ban.": "Choose a permanent or temporary ban.",
"Personal | Moderator | Admin": "Personal | Moderator | Admin",
"Personal | Moderator": "Personal | Moderator",
"Personal | Admin": "Personal | Admin",
"Hide this channel for you only.": "Hide this channel for you only.",
"Interacting as %channelName%": "Interacting as %channelName%",
"Page Not Found": "Page Not Found",
@@ -1727,6 +1740,7 @@
"Are you sure you want to view this content? Viewing will not unmute @%channel%": "Are you sure you want to view this content? Viewing will not unmute @%channel%",
"View Content": "View Content",
"Global": "Global",
"Global Admin": "Global Admin",
"Moderator": "Moderator",
"Global Unblock Channel": "Global Unblock Channel",
"Global Block Channel": "Global Block Channel",
@@ -1736,14 +1750,23 @@
"Moderator Block": "Moderator Block",
"Block this channel on behalf of %creator%": "Block this channel on behalf of %creator%",
"creator": "creator",
"Enter the timeout duration. Examples: %examples%": "Enter the timeout duration. Examples: %examples%",
"Wow, banned for more than 100 years?": "Wow, banned for more than 100 years?",
"Invalid duration.": "Invalid duration.",
"Permanent": "Permanent",
"Timeout --[time-based ban instead of permanent]--": "Timeout",
"(Remaining: %duration%) --[timeout ban duration]--": "(Remaining: %duration%)",
"Create a channel to change this setting.": "Create a channel to change this setting.",
"Invalid channel URL \"%url%\"": "Invalid channel URL \"%url%\"",
"Delegation": "Delegation",
"Add moderator": "Add moderator",
"Search channel": "Search channel",
"Enter a @username or URL": "Enter a @username or URL",
"examples: @channel, @channel#3, https://odysee.com/@Odysee:8, lbry://@Odysee#8": "examples: @channel, @channel#3, https://odysee.com/@Odysee:8, lbry://@Odysee#8",
"Enter a channel name or URL to add as a moderator.\nExamples:\n - @channel\n - @channel#3\n - https://odysee.com/@Odysee:8\n - lbry://@Odysee#8": "Enter a channel name or URL to add as a moderator.\nExamples:\n - @channel\n - @channel#3\n - https://odysee.com/@Odysee:8\n - lbry://@Odysee#8",
"Moderators": "Moderators",
"Moderators can block channels on your behalf. Blocked channels will appear in your \"Blocked and Muted\" list.": "Moderators can block channels on your behalf. Blocked channels will appear in your \"Blocked and Muted\" list.",
"Add as moderator": "Add as moderator",
"Assign this user to moderate %channel%": "Assign this user to moderate %channel%",
"Mute (m)": "Mute (m)",
"Playback Rate (<, >)": "Playback Rate (<, >)",
"Fullscreen (f)": "Fullscreen (f)",
@@ -1751,8 +1774,11 @@
"Play (space)": "Play (space)",
"Unmute (m)": "Unmute (m)",
"Exit Fullscreen (f)": "Exit Fullscreen (f)",
"Toggle Theater mode (t)": "Toggle Theater mode (t)",
"Theater Mode (t)": "Theater Mode (t)",
"Default Mode (t)": "Default Mode (t)",
"Quality": "Quality",
"Autoplay Next On": "Autoplay Next On",
"Autoplay Next Off": "Autoplay Next Off",
"Announcements, updates, and rewards specific to users of LBRY Android.": "Announcements, updates, and rewards specific to users of LBRY Android.",
"LBRY has special programs and opportunities for people in school.": "LBRY has special programs and opportunities for people in school.",
"Creator specific news, automated reports, and other updates.": "Creator specific news, automated reports, and other updates.",
@@ -1931,16 +1957,24 @@
"Clarification": "Clarification",
"Client name": "Client name",
"Creator settings": "Creator settings",
"Comments and livestream chat containing these words will be blocked.": "Comments and livestream chat containing these words will be blocked.",
"Muted words": "Muted words",
"Add words": "Add words",
"Suggestions": "Suggestions",
"Add words to block": "Add words to block",
"Enable comments for channel.": "Enable comments for channel.",
"Slow mode": "Slow mode",
"Minimum time gap in seconds between comments (affects livestream chat as well).": "Minimum time gap in seconds between comments (affects livestream chat as well).",
"Minimum %lbc% tip amount for comments": "Minimum %lbc% tip amount for comments",
"Enabling a minimum amount to comment will force all comments, including livestreams, to have tips associated with them. This can help prevent spam.": "Enabling a minimum amount to comment will force all comments, including livestreams, to have tips associated with them. This can help prevent spam.",
"Minimum %lbc% tip amount for hyperchats": "Minimum %lbc% tip amount for hyperchats",
"Enabling a minimum amount to hyperchat will force all TIPPED comments to have this value in order to be shown. This still allows regular comments to be posted.": "Enabling a minimum amount to hyperchat will force all TIPPED comments to have this value in order to be shown. This still allows regular comments to be posted.",
"This channel requires a minimum tip for each comment.": "This channel requires a minimum tip for each comment.",
"Comment min: %lbc%": "Comment min: %lbc%",
"This channel requires a minimum amount for HyperChats to be visible.": "This channel requires a minimum amount for HyperChats to be visible.",
"This settings is not applicable if all comments require a tip.": "This settings is not applicable if all comments require a tip.",
"HyperChat min: %lbc%": "HyperChat min: %lbc%",
"The creator just updated the minimum setting. Please revise or double-check your tip amount.": "The creator just updated the minimum setting. Please revise or double-check your tip amount.",
"Settings unavailable for this channel": "Settings unavailable for this channel",
"This channel isn't staking enough LBRY Credits to enable Creator Settings.": "This channel isn't staking enough LBRY Credits to enable Creator Settings.",
"Not a channel (prefix with \"@\", or enter the channel URL)": "Not a channel (prefix with \"@\", or enter the channel URL)",
@@ -1991,6 +2025,7 @@
"Edit List": "Edit List",
"Delete List": "Delete List",
"Private": "Private",
"Public": "Public",
"View List": "View List",
"Publish List": "Publish List",
"Info": "Info",
@@ -2021,43 +2056,107 @@
"Chat": "Chat",
"Tipped": "Tipped",
"Fromage": "Fromage",
"In Favorites": "In Favorites",
"In Favorites": "In Favorites",
"In Watch Later": "In Watch Later",
"In %lastCollectionName%": "In %lastCollectionName%",
"Remove from Watch Later": "Remove from Watch Later",
"Add to Watch Later": "Add to Watch Later",
"Added": "Added",
"Added": "Added",
"Item removed from %name%": "Item removed from %name%",
"Item added to %name%": "Item added to %name%",
"Item added to Watch Later": "Item added to Watch Later",
"Item removed from Watch Later": "Item removed from Watch Later",
"Item added to %lastCollectionName%": "Item added to %lastCollectionName%",
"Item removed from %lastCollectionName%": "Item removed from %lastCollectionName%",
"Item removed from Watch Later": "Item removed from Watch Later",
"Item added to Favorites": "Item added to Favorites",
"Item removed from Favorites": "Item removed from Favorites",
"Your publish is being confirmed and will be live soon": "Your publish is being confirmed and will be live soon",
"Clear Edits": "Clear Edits",
"Something not quite right..": "Something not quite right..",
"Comments server": "Comments server",
"Default comments server (%name%)": "Default comments server (%name%)",
"Custom comments server": "Custom comments server",
"Failed to fetch comments.": "Failed to fetch comments.",
"Failed to fetch comments. Verify custom server settings.": "Failed to fetch comments. Verify custom server settings.",
"Commenting server is not set.": "Commenting server is not set.",
"Comments are not currently enabled.": "Comments are not currently enabled.",
"See All": "See All",
"System": "System",
"Supporting content requires %lbc%": "Supporting content requires %lbc%",
"With %lbc%, you can send tips to your favorite creators, or help boost their content for more people to see.": "With %lbc%, you can send tips to your favorite creators, or help boost their content for more people to see.",
"Show this channel your appreciation by sending a donation in USD.": "Show this channel your appreciation by sending a donation in USD.",
"This refundable boost will improve the discoverability of this %claimTypeText% while active.": "This refundable boost will improve the discoverability of this %claimTypeText% while active.",
"Show this channel your appreciation by sending a donation of Credits.": "Show this channel your appreciation by sending a donation of Credits.",
"Add card to tip creators in USD": "Add card to tip creators in USD",
"Add a credit card to tip creators in their local currency.": "Add a credit card to tip creators in their local currency.",
"Add Card": "Add Card",
"Tip History": "Tip History",
"Connect a bank account": "Connect a bank account",
"Connect your card with Odysee": "Connect your card with Odysee",
"Getting your card connection status...": "Getting your card connection status...",
"Getting your bank account connection status...": "Getting your bank account connection status...",
"Connect your bank account to Odysee to receive donations directly from users": "Connect your bank account to Odysee to receive donations directly from users",
"Connect your bank account": "Connect your bank account",
"Manage Card": "Manage Card",
"Card Details": "Card Details",
"Remove Card": "Remove Card",
"Congratulations! Your account has been connected with Odysee.": "Congratulations! Your account has been connected with Odysee.",
"Your account balance is %balance% USD. Functionality to view your transactions and withdraw your balance will be landing shortly.": "Your account balance is %balance% USD. Functionality to view your transactions and withdraw your balance will be landing shortly.",
"Your account balance is $0 USD. When you receive a tip you will see it here.": "Your account balance is $0 USD. When you receive a tip you will see it here.",
"Congratulations, you have already begun receiving tips on Odysee!": "Congratulations, you have already begun receiving tips on Odysee!",
"Your pending account balance is %balance% USD. Functionality to view and receive your transactions will land soon.": "Your pending account balance is %balance% USD. Functionality to view and receive your transactions will land soon.",
"Connect your bank account to be able to cash your pending balance out to your account.": "Connect your bank account to be able to cash your pending balance out to your account.",
"You sent $%amount% as a tip to %tipChannelName%, I'm sure they appreciate it!": "You sent $%amount% as a tip to %tipChannelName%, I'm sure they appreciate it!",
"Tip Creators": "Tip Creators",
"Only select creators can receive tips at this time": "Only select creators can receive tips at this time",
"The payment will be made from your saved card": "The payment will be made from your saved card",
"When you begin to receive tips your balance will be updated here.": "When you begin to receive tips your balance will be updated here.",
"This is your pending balance that will be automatically sent to your bank account.": "This is your pending balance that will be automatically sent to your bank account.",
"Commenting...": "Commenting...",
"Show %count% replies": "Show %count% replies",
"Show reply": "Show reply",
"added to": "added to",
"removed from": "removed from",
"Skip Navigation": "Skip Navigation",
"Reset": "Reset",
"Reset to original (previous) publish date": "Reset to original (previous) publish date",
"Search for something...": "Search for something...",
"Confirm Comment Deletion": "Confirm Comment Deletion",
"Remove Comment": "Remove Comment",
"Are you sure you want to remove this comment?": "Are you sure you want to remove this comment?",
"This comment has a tip associated with it which cannot be reverted.": "This comment has a tip associated with it which cannot be reverted.",
"Dismiss pinned comment": "Dismiss pinned comment",
"Recent Comments": "Recent Comments",
"%title% by %channelTitle%": "%title% by %channelTitle%",
"%title% by %channelTitle% %ariaDate%": "%title% by %channelTitle% %ariaDate%",
"%title% by %channelTitle% %ariaDate%, %mediaDuration%": "%title% by %channelTitle% %ariaDate%, %mediaDuration%",
"Collapse Thread": "Collapse Thread",
"Collapse": "Collapse",
"Expand Comments": "Expand Comments",
"Expand": "Expand",
"Load More": "Load More",
"%formattedSubCount% Followers": "%formattedSubCount% Followers",
"1 Follower": "1 Follower",
"Collection": "Collection",
"%channelName% isn't live right now, but the chat is! Check back later to watch the stream.": "%channelName% isn't live right now, but the chat is! Check back later to watch the stream.",
"Review": "Review",
"Account History": "Account History",
"Payment History": "Payment History",
"There was an error from the server, please try again later": "There was an error from the server, please try again later",
"There was an error getting your card setup, please try again later": "There was an error getting your card setup, please try again later",
"View Transactions": "View Transactions",
"Bank Accounts": "Bank Accounts",
"Connect a bank account to receive tips and compensation in your local currency.": "Connect a bank account to receive tips and compensation in your local currency.",
"Payment Methods": "Payment Methods",
"Incoming": "Incoming",
"Outgoing": "Outgoing",
"Credits --[transactions tab]--": "Credits",
"USD --[transactions tab]--": "USD",
"Receiving Channel Name": "Receiving Channel Name",
"Tip Location": "Tip Location",
"Amount (USD)": "Amount (USD)",
"Processing Fee": "Processing Fee",
"Odysee Fee": "Odysee Fee",
"Received Amount": "Received Amount",
"Channel Page": "Channel Page",
"Content Page": "Content Page",
"Card Last 4": "Card Last 4",
"--end--": "--end--"
}
+179 -37
View File
@@ -9,14 +9,17 @@ import Native from 'native';
import ElectronCookies from '@exponent/electron-cookies';
import { generateInitialUrl } from 'util/url';
// @endif
import { MATOMO_ID, MATOMO_URL, LBRY_WEB_BUFFER_API } from 'config';
import { MATOMO_ID, MATOMO_URL } from 'config';
const isProduction = process.env.NODE_ENV === 'production';
const devInternalApis = process.env.LBRY_API_URL;
const devInternalApis = process.env.LBRY_API_URL && process.env.LBRY_API_URL.includes('dev');
export const SHARE_INTERNAL = 'shareInternal';
const SHARE_THIRD_PARTY = 'shareThirdParty';
const WATCHMAN_BACKEND_ENDPOINT = 'https://watchman.na-backend.odysee.com/reports/playback';
const SEND_DATA_TO_WATCHMAN_INTERVAL = 10; // in seconds
// @if TARGET='app'
if (isProduction) {
ElectronCookies.enable({
@@ -37,7 +40,8 @@ type Analytics = {
tagFollowEvent: (string, boolean, ?string) => void,
playerLoadedEvent: (?boolean) => void,
playerStartedEvent: (?boolean) => void,
videoStartEvent: (string, number) => void,
videoStartEvent: (string, number, string, number, string, any) => void,
videoIsPlaying: (boolean, any) => void,
videoBufferEvent: (
StreamClaim,
{
@@ -49,7 +53,7 @@ type Analytics = {
playerPoweredBy: string,
readyState: number,
}
) => void,
) => Promise<any>,
adsFetchedEvent: () => void,
adsReceivedEvent: (any) => void,
adsErrorEvent: (any) => void,
@@ -76,7 +80,178 @@ if (window.localStorage.getItem(SHARE_INTERNAL) === 'true') internalAnalyticsEna
// if (window.localStorage.getItem(SHARE_THIRD_PARTY) === 'true') thirdPartyAnalyticsEnabled = true;
// @endif
/**
* Determine the mobile device type viewing the data
* This function returns one of 'and' (Android), 'ios', or 'web'.
*
* @returns {String}
*/
function getDeviceType() {
// We may not care what the device is if it's in a web browser. Commenting out for now.
// if (!IS_WEB) {
// return 'elt';
// }
// const userAgent = navigator.userAgent || navigator.vendor || window.opera;
//
// if (/android/i.test(userAgent)) {
// return 'adr';
// }
//
// // iOS detection from: http://stackoverflow.com/a/9039885/177710
// if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
// return 'ios';
// }
// default as web, this can be optimized
if (!IS_WEB) {
return 'dsk';
}
return 'web';
}
// variables initialized for watchman
let amountOfBufferEvents = 0;
let amountOfBufferTimeInMS = 0;
let videoType, userId, claimUrl, playerPoweredBy, videoPlayer;
let lastSentTime;
// calculate data for backend, send them, and reset buffer data for next interval
async function sendAndResetWatchmanData() {
if (!userId) {
return 'Can only be used with a user id';
}
if (!videoPlayer) {
return 'Video player not initialized';
}
let timeSinceLastIntervalSend = new Date() - lastSentTime;
lastSentTime = new Date();
let protocol;
if (videoType === 'application/x-mpegURL') {
protocol = 'hls';
} else {
protocol = 'stb';
}
// current position in video in MS
const positionInVideo = Math.round(videoPlayer.currentTime()) * 1000;
// get the duration marking the time in the video for relative position calculation
const totalDurationInSeconds = Math.round(videoPlayer.duration());
// build object for watchman backend
const objectToSend = {
rebuf_count: amountOfBufferEvents,
rebuf_duration: amountOfBufferTimeInMS,
url: claimUrl.replace('lbry://', ''),
device: getDeviceType(),
duration: timeSinceLastIntervalSend,
protocol,
player: playerPoweredBy,
user_id: userId.toString(),
position: Math.round(positionInVideo),
rel_position: Math.round((positionInVideo / (totalDurationInSeconds * 1000)) * 100),
};
// post to watchman
await sendWatchmanData(objectToSend);
// reset buffer data
amountOfBufferEvents = 0;
amountOfBufferTimeInMS = 0;
}
let watchmanInterval;
// clear watchman interval and mark it as null (when video paused)
function stopWatchmanInterval() {
clearInterval(watchmanInterval);
watchmanInterval = null;
}
// creates the setInterval that will run send to watchman on recurring basis
function startWatchmanIntervalIfNotRunning() {
if (!watchmanInterval) {
// instantiate the first time to calculate duration from
lastSentTime = new Date();
// only set an interval if analytics are enabled and is prod
if (isProduction && IS_WEB) {
watchmanInterval = setInterval(sendAndResetWatchmanData, 1000 * SEND_DATA_TO_WATCHMAN_INTERVAL);
}
}
}
// post data to the backend
async function sendWatchmanData(body) {
try {
const response = await fetch(WATCHMAN_BACKEND_ENDPOINT, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return response;
} catch (err) {
console.log('ERROR FROM WATCHMAN BACKEND');
console.log(err);
}
}
const analytics: Analytics = {
// receive buffer events from tracking plugin and jklj
videoBufferEvent: async (claim, data) => {
amountOfBufferEvents = amountOfBufferEvents + 1;
amountOfBufferTimeInMS = amountOfBufferTimeInMS + data.bufferDuration;
},
onDispose: () => {
stopWatchmanInterval();
},
/**
* Is told whether video is being started or paused, and adjusts interval accordingly
* @param {boolean} isPlaying - Whether video was started or paused
* @param {object} passedPlayer - VideoJS Player object
*/
videoIsPlaying: (isPlaying, passedPlayer) => {
let playerIsSeeking = false;
// have to use this because videojs pauses/unpauses during seek
// sometimes the seeking function isn't populated yet so check for it as well
if (passedPlayer && passedPlayer.seeking) {
playerIsSeeking = passedPlayer.seeking();
}
// if being paused, and not seeking, send existing data and stop interval
if (!isPlaying && !playerIsSeeking) {
sendAndResetWatchmanData();
stopWatchmanInterval();
// if being told to pause, and seeking, send and restart interval
} else if (!isPlaying && playerIsSeeking) {
sendAndResetWatchmanData();
stopWatchmanInterval();
startWatchmanIntervalIfNotRunning();
// is being told to play, and seeking, don't do anything,
// assume it's been started already from pause
} else if (isPlaying && playerIsSeeking) {
// start but not a seek, assuming a start from paused content
} else if (isPlaying && !playerIsSeeking) {
startWatchmanIntervalIfNotRunning();
}
},
videoStartEvent: (claimId, duration, poweredBy, passedUserId, canonicalUrl, passedPlayer) => {
// populate values for watchman when video starts
userId = passedUserId;
claimUrl = canonicalUrl;
playerPoweredBy = poweredBy;
videoType = passedPlayer.currentSource().type;
videoPlayer = passedPlayer;
sendPromMetric('time_to_start', duration);
sendMatomoEvent('Media', 'TimeToStart', claimId, duration);
},
error: (message) => {
return new Promise((resolve) => {
if (internalAnalyticsEnabled && isProduction) {
@@ -195,39 +370,6 @@ const analytics: Analytics = {
Lbryio.call('content_tags', 'sync', params);
}
},
videoStartEvent: (claimId, duration) => {
sendPromMetric('time_to_start', duration);
sendMatomoEvent('Media', 'TimeToStart', claimId, duration);
},
videoBufferEvent: (claim, data) => {
sendMatomoEvent('Media', 'BufferTimestamp', claim.claim_id, data.timeAtBuffer);
if (LBRY_WEB_BUFFER_API) {
fetch(LBRY_WEB_BUFFER_API, {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
device: 'web',
type: 'buffering',
client: data.userId,
data: {
url: claim.canonical_url,
position: data.timeAtBuffer,
duration: data.bufferDuration,
player: data.playerPoweredBy,
readyState: data.readyState,
stream_duration: data.duration,
stream_bitrate: data.bitRate,
},
}),
});
}
},
adsFetchedEvent: () => {
sendMatomoEvent('Media', 'AdsFetched');
},
+13 -3
View File
@@ -4,10 +4,17 @@ import { COMMENT_SERVER_API } from 'config';
const Comments = {
url: COMMENT_SERVER_API,
enabled: Boolean(COMMENT_SERVER_API),
isCustomServer: false,
setServerUrl: (customUrl: ?string) => {
Comments.url = customUrl === undefined ? COMMENT_SERVER_API : customUrl;
Comments.enabled = Boolean(Comments.url);
Comments.isCustomServer = Comments.url !== COMMENT_SERVER_API;
},
moderation_block: (params: ModerationBlockParams) => fetchCommentsApi('moderation.Block', params),
moderation_unblock: (params: ModerationBlockParams) => fetchCommentsApi('moderation.UnBlock', params),
moderation_block_list: (params: ModerationBlockParams) => fetchCommentsApi('moderation.BlockedList', params),
moderation_block_list: (params: BlockedListArgs) => fetchCommentsApi('moderation.BlockedList', params),
moderation_add_delegate: (params: ModerationAddDelegateParams) => fetchCommentsApi('moderation.AddDelegate', params),
moderation_remove_delegate: (params: ModerationRemoveDelegateParams) =>
fetchCommentsApi('moderation.RemoveDelegate', params),
@@ -27,12 +34,15 @@ const Comments = {
setting_unblock_word: (params: BlockWordParams) => fetchCommentsApi('setting.UnBlockWord', params),
setting_list_blocked_words: (params: SettingsParams) => fetchCommentsApi('setting.ListBlockedWords', params),
setting_update: (params: UpdateSettingsParams) => fetchCommentsApi('setting.Update', params),
setting_get: (params: SettingsParams) => fetchCommentsApi('setting.Get', params),
super_list: (params: SuperListParams) => fetchCommentsApi('comment.SuperChatList', params),
};
function fetchCommentsApi(method: string, params: {}) {
if (!Comments.enabled) {
return Promise.reject('Comments are not currently enabled'); // eslint-disable-line
if (!Comments.url) {
return Promise.reject(new Error('Commenting server is not set.'));
} else if (!Comments.enabled) {
return Promise.reject('Comments are not currently enabled.'); // eslint-disable-line
}
const url = `${Comments.url}?m=${method}`;
+29
View File
@@ -48,9 +48,11 @@ const NagDegradedPerformance = lazyImport(() =>
import('web/component/nag-degraded-performance' /* webpackChunkName: "secondary" */)
);
const NagNoUser = lazyImport(() => import('web/component/nag-no-user' /* webpackChunkName: "nag-no-user" */));
const NagSunset = lazyImport(() => import('web/component/nag-sunset' /* webpackChunkName: "nag-no-user" */));
const YoutubeWelcome = lazyImport(() =>
import('web/component/youtubeReferralWelcome' /* webpackChunkName: "secondary" */)
);
// @endif
const SyncFatalError = lazyImport(() => import('component/syncFatalError' /* webpackChunkName: "syncFatalError" */));
@@ -162,12 +164,14 @@ function App(props: Props) {
const [upgradeNagClosed, setUpgradeNagClosed] = useState(false);
const [resolvedSubscriptions, setResolvedSubscriptions] = useState(false);
const [sidebarOpen] = usePersistedState('sidebar', true);
const [seenSunsestMessage, setSeenSunsetMessage] = usePersistedState('lbrytv-sunset', false);
const showUpgradeButton =
(autoUpdateDownloaded || (process.platform === 'linux' && isUpgradeAvailable)) && !upgradeNagClosed;
// referral claiming
const referredRewardAvailable = rewards && rewards.some((reward) => reward.reward_type === REWARDS.TYPE_REFEREE);
const urlParams = new URLSearchParams(search);
const rawReferrerParam = urlParams.get('r');
const fromLbrytvParam = urlParams.get('sunset');
const sanitizedReferrerParam = rawReferrerParam && rawReferrerParam.replace(':', '#');
const shouldHideNag = pathname.startsWith(`/$/${PAGES.EMBED}`) || pathname.startsWith(`/$/${PAGES.AUTH_VERIFY}`);
const userId = user && user.id;
@@ -285,6 +289,11 @@ function App(props: Props) {
}
}, [hasMyChannels, hasNoChannels, hasActiveChannelClaim, setActiveChannelIfNotSet, setIncognito]);
useEffect(() => {
// $FlowFixMe
document.documentElement.setAttribute('lang', language);
}, [language]);
useEffect(() => {
if (!languages.includes(language)) {
setLanguage(language);
@@ -316,6 +325,23 @@ function App(props: Props) {
}
}, [previousRewardApproved, isRewardApproved]);
// Load IMA3 SDK for aniview: DISABLED FOR NOW
// @if TARGET='web'
// useEffect(() => {
// if (ENABLE_PREROLL_ADS) {
// const script = document.createElement('script');
// script.src = `https://imasdk.googleapis.com/js/sdkloader/ima3.js`;
// script.async = true;
// // $FlowFixMe
// document.body.appendChild(script);
// return () => {
// // $FlowFixMe
// document.body.removeChild(script);
// };
// }
// });
// @endif
// @if TARGET='app'
useEffect(() => {
if (updatePreferences && getWalletSyncPref && readyForPrefs) {
@@ -455,6 +481,9 @@ function App(props: Props) {
<YoutubeWelcome />
{!SIMPLE_SITE && !shouldHideNag && <OpenInAppLink uri={uri} />}
{!shouldHideNag && <NagContinueFirstRun />}
{fromLbrytvParam && !seenSunsestMessage && !shouldHideNag && (
<NagSunset email={hasVerifiedEmail} onClose={() => setSeenSunsetMessage(true)} />
)}
{(lbryTvApiStatus === STATUS_DEGRADED || lbryTvApiStatus === STATUS_FAILING) && !shouldHideNag && (
<NagDegradedPerformance onClose={() => setLbryTvApiStatus(STATUS_OK)} />
)}
+6 -32
View File
@@ -1,9 +1,6 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, SETTINGS, COLLECTIONS_CONSTS, makeSelectNextUrlForCollectionAndUrl } from 'lbry-redux';
import { makeSelectClaimForUri } from 'lbry-redux';
import { withRouter } from 'react-router';
import { makeSelectIsPlayerFloating, makeSelectNextUnplayedRecommended } from 'redux/selectors/content';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { doSetPlayingUri, doPlayUri } from 'redux/actions/content';
import AutoplayCountdown from './view';
import { selectModal } from 'redux/selectors/app';
@@ -11,32 +8,9 @@ import { selectModal } from 'redux/selectors/app';
AutoplayCountdown does not fetch it's own next content to play, it relies on <RecommendedContent> being rendered.
This is dumb but I'm just the guy who noticed -kj
*/
const select = (state, props) => {
const { location } = props;
const { search } = location;
const urlParams = new URLSearchParams(search);
const collectionId = urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID);
const select = (state, props) => ({
nextRecommendedClaim: makeSelectClaimForUri(props.nextRecommendedUri)(state),
modal: selectModal(state),
});
let nextRecommendedUri;
if (collectionId) {
nextRecommendedUri = makeSelectNextUrlForCollectionAndUrl(collectionId, props.uri)(state);
} else {
nextRecommendedUri = makeSelectNextUnplayedRecommended(props.uri)(state);
}
return {
collectionId,
nextRecommendedUri,
nextRecommendedClaim: makeSelectClaimForUri(nextRecommendedUri)(state),
isFloating: makeSelectIsPlayerFloating(props.location)(state),
autoplay: makeSelectClientSetting(SETTINGS.AUTOPLAY)(state),
modal: selectModal(state),
};
};
export default withRouter(
connect(select, {
doSetPlayingUri,
doPlayUri,
})(AutoplayCountdown)
);
export default withRouter(connect(select, null)(AutoplayCountdown));
+17 -37
View File
@@ -1,12 +1,12 @@
// @flow
import React, { useCallback } from 'react';
import React from 'react';
import Button from 'component/button';
import UriIndicator from 'component/uriIndicator';
import I18nMessage from 'component/i18nMessage';
import { formatLbryUrlForWeb } from 'util/url';
import { withRouter } from 'react-router';
import debounce from 'util/debounce';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
import * as ICONS from 'constants/icons';
const DEBOUNCE_SCROLL_HANDLER_MS = 150;
const CLASSNAME_AUTOPLAY_COUNTDOWN = 'autoplay-countdown';
@@ -14,23 +14,19 @@ type Props = {
history: { push: (string) => void },
nextRecommendedClaim: ?StreamClaim,
nextRecommendedUri: string,
isFloating: boolean,
doSetPlayingUri: ({ uri: ?string }) => void,
doPlayUri: (string) => void,
modal: { id: string, modalProps: {} },
collectionId?: string,
doNavigate: () => void,
doReplay: () => void,
};
function AutoplayCountdown(props: Props) {
const {
nextRecommendedUri,
nextRecommendedClaim,
doSetPlayingUri,
doPlayUri,
isFloating,
history: { push },
modal,
collectionId,
doNavigate,
doReplay,
} = props;
const nextTitle = nextRecommendedClaim && nextRecommendedClaim.value && nextRecommendedClaim.value.title;
@@ -43,31 +39,6 @@ function AutoplayCountdown(props: Props) {
const anyModalPresent = modal !== undefined && modal !== null;
const isTimerPaused = timerPaused || anyModalPresent;
let navigateUrl;
if (nextTitle) {
navigateUrl = formatLbryUrlForWeb(nextRecommendedUri);
if (collectionId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
}
}
const doNavigate = useCallback(() => {
if (!isFloating) {
if (navigateUrl) {
push(navigateUrl);
doSetPlayingUri({ uri: nextRecommendedUri });
doPlayUri(nextRecommendedUri);
}
} else {
if (nextRecommendedUri) {
doSetPlayingUri({ uri: nextRecommendedUri });
doPlayUri(nextRecommendedUri);
}
}
}, [navigateUrl, nextRecommendedUri, isFloating, doSetPlayingUri, doPlayUri, push]);
function shouldPauseAutoplay() {
const elm = document.querySelector(`.${CLASSNAME_AUTOPLAY_COUNTDOWN}`);
return elm && elm.getBoundingClientRect().top < 0;
@@ -107,7 +78,7 @@ function AutoplayCountdown(props: Props) {
return () => {
clearInterval(interval);
};
}, [timer, doNavigate, navigateUrl, push, timerCanceled, isTimerPaused, nextRecommendedUri]);
}, [timer, doNavigate, push, timerCanceled, isTimerPaused, nextRecommendedUri]);
if (timerCanceled || !nextRecommendedUri) {
return null;
@@ -138,6 +109,15 @@ function AutoplayCountdown(props: Props) {
<Button label={__('Cancel')} button="link" onClick={() => setTimerCanceled(true)} />
</div>
)}
<Button
label={__('Replay?')}
button="link"
iconRight={ICONS.REPLAY}
onClick={() => {
setTimerCanceled(true);
doReplay();
}}
/>
</div>
</div>
</div>
+7 -1
View File
@@ -97,6 +97,9 @@ const Button = forwardRef<any, {}>((props: Props, ref: any) => {
const combinedRef = useCombinedRefs(ref, innerRef, myref);
const size = iconSize || (!label && !children) ? 18 : undefined; // Fall back to default
// Label can be a string or object ( use title instead )
const ariaLabel = description || (typeof label === 'string' ? label : title);
const content = (
<span className="button__content">
{icon && <Icon icon={icon} iconColor={iconColor} size={iconSize} />}
@@ -150,6 +153,7 @@ const Button = forwardRef<any, {}>((props: Props, ref: any) => {
className={combinedClassName}
title={title}
onClick={onClick}
aria-label={ariaLabel}
>
{content}
</a>
@@ -196,6 +200,7 @@ const Button = forwardRef<any, {}>((props: Props, ref: any) => {
disabled={disable}
className={combinedClassName}
activeClassName={activeClass}
aria-label={ariaLabel}
>
{content}
</NavLink>
@@ -216,6 +221,7 @@ const Button = forwardRef<any, {}>((props: Props, ref: any) => {
}}
className={combinedClassName}
activeClassName={activeClass}
aria-label={ariaLabel}
{...otherProps}
>
{content}
@@ -224,7 +230,7 @@ const Button = forwardRef<any, {}>((props: Props, ref: any) => {
<button
ref={combinedRef}
title={title || defaultTooltip}
aria-label={description || label || title}
aria-label={ariaLabel}
className={combinedClassName}
onClick={(e) => {
if (onClick) {
+2 -2
View File
@@ -12,7 +12,7 @@ type Props = {
isBlockingOrUnBlocking: boolean,
isToggling: boolean,
doCommentModUnBlock: (string, boolean) => void,
doCommentModBlock: (string, boolean) => void,
doCommentModBlock: (string, ?Number, boolean) => void,
doCommentModUnBlockAsAdmin: (string, string) => void,
doCommentModBlockAsAdmin: (string, string) => void,
doCommentModUnBlockAsModerator: (string, string, string) => void,
@@ -42,7 +42,7 @@ function ChannelBlockButton(props: Props) {
if (isBlocked) {
doCommentModUnBlock(uri, false);
} else {
doCommentModBlock(uri, false);
doCommentModBlock(uri, undefined, false);
}
break;
+9 -2
View File
@@ -14,6 +14,8 @@ import { Form, FormField } from 'component/common/form';
import { DEBOUNCE_WAIT_DURATION_MS } from 'constants/search';
import { lighthouse } from 'redux/actions/search';
const TYPES_TO_ALLOW_FILTER = ['stream', 'repost'];
type Props = {
uri: string,
totalPages: number,
@@ -62,7 +64,11 @@ function ChannelContent(props: Props) {
} = useHistory();
const url = `${pathname}${search}`;
const claimId = claim && claim.claim_id;
const showFilters = !claimType || claimType === 'stream';
const showFilters =
!claimType ||
(Array.isArray(claimType)
? claimType.every((ct) => TYPES_TO_ALLOW_FILTER.includes(ct))
: TYPES_TO_ALLOW_FILTER.includes(claimType));
function handleInputChange(e) {
const { value } = e.target;
@@ -81,7 +87,7 @@ function ChannelContent(props: Props) {
!showMature ? '&nsfw=false&size=50&from=0' : ''
}`
)
.then((results) => {
.then(({ body: results }) => {
const urls = results.map(({ name, claimId }) => {
return `lbry://${name}#${claimId}`;
});
@@ -140,6 +146,7 @@ function ChannelContent(props: Props) {
defaultFreshness={CS.FRESH_ALL}
showHiddenByUser={viewHiddenChannels}
forceShowReposts
// fetchViewCount
hideFilters={!showFilters}
hideAdvancedFilter={!showFilters}
tileLayout={tileLayout}
+5
View File
@@ -17,6 +17,8 @@ import {
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { doUpdateBlockListForPublishedChannel } from 'redux/actions/comments';
import { doClaimInitialRewards } from 'redux/actions/rewards';
import { selectIsClaimingInitialRewards, selectHasClaimedInitialRewards } from 'redux/selectors/rewards';
import ChannelForm from './view';
const select = (state, props) => ({
@@ -36,6 +38,8 @@ const select = (state, props) => ({
createError: selectCreateChannelError(state),
creatingChannel: selectCreatingChannel(state),
balance: selectBalance(state),
isClaimingInitialRewards: selectIsClaimingInitialRewards(state),
hasClaimedInitialRewards: selectHasClaimedInitialRewards(state),
});
const perform = (dispatch) => ({
@@ -50,6 +54,7 @@ const perform = (dispatch) => ({
);
},
clearChannelErrors: () => dispatch(doClearChannelErrors()),
claimInitialRewards: () => dispatch(doClaimInitialRewards()),
});
export default connect(select, perform)(ChannelForm);
+74 -17
View File
@@ -22,6 +22,8 @@ import SUPPORTED_LANGUAGES from 'constants/supported_languages';
import WalletSpendableBalanceHelp from 'component/walletSpendableBalanceHelp';
import { SIMPLE_SITE } from 'config';
import { sortLanguageMap } from 'util/default-languages';
import ThumbnailBrokenImage from 'component/selectThumbnail/thumbnail-broken.png';
import Gerbil from 'component/channelThumbnail/gerbil.png';
const LANG_NONE = 'none';
@@ -48,13 +50,16 @@ type Props = {
createError: string,
creatingChannel: boolean,
clearChannelErrors: () => void,
claimInitialRewards: () => void,
onDone: () => void,
openModal: (
id: string,
{ onUpdate: (string) => void, assetName: string, helpText: string, currentValue: string, title: string }
{ onUpdate: (string, boolean) => void, assetName: string, helpText: string, currentValue: string, title: string }
) => void,
uri: string,
disabled: boolean,
isClaimingInitialRewards: boolean,
hasClaimedInitialRewards: boolean,
};
function ChannelForm(props: Props) {
@@ -79,12 +84,17 @@ function ChannelForm(props: Props) {
creatingChannel,
createError,
clearChannelErrors,
claimInitialRewards,
openModal,
disabled,
isClaimingInitialRewards,
hasClaimedInitialRewards,
} = props;
const [nameError, setNameError] = React.useState(undefined);
const [bidError, setBidError] = React.useState('');
const [isUpload, setIsUpload] = React.useState({ cover: false, thumbnail: false });
const [coverError, setCoverError] = React.useState(false);
const [thumbError, setThumbError] = React.useState(false);
const { claim_id: claimId } = claim || {};
const [params, setParams]: [any, (any) => void] = React.useState(getChannelParams());
const { channelName } = parseURI(uri);
@@ -94,6 +104,34 @@ function ChannelForm(props: Props) {
const languageParam = params.languages;
const primaryLanguage = Array.isArray(languageParam) && languageParam.length && languageParam[0];
const secondaryLanguage = Array.isArray(languageParam) && languageParam.length >= 2 && languageParam[1];
const submitLabel = React.useMemo(() => {
if (isClaimingInitialRewards) {
return __('Claiming credits...');
}
return creatingChannel || updatingChannel ? __('Submitting...') : __('Submit');
}, [isClaimingInitialRewards, creatingChannel, updatingChannel]);
const submitDisabled = React.useMemo(() => {
return (
isClaimingInitialRewards ||
creatingChannel ||
updatingChannel ||
nameError ||
thumbError ||
coverError ||
bidError ||
(isNewChannel && !params.name)
);
}, [
isClaimingInitialRewards,
creatingChannel,
updatingChannel,
nameError,
thumbError,
coverError,
bidError,
isNewChannel,
params.name,
]);
function getChannelParams() {
// fill this in with sdk data
@@ -173,12 +211,16 @@ function ChannelForm(props: Props) {
setParams({ ...params, languages: langs });
}
function handleThumbnailChange(thumbnailUrl: string) {
function handleThumbnailChange(thumbnailUrl: string, uploadSelected: boolean) {
setParams({ ...params, thumbnailUrl });
setIsUpload({ ...isUpload, thumbnail: uploadSelected });
setThumbError(false);
}
function handleCoverChange(coverUrl: string) {
function handleCoverChange(coverUrl: string, uploadSelected: boolean) {
setParams({ ...params, coverUrl });
setIsUpload({ ...isUpload, cover: uploadSelected });
setCoverError(false);
}
function handleSubmit() {
@@ -203,6 +245,9 @@ function ChannelForm(props: Props) {
if (errorMsg && errorMsg.includes(LIMIT_ERR_PARTIAL_MSG)) {
errorMsg = __('Transaction limit reached. Try reducing the Description length.');
}
if ((!isUpload.thumbnail && thumbError) || (!isUpload.cover && coverError)) {
errorMsg = __('Invalid %error_type%', { error_type: (thumbError && 'thumbnail') || (coverError && 'cover image') });
}
React.useEffect(() => {
let nameError;
@@ -219,6 +264,23 @@ function ChannelForm(props: Props) {
clearChannelErrors();
}, [clearChannelErrors]);
React.useEffect(() => {
if (!hasClaimedInitialRewards) {
claimInitialRewards();
}
}, [hasClaimedInitialRewards, claimInitialRewards]);
const coverSrc = coverError ? ThumbnailBrokenImage : params.coverUrl;
let thumbnailPreview;
if (!params.thumbnailUrl) {
thumbnailPreview = Gerbil;
} else if (thumbError) {
thumbnailPreview = ThumbnailBrokenImage;
} else {
thumbnailPreview = params.thumbnailUrl;
}
// TODO clear and bail after submit
return (
<>
@@ -230,7 +292,7 @@ function ChannelForm(props: Props) {
title={__('Cover')}
onClick={() =>
openModal(MODALS.IMAGE_UPLOAD, {
onUpdate: (coverUrl) => handleCoverChange(coverUrl),
onUpdate: (coverUrl, isUpload) => handleCoverChange(coverUrl, isUpload),
title: __('Edit Cover Image'),
helpText: __('(6.25:1)'),
assetName: __('Cover Image'),
@@ -242,10 +304,10 @@ function ChannelForm(props: Props) {
/>
</div>
{params.coverUrl &&
(coverError ? (
(coverError && isUpload.cover ? (
<div className="channel-cover__custom--waiting">{__('This will be visible in a few minutes.')}</div>
) : (
<img className="channel-cover__custom" src={params.coverUrl} onError={() => setCoverError(true)} />
<img className="channel-cover__custom" src={coverSrc} onError={() => setCoverError(true)} />
))}
<div className="channel__primary-info">
<div className="channel__edit-thumb">
@@ -254,7 +316,7 @@ function ChannelForm(props: Props) {
title={__('Edit')}
onClick={() =>
openModal(MODALS.IMAGE_UPLOAD, {
onUpdate: (v) => handleThumbnailChange(v),
onUpdate: (thumbnailUrl, isUpload) => handleThumbnailChange(thumbnailUrl, isUpload),
title: __('Edit Thumbnail Image'),
helpText: __('(1:1)'),
assetName: __('Thumbnail'),
@@ -268,9 +330,11 @@ function ChannelForm(props: Props) {
<ChannelThumbnail
className="channel__thumbnail--channel-page"
uri={uri}
thumbnailPreview={params.thumbnailUrl}
thumbnailPreview={thumbnailPreview}
allowGifs
showDelayedMessage
showDelayedMessage={isUpload.thumbnail}
setThumbUploadError={setThumbError}
thumbUploadError={thumbError}
/>
<h1 className="channel__title">
{params.title || (channelName && '@' + channelName) || (params.name && '@' + params.name)}
@@ -453,14 +517,7 @@ function ChannelForm(props: Props) {
actions={
<>
<div className="section__actions">
<Button
button="primary"
disabled={
creatingChannel || updatingChannel || nameError || bidError || (isNewChannel && !params.name)
}
label={creatingChannel || updatingChannel ? __('Submitting') : __('Submit')}
onClick={handleSubmit}
/>
<Button button="primary" disabled={submitDisabled} label={submitLabel} onClick={handleSubmit} />
<Button button="link" label={__('Cancel')} onClick={onDone} />
</div>
{errorMsg ? (
+22 -22
View File
@@ -23,6 +23,10 @@ type Props = {
showDelayedMessage?: boolean,
noLazyLoad?: boolean,
hideStakedIndicator?: boolean,
xsmall?: boolean,
noOptimization?: boolean,
setThumbUploadError: (boolean) => void,
ThumbUploadError: boolean,
};
function ChannelThumbnail(props: Props) {
@@ -41,15 +45,17 @@ function ChannelThumbnail(props: Props) {
showDelayedMessage = false,
noLazyLoad,
hideStakedIndicator = false,
setThumbUploadError,
ThumbUploadError,
} = props;
const [thumbError, setThumbError] = React.useState(false);
const [thumbLoadError, setThumbLoadError] = React.useState(ThumbUploadError);
const shouldResolve = claim === undefined;
const thumbnail = rawThumbnail && rawThumbnail.trim().replace(/^http:\/\//i, 'https://');
const thumbnailPreview = rawThumbnailPreview && rawThumbnailPreview.trim().replace(/^http:\/\//i, 'https://');
const channelThumbnail = thumbnail || thumbnailPreview;
const defaultAvatar = AVATAR_DEFAULT || Gerbil;
const channelThumbnail = thumbnailPreview || thumbnail || defaultAvatar;
const isGif = channelThumbnail && channelThumbnail.endsWith('gif');
const showThumb = (!obscure && !!thumbnail) || thumbnailPreview;
const defaultAvater = AVATAR_DEFAULT || Gerbil;
// Generate a random color class based on the first letter of the channel name
const { channelName } = parseURI(uri);
@@ -75,6 +81,7 @@ function ChannelThumbnail(props: Props) {
</FreezeframeWrapper>
);
}
return (
<div
className={classnames('channel-thumbnail', className, {
@@ -84,30 +91,23 @@ function ChannelThumbnail(props: Props) {
'channel-thumbnail--resolving': isResolving,
})}
>
{!showThumb && (
{showDelayedMessage ? (
<div className="channel-thumbnail--waiting">{__('This will be visible in a few minutes.')}</div>
) : (
<OptimizedImage
alt={__('Channel profile picture')}
className="channel-thumbnail__default"
src={!thumbError && channelThumbnail ? channelThumbnail : defaultAvater}
className={!channelThumbnail ? 'channel-thumbnail__default' : 'channel-thumbnail__custom'}
src={(!thumbLoadError && channelThumbnail) || defaultAvatar}
loading={noLazyLoad ? undefined : 'lazy'}
onError={() => setThumbError(true)} // if thumb fails (including due to https replace, show gerbil.
onError={() => {
if (setThumbUploadError) {
setThumbUploadError(true);
} else {
setThumbLoadError(true);
}
}}
/>
)}
{showThumb && (
<>
{showDelayedMessage && thumbError ? (
<div className="chanel-thumbnail--waiting">{__('This will be visible in a few minutes.')}</div>
) : (
<OptimizedImage
alt={__('Channel profile picture')}
className="channel-thumbnail__custom"
src={!thumbError && channelThumbnail ? channelThumbnail : defaultAvater}
loading={noLazyLoad ? undefined : 'lazy'}
onError={() => setThumbError(true)} // if thumb fails (including due to https replace, show gerbil.
/>
)}
</>
)}
{!hideStakedIndicator && <ChannelStakedIndicator uri={uri} claim={claim} />}
</div>
);
+10 -2
View File
@@ -5,13 +5,21 @@ import ClaimPreview from 'component/claimPreview';
type Props = {
channelUri: string,
hideActions?: boolean,
channelSubCount?: number,
};
function ClaimAuthor(props: Props) {
const { channelUri, hideActions } = props;
const { channelUri, hideActions, channelSubCount } = props;
return channelUri ? (
<ClaimPreview uri={channelUri} type="inline" properties={false} hideMenu hideActions={hideActions} />
<ClaimPreview
uri={channelUri}
type="inline"
properties={false}
hideMenu
hideActions={hideActions}
channelSubCount={channelSubCount}
/>
) : (
<div className="claim-preview--inline claim-preview__title">{__('Anonymous')}</div>
);
+2 -2
View File
@@ -5,6 +5,7 @@ import Button from 'component/button';
import Card from 'component/common/card';
import { FormField } from 'component/common/form';
import * as ICONS from 'constants/icons';
import * as KEYCODES from 'constants/keycodes';
import CollectionSelectItem from 'component/collectionSelectItem';
type Props = {
@@ -46,8 +47,7 @@ const ClaimCollectionAdd = (props: Props) => {
}
function altEnterListener(e: SyntheticKeyboardEvent<*>) {
const KEYCODE_ENTER = 13;
if (e.keyCode === KEYCODE_ENTER) {
if (e.keyCode === KEYCODES.ENTER) {
e.preventDefault();
buttonref.current.click();
}
+10 -4
View File
@@ -1,11 +1,17 @@
import { connect } from 'react-redux';
import { doOpenModal } from 'redux/actions/app';
import CollectionAddButton from './view';
import { makeSelectClaimForUri } from 'lbry-redux';
import { makeSelectClaimForUri, makeSelectClaimUrlInCollection } from 'lbry-redux';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
});
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri)(state);
const permanentUrl = claim && claim.permanent_url;
return {
claim,
isSaved: makeSelectClaimUrlInCollection(permanentUrl)(state),
};
};
export default connect(select, {
doOpenModal,
@@ -11,10 +11,11 @@ type Props = {
fileAction?: boolean,
type?: boolean,
claim: Claim,
isSaved: boolean,
};
export default function CollectionAddButton(props: Props) {
const { doOpenModal, uri, fileAction, type = 'playlist', claim } = props;
const { doOpenModal, uri, fileAction, type = 'playlist', claim, isSaved } = props;
// $FlowFixMe
const streamType = (claim && claim.value && claim.value.stream_type) || '';
@@ -25,9 +26,9 @@ export default function CollectionAddButton(props: Props) {
<Button
button={fileAction ? undefined : 'alt'}
className={classnames({ 'button--file-action': fileAction })}
icon={fileAction ? ICONS.ADD : ICONS.LIBRARY}
icon={fileAction ? (!isSaved ? ICONS.ADD : ICONS.STACK) : ICONS.LIBRARY}
iconSize={fileAction ? 22 : undefined}
label={uri ? __('Save') : __('New List')}
label={uri ? (!isSaved ? __('Save') : __('Saved')) : __('New List')}
requiresAuth={IS_WEB}
title={__('Add this claim to a list')}
onClick={(e) => {
+10 -1
View File
@@ -27,7 +27,6 @@ type Props = {
onScrollBottom?: (any) => void,
page?: number,
pageSize?: number,
id?: string,
// If using the default header, this is a unique ID needed to persist the state of the filter setting
persistedStorageKey?: string,
showHiddenByUser: boolean,
@@ -47,6 +46,7 @@ type Props = {
searchOptions?: any,
collectionId?: string,
showNoSourceClaims?: boolean,
onClick?: (e: any, claim?: ?Claim, index?: number) => void,
};
export default function ClaimList(props: Props) {
@@ -80,6 +80,7 @@ export default function ClaimList(props: Props) {
searchOptions,
collectionId,
showNoSourceClaims,
onClick,
} = props;
const [currentSort, setCurrentSort] = usePersistedState(persistedStorageKey, SORT_NEW);
@@ -107,6 +108,12 @@ export default function ClaimList(props: Props) {
setCurrentSort(currentSort === SORT_NEW ? SORT_OLD : SORT_NEW);
}
function handleClaimClicked(e, claim, index) {
if (onClick) {
onClick(e, claim, index);
}
}
useEffect(() => {
const handleScroll = debounce((e) => {
if (page && pageSize && onScrollBottom) {
@@ -191,6 +198,7 @@ export default function ClaimList(props: Props) {
{injectedItem && index === 4 && <li>{injectedItem}</li>}
<ClaimPreview
uri={uri}
indexInContainer={index}
type={type}
active={activeUri && uri === activeUri}
hideMenu={hideMenu}
@@ -209,6 +217,7 @@ export default function ClaimList(props: Props) {
return claim.name.length === 24 && !claim.name.includes(' ') && claim.value.author === 'Spee.ch';
}}
live={resolveLive(index)}
onClick={(e, claim, index) => handleClaimClicked(e, claim, index)}
/>
</React.Fragment>
))}
+4
View File
@@ -1,6 +1,7 @@
import { connect } from 'react-redux';
import {
doClaimSearch,
selectClaimsByUri,
selectClaimSearchByQuery,
selectClaimSearchByQueryLastPageReached,
selectFetchingClaimSearch,
@@ -12,11 +13,13 @@ import { doToggleTagFollowDesktop } from 'redux/actions/tags';
import { makeSelectClientSetting, selectShowMatureContent, selectLanguage } from 'redux/selectors/settings';
import { selectModerationBlockList } from 'redux/selectors/comments';
import ClaimListDiscover from './view';
import { doFetchViewCount } from 'lbryinc';
const select = (state) => ({
followedTags: selectFollowedTags(state),
claimSearchByQuery: selectClaimSearchByQuery(state),
claimSearchByQueryLastPageReached: selectClaimSearchByQueryLastPageReached(state),
claimsByUri: selectClaimsByUri(state),
loading: selectFetchingClaimSearch(state),
showNsfw: selectShowMatureContent(state),
hideReposts: makeSelectClientSetting(SETTINGS.HIDE_REPOSTS)(state),
@@ -29,6 +32,7 @@ const select = (state) => ({
const perform = {
doClaimSearch,
doToggleTagFollowDesktop,
doFetchViewCount,
};
export default connect(select, perform)(ClaimListDiscover);
+63 -9
View File
@@ -28,6 +28,7 @@ type Props = {
meta?: Node,
showNsfw: boolean,
hideReposts: boolean,
fetchViewCount?: boolean,
history: { action: string, push: (string) => void, replace: (string) => void },
location: { search: string, pathname: string },
claimSearchByQuery: {
@@ -72,11 +73,14 @@ type Props = {
liveLivestreamsFirst?: boolean,
livestreamMap?: { [string]: any },
hasSource?: boolean,
hasNoSource?: boolean,
limitClaimsPerChannel?: number,
releaseTime?: string,
showNoSourceClaims?: boolean,
isChannel?: boolean,
empty?: string,
claimsByUri: { [string]: any },
doFetchViewCount: (claimIdCsv: string) => void,
};
function ClaimListDiscover(props: Props) {
@@ -93,6 +97,7 @@ function ClaimListDiscover(props: Props) {
channelIds,
showNsfw,
hideReposts,
fetchViewCount,
history,
location,
mutedUris,
@@ -106,7 +111,7 @@ function ClaimListDiscover(props: Props) {
claimType,
pageSize,
defaultClaimType,
streamType = SIMPLE_SITE ? CS.FILE_VIDEO : undefined,
streamType = SIMPLE_SITE ? [CS.FILE_VIDEO, CS.FILE_AUDIO] : undefined,
defaultStreamType = SIMPLE_SITE ? CS.FILE_VIDEO : undefined, // add param for DEFAULT_STREAM_TYPE
freshness,
defaultFreshness = CS.FRESH_WEEK,
@@ -133,15 +138,17 @@ function ClaimListDiscover(props: Props) {
liveLivestreamsFirst,
livestreamMap,
hasSource,
hasNoSource,
isChannel = false,
showNoSourceClaims,
empty,
claimsByUri,
doFetchViewCount,
} = props;
const didNavigateForward = history.action === 'PUSH';
const { search } = location;
const [page, setPage] = React.useState(1);
const [forceRefresh, setForceRefresh] = React.useState();
const [finalUris, setFinalUris] = React.useState([]);
const isLargeScreen = useIsLargeScreen();
const [orderParamEntry, setOrderParamEntry] = usePersistedState(`entry-${location.pathname}`, CS.ORDER_BY_TRENDING);
const [orderParamUser, setOrderParamUser] = usePersistedState(`orderUser-${location.pathname}`, CS.ORDER_BY_TRENDING);
@@ -231,7 +238,7 @@ function ClaimListDiscover(props: Props) {
page_size: dynamicPageSize,
page,
name,
claim_type: claimType || undefined,
claim_type: claimType || ['stream', 'repost', 'channel'],
// no_totals makes it so the sdk doesn't have to calculate total number pages for pagination
// it's faster, but we will need to remove it if we start using total_pages
no_totals: true,
@@ -245,7 +252,9 @@ function ClaimListDiscover(props: Props) {
: CS.ORDER_BY_TOP_VALUE, // Sort by top
};
if (hasSource || (!ENABLE_NO_SOURCE_CLAIMS && (!claimType || claimType === CS.CLAIM_STREAM))) {
if (ENABLE_NO_SOURCE_CLAIMS && hasNoSource) {
options.has_no_source = true;
} else if (hasSource || (!ENABLE_NO_SOURCE_CLAIMS && (!claimType || claimType === 'stream'))) {
options.has_source = true;
}
@@ -319,7 +328,7 @@ function ClaimListDiscover(props: Props) {
}
if (streamTypeParam && streamTypeParam !== CS.CONTENT_ALL && claimType !== CS.CLAIM_CHANNEL) {
options.stream_types = [streamTypeParam];
options.stream_types = typeof streamTypeParam === 'string' ? [streamTypeParam] : streamTypeParam;
}
if (claimTypeParam) {
@@ -387,6 +396,9 @@ function ClaimListDiscover(props: Props) {
: undefined;
const livestreamSearchResult = livestreamSearchKey && claimSearchByQuery[livestreamSearchKey];
const [finalUris, setFinalUris] = React.useState(
getFinalUrisInitialState(history.action === 'POP', claimSearchResult)
);
const [prevOptions, setPrevOptions] = React.useState(null);
if (!isJustScrollingToNewPage(prevOptions, options)) {
@@ -448,6 +460,10 @@ function ClaimListDiscover(props: Props) {
</div>
);
// **************************************************************************
// Helpers
// **************************************************************************
// Returns true if the change in 'options' indicate that we are simply scrolling
// down to a new page; false otherwise.
function isJustScrollingToNewPage(prevOptions, options) {
@@ -500,6 +516,33 @@ function ClaimListDiscover(props: Props) {
return prev.length === next.length && prev.every((value, index) => value === next[index]);
}
function getFinalUrisInitialState(isNavigatingBack, claimSearchResult) {
if (isNavigatingBack && claimSearchResult && claimSearchResult.length > 0) {
return claimSearchResult;
} else {
return [];
}
}
function fetchViewCountForUris(uris) {
const claimIds = [];
if (uris) {
uris.forEach((uri) => {
if (claimsByUri[uri]) {
claimIds.push(claimsByUri[uri].claim_id);
}
});
}
if (claimIds.length > 0) {
doFetchViewCount(claimIds.join(','));
}
}
// **************************************************************************
// **************************************************************************
React.useEffect(() => {
if (shouldPerformSearch) {
const searchOptions = JSON.parse(optionsStringForEffect);
@@ -526,6 +569,12 @@ function ClaimListDiscover(props: Props) {
}
}, [uris, claimSearchResult, finalUris, setFinalUris, liveLivestreamsFirst, livestreamSearchResult]);
React.useEffect(() => {
if (fetchViewCount) {
fetchViewCountForUris(finalUris);
}
}, [finalUris]); // eslint-disable-line react-hooks/exhaustive-deps
const headerToUse = header || (
<ClaimListHeader
channelIds={channelIds}
@@ -562,7 +611,6 @@ function ClaimListDiscover(props: Props) {
)}
<ClaimList
tileLayout
id={mainSearchKey}
loading={loading}
uris={finalUris}
onScrollBottom={handleScrollBottom}
@@ -596,7 +644,6 @@ function ClaimListDiscover(props: Props) {
</div>
)}
<ClaimList
id={mainSearchKey}
type={type}
loading={loading}
uris={finalUris}
@@ -611,13 +658,20 @@ function ClaimListDiscover(props: Props) {
liveLivestreamsFirst={liveLivestreamsFirst}
livestreamMap={livestreamMap}
searchOptions={options}
showNoSourceClaims={showNoSourceClaims}
showNoSourceClaims={hasNoSource || showNoSourceClaims}
empty={empty}
/>
{loading &&
new Array(dynamicPageSize)
.fill(1)
.map((x, i) => <ClaimPreview key={i} placeholder="loading" type={type} />)}
.map((x, i) => (
<ClaimPreview
showNoSourceClaims={hasNoSource || showNoSourceClaims}
key={i}
placeholder="loading"
type={type}
/>
))}
</div>
)}
</React.Fragment>
+29 -10
View File
@@ -8,6 +8,9 @@ import {
makeSelectCollectionIsMine,
COLLECTIONS_CONSTS,
makeSelectEditedCollectionForId,
makeSelectClaimIsMine,
doFetchItemsInCollection,
makeSelectUrlsForCollectionId,
} from 'lbry-redux';
import { makeSelectChannelIsMuted } from 'redux/selectors/blocked';
import { doChannelMute, doChannelUnmute } from 'redux/actions/blocked';
@@ -24,20 +27,26 @@ import {
makeSelectChannelIsAdminBlocked,
} from 'redux/selectors/comments';
import { doToast } from 'redux/actions/notifications';
import { makeSelectSigningIsMine } from 'redux/selectors/content';
import { doChannelSubscribe, doChannelUnsubscribe } from 'redux/actions/subscriptions';
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectListShuffle } from 'redux/selectors/content';
import { doSetPlayingUri, doToggleShuffleList } from 'redux/actions/content';
import ClaimPreview from './view';
import fs from 'fs';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri, false)(state);
const collectionId = props.collectionId;
const resolvedList = makeSelectUrlsForCollectionId(collectionId)(state);
const repostedClaim = claim && claim.reposted_claim;
const contentClaim = repostedClaim || claim;
const contentSigningChannel = contentClaim && contentClaim.signing_channel;
const contentPermanentUri = contentClaim && contentClaim.permanent_url;
const contentChannelUri = (contentSigningChannel && contentSigningChannel.permanent_url) || contentPermanentUri;
const shuffleList = selectListShuffle(state);
const shuffle = shuffleList && shuffleList.collectionId === collectionId && shuffleList.newUrls;
const playNextUri = shuffle && shuffle[0];
return {
claim,
@@ -45,19 +54,27 @@ const select = (state, props) => {
contentClaim,
contentSigningChannel,
contentChannelUri,
claimIsMine: makeSelectSigningIsMine(props.uri)(state),
hasClaimInWatchLater: makeSelectCollectionForIdHasClaimUrl(COLLECTIONS_CONSTS.WATCH_LATER_ID, contentPermanentUri)(state),
hasClaimInCustom: makeSelectCollectionForIdHasClaimUrl(COLLECTIONS_CONSTS.FAVORITES_ID, contentPermanentUri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
hasClaimInWatchLater: makeSelectCollectionForIdHasClaimUrl(
COLLECTIONS_CONSTS.WATCH_LATER_ID,
contentPermanentUri
)(state),
hasClaimInFavorites: makeSelectCollectionForIdHasClaimUrl(
COLLECTIONS_CONSTS.FAVORITES_ID,
contentPermanentUri
)(state),
channelIsMuted: makeSelectChannelIsMuted(contentChannelUri)(state),
channelIsBlocked: makeSelectChannelIsBlocked(contentChannelUri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(contentPermanentUri)(state),
isSubscribed: makeSelectIsSubscribed(contentChannelUri, true)(state),
channelIsAdminBlocked: makeSelectChannelIsAdminBlocked(props.uri)(state),
isAdmin: selectHasAdminChannel(state),
claimInCollection: makeSelectCollectionForIdHasClaimUrl(props.collectionId, contentPermanentUri)(state),
isMyCollection: makeSelectCollectionIsMine(props.collectionId)(state),
editedCollection: makeSelectEditedCollectionForId(props.collectionId)(state),
claimInCollection: makeSelectCollectionForIdHasClaimUrl(collectionId, contentPermanentUri)(state),
isMyCollection: makeSelectCollectionIsMine(collectionId)(state),
editedCollection: makeSelectEditedCollectionForId(collectionId)(state),
isAuthenticated: Boolean(selectUserVerifiedEmail(state)),
resolvedList,
playNextUri,
};
};
@@ -78,13 +95,15 @@ const perform = (dispatch) => ({
doChannelUnmute: (channelUri) => dispatch(doChannelUnmute(channelUri)),
doCommentModBlock: (channelUri) => dispatch(doCommentModBlock(channelUri)),
doCommentModUnBlock: (channelUri) => dispatch(doCommentModUnBlock(channelUri)),
doCommentModBlockAsAdmin: (commenterUri, blockerId) =>
dispatch(doCommentModBlockAsAdmin(commenterUri, blockerId)),
doCommentModBlockAsAdmin: (commenterUri, blockerId) => dispatch(doCommentModBlockAsAdmin(commenterUri, blockerId)),
doCommentModUnBlockAsAdmin: (commenterUri, blockerId) =>
dispatch(doCommentModUnBlockAsAdmin(commenterUri, blockerId)),
doChannelSubscribe: (subscription) => dispatch(doChannelSubscribe(subscription)),
doChannelUnsubscribe: (subscription) => dispatch(doChannelUnsubscribe(subscription)),
doCollectionEdit: (collection, props) => dispatch(doCollectionEdit(collection, props)),
fetchCollectionItems: (collectionId) => dispatch(doFetchItemsInCollection({ collectionId })),
doSetPlayingUri: (uri) => dispatch(doSetPlayingUri({ uri })),
doToggleShuffleList: (collectionId) => dispatch(doToggleShuffleList(undefined, collectionId, true, true)),
});
export default connect(select, perform)(ClaimPreview);
+72 -27
View File
@@ -7,12 +7,12 @@ import React from 'react';
import classnames from 'classnames';
import { Menu, MenuButton, MenuList, MenuItem } from '@reach/menu-button';
import Icon from 'component/common/icon';
import { generateShareUrl, generateRssUrl, generateLbryContentUrl } from 'util/url';
import { generateShareUrl, generateRssUrl, generateLbryContentUrl, formatLbryUrlForWeb } from 'util/url';
import { useHistory } from 'react-router';
import { buildURI, parseURI, COLLECTIONS_CONSTS } from 'lbry-redux';
const SHARE_DOMAIN = SHARE_DOMAIN_URL || URL;
const PAGE_VIEW_QUERY = `view`;
const PAGE_VIEW_QUERY = 'view';
const EDIT_PAGE = 'edit';
type SubscriptionArgs = {
@@ -42,7 +42,7 @@ type Props = {
doCommentModUnBlockAsAdmin: (string, string) => void,
doCollectionEdit: (string, any) => void,
hasClaimInWatchLater: boolean,
hasClaimInCustom: boolean,
hasClaimInFavorites: boolean,
claimInCollection: boolean,
collectionId: string,
isMyCollection: boolean,
@@ -56,6 +56,11 @@ type Props = {
isChannelPage: boolean,
editedCollection: Collection,
isAuthenticated: boolean,
playNextUri: string,
resolvedList: boolean,
fetchCollectionItems: (string) => void,
doSetPlayingUri: (string) => void,
doToggleShuffleList: (string) => void,
};
function ClaimMenuList(props: Props) {
@@ -80,7 +85,7 @@ function ClaimMenuList(props: Props) {
doCommentModUnBlockAsAdmin,
doCollectionEdit,
hasClaimInWatchLater,
hasClaimInCustom,
hasClaimInFavorites,
collectionId,
isMyCollection,
doToast,
@@ -93,7 +98,13 @@ function ClaimMenuList(props: Props) {
isChannelPage = false,
editedCollection,
isAuthenticated,
playNextUri,
resolvedList,
fetchCollectionItems,
doSetPlayingUri,
doToggleShuffleList,
} = props;
const [doShuffle, setDoShuffle] = React.useState(false);
const incognitoClaim = contentChannelUri && !contentChannelUri.includes('@');
const isChannel = !incognitoClaim && !contentSigningChannel;
const { channelName } = parseURI(contentChannelUri);
@@ -105,10 +116,29 @@ function ClaimMenuList(props: Props) {
: isSubscribed
? __('Unfollow')
: __('Follow');
const lastCollectionName = 'Favorites';
const lastCollectionId = COLLECTIONS_CONSTS.FAVORITES_ID;
const { push, replace } = useHistory();
const fetchItems = React.useCallback(() => {
if (collectionId) {
fetchCollectionItems(collectionId);
}
}, [collectionId, fetchCollectionItems]);
React.useEffect(() => {
if (doShuffle && resolvedList) {
doToggleShuffleList(collectionId);
if (playNextUri) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
const navigateUrl = formatLbryUrlForWeb(playNextUri) + `?` + collectionParams.toString();
setDoShuffle(false);
doSetPlayingUri(playNextUri);
push(navigateUrl);
}
}
}, [collectionId, doSetPlayingUri, doShuffle, doToggleShuffleList, playNextUri, push, resolvedList]);
if (!claim) {
return null;
}
@@ -248,9 +278,21 @@ function ClaimMenuList(props: Props) {
{collectionId && isCollectionClaim ? (
<>
<MenuItem className="comment__menu-option" onSelect={() => push(`/$/${PAGES.LIST}/${collectionId}`)}>
<div className="menu__link">
<a className="menu__link" href={`/$/${PAGES.LIST}/${collectionId}`}>
<Icon aria-hidden icon={ICONS.VIEW} />
{__('View List')}
</a>
</MenuItem>
<MenuItem
className="comment__menu-option"
onSelect={() => {
if (!resolvedList) fetchItems();
setDoShuffle(true);
}}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SHUFFLE} />
{__('Shuffle Play')}
</div>
</MenuItem>
{isMyCollection && (
@@ -282,21 +324,23 @@ function ClaimMenuList(props: Props) {
{/* WATCH LATER */}
<MenuItem
className="comment__menu-option"
onSelect={() => handleAdd(hasClaimInWatchLater, 'Watch Later', COLLECTIONS_CONSTS.WATCH_LATER_ID)}
onSelect={() =>
handleAdd(hasClaimInWatchLater, __('Watch Later'), COLLECTIONS_CONSTS.WATCH_LATER_ID)
}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInWatchLater ? ICONS.DELETE : ICONS.TIME} />
{hasClaimInWatchLater ? __('In Watch Later') : __('Watch Later')}
</div>
</MenuItem>
{/* CUSTOM LIST */}
{/* FAVORITES LIST */}
<MenuItem
className="comment__menu-option"
onSelect={() => handleAdd(hasClaimInCustom, lastCollectionName, lastCollectionId)}
onSelect={() => handleAdd(hasClaimInFavorites, __('Favorites'), COLLECTIONS_CONSTS.FAVORITES_ID)}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInCustom ? ICONS.DELETE : ICONS.STAR} />
{hasClaimInCustom ? __(`In ${lastCollectionName}`) : __(`${lastCollectionName}`)}
<Icon aria-hidden icon={hasClaimInFavorites ? ICONS.DELETE : ICONS.STAR} />
{hasClaimInFavorites ? __('In Favorites') : __('Favorites')}
</div>
</MenuItem>
{/* CURRENTLY ONLY SUPPORT PLAYLISTS FOR PLAYABLE; LATER DIFFERENT TYPES */}
@@ -378,22 +422,30 @@ function ClaimMenuList(props: Props) {
</div>
</MenuItem>
)}
{showDelete && (
<MenuItem className="comment__menu-option" onSelect={handleDelete}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete')}
</div>
</MenuItem>
)}
</>
)}
{showDelete && (
<MenuItem className="comment__menu-option" onSelect={handleDelete}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete')}
</div>
</MenuItem>
)}
</>
)}
</>
)}
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleCopyLink}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.COPY_LINK} />
{__('Copy Link')}
</div>
</MenuItem>
{isChannelPage && IS_WEB && rssUrl && (
<MenuItem className="comment__menu-option" onSelect={handleCopyRssLink}>
<div className="menu__link">
@@ -403,13 +455,6 @@ function ClaimMenuList(props: Props) {
</MenuItem>
)}
<MenuItem className="comment__menu-option" onSelect={handleCopyLink}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SHARE} />
{__('Copy Link')}
</div>
</MenuItem>
{!claimIsMine && !isMyCollection && (
<MenuItem className="comment__menu-option" onSelect={handleReportContent}>
<div className="menu__link">
+38 -25
View File
@@ -15,6 +15,8 @@ import {
doCollectionEdit,
makeSelectUrlsForCollectionId,
makeSelectIndexForUrlInCollection,
makeSelectTitleForUri,
makeSelectDateForUri,
} from 'lbry-redux';
import { selectMutedChannels, makeSelectChannelIsMuted } from 'redux/selectors/blocked';
import { selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
@@ -22,32 +24,43 @@ import { selectShowMatureContent } from 'redux/selectors/settings';
import { makeSelectHasVisitedUri } from 'redux/selectors/content';
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
import { selectModerationBlockList } from 'redux/selectors/comments';
import ClaimPreview from './view';
const select = (state, props) => ({
pending: props.uri && makeSelectClaimIsPending(props.uri)(state),
claim: props.uri && makeSelectClaimForUri(props.uri)(state),
reflectingProgress: props.uri && makeSelectReflectingClaimForUri(props.uri)(state),
obscureNsfw: selectShowMatureContent(state) === false,
claimIsMine: props.uri && makeSelectClaimIsMine(props.uri)(state),
isResolvingUri: props.uri && makeSelectIsUriResolving(props.uri)(state),
isResolvingRepost: props.uri && makeSelectIsUriResolving(props.repostUrl)(state),
repostClaim: props.uri && makeSelectClaimForUri(props.uri)(state),
nsfw: props.uri && makeSelectClaimIsNsfw(props.uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
filteredOutpoints: selectFilteredOutpoints(state),
mutedUris: selectMutedChannels(state),
blockedUris: selectModerationBlockList(state),
hasVisitedUri: props.uri && makeSelectHasVisitedUri(props.uri)(state),
channelIsBlocked: props.uri && makeSelectChannelIsMuted(props.uri)(state),
isSubscribed: props.uri && makeSelectIsSubscribed(props.uri, true)(state),
streamingUrl: props.uri && makeSelectStreamingUrlForUri(props.uri)(state),
wasPurchased: props.uri && makeSelectClaimWasPurchased(props.uri)(state),
isLivestream: makeSelectClaimIsStreamPlaceholder(props.uri)(state),
isCollectionMine: makeSelectCollectionIsMine(props.collectionId)(state),
collectionUris: makeSelectUrlsForCollectionId(props.collectionId)(state),
collectionIndex: makeSelectIndexForUrlInCollection(props.uri, props.collectionId)(state),
});
import ClaimPreview from './view';
import formatMediaDuration from 'util/formatMediaDuration';
const select = (state, props) => {
const claim = props.uri && makeSelectClaimForUri(props.uri)(state);
const media = claim && claim.value && (claim.value.video || claim.value.audio);
const mediaDuration = media && media.duration && formatMediaDuration(media.duration, { screenReader: true });
return {
claim,
mediaDuration,
date: props.uri && makeSelectDateForUri(props.uri)(state),
title: props.uri && makeSelectTitleForUri(props.uri)(state),
pending: props.uri && makeSelectClaimIsPending(props.uri)(state),
reflectingProgress: props.uri && makeSelectReflectingClaimForUri(props.uri)(state),
obscureNsfw: selectShowMatureContent(state) === false,
claimIsMine: props.uri && makeSelectClaimIsMine(props.uri)(state),
isResolvingUri: props.uri && makeSelectIsUriResolving(props.uri)(state),
isResolvingRepost: props.uri && makeSelectIsUriResolving(props.repostUrl)(state),
repostClaim: props.uri && makeSelectClaimForUri(props.uri)(state),
nsfw: props.uri && makeSelectClaimIsNsfw(props.uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
filteredOutpoints: selectFilteredOutpoints(state),
mutedUris: selectMutedChannels(state),
blockedUris: selectModerationBlockList(state),
hasVisitedUri: props.uri && makeSelectHasVisitedUri(props.uri)(state),
channelIsBlocked: props.uri && makeSelectChannelIsMuted(props.uri)(state),
isSubscribed: props.uri && makeSelectIsSubscribed(props.uri, true)(state),
streamingUrl: props.uri && makeSelectStreamingUrlForUri(props.uri)(state),
wasPurchased: props.uri && makeSelectClaimWasPurchased(props.uri)(state),
isLivestream: makeSelectClaimIsStreamPlaceholder(props.uri)(state),
isCollectionMine: makeSelectCollectionIsMine(props.collectionId)(state),
collectionUris: makeSelectUrlsForCollectionId(props.collectionId)(state),
collectionIndex: makeSelectIndexForUrlInCollection(props.uri, props.collectionId)(state),
};
};
const perform = (dispatch) => ({
resolveUri: (uri) => dispatch(doResolveUri(uri)),
+76 -28
View File
@@ -2,11 +2,12 @@
import type { Node } from 'react';
import React, { useEffect, forwardRef } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { isEmpty } from 'util/object';
import { lazyImport } from 'util/lazyImport';
import classnames from 'classnames';
import { parseURI, COLLECTIONS_CONSTS, isURIEqual } from 'lbry-redux';
import { formatLbryUrlForWeb } from 'util/url';
import { isEmpty } from 'util/object';
import { formatClaimPreviewTitle } from 'util/formatAriaLabel';
import FileThumbnail from 'component/fileThumbnail';
import UriIndicator from 'component/uriIndicator';
import PreviewOverlayProperties from 'component/previewOverlayProperties';
@@ -33,6 +34,7 @@ const AbandonedChannelPreview = lazyImport(() =>
import('component/abandonedChannelPreview' /* webpackChunkName: "abandonedChannelPreview" */)
);
// preview images used on the landing page and on the channel page
type Props = {
uri: string,
claim: ?Claim,
@@ -44,7 +46,7 @@ type Props = {
reflectingProgress?: any, // fxme
resolveUri: (string) => void,
isResolvingUri: boolean,
history: { push: (string) => void },
history: { push: (string | any) => void },
title: string,
nsfw: boolean,
placeholder: string,
@@ -64,7 +66,7 @@ type Props = {
actions: boolean | Node | string | number,
properties: boolean | Node | string | number | ((Claim) => Node),
empty?: Node,
onClick?: (any) => any,
onClick?: (e: any, claim?: ?Claim, index?: number) => any,
streamingUrl: ?string,
getFile: (string) => void,
customShouldHide?: (Claim) => boolean,
@@ -85,6 +87,10 @@ type Props = {
collectionUris: Array<Collection>,
collectionIndex?: number,
disableNavigation?: boolean,
mediaDuration?: string,
date?: any,
indexInContainer?: number, // The index order of this component within 'containerId'.
channelSubCount?: number,
};
const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
@@ -99,8 +105,11 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
// claim properties
// is the claim consider nsfw?
nsfw,
date,
title,
claimIsMine,
streamingUrl,
mediaDuration,
// user properties
channelIsBlocked,
hasVisitedUri,
@@ -143,6 +152,8 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
isCollectionMine,
collectionUris,
disableNavigation,
indexInContainer,
channelSubCount,
} = props;
const isCollection = claim && claim.value_type === 'collection';
const collectionClaimId = isCollection && claim && claim.claim_id;
@@ -155,6 +166,17 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
const shouldHideActions = hideActions || isMyCollection || type === 'small' || type === 'tooltip';
const canonicalUrl = claim && claim.canonical_url;
const lastCollectionIndex = collectionUris ? collectionUris.length - 1 : 0;
const channelSubscribers = React.useMemo(() => {
if (channelSubCount === undefined) {
return <span />;
}
const formattedSubCount = Number(channelSubCount).toLocaleString();
return (
<span className="claim-preview__channel-sub-count">
{channelSubCount === 1 ? __('1 Follower') : __('%formattedSubCount% Followers', { formattedSubCount })}
</span>
);
}, [channelSubCount]);
let isValid = false;
if (uri) {
try {
@@ -175,15 +197,41 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
(claim.value.stream_type === 'audio' || claim.value.stream_type === 'video');
const isChannelUri = isValid ? parseURI(uri).isChannel : false;
const signingChannel = claim && claim.signing_channel;
let navigateUrl = formatLbryUrlForWeb((claim && claim.canonical_url) || uri || '/');
if (listId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, listId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
// Get channel title ( use name as fallback )
let channelTitle = null;
if (signingChannel) {
const { value, name } = signingChannel;
if (value && value.title) {
channelTitle = value.title;
} else {
channelTitle = name;
}
}
// Aria-label value for claim preview
let ariaLabelData = isChannelUri ? title : formatClaimPreviewTitle(title, channelTitle, date, mediaDuration);
let navigateUrl = formatLbryUrlForWeb((claim && claim.canonical_url) || uri || '/');
let navigateSearch = new URLSearchParams();
if (listId) {
navigateSearch.set(COLLECTIONS_CONSTS.COLLECTION_ID, listId);
}
const handleNavLinkClick = (e) => {
if (onClick) {
onClick(e, claim, indexInContainer); // not sure indexInContainer is used for anything.
}
e.stopPropagation();
};
const navLinkProps = {
to: navigateUrl,
onClick: (e) => e.stopPropagation(),
to: {
pathname: navigateUrl,
search: navigateSearch.toString() ? '?' + navigateSearch.toString() : '',
},
onClick: handleNavLinkClick,
onAuxClick: handleNavLinkClick,
};
// do not block abandoned and nsfw claims if showUserBlocked is passed
@@ -229,11 +277,14 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
function handleOnClick(e) {
if (onClick) {
onClick(e);
onClick(e, claim, indexInContainer);
}
if (claim && !pending && !disableNavigation) {
history.push(navigateUrl);
history.push({
pathname: navigateUrl,
search: navigateSearch.toString() ? '?' + navigateSearch.toString() : '',
});
}
}
@@ -313,31 +364,29 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
})}
>
{isChannelUri && claim ? (
<UriIndicator uri={uri} link>
<UriIndicator focusable={false} uri={uri} link>
<ChannelThumbnail uri={uri} small={type === 'inline'} />
</UriIndicator>
) : (
<>
{!pending ? (
<NavLink {...navLinkProps}>
<NavLink aria-hidden tabIndex={-1} {...navLinkProps}>
<FileThumbnail thumbnail={thumbnailUrl}>
<div className="claim-preview__hover-actions">
{isPlayable && <FileWatchLaterLink focusable={false} uri={uri} />}
</div>
{/* @if TARGET='app' */}
{claim && !isCollection && (
<div className="claim-preview__hover-actions">
<FileDownloadLink uri={canonicalUrl} hideOpenButton hideDownloadStatus />
</div>
)}
<div className="claim-preview__hover-actions">
{claim && !isCollection && (
<FileDownloadLink focusable={false} uri={canonicalUrl} hideOpenButton hideDownloadStatus />
)}
</div>
{/* @endif */}
{!isLivestream && (
<div className="claim-preview__file-property-overlay">
<PreviewOverlayProperties uri={uri} small={type === 'small'} properties={liveProperty} />
</div>
)}
{isPlayable && (
<div className="claim-preview__hover-actions">
<FileWatchLaterLink uri={uri} />
</div>
)}
</FileThumbnail>
</NavLink>
) : (
@@ -352,13 +401,14 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
{pending ? (
<ClaimPreviewTitle uri={uri} />
) : (
<NavLink aria-current={active && 'page'} {...navLinkProps}>
<NavLink aria-label={ariaLabelData} aria-current={active ? 'page' : null} {...navLinkProps}>
<ClaimPreviewTitle uri={uri} />
</NavLink>
)}
</div>
<ClaimPreviewSubtitle uri={uri} type={type} />
{(pending || !!reflectingProgress) && <PublishPending uri={uri} />}
{channelSubscribers}
</div>
{type !== 'small' && (
<div className="claim-preview__actions">
@@ -451,9 +501,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
)}
</div>
</div>
{!hideMenu && (
<ClaimMenuList uri={uri} collectionId={listId} />
)}
{!hideMenu && <ClaimMenuList uri={uri} collectionId={listId} />}
</>
</WrapperElement>
);
+9 -1
View File
@@ -4,6 +4,7 @@ import React from 'react';
import UriIndicator from 'component/uriIndicator';
import DateTime from 'component/dateTime';
import Button from 'component/button';
import FileViewCountInline from 'component/fileViewCountInline';
import { parseURI } from 'lbry-redux';
type Props = {
@@ -37,7 +38,14 @@ function ClaimPreviewSubtitle(props: Props) {
`${claimsInChannel} ${claimsInChannel === 1 ? __('upload') : __('uploads')}`}
{!isChannel &&
(isLivestream && ENABLE_NO_SOURCE_CLAIMS ? __('Livestream') : <DateTime timeAgo uri={uri} />)}
(isLivestream && ENABLE_NO_SOURCE_CLAIMS ? (
__('Livestream')
) : (
<>
<FileViewCountInline uri={uri} isLivestream={isLivestream} />
<DateTime timeAgo uri={uri} />
</>
))}
</>
)}
</React.Fragment>
+23 -13
View File
@@ -9,25 +9,35 @@ import {
makeSelectChannelForClaimUri,
makeSelectClaimIsNsfw,
makeSelectClaimIsStreamPlaceholder,
makeSelectDateForUri,
} from 'lbry-redux';
import { selectMutedChannels } from 'redux/selectors/blocked';
import { selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { selectShowMatureContent } from 'redux/selectors/settings';
import ClaimPreviewTile from './view';
import formatMediaDuration from 'util/formatMediaDuration';
const select = (state, props) => ({
claim: props.uri && makeSelectClaimForUri(props.uri)(state),
channel: props.uri && makeSelectChannelForClaimUri(props.uri)(state),
isResolvingUri: props.uri && makeSelectIsUriResolving(props.uri)(state),
thumbnail: props.uri && makeSelectThumbnailForUri(props.uri)(state),
title: props.uri && makeSelectTitleForUri(props.uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
filteredOutpoints: selectFilteredOutpoints(state),
blockedChannelUris: selectMutedChannels(state),
showMature: selectShowMatureContent(state),
isMature: makeSelectClaimIsNsfw(props.uri)(state),
isLivestream: makeSelectClaimIsStreamPlaceholder(props.uri)(state),
});
const select = (state, props) => {
const claim = props.uri && makeSelectClaimForUri(props.uri)(state);
const media = claim && claim.value && (claim.value.video || claim.value.audio);
const mediaDuration = media && media.duration && formatMediaDuration(media.duration, { screenReader: true });
return {
claim,
mediaDuration,
date: props.uri && makeSelectDateForUri(props.uri)(state),
channel: props.uri && makeSelectChannelForClaimUri(props.uri)(state),
isResolvingUri: props.uri && makeSelectIsUriResolving(props.uri)(state),
thumbnail: props.uri && makeSelectThumbnailForUri(props.uri)(state),
title: props.uri && makeSelectTitleForUri(props.uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
filteredOutpoints: selectFilteredOutpoints(state),
blockedChannelUris: selectMutedChannels(state),
showMature: selectShowMatureContent(state),
isMature: makeSelectClaimIsNsfw(props.uri)(state),
isLivestream: makeSelectClaimIsStreamPlaceholder(props.uri)(state),
};
};
const perform = (dispatch) => ({
resolveUri: (uri) => dispatch(doResolveUri(uri)),
+36 -26
View File
@@ -7,9 +7,11 @@ import UriIndicator from 'component/uriIndicator';
import TruncatedText from 'component/common/truncated-text';
import DateTime from 'component/dateTime';
import ChannelThumbnail from 'component/channelThumbnail';
import FileViewCountInline from 'component/fileViewCountInline';
import SubscribeButton from 'component/subscribeButton';
import useGetThumbnail from 'effects/use-get-thumbnail';
import { formatLbryUrlForWeb } from 'util/url';
import { formatClaimPreviewTitle } from 'util/formatAriaLabel';
import { parseURI, COLLECTIONS_CONSTS, isURIEqual } from 'lbry-redux';
import PreviewOverlayProperties from 'component/previewOverlayProperties';
import FileDownloadLink from 'component/fileDownloadLink';
@@ -22,7 +24,9 @@ import PlaceholderTx from 'static/img/placeholderTx.gif';
type Props = {
uri: string,
date?: any,
claim: ?Claim,
mediaDuration?: string,
resolveUri: (string) => void,
isResolvingUri: boolean,
history: { push: (string) => void },
@@ -50,10 +54,12 @@ type Props = {
isLivestream: boolean,
};
// preview image cards used in related video functionality
function ClaimPreviewTile(props: Props) {
const {
history,
uri,
date,
isResolvingUri,
thumbnail,
title,
@@ -73,6 +79,7 @@ function ClaimPreviewTile(props: Props) {
showNoSourceClaims,
isLivestream,
collectionId,
mediaDuration,
} = props;
const isRepost = claim && claim.repost_channel_url;
const isCollection = claim && claim.value_type === 'collection';
@@ -115,6 +122,10 @@ function ClaimPreviewTile(props: Props) {
const signingChannel = claim && claim.signing_channel;
const isChannel = claim && claim.value_type === 'channel';
const channelUri = !isChannel ? signingChannel && signingChannel.permanent_url : claim && claim.permanent_url;
const channelTitle = signingChannel && ((signingChannel.value && signingChannel.value.title) || signingChannel.name);
// Aria-label value for claim preview
let ariaLabelData = isChannel ? title : formatClaimPreviewTitle(title, channelTitle, date, mediaDuration);
function handleClick(e) {
if (navigateUrl) {
@@ -189,31 +200,25 @@ function ClaimPreviewTile(props: Props) {
return (
<li
role="link"
onClick={handleClick}
className={classnames('card claim-preview--tile', {
'claim-preview__wrapper--channel': isChannel,
'claim-preview__live': live,
})}
>
<NavLink {...navLinkProps}>
<NavLink {...navLinkProps} role="none" tabIndex={-1} aria-hidden>
<FileThumbnail thumbnail={thumbnailUrl} allowGifs>
{!isChannel && (
<React.Fragment>
<div className="claim-preview__hover-actions">
{isPlayable && <FileWatchLaterLink focusable={false} uri={uri} />}
</div>
{/* @if TARGET='app' */}
{isStream && (
<div className="claim-preview__hover-actions">
<FileDownloadLink uri={canonicalUrl} hideOpenButton />
</div>
)}
<div className="claim-preview__hover-actions">
{isStream && <FileDownloadLink focusable={false} uri={canonicalUrl} hideOpenButton />}
</div>
{/* @endif */}
{isPlayable && (
<div className="claim-preview__hover-actions">
<FileWatchLaterLink uri={uri} />
</div>
)}
<div className="claim-preview__file-property-overlay">
<PreviewOverlayProperties uri={uri} properties={liveProperty || properties} />
</div>
@@ -228,17 +233,19 @@ function ClaimPreviewTile(props: Props) {
)}
</FileThumbnail>
</NavLink>
<NavLink {...navLinkProps}>
<h2 className="claim-tile__title">
<TruncatedText text={title || (claim && claim.name)} lines={isChannel ? 1 : 2} />
{isChannel && (
<div className="claim-tile__about">
<UriIndicator uri={uri} />
</div>
)}
<ClaimMenuList uri={uri} collectionId={listId} />
</h2>
</NavLink>
<div className="claim-tile__header">
<NavLink aria-label={ariaLabelData} {...navLinkProps}>
<h2 className="claim-tile__title">
<TruncatedText text={title || (claim && claim.name)} lines={isChannel ? 1 : 2} />
{isChannel && (
<div className="claim-tile__about">
<UriIndicator uri={uri} />
</div>
)}
</h2>
</NavLink>
<ClaimMenuList uri={uri} collectionId={listId} channelUri={channelUri} />
</div>
<div>
<div className="claim-tile__info">
{isChannel ? (
@@ -247,13 +254,16 @@ function ClaimPreviewTile(props: Props) {
</div>
) : (
<React.Fragment>
<UriIndicator uri={uri} link hideAnonymous>
<UriIndicator focusable={false} uri={uri} link hideAnonymous>
<ChannelThumbnail uri={channelUri} xsmall />
</UriIndicator>
<div className="claim-tile__about">
<UriIndicator uri={uri} link />
<DateTime timeAgo uri={uri} />
<div className="claim-tile__about--counts">
<FileViewCountInline uri={uri} isLivestream={isLivestream} />
<DateTime timeAgo uri={uri} />
</div>
</div>
</React.Fragment>
)}
+2
View File
@@ -6,6 +6,7 @@ import {
SETTINGS,
selectClaimsByUri,
} from 'lbry-redux';
import { doFetchViewCount } from 'lbryinc';
import { doToggleTagFollowDesktop } from 'redux/actions/tags';
import { makeSelectClientSetting, selectShowMatureContent } from 'redux/selectors/settings';
import { selectModerationBlockList } from 'redux/selectors/comments';
@@ -25,6 +26,7 @@ const select = (state) => ({
const perform = {
doClaimSearch,
doToggleTagFollowDesktop,
doFetchViewCount,
};
export default connect(select, perform)(ClaimListDiscover);
+81 -41
View File
@@ -86,18 +86,15 @@ export function prioritizeActiveLivestreams(
type Props = {
prefixUris?: Array<string>,
pinUrls?: Array<string>,
uris: Array<string>,
doClaimSearch: ({}) => void,
showNsfw: boolean,
hideReposts: boolean,
history: { action: string, push: (string) => void, replace: (string) => void },
claimSearchByQuery: { [string]: Array<string> },
fetchingClaimSearchByQuery: { [string]: boolean },
claimsByUri: { [string]: any },
liveLivestreamsFirst?: boolean,
livestreamMap?: { [string]: any },
showNoSourceClaims?: boolean,
renderProperties?: (Claim) => ?Node,
fetchViewCount?: boolean,
// claim search options are below
tags: Array<string>,
blockedUris: Array<string>,
mutedUris: Array<string>,
claimIds?: Array<string>,
channelIds?: Array<string>,
pageSize: number,
@@ -111,11 +108,17 @@ type Props = {
limitClaimsPerChannel?: number,
hasSource?: boolean,
hasNoSource?: boolean,
renderProperties?: (Claim) => ?Node,
liveLivestreamsFirst?: boolean,
livestreamMap?: { [string]: any },
pinUrls?: Array<string>,
showNoSourceClaims?: boolean,
// --- select ---
claimSearchByQuery: { [string]: Array<string> },
claimsByUri: { [string]: any },
fetchingClaimSearchByQuery: { [string]: boolean },
showNsfw: boolean,
hideReposts: boolean,
mutedUris: Array<string>,
blockedUris: Array<string>,
// --- perform ---
doClaimSearch: ({}) => void,
doFetchViewCount: (claimIdCsv: string) => void,
};
function ClaimTilesDiscover(props: Props) {
@@ -125,6 +128,7 @@ function ClaimTilesDiscover(props: Props) {
claimsByUri,
showNsfw,
hideReposts,
fetchViewCount,
// Below are options to pass that are forwarded to claim_search
tags,
channelIds,
@@ -149,6 +153,7 @@ function ClaimTilesDiscover(props: Props) {
pinUrls,
prefixUris,
showNoSourceClaims,
doFetchViewCount,
} = props;
const { location } = useHistory();
@@ -159,6 +164,12 @@ function ClaimTilesDiscover(props: Props) {
new Set(mutedUris.concat(blockedUris).map((uri) => splitBySeparator(uri)[1]))
);
const liveUris = [];
let streamTypesParam;
if (streamTypes) {
streamTypesParam = streamTypes;
} else if (SIMPLE_SITE && !hasNoSource && streamTypes !== null) {
streamTypesParam = [CS.FILE_VIDEO, CS.FILE_AUDIO];
}
const [prevUris, setPrevUris] = React.useState([]);
@@ -182,7 +193,7 @@ function ClaimTilesDiscover(props: Props) {
has_no_source?: boolean,
} = {
page_size: pageSize,
claim_type: claimType || undefined,
claim_type: claimType || ['stream', 'repost', 'channel'],
// no_totals makes it so the sdk doesn't have to calculate total number pages for pagination
// it's faster, but we will need to remove it if we start using total_pages
no_totals: true,
@@ -192,8 +203,7 @@ function ClaimTilesDiscover(props: Props) {
channel_ids: channelIds || [],
not_channel_ids: mutedAndBlockedChannelIds,
order_by: orderBy || ['trending_group', 'trending_mixed'],
stream_types:
streamTypes === null ? undefined : SIMPLE_SITE && !hasNoSource ? [CS.FILE_VIDEO, CS.FILE_AUDIO] : undefined,
stream_types: streamTypesParam,
};
if (ENABLE_NO_SOURCE_CLAIMS && hasNoSource) {
@@ -264,30 +274,6 @@ function ClaimTilesDiscover(props: Props) {
}
}
React.useEffect(() => {
if (shouldPerformSearch) {
const searchOptions = JSON.parse(optionsStringForEffect);
doClaimSearch(searchOptions);
if (liveLivestreamsFirst) {
doClaimSearch(getLivestreamOnlyOptions(searchOptions));
}
}
}, [doClaimSearch, shouldPerformSearch, optionsStringForEffect, liveLivestreamsFirst]);
React.useEffect(() => {
if (JSON.stringify(prevUris) !== JSON.stringify(uris) && !shouldPerformSearch) {
setPrevUris(uris);
}
}, [shouldPerformSearch, prevUris, uris]);
const resolveLive = (index) => {
if (liveLivestreamsFirst && livestreamMap && index < liveUris.length) {
return true;
}
return undefined;
};
const modifiedUris = uris ? uris.slice() : [];
const fixUris = pinUrls || [];
@@ -302,6 +288,60 @@ function ClaimTilesDiscover(props: Props) {
modifiedUris.splice(2, 0, ...fixUris);
}
// **************************************************************************
// **************************************************************************
function resolveLive(index) {
if (liveLivestreamsFirst && livestreamMap && index < liveUris.length) {
return true;
}
return undefined;
}
function fetchViewCountForUris(uris) {
const claimIds = [];
if (uris) {
uris.forEach((uri) => {
if (claimsByUri[uri]) {
claimIds.push(claimsByUri[uri].claim_id);
}
});
}
if (claimIds.length > 0) {
doFetchViewCount(claimIds.join(','));
}
}
// **************************************************************************
// **************************************************************************
React.useEffect(() => {
if (shouldPerformSearch) {
const searchOptions = JSON.parse(optionsStringForEffect);
doClaimSearch(searchOptions);
if (liveLivestreamsFirst) {
doClaimSearch(getLivestreamOnlyOptions(searchOptions));
}
}
}, [doClaimSearch, shouldPerformSearch, optionsStringForEffect, liveLivestreamsFirst]);
React.useEffect(() => {
if (JSON.stringify(prevUris) !== JSON.stringify(uris) && !shouldPerformSearch) {
// Stash new results for next render cycle:
setPrevUris(uris);
// Fetch view count:
if (fetchViewCount) {
fetchViewCountForUris(uris);
}
}
}, [shouldPerformSearch, prevUris, uris]); // eslint-disable-line react-hooks/exhaustive-deps
// **************************************************************************
// **************************************************************************
return (
<ul className="claim-grid">
{modifiedUris && modifiedUris.length
+38 -9
View File
@@ -10,21 +10,50 @@ import {
import { makeSelectCostInfoForUri } from 'lbryinc';
import { doToast } from 'redux/actions/notifications';
import { doOpenModal } from 'redux/actions/app';
import { selectListShuffle } from 'redux/selectors/content';
import { doPlayUri, doSetPlayingUri, doToggleShuffleList, doToggleLoopList } from 'redux/actions/content';
import CollectionActions from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
myChannels: selectMyChannelClaims(state),
claimIsPending: makeSelectClaimIsPending(props.uri)(state),
isMyCollection: makeSelectCollectionIsMine(props.collectionId)(state),
collectionHasEdits: Boolean(makeSelectEditedCollectionForId(props.collectionId)(state)),
});
const select = (state, props) => {
let firstItem;
const collectionUrls = props.collectionUrls;
if (collectionUrls) {
// this will help play the first valid claim in a list
// in case the first urls have been deleted
collectionUrls.map((url) => {
const claim = makeSelectClaimForUri(url)(state);
if (firstItem === undefined && claim) {
firstItem = claim.permanent_url;
}
});
}
const collectionId = props.collectionId;
const shuffleList = selectListShuffle(state);
const shuffle = shuffleList && shuffleList.collectionId === collectionId && shuffleList.newUrls;
const playNextUri = shuffle && shuffle[0];
const playNextClaim = makeSelectClaimForUri(playNextUri)(state);
return {
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
myChannels: selectMyChannelClaims(state),
claimIsPending: makeSelectClaimIsPending(props.uri)(state),
isMyCollection: makeSelectCollectionIsMine(collectionId)(state),
collectionHasEdits: Boolean(makeSelectEditedCollectionForId(collectionId)(state)),
firstItem,
playNextUri,
playNextClaim,
};
};
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
doToast: (options) => dispatch(doToast(options)),
doPlayUri: (uri) => dispatch(doPlayUri(uri)),
doSetPlayingUri: (uri) => dispatch(doSetPlayingUri({ uri })),
doToggleShuffleList: (collectionId, shuffle) => dispatch(doToggleShuffleList(undefined, collectionId, shuffle, true)),
doToggleLoopList: (collectionId, loop) => dispatch(doToggleLoopList(collectionId, loop)),
});
export default connect(select, perform)(CollectionActions);
+106 -42
View File
@@ -11,6 +11,8 @@ import { useHistory } from 'react-router';
import { EDIT_PAGE, PAGE_VIEW_QUERY } from 'page/collection/view';
import classnames from 'classnames';
import { ENABLE_FILE_REACTIONS } from 'config';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
import { formatLbryUrlForWeb } from 'util/url';
type Props = {
uri: string,
@@ -24,6 +26,14 @@ type Props = {
showInfo: boolean,
setShowInfo: (boolean) => void,
collectionHasEdits: boolean,
isBuiltin: boolean,
doToggleShuffleList: (string, boolean) => void,
doToggleLoopList: (string, boolean) => void,
playNextUri: string,
playNextClaim: StreamClaim,
doPlayUri: (string) => void,
doSetPlayingUri: (string) => void,
firstItem: string,
};
function CollectionActions(props: Props) {
@@ -37,61 +47,115 @@ function CollectionActions(props: Props) {
showInfo,
setShowInfo,
collectionHasEdits,
isBuiltin,
doToggleShuffleList,
doToggleLoopList,
playNextUri,
playNextClaim,
doPlayUri,
doSetPlayingUri,
firstItem,
} = props;
const [doShuffle, setDoShuffle] = React.useState(false);
const { push } = useHistory();
const isMobile = useIsMobile();
const claimId = claim && claim.claim_id;
const webShareable = true; // collections have cost?
const doPlay = React.useCallback(
(uri) => {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
const navigateUrl = formatLbryUrlForWeb(uri) + `?` + collectionParams.toString();
push(navigateUrl);
doSetPlayingUri(uri);
doPlayUri(uri);
},
[collectionId, push, doSetPlayingUri, doPlayUri]
);
React.useEffect(() => {
if (playNextClaim && doShuffle) {
setDoShuffle(false);
doPlay(playNextUri);
}
}, [doPlay, doShuffle, playNextClaim, playNextUri]);
const lhsSection = (
<>
{ENABLE_FILE_REACTIONS && uri && <FileReactions uri={uri} />}
{uri && <ClaimSupportButton uri={uri} fileAction />}
{/* TODO Add ClaimRepostButton component */}
{uri && (
<Button
className="button--file-action"
icon={ICONS.SHARE}
label={__('Share')}
title={__('Share')}
onClick={() => openModal(MODALS.SOCIAL_SHARE, { uri, webShareable })}
/>
<Button
className="button--file-action"
icon={ICONS.PLAY}
label={__('Play')}
title={__('Play')}
onClick={() => {
doToggleShuffleList(collectionId, false);
doToggleLoopList(collectionId, false);
doPlay(firstItem);
}}
/>
<Button
className="button--file-action"
icon={ICONS.SHUFFLE}
label={__('Shuffle Play')}
title={__('Shuffle Play')}
onClick={() => {
doToggleShuffleList(collectionId, true);
setDoShuffle(true);
}}
/>
{!isBuiltin && (
<>
{ENABLE_FILE_REACTIONS && uri && <FileReactions uri={uri} />}
{uri && <ClaimSupportButton uri={uri} fileAction />}
{/* TODO Add ClaimRepostButton component */}
{uri && (
<Button
className="button--file-action"
icon={ICONS.SHARE}
label={__('Share')}
title={__('Share')}
onClick={() => openModal(MODALS.SOCIAL_SHARE, { uri, webShareable })}
/>
)}
</>
)}
</>
);
const rhsSection = (
<>
{isMyCollection && (
<Button
title={uri ? __('Update') : __('Publish')}
label={uri ? __('Update') : __('Publish')}
className={classnames('button--file-action')}
onClick={() => push(`?${PAGE_VIEW_QUERY}=${EDIT_PAGE}`)}
icon={ICONS.PUBLISH}
iconColor={collectionHasEdits && 'red'}
iconSize={18}
disabled={claimIsPending}
/>
)}
{isMyCollection && (
<Button
className={classnames('button--file-action')}
title={__('Delete List')}
onClick={() => openModal(MODALS.COLLECTION_DELETE, { uri, collectionId, redirect: `/$/${PAGES.LISTS}` })}
icon={ICONS.DELETE}
iconSize={18}
description={__('Delete List')}
disabled={claimIsPending}
/>
)}
{!isMyCollection && (
<Button
title={__('Report content')}
className="button--file-action"
icon={ICONS.REPORT}
navigate={`/$/${PAGES.REPORT_CONTENT}?claimId=${claimId}`}
/>
)}
{!isBuiltin &&
(isMyCollection ? (
<>
<Button
title={uri ? __('Update') : __('Publish')}
label={uri ? __('Update') : __('Publish')}
className={classnames('button--file-action')}
onClick={() => push(`?${PAGE_VIEW_QUERY}=${EDIT_PAGE}`)}
icon={ICONS.PUBLISH}
iconColor={collectionHasEdits && 'red'}
iconSize={18}
disabled={claimIsPending}
/>
<Button
className={classnames('button--file-action')}
title={__('Delete List')}
onClick={() => openModal(MODALS.COLLECTION_DELETE, { uri, collectionId, redirect: `/$/${PAGES.LISTS}` })}
icon={ICONS.DELETE}
iconSize={18}
description={__('Delete List')}
disabled={claimIsPending}
/>
</>
) : (
<Button
title={__('Report content')}
className="button--file-action"
icon={ICONS.REPORT}
navigate={`/$/${PAGES.REPORT_CONTENT}?claimId=${claimId}`}
/>
))}
</>
);
+15 -2
View File
@@ -7,10 +7,18 @@ import {
makeSelectClaimForUri,
makeSelectClaimIsMine,
} from 'lbry-redux';
import { selectPlayingUri, selectListLoop, selectListShuffle } from 'redux/selectors/content';
import { doToggleLoopList, doToggleShuffleList } from 'redux/actions/content';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri)(state);
const playingUri = selectPlayingUri(state);
const playingUrl = playingUri && playingUri.uri;
const claim = makeSelectClaimForUri(playingUrl)(state);
const url = claim && claim.permanent_url;
const loopList = selectListLoop(state);
const loop = loopList && loopList.collectionId === props.id && loopList.loop;
const shuffleList = selectListShuffle(state);
const shuffle = shuffleList && shuffleList.collectionId === props.id && shuffleList.newUrls;
return {
url,
@@ -18,7 +26,12 @@ const select = (state, props) => {
collectionUrls: makeSelectUrlsForCollectionId(props.id)(state),
collectionName: makeSelectNameForCollectionId(props.id)(state),
isMine: makeSelectClaimIsMine(url)(state),
loop,
shuffle,
};
};
export default connect(select)(CollectionContent);
export default connect(select, {
doToggleLoopList,
doToggleShuffleList,
})(CollectionContent);
+38 -9
View File
@@ -15,23 +15,52 @@ type Props = {
collectionUrls: Array<Claim>,
collectionName: string,
collection: any,
loop: boolean,
shuffle: boolean,
doToggleLoopList: (string, boolean) => void,
doToggleShuffleList: (string, string, boolean) => void,
createUnpublishedCollection: (string, Array<any>, ?string) => void,
};
export default function CollectionContent(props: Props) {
const { collectionUrls, collectionName, id, url } = props;
const { collectionUrls, collectionName, id, url, loop, shuffle, doToggleLoopList, doToggleShuffleList } = props;
return (
<Card
isBodyList
className="file-page__recommended"
className="file-page__recommended-collection"
title={
<span>
<Icon
icon={(id === COLLECTIONS_CONSTS.WATCH_LATER_ID && ICONS.TIME) ||
(id === COLLECTIONS_CONSTS.FAVORITES_ID && ICONS.STAR) || ICONS.STACK}
className="icon--margin-right" />
{collectionName}
</span>
<>
<span className="file-page__recommended-collection__row">
<Icon
icon={
(id === COLLECTIONS_CONSTS.WATCH_LATER_ID && ICONS.TIME) ||
(id === COLLECTIONS_CONSTS.FAVORITES_ID && ICONS.STAR) ||
ICONS.STACK
}
className="icon--margin-right"
/>
{collectionName}
</span>
<span className="file-page__recommended-collection__row">
<Button
button="alt"
title="Loop"
icon={ICONS.REPEAT}
iconColor={loop && 'blue'}
className="button--file-action"
onClick={() => doToggleLoopList(id, !loop)}
/>
<Button
button="alt"
title="Shuffle"
icon={ICONS.SHUFFLE}
iconColor={shuffle && 'blue'}
className="button--file-action"
onClick={() => doToggleShuffleList(url, id, !shuffle)}
/>
</span>
</>
}
titleActions={
<div className="card__title-actions--link">
+10
View File
@@ -1,11 +1,19 @@
import { connect } from 'react-redux';
import { doCollectionEdit, makeSelectNameForCollectionId, doCollectionDelete } from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { selectListShuffle } from 'redux/selectors/content';
import { doSetPlayingUri, doToggleShuffleList } from 'redux/actions/content';
import CollectionMenuList from './view';
const select = (state, props) => {
const collectionId = props.collectionId;
const shuffleList = selectListShuffle(state);
const shuffle = shuffleList && shuffleList.collectionId === collectionId && shuffleList.newUrls;
const playNextUri = shuffle && shuffle[0];
return {
collectionName: makeSelectNameForCollectionId(props.collectionId)(state),
playNextUri,
};
};
@@ -13,4 +21,6 @@ export default connect(select, {
doCollectionEdit,
doOpenModal,
doCollectionDelete,
doSetPlayingUri,
doToggleShuffleList,
})(CollectionMenuList);
+39 -2
View File
@@ -7,19 +7,44 @@ import { Menu, MenuButton, MenuList, MenuItem } from '@reach/menu-button';
import Icon from 'component/common/icon';
import * as PAGES from 'constants/pages';
import { useHistory } from 'react-router';
import { formatLbryUrlForWeb } from 'util/url';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
type Props = {
inline?: boolean,
doOpenModal: (string, {}) => void,
collectionName?: string,
collectionId: string,
playNextUri: string,
doSetPlayingUri: ({ uri: ?string }) => void,
doToggleShuffleList: (string, string, boolean, boolean) => void,
};
function CollectionMenuList(props: Props) {
const { inline = false, collectionId, collectionName, doOpenModal } = props;
const {
inline = false,
collectionId,
collectionName,
doOpenModal,
playNextUri,
doSetPlayingUri,
doToggleShuffleList,
} = props;
const [doShuffle, setDoShuffle] = React.useState(false);
const { push } = useHistory();
React.useEffect(() => {
if (playNextUri && doShuffle) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
const navigateUrl = formatLbryUrlForWeb(playNextUri) + `?` + collectionParams.toString();
setDoShuffle(false);
doSetPlayingUri({ uri: playNextUri });
push(navigateUrl);
}
}, [push, doSetPlayingUri, collectionId, playNextUri, doShuffle]);
return (
<Menu>
<MenuButton
@@ -35,9 +60,21 @@ function CollectionMenuList(props: Props) {
{collectionId && collectionName && (
<>
<MenuItem className="comment__menu-option" onSelect={() => push(`/$/${PAGES.LIST}/${collectionId}`)}>
<div className="menu__link">
<a className="menu__link" href={`/$/${PAGES.LIST}/${collectionId}`}>
<Icon aria-hidden icon={ICONS.VIEW} />
{__('View List')}
</a>
</MenuItem>
<MenuItem
className="comment__menu-option"
onSelect={() => {
doToggleShuffleList('', collectionId, true, true);
setDoShuffle(true);
}}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SHUFFLE} />
{__('Shuffle Play')}
</div>
</MenuItem>
<MenuItem
+1 -1
View File
@@ -9,7 +9,7 @@ import CollectionsListMine from './view';
const select = (state) => ({
builtinCollections: selectBuiltinCollections(state),
publishedPlaylists: selectMyPublishedPlaylistCollections(state),
publishedCollections: selectMyPublishedPlaylistCollections(state),
unpublishedCollections: selectMyUnpublishedCollections(state),
// savedCollections: selectSavedCollections(state),
});
+91 -51
View File
@@ -7,49 +7,79 @@ import { COLLECTIONS_CONSTS } from 'lbry-redux';
import Icon from 'component/common/icon';
import * as ICONS from 'constants/icons';
import * as PAGES from 'constants/pages';
import * as KEYCODES from 'constants/keycodes';
import Yrbl from 'component/yrbl';
import usePersistedState from 'effects/use-persisted-state';
import Card from 'component/common/card';
import classnames from 'classnames';
import { FormField, Form } from 'component/common/form';
type Props = {
builtinCollections: CollectionGroup,
publishedCollections: CollectionGroup,
publishedPlaylists: CollectionGroup,
unpublishedCollections: CollectionGroup,
// savedCollections: CollectionGroup,
};
const ALL = 'All';
const PRIVATE = 'Private';
const PUBLIC = 'Public';
const COLLECTION_FILTERS = [ALL, PRIVATE, PUBLIC];
export default function CollectionsListMine(props: Props) {
const {
builtinCollections,
publishedPlaylists,
publishedCollections,
unpublishedCollections,
// savedCollections, these are resolved on startup from sync'd claimIds or urls
} = props;
const builtinCollectionsList = (Object.values(builtinCollections || {}): any);
const unpublishedCollectionsList = (Object.keys(unpublishedCollections || {}): any);
const publishedList = (Object.keys(publishedPlaylists || {}): any);
const publishedList = (Object.keys(publishedCollections || {}): any);
const hasCollections = unpublishedCollectionsList.length || publishedList.length;
const [filterType, setFilterType] = React.useState(ALL);
const [searchText, setSearchText] = React.useState('');
let collectionsToShow = [];
if (filterType === ALL) {
collectionsToShow = unpublishedCollectionsList.concat(publishedList);
} else if (filterType === PRIVATE) {
collectionsToShow = unpublishedCollectionsList;
} else if (filterType === PUBLIC) {
collectionsToShow = publishedList;
}
let filteredCollections;
if (searchText && collectionsToShow) {
filteredCollections = collectionsToShow.filter((id) => {
return (
(unpublishedCollections[id] &&
unpublishedCollections[id].name.toLocaleLowerCase().includes(searchText.toLocaleLowerCase())) ||
(publishedCollections[id] &&
publishedCollections[id].name.toLocaleLowerCase().includes(searchText.toLocaleLowerCase()))
);
});
} else {
filteredCollections = collectionsToShow || [];
}
const watchLater = builtinCollectionsList.find((list) => list.id === COLLECTIONS_CONSTS.WATCH_LATER_ID);
const favorites = builtinCollectionsList.find((list) => list.id === COLLECTIONS_CONSTS.FAVORITES_ID);
const builtin = [watchLater, favorites];
const [showHelp, setShowHelp] = usePersistedState('livestream-help-seen', true);
function escapeListener(e: SyntheticKeyboardEvent<*>) {
if (e.keyCode === KEYCODES.ESCAPE) {
e.preventDefault();
setSearchText('');
}
}
const helpText = (
<div className="section__subtitle">
<p>{__(`Everyone starts with 2 private lists - Watch Later and Favorites.`)}</p>
<p>{__(`Add content to existing lists or new lists from content pages or content previews.`)}</p>
<p>
{__(
`By default, lists are private. You can edit them and later publish them from the Lists page or the Publish context menu on this page. Similar to uploads, small blockchain fees apply.`
)}
</p>
</div>
);
function onTextareaFocus() {
window.addEventListener('keydown', escapeListener);
}
function onTextareaBlur() {
window.removeEventListener('keydown', escapeListener);
}
return (
<>
{builtin.map((list: Collection) => {
@@ -68,9 +98,14 @@ export default function CollectionsListMine(props: Props) {
<span className="claim-grid__title-span">
{__(`${list.name}`)}
<div className="claim-grid__title--empty">
<Icon className="icon--margin-right"
icon={(list.id === COLLECTIONS_CONSTS.WATCH_LATER_ID && ICONS.TIME) ||
(list.id === COLLECTIONS_CONSTS.FAVORITES_ID && ICONS.STAR) || ICONS.STACK} />
<Icon
className="icon--margin-right"
icon={
(list.id === COLLECTIONS_CONSTS.WATCH_LATER_ID && ICONS.TIME) ||
(list.id === COLLECTIONS_CONSTS.FAVORITES_ID && ICONS.STAR) ||
ICONS.STACK
}
/>
{itemUrls.length}
</div>
</span>
@@ -91,52 +126,57 @@ export default function CollectionsListMine(props: Props) {
);
})}
<div className="claim-grid__wrapper">
<div className="claim-grid__header claim-grid__header--between section">
<div className="claim-grid__header section">
<h1 className="claim-grid__title">
{__('Playlists')}
{!hasCollections && (
<div className="claim-grid__title--empty">{__('(Empty) --[indicates empty playlist]--')}</div>
)}
</h1>
<Button button="link" onClick={() => setShowHelp(!showHelp)} label={__('How does this work?')} />
</div>
{showHelp && (
<Card
titleActions={<Button button="close" icon={ICONS.REMOVE} onClick={() => setShowHelp(false)} />}
title={__('Introducing Lists')}
actions={helpText}
/>
)}
<div className="section__header--actions">
<div className="claim-search__wrapper">
<div className="claim-search__menu-group">
{COLLECTION_FILTERS.map((value) => (
<Button
label={__(value)}
key={value}
button="alt"
onClick={() => setFilterType(value)}
className={classnames('button-toggle', {
'button-toggle--active': filterType === value,
})}
/>
))}
</div>
</div>
<Form onSubmit={() => {}} className="wunderbar--inline">
<Icon icon={ICONS.SEARCH} />
<FormField
onFocus={onTextareaFocus}
onBlur={onTextareaBlur}
className="wunderbar__input--inline"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
type="text"
placeholder={__('Search')}
/>
</Form>
</div>
{Boolean(hasCollections) && (
<div
className={classnames({
section: showHelp,
})}
>
<div>
{/* TODO: fix above spacing hack */}
<div className="claim-grid">
{unpublishedCollectionsList &&
unpublishedCollectionsList.length > 0 &&
unpublishedCollectionsList.map((key) => (
<CollectionPreviewTile tileLayout collectionId={key} key={key} />
))}
{publishedList &&
publishedList.length > 0 &&
publishedList.map((key) => <CollectionPreviewTile tileLayout collectionId={key} key={key} />)}
{filteredCollections &&
filteredCollections.length > 0 &&
filteredCollections.map((key) => <CollectionPreviewTile tileLayout collectionId={key} key={key} />)}
{!filteredCollections.length && <div className="empty main--empty">{__('No matching collections')}</div>}
</div>
</div>
)}
{!hasCollections && (
<div className="main--empty">
<Yrbl
type={'sad'}
title={__('You have no lists yet. Better start hoarding!')}
// actions={
// <div className="section__actions">
// <Button button="primary" label={__('View Content')} onClick={() => setViewBlockedChannel(true)} />
// </div>
// }
/>
<Yrbl type={'sad'} title={__('You have no lists yet. Better start hoarding!')} />
</div>
)}
</div>
+6 -1
View File
@@ -10,7 +10,11 @@ import { makeSelectChannelIsMuted } from 'redux/selectors/blocked';
import { doToast } from 'redux/actions/notifications';
import { doSetPlayingUri } from 'redux/actions/content';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectLinkedCommentAncestors, makeSelectOthersReactionsForComment } from 'redux/selectors/comments';
import {
selectLinkedCommentAncestors,
makeSelectOthersReactionsForComment,
makeSelectTotalReplyPagesForParentId,
} from 'redux/selectors/comments';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import { selectPlayingUri } from 'redux/selectors/content';
import Comment from './view';
@@ -31,6 +35,7 @@ const select = (state, props) => {
playingUri: selectPlayingUri(state),
stakedLevel: makeSelectStakedLevelForChannelUri(props.authorUri)(state),
linkedCommentAncestors: selectLinkedCommentAncestors(state),
totalReplyPages: makeSelectTotalReplyPagesForParentId(props.commentId)(state),
};
};
+47 -14
View File
@@ -1,6 +1,8 @@
// @flow
import * as ICONS from 'constants/icons';
import * as PAGES from 'constants/pages';
import * as KEYCODES from 'constants/keycodes';
import { COMMENT_HIGHLIGHTED } from 'constants/classnames';
import { SORT_BY, COMMENT_PAGE_SIZE_REPLIES } from 'constants/comment';
import { FF_MAX_CHARS_IN_COMMENT } from 'constants/form-field';
import { SITE_NAME, SIMPLE_SITE, ENABLE_COMMENT_REACTIONS } from 'config';
@@ -10,6 +12,7 @@ import DateTime from 'component/dateTime';
import Button from 'component/button';
import Expandable from 'component/expandable';
import MarkdownPreview from 'component/common/markdown-preview';
import Tooltip from 'component/common/tooltip';
import ChannelThumbnail from 'component/channelThumbnail';
import { Menu, MenuButton } from '@reach/menu-button';
import Icon from 'component/common/icon';
@@ -40,6 +43,7 @@ type Props = {
commentIsMine: boolean, // if this comment was signed by an owned channel
updateComment: (string, string) => void,
fetchReplies: (string, string, number, number, number) => void,
totalReplyPages: number,
commentModBlock: (string) => void,
linkedCommentId?: string,
linkedCommentAncestors: { [string]: Array<string> },
@@ -59,11 +63,15 @@ type Props = {
stakedLevel: number,
supportAmount: number,
numDirectReplies: number,
isFiat: boolean
isModerator: boolean,
isGlobalMod: boolean,
isFiat: boolean,
supportDisabled: boolean,
setQuickReply: (any) => void,
quickReply: any,
};
const LENGTH_TO_COLLAPSE = 300;
const ESCAPE_KEY = 27;
function Comment(props: Props) {
const {
@@ -79,6 +87,7 @@ function Comment(props: Props) {
commentId,
updateComment,
fetchReplies,
totalReplyPages,
linkedCommentId,
linkedCommentAncestors,
commentingEnabled,
@@ -92,7 +101,12 @@ function Comment(props: Props) {
stakedLevel,
supportAmount,
numDirectReplies,
isModerator,
isGlobalMod,
isFiat,
supportDisabled,
setQuickReply,
quickReply,
} = props;
const {
@@ -105,8 +119,6 @@ function Comment(props: Props) {
const [isEditing, setEditing] = useState(false);
const [editedMessage, setCommentValue] = useState(message);
const [charCount, setCharCount] = useState(editedMessage.length);
// used for controlling the visibility of the menu icon
const [mouseIsHovering, setMouseHover] = useState(false);
const [showReplies, setShowReplies] = useState(false);
const [page, setPage] = useState(0);
const [advancedEditor] = usePersistedState('comment-editor-mode', false);
@@ -145,7 +157,7 @@ function Comment(props: Props) {
// a user will try and press the escape key to cancel editing their comment
const handleEscape = (event) => {
if (event.keyCode === ESCAPE_KEY) {
if (event.keyCode === KEYCODES.ESCAPE) {
setEditing(false);
}
};
@@ -178,6 +190,7 @@ function Comment(props: Props) {
function handleSubmit() {
updateComment(commentId, editedMessage);
if (setQuickReply) setQuickReply({ ...quickReply, comment_id: commentId, comment: editedMessage });
setEditing(false);
}
@@ -205,12 +218,10 @@ function Comment(props: Props) {
'comment--superchat': supportAmount > 0,
})}
id={commentId}
onMouseOver={() => setMouseHover(true)}
onMouseOut={() => setMouseHover(false)}
>
<div
className={classnames('comment__content', {
'comment--highlighted': linkedCommentId && linkedCommentId === commentId,
[COMMENT_HIGHLIGHTED]: linkedCommentId && linkedCommentId === commentId,
'comment--slimed': slimedToDeath && !displayDeadComment,
})}
>
@@ -225,6 +236,22 @@ function Comment(props: Props) {
<div className="comment__body-container">
<div className="comment__meta">
<div className="comment__meta-information">
{isGlobalMod && (
<Tooltip label={__('Admin')}>
<span className="comment__badge comment__badge--global-mod">
<Icon icon={ICONS.BADGE_MOD} size={20} />
</span>
</Tooltip>
)}
{isModerator && (
<Tooltip label={__('Moderator')}>
<span className="comment__badge comment__badge--mod">
<Icon icon={ICONS.BADGE_MOD} size={20} />
</span>
</Tooltip>
)}
{!author ? (
<span className="comment__author">{__('Anonymous')}</span>
) : (
@@ -256,11 +283,7 @@ function Comment(props: Props) {
<div className="comment__menu">
<Menu>
<MenuButton className="menu__button">
<Icon
size={18}
className={mouseIsHovering ? 'comment__menu-icon--hovering' : 'comment__menu-icon'}
icon={ICONS.MORE_VERTICAL}
/>
<Icon size={18} icon={ICONS.MORE_VERTICAL} />
</MenuButton>
<CommentMenuList
uri={uri}
@@ -270,6 +293,8 @@ function Comment(props: Props) {
authorUri={authorUri}
commentIsMine={commentIsMine}
handleEditComment={handleEditComment}
supportAmount={supportAmount}
setQuickReply={setQuickReply}
/>
</Menu>
</div>
@@ -351,13 +376,19 @@ function Comment(props: Props) {
setPage(1);
}
}}
icon={ICONS.DOWN}
/>
</div>
)}
{numDirectReplies > 0 && showReplies && (
<div className="comment__actions">
<Button label={__('Hide replies')} button="link" onClick={() => setShowReplies(false)} />
<Button
label={__('Hide replies')}
button="link"
onClick={() => setShowReplies(false)}
icon={ICONS.UP}
/>
</div>
)}
@@ -373,6 +404,7 @@ function Comment(props: Props) {
onCancelReplying={() => {
setReplying(false);
}}
supportDisabled={supportDisabled}
/>
)}
</>
@@ -389,6 +421,7 @@ function Comment(props: Props) {
linkedCommentId={linkedCommentId}
numDirectReplies={numDirectReplies}
onShowMore={() => setPage(page + 1)}
hasMore={page < totalReplyPages}
/>
)}
</li>
+17 -4
View File
@@ -7,30 +7,43 @@ import {
doSendTip,
} from 'lbry-redux';
import { doOpenModal, doSetActiveChannel } from 'redux/actions/app';
import { doCommentCreate } from 'redux/actions/comments';
import { doCommentCreate, doFetchCreatorSettings, doCommentById } from 'redux/actions/comments';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import { makeSelectCommentsDisabledForUri } from 'redux/selectors/comments';
import { selectSettingsByChannelId } from 'redux/selectors/comments';
import { CommentCreate } from './view';
import { doToast } from 'redux/actions/notifications';
const select = (state, props) => ({
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
commentsDisabledBySettings: makeSelectCommentsDisabledForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
channels: selectMyChannelClaims(state),
isFetchingChannels: selectFetchingMyChannels(state),
activeChannelClaim: selectActiveChannelClaim(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
settingsByChannelId: selectSettingsByChannelId(state),
});
const perform = (dispatch, ownProps) => ({
createComment: (comment, claimId, parentId, txid, payment_intent_id, environment) =>
dispatch(doCommentCreate(comment, claimId, parentId, ownProps.uri, ownProps.livestream, txid, payment_intent_id, environment)),
dispatch(
doCommentCreate(
comment,
claimId,
parentId,
ownProps.uri,
ownProps.livestream,
txid,
payment_intent_id,
environment
)
),
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
setActiveChannel: (claimId) => dispatch(doSetActiveChannel(claimId)),
sendTip: (params, callback, errorCallback) => dispatch(doSendTip(params, false, callback, errorCallback, false)),
doToast: (options) => dispatch(doToast(options)),
doFetchCreatorSettings: (channelClaimId) => dispatch(doFetchCreatorSettings(channelClaimId)),
fetchComment: (commentId) => dispatch(doCommentById(commentId, false)),
});
export default connect(select, perform)(CommentCreate);
+232 -98
View File
@@ -1,11 +1,13 @@
// @flow
import type { ElementRef } from 'react';
import { SIMPLE_SITE, STRIPE_PUBLIC_KEY } from 'config';
import { SIMPLE_SITE } from 'config';
import * as PAGES from 'constants/pages';
import * as ICONS from 'constants/icons';
import * as KEYCODES from 'constants/keycodes';
import React from 'react';
import classnames from 'classnames';
import { FormField, Form } from 'component/common/form';
import Icon from 'component/common/icon';
import Button from 'component/button';
import SelectChannel from 'component/selectChannel';
import usePersistedState from 'effects/use-persisted-state';
@@ -14,16 +16,14 @@ import { useHistory } from 'react-router';
import WalletTipAmountSelector from 'component/walletTipAmountSelector';
import CreditAmount from 'component/common/credit-amount';
import ChannelThumbnail from 'component/channelThumbnail';
import I18nMessage from 'component/i18nMessage';
import UriIndicator from 'component/uriIndicator';
import Empty from 'component/common/empty';
import { getChannelIdFromClaim } from 'util/claim';
import { Lbryio } from 'lbryinc';
let stripeEnvironment = 'test';
// if the key contains pk_live it's a live key
// update the environment for the calls to the backend to indicate which environment to hit
if (STRIPE_PUBLIC_KEY.indexOf('pk_live') > -1) {
stripeEnvironment = 'live';
}
import { getStripeEnvironment } from 'util/stripe';
let stripeEnvironment = getStripeEnvironment();
const TAB_FIAT = 'TabFiat';
const TAB_LBC = 'TabLBC';
@@ -32,7 +32,6 @@ type Props = {
uri: string,
claim: StreamClaim,
createComment: (string, string, string, ?string, ?string, ?string) => Promise<any>,
commentsDisabledBySettings: boolean,
channels: ?Array<ChannelClaim>,
onDoneReplying?: () => void,
onCancelReplying?: () => void,
@@ -42,18 +41,24 @@ type Props = {
isReply: boolean,
activeChannel: string,
activeChannelClaim: ?ChannelClaim,
bottom: boolean,
livestream?: boolean,
embed?: boolean,
toast: (string) => void,
claimIsMine: boolean,
sendTip: ({}, (any) => void, (any) => void) => void,
doToast: ({ message: string }) => void,
disabled: boolean,
supportDisabled: boolean,
doFetchCreatorSettings: (channelId: string) => Promise<any>,
settingsByChannelId: { [channelId: string]: PerChannelSettings },
setQuickReply: (any) => void,
fetchComment: (commentId: string) => Promise<any>,
shouldFetchComment: boolean,
};
export function CommentCreate(props: Props) {
const {
createComment,
commentsDisabledBySettings,
claim,
channels,
onDoneReplying,
@@ -63,13 +68,20 @@ export function CommentCreate(props: Props) {
isReply,
parentId,
activeChannelClaim,
bottom,
livestream,
embed,
claimIsMine,
sendTip,
doToast,
doFetchCreatorSettings,
settingsByChannelId,
supportDisabled,
setQuickReply,
fetchComment,
shouldFetchComment,
} = props;
const buttonref: ElementRef<any> = React.useRef();
const buttonRef: ElementRef<any> = React.useRef();
const {
push,
location: { pathname },
@@ -77,7 +89,7 @@ export function CommentCreate(props: Props) {
const [isSubmitting, setIsSubmitting] = React.useState(false);
const [commentFailure, setCommentFailure] = React.useState(false);
const [successTip, setSuccessTip] = React.useState({ txid: undefined, tipAmount: undefined });
const { claim_id: claimId } = claim;
const claimId = claim && claim.claim_id;
const [isSupportComment, setIsSupportComment] = React.useState();
const [isReviewingSupportComment, setIsReviewingSupportComment] = React.useState();
const [tipAmount, setTipAmount] = React.useState(1);
@@ -85,13 +97,54 @@ export function CommentCreate(props: Props) {
const [advancedEditor, setAdvancedEditor] = usePersistedState('comment-editor-mode', false);
const hasChannels = channels && channels.length;
const charCount = commentValue.length;
const [activeTab, setActiveTab] = React.useState('');
const [tipError, setTipError] = React.useState();
const disabled = isSubmitting || !activeChannelClaim || !commentValue.length;
const [deletedComment, setDeletedComment] = React.useState(false);
const disabled = deletedComment || isSubmitting || isFetchingChannels || !commentValue.length;
const [shouldDisableReviewButton, setShouldDisableReviewButton] = React.useState();
const channelId = getChannelIdFromClaim(claim);
const channelSettings = channelId ? settingsByChannelId[channelId] : undefined;
const minSuper = (channelSettings && channelSettings.min_tip_amount_super_chat) || 0;
const minTip = (channelSettings && channelSettings.min_tip_amount_comment) || 0;
const minAmount = minTip || minSuper || 0;
const minAmountMet = minAmount === 0 || tipAmount >= minAmount;
// Fetch top-level comments to identify if it has been deleted and can reply to it
React.useEffect(() => {
if (shouldFetchComment && fetchComment) {
fetchComment(parentId).then((result) => {
setDeletedComment(String(result).includes('Error'));
});
}
}, [fetchComment, shouldFetchComment, parentId]);
const minAmountRef = React.useRef(minAmount);
minAmountRef.current = minAmount;
const MinAmountNotice = minAmount ? (
<div className="help--notice comment--min-amount-notice">
<I18nMessage tokens={{ lbc: <CreditAmount noFormat amount={minAmount} /> }}>
{minTip ? 'Comment min: %lbc%' : minSuper ? 'HyperChat min: %lbc%' : ''}
</I18nMessage>
<Icon
customTooltipText={
minTip
? __('This channel requires a minimum tip for each comment.')
: minSuper
? __('This channel requires a minimum amount for HyperChats to be visible.')
: ''
}
className="icon--help"
icon={ICONS.HELP}
tooltip
size={16}
/>
</div>
) : null;
// **************************************************************************
// Functions
// **************************************************************************
function handleCommentChange(event) {
let commentValue;
@@ -105,10 +158,9 @@ export function CommentCreate(props: Props) {
}
function altEnterListener(e: SyntheticKeyboardEvent<*>) {
const KEYCODE_ENTER = 13;
if ((e.ctrlKey || e.metaKey) && e.keyCode === KEYCODE_ENTER) {
if ((livestream || e.ctrlKey || e.metaKey) && e.keyCode === KEYCODES.ENTER) {
e.preventDefault();
buttonref.current.click();
buttonRef.current.click();
}
}
@@ -131,6 +183,15 @@ export function CommentCreate(props: Props) {
return;
}
if (!channelId) {
doToast({
message: __('Unable to verify channel settings. Try refreshing the page.'),
isError: true,
});
return;
}
// if comment post didn't work, but tip was already made, try again to create comment
if (commentFailure && tipAmount === successTip.tipAmount) {
handleCreateComment(successTip.txid);
return;
@@ -138,6 +199,29 @@ export function CommentCreate(props: Props) {
setSuccessTip({ txid: undefined, tipAmount: undefined });
}
// !! Beware of stale closure when editing the then-block, including doSubmitTip().
doFetchCreatorSettings(channelId).then(() => {
const lockedMinAmount = minAmount; // value during closure.
const currentMinAmount = minAmountRef.current; // value from latest doFetchCreatorSettings().
if (lockedMinAmount !== currentMinAmount) {
doToast({
message: __('The creator just updated the minimum setting. Please revise or double-check your tip amount.'),
isError: true,
});
setIsReviewingSupportComment(false);
return;
}
doSubmitTip();
});
}
function doSubmitTip() {
if (!activeChannelClaim) {
return;
}
const params = {
amount: tipAmount,
claim_id: claimId,
@@ -147,7 +231,18 @@ export function CommentCreate(props: Props) {
const activeChannelName = activeChannelClaim && activeChannelClaim.name;
const activeChannelId = activeChannelClaim && activeChannelClaim.claim_id;
console.log(activeChannelClaim);
// setup variables for tip API
let channelClaimId, tipChannelName;
// if there is a signing channel it's on a file
if (claim.signing_channel) {
channelClaimId = claim.signing_channel.claim_id;
tipChannelName = claim.signing_channel.name;
// otherwise it's on the channel page
} else {
channelClaimId = claim.claim_id;
tipChannelName = claim.name;
}
setIsSubmitting(true);
@@ -162,6 +257,17 @@ export function CommentCreate(props: Props) {
setTimeout(() => {
handleCreateComment(txid);
}, 1500);
doToast({
message: __(
"You sent %tipAmount% LBRY Credits as a tip to %tipChannelName%, I'm sure they appreciate it!",
{
tipAmount: tipAmount, // force show decimal places
tipChannelName,
}
),
});
setSuccessTip({ txid, tipAmount });
},
() => {
@@ -170,28 +276,15 @@ export function CommentCreate(props: Props) {
}
);
} else {
// setup variables for tip API
let channelClaimId, tipChannelName;
// if there is a signing channel it's on a file
if (claim.signing_channel) {
channelClaimId = claim.signing_channel.claim_id;
tipChannelName = claim.signing_channel.name;
// otherwise it's on the channel page
} else {
channelClaimId = claim.claim_id;
tipChannelName = claim.name;
}
const sourceClaimId = claim.claim_id;
var roundedAmount = Math.round(tipAmount * 100) / 100;
const roundedAmount = Math.round(tipAmount * 100) / 100;
Lbryio.call(
'customer',
'tip',
{
amount: 100 * roundedAmount, // convert from dollars to cents
// round to deal with floating point precision
amount: Math.round(100 * roundedAmount), // convert from dollars to cents
creator_channel_name: tipChannelName, // creator_channel_name
creator_channel_claim_id: channelClaimId,
tipper_channel_name: activeChannelName,
@@ -204,8 +297,6 @@ export function CommentCreate(props: Props) {
'post'
)
.then((customerTipResponse) => {
console.log(customerTipResponse);
const paymentIntendId = customerTipResponse.payment_intent_id;
handleCreateComment(null, paymentIntendId, stripeEnvironment);
@@ -225,14 +316,14 @@ export function CommentCreate(props: Props) {
// handleCreateComment(null);
})
.catch(function (error) {
var displayError = 'Sorry, there was an error in processing your payment!';
if (error.message !== 'payment intent failed to confirm') {
displayError = error.message;
}
doToast({ message: displayError, isError: true });
.catch((error) => {
doToast({
message:
error.message !== 'payment intent failed to confirm'
? error.message
: 'Sorry, there was an error in processing your payment!',
isError: true,
});
});
}
}
@@ -249,6 +340,7 @@ export function CommentCreate(props: Props) {
createComment(commentValue, claimId, parentId, txid, payment_intent_id, environment)
.then((res) => {
setIsSubmitting(false);
if (setQuickReply) setQuickReply(res);
if (res && res.signature) {
setCommentValue('');
@@ -261,9 +353,15 @@ export function CommentCreate(props: Props) {
}
}
})
.catch((e) => {
.catch(() => {
setIsSubmitting(false);
setCommentFailure(true);
if (channelId) {
// It could be that the creator added a minimum tip setting.
// Manually update for now until a websocket msg is available.
doFetchCreatorSettings(channelId);
}
});
}
@@ -271,15 +369,35 @@ export function CommentCreate(props: Props) {
setAdvancedEditor(!advancedEditor);
}
if (commentsDisabledBySettings) {
// **************************************************************************
// Effects
// **************************************************************************
// Fetch channel constraints if not already.
React.useEffect(() => {
if (!channelSettings && channelId) {
doFetchCreatorSettings(channelId);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// **************************************************************************
// Render
// **************************************************************************
if (channelSettings && !channelSettings.comments_enabled) {
return <Empty padded text={__('This channel has disabled comments on their page.')} />;
}
if (!hasChannels) {
if (!isFetchingChannels && !hasChannels) {
return (
<div
role="button"
onClick={() => {
if (embed) {
window.open(`https://odysee.com/$/${PAGES.AUTH}?redirect=/$/${PAGES.LIVESTREAM}`);
return;
}
const pathPlusRedirect = `/$/${PAGES.CHANNEL_NEW}?redirect=${pathname}`;
if (livestream) {
window.open(pathPlusRedirect);
@@ -288,12 +406,7 @@ export function CommentCreate(props: Props) {
}
}}
>
<FormField
type="textarea"
name={'comment_signup_prompt'}
placeholder={__('Say something about this...')}
label={isFetchingChannels ? __('Comment') : undefined}
/>
<FormField type="textarea" name={'comment_signup_prompt'} placeholder={__('Say something about this...')} />
<div className="section__actions--no-margin">
<Button disabled button="primary" label={__('Post --[button to submit something]--')} requiresAuth={IS_WEB} />
</div>
@@ -306,7 +419,7 @@ export function CommentCreate(props: Props) {
<div className="comment__create">
<div className="comment__sc-preview">
<CreditAmount
className="comment__scpreview-amount"
className="comment__sc-preview-amount"
isFiat={activeTab === TAB_FIAT}
amount={tipAmount}
size={activeTab === TAB_LBC ? 18 : 2}
@@ -322,7 +435,7 @@ export function CommentCreate(props: Props) {
<Button
autoFocus
button="primary"
disabled={disabled}
disabled={disabled || !minAmountMet}
label={
isSubmitting
? __('Sending...')
@@ -332,7 +445,13 @@ export function CommentCreate(props: Props) {
}
onClick={handleSupportComment}
/>
<Button button="link" label={__('Cancel')} onClick={() => setIsReviewingSupportComment(false)} />
<Button
disabled={isSubmitting}
button="link"
label={__('Cancel')}
onClick={() => setIsReviewingSupportComment(false)}
/>
{MinAmountNotice}
</div>
</div>
);
@@ -344,10 +463,11 @@ export function CommentCreate(props: Props) {
className={classnames('comment__create', {
'comment__create--reply': isReply,
'comment__create--nested-reply': isNested,
'comment__create--bottom': bottom,
})}
>
<FormField
disabled={!activeChannelClaim}
disabled={isFetchingChannels}
type={SIMPLE_SITE ? 'textarea' : advancedEditor && !isReply ? 'markdown' : 'textarea'}
name={isReply ? 'content_reply' : 'content_description'}
label={
@@ -385,59 +505,71 @@ export function CommentCreate(props: Props) {
{isSupportComment ? (
<>
<Button
disabled={disabled || tipError || shouldDisableReviewButton}
disabled={disabled || tipError || shouldDisableReviewButton || !minAmountMet}
type="button"
button="primary"
icon={activeTab === TAB_LBC ? ICONS.LBC : ICONS.FINANCE}
label={__('Review')}
onClick={() => setIsReviewingSupportComment(true)}
requiresAuth={IS_WEB}
/>
<Button disabled={disabled} button="link" label={__('Cancel')} onClick={() => setIsSupportComment(false)} />
<Button
disabled={isSubmitting}
button="link"
label={__('Cancel')}
onClick={() => setIsSupportComment(false)}
/>
</>
) : (
<>
<Button
ref={buttonref}
button="primary"
disabled={disabled}
type="submit"
label={
isReply
? isSubmitting
? __('Replying...')
: __('Reply')
: isSubmitting
? __('Commenting...')
: __('Comment --[button to submit something]--')
}
requiresAuth={IS_WEB}
/>
{!claimIsMine && (
{(!minTip || claimIsMine) && (
<Button
ref={buttonRef}
button="primary"
disabled={disabled}
button="alt"
className="thatButton"
icon={ICONS.LBC}
onClick={() => {
setIsSupportComment(true);
setActiveTab(TAB_LBC);
}}
type="submit"
label={
isReply
? isSubmitting
? __('Replying...')
: __('Reply')
: isSubmitting
? __('Commenting...')
: __('Comment --[button to submit something]--')
}
requiresAuth={IS_WEB}
/>
)}
{!claimIsMine && (
<Button
disabled={disabled}
button="alt"
className="thisButton"
icon={ICONS.FINANCE}
onClick={() => {
setIsSupportComment(true);
setActiveTab(TAB_FIAT);
}}
/>
{!supportDisabled && !claimIsMine && (
<>
<Button
disabled={disabled}
button="alt"
className="thatButton"
icon={ICONS.LBC}
onClick={() => {
setIsSupportComment(true);
setActiveTab(TAB_LBC);
}}
/>
{/* @if TARGET='web' */}
{stripeEnvironment && (
<Button
disabled={disabled}
button="alt"
className="thisButton"
icon={ICONS.FINANCE}
onClick={() => {
setIsSupportComment(true);
setActiveTab(TAB_FIAT);
}}
/>
)}
{/* @endif */}
</>
)}
{isReply && (
{isReply && !minTip && (
<Button
button="link"
label={__('Cancel')}
@@ -450,6 +582,8 @@ export function CommentCreate(props: Props) {
)}
</>
)}
{deletedComment && <div className="error__text">{__('This comment has been deleted.')}</div>}
{MinAmountNotice}
</div>
</Form>
);
+3 -13
View File
@@ -1,15 +1,9 @@
import { connect } from 'react-redux';
import { makeSelectChannelPermUrlForClaimUri, makeSelectClaimIsMine, makeSelectClaimForUri } from 'lbry-redux';
import {
doCommentAbandon,
doCommentPin,
doCommentModBlock,
doCommentModBlockAsAdmin,
doCommentModBlockAsModerator,
doCommentModAddDelegate,
} from 'redux/actions/comments';
import { doCommentPin, doCommentModAddDelegate } from 'redux/actions/comments';
import { doChannelMute } from 'redux/actions/blocked';
// import { doSetActiveChannel } from 'redux/actions/app';
import { doOpenModal } from 'redux/actions/app';
import { doSetPlayingUri } from 'redux/actions/content';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import { selectPlayingUri } from 'redux/selectors/content';
@@ -26,15 +20,11 @@ const select = (state, props) => ({
});
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
clearPlayingUri: () => dispatch(doSetPlayingUri({ uri: null })),
deleteComment: (commentId, creatorChannelUrl) => dispatch(doCommentAbandon(commentId, creatorChannelUrl)),
muteChannel: (channelUri) => dispatch(doChannelMute(channelUri)),
pinComment: (commentId, claimId, remove) => dispatch(doCommentPin(commentId, claimId, remove)),
// setActiveChannel: channelId => dispatch(doSetActiveChannel(channelId)),
commentModBlock: (commenterUri) => dispatch(doCommentModBlock(commenterUri)),
commentModBlockAsAdmin: (commenterUri, blockerId) => dispatch(doCommentModBlockAsAdmin(commenterUri, blockerId)),
commentModBlockAsModerator: (commenterUri, creatorId, blockerId) =>
dispatch(doCommentModBlockAsModerator(commenterUri, creatorId, blockerId)),
commentModAddDelegate: (modChanId, modChanName, creatorChannelClaim) =>
dispatch(doCommentModAddDelegate(modChanId, modChanName, creatorChannelClaim, true)),
});
+84 -73
View File
@@ -1,42 +1,47 @@
// @flow
import * as ICONS from 'constants/icons';
import * as MODALS from 'constants/modal_types';
import React from 'react';
import { MenuList, MenuItem } from '@reach/menu-button';
import ChannelThumbnail from 'component/channelThumbnail';
import Icon from 'component/common/icon';
import { parseURI } from 'lbry-redux';
import { getChannelFromClaim } from 'util/claim';
type Props = {
claim: ?Claim,
clearPlayingUri: () => void,
uri: ?string,
authorUri: string, // full LBRY Channel URI: lbry://@channel#123...
commentId: string, // sha256 digest identifying the comment
commentIsMine: boolean, // if this comment was signed by an owned channel
deleteComment: (string, ?string) => void,
isPinned: boolean,
pinComment: (string, string, boolean) => Promise<any>,
muteChannel: (string) => void,
handleEditComment: () => void,
contentChannelPermanentUrl: any,
activeChannelClaim: ?ChannelClaim,
isTopLevel: boolean,
commentModBlock: (string) => void,
commentModBlockAsAdmin: (string, string) => void,
commentModBlockAsModerator: (string, string, string) => void,
commentModAddDelegate: (string, string, ChannelClaim) => void,
playingUri: ?PlayingUri,
isPinned: boolean,
commentIsMine: boolean, // if this comment was signed by an owned channel
disableEdit?: boolean,
disableRemove?: boolean,
supportAmount?: any,
handleEditComment: () => void,
// --- select ---
claim: ?Claim,
claimIsMine: boolean,
contentChannelPermanentUrl: any,
activeChannelClaim: ?ChannelClaim,
playingUri: ?PlayingUri,
moderationDelegatorsById: { [string]: { global: boolean, delegators: { name: string, claimId: string } } },
// --- perform ---
openModal: (id: string, {}) => void,
clearPlayingUri: () => void,
muteChannel: (string) => void,
pinComment: (string, string, boolean) => Promise<any>,
commentModAddDelegate: (string, string, ChannelClaim) => void,
setQuickReply: (any) => void,
};
function CommentMenuList(props: Props) {
const {
uri,
claim,
authorUri,
commentIsMine,
commentId,
deleteComment,
muteChannel,
pinComment,
clearPlayingUri,
@@ -45,24 +50,17 @@ function CommentMenuList(props: Props) {
isTopLevel,
isPinned,
handleEditComment,
commentModBlock,
commentModBlockAsAdmin,
commentModBlockAsModerator,
commentModAddDelegate,
playingUri,
moderationDelegatorsById,
disableEdit,
disableRemove,
moderationDelegatorsById,
openModal,
supportAmount,
setQuickReply,
} = props;
const contentChannelClaim = !claim
? null
: claim.value_type === 'channel'
? claim
: claim.signing_channel && claim.is_channel_signature_valid
? claim.signing_channel
: null;
const contentChannelClaim = getChannelFromClaim(claim);
const activeModeratorInfo = activeChannelClaim && moderationDelegatorsById[activeChannelClaim.claim_id];
const activeChannelIsCreator = activeChannelClaim && activeChannelClaim.permanent_url === contentChannelPermanentUrl;
const activeChannelIsAdmin = activeChannelClaim && activeModeratorInfo && activeModeratorInfo.global;
@@ -80,11 +78,17 @@ function CommentMenuList(props: Props) {
if (playingUri && playingUri.source === 'comment') {
clearPlayingUri();
}
deleteComment(commentId, commentIsMine ? undefined : contentChannelPermanentUrl);
openModal(MODALS.CONFIRM_REMOVE_COMMENT, {
commentId,
commentIsMine,
contentChannelPermanentUrl,
supportAmount,
setQuickReply,
});
}
function handleCommentBlock() {
commentModBlock(authorUri);
openModal(MODALS.BLOCK_CHANNEL, { contentUri: uri, commenterUri: authorUri });
}
function handleCommentMute() {
@@ -98,16 +102,57 @@ function CommentMenuList(props: Props) {
}
}
function blockCommentAsModerator() {
if (activeChannelClaim && contentChannelClaim) {
commentModBlockAsModerator(authorUri, contentChannelClaim.claim_id, activeChannelClaim.claim_id);
}
}
function getBlockOptionElem() {
const isPersonalBlockTheOnlyOption = !activeChannelIsModerator && !activeChannelIsAdmin;
const isTimeoutBlockAvailable = (claim && claim.is_my_output) || activeChannelIsModerator;
const personalPermanentBlockOnly = isPersonalBlockTheOnlyOption && !isTimeoutBlockAvailable;
function blockCommentAsAdmin() {
if (activeChannelClaim) {
commentModBlockAsAdmin(authorUri, activeChannelClaim.claim_id);
function getSubtitle() {
if (personalPermanentBlockOnly) {
return {
line1: __('Prevent this channel from interacting with you.'),
line2: null,
};
} else {
if (activeChannelIsModerator && activeChannelIsAdmin) {
return {
line1: __('Personal | Moderator | Admin'),
line2: __('Choose a permanent or temporary ban.'),
};
} else if (activeChannelIsModerator && !activeChannelIsAdmin) {
return {
line1: __('Personal | Moderator'),
line2: __('Choose a permanent or temporary ban.'),
};
} else if (!activeChannelIsModerator && activeChannelIsAdmin) {
return {
line1: __('Personal | Admin'),
line2: __('Choose a permanent or temporary ban.'),
};
} else {
return {
line1: null,
line2: __('Choose a permanent or temporary ban.'),
};
}
}
}
const subtitle = getSubtitle();
return (
<>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.BLOCK} />
{__('Block')}
</div>
{subtitle.line1 && <span className="comment__menu-help">{subtitle.line1}</span>}
{subtitle.line2 && (
<span className="comment__menu-help">
{subtitle.line2} {!personalPermanentBlockOnly && <Icon aria-hidden icon={ICONS.EXTERNAL} />}
</span>
)}
</>
);
}
return (
@@ -161,13 +206,7 @@ function CommentMenuList(props: Props) {
{!commentIsMine && (
<MenuItem className="comment__menu-option" onSelect={handleCommentBlock}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.BLOCK} />
{__('Block')}
</div>
{activeChannelIsCreator && (
<span className="comment__menu-help">{__('Prevent this channel from interacting with you.')}</span>
)}
{getBlockOptionElem()}
</MenuItem>
)}
@@ -183,34 +222,6 @@ function CommentMenuList(props: Props) {
</MenuItem>
)}
{(activeChannelIsAdmin || activeChannelIsModerator) && (
<div className="comment__menu-title">{__('Moderator tools')}</div>
)}
{!commentIsMine && activeChannelIsAdmin && (
<MenuItem className="comment__menu-option" onSelect={blockCommentAsAdmin}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.GLOBE} />
{__('Global Block')}
</div>
<span className="comment__menu-help">{__('Block this channel as global admin')}</span>
</MenuItem>
)}
{!commentIsMine && activeChannelIsModerator && (
<MenuItem className="comment__menu-option" onSelect={blockCommentAsModerator}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.BLOCK} />
{__('Moderator Block')}
</div>
<span className="comment__menu-help">
{__('Block this channel on behalf of %creator%', {
creator: contentChannelClaim ? contentChannelClaim.name : __('creator'),
})}
</span>
</MenuItem>
)}
{activeChannelClaim && (
<div className="comment__menu-active">
<ChannelThumbnail xsmall noLazyLoad uri={activeChannelClaim.permanent_url} />
+2 -1
View File
@@ -1,6 +1,6 @@
import { connect } from 'react-redux';
import Comment from './view';
import { makeSelectClaimIsMine, makeSelectClaimForUri } from 'lbry-redux';
import { makeSelectClaimIsMine, makeSelectClaimForUri, doResolveUri } from 'lbry-redux';
import { doToast } from 'redux/actions/notifications';
import { makeSelectMyReactionsForComment, makeSelectOthersReactionsForComment } from 'redux/selectors/comments';
import { doCommentReact } from 'redux/actions/comments';
@@ -21,6 +21,7 @@ const select = (state, props) => {
};
const perform = (dispatch) => ({
resolve: (uri) => dispatch(doResolveUri(uri)),
react: (commentId, type) => dispatch(doCommentReact(commentId, type)),
doToast: (params) => dispatch(doToast(params)),
});
+26 -5
View File
@@ -17,16 +17,38 @@ type Props = {
pendingCommentReacts: Array<string>,
claimIsMine: boolean,
activeChannelId: ?string,
uri: string,
claim: ?ChannelClaim,
doToast: ({ message: string }) => void,
hideCreatorLike: boolean,
resolve: (string) => void,
};
export default function CommentReactions(props: Props) {
const { myReacts, othersReacts, commentId, react, claimIsMine, claim, activeChannelId, doToast } = props;
const {
myReacts,
othersReacts,
commentId,
react,
claimIsMine,
uri,
claim,
activeChannelId,
doToast,
hideCreatorLike,
resolve,
} = props;
const {
push,
location: { pathname },
} = useHistory();
React.useEffect(() => {
if (!claim) {
resolve(uri);
}
}, [claim, resolve, uri]);
const canCreatorReact =
claim &&
claimIsMine &&
@@ -48,7 +70,7 @@ export default function CommentReactions(props: Props) {
}
return count;
};
const shouldHide = !canCreatorReact && hideCreatorLike;
const creatorLiked = getCountForReact(REACTION_TYPES.CREATOR_LIKE) > 0;
const likeIcon = SIMPLE_SITE
? myReacts.includes(REACTION_TYPES.LIKE)
@@ -105,9 +127,8 @@ export default function CommentReactions(props: Props) {
label={<span className="comment__reaction-count">{getCountForReact(REACTION_TYPES.DISLIKE)}</span>}
/>
{ENABLE_CREATOR_REACTIONS && (canCreatorReact || creatorLiked) && (
{!shouldHide && ENABLE_CREATOR_REACTIONS && (canCreatorReact || creatorLiked) && (
<Button
iconOnly
disabled={!canCreatorReact || !claimIsMine}
requiresAuth={IS_WEB}
title={claimIsMine ? __('You loved this') : __('Creator loved this')}
@@ -116,7 +137,7 @@ export default function CommentReactions(props: Props) {
onClick={() => react(commentId, REACTION_TYPES.CREATOR_LIKE)}
>
{creatorLiked && (
<ChannelThumbnail xsmall uri={authorUri} hideStakedIndicator className="comment__creator-like" />
<ChannelThumbnail xsmall uri={authorUri} hideStakedIndicator className="comment__creator-like" allowGifs />
)}
</Button>
)}
+11 -5
View File
@@ -1,5 +1,10 @@
import { connect } from 'react-redux';
import { makeSelectClaimIsMine, selectFetchingMyChannels, selectMyChannelClaims } from 'lbry-redux';
import {
makeSelectClaimForUri,
makeSelectClaimIsMine,
selectFetchingMyChannels,
selectMyChannelClaims,
} from 'lbry-redux';
import {
makeSelectTopLevelCommentsForUri,
makeSelectTopLevelTotalPagesForUri,
@@ -7,12 +12,12 @@ import {
selectIsFetchingReacts,
makeSelectTotalCommentsCountForUri,
selectOthersReactsById,
makeSelectCommentsDisabledForUri,
selectMyReactionsByCommentId,
makeSelectCommentIdsForUri,
selectSettingsByChannelId,
makeSelectPinnedCommentsForUri,
} from 'redux/selectors/comments';
import { doCommentReset, doCommentList, doCommentById, doCommentReactList } from 'redux/actions/comments';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import CommentsList from './view';
@@ -21,15 +26,16 @@ const select = (state, props) => {
return {
myChannels: selectMyChannelClaims(state),
allCommentIds: makeSelectCommentIdsForUri(props.uri)(state),
pinnedComments: makeSelectPinnedCommentsForUri(props.uri)(state),
topLevelComments: makeSelectTopLevelCommentsForUri(props.uri)(state),
topLevelTotalPages: makeSelectTopLevelTotalPagesForUri(props.uri)(state),
totalComments: makeSelectTotalCommentsCountForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
isFetchingComments: selectIsFetchingComments(state),
isFetchingReacts: selectIsFetchingReacts(state),
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
commentsDisabledBySettings: makeSelectCommentsDisabledForUri(props.uri)(state),
fetchingChannels: selectFetchingMyChannels(state),
settingsByChannelId: selectSettingsByChannelId(state),
myReactsByCommentId: selectMyReactionsByCommentId(state),
othersReactsById: selectOthersReactsById(state),
activeChannelId: activeChannelClaim && activeChannelClaim.claim_id,
+100 -38
View File
@@ -1,6 +1,7 @@
// @flow
import * as REACTION_TYPES from 'constants/reactions';
import * as ICONS from 'constants/icons';
import { COMMENT_HIGHLIGHTED } from 'constants/classnames';
import { COMMENT_PAGE_SIZE_TOP_LEVEL, SORT_BY } from 'constants/comment';
import React, { useEffect } from 'react';
import classnames from 'classnames';
@@ -13,9 +14,14 @@ import usePersistedState from 'effects/use-persisted-state';
import { ENABLE_COMMENT_REACTIONS } from 'config';
import Empty from 'component/common/empty';
import debounce from 'util/debounce';
import { useIsMobile } from 'effects/use-screensize';
import { getChannelIdFromClaim } from 'util/claim';
const DEBOUNCE_SCROLL_HANDLER_MS = 200;
// "3" due to 2 separate fetches needed + 1 buffer just in case.
const MAX_LINKED_COMMENT_SCROLL_ATTEMPTS = 3;
function scaleToDevicePixelRatio(value) {
const devicePixelRatio = window.devicePixelRatio || 1.0;
if (devicePixelRatio < 1.0) {
@@ -26,14 +32,15 @@ function scaleToDevicePixelRatio(value) {
type Props = {
allCommentIds: any,
pinnedComments: Array<Comment>,
topLevelComments: Array<Comment>,
topLevelTotalPages: number,
commentsDisabledBySettings: boolean,
fetchTopLevelComments: (string, number, number, number) => void,
fetchComment: (string) => void,
fetchReacts: (Array<string>) => Promise<any>,
resetComments: (string) => void,
uri: string,
claim: ?Claim,
claimIsMine: boolean,
myChannels: ?Array<ChannelClaim>,
isFetchingComments: boolean,
@@ -44,6 +51,7 @@ type Props = {
myReactsByCommentId: ?{ [string]: Array<string> }, // "CommentId:MyChannelId" -> reaction array (note the ID concatenation)
othersReactsById: ?{ [string]: { [REACTION_TYPES.LIKE | REACTION_TYPES.DISLIKE]: number } },
activeChannelId: ?string,
settingsByChannelId: { [channelId: string]: PerChannelSettings },
};
function CommentList(props: Props) {
@@ -54,9 +62,10 @@ function CommentList(props: Props) {
fetchReacts,
resetComments,
uri,
pinnedComments,
topLevelComments,
topLevelTotalPages,
commentsDisabledBySettings,
claim,
claimIsMine,
myChannels,
isFetchingComments,
@@ -67,14 +76,21 @@ function CommentList(props: Props) {
myReactsByCommentId,
othersReactsById,
activeChannelId,
settingsByChannelId,
} = props;
const commentRef = React.useRef();
const spinnerRef = React.useRef();
const DEFAULT_SORT = ENABLE_COMMENT_REACTIONS ? SORT_BY.POPULARITY : SORT_BY.NEWEST;
const [sort, setSort] = usePersistedState('comment-sort-by', DEFAULT_SORT);
const [page, setPage] = React.useState(0);
const [lcScrollAttempts, setLcScrollAttempts] = React.useState(
linkedCommentId ? 0 : MAX_LINKED_COMMENT_SCROLL_ATTEMPTS
);
const isMobile = useIsMobile();
const [expandedComments, setExpandedComments] = React.useState(!isMobile);
const totalFetchedComments = allCommentIds ? allCommentIds.length : 0;
const channelId = getChannelIdFromClaim(claim);
const channelSettings = channelId ? settingsByChannelId[channelId] : undefined;
// Display comments immediately if not fetching reactions
// If not, wait to show comments until reactions are fetched
@@ -103,6 +119,34 @@ function CommentList(props: Props) {
}
}
function getCommentElems(comments) {
return comments.map((comment) => {
return (
<CommentView
isTopLevel
threadDepth={3}
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
author={comment.channel_name}
claimId={comment.claim_id}
commentId={comment.comment_id}
message={comment.comment}
timePosted={comment.timestamp * 1000}
claimIsMine={claimIsMine}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
linkedCommentId={linkedCommentId}
isPinned={comment.is_pinned}
supportAmount={comment.support_amount}
numDirectReplies={comment.replies}
isModerator={comment.is_moderator}
isGlobalMod={comment.is_global_mod}
isFiat={comment.is_fiat}
/>
);
});
}
// Reset comments
useEffect(() => {
if (page === 0) {
@@ -158,11 +202,19 @@ function CommentList(props: Props) {
// Scroll to linked-comment
useEffect(() => {
if (readyToDisplayComments && linkedCommentId && commentRef && commentRef.current) {
commentRef.current.scrollIntoView({ block: 'start' });
window.scrollBy(0, -125);
if (lcScrollAttempts < MAX_LINKED_COMMENT_SCROLL_ATTEMPTS && readyToDisplayComments && !isFetchingComments) {
const elems = document.getElementsByClassName(COMMENT_HIGHLIGHTED);
if (elems.length > 0) {
setLcScrollAttempts(MAX_LINKED_COMMENT_SCROLL_ATTEMPTS);
const linkedComment = elems[0];
linkedComment.scrollIntoView({ block: 'start' });
window.scrollBy(0, -125);
} else {
setLcScrollAttempts(lcScrollAttempts + 1);
}
}
}, [readyToDisplayComments, linkedCommentId]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [readyToDisplayComments, isFetchingComments]); // We just want to respond to these, nothing else.
// Infinite scroll
useEffect(() => {
@@ -191,7 +243,7 @@ function CommentList(props: Props) {
}
const handleCommentScroll = debounce(() => {
if (shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
if (!isMobile && shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
setPage(page + 1);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
@@ -205,6 +257,7 @@ function CommentList(props: Props) {
}
}
}, [
isMobile,
page,
moreBelow,
spinnerRef,
@@ -214,8 +267,6 @@ function CommentList(props: Props) {
topLevelTotalPages,
]);
const displayedComments = readyToDisplayComments ? topLevelComments : [];
return (
<Card
title={
@@ -275,39 +326,50 @@ function CommentList(props: Props) {
<>
<CommentCreate uri={uri} />
{!commentsDisabledBySettings && !isFetchingComments && hasNoComments && (
{channelSettings && channelSettings.comments_enabled && !isFetchingComments && hasNoComments && (
<Empty padded text={__('That was pretty deep. What do you think?')} />
)}
<ul className="comments" ref={commentRef}>
{topLevelComments &&
displayedComments &&
displayedComments.map((comment) => {
return (
<CommentView
isTopLevel
threadDepth={3}
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
author={comment.channel_name}
claimId={comment.claim_id}
commentId={comment.comment_id}
message={comment.comment}
timePosted={comment.timestamp * 1000}
claimIsMine={claimIsMine}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
linkedCommentId={linkedCommentId}
isPinned={comment.is_pinned}
supportAmount={comment.support_amount}
numDirectReplies={comment.replies}
isFiat={comment.is_fiat}
/>
);
})}
<ul
className={classnames({
comments: expandedComments,
'comments--contracted': !expandedComments,
})}
>
{readyToDisplayComments && pinnedComments && getCommentElems(pinnedComments)}
{readyToDisplayComments && topLevelComments && getCommentElems(topLevelComments)}
</ul>
{(isFetchingComments || moreBelow) && (
{isMobile && (
<div className="card__bottom-actions--comments">
{(!expandedComments || moreBelow) && (
<Button
button="link"
title={!expandedComments ? __('Expand Comments') : __('Load More')}
label={!expandedComments ? __('Expand') : __('More')}
onClick={() => {
if (!expandedComments) {
setExpandedComments(true);
} else {
setPage(page + 1);
}
}}
/>
)}
{expandedComments && (
<Button
button="link"
title={__('Collapse Thread')}
label={__('Collapse')}
onClick={() => {
setExpandedComments(false);
}}
/>
)}
</div>
)}
{(isFetchingComments || (!isMobile && moreBelow)) && (
<div className="main--empty" ref={spinnerRef}>
<Spinner type="small" />
</div>
+1 -6
View File
@@ -1,16 +1,11 @@
import { connect } from 'react-redux';
import { makeSelectClaimIsMine, selectMyChannelClaims } from 'lbry-redux';
import {
selectIsFetchingCommentsByParentId,
makeSelectRepliesForParentId,
makeSelectTotalRepliesForParentId,
} from 'redux/selectors/comments';
import { selectIsFetchingCommentsByParentId, makeSelectRepliesForParentId } from 'redux/selectors/comments';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import CommentsReplies from './view';
const select = (state, props) => ({
fetchedReplies: makeSelectRepliesForParentId(props.parentId)(state),
totalReplies: makeSelectTotalRepliesForParentId(props.parentId)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
myChannels: selectMyChannelClaims(state),
+9 -22
View File
@@ -4,11 +4,9 @@ import React from 'react';
import Comment from 'component/comment';
import Button from 'component/button';
import Spinner from 'component/spinner';
import ChannelThumbnail from 'component/channelThumbnail';
type Props = {
fetchedReplies: Array<any>,
totalReplies: number,
uri: string,
parentId: string,
claimIsMine: boolean,
@@ -16,9 +14,11 @@ type Props = {
linkedCommentId?: string,
commentingEnabled: boolean,
threadDepth: number,
numDirectReplies: number,
numDirectReplies: number, // Total replies for parentId as reported by 'comment[replies]'. Includes blocked items.
isFetchingByParentId: { [string]: boolean },
onShowMore?: () => void,
hasMore: boolean,
supportDisabled: boolean,
};
function CommentsReplies(props: Props) {
@@ -26,7 +26,6 @@ function CommentsReplies(props: Props) {
uri,
parentId,
fetchedReplies,
totalReplies,
claimIsMine,
myChannels,
linkedCommentId,
@@ -35,6 +34,8 @@ function CommentsReplies(props: Props) {
numDirectReplies,
isFetchingByParentId,
onShowMore,
hasMore,
supportDisabled,
} = props;
const [isExpanded, setExpanded] = React.useState(true);
@@ -97,31 +98,17 @@ function CommentsReplies(props: Props) {
commentingEnabled={commentingEnabled}
supportAmount={comment.support_amount}
numDirectReplies={comment.replies}
isModerator={comment.is_moderator}
isGlobalMod={comment.is_global_mod}
supportDisabled={supportDisabled}
/>
);
})}
{!isFetchingByParentId[parentId] && totalReplies < numDirectReplies && (
<li className="comment comment--reply">
<div className="comment__content">
<div className="comment__thumbnail-wrapper">
<ChannelThumbnail xsmall className="comment__author-thumbnail" />
</div>
<div className="comment__body-container comment--blocked">
<div className="comment__meta">
<em>---</em>
</div>
<div>
<em>{__('Comment(s) blocked.')}</em>
</div>
</div>
</div>
</li>
)}
</ul>
</div>
</div>
)}
{isExpanded && fetchedReplies && displayedComments.length < totalReplies && (
{isExpanded && fetchedReplies && hasMore && (
<div className="comment__actions--nested">
<Button button="link" label={__('Show more')} onClick={showMore} className="button--uri-indicator" />
</div>
+3
View File
@@ -10,6 +10,7 @@ type Props = {
title?: string | Node,
subtitle?: string | Node,
titleActions?: string | Node,
id?: string,
body?: string | Node,
actions?: string | Node,
icon?: string,
@@ -30,6 +31,7 @@ export default function Card(props: Props) {
title,
subtitle,
titleActions,
id,
body,
actions,
icon,
@@ -53,6 +55,7 @@ export default function Card(props: Props) {
className={classnames(className, 'card', {
'card__multi-pane': Boolean(secondPane),
})}
id={id}
onClick={(e) => {
if (onClick) {
onClick();
+5
View File
@@ -49,6 +49,11 @@ class CreditAmount extends React.PureComponent<Props> {
isFiat,
} = this.props;
const minimumRenderableAmount = 10 ** (-1 * precision);
// return null, otherwise it will try and convert undefined to a string
if (amount === undefined) {
return null;
}
const fullPrice = formatFullPrice(amount, 2);
const isFree = parseFloat(amount) === 0;
+3 -12
View File
@@ -7,7 +7,7 @@ import { FormField } from 'component/common/form';
type Props = {
type: string,
currentPath?: ?string,
onFileChosen: WebFile => void,
onFileChosen: (WebFile) => void,
label?: string,
placeholder?: string,
accept?: string,
@@ -19,17 +19,6 @@ type Props = {
class FileSelector extends React.PureComponent<Props> {
static defaultProps = {
autoFocus: false,
};
componentDidUpdate(prevProps: Props) {
// If the form has just been cleared,
// clear the file input
if (prevProps.currentPath && !this.props.currentPath) {
this.fileInput.current.value = null;
}
}
static defaultProps = {
type: 'file',
};
@@ -39,6 +28,7 @@ class FileSelector extends React.PureComponent<Props> {
super();
this.fileInput = React.createRef();
this.handleFileInputSelection = this.handleFileInputSelection.bind(this);
this.handleDirectoryInputSelection = this.handleDirectoryInputSelection.bind(this);
this.fileInputButton = this.fileInputButton.bind(this);
}
@@ -53,6 +43,7 @@ class FileSelector extends React.PureComponent<Props> {
if (this.props.onFileChosen) {
this.props.onFileChosen(file);
}
this.fileInput.current.value = null; // clear the file input
};
handleDirectoryInputSelection = () => {
+141 -1
View File
@@ -44,7 +44,15 @@ const buildIcon = (iconStrokes: React$Node, customSvgValues = {}) =>
export const icons = {
// The LBRY icon is different from the base icon set so don't use buildIcon()
[ICONS.LBRY]: (props: IconProps) => (
<svg stroke="currentColor" fill="currentColor" x="0px" y="0px" viewBox="0 0 322 254" className="icon lbry-icon">
<svg
{...props}
stroke="currentColor"
fill="currentColor"
x="0px"
y="0px"
viewBox="0 0 322 254"
className="icon lbry-icon"
>
<path d="M296,85.9V100l-138.8,85.3L52.6,134l0.2-7.9l104,51.2L289,96.1v-5.8L164.2,30.1L25,116.2v38.5l131.8,65.2 l137.6-84.4l3.9,6l-141.1,86.4L18.1,159.1v-46.8l145.8-90.2C163.9,22.1,296,85.9,296,85.9z" />
<path d="M294.3,150.9l2-12.6l-12.2-2.1l0.8-4.9l17.1,2.9l-2.8,17.5L294.3,150.9L294.3,150.9z" />
</svg>
@@ -193,6 +201,26 @@ export const icons = {
[ICONS.SUBSCRIBE]: buildIcon(
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
),
[ICONS.SUBSCRIBED]: (props: IconProps) => {
const { size = 24, color = 'currentColor', ...otherProps } = props;
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width={size}
height={size}
fill={color}
stroke={color}
strokeWidth="1"
strokeLinecap="round"
strokeLinejoin="round"
{...otherProps}
>
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>
);
},
[ICONS.UNSUBSCRIBE]: buildIcon(
<path d="M 12,5.67 10.94,4.61 C 5.7533356,-0.57666427 -2.0266644,7.2033357 3.16,12.39 l 1.06,1.06 7.78,7.78 7.78,-7.78 1.06,-1.06 c 2.149101,-2.148092 2.149101,-5.6319078 0,-7.78 -2.148092,-2.1491008 -5.631908,-2.1491008 -7.78,0 L 9.4481298,8.2303201 15.320603,9.2419066 11.772427,13.723825" />
),
@@ -2310,6 +2338,23 @@ export const icons = {
<path d="M.75 19.497a3.75 3.75 0 107.5 0 3.75 3.75 0 10-7.5 0zM.75 8.844a11.328 11.328 0 0114.4 14.4M.75 1.113a18.777 18.777 0 0122.139 22.123" />
</g>
),
[ICONS.APPEARANCE]: buildIcon(
<g>
<path d="M16.022,15.624c.3,3.856,6.014,1.2,5.562,2.54-2.525,7.481-12.648,5.685-16.966,1.165A10.9,10.9,0,0,1,4.64,4.04C8.868-.188,16.032-.495,19.928,4.018,27.56,12.858,15.758,12.183,16.022,15.624Z" />
<path d="M5.670 13.309 A1.520 1.520 0 1 0 8.710 13.309 A1.520 1.520 0 1 0 5.670 13.309 Z" />
<path d="M9.430 18.144 A1.520 1.520 0 1 0 12.470 18.144 A1.520 1.520 0 1 0 9.430 18.144 Z" />
<path d="M13.066 5.912 A1.520 1.520 0 1 0 16.106 5.912 A1.520 1.520 0 1 0 13.066 5.912 Z" />
<path d="M6.620 7.524 A1.520 1.520 0 1 0 9.660 7.524 A1.520 1.520 0 1 0 6.620 7.524 Z" />
</g>
),
[ICONS.CONTENT]: buildIcon(
<g>
<path d="M15.750 16.500 A1.500 1.500 0 1 0 18.750 16.500 A1.500 1.500 0 1 0 15.750 16.500 Z" />
<path d="M18.524,10.7l.442,1.453a.994.994,0,0,0,1.174.681l1.472-.341a1.339,1.339,0,0,1,1.275,2.218l-1.031,1.111a1,1,0,0,0,0,1.362l1.031,1.111a1.339,1.339,0,0,1-1.275,2.218l-1.472-.341a.994.994,0,0,0-1.174.681L18.524,22.3a1.33,1.33,0,0,1-2.548,0l-.442-1.453a.994.994,0,0,0-1.174-.681l-1.472.341a1.339,1.339,0,0,1-1.275-2.218l1.031-1.111a1,1,0,0,0,0-1.362l-1.031-1.111a1.339,1.339,0,0,1,1.275-2.218l1.472.341a.994.994,0,0,0,1.174-.681l.442-1.453A1.33,1.33,0,0,1,18.524,10.7Z" />
<path d="M8.25,20.25h-6a1.5,1.5,0,0,1-1.5-1.5V2.25A1.5,1.5,0,0,1,2.25.75H12.879a1.5,1.5,0,0,1,1.06.439l2.872,2.872a1.5,1.5,0,0,1,.439,1.06V6.75" />
<path d="M6.241,12.678a.685.685,0,0,1-.991-.613V7.435a.685.685,0,0,1,.991-.613l4.631,2.316a.684.684,0,0,1,0,1.224Z" />
</g>
),
[ICONS.STAR]: buildIcon(
<g>
<path d="M12.729 1.2l3.346 6.629 6.44.638a.805.805 0 01.5 1.374l-5.3 5.253 1.965 7.138a.813.813 0 01-1.151.935L12 19.934l-6.52 3.229a.813.813 0 01-1.151-.935l1.965-7.138L.99 9.837a.805.805 0 01.5-1.374l6.44-.638L11.271 1.2a.819.819 0 011.458 0z" />
@@ -2323,4 +2368,99 @@ export const icons = {
<path d="M4.954 14.753l3.535 3.535-1.768 1.768-3.535-3.535z" />
</g>
),
[ICONS.BADGE_MOD]: (props: IconProps) => (
<svg
{...props}
version="1.1"
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
width="24"
height="24"
viewBox="0 0 24 24"
xmlSpace="preserve"
>
<style type="text/css">{'.st0{fill:FF3850}.st1{fill:#181021}.st2{fill:#FFFFFF}'}</style>
<g>
<g>
<path
className="st0"
d="M11.69,6.77c4.86,0,7.55,0.9,8.52,1.31c1.29-1.46,3.28-4.14,3.28-6.76c0,0-4.17,4.86-6.92,5.12 c-1.25-0.87-2.77-1.38-4.41-1.38c0,0-3.21-0.06-4.63,1.31C4.81,6.44,0.51,1.32,0.51,1.32c0,2.61,1.97,5.27,3.25,6.74 C4.71,7.59,7.03,6.77,11.69,6.77z M19.87,19.38c0.02-0.13,0.04-0.27,0.04-0.4V12.8c0-1.03-0.21-2.02-0.58-2.92 c-0.83-0.33-3.25-1.11-7.64-1.11c-4.29,0-6.33,0.75-7,1.06c-0.38,0.91-0.6,1.91-0.6,2.97v6.18c0,0.13,0.02,0.26,0.04,0.39 C1.6,19.73,0,22.54,0,22.54L12,24l12-1.46C24,22.54,22.36,19.79,19.87,19.38z"
/>
</g>
</g>
<path
className="st1"
d="M13,18.57H11c-2.27,0-4.12-0.82-4.12-2.88v-2.46c0-2.77,2.17-3.94,5.11-3.94s5.11,1.17,5.11,3.94v2.46 C17.11,17.75,15.27,18.57,13,18.57z"
/>
<path
className="st2"
d="M15.06,15.25c-0.28,0-0.5-0.22-0.5-0.5v-1.42c0-0.32,0-1.31-1.63-1.31c-0.28,0-0.5-0.22-0.5-0.5 s0.22-0.5,0.5-0.5c1.65,0,2.63,0.86,2.63,2.31v1.42C15.56,15.02,15.33,15.25,15.06,15.25z"
/>
</svg>
),
[ICONS.BADGE_STREAMER]: (props: IconProps) => (
<svg
{...props}
version="1.1"
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
width="24"
height="24"
viewBox="-1182 401 24 24"
xmlSpace="preserve"
>
<style type="text/css">{'.st0{fill:#FF5490}.st1{fill:#81BBB9}.st2{fill:#2E2A2F}.st3{fill:#FFFFFF}'}</style>
<path
className="st0"
d="M-1169.8,406.4c-4.3,0-7.8,3.5-7.8,7.8c0,0.4,0,0.8,0.1,1.1h1c-0.1-0.4-0.1-0.7-0.1-1.1c0-3.7,3-6.8,6.8-6.8 s6.8,3,6.8,6.8c0,0.4,0,0.8-0.1,1.1h1c0.1-0.4,0.1-0.7,0.1-1.1C-1162.1,409.9-1165.5,406.4-1169.8,406.4z"
/>
<path
className="st0"
d="M-1180,414.2c0-5.6,4.6-10.2,10.2-10.2c5.6,0,10.2,4.6,10.2,10.2c0,2.2-0.7,4.3-1.9,5.9l0.8,0.6 c1.3-1.8,2.1-4.1,2.1-6.5c0-6.2-5-11.2-11.2-11.2c-6.2,0-11.2,5-11.2,11.2c0,2.1,0.6,4.1,1.6,5.8l1-0.3 C-1179.4,418-1180,416.2-1180,414.2z"
/>
<path className="st1" d="M-1163.7,419.4" />
<path
className="st1"
d="M-1165.6,418.5c0-0.1,0-3.6,0-3.6c0-1.9-1-4.3-4.4-4.3s-4.4,2.4-4.4,4.3c0,0,0,3.6,0,3.6 c-1.4,0.2-1.8,0.7-1.8,0.7s2.2,2.7,6.2,2.7s6.2-2.7,6.2-2.7S-1164.2,418.7-1165.6,418.5z"
/>
<path
className="st2"
d="M-1169.2,418.5h-1.5c-1.7,0-3.1-0.6-3.1-2.2v-1.9c0-2.1,1.6-3,3.9-3s3.9,0.9,3.9,3v1.9 C-1166.1,417.8-1167.5,418.5-1169.2,418.5z"
/>
<path
className="st3"
d="M-1167.8,416.2c-0.2,0-0.4-0.2-0.4-0.4v-1.1c0-0.2,0-1-1.2-1c-0.2,0-0.4-0.2-0.4-0.4s0.2-0.4,0.4-0.4 c1.2,0,2,0.6,2,1.7v1.1C-1167.4,416.1-1167.6,416.2-1167.8,416.2z"
/>
</svg>
),
[ICONS.PLAY]: buildIcon(<polygon points="5 3 19 12 5 21 5 3" />),
[ICONS.REPLAY]: buildIcon(
<g>
<polyline points="1 4 1 10 7 10" />
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" />
</g>
),
[ICONS.REPEAT]: buildIcon(
<g>
<polyline points="17 1 21 5 17 9" />
<path d="M3 11V9a4 4 0 0 1 4-4h14" />
<polyline points="7 23 3 19 7 15" />
<path d="M21 13v2a4 4 0 0 1-4 4H3" />
</g>
),
[ICONS.SHUFFLE]: buildIcon(
<g>
<polyline points="16 3 21 3 21 8" />
<line x1="4" y1="20" x2="21" y2="3" />
<polyline points="21 16 21 21 16 21" />
<line x1="15" y1="15" x2="21" y2="21" />
<line x1="4" y1="4" x2="9" y2="9" />
</g>
),
};
+1
View File
@@ -73,6 +73,7 @@ class IconComponent extends React.PureComponent<Props> {
size={size || (sectionIcon ? 20 : 16)}
className={classnames(`icon icon--${icon}`, className, { 'color-override': iconColor })}
color={color}
aria-hidden
{...rest}
/>
);
+1 -1
View File
@@ -28,7 +28,7 @@ import { useRect } from '@reach/rect';
// </TabPanels>
// </Tabs>
//
// the base @reach/tabs components handle all the focus/accessibilty labels
// the base @reach/tabs components handle all the focus/accessibility labels
// We're just adding some styling
type TabsProps = {
+1
View File
@@ -99,6 +99,7 @@ function FileActions(props: Props) {
React.useEffect(() => {
if (downloadClicked && streamingUrl) {
webDownloadClaim(streamingUrl, fileName);
setDownloadClicked(false);
}
}, [downloadClicked, streamingUrl, fileName]);
// @endif
+6
View File
@@ -11,6 +11,7 @@ type Props = {
claimIsMine: boolean,
downloading: boolean,
loading: boolean,
focusable: boolean,
fileInfo: ?FileListItem,
openModal: (id: string, { path: string }) => void,
pause: () => void,
@@ -35,6 +36,7 @@ function FileDownloadLink(props: Props) {
uri,
claim,
buttonType,
focusable = true,
showLabel = false,
hideOpenButton = false,
hideDownloadStatus = false,
@@ -91,6 +93,8 @@ function FileDownloadLink(props: Props) {
pause();
openModal(MODALS.CONFIRM_EXTERNAL_RESOURCE, { path: fileInfo.download_path, isMine: claimIsMine });
}}
aria-hidden={!focusable}
tabIndex={focusable ? 0 : -1}
/>
);
}
@@ -105,6 +109,8 @@ function FileDownloadLink(props: Props) {
icon={ICONS.DOWNLOAD}
label={showLabel ? label : null}
onClick={handleDownload}
aria-hidden={!focusable}
tabIndex={focusable ? 0 : -1}
/>
);
}
+12 -9
View File
@@ -23,7 +23,7 @@ type Props = {
index: number,
length: number,
location: { pathname: string },
push: string => void,
push: (string) => void,
},
};
@@ -43,7 +43,7 @@ function FileDrop(props: Props) {
const navigationTimer = React.useRef(null);
// Gets respective icon given a mimetype
const getFileIcon = type => {
const getFileIcon = (type) => {
// Not all files have a type
if (!type) return ICONS.FILE;
// Detect common types
@@ -77,10 +77,13 @@ function FileDrop(props: Props) {
}, [navigateToPublish]);
// Handle file selection
const handleFileSelected = React.useCallback((selectedFile) => {
updatePublishForm({ filePath: selectedFile });
hideDropArea();
}, [updatePublishForm, hideDropArea]);
const handleFileSelected = React.useCallback(
(selectedFile) => {
updatePublishForm({ filePath: selectedFile });
hideDropArea();
},
[updatePublishForm, hideDropArea]
);
// Clear timers when unmounted
React.useEffect(() => {
@@ -114,12 +117,12 @@ function FileDrop(props: Props) {
React.useEffect(() => {
if (dropData && !files.length && (!modal || modal.id !== MODALS.FILE_SELECTION)) {
getTree(dropData)
.then(entries => {
.then((entries) => {
if (entries && entries.length) {
setFiles(entries);
}
})
.catch(error => {
.catch((error) => {
setError(error || true);
});
}
@@ -146,7 +149,7 @@ function FileDrop(props: Props) {
const show = files.length === 1 || (!target && drag && (!modal || modal.id !== MODALS.FILE_SELECTION));
return (
<div className={classnames('file-drop', show && 'file-drop--show')}>
<div aria-hidden={!show} className={classnames('file-drop', show && 'file-drop--show')}>
<div className={classnames('card', 'file-drop__area')}>
<Icon size={64} icon={icon} className={'main-icon'} />
<p>{target ? target.name : __(`Drop here to publish!`)} </p>
+70 -9
View File
@@ -1,10 +1,12 @@
// @flow
import * as REACTION_TYPES from 'constants/reactions';
import * as ICONS from 'constants/icons';
import React from 'react';
import classnames from 'classnames';
import Button from 'component/button';
import { formatNumberWithCommas } from 'util/number';
import NudgeFloating from 'component/nudgeFloating';
import { SIMPLE_SITE } from 'config';
type Props = {
claim: StreamClaim,
@@ -15,18 +17,51 @@ type Props = {
likeCount: number,
dislikeCount: number,
myReaction: ?string,
livestream?: boolean,
};
function FileReactions(props: Props) {
const { claim, uri, doFetchReactions, doReactionLike, doReactionDislike, likeCount, dislikeCount } = props;
const {
claim,
uri,
doFetchReactions,
doReactionLike,
doReactionDislike,
myReaction,
likeCount,
dislikeCount,
livestream,
} = props;
const claimId = claim && claim.claim_id;
const channel = claim && claim.signing_channel && claim.signing_channel.name;
const isCollection = claim && claim.value_type === 'collection'; // hack because nudge gets cut off by card on cols.
const likeIcon = SIMPLE_SITE ? (myReaction === REACTION_TYPES.LIKE ? ICONS.FIRE_ACTIVE : ICONS.FIRE) : ICONS.UPVOTE;
const dislikeIcon = SIMPLE_SITE
? myReaction === REACTION_TYPES.DISLIKE
? ICONS.SLIME_ACTIVE
: ICONS.SLIME
: ICONS.DOWNVOTE;
React.useEffect(() => {
if (claimId) {
function fetchReactions() {
doFetchReactions(claimId);
}
}, [claimId, doFetchReactions]);
let fetchInterval;
if (claimId) {
fetchReactions();
if (livestream) {
fetchInterval = setInterval(fetchReactions, 45000);
}
}
return () => {
if (fetchInterval) {
clearInterval(fetchInterval);
}
};
}, [claimId, doFetchReactions, livestream]);
return (
<>
@@ -41,20 +76,46 @@ function FileReactions(props: Props) {
title={__('I like this')}
requiresAuth={IS_WEB}
authSrc="filereaction_like"
className={classnames('button--file-action')}
label={formatNumberWithCommas(likeCount, 0)}
className={classnames('button--file-action', { 'button--fire': myReaction === REACTION_TYPES.LIKE })}
label={
<>
{myReaction === REACTION_TYPES.LIKE && SIMPLE_SITE && (
<>
<div className="button__fire-glow" />
<div className="button__fire-particle1" />
<div className="button__fire-particle2" />
<div className="button__fire-particle3" />
<div className="button__fire-particle4" />
<div className="button__fire-particle5" />
<div className="button__fire-particle6" />
</>
)}
{formatNumberWithCommas(likeCount, 0)}
</>
}
iconSize={18}
icon={ICONS.UPVOTE}
icon={likeIcon}
onClick={() => doReactionLike(uri)}
/>
<Button
requiresAuth={IS_WEB}
authSrc={'filereaction_dislike'}
title={__('I dislike this')}
className={classnames('button--file-action')}
label={formatNumberWithCommas(dislikeCount, 0)}
className={classnames('button--file-action', { 'button--slime': myReaction === REACTION_TYPES.DISLIKE })}
label={
<>
{myReaction === REACTION_TYPES.DISLIKE && SIMPLE_SITE && (
<>
<div className="button__slime-stain" />
<div className="button__slime-drop1" />
<div className="button__slime-drop2" />
</>
)}
{formatNumberWithCommas(dislikeCount, 0)}
</>
}
iconSize={18}
icon={ICONS.DOWNVOTE}
icon={dislikeIcon}
onClick={() => doReactionDislike(uri)}
/>
</>
+1 -1
View File
@@ -12,7 +12,7 @@ import { makeSelectFileRenderModeForUri, makeSelectFileExtensionForUri } from 'r
import FileRender from './view';
const select = (state, props) => {
const autoplay = props.embedded ? false : makeSelectClientSetting(SETTINGS.AUTOPLAY)(state);
const autoplay = props.embedded ? false : makeSelectClientSetting(SETTINGS.AUTOPLAY_MEDIA)(state);
return {
currentTheme: makeSelectClientSetting(SETTINGS.THEME)(state),
claim: makeSelectClaimForUri(props.uri)(state),
+2 -1
View File
@@ -4,6 +4,7 @@ import React from 'react';
import { lazyImport } from 'util/lazyImport';
import classnames from 'classnames';
import * as RENDER_MODES from 'constants/file_render_modes';
import * as KEYCODES from 'constants/keycodes';
import VideoViewer from 'component/viewers/videoViewer';
import { withRouter } from 'react-router-dom';
import fs from 'fs';
@@ -57,7 +58,7 @@ class FileRender extends React.PureComponent<Props> {
}
escapeListener(e: SyntheticKeyboardEvent<*>) {
if (e.keyCode === 27) {
if (e.keyCode === KEYCODES.ESCAPE) {
e.preventDefault();
this.exitFullscreen();
+2
View File
@@ -22,6 +22,7 @@ const select = (state, props) => {
const playingUri = selectPlayingUri(state);
const primaryUri = selectPrimaryUri(state);
const uri = playingUri && playingUri.uri;
const collectionId = playingUri && playingUri.collectionId;
return {
uri,
@@ -35,6 +36,7 @@ const select = (state, props) => {
floatingPlayerEnabled: makeSelectClientSetting(SETTINGS.FLOATING_PLAYER)(state),
renderMode: makeSelectFileRenderModeForUri(uri)(state),
videoTheaterMode: makeSelectClientSetting(SETTINGS.VIDEO_THEATER_MODE)(state),
collectionId,
};
};
+16 -2
View File
@@ -14,7 +14,7 @@ import { onFullscreenChange } from 'util/full-screen';
import { useIsMobile } from 'effects/use-screensize';
import debounce from 'util/debounce';
import { useHistory } from 'react-router';
import { isURIEqual } from 'lbry-redux';
import { isURIEqual, COLLECTIONS_CONSTS } from 'lbry-redux';
const IS_DESKTOP_MAC = typeof process === 'object' ? process.platform === 'darwin' : false;
const DEBOUNCE_WINDOW_RESIZE_HANDLER_MS = 60;
@@ -34,6 +34,7 @@ type Props = {
primaryUri: ?string,
videoTheaterMode: boolean,
doFetchRecommendedContent: (string, boolean) => void,
collectionId: string,
};
export default function FileRenderFloating(props: Props) {
@@ -51,6 +52,7 @@ export default function FileRenderFloating(props: Props) {
primaryUri,
videoTheaterMode,
doFetchRecommendedContent,
collectionId,
} = props;
const {
location: { pathname },
@@ -69,6 +71,13 @@ export default function FileRenderFloating(props: Props) {
y: 0,
});
let navigateUrl;
if (collectionId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
navigateUrl = uri + `?` + collectionParams.toString();
}
const playingUriSource = playingUri && playingUri.source;
const isPlayable = RENDER_MODES.FLOATING_MODES.includes(renderMode);
const isReadyToPlay = isPlayable && (streamingUrl || (fileInfo && fileInfo.completed));
@@ -303,7 +312,12 @@ export default function FileRenderFloating(props: Props) {
{isFloating && (
<div className="draggable content__info">
<div className="claim-preview__title" title={title || uri}>
<Button label={title || uri} navigate={uri} button="link" className="content__floating-link" />
<Button
label={title || uri}
navigate={navigateUrl || uri}
button="link"
className="content__floating-link"
/>
</div>
<UriIndicator link uri={uri} />
</div>
+26 -18
View File
@@ -7,6 +7,7 @@ import {
makeSelectStreamingUrlForUri,
makeSelectClaimWasPurchased,
SETTINGS,
COLLECTIONS_CONSTS,
} from 'lbry-redux';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
@@ -22,27 +23,34 @@ import {
import FileRenderInitiator from './view';
import { doAnaltyicsPurchaseEvent } from 'redux/actions/app';
const select = (state, props) => ({
claimThumbnail: makeSelectThumbnailForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
obscurePreview: makeSelectShouldObscurePreview(props.uri)(state),
isPlaying: makeSelectIsPlaying(props.uri)(state),
playingUri: selectPlayingUri(state),
insufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
autoplay: makeSelectClientSetting(SETTINGS.AUTOPLAY)(state),
hasCostInfo: Boolean(makeSelectCostInfoForUri(props.uri)(state)),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
authenticated: selectUserVerifiedEmail(state),
});
const select = (state, props) => {
const { search } = props.location;
const urlParams = new URLSearchParams(search);
const collectionId = urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID);
return {
claimThumbnail: makeSelectThumbnailForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
obscurePreview: makeSelectShouldObscurePreview(props.uri)(state),
isPlaying: makeSelectIsPlaying(props.uri)(state),
playingUri: selectPlayingUri(state),
insufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
autoplay: makeSelectClientSetting(SETTINGS.AUTOPLAY_MEDIA)(state),
hasCostInfo: Boolean(makeSelectCostInfoForUri(props.uri)(state)),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
authenticated: selectUserVerifiedEmail(state),
collectionId,
};
};
const perform = (dispatch) => ({
play: (uri) => {
play: (uri, collectionId) => {
dispatch(doSetPrimaryUri(uri));
dispatch(doSetPlayingUri({ uri }));
dispatch(doSetPlayingUri({ uri, collectionId }));
dispatch(doPlayUri(uri, undefined, undefined, (fileInfo) => dispatch(doAnaltyicsPurchaseEvent(fileInfo))));
},
});
+7 -6
View File
@@ -7,6 +7,7 @@ import React, { useEffect, useCallback } from 'react';
import classnames from 'classnames';
import * as PAGES from 'constants/pages';
import * as RENDER_MODES from 'constants/file_render_modes';
import * as KEYCODES from 'constants/keycodes';
import Button from 'component/button';
import isUserTyping from 'util/detect-typing';
import { getThumbnailCdnUrl } from 'util/thumbnail';
@@ -14,10 +15,8 @@ import Nag from 'component/common/nag';
// $FlowFixMe cannot resolve ...
import FileRenderPlaceholder from 'static/img/fileRenderPlaceholder.png';
const SPACE_BAR_KEYCODE = 32;
type Props = {
play: (string) => void,
play: (string, string) => void,
isLoading: boolean,
isPlaying: boolean,
fileInfo: FileListItem,
@@ -36,6 +35,7 @@ type Props = {
claimWasPurchased: boolean,
authenticated: boolean,
videoTheaterMode: boolean,
collectionId: string,
};
export default function FileRenderInitiator(props: Props) {
@@ -55,6 +55,7 @@ export default function FileRenderInitiator(props: Props) {
claimWasPurchased,
authenticated,
videoTheaterMode,
collectionId,
} = props;
// force autoplay if a timestamp is present
@@ -109,16 +110,16 @@ export default function FileRenderInitiator(props: Props) {
e.stopPropagation();
}
play(uri);
play(uri, collectionId);
},
[play, uri]
[play, uri, collectionId]
);
useEffect(() => {
// This is just for beginning to download a file
// Play/Pause/Fullscreen will be handled by the respective viewers because not every file type should behave the same
function handleKeyDown(e: KeyboardEvent) {
if (!isUserTyping() && e.keyCode === SPACE_BAR_KEYCODE) {
if (!isUserTyping() && e.keyCode === KEYCODES.SPACEBAR) {
e.preventDefault();
if (!isPlaying || fileStatus === 'stopped') {
@@ -6,8 +6,7 @@ $transition-duration: 300ms;
// Classnames must line up with classes in classes.js
.ff-container {
display: inline-block;
position: relative;
position: absolute;
.ff-image {
z-index: $base-zindex;
+6 -3
View File
@@ -6,16 +6,19 @@ import useLazyLoading from 'effects/use-lazy-loading';
type Props = {
thumb: string,
fallback: ?string,
children?: Node,
className?: string,
};
const Thumb = (props: Props) => {
const { thumb, children } = props;
const { thumb, fallback, children, className } = props;
const thumbnailRef = React.useRef(null);
useLazyLoading(thumbnailRef);
useLazyLoading(thumbnailRef, fallback || '');
return (
<div ref={thumbnailRef} data-background-image={thumb} className={classnames('media__thumb')}>
<div ref={thumbnailRef} data-background-image={thumb} className={classnames('media__thumb', className)}>
{children}
</div>
);
+8 -1
View File
@@ -4,6 +4,7 @@ import { getThumbnailCdnUrl } from 'util/thumbnail';
import React from 'react';
import FreezeframeWrapper from './FreezeframeWrapper';
import Placeholder from './placeholder.png';
import { MISSING_THUMB_DEFAULT } from 'config';
import classnames from 'classnames';
import Thumb from './thumb';
@@ -42,6 +43,8 @@ function FileThumbnail(props: Props) {
);
}
const fallback = MISSING_THUMB_DEFAULT ? getThumbnailCdnUrl({ thumbnail: MISSING_THUMB_DEFAULT }) : undefined;
let url = thumbnail || (hasResolvedClaim ? Placeholder : '');
// @if TARGET='web'
// Pass image urls through a compression proxy
@@ -53,7 +56,11 @@ function FileThumbnail(props: Props) {
const thumbnailUrl = url ? url.replace(/'/g, "\\'") : '';
if (hasResolvedClaim || thumbnailUrl) {
return <Thumb thumb={thumbnailUrl}>{children}</Thumb>;
return (
<Thumb thumb={thumbnailUrl} fallback={fallback} className={className}>
{children}
</Thumb>
);
}
return (
<div
+12 -1
View File
@@ -1,4 +1,5 @@
import { connect } from 'react-redux';
import { doFetchSubCount, makeSelectSubCountForUri } from 'lbryinc';
import { makeSelectTitleForUri, makeSelectClaimForUri } from 'lbry-redux';
import { makeSelectInsufficientCreditsForUri } from 'redux/selectors/content';
import { makeSelectViewersForId } from 'redux/selectors/livestream';
@@ -7,11 +8,21 @@ import FileTitleSection from './view';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri)(state);
const viewers = claim && makeSelectViewersForId(claim.claim_id)(state);
const channelClaimId = claim && claim.signing_channel ? claim.signing_channel.claim_id : undefined;
const channelUri = claim && claim.signing_channel ? claim.signing_channel.canonical_url : undefined;
const subCount = channelUri && makeSelectSubCountForUri(channelUri)(state);
return {
viewers,
isInsufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
channelClaimId,
subCount,
};
};
export default connect(select)(FileTitleSection);
const perform = (dispatch) => ({
fetchSubCount: (claimId) => dispatch(doFetchSubCount(claimId)),
});
export default connect(select, perform)(FileTitleSection);
+22 -2
View File
@@ -23,12 +23,32 @@ type Props = {
livestream?: boolean,
isLive?: boolean,
viewers?: number,
subCount: number,
channelClaimId?: string,
fetchSubCount: (string) => void,
};
function FileTitleSection(props: Props) {
const { title, uri, nsfw, isNsfwBlocked, livestream = false, isLive = false, viewers } = props;
const {
title,
uri,
nsfw,
isNsfwBlocked,
livestream = false,
isLive = false,
viewers,
subCount,
channelClaimId,
fetchSubCount,
} = props;
const [hasAcknowledgedSec, setHasAcknowledgedSec] = usePersistedState('sec-nag', false);
React.useEffect(() => {
if (channelClaimId) {
fetchSubCount(channelClaimId);
}
}, [channelClaimId, fetchSubCount]);
return (
<>
{!hasAcknowledgedSec && (
@@ -108,7 +128,7 @@ function FileTitleSection(props: Props) {
</div>
) : (
<div className="section">
<ClaimAuthor uri={uri} />
<ClaimAuthor channelSubCount={subCount} uri={uri} />
<FileDescription uri={uri} />
</div>
)
+13
View File
@@ -0,0 +1,13 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri } from 'lbry-redux';
import { makeSelectViewCountForUri } from 'lbryinc';
import FileViewCountInline from './view';
const select = (state, props) => {
return {
claim: makeSelectClaimForUri(props.uri)(state),
viewCount: makeSelectViewCountForUri(props.uri)(state),
};
};
export default connect(select, null)(FileViewCountInline);
+30
View File
@@ -0,0 +1,30 @@
// @flow
import React from 'react';
type Props = {
uri: string,
isLivestream?: boolean,
// --- select ---
claim: ?StreamClaim,
viewCount: string,
};
export default function FileViewCountInline(props: Props) {
const { isLivestream, claim, viewCount } = props;
const formattedViewCount = Number(viewCount).toLocaleString();
if (!viewCount || (claim && claim.repost_url) || isLivestream) {
// (1) Currently, makeSelectViewCountForUri doesn't differentiate between
// unfetched view-count vs zero view-count. But since it's probably not
// ideal to highlight that a view has 0 count, let's just not show anything.
// (2) No idea how to get the repost src's claim ID from the repost claim,
// so hiding it for now.
return null;
}
return (
<span className="view_count">
{viewCount !== 1 ? __('%view_count% views', { view_count: formattedViewCount }) : __('1 view')}
</span>
);
}
@@ -5,7 +5,7 @@ import FilePrice from 'component/filePrice';
import { formatLbryUrlForWeb } from 'util/url';
import { withRouter } from 'react-router';
import { URL } from 'config';
import * as ICONS from 'constants/icons';
import Logo from 'component/logo';
type Props = {
uri: string,
@@ -36,7 +36,9 @@ function FileViewerEmbeddedTitle(props: Props) {
{...contentLinkProps}
/>
<div className="file-viewer__embedded-info">
<Button className="file-viewer__overlay-logo" icon={ICONS.LBRY} aria-label={__('Home')} {...lbryLinkProps} />
<Button className="file-viewer__overlay-logo" aria-label={__('Home')} {...lbryLinkProps}>
<Logo type={'embed'} />
</Button>
{isInApp && <FilePrice uri={uri} />}
</div>
</div>
+6 -1
View File
@@ -8,13 +8,14 @@ import { COLLECTIONS_CONSTS } from 'lbry-redux';
type Props = {
uri: string,
claim: StreamClaim,
focusable: boolean,
hasClaimInWatchLater: boolean,
doToast: ({ message: string }) => void,
doCollectionEdit: (string, any) => void,
};
function FileWatchLaterLink(props: Props) {
const { claim, hasClaimInWatchLater, doToast, doCollectionEdit } = props;
const { claim, hasClaimInWatchLater, doToast, doCollectionEdit, focusable = true } = props;
const buttonRef = useRef();
let isHovering = useHover(buttonRef);
@@ -36,7 +37,10 @@ function FileWatchLaterLink(props: Props) {
});
}
// text that will show if you keep cursor over button
const title = hasClaimInWatchLater ? __('Remove from Watch Later') : __('Add to Watch Later');
// label that is shown after hover
const label = !hasClaimInWatchLater ? __('Add') : __('Added');
return (
@@ -51,6 +55,7 @@ function FileWatchLaterLink(props: Props) {
(isHovering ? ICONS.COMPLETED : ICONS.TIME)
}
onClick={(e) => handleWatchLater(e)}
tabIndex={focusable ? 0 : -1}
/>
);
}
+9 -10
View File
@@ -1,5 +1,5 @@
// @flow
import { LOGO_TITLE, ENABLE_NO_SOURCE_CLAIMS, CHANNEL_STAKED_LEVEL_LIVESTREAM, ENABLE_UI_NOTIFICATIONS } from 'config';
import { ENABLE_NO_SOURCE_CLAIMS, CHANNEL_STAKED_LEVEL_LIVESTREAM, ENABLE_UI_NOTIFICATIONS } from 'config';
import * as ICONS from 'constants/icons';
import { SETTINGS } from 'lbry-redux';
import * as PAGES from 'constants/pages';
@@ -15,6 +15,8 @@ import { useIsMobile } from 'effects/use-screensize';
import NotificationBubble from 'component/notificationBubble';
import NotificationHeaderButton from 'component/notificationHeaderButton';
import ChannelThumbnail from 'component/channelThumbnail';
import SkipNavigationButton from 'component/skipNavigationButton';
import Logo from 'component/logo';
// @if TARGET='app'
import { remote } from 'electron';
import { IS_MAC } from 'component/app/view';
@@ -234,6 +236,7 @@ const Header = (props: Props) => {
) : (
<>
<div className="header__navigation">
<SkipNavigationButton />
{!authHeader && (
<span style={{ position: 'relative' }}>
<Button
@@ -244,6 +247,7 @@ const Header = (props: Props) => {
}
className="header__navigation-item menu__title header__navigation-item--icon"
icon={ICONS.MENU}
aria-expanded={sidebarOpen}
onClick={() => setSidebarOpen(!sidebarOpen)}
>
{isAbsoluteSideNavHidden && isMobile && notificationsEnabled && <NotificationBubble />}
@@ -251,14 +255,8 @@ const Header = (props: Props) => {
</span>
)}
<Button
aria-label={__('Home')}
className="header__navigation-item header__navigation-item--lbry"
// @if TARGET='app'
label={'LBRY'}
// @endif
// @if TARGET='web'
label={LOGO_TITLE} // eslint-disable-line
// @endif
icon={ICONS.LBRY}
onClick={() => {
if (history.location.pathname === '/') window.location.reload();
}}
@@ -268,8 +266,9 @@ const Header = (props: Props) => {
}}
// @endif
{...homeButtonNavigationProps}
/>
>
<Logo />
</Button>
{!authHeader && (
<div className="header__center">
{/* @if TARGET='app' */}
+2 -4
View File
@@ -8,7 +8,7 @@ import { getDefaultHomepageKey } from 'util/default-languages';
type Props = {
homepage: string,
setHomepage: string => void,
setHomepage: (string) => void,
};
function SelectHomepage(props: Props) {
@@ -26,12 +26,10 @@ function SelectHomepage(props: Props) {
<FormField
name="homepage_select"
type="select"
label={__('Homepage')}
onChange={handleSetHomepage}
value={homepage || getDefaultHomepageKey()}
helper={__('Tailor your experience.')}
>
{Object.keys(homepages).map(hp => (
{Object.keys(homepages).map((hp) => (
<option key={'hp' + hp} value={hp}>
{`${LANGUAGES[hp][1]}`}
</option>
+76 -71
View File
@@ -11,7 +11,7 @@ import LbcSymbol from 'component/common/lbc-symbol';
type Props = {
errorMessage: ?string,
inviteNew: string => void,
inviteNew: (string) => void,
isPending: boolean,
referralLink: string,
referralCode: string,
@@ -35,10 +35,10 @@ function InviteNew(props: Props) {
const [referralSource, setReferralSource] = useState(referralCode);
const handleReferralChange = React.useCallback(
code => {
(code) => {
setReferralSource(code);
// TODO: keep track of this in an array?
const matchingChannel = channels && channels.find(ch => ch.name === code);
const matchingChannel = channels && channels.find((ch) => ch.name === code);
if (matchingChannel) {
analytics.apiLogPublish(matchingChannel);
}
@@ -68,80 +68,85 @@ function InviteNew(props: Props) {
}, [topChannel, handleReferralChange]);
function lookupUrlByClaimName(name, channels) {
const claim = channels.find(channel => channel.name === name);
const claim = channels.find((channel) => channel.name === name);
return claim && claim.canonical_url ? claim.canonical_url.replace('lbry://', '') : name;
}
return (
<div className={'columns'}>
<Card
title={__('Invites')}
subtitle={
<I18nMessage tokens={{ SITE_NAME, lbc: <LbcSymbol /> }}>
Earn %lbc% for inviting subscribers, followers, fans, friends, etc. to join and follow you on %SITE_NAME%.
You can use invites just like affiliate links.
</I18nMessage>
}
actions={
<React.Fragment>
<CopyableText label={__('Your invite link')} copyable={referral} />
{channels && channels.length > 0 && (
<FormField
type="select"
label={__('Customize link')}
value={referralSource}
onChange={e => handleReferralChange(e.target.value)}
>
{channels.map(channel => (
<option key={channel.claim_id} value={channel.name}>
{channel.name}
</option>
))}
<option value={referralCode}>{referralCode}</option>
</FormField>
)}
</React.Fragment>
}
/>
<Card
title={__('Invite by email')}
subtitle={
<I18nMessage tokens={{ SITE_NAME, lbc: <LbcSymbol /> }}>
Invite someone you know by email and earn %lbc% when they join %SITE_NAME%.
</I18nMessage>
}
actions={
<React.Fragment>
<Form onSubmit={handleSubmit}>
<FormField
type="text"
label={__('Email')}
placeholder="youremail@example.org"
name="email"
value={email}
error={errorMessage}
inputButton={
<Button button="secondary" type="submit" label={__('Invite')} disabled={isPending || !email} />
}
onChange={event => {
handleEmailChanged(event);
}}
/>
<p className="help">
<I18nMessage
tokens={{
rewards_link: <Button button="link" navigate="/$/rewards" label={__('rewards')} />,
referral_faq_link: <Button button="link" label={__('FAQ')} href="https://lbry.com/faq/referrals" />,
}}
<div className="column">
<Card
title={__('Invites')}
subtitle={
<I18nMessage tokens={{ SITE_NAME, lbc: <LbcSymbol /> }}>
Earn %lbc% for inviting subscribers, followers, fans, friends, etc. to join and follow you on %SITE_NAME%.
You can use invites just like affiliate links.
</I18nMessage>
}
actions={
<React.Fragment>
<CopyableText label={__('Your invite link')} copyable={referral} />
{channels && channels.length > 0 && (
<FormField
type="select"
label={__('Customize link')}
value={referralSource}
onChange={(e) => handleReferralChange(e.target.value)}
>
Read our %referral_faq_link% to learn more about rewards.
</I18nMessage>
</p>
</Form>
</React.Fragment>
}
/>
{channels.map((channel) => (
<option key={channel.claim_id} value={channel.name}>
{channel.name}
</option>
))}
<option value={referralCode}>{referralCode}</option>
</FormField>
)}
</React.Fragment>
}
/>
</div>
<div className="column">
<Card
title={__('Invite by email')}
subtitle={
<I18nMessage tokens={{ SITE_NAME, lbc: <LbcSymbol /> }}>
Invite someone you know by email and earn %lbc% when they join %SITE_NAME%.
</I18nMessage>
}
actions={
<React.Fragment>
<Form onSubmit={handleSubmit}>
<FormField
type="text"
label={__('Email')}
placeholder="youremail@example.org"
name="email"
value={email}
error={errorMessage}
inputButton={
<Button button="secondary" type="submit" label={__('Invite')} disabled={isPending || !email} />
}
onChange={(event) => {
handleEmailChanged(event);
}}
/>
<p className="help">
<I18nMessage
tokens={{
rewards_link: <Button button="link" navigate="/$/rewards" label={__('rewards')} />,
referral_faq_link: (
<Button button="link" label={__('FAQ')} href="https://lbry.com/faq/referrals" />
),
}}
>
Read our %referral_faq_link% to learn more about rewards.
</I18nMessage>
</p>
</Form>
</React.Fragment>
}
/>
</div>
</div>
);
}
+53 -9
View File
@@ -3,6 +3,7 @@ import * as ICONS from 'constants/icons';
import React from 'react';
import { parseURI } from 'lbry-redux';
import MarkdownPreview from 'component/common/markdown-preview';
import Tooltip from 'component/common/tooltip';
import ChannelThumbnail from 'component/channelThumbnail';
import { Menu, MenuButton } from '@reach/menu-button';
import Icon from 'component/common/icon';
@@ -20,12 +21,28 @@ type Props = {
commentIsMine: boolean,
stakedLevel: number,
supportAmount: number,
isModerator: boolean,
isGlobalMod: boolean,
isFiat: boolean,
isPinned: boolean,
};
function LivestreamComment(props: Props) {
const { claim, uri, authorUri, message, commentIsMine, commentId, stakedLevel, supportAmount, isFiat } = props;
const [mouseIsHovering, setMouseHover] = React.useState(false);
const {
claim,
uri,
authorUri,
message,
commentIsMine,
commentId,
stakedLevel,
supportAmount,
isModerator,
isGlobalMod,
isFiat,
isPinned,
} = props;
const commentByOwnerOfContent = claim && claim.signing_channel && claim.signing_channel.permanent_url === authorUri;
const { claimName } = parseURI(authorUri);
@@ -34,8 +51,6 @@ function LivestreamComment(props: Props) {
className={classnames('livestream-comment', {
'livestream-comment--superchat': supportAmount > 0,
})}
onMouseOver={() => setMouseHover(true)}
onMouseOut={() => setMouseHover(false)}
>
{supportAmount > 0 && (
<div className="super-chat livestream-superchat__banner">
@@ -47,6 +62,30 @@ function LivestreamComment(props: Props) {
<div className="livestream-comment__body">
{supportAmount > 0 && <ChannelThumbnail uri={authorUri} xsmall />}
<div className="livestream-comment__info">
{isGlobalMod && (
<Tooltip label={__('Admin')}>
<span className="comment__badge comment__badge--global-mod">
<Icon icon={ICONS.BADGE_MOD} size={16} />
</span>
</Tooltip>
)}
{isModerator && (
<Tooltip label={__('Moderator')}>
<span className="comment__badge comment__badge--mod">
<Icon icon={ICONS.BADGE_MOD} size={16} />
</span>
</Tooltip>
)}
{commentByOwnerOfContent && (
<Tooltip label={__('Streamer')}>
<span className="comment__badge">
<Icon icon={ICONS.BADGE_STREAMER} size={16} />
</span>
</Tooltip>
)}
<Button
className={classnames('button--uri-indicator comment__author', {
'comment__author--creator': commentByOwnerOfContent,
@@ -57,6 +96,13 @@ function LivestreamComment(props: Props) {
{claimName}
</Button>
{isPinned && (
<span className="comment__pin">
<Icon icon={ICONS.PIN} size={14} />
{__('Pinned')}
</span>
)}
<div className="livestream-comment__text">
<MarkdownPreview content={message} promptLinks stakedLevel={stakedLevel} />
</div>
@@ -66,11 +112,7 @@ function LivestreamComment(props: Props) {
<div className="livestream-comment__menu">
<Menu>
<MenuButton className="menu__button">
<Icon
size={18}
className={mouseIsHovering ? 'comment__menu-icon--hovering' : 'comment__menu-icon'}
icon={ICONS.MORE_VERTICAL}
/>
<Icon size={18} icon={ICONS.MORE_VERTICAL} />
</MenuButton>
<CommentMenuList
uri={uri}
@@ -78,6 +120,8 @@ function LivestreamComment(props: Props) {
authorUri={authorUri}
commentIsMine={commentIsMine}
disableEdit
isTopLevel
isPinned={isPinned}
disableRemove={supportAmount > 0}
/>
</Menu>
+2
View File
@@ -7,12 +7,14 @@ import {
selectIsFetchingComments,
makeSelectSuperChatsForUri,
makeSelectSuperChatTotalAmountForUri,
makeSelectPinnedCommentsForUri,
} from 'redux/selectors/comments';
import LivestreamComments from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
comments: makeSelectTopLevelCommentsForUri(props.uri)(state).slice(0, 75),
pinnedComments: makeSelectPinnedCommentsForUri(props.uri)(state),
fetchingComments: selectIsFetchingComments(state),
superChats: makeSelectSuperChatsForUri(props.uri)(state),
superChatsTotalAmount: makeSelectSuperChatTotalAmountForUri(props.uri)(state),
+169 -75
View File
@@ -9,6 +9,7 @@ import UriIndicator from 'component/uriIndicator';
import CreditAmount from 'component/common/credit-amount';
import ChannelThumbnail from 'component/channelThumbnail';
import Tooltip from 'component/common/tooltip';
import * as ICONS from 'constants/icons';
type Props = {
uri: string,
@@ -19,16 +20,15 @@ type Props = {
doCommentSocketDisconnect: (string) => void,
doCommentList: (string, string, number, number) => void,
comments: Array<Comment>,
pinnedComments: Array<Comment>,
fetchingComments: boolean,
doSuperChatList: (string) => void,
superChats: Array<Comment>,
superChatsTotalAmount: number,
myChannels: ?Array<ChannelClaim>,
};
const VIEW_MODE_CHAT = 'view_chat';
const VIEW_MODE_SUPER_CHAT = 'view_superchat';
const COMMENT_SCROLL_OFFSET = 100;
const COMMENT_SCROLL_TIMEOUT = 25;
export default function LivestreamComments(props: Props) {
@@ -38,36 +38,35 @@ export default function LivestreamComments(props: Props) {
embed,
doCommentSocketConnect,
doCommentSocketDisconnect,
comments,
comments: commentsByChronologicalOrder,
pinnedComments,
doCommentList,
fetchingComments,
doSuperChatList,
superChats,
superChatsTotalAmount,
myChannels,
superChats: superChatsByTipAmount,
} = props;
let superChatsFiatAmount, superChatsTotalAmount;
const commentsRef = React.createRef();
const [scrollBottom, setScrollBottom] = React.useState(true);
const [viewMode, setViewMode] = React.useState(VIEW_MODE_CHAT);
const [performedInitialScroll, setPerformedInitialScroll] = React.useState(false);
const [scrollPos, setScrollPos] = React.useState(0);
const [showPinned, setShowPinned] = React.useState(true);
const claimId = claim && claim.claim_id;
const commentsLength = comments && comments.length;
const commentsToDisplay = viewMode === VIEW_MODE_CHAT ? comments : superChats;
const commentsLength = commentsByChronologicalOrder && commentsByChronologicalOrder.length;
// which kind of superchat to display, either
const commentsToDisplay = viewMode === VIEW_MODE_CHAT ? commentsByChronologicalOrder : superChatsByTipAmount;
const discussionElement = document.querySelector('.livestream__comments');
const commentElement = document.querySelector('.livestream-comment');
// todo: implement comment_list --mine in SDK so redux can grab with selectCommentIsMine
function isMyComment(channelId: string) {
if (myChannels != null && channelId != null) {
for (let i = 0; i < myChannels.length; i++) {
if (myChannels[i].claim_id === channelId) {
return true;
}
}
const pinnedComment = pinnedComments.length > 0 ? pinnedComments[0] : null;
function restoreScrollPos() {
if (discussionElement) {
discussionElement.scrollTop = 0;
}
return false;
}
React.useEffect(() => {
@@ -84,87 +83,134 @@ export default function LivestreamComments(props: Props) {
};
}, [claimId, uri, doCommentList, doSuperChatList, doCommentSocketConnect, doCommentSocketDisconnect]);
const handleScroll = React.useCallback(() => {
if (discussionElement) {
const negativeCommentHeight = commentElement && -1 * commentElement.offsetHeight;
const isAtRecent = negativeCommentHeight && discussionElement.scrollTop >= negativeCommentHeight;
setScrollBottom(isAtRecent);
}
}, [commentElement, discussionElement]);
// Register scroll handler (TODO: Should throttle/debounce)
React.useEffect(() => {
if (discussionElement) {
discussionElement.addEventListener('scroll', handleScroll);
if (commentsLength > 0) {
// Only update comment scroll if the user hasn't scrolled up to view old comments
// If they have, do nothing
if (!performedInitialScroll) {
setTimeout(
() =>
(discussionElement.scrollTop =
discussionElement.scrollHeight - discussionElement.offsetHeight + COMMENT_SCROLL_OFFSET),
COMMENT_SCROLL_TIMEOUT
);
setPerformedInitialScroll(true);
function handleScroll() {
if (discussionElement) {
const scrollTop = discussionElement.scrollTop;
if (scrollTop !== scrollPos) {
setScrollPos(scrollTop);
}
}
}
if (discussionElement) {
discussionElement.addEventListener('scroll', handleScroll);
return () => discussionElement.removeEventListener('scroll', handleScroll);
}
}, [commentsLength, discussionElement, handleScroll, performedInitialScroll, setPerformedInitialScroll]);
}, [discussionElement, scrollPos]);
// Retain scrollPos=0 when receiving new messages.
React.useEffect(() => {
if (discussionElement && commentsLength > 0) {
// Only update comment scroll if the user hasn't scrolled up to view old comments
if (scrollPos >= 0) {
// +ve scrollPos: not scrolled (Usually, there'll be a few pixels beyond 0).
// -ve scrollPos: user scrolled.
const timer = setTimeout(() => {
// Use a timer here to ensure we reset after the new comment has been rendered.
discussionElement.scrollTop = 0;
}, COMMENT_SCROLL_TIMEOUT);
return () => clearTimeout(timer);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [commentsLength]); // (Just respond to 'commentsLength' updates and nothing else)
// sum total amounts for fiat tips and lbc tips
if (superChatsByTipAmount) {
let fiatAmount = 0;
let LBCAmount = 0;
for (const superChat of superChatsByTipAmount) {
if (superChat.is_fiat) {
fiatAmount = fiatAmount + superChat.support_amount;
} else {
LBCAmount = LBCAmount + superChat.support_amount;
}
}
superChatsFiatAmount = fiatAmount;
superChatsTotalAmount = LBCAmount;
}
let superChatsReversed;
// array of superchats organized by fiat or not first, then support amount
if (superChatsByTipAmount) {
const clonedSuperchats = JSON.parse(JSON.stringify(superChatsByTipAmount));
// for top to bottom display, oldest superchat on top most recent on bottom
superChatsReversed = clonedSuperchats
.sort((a, b) => {
return b.timestamp - a.timestamp;
}); }
// todo: implement comment_list --mine in SDK so redux can grab with selectCommentIsMine
function isMyComment(channelId: string) {
if (myChannels != null && channelId != null) {
for (let i = 0; i < myChannels.length; i++) {
if (myChannels[i].claim_id === channelId) {
return true;
}
}
}
return false;
}
if (!claim) {
return null;
}
function scrollBack() {
if (discussionElement) {
discussionElement.scrollTop = 0;
setScrollBottom(true);
}
}
return (
<div className="card livestream__discussion">
<div className="card__header--between livestream-discussion__header">
<div className="livestream-discussion__title">{__('Live discussion')}</div>
{superChatsTotalAmount > 0 && (
{(superChatsTotalAmount || 0) > 0 && (
<div className="recommended-content__toggles">
{/* the superchats in chronological order button */}
<Button
className={classnames('button-toggle', {
'button-toggle--active': viewMode === VIEW_MODE_CHAT,
})}
label={__('Chat')}
onClick={() => setViewMode(VIEW_MODE_CHAT)}
onClick={() => {
setViewMode(VIEW_MODE_CHAT);
const livestreamCommentsDiv = document.getElementsByClassName('livestream__comments')[0];
livestreamCommentsDiv.scrollTop = livestreamCommentsDiv.scrollHeight;
}}
/>
{/* the button to show superchats listed by most to least support amount */}
<Button
className={classnames('button-toggle', {
'button-toggle--active': viewMode === VIEW_MODE_SUPER_CHAT,
})}
label={
<>
<CreditAmount amount={superChatsTotalAmount} size={8} /> {__('Tipped')}
<CreditAmount amount={superChatsTotalAmount || 0} size={8} /> /
<CreditAmount amount={superChatsFiatAmount || 0} size={8} isFiat /> {__('Tipped')}
</>
}
onClick={() => setViewMode(VIEW_MODE_SUPER_CHAT)}
onClick={() => {
setViewMode(VIEW_MODE_SUPER_CHAT);
const livestreamCommentsDiv = document.getElementsByClassName('livestream__comments')[0];
const divHeight = livestreamCommentsDiv.scrollHeight;
livestreamCommentsDiv.scrollTop = divHeight * -1;
}}
/>
</div>
)}
</div>
<>
{fetchingComments && !comments && (
{fetchingComments && !commentsByChronologicalOrder && (
<div className="main--empty">
<Spinner />
</div>
)}
<div ref={commentsRef} className="livestream__comments-wrapper">
{viewMode === VIEW_MODE_CHAT && superChatsTotalAmount > 0 && superChats && (
{viewMode === VIEW_MODE_CHAT && superChatsByTipAmount && (superChatsTotalAmount || 0) > 0 && (
<div className="livestream-superchats__wrapper">
<div className="livestream-superchats__inner">
{superChats.map((superChat: Comment) => (
{superChatsByTipAmount.map((superChat: Comment) => (
<Tooltip key={superChat.comment_id} label={superChat.comment}>
<div className="livestream-superchat">
<div className="livestream-superchat__thumbnail">
@@ -187,36 +233,84 @@ export default function LivestreamComments(props: Props) {
</div>
)}
{!fetchingComments && comments.length > 0 ? (
{pinnedComment && showPinned && viewMode === VIEW_MODE_CHAT && (
<div className="livestream-pinned__wrapper">
<LivestreamComment
key={pinnedComment.comment_id}
uri={uri}
authorUri={pinnedComment.channel_url}
commentId={pinnedComment.comment_id}
message={pinnedComment.comment}
supportAmount={pinnedComment.support_amount}
isModerator={pinnedComment.is_moderator}
isGlobalMod={pinnedComment.is_global_mod}
isFiat={pinnedComment.is_fiat}
isPinned={pinnedComment.is_pinned}
commentIsMine={pinnedComment.channel_id && isMyComment(pinnedComment.channel_id)}
/>
<Button
title={__('Dismiss pinned comment')}
button="inverse"
className="close-button"
onClick={() => setShowPinned(false)}
icon={ICONS.REMOVE}
/>
</div>
)}
{/* top to bottom comment display */}
{!fetchingComments && commentsByChronologicalOrder.length > 0 ? (
<div className="livestream__comments">
{commentsToDisplay.map((comment) => (
<LivestreamComment
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
commentId={comment.comment_id}
message={comment.comment}
supportAmount={comment.support_amount}
isFiat={comment.is_fiat}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
/>
))}
{viewMode === VIEW_MODE_CHAT &&
commentsToDisplay.map((comment) => (
<LivestreamComment
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
commentId={comment.comment_id}
message={comment.comment}
supportAmount={comment.support_amount}
isModerator={comment.is_moderator}
isGlobalMod={comment.is_global_mod}
isFiat={comment.is_fiat}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
/>
))}
{/* listing comments on top of eachother */}
{viewMode === VIEW_MODE_SUPER_CHAT &&
superChatsReversed &&
superChatsReversed.map((comment) => (
<LivestreamComment
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
commentId={comment.comment_id}
message={comment.comment}
supportAmount={comment.support_amount}
isModerator={comment.is_moderator}
isGlobalMod={comment.is_global_mod}
isFiat={comment.is_fiat}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
/>
))}
</div>
) : (
<div className="main--empty" style={{ flex: 1 }} />
)}
{!scrollBottom && (
{scrollPos < 0 && viewMode === VIEW_MODE_CHAT && (
<Button
button="alt"
className="livestream__comments-scroll__down"
button="secondary"
className="livestream__comments__scroll-to-recent"
label={__('Recent Comments')}
onClick={scrollBack}
onClick={restoreScrollPos}
iconRight={ICONS.DOWN}
/>
)}
<div className="livestream__comment-create">
<CommentCreate livestream bottom embed={embed} uri={uri} />
<CommentCreate livestream bottom embed={embed} uri={uri} onDoneReplying={restoreScrollPos} />
</div>
</div>
</>
+2 -2
View File
@@ -1,5 +1,5 @@
// @flow
import { BITWAVE_EMBED_URL } from 'constants/livestream';
import { LIVESTREAM_EMBED_URL } from 'constants/livestream';
import React from 'react';
import FileTitleSection from 'component/fileTitleSection';
import LivestreamComments from 'component/livestreamComments';
@@ -29,7 +29,7 @@ export default function LivestreamLayout(props: Props) {
<div className="file-render file-render--video livestream">
<div className="file-viewer">
<iframe
src={`${BITWAVE_EMBED_URL}/${channelClaimId}?skin=odysee&autoplay=1`}
src={`${LIVESTREAM_EMBED_URL}/${channelClaimId}?skin=odysee&autoplay=1`}
scrolling="no"
allowFullScreen
/>
+19 -8
View File
@@ -1,5 +1,5 @@
// @flow
import { BITWAVE_LIVE_API } from 'constants/livestream';
import { LIVESTREAM_LIVE_API } from 'constants/livestream';
import * as CS from 'constants/claim_search';
import React from 'react';
import Card from 'component/common/card';
@@ -18,11 +18,16 @@ export default function LivestreamLink(props: Props) {
const [livestreamClaim, setLivestreamClaim] = React.useState(false);
const [isLivestreaming, setIsLivestreaming] = React.useState(false);
const livestreamChannelId = (channelClaim && channelClaim.claim_id) || ''; // TODO: fail in a safer way, probably
const isChannelEmpty = !channelClaim || !channelClaim.meta || !channelClaim.meta.claims_in_channel;
React.useEffect(() => {
if (livestreamChannelId) {
// Don't search empty channels
if (livestreamChannelId && !isChannelEmpty) {
Lbry.claim_search({
channel_ids: [livestreamChannelId],
page: 1,
page_size: 1,
no_totals: true,
has_no_source: true,
claim_type: ['stream'],
order_by: CS.ORDER_BY_NEW_VALUE,
@@ -35,12 +40,12 @@ export default function LivestreamLink(props: Props) {
})
.catch(() => {});
}
}, [livestreamChannelId]);
}, [livestreamChannelId, isChannelEmpty]);
React.useEffect(() => {
function fetchIsStreaming() {
// $FlowFixMe Bitwave's API can handle garbage
fetch(`${BITWAVE_LIVE_API}/${livestreamChannelId}`)
// $FlowFixMe livestream API can handle garbage
fetch(`${LIVESTREAM_LIVE_API}/${livestreamChannelId}`)
.then((res) => res.json())
.then((res) => {
if (res && res.success && res.data && res.data.live) {
@@ -53,17 +58,23 @@ export default function LivestreamLink(props: Props) {
}
let interval;
if (livestreamChannelId) {
// Only call livestream api if channel has livestream claims
if (livestreamChannelId && livestreamClaim) {
if (!interval) fetchIsStreaming();
interval = setInterval(fetchIsStreaming, 10 * 1000);
}
// Prevent any more api calls on update
if (!livestreamChannelId || !livestreamClaim) {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [livestreamChannelId]);
}, [livestreamChannelId, livestreamClaim]);
if (!livestreamClaim || !isLivestreaming) {
return null;
+2 -2
View File
@@ -1,6 +1,6 @@
// @flow
import * as ICONS from 'constants/icons';
import { BITWAVE_LIVE_API } from 'constants/livestream';
import { LIVESTREAM_LIVE_API } from 'constants/livestream';
import React from 'react';
import Icon from 'component/common/icon';
import Spinner from 'component/spinner';
@@ -14,7 +14,7 @@ export default function LivestreamList() {
React.useEffect(() => {
function checkCurrentLivestreams() {
fetch(BITWAVE_LIVE_API)
fetch(LIVESTREAM_LIVE_API)
.then((res) => res.json())
.then((res) => {
setLoading(false);
+10
View File
@@ -0,0 +1,10 @@
import { connect } from 'react-redux';
import Logo from './view';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { SETTINGS } from 'lbry-redux';
const select = (state, props) => ({
currentTheme: makeSelectClientSetting(SETTINGS.THEME)(state),
});
export default connect(select)(Logo);
+64
View File
@@ -0,0 +1,64 @@
// @flow
import React from 'react';
import * as ICONS from 'constants/icons';
import { LOGO_TITLE, LOGO, LOGO_TEXT_LIGHT, LOGO_TEXT_DARK } from 'config';
import Icon from 'component/common/icon';
import { useIsMobile } from 'effects/use-screensize';
type Props = {
type: string,
currentTheme: string,
};
export default function Logo(props: Props) {
const { type, currentTheme } = props;
const isMobile = useIsMobile();
const defaultWithLabel = (
<>
<Icon icon={ICONS.LBRY} />
{/* @if TARGET='app' */}
<div className={'button__label'}>{'LBRY'}</div>
{/* @endif */}
{/* @if TARGET='web' */}
<div className={'button__label'}>{LOGO_TITLE}</div>
{/* @endif */}
</>
);
if (type === 'small' || (isMobile && type !== 'embed')) {
return LOGO ? <img className={'header__navigation-logo'} src={LOGO} /> : <Icon icon={ICONS.LBRY} />;
} else if (type === 'embed') {
if (LOGO_TEXT_LIGHT) {
return (
<>
<img className={'embed__overlay-logo'} src={LOGO_TEXT_LIGHT} />
</>
);
} else {
return defaultWithLabel;
}
} else if (type === 'embed-ended') {
if (LOGO_TEXT_LIGHT) {
return (
<>
<img className={'embed__overlay-logo'} src={LOGO_TEXT_LIGHT} />
</>
);
} else {
return defaultWithLabel;
}
} else {
if (LOGO_TEXT_LIGHT && LOGO_TEXT_DARK) {
return (
<>
<img
className={'header__navigation-logo'}
src={currentTheme === 'light' ? LOGO_TEXT_DARK : LOGO_TEXT_LIGHT}
/>
</>
);
} else {
return defaultWithLabel;
}
}
}
+13
View File
@@ -0,0 +1,13 @@
import { connect } from 'react-redux';
import { doSetDaemonSetting } from 'redux/actions/settings';
import { selectDaemonSettings } from 'redux/selectors/settings';
import MaxPurchasePrice from './view';
const select = (state) => ({
daemonSettings: selectDaemonSettings(state),
});
const perform = (dispatch) => ({
setDaemonSetting: (key, value) => dispatch(doSetDaemonSetting(key, value)),
});
export default connect(select, perform)(MaxPurchasePrice);
+72
View File
@@ -0,0 +1,72 @@
// @flow
import React from 'react';
import { FormField, FormFieldPrice } from 'component/common/form';
type Price = {
currency: string,
amount: number,
};
type DaemonSettings = {
download_dir: string,
share_usage_data: boolean,
max_key_fee?: Price,
max_connections_per_download?: number,
save_files: boolean,
save_blobs: boolean,
ffmpeg_path: string,
};
type SetDaemonSettingArg = boolean | string | number | Price;
type Props = {
daemonSettings: DaemonSettings,
setDaemonSetting: (string, ?SetDaemonSettingArg) => void,
};
export default function MaxPurchasePrice(props: Props) {
const { daemonSettings, setDaemonSetting } = props;
const defaultMaxKeyFee = { currency: 'USD', amount: 50 };
const disableMaxKeyFee = !(daemonSettings && daemonSettings.max_key_fee);
function onKeyFeeDisableChange(isDisabled: boolean) {
if (isDisabled) {
setDaemonSetting('max_key_fee');
}
}
function onKeyFeeChange(newValue: Price) {
setDaemonSetting('max_key_fee', newValue);
}
return (
<>
<FormField
type="radio"
name="no_max_purchase_no_limit"
checked={disableMaxKeyFee}
label={__('No Limit')}
onChange={() => onKeyFeeDisableChange(true)}
/>
<FormField
type="radio"
name="max_purchase_limit"
checked={!disableMaxKeyFee}
onChange={() => {
onKeyFeeDisableChange(false);
onKeyFeeChange(defaultMaxKeyFee);
}}
label={__('Choose limit')}
/>
<FormFieldPrice
name="max_key_fee"
min={0}
onChange={onKeyFeeChange}
price={daemonSettings.max_key_fee ? daemonSettings.max_key_fee : defaultMaxKeyFee}
disabled={disableMaxKeyFee}
/>
</>
);
}
+137 -48
View File
@@ -16,6 +16,11 @@ import FileThumbnail from 'component/fileThumbnail';
import { Menu, MenuList, MenuButton, MenuItem } from '@reach/menu-button';
import NotificationContentChannelMenu from 'component/notificationContentChannelMenu';
import LbcMessage from 'component/common/lbc-message';
import UriIndicator from 'component/uriIndicator';
import { NavLink } from 'react-router-dom';
import CommentReactions from 'component/commentReactions';
import CommentCreate from 'component/commentCreate';
import CommentsReplies from 'component/commentsReplies';
type Props = {
notification: WebNotification,
@@ -29,13 +34,14 @@ export default function Notification(props: Props) {
const { notification, menuButton = false, doReadNotifications, doDeleteNotification } = props;
const { push } = useHistory();
const { notification_rule, notification_parameters, is_read, id } = notification;
const [isReplying, setReplying] = React.useState(false);
const [quickReply, setQuickReply] = React.useState();
const isCommentNotification =
notification_rule === RULE.COMMENT ||
notification_rule === RULE.COMMENT_REPLY ||
notification_rule === RULE.CREATOR_COMMENT;
const commentText = isCommentNotification && notification_parameters.dynamic.comment;
const channelUrl =
(notification_rule === RULE.NEW_CONTENT && notification.notification_parameters.dynamic.channel_url) || '';
let notificationTarget;
switch (notification_rule) {
@@ -51,21 +57,14 @@ export default function Notification(props: Props) {
notificationTarget = notification_parameters.device.target;
}
let notificationLink = formatLbryUrlForWeb(notificationTarget);
let urlParams = new URLSearchParams();
if (isCommentNotification && notification_parameters.dynamic.hash) {
urlParams.append('lc', notification_parameters.dynamic.hash);
}
try {
const { isChannel } = parseURI(notificationTarget);
if (isChannel) {
urlParams.append(PAGE_VIEW_QUERY, DISCUSSION_PAGE);
}
} catch (e) {}
notificationLink += `?${urlParams.toString()}`;
const creatorIcon = (channelUrl) => {
return (
<UriIndicator uri={channelUrl} link>
<ChannelThumbnail small uri={channelUrl} />
</UriIndicator>
);
};
let channelUrl;
let icon;
switch (notification_rule) {
case RULE.CREATOR_SUBSCRIBER:
@@ -73,16 +72,20 @@ export default function Notification(props: Props) {
break;
case RULE.COMMENT:
case RULE.CREATOR_COMMENT:
icon = <ChannelThumbnail small uri={notification_parameters.dynamic.comment_author} />;
channelUrl = notification_parameters.dynamic.comment_author;
icon = creatorIcon(channelUrl);
break;
case RULE.COMMENT_REPLY:
icon = <ChannelThumbnail small uri={notification_parameters.dynamic.reply_author} />;
channelUrl = notification_parameters.dynamic.reply_author;
icon = creatorIcon(channelUrl);
break;
case RULE.NEW_CONTENT:
icon = <ChannelThumbnail small uri={notification_parameters.dynamic.channel_url} />;
channelUrl = notification_parameters.dynamic.channel_url;
icon = creatorIcon(channelUrl);
break;
case RULE.NEW_LIVESTREAM:
icon = <ChannelThumbnail small uri={notification_parameters.dynamic.channel_url} />;
channelUrl = notification_parameters.dynamic.channel_url;
icon = creatorIcon(channelUrl);
break;
case RULE.DAILY_WATCH_AVAILABLE:
case RULE.DAILY_WATCH_REMIND:
@@ -97,21 +100,59 @@ export default function Notification(props: Props) {
icon = <Icon icon={ICONS.NOTIFICATION} sectionIcon />;
}
let notificationLink = formatLbryUrlForWeb(notificationTarget);
let urlParams = new URLSearchParams();
if (isCommentNotification && notification_parameters.dynamic.hash) {
urlParams.append('lc', notification_parameters.dynamic.hash);
}
let channelName = channelUrl && '@' + channelUrl.split('@')[1].split('#')[0];
const notificationTitle = notification_parameters.device.title;
const titleSplit = notificationTitle.split(' ');
let fullTitle = [' '];
let uriIndicator;
const title = titleSplit.map((message, index) => {
if (channelName === message) {
uriIndicator = <UriIndicator uri={channelUrl} link />;
fullTitle.push(' ');
const resultTitle = fullTitle;
fullTitle = [' '];
return [resultTitle.join(' '), uriIndicator];
} else {
fullTitle.push(message);
if (index === titleSplit.length - 1) {
const result = fullTitle.join(' ');
return <LbcMessage key={result}>{result}</LbcMessage>;
}
}
});
try {
const { isChannel } = parseURI(notificationTarget);
if (isChannel) {
urlParams.append(PAGE_VIEW_QUERY, DISCUSSION_PAGE);
}
} catch (e) {}
notificationLink += `?${urlParams.toString()}`;
const navLinkProps = {
to: notificationLink,
onClick: (e) => e.stopPropagation(),
};
function handleNotificationClick() {
if (!is_read) {
doReadNotifications([id]);
}
if (notificationLink) {
if (menuButton && notificationLink) {
push(notificationLink);
}
}
function handleReadNotification(e) {
e.stopPropagation();
doReadNotifications([id]);
}
const Wrapper = menuButton
? (props: { children: any }) => (
<MenuItem className="menu__link--notification" onSelect={handleNotificationClick}>
@@ -120,9 +161,9 @@ export default function Notification(props: Props) {
)
: notificationLink
? (props: { children: any }) => (
<a className="menu__link--notification" onClick={handleNotificationClick}>
<NavLink {...navLinkProps} className="menu__link--notification" onClick={handleNotificationClick}>
{props.children}
</a>
</NavLink>
)
: (props: { children: any }) => (
<span
@@ -134,29 +175,23 @@ export default function Notification(props: Props) {
);
return (
<Wrapper>
<div
className={classnames('notification__wrapper', {
'notification__wrapper--unread': !is_read,
})}
>
<div
className={classnames('notification__wrapper', {
'notification__wrapper--unread': !is_read,
})}
>
<Wrapper>
<div className="notification__icon">{icon}</div>
<div className="notification__content-wrapper">
<div className="notification__content">
<div className="notification__text-wrapper">
{!isCommentNotification && (
<div className="notification__title">
<LbcMessage>{notification_parameters.device.title}</LbcMessage>
</div>
)}
{!isCommentNotification && <div className="notification__title">{title}</div>}
{isCommentNotification && commentText ? (
<>
<div className="notification__title">
<LbcMessage>{notification_parameters.device.title}</LbcMessage>
</div>
<div title={commentText} className="notification__text mobile-hidden">
<div className="notification__title">{title}</div>
<div title={commentText} className="notification__text">
{commentText}
</div>
</>
@@ -184,7 +219,15 @@ export default function Notification(props: Props) {
</div>
<div className="notification__extra">
{!is_read && <Button className="notification__mark-seen" onClick={handleReadNotification} />}
{!is_read && (
<Button
className="notification__mark-seen"
onClick={(e) => {
e.stopPropagation();
doReadNotifications([id]);
}}
/>
)}
<div className="notification__time">
<DateTime timeAgo date={notification.active_at} />
</div>
@@ -193,7 +236,13 @@ export default function Notification(props: Props) {
<div className="notification__menu">
<Menu>
<MenuButton onClick={(e) => e.stopPropagation()}>
<MenuButton
className={'menu__button notification__menu-button'}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
}}
>
<Icon size={18} icon={ICONS.MORE_VERTICAL} />
</MenuButton>
<MenuList className="menu__list">
@@ -207,7 +256,47 @@ export default function Notification(props: Props) {
</MenuList>
</Menu>
</div>
</div>
</Wrapper>
</Wrapper>
{isCommentNotification && (
<div>
<div className="notification__reactions">
<Button
label={__('Reply')}
className="comment__action"
onClick={() => setReplying(!isReplying)}
icon={ICONS.REPLY}
/>
<CommentReactions
uri={notificationTarget}
commentId={notification_parameters.dynamic.hash}
hideCreatorLike
/>
</div>
{isReplying && (
<CommentCreate
isReply
uri={notificationTarget}
parentId={notification_parameters.dynamic.hash}
onDoneReplying={() => setReplying(false)}
onCancelReplying={() => setReplying(false)}
setQuickReply={setQuickReply}
supportDisabled
shouldFetchComment
/>
)}
{quickReply && (
<CommentsReplies
uri={notificationTarget}
parentId={notification_parameters.dynamic.hash}
numDirectReplies={1}
supportDisabled
/>
)}
</div>
)}
</div>
);
}
+25 -8
View File
@@ -4,6 +4,7 @@ import React, { Fragment } from 'react';
import classnames from 'classnames';
import { lazyImport } from 'util/lazyImport';
import SideNavigation from 'component/sideNavigation';
import SettingsSideNavigation from 'component/settingsSideNavigation';
import Header from 'component/header';
/* @if TARGET='app' */
import StatusBar from 'component/common/status-bar';
@@ -23,6 +24,7 @@ type Props = {
isUpgradeAvailable: boolean,
authPage: boolean,
filePage: boolean,
settingsPage?: boolean,
noHeader: boolean,
noFooter: boolean,
noSideNavigation: boolean,
@@ -45,6 +47,7 @@ function Page(props: Props) {
children,
className,
filePage = false,
settingsPage,
authPage = false,
fullWidthPage = false,
noHeader = false,
@@ -76,6 +79,24 @@ function Page(props: Props) {
const isAbsoluteSideNavHidden = (isOnFilePage || isMobile) && !sidebarOpen;
function getSideNavElem() {
if (!authPage) {
if (settingsPage) {
return <SettingsSideNavigation />;
} else if (!noSideNavigation) {
return (
<SideNavigation
sidebarOpen={sidebarOpen}
setSidebarOpen={setSidebarOpen}
isMediumScreen={isMediumScreen}
isOnFilePage={isOnFilePage}
/>
);
}
}
return null;
}
React.useEffect(() => {
if (isOnFilePage || isMediumScreen) {
setSidebarOpen(false);
@@ -100,19 +121,15 @@ function Page(props: Props) {
'main-wrapper__inner--theater-mode': isOnFilePage && videoTheaterMode,
})}
>
{!authPage && !noSideNavigation && (
<SideNavigation
sidebarOpen={sidebarOpen}
setSidebarOpen={setSidebarOpen}
isMediumScreen={isMediumScreen}
isOnFilePage={isOnFilePage}
/>
)}
{getSideNavElem()}
<main
id={'main-content'}
className={classnames(MAIN_CLASS, className, {
'main--full-width': fullWidthPage,
'main--auth-page': authPage,
'main--file-page': filePage,
'main--settings-page': settingsPage,
'main--markdown': isMarkdown,
'main--theater-mode': isOnFilePage && videoTheaterMode && !livestream,
'main--livestream': livestream && !chatDisabled,
@@ -36,7 +36,7 @@ export default function PreviewOverlayProperties(props: Props) {
} = props;
const isCollection = claim && claim.value_type === 'collection';
// $FlowFixMe
const claimLength = claim && claim.value.claims && claim.value.claims.length;
const claimLength = claim && claim.value && claim.value.claims && claim.value.claims.length;
const claimCount = editedCollection ? editedCollection.items.length : claimLength;
const isStream = claim && claim.value_type === 'stream';
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff. Show more