Compare commits

..
1 Commits
Author SHA1 Message Date
infinite-persistence a7c95d0bc9 Allow admins to delete comments as well. (#250) 2022-01-24 11:46:43 -05:00
270 changed files with 6790 additions and 9360 deletions

No files matched your search

+3 -8
View File
@@ -24,7 +24,7 @@ jobs:
os:
- ubuntu-latest
- macos-latest
# - windows-latest
- windows-latest
runs-on: ${{ matrix.os }}
steps:
@@ -49,19 +49,14 @@ jobs:
yarn global add cross-env
yarn
yarn build
node ./build/afterSignHook.js
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
NOTARIZATION_USERNAME: ${{ secrets.NOTARIZATION_USERNAME }}
NOTARIZATION_PASSWORD: ${{ secrets.NOTARIZATION_PASSWORD }}
WIN_CSC_KEY_PASSWORD: ${{ secrets.WIN_CSC_KEY_PASSWORD }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
ARTIFACTS_BUCKET: ${{ secrets.ARTIFACTS_BUCKET }}
ARTIFACTS_KEY: ${{ secrets.ARTIFACTS_KEY }}
ARTIFACTS_SECRET: ${{ secrets.ARTIFACTS_SECRET }}
ARTIFACTS_REGION: ${{ secrets.ARTIFACTS_REGION }}
WIN_CSC_LINK: https://raw.githubusercontent.com/lbryio/lbry-desktop/master/build/win-csc-2021-2022-08.p12
WIN_CSC_LINK: https://raw.githubusercontent.com/lbryio/lbry-desktop/master/build/cert-2021-2022.pfx
CSC_LINK: https://s3.amazonaws.com/files.lbry.io/cert/osx-csc-2021-2022.p12
# UI
@@ -99,7 +94,7 @@ jobs:
- uses: actions/upload-artifact@v2
if: |
github.event.pull_request.head.repo.full_name == github.repository
startsWith(runner.os, 'windows')
with:
name: Windows
path: ./dist/electron/*.*
+35 -4
View File
@@ -4,12 +4,31 @@ 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.52.0] - [2021-10-24]
## [0.52.1-alpha.3] - [2021-12-31]
### Added
- Reenabled generating thumbs from video ([#7384](https://github.com/lbryio/lbry-desktop/pull/7409))
### Changed
- Upgraded Electron to v15 ([#7384](https://github.com/lbryio/lbry-desktop/pull/7384))
- Performance improvements in some selectors ([#7370](https://github.com/lbryio/lbry-desktop/pull/7370))
### Fixed
- Several fallout bugs from recent changes
- Added duration overlays to ClaimPreview component ([#7420](https://github.com/lbryio/lbry-desktop/pull/7420))
## [0.52.0] - [2021-12-31]
### Compatibility
- Mac <= 10.13 (High Sierra) and Ubuntu <= 16 (Xenial) are no longer supported. If you upgrade, you will need to manually build and install your own lbrynet SDK
### 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))
@@ -20,8 +39,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Disk space setting under Data Hosting ([#7266](https://github.com/lbryio/lbry-desktop/pull/7266))
- Paginated 'All Playlists' page ([#7268](https://github.com/lbryio/lbry-desktop/pull/7268))
- Expanded playlist ordering tools ([#7305](https://github.com/lbryio/lbry-desktop/pull/7305))
- Setting to upgrade to alpha prerelease builds ([#7353](https://github.com/lbryio/lbry-desktop/pull/7353))
### Changed
- 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))
@@ -33,8 +54,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Upgraded Electron to v11.5.0 ([#7276](https://github.com/lbryio/lbry-desktop/pull/7276))
- Cleaner Discover page filters ([#7306](https://github.com/lbryio/lbry-desktop/pull/7306))
- Scroll bar styling ([#7314](https://github.com/lbryio/lbry-desktop/pull/7314))
- Remove pages for obsolete features like invites, rewards, swap ([#7330](https://github.com/lbryio/lbry-desktop/pull/7330))
- Change file repost to modal _community pr!_ ([#7341](https://github.com/lbryio/lbry-desktop/pull/7341))
### Fixed
- Clicking on the title of a floating player will take you back to the list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Fix floating player stopping on markdown or image files ([#7073](https://github.com/lbryio/lbry-desktop/pull/7073))
- Fix list thumbnail upload ([#7074](https://github.com/lbryio/lbry-desktop/pull/7074))
@@ -43,17 +67,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Fixed “Your Account” popup on mobile ([#7172](https://github.com/lbryio/lbry-desktop/pull/7172))
- Fix disable-support for comments ([#7245](https://github.com/lbryio/lbry-desktop/pull/7245))
- Fix Electron taking over .html files on linux ([#7291](https://github.com/lbryio/lbry-desktop/pull/7291))
- Fix floating player play/pause on drag _community pr!_ ([#7339](https://github.com/lbryio/lbry-desktop/pull/7339))
- Fix card dropdown menus triggering menu actions _community pr!_ ([#7335](https://github.com/lbryio/lbry-desktop/pull/7335))
## [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 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))
### 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))
@@ -64,6 +92,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Improved clickability of notification links _community pr!_ ([#6711](https://github.com/lbryio/lbry-desktop/pull/6711))
### 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))
@@ -89,18 +118,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Changed
### Fixed
- Enable sign up on desktop ([#6071](https://github.com/lbryio/lbry-desktop/issues/6071))
## [0.51.0] - [2021-06-26]
### Added
- Private and Publishable Playlists ([#6157](https://github.com/lbryio/lbry-desktop/pull/6157))
- Channel thumbnails in following side menu ([#6193](https://github.com/lbryio/lbry-desktop/pull/6193))
- Web is now PWA app ([#6120](https://github.com/lbryio/lbry-desktop/pull/6120))
- Send a tip with your comment ([#5920](https://github.com/lbryio/lbry-desktop/issues/5920))
- Search for tags in search dropdown ([#5876](https://github.com/lbryio/lbry-desktop/issues/5876))
- Japanese, Afrikaans, Filipino, Thai and Vietnamese language support ([#5684](https://github.com/lbryio/lbry-desktop/issues/5684))
- Brazilian-Portuguese language support ([#5900](https://github.com/lbryio/lbry-desktop/issues/5900))
- Brazilian-Portuguese language support ([#5900](https://github.com/lbryio/lbry-desktop/issues/5900))
- Highlight comments made by content owner _community pr!_ ([#5744](https://github.com/lbryio/lbry-desktop/pull/5744))
- Ability to report infringing content directly from the application ([#5808](https://github.com/lbryio/lbry-desktop/pull/5808))
- Re-added ability to export wallet transactions ([#5899](https://github.com/lbryio/lbry-desktop/pull/5899))
Binary file not shown.
Binary file not shown.
-5
View File
@@ -20,11 +20,6 @@
"to": "static/daemon/",
"filter": ["**/*"]
},
{
"from": "./static/lbry-first/",
"to": "static/lbry-first/",
"filter": ["**/*"]
},
{
"from": "./static/img",
"to": "static/img",
+6 -5
View File
@@ -1,5 +1,5 @@
import { WEBPACK_ELECTRON_PORT } from 'config';
import { app, BrowserWindow, dialog, shell, screen, nativeImage } from 'electron';
import { app, BrowserWindow, dialog, screen, nativeImage } from 'electron';
import isDev from 'electron-is-dev';
import windowStateKeeper from 'electron-window-state';
import SUPPORTED_LANGUAGES from 'constants/supported_languages';
@@ -9,7 +9,7 @@ import { TO_TRAY_WHEN_CLOSED } from 'constants/settings';
import setupBarMenu from './menu/setupBarMenu';
import * as PAGES from 'constants/pages';
const remote = require('@electron/remote/main');
function GetAppLangCode() {
// https://www.electronjs.org/docs/api/locales
// 1. Gets the user locale.
@@ -54,6 +54,7 @@ export default appState => {
webSecurity: !isDev,
plugins: true,
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true, // see about removing this
},
};
@@ -62,6 +63,7 @@ export default appState => {
const rendererURL = isDev ? `http://localhost:${WEBPACK_ELECTRON_PORT}` : `file://${__dirname}/index.html`;
let window = new BrowserWindow(windowConfiguration);
remote.enable(window.webContents);
// Let us register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
@@ -187,9 +189,8 @@ export default appState => {
window = null;
});
window.webContents.on('new-window', (event, url) => {
event.preventDefault();
shell.openExternal(url);
window.webContents.setWindowOpenHandler((details) => {
return { action: 'deny' };
});
window.webContents.on('update-target-url', (event, url) => {
+2
View File
@@ -18,6 +18,8 @@ import installDevtools from './installDevtools';
import fs from 'fs';
import path from 'path';
const { download } = require('electron-dl');
const remote = require('@electron/remote/main');
remote.initialize();
const filePath = path.join(process.resourcesPath, 'static', 'upgradeDisabled');
let upgradeDisabled;
try {
+7 -4
View File
@@ -38,8 +38,8 @@ export { syncReducer } from './redux/reducers/sync';
// selectors
export { selectAuthToken, selectIsAuthenticating } from './redux/selectors/auth';
export {
makeSelectFetchingCostInfoForUri,
makeSelectCostInfoForUri,
selectFetchingCostInfoForUri,
selectCostInfoForUri,
selectAllCostInfoByUri,
selectFetchingCostInfo,
} from './redux/selectors/cost_info';
@@ -50,9 +50,12 @@ export {
export { selectFilteredOutpoints, selectFilteredOutpointMap } from './redux/selectors/filtered';
export {
selectViewCount,
makeSelectViewCountForUri,
makeSelectSubCountForUri,
selectViewCountForUri,
// makeSelectViewCountForUri, // deprecated
selectSubCountForUri,
// makeSelectSubCountForUri, // deprecated
} from './redux/selectors/stats';
export { selectBanStateForUri } from './redux/selectors/ban';
export {
selectHasSyncedWallet,
selectSyncData,
+68
View File
@@ -0,0 +1,68 @@
// @flow
// TODO: This should be in 'redux/selectors/claim.js'. Temporarily putting it
// here to get past importing issues with 'lbryinc', which the real fix might
// involve moving it from 'extras' to 'ui' (big change).
import { createCachedSelector } from 're-reselect';
import { selectClaimForUri } from 'redux/selectors/claims';
import { selectMutedChannels } from 'redux/selectors/blocked';
import { selectModerationBlockList } from 'redux/selectors/comments';
import { selectBlacklistedOutpointMap, selectFilteredOutpointMap } from 'lbryinc';
import { getChannelFromClaim } from 'util/claim';
import { isURIEqual } from 'util/lbryURI';
export const selectBanStateForUri = createCachedSelector(
selectClaimForUri,
selectBlacklistedOutpointMap,
selectFilteredOutpointMap,
selectMutedChannels,
selectModerationBlockList,
(claim, blackListedOutpointMap, filteredOutpointMap, mutedChannelUris, personalBlocklist) => {
const banState = {};
if (!claim) {
return banState;
}
const channelClaim = getChannelFromClaim(claim);
// This will be replaced once blocking is done at the wallet server level.
if (blackListedOutpointMap) {
if (
(channelClaim && blackListedOutpointMap[`${channelClaim.txid}:${channelClaim.nout}`]) ||
blackListedOutpointMap[`${claim.txid}:${claim.nout}`]
) {
banState['blacklisted'] = true;
}
}
// We're checking to see if the stream outpoint or signing channel outpoint
// is in the filter list.
if (filteredOutpointMap) {
if (
(channelClaim && filteredOutpointMap[`${channelClaim.txid}:${channelClaim.nout}`]) ||
filteredOutpointMap[`${claim.txid}:${claim.nout}`]
) {
banState['filtered'] = true;
}
}
// block stream claims
// block channel claims if we can't control for them in claim search
if (mutedChannelUris.length && channelClaim) {
if (mutedChannelUris.some((blockedUri) => isURIEqual(blockedUri, channelClaim.permanent_url))) {
banState['muted'] = true;
}
}
// Commentron blocklist
if (personalBlocklist.length && channelClaim) {
if (personalBlocklist.some((blockedUri) => isURIEqual(blockedUri, channelClaim.permanent_url))) {
banState['blocked'] = true;
}
}
return banState;
}
)((state, uri) => String(uri));
+13 -10
View File
@@ -1,13 +1,16 @@
import { createSelector } from 'reselect';
// @flow
type State = { costInfo: any };
export const selectState = state => state.costInfo || {};
export const selectState = (state: State) => state.costInfo || {};
export const selectAllCostInfoByUri = (state: State) => selectState(state).byUri;
export const selectFetchingCostInfo = (state: State) => selectState(state).fetching;
export const selectAllCostInfoByUri = createSelector(selectState, state => state.byUri || {});
export const selectCostInfoForUri = (state: State, uri: string) => {
const costInfos = selectAllCostInfoByUri(state);
return costInfos && costInfos[uri];
};
export const makeSelectCostInfoForUri = uri =>
createSelector(selectAllCostInfoByUri, costInfos => costInfos && costInfos[uri]);
export const selectFetchingCostInfo = createSelector(selectState, state => state.fetching || {});
export const makeSelectFetchingCostInfoForUri = uri =>
createSelector(selectFetchingCostInfo, fetchingByUri => fetchingByUri && fetchingByUri[uri]);
export const selectFetchingCostInfoForUri = (state: State, uri: string) => {
const fetchingByUri = selectFetchingCostInfo(state);
return fetchingByUri && fetchingByUri[uri];
};
+13 -13
View File
@@ -1,20 +1,20 @@
// @flow
import { createSelector } from 'reselect';
import { makeSelectClaimForUri } from 'redux/selectors/claims';
import { selectClaimIdForUri } from 'redux/selectors/claims';
type State = { claims: any };
const selectState = state => state.stats || {};
export const selectViewCount = createSelector(selectState, state => state.viewCountById);
export const selectSubCount = createSelector(selectState, state => state.subCountById);
export const makeSelectViewCountForUri = uri =>
createSelector(
makeSelectClaimForUri(uri),
selectViewCount,
(claim, viewCountById) => (claim ? viewCountById[claim.claim_id] || 0 : 0)
);
export const selectViewCountForUri = (state: State, uri: string) => {
const claimId = selectClaimIdForUri(state, uri);
const viewCountById = selectViewCount(state);
return claimId ? viewCountById[claimId] || 0 : 0;
};
export const makeSelectSubCountForUri = uri =>
createSelector(
makeSelectClaimForUri(uri),
selectSubCount,
(claim, subCountById) => (claim ? subCountById[claim.claim_id] || 0 : 0)
);
export const selectSubCountForUri = (state: State, uri: string) => {
const claimId = selectClaimIdForUri(state, uri);
const subCountById = selectSubCount(state);
return claimId ? subCountById[claimId] || 0 : 0;
};
+2 -1
View File
@@ -94,7 +94,8 @@ const recsys = {
createRecsysEntry: function (claimId, parentUuid) {
if (window.store && claimId) {
const state = window.store.getState();
const { id: userId } = selectUser(state);
const user = selectUser(state);
const userId = user ? user.id : null;
if (parentUuid) {
// Make a stub entry that will be filled out on page load
recsys.entries[claimId] = {
+3 -1
View File
@@ -204,9 +204,11 @@ declare type ModerationBlockParams = {
// Creator that Moderator is delegated from. Used for delegated moderation
creator_channel_id?: string,
creator_channel_name?: string,
// ID of comment to remove as part of this block
offending_comment_id?: string,
// Blocks identity from comment universally, requires Admin rights on commentron instance
block_all?: boolean,
time_out?: number,
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
+3
View File
@@ -29,8 +29,10 @@ declare type SearchOptions = {
declare type SearchState = {
options: SearchOptions,
resultsByQuery: {},
results: Array<string>,
hasReachedMaxResultsLength: {},
searching: boolean,
mentionQuery: string,
};
declare type SearchSuccess = {
@@ -41,6 +43,7 @@ declare type SearchSuccess = {
size: number,
uris: Array<string>,
recsys: string,
query: string,
},
};
+13 -11
View File
@@ -1,6 +1,6 @@
{
"name": "lbry",
"version": "0.52.0-rc.7",
"version": "0.52.1-alpha.5",
"description": "A browser for the LBRY network, a digital marketplace controlled by its users.",
"keywords": [
"lbry"
@@ -44,6 +44,10 @@
"postinstall:warning": "echo '\n\nWARNING\n\nNot all node modules were installed because NODE_ENV is set to \"production\".\nThis should only be set after installing dependencies with \"yarn\". The app will not work.\n\n'"
},
"dependencies": {
"@emotion/react": "^11.6.0",
"@emotion/styled": "^11.6.0",
"@mui/material": "^5.2.1",
"@electron/remote": "^2.0.1",
"@ungap/from-entries": "^0.2.1",
"auto-launch": "^5.0.5",
"electron-dl": "^3.2.0",
@@ -54,18 +58,15 @@
"humanize-duration": "^3.27.0",
"if-env": "^1.0.4",
"match-sorter": "^6.3.0",
"node-html-parser": "^5.1.0",
"parse-duration": "^1.0.0",
"proxy-polyfill": "0.1.6",
"re-reselect": "^4.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",
"videojs-ima": "^1.11.0",
"videojs-logo": "^2.1.4"
},
"devDependencies": {
@@ -83,12 +84,12 @@
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.0.0",
"@datapunt/matomo-tracker-js": "^0.1.4",
"@exponent/electron-cookies": "^2.0.0",
"@hot-loader/react-dom": "^16.13",
"@meetfranz/electron-cookies": "^3.0.2",
"@reach/auto-id": "^0.13.0",
"@reach/combobox": "^0.12.1",
"@reach/menu-button": "0.7.4",
"@reach/rect": "^0.13.0",
"@reach/rect": "^0.16.0",
"@reach/tabs": "^0.1.5",
"@reach/tooltip": "^0.12.1",
"@reach/utils": "^0.12.1",
@@ -109,7 +110,7 @@
"codemirror": "^5.39.2",
"concurrently": "^4.1.2",
"connected-react-router": "^6.8.0",
"copy-webpack-plugin": "^5.1.2",
"copy-webpack-plugin": "^6.4.1",
"copyfiles": "^2.4.1",
"country-data": "^0.0.31",
"cross-env": "^7.0.3",
@@ -124,7 +125,7 @@
"dom-scroll-into-view": "^1.2.1",
"dotenv-defaults": "^2.0.1",
"dotenv-webpack": "^1.8.0",
"electron": "11.5.0",
"electron": "15.3.2",
"electron-builder": "^22.9.1",
"electron-devtools-installer": "^3.1.1",
"electron-is-dev": "^0.3.0",
@@ -162,6 +163,7 @@
"moment": "^2.22.0",
"node-abi": "^2.5.1",
"node-fetch": "^2.6.1",
"node-html-parser": "^5.1.0",
"node-libs-browser": "^2.1.0",
"node-loader": "^0.6.0",
"node-wget": "^0.4.3",
@@ -208,7 +210,7 @@
"stream-to-blob-url": "^2.1.1",
"strip-markdown": "^3.0.3",
"style-loader": "^0.23.1",
"terser-webpack-plugin": "^1.2.3",
"terser-webpack-plugin": "^4.2.3",
"three": "^0.125.0",
"three-full": "^17.1.0",
"tiny-relative-date": "^1.3.0",
@@ -221,7 +223,7 @@
"videojs-event-tracking": "^1.0.1",
"villain-react": "^1.0.9",
"wavesurfer.js": "^2.2.1",
"webpack": "^4.28.4",
"webpack": "^4.44.2",
"webpack-bundle-analyzer": "^3.1.0",
"webpack-cli": "^3.3.10",
"webpack-config-utils": "^2.3.1",
+25
View File
@@ -2222,5 +2222,30 @@
"Your wallet is not currently using a cloud sync service. You are in control of backing up your wallet.": "Your wallet is not currently using a cloud sync service. You are in control of backing up your wallet.",
"Sending": "Sending",
"You sent %lbc%": "You sent %lbc%",
"Buy LBC": "Buy LBC",
"This is information like error logging, performance tracking, and usage statistics. It includes your IP address and basic system details, but no other identifying information (unless you connect to a cloud service)": "This is information like error logging, performance tracking, and usage statistics. It includes your IP address and basic system details, but no other identifying information (unless you connect to a cloud service)",
"Use official LBRY wallet servers": "Use official LBRY wallet servers",
"Enable Prerelease Updates": "Enable Prerelease Updates",
"Enable Upgrade to Test Builds": "Enable Upgrade to Test Builds",
"Prereleases may break things and we may not be able to fix them for you.": "Prereleases may break things and we may not be able to fix them for you.",
"Limit (GB)": "Limit (GB)",
"Limit Hosting for Content you Use": "Limit Hosting for Content you Use",
"Allow (GB)": "Allow (GB)",
"Content Data Hosting helps to seed things that you watch and download.": "Content Data Hosting helps to seed things that you watch and download.",
"Network Data Hosting allows the p2p network to store blobs unrelated to your browsing.": "Network Data Hosting allows the p2p network to store blobs unrelated to your browsing.",
"Content: Limit (GB)": "Content: Limit (GB)",
"Network: Allow (GB)": "Network: Allow (GB)",
"A channel is required to repost on LBRY": "A channel is required to repost on LBRY",
"Admin": "Admin",
"Stickers": "Stickers",
"Different Sticker": "Different Sticker",
"LBC": "LBC",
"Add a Card": "Add a Card",
" To Tip Creators": " To Tip Creators",
"Nothing found": "Nothing found",
"From Comments": "From Comments",
"This support is priced in $USD.": "This support is priced in $USD.",
"The current exchange rate for the submitted LBC amount is ~ $%exchange_amount%.": "The current exchange rate for the submitted LBC amount is ~ $%exchange_amount%.",
"Amount of $%input_amount% LBC in USB is lower than price of $%price_amount%": "Amount of $%input_amount% LBC in USB is lower than price of $%price_amount%",
"--end--": "--end--"
}
+16 -67
View File
@@ -3,22 +3,10 @@ import { Lbryio } from 'lbryinc';
import * as Sentry from '@sentry/browser';
import MatomoTracker from '@datapunt/matomo-tracker-js';
import { history } from './store';
import { SDK_API_PATH } from './index';
// @if TARGET='app'
import Native from 'native';
import ElectronCookies from '@exponent/electron-cookies';
import ElectronCookies from '@meetfranz/electron-cookies';
import { generateInitialUrl } from 'util/url';
// @endif
import { MATOMO_ID, MATOMO_URL } from 'config';
// import getConnectionSpeed from 'util/detect-user-bandwidth';
// let userDownloadBandwidthInBitsPerSecond;
// async function getUserBandwidth() {
// userDownloadBandwidthInBitsPerSecond = await getConnectionSpeed();
// }
// get user bandwidth every minute, starting after an initial one minute wait
// setInterval(getUserBandwidth, 1000 * 60);
const isProduction = process.env.NODE_ENV === 'production';
const devInternalApis = process.env.LBRY_API_URL && process.env.LBRY_API_URL.includes('dev');
@@ -27,15 +15,13 @@ 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
// const SEND_DATA_TO_WATCHMAN_INTERVAL = 10; // in seconds
// @if TARGET='app'
if (isProduction) {
ElectronCookies.enable({
origin: 'https://lbry.tv',
});
}
// @endif
type Analytics = {
error: (string) => Promise<any>,
@@ -82,12 +68,8 @@ type LogPublishParams = {
channel_claim_id?: string,
};
let internalAnalyticsEnabled: boolean = IS_WEB || false;
// let thirdPartyAnalyticsEnabled: boolean = IS_WEB || false;
// @if TARGET='app'
let internalAnalyticsEnabled: boolean = false;
if (window.localStorage.getItem(SHARE_INTERNAL) === 'true') internalAnalyticsEnabled = true;
// if (window.localStorage.getItem(SHARE_THIRD_PARTY) === 'true') thirdPartyAnalyticsEnabled = true;
// @endif
/**
* Determine the mobile device type viewing the data
@@ -96,26 +78,7 @@ if (window.localStorage.getItem(SHARE_INTERNAL) === 'true') internalAnalyticsEna
* @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';
return 'dsk';
}
// variables initialized for watchman
let amountOfBufferEvents = 0;
@@ -189,11 +152,6 @@ 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);
}
}
}
@@ -265,7 +223,7 @@ const analytics: Analytics = {
videoPlayer = passedPlayer;
bitrateAsBitsPerSecond = videoBitrate;
sendPromMetric('time_to_start', duration);
// sendPromMetric('time_to_start', duration);
sendMatomoEvent('Media', 'TimeToStart', claimId, duration);
},
error: (message) => {
@@ -338,7 +296,7 @@ const analytics: Analytics = {
claim_id: claimId,
};
if (timeToStart && !IS_WEB) {
if (timeToStart) {
params.time_to_start = timeToStart;
}
@@ -430,14 +388,15 @@ function sendMatomoEvent(category, action, name, value) {
}
}
function sendPromMetric(name: string, value?: number) {
if (IS_WEB) {
let url = new URL(SDK_API_PATH + '/metric/ui');
const params = { name: name, value: value ? value.toString() : '' };
url.search = new URLSearchParams(params).toString();
return fetch(url, { method: 'post' });
}
}
// Prometheus
// function sendPromMetric(name: string, value?: number) {
// if (IS_WEB) {
// let url = new URL(SDK_API_PATH + '/metric/ui');
// const params = { name: name, value: value ? value.toString() : '' };
// url.search = new URLSearchParams(params).toString();
// return fetch(url, { method: 'post' });
// }
// }
const MatomoInstance = new MatomoTracker({
urlBase: MATOMO_URL,
@@ -449,17 +408,7 @@ const MatomoInstance = new MatomoTracker({
// linkTracking: false // optional, default value: true
});
// Manually call the first page view
// React Router doesn't include this on `history.listen`
// @if TARGET='web'
analytics.pageView(window.location.pathname + window.location.search, window.location.search);
// @endif
// @if TARGET='app'
analytics.pageView(
window.location.pathname.split('.html')[1] + window.location.search || generateInitialUrl(window.location.hash)
);
// @endif;
analytics.pageView(generateInitialUrl(window.location.hash));
// Listen for url changes and report
// This will include search queries
+10 -12
View File
@@ -68,8 +68,8 @@ type Props = {
syncLoop: (?boolean) => void,
currentModal: any,
syncFatalError: boolean,
activeChannelClaim: ?ChannelClaim,
myChannelUrls: ?Array<string>,
activeChannelId: ?string,
myChannelClaimIds: ?Array<string>,
subscriptions: Array<Subscription>,
setActiveChannelIfNotSet: () => void,
setIncognito: (boolean) => void,
@@ -103,8 +103,8 @@ function App(props: Props) {
syncLoop,
currentModal,
syncFatalError,
myChannelUrls,
activeChannelClaim,
myChannelClaimIds,
activeChannelId,
setActiveChannelIfNotSet,
setIncognito,
fetchModBlockedList,
@@ -125,6 +125,7 @@ function App(props: Props) {
const { pathname, search } = props.location;
const [upgradeNagClosed, setUpgradeNagClosed] = useState(false);
const [resolvedSubscriptions, setResolvedSubscriptions] = useState(false);
// const [retryingSync, setRetryingSync] = useState(false);
const [sidebarOpen] = usePersistedState('sidebar', true);
const showUpgradeButton =
(autoUpdateDownloaded || (process.platform === 'linux' && isUpgradeAvailable)) && !upgradeNagClosed;
@@ -135,10 +136,10 @@ function App(props: Props) {
const sanitizedReferrerParam = rawReferrerParam && rawReferrerParam.replace(':', '#');
const userId = user && user.id;
const useCustomScrollbar = !IS_MAC;
const hasMyChannels = myChannelUrls && myChannelUrls.length > 0;
const hasNoChannels = myChannelUrls && myChannelUrls.length === 0;
const hasMyChannels = myChannelClaimIds && myChannelClaimIds.length > 0;
const hasNoChannels = myChannelClaimIds && myChannelClaimIds.length === 0;
const shouldMigrateLanguage = LANGUAGE_MIGRATIONS[language];
const hasActiveChannelClaim = activeChannelClaim !== undefined;
const hasActiveChannelClaim = activeChannelId !== undefined;
const isPersonalized = hasVerifiedEmail;
const renderFiledrop = isAuthenticated;
@@ -152,7 +153,7 @@ function App(props: Props) {
if (!uploadCount) return;
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = 'magic'; // without setting this to something it doesn't work
event.returnValue = __('There are pending uploads.'); // without setting this to something it doesn't work
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => window.removeEventListener('beforeunload', handleBeforeUnload);
@@ -272,7 +273,6 @@ function App(props: Props) {
}
}, [previousRewardApproved, isRewardApproved]);
// @if TARGET='app'
useEffect(() => {
if (updatePreferences && getWalletSyncPref && readyForPrefs) {
getWalletSyncPref()
@@ -282,7 +282,6 @@ function App(props: Props) {
});
}
}, [updatePreferences, getWalletSyncPref, setReadyForSync, readyForPrefs, hasVerifiedEmail]);
// @endif
// ready for sync syncs, however after signin when hasVerifiedEmail, that syncs too.
useEffect(() => {
@@ -314,7 +313,6 @@ function App(props: Props) {
if (!hasSignedIn && hasVerifiedEmail) {
signIn();
setHasSignedIn(true);
if (IS_WEB) setReadyForSync(true);
}
}, [hasVerifiedEmail, signIn, hasSignedIn]);
@@ -339,7 +337,7 @@ function App(props: Props) {
[`${MAIN_WRAPPER_CLASS}--scrollbar`]: useCustomScrollbar,
})}
ref={appRef}
onContextMenu={IS_WEB ? undefined : (e) => openContextMenu(e)}
onContextMenu={(e) => openContextMenu(e)}
>
<Router />
<ModalRouter />
+2 -2
View File
@@ -1,5 +1,5 @@
import { connect } from 'react-redux';
import { makeSelectClaimIdForUri } from 'redux/selectors/claims';
import { selectClaimIdForUri } from 'redux/selectors/claims';
import {
doCommentModUnBlock,
doCommentModBlock,
@@ -43,7 +43,7 @@ const select = (state, props) => {
isBlocked,
isToggling,
isBlockingOrUnBlocking: makeSelectUriIsBlockingOrUnBlocking(props.uri)(state),
creatorId: makeSelectClaimIdForUri(props.creatorUri)(state),
creatorId: selectClaimIdForUri(state, props.creatorUri),
};
};
+6 -6
View File
@@ -11,11 +11,11 @@ type Props = {
isBlockingOrUnBlocking: boolean,
isToggling: boolean,
doCommentModUnBlock: (string, boolean) => void,
doCommentModBlock: (string, ?Number, boolean) => void,
doCommentModBlock: (string, ?string, ?Number, boolean) => void,
doCommentModUnBlockAsAdmin: (string, string) => void,
doCommentModBlockAsAdmin: (string, string) => void,
doCommentModBlockAsAdmin: (string, ?string, ?string) => void,
doCommentModUnBlockAsModerator: (string, string, string) => void,
doCommentModBlockAsModerator: (string, string, string) => void,
doCommentModBlockAsModerator: (string, ?string, string, ?string) => void,
};
function ChannelBlockButton(props: Props) {
@@ -41,7 +41,7 @@ function ChannelBlockButton(props: Props) {
if (isBlocked) {
doCommentModUnBlock(uri, false);
} else {
doCommentModBlock(uri, undefined, false);
doCommentModBlock(uri, undefined, undefined, false);
}
break;
@@ -50,7 +50,7 @@ function ChannelBlockButton(props: Props) {
if (isBlocked) {
doCommentModUnBlockAsModerator(uri, creatorUri, '');
} else {
doCommentModBlockAsModerator(uri, creatorUri, '');
doCommentModBlockAsModerator(uri, undefined, creatorUri, undefined);
}
}
break;
@@ -59,7 +59,7 @@ function ChannelBlockButton(props: Props) {
if (isBlocked) {
doCommentModUnBlockAsAdmin(uri, '');
} else {
doCommentModBlockAsAdmin(uri, '');
doCommentModBlockAsAdmin(uri, undefined, undefined);
}
break;
}
+6 -4
View File
@@ -3,9 +3,9 @@ import { PAGE_SIZE } from 'constants/claim';
import {
makeSelectClaimsInChannelForPage,
makeSelectFetchingChannelClaims,
makeSelectClaimIsMine,
selectClaimIsMine,
makeSelectTotalPagesInChannelSearch,
makeSelectClaimForUri,
selectClaimForUri,
} from 'redux/selectors/claims';
import { doResolveUris } from 'redux/actions/claims';
import * as SETTINGS from 'constants/settings';
@@ -20,13 +20,15 @@ const select = (state, props) => {
const { search } = props.location;
const urlParams = new URLSearchParams(search);
const page = urlParams.get('page') || 0;
const claim = props.uri && selectClaimForUri(state, props.uri);
return {
pageOfClaimsInChannel: makeSelectClaimsInChannelForPage(props.uri, page)(state),
fetching: makeSelectFetchingChannelClaims(props.uri)(state),
totalPages: makeSelectTotalPagesInChannelSearch(props.uri, PAGE_SIZE)(state),
channelIsMine: makeSelectClaimIsMine(props.uri)(state),
channelIsMine: selectClaimIsMine(state, claim),
channelIsBlocked: makeSelectChannelIsMuted(props.uri)(state),
claim: props.uri && makeSelectClaimForUri(props.uri)(state),
claim,
isAuthenticated: selectUserVerifiedEmail(state),
showMature: selectShowMatureContent(state),
tileLayout: makeSelectClientSetting(SETTINGS.TILE_LAYOUT)(state),
@@ -1,7 +1,7 @@
import { connect } from 'react-redux';
import {
makeSelectTitleForUri,
makeSelectThumbnailForUri,
selectTitleForUri,
selectThumbnailForUri,
makeSelectCoverForUri,
makeSelectMetadataItemForUri,
makeSelectAmountForUri,
@@ -21,8 +21,8 @@ import ChannelForm from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
thumbnailUrl: makeSelectThumbnailForUri(props.uri)(state),
title: selectTitleForUri(state, props.uri),
thumbnailUrl: selectThumbnailForUri(state, props.uri),
coverUrl: makeSelectCoverForUri(props.uri)(state),
description: makeSelectMetadataItemForUri(props.uri, 'description')(state),
website: makeSelectMetadataItemForUri(props.uri, 'website_url')(state),
File renamed without changes.
@@ -1,10 +0,0 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectIsUriResolving } from 'redux/selectors/claims';
import ChannelMentionSuggestion from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
});
export default connect(select)(ChannelMentionSuggestion);
@@ -1,32 +0,0 @@
// @flow
import { ComboboxOption } from '@reach/combobox';
import ChannelThumbnail from 'component/channelThumbnail';
import React from 'react';
type Props = {
claim: ?Claim,
uri?: string,
isResolvingUri: boolean,
};
export default function ChannelMentionSuggestion(props: Props) {
const { claim, uri, isResolvingUri } = props;
return !claim ? null : (
<ComboboxOption value={uri}>
{isResolvingUri ? (
<div className="channel-mention__suggestion">
<div className="media__thumb media__thumb--resolving" />
</div>
) : (
<div className="channel-mention__suggestion">
<ChannelThumbnail xsmall uri={uri} />
<span className="channel-mention__suggestion-label">
<div className="channel-mention__suggestion-title">{(claim.value && claim.value.title) || claim.name}</div>
<div className="channel-mention__suggestion-name">{claim.name}</div>
</span>
</div>
)}
</ComboboxOption>
);
}
@@ -1,37 +0,0 @@
import { connect } from 'react-redux';
import { selectShowMatureContent } from 'redux/selectors/settings';
import { selectSubscriptions } from 'redux/selectors/subscriptions';
import { withRouter } from 'react-router';
import { makeSelectClaimForUri } from 'redux/selectors/claims';
import { doResolveUris } from 'redux/actions/claims';
import { selectTopLevelCommentsForUri } from 'redux/selectors/comments';
import ChannelMentionSuggestions from './view';
const select = (state, props) => {
const subscriptionUris = selectSubscriptions(state).map(({ uri }) => uri);
const topLevelComments = selectTopLevelCommentsForUri(state, props.uri);
const commentorUris = [];
// Avoid repeated commentors
topLevelComments.map(({ channel_url }) => !commentorUris.includes(channel_url) && commentorUris.push(channel_url));
const getUnresolved = (uris) =>
uris.map((uri) => !makeSelectClaimForUri(uri)(state) && uri).filter((uri) => uri !== false);
const getCanonical = (uris) =>
uris
.map((uri) => makeSelectClaimForUri(uri)(state) && makeSelectClaimForUri(uri)(state).canonical_url)
.filter((uri) => Boolean(uri));
return {
commentorUris,
subscriptionUris,
unresolvedCommentors: getUnresolved(commentorUris),
unresolvedSubscriptions: getUnresolved(subscriptionUris),
canonicalCreator: getCanonical([props.creatorUri])[0],
canonicalCommentors: getCanonical(commentorUris),
canonicalSubscriptions: getCanonical(subscriptionUris),
showMature: selectShowMatureContent(state),
};
};
export default withRouter(connect(select, { doResolveUris })(ChannelMentionSuggestions));
@@ -1,277 +0,0 @@
// @flow
import { Combobox, ComboboxInput, ComboboxPopover, ComboboxList } from '@reach/combobox';
import { Form } from 'component/common/form';
import { parseURI, regexInvalidURI } from 'util/lbryURI';
import { SEARCH_OPTIONS } from 'constants/search';
import * as KEYCODES from 'constants/keycodes';
import ChannelMentionSuggestion from 'component/channelMentionSuggestion';
import ChannelMentionTopSuggestion from 'component/channelMentionTopSuggestion';
import React from 'react';
import Spinner from 'component/spinner';
import type { ElementRef } from 'react';
import useLighthouse from 'effects/use-lighthouse';
const INPUT_DEBOUNCE_MS = 1000;
const LIGHTHOUSE_MIN_CHARACTERS = 3;
type Props = {
inputRef: any,
mentionTerm: string,
noTopSuggestion?: boolean,
showMature: boolean,
creatorUri: string,
commentorUris: Array<string>,
subscriptionUris: Array<string>,
unresolvedSubscriptions: Array<string>,
canonicalCreator: string,
canonicalCommentors: Array<string>,
canonicalSubscriptions: Array<string>,
doResolveUris: (Array<string>) => void,
customSelectAction?: (string, number) => void,
};
export default function ChannelMentionSuggestions(props: Props) {
const {
unresolvedSubscriptions,
canonicalCreator,
creatorUri,
inputRef,
showMature,
noTopSuggestion,
mentionTerm,
doResolveUris,
customSelectAction,
} = props;
const comboboxInputRef: ElementRef<any> = React.useRef();
const comboboxListRef: ElementRef<any> = React.useRef();
const mainEl = document.querySelector('.channel-mention__suggestions');
const [debouncedTerm, setDebouncedTerm] = React.useState('');
const [mostSupported, setMostSupported] = React.useState('');
const [canonicalResults, setCanonicalResults] = React.useState([]);
const isRefFocused = (ref) => ref && ref.current === document.activeElement;
const subscriptionUris = props.subscriptionUris.filter((uri) => uri !== creatorUri);
const canonicalSubscriptions = props.canonicalSubscriptions.filter((uri) => uri !== canonicalCreator);
const commentorUris = props.commentorUris.filter((uri) => uri !== creatorUri && !subscriptionUris.includes(uri));
const canonicalCommentors = props.canonicalCommentors.filter(
(uri) => uri !== canonicalCreator && !canonicalSubscriptions.includes(uri)
);
const termToMatch = mentionTerm && mentionTerm.replace('@', '').toLowerCase();
const allShownUris = [creatorUri, ...subscriptionUris, ...commentorUris];
const allShownCanonical = [canonicalCreator, ...canonicalSubscriptions, ...canonicalCommentors];
const possibleMatches = allShownUris.filter((uri) => {
try {
// yuck a try catch in a filter?
const { channelName } = parseURI(uri);
return channelName && channelName.toLowerCase().includes(termToMatch);
} catch (e) {}
});
const searchSize = 5;
const additionalOptions = { isBackgroundSearch: false, [SEARCH_OPTIONS.CLAIM_TYPE]: SEARCH_OPTIONS.INCLUDE_CHANNELS };
const { results, loading } = useLighthouse(debouncedTerm, showMature, searchSize, additionalOptions, 0);
const stringifiedResults = JSON.stringify(results);
const hasMinLength = mentionTerm && mentionTerm.length >= LIGHTHOUSE_MIN_CHARACTERS;
const isTyping = debouncedTerm !== mentionTerm;
const showPlaceholder = isTyping || loading;
const isUriFromTermValid = !regexInvalidURI.test(mentionTerm.substring(1));
const handleSelect = React.useCallback(
(value, key) => {
if (customSelectAction) {
// Give them full results, as our resolved one might truncate the claimId.
customSelectAction(value || (results && results.find((r) => r.startsWith(value))) || '', Number(key));
}
},
[customSelectAction, results]
);
React.useEffect(() => {
const timer = setTimeout(() => {
if (isTyping) setDebouncedTerm(!hasMinLength ? '' : mentionTerm);
}, INPUT_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [hasMinLength, isTyping, mentionTerm]);
React.useEffect(() => {
if (!mainEl) return;
const header = document.querySelector('.header__navigation');
function handleReflow() {
const boxAtTopOfPage = header && mainEl.getBoundingClientRect().top <= header.offsetHeight;
const boxAtBottomOfPage = mainEl.getBoundingClientRect().bottom >= window.innerHeight;
if (boxAtTopOfPage) {
mainEl.setAttribute('flow-bottom', '');
}
if (mainEl.getAttribute('flow-bottom') !== null && boxAtBottomOfPage) {
mainEl.removeAttribute('flow-bottom');
}
}
handleReflow();
window.addEventListener('scroll', handleReflow);
return () => window.removeEventListener('scroll', handleReflow);
}, [mainEl]);
React.useEffect(() => {
if (!inputRef || !comboboxInputRef || !mentionTerm) return;
function handleKeyDown(event) {
const { keyCode } = event;
const activeElement = document.activeElement;
if (keyCode === KEYCODES.UP || keyCode === KEYCODES.DOWN) {
if (isRefFocused(comboboxInputRef)) {
const selectedId = activeElement && activeElement.getAttribute('aria-activedescendant');
const selectedItem = selectedId && document.querySelector(`li[id="${selectedId}"]`);
if (selectedItem) selectedItem.scrollIntoView({ block: 'nearest', inline: 'nearest' });
} else {
// $FlowFixMe
comboboxInputRef.current.focus();
}
} else {
if ((isRefFocused(comboboxInputRef) || isRefFocused(inputRef)) && keyCode === KEYCODES.TAB) {
event.preventDefault();
const activeValue = activeElement && activeElement.getAttribute('value');
if (activeValue) {
handleSelect(activeValue, keyCode);
} else if (possibleMatches.length) {
// $FlowFixMe
const suggest = allShownCanonical.find((matchUri) => possibleMatches.find((uri) => uri.includes(matchUri)));
if (suggest) handleSelect(suggest, keyCode);
} else if (results) {
handleSelect(mentionTerm, keyCode);
}
}
if (isRefFocused(comboboxInputRef)) {
// $FlowFixMe
inputRef.current.focus();
}
}
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [allShownCanonical, handleSelect, inputRef, mentionTerm, possibleMatches, results]);
React.useEffect(() => {
if (!stringifiedResults) return;
const arrayResults = JSON.parse(stringifiedResults);
if (arrayResults && arrayResults.length > 0) {
// $FlowFixMe
doResolveUris(arrayResults).then((response) => {
try {
// $FlowFixMe
const canonical_urls = Object.values(response).map(({ canonical_url }) => canonical_url);
setCanonicalResults(canonical_urls);
} catch (e) {}
});
}
}, [doResolveUris, stringifiedResults]);
// Only resolve the subscriptions that match the mention term, instead of all
React.useEffect(() => {
if (isTyping) return;
const urisToResolve = [];
subscriptionUris.map(
(uri) =>
hasMinLength &&
possibleMatches.includes(uri) &&
unresolvedSubscriptions.includes(uri) &&
urisToResolve.push(uri)
);
if (urisToResolve.length > 0) doResolveUris(urisToResolve);
}, [doResolveUris, hasMinLength, isTyping, possibleMatches, subscriptionUris, unresolvedSubscriptions]);
const suggestionsRow = (
label: string,
suggestions: Array<string>,
canonical: Array<string>,
hasSuggestionsBelow: boolean
) => {
if (mentionTerm.length > 1 && suggestions !== results) {
suggestions = suggestions.filter((uri) => possibleMatches.includes(uri));
} else if (suggestions === results) {
suggestions = suggestions.filter((uri) => !allShownUris.includes(uri));
}
// $FlowFixMe
suggestions = suggestions
.map((matchUri) => canonical.find((uri) => matchUri.includes(uri)))
.filter((uri) => Boolean(uri));
if (canonical === canonicalResults) {
suggestions = suggestions.filter((uri) => uri !== mostSupported);
}
return !suggestions.length ? null : (
<>
<div className="channel-mention__label">{label}</div>
{suggestions.map((uri) => (
<ChannelMentionSuggestion key={uri} uri={uri} />
))}
{hasSuggestionsBelow && <hr className="channel-mention__top-separator" />}
</>
);
};
return isRefFocused(inputRef) || isRefFocused(comboboxInputRef) ? (
<Form onSubmit={() => handleSelect(mentionTerm)}>
<Combobox className="channel-mention" onSelect={handleSelect}>
<ComboboxInput ref={comboboxInputRef} className="channel-mention__input--none" value={mentionTerm} />
{mentionTerm && isUriFromTermValid && (
<ComboboxPopover portal={false} className="channel-mention__suggestions">
<ComboboxList ref={comboboxListRef}>
{creatorUri &&
suggestionsRow(
__('Creator'),
[creatorUri],
[canonicalCreator],
canonicalSubscriptions.length > 0 || commentorUris.length > 0 || !showPlaceholder
)}
{canonicalSubscriptions.length > 0 &&
suggestionsRow(
__('Following'),
subscriptionUris,
canonicalSubscriptions,
commentorUris.length > 0 || !showPlaceholder
)}
{commentorUris.length > 0 &&
suggestionsRow(__('From comments'), commentorUris, canonicalCommentors, !showPlaceholder)}
{hasMinLength &&
(showPlaceholder ? (
<Spinner type="small" />
) : (
results && (
<>
{!noTopSuggestion && (
<ChannelMentionTopSuggestion
query={debouncedTerm}
shownUris={allShownCanonical}
setMostSupported={(winningUri) => setMostSupported(winningUri)}
/>
)}
{suggestionsRow(__('From search'), results, canonicalResults, false)}
</>
)
))}
</ComboboxList>
</ComboboxPopover>
)}
</Combobox>
</Form>
) : null;
}
@@ -1,16 +0,0 @@
import { connect } from 'react-redux';
import { makeSelectIsUriResolving } from 'redux/selectors/claims';
import { doResolveUri } from 'redux/actions/claims';
import { makeSelectWinningUriForQuery } from 'redux/selectors/search';
import ChannelMentionTopSuggestion from './view';
const select = (state, props) => {
const uriFromQuery = `lbry://${props.query}`;
return {
uriFromQuery,
isResolvingUri: makeSelectIsUriResolving(uriFromQuery)(state),
winningUri: makeSelectWinningUriForQuery(props.query)(state),
};
};
export default connect(select, { doResolveUri })(ChannelMentionTopSuggestion);
@@ -1,49 +0,0 @@
// @flow
import ChannelMentionSuggestion from 'component/channelMentionSuggestion';
import LbcSymbol from 'component/common/lbc-symbol';
import React from 'react';
type Props = {
uriFromQuery: string,
winningUri: string,
isResolvingUri: boolean,
shownUris: Array<string>,
setMostSupported: (string) => void,
doResolveUri: (string) => void,
};
export default function ChannelMentionTopSuggestion(props: Props) {
const { uriFromQuery, winningUri, isResolvingUri, shownUris, setMostSupported, doResolveUri } = props;
React.useEffect(() => {
if (uriFromQuery) doResolveUri(uriFromQuery);
}, [doResolveUri, uriFromQuery]);
React.useEffect(() => {
if (winningUri) setMostSupported(winningUri);
}, [setMostSupported, winningUri]);
if (isResolvingUri) {
return (
<div className="channel-mention__winning-claim">
<div className="channel-mention__label channel-mention__placeholder-label" />
<div className="channel-mention__suggestion channel-mention__placeholder-suggestion">
<div className="channel-mention__placeholder-thumbnail" />
<div className="channel-mention__placeholder-info" />
</div>
<hr className="channel-mention__top-separator" />
</div>
);
}
return !winningUri || shownUris.includes(winningUri) ? null : (
<>
<div className="channel-mention__label">
<LbcSymbol prefix={__('Most Supported')} />
</div>
<ChannelMentionSuggestion uri={winningUri} />
<hr className="channel-mention__top-separator" />
</>
);
}
+4 -4
View File
@@ -1,15 +1,15 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
makeSelectStakedLevelForChannelUri,
makeSelectTotalStakedAmountForChannelUri,
selectTotalStakedAmountForChannelUri,
selectStakedLevelForChannelUri,
} from 'redux/selectors/claims';
import ChannelStakedIndicator from './view';
const select = (state, props) => ({
channelClaim: makeSelectClaimForUri(props.uri)(state),
amount: makeSelectTotalStakedAmountForChannelUri(props.uri)(state),
level: makeSelectStakedLevelForChannelUri(props.uri)(state),
amount: selectTotalStakedAmountForChannelUri(state, props.uri),
level: selectStakedLevelForChannelUri(state, props.uri),
});
export default connect(select)(ChannelStakedIndicator);
+4 -4
View File
@@ -1,12 +1,12 @@
import { connect } from 'react-redux';
import { makeSelectThumbnailForUri, makeSelectClaimForUri, makeSelectIsUriResolving } from 'redux/selectors/claims';
import { selectThumbnailForUri, selectClaimForUri, selectIsUriResolving } from 'redux/selectors/claims';
import { doResolveUri } from 'redux/actions/claims';
import ChannelThumbnail from './view';
const select = (state, props) => ({
thumbnail: makeSelectThumbnailForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
isResolving: makeSelectIsUriResolving(props.uri)(state),
thumbnail: selectThumbnailForUri(state, props.uri),
claim: selectClaimForUri(state, props.uri),
isResolving: selectIsUriResolving(state, props.uri),
});
export default connect(select, {
+2 -2
View File
@@ -1,9 +1,9 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectTitleForUri } from 'redux/selectors/claims';
import { makeSelectClaimForUri, selectTitleForUri } from 'redux/selectors/claims';
import ChannelTitle from './view';
const select = (state, props) => ({
title: makeSelectTitleForUri(props.uri)(state),
title: selectTitleForUri(state, props.uri),
claim: makeSelectClaimForUri(props.uri)(state),
});
@@ -29,7 +29,6 @@ export default function CollectionAddButton(props: Props) {
icon={fileAction ? (!isSaved ? ICONS.ADD : ICONS.STACK) : ICONS.LIBRARY}
iconSize={fileAction ? 22 : undefined}
label={uri ? (!isSaved ? __('Save') : __('Saved')) : __('New List')}
requiresAuth={IS_WEB}
title={__('Add this claim to a list')}
onClick={(e) => {
e.preventDefault();
@@ -1,10 +1,10 @@
import { connect } from 'react-redux';
import { makeSelectInsufficientCreditsForUri } from 'redux/selectors/content';
import { selectInsufficientCreditsForUri } from 'redux/selectors/content';
import { makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import ClaimInsufficientCredits from './view';
const select = (state, props) => ({
isInsufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
isInsufficientCredits: selectInsufficientCreditsForUri(state, props.uri),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
});
+2 -4
View File
@@ -1,9 +1,8 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectIsUriResolving } from 'redux/selectors/claims';
import { makeSelectClaimForUri, selectIsUriResolving } from 'redux/selectors/claims';
import { doResolveUri } from 'redux/actions/claims';
import { doSetPlayingUri } from 'redux/actions/content';
import { punctuationMarks } from 'util/remark-lbry';
import { selectBlackListedOutpoints } from 'lbryinc';
import { selectPlayingUri } from 'redux/selectors/content';
import ClaimLink from './view';
@@ -25,8 +24,7 @@ const select = (state, props) => {
uri,
claim,
fullUri: props.uri,
isResolvingUri: makeSelectIsUriResolving(uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
isResolvingUri: selectIsUriResolving(state, uri),
playingUri: selectPlayingUri(state),
};
};
+1 -21
View File
@@ -14,10 +14,6 @@ type Props = {
description: ?string,
isResolvingUri: boolean,
doResolveUri: (string) => void,
blackListedOutpoints: Array<{
txid: string,
nout: number,
}>,
playingUri: ?PlayingUri,
parentCommentId?: string,
isMarkdownPost?: boolean,
@@ -42,21 +38,6 @@ class ClaimLink extends React.Component<Props> {
this.resolve(this.props);
}
isClaimBlackListed() {
const { claim, blackListedOutpoints } = this.props;
const signingChannel = claim && claim.signing_channel;
if (claim && blackListedOutpoints) {
let blackListed = false;
blackListed = blackListedOutpoints.some(
(outpoint) =>
(signingChannel && outpoint.txid === signingChannel.txid && outpoint.nout === signingChannel.nout) ||
(outpoint.txid === claim.txid && outpoint.nout === claim.nout)
);
return blackListed;
}
}
resolve = (props: Props) => {
const { isResolvingUri, doResolveUri, claim, uri } = props;
@@ -78,14 +59,13 @@ class ClaimLink extends React.Component<Props> {
allowPreview,
} = this.props;
const isUnresolved = (!isResolvingUri && !claim) || !claim;
const isBlacklisted = this.isClaimBlackListed();
const isPlayingInline =
playingUri &&
playingUri.uri === uri &&
((playingUri.source === 'comment' && parentCommentId === playingUri.commentId) ||
playingUri.source === 'markdown');
if (isBlacklisted || isUnresolved) {
if (isUnresolved) {
return <span>{children}</span>;
}
+1 -1
View File
@@ -1,5 +1,5 @@
// @flow
import { MAIN_CLASS } from 'component/page/view';
import { MAIN_CLASS } from 'constants/classnames';
import type { Node } from 'react';
import React, { useEffect } from 'react';
import classnames from 'classnames';
-16
View File
@@ -384,22 +384,6 @@ function ClaimListDiscover(props: Props) {
const claimSearchResult = claimSearchByQuery[searchKey];
const claimSearchResultLastPageReached = claimSearchByQueryLastPageReached[searchKey];
// uncomment to fix an item on a page
// const fixUri = 'lbry://@corbettreport#0/lbryodysee#5';
// if (
// orderParam === CS.ORDER_BY_NEW &&
// claimSearchResult &&
// claimSearchResult.length > 2 &&
// window.location.pathname === '/$/rabbithole'
// ) {
// if (claimSearchResult.indexOf(fixUri) !== -1) {
// claimSearchResult.splice(claimSearchResult.indexOf(fixUri), 1);
// } else {
// claimSearchResult.pop();
// }
// claimSearchResult.splice(2, 0, fixUri);
// }
const [prevOptions, setPrevOptions] = React.useState(null);
if (!isJustScrollingToNewPage(prevOptions, options)) {
+6 -8
View File
@@ -1,5 +1,5 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectClaimIsMine } from 'redux/selectors/claims';
import { selectClaimForUri, selectClaimIsMine } from 'redux/selectors/claims';
import { doCollectionEdit, doFetchItemsInCollection } from 'redux/actions/collections';
import { doPrepareEdit } from 'redux/actions/publish';
import {
@@ -26,15 +26,14 @@ import {
} from 'redux/selectors/comments';
import { doToast } from 'redux/actions/notifications';
import { doChannelSubscribe, doChannelUnsubscribe } from 'redux/actions/subscriptions';
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectIsSubscribedForUri } from 'redux/selectors/subscriptions';
import { selectListShuffle } from 'redux/selectors/content';
import { doToggleLoopList, 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 claim = selectClaimForUri(state, props.uri, false); // @KP test no repost!
const collectionId = props.collectionId;
const repostedClaim = claim && claim.reposted_claim;
const contentClaim = repostedClaim || claim;
@@ -51,7 +50,7 @@ const select = (state, props) => {
contentClaim,
contentSigningChannel,
contentChannelUri,
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
claimIsMine: selectClaimIsMine(state, claim),
hasClaimInWatchLater: makeSelectCollectionForIdHasClaimUrl(
COLLECTIONS_CONSTS.WATCH_LATER_ID,
contentPermanentUri
@@ -63,13 +62,12 @@ const select = (state, props) => {
channelIsMuted: makeSelectChannelIsMuted(contentChannelUri)(state),
channelIsBlocked: makeSelectChannelIsBlocked(contentChannelUri)(state),
fileInfo: makeSelectFileInfoForUri(contentPermanentUri)(state),
isSubscribed: makeSelectIsSubscribed(contentChannelUri, true)(state),
isSubscribed: selectIsSubscribedForUri(state, contentChannelUri),
channelIsAdminBlocked: makeSelectChannelIsAdminBlocked(props.uri)(state),
isAdmin: selectHasAdminChannel(state),
claimInCollection: makeSelectCollectionForIdHasClaimUrl(collectionId, contentPermanentUri)(state),
isMyCollection: makeSelectCollectionIsMine(collectionId)(state),
editedCollection: makeSelectEditedCollectionForId(collectionId)(state),
isAuthenticated: Boolean(selectUserVerifiedEmail(state)),
resolvedList: makeSelectUrlsForCollectionId(collectionId)(state),
playNextUri,
};
@@ -92,7 +90,7 @@ 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: (a, b, c) => dispatch(doCommentModBlockAsAdmin(a, b, c)),
doCommentModUnBlockAsAdmin: (commenterUri, blockerId) =>
dispatch(doCommentModUnBlockAsAdmin(commenterUri, blockerId)),
doChannelSubscribe: (subscription) => dispatch(doChannelSubscribe(subscription)),
+88 -100
View File
@@ -8,13 +8,7 @@ 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,
formatLbryUrlForWeb,
generateListSearchUrlParams,
} from 'util/url';
import { generateShareUrl, generateLbryContentUrl, formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { useHistory } from 'react-router';
import { buildURI, parseURI } from 'util/lbryURI';
@@ -45,7 +39,7 @@ type Props = {
doChannelUnmute: (string) => void,
doCommentModBlock: (string) => void,
doCommentModUnBlock: (string) => void,
doCommentModBlockAsAdmin: (string, string) => void,
doCommentModBlockAsAdmin: (commenterUri: string, offendingCommentId: ?string, blockerId: ?string) => void,
doCommentModUnBlockAsAdmin: (string, string) => void,
doCollectionEdit: (string, any) => void,
hasClaimInWatchLater: boolean,
@@ -62,7 +56,6 @@ type Props = {
doChannelUnsubscribe: (SubscriptionArgs) => void,
isChannelPage: boolean,
editedCollection: Collection,
isAuthenticated: boolean,
playNextUri: string,
resolvedList: boolean,
fetchCollectionItems: (string) => void,
@@ -103,7 +96,6 @@ function ClaimMenuList(props: Props) {
doChannelUnsubscribe,
isChannelPage = false,
editedCollection,
isAuthenticated,
playNextUri,
resolvedList,
fetchCollectionItems,
@@ -150,7 +142,6 @@ function ClaimMenuList(props: Props) {
const lbryUrl: string = generateLbryContentUrl(claim.canonical_url, claim.permanent_url);
const shareUrl: string = generateShareUrl(SHARE_DOMAIN, lbryUrl);
const rssUrl: string = isChannel ? generateRssUrl(SHARE_DOMAIN, claim) : '';
const isCollectionClaim = claim && claim.value_type === 'collection';
// $FlowFixMe
const isPlayable =
@@ -237,7 +228,7 @@ function ClaimMenuList(props: Props) {
if (channelIsAdminBlocked) {
doCommentModUnBlockAsAdmin(contentChannelUri, '');
} else {
doCommentModBlockAsAdmin(contentChannelUri, '');
doCommentModBlockAsAdmin(contentChannelUri, undefined, undefined);
}
}
@@ -252,10 +243,6 @@ function ClaimMenuList(props: Props) {
});
}
function handleCopyRssLink() {
copyToClipboard(rssUrl, 'RSS URL copied.', 'Failed to copy RSS URL.');
}
function handleCopyLink() {
copyToClipboard(shareUrl, 'Link copied.', 'Failed to copy link.');
}
@@ -265,15 +252,33 @@ function ClaimMenuList(props: Props) {
push(`/$/${PAGES.REPORT_CONTENT}?claimId=${contentClaim && contentClaim.claim_id}`);
}
const shouldShow = !IS_WEB || (IS_WEB && isAuthenticated);
// changes MenuButton behavior to show/hide MenuList not on press but on click event
let isEventSimulated = false;
const menuButtonHandler = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.type = 'click';
}
if (!isEventSimulated && e.type === 'mousedown') {
e.preventDefault();
} else if (e.type === 'click') {
isEventSimulated = true;
e.target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
isEventSimulated = false;
}
};
return (
<Menu>
<MenuButton
className={classnames('menu__button', { 'claim__menu-button': !inline, 'claim__menu-button--inline': inline })}
onMouseDown={menuButtonHandler}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
menuButtonHandler(e);
}}
onKeyDown={menuButtonHandler}
>
<Icon size={20} icon={ICONS.MORE_VERTICAL} />
</MenuButton>
@@ -324,7 +329,6 @@ function ClaimMenuList(props: Props) {
)}
</>
) : (
shouldShow &&
isPlayable && (
<>
{/* WATCH LATER */}
@@ -362,105 +366,89 @@ function ClaimMenuList(props: Props) {
)
)}
</>
{shouldShow && (
{!isChannelPage && (
<>
{!isChannelPage && (
<>
<MenuItem className="comment__menu-option" onSelect={handleSupport}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.LBC} />
{__('Support --[button to support a claim]--')}
</div>
</MenuItem>
</>
)}
<MenuItem className="comment__menu-option" onSelect={handleSupport}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.LBC} />
{__('Support --[button to support a claim]--')}
</div>
</MenuItem>
</>
)}
{!incognitoClaim && !claimIsMine && !isChannelPage && (
<>
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleFollow}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SUBSCRIBE} />
{subscriptionLabel}
</div>
</MenuItem>
</>
)}
{!incognitoClaim && !claimIsMine && !isChannelPage && (
<>
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleFollow}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SUBSCRIBE} />
{subscriptionLabel}
</div>
</MenuItem>
</>
)}
{!isMyCollection && (
<>
{(!claimIsMine || channelIsBlocked) && contentChannelUri ? (
!incognitoClaim && (
<>
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleToggleBlock}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.BLOCK} />
{channelIsBlocked ? __('Unblock Channel') : __('Block Channel')}
</div>
</MenuItem>
{isAdmin && (
<MenuItem className="comment__menu-option" onSelect={handleToggleAdminBlock}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.GLOBE} />
{channelIsAdminBlocked ? __('Global Unblock Channel') : __('Global Block Channel')}
</div>
</MenuItem>
)}
<MenuItem className="comment__menu-option" onSelect={handleToggleMute}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.MUTE} />
{channelIsMuted ? __('Unmute Channel') : __('Mute Channel')}
</div>
</MenuItem>
</>
)
) : (
<>
{!isChannelPage && !repostedClaim && (
<MenuItem className="comment__menu-option" onSelect={handleEdit}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.EDIT} />
{__('Edit')}
</div>
</MenuItem>
)}
</>
)}
{showDelete && (
<MenuItem className="comment__menu-option" onSelect={handleDelete}>
{!isMyCollection && (
<>
{(!claimIsMine || channelIsBlocked) && contentChannelUri ? (
!incognitoClaim && (
<>
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleToggleBlock}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete')}
<Icon aria-hidden icon={ICONS.BLOCK} />
{channelIsBlocked ? __('Unblock Channel') : __('Block Channel')}
</div>
</MenuItem>
{isAdmin && (
<MenuItem className="comment__menu-option" onSelect={handleToggleAdminBlock}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.GLOBE} />
{channelIsAdminBlocked ? __('Global Unblock Channel') : __('Global Block Channel')}
</div>
</MenuItem>
)}
<MenuItem className="comment__menu-option" onSelect={handleToggleMute}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.MUTE} />
{channelIsMuted ? __('Unmute Channel') : __('Mute Channel')}
</div>
</MenuItem>
</>
)
) : (
<>
{!isChannelPage && !repostedClaim && (
<MenuItem className="comment__menu-option" onSelect={handleEdit}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.EDIT} />
{__('Edit')}
</div>
</MenuItem>
)}
</>
)}
<hr className="menu__separator" />
{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">
<Icon aria-hidden icon={ICONS.RSS} />
{__('Copy RSS URL')}
</div>
</MenuItem>
)}
{!claimIsMine && !isMyCollection && (
<MenuItem className="comment__menu-option" onSelect={handleReportContent}>
<div className="menu__link">
+13 -19
View File
@@ -1,13 +1,12 @@
import { connect } from 'react-redux';
import {
selectClaimForUri,
makeSelectIsUriResolving,
makeSelectClaimIsMine,
selectIsUriResolving,
selectClaimIsMine,
makeSelectClaimIsPending,
makeSelectClaimIsNsfw,
makeSelectReflectingClaimForUri,
makeSelectClaimWasPurchased,
makeSelectTitleForUri,
selectTitleForUri,
selectDateForUri,
} from 'redux/selectors/claims';
import { makeSelectStreamingUrlForUri } from 'redux/selectors/file_info';
@@ -20,12 +19,11 @@ import {
import { doResolveUri } from 'redux/actions/claims';
import { doCollectionEdit } from 'redux/actions/collections';
import { doFileGet } from 'redux/actions/file';
import { selectMutedChannels, makeSelectChannelIsMuted } from 'redux/selectors/blocked';
import { selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { selectBanStateForUri } from 'lbryinc';
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 { selectIsSubscribedForUri } from 'redux/selectors/subscriptions';
import { isClaimNsfw } from 'util/claim';
import ClaimPreview from './view';
import formatMediaDuration from 'util/formatMediaDuration';
@@ -38,21 +36,17 @@ const select = (state, props) => {
claim,
mediaDuration,
date: props.uri && selectDateForUri(state, props.uri),
title: props.uri && makeSelectTitleForUri(props.uri)(state),
title: props.uri && selectTitleForUri(state, props.uri),
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),
nsfw: props.uri && makeSelectClaimIsNsfw(props.uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
filteredOutpoints: selectFilteredOutpoints(state),
mutedUris: selectMutedChannels(state),
blockedUris: selectModerationBlockList(state),
claimIsMine: props.uri && selectClaimIsMine(state, claim),
isResolvingUri: props.uri && selectIsUriResolving(state, props.uri),
isResolvingRepost: props.uri && selectIsUriResolving(state, props.repostUrl),
nsfw: claim ? isClaimNsfw(claim) : false,
banState: selectBanStateForUri(state, props.uri),
hasVisitedUri: props.uri && makeSelectHasVisitedUri(props.uri)(state),
channelIsBlocked: props.uri && makeSelectChannelIsMuted(props.uri)(state),
isSubscribed: props.uri && makeSelectIsSubscribed(props.uri, true)(state),
isSubscribed: props.uri && selectIsSubscribedForUri(state, props.uri),
streamingUrl: props.uri && makeSelectStreamingUrlForUri(props.uri)(state),
wasPurchased: props.uri && makeSelectClaimWasPurchased(props.uri)(state),
isCollectionMine: makeSelectCollectionIsMine(props.collectionId)(state),
+12 -35
View File
@@ -4,7 +4,7 @@ import React, { useEffect, forwardRef } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { isEmpty } from 'util/object';
import classnames from 'classnames';
import { isURIEqual, isURIValid } from 'util/lbryURI';
import { isURIValid } from 'util/lbryURI';
import * as COLLECTIONS_CONSTS from 'constants/collections';
import { formatLbryUrlForWeb } from 'util/url';
import { formatClaimPreviewTitle } from 'util/formatAriaLabel';
@@ -28,6 +28,7 @@ import ClaimPreviewNoContent from './claim-preview-no-content';
import CollectionEditButtons from './collection-buttons';
import AbandonedChannelPreview from 'component/abandonedChannelPreview';
import PreviewOverlayProperties from 'component/previewOverlayProperties';
// preview images used on the landing page and on the channel page
type Props = {
@@ -46,17 +47,8 @@ type Props = {
nsfw: boolean,
placeholder: string,
type: string,
banState: { blacklisted?: boolean, filtered?: boolean, muted?: boolean, blocked?: boolean },
hasVisitedUri: boolean,
blackListedOutpoints: Array<{
txid: string,
nout: number,
}>,
filteredOutpoints: Array<{
txid: string,
nout: number,
}>,
mutedUris: Array<string>,
blockedUris: Array<string>,
channelIsBlocked: boolean,
actions: boolean | Node | string | number,
properties: boolean | Node | string | number | ((Claim) => Node),
@@ -131,10 +123,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
properties,
onClick,
actions,
mutedUris,
blockedUris,
blackListedOutpoints,
filteredOutpoints,
banState,
includeSupportAction,
renderActions,
hideMenu = false,
@@ -236,28 +225,13 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
((abandoned && !showUnresolvedClaim) || (!claimIsMine && obscureNsfw && nsfw));
// This will be replaced once blocking is done at the wallet server level
if (claim && !claimIsMine && !shouldHide && blackListedOutpoints) {
shouldHide = blackListedOutpoints.some(
(outpoint) =>
(signingChannel && outpoint.txid === signingChannel.txid && outpoint.nout === signingChannel.nout) ||
(outpoint.txid === claim.txid && outpoint.nout === claim.nout)
);
}
// We're checking to see if the stream outpoint
// or signing channel outpoint is in the filter list
if (claim && !claimIsMine && !shouldHide && filteredOutpoints) {
shouldHide = filteredOutpoints.some(
(outpoint) =>
(signingChannel && outpoint.txid === signingChannel.txid && outpoint.nout === signingChannel.nout) ||
(outpoint.txid === claim.txid && outpoint.nout === claim.nout)
);
if (claim && !claimIsMine && (banState.blacklisted || banState.filtered)) {
shouldHide = true;
}
// block stream claims
if (claim && !shouldHide && !showUserBlocked && mutedUris.length && signingChannel) {
shouldHide = mutedUris.some((blockedUri) => isURIEqual(blockedUri, signingChannel.permanent_url));
}
if (claim && !shouldHide && !showUserBlocked && blockedUris.length && signingChannel) {
shouldHide = blockedUris.some((blockedUri) => isURIEqual(blockedUri, signingChannel.permanent_url));
if (!shouldHide && !showUserBlocked && (banState.muted || banState.blocked)) {
shouldHide = true;
}
if (!shouldHide && customShouldHide && claim) {
@@ -377,6 +351,9 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
)}
</div>
{/* @endif */}
<div className="claim-preview__file-property-overlay">
<PreviewOverlayProperties uri={uri} properties={properties} />
</div>
</FileThumbnail>
</NavLink>
) : (
+11 -16
View File
@@ -1,18 +1,16 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
makeSelectIsUriResolving,
makeSelectThumbnailForUri,
makeSelectTitleForUri,
makeSelectChannelForClaimUri,
makeSelectClaimIsNsfw,
selectIsUriResolving,
getThumbnailFromClaim,
selectTitleForUri,
selectDateForUri,
} from 'redux/selectors/claims';
import { doFileGet } from 'redux/actions/file';
import { doResolveUri } from 'redux/actions/claims';
import { selectMutedChannels } from 'redux/selectors/blocked';
import { makeSelectViewCountForUri, selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { selectViewCountForUri, selectBanStateForUri } from 'lbryinc';
import { selectShowMatureContent } from 'redux/selectors/settings';
import { isClaimNsfw } from 'util/claim';
import ClaimPreviewTile from './view';
import formatMediaDuration from 'util/formatMediaDuration';
@@ -25,16 +23,13 @@ const select = (state, props) => {
claim,
mediaDuration,
date: props.uri && selectDateForUri(state, props.uri),
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),
isResolvingUri: props.uri && selectIsUriResolving(state, props.uri),
thumbnail: getThumbnailFromClaim(claim),
title: props.uri && selectTitleForUri(state, props.uri),
banState: selectBanStateForUri(state, props.uri),
showMature: selectShowMatureContent(state),
isMature: makeSelectClaimIsNsfw(props.uri)(state),
viewCount: makeSelectViewCountForUri(props.uri)(state),
isMature: claim ? isClaimNsfw(claim) : false,
viewCount: selectViewCountForUri(state, props.uri),
};
};
+10 -74
View File
@@ -12,7 +12,7 @@ import SubscribeButton from 'component/subscribeButton';
import useGetThumbnail from 'effects/use-get-thumbnail';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { formatClaimPreviewTitle } from 'util/formatAriaLabel';
import { parseURI, isURIEqual } from 'util/lbryURI';
import { parseURI } from 'util/lbryURI';
import PreviewOverlayProperties from 'component/previewOverlayProperties';
import FileDownloadLink from 'component/fileDownloadLink';
import FileWatchLaterLink from 'component/fileWatchLaterLink';
@@ -29,19 +29,11 @@ type Props = {
mediaDuration?: string,
resolveUri: (string) => void,
isResolvingUri: boolean,
history: { push: (string) => void },
history: { push: (string) => void, location: { pathname: string } },
thumbnail: string,
title: string,
placeholder: boolean,
blackListedOutpoints: Array<{
txid: string,
nout: number,
}>,
filteredOutpoints: Array<{
txid: string,
nout: number,
}>,
blockedChannelUris: Array<string>,
banState: { blacklisted?: boolean, filtered?: boolean, muted?: boolean, blocked?: boolean },
getFile: (string) => void,
streamingUrl: string,
isMature: boolean,
@@ -64,11 +56,9 @@ function ClaimPreviewTile(props: Props) {
resolveUri,
claim,
placeholder,
blackListedOutpoints,
filteredOutpoints,
banState,
getFile,
streamingUrl,
blockedChannelUris,
isMature,
showMature,
showHiddenByUser,
@@ -101,6 +91,7 @@ function ClaimPreviewTile(props: Props) {
to: navigateUrl,
onClick: (e) => e.stopPropagation(),
};
const { location } = history;
let isValid = false;
if (uri) {
@@ -139,41 +130,16 @@ function ClaimPreviewTile(props: Props) {
// Unfortunately needed until this is resolved
// https://github.com/lbryio/lbry-sdk/issues/2785
shouldHide = true;
}
// This will be replaced once blocking is done at the wallet server level
if (claim && !shouldHide && blackListedOutpoints) {
shouldHide = blackListedOutpoints.some(
(outpoint) =>
(signingChannel && outpoint.txid === signingChannel.txid && outpoint.nout === signingChannel.nout) ||
(outpoint.txid === claim.txid && outpoint.nout === claim.nout)
);
}
// We're checking to see if the stream outpoint
// or signing channel outpoint is in the filter list
if (claim && !shouldHide && filteredOutpoints) {
shouldHide = filteredOutpoints.some(
(outpoint) =>
(signingChannel && outpoint.txid === signingChannel.txid && outpoint.nout === signingChannel.nout) ||
(outpoint.txid === claim.txid && outpoint.nout === claim.nout)
);
}
// block stream claims
if (claim && !shouldHide && !showHiddenByUser && blockedChannelUris.length && signingChannel) {
shouldHide = blockedChannelUris.some((blockedUri) => isURIEqual(blockedUri, signingChannel.permanent_url));
}
// block channel claims if we can't control for them in claim search
// e.g. fetchRecommendedSubscriptions
if (claim && isChannel && !shouldHide && !showHiddenByUser && blockedChannelUris.length && signingChannel) {
shouldHide = blockedChannelUris.some((blockedUri) => isURIEqual(blockedUri, signingChannel.permanent_url));
} else {
shouldHide =
banState.blacklisted || banState.filtered || (!showHiddenByUser && (banState.muted || banState.blocked));
}
if (shouldHide) {
return null;
}
const isChannelPage = window.location.pathname.startsWith('/@');
const isChannelPage = location.pathname.startsWith('/@');
const shouldShowViewCount = !(!viewCount || (claim && claim.repost_url) || !isChannelPage);
@@ -280,34 +246,4 @@ function ClaimPreviewTile(props: Props) {
);
}
export default React.memo<Props>(withRouter(ClaimPreviewTile), areEqual);
const BLOCKLIST_KEYS = ['blackListedOutpoints', 'filteredOutpoints', 'blockedChannelUris'];
const HANDLED_KEYS = [...BLOCKLIST_KEYS, 'date'];
function areEqual(prev: Props, next: Props) {
for (let i = 0; i < BLOCKLIST_KEYS.length; ++i) {
const key = BLOCKLIST_KEYS[i];
const a = prev[key];
const b = next[key];
if (((!a || !b) && a !== b) || (a && b && a.length !== b.length)) {
// The arrays are huge, so just compare the length instead of each entry.
return false;
}
}
if (Number(prev.date) !== Number(next.date)) {
return false;
}
const propKeys = Object.keys(next);
for (let i = 0; i < propKeys.length; ++i) {
const pk = propKeys[i];
if (!HANDLED_KEYS.includes(pk) && prev[pk] !== next[pk]) {
return false;
}
}
return true;
}
export default withRouter(ClaimPreviewTile);
+2 -2
View File
@@ -1,10 +1,10 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectTitleForUri } from 'redux/selectors/claims';
import { makeSelectClaimForUri, selectTitleForUri } from 'redux/selectors/claims';
import ClaimPreviewTitle from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
title: selectTitleForUri(state, props.uri),
});
export default connect(select)(ClaimPreviewTitle);
+11 -7
View File
@@ -1,12 +1,16 @@
import { connect } from 'react-redux';
import { makeSelectClaimIsMine, makeSelectClaimForUri } from 'redux/selectors/claims';
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
import { selectClaimIsMine, selectClaimForUri } from 'redux/selectors/claims';
import { selectIsSubscribedForUri } from 'redux/selectors/subscriptions';
import ClaimProperties from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
isSubscribed: makeSelectIsSubscribed(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
claim,
isSubscribed: selectIsSubscribedForUri(state, props.uri),
claimIsMine: selectClaimIsMine(state, claim),
};
};
export default connect(select, null)(ClaimProperties);
+6
View File
@@ -0,0 +1,6 @@
import { connect } from 'react-redux';
import { doOpenModal } from 'redux/actions/app';
import { doToast } from 'redux/actions/notifications';
import ClaimReportButton from './view';
export default connect(null, { doOpenModal, doToast })(ClaimReportButton);
+43
View File
@@ -0,0 +1,43 @@
// @flow
import { SITE_NAME } from 'config';
import * as MODALS from 'constants/modal_types';
import * as ICONS from 'constants/icons';
import React from 'react';
import Button from 'component/button';
type Props = {
uri: string,
claim: StreamClaim,
hasChannels: boolean,
doOpenModal: (string, {}) => void,
doToast: ({ message: string }) => void,
};
export default function ClaimRepostButton(props: Props) {
const { uri, claim, hasChannels, doOpenModal, doToast } = props;
const [contentUri, setContentUri] = React.useState('');
const [repostUri, setRepostUri] = React.useState('');
return (
<Button
button="alt"
className="button--file-action"
icon={ICONS.REPOST}
label={
claim.meta.reposted > 1 ? __(`%repost_total% Reposts`, { repost_total: claim.meta.reposted }) : __('Repost')
}
description={__('Repost')}
onClick={() => {
if (!hasChannels) {
doToast({
message: __('A channel is required to repost on %SITE_NAME%', { SITE_NAME }),
linkText: __('Create Channel'),
linkTarget: '/channel/new',
});
} else {
doOpenModal(MODALS.REPOST, { uri, contentUri, setContentUri, repostUri, setRepostUri, isModal: true });
}
}}
/>
);
}
-1
View File
@@ -28,7 +28,6 @@ export default function ClaimSupportButton(props: Props) {
icon={ICONS.LBC}
iconSize={fileAction ? 22 : undefined}
label={isRepost ? __('Support Repost') : __('Support --[button to support a claim]--')}
requiresAuth={IS_WEB}
title={__('Support this claim')}
onClick={() => doOpenModal(MODALS.SEND_TIP, { uri, isSupport: true })}
/>
+12 -12
View File
@@ -88,7 +88,7 @@ function ClaimTilesDiscover(props: Props) {
fetchingClaimSearchByQuery,
hasNoSource,
renderProperties,
pinUrls,
// pinUrls,
prefixUris,
showNoSourceClaims,
doFetchViewCount,
@@ -106,17 +106,17 @@ function ClaimTilesDiscover(props: Props) {
const shouldPerformSearch = !fetchingClaimSearch && claimSearchUris.length === 0;
const uris = (prefixUris || []).concat(claimSearchUris);
if (pinUrls && uris && uris.length > 2 && window.location.pathname === '/') {
pinUrls.forEach((pin) => {
if (uris.indexOf(pin) !== -1) {
uris.splice(uris.indexOf(pin), 1);
} else {
uris.pop();
}
});
uris.splice(2, 0, ...pinUrls);
}
// Not sure what to do with pinUrls
// if (pinUrls && uris && uris.length > 2 && window.location.pathname === '/') {
// pinUrls.forEach((pin) => {
// if (uris.indexOf(pin) !== -1) {
// uris.splice(uris.indexOf(pin), 1);
// } else {
// uris.pop();
// }
// });
// uris.splice(2, 0, ...pinUrls);
// }
if (uris.length > 0 && uris.length < pageSize && shouldPerformSearch) {
// prefixUri and pinUrls might already be present while waiting for the
+20 -8
View File
@@ -55,6 +55,20 @@ function CollectionActions(props: Props) {
const claimId = claim && claim.claim_id;
const webShareable = true; // collections have cost?
/*
A bit too much dependency with both ordering and shuffling depending on a single list item index selector
For now when they click edit, we'll toggle shuffle off for them.
*/
const handleSetShowEdit = (setting) => {
doToggleShuffleList(collectionId, false);
setShowEdit(setting);
};
const handlePublishMode = () => {
doToggleShuffleList(collectionId, false);
push(`?${PAGE_VIEW_QUERY}=${EDIT_PAGE}`);
};
const doPlay = React.useCallback(
(playUri) => {
const navigateUrl = formatLbryUrlForWeb(playUri);
@@ -124,7 +138,7 @@ function CollectionActions(props: Props) {
title={uri ? __('Update') : __('Publish')}
label={uri ? __('Update') : __('Publish')}
className={classnames('button--file-action')}
onClick={() => push(`?${PAGE_VIEW_QUERY}=${EDIT_PAGE}`)}
onClick={() => handlePublishMode()}
icon={ICONS.PUBLISH}
iconColor={collectionHasEdits && 'red'}
iconSize={18}
@@ -169,7 +183,7 @@ function CollectionActions(props: Props) {
'button-toggle--active': showEdit,
})}
icon={ICONS.EDIT}
onClick={() => setShowEdit(!showEdit)}
onClick={() => handleSetShowEdit(!showEdit)}
/>
);
@@ -188,12 +202,10 @@ function CollectionActions(props: Props) {
{lhsSection}
{rhsSection}
</div>
{uri && (
<div className="section">
{infoButton}
{showEditButton}
</div>
)}
<div className="section">
{uri && infoButton}
{showEditButton}
</div>
</div>
);
}
@@ -1,6 +1,6 @@
import { connect } from 'react-redux';
import CollectionContent from './view';
import { makeSelectClaimForUri, makeSelectClaimIsMine } from 'redux/selectors/claims';
import { selectClaimForUri, selectClaimIsMine } from 'redux/selectors/claims';
import {
makeSelectUrlsForCollectionId,
makeSelectNameForCollectionId,
@@ -12,7 +12,7 @@ import { doToggleLoopList, doToggleShuffleList } from 'redux/actions/content';
const select = (state, props) => {
const playingUri = selectPlayingUri(state);
const playingUrl = playingUri && playingUri.uri;
const claim = makeSelectClaimForUri(playingUrl)(state);
const claim = selectClaimForUri(state, playingUrl);
const url = claim && claim.permanent_url;
const loopList = selectListLoop(state);
const loop = loopList && loopList.collectionId === props.id && loopList.loop;
@@ -24,7 +24,7 @@ const select = (state, props) => {
collection: makeSelectCollectionForId(props.id)(state),
collectionUrls: makeSelectUrlsForCollectionId(props.id)(state),
collectionName: makeSelectNameForCollectionId(props.id)(state),
isMine: makeSelectClaimIsMine(url)(state),
isMine: selectClaimIsMine(state, claim),
loop,
shuffle,
};
+4 -4
View File
@@ -1,7 +1,7 @@
import { connect } from 'react-redux';
import {
makeSelectTitleForUri,
makeSelectThumbnailForUri,
selectTitleForUri,
selectThumbnailForUri,
makeSelectMetadataItemForUri,
makeSelectAmountForUri,
makeSelectClaimForUri,
@@ -25,8 +25,8 @@ import { doSetActiveChannel, doSetIncognito } from 'redux/actions/app';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
thumbnailUrl: makeSelectThumbnailForUri(props.uri)(state),
title: selectTitleForUri(state, props.uri),
thumbnailUrl: selectThumbnailForUri(state, props.uri),
description: makeSelectMetadataItemForUri(props.uri, 'description')(state),
tags: makeSelectMetadataItemForUri(props.uri, 'tags')(state),
locations: makeSelectMetadataItemForUri(props.uri, 'locations')(state),
+1 -2
View File
@@ -1,5 +1,4 @@
// @flow
import { DOMAIN } from 'config';
import React from 'react';
import classnames from 'classnames';
import Button from 'component/button';
@@ -90,7 +89,7 @@ function CollectionForm(props: Props) {
onDone,
} = props;
const activeChannelName = activeChannelClaim && activeChannelClaim.name;
let prefix = IS_WEB ? `${DOMAIN}/` : 'lbry://';
let prefix = 'lbry://';
if (activeChannelName && !incognito) {
prefix += `${activeChannelName}/`;
}
@@ -1,5 +1,5 @@
import { connect } from 'react-redux';
import { makeSelectIsUriResolving, makeSelectClaimIdForUri, makeSelectClaimForClaimId } from 'redux/selectors/claims';
import { selectIsUriResolving, selectClaimIdForUri, makeSelectClaimForClaimId } from 'redux/selectors/claims';
import {
makeSelectUrlsForCollectionId,
makeSelectNameForCollectionId,
@@ -10,7 +10,7 @@ import { doFetchItemsInCollection } from 'redux/actions/collections';
import CollectionPreviewOverlay from './view';
const select = (state, props) => {
const collectionId = props.collectionId || (props.uri && makeSelectClaimIdForUri(props.uri)(state));
const collectionId = props.collectionId || (props.uri && selectClaimIdForUri(state, props.uri));
const claim = props.collectionId && makeSelectClaimForClaimId(props.collectionId)(state);
const collectionUri = props.uri || (claim && (claim.canonical_url || claim.permanent_url)) || null;
@@ -22,7 +22,7 @@ const select = (state, props) => {
collectionItemUrls: makeSelectUrlsForCollectionId(collectionId)(state), // ForId || ForUri
pendingCollection: makeSelectPendingCollectionForId(collectionId)(state),
claim,
isResolvingUri: collectionUri && makeSelectIsUriResolving(collectionUri)(state),
isResolvingUri: collectionUri && selectIsUriResolving(state, collectionUri),
};
};
+8 -8
View File
@@ -1,11 +1,11 @@
import { connect } from 'react-redux';
import {
makeSelectIsUriResolving,
makeSelectThumbnailForUri,
makeSelectTitleForUri,
selectIsUriResolving,
getThumbnailFromClaim,
selectTitleForUri,
makeSelectChannelForClaimUri,
makeSelectClaimIsNsfw,
makeSelectClaimIdForUri,
selectClaimIdForUri,
makeSelectClaimForClaimId,
} from 'redux/selectors/claims';
import {
@@ -24,7 +24,7 @@ import { selectShowMatureContent } from 'redux/selectors/settings';
import CollectionPreviewTile from './view';
const select = (state, props) => {
const collectionId = props.collectionId || (props.uri && makeSelectClaimIdForUri(props.uri)(state));
const collectionId = props.collectionId || (props.uri && selectClaimIdForUri(state, props.uri));
const claim = props.collectionId && makeSelectClaimForClaimId(props.collectionId)(state);
const collectionUri = props.uri || (claim && (claim.canonical_url || claim.permanent_url)) || null;
@@ -39,9 +39,9 @@ const select = (state, props) => {
claim,
isResolvingCollectionClaims: makeSelectIsResolvingCollectionForId(collectionId)(state),
channelClaim: collectionUri && makeSelectChannelForClaimUri(collectionUri)(state),
isResolvingUri: collectionUri && makeSelectIsUriResolving(collectionUri)(state),
thumbnail: collectionUri && makeSelectThumbnailForUri(collectionUri)(state),
title: collectionUri && makeSelectTitleForUri(collectionUri)(state),
isResolvingUri: collectionUri && selectIsUriResolving(state, collectionUri),
thumbnail: getThumbnailFromClaim(claim),
title: collectionUri && selectTitleForUri(state, collectionUri),
blackListedOutpoints: selectBlackListedOutpoints(state),
filteredOutpoints: selectFilteredOutpoints(state),
blockedChannelUris: selectMutedChannels(state),
+29 -37
View File
@@ -95,44 +95,36 @@ export default function CollectionsListMine(props: Props) {
{builtin.map((list: Collection) => {
const { items: itemUrls } = list;
return (
<div className="claim-grid__wrapper" key={list.name}>
<>
{Boolean(itemUrls && itemUrls.length) && (
<>
<h1 className="claim-grid__header">
<Button
className="claim-grid__title"
button="link"
navigate={`/$/${PAGES.LIST}/${list.id}`}
label={
<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
}
/>
{itemUrls.length}
</div>
</span>
}
/>
</h1>
<ClaimList tileLayout key={list.name} uris={itemUrls.slice(0, 6)} collectionId={list.id} />
</>
)}
{!(itemUrls && itemUrls.length) && (
<h1 className="claim-grid__header claim-grid__title">
{__(`${list.name}`)}
<div className="claim-grid__title--empty">{__('(Empty) --[indicates empty playlist]--')}</div>
<>
{Boolean(itemUrls && itemUrls.length) && (
<div className="claim-grid__wrapper" key={list.name}>
<h1 className="claim-grid__header">
<Button
className="claim-grid__title"
button="link"
navigate={`/$/${PAGES.LIST}/${list.id}`}
label={
<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
}
/>
{itemUrls.length}
</div>
</span>
}
/>
</h1>
)}
</>
</div>
<ClaimList tileLayout key={list.name} uris={itemUrls.slice(0, 6)} collectionId={list.id} />
</div>
)}
</>
);
})}
<div className="claim-grid__wrapper">
+7 -8
View File
@@ -1,15 +1,14 @@
import { connect } from 'react-redux';
import {
makeSelectStakedLevelForChannelUri,
selectTotalStakedAmountForChannelUri,
makeSelectClaimForUri,
makeSelectThumbnailForUri,
selectMyChannelClaims,
selectThumbnailForUri,
selectHasChannels,
} from 'redux/selectors/claims';
import { doCommentUpdate, doCommentList } from 'redux/actions/comments';
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,
selectOthersReactsForComment,
@@ -26,14 +25,14 @@ const select = (state, props) => {
return {
claim: makeSelectClaimForUri(props.uri)(state),
thumbnail: props.authorUri && makeSelectThumbnailForUri(props.authorUri)(state),
thumbnail: props.authorUri && selectThumbnailForUri(state, props.authorUri),
channelIsBlocked: props.authorUri && makeSelectChannelIsMuted(props.authorUri)(state),
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
commentingEnabled: true,
othersReacts: selectOthersReactsForComment(state, reactionKey),
activeChannelClaim,
myChannels: selectMyChannelClaims(state),
hasChannels: selectHasChannels(state),
playingUri: selectPlayingUri(state),
stakedLevel: makeSelectStakedLevelForChannelUri(props.authorUri)(state),
stakedLevel: selectTotalStakedAmountForChannelUri(state, props.authorUri),
linkedCommentAncestors: selectLinkedCommentAncestors(state),
totalReplyPages: makeSelectTotalReplyPagesForParentId(props.commentId)(state),
};
+10 -11
View File
@@ -26,6 +26,8 @@ import CommentCreate from 'component/commentCreate';
import CommentMenuList from 'component/commentMenuList';
import UriIndicator from 'component/uriIndicator';
import CreditAmount from 'component/common/credit-amount';
import OptimizedImage from 'component/optimizedImage';
import { parseSticker } from 'util/comments';
const AUTO_EXPAND_ALL_REPLIES = false;
@@ -47,7 +49,7 @@ type Props = {
commentModBlock: (string) => void,
linkedCommentId?: string,
linkedCommentAncestors: { [string]: Array<string> },
myChannels: ?Array<ChannelClaim>,
hasChannels: boolean,
commentingEnabled: boolean,
doToast: ({ message: string }) => void,
isTopLevel?: boolean,
@@ -92,7 +94,7 @@ function Comment(props: Props) {
linkedCommentId,
linkedCommentAncestors,
commentingEnabled,
myChannels,
hasChannels,
doToast,
isTopLevel,
threadDepth,
@@ -125,12 +127,12 @@ function Comment(props: Props) {
const [page, setPage] = useState(0);
const [advancedEditor] = usePersistedState('comment-editor-mode', false);
const [displayDeadComment, setDisplayDeadComment] = React.useState(false);
const hasChannels = myChannels && myChannels.length > 0;
const likesCount = (othersReacts && othersReacts.like) || 0;
const dislikesCount = (othersReacts && othersReacts.dislike) || 0;
const totalLikesAndDislikes = likesCount + dislikesCount;
const slimedToDeath = totalLikesAndDislikes >= 5 && dislikesCount / totalLikesAndDislikes > 0.8;
const commentByOwnerOfContent = claim && claim.signing_channel && claim.signing_channel.permanent_url === authorUri;
const stickerFromMessage = parseSticker(message);
let channelOwnerOfContent;
try {
@@ -314,13 +316,7 @@ function Comment(props: Props) {
textAreaMaxLength={FF_MAX_CHARS_IN_COMMENT}
/>
<div className="section__actions section__actions--no-margin">
<Button
button="primary"
type="submit"
label={__('Done')}
requiresAuth={IS_WEB}
disabled={message === editedMessage}
/>
<Button button="primary" type="submit" label={__('Done')} disabled={message === editedMessage} />
<Button button="link" label={__('Cancel')} onClick={() => setEditing(false)} />
</div>
</Form>
@@ -331,6 +327,10 @@ function Comment(props: Props) {
<div onClick={() => setDisplayDeadComment(true)} className="comment__dead">
{__('This comment was slimed to death.')} <Icon icon={ICONS.SLIME_ACTIVE} />
</div>
) : stickerFromMessage ? (
<div className="sticker__comment">
<OptimizedImage src={stickerFromMessage.url} waitLoad loading="lazy" />
</div>
) : editedMessage.length >= LENGTH_TO_COLLAPSE ? (
<Expandable>
<MarkdownPreview
@@ -354,7 +354,6 @@ function Comment(props: Props) {
<div className="comment__actions">
{threadDepth !== 0 && (
<Button
requiresAuth={IS_WEB}
label={commentingEnabled ? __('Reply') : __('Log in to reply')}
className="comment__action"
onClick={handleCommentReply}
@@ -0,0 +1,66 @@
// @flow
import 'scss/component/_emote-selector.scss';
import { EMOTES_48px as EMOTES } from 'constants/emotes';
import * as ICONS from 'constants/icons';
import Button from 'component/button';
import EMOJIS from 'emoji-dictionary';
import OptimizedImage from 'component/optimizedImage';
import React from 'react';
const OLD_QUICK_EMOJIS = [
EMOJIS.getUnicode('rocket'),
EMOJIS.getUnicode('jeans'),
EMOJIS.getUnicode('fire'),
EMOJIS.getUnicode('heart'),
EMOJIS.getUnicode('open_mouth'),
];
type Props = { commentValue: string, setCommentValue: (string) => void, closeSelector: () => void };
export default function EmoteSelector(props: Props) {
const { commentValue, setCommentValue, closeSelector } = props;
function addEmoteToComment(emote: string) {
setCommentValue(
commentValue + (commentValue && commentValue.charAt(commentValue.length - 1) !== ' ' ? ` ${emote} ` : `${emote} `)
);
}
return (
<div className="emoteSelector">
<Button button="close" icon={ICONS.REMOVE} onClick={closeSelector} />
<div className="emoteSelector__list">
<div className="emoteSelector__listRow">
<div className="emoteSelector__listRowItems">
{OLD_QUICK_EMOJIS.map((emoji) => (
<Button
key={emoji}
label={emoji}
title={`:${EMOJIS.getName(emoji)}:`}
button="alt"
className="button--file-action"
onClick={() => addEmoteToComment(emoji)}
/>
))}
{EMOTES.map((emote) => {
const emoteName = emote.name.toLowerCase();
return (
<Button
key={emoteName}
title={emoteName}
button="alt"
className="button--file-action"
onClick={() => addEmoteToComment(emoteName)}
>
<OptimizedImage src={emote.url} waitLoad />
</Button>
);
})}
</div>
</div>
</div>
</div>
);
}
+23 -20
View File
@@ -1,36 +1,39 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
makeSelectClaimIsMine,
selectMyChannelClaims,
selectClaimForUri,
selectClaimIsMine,
selectHasChannels,
selectFetchingMyChannels,
makeSelectTagInClaimOrChannelForUri,
} from 'redux/selectors/claims';
import { doSendTip } from 'redux/actions/wallet';
import { CommentCreate } from './view';
import { DISABLE_SUPPORT_TAG } from 'constants/tags';
import { doCommentCreate, doFetchCreatorSettings, doCommentById } from 'redux/actions/comments';
import { doSendTip } from 'redux/actions/wallet';
import { doToast } from 'redux/actions/notifications';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import { selectSettingsByChannelId } from 'redux/selectors/comments';
import { CommentCreate } from './view';
import { doToast } from 'redux/actions/notifications';
import { DISABLE_SUPPORT_TAG } from 'constants/tags';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
channels: selectMyChannelClaims(state),
isFetchingChannels: selectFetchingMyChannels(state),
activeChannelClaim: selectActiveChannelClaim(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
settingsByChannelId: selectSettingsByChannelId(state),
supportDisabled: makeSelectTagInClaimOrChannelForUri(props.uri, DISABLE_SUPPORT_TAG)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
activeChannelClaim: selectActiveChannelClaim(state),
hasChannels: selectHasChannels(state),
claim,
claimIsMine: selectClaimIsMine(state, claim),
isFetchingChannels: selectFetchingMyChannels(state),
settingsByChannelId: selectSettingsByChannelId(state),
supportDisabled: makeSelectTagInClaimOrChannelForUri(props.uri, DISABLE_SUPPORT_TAG)(state),
};
};
const perform = (dispatch, ownProps) => ({
createComment: (comment, claimId, parentId, txid, payment_intent_id, environment) =>
dispatch(doCommentCreate(comment, claimId, parentId, ownProps.uri, txid, payment_intent_id, environment)),
sendTip: (params, callback, errorCallback) => dispatch(doSendTip(params, false, callback, errorCallback, false)),
doToast: (options) => dispatch(doToast(options)),
createComment: (comment, claimId, parentId, txid, payment_intent_id, environment, sticker) =>
dispatch(doCommentCreate(comment, claimId, parentId, ownProps.uri, txid, payment_intent_id, environment, sticker)),
doFetchCreatorSettings: (channelClaimId) => dispatch(doFetchCreatorSettings(channelClaimId)),
doToast: (options) => dispatch(doToast(options)),
fetchComment: (commentId) => dispatch(doCommentById(commentId, false)),
sendTip: (params, callback, errorCallback) => dispatch(doSendTip(params, false, callback, errorCallback, false)),
});
export default connect(select, perform)(CommentCreate);
@@ -0,0 +1,94 @@
// @flow
import 'scss/component/_sticker-selector.scss';
import { FREE_GLOBAL_STICKERS, PAID_GLOBAL_STICKERS } from 'constants/stickers';
import * as ICONS from 'constants/icons';
import Button from 'component/button';
import CreditAmount from 'component/common/credit-amount';
import OptimizedImage from 'component/optimizedImage';
import React from 'react';
const buildStickerSideLink = (section: string, icon: string) => ({ section, icon });
const STICKER_SIDE_LINKS = [
buildStickerSideLink(__('Free'), ICONS.TAG),
buildStickerSideLink(__('Tips'), ICONS.FINANCE),
// Future work may include Channel, Subscriptions, ...
];
type Props = { claimIsMine: boolean, onSelect: (any) => void };
export default function StickerSelector(props: Props) {
const { claimIsMine, onSelect } = props;
function scrollToStickerSection(section: string) {
const listBodyEl = document.querySelector('.stickerSelector__listBody');
const sectionToScroll = document.getElementById(section);
if (listBodyEl && sectionToScroll) {
// $FlowFixMe
listBodyEl.scrollTo({
top: sectionToScroll.offsetTop - sectionToScroll.getBoundingClientRect().height * 2,
behavior: 'smooth',
});
}
}
const getListRow = (rowTitle: string, rowStickers: any) => (
<div className="stickerSelector__listBody-row">
<div id={rowTitle} className="stickerSelector__listBody-rowTitle">
{rowTitle}
</div>
<div className="stickerSelector__listBody-rowItems">
{rowStickers.map((sticker) => (
<Button
key={sticker.name}
title={sticker.name}
button="alt"
className="button--file-action"
onClick={() => onSelect(sticker)}
>
<OptimizedImage src={sticker.url} waitLoad loading="lazy" />
{sticker.price && sticker.price > 0 && (
<CreditAmount superChatLight amount={sticker.price} size={2} isFiat />
)}
</Button>
))}
</div>
</div>
);
return (
<div className="stickerSelector">
<div className="stickerSelector__header card__header--between">
<div className="stickerSelector__headerTitle card__title-section--small">{__('Stickers')}</div>
</div>
<div className="stickerSelector__list">
<div className="stickerSelector__listBody">
{getListRow(__('Free'), FREE_GLOBAL_STICKERS)}
{!claimIsMine && getListRow(__('Tips'), PAID_GLOBAL_STICKERS)}
</div>
<div className="navigation__wrapper">
<ul className="navigation-links">
{STICKER_SIDE_LINKS.map(
(linkProps) =>
((claimIsMine && linkProps.section !== 'Tips') || !claimIsMine) && (
<li key={linkProps.section}>
<Button
label={__(linkProps.section)}
title={__(linkProps.section)}
icon={linkProps.icon}
iconSize={1}
className="navigation-link"
onClick={() => scrollToStickerSection(linkProps.section)}
/>
</li>
)
)}
</ul>
</div>
</div>
</div>
);
}
+391 -344
View File
@@ -1,4 +1,8 @@
// @flow
import 'scss/component/_comment-create.scss';
import { buildValidSticker } from 'util/comments';
import { FF_MAX_CHARS_IN_COMMENT } from 'constants/form-field';
import { FormField, Form } from 'component/common/form';
import { getChannelIdFromClaim } from 'util/claim';
@@ -8,163 +12,146 @@ import * as ICONS from 'constants/icons';
import * as KEYCODES from 'constants/keycodes';
import * as PAGES from 'constants/pages';
import Button from 'component/button';
import ChannelMentionSuggestions from 'component/channelMentionSuggestions';
import ChannelThumbnail from 'component/channelThumbnail';
import classnames from 'classnames';
import CreditAmount from 'component/common/credit-amount';
import EmoteSelector from './emote-selector';
import Empty from 'component/common/empty';
import FilePrice from 'component/filePrice';
import I18nMessage from 'component/i18nMessage';
import Icon from 'component/common/icon';
import OptimizedImage from 'component/optimizedImage';
import React from 'react';
import SelectChannel from 'component/selectChannel';
import StickerSelector from './sticker-selector';
import type { ElementRef } from 'react';
import UriIndicator from 'component/uriIndicator';
import usePersistedState from 'effects/use-persisted-state';
import WalletTipAmountSelector from 'component/walletTipAmountSelector';
import { getStripeEnvironment } from 'util/stripe';
let stripeEnvironment = getStripeEnvironment();
const stripeEnvironment = getStripeEnvironment();
const TAB_FIAT = 'TabFiat';
const TAB_LBC = 'TabLBC';
const MENTION_DEBOUNCE_MS = 100;
// for sendCashTip REMOVE
// type TipParams = { tipAmount: number, tipChannelName: string, channelClaimId: string };
// type UserParams = { activeChannelName: ?string, activeChannelId: ?string };
type Props = {
uri: string,
claim: StreamClaim,
channels: ?Array<ChannelClaim>,
isNested: boolean,
isFetchingChannels: boolean,
parentId: string,
isReply: boolean,
activeChannel: string,
activeChannelClaim: ?ChannelClaim,
bottom: boolean,
embed?: boolean,
hasChannels: boolean,
claim: StreamClaim,
claimIsMine: boolean,
supportDisabled: boolean,
isFetchingChannels: boolean,
isNested: boolean,
isReply: boolean,
parentId: string,
settingsByChannelId: { [channelId: string]: PerChannelSettings },
shouldFetchComment: boolean,
doToast: ({ message: string }) => void,
createComment: (string, string, string, ?string, ?string, ?string) => Promise<any>,
onDoneReplying?: () => void,
onCancelReplying?: () => void,
toast: (string) => void,
sendTip: ({}, (any) => void, (any) => void) => void,
supportDisabled: boolean,
uri: string,
createComment: (string, string, string, ?string, ?string, ?string, ?boolean) => Promise<any>,
doFetchCreatorSettings: (channelId: string) => Promise<any>,
setQuickReply: (any) => void,
doToast: ({ message: string }) => void,
fetchComment: (commentId: string) => Promise<any>,
onCancelReplying?: () => void,
onDoneReplying?: () => void,
sendTip: ({}, (any) => void, (any) => void) => void,
setQuickReply: (any) => void,
toast: (string) => void,
};
export function CommentCreate(props: Props) {
const {
uri,
claim,
channels,
isNested,
isFetchingChannels,
isReply,
parentId,
activeChannelClaim,
bottom,
hasChannels,
claim,
claimIsMine,
isFetchingChannels,
isNested,
isReply,
parentId,
settingsByChannelId,
supportDisabled,
shouldFetchComment,
doToast,
supportDisabled,
createComment,
onDoneReplying,
onCancelReplying,
sendTip,
doFetchCreatorSettings,
setQuickReply,
doToast,
fetchComment,
onCancelReplying,
onDoneReplying,
sendTip,
setQuickReply,
} = props;
const formFieldRef: ElementRef<any> = React.useRef();
const formFieldInputRef = formFieldRef && formFieldRef.current && formFieldRef.current.input;
const selectionIndex = formFieldInputRef && formFieldInputRef.current && formFieldInputRef.current.selectionStart;
const buttonRef: ElementRef<any> = React.useRef();
const {
push,
location: { pathname },
} = useHistory();
const [isSubmitting, setIsSubmitting] = React.useState(false);
const [isSubmitting, setSubmitting] = React.useState(false);
const [commentFailure, setCommentFailure] = React.useState(false);
const [successTip, setSuccessTip] = React.useState({ txid: undefined, tipAmount: undefined });
const [isSupportComment, setIsSupportComment] = React.useState();
const [isReviewingSupportComment, setIsReviewingSupportComment] = React.useState();
const [isReviewingSupportComment, setReviewingSupportComment] = React.useState();
const [isReviewingStickerComment, setReviewingStickerComment] = React.useState();
const [selectedSticker, setSelectedSticker] = React.useState();
const [tipAmount, setTipAmount] = React.useState(1);
const [convertedAmount, setConvertedAmount] = React.useState();
const [commentValue, setCommentValue] = React.useState('');
const [advancedEditor, setAdvancedEditor] = usePersistedState('comment-editor-mode', false);
const [activeTab, setActiveTab] = React.useState('');
const [stickerSelector, setStickerSelector] = React.useState();
const [activeTab, setActiveTab] = React.useState();
const [tipError, setTipError] = React.useState();
const [deletedComment, setDeletedComment] = React.useState(false);
const [pauseQuickSend, setPauseQuickSend] = React.useState(false);
const [shouldDisableReviewButton, setShouldDisableReviewButton] = React.useState();
const selectedMentionIndex =
commentValue.indexOf('@', selectionIndex) === selectionIndex
? commentValue.indexOf('@', selectionIndex)
: commentValue.lastIndexOf('@', selectionIndex);
const modifierIndex = commentValue.indexOf(':', selectedMentionIndex);
const spaceIndex = commentValue.indexOf(' ', selectedMentionIndex);
const mentionLengthIndex =
modifierIndex >= 0 && (spaceIndex === -1 || modifierIndex < spaceIndex)
? modifierIndex
: spaceIndex >= 0 && (modifierIndex === -1 || spaceIndex < modifierIndex)
? spaceIndex
: commentValue.length;
const channelMention =
selectedMentionIndex >= 0 && selectionIndex <= mentionLengthIndex
? commentValue.substring(selectedMentionIndex, mentionLengthIndex)
: '';
const [showEmotes, setShowEmotes] = React.useState(false);
const [disableReviewButton, setDisableReviewButton] = React.useState();
const [exchangeRate, setExchangeRate] = React.useState();
const [canReceiveFiatTip, setCanReceiveFiatTip] = React.useState(undefined);
const claimId = claim && claim.claim_id;
const signingChannel = (claim && claim.signing_channel) || claim;
const channelUri = signingChannel && signingChannel.permanent_url;
const hasChannels = channels && channels.length;
const charCount = commentValue ? commentValue.length : 0;
const disabled = deletedComment || isSubmitting || isFetchingChannels || !commentValue.length || pauseQuickSend;
const disabled = deletedComment || isSubmitting || isFetchingChannels || !commentValue.length;
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;
const stickerPrice = selectedSticker && selectedSticker.price;
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 handleSelectSticker(sticker: any) {
// $FlowFixMe
setSelectedSticker(sticker);
setReviewingStickerComment(true);
setTipAmount(sticker.price || 0);
setStickerSelector(false);
if (sticker.price && sticker.price > 0) {
setActiveTab(TAB_LBC);
setIsSupportComment(true);
}
}
function handleCommentChange(event) {
let commentValue;
if (isReply) {
commentValue = event.target.value;
commentValue = advancedEditor ? event : event.target.value;
} else {
commentValue = advancedEditor ? event : event.target.value;
}
@@ -172,19 +159,6 @@ export function CommentCreate(props: Props) {
setCommentValue(commentValue);
}
function handleSelectMention(mentionValue, key) {
let newMentionValue = mentionValue.replace('lbry://', '');
if (newMentionValue.includes('#')) newMentionValue = newMentionValue.replace('#', ':');
setCommentValue(
commentValue.substring(0, selectedMentionIndex) +
`${newMentionValue}` +
(commentValue.length > mentionLengthIndex + 1
? commentValue.substring(mentionLengthIndex, commentValue.length)
: ' ')
);
}
function altEnterListener(e: SyntheticKeyboardEvent<*>) {
if ((e.ctrlKey || e.metaKey) && e.keyCode === KEYCODES.ENTER) {
e.preventDefault();
@@ -200,16 +174,8 @@ export function CommentCreate(props: Props) {
window.removeEventListener('keydown', altEnterListener);
}
function handleSubmit() {
if (activeChannelClaim && commentValue.length) {
handleCreateComment();
}
}
function handleSupportComment() {
if (!activeChannelClaim) {
return;
}
if (!activeChannelClaim) return;
if (!channelId) {
doToast({
@@ -237,7 +203,7 @@ export function CommentCreate(props: Props) {
message: __('The creator just updated the minimum setting. Please revise or double-check your tip amount.'),
isError: true,
});
setIsReviewingSupportComment(false);
setReviewingSupportComment(false);
return;
}
@@ -246,33 +212,18 @@ export function CommentCreate(props: Props) {
}
function doSubmitTip() {
if (!activeChannelClaim) {
return;
}
if (!activeChannelClaim || isSubmitting) return;
const params = {
amount: tipAmount,
claim_id: claimId,
channel_id: activeChannelClaim.claim_id,
};
setSubmitting(true);
const activeChannelName = activeChannelClaim && activeChannelClaim.name;
const activeChannelId = activeChannelClaim && activeChannelClaim.claim_id;
const params = { amount: tipAmount, claim_id: claimId, channel_id: activeChannelClaim.claim_id };
// FIAT ONLY - REMOVE
// const activeChannelName = activeChannelClaim && activeChannelClaim.name;
// const activeChannelId = activeChannelClaim && activeChannelClaim.claim_id;
// 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);
// const channelClaimId = claim.signing_channel ? claim.signing_channel.claim_id : claim.claim_id;
const tipChannelName = claim.signing_channel ? claim.signing_channel.name : claim.name;
if (activeTab === TAB_LBC) {
// call sendTip and then run the callback from the response
@@ -287,72 +238,34 @@ export function CommentCreate(props: Props) {
}, 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,
}
),
message: __("You sent %tipAmount% Credits as a tip to %tipChannelName%, I'm sure they appreciate it!", {
tipAmount: tipAmount, // force show decimal places
tipChannelName,
}),
});
setSuccessTip({ txid, tipAmount });
},
() => {
// reset the frontend so people can send a new comment
setIsSubmitting(false);
setSubmitting(false);
}
);
} else {
const sourceClaimId = claim.claim_id;
const roundedAmount = Math.round(tipAmount * 100) / 100;
Lbryio.call(
'customer',
'tip',
{
// 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,
tipper_channel_claim_id: activeChannelId,
currency: 'USD',
anonymous: false,
source_claim_id: sourceClaimId,
environment: stripeEnvironment,
},
'post'
)
.then((customerTipResponse) => {
const paymentIntendId = customerTipResponse.payment_intent_id;
handleCreateComment(null, paymentIntendId, stripeEnvironment);
setCommentValue('');
setIsReviewingSupportComment(false);
setIsSupportComment(false);
setCommentFailure(false);
setIsSubmitting(false);
doToast({
message: __("You sent $%formattedAmount% as a tip to %tipChannelName%, I'm sure they appreciate it!", {
formattedAmount: roundedAmount.toFixed(2), // force show decimal places
tipChannelName,
}),
});
// handleCreateComment(null);
})
.catch((error) => {
doToast({
message:
error.message !== 'payment intent failed to confirm'
? error.message
: 'Sorry, there was an error in processing your payment!',
isError: true,
});
});
// No cash tips - REMOVE
// const tipParams: TipParams = { tipAmount: Math.round(tipAmount * 100) / 100, tipChannelName, channelClaimId };
// const userParams: UserParams = { activeChannelName, activeChannelId };
// sendCashTip(tipParams, userParams, claim.claim_id, stripeEnvironment, (customerTipResponse) => {
// const { payment_intent_id } = customerTipResponse;
//
// handleCreateComment(null, payment_intent_id, stripeEnvironment);
//
// setCommentValue('');
// setReviewingSupportComment(false);
// setIsSupportComment(false);
// setCommentFailure(false);
// setSubmitting(false);
// });
}
}
@@ -363,16 +276,21 @@ export function CommentCreate(props: Props) {
* @param {string} [environment] Optional environment for Stripe (test|live)
*/
function handleCreateComment(txid, payment_intent_id, environment) {
setIsSubmitting(true);
if (isSubmitting) return;
createComment(commentValue, claimId, parentId, txid, payment_intent_id, environment)
setShowEmotes(false);
setSubmitting(true);
const stickerValue = selectedSticker && buildValidSticker(selectedSticker.name);
createComment(stickerValue || commentValue, claimId, parentId, txid, payment_intent_id, environment, !!stickerValue)
.then((res) => {
setIsSubmitting(false);
setSubmitting(false);
if (setQuickReply) setQuickReply(res);
if (res && res.signature) {
setCommentValue('');
setIsReviewingSupportComment(false);
if (!stickerValue) setCommentValue('');
setReviewingSupportComment(false);
setIsSupportComment(false);
setCommentFailure(false);
@@ -382,7 +300,7 @@ export function CommentCreate(props: Props) {
}
})
.catch(() => {
setIsSubmitting(false);
setSubmitting(false);
setCommentFailure(true);
if (channelId) {
@@ -413,22 +331,72 @@ export function CommentCreate(props: Props) {
}
}, [fetchComment, shouldFetchComment, parentId]);
// Debounce for disabling the submit button when mentioning a user with Enter
// so that the comment isn't sent at the same time
// Stickers: Get LBC-USD exchange rate if hasn't yet and selected a paid sticker
React.useEffect(() => {
const timer = setTimeout(() => {
if (pauseQuickSend) {
setPauseQuickSend(false);
}
}, MENTION_DEBOUNCE_MS);
if (stickerPrice && !exchangeRate) Lbryio.getExchangeRates().then(({ LBC_USD }) => setExchangeRate(LBC_USD));
}, [exchangeRate, stickerPrice]);
return () => clearTimeout(timer);
}, [pauseQuickSend]);
// Stickers: Check if creator has a tip account saved (on selector so that if a paid sticker is selected,
// it defaults to LBC tip instead of USD)
React.useEffect(() => {
if (!stripeEnvironment || !stickerSelector || canReceiveFiatTip !== undefined) return;
const channelClaimId = claim.signing_channel ? claim.signing_channel.claim_id : claim.claim_id;
const tipChannelName = claim.signing_channel ? claim.signing_channel.name : claim.name;
Lbryio.call(
'account',
'check',
{
channel_claim_id: channelClaimId,
channel_name: tipChannelName,
environment: stripeEnvironment,
},
'post'
)
.then((accountCheckResponse) => {
if (accountCheckResponse === true && canReceiveFiatTip !== true) {
setCanReceiveFiatTip(true);
} else {
setCanReceiveFiatTip(false);
}
})
.catch(() => {});
}, [canReceiveFiatTip, claim.claim_id, claim.name, claim.signing_channel, stickerSelector]);
// LIVESTREAM ONLY - REMOVE
// Handle keyboard shortcut comment creation
// React.useEffect(() => {
// function altEnterListener(e: SyntheticKeyboardEvent<*>) {
// const inputRef = formFieldRef && formFieldRef.current && formFieldRef.current.input;
//
// if (inputRef && inputRef.current === document.activeElement) {
// // $FlowFixMe
// const isTyping = e.target.attributes['term'];
//
// if (((isLivestream && !isTyping) || e.ctrlKey || e.metaKey) && e.keyCode === KEYCODES.ENTER) {
// e.preventDefault();
// buttonRef.current.click();
// }
// }
// }
//
// window.addEventListener('keydown', altEnterListener);
//
// // removes the listener so it doesn't cause problems elsewhere in the app
// return () => {
// window.removeEventListener('keydown', altEnterListener);
// };
// }, [isLivestream]);
// **************************************************************************
// Render
// **************************************************************************
const getActionButton = (title: string, label?: string, icon: string, handleClick: () => void) => (
<Button title={title} label={label} button="alt" icon={icon} onClick={handleClick} />
);
if (channelSettings && !channelSettings.comments_enabled) {
return <Empty padded text={__('This channel has disabled comments on their page.')} />;
}
@@ -444,30 +412,113 @@ export function CommentCreate(props: Props) {
>
<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} />
<Button disabled button="primary" label={__('Post --[button to submit something]--')} />
</div>
</div>
);
}
if (isReviewingSupportComment && activeChannelClaim) {
return (
<div className="comment__create">
<div className="comment__sc-preview">
return (
<Form
onSubmit={() => {}}
className={classnames('commentCreate', {
'commentCreate--reply': isReply,
'commentCreate--nestedReply': isNested,
'commentCreate--bottom': bottom,
})}
>
{/* Input Box/Preview Box */}
{stickerSelector ? (
<StickerSelector onSelect={(sticker) => handleSelectSticker(sticker)} claimIsMine={claimIsMine} />
) : isReviewingStickerComment && activeChannelClaim && selectedSticker ? (
<div className="commentCreate__stickerPreview">
<div className="commentCreate__stickerPreviewInfo">
<ChannelThumbnail xsmall uri={activeChannelClaim.canonical_url} />
<UriIndicator uri={activeChannelClaim.canonical_url} link />
</div>
<div className="commentCreate__stickerPreviewImage">
<OptimizedImage src={selectedSticker && selectedSticker.url} waitLoad loading="lazy" />
</div>
{/* figure out lbc sticker prices */}
{selectedSticker.price && exchangeRate && (
<FilePrice
customPrices={{ priceFiat: selectedSticker.price, priceLBC: selectedSticker.price / exchangeRate }}
isFiat
/>
)}
</div>
) : isReviewingSupportComment && activeChannelClaim ? (
<div className="commentCreate__supportCommentPreview">
<CreditAmount
className="comment__sc-preview-amount"
isFiat={activeTab === TAB_FIAT}
amount={tipAmount}
className="commentCreate__supportCommentPreviewAmount"
isFiat={activeTab === TAB_FIAT}
size={activeTab === TAB_LBC ? 18 : 2}
/>
<ChannelThumbnail xsmall uri={activeChannelClaim.canonical_url} />
<div>
<UriIndicator uri={activeChannelClaim.name} link />
<div className="commentCreate__supportCommentBody">
<UriIndicator uri={activeChannelClaim.canonical_url} link />
<div>{commentValue}</div>
</div>
</div>
<div className="section__actions--no-margin">
) : (
<>
{showEmotes && (
<EmoteSelector
commentValue={commentValue}
setCommentValue={setCommentValue}
closeSelector={() => setShowEmotes(false)}
/>
)}
<FormField
autoFocus={isReply}
charCount={charCount}
className={isReply ? 'content_reply' : 'content_comment'}
disabled={isFetchingChannels}
label={
<div className="commentCreate__labelWrapper">
<span className="commentCreate__label">{(isReply ? __('Replying as') : __('Comment as')) + ' '}</span>
<SelectChannel tiny />
</div>
}
name={isReply ? 'content_reply' : 'content_description'}
quickActionLabel={isReply ? undefined : advancedEditor ? __('Simple Editor') : __('Advanced Editor')}
ref={formFieldRef}
onChange={handleCommentChange}
openEmoteMenu={() => setShowEmotes(!showEmotes)}
quickActionHandler={() => setAdvancedEditor(!advancedEditor)}
onFocus={onTextareaFocus}
onBlur={onTextareaBlur}
placeholder={__('Say something about this...')}
value={commentValue}
type={advancedEditor ? 'markdown' : 'textarea'}
textAreaMaxLength={FF_MAX_CHARS_IN_COMMENT}
/>
</>
)}
{(isSupportComment || (isReviewingStickerComment && stickerPrice)) && (
<WalletTipAmountSelector
activeTab={activeTab}
amount={tipAmount}
claim={claim}
convertedAmount={convertedAmount}
customTipAmount={stickerPrice}
exchangeRate={exchangeRate}
fiatConversion={selectedSticker && !!selectedSticker.price} // REMOVE / figure out
onChange={(amount) => setTipAmount(amount)}
setConvertedAmount={setConvertedAmount}
setDisableSubmitButton={setDisableReviewButton}
setTipError={setTipError}
tipError={tipError}
/>
)}
{/* Bottom Action Buttons */}
<div className="section__actions section__actions--no-margin">
{/* Submit Button */}
{isReviewingSupportComment ? (
<Button
autoFocus
button="primary"
@@ -481,152 +532,148 @@ export function CommentCreate(props: Props) {
}
onClick={handleSupportComment}
/>
) : isReviewingStickerComment && selectedSticker ? (
<Button
disabled={isSubmitting}
button="link"
label={__('Cancel')}
onClick={() => setIsReviewingSupportComment(false)}
button="primary"
label={__('Send')}
disabled={isSupportComment && (tipError || disableReviewButton)}
onClick={() => {
if (isSupportComment) {
handleSupportComment();
} else {
handleCreateComment();
}
setSelectedSticker(null);
setReviewingStickerComment(false);
setStickerSelector(false);
setIsSupportComment(false);
}}
/>
) : isSupportComment ? (
<Button
disabled={disabled || tipError || disableReviewButton || !minAmountMet}
type="button"
button="primary"
icon={activeTab === TAB_LBC ? ICONS.LBC : ICONS.FINANCE} // only LBC
label={__('Review')}
onClick={() => setReviewingSupportComment(true)}
/>
{MinAmountNotice}
</div>
</div>
);
}
return (
<Form
onSubmit={handleSubmit}
className={classnames('comment__create', {
'comment__create--reply': isReply,
'comment__create--nested-reply': isNested,
'comment__create--bottom': bottom,
})}
>
{!advancedEditor && (
<ChannelMentionSuggestions
uri={uri}
inputRef={formFieldInputRef}
mentionTerm={channelMention}
creatorUri={channelUri}
customSelectAction={handleSelectMention}
/>
)}
<FormField
disabled={isFetchingChannels}
type={'textarea'}
name={isReply ? 'content_reply' : 'content_description'}
ref={formFieldRef}
className={isReply ? 'content_reply' : 'content_comment'}
label={
<span className="comment-new__label-wrapper">
<div className="comment-new__label">{isReply ? __('Replying as') + ' ' : __('Comment as') + ' '}</div>
<SelectChannel tiny />
</span>
}
quickActionLabel={isReply ? undefined : advancedEditor ? __('Simple Editor') : __('Advanced Editor')}
quickActionHandler={() => setAdvancedEditor(!advancedEditor)}
onFocus={onTextareaFocus}
onBlur={onTextareaBlur}
placeholder={__('Say something about this...')}
value={commentValue}
charCount={charCount}
onChange={handleCommentChange}
autoFocus={isReply}
textAreaMaxLength={FF_MAX_CHARS_IN_COMMENT}
/>
{isSupportComment && (
<WalletTipAmountSelector
onTipErrorChange={setTipError}
shouldDisableReviewButton={setShouldDisableReviewButton}
claim={claim}
activeTab={activeTab}
amount={tipAmount}
onChange={(amount) => setTipAmount(amount)}
/>
)}
<div className="section__actions section__actions--no-margin">
{isSupportComment ? (
<>
<Button
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={isSubmitting}
button="link"
label={__('Cancel')}
onClick={() => setIsSupportComment(false)}
/>
</>
) : (
(!minTip || claimIsMine) && (
<Button
ref={buttonRef}
button="primary"
disabled={disabled || stickerSelector}
type="submit"
label={
isReply
? isSubmitting
? __('Replying...')
: __('Reply')
: isSubmitting
? __('Commenting...')
: __('Comment --[button to submit something]--')
}
onClick={() => activeChannelClaim && commentValue.length && handleCreateComment()}
/>
)
)}
{/** Stickers/Support Buttons **/}
{!supportDisabled && !stickerSelector && (
<>
{(!minTip || claimIsMine) && (
<Button
ref={buttonRef}
button="primary"
disabled={disabled}
type="submit"
label={
isReply
? isSubmitting
? __('Replying...')
: __('Reply')
: isSubmitting
? __('Commenting...')
: __('Comment --[button to submit something]--')
}
requiresAuth={IS_WEB}
/>
{getActionButton(
__('Stickers'),
isReviewingStickerComment ? __('Different Sticker') : undefined,
ICONS.STICKER,
() => {
if (isReviewingStickerComment) setReviewingStickerComment(false);
setIsSupportComment(false);
setStickerSelector(true);
}
)}
{!supportDisabled && !claimIsMine && (
{/* below buttons are unnecessary - REMOVE */}
{!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={() => {
{(!isSupportComment || activeTab !== TAB_LBC) &&
getActionButton(
__('Credits'),
isSupportComment ? __('Switch to Credits') : undefined,
ICONS.LBC,
() => {
setIsSupportComment(true);
setActiveTab(TAB_LBC);
}
)}
{stripeEnvironment &&
(!isSupportComment || activeTab !== TAB_FIAT) &&
getActionButton(
__('Cash'),
isSupportComment ? __('Switch to Cash') : undefined,
ICONS.FINANCE,
() => {
setIsSupportComment(true);
setActiveTab(TAB_FIAT);
}}
/>
)}
{/* @endif */}
}
)}
</>
)}
{isReply && !minTip && (
<Button
button="link"
label={__('Cancel')}
onClick={() => {
if (onCancelReplying) {
onCancelReplying();
}
}}
/>
)}
</>
)}
{/* Cancel Button */}
{(isSupportComment ||
isReviewingSupportComment ||
stickerSelector ||
isReviewingStickerComment ||
(isReply && !minTip)) && (
<Button
disabled={isSupportComment && isSubmitting}
button="link"
label={__('Cancel')}
onClick={() => {
if (isSupportComment || isReviewingSupportComment) {
if (!isReviewingSupportComment) setIsSupportComment(false);
setReviewingSupportComment(false);
if (stickerPrice) {
setReviewingStickerComment(false);
setStickerSelector(false);
setSelectedSticker(null);
}
} else if (stickerSelector || isReviewingStickerComment) {
setReviewingStickerComment(false);
setStickerSelector(false);
setSelectedSticker(null);
} else if (isReply && !minTip && onCancelReplying) {
onCancelReplying();
}
}}
/>
)}
{/* Help Text */}
{deletedComment && <div className="error__text">{__('This comment has been deleted.')}</div>}
{MinAmountNotice}
{!!minAmount && (
<div className="help--notice commentCreate__minAmountNotice">
<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>
)}
</div>
</Form>
);
+11 -15
View File
@@ -3,25 +3,22 @@ import { doChannelMute } from 'redux/actions/blocked';
import { doCommentPin, doCommentModAddDelegate } from 'redux/actions/comments';
import { doOpenModal } from 'redux/actions/app';
import { doSetPlayingUri } from 'redux/actions/content';
import { doToast } from 'redux/actions/notifications';
import {
makeSelectChannelPermUrlForClaimUri,
makeSelectClaimIsMine,
makeSelectClaimForUri,
} from 'redux/selectors/claims';
import { selectClaimIsMine, selectClaimForUri } from 'redux/selectors/claims';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import { selectModerationDelegatorsById } from 'redux/selectors/comments';
import { selectPlayingUri } from 'redux/selectors/content';
import CommentMenuList from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
contentChannelPermanentUrl: makeSelectChannelPermUrlForClaimUri(props.uri)(state),
activeChannelClaim: selectActiveChannelClaim(state),
playingUri: selectPlayingUri(state),
moderationDelegatorsById: selectModerationDelegatorsById(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
claim,
claimIsMine: selectClaimIsMine(state, claim),
activeChannelClaim: selectActiveChannelClaim(state),
playingUri: selectPlayingUri(state),
moderationDelegatorsById: selectModerationDelegatorsById(state),
};
};
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
@@ -30,7 +27,6 @@ const perform = (dispatch) => ({
pinComment: (commentId, claimId, remove) => dispatch(doCommentPin(commentId, claimId, remove)),
commentModAddDelegate: (modChanId, modChanName, creatorChannelClaim) =>
dispatch(doCommentModAddDelegate(modChanId, modChanName, creatorChannelClaim, true)),
doToast: (props) => dispatch(doToast(props)),
});
export default connect(select, perform)(CommentMenuList);
+16 -31
View File
@@ -2,8 +2,6 @@
import { getChannelFromClaim } from 'util/claim';
import { MenuList, MenuItem } from '@reach/menu-button';
import { parseURI } from 'util/lbryURI';
import { URL } from 'config';
import { useHistory } from 'react-router';
import * as ICONS from 'constants/icons';
import * as MODALS from 'constants/modal_types';
import ChannelThumbnail from 'component/channelThumbnail';
@@ -23,7 +21,6 @@ type Props = {
// --- select ---
claim: ?Claim,
claimIsMine: boolean,
contentChannelPermanentUrl: any,
activeChannelClaim: ?ChannelClaim,
playingUri: ?PlayingUri,
moderationDelegatorsById: { [string]: { global: boolean, delegators: { name: string, claimId: string } } },
@@ -46,7 +43,6 @@ function CommentMenuList(props: Props) {
commentIsMine,
commentId,
activeChannelClaim,
contentChannelPermanentUrl,
isTopLevel,
isPinned,
playingUri,
@@ -54,7 +50,6 @@ function CommentMenuList(props: Props) {
disableEdit,
disableRemove,
supportAmount,
doToast,
handleEditComment,
openModal,
clearPlayingUri,
@@ -64,11 +59,9 @@ function CommentMenuList(props: Props) {
setQuickReply,
} = props;
const {
location: { pathname, search },
} = useHistory();
const contentChannelClaim = getChannelFromClaim(claim);
const contentChannelPermanentUrl = contentChannelClaim && contentChannelClaim.permanent_url;
const activeModeratorInfo = activeChannelClaim && moderationDelegatorsById[activeChannelClaim.claim_id];
const activeChannelIsCreator = activeChannelClaim && activeChannelClaim.permanent_url === contentChannelPermanentUrl;
const activeChannelIsAdmin = activeChannelClaim && activeModeratorInfo && activeModeratorInfo.global;
@@ -82,10 +75,12 @@ function CommentMenuList(props: Props) {
if (playingUri && playingUri.source === 'comment') {
clearPlayingUri();
}
openModal(MODALS.CONFIRM_REMOVE_COMMENT, {
commentId,
commentIsMine,
contentChannelPermanentUrl,
deleterClaim: activeChannelClaim,
deleterIsModOrAdmin: activeChannelIsAdmin || activeChannelIsModerator,
creatorClaim: commentIsMine ? undefined : contentChannelClaim,
supportAmount,
setQuickReply,
});
@@ -151,15 +146,6 @@ function CommentMenuList(props: Props) {
);
}
function handleCopyCommentLink() {
const urlParams = new URLSearchParams(search);
urlParams.delete('lc');
urlParams.append('lc', commentId);
navigator.clipboard
.writeText(`${URL}${pathname}?${urlParams.toString()}`)
.then(() => doToast({ message: __('Link copied.') }));
}
return (
<MenuList className="menu__list">
{activeChannelIsCreator && <div className="comment__menu-title">{__('Creator tools')}</div>}
@@ -199,7 +185,9 @@ function CommentMenuList(props: Props) {
{!disableRemove &&
activeChannelClaim &&
(activeChannelClaim.permanent_url === authorUri ||
(activeChannelIsModerator ||
activeChannelIsAdmin ||
activeChannelClaim.permanent_url === authorUri ||
activeChannelClaim.permanent_url === contentChannelPermanentUrl) && (
<MenuItem className="comment__menu-option" onSelect={handleDeleteComment}>
<div className="menu__link">
@@ -213,7 +201,13 @@ function CommentMenuList(props: Props) {
<>
<MenuItem
className="comment__menu-option"
onSelect={() => openModal(MODALS.BLOCK_CHANNEL, { contentUri: uri, commenterUri: authorUri })}
onSelect={() =>
openModal(MODALS.BLOCK_CHANNEL, {
contentUri: uri,
commenterUri: authorUri,
offendingCommentId: commentId,
})
}
>
{getBlockOptionElem()}
</MenuItem>
@@ -229,15 +223,6 @@ function CommentMenuList(props: Props) {
</>
)}
{IS_WEB && (
<MenuItem className="comment__menu-option" onSelect={handleCopyCommentLink}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.COPY_LINK} />
{__('Copy Link')}
</div>
</MenuItem>
)}
{activeChannelClaim && (
<div className="comment__menu-active">
<ChannelThumbnail xsmall noLazyLoad uri={activeChannelClaim.permanent_url} />
+4 -3
View File
@@ -1,6 +1,6 @@
import { connect } from 'react-redux';
import Comment from './view';
import { makeSelectClaimIsMine, makeSelectClaimForUri } from 'redux/selectors/claims';
import { selectClaimIsMine, selectClaimForUri } from 'redux/selectors/claims';
import { doResolveUri } from 'redux/actions/claims';
import { doToast } from 'redux/actions/notifications';
import { selectMyReactsForComment, selectOthersReactsForComment } from 'redux/selectors/comments';
@@ -11,10 +11,11 @@ const select = (state, props) => {
const activeChannelClaim = selectActiveChannelClaim(state);
const activeChannelId = activeChannelClaim && activeChannelClaim.claim_id;
const reactionKey = activeChannelId ? `${props.commentId}:${activeChannelId}` : props.commentId;
const claim = selectClaimForUri(state, props.uri);
return {
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
claim,
claimIsMine: selectClaimIsMine(state, claim),
myReacts: selectMyReactsForComment(state, reactionKey),
othersReacts: selectOthersReactsForComment(state, reactionKey),
activeChannelId,
-3
View File
@@ -99,7 +99,6 @@ export default function CommentReactions(props: Props) {
return (
<>
<Button
requiresAuth={IS_WEB}
title={__('Upvote')}
icon={likeIcon}
className={classnames('comment__action', {
@@ -109,7 +108,6 @@ export default function CommentReactions(props: Props) {
label={<span className="comment__reaction-count">{getCountForReact(REACTION_TYPES.LIKE)}</span>}
/>
<Button
requiresAuth={IS_WEB}
title={__('Downvote')}
icon={dislikeIcon}
className={classnames('comment__action', {
@@ -122,7 +120,6 @@ export default function CommentReactions(props: Props) {
{!shouldHide && ENABLE_CREATOR_REACTIONS && (canCreatorReact || creatorLiked) && (
<Button
disabled={!canCreatorReact || !claimIsMine}
requiresAuth={IS_WEB}
title={claimIsMine ? __('You loved this') : __('Creator loved this')}
icon={creatorLiked ? ICONS.CREATOR_LIKE : ICONS.SUBSCRIBE}
className={classnames('comment__action comment__action--creator-like')}
+9 -7
View File
@@ -1,10 +1,11 @@
import { connect } from 'react-redux';
import { doResolveUris } from 'redux/actions/claims';
import {
selectClaimForUri,
makeSelectClaimForUri,
makeSelectClaimIsMine,
selectClaimIsMine,
selectFetchingMyChannels,
selectMyChannelClaims,
selectMyClaimIdsRaw,
} from 'redux/selectors/claims';
import {
selectTopLevelCommentsForUri,
@@ -15,7 +16,7 @@ import {
makeSelectTotalCommentsCountForUri,
selectOthersReacts,
selectMyReacts,
makeSelectCommentIdsForUri,
selectCommentIdsForUri,
selectSettingsByChannelId,
selectPinnedCommentsForUri,
} from 'redux/selectors/comments';
@@ -24,6 +25,7 @@ import { selectActiveChannelClaim } from 'redux/selectors/app';
import CommentsList from './view';
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
const activeChannelClaim = selectActiveChannelClaim(state);
const topLevelComments = selectTopLevelCommentsForUri(state, props.uri);
@@ -35,13 +37,13 @@ const select = (state, props) => {
return {
topLevelComments,
resolvedComments,
myChannels: selectMyChannelClaims(state),
allCommentIds: makeSelectCommentIdsForUri(props.uri)(state),
myChannelIds: selectMyClaimIdsRaw(state),
allCommentIds: selectCommentIdsForUri(state, props.uri),
pinnedComments: selectPinnedCommentsForUri(state, props.uri),
topLevelTotalPages: makeSelectTopLevelTotalPagesForUri(props.uri)(state),
totalComments: makeSelectTotalCommentsCountForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
claim,
claimIsMine: selectClaimIsMine(state, claim),
isFetchingComments: selectIsFetchingComments(state),
isFetchingCommentsById: selectIsFetchingCommentsById(state),
isFetchingReacts: selectIsFetchingReacts(state),
+1 -2
View File
@@ -2,7 +2,6 @@ import { connect } from 'react-redux';
import { doResolveUris } from 'redux/actions/claims';
import { makeSelectClaimIsMine, selectMyChannelClaims, makeSelectClaimForUri } from 'redux/selectors/claims';
import { selectIsFetchingCommentsByParentId, selectRepliesForParentId } from 'redux/selectors/comments';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import CommentsReplies from './view';
const select = (state, props) => {
@@ -16,7 +15,7 @@ const select = (state, props) => {
fetchedReplies,
resolvedReplies,
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
userCanComment: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
userCanComment: true,
myChannels: selectMyChannelClaims(state),
isFetchingByParentId: selectIsFetchingCommentsByParentId(state),
};
+60 -50
View File
@@ -1,102 +1,112 @@
// @flow
import React from 'react';
import { formatCredits, formatFullPrice } from 'util/format-credits';
import classnames from 'classnames';
import LbcSymbol from 'component/common/lbc-symbol';
import { formatCredits, formatFullPrice } from 'util/format-credits';
import React from 'react';
type Props = {
amount: number,
amount?: number,
className?: string,
customAmounts?: { amountFiat: number, amountLBC: number },
fee?: boolean,
isEstimate?: boolean,
isFiat?: boolean,
noFormat?: boolean,
precision: number,
showFree: boolean,
showFullPrice: boolean,
showPlus: boolean,
isEstimate?: boolean,
showLBC?: boolean,
fee?: boolean,
className?: string,
noFormat?: boolean,
showPlus: boolean,
size?: number,
superChat?: boolean,
superChatLight?: boolean,
isFiat?: boolean,
};
class CreditAmount extends React.PureComponent<Props> {
static defaultProps = {
noFormat: false,
precision: 2,
showFree: false,
showFullPrice: false,
showPlus: false,
showLBC: true,
noFormat: false,
showPlus: false,
};
render() {
const {
amount,
precision,
showFullPrice,
showFree,
showPlus,
isEstimate,
fee,
showLBC,
className,
customAmounts,
fee,
isEstimate,
isFiat,
noFormat,
precision,
showFree,
showFullPrice,
showLBC,
showPlus,
size,
superChat,
superChatLight,
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;
if (amount === undefined && customAmounts === undefined) return null;
let formattedAmount;
if (showFullPrice) {
formattedAmount = fullPrice;
} else {
formattedAmount =
amount > 0 && amount < minimumRenderableAmount
? `<${minimumRenderableAmount}`
: formatCredits(amount, precision, true);
}
function getAmountText(amount: number, isFiat?: boolean) {
const fullPrice = formatFullPrice(amount, 2);
const isFree = parseFloat(amount) === 0;
let formattedAmount;
let amountText;
if (showFree && isFree) {
amountText = __('Free');
} else {
amountText = noFormat ? amount : formattedAmount;
if (showPlus && amount > 0) {
amountText = `+${amountText}`;
if (showFullPrice) {
formattedAmount = fullPrice;
} else {
formattedAmount =
amount > 0 && amount < minimumRenderableAmount
? `<${minimumRenderableAmount}`
: formatCredits(amount, precision, true);
}
if (showLBC && !isFiat) {
amountText = <LbcSymbol postfix={amountText} size={size} />;
} else if (showLBC && isFiat) {
amountText = <p style={{ display: 'inline' }}> ${(Math.round(Number(amountText) * 100) / 100).toFixed(2)}</p>;
}
if (showFree && isFree) {
return __('Free');
} else {
let amountText = noFormat ? amount : formattedAmount;
if (fee) {
amountText = __('%amount% fee', { amount: amountText });
if (showPlus && amount > 0) {
amountText = `+${amountText}`;
}
if (showLBC && !isFiat) {
amountText = <LbcSymbol postfix={amountText} size={size} />;
} else if (showLBC && isFiat) {
amountText = <p style={{ display: 'inline' }}> ${(Math.round(Number(amountText) * 100) / 100).toFixed(2)}</p>;
}
if (fee) {
amountText = __('%amount% fee', { amount: amountText });
}
return amountText;
}
}
return (
<span
title={fullPrice}
title={amount ? formatFullPrice(amount, 2) : ''}
className={classnames(className, {
'super-chat': superChat,
'super-chat--light': superChatLight,
})}
>
<span className="credit-amount">{amountText}</span>
{customAmounts
? Object.values(customAmounts).map((amount, index) => (
<span key={String(amount)} className="credit-amount">
{getAmountText(Number(amount), !index)}
</span>
))
: amount && <span className="credit-amount">{getAmountText(amount, isFiat)}</span>}
{isEstimate ? (
<span className="credit-amount__estimate" title={__('This is an estimate and does not include data fees')}>
+2 -2
View File
@@ -1,6 +1,6 @@
// @flow
import * as React from 'react';
import { remote } from 'electron';
import * as remote from '@electron/remote';
import Button from 'component/button';
import { FormField } from 'component/common/form';
@@ -47,7 +47,7 @@ class FileSelector extends React.PureComponent<Props> {
};
handleDirectoryInputSelection = () => {
remote.dialog.showOpenDialog({ properties: ['openDirectory'] }).then(result => {
remote.dialog.showOpenDialog({ properties: ['openDirectory'] }).then((result) => {
const path = result && result.filePaths[0];
if (path) {
// $FlowFixMe
+227 -254
View File
@@ -1,60 +1,53 @@
// @flow
import type { ElementRef, Node } from 'react';
import 'easymde/dist/easymde.min.css';
import { FF_MAX_CHARS_DEFAULT } from 'constants/form-field';
import { openEditorMenu, stopContextMenu } from 'util/context-menu';
import * as ICONS from 'constants/icons';
import Button from 'component/button';
import MarkdownPreview from 'component/common/markdown-preview';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import SimpleMDE from 'react-simplemde-editor';
import MarkdownPreview from 'component/common/markdown-preview';
import { openEditorMenu, stopContextMenu } from 'util/context-menu';
import { FF_MAX_CHARS_DEFAULT } from 'constants/form-field';
import 'easymde/dist/easymde.min.css';
import Button from 'component/button';
import emoji from 'emoji-dictionary';
const QUICK_EMOJIS = [
emoji.getUnicode('rocket'),
emoji.getUnicode('jeans'),
emoji.getUnicode('fire'),
emoji.getUnicode('heart'),
emoji.getUnicode('open_mouth'),
];
import TextareaWithSuggestions from 'component/textareaWithSuggestions';
import type { ElementRef, Node } from 'react';
type Props = {
name: string,
label?: string | Node,
render?: () => React$Node,
prefix?: string,
postfix?: string,
error?: string | boolean,
helper?: string | React$Node,
type?: string,
onChange?: (any) => any,
defaultValue?: string | number,
placeholder?: string | number,
children?: React$Node,
stretch?: boolean,
affixClass?: string, // class applied to prefix/postfix label
autoFocus?: boolean,
labelOnLeft: boolean,
inputButton?: React$Node,
blockWrap: boolean,
charCount?: number,
textAreaMaxLength?: number,
range?: number,
min?: number,
max?: number,
quickActionLabel?: string,
quickActionHandler?: (any) => any,
children?: React$Node,
defaultValue?: string | number,
disabled?: boolean,
onChange: (any) => void,
value?: string | number,
error?: string | boolean,
helper?: string | React$Node,
hideSuggestions?: boolean,
inputButton?: React$Node,
isLivestream?: boolean,
label?: string | Node,
labelOnLeft: boolean,
max?: number,
min?: number,
name: string,
noEmojis?: boolean,
placeholder?: string | number,
postfix?: string,
prefix?: string,
quickActionLabel?: string,
range?: number,
readOnly?: boolean,
stretch?: boolean,
textAreaMaxLength?: number,
type?: string,
value?: string | number,
onChange?: (any) => any,
openEmoteMenu?: () => void,
quickActionHandler?: (any) => any,
render?: () => React$Node,
};
export class FormField extends React.PureComponent<Props> {
static defaultProps = {
labelOnLeft: false,
blockWrap: true,
};
static defaultProps = { labelOnLeft: false, blockWrap: true };
input: { current: ElementRef<any> };
@@ -67,36 +60,48 @@ export class FormField extends React.PureComponent<Props> {
const { autoFocus } = this.props;
const input = this.input.current;
if (input && autoFocus) {
input.focus();
}
if (input && autoFocus) input.focus();
}
render() {
const {
render,
label,
prefix,
postfix,
error,
helper,
name,
type,
children,
stretch,
affixClass,
autoFocus,
inputButton,
labelOnLeft,
blockWrap,
charCount,
textAreaMaxLength,
quickActionLabel,
quickActionHandler,
children,
error,
helper,
hideSuggestions,
inputButton,
isLivestream,
label,
labelOnLeft,
name,
noEmojis,
postfix,
prefix,
quickActionLabel,
stretch,
textAreaMaxLength,
type,
openEmoteMenu,
quickActionHandler,
render,
...inputProps
} = this.props;
const errorMessage = typeof error === 'object' ? error.message : error;
// Ideally, the character count should (and can) be appended to the
// SimpleMDE's "options::status" bar. However, I couldn't figure out how
// to pass the current value to it's callback, nor query the current
// text length from the callback. So, we'll use our own widget.
const hasCharCount = charCount !== undefined && charCount >= 0;
const countInfo = hasCharCount && textAreaMaxLength !== undefined && (
<span className="comment__char-count-mde">{`${charCount || '0'}/${textAreaMaxLength}`}</span>
);
const Wrapper = blockWrap
? ({ children: innerChildren }) => <fieldset-section class="radio">{innerChildren}</fieldset-section>
: ({ children: innerChildren }) => <span className="radio">{innerChildren}</span>;
@@ -108,207 +113,177 @@ export class FormField extends React.PureComponent<Props> {
</div>
) : null;
let input;
if (type) {
if (type === 'radio') {
input = (
<Wrapper>
<input id={name} type="radio" {...inputProps} />
<label htmlFor={name}>{label}</label>
</Wrapper>
);
} else if (type === 'checkbox') {
input = (
<div className="checkbox">
<input id={name} type="checkbox" {...inputProps} />
<label htmlFor={name}>{label}</label>
</div>
);
} else if (type === 'range') {
input = (
<div>
<input id={name} type="range" {...inputProps} />
<label htmlFor={name}>{label}</label>
</div>
);
} else if (type === 'select') {
input = (
<fieldset-section>
{(label || errorMessage) && (
<label htmlFor={name}>{errorMessage ? <span className="error__text">{errorMessage}</span> : label}</label>
)}
<select id={name} {...inputProps}>
{children}
</select>
</fieldset-section>
);
} else if (type === 'select-tiny') {
input = (
<fieldset-section class="select--slim">
{(label || errorMessage) && (
<label htmlFor={name}>{errorMessage ? <span className="error__text">{errorMessage}</span> : label}</label>
)}
<select id={name} {...inputProps}>
{children}
</select>
</fieldset-section>
);
} else if (type === 'markdown') {
const handleEvents = {
contextmenu: openEditorMenu,
};
const inputSimple = (type: string) => (
<>
<input id={name} type={type} {...inputProps} />
<label htmlFor={name}>{label}</label>
</>
);
const getInstance = (editor) => {
// SimpleMDE max char check
editor.codemirror.on('beforeChange', (instance, changes) => {
if (textAreaMaxLength && changes.update) {
var str = changes.text.join('\n');
var delta = str.length - (instance.indexFromPos(changes.to) - instance.indexFromPos(changes.from));
if (delta <= 0) {
return;
}
delta = instance.getValue().length + delta - textAreaMaxLength;
if (delta > 0) {
str = str.substr(0, str.length - delta);
changes.update(changes.from, changes.to, str.split('\n'));
}
}
});
const inputSelect = (selectClass: string) => (
<fieldset-section class={selectClass}>
{(label || errorMessage) && (
<label htmlFor={name}>{errorMessage ? <span className="error__text">{errorMessage}</span> : label}</label>
)}
<select id={name} {...inputProps}>
{children}
</select>
</fieldset-section>
);
// "Create Link (Ctrl-K)": highlight URL instead of label:
editor.codemirror.on('changes', (instance, changes) => {
try {
// Grab the last change from the buffered list. I assume the
// buffered one ('changes', instead of 'change') is more efficient,
// and that "Create Link" will always end up last in the list.
const lastChange = changes[changes.length - 1];
if (lastChange.origin === '+input') {
// https://github.com/Ionaru/easy-markdown-editor/blob/8fa54c496f98621d5f45f57577ce630bee8c41ee/src/js/easymde.js#L765
const EASYMDE_URL_PLACEHOLDER = '(https://)';
const input = () => {
switch (type) {
case 'radio':
return <Wrapper>{inputSimple('radio')}</Wrapper>;
case 'checkbox':
return <div className="checkbox">{inputSimple('checkbox')}</div>;
case 'range':
return <div>{inputSimple('range')}</div>;
case 'select':
return inputSelect('');
case 'select-tiny':
return inputSelect('select--slim');
case 'markdown':
const handleEvents = { contextmenu: openEditorMenu };
// The URL placeholder is always placed last, so just look at the
// last text in the array to also cover the multi-line case:
const urlLineText = lastChange.text[lastChange.text.length - 1];
const getInstance = (editor) => {
// SimpleMDE max char check
editor.codemirror.on('beforeChange', (instance, changes) => {
if (textAreaMaxLength && changes.update) {
var str = changes.text.join('\n');
var delta = str.length - (instance.indexFromPos(changes.to) - instance.indexFromPos(changes.from));
if (urlLineText.endsWith(EASYMDE_URL_PLACEHOLDER) && urlLineText !== '[]' + EASYMDE_URL_PLACEHOLDER) {
const from = lastChange.from;
const to = lastChange.to;
const isSelectionMultiline = lastChange.text.length > 1;
const baseIndex = isSelectionMultiline ? 0 : from.ch;
if (delta <= 0) return;
// Everything works fine for the [Ctrl-K] case, but for the
// [Button] case, this handler happens before the original
// code, thus our change got wiped out.
// Add a small delay to handle that case.
setTimeout(() => {
instance.setSelection(
{ line: to.line, ch: baseIndex + urlLineText.lastIndexOf('(') + 1 },
{ line: to.line, ch: baseIndex + urlLineText.lastIndexOf(')') }
);
}, 25);
delta = instance.getValue().length + delta - textAreaMaxLength;
if (delta > 0) {
str = str.substr(0, str.length - delta);
changes.update(changes.from, changes.to, str.split('\n'));
}
}
} catch (err) {
// Do nothing (revert to original behavior)
}
});
};
});
// Ideally, the character count should (and can) be appended to the
// SimpleMDE's "options::status" bar. However, I couldn't figure out how
// to pass the current value to it's callback, nor query the current
// text length from the callback. So, we'll use our own widget.
const hasCharCount = charCount !== undefined && charCount >= 0;
const countInfo = hasCharCount && textAreaMaxLength !== undefined && (
<span className="comment__char-count-mde">{`${charCount || '0'}/${textAreaMaxLength}`}</span>
);
// "Create Link (Ctrl-K)": highlight URL instead of label:
editor.codemirror.on('changes', (instance, changes) => {
try {
// Grab the last change from the buffered list. I assume the
// buffered one ('changes', instead of 'change') is more efficient,
// and that "Create Link" will always end up last in the list.
const lastChange = changes[changes.length - 1];
if (lastChange.origin === '+input') {
// https://github.com/Ionaru/easy-markdown-editor/blob/8fa54c496f98621d5f45f57577ce630bee8c41ee/src/js/easymde.js#L765
const EASYMDE_URL_PLACEHOLDER = '(https://)';
input = (
<div className="form-field--SimpleMDE" onContextMenu={stopContextMenu}>
// The URL placeholder is always placed last, so just look at the
// last text in the array to also cover the multi-line case:
const urlLineText = lastChange.text[lastChange.text.length - 1];
if (urlLineText.endsWith(EASYMDE_URL_PLACEHOLDER) && urlLineText !== '[]' + EASYMDE_URL_PLACEHOLDER) {
const from = lastChange.from;
const to = lastChange.to;
const isSelectionMultiline = lastChange.text.length > 1;
const baseIndex = isSelectionMultiline ? 0 : from.ch;
// Everything works fine for the [Ctrl-K] case, but for the
// [Button] case, this handler happens before the original
// code, thus our change got wiped out.
// Add a small delay to handle that case.
setTimeout(() => {
instance.setSelection(
{ line: to.line, ch: baseIndex + urlLineText.lastIndexOf('(') + 1 },
{ line: to.line, ch: baseIndex + urlLineText.lastIndexOf(')') }
);
}, 25);
}
}
} catch (e) {} // Do nothing (revert to original behavior)
});
};
return (
<div className="form-field--SimpleMDE" onContextMenu={stopContextMenu}>
<fieldset-section>
<div className="form-field__two-column">
<div>
<label htmlFor={name}>{label}</label>
</div>
{quickAction}
</div>
<SimpleMDE
{...inputProps}
id={name}
type="textarea"
events={handleEvents}
getMdeInstance={getInstance}
options={{
spellChecker: true,
hideIcons: ['heading', 'image', 'fullscreen', 'side-by-side'],
previewRender(plainText) {
const preview = <MarkdownPreview content={plainText} noDataStore />;
return ReactDOMServer.renderToString(preview);
},
}}
/>
{countInfo}
</fieldset-section>
</div>
);
case 'textarea':
return (
<fieldset-section>
<div className="form-field__two-column">
<div>
{(label || quickAction) && (
<div className="form-field__two-column">
<label htmlFor={name}>{label}</label>
</div>
{quickAction}
</div>
<SimpleMDE
{...inputProps}
id={name}
type="textarea"
events={handleEvents}
getMdeInstance={getInstance}
options={{
spellChecker: true,
hideIcons: ['heading', 'image', 'fullscreen', 'side-by-side'],
previewRender(plainText) {
const preview = <MarkdownPreview content={plainText} noDataStore />;
return ReactDOMServer.renderToString(preview);
},
}}
/>
{countInfo}
</fieldset-section>
</div>
);
} else if (type === 'textarea') {
const hasCharCount = charCount !== undefined && charCount >= 0;
const countInfo = hasCharCount && textAreaMaxLength !== undefined && (
<span className="comment__char-count">{`${charCount || '0'}/${textAreaMaxLength}`}</span>
);
input = (
<fieldset-section>
{(label || quickAction) && (
<div className="form-field__two-column">
<div>
<label htmlFor={name}>{label}</label>
</div>
{quickAction}
</div>
)}
<textarea
type={type}
id={name}
maxLength={textAreaMaxLength || FF_MAX_CHARS_DEFAULT}
ref={this.input}
{...inputProps}
/>
<div className="form-field__textarea-info">
{!noEmojis && (
<div className="form-field__quick-emojis">
{QUICK_EMOJIS.map((emoji) => (
<Button
key={emoji}
disabled={inputProps.disabled}
type="button"
className="button--emoji"
label={emoji}
onClick={() => {
inputProps.onChange({
target: { value: inputProps.value ? `${inputProps.value} ${emoji}` : emoji },
});
}}
/>
))}
{quickAction}
</div>
)}
{countInfo}
</div>
</fieldset-section>
);
} else {
const inputElement = <input type={type} id={name} {...inputProps} ref={this.input} />;
const inner = inputButton ? (
<input-submit>
{inputElement}
{inputButton}
</input-submit>
) : (
inputElement
);
input = (
<React.Fragment>
{hideSuggestions ? (
<textarea
type={type}
id={name}
maxLength={textAreaMaxLength || FF_MAX_CHARS_DEFAULT}
ref={this.input}
{...inputProps}
/>
) : (
<TextareaWithSuggestions
type={type}
id={name}
maxLength={textAreaMaxLength || FF_MAX_CHARS_DEFAULT}
inputRef={this.input}
isLivestream={isLivestream}
{...inputProps}
/>
)}
<div className="form-field__textarea-info">
{!noEmojis && openEmoteMenu && (
<Button
type="alt"
className="button--file-action"
title="Emotes"
onClick={openEmoteMenu}
icon={ICONS.EMOJI}
iconSize={20}
/>
)}
{countInfo}
</div>
</fieldset-section>
);
default:
const inputElement = <input type={type} id={name} {...inputProps} ref={this.input} />;
const inner = inputButton ? (
<input-submit>
{inputElement}
{inputButton}
</input-submit>
) : (
inputElement
);
return (
<fieldset-section>
{(label || errorMessage) && (
<label htmlFor={name}>
@@ -318,17 +293,15 @@ export class FormField extends React.PureComponent<Props> {
{prefix && <label htmlFor={name}>{prefix}</label>}
{inner}
</fieldset-section>
</React.Fragment>
);
);
}
}
};
return (
<React.Fragment>
{input}
<>
{type && input()}
{helper && <div className="form-field__help">{helper}</div>}
</React.Fragment>
</>
);
}
}
+1 -3
View File
@@ -19,9 +19,7 @@ export default function HiddenNsfw(props: Props) {
<I18nMessage
tokens={{
type,
settings: (
<Button button="link" label={__('settings')} navigate={`/$/${PAGES.SETTINGS}`} requiresAuth={IS_WEB} />
),
settings: <Button button="link" label={__('settings')} navigate={`/$/${PAGES.SETTINGS}`} />,
}}
>
Content may be hidden on this %type% because of your %settings%.
+18
View File
@@ -2014,4 +2014,22 @@ export const icons = {
<line x1="19" y1="20.5" x2="20" y2="20.5" />
</g>
),
[ICONS.EMOJI]: buildIcon(
<g>
<circle cx="12" cy="12" r="10" />
<path d="M8 14s1.5 2 4 2 4-2 4-2" />
<line x1="9" y1="9" x2="9.01" y2="9" />
<line x1="15" y1="9" x2="15.01" y2="9" />
</g>
),
[ICONS.STICKER]: buildIcon(
<g>
<path d="M7.13,9a.38.38,0,1,1-.38.38A.38.38,0,0,1,7.13,9" />
<path d="M5.51,15.42A7.34,7.34,0,0,0,12,19.34a7.83,7.83,0,0,0,.92-.06" />
<path d="M23.24,11.52A11.25,11.25,0,1,0,12,23.25h.5" />
<path d="M14.45,9.66a2.31,2.31,0,0,1,3.91,0" />
<line x1="23.24" y1="11.52" x2="12.5" y2="23.24" />
<path d="M12.5,23.24v-1A10.74,10.74,0,0,1,23.24,11.52" />
</g>
),
};
+67 -20
View File
@@ -10,12 +10,21 @@ import remarkFrontMatter from 'remark-frontmatter';
import reactRenderer from 'remark-react';
import MarkdownLink from 'component/markdownLink';
import defaultSchema from 'hast-util-sanitize/lib/github.json';
import { formatedLinks, inlineLinks } from 'util/remark-lbry';
import { formattedLinks, inlineLinks } from 'util/remark-lbry';
import { formattedTimestamp, inlineTimestamp } from 'util/remark-timestamp';
import { formattedEmote, inlineEmote } from 'util/remark-emote';
import ZoomableImage from 'component/zoomableImage';
import { CHANNEL_STAKED_LEVEL_VIDEO_COMMENTS } from 'config';
import Button from 'component/button';
import * as ICONS from 'constants/icons';
import { parse } from 'node-html-parser';
import OptimizedImage from 'component/optimizedImage';
const RE_EMOTE = /:\+1:|:-1:|:[\w-]+:/;
function isEmote(title, src) {
return title && RE_EMOTE.test(title) && src.includes('static.odycdn.com/emoticons');
}
type SimpleTextProps = {
children?: React.Node,
@@ -42,6 +51,7 @@ type MarkdownProps = {
className?: string,
parentCommentId?: string,
isMarkdownPost?: boolean,
disableTimestamps?: boolean,
stakedLevel?: number,
};
@@ -93,10 +103,15 @@ const SimpleLink = (props: SimpleLinkProps) => {
const SimpleImageLink = (props: ImageLinkProps) => {
const { src, title, alt, helpText } = props;
if (!src) {
return null;
}
if (isEmote(title, src)) {
return <OptimizedImage src={src} title={title} className="emote" waitLoad loading="lazy" />;
}
return (
<Button
button="link"
@@ -132,26 +147,41 @@ function isStakeEnoughForPreview(stakedLevel) {
// ****************************************************************************
const MarkdownPreview = (props: MarkdownProps) => {
const { content, strip, simpleLinks, noDataStore, className, parentCommentId, isMarkdownPost, stakedLevel } = props;
const {
content,
strip,
simpleLinks,
noDataStore,
className,
parentCommentId,
isMarkdownPost,
disableTimestamps,
stakedLevel,
} = props;
const strippedContent = content
? content.replace(REPLACE_REGEX, (iframeHtml, y, iframeSrc) => {
? content.replace(REPLACE_REGEX, (iframeHtml) => {
// Let the browser try to create an iframe to see if the markup is valid
const outer = document.createElement('div');
outer.innerHTML = iframeHtml;
const iframe = ((outer.querySelector('iframe'): any): ?HTMLIFrameElement);
let lbrySrc;
try {
let p = parse(iframeHtml);
const tag = p.getElementsByTagName('iframe');
const s = tag[0];
lbrySrc = s && s.getAttribute('src');
} catch (e) {}
if (iframe) {
const src = iframe.src;
if (src && src.startsWith('lbry://')) {
return src;
}
if (lbrySrc && lbrySrc.startsWith('lbry://')) {
return lbrySrc;
}
return iframeHtml;
})
: '';
const initialQuote = strippedContent.split(' ').find((word) => word.length > 0 || word.charAt(0) === '>');
let stripQuote;
if (initialQuote && initialQuote.charAt(0) === '>') stripQuote = true;
const remarkOptions: Object = {
sanitize: schema,
fragment: React.Fragment,
@@ -169,9 +199,12 @@ const MarkdownPreview = (props: MarkdownProps) => {
),
// Workaraund of remarkOptions.Fragment
div: React.Fragment,
img: isStakeEnoughForPreview(stakedLevel)
? ZoomableImage
: (imgProps) => <SimpleImageLink src={imgProps.src} alt={imgProps.alt} title={imgProps.title} />,
img: (imgProps) =>
isStakeEnoughForPreview(stakedLevel) && !isEmote(imgProps.title, imgProps.src) ? (
ZoomableImage
) : (
<SimpleImageLink src={imgProps.src} alt={imgProps.alt} title={imgProps.title} />
),
},
};
@@ -183,10 +216,22 @@ const MarkdownPreview = (props: MarkdownProps) => {
};
// Strip all content and just render text
if (strip) {
if (strip || stripQuote) {
// Remove new lines and extra space
remarkOptions.remarkReactComponents.p = SimpleText;
return (
return stripQuote ? (
<span dir="auto" className="markdown-preview">
<blockquote>
{
remark()
.use(remarkStrip)
.use(remarkFrontMatter, ['yaml'])
.use(reactRenderer, remarkOptions)
.processSync(content).contents
}
</blockquote>
</span>
) : (
<span dir="auto" className="markdown-preview">
{
remark()
@@ -206,11 +251,13 @@ const MarkdownPreview = (props: MarkdownProps) => {
.use(remarkAttr, remarkAttrOpts)
// Remark plugins for lbry urls
// Note: The order is important
.use(formatedLinks)
.use(formattedLinks)
.use(inlineLinks)
.use(isMarkdownPost ? null : inlineTimestamp)
.use(isMarkdownPost ? null : formattedTimestamp)
.use(disableTimestamps || isMarkdownPost ? null : inlineTimestamp)
.use(disableTimestamps || isMarkdownPost ? null : formattedTimestamp)
// Emojis
.use(inlineEmote)
.use(formattedEmote)
.use(remarkEmoji)
// Render new lines without needing spaces.
.use(remarkBreaks)
+4 -4
View File
@@ -1,8 +1,8 @@
import { connect } from 'react-redux';
import { makeSelectThumbnailForUri, makeSelectClaimForUri } from 'redux/selectors/claims';
import { selectThumbnailForUri, makeSelectClaimForUri } from 'redux/selectors/claims';
import { doResolveUri } from 'redux/actions/claims';
import * as SETTINGS from 'constants/settings';
import { doFetchCostInfoForUri, makeSelectCostInfoForUri } from 'lbryinc';
import { doFetchCostInfoForUri, selectCostInfoForUri } from 'lbryinc';
import { doPlayUri, doSetPlayingUri } from 'redux/actions/content';
import { doAnaltyicsPurchaseEvent } from 'redux/actions/app';
import { makeSelectClientSetting } from 'redux/selectors/settings';
@@ -11,10 +11,10 @@ import { makeSelectFileRenderModeForUri } from 'redux/selectors/content';
import ChannelThumbnail from './view';
const select = (state, props) => ({
thumbnail: makeSelectThumbnailForUri(props.uri)(state),
thumbnail: selectThumbnailForUri(state, props.uri),
claim: makeSelectClaimForUri(props.uri)(state),
floatingPlayerEnabled: makeSelectClientSetting(SETTINGS.FLOATING_PLAYER)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
costInfo: selectCostInfoForUri(state, props.uri),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
});
+2 -2
View File
@@ -61,9 +61,9 @@ class ErrorBoundary extends React.Component<Props, State> {
render() {
const { hasError } = this.state;
const { sentryEventId, desktopErrorReported } = this.state;
const { desktopErrorReported } = this.state;
const errorWasReported = IS_WEB ? sentryEventId !== null : desktopErrorReported;
const errorWasReported = desktopErrorReported;
if (hasError) {
return (
+15 -18
View File
@@ -1,14 +1,8 @@
import { connect } from 'react-redux';
import {
makeSelectClaimIsMine,
makeSelectClaimForUri,
selectMyChannelClaims,
makeSelectTagInClaimOrChannelForUri,
} from 'redux/selectors/claims';
import { selectClaimIsMine, selectClaimForUri, selectHasChannels } from 'redux/selectors/claims';
import { makeSelectStreamingUrlForUri, makeSelectFileInfoForUri } from 'redux/selectors/file_info';
import { doPrepareEdit } from 'redux/actions/publish';
import { DISABLE_COMMENTS_TAG } from 'constants/tags';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { selectCostInfoForUri } from 'lbryinc';
import { doSetPlayingUri, doPlayUri } from 'redux/actions/content';
import { doToast } from 'redux/actions/notifications';
import { doOpenModal, doSetActiveChannel, doSetIncognito, doAnalyticsView } from 'redux/actions/app';
@@ -16,16 +10,19 @@ import fs from 'fs';
import FileActions from './view';
import { makeSelectFileRenderModeForUri } from 'redux/selectors/content';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
myChannels: selectMyChannelClaims(state),
reactionsDisabled: makeSelectTagInClaimOrChannelForUri(props.uri, DISABLE_COMMENTS_TAG)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
claim,
claimIsMine: selectClaimIsMine(state, claim),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
costInfo: selectCostInfoForUri(state, props.uri),
hasChannels: selectHasChannels(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
};
};
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
+7 -35
View File
@@ -1,5 +1,5 @@
// @flow
import { SITE_NAME, ENABLE_FILE_REACTIONS } from 'config';
import { ENABLE_FILE_REACTIONS } from 'config';
import * as PAGES from 'constants/pages';
import * as MODALS from 'constants/modal_types';
import * as ICONS from 'constants/icons';
@@ -16,6 +16,7 @@ import { useHistory } from 'react-router';
import FileReactions from 'component/fileReactions';
import { Menu, MenuButton, MenuList, MenuItem } from '@reach/menu-button';
import Icon from 'component/common/icon';
import ClaimRepostButton from 'component/claimRepostButton';
type Props = {
uri: string,
@@ -26,11 +27,8 @@ type Props = {
fileInfo: FileListItem,
costInfo: ?{ cost: number },
renderMode: string,
myChannels: ?Array<ChannelClaim>,
doToast: ({ message: string }) => void,
clearPlayingUri: () => void,
hasChannels: boolean,
hideRepost?: boolean,
reactionsDisabled: boolean,
download: (string) => void,
streamingUrl: ?string,
};
@@ -45,20 +43,16 @@ function FileActions(props: Props) {
costInfo,
renderMode,
prepareEdit,
myChannels,
clearPlayingUri,
doToast,
hasChannels,
hideRepost,
reactionsDisabled,
} = props;
const {
push,
location: { pathname, search },
location: { search },
} = useHistory();
const isMobile = useIsMobile();
const webShareable = costInfo && costInfo.cost === 0 && RENDER_MODES.WEB_SHAREABLE_MODES.includes(renderMode);
const showDelete = claimIsMine || (fileInfo && (fileInfo.written_bytes > 0 || fileInfo.blobs_completed > 0));
const hasChannels = myChannels && myChannels.length > 0;
const claimId = claim && claim.claim_id;
const { signing_channel: signingChannel } = claim;
const channelName = signingChannel && signingChannel.name;
@@ -82,34 +76,12 @@ function FileActions(props: Props) {
const urlParams = new URLSearchParams(search);
const collectionId = urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID);
function handleRepostClick() {
if (!hasChannels) {
clearPlayingUri();
push(`/$/${PAGES.CHANNEL_NEW}?redirect=${pathname}`);
doToast({ message: __('A channel is required to repost on %SITE_NAME%', { SITE_NAME }) });
} else {
push(`/$/${PAGES.REPOST_NEW}?from=${encodeURIComponent(uri)}&redirect=${pathname}`);
}
}
const lhsSection = (
<>
{ENABLE_FILE_REACTIONS && !reactionsDisabled && <FileReactions uri={uri} />}
{ENABLE_FILE_REACTIONS && <FileReactions uri={uri} />}
<ClaimSupportButton uri={uri} fileAction />
<ClaimCollectionAddButton uri={uri} fileAction />
{!hideRepost && (
<Button
button="alt"
className="button--file-action"
icon={ICONS.REPOST}
label={
claim.meta.reposted > 1 ? __(`%repost_total% Reposts`, { repost_total: claim.meta.reposted }) : __('Repost')
}
description={__('Repost')}
requiresAuth={IS_WEB}
onClick={handleRepostClick}
/>
)}
{!hideRepost && <ClaimRepostButton uri={uri} claim={claim} hasChannels={hasChannels} />}
<Button
className="button--file-action"
icon={ICONS.SHARE}
+14 -10
View File
@@ -1,23 +1,27 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
selectClaimForUri,
makeSelectMetadataForUri,
selectClaimIsMine,
makeSelectTagsForUri,
makeSelectClaimIsMine,
} from 'redux/selectors/claims';
import { makeSelectPendingAmountByUri } from 'redux/selectors/wallet';
import { doOpenModal } from 'redux/actions/app';
import { selectUser } from 'redux/selectors/user';
import FileDescription from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
metadata: makeSelectMetadataForUri(props.uri)(state),
user: selectUser(state),
tags: makeSelectTagsForUri(props.uri)(state),
pendingAmount: makeSelectPendingAmountByUri(props.uri)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
claim,
claimIsMine: selectClaimIsMine(state, claim),
metadata: makeSelectMetadataForUri(props.uri)(state),
user: selectUser(state),
pendingAmount: makeSelectPendingAmountByUri(props.uri)(state),
tags: makeSelectTagsForUri(props.uri)(state),
};
};
export default connect(select, {
doOpenModal,
+16 -12
View File
@@ -1,26 +1,30 @@
import { connect } from 'react-redux';
import { makeSelectClaimIsMine, makeSelectClaimForUri, makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import { selectClaimIsMine, selectClaimForUri, makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import {
makeSelectFileInfoForUri,
makeSelectDownloadingForUri,
makeSelectLoadingForUri,
makeSelectStreamingUrlForUri,
} from 'redux/selectors/file_info';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { selectCostInfoForUri } from 'lbryinc';
import { doOpenModal, doAnalyticsView } from 'redux/actions/app';
import { doSetPlayingUri, doPlayUri } from 'redux/actions/content';
import FileDownloadLink from './view';
const select = (state, props) => ({
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
downloading: makeSelectDownloadingForUri(props.uri)(state),
loading: makeSelectLoadingForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
downloading: makeSelectDownloadingForUri(props.uri)(state),
loading: makeSelectLoadingForUri(props.uri)(state),
claimIsMine: selectClaimIsMine(state, claim),
claim,
costInfo: selectCostInfoForUri(state, props.uri),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
};
};
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
+13 -13
View File
@@ -1,18 +1,18 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectClaimWasPurchased, makeSelectClaimIsMine } from 'redux/selectors/claims';
import { makeSelectCostInfoForUri, doFetchCostInfoForUri, makeSelectFetchingCostInfoForUri } from 'lbryinc';
import { selectClaimForUri, makeSelectClaimWasPurchased, selectClaimIsMine } from 'redux/selectors/claims';
import { selectCostInfoForUri, doFetchCostInfoForUri, selectFetchingCostInfoForUri } from 'lbryinc';
import FilePrice from './view';
const select = (state, props) => ({
costInfo: makeSelectCostInfoForUri(props.uri)(state),
fetching: makeSelectFetchingCostInfoForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
const perform = (dispatch) => ({
fetchCostInfo: (uri) => dispatch(doFetchCostInfoForUri(uri)),
});
return {
claim,
claimIsMine: selectClaimIsMine(state, claim),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
costInfo: selectCostInfoForUri(state, props.uri),
fetching: selectFetchingCostInfoForUri(state, props.uri),
};
};
export default connect(select, perform)(FilePrice);
export default connect(select, { doFetchCostInfoForUri })(FilePrice);
+40 -33
View File
@@ -1,30 +1,30 @@
// @flow
import 'scss/component/_file-price.scss';
import * as ICONS from 'constants/icons';
import React from 'react';
import classnames from 'classnames';
import CreditAmount from 'component/common/credit-amount';
import Icon from 'component/common/icon';
import React from 'react';
type Props = {
showFullPrice: boolean,
costInfo: ?{ includesData: boolean, cost: number },
fetchCostInfo: string => void,
uri: string,
fetching: boolean,
claim: ?{},
claimWasPurchased: boolean,
claimIsMine: boolean,
claimWasPurchased: boolean,
costInfo: ?{ includesData: boolean, cost: number },
fetching: boolean,
showFullPrice: boolean,
type?: string,
uri: string,
// below props are just passed to <CreditAmount />
inheritStyle?: boolean,
showLBC?: boolean,
customPrices?: { priceFiat: number, priceLBC: number },
hideFree?: boolean, // hide the file price if it's free
isFiat?: boolean,
showLBC?: boolean,
doFetchCostInfoForUri: (string) => void,
};
class FilePrice extends React.PureComponent<Props> {
static defaultProps = {
showFullPrice: false,
};
static defaultProps = { showFullPrice: false };
componentDidMount() {
this.fetchCost(this.props);
@@ -35,40 +35,47 @@ class FilePrice extends React.PureComponent<Props> {
}
fetchCost = (props: Props) => {
const { costInfo, fetchCostInfo, uri, fetching, claim } = props;
const { costInfo, doFetchCostInfoForUri, uri, fetching, claim } = props;
if (costInfo === undefined && !fetching && claim) {
fetchCostInfo(uri);
}
if (uri && costInfo === undefined && !fetching && claim) doFetchCostInfoForUri(uri);
};
render() {
const { costInfo, showFullPrice, showLBC, hideFree, claimWasPurchased, type, claimIsMine } = this.props;
const {
costInfo,
showFullPrice,
showLBC,
isFiat, // this goes
hideFree,
claimWasPurchased,
type,
claimIsMine,
customPrices,
} = this.props;
if (claimIsMine || !costInfo || !costInfo.cost || (!costInfo.cost && hideFree)) {
return null;
}
if (!customPrices && (claimIsMine || !costInfo || !costInfo.cost || (!costInfo.cost && hideFree))) return null;
const className = classnames(claimWasPurchased ? 'filePrice__key' : 'filePrice', {
'filePrice--filepage': type === 'filepage',
'filePrice--modal': type === 'modal',
});
return claimWasPurchased ? (
<span
className={classnames('file-price__key', {
'file-price__key--filepage': type === 'filepage',
'file-price__key--modal': type === 'modal',
})}
>
<span className={className}>
<Icon icon={ICONS.PURCHASED} size={type === 'filepage' ? 22 : undefined} />
</span>
) : (
<CreditAmount
className={classnames('file-price', {
'file-price--filepage': type === 'filepage',
'file-price--modal': type === 'modal',
})}
amount={costInfo ? costInfo.cost : undefined}
customAmounts={
customPrices ? { amountFiat: customPrices.priceFiat, amountLBC: customPrices.priceLBC } : undefined
}
className={className}
isEstimate={!!costInfo && !costInfo.includesData}
isFiat={isFiat} // this goes
showFree
showLBC={showLBC}
amount={costInfo.cost}
isEstimate={!costInfo.includesData}
showFullPrice={showFullPrice}
showLBC={showLBC}
/>
);
}
-1
View File
@@ -82,7 +82,6 @@ function FileReactions(props: Props) {
onClick={() => doReactionLike(uri)}
/>
<Button
requiresAuth={IS_WEB}
authSrc={'filereaction_dislike'}
title={__('I dislike this')}
className={classnames('button--file-action', {
+2 -2
View File
@@ -1,6 +1,6 @@
import { connect } from 'react-redux';
import { makeSelectDownloadPathForUri, makeSelectStreamingUrlForUri } from 'redux/selectors/file_info';
import { makeSelectClaimForUri, makeSelectThumbnailForUri, makeSelectContentTypeForUri } from 'redux/selectors/claims';
import { makeSelectClaimForUri, selectThumbnailForUri, makeSelectContentTypeForUri } from 'redux/selectors/claims';
import * as SETTINGS from 'constants/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { makeSelectFileRenderModeForUri, makeSelectFileExtensionForUri } from 'redux/selectors/content';
@@ -11,7 +11,7 @@ const select = (state, props) => {
return {
currentTheme: makeSelectClientSetting(SETTINGS.THEME)(state),
claim: makeSelectClaimForUri(props.uri)(state),
thumbnail: makeSelectThumbnailForUri(props.uri)(state),
thumbnail: selectThumbnailForUri(state, props.uri),
contentType: makeSelectContentTypeForUri(props.uri)(state),
downloadPath: makeSelectDownloadPathForUri(props.uri)(state),
fileExtension: makeSelectFileExtensionForUri(props.uri)(state),
+1 -1
View File
@@ -1,5 +1,5 @@
// @flow
import { remote } from 'electron';
import * as remote from '@electron/remote';
import React from 'react';
import classnames from 'classnames';
import * as RENDER_MODES from 'constants/file_render_modes';
+4 -4
View File
@@ -1,5 +1,5 @@
import { connect } from 'react-redux';
import { makeSelectTitleForUri, makeSelectClaimIsNsfw, makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import { selectTitleForUri, makeSelectClaimIsNsfw, makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import { makeSelectFileInfoForUri, makeSelectStreamingUrlForUri } from 'redux/selectors/file_info';
import {
makeSelectNextUrlForCollectionAndUrl,
@@ -13,7 +13,7 @@ import {
makeSelectFileRenderModeForUri,
} from 'redux/selectors/content';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { selectCostInfoForUri } from 'lbryinc';
import { doPlayUri, doSetPlayingUri } from 'redux/actions/content';
import { doFetchRecommendedContent } from 'redux/actions/search';
import { doAnaltyicsPurchaseEvent } from 'redux/actions/app';
@@ -30,7 +30,7 @@ const select = (state, props) => {
uri,
primaryUri,
playingUri,
title: makeSelectTitleForUri(uri)(state),
title: selectTitleForUri(state, uri),
fileInfo: makeSelectFileInfoForUri(uri)(state),
mature: makeSelectClaimIsNsfw(uri)(state),
isFloating: makeSelectIsPlayerFloating(props.location)(state),
@@ -38,7 +38,7 @@ const select = (state, props) => {
floatingPlayerEnabled: makeSelectClientSetting(SETTINGS.FLOATING_PLAYER)(state),
renderMode: makeSelectFileRenderModeForUri(uri)(state),
videoTheaterMode: makeSelectClientSetting(SETTINGS.VIDEO_THEATER_MODE)(state),
costInfo: makeSelectCostInfoForUri(uri)(state),
costInfo: selectCostInfoForUri(state, uri),
claimWasPurchased: makeSelectClaimWasPurchased(uri)(state),
nextListUri: collectionId && makeSelectNextUrlForCollectionAndUrl(collectionId, uri)(state),
previousListUri: collectionId && makeSelectPreviousUrlForCollectionAndUrl(collectionId, uri)(state),
+8 -10
View File
@@ -1,17 +1,16 @@
import { connect } from 'react-redux';
import { doPlayUri, doSetPlayingUri, doSetPrimaryUri } from 'redux/actions/content';
import { makeSelectThumbnailForUri, makeSelectClaimForUri, makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import { selectThumbnailForUri, makeSelectClaimForUri, makeSelectClaimWasPurchased } from 'redux/selectors/claims';
import { makeSelectFileInfoForUri } from 'redux/selectors/file_info';
import * as SETTINGS from 'constants/settings';
import * as COLLECTIONS_CONSTS from 'constants/collections';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectCostInfoForUri } from 'lbryinc';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { withRouter } from 'react-router';
import {
makeSelectIsPlaying,
makeSelectShouldObscurePreview,
makeSelectInsufficientCreditsForUri,
selectShouldObscurePreviewForUri,
selectInsufficientCreditsForUri,
makeSelectFileRenderModeForUri,
} from 'redux/selectors/content';
import FileRenderInitiator from './view';
@@ -23,17 +22,16 @@ const select = (state, props) => {
const collectionId = urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID);
return {
claimThumbnail: makeSelectThumbnailForUri(props.uri)(state),
claimThumbnail: selectThumbnailForUri(state, props.uri),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
obscurePreview: makeSelectShouldObscurePreview(props.uri)(state),
obscurePreview: selectShouldObscurePreviewForUri(state, props.uri),
isPlaying: makeSelectIsPlaying(props.uri)(state),
insufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
insufficientCredits: selectInsufficientCreditsForUri(state, props.uri),
autoplay: makeSelectClientSetting(SETTINGS.AUTOPLAY_MEDIA)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
costInfo: selectCostInfoForUri(state, props.uri),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
authenticated: selectUserVerifiedEmail(state),
collectionId,
};
};
+3 -21
View File
@@ -31,7 +31,6 @@ type Props = {
renderMode: string,
claim: StreamClaim,
claimWasPurchased: boolean,
authenticated: boolean,
videoTheaterMode: boolean,
collectionId: string,
};
@@ -50,7 +49,6 @@ export default function FileRenderInitiator(props: Props) {
renderMode,
costInfo,
claimWasPurchased,
authenticated,
videoTheaterMode,
collectionId,
} = props;
@@ -91,10 +89,6 @@ export default function FileRenderInitiator(props: Props) {
}
}, [claimThumbnail, thumbnail]);
function doAuthRedirect() {
history.push(`/$/${PAGES.AUTH}?redirect=${encodeURIComponent(location.pathname)}`);
}
// Wrap this in useCallback because we need to use it to the keyboard effect
// If we don't a new instance will be created for every render and react will think the dependencies have changed, which will add/remove the listener for every render
const viewFile = useCallback(
@@ -148,14 +142,12 @@ export default function FileRenderInitiator(props: Props) {
}
}
const showAppNag = IS_WEB && RENDER_MODES.UNSUPPORTED_IN_THIS_APP.includes(renderMode);
const disabled = showAppNag || (!fileInfo && insufficientCredits && !claimWasPurchased);
const shouldRedirect = IS_WEB && !authenticated && !isFree;
const disabled = !fileInfo && insufficientCredits && !claimWasPurchased;
return (
<div
ref={containerRef}
onClick={disabled ? undefined : shouldRedirect ? doAuthRedirect : viewFile}
onClick={disabled ? undefined : viewFile}
style={thumbnail && !obscurePreview ? { backgroundImage: `url("${thumbnail}")` } : {}}
className={classnames('content__cover', {
'content__cover--disabled': disabled,
@@ -164,16 +156,7 @@ export default function FileRenderInitiator(props: Props) {
'card__media--nsfw': obscurePreview,
})}
>
{showAppNag && (
<Nag
type="helpful"
inline
message={__('This content requires LBRY Desktop to display.')}
actionText={__('Get the App')}
href="https://lbry.com/get"
/>
)}
{!claimWasPurchased && insufficientCredits && !showAppNag && (
{!claimWasPurchased && insufficientCredits && (
<Nag
type="helpful"
inline
@@ -184,7 +167,6 @@ export default function FileRenderInitiator(props: Props) {
)}
{!disabled && (
<Button
requiresAuth={shouldRedirect}
onClick={viewFile}
iconSize={30}
title={isPlayable ? __('Play') : __('View')}
+2 -2
View File
@@ -6,14 +6,14 @@ import { makeSelectFileRenderModeForUri, selectPrimaryUri } from 'redux/selector
import { withRouter } from 'react-router';
import { doAnalyticsView } from 'redux/actions/app';
import FileRenderInline from './view';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { selectCostInfoForUri } from 'lbryinc';
const select = (state, props) => ({
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
isPlaying: selectPrimaryUri(state) === props.uri,
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
costInfo: selectCostInfoForUri(state, props.uri),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
});
+2 -2
View File
@@ -1,9 +1,9 @@
import { connect } from 'react-redux';
import { makeSelectTitleForUri } from 'redux/selectors/claims';
import { selectTitleForUri } from 'redux/selectors/claims';
import FileTitleSection from './view';
const select = (state, props) => ({
title: makeSelectTitleForUri(props.uri)(state),
title: selectTitleForUri(state, props.uri),
});
export default connect(select)(FileTitleSection);
+7 -7
View File
@@ -1,18 +1,18 @@
import { connect } from 'react-redux';
import { doFetchSubCount, makeSelectSubCountForUri } from 'lbryinc';
import { makeSelectTitleForUri, makeSelectClaimForUri } from 'redux/selectors/claims';
import { makeSelectInsufficientCreditsForUri } from 'redux/selectors/content';
import { doFetchSubCount, selectSubCountForUri } from 'lbryinc';
import { selectTitleForUri, selectClaimForUri } from 'redux/selectors/claims';
import { selectInsufficientCreditsForUri } from 'redux/selectors/content';
import FileTitleSection from './view';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri)(state);
const claim = selectClaimForUri(state, props.uri);
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);
const subCount = channelUri && selectSubCountForUri(state, channelUri);
return {
isInsufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
isInsufficientCredits: selectInsufficientCreditsForUri(state, props.uri),
title: selectTitleForUri(state, props.uri),
channelClaimId,
subCount,
};
+15 -11
View File
@@ -1,9 +1,9 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
selectClaimForUri,
makeSelectContentTypeForUri,
makeSelectMetadataForUri,
makeSelectClaimIsMine,
selectClaimIsMine,
} from 'redux/selectors/claims';
import { makeSelectPendingAmountByUri } from 'redux/selectors/wallet';
import { makeSelectFileInfoForUri } from 'redux/selectors/file_info';
@@ -12,15 +12,19 @@ import { doOpenModal } from 'redux/actions/app';
import FileValues from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
contentType: makeSelectContentTypeForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
metadata: makeSelectMetadataForUri(props.uri)(state),
user: selectUser(state),
pendingAmount: makeSelectPendingAmountByUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
});
const select = (state, props) => {
const claim = selectClaimForUri(state, props.uri);
return {
claim,
contentType: makeSelectContentTypeForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
metadata: makeSelectMetadataForUri(props.uri)(state),
user: selectUser(state),
pendingAmount: makeSelectPendingAmountByUri(props.uri)(state),
claimIsMine: selectClaimIsMine(state, claim),
};
};
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
+4 -4
View File
@@ -1,12 +1,12 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri } from 'redux/selectors/claims';
import { doFetchViewCount, makeSelectViewCountForUri } from 'lbryinc';
import { selectClaimForUri } from 'redux/selectors/claims';
import { doFetchViewCount, selectViewCountForUri } from 'lbryinc';
import { doAnalyticsView } from 'redux/actions/app';
import FileViewCount from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
viewCount: makeSelectViewCountForUri(props.uri)(state),
claim: selectClaimForUri(state, props.uri),
viewCount: selectViewCountForUri(state, props.uri),
});
const perform = (dispatch) => ({
+4 -4
View File
@@ -1,13 +1,13 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri } from 'redux/selectors/claims';
import { makeSelectViewCountForUri } from 'lbryinc';
import { selectClaimForUri } from 'redux/selectors/claims';
import { selectViewCountForUri } from 'lbryinc';
import { selectLanguage } from 'redux/selectors/settings';
import FileViewCountInline from './view';
const select = (state, props) => {
return {
claim: makeSelectClaimForUri(props.uri)(state),
viewCount: makeSelectViewCountForUri(props.uri)(state),
claim: selectClaimForUri(state, props.uri),
viewCount: selectViewCountForUri(state, props.uri),
lang: selectLanguage(state),
};
};
+5 -1
View File
@@ -1,6 +1,7 @@
// @flow
import React from 'react';
import 'scss/component/_view_count.scss';
import { useHistory } from 'react-router';
type Props = {
uri: string,
@@ -12,6 +13,9 @@ type Props = {
export default function FileViewCountInline(props: Props) {
const { claim, viewCount, lang } = props;
const {
location: { pathname },
} = useHistory();
let formattedViewCount;
try {
@@ -27,7 +31,7 @@ export default function FileViewCountInline(props: Props) {
// Limit the view-count visibility to Channel Pages for now. I believe we'll
// eventually show it everywhere, so this band-aid would be the easiest to
// clean up (only one place edit/remove).
const isChannelPage = window.location.pathname.startsWith('/@');
const isChannelPage = pathname.startsWith('/@');
// dont show if no view count, if it's a repost or isn't a channel page
if (!viewCount || (claim && claim.repost_url) || !isChannelPage) {
@@ -1,11 +1,11 @@
import { connect } from 'react-redux';
import fileViewerEmbeddedTitle from './view';
import { makeSelectTagInClaimOrChannelForUri, makeSelectTitleForUri } from 'redux/selectors/claims';
import { makeSelectTagInClaimOrChannelForUri, selectTitleForUri } from 'redux/selectors/claims';
import { PREFERENCE_EMBED } from 'constants/tags';
export default connect((state, props) => {
return {
title: makeSelectTitleForUri(props.uri)(state),
title: selectTitleForUri(state, props.uri),
preferEmbed: makeSelectTagInClaimOrChannelForUri(props.uri, PREFERENCE_EMBED)(state),
};
})(fileViewerEmbeddedTitle);
-1
View File
@@ -46,7 +46,6 @@ function FileWatchLaterLink(props: Props) {
return (
<Button
ref={buttonRef}
requiresAuth={IS_WEB}
title={title}
label={label}
className="button--file-action"
+2
View File
@@ -11,6 +11,7 @@ import { doSignOut, doOpenModal } from 'redux/actions/app';
import { makeSelectClientSetting, selectLanguage } from 'redux/selectors/settings';
import { selectHasNavigated, selectActiveChannelClaim } from 'redux/selectors/app';
import Header from './view';
import { selectMyChannelClaims } from 'redux/selectors/claims';
const select = (state) => ({
language: selectLanguage(state),
@@ -27,6 +28,7 @@ const select = (state) => ({
hasNavigated: selectHasNavigated(state),
user: selectUser(state),
activeChannelClaim: selectActiveChannelClaim(state),
myChannels: selectMyChannelClaims(state),
});
const perform = (dispatch) => ({
+80 -111
View File
@@ -17,10 +17,8 @@ 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 * as remote from '@electron/remote';
import { IS_MAC } from 'component/app/view';
// @endif
type Props = {
user: ?User,
@@ -63,6 +61,7 @@ type Props = {
isAbsoluteSideNavHidden: boolean,
hideCancel: boolean,
activeChannelClaim: ?ChannelClaim,
myChannels: ?Array<ChannelClaim>,
};
const Header = (props: Props) => {
@@ -91,6 +90,7 @@ const Header = (props: Props) => {
hideCancel,
user,
activeChannelClaim,
myChannels,
} = props;
const isMobile = useIsMobile();
// on the verify page don't let anyone escape other than by closing the tab to keep session data consistent
@@ -102,6 +102,7 @@ const Header = (props: Props) => {
const { backLabel, backNavDefault, title: backTitle, simpleTitle: simpleBackTitle } = backout || {};
const notificationsEnabled = ENABLE_UI_NOTIFICATIONS || (user && user.experimental_ui);
const activeChannelUrl = activeChannelClaim && activeChannelClaim.permanent_url;
const hasChannels = myChannels && myChannels.length > 0;
// Sign out if they click the "x" when they are on the password prompt
const authHeaderAction = syncError ? { onClick: signOut } : { navigate: '/' };
@@ -162,19 +163,6 @@ const Header = (props: Props) => {
}
}
const loginButtons = (
<div className="header__auth-buttons">
<Button
navigate={`/$/${PAGES.AUTH_SIGNIN}`}
button="link"
label={__('Log In')}
className="mobile-hidden"
disabled={user === null}
/>
<Button navigate={`/$/${PAGES.AUTH}`} button="primary" label={__('Sign Up')} disabled={user === null} />
</div>
);
type BalanceButtonProps = { className: string };
const BalanceButton = (balanceButtonProps: BalanceButtonProps) => (
<Button
@@ -219,11 +207,7 @@ const Header = (props: Props) => {
icon={ICONS.ARROW_LEFT}
/>
{backTitle && <h1 className="header__auth-title">{isMobile ? simpleBackTitle || backTitle : backTitle}</h1>}
{authenticated || !IS_WEB ? (
<BalanceButton className="header__navigation-item menu__title" />
) : (
loginButtons
)}
<BalanceButton className="header__navigation-item menu__title" />
</div>
) : (
<>
@@ -250,6 +234,7 @@ const Header = (props: Props) => {
aria-label={__('Home')}
className="header__navigation-item header__navigation-item--lbry"
onClick={() => {
// here use state.router.location.pathname
if (history.location.pathname === '/') window.location.reload();
}}
// @if TARGET='app'
@@ -286,75 +271,61 @@ const Header = (props: Props) => {
</div>
{!authHeader && !backout ? (
<div className={classnames('header__menu', { 'header__menu--with-balance': !IS_WEB || authenticated })}>
{(!IS_WEB || authenticated) && (
<BalanceButton className="header__navigation-item menu__title mobile-hidden" />
)}
{IS_WEB && !authenticated && loginButtons}
{(authenticated || !IS_WEB) && (
<Menu>
<MenuButton
aria-label={__('Your account')}
title={__('Your account')}
className={classnames('header__navigation-item', {
'menu__title header__navigation-item--icon': !activeChannelUrl,
'header__navigation-item--profile-pic': activeChannelUrl,
})}
// @if TARGET='app'
onDoubleClick={(e) => {
e.stopPropagation();
}}
// @endif
>
{activeChannelUrl ? (
<ChannelThumbnail uri={activeChannelUrl} small noLazyLoad />
) : (
<Icon size={18} icon={ICONS.ACCOUNT} aria-hidden />
)}
</MenuButton>
<MenuList className="menu__list--header">
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.UPLOADS}`)}>
<Icon aria-hidden icon={ICONS.PUBLISH} />
{__('Uploads')}
</MenuItem>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.CHANNELS}`)}>
<Icon aria-hidden icon={ICONS.CHANNEL} />
{__('Channels')}
</MenuItem>
<div className={classnames('header__menu', 'header__menu--with-balance')}>
<BalanceButton className="header__navigation-item menu__title mobile-hidden" />
<Menu>
<MenuButton
aria-label={__('Your account')}
title={__('Your account')}
className={classnames('header__navigation-item', {
'menu__title header__navigation-item--icon': !activeChannelUrl,
'header__navigation-item--profile-pic': activeChannelUrl,
})}
// @if TARGET='app'
onDoubleClick={(e) => {
e.stopPropagation();
}}
// @endif
>
{activeChannelUrl ? (
<ChannelThumbnail uri={activeChannelUrl} small noLazyLoad />
) : (
<Icon size={18} icon={ICONS.ACCOUNT} aria-hidden />
)}
</MenuButton>
<MenuList className="menu__list--header">
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.UPLOADS}`)}>
<Icon aria-hidden icon={ICONS.PUBLISH} />
{__('Uploads')}
</MenuItem>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.CHANNELS}`)}>
<Icon aria-hidden icon={ICONS.CHANNEL} />
{__('Channels')}
</MenuItem>
{hasChannels && authenticated && (
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.CREATOR_DASHBOARD}`)}>
<Icon aria-hidden icon={ICONS.ANALYTICS} />
{__('Creator Analytics')}
</MenuItem>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.REWARDS}`)}>
<Icon aria-hidden icon={ICONS.REWARDS} />
{__('Rewards')}
)}
{authenticated ? (
<MenuItem onSelect={openSignOutModal}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SIGN_OUT} />
{__('Sign Out')}
</div>
<span className="menu__link-help">{email}</span>
</MenuItem>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.INVITE}`)}>
<Icon aria-hidden icon={ICONS.INVITE} />
{__('Invites')}
</MenuItem>
{authenticated ? (
<MenuItem onSelect={IS_WEB ? signOut : openSignOutModal}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SIGN_OUT} />
{__('Sign Out')}
</div>
<span className="menu__link-help">{email}</span>
) : (
<>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.AUTH_SIGNIN}`)}>
<Icon aria-hidden icon={ICONS.SIGN_IN} />
{__('Cloud Connect')}
</MenuItem>
) : !IS_WEB ? (
<>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.AUTH_SIGNIN}`)}>
<Icon aria-hidden icon={ICONS.SIGN_IN} />
{__('Cloud Connect')}
</MenuItem>
</>
) : null}
</MenuList>
</Menu>
)}
</>
)}
</MenuList>
</Menu>
</div>
) : (
!isVerifyPage &&
@@ -395,37 +366,35 @@ type HeaderMenuButtonProps = {
};
function HeaderMenuButtons(props: HeaderMenuButtonProps) {
const { authenticated, notificationsEnabled, history, handleThemeToggle, currentTheme } = props;
const { notificationsEnabled, history, handleThemeToggle, currentTheme } = props;
return (
<div className="header__buttons">
{(authenticated || !IS_WEB) && (
<Menu>
<MenuButton
aria-label={__('Publish a file, or create a channel')}
title={__('Publish a file, or create a channel')}
className="header__navigation-item menu__title header__navigation-item--icon mobile-hidden"
// @if TARGET='app'
onDoubleClick={(e) => {
e.stopPropagation();
}}
// @endif
>
<Icon size={18} icon={ICONS.PUBLISH} aria-hidden />
</MenuButton>
<Menu>
<MenuButton
aria-label={__('Publish a file, or create a channel')}
title={__('Publish a file, or create a channel')}
className="header__navigation-item menu__title header__navigation-item--icon mobile-hidden"
// @if TARGET='app'
onDoubleClick={(e) => {
e.stopPropagation();
}}
// @endif
>
<Icon size={18} icon={ICONS.PUBLISH} aria-hidden />
</MenuButton>
<MenuList className="menu__list--header">
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.UPLOAD}`)}>
<Icon aria-hidden icon={ICONS.PUBLISH} />
{__('Upload')}
</MenuItem>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.CHANNEL_NEW}`)}>
<Icon aria-hidden icon={ICONS.CHANNEL} />
{__('New Channel')}
</MenuItem>
</MenuList>
</Menu>
)}
<MenuList className="menu__list--header">
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.UPLOAD}`)}>
<Icon aria-hidden icon={ICONS.PUBLISH} />
{__('Upload')}
</MenuItem>
<MenuItem className="menu__link" onSelect={() => history.push(`/$/${PAGES.CHANNEL_NEW}`)}>
<Icon aria-hidden icon={ICONS.CHANNEL} />
{__('New Channel')}
</MenuItem>
</MenuList>
</Menu>
{notificationsEnabled && <NotificationHeaderButton />}
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff. Show more