index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
|---|---|---|---|---|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/assets.loader.js
|
const DESIGN_SYSTEM_ICONS_SVG = 'sprite-icons.svg|mime-icons.svg|file-icons.svg';
const DESIGN_SYSTEM_CSS_SVG = 'sprite-for-css-only.svg';
module.exports = () => [
{
/**
* oneOf allows to take the first match instead of all matches, .e.g
*
* without one of:
*
* sprite-icons.svg -> [svg-inline-loader, url-loader, file-loader]
* img-1.svg -> [url loader, file loader]
* design-system-icon.svg -> file loader
*
* with one of:
*
* sprite-icons.svg -> svg-inline-loader
* img-1.svg -> url loader
* design-system-icon.svg -> file loader
*/
oneOf: [
{
test: new RegExp(`${DESIGN_SYSTEM_ICONS_SVG}$`),
type: 'asset/source',
},
{
test: /\.(bmp|png|jpg|jpeg|gif|svg)$/,
type: 'asset',
exclude: new RegExp(`${DESIGN_SYSTEM_CSS_SVG}`),
parser: {
dataUrlCondition: (source, { filename }) => {
// Don't inline the asset into a data url if the filename includes favicon, or if the size is greater than 4 KB
return filename.includes('favicon') ? false : Buffer.byteLength(source) <= 4 * 1024; // 4KB;
},
},
},
{
test: /\.(woff|woff2|eot|ttf|otf|mp4|webm|pdf)$/,
type: 'asset/resource',
},
{
test: /\.md$/,
type: 'asset/source',
},
],
},
];
| 7,500
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/constants.js
|
const BABEL_INCLUDE_NODE_MODULES = [
'asmcrypto.js',
'pmcrypto',
'proton-mail',
'@proton/pack',
'@proton/shared',
'@proton/srp',
'@proton/sieve',
'@sentry/core',
'@floating-ui/utils',
'@floating-ui/core',
'@floating-ui/dom',
'@proton/components',
'@protontech/mutex-browser',
'@protontech/interval-tree',
'@proton/recovery-kit',
'emoji-mart',
'idb',
'@protontech/bip39',
];
const BABEL_EXCLUDE_FILES = ['mailparser.js'];
module.exports = {
BABEL_EXCLUDE_FILES,
BABEL_INCLUDE_NODE_MODULES,
};
| 7,501
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/css.loader.js
|
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RAW_TEXT = /.*\.theme\.css|\.raw\.scss$/;
const handleUrlResolve = (url) => {
// Transparent image, included through write
if (url.includes('host.png')) {
return false;
}
return true;
};
module.exports = ({ browserslist, logical }) => {
const sassLoaders = [
{
loader: require.resolve('css-loader'),
options: {
url: { filter: handleUrlResolve },
},
},
{
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: browserslist,
flexbox: 'no-2009',
}),
require('postcss-color-functional-notation')(),
!logical && require('postcss-logical')(),
].filter(Boolean),
},
},
},
{
loader: require.resolve('resolve-url-loader'),
},
{
loader: require.resolve('sass-loader'),
},
].filter(Boolean);
const miniLoader = {
loader: MiniCssExtractPlugin.loader,
};
return [
{
test: /\.css$/,
exclude: /.*\.theme\.css/,
use: [
miniLoader,
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
url: { filter: handleUrlResolve },
},
},
],
sideEffects: true,
},
{
test: /\.scss$/,
exclude: RAW_TEXT,
use: [miniLoader, ...sassLoaders],
sideEffects: true,
},
{
test: RAW_TEXT,
// Prevent loading the theme in <style>, we want to load it as a raw string
use: [...sassLoaders],
},
];
};
| 7,502
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/favicon.config.js
|
const offsetIcon = {
offset: 15,
background: false,
};
module.exports = {
developerName: 'Proton AG',
developerURL: 'https://github.com/ProtonMail/WebClients',
background: '#fff',
theme_color: '#1b1340',
appleStatusBarStyle: 'default',
display: 'standalone',
start_url: '/',
loadManifestWithCredentials: true,
manifestMaskable: true,
icons: {
android: offsetIcon,
appleIcon: {
offset: 15,
background: '#fff',
},
appleStartup: false,
// Only interested in the .ico file, not the custom 16x16, 32x32 pngs it generates
// because we default to a .svg favicon (with our own custom implementation because
// the favicons library (6.x) doesn't support it by default)
favicons: ['favicon.ico'],
windows: offsetIcon,
yandex: offsetIcon,
},
};
| 7,503
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/js.loader.js
|
const { excludeNodeModulesExcept, excludeFiles, createRegex } = require('./helpers/regex');
const { BABEL_EXCLUDE_FILES, BABEL_INCLUDE_NODE_MODULES } = require('./constants');
const UNSUPPORTED_JS_LOADER = [
{
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
cacheCompression: true,
compact: true,
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: { browsers: ['ie 11'] },
useBuiltIns: 'entry',
corejs: { version: '3.27' },
},
],
[require.resolve('@babel/preset-typescript')],
],
plugins: [],
},
},
];
const getBabelLoader = ({ browserslist, isProduction = false, hasReactRefresh = true, isTtag = false } = {}) => {
const babelReactRefresh = hasReactRefresh ? [require.resolve('react-refresh/babel')] : [];
const babelPluginsDev = [...babelReactRefresh];
const babelPluginsProd = [
[require.resolve('babel-plugin-transform-react-remove-prop-types'), { removeImport: true }],
];
return {
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
cacheCompression: isProduction,
compact: isProduction,
babelrc: false,
configFile: false,
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: browserslist,
useBuiltIns: 'entry',
corejs: { version: '3.27' },
exclude: ['transform-typeof-symbol'], // Exclude transforms that make all code slower
},
],
[
require.resolve('@babel/preset-react'),
{
// Adds component stack to warning messages
// Adds __self attribute to JSX which React will use for some warnings
development: !isProduction,
runtime: 'automatic',
},
],
[require.resolve('@babel/preset-typescript')],
],
plugins: [
require.resolve('@babel/plugin-syntax-dynamic-import'),
require.resolve('@babel/plugin-proposal-object-rest-spread'),
require.resolve('@babel/plugin-proposal-nullish-coalescing-operator'),
require.resolve('@babel/plugin-proposal-optional-chaining'),
require.resolve('@babel/plugin-proposal-class-properties'),
require.resolve('@babel/plugin-proposal-private-methods'),
require.resolve('@babel/plugin-transform-runtime'),
...(isTtag ? [[require.resolve('ttag'), { extract: { output: 'i18n/template.pot' } }]] : []),
...(isProduction ? babelPluginsProd : babelPluginsDev),
],
},
};
};
const getJsLoader = (options) => {
return {
test: /\.js$|\.tsx?$|\.mjs$/,
exclude: createRegex(
excludeNodeModulesExcept(BABEL_INCLUDE_NODE_MODULES),
excludeFiles([...BABEL_EXCLUDE_FILES, 'pre.ts', 'unsupported.ts'])
),
use: getBabelLoader(options),
};
};
const getJsLoaders = (options) => {
return [
{
test: /(unsupported|pre)\.ts$/,
use: UNSUPPORTED_JS_LOADER,
},
getJsLoader(options),
];
};
module.exports = { getJsLoader, getJsLoaders };
| 7,504
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/optimization.js
|
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = /** @type { (env: any) => import('webpack').Options.Optimization } */ ({ isProduction }) => ({
// Needs to be single because we embed two entry points
runtimeChunk: 'single',
minimize: isProduction,
minimizer: [
new TerserPlugin({
extractComments: false,
}),
new CssMinimizerPlugin({
minimizerOptions: {
preset: [
'default',
{
calc: false,
},
],
},
}),
],
splitChunks: {
chunks(chunk) {
// This is the default "async" filter provided by webpack
const async = !chunk.canBeInitial();
// We exclude the crypto-worker and recovery-kit to be split, because we want them all in one file
return chunk.name !== 'recovery-kit' && chunk.name !== 'crypto-worker' && async;
},
},
});
| 7,505
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/plugins.js
|
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const { SubresourceIntegrityPlugin } = require('webpack-subresource-integrity');
const { RetryChunkLoadPlugin } = require('webpack-retry-chunk-load-plugin');
const SentryCliPlugin = require('@sentry/webpack-plugin');
const PostCssLogicalWebpackPlugin = require('./postcss-logical-webpack-plugin').default;
const WriteWebpackPlugin = require('./write-webpack-plugin').default;
const HtmlEditWebpackPlugin = require('./html-edit-webpack-plugin').default;
const defaultFaviconConfig = require('./favicon.config');
const faviconConfig = require(path.resolve('./favicon.config.js'));
module.exports = ({
isProduction,
isRelease,
publicPath,
appMode,
buildData,
featureFlags,
writeSRI,
warningLogs,
errorLogs,
logical,
cssName,
}) => {
return [
...(isProduction
? []
: [
new ReactRefreshWebpackPlugin({
overlay: false,
}),
(warningLogs || errorLogs) &&
new ESLintPlugin({
extensions: ['js', 'ts', 'tsx'],
eslintPath: require.resolve('eslint'),
context: path.resolve('.'),
emitWarning: warningLogs,
emitError: errorLogs,
// ESLint class options
resolvePluginsRelativeTo: __dirname,
cwd: path.resolve('.'),
cache: true,
}),
(warningLogs || errorLogs) &&
new ForkTsCheckerWebpackPlugin({
async: true,
formatter: 'basic',
issue: {
include: (issue) => {
if (warningLogs && issue.severity === 'warning') {
return true;
}
if (errorLogs && issue.severity === 'error') {
return true;
}
return false;
},
},
}),
]),
/*
* Sentry webpack plugin is only run on tag creation (IS_RELEASE_BUNDLE)
* Needed values for source-maps upload
* project: defined in sentry.properties of each app
* org: defined in SENTRY_ORG (gitlab env)
* url: defined in SENTRY_URL (gitlab env)
* authToken: defined in SENTRY_AUTH_TOKEN (gitlab env)
* */
isRelease &&
new SentryCliPlugin({
include: './dist',
ignore: ['node_modules', 'webpack.config.js'],
configFile: 'sentry.properties',
// This prevents build to fail if any issue happened
errorHandler: (err, invokeErr, compilation) => {
compilation.warnings.push('Sentry CLI Plugin: ' + err.message);
},
release: buildData.version,
}),
new CopyWebpackPlugin({
patterns: [
{
from: `${path.dirname(require.resolve('push.js'))}/serviceWorker.min.js`,
to: 'assets/serviceWorker.min.js',
},
],
}),
new WriteWebpackPlugin([
{
name: 'assets/version.json',
data: Buffer.from(JSON.stringify(buildData, null, 2)),
},
]),
new WriteWebpackPlugin([
{
name: 'assets/host.png',
data: Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'),
},
]),
new CopyWebpackPlugin({
patterns: [
{ from: 'src/.htaccess' },
// Fix max file limit if the folder does not exist
fs.existsSync('public') && { from: 'public', noErrorOnMissing: true },
].filter(Boolean),
}),
new MiniCssExtractPlugin({
filename: cssName,
chunkFilename: cssName,
}),
new HtmlWebpackPlugin({
template: path.resolve('./src/app.ejs'),
templateParameters: {
appName: faviconConfig.favicons.appName,
title: faviconConfig.favicons.appName,
description: faviconConfig.favicons.appDescription,
url: faviconConfig.url,
locales: faviconConfig.locales,
ogImage: faviconConfig.ogImage,
lang: 'en-US',
},
inject: 'body',
scriptLoading: 'defer',
minify: isProduction && {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
new FaviconsWebpackPlugin({
logo: path.resolve(faviconConfig.logo),
logoMaskable: path.resolve(faviconConfig.logoMaskable),
cache: path.resolve('./node_modules/.cache'),
favicons: {
version: buildData.version,
...defaultFaviconConfig,
...faviconConfig.favicons,
},
}),
...(writeSRI
? [
new SubresourceIntegrityPlugin(),
new HtmlEditWebpackPlugin((tag) => {
const src = tag.attributes.href || tag.attributes.src;
// Remove the integrity and crossorigin attributes for these files because we don't
// want to validate them since we may override the server response on these assets
// for certain scenarios.
if (/\.(css|png|svg|ico|json)(?:\?.+)?$/.test(src)) {
if (tag.attributes.integrity || tag.attributes.crossorigin) {
delete tag.attributes.integrity;
delete tag.attributes.crossorigin;
}
}
return tag;
}),
]
: []),
new HtmlEditWebpackPlugin((tag) => {
// Remove the favicon.ico tag that the FaviconsWebpackPlugin generates because:
// 1) We want it to be listed before the .svg icon that we manually inject
// 2) We want it to have the sizes="any" attribute because of this chrome bug
// https://twitter.com/subzey/status/1417099064949235712
if (tag.tagName === 'link' && tag.attributes.href.endsWith('favicon.ico')) {
return null;
}
// With enabling the loadManifestWithCredentials option in the FaviconsWebpackPlugin the
// crossorigin attribute for the manifest.json link is added correctly, however the SRI
// plugin removes it and replaces it with SRI attributes. This plugin adds back the use-credentials
// crossorigin attribute for the manifest link.
if (tag.tagName === 'link' && tag.attributes.href.endsWith('manifest.webmanifest')) {
tag.attributes.crossorigin = 'use-credentials';
}
return tag;
}),
new RetryChunkLoadPlugin({
cacheBust: `function() {
return Date.now();
}`,
retryDelay: 5000,
maxRetries: 3,
}),
new webpack.DefinePlugin({
WEBPACK_APP_MODE: JSON.stringify(appMode),
WEBPACK_PUBLIC_PATH: JSON.stringify(publicPath),
WEBPACK_FEATURE_FLAGS: JSON.stringify(featureFlags),
}),
logical && new PostCssLogicalWebpackPlugin(),
].filter(Boolean);
};
| 7,506
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/copy-index-html-webpack-plugin/index.ts
|
import { Compiler, sources } from 'webpack';
interface File {
name: string;
data: string;
}
export default class CopyIndexHtmlWebpackPlugin {
constructor(private handle: (source: string) => File[]) {}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap('CopyIndexHtmlWebpackPlugin', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'CopyIndexHtmlWebpackPlugin',
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
additionalAssets: true,
},
(assets) => {
const targetFilename = 'index.html';
const [assetName, source] = Object.entries(assets).find(([key]) => key === targetFilename) || [];
if (!assetName || !source) {
return;
}
const files = this.handle(source.source().toString());
files.forEach((file) => {
if (file.name === targetFilename) {
compilation.updateAsset(file.name, new sources.RawSource(file.data));
} else {
compilation.emitAsset(file.name, new sources.RawSource(file.data));
}
});
}
);
});
}
}
| 7,507
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/helpers/babel.js
|
/**
* Escape a string for a regex. NOTE: Does not cover all cases. Just the ones we expect.
* @param {string} str
* @return {string}
*/
const escapeRegex = (str) => str.replace(/[-.]/g, '\\$&');
/**
* Transform an array of strings into a regex catch.
* @param {Array} arr
* @return {string}
*/
const transform = (arr = []) => {
return arr.map(escapeRegex).join('|');
};
/**
* Exclude all node modules, EXCEPT the node modules specified.
* Also exclude any specified files.
* @param {Array} nodeModules
* @param {Array} files
* @return {RegExp}
*/
module.exports = (nodeModules = [], files = []) =>
new RegExp(`(/node_modules/(?!(${transform(nodeModules)})))|(${transform(files)})`);
| 7,508
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/helpers/files.js
|
const path = require('path');
const createHash = require('crypto').createHash;
const fs = require('fs');
const SRI_ALGORITHM = 'sha384';
const getHash = (out, encoding) => createHash('sha1').update(out, encoding).digest('hex');
const integrityHelper = (out, encoding, algorithm) => createHash(algorithm).update(out, encoding).digest('base64');
const getIntegrity = (out, encoding) => `${SRI_ALGORITHM}-${integrityHelper(out, encoding, SRI_ALGORITHM)}`;
const defaultPath = ({ basename, ext, hash }) => [basename, hash, ext].filter(Boolean).join('.');
const defaultContents = (path, contents) => contents;
/**
* Transform a file with an optional shasum.
* @param {String} filepath
* @param {boolean} hash
* @param {Function} transformPath
* @param {Function} transformContents
* @returns {Array}
*/
const transformFile = ({
filepath = '',
hash: shouldHash = false,
transformPath = defaultPath,
transformContents = defaultContents,
encoding = 'utf8',
}) => {
const contents = fs.readFileSync(filepath, { encoding });
const transformedContents = transformContents(filepath, contents);
const hash = shouldHash ? getHash(transformedContents, encoding) : '';
const ext = path.extname(filepath);
const basename = path.basename(filepath, ext);
const transformedPath = transformPath({ filepath, basename, ext: ext.slice(1), hash });
const integrity = getIntegrity(transformedContents, encoding);
return {
filepath: transformedPath,
contents: transformedContents,
integrity,
};
};
module.exports = transformFile;
| 7,509
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/helpers/regex.js
|
/**
* Escape a string for a regex. NOTE: Does not cover all cases. Just the ones we expect.
* @param {string} str
* @return {string}
*/
const escapeRegex = (str) => str.replace(/[-.]/g, '\\$&');
/**
* Transform an array of strings into a regex catch.
* @param {Array} arr
* @return {string}
*/
const transform = (arr = []) => {
return arr.map(escapeRegex).join('|');
};
/**
* Exclude all node modules, EXCEPT the node modules specified.
* @param {Array} nodeModules
* @return {String}
*/
const excludeNodeModulesExcept = (nodeModules = []) => `/node_modules/(?!(${transform(nodeModules)}))`;
/**
* Create a regex matching the strings in the array.
* @param {Array} arr
* @return {string}
*/
const excludeFiles = (arr = []) => `${transform(arr)}`;
/**
* Create a regex out of regex-strings.
* @param {Array} regexes
* @return {RegExp}
*/
const createRegex = (...regexes) => new RegExp(`${regexes.join('|')}`);
module.exports = {
excludeFiles,
excludeNodeModulesExcept,
createRegex,
};
| 7,510
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/html-edit-webpack-plugin/index.ts
|
import HtmlWebpackPlugin, { HtmlTagObject } from 'html-webpack-plugin';
import { Compiler } from 'webpack';
export default class HtmlEditWebpackPlugin {
constructor(private handle: (node: HtmlTagObject) => HtmlTagObject) {}
apply(compiler: Compiler) {
// afterPlugins and thisCompilation for compatibility with the SRI plugin so that it's run after it
compiler.hooks.afterPlugins.tap('HtmlEditWebpackPlugin', (compiler) => {
compiler.hooks.thisCompilation.tap(
{
name: 'HtmlEditWebpackPlugin',
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS,
},
(compilation) => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapPromise(
{
name: 'HtmlEditWebpackPlugin',
stage: 10000,
},
async (data) => {
data.headTags = data.headTags.map(this.handle).filter((tag) => !!tag);
data.bodyTags = data.bodyTags.map(this.handle).filter((tag) => !!tag);
return data;
}
);
}
);
});
}
}
| 7,511
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/postcss-logical-webpack-plugin/index.ts
|
import logical from 'postcss-logical';
import { Compiler, sources } from 'webpack';
import postcss from 'postcss';
export default class PostCssLogicalWebpackPlugin {
apply(compiler: Compiler) {
const processor = postcss([logical()]);
compiler.hooks.thisCompilation.tap('PostCssLogicalWebpackPlugin', (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: 'PostCssLogicalWebpackPlugin',
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
additionalAssets: true,
},
async (assets) => {
await Promise.all(
Object.entries(assets)
.filter(([path]) => {
const targetOrigin = 'https://proton.local';
const url = new URL(path, targetOrigin);
return (
url.origin === targetOrigin &&
url.pathname.endsWith('.css') &&
!url.pathname.endsWith('.ltr.css')
);
})
.map(async ([path, asset]) => {
const result = await processor.process(asset.source(), {
map: false,
from: undefined,
to: undefined,
});
const filename = `${path.replace(/\.css/, '.ltr.css')}`;
const source = new sources.RawSource(result.css);
if (compilation.getAsset(filename)) {
compilation.updateAsset(filename, source);
} else {
compilation.emitAsset(filename, source);
}
})
);
return undefined;
}
);
});
}
}
| 7,512
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack
|
petrpan-code/ProtonMail/WebClients/packages/pack/webpack/write-webpack-plugin/index.ts
|
import { Compiler, sources } from 'webpack';
interface File {
name: string;
data: string | Buffer;
}
export default class WriteWebpackPlugin {
constructor(private files: File[]) {}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap('WriteWebpackPlugin', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'WriteWebpackPlugin',
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
() => {
for (const file of this.files) {
compilation.emitAsset(file.name, new sources.RawSource(file.data));
}
}
);
});
}
}
| 7,513
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/.browserslistrc
|
[test]
node 18
| 7,514
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/.eslintrc.js
|
module.exports = {
extends: ['@proton/eslint-config-proton'],
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.json',
},
rules: {
'no-console': ['error', { allow: ['warn', 'error'] }],
'@typescript-eslint/consistent-type-imports': 'error',
curly: ['error', 'multi-line'],
},
ignorePatterns: ['.eslintrc.js', 'fathom/'],
};
| 7,515
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/babel.config.js
|
// The Extension build handles transpiling & bundling with Webpack
// and leverages Babel with its own configuration. This configuration
// is only consumed by babel-jest for tests at the moment.
const presetEnvOpts = {
bugfixes: true,
useBuiltIns: 'usage',
corejs: '3.29',
};
module.exports = {
presets: [
['@babel/preset-env', presetEnvOpts],
'@babel/preset-typescript',
['@babel/preset-react', { development: true, runtime: 'automatic' }],
],
};
| 7,516
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/constants.ts
|
export const VAULT_CONTENT_FORMAT_VERSION = 1;
export const LABEL_CONTENT_FORMAT_VERSION = 1;
export const ITEM_CONTENT_FORMAT_VERSION = 1;
export const MAX_BATCH_ITEMS_PER_REQUEST = 100;
export const ALIAS_OPTIONS_MAX_AGE = 10 * 60;
export const ALIAS_DETAILS_MAX_AGE = 30;
export const MAX_ITEM_NAME_LENGTH = 200;
export const MAX_ITEM_NOTE_LENGTH = 25_000;
export const PASS_VIDEO_URL = 'https://www.youtube.com/embed/Nm4DCAjePOM?cc_load_policy=1';
export const PASS_ANDROID_URL = 'https://play.google.com/store/apps/details?id=proton.android.pass';
export const PASS_IOS_URL = 'https://apps.apple.com/us/app/proton-pass-password-manager/id6443490629';
export const PASS_X_URL = 'https://x.com/Proton_Pass';
export const PASS_REDDIT_URL = 'https://www.reddit.com/r/ProtonPass/';
export const PASS_GITHUB_URL = 'https://github.com/ProtonMail/WebClients/tree/main/applications/pass-extension';
export const PASS_REQUEST_URL = 'https://protonmail.uservoice.com/forums/953584-proton-pass';
export const PASS_BLOG_TRIAL_URL = 'https://proton.me/support/pass-trial';
export const PASS_BF_MONTHLY_PRICE = 199;
export const PASS_BF_2023_DATES = [
ENV === 'development' ? Date.now() - 1 : +new Date('2023-11-02T06:00:00'),
+new Date('2023-12-04T00:00:00'),
] as const;
| 7,517
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/globals.d.ts
|
declare const BUILD_TARGET: string;
declare const ENV: string;
declare const REDUX_DEVTOOLS_PORT: number;
declare const RESUME_FALLBACK: boolean;
declare const RUNTIME_RELOAD_PORT: number;
declare const RUNTIME_RELOAD: boolean;
declare const VERSION: string;
| 7,518
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/jest.config.js
|
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
moduleDirectories: ['<rootDir>/node_modules', 'node_modules'],
testEnvironment: './jest.env.js',
transformIgnorePatterns: [
'node_modules/(?!(@proton/shared|@proton/components|jsmimeparser|@protontech/mutex-browser|pmcrypto|openpgp|@openpgp/web-stream-tools|asmcrypto.js|otpauth)/)',
],
transform: { '^.+\\.(m?js|tsx?)$': 'babel-jest' },
reporters: ['default', ['jest-junit', { outputName: 'test-report.xml' }]],
testTimeout: 30000,
};
| 7,519
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/jest.env.js
|
// Stolen from: https://github.com/ipfs/jest-environment-aegir/blob/master/src/index.js
// Overcomes error from jest internals.. this thing: https://github.com/facebook/jest/issues/6248
// Mostly needed for making OpenPGP.js works
const JSDOMEnvironment = require('jest-environment-jsdom').default;
class MyEnvironment extends JSDOMEnvironment {
constructor({ globalConfig, projectConfig }, context) {
super(
{
globalConfig,
projectConfig: {
...projectConfig,
globals: { ...projectConfig.globals, Uint32Array, Uint8Array, ArrayBuffer },
},
},
context
);
}
async setup() {} // eslint-disable-line
async teardown() {} // eslint-disable-line
}
module.exports = MyEnvironment;
| 7,520
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/jest.setup.js
|
import '@testing-library/jest-dom';
import { TextDecoder, TextEncoder } from 'util';
// Getting ReferenceError: TextDecoder is not defined without
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
global.ENV = 'test';
// Do not start crypto worker pool, let the single tests setup/mock the CryptoProxy as needed
jest.mock('@proton/shared/lib/helpers/setupCryptoWorker', () => ({
__esModule: true,
loadCryptoWorker: jest.fn(),
}));
jest.mock('@proton/shared/lib/i18n/dateFnLocales', () => ({
__esModule: true,
}));
jest.mock('@proton/shared/lib/pow/wasmWorkerWrapper.ts', () => ({
__esModule: true,
}));
jest.mock('@proton/shared/lib/pow/pbkdfWorkerWrapper.ts', () => ({
__esModule: true,
}));
jest.mock('loglevel');
// JSDom does not include webcrypto
const crypto = require('crypto').webcrypto;
global.crypto.subtle = crypto.subtle;
| 7,521
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/package.json
|
{
"name": "@proton/pass",
"description": "Proton Pass shared codebase",
"license": "GPL-3.0",
"sideEffects": [
"./src/lib/api/api.ts",
"./src/lib/auth/authentication.ts",
"./src/lib/globals/browser.ts"
],
"scripts": {
"build": "cross-env NODE_ENV=production proton-pack build --appMode=standalone",
"check-types": "tsc",
"docs": "docsify serve ./docs",
"generate:proto": "scripts/generate-protos.sh",
"i18n:validate": "proton-i18n validate lint-functions",
"i18n:validate:context": "proton-i18n extract && proton-i18n validate",
"install:additional-tools": "npm i docsify-cli@latest @redux-devtools/cli@latest -g",
"lint": "eslint . --ext .js,.ts,.tsx --quiet --cache",
"pretty": "prettier --write $(find src/app -type f -name '*.js' -o -name '*.ts' -o -name '*.tsx')",
"start": "proton-pack dev-server --appMode=standalone",
"sync:fathom": "scripts/sync-fathom.sh",
"test": "NODE_NO_WARNINGS=1 jest --runInBand --ci --verbose"
},
"dependencies": {
"@proton/atoms": "workspace:^",
"@proton/crypto": "workspace:packages/crypto",
"@proton/polyfill": "workspace:packages/polyfill",
"@proton/shared": "workspace:packages/shared",
"@proton/styles": "workspace:^",
"@reduxjs/toolkit": "^1.9.7",
"formik": "^2.4.5",
"idb": "^7.1.1",
"imask": "^7.1.3",
"loglevel": "^1.8.1",
"otpauth": "^9.2.0",
"papaparse": "^5.4.1",
"react": "^17.0.2",
"react-redux": "^8.1.3",
"redux": "^4.2.1",
"redux-saga": "^1.2.3",
"tldts": "^6.0.21",
"webextension-polyfill": "^0.10.0",
"x2js": "^3.4.4"
},
"devDependencies": {
"@protobuf-ts/plugin": "^2.9.1",
"@proton/eslint-config-proton": "workspace:packages/eslint-config-proton",
"@proton/i18n": "workspace:packages/i18n",
"@types/chrome": "^0.0.252",
"@types/lodash": "^4.14.202",
"@types/webextension-polyfill": "^0.10.6",
"cross-env": "^7.0.3",
"eslint": "^8.54.0",
"jest": "^29.7.0",
"prettier": "^3.1.0",
"typescript": "^5.3.2"
}
}
| 7,522
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/pass/tsconfig.json
|
{
"extends": "../../tsconfig.base.json",
"exclude": ["**/node_modules", "**/dist", "**/public", "**/.*/"],
"compilerOptions": {
"target": "ESNext",
"lib": ["dom", "dom.iterable", "esnext", "WebWorker"],
"types": ["webpack-env", "jest", "chrome", "webextension-polyfill", "./globals.d.ts"]
}
}
| 7,523
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/assets/protonpass-account.svg
|
<svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M40 80C62.0914 80 80 62.0914 80 40C80 17.9086 62.0914 0 40 0C17.9086 0 0 17.9086 0 40C0 62.0914 17.9086 80 40 80Z"
fill="#302D45"
/>
<path
d="M51.3503 33.5229H28.9845C27.1653 33.5229 25.6904 34.9978 25.6904 36.8171V64.8899C25.6904 66.7092 27.1653 68.184 28.9845 68.184H51.3503C53.1696 68.184 54.6444 66.7092 54.6444 64.8899V36.8171C54.6444 34.9978 53.1696 33.5229 51.3503 33.5229Z"
fill="white"
/>
<path
d="M37.736 56.9414H32.4108C32.1839 56.9414 32 57.1253 32 57.3522C32 57.5791 32.1839 57.763 32.4108 57.763H37.736C37.9628 57.763 38.1468 57.5791 38.1468 57.3522C38.1468 57.1253 37.9628 56.9414 37.736 56.9414Z"
fill="#D1CFCD"
/>
<path
d="M47.4426 56.9414H39.7135C39.4867 56.9414 39.3027 57.1253 39.3027 57.3522C39.3027 57.5791 39.4867 57.763 39.7135 57.763H47.4426C47.6695 57.763 47.8534 57.5791 47.8534 57.3522C47.8534 57.1253 47.6695 56.9414 47.4426 56.9414Z"
fill="#D1CFCD"
/>
<path
d="M43.1071 60.2578H36.6462C36.4193 60.2578 36.2354 60.4417 36.2354 60.6686C36.2354 60.8955 36.4193 61.0794 36.6462 61.0794H43.1071C43.3339 61.0794 43.5179 60.8955 43.5179 60.6686C43.5179 60.4417 43.3339 60.2578 43.1071 60.2578Z"
fill="#D1CFCD"
/>
<path
d="M40.251 54.0254C44.1331 54.0254 47.2803 50.8783 47.2803 46.9961C47.2803 43.1139 44.1331 39.9668 40.251 39.9668C36.3688 39.9668 33.2217 43.1139 33.2217 46.9961C33.2217 50.8783 36.3688 54.0254 40.251 54.0254Z"
fill="#F5F4F2"
/>
<path
d="M40.2511 48.3679C41.73 48.3679 42.9289 47.169 42.9289 45.69C42.9289 44.2111 41.73 43.0122 40.2511 43.0122C38.7721 43.0122 37.5732 44.2111 37.5732 45.69C37.5732 47.169 38.7721 48.3679 40.2511 48.3679Z"
fill="#D1CFCD"
/>
<path
d="M40.2514 54.0253C42.2263 54.0253 44.0003 53.222 45.2723 51.9165C44.1008 50.427 42.2932 49.4897 40.2514 49.4897C38.2095 49.4897 36.402 50.4437 35.2305 51.9165C36.5024 53.2052 38.2765 54.0253 40.2514 54.0253Z"
fill="#D1CFCD"
/>
<path
d="M43.3023 36.7058H37.1686C36.9153 36.7058 36.7061 36.4929 36.7061 36.2352C36.7061 35.9775 36.9153 35.7646 37.1686 35.7646H43.3023C43.5556 35.7646 43.7649 35.9775 43.7649 36.2352C43.7649 36.4929 43.5556 36.7058 43.3023 36.7058Z"
fill="#6D4AFF"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M45.6055 0.389648L36.7061 33.5564H44.5722L52.9814 2.15359C50.6151 1.34211 48.1487 0.746311 45.6055 0.389648Z"
fill="#372580"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M27.4805 1.99846L35.9314 33.5568H43.7975L34.8805 0.324707C32.331 0.650414 29.8565 1.21612 27.4805 1.99846Z"
fill="url(#paint0_linear_8098_98264)"
/>
<path
d="M63.3683 30.2673C64.5791 30.2673 65.5607 29.2857 65.5607 28.0748C65.5607 26.8639 64.5791 25.8823 63.3683 25.8823C62.1574 25.8823 61.1758 26.8639 61.1758 28.0748C61.1758 29.2857 62.1574 30.2673 63.3683 30.2673Z"
fill="#372580"
/>
<path
d="M20.7238 41.1852L17.7782 40.0973L16.4226 39.5952L15.9205 38.2396L14.8326 35.2939L13.7448 38.2396L13.2427 39.5952L11.887 40.0973L8.94141 41.1852L11.887 42.273L13.2427 42.7751L13.7448 44.1308L14.8326 47.0764L15.9205 44.1308L16.4226 42.7751L17.7782 42.273L20.7238 41.1852Z"
fill="white"
/>
<defs>
<linearGradient
id="paint0_linear_8098_98264"
x1="29.412"
y1="-3.99974"
x2="39.0591"
y2="38.1179"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#D7B7FF" />
<stop offset="1" stop-color="#6D4AFF" />
</linearGradient>
</defs>
</svg>
| 7,524
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/assets/protonpass-brand.svg
|
<?xml version="1.0" encoding="utf-8"?>
<svg
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 162.5 27.6"
style="enable-background: new 0 0 162.5 27.6"
xml:space="preserve"
>
<style type="text/css">
.st0 {
fill: #ffffff;
}
</style>
<path
class="st0"
d="M3,18.5v5.8h4.1v-5.6c0-0.5,0.2-1.1,0.6-1.4c0.4-0.4,0.9-0.6,1.4-0.6h4.2c1.9,0,3.8-0.8,5.2-2.2
c1.4-1.4,2.2-3.3,2.2-5.2c0-2-0.8-3.8-2.2-5.2c-1.4-1.4-3.3-2.2-5.2-2.2H3v7.3h4.1V5.8h5.9c0.9,0,1.8,0.4,2.5,1c0.7,0.7,1,1.5,1,2.5
c0,0.9-0.4,1.8-1,2.5c-0.7,0.7-1.5,1-2.5,1H8.7c-0.7,0-1.5,0.1-2.2,0.4c-0.7,0.3-1.3,0.7-1.8,1.2c-0.5,0.5-0.9,1.2-1.2,1.9
C3.2,17,3,17.7,3,18.5z"
/>
<path
class="st0"
d="M21.3,24.3v-8.9c0-3.6,2.1-6.5,6.3-6.5c0.7,0,1.4,0.1,2,0.2v3.7c-0.5,0-0.9,0-1.1,0c-2.2,0-3.2,1-3.2,3.1v8.5
H21.3z"
/>
<path
class="st0"
d="M30.9,16.8c0-4.5,3.4-7.9,8-7.9c4.7,0,8,3.4,8,7.9s-3.4,7.9-8,7.9C34.2,24.7,30.9,21.3,30.9,16.8z M42.9,16.8
c0-2.5-1.7-4.3-4-4.3c-2.3,0-4,1.8-4,4.3c0,2.6,1.7,4.3,4,4.3C41.2,21.1,42.9,19.4,42.9,16.8z"
/>
<path
class="st0"
d="M59.9,16.8c0-4.5,3.4-7.9,8-7.9c4.7,0,8,3.4,8,7.9s-3.4,7.9-8,7.9C63.2,24.7,59.9,21.3,59.9,16.8z M71.9,16.8
c0-2.5-1.7-4.3-4-4.3c-2.3,0-4,1.8-4,4.3c0,2.6,1.7,4.3,4,4.3C70.2,21.1,71.9,19.4,71.9,16.8z"
/>
<path
class="st0"
d="M78,24.3v-8.6c0-4,2.5-6.8,7-6.8c4.5,0,7,2.9,7,6.8v8.6h-4v-8.3c0-2.2-1-3.6-3-3.6c-2,0-3,1.4-3,3.6v8.3H78z"
/>
<path
class="st0"
d="M58.7,12.5h-4.4v5.6c0,2,0.7,2.9,2.7,2.9c0.2,0,0.7,0,1.3,0v3.3c-0.8,0.2-1.6,0.4-2.4,0.4
c-3.4,0-5.7-2.1-5.7-5.9v-6.2h-2.7V9.2h0.7c0.3,0,0.5-0.1,0.8-0.2c0.2-0.1,0.5-0.3,0.7-0.4C49.8,8.4,50,8.2,50.1,8
c0.1-0.3,0.2-0.5,0.2-0.8V4.1h4.1v5.1h4.4L58.7,12.5L58.7,12.5z"
/>
<path
class="st0"
d="M125.8,9.6c-4.6,0-7.9,3.3-7.9,7.8c0,4.7,3.3,7.8,7.2,7.8c2.2,0,3.9-1,4.8-2.6l0.3,2.2h3.6v-7.5
C133.7,12.6,130.3,9.6,125.8,9.6z M125.8,21.7c-2.3,0-4-1.8-4-4.3c0-2.6,1.7-4.3,4-4.3c2.2,0,3.9,1.7,3.9,4.3
C129.7,20.3,127.8,21.7,125.8,21.7z"
/>
<path
class="st0"
d="M141.5,25.2c3.1,0,5.7-1.8,5.7-4.4c0-5.7-7.7-4.4-7.7-6.7c0-0.8,0.7-1.3,1.7-1.3c1.1,0,1.8,0.6,1.9,1.5h3.8
c-0.2-2.9-2.5-4.7-5.7-4.7c-3.4,0-5.5,2-5.5,4.5c0,5.8,7.7,4.3,7.7,6.7c0,0.7-0.7,1.3-1.8,1.3c-1.1,0-2.1-0.5-2.3-1.7h-3.9
C135.6,23.2,138.1,25.2,141.5,25.2z"
/>
<path
class="st0"
d="M155,25.2c3.1,0,5.7-1.8,5.7-4.4c0-5.7-7.7-4.4-7.7-6.7c0-0.8,0.7-1.3,1.7-1.3c1.1,0,1.8,0.6,1.9,1.5h3.8
c-0.2-2.9-2.5-4.7-5.7-4.7c-3.4,0-5.5,2-5.5,4.5c0,5.8,7.7,4.3,7.7,6.7c0,0.7-0.7,1.3-1.8,1.3c-1.1,0-2.1-0.5-2.3-1.7h-3.9
C149,23.2,151.5,25.2,155,25.2z"
/>
<path
class="st0"
d="M110.6,2.1h-10.5v22.7h4.1v-5.7c0-0.5,0.2-1.1,0.6-1.5c0.4-0.4,0.9-0.6,1.5-0.6h4.3c2,0,3.9-0.8,5.3-2.2
c1.4-1.4,2.2-3.3,2.2-5.3c0-1-0.2-2-0.6-2.9c-0.4-0.9-0.9-1.7-1.6-2.4c-0.7-0.7-1.5-1.3-2.4-1.6C112.6,2.3,111.6,2.1,110.6,2.1z
M113.9,9.6c0,0.5-0.1,0.9-0.3,1.4c-0.2,0.4-0.4,0.8-0.8,1.1c-0.3,0.3-0.7,0.6-1.1,0.8c-0.4,0.2-0.9,0.3-1.4,0.3h-6.1V6.1h6.1
c0.5,0,0.9,0.1,1.4,0.3c0.4,0.2,0.8,0.4,1.1,0.8c0.3,0.3,0.6,0.7,0.8,1.2C113.8,8.7,113.9,9.2,113.9,9.6L113.9,9.6z"
/>
</svg>
| 7,525
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/assets/protonpass-icon.svg
|
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M153.963 64.6798C189.679 28.9634 207.537 11.1052 228.13 4.41417C246.244 -1.47139 265.756 -1.47139 283.87 4.41417C304.463 11.1052 322.321 28.9634 358.037 64.6798L447.32 153.963C483.037 189.679 500.895 207.537 507.586 228.13C513.471 246.244 513.471 265.756 507.586 283.87C500.895 304.463 483.037 322.321 447.32 358.037L358.037 447.32C322.321 483.037 304.463 500.895 283.87 507.586C265.756 513.471 246.244 513.471 228.13 507.586C207.537 500.895 189.679 483.037 153.962 447.32L137.176 428.501C127.018 417.113 121.939 411.419 118.318 404.943C115.106 399.199 112.75 393.017 111.324 386.593C109.715 379.35 109.715 371.72 109.715 356.46L109.715 155.541C109.715 140.28 109.715 132.65 111.323 125.407C112.75 118.983 115.106 112.801 118.318 107.057C121.939 100.581 127.018 94.887 137.176 83.4988L153.963 64.6798Z"
fill="url(#paint0_radial_3371_26980)"
/>
<path
d="M153.963 64.6798C189.679 28.9634 207.537 11.1052 228.13 4.41417C246.244 -1.47139 265.756 -1.47139 283.87 4.41417C304.463 11.1052 322.321 28.9634 358.037 64.6798L447.32 153.963C483.037 189.679 500.895 207.537 507.586 228.13C513.471 246.244 513.471 265.756 507.586 283.87C500.895 304.463 483.037 322.321 447.32 358.037L358.037 447.32C322.321 483.037 304.463 500.895 283.87 507.586C265.756 513.471 246.244 513.471 228.13 507.586C207.537 500.895 189.679 483.037 153.962 447.32L137.176 428.501C127.018 417.113 121.939 411.419 118.318 404.943C115.106 399.199 112.75 393.017 111.324 386.593C109.715 379.35 109.715 371.72 109.715 356.46L109.715 155.541C109.715 140.28 109.715 132.65 111.323 125.407C112.75 118.983 115.106 112.801 118.318 107.057C121.939 100.581 127.018 94.887 137.176 83.4988L153.963 64.6798Z"
fill="url(#paint1_linear_3371_26980)"
/>
<path
d="M147.585 71.0519C165.443 53.1937 174.373 44.2646 184.669 40.9191C193.726 37.9764 203.482 37.9764 212.539 40.9191C222.835 44.2646 231.764 53.1937 249.623 71.052L383.547 204.976C401.405 222.834 410.334 231.763 413.68 242.06C416.622 251.117 416.622 260.873 413.68 269.93C410.334 280.226 401.405 289.155 383.547 307.013L249.623 440.938C231.764 458.796 222.835 467.725 212.539 471.07C203.482 474.013 193.726 474.013 184.669 471.07C174.373 467.725 165.443 458.796 147.585 440.938L64.6798 358.032C28.9634 322.316 11.1052 304.457 4.41417 283.865C-1.47139 265.751 -1.47139 246.239 4.41417 228.125C11.1052 207.532 28.9634 189.674 64.6798 153.957L147.585 71.0519Z"
fill="url(#paint2_radial_3371_26980)"
/>
<defs>
<radialGradient
id="paint0_radial_3371_26980"
cx="0"
cy="0"
r="1"
gradientUnits="userSpaceOnUse"
gradientTransform="translate(154.521 521.978) rotate(-58.142) scale(427.395 668.358)"
>
<stop stop-color="#FFD580" />
<stop offset="0.09375" stop-color="#F6C592" />
<stop offset="0.205" stop-color="#EBB6A2" />
<stop offset="0.324466" stop-color="#DFA5AF" />
<stop offset="0.42875" stop-color="#D397BE" />
<stop offset="0.53375" stop-color="#C486CB" />
<stop offset="0.64875" stop-color="#B578D9" />
<stop offset="0.77125" stop-color="#A166E5" />
<stop offset="0.89125" stop-color="#8B57F2" />
<stop offset="1" stop-color="#704CFF" />
</radialGradient>
<linearGradient
id="paint1_linear_3371_26980"
x1="136.887"
y1="-101.663"
x2="236.456"
y2="506.122"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#6D4AFF" />
<stop offset="0.392009" stop-color="#B39FFB" stop-opacity="0.978022" />
<stop offset="1" stop-color="#FFE8DB" stop-opacity="0.8" />
</linearGradient>
<radialGradient
id="paint2_radial_3371_26980"
cx="0"
cy="0"
r="1"
gradientUnits="userSpaceOnUse"
gradientTransform="translate(116.979 469.934) rotate(-58.142) scale(343.774 537.592)"
>
<stop stop-color="#FFD580" />
<stop offset="0.09375" stop-color="#F6C592" />
<stop offset="0.205" stop-color="#EBB6A2" />
<stop offset="0.324466" stop-color="#DFA5AF" />
<stop offset="0.42875" stop-color="#D397BE" />
<stop offset="0.53375" stop-color="#C486CB" />
<stop offset="0.64875" stop-color="#B578D9" />
<stop offset="0.77125" stop-color="#A166E5" />
<stop offset="0.89125" stop-color="#8B57F2" />
<stop offset="1" stop-color="#704CFF" />
</radialGradient>
</defs>
</svg>
| 7,526
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Alias/Alias.preview.scss
|
.pass-alias-preview--content {
color: var(--interaction-norm);
}
| 7,527
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Alias/Alias.preview.tsx
|
import { type VFC } from 'react';
import { c } from 'ttag';
import { MiddleEllipsis } from '@proton/components/components';
import { SubTheme } from '@proton/pass/components/Layout/Theme/types';
import clsx from '@proton/utils/clsx';
import './Alias.preview.scss';
export const AliasPreview: VFC<{
loading?: boolean;
prefix: string;
suffix: string;
className?: string;
}> = ({ loading, prefix, suffix, className }) => {
const suffixLastChars = (suffix.split('@')?.[1]?.length ?? 5) + 1;
return (
<div className={clsx(['flex flex-column flex-align-items-center mb-4', className])}>
<div className="mb-2 color-weak">{c('Info').t`You are about to create:`}</div>
<div className="w-full text-center">
{loading ? (
<div className="w-full pass-skeleton pass-skeleton--alias-preview" />
) : (
<MiddleEllipsis
className={`${SubTheme.VIOLET} pass-alias-preview--content text-lg`}
charsToDisplayEnd={suffixLastChars}
displayTitle
text={prefix + suffix}
/>
)}
</div>
</div>
);
};
| 7,528
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Alias
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Alias/legacy/Alias.preview.tsx
|
import { type VFC } from 'react';
import { c } from 'ttag';
import { MiddleEllipsis } from '@proton/components/components';
import clsx from '@proton/utils/clsx';
export const AliasPreview: VFC<{
loading?: boolean;
prefix: string;
suffix: string;
className?: string;
standalone?: boolean;
}> = ({ loading, prefix, suffix, className, standalone = false }) => {
const suffixLastChars = (suffix.split('@')?.[1]?.length ?? 5) + 1;
const content = loading ? (
<div className="ml-0.5 pass-skeleton pass-skeleton--alias-preview" />
) : (
<MiddleEllipsis charsToDisplayEnd={suffixLastChars} text={prefix + suffix} />
);
return standalone ? (
<div className={className}>{content}</div>
) : (
<div className={clsx(['flex mb-4', className])}>
<small className="flex-item-nogrow flex-item-noshrink mr-0.5">{c('Info').t`You're about to create`}</small>
<small className="color-primary flex-item-fluid">{content}</small>
</div>
);
};
| 7,529
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Confirmation/ConfirmationModal.tsx
|
import type { ReactNode } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
Alert,
ErrorButton,
type ModalSize,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
} from '@proton/components';
export type ConfirmationModalProps = {
onClose?: () => void;
onSubmit?: () => any | Promise<any>;
title?: string;
children?: ReactNode;
alertText?: ReactNode;
cancelText?: ReactNode;
submitText?: ReactNode;
open?: boolean;
disabled?: boolean;
size?: ModalSize;
};
export const ConfirmationModal = ({
alertText,
cancelText = c('Action').t`Cancel`,
submitText = c('Action').t`Submit`,
disabled = false,
title,
children,
open,
size,
onClose,
onSubmit,
}: ConfirmationModalProps) => {
const handleSubmit = async () => {
await onSubmit?.();
onClose?.();
};
return (
<ModalTwo onClose={onClose} onReset={onClose} open={open} size={size ?? 'small'}>
<ModalTwoHeader title={title} />
<ModalTwoContent>
{alertText && (
<Alert className="mb-4" type="error">
{alertText}
</Alert>
)}
{children}
</ModalTwoContent>
<ModalTwoFooter>
<Button type="reset" onClick={onClose}>
{cancelText}
</Button>
<ErrorButton type="button" disabled={disabled} onClick={handleSubmit}>
{submitText}
</ErrorButton>
</ModalTwoFooter>
</ModalTwo>
);
};
| 7,530
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Core/NavigationProvider.tsx
|
import type { FC } from 'react';
import { createContext, useCallback, useContext, useMemo } from 'react';
import { useHistory, useRouteMatch } from 'react-router-dom';
import { useFilters } from '@proton/pass/hooks/useFilters';
import type { ItemFilters, Maybe, MaybeNull, SelectedItem } from '@proton/pass/types';
import { getItemRoute, getLocalPath, getTrashRoute } from './routing';
type NavigateOptions = { mode?: 'push' | 'replace'; search?: string };
type ItemSelectOptions = NavigateOptions & { view?: 'edit' | 'view'; inTrash?: boolean };
type NavigationContextValue = {
/** Parsed search parameter filters. */
filters: ItemFilters;
/** Flag indicating wether we are currently on an empty route */
matchEmpty: boolean;
/** Flag indicating wether we are currently on a settings route */
matchSettings: boolean;
/** Flag indicating wether we are currently on a trash route */
matchTrash: boolean;
/** Selected item's `itemId` and `shareId` parsed from URL */
selectedItem: Maybe<SelectedItem>;
/** Wraps react-router-dom's `useHistory` and provides extra options
* to chose the navigation mode (push, replace) and wether you want to
* push new search parameters to the target path. */
navigate: (pathname: string, options?: NavigateOptions) => void;
/** Navigates to an item view. By default it will go to the `view` screen,
* but this can be customized via options. */
selectItem: (shareId: string, itemId: string, options?: ItemSelectOptions) => void;
/** Sets the filters and updates the location's search parameters. You can pass
* an optional `pathname` argument if you want to navigate in the same call */
setFilters: (filters: Partial<ItemFilters>, pathname?: string) => void;
};
const NavigationContext = createContext<MaybeNull<NavigationContextValue>>(null);
export const NavigationProvider: FC = ({ children }) => {
const history = useHistory();
const { filters, setFilters } = useFilters();
const matchEmpty = useRouteMatch(getLocalPath('empty')) !== null;
const matchSettings = useRouteMatch(getLocalPath('settings')) !== null;
const matchTrash = useRouteMatch(getTrashRoute()) !== null;
const selectedItem = useRouteMatch<SelectedItem>(getItemRoute(':shareId', ':itemId', matchTrash))?.params;
const navigate = useCallback(
(pathname: string, options: NavigateOptions = { mode: 'push' }) =>
history[options.mode ?? 'push']({
pathname,
search: options.search ?? history.location.search,
}),
[]
);
const navigation = useMemo<NavigationContextValue>(
() => ({
filters,
matchEmpty,
matchSettings,
matchTrash,
selectedItem,
navigate,
selectItem: (shareId: string, itemId: string, options?: ItemSelectOptions) => {
const base = getItemRoute(shareId, itemId, options?.inTrash);
const view = options?.view && options.view !== 'view' ? `/${options.view}` : '';
navigate(base + view, options);
},
setFilters,
}),
[filters, matchEmpty, matchSettings, matchTrash, setFilters]
);
return <NavigationContext.Provider value={navigation}>{children}</NavigationContext.Provider>;
};
export const useNavigation = (): NavigationContextValue => useContext(NavigationContext)!;
| 7,531
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Core/PassCoreProvider.tsx
|
import type { FC } from 'react';
import { createContext, useContext, useMemo } from 'react';
import { ConfigProvider } from '@proton/components/containers/config';
import type { PassConfig } from '@proton/pass/hooks/usePassConfig';
import type { UsePeriodOtpCodeOptions } from '@proton/pass/hooks/usePeriodicOtpCode';
import type { Maybe, MaybeNull } from '@proton/pass/types';
import type { TelemetryEvent } from '@proton/pass/types/data/telemetry';
type PassCoreContextValue = {
config: PassConfig;
/** In the extension: leverage worker communication to generate
* a token. In the web-app: use the OTP utils in-place */
generateOTP: UsePeriodOtpCodeOptions['generate'];
/* Defines how the item domain image URLs should be built */
getDomainImageURL: (domain?: string) => Maybe<string>;
/** defines how a client handles external links.
* In extension, this will leverage the `browser.tabs` API
* whereas in the web-app, we can use `window.location` */
onLink: (url: string) => void;
/** Processes a telemetry event */
onTelemetry: (event: TelemetryEvent) => void;
/** Open the settings view at a particular page */
openSettings?: (page?: string) => void;
};
const PassCoreContext = createContext<MaybeNull<PassCoreContextValue>>(null);
/** The `PassCoreProvider` must be made available on all pass
* clients : it provides implementations for processes that are
* dependent on the platform. */
export const PassCoreProvider: FC<PassCoreContextValue> = ({ children, ...core }) => (
<ConfigProvider config={core.config}>
<PassCoreContext.Provider value={useMemo(() => core, [])}>{children}</PassCoreContext.Provider>
</ConfigProvider>
);
export const usePassCore = (): PassCoreContextValue => useContext(PassCoreContext)!;
| 7,532
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Core/routing.ts
|
import { authentication } from '@proton/pass/lib/auth/store';
import { type ItemType } from '@proton/pass/types';
import { getLocalIDPath } from '@proton/shared/lib/authentication/pathnameHelper';
export type ItemNewRouteParams = { type: ItemType };
/** Joins the current location search parameters to the provided path */
export const preserveSearch = (path: string) => path + location.search;
/** Appends the localID path to the provided path */
export const getLocalPath = (path: string = '') => `/${getLocalIDPath(authentication.getLocalID())}/${path}`;
export const maybeTrash = (path: string, inTrash?: boolean) => `${inTrash ? 'trash/' : ''}${path}`;
export const getTrashRoute = () => getLocalPath('trash');
/** Resolves the item route given a shareId and an itemId. */
export const getItemRoute = (shareId: string, itemId: string, trashed?: boolean) =>
getLocalPath(maybeTrash(`share/${shareId}/item/${itemId}`, trashed));
| 7,533
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Export/Exporter.tsx
|
import { useState } from 'react';
import { Field, Form, type FormikErrors, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Checkbox, useNotifications } from '@proton/components';
import { PasswordField } from '@proton/pass/components/Form/legacy/PasswordField';
import { pageMessage, sendMessage } from '@proton/pass/lib/extension/message';
import { WorkerMessageType } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { wait } from '@proton/shared/lib/helpers/promise';
import { createExportFile } from './createExportFile';
type ExportFormValues = { passphrase: string; encrypted: boolean };
const initialValues: ExportFormValues = { passphrase: '', encrypted: false };
const validateFormValues = ({ encrypted, passphrase }: ExportFormValues): FormikErrors<ExportFormValues> =>
encrypted && isEmptyString(passphrase) ? { passphrase: c('Warning').t`Passphrase is required` } : {};
export const Exporter: React.FC = () => {
const [loading, setLoading] = useState(false);
const { createNotification } = useNotifications();
const form = useFormik<ExportFormValues>({
initialValues: initialValues,
initialErrors: validateFormValues(initialValues),
validateOnChange: true,
validateOnMount: true,
validate: validateFormValues,
onSubmit: async ({ encrypted, passphrase }) => {
try {
setLoading(true);
await sendMessage.on(
pageMessage({
type: WorkerMessageType.EXPORT_REQUEST,
payload: encrypted ? { encrypted, passphrase } : { encrypted: false },
}),
async (res) => {
await wait(500);
if (res.type === 'success') {
const { filename, blob } = createExportFile(encrypted, res.data);
downloadFile(blob, filename);
createNotification({
type: 'success',
text: c('Info').t`Successfully exported all your items`,
});
} else {
throw new Error(res.error);
}
}
);
} catch (e) {
logger.warn(`[Settings::Exporter] export failed`, e);
createNotification({ type: 'error', text: c('Warning').t`An error occured while exporting your data` });
} finally {
setLoading(false);
}
},
});
return (
<FormikProvider value={form}>
<Form className="modal-two-dialog-container">
<Checkbox
checked={form.values.encrypted}
onChange={(e) => form.setFieldValue('encrypted', e.target.checked)}
className="mb-4"
>
<span>
{c('Label').t`Encrypt your ${PASS_APP_NAME} data export file`}
<span className="block color-weak text-sm">{c('Info')
.t`Export is encrypted using PGP and requires a strong passphrase.`}</span>
</span>
</Checkbox>
{form.values.encrypted ? (
<Field name="passphrase" label={c('Label').t`Passphrase`} component={PasswordField} />
) : (
<em className="block text-sm color-weak mt-2">
{c('Info')
.t`This export will be unencrypted and anyone with access to your exported file will be able to see your passwords. For security, please delete it after you are done using it.`}
</em>
)}
<Button
type="submit"
color="norm"
loading={loading}
disabled={!form.isValid || loading}
className="mt-3 w-full"
>
{c('Action').t`Export`}
</Button>
</Form>
</FormikProvider>
);
};
| 7,534
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Export/createExportFile.ts
|
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
export const createExportFile = (encrypted: boolean, data: string): { filename: string; blob: Blob } => {
const content = encrypted ? data : base64StringToUint8Array(data);
const timestamp = new Date().toISOString().split('T')[0];
return {
filename: `${PASS_APP_NAME}_export_${timestamp}.${encrypted ? 'pgp' : 'zip'}`,
blob: new Blob([content], { type: encrypted ? 'application/zip' : 'data:text/plain;charset=utf-8;' }),
};
};
| 7,535
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Field.tsx
|
import type { ComponentType, ReactNode } from 'react';
import type { FieldValidator, FieldProps as FormikFieldProps, GenericFieldHTMLAttributes } from 'formik';
import { Field as FormikField } from 'formik';
type FieldProps = GenericFieldHTMLAttributes & { name: string; validate?: FieldValidator };
type Props<T extends FormikFieldProps> = {
component: ComponentType<T>;
name: string;
children?: ReactNode;
} & Omit<T, keyof FormikFieldProps> &
FieldProps;
export const Field = <T extends FormikFieldProps>(props: Props<T>) => <FormikField {...props} />;
| 7,536
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/MaskedTextField.tsx
|
import { type RefObject, type VFC } from 'react';
import { type FactoryOpts } from 'imask/esm/masked/factory';
import noop from '@proton/utils/noop';
import { useFieldMask } from '../../../hooks/useFieldMask';
import { FieldBox, type FieldBoxProps } from './Layout/FieldBox';
import { BaseTextField, type BaseTextFieldProps } from './TextField';
export type MaskedTextFieldProps = FieldBoxProps &
BaseTextFieldProps & {
mask: FactoryOpts;
};
export const MaskedTextField: VFC<MaskedTextFieldProps> = (props) => {
const { actions, actionsContainerClassName, className, icon, mask, ...rest } = props;
const { inputRef, maskedValue } = useFieldMask(props, mask);
return (
<FieldBox
actions={actions}
actionsContainerClassName={actionsContainerClassName}
className={className}
icon={icon}
>
<BaseTextField
{...rest}
field={{
...props.field,
onChange: noop,
value: maskedValue,
}}
ref={inputRef as RefObject<HTMLInputElement>}
/>
</FieldBox>
);
};
| 7,537
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/PasswordField.scss
|
@import '~@proton/styles/scss/proton-pass';
.pass-password-field--input::placeholder {
font-family: var(--optional-font-family, 'Inter', #{$fallback-fonts});
}
| 7,538
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/PasswordField.tsx
|
import { type VFC, useCallback } from 'react';
import { PasswordGeneratorButton } from '@proton/pass/components/PasswordGenerator/PasswordGeneratorButton';
import clsx from '@proton/utils/clsx';
import { TextField, type TextFieldProps } from './TextField';
import './PasswordField.scss';
type Props = { onPasswordGenerated: (password: string) => void } & TextFieldProps;
export const PasswordField: VFC<Props> = (props) => {
const { field, form, onPasswordGenerated, ...rest } = props;
const handlePasswordGeneratorDone = useCallback(
async (password: string) => {
onPasswordGenerated?.(password);
await form.setFieldValue(field.name, password);
},
[form, field.name, onPasswordGenerated]
);
const actions =
rest.actions !== null ? (
<PasswordGeneratorButton
key="password-generator-button"
onSubmit={handlePasswordGeneratorDone}
tabIndex={-1}
/>
) : undefined;
return (
<TextField
hidden
field={field}
form={form}
{...rest}
actions={actions}
inputClassName={clsx('pass-password-field--input text-monospace', rest.inputClassName)}
/>
);
};
| 7,539
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/RadioButtonGroupField.scss
|
@import '~@proton/styles/scss/lib';
.pass-radio-group--button {
--focus-ring: var(--text-hint);
.input-button-input {
+ span {
transition:
opacity 0.12s,
outline 0.12s,
outline-offset 0.12s;
background: var(--radio-button-background);
inline-size: rem(36);
block-size: rem(36);
border: none;
&:hover {
background: var(--radio-button-background);
opacity: 0.8;
}
}
&:checked {
+ span {
outline: 2px solid var(--focus-ring);
outline-offset: 3px;
color: var(--text-norm);
}
}
}
}
.pass-radio-group--labelled-button {
input[type='radio'] {
+ div {
border-block-end: 1px solid var(--border-norm);
}
&:focus-visible {
+ div {
outline: 2px solid var(--focus-ring);
}
}
}
&:last-of-type {
input[type='radio'] + div {
border-block-end: none;
}
}
}
| 7,540
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/RadioButtonGroupField.tsx
|
import { Children, type FC, type ReactElement, type ReactNode, cloneElement } from 'react';
import { type FieldProps } from 'formik';
import { Icon, type IconName, InputButton, InputFieldTwo } from '@proton/components';
import { type InputFieldProps } from '@proton/components/components/v2/field/InputField';
import type { MaybeArray } from '@proton/pass/types';
import { type ColorRGB } from '@proton/pass/types';
import clsx from '@proton/utils/clsx';
import { useFieldControl } from '../../../hooks/useFieldControl';
import type { RadioValue } from './RadioGroupField';
import './RadioButtonGroupField.scss';
type BaseRadioProps<T> = {
checked?: boolean;
disabled?: boolean;
id?: string;
name?: string;
onChange?: (value: T) => void;
value: T;
};
type RadioButtonProps<T> = BaseRadioProps<T> & { color?: ColorRGB; icon?: IconName };
export const RadioButton = <T,>({ onChange, id, checked, value, name, color, icon }: RadioButtonProps<T>) => {
return (
<InputButton
type="radio"
id={id}
name={name}
checked={checked}
onChange={(e) => e.target.checked && onChange?.(value)}
labelProps={{
className: 'pass-radio-group--button',
style: { '--radio-button-background': color ? `rgb(${color})` : 'var(--background-weak)' },
}}
>
{icon && <Icon name={icon} size={20} />}
</InputButton>
);
};
type RadioLabelledButtonProps<T> = BaseRadioProps<T> & { children: MaybeArray<ReactNode> };
export const RadioLabelledButton = <T extends RadioValue>({
id,
name,
disabled,
value,
checked,
onChange,
children,
}: RadioLabelledButtonProps<T>) => {
return (
<label
htmlFor={id}
className={clsx([
'pass-radio-group--labelled-button w-full increase-click-surface relative',
disabled && 'opacity-50 no-pointer-events',
])}
>
<input
id={id}
type="radio"
className="radio"
name={name}
disabled={disabled}
value={value}
onChange={(e) => e.target.checked && onChange?.(value)}
/>
<div className="flex flex-align-items-center gap-x-3 py-4">
{children}
{checked && <Icon name="checkmark" size={24} color="var(--interaction-norm)" />}
</div>
</label>
);
};
type RadioButtonGroupProps<T> = {
children: ReactElement<BaseRadioProps<T>>[];
className?: string;
name: string;
onChange?: (value: T) => void;
value?: T;
};
export const RadioButtonGroup = <T extends RadioValue>(props: RadioButtonGroupProps<T>) => {
const radioButtons = Children.map(props.children, (child, id) => {
return cloneElement(child, {
checked: props.value === child.props.value,
id: `${props.name}-${id}`,
name: props.name,
onChange: props.onChange,
});
});
return <div className={clsx('flex', props.className)}>{radioButtons}</div>;
};
type RadioButtonGroupFieldProps = FieldProps & InputFieldProps<typeof RadioButtonGroup>;
export const RadioButtonGroupField: FC<RadioButtonGroupFieldProps> = ({ field, form, meta, onChange, ...props }) => {
const { error } = useFieldControl({ field, form, meta });
return (
<InputFieldTwo<typeof RadioButtonGroup>
as={RadioButtonGroup}
assistContainerClassName="hidden-empty"
error={error}
{...field}
{...props}
onChange={async (value: RadioValue) => {
onChange?.(value);
await form.setFieldValue(field.name, value);
}}
/>
);
};
| 7,541
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/RadioGroupField.tsx
|
import type { ReactNode } from 'react';
import { type FieldProps } from 'formik';
import { InputFieldTwo, Radio } from '@proton/components';
import type { InputFieldProps } from '@proton/components/components/v2/field/InputField';
import clsx from '@proton/utils/clsx';
import { useFieldControl } from '../../../hooks/useFieldControl';
export type RadioValue = string | number | readonly string[];
type RadioGroupProps<T extends RadioValue> = {
className?: string;
name: string;
value?: T;
onChange?: (value: T) => void;
options: { label: ReactNode; value: T; disabled?: boolean }[];
};
const RadioGroup = <T extends RadioValue>({ name, options, value, className, onChange }: RadioGroupProps<T>) => {
const handleChange = (value: T) => () => onChange?.(value);
return (
<>
{options.map((option, i) => (
<Radio
key={i}
id={`${name}[${i}]`}
onChange={handleChange(option.value)}
checked={value === option.value}
name={name}
className={clsx(['mr-8', 'mb-2', 'flex', 'inline-flex-vcenter', className])}
disabled={option.disabled}
>
{option.label}
</Radio>
))}
</>
);
};
type RadioGroupFieldProps<T extends RadioValue> = FieldProps & InputFieldProps<typeof RadioGroup<T>>;
export const RadioGroupField = <T extends RadioValue>({
field,
form,
meta,
onChange,
...props
}: RadioGroupFieldProps<T>) => {
const { error } = useFieldControl({ field, form, meta });
return (
<InputFieldTwo<typeof RadioGroup<T>>
as={RadioGroup}
assistContainerClassName="hidden-empty"
error={error}
{...field}
{...props}
onChange={async (value) => {
await form.setFieldValue(field.name, value);
onChange?.(value);
}}
/>
);
};
| 7,542
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/SelectField.tsx
|
import { type FC } from 'react';
import { type FieldProps } from 'formik';
import { InputFieldTwo, SelectTwo } from '@proton/components';
import { type InputFieldProps } from '@proton/components/components/v2/field/InputField';
import clsx from '@proton/utils/clsx';
import { useFieldControl } from '../../../hooks/useFieldControl';
import { FieldBox, type FieldBoxProps } from './Layout/FieldBox';
export type SelectFieldProps = FieldProps &
InputFieldProps<typeof SelectTwo> &
Omit<FieldBoxProps, 'actions' | 'actionsContainerClassName'>;
export const SelectField: FC<SelectFieldProps> = ({
className,
field,
form,
meta,
children,
icon,
loading,
onValue,
...props
}) => {
const { error } = useFieldControl({ field, form, meta });
return (
<FieldBox className={clsx('flex-align-items-center', className)} icon={icon}>
<InputFieldTwo<typeof SelectTwo>
unstyled
as={SelectTwo}
assistContainerClassName="hidden-empty"
caretIconName="chevron-down"
error={error}
labelContainerClassName="increase-click-surface color-weak m-0 text-normal text-sm"
renderSelected={loading ? () => <div className="pass-skeleton pass-skeleton--select" /> : undefined}
{...field}
{...props}
onChange={undefined}
onValue={(value: unknown) => {
onValue?.(value);
return form.setFieldValue(field.name, value);
}}
>
{children}
</InputFieldTwo>
</FieldBox>
);
};
| 7,543
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/TextField.tsx
|
import type { ForwardRefRenderFunction } from 'react';
import { type VFC, forwardRef, useState } from 'react';
import { type FieldProps } from 'formik';
import type { Input } from '@proton/atoms/Input';
import { InputFieldTwo } from '@proton/components';
import { type InputFieldProps } from '@proton/components/components/v2/field/InputField';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import clsx from '@proton/utils/clsx';
import identity from '@proton/utils/identity';
import { useFieldControl } from '../../../hooks/useFieldControl';
import { useMaxLengthLimiter } from '../../../hooks/useMaxLengthLimiter';
import { usePasteLengthLimiter } from '../../../hooks/usePasteLengthLimiter';
import { FieldBox, type FieldBoxProps } from './Layout/FieldBox';
export type BaseTextFieldProps = FieldProps &
InputFieldProps<typeof Input> & {
hidden?: boolean;
hiddenValue?: string;
lengthLimiters?: boolean;
};
const BaseTextFieldRender: ForwardRefRenderFunction<HTMLInputElement, BaseTextFieldProps> = (
{
field,
form,
meta,
hidden = false,
hiddenValue,
inputClassName,
labelContainerClassName,
lengthLimiters = false,
onKeyDown,
onFocus = identity,
onPaste,
...props
},
ref
) => {
const { onBlur, value } = field;
const { error } = useFieldControl({ field, form, meta });
const [focused, setFocused] = useState<boolean>(false);
const hide = hidden && !isEmptyString(value) && !focused;
const pasteLengthLimiter = usePasteLengthLimiter();
const maxLengthLimiter = useMaxLengthLimiter();
const defaultHiddenValue = '••••••••••••';
return (
<InputFieldTwo
unstyled
assistContainerClassName="hidden-empty"
error={error}
inputClassName={clsx('p-0 rounded-none', props.disabled ? 'color-disabled' : 'color-norm', inputClassName)}
labelContainerClassName={clsx(
'm-0 text-normal text-sm',
error ? 'color-danger' : 'color-weak',
labelContainerClassName
)}
{...props}
{...field}
onBlur={pipe(onBlur, () => setFocused(false))}
onFocus={pipe(onFocus, () => setFocused(true))}
onKeyDown={lengthLimiters && props.maxLength ? maxLengthLimiter(props.maxLength, onKeyDown) : onKeyDown}
onPaste={lengthLimiters && props.maxLength ? pasteLengthLimiter(props.maxLength, onPaste) : onPaste}
ref={ref}
type="text"
value={hide ? hiddenValue ?? defaultHiddenValue : value}
/>
);
};
export const BaseTextField = forwardRef(BaseTextFieldRender);
export type TextFieldProps = FieldBoxProps & BaseTextFieldProps;
export const TextField: VFC<TextFieldProps> = (props) => {
const { actions, actionsContainerClassName, className, icon, ...rest } = props;
return (
<FieldBox
actions={actions}
actionsContainerClassName={actionsContainerClassName}
className={className}
icon={icon}
>
<BaseTextField {...rest} />
</FieldBox>
);
};
| 7,544
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/TextareaField.tsx
|
import type { ForwardRefRenderFunction } from 'react';
import { type VFC, forwardRef, useEffect, useMemo, useRef, useState } from 'react';
import { type FieldProps } from 'formik';
import { InputFieldTwo, TextAreaTwo } from '@proton/components';
import { type InputFieldProps } from '@proton/components/components/v2/field/InputField';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import clsx from '@proton/utils/clsx';
import { useFieldControl } from '../../../hooks/useFieldControl';
import { useMaxLengthLimiter } from '../../../hooks/useMaxLengthLimiter';
import { usePasteLengthLimiter } from '../../../hooks/usePasteLengthLimiter';
import { FieldBox, type FieldBoxProps } from './Layout/FieldBox';
export type BaseTextAreaFieldProps = FieldProps & InputFieldProps<typeof TextAreaTwo>;
const DEFAULT_MIN_ROWS = 1;
const DEFAULT_MAX_ROWS = 5;
const BaseTextAreaFieldRender: ForwardRefRenderFunction<HTMLTextAreaElement, BaseTextAreaFieldProps> = (
{ className, form, field, labelContainerClassName, meta, onKeyDown, onPaste, ...props },
ref
) => {
const { error } = useFieldControl({ form, field, meta });
const pasteLengthLimiter = usePasteLengthLimiter();
const maxLengthLimiter = useMaxLengthLimiter();
const { value } = field;
const { minRows, rows } = props;
/* the nested `useAutoGrow` doesn't support initial row resolution
* on initial mount - we resort to a dynamic `minRows` prop */
const dynamicMinRows = useMemo(
() => Math.max(minRows ?? DEFAULT_MIN_ROWS, Math.min(value.split('\n').length, rows ?? DEFAULT_MAX_ROWS)),
[minRows, rows, value]
);
return (
<InputFieldTwo
as={TextAreaTwo}
ref={ref}
autoGrow
unstyled
assistContainerClassName="hidden-empty"
className={clsx(
'border-none flex p-0 resize-none',
props.disabled ? 'color-disabled' : 'color-norm',
className
)}
error={error}
labelContainerClassName={clsx(
'm-0 text-normal text-sm',
error ? 'color-danger' : 'color-weak',
labelContainerClassName
)}
rows={DEFAULT_MAX_ROWS}
{...field}
{...props}
minRows={dynamicMinRows}
onPaste={props.maxLength ? pasteLengthLimiter(props.maxLength, onPaste) : onPaste}
onKeyDown={props.maxLength ? maxLengthLimiter(props.maxLength, onKeyDown) : onKeyDown}
/>
);
};
export const BaseTextAreaField = forwardRef(BaseTextAreaFieldRender);
export const BaseMaskedTextAreaField: VFC<BaseTextAreaFieldProps> = ({ form, field, ...rest }) => {
const { value } = field;
const [masked, setMasked] = useState<boolean>(true);
const ref = useRef<HTMLTextAreaElement>(null);
const isEmpty = isEmptyString(value);
useEffect(() => {
if (!masked) {
setTimeout(() => ref?.current?.scrollIntoView({ behavior: 'smooth' }), 50);
}
}, [masked]);
const maskedValue = !masked || isEmpty ? value : '••••••••••••••••';
return (
<BaseTextAreaField
className={clsx(!isEmpty && masked && 'text-monospace')}
onFocus={() => setMasked(false)}
onBlur={pipe(field.onBlur, () => setMasked(true))}
form={form}
field={field}
ref={ref}
rows={masked ? DEFAULT_MIN_ROWS : rest.rows}
value={maskedValue}
{...rest}
/>
);
};
export type TextAreaFieldProps = FieldBoxProps & BaseTextAreaFieldProps;
export const TextAreaField: VFC<TextAreaFieldProps> = ({
actions,
actionsContainerClassName,
className,
icon,
...props
}) => (
<FieldBox actions={actions} actionsContainerClassName={actionsContainerClassName} className={className} icon={icon}>
<BaseTextAreaField {...props} />
</FieldBox>
);
| 7,545
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/TitleField.tsx
|
import { type VFC } from 'react';
import type { BaseTextFieldProps } from './TextField';
import { BaseTextField, TextField, type TextFieldProps } from './TextField';
export const BaseTitleField: VFC<BaseTextFieldProps> = (props) => (
<BaseTextField inputClassName="text-2xl text-bold" {...props} />
);
export const TitleField: VFC<TextFieldProps> = (props) => <TextField inputClassName="text-2xl text-bold" {...props} />;
| 7,546
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/UrlGroupField.tsx
|
import type { ReactNode } from 'react';
import { type KeyboardEvent, useRef } from 'react';
import { FieldArray, type FormikContextType, type FormikErrors } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, InputFieldTwo } from '@proton/components/';
import type { UrlGroupValues, UrlItem } from '@proton/pass/types';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { isValidURL } from '@proton/pass/utils/url/is-valid-url';
import { FieldBox } from './Layout/FieldBox';
export type UrlGroupProps<V extends UrlGroupValues = UrlGroupValues> = {
form: FormikContextType<V>;
renderExtraActions?: (helpers: {
handleRemove: (idx: number) => () => void;
handleAdd: (url: string) => void;
handleReplace: (idx: number) => (url: string) => void;
}) => ReactNode;
};
export const createNewUrl = (url: string) => ({ id: uniqueId(), url: isValidURL(url).valid ? url : '' });
export const UrlGroupField = <T extends UrlGroupValues>({ form, renderExtraActions }: UrlGroupProps<T>) => {
const inputRef = useRef<HTMLInputElement>(null);
const { values, errors, handleChange } = form;
const onKeyEnter = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
event.preventDefault(); /* avoid submitting the form */
event.currentTarget.blur();
}
};
const hasURL = Boolean(values.url) || values.urls.some(({ url }) => !isEmptyString(url));
return (
<FieldBox icon="earth">
<label
htmlFor="next-url-field"
className="field-two-label text-sm"
style={{ color: hasURL ? 'var(--text-weak)' : 'inherit' }}
>
{c('Label').t`Websites`}
</label>
<FieldArray
name="urls"
render={(helpers) => {
const handleRemove = helpers.handleRemove;
const handleReplace = (index: number) => (url: string) =>
helpers.replace(index, { id: values.urls[index].id, url });
const handleAdd = (url: string) => {
helpers.push(createNewUrl(isValidURL(url).url));
return form.setFieldValue('url', '');
};
return (
<>
<ul className="unstyled m-0 mb-1">
{values.urls.map(({ url, id }, index) => (
<li key={id} className="flex flex-align-items-center flex-nowrap">
<InputFieldTwo
error={(errors.urls?.[index] as FormikErrors<UrlItem>)?.url}
onValue={handleReplace(index)}
onBlur={() => handleReplace(index)(isValidURL(url).url)}
value={url}
unstyled
assistContainerClassName="hidden-empty"
inputClassName="color-norm p-0 rounded-none"
placeholder="https://"
onKeyDown={onKeyEnter}
/>
<Button
icon
pill
className="flex-item-noshrink ml-2"
color="weak"
onClick={handleRemove(index)}
shape="ghost"
size="small"
title={c('Action').t`Delete`}
>
<Icon name="cross" size={20} className="color-weak" />
</Button>
</li>
))}
</ul>
<InputFieldTwo
unstyled
id="next-url-field"
assistContainerClassName="hidden-empty"
inputClassName="color-norm p-0 rounded-none"
placeholder="https://"
name="url"
value={values.url}
error={errors.url}
onChange={handleChange}
onBlur={() => values.url && !errors.url && handleAdd(values.url)}
onKeyDown={onKeyEnter}
ref={inputRef}
/>
<hr className="mt-3 mb-1" />
{renderExtraActions?.({ handleAdd, handleRemove, handleReplace })}
<Button
icon
color="norm"
shape="ghost"
size="small"
title={c('Action').t`Add`}
className="flex flex-align-items-center gap-1"
onClick={() => handleAdd(values.url).then(() => inputRef.current?.focus())}
>
<Icon name="plus" /> {c('Action').t`Add`}
</Button>
</>
);
}}
/>
</FieldBox>
);
};
| 7,547
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/VaultSelectField.tsx
|
import { type VFC, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { c } from 'ttag';
import { Icon, Option } from '@proton/components';
import type { VaultIconName } from '@proton/pass/components/Vault/VaultIcon';
import { VaultIcon } from '@proton/pass/components/Vault/VaultIcon';
import { selectVaultLimits, selectWritableVaults } from '@proton/pass/store/selectors';
import { type Maybe } from '@proton/pass/types';
import { VaultColor } from '@proton/pass/types/protobuf/vault-v1';
import { prop } from '@proton/pass/utils/fp/lens';
import { notIn } from '@proton/pass/utils/fp/predicates';
import { SelectField, type SelectFieldProps } from './SelectField';
type ExtraVaultSelectOption = { value: string; title: string; icon: VaultIconName; color?: VaultColor };
type SelectedVaultOption = { title: string; icon?: VaultIconName; color?: VaultColor };
type VaultSelectFieldProps = Omit<SelectFieldProps, 'children'> & {
extraOptions?: ExtraVaultSelectOption[];
excludeOptions?: string[];
placeholder?: string;
};
export const VaultSelectField: VFC<VaultSelectFieldProps> = ({
extraOptions = [],
excludeOptions = [],
placeholder,
...props
}) => {
const vaults = useSelector(selectWritableVaults);
const writableShareIds = useSelector(selectWritableVaults).map(prop('shareId'));
const { didDowngrade } = useSelector(selectVaultLimits);
const selectedId = props.field.value;
const selectedVault = useMemo<Maybe<SelectedVaultOption>>(() => {
const vaultMatch = vaults.find(({ shareId }) => shareId === selectedId);
const extraMatch = extraOptions.find(({ value }) => value === selectedId);
if (vaultMatch || extraMatch) {
return {
title: vaultMatch?.content.name ?? extraMatch?.title!,
icon: vaultMatch?.content.display.icon ?? extraMatch?.icon!,
color: vaultMatch?.content.display.color ?? extraMatch?.color!,
};
}
}, [selectedId, vaults]);
return (
<SelectField
{...props}
icon={<VaultIcon icon={selectedVault?.icon} color={selectedVault?.color} size={20} background />}
renderSelected={() =>
selectedVault?.title ?? (
<span className="color-weak">{placeholder ?? c('Placeholder').t`Pick a vault`}</span>
)
}
>
{vaults
.filter(({ shareId }) => notIn(excludeOptions)(shareId))
.map(({ shareId, content, shared }) => {
const selected = selectedId === shareId;
return (
<Option
key={shareId}
value={shareId}
title={content.name}
/* only allow selecting writable vaults if a downgrade was detected */
disabled={didDowngrade && !writableShareIds.includes(shareId)}
>
<div className="flex gap-x-3 flex-align-items-center">
<VaultIcon
icon={content.display.icon}
color={content.display.color}
size={16}
highlighted={selected}
/>
<span className="flex-item-fluid text-ellipsis">{content.name}</span>
{shared && (
<Icon
name="users"
color={`var(${selected ? '--interaction-norm-contrast' : '--text-weak'})`}
size={16}
/>
)}
</div>
</Option>
);
})
.concat(
...extraOptions.map(({ value, title, icon, color }) => (
<Option key={value} value={value} title={title}>
<div className="flex gap-x-3 flex-align-items-center">
<VaultIcon
icon={icon}
size={16}
color={selectedId ? VaultColor.COLOR_CUSTOM : color}
highlighted={selectedId === value}
/>
<span className="flex-item-fluid text-ellipsis">{title}</span>
</div>
</Option>
))
)}
</SelectField>
);
};
| 7,548
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/ClickToCopy.tsx
|
import type { MouseEvent } from 'react';
import { type FC, useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { useCopyToClipboard } from '@proton/pass/hooks/useCopyToClipboard';
import clsx from '@proton/utils/clsx';
export type ClickToCopyProps = { className?: string; value?: string };
export const ClickToCopy: FC<ClickToCopyProps> = ({ className, children, value = '' }) => {
const ref = useRef<HTMLDivElement>(null);
const copyToClipboard = useCopyToClipboard();
const [selection, setSelection] = useState(false);
const handleClick = (evt: MouseEvent) => {
if (selection) evt.preventDefault();
else if (value) void copyToClipboard(value);
};
useEffect(() => {
const onSelectionChange = () => {
const selection = window.getSelection();
setSelection(selection !== null && selection.toString().length > 0);
};
document.addEventListener('selectionchange', onSelectionChange);
return () => document.removeEventListener('selectionchange', onSelectionChange);
}, []);
return (
/* disabling `prefer-tag-over-role` as we cannot use a
* `button` element here - children may include buttons and
* this would lead to invalid DOM structure */
/* eslint-disable-next-line jsx-a11y/prefer-tag-over-role */
<div
ref={ref}
className={clsx('cursor-pointer overflow-hidden', className)}
onKeyDown={(evt) => evt.key === 'Enter' && copyToClipboard(value)}
onClick={handleClick}
tabIndex={0}
role="button"
>
<span className="sr-only"> {c('Info').t`Press Enter to copy`}</span>
{children}
</div>
);
};
| 7,549
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/ExtraFieldsControl.tsx
|
import { type VFC, useCallback } from 'react';
import { useSelector } from 'react-redux';
import { selectExtraFieldLimits } from '@proton/pass/store/selectors';
import type { UnsafeItemExtraField } from '@proton/pass/types';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { TextAreaReadonly } from '../../legacy/TextAreaReadonly';
import { getExtraFieldOption } from '../ExtraFieldGroup/ExtraField';
import { FieldsetCluster } from '../Layout/FieldsetCluster';
import { OTPValueControl } from './OTPValueControl';
import { UpgradeControl } from './UpgradeControl';
import { ValueControl } from './ValueControl';
type ExtraFieldsControlProps = {
extraFields: UnsafeItemExtraField[];
itemId: string;
shareId: string;
};
export const ExtraFieldsControl: VFC<ExtraFieldsControlProps> = ({ extraFields, itemId, shareId }) => {
const { needsUpgrade } = useSelector(selectExtraFieldLimits);
const getControlByType = useCallback(
({ fieldName, type, data }: UnsafeItemExtraField, index: number) => {
const { icon } = getExtraFieldOption(type);
const key = `${index}-${fieldName}`;
if (needsUpgrade) {
return <UpgradeControl icon={icon} key={key} label={fieldName} />;
}
switch (type) {
case 'totp':
return isEmptyString(data.totpUri) ? (
<ValueControl icon={icon} key={key} label={fieldName} value={undefined} />
) : (
<OTPValueControl
key={key}
label={fieldName}
payload={{
index,
itemId,
shareId,
totpUri: data.totpUri,
type: 'extraField',
}}
/>
);
case 'hidden':
case 'text':
return (
<ValueControl
clickToCopy
as={TextAreaReadonly}
key={key}
hidden={type === 'hidden'}
icon={icon}
label={fieldName}
value={data.content}
/>
);
}
},
[itemId, shareId]
);
return (
<FieldsetCluster mode="read" as="div">
{extraFields.map((extraField, index) => getControlByType(extraField, index))}
</FieldsetCluster>
);
};
| 7,550
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/MaskedValueControl.tsx
|
import type { ElementType } from 'react';
import { type FactoryArg } from 'imask/esm/masked/factory';
import { pipe } from 'imask/esm/masked/pipe';
import { ValueControl, type ValueControlProps } from './ValueControl';
export type MaskedValueControlProps<E extends ElementType> = ValueControlProps<E> & {
mask: FactoryArg;
};
export const MaskedValueControl = <E extends ElementType>({ mask, ...props }: MaskedValueControlProps<E>) => {
const { value } = props;
const maskedValue = value ? pipe(value, mask) : '';
return <ValueControl {...props} value={maskedValue} />;
};
| 7,551
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/OTPValueControl.tsx
|
import { type VFC } from 'react';
import { c } from 'ttag';
import { usePassCore } from '@proton/pass/components/Core/PassCoreProvider';
import { OTPDonut } from '@proton/pass/components/Otp/OTPDonut';
import { OTPValue } from '@proton/pass/components/Otp/OTPValue';
import { usePeriodicOtpCode } from '@proton/pass/hooks/usePeriodicOtpCode';
import { type OtpRequest } from '@proton/pass/types';
import { ValueControl } from './ValueControl';
type Props = { label?: string; payload: OtpRequest };
/* This component handles the period otp code generation
* to avoid cluttering the render cycle of a component in
* need of the OTP code generation as it involves alot of
* re-rendering. eg: we do not want to re-render `Login.view`
* everytime the OTP countdown updates */
export const OTPValueControl: VFC<Props> = ({ label, payload }) => {
const { generateOTP } = usePassCore();
const [otp, percent] = usePeriodicOtpCode({ generate: generateOTP, payload });
return (
<ValueControl
clickToCopy
icon="lock"
value={otp?.token ?? ''}
label={label ?? c('Label').t`2FA token (TOTP)`}
actions={<OTPDonut enabled={otp !== null} percent={percent} period={otp?.period} />}
>
<OTPValue code={otp?.token ?? ''} />
</ValueControl>
);
};
| 7,552
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/UpgradeControl.tsx
|
import { type VFC } from 'react';
import { type IconName } from '@proton/components/components';
import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton';
import { ValueControl } from './ValueControl';
type UpgradeControlProps = {
icon: IconName;
label: string;
};
export const UpgradeControl: VFC<UpgradeControlProps> = ({ icon, label }) => (
<ValueControl icon={icon} label={label}>
<UpgradeButton inline />
</ValueControl>
);
| 7,553
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/ValueControl.scss
|
@import '~@proton/styles/scss/lib';
.pass-value-control {
&--value {
min-block-size: rem(20);
& > *:last-child {
margin-block-end: 0;
}
}
&--interactive {
transition: background-color 250ms;
&:hover {
background-color: var(--background-weak);
}
/*
* remove hard coded color value -> consider 'interactive background` colors in theme
*/
&:active {
background-color: #27273d;
}
&:focus-visible {
z-index: 1;
outline: 1px solid var(--interaction-norm);
}
}
}
| 7,554
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Control/ValueControl.tsx
|
import type { ComponentType, ElementType } from 'react';
import { type ReactNode, useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, type IconName } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { FieldBox, type FieldBoxProps } from '../Layout/FieldBox';
import type { ClickToCopyProps } from './ClickToCopy';
import { ClickToCopy } from './ClickToCopy';
import './ValueControl.scss';
const isIntrinsicElement = <E extends ElementType>(c: E) => typeof c === 'string' || typeof c === 'symbol';
export type ValueControlProps<E extends ElementType> = Omit<FieldBoxProps, 'icon'> & {
as?: E;
children?: E extends ComponentType<infer U> ? (U extends { children?: infer C } ? C : never) : ReactNode;
clickToCopy?: boolean;
error?: boolean;
ellipsis?: boolean;
extra?: ReactNode;
hidden?: boolean;
hiddenValue?: string;
icon?: IconName;
label: string;
loading?: boolean;
value?: string;
valueClassName?: string;
};
const HideButton = ({ hidden, onClick }: { hidden: boolean; onClick: () => void }) => (
<Button
icon
pill
color="weak"
onClick={onClick}
size="medium"
shape="solid"
title={hidden ? c('Action').t`Show` : c('Action').t`Hide`}
>
<Icon size={20} name={hidden ? 'eye' : 'eye-slash'} />
</Button>
);
/* When passed both children and a value prop:
* children will be rendered, value will be passed
* to ClickToCopy */
export const ValueControl = <E extends ElementType = 'div'>({
actions,
actionsContainerClassName,
as,
children,
clickToCopy = false,
ellipsis = true,
error = false,
extra,
hidden = false,
hiddenValue,
icon,
label,
loading = false,
value,
valueClassName,
}: ValueControlProps<E>) => {
/* we're leveraging type-safety at the consumer level - we're recasting
* the `as` prop as a generic `ElementType` to avoid switching over all
* possible sub-types. Trade-off is being extra careful with the children
* the `ValueContainer` can accept */
const ValueContainer = (as ?? 'div') as ElementType;
const intrinsicEl = isIntrinsicElement(ValueContainer);
const [hide, setHide] = useState(hidden);
const defaultHiddenValue = '••••••••••••';
const displayValue = useMemo(() => {
/* intrinsinc elements support nesting custom DOM structure */
if (intrinsicEl && loading) return <div className="pass-skeleton pass-skeleton--value" />;
if (intrinsicEl && !value && !children) return <div className="color-weak">{c('Info').t`None`}</div>;
if (hide) return hiddenValue ?? defaultHiddenValue;
/* if children are passed: display them - when working with
* a `ValueContainer` component, we leverage the inherited prop
* type-safety */
if (children) return children;
/* if no children provided: fallback to value which is always
* a valid "string" ReactNode */
return value ?? '';
}, [value, children, loading, hide, intrinsicEl]);
const canCopy = clickToCopy && value;
const MaybeClickToCopy: ElementType<ClickToCopyProps> = canCopy ? ClickToCopy : 'div';
return (
<MaybeClickToCopy
className={clsx(canCopy && 'pass-value-control--interactive', !loading && error && 'border-danger')}
{...(canCopy ? { value } : {})}
>
<FieldBox
actions={
hidden && value
? [<HideButton hidden={hide} onClick={() => setHide((prev) => !prev)} />, actions ?? []].flat()
: actions
}
actionsContainerClassName={actionsContainerClassName}
icon={icon}
>
<div className="color-weak text-sm">{label}</div>
<ValueContainer
className={clsx(
'pass-value-control--value m-0 p-0 cursor-pointer',
ellipsis && 'text-ellipsis',
valueClassName
)}
children={displayValue}
/>
{extra}
</FieldBox>
</MaybeClickToCopy>
);
};
| 7,555
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/ExtraFieldGroup/AddExtraFieldDropdown.tsx
|
import { type VFC } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Dropdown, DropdownMenu, Icon, usePopperAnchor } from '@proton/components';
import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton';
import type { ExtraFieldType } from '@proton/pass/types';
import { getExtraFieldOptions } from './ExtraField';
type CustomFieldsDropdownProps = { onAdd: (type: ExtraFieldType) => void };
export const AddExtraFieldDropdown: VFC<CustomFieldsDropdownProps> = ({ onAdd }) => {
const { anchorRef, isOpen, close, toggle } = usePopperAnchor<HTMLButtonElement>();
const handleAddClick = (type: ExtraFieldType) => {
onAdd(type);
setTimeout(() => anchorRef?.current?.scrollIntoView({ behavior: 'smooth' }), 50);
};
return (
<>
<Button
pill
className="flex flex-align-items-center mb-2"
color="norm"
onClick={toggle}
ref={anchorRef}
shape="ghost"
>
<Icon className="mr-2" name="plus" />
<span className="line-height-1">{c('Action').t`Add more`}</span>
</Button>
<Dropdown anchorRef={anchorRef} isOpen={isOpen} onClose={close} originalPlacement="top-start">
<DropdownMenu>
{Object.entries(getExtraFieldOptions()).map(([type, { icon, label }]) => (
<DropdownMenuButton
key={type}
onClick={() => handleAddClick(type as ExtraFieldType)}
size="small"
icon={icon}
label={label}
/>
))}
</DropdownMenu>
</Dropdown>
</>
);
};
| 7,556
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/ExtraFieldGroup/ExtraField.tsx
|
import type { ChangeEvent, VFC } from 'react';
import type { FieldInputProps, FormikErrors } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import type { IconName } from '@proton/components/components';
import { Icon } from '@proton/components/components';
import type { ExtraFieldType, UnsafeItemExtraField } from '@proton/pass/types';
import { partialMerge } from '@proton/pass/utils/object/merge';
import clsx from '@proton/utils/clsx';
import type { FieldBoxProps } from '../Layout/FieldBox';
import { FieldBox } from '../Layout/FieldBox';
import type { BaseTextFieldProps } from '../TextField';
import { BaseTextField } from '../TextField';
import type { BaseTextAreaFieldProps } from '../TextareaField';
import { BaseMaskedTextAreaField, BaseTextAreaField } from '../TextareaField';
type ExtraFieldOption = {
icon: IconName;
label: string;
placeholder: string;
};
type ExtraFieldError<T extends ExtraFieldType> = FormikErrors<UnsafeItemExtraField<T>>;
export type ExtraFieldProps = FieldBoxProps &
Omit<BaseTextFieldProps & BaseTextAreaFieldProps, 'field' | 'placeholder' | 'error'> & {
type: ExtraFieldType;
field: FieldInputProps<UnsafeItemExtraField>;
error?: ExtraFieldError<ExtraFieldType>;
touched?: boolean;
autoFocus?: boolean;
onDelete: () => void;
};
export const getExtraFieldOptions = (): Record<ExtraFieldType, ExtraFieldOption> => ({
text: {
icon: 'text-align-left',
label: c('Label').t`Text`,
placeholder: c('Placeholder').t`Add text`,
},
totp: {
icon: 'lock',
label: c('Label').t`2FA secret key (TOTP)`,
placeholder: c('Placeholder').t`Add 2FA secret key`,
},
hidden: {
icon: 'eye-slash',
// translator: label for a field that is hidden. Singular only.
label: c('Label').t`Hidden`,
placeholder: c('Placeholder').t`Add hidden text`,
},
});
export const getExtraFieldOption = (type: ExtraFieldType) => getExtraFieldOptions()[type];
const DeleteButton: VFC<{ onDelete: () => void }> = ({ onDelete }) => (
<Button icon pill color="weak" onClick={onDelete} shape="solid" size="medium" title={c('Action').t`Delete`}>
<Icon name="cross" size={20} />
</Button>
);
export const ExtraFieldComponent: VFC<ExtraFieldProps> = (props) => {
const { className, field, onDelete, type, error, touched, autoFocus, ...rest } = props;
const { icon, placeholder } = getExtraFieldOption(type);
const onChangeHandler =
(merge: (evt: ChangeEvent<HTMLInputElement>, field: UnsafeItemExtraField) => UnsafeItemExtraField) =>
(evt: ChangeEvent<HTMLInputElement>) => {
void props.form.setFieldValue(field.name, merge(evt, props.field.value));
};
const fieldValueEmpty = Object.values(field.value.data).every((value) => !value);
return (
<FieldBox actions={[<DeleteButton onDelete={onDelete} />]} className={className} icon={icon}>
<BaseTextField
inputClassName={clsx(
'text-sm',
!fieldValueEmpty && 'color-weak',
touched && error?.fieldName && 'placeholder-danger'
)}
placeholder={c('Label').t`Field name`}
autoFocus={autoFocus}
field={{
...field,
value: field.value.fieldName,
onChange: onChangeHandler((evt, values) => partialMerge(values, { fieldName: evt.target.value })),
}}
{...rest}
/>
{(() => {
switch (field.value.type) {
case 'text':
case 'hidden': {
const FieldComponent =
field.value.type === 'hidden' ? BaseMaskedTextAreaField : BaseTextAreaField;
const fieldError = error as ExtraFieldError<'text' | 'hidden'>;
return (
<FieldComponent
placeholder={placeholder}
error={touched && (error?.fieldName || fieldError?.data?.content)}
field={{
...field,
value: field.value.data.content,
onChange: onChangeHandler((evt, values) =>
partialMerge(values, { data: { content: evt.target.value } })
),
}}
{...rest}
/>
);
}
case 'totp': {
const fieldError = error as ExtraFieldError<'totp'>;
return (
<BaseTextField
hidden
placeholder={placeholder}
error={touched && (error?.fieldName || fieldError?.data?.totpUri)}
field={{
...field,
value: field.value.data.totpUri,
onChange: onChangeHandler((evt, values) =>
partialMerge(values, { data: { totpUri: evt.target.value } })
),
}}
{...rest}
/>
);
}
}
})()}
</FieldBox>
);
};
| 7,557
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/ExtraFieldGroup/ExtraFieldGroup.tsx
|
import { useState } from 'react';
import { useSelector } from 'react-redux';
import type { FormikErrors, FormikProps } from 'formik';
import { FieldArray } from 'formik';
import { selectExtraFieldLimits } from '@proton/pass/store/selectors';
import type { ExtraFieldGroupValues, ExtraFieldType, UnsafeItemExtraField } from '@proton/pass/types';
import { Field } from '../Field';
import { FieldsetCluster } from '../Layout/FieldsetCluster';
import { AddExtraFieldDropdown } from './AddExtraFieldDropdown';
import { ExtraFieldComponent } from './ExtraField';
export type ExtraFieldGroupProps<V extends ExtraFieldGroupValues> = { form: FormikProps<V> };
const getNewField = <T extends ExtraFieldType>(type: T): UnsafeItemExtraField => {
switch (type) {
case 'text':
case 'hidden':
return { type, fieldName: '', data: { content: '' } };
case 'totp':
return { type, fieldName: '', data: { totpUri: '' } };
default:
throw new Error('Unsupported field type');
}
};
export const ExtraFieldGroup = <T extends ExtraFieldGroupValues>({ form }: ExtraFieldGroupProps<T>) => {
const [autofocusIndex, setAutofocusIndex] = useState<number>();
const { needsUpgrade } = useSelector(selectExtraFieldLimits);
return (
<FieldArray
name="extraFields"
render={(helpers) => {
const addCustomField = (type: ExtraFieldType) => {
helpers.push(getNewField(type));
setAutofocusIndex(form.values.extraFields.length);
};
return (
<>
{Boolean(form.values.extraFields.length) && (
<FieldsetCluster>
{form.values.extraFields.map(({ type }, index) => (
<Field
key={index}
component={ExtraFieldComponent}
onDelete={() => helpers.remove(index)}
name={`extraFields[${index}]`}
type={type}
/* Formik TS type are wrong for FormikTouched */
touched={(form.touched.extraFields as unknown as boolean[])?.[index]}
error={form.errors.extraFields?.[index] as FormikErrors<UnsafeItemExtraField>}
autoFocus={autofocusIndex === index} /* focus on add only */
/>
))}
</FieldsetCluster>
)}
{!needsUpgrade && <AddExtraFieldDropdown onAdd={addCustomField} />}
</>
);
}}
/>
);
};
| 7,558
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Layout/FieldBox.scss
|
.pass-field-box {
&:not(.pass-input-group--no-focus) {
&::before {
content: '';
border: 1px solid transparent;
position: absolute;
inset: -1px;
z-index: 1;
pointer-events: none;
transition: 0.15s ease;
}
&:has(
input:focus-visible,
textarea:focus-visible,
button[aria-expanded='false']:focus,
button[aria-expanded='true']
) {
&::before {
border-color: var(--interaction-norm);
}
}
&:has(input:placeholder-shown, textarea:placeholder-shown) {
label,
label > span {
color: var(--text-norm);
}
}
}
&:has(button[aria-expanded='false']:focus) button {
outline: none;
}
.field-two-container button svg {
position: relative;
inset-block-end: var(--space-2);
}
}
| 7,559
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Layout/FieldBox.tsx
|
import { Children, type FC, type ReactElement, cloneElement, isValidElement } from 'react';
import { Icon, type IconName } from '@proton/components';
import type { MaybeArray } from '@proton/pass/types';
import clsx from '@proton/utils/clsx';
import './FieldBox.scss';
export type FieldBoxProps = {
actions?: MaybeArray<ReactElement>;
actionsContainerClassName?: string;
className?: string;
icon?: IconName | ReactElement;
};
const stopOnClickPropagation = (nodes: MaybeArray<ReactElement>): MaybeArray<ReactElement> =>
Children.map(nodes, (node: ReactElement, index) => {
const props = node.props as any;
return isValidElement(node)
? cloneElement<any>(node, {
key: node.key || index,
...(props?.onClick
? {
onClick: (e: MouseEvent) => {
e.stopPropagation();
props?.onClick?.(e);
},
}
: {}),
children: props?.children ? stopOnClickPropagation(props?.children) : undefined,
})
: node;
});
export const FieldBox: FC<FieldBoxProps> = (props) => {
const { className, actions, actionsContainerClassName, children, icon } = props;
const isCoreIcon = typeof icon == 'string';
const iconEl = isCoreIcon ? <Icon name={icon} size={20} /> : icon;
return (
<div className={clsx('pass-field-box flex flex-nowrap flex-align-items-start px-4 py-3', className)}>
{icon && (
<span
className={clsx(
'flex flex-justify-center flex-align-items-center flex-item-noshrink pr-4',
isCoreIcon && 'mt-2'
)}
style={{ color: 'var(--fieldset-cluster-icon-color)' }}
>
{iconEl}
</span>
)}
<div className="w-full">{children}</div>
{actions && (
<span className={clsx('flex-item-noshrink ml-3', actionsContainerClassName)}>
{stopOnClickPropagation(actions)}
</span>
)}
</div>
);
};
| 7,560
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Layout/FieldsetCluster.scss
|
.pass-fieldset-cluster {
--fieldset-cluster-icon-color: var(--interaction-norm);
&--write {
--fieldset-cluster-icon-color: var(--field-placeholder-color);
}
// Set min-width: 0 on the parent of the flexbox to enable text-ellipsis
// and prevent content overflow. This allows the flex item to shrink to its
// content size, which is especially helpful when the item has a fixed or
// percentage-based width that causes issues with the Flexbox layout.
min-inline-size: 0;
}
.pass-fieldset-cluster > * {
border: 1px solid var(--border-norm);
margin-block-start: -1px;
position: relative;
&:first-child,
&:first-child::before {
border-start-start-radius: var(--border-radius-xl) !important;
border-start-end-radius: var(--border-radius-xl) !important;
border-end-start-radius: 0 !important;
border-end-end-radius: 0 !important;
}
&:last-child,
&:last-child::before {
border-start-start-radius: 0 !important;
border-start-end-radius: 0 !important;
border-end-start-radius: var(--border-radius-xl) !important;
border-end-end-radius: var(--border-radius-xl) !important;
}
&:only-child,
&:only-child::before {
border-radius: var(--border-radius-xl) !important;
}
}
.pass-fieldset-cluster textarea {
min-block-size: 1.25rem;
}
| 7,561
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/Layout/FieldsetCluster.tsx
|
import { type FC } from 'react';
import clsx from '@proton/utils/clsx';
import './FieldsetCluster.scss';
type Props = { as?: 'fieldset' | 'div' | 'span'; className?: string; mode?: 'read' | 'write' };
export const FieldsetCluster: FC<Props> = ({ children, as = 'fieldset', className, mode = 'write' }) => {
const Component = as;
return (
<Component
className={clsx(
'pass-fieldset-cluster border-none rounded-xl p-0 m-0 mb-2',
mode === 'write' ? 'pass-fieldset-cluster--write' : 'pass-fieldset-cluster--read',
className
)}
style={mode === 'write' ? { background: 'var(--field-norm)' } : undefined}
>
{children}
</Component>
);
};
| 7,562
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/Field/masks/credit-card.ts
|
import type { FactoryOpts } from 'imask';
import MaskedRange from 'imask/esm/masked/range';
export const cardNumberMask = (value: string): FactoryOpts => {
switch (Number(value.slice(0, 2))) {
/* AMEX */
case 34:
case 37:
return { mask: '0000 000000 00000' };
default:
return { mask: '0000 0000 0000 0000 000' };
}
};
export const cardNumberHiddenValue = (value: string): string => {
if (!value.length) {
return '';
}
if (value.length < 12) {
return '•••• •••• •••• ••••';
}
const firstFour = value.slice(0, 4);
const lastFour = value.slice(-4);
switch (Number(value.slice(0, 2))) {
case 34:
case 37:
return `${firstFour} •••••• •${lastFour}`;
default:
return `${firstFour} •••• •••• ${lastFour}`;
}
};
export const expDateMask = {
mask: 'MM/YYYY',
blocks: {
MM: {
mask: MaskedRange,
from: 1,
to: 12,
},
YYYY: {
mask: MaskedRange,
from: 1900,
to: 2100,
},
},
} as FactoryOpts;
| 7,563
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/legacy/LocaleSelect.tsx
|
import { type VFC } from 'react';
import { c } from 'ttag';
import { Option, SelectTwo } from '@proton/components/components';
import { useConfig } from '@proton/components/hooks';
type Props = {
value: string;
onChange: (locale: string) => void;
};
export const LocaleSelect: VFC<Props> = ({ value, onChange }) => {
const { LOCALES } = useConfig();
return (
<SelectTwo<string> placeholder={c('Label').t`Select preferred language`} onValue={onChange} value={value}>
{Object.keys(LOCALES).map((locale) => (
<Option key={locale} title={LOCALES[locale]} value={locale} />
))}
</SelectTwo>
);
};
| 7,564
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/legacy/PasswordField.tsx
|
/**
* TODO: this component is still used in the Exporter
* and the ImportForm components. Disabled password
* generation on this component for now.. It was used
* in the Exporter to generate a password for PGP
* encryption but we can do without for now..
*/
import type { FC } from 'react';
import type { FieldProps } from 'formik';
import { InputFieldTwo, PasswordInputTwo } from '@proton/components';
import type { InputFieldOwnProps } from '@proton/components/components/v2/field/InputField';
type PasswordFieldProps = FieldProps & InputFieldOwnProps;
export const PasswordField: FC<PasswordFieldProps> = ({ field, form, ...rest }) => {
const { name } = field;
const { touched, errors } = form;
const error = touched[name] && errors[name];
return (
<div className="flex flex-nowrap flex-align-items-end mb-3">
<InputFieldTwo dense as={PasswordInputTwo} error={error} {...field} {...rest} />
</div>
);
};
| 7,565
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Form/legacy/TextAreaReadonly.tsx
|
import type { VFC } from 'react';
import { useEffect, useRef, useState } from 'react';
import clsx from '@proton/utils/clsx';
type Props = { children: string; className?: string };
export const TextAreaReadonly: VFC<Props> = ({ children, className }) => {
const [height, setHeight] = useState(0);
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (ref.current) setHeight(ref.current.scrollHeight);
}, [children]);
return (
<textarea
ref={ref}
readOnly
disabled
value={children}
className={clsx('w-full h-full text-pre-wrap overflow-hidden resize-none h-custom', className)}
style={{ '--h-custom': `${height}px` }}
/>
);
};
| 7,566
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportForm.scss
|
@import '~@proton/styles/scss/lib';
.pass-import-providers--grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(#{rem(110)}, 1fr));
}
.pass-import-upload {
--min-h-custom: #{rem(250)};
transition: min-block-size 0.25s ease-in-out 0.05s;
&--has-file {
--min-h-custom: 1px;
}
}
| 7,567
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportForm.tsx
|
import { type VFC, useMemo } from 'react';
import { Field } from 'formik';
import { c } from 'ttag';
import { Href } from '@proton/atoms/Href';
import { AttachedFile, Bordered, Dropzone, FileInput, Icon, InlineLinkButton } from '@proton/components/components';
import { PasswordField } from '@proton/pass/components/Form/legacy/PasswordField';
import type { ImportFormContext } from '@proton/pass/hooks/useImportForm';
import { SUPPORTED_IMPORT_FILE_TYPES } from '@proton/pass/hooks/useImportForm';
import { extractFileExtension } from '@proton/pass/lib/import/reader';
import { ImportProvider, ImportProviderValues, PROVIDER_INFO_MAP } from '@proton/pass/lib/import/types';
import type { MaybeNull } from '@proton/pass/types';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import clsx from '@proton/utils/clsx';
import { ImportProviderItem } from './ImportProviderItem';
import './ImportForm.scss';
const providerHasUnsupportedItemTypes = (provider: ImportProvider) => {
return (
provider !== ImportProvider.BRAVE &&
provider !== ImportProvider.FIREFOX &&
provider !== ImportProvider.CHROME &&
provider !== ImportProvider.EDGE &&
provider !== ImportProvider.SAFARI &&
provider !== ImportProvider.PROTONPASS
);
};
export const ImportForm: VFC<Omit<ImportFormContext, 'reset' | 'result'>> = ({ form, dropzone, busy }) => {
const needsPassphrase = useMemo(
() =>
form.values.file &&
extractFileExtension(form.values.file.name) === 'pgp' &&
form.values.provider === ImportProvider.PROTONPASS,
[form.values]
);
const onSelectProvider = (provider: MaybeNull<ImportProvider>) => () => form.setFieldValue('provider', provider);
return (
<>
<div className="mb-2">
<strong>{c('Label').t`Select your password manager`}</strong>
{form.values.provider && (
<InlineLinkButton onClick={onSelectProvider(null)} className="ml-2">
{c('Action').t`Change`}
</InlineLinkButton>
)}
</div>
{!form.values.provider && (
<>
<div className="pass-import-providers--grid gap-3 mb-4">
{ImportProviderValues.map((provider) => (
<ImportProviderItem
onClick={onSelectProvider(provider)}
key={provider}
value={provider}
title={PROVIDER_INFO_MAP[provider].title}
fileExtension={PROVIDER_INFO_MAP[provider].fileExtension}
/>
))}
</div>
<Href href="https://protonmail.uservoice.com/forums/953584-proton-pass">{c('Action')
.t`Your password manager not here? Request it.`}</Href>
</>
)}
{form.values.provider && (
<>
<div className="flex flex-justify-space-between flex-align-items-center mt-3 mb-4">
<div className="flex flex-align-items-center">
<div className="mr-2">
<img
src={`/assets/${form.values.provider}-icon-48.png`}
width="24"
height="24"
alt=""
/>
</div>
<div className="flex flex-column ml-3">
<span>{PROVIDER_INFO_MAP[form.values.provider].title}</span>
<span className="color-weak">
{PROVIDER_INFO_MAP[form.values.provider].fileExtension}
</span>
</div>
</div>
{PROVIDER_INFO_MAP[form.values.provider].tutorialUrl && (
<Href
href={PROVIDER_INFO_MAP[form.values.provider].tutorialUrl}
className="flex flex-align-items-center"
>
{c('Action').t`How do I export my data from ${
PROVIDER_INFO_MAP[form.values.provider].title
}?`}
<Icon className="ml-2" name="arrow-out-square" />
</Href>
)}
</div>
<Dropzone onDrop={dropzone.onDrop} disabled={busy} border={false}>
<Bordered
className={clsx([
'flex flex-columns flex-justify-center flex-align-items-center relative p-4 mb-4 rounded border-weak min-h-custom pass-import-upload',
form.values.file ? 'pass-import-upload--has-file' : 'border-dashed',
form.errors.file && 'border-danger',
])}
>
{form.values.file ? (
<AttachedFile
file={form.values.file}
className={clsx('border-none', busy && 'no-pointer-events')}
iconName="file-lines"
clear={c('Action').t`Delete`}
onClear={() => form.setFieldValue('file', undefined)}
/>
) : (
<FileInput
accept={SUPPORTED_IMPORT_FILE_TYPES.map((ext) => `.${ext}`).join(',')}
onChange={dropzone.onAttach}
disabled={busy}
shape="solid"
color="weak"
>
{c('Action').t`Choose a file or drag it here`}
</FileInput>
)}
</Bordered>
</Dropzone>
{needsPassphrase && (
<Field name="passphrase" label={c('Label').t`Passphrase`} component={PasswordField} />
)}
{providerHasUnsupportedItemTypes(form.values.provider) && (
<em className="block text-sm color-weak mb-2">
{c('Info').t`${PASS_APP_NAME} will only import logins, notes and credit cards.`}
</em>
)}
</>
)}
</>
);
};
| 7,568
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportProgress.tsx
|
import { type FC } from 'react';
import { useSelector } from 'react-redux';
import { c, msgid } from 'ttag';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import { importItemsRequest } from '@proton/pass/store/actions/requests';
import { selectRequest } from '@proton/pass/store/selectors';
/* we need to pass the runtime port object to this component
* as it may be loaded inside a Portal outside of the extension
* context provider's children */
export const ImportProgress: FC<{ total: number }> = ({ total }) => {
const req = useSelector(selectRequest(importItemsRequest()));
const progress = req?.status === 'start' ? req.progress ?? 0 : 0;
return (
<>
{c('Info').t`Import in progress:`}{' '}
<strong className="mx-2">
{progress}/{total} {c('Info').ngettext(msgid`item`, `items`, total)}
</strong>
<CircleLoader />
</>
);
};
| 7,569
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportProviderItem.scss
|
.pass-import-providers--item {
outline: 1px solid var(--border-weak);
}
| 7,570
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportProviderItem.tsx
|
import type { VFC } from 'react';
import ButtonLike from '@proton/atoms/Button/ButtonLike';
import './ImportProviderItem.scss';
export const ImportProviderItem: VFC<{
value: string;
title: string;
fileExtension: string;
onClick?: () => void;
}> = ({ value, title, fileExtension, onClick }) => {
return (
<ButtonLike onClick={onClick} shape="ghost" className="rounded pass-import-providers--item px-0 py-2">
<div className="flex flex-column flex-align-items-center">
<img className="m-2" alt={title} src={`/assets/${value}-icon-48.png`} width="24" height="24"></img>
<span className="mb-0.5">{title}</span>
<span className="color-weak">{fileExtension}</span>
</div>
</ButtonLike>
);
};
| 7,571
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportVaultsPickerModal.tsx
|
import type { VFC } from 'react';
import { useCallback, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Card } from '@proton/atoms/Card';
import type { ModalProps } from '@proton/components/components';
import { ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components/components';
import { type ImportPayload, type ImportVault } from '@proton/pass/lib/import/types';
import {
selectDefaultVault,
selectPassPlan,
selectVaultLimits,
selectWritableVaults,
} from '@proton/pass/store/selectors';
import { UserPassPlan } from '@proton/pass/types/api/plan';
import { omit } from '@proton/shared/lib/helpers/object';
import { UpgradeButton } from '../Layout/Button/UpgradeButton';
import { ImportVaultPickerOption } from './ImportVaultsPickerOption';
type VaultPickerValue = ImportVault & { selected: boolean };
type VaultsPickerFormValues = { vaults: VaultPickerValue[] };
type ImportVaultsPickerProps = Omit<ModalProps, 'onSubmit'> & {
payload: ImportPayload;
onSubmit: (payload: ImportPayload) => void;
};
export type ImportVaultsPickerHandle = { submit: () => void };
const FORM_ID = 'vault-picker';
export const ImportVaultsPickerModal: VFC<ImportVaultsPickerProps> = ({ payload, onClose, onReset, onSubmit }) => {
const writableVaults = useSelector(selectWritableVaults);
const defaultVault = useSelector(selectDefaultVault);
const { vaultLimit, vaultTotalCount } = useSelector(selectVaultLimits);
const plan = useSelector(selectPassPlan);
const handleSubmit = useCallback(
(values: VaultsPickerFormValues) =>
onSubmit({
vaults: values.vaults
.filter((vault) => vault.selected)
.map((vault) => omit(vault, ['selected']) as ImportVault),
ignored: payload.ignored,
warnings: payload.warnings,
}),
[onSubmit]
);
const form = useFormik<VaultsPickerFormValues>({
onSubmit: handleSubmit,
initialValues: {
vaults: payload.vaults.map(
(vault): VaultPickerValue => ({
...vault,
shareId: defaultVault.shareId,
name: defaultVault.content.name,
selected: true,
})
),
},
});
const vaultsToCreate = useMemo(
() => form.values.vaults.filter((vault) => vault.shareId === null).length,
[form.values]
);
const vaultsRemaining = vaultLimit - vaultTotalCount - vaultsToCreate;
const canCreateVault = vaultsRemaining > 0;
return (
<ModalTwo open onClose={onClose} onReset={onReset} size={'medium'} className="mt-10">
<ModalTwoHeader
title={
// translator: this is generic title of the modal where user can select 1 or more vaults to do the import (the number is not determined and title is not changeable)
c('Title').t`Import to vault(s)`
}
/>
<ModalTwoContent>
<FormikProvider value={form}>
<Form id={FORM_ID}>
<Card rounded className="mb-4 text-sm">
{
// translator: this is generic instruction message in import modal suggesting that user may select one or more vaults
c('Info').t`Select where you want your imported vault(s) to be saved.`
}
{vaultsRemaining <= 0 && (
<>
<hr className="mt-2 mb-2" />
{plan === UserPassPlan.FREE ? (
<>
{c('Warning')
.t`Your subscription does not allow you to create multiple vaults. All items will be imported to your first vault. To import into multiple vaults upgrade your subscription.`}
<UpgradeButton inline className="ml-1" />
</>
) : (
c('Warning').t`You cannot create more vaults than your subscription allows.`
)}
</>
)}
</Card>
{payload.vaults.map((importedVault, idx) => {
const value = form.values.vaults[idx];
const { selected } = value;
return (
<Card
key={`import-vault-${idx}`}
background={!selected}
style={{ opacity: selected ? 1 : 0.5 }}
className="mb-3"
rounded
>
<ImportVaultPickerOption
data={importedVault}
vaults={writableVaults}
allowNewVault={canCreateVault}
value={value.shareId}
selected={value.selected}
onToggle={(checked) =>
form.setFieldValue(
'vaults',
form.values.vaults.map((vault, j) => ({
...vault,
selected: j === idx ? checked : vault.selected,
}))
)
}
onChange={async (shareId) =>
form.setFieldValue(
'vaults',
form.values.vaults.map((vault, j): VaultPickerValue => {
if (idx !== j) return vault;
return { ...importedVault, selected: true, shareId };
})
)
}
/>
</Card>
);
})}
</Form>
</FormikProvider>
</ModalTwoContent>
<ModalTwoFooter>
<Button type="reset" onClick={onClose} color="danger">
{c('Action').t`Cancel`}
</Button>
<Button type="submit" color="norm" disabled={vaultsRemaining < 0} form={FORM_ID}>{c('Action')
.t`Confirm`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
| 7,572
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Import/ImportVaultsPickerOption.tsx
|
import type { FC } from 'react';
import { useMemo } from 'react';
import { c, msgid } from 'ttag';
import { Checkbox, Icon, Option, SelectTwo } from '@proton/components';
import { VAULT_ICON_MAP } from '@proton/pass/components/Vault/constants';
import { type ImportVault } from '@proton/pass/lib/import/types';
import type { VaultShareItem } from '@proton/pass/store/reducers';
import type { MaybeNull } from '@proton/pass/types';
import { truthy } from '@proton/pass/utils/fp/predicates';
type VaultsPickerOptionProps = {
data: ImportVault;
vaults: VaultShareItem[];
allowNewVault: boolean;
value: MaybeNull<string>;
selected: boolean;
onToggle: (checked: boolean) => void;
onChange: (shareId: MaybeNull<string>) => void;
};
export const ImportVaultPickerOption: FC<VaultsPickerOptionProps> = ({
data: { name, items },
vaults,
allowNewVault,
value,
selected,
onToggle,
onChange,
}) => {
const count = useMemo(() => items.length, [items]);
return (
<div className="flex flex-justify-space-between flex-align-items-center">
<Checkbox checked={selected} onChange={(e) => onToggle(e.target.checked)}>
<div className="w-custom" style={{ '--w-custom': '6.25rem' }}>
<strong className="text-sm block text-ellipsis">{name}</strong>
<span className="text-sm text-weak">
{c('Info').ngettext(msgid`${count} item`, `${count} items`, count)}
</span>
</div>
</Checkbox>
<Icon name="arrow-right" />
<div className="w-custom" style={{ '--w-custom': '9.375rem' }}>
<SelectTwo value={value} className="text-sm" onValue={(value) => onChange(value)} disabled={!selected}>
{[
/* if user needs to upgrade, this means he cannot
* create any more vaults - disable this option when
* trying to import if that is the case */
<Option
key={'new-vault'}
title={c('Label').t`Create new vault`}
value={null}
className="text-sm"
disabled={!allowNewVault}
>
<span className="flex flex-align-items-center">
<Icon name="plus" size={14} className="mr-3 flex-item-nogrow" />
<span className="flex-item-fluid text-ellipsis">{c('Label').t`New vault`}</span>
</span>
</Option>,
...vaults.map((vault) => (
<Option
key={vault.shareId}
title={vault.content.name}
value={vault.shareId}
className="text-sm"
>
<span className="flex flex-align-items-center">
<Icon
name={
vault.content.display.icon
? VAULT_ICON_MAP[vault.content.display.icon]
: 'pass-home'
}
size={14}
className="mr-3 flex-item-nogrow"
/>
<span className="flex-item-fluid text-ellipsis">{vault.content.name}</span>
</span>
</Option>
)),
].filter(truthy)}
</SelectTwo>
</div>
</div>
);
};
| 7,573
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/InviteContextProvider.tsx
|
import type { FC } from 'react';
import { createContext, useContext, useMemo, useState } from 'react';
import type { MaybeNull } from '@proton/pass/types';
import type { Invite } from '@proton/pass/types/data/invites';
import noop from '@proton/utils/noop';
import { VaultAccessManager } from './VaultAccessManager';
import { VaultInviteCreate, type VaultInviteCreateValues } from './VaultInviteCreate';
import { VaultInviteRespond } from './VaultInviteRespond';
export type InviteContextValue = {
close: () => void;
createInvite: (props: VaultInviteCreateValues<false>) => void;
createSharedVault: (props: VaultInviteCreateValues<true>) => void;
manageAccess: (shareId: string) => void;
onInviteResponse: () => void;
onShareDisabled: (disabledShareId: string) => void;
respondToInvite: (invite: Invite) => void;
};
const InviteContext = createContext<InviteContextValue>({
close: noop,
createInvite: noop,
createSharedVault: noop,
manageAccess: noop,
onInviteResponse: noop,
onShareDisabled: noop,
respondToInvite: noop,
});
type InviteContextState =
| ({ view: 'invite' } & VaultInviteCreateValues<false>)
| ({ view: 'invite-new' } & VaultInviteCreateValues<true>)
| { view: 'manage'; shareId: string };
type InviteContextProps = { onVaultCreated?: (shareId: string) => void };
export const InviteContextProvider: FC<InviteContextProps> = ({ children, onVaultCreated }) => {
const [state, setState] = useState<MaybeNull<InviteContextState>>(null);
const [invite, setInvite] = useState<MaybeNull<Invite>>(null);
const handles = useMemo(
() => ({
close: () => setState(null),
createInvite: (props: VaultInviteCreateValues<false>) => setState({ view: 'invite', ...props }),
createSharedVault: (props: VaultInviteCreateValues<true>) => setState({ view: 'invite-new', ...props }),
manageAccess: (shareId: string) => setState({ view: 'manage', shareId }),
onInviteResponse: () => setInvite(null),
}),
[]
);
const contextValue = useMemo<InviteContextValue>(
() => ({
...handles,
onShareDisabled: (disabledShareId: string) => {
const shareId = (() => {
switch (state?.view) {
case 'invite':
return state.vault.shareId;
case 'manage':
return state.shareId;
default:
return null;
}
})();
if (disabledShareId === shareId) {
setInvite(null);
setState(null);
}
},
respondToInvite: setInvite,
}),
[state]
);
return (
<InviteContext.Provider value={contextValue}>
{(() => {
switch (state?.view) {
case 'invite':
return <VaultInviteCreate withVaultCreation={false} {...state} />;
case 'invite-new':
return <VaultInviteCreate withVaultCreation {...state} onVaultCreated={onVaultCreated} />;
case 'manage':
return <VaultAccessManager shareId={state.shareId} />;
default:
return null;
}
})()}
{invite && <VaultInviteRespond {...invite} />}
{children}
</InviteContext.Provider>
);
};
export const useInviteContext = () => useContext(InviteContext);
| 7,574
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/UserVerificationMessage.tsx
|
import { type VFC } from 'react';
import { c } from 'ttag';
import { Card } from '../Layout/Card/Card';
export const UserVerificationMessage: VFC = () => {
return (
<Card className="mb-2">{c('Warning').t`Please verify your email address in order to use vault sharing`}</Card>
);
};
| 7,575
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/VaultAccessManager.tsx
|
import { type FC, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Icon, Prompt } from '@proton/components/components';
import { useInviteContext } from '@proton/pass/components/Invite/InviteContextProvider';
import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton';
import { Card } from '@proton/pass/components/Layout/Card/Card';
import { SidebarModal } from '@proton/pass/components/Layout/Modal/SidebarModal';
import { Panel } from '@proton/pass/components/Layout/Panel/Panel';
import { PanelHeader } from '@proton/pass/components/Layout/Panel/PanelHeader';
import { ShareMember } from '@proton/pass/components/Share/ShareMember';
import { PendingExistingMember, PendingNewMember } from '@proton/pass/components/Share/SharePendingMember';
import { SharedVaultItem } from '@proton/pass/components/Vault/SharedVaultItem';
import { useShareAccessOptionsPolling } from '@proton/pass/hooks/useShareAccessOptionsPolling';
import { isShareManageable } from '@proton/pass/lib/shares/share.predicates';
import { isVaultMemberLimitReached } from '@proton/pass/lib/vaults/vault.predicates';
import { selectOwnWritableVaults, selectPassPlan, selectShareOrThrow } from '@proton/pass/store/selectors';
import type { NewUserPendingInvite, PendingInvite, ShareType } from '@proton/pass/types';
import { type ShareMember as ShareMemberType } from '@proton/pass/types';
import { UserPassPlan } from '@proton/pass/types/api/plan';
import { sortOn } from '@proton/pass/utils/fp/sort';
type Props = { shareId: string };
type InviteListItem =
| { key: string; type: 'existing'; invite: PendingInvite }
| { key: string; type: 'new'; invite: NewUserPendingInvite };
export const VaultAccessManager: FC<Props> = ({ shareId }) => {
const { createInvite, close } = useInviteContext();
const vault = useSelector(selectShareOrThrow<ShareType.Vault>(shareId));
const plan = useSelector(selectPassPlan);
const loading = useShareAccessOptionsPolling(shareId);
const canManage = isShareManageable(vault);
const hasMultipleOwnedWritableVaults = useSelector(selectOwnWritableVaults).length > 1;
const [limitModalOpen, setLimitModalOpen] = useState(false);
const members = useMemo<ShareMemberType[]>(() => (vault.members ?? []).sort(sortOn('email', 'ASC')), [vault]);
const invites = useMemo<InviteListItem[]>(
() =>
[
...(vault.invites ?? []).map((invite) => ({
key: invite.invitedEmail,
type: 'existing' as const,
invite,
})),
...(vault.newUserInvites ?? []).map((invite) => ({
key: invite.invitedEmail,
type: 'new' as const,
invite,
})),
].sort(sortOn('key', 'ASC')),
[vault]
);
const memberLimitReached = isVaultMemberLimitReached(vault);
const warning = (() => {
if (canManage && memberLimitReached) {
const upgradeLink = <UpgradeButton inline label={c('Action').t`Upgrade now to share with more people`} />;
return plan === UserPassPlan.FREE
? c('Warning').jt`You have reached the limit of users in this vault. ${upgradeLink}`
: c('Warning').t`You have reached the limit of members who can access this vault.`;
}
})();
return (
<SidebarModal onClose={close} open>
<Panel
loading={loading}
header={
<PanelHeader
actions={[
<Button
key="modal-close-button"
className="flex-item-noshrink"
icon
pill
shape="solid"
onClick={close}
>
<Icon className="modal-close-icon" name="cross-big" alt={c('Action').t`Close`} />
</Button>,
<Button
key="modal-invite-button"
color="norm"
pill
onClick={() => (memberLimitReached ? setLimitModalOpen(true) : createInvite({ vault }))}
disabled={!canManage || (plan === UserPassPlan.FREE && memberLimitReached)}
>
{c('Action').t`Invite others`}
</Button>,
]}
/>
}
>
<SharedVaultItem
className="mt-3 mb-6"
color={vault.content.display.color}
icon={vault.content.display.icon}
name={vault.content.name}
shareId={vault.shareId}
/>
{vault.shared ? (
<div className="flex flex-column gap-y-3">
{invites.length > 0 && <span className="color-weak">{c('Label').t`Invitations`}</span>}
{invites.map((item) => {
switch (item.type) {
case 'new':
return (
<PendingNewMember
shareId={vault.shareId}
key={item.key}
email={item.invite.invitedEmail}
newUserInviteId={item.invite.newUserInviteId}
canManage={canManage}
state={item.invite.state}
/>
);
case 'existing':
return (
<PendingExistingMember
key={item.key}
shareId={vault.shareId}
email={item.invite.invitedEmail}
inviteId={item.invite.inviteId}
canManage={canManage}
/>
);
}
})}
{members.length > 0 && <span className="color-weak">{c('Label').t`Members`}</span>}
{members.map((member) => (
<ShareMember
key={member.email}
email={member.email}
shareId={vault.shareId}
userShareId={member.shareId}
me={vault.shareId === member.shareId}
owner={member.owner}
role={member.shareRoleId}
canManage={canManage}
canTransfer={vault.owner && hasMultipleOwnedWritableVaults}
/>
))}
{warning && <Card>{warning}</Card>}
</div>
) : (
<div className="absolute-center flex flex-column gap-y-3 text-center color-weak text-sm">
{c('Info')
.t`This vault is not currently shared with anyone. Invite people to share it with others.`}
</div>
)}
<Prompt
buttons={
<Button
pill
onClick={() => setLimitModalOpen(false)}
className="w-full"
shape="solid"
color="weak"
>
{c('Action').t`OK`}
</Button>
}
className="text-center"
onClose={() => setLimitModalOpen(false)}
open={limitModalOpen}
title={c('Title').t`Member limit`}
>
<p>
{
// translator: full message is "Vaults can’t contain more than 10 users.""
c('Success').ngettext(
msgid`Vaults can’t contain more than ${vault.targetMaxMembers} user.`,
`Vaults can’t contain more than ${vault.targetMaxMembers} users.`,
vault.targetMaxMembers
)
}
</p>
</Prompt>
</Panel>
</SidebarModal>
);
};
| 7,576
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/VaultInviteCreate.tsx
|
import { type FC } from 'react';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Icon } from '@proton/components/components';
import { SidebarModal } from '@proton/pass/components/Layout/Modal/SidebarModal';
import { Panel } from '@proton/pass/components/Layout/Panel/Panel';
import { PanelHeader } from '@proton/pass/components/Layout/Panel/PanelHeader';
import { SharedVaultItem } from '@proton/pass/components/Vault/SharedVaultItem';
import type { RequestEntryFromAction } from '@proton/pass/hooks/useActionRequest';
import { useActionRequest } from '@proton/pass/hooks/useActionRequest';
import { validateShareInviteValues } from '@proton/pass/lib/validation/vault-invite';
import type { inviteCreationSuccess } from '@proton/pass/store/actions';
import { inviteCreationIntent } from '@proton/pass/store/actions';
import type { VaultShareItem } from '@proton/pass/store/reducers';
import type { InviteFormValues, SelectedItem } from '@proton/pass/types';
import { ShareRole } from '@proton/pass/types';
import { VaultColor, VaultIcon } from '@proton/pass/types/protobuf/vault-v1';
import clsx from '@proton/utils/clsx';
import { useInviteContext } from './InviteContextProvider';
import { FORM_ID, VaultInviteForm } from './VaultInviteForm';
export type VaultInviteCreateProps =
| { withVaultCreation: false; vault: VaultShareItem }
| { withVaultCreation: true; item: SelectedItem; onVaultCreated?: (shareId: string) => void };
export type VaultInviteCreateValues<T extends boolean = boolean> = Omit<
Extract<VaultInviteCreateProps, { withVaultCreation: T }>,
'withVaultCreation' | 'onVaultCreated'
>;
export const VaultInviteCreate: FC<VaultInviteCreateProps> = (props) => {
const { close, manageAccess } = useInviteContext();
const createInvite = useActionRequest({
action: inviteCreationIntent,
onSuccess: (req: RequestEntryFromAction<ReturnType<typeof inviteCreationSuccess>>) => {
const { shareId } = req.data;
if (props.withVaultCreation) props.onVaultCreated?.(shareId);
manageAccess(shareId);
},
});
const form = useFormik<InviteFormValues>({
initialValues: {
step: 'email',
email: '',
role: ShareRole.READ,
...(props.withVaultCreation
? {
withVaultCreation: true,
name: c('Placeholder').t`Shared vault`,
description: '',
color: VaultColor.COLOR3,
icon: VaultIcon.ICON9,
item: props.item,
}
: { withVaultCreation: false, shareId: props.vault.shareId }),
},
validateOnChange: true,
validate: validateShareInviteValues,
onSubmit: (values, { setFieldValue }) => {
switch (values.step) {
case 'email':
return setFieldValue('step', 'permissions');
case 'vault':
return setFieldValue('step', 'email');
case 'permissions':
createInvite.dispatch(values);
break;
}
},
});
const submitText = (() => {
switch (form.values.step) {
case 'email':
return c('Action').t`Continue`;
case 'vault':
return c('Action').t`Update vault`;
case 'permissions':
return !props.withVaultCreation && props.vault.shared
? c('Action').t`Send invite`
: c('Action').t`Share vault`;
}
})();
return (
<SidebarModal onClose={close} open>
{(didEnter) => (
<Panel
loading={createInvite.loading}
header={
<PanelHeader
actions={[
<Button
className="flex-item-noshrink"
icon
key="modal-close-button"
onClick={close}
pill
shape="solid"
>
<Icon className="modal-close-icon" name="cross-big" alt={c('Action').t`Close`} />
</Button>,
<Button
color="norm"
disabled={createInvite.loading || !form.isValid || !form.dirty}
form={FORM_ID}
key="modal-submit-button"
loading={createInvite.loading}
pill
type="submit"
>
{submitText}
</Button>,
]}
/>
}
>
{form.values.step !== 'vault' && (
<div
className={clsx(
'flex flex-justify-space-between flex-align-items-center flex-nowrap mt-3 mb-6 gap-3 anime-fade-in',
props.withVaultCreation && 'border rounded-xl p-3'
)}
>
{form.values.withVaultCreation && (
<>
<SharedVaultItem
color={form.values.color}
icon={form.values.icon}
name={form.values.name}
/>
<Button
className="flex-item-noshrink"
color="weak"
onClick={() => form.setFieldValue('step', 'vault')}
pill
shape="solid"
>
{c('Action').t`Customize`}
</Button>
</>
)}
{!props.withVaultCreation && (
<SharedVaultItem
color={props.vault.content.display.color}
icon={props.vault.content.display.icon}
name={props.vault.content.name}
shareId={props.vault.shareId}
/>
)}
</div>
)}
<FormikProvider value={form}>
<Form id={FORM_ID}>
<VaultInviteForm form={form} autoFocus={didEnter} />
</Form>
</FormikProvider>
</Panel>
)}
</SidebarModal>
);
};
| 7,577
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/VaultInviteForm.tsx
|
import type { VFC } from 'react';
import { useSelector } from 'react-redux';
import { type FormikContextType } from 'formik';
import { c } from 'ttag';
import { Icon } from '@proton/components/components';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { RadioGroupField } from '@proton/pass/components/Form/Field/RadioGroupField';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import { IconBox } from '@proton/pass/components/Layout/Icon/IconBox';
import { shareRoleOptions } from '@proton/pass/components/Share/ShareRoleOptions';
import { VaultForm } from '@proton/pass/components/Vault/Vault.form';
import { selectUserVerified } from '@proton/pass/store/selectors';
import type { InviteFormValues } from '@proton/pass/types';
import { UserVerificationMessage } from './UserVerificationMessage';
export const FORM_ID = 'vault-invite';
type Props = { form: FormikContextType<InviteFormValues>; autoFocus?: boolean };
export const VaultInviteForm: VFC<Props> = ({ form, autoFocus }) => {
const { email, step } = form.values;
const userVerified = useSelector(selectUserVerified);
return (
<>
{!userVerified && <UserVerificationMessage />}
{step === 'email' && (
<div className="anime-fade-in">
<h2 className="text-xl text-bold mb-3">{c('Title').t`Share with`}</h2>
<FieldsetCluster>
<Field
name="email"
component={TextField}
placeholder={c('Placeholder').t`Email address`}
type="email"
disabled={!userVerified}
autoFocus={autoFocus}
key={`autofocus-email-${autoFocus}`}
/>
</FieldsetCluster>
</div>
)}
{step === 'vault' && (
<div className="flex flex-column gap-y-4 anime-fade-in">
<VaultForm form={form as FormikContextType<InviteFormValues<true>>} autoFocus={autoFocus} />
</div>
)}
{step === 'permissions' && (
<div className="anime-fade-in">
<h2 className="text-xl text-bold mb-3">{c('Title').t`Set access level`}</h2>
<button
className="flex flex-align-items-center flex-nowrap gap-3 mb-3"
onClick={() => form.setFieldValue('step', 'email')}
>
<IconBox size={18} mode="icon" className="flex-item-noshrink">
<Icon
className={'absolute-center'}
color="var(--interaction-norm)"
name={'envelope'}
size={16}
/>
</IconBox>
<div className="text-break-all text-left">{email}</div>
</button>
<div className="border border-norm rounded pl-4 py-3">
<Field
name="role"
className="flex flex-nowrap gap-2 mr-0"
component={RadioGroupField}
options={shareRoleOptions()}
/>
</div>
</div>
)}
</>
);
};
| 7,578
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/VaultInviteFromItemModal.tsx
|
import { type VFC } from 'react';
import { useSelector } from 'react-redux';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import type { ModalProps } from '@proton/components/components';
import { ModalTwo, ModalTwoFooter, ModalTwoHeader } from '@proton/components/components';
import { VaultTag } from '@proton/pass/components/Vault/VaultTag';
import { VAULT_ICON_MAP } from '@proton/pass/components/Vault/constants';
import type { ShareItem } from '@proton/pass/store/reducers';
import { selectVaultLimits, selectWritableSharedVaults } from '@proton/pass/store/selectors';
import type { ShareType } from '@proton/pass/types';
export type Props = ModalProps & {
handleCreateSharedVaultClick: () => void;
handleMoveToSharedVaultClick: () => void;
handleShareVaultClick: () => void;
itemId: string;
shareId: string;
vault: ShareItem<ShareType.Vault>;
};
export const VaultInviteFromItemModal: VFC<Props> = ({
handleCreateSharedVaultClick,
handleMoveToSharedVaultClick,
handleShareVaultClick,
onClose,
itemId,
shareId,
vault,
...props
}) => {
const hasWritableSharedVaults = useSelector(selectWritableSharedVaults).length > 0;
const { vaultLimitReached } = useSelector(selectVaultLimits);
return (
<ModalTwo size="small" enableCloseWhenClickOutside onClose={onClose} {...props}>
<ModalTwoHeader
title={c('Action').t`Share`}
subline={c('Info').t`Use vaults to share this item with others.`}
className="text-center text-break-all"
hasClose={false}
/>
<ModalTwoFooter className="flex flex-column flex-align-items-stretch text-center">
<Button
pill
size="large"
shape="solid"
color="weak"
className="max-w-full"
onClick={handleShareVaultClick}
>
<div className="flex flex-justify-space-between flex-align-items-center flex-nowrap max-w-full gap-4">
<span className="flex flex-item-noshrink text-no-wrap">{c('Action').t`Share this vault`}</span>
<VaultTag
title={vault.content.name}
color={vault.content.display.color}
count={vault.targetMembers}
shared
icon={
vault.content.display.icon
? VAULT_ICON_MAP[vault.content.display.icon]
: 'pass-all-vaults'
}
iconSize={20}
/>
</div>
</Button>
{hasWritableSharedVaults && (
<Button pill size="large" shape="solid" color="norm" onClick={handleMoveToSharedVaultClick}>
{c('Action').t`Move to a shared vault`}
</Button>
)}
{!vaultLimitReached && (
<Button
pill
size="large"
shape="solid"
color={hasWritableSharedVaults ? 'weak' : 'norm'}
onClick={handleCreateSharedVaultClick}
>
{c('Action').t`Create a new vault to share`}
</Button>
)}
</ModalTwoFooter>
</ModalTwo>
);
};
| 7,579
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Invite/VaultInviteRespond.tsx
|
import { type VFC } from 'react';
import { useSelector } from 'react-redux';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import { ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Progress } from '@proton/components/components';
import { Card } from '@proton/pass/components/Layout/Card/Card';
import { VaultIcon } from '@proton/pass/components/Vault/VaultIcon';
import { useActionRequest } from '@proton/pass/hooks/useActionRequest';
import { inviteAcceptIntent, inviteRejectIntent } from '@proton/pass/store/actions';
import { selectUserVerified, selectVaultLimits } from '@proton/pass/store/selectors';
import type { Invite } from '@proton/pass/types/data/invites';
import { useInviteContext } from './InviteContextProvider';
import { UserVerificationMessage } from './UserVerificationMessage';
export const VaultInviteRespond: VFC<Invite> = (invite) => {
const { inviterEmail, invitedAddressId, token, vault, fromNewUser } = invite;
const { itemCount, memberCount } = vault;
const { vaultLimitReached } = useSelector(selectVaultLimits);
const { onInviteResponse } = useInviteContext();
const acceptInvite = useActionRequest({ action: inviteAcceptIntent, onSuccess: onInviteResponse });
const rejectInvite = useActionRequest({ action: inviteRejectIntent, onSuccess: onInviteResponse });
const handleRejectInvite = () => rejectInvite.dispatch({ inviteToken: invite.token });
const handleAcceptInvite = () => acceptInvite.dispatch({ inviteToken: token, inviterEmail, invitedAddressId });
const loading = acceptInvite.loading || rejectInvite.loading;
const userVerified = useSelector(selectUserVerified);
return (
<ModalTwo size="small" open onClose={onInviteResponse} enableCloseWhenClickOutside>
<ModalTwoHeader
className="text-center text-break-all"
hasClose={false}
{...(fromNewUser
? { title: c('Info').t`Congratulations, your access has been confirmed` }
: {
title: inviterEmail,
// translator: full sentence is split into 3 components in our design. Example: {eric.norbert@proton.me} invites you to access items in {name of the vault}"
subline: c('Info').t`invites you to access items in`,
})}
/>
<ModalTwoContent className="flex flex-column flex-align-items-center">
<VaultIcon
color={vault.content.display.color}
icon={vault.content.display.icon}
size={32}
background
className="mb-2"
/>
<div className="text-xl text-bold text-ellipsis max-w-full">{vault.content.name}</div>
<div className="color-weak">
<span>{c('Info').ngettext(msgid`${itemCount} item`, `${itemCount} items`, itemCount)}</span>
<span> • </span>
<span>
{c('Info').ngettext(msgid`${memberCount} member`, `${memberCount} members`, memberCount)}
</span>
</div>
</ModalTwoContent>
<ModalTwoFooter className="flex flex-column flex-align-items-stretch text-center">
{!userVerified && <UserVerificationMessage />}
{userVerified && vaultLimitReached && (
<Card className="mb-2">
{c('Warning').t`You have reached the limit of vaults you can have in your plan.`}
</Card>
)}
<Button
pill
size="large"
shape="solid"
color="norm"
disabled={loading || !userVerified || vaultLimitReached}
loading={acceptInvite.loading}
onClick={handleAcceptInvite}
>
{fromNewUser ? c('Action').t`Continue` : c('Action').t`Join shared vault`}
</Button>
<Button
pill
size="large"
shape="solid"
color="weak"
disabled={loading || !userVerified}
loading={rejectInvite.loading}
onClick={handleRejectInvite}
>
{fromNewUser ? c('Action').t`Reject` : c('Action').t`Reject invitation`}
</Button>
{acceptInvite.loading && (
<div className="ui-purple flex gap-x-2 flex-align-items-center">
<Progress
value={
invite.vault.itemCount > 0
? Math.round(100 * (acceptInvite.progress / invite.vault.itemCount))
: 0
}
className="flex-item-fluid progress-bar--norm"
/>
<small className="block">
{acceptInvite.progress} / {invite.vault.itemCount}
</small>
<CircleLoader size="small" />
</div>
)}
</ModalTwoFooter>
</ModalTwo>
);
};
| 7,580
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Alias/Alias.edit.tsx
|
import { type VFC, useRef, useState } from 'react';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Icon, Option } from '@proton/components';
import { ValueControl } from '@proton/pass/components/Form/Field/Control/ValueControl';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { SelectField } from '@proton/pass/components/Form/Field/SelectField';
import { TextAreaField } from '@proton/pass/components/Form/Field/TextareaField';
import { TitleField } from '@proton/pass/components/Form/Field/TitleField';
import { ItemEditPanel } from '@proton/pass/components/Layout/Panel/ItemEditPanel';
import type { ItemEditViewProps } from '@proton/pass/components/Views/types';
import { MAX_ITEM_NAME_LENGTH, MAX_ITEM_NOTE_LENGTH } from '@proton/pass/constants';
import { useAliasDetails } from '@proton/pass/hooks/useAliasDetails';
import { useAliasOptions } from '@proton/pass/hooks/useAliasOptions';
import { useDeobfuscatedValue } from '@proton/pass/hooks/useDeobfuscatedValue';
import { useDraftSync } from '@proton/pass/hooks/useItemDraft';
import { createEditAliasFormValidator } from '@proton/pass/lib/validation/alias';
import type { AliasMailbox, EditAliasFormValues } from '@proton/pass/types';
import { type MaybeNull } from '@proton/pass/types';
import { awaiter } from '@proton/pass/utils/fp/promises';
import { obfuscate } from '@proton/pass/utils/obfuscate/xor';
const FORM_ID = 'edit-alias';
export const AliasEdit: VFC<ItemEditViewProps<'alias'>> = ({ vault, revision, onCancel, onSubmit }) => {
const { shareId } = vault;
const { data: item, itemId, revision: lastRevision } = revision;
const aliasEmail = revision.aliasEmail!;
const { metadata, ...uneditable } = item;
const { name, itemUuid } = metadata;
const { current: draftHydrated } = useRef(awaiter<MaybeNull<EditAliasFormValues>>());
/* If vault is not shared, we can safely assume the user is
* the owner of the alias and can edit the mailboxes */
const [aliasOwner, setAliasOwner] = useState(!vault.shared);
/* Keeping a ref to the alias details for composing the result
* of `onAliasDetailsLoaded` with `onAliasOptionsLoading` effect */
const mailboxesForAlias = useRef<AliasMailbox[]>([]);
const note = useDeobfuscatedValue(metadata.note);
const initialValues: EditAliasFormValues = { name, note, mailboxes: [] };
const validateEditAliasForm = createEditAliasFormValidator(aliasOwner);
const form = useFormik<EditAliasFormValues>({
initialValues,
initialErrors: validateEditAliasForm(initialValues),
onSubmit: ({ name, note, mailboxes }) => {
onSubmit({
...uneditable,
shareId: vault.shareId,
itemId,
lastRevision,
metadata: {
name,
note: obfuscate(note),
itemUuid,
},
extraData: {
aliasOwner,
mailboxes,
aliasEmail: aliasEmail!,
},
});
},
validate: validateEditAliasForm,
validateOnChange: true,
});
const aliasOptions = useAliasOptions({
shareId: vault.shareId,
lazy: true,
onAliasOptionsLoaded: async ({ mailboxes }) => {
const draft = await draftHydrated;
const formValues = draft ?? form.values;
const prevMailboxes = draft?.mailboxes ?? mailboxesForAlias.current;
const sanitizedMailboxes = mailboxes.filter((mailbox) => prevMailboxes.some(({ id }) => id === mailbox.id));
/* if the mailboxes do not match the user's alias options and the
* vault is shared, then the user cannot manage its mailboxes */
if (vault.shared) setAliasOwner(sanitizedMailboxes.length > 0);
const values = { ...formValues, mailboxes: sanitizedMailboxes };
const errors = validateEditAliasForm(values);
if (draft) {
await form.setValues(values);
form.setErrors(errors);
} else form.resetForm({ values, errors });
},
});
const aliasDetails = useAliasDetails({
aliasEmail,
itemId,
shareId,
onAliasDetailsLoaded: (mailboxes) => {
mailboxesForAlias.current = mailboxes ?? [];
aliasOptions.request();
},
});
const mailboxes = aliasOptions.value?.mailboxes ?? [];
const disabledMailboxes = aliasOptions.loading || !aliasOptions;
useDraftSync<EditAliasFormValues>(form, {
type: 'alias',
mode: 'edit',
itemId: itemId,
shareId: vault.shareId,
onHydrated: draftHydrated.resolve,
});
const loading = (aliasDetails.loading && aliasDetails.value.length === 0) || aliasOptions.loading;
return (
<ItemEditPanel
type="alias"
formId={FORM_ID}
valid={!(aliasOwner && loading) && form.isValid && form.dirty}
discardable={!form.dirty}
handleCancelClick={onCancel}
>
{() => (
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
<Field
lengthLimiters
name="name"
label={c('Label').t`Title`}
placeholder={c('Label').t`Untitled`}
component={TitleField}
maxLength={MAX_ITEM_NAME_LENGTH}
/>
</FieldsetCluster>
<FieldsetCluster mode="read" as="div">
<ValueControl icon="alias" label={c('Label').t`Alias address`}>
{aliasEmail}
</ValueControl>
{aliasOwner ? (
<Field
name="mailboxes"
label={c('Label').t`Forwards to`}
placeholder={c('Label').t`Select an email address`}
component={SelectField}
icon="arrow-up-and-right-big"
multiple
disabled={disabledMailboxes}
loading={loading}
>
{mailboxes.map((mailbox) => (
<Option value={mailbox} title={mailbox.email} key={mailbox.id}>
{mailbox.email}
</Option>
))}
</Field>
) : (
<ValueControl
icon="arrow-up-and-right-big"
label={c('Label').t`Forwards to`}
loading={loading}
>
{!loading ? (
<span className="mt-1 text-xs color-weak flex flex-align-items-center gap-1">
<Icon name="exclamation-circle" size={16} />
<span className="text-pre-wrap flex-item-fluid">{c('Info')
.t`You cannot change the mailboxes for this alias.`}</span>
</span>
) : undefined}
</ValueControl>
)}
</FieldsetCluster>
<FieldsetCluster>
<Field
name="note"
label={c('Label').t`Note`}
placeholder={c('Placeholder').t`Enter a note...`}
component={TextAreaField}
icon="note"
maxLength={MAX_ITEM_NOTE_LENGTH}
/>
</FieldsetCluster>
</Form>
</FormikProvider>
)}
</ItemEditPanel>
);
};
| 7,581
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Alias/Alias.form.tsx
|
import { type FC, useState } from 'react';
import { type FormikContextType } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, Option } from '@proton/components';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { SelectField } from '@proton/pass/components/Form/Field/SelectField';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import type { SanitizedAliasOptions } from '@proton/pass/hooks/useAliasOptions';
import type { AliasFormValues, AliasMailbox, MaybeNull } from '@proton/pass/types';
type AliasFormProps<V extends AliasFormValues> = {
aliasOptions: MaybeNull<SanitizedAliasOptions>;
disabled?: boolean;
form: FormikContextType<V>;
loading: boolean;
};
const AliasFormBase: FC<{
disabled: boolean;
loading: boolean;
mailboxes: AliasMailbox[];
toggleShowAdvanced: () => void;
}> = ({ children, disabled, loading, mailboxes, toggleShowAdvanced }) => {
return (
<>
<div className="flex flex-justify-end mb-2">
<Button shape="ghost" onClick={toggleShowAdvanced}>
<span className="flex flex-align-items-center color-weak text-sm">
<Icon name="cog-wheel" className="mr-1" />
{c('Action').t`Advanced options`}
</span>
</Button>
</div>
{children}
<FieldsetCluster>
<Field
name="mailboxes"
label={c('Label').t`Forwards to`}
placeholder={c('Label').t`Select an email address`}
component={SelectField}
icon="arrow-up-and-right-big"
multiple
disabled={disabled || mailboxes.length <= 1}
loading={loading}
>
{mailboxes.map((mailbox) => (
<Option value={mailbox} title={mailbox.email} key={mailbox.id}>
{mailbox.email}
</Option>
))}
</Field>
</FieldsetCluster>
</>
);
};
export const AliasForm = <V extends AliasFormValues>({ form, loading, aliasOptions, disabled }: AliasFormProps<V>) => {
const [showAdvanced, setShowAdvanced] = useState(false);
const toggleShowAdvanced = () => setShowAdvanced((state) => !state);
const disabledForm = disabled || loading || aliasOptions === null;
const wrapperProps = {
disabled: disabledForm,
loading,
mailboxes: aliasOptions?.mailboxes ?? [],
toggleShowAdvanced,
};
return showAdvanced ? (
<AliasFormBase {...wrapperProps}>
<FieldsetCluster>
<Field
name="aliasPrefix"
label={c('Label').t`Prefix`}
placeholder={c('Placeholder').t`Enter a prefix`}
component={TextField}
onFocus={() => form.setFieldTouched('aliasPrefix', true)}
/>
<Field
name="aliasSuffix"
label={c('Label').t`Suffix`}
placeholder={c('Placeholder').t`Select a suffix`}
component={SelectField}
disabled={disabledForm}
loading={loading}
>
{(aliasOptions?.suffixes ?? []).map((suffix) => (
<Option key={suffix.value} value={suffix} title={suffix.value}>
{suffix.value}
</Option>
))}
</Field>
</FieldsetCluster>
</AliasFormBase>
) : (
<AliasFormBase {...wrapperProps} />
);
};
| 7,582
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Alias/Alias.modal.tsx
|
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { type FormikContextType, FormikProvider } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, type ModalProps } from '@proton/components/components';
import { AliasPreview } from '@proton/pass/components/Alias/Alias.preview';
import { AliasForm } from '@proton/pass/components/Item/Alias/Alias.form';
import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton';
import { Card } from '@proton/pass/components/Layout/Card/Card';
import { SidebarModal } from '@proton/pass/components/Layout/Modal/SidebarModal';
import { Panel } from '@proton/pass/components/Layout/Panel/Panel';
import { PanelHeader } from '@proton/pass/components/Layout/Panel/PanelHeader';
import type { SanitizedAliasOptions } from '@proton/pass/hooks/useAliasOptions';
import { validateAliasForm } from '@proton/pass/lib/validation/alias';
import { selectAliasLimits } from '@proton/pass/store/selectors';
import type { AliasFormValues, MaybeNull } from '@proton/pass/types';
import noop from '@proton/utils/noop';
export type AliasModalRef = {
open: () => void;
};
type AliasModalProps<T extends AliasFormValues> = {
shareId: string;
form: FormikContextType<T>;
aliasOptions: MaybeNull<SanitizedAliasOptions>;
loading: boolean;
handleSubmitClick: () => void;
} & ModalProps;
export const AliasModal = <T extends AliasFormValues>({
open,
form,
shareId,
aliasOptions,
loading,
handleSubmitClick,
...modalProps
}: AliasModalProps<T>) => {
const [ready, setReady] = useState(false);
const { needsUpgrade } = useSelector(selectAliasLimits);
useEffect(() => {
if (open && aliasOptions) {
const firstSuffix = aliasOptions.suffixes?.[0];
const firstMailBox = aliasOptions.mailboxes?.[0];
form.setValues(
(values) => ({
...values,
...(firstSuffix && { aliasSuffix: firstSuffix }),
...(firstMailBox && { mailboxes: [firstMailBox] }),
}),
true
).catch(noop);
setReady(true);
}
}, [open, aliasOptions]);
return (
<SidebarModal {...modalProps} open={open}>
<Panel
className="ui-violet"
header={
<PanelHeader
actions={[
<Button
key="modal-close-button"
className="flex-item-noshrink"
icon
pill
shape="solid"
onClick={modalProps.onClose}
>
<Icon className="modal-close-icon" name="cross" alt={c('Action').t`Close`} />
</Button>,
/* if user has reached his alias limit prompt
* him to upgrade his plan*/
needsUpgrade ? (
<UpgradeButton key="upgrade-button" />
) : (
<Button
className="text-sm"
key="modal-submit-button"
onClick={handleSubmitClick}
color="norm"
pill
disabled={!(ready && Object.keys(validateAliasForm(form.values)).length === 0)}
>
{c('Action').t`Confirm`}
</Button>
),
]}
/>
}
>
{needsUpgrade && (
<Card>
{c('Info')
.t`You have reached the limit of aliases you can create. Create an unlimited number of aliases when you upgrade your subscription.`}
</Card>
)}
<FormikProvider value={form}>
<AliasPreview
className="mt-6"
prefix={form.values.aliasPrefix ?? '<prefix>'}
suffix={form.values.aliasSuffix?.value ?? '<suffix>'}
loading={loading}
/>
<AliasForm<T> form={form} aliasOptions={aliasOptions} loading={loading} />
</FormikProvider>
</Panel>
</SidebarModal>
);
};
| 7,583
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Alias/Alias.new.tsx
|
import { type VFC, useEffect, useMemo, useRef } from 'react';
import { useSelector } from 'react-redux';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { ValueControl } from '@proton/pass/components/Form/Field/Control/ValueControl';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { TextAreaField } from '@proton/pass/components/Form/Field/TextareaField';
import { TitleField } from '@proton/pass/components/Form/Field/TitleField';
import { VaultSelectField } from '@proton/pass/components/Form/Field/VaultSelectField';
import { AliasForm } from '@proton/pass/components/Item/Alias/Alias.form';
import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton';
import { Card } from '@proton/pass/components/Layout/Card/Card';
import { ItemCreatePanel } from '@proton/pass/components/Layout/Panel/ItemCreatePanel';
import type { ItemNewViewProps } from '@proton/pass/components/Views/types';
import { MAX_ITEM_NAME_LENGTH, MAX_ITEM_NOTE_LENGTH } from '@proton/pass/constants';
import { useAliasOptions } from '@proton/pass/hooks/useAliasOptions';
import { useDraftSync } from '@proton/pass/hooks/useItemDraft';
import { deriveAliasPrefix, reconciliateAliasFromDraft, validateNewAliasForm } from '@proton/pass/lib/validation/alias';
import { selectAliasLimits, selectUserVerified, selectVaultLimits } from '@proton/pass/store/selectors';
import type { MaybeNull, NewAliasFormValues } from '@proton/pass/types';
import { awaiter } from '@proton/pass/utils/fp/promises';
import { obfuscate } from '@proton/pass/utils/obfuscate/xor';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import noop from '@proton/utils/noop';
const FORM_ID = 'new-alias';
export const AliasNew: VFC<ItemNewViewProps<'alias'>> = ({ shareId, url, onSubmit, onCancel }) => {
const { domain, subdomain, displayName } = url ?? {};
const { needsUpgrade } = useSelector(selectAliasLimits);
const { vaultTotalCount } = useSelector(selectVaultLimits);
const userVerified = useSelector(selectUserVerified);
const { current: draftHydrated } = useRef(awaiter<MaybeNull<NewAliasFormValues>>());
const { aliasPrefix: defaultAliasPrefix, ...defaults } = useMemo(() => {
const url = subdomain ?? domain ?? '';
const validURL = url !== null;
return {
name: validURL ? url : '',
note: validURL ? c('Placeholder').t`Used on ${url}` : '',
aliasPrefix: displayName ? deriveAliasPrefix(displayName) : '',
};
}, []);
/* set initial `aliasPrefix` to an empty string to avoid a
* form error state if `aliasOptions` have not loaded yet */
const initialValues: NewAliasFormValues = useMemo(
() => ({
shareId,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
...defaults,
}),
[]
);
const form = useFormik<NewAliasFormValues>({
initialValues,
initialErrors: validateNewAliasForm(initialValues),
onSubmit: ({ name, note, shareId, aliasPrefix, aliasSuffix, mailboxes }) => {
if (needsUpgrade) return;
if (aliasPrefix !== undefined && aliasSuffix !== undefined) {
const optimisticId = uniqueId();
onSubmit({
type: 'alias',
optimisticId,
shareId,
createTime: getEpoch(),
metadata: {
name,
note: obfuscate(note),
itemUuid: optimisticId,
},
content: {},
extraFields: [],
extraData: {
mailboxes,
prefix: aliasPrefix,
signedSuffix: aliasSuffix.signature,
aliasEmail: aliasPrefix + aliasSuffix.value,
},
});
}
},
validate: validateNewAliasForm,
validateOnChange: true,
});
const aliasOptions = useAliasOptions({
shareId,
onAliasOptionsLoaded: async (options) => {
const draft = await draftHydrated;
const formValues = draft ?? form.values;
const firstSuffix = options.suffixes[0];
const firstMailBox = options.mailboxes[0];
const prefixFromURL = !isEmptyString(defaultAliasPrefix);
const aliasPrefix = prefixFromURL ? defaultAliasPrefix : deriveAliasPrefix(formValues.name);
const defaultAlias = { aliasPrefix, aliasSuffix: firstSuffix, mailboxes: [firstMailBox] };
const draftAlias = draft ? reconciliateAliasFromDraft(formValues, options, defaultAlias) : null;
const values = { ...formValues, ...(draftAlias ?? defaultAlias) };
const errors = validateNewAliasForm(values);
if (draft) {
await form.setValues(values);
form.setErrors(errors);
} else form.resetForm({ values, errors });
},
lazy: !userVerified,
});
const draft = useDraftSync<NewAliasFormValues>(form, {
type: 'alias',
mode: 'new',
itemId: 'draft-alias',
shareId: form.values.shareId,
onHydrated: draftHydrated.resolve,
});
const { values, touched, setFieldValue } = form;
const { name, aliasPrefix, aliasSuffix } = values;
useEffect(() => {
/* update the aliasPrefix with the item's name only :
- if it hasn't been touched by the user yet
- a default alias prefix was not resolved */
void draftHydrated.then((hydrated) => {
if (!hydrated && !defaultAliasPrefix && !touched.aliasPrefix) {
setFieldValue('aliasPrefix', deriveAliasPrefix(name), true).catch(noop);
}
});
}, [name, touched.aliasPrefix]);
return (
<ItemCreatePanel
type="alias"
formId={FORM_ID}
handleCancelClick={onCancel}
valid={form.isValid && userVerified}
discardable={!form.dirty}
/* if user has reached his alias limit: disable submit and prompt for upgrade */
renderSubmitButton={needsUpgrade ? <UpgradeButton key="upgrade-button" /> : undefined}
>
{({ didEnter }) => (
<>
{needsUpgrade && (
<Card className="mb-2">
{c('Info')
.t`You have reached the limit of aliases you can create. Create an unlimited number of aliases when you upgrade your subscription.`}
</Card>
)}
{!userVerified && (
<Card className="mb-2">
{c('Warning').t`Please verify your email address in order to use email aliases`}
</Card>
)}
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
{vaultTotalCount > 1 && (
<Field component={VaultSelectField} label={c('Label').t`Vault`} name="shareId" />
)}
<Field
lengthLimiters
name="name"
label={c('Label').t`Title`}
placeholder={c('Label').t`Untitled`}
component={TitleField}
autoFocus={!draft && didEnter && !needsUpgrade}
key={`alias-name-${didEnter}`}
maxLength={MAX_ITEM_NAME_LENGTH}
disabled={!userVerified}
/>
</FieldsetCluster>
<FieldsetCluster mode="read" as="div">
<ValueControl
icon="alias"
label={c('Label').t`You are about to create`}
loading={aliasOptions.loading}
error={Boolean(
Object.keys(form.touched).length > 0 &&
(form.errors.aliasPrefix || form.errors.aliasSuffix)
)}
>
{`${aliasPrefix}${aliasSuffix?.value ?? ''}`}
</ValueControl>
</FieldsetCluster>
<AliasForm aliasOptions={aliasOptions.value} loading={aliasOptions.loading} form={form} />
<FieldsetCluster>
<Field
name="note"
label={c('Label').t`Note`}
placeholder={c('Placeholder').t`Enter a note...`}
component={TextAreaField}
icon="note"
maxLength={MAX_ITEM_NOTE_LENGTH}
disabled={!userVerified}
/>
</FieldsetCluster>
</Form>
</FormikProvider>
</>
)}
</ItemCreatePanel>
);
};
| 7,584
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Alias/Alias.view.tsx
|
import { type MouseEvent, type VFC, useCallback, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { c, msgid } from 'ttag';
import { InlineLinkButton, useNotifications } from '@proton/components';
import { ConfirmationModal } from '@proton/pass/components/Confirmation/ConfirmationModal';
import { ValueControl } from '@proton/pass/components/Form/Field/Control/ValueControl';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { TextAreaReadonly } from '@proton/pass/components/Form/legacy/TextAreaReadonly';
import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton';
import { MoreInfoDropdown } from '@proton/pass/components/Layout/Dropdown/MoreInfoDropdown';
import { ItemViewPanel } from '@proton/pass/components/Layout/Panel/ItemViewPanel';
import type { ItemViewProps } from '@proton/pass/components/Views/types';
import { useActionRequest } from '@proton/pass/hooks/useActionRequest';
import { useDeobfuscatedValue } from '@proton/pass/hooks/useDeobfuscatedValue';
import { getAliasDetailsIntent } from '@proton/pass/store/actions';
import { aliasDetailsRequest } from '@proton/pass/store/actions/requests';
import { selectAliasDetails, selectLoginItemByUsername } from '@proton/pass/store/selectors';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { getFormattedDateFromTimestamp } from '@proton/pass/utils/time/format';
export const AliasView: VFC<ItemViewProps<'alias'>> = ({ vault, revision, ...itemViewProps }) => {
const history = useHistory();
const { createNotification } = useNotifications();
const { data: item, itemId, createTime, modifyTime, revision: revisionNumber } = revision;
const { name } = item.metadata;
const { shareId } = vault;
const { optimistic, trashed } = itemViewProps;
const aliasEmail = revision.aliasEmail!;
const relatedLogin = useSelector(selectLoginItemByUsername(aliasEmail));
const relatedLoginName = relatedLogin?.data.metadata.name ?? '';
const note = useDeobfuscatedValue(item.metadata.note);
const getAliasDetails = useActionRequest({
action: getAliasDetailsIntent,
initialRequestId: aliasDetailsRequest(aliasEmail),
onFailure: () => {
createNotification({
type: 'warning',
text: c('Warning').t`Cannot retrieve mailboxes for this alias right now`,
});
},
});
const mailboxesForAlias = useSelector(selectAliasDetails(aliasEmail!));
const [confirmTrash, setConfirmTrash] = useState(false);
const ready = !(getAliasDetails.loading && mailboxesForAlias === undefined);
const createLoginFromAlias = (evt: MouseEvent) => {
evt.stopPropagation();
evt.preventDefault();
history.push(`/item/new/login?username=${aliasEmail}`);
};
useEffect(() => {
if (!optimistic) getAliasDetails.dispatch({ shareId, itemId, aliasEmail });
}, [optimistic, shareId, itemId, aliasEmail]);
const handleMoveToTrashClick = useCallback(() => {
if (!relatedLogin) return itemViewProps.handleMoveToTrashClick();
return setConfirmTrash(true);
}, [relatedLogin, itemViewProps.handleMoveToTrashClick]);
return (
<ItemViewPanel
type="alias"
name={name}
vault={vault}
{...itemViewProps}
{...(!trashed
? {
quickActions: [
<DropdownMenuButton
key="create-login"
onClick={createLoginFromAlias}
icon="user"
label={c('Action').t`Create login`}
/>,
],
}
: {})}
handleMoveToTrashClick={handleMoveToTrashClick}
>
<FieldsetCluster mode="read" as="div">
<ValueControl
clickToCopy
icon="alias"
label={c('Label').t`Alias address`}
value={aliasEmail ?? undefined}
{...(!trashed
? {
extra: (
<InlineLinkButton className="text-underline" onClick={createLoginFromAlias}>{c(
'Action'
).t`Create login`}</InlineLinkButton>
),
}
: {})}
/>
<ValueControl as="ul" loading={!ready} icon="arrow-up-and-right-big" label={c('Label').t`Forwards to`}>
{mailboxesForAlias?.map(({ email }) => (
<li key={email} className="text-ellipsis">
{email}
</li>
))}
</ValueControl>
</FieldsetCluster>
{note && (
<FieldsetCluster mode="read" as="div">
<ValueControl
clickToCopy
as={TextAreaReadonly}
icon="note"
label={c('Label').t`Note`}
value={note}
/>
</FieldsetCluster>
)}
<MoreInfoDropdown
info={[
{
label: c('Label').t`Modified`,
values: [
c('Info').ngettext(
msgid`${revisionNumber} time`,
`${revisionNumber} times`,
revisionNumber
),
getFormattedDateFromTimestamp(modifyTime),
],
},
{ label: c('Label').t`Created`, values: [getFormattedDateFromTimestamp(createTime)] },
]}
/>
<ConfirmationModal
open={confirmTrash}
title={c('Warning').t`Trash alias ?`}
alertText={c('Warning')
.t`Alias "${name}" is currently used in login item "${relatedLoginName}". You will also stop receiving emails sent to "${aliasEmail}"`}
submitText={c('Action').t`Move to trash`}
onClose={() => setConfirmTrash(false)}
onSubmit={pipe(() => setConfirmTrash(false), itemViewProps.handleMoveToTrashClick)}
/>
</ItemViewPanel>
);
};
| 7,585
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Containers/ItemEdit.tsx
|
import { type VFC } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Redirect, useParams } from 'react-router-dom';
import { useNavigation } from '@proton/pass/components/Core/NavigationProvider';
import { getLocalPath, preserveSearch } from '@proton/pass/components/Core/routing';
import { AliasEdit } from '@proton/pass/components/Item/Alias/Alias.edit';
import { CreditCardEdit } from '@proton/pass/components/Item/CreditCard/CreditCard.edit';
import { LoginEdit } from '@proton/pass/components/Item/Login/Login.edit';
import { NoteEdit } from '@proton/pass/components/Item/Note/Note.edit';
import type { ItemEditViewProps } from '@proton/pass/components/Views/types';
import { itemEditIntent } from '@proton/pass/store/actions';
import { selectItemByShareIdAndId, selectShare } from '@proton/pass/store/selectors';
import type { ItemEditIntent, ItemType, SelectedItem, ShareType } from '@proton/pass/types';
const itemEditMap: { [T in ItemType]: VFC<ItemEditViewProps<T>> } = {
login: LoginEdit,
note: NoteEdit,
alias: AliasEdit,
creditCard: CreditCardEdit,
};
export const ItemEdit: VFC = () => {
const { shareId, itemId } = useParams<SelectedItem>();
const { selectItem } = useNavigation();
const dispatch = useDispatch();
const vault = useSelector(selectShare<ShareType.Vault>(shareId));
const item = useSelector(selectItemByShareIdAndId(shareId, itemId));
const handleSubmit = (data: ItemEditIntent) => {
dispatch(itemEditIntent(data));
selectItem(shareId, itemId, { mode: 'replace' });
};
if (!(item && vault)) return <Redirect to={preserveSearch(getLocalPath('/'))} push={false} />;
const EditViewComponent = itemEditMap[item.data.type] as VFC<ItemEditViewProps>;
return (
<EditViewComponent
vault={vault}
revision={item}
onSubmit={handleSubmit}
url={null}
onCancel={() => selectItem(shareId, itemId, { mode: 'replace' })}
/>
);
};
| 7,586
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Containers/ItemNew.tsx
|
import type { VFC } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useParams } from 'react-router-dom';
import { useNavigation } from '@proton/pass/components/Core/NavigationProvider';
import type { ItemNewRouteParams } from '@proton/pass/components/Core/routing';
import { AliasNew } from '@proton/pass/components/Item/Alias/Alias.new';
import { CreditCardNew } from '@proton/pass/components/Item/CreditCard/CreditCard.new';
import { LoginNew } from '@proton/pass/components/Item/Login/Login.new';
import { NoteNew } from '@proton/pass/components/Item/Note/Note.new';
import type { ItemNewViewProps } from '@proton/pass/components/Views/types';
import { itemCreationIntent } from '@proton/pass/store/actions';
import { selectDefaultVault, selectVaultLimits } from '@proton/pass/store/selectors';
import type { ItemCreateIntent, ItemType } from '@proton/pass/types';
const itemNewMap: { [T in ItemType]: VFC<ItemNewViewProps<T>> } = {
login: LoginNew,
note: NoteNew,
alias: AliasNew,
creditCard: CreditCardNew,
};
export const ItemNew: VFC = () => {
const { selectItem, setFilters, filters } = useNavigation();
const selectedShareId = filters.selectedShareId;
const history = useHistory();
const dispatch = useDispatch();
const { type } = useParams<ItemNewRouteParams>();
const { didDowngrade } = useSelector(selectVaultLimits);
/* if user downgraded - always auto-select the default vault id */
const defaultVault = useSelector(selectDefaultVault);
const shareId = didDowngrade ? defaultVault.shareId : selectedShareId ?? defaultVault.shareId;
const ItemNewComponent = itemNewMap[type];
const handleSubmit = (createIntent: ItemCreateIntent) => {
dispatch(itemCreationIntent(createIntent));
/* if the user put the item in a vault which is currently not selected,
* autoselect it so the following call to `selectItem` passes */
if (selectedShareId && selectedShareId !== createIntent.shareId) {
setFilters({ selectedShareId: createIntent.shareId });
}
selectItem(createIntent.shareId, createIntent.optimisticId);
};
const handleCancel = () => history.goBack();
return <ItemNewComponent shareId={shareId} onSubmit={handleSubmit} onCancel={handleCancel} url={null} />;
};
| 7,587
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Containers/ItemView.tsx
|
import { type VFC, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Redirect, useParams } from 'react-router-dom';
import { c } from 'ttag';
import { useNavigation } from '@proton/pass/components/Core/NavigationProvider';
import { getItemRoute, getLocalPath, preserveSearch } from '@proton/pass/components/Core/routing';
import { useInviteContext } from '@proton/pass/components/Invite/InviteContextProvider';
import { VaultInviteFromItemModal } from '@proton/pass/components/Invite/VaultInviteFromItemModal';
import { AliasView } from '@proton/pass/components/Item/Alias/Alias.view';
import { CreditCardView } from '@proton/pass/components/Item/CreditCard/CreditCard.view';
import { LoginView } from '@proton/pass/components/Item/Login/Login.view';
import { NoteView } from '@proton/pass/components/Item/Note/Note.view';
import { VaultSelect, useVaultSelectModalHandles } from '@proton/pass/components/Vault/VaultSelect';
import type { ItemViewProps } from '@proton/pass/components/Views/types';
import { isTrashed } from '@proton/pass/lib/items/item.predicates';
import { getItemActionId } from '@proton/pass/lib/items/item.utils';
import {
itemCreationDismiss,
itemCreationIntent,
itemDeleteIntent,
itemEditDismiss,
itemEditIntent,
itemMoveIntent,
itemRestoreIntent,
itemTrashIntent,
} from '@proton/pass/store/actions';
import selectFailedAction from '@proton/pass/store/optimistic/selectors/select-failed-action';
import {
selectByShareId,
selectItemWithOptimistic,
selectResolvedOptimisticId,
selectShare,
selectWritableSharedVaultsWithItemsCount,
selectWritableVaultsWithItemsCount,
} from '@proton/pass/store/selectors';
import type { ItemType, SelectedItem, ShareType } from '@proton/pass/types';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
const itemTypeViewMap: { [T in ItemType]: VFC<ItemViewProps<T>> } = {
login: LoginView,
note: NoteView,
alias: AliasView,
creditCard: CreditCardView,
};
export const ItemView: VFC = () => {
const { selectItem } = useNavigation();
const inviteContext = useInviteContext();
const dispatch = useDispatch();
const { shareId, itemId } = useParams<SelectedItem>();
const [inviteOpen, setInviteOpen] = useState(false);
const { closeVaultSelect, openVaultSelect, modalState } = useVaultSelectModalHandles();
const optimisticItemId = getItemActionId({ itemId, shareId });
const optimisticResolved = useSelector(selectResolvedOptimisticId(itemId));
const itemSelector = useMemo(() => selectItemWithOptimistic(shareId, itemId), [shareId, itemId]);
const failedItemActionSelector = pipe(selectByShareId, selectFailedAction(optimisticItemId));
const vault = useSelector(selectShare<ShareType.Vault>(shareId));
const item = useSelector(itemSelector);
const failure = useSelector(failedItemActionSelector);
/* if vault or item cannot be found : redirect to base path */
if (!(vault && item)) return <Redirect to={preserveSearch(getLocalPath('/'))} push={false} />;
/* if the item is optimistic and can be resolved to a non-optimistic item : replace */
if (optimisticResolved) return <Redirect to={preserveSearch(getItemRoute(shareId, item.itemId))} push={false} />;
const trashed = isTrashed(item);
const handleEdit = () => selectItem(shareId, itemId, { view: 'edit', mode: 'replace' });
const handleRetry = () => failure !== undefined && dispatch(failure.action);
const handleTrash = () => dispatch(itemTrashIntent({ itemId, shareId, item }));
const handleMove = () => openVaultSelect(item.shareId, selectWritableVaultsWithItemsCount);
const handleMoveToSharedVault = () => openVaultSelect(item.shareId, selectWritableSharedVaultsWithItemsCount);
const handleRestore = () => dispatch(itemRestoreIntent({ item, itemId, shareId }));
const handleDelete = () => dispatch(itemDeleteIntent({ item, itemId, shareId }));
const handleInviteClick = () => setInviteOpen(true);
const handleVaultManage = () => inviteContext.manageAccess(shareId);
const handleCreateSharedVault = () => {
inviteContext.createSharedVault({ item: { shareId, itemId } });
setInviteOpen(false);
};
const handleShareVaultClick = () => {
inviteContext.createInvite({ vault });
setInviteOpen(false);
};
const handleDismiss = () => {
if (failure === undefined) return;
if (itemCreationIntent.match(failure.action)) {
dispatch(itemCreationDismiss({ shareId, optimisticId: itemId, item }));
}
if (itemEditIntent.match(failure.action)) {
dispatch(itemEditDismiss({ shareId, itemId, item }));
}
};
const doMoveItem = (destinationShareId: string) => {
const optimisticId = uniqueId();
dispatch(itemMoveIntent({ item, shareId: destinationShareId, optimisticId }));
selectItem(destinationShareId, optimisticId, { mode: 'replace' });
closeVaultSelect();
setInviteOpen(false);
};
const ItemTypeViewComponent = itemTypeViewMap[item.data.type] as VFC<ItemViewProps>;
return (
<>
<ItemTypeViewComponent
key={item.itemId}
vault={vault}
revision={item}
handleEditClick={handleEdit}
handleRetryClick={handleRetry}
handleMoveToTrashClick={handleTrash}
handleMoveToVaultClick={handleMove}
handleDismissClick={handleDismiss}
handleRestoreClick={handleRestore}
handleDeleteClick={handleDelete}
handleInviteClick={handleInviteClick}
handleManageClick={handleVaultManage}
optimistic={item.optimistic}
failed={item.failed}
trashed={trashed}
/>
<VaultSelect
downgradeMessage={c('Info')
.t`You have exceeded the number of vaults included in your subscription. Items can only be moved to your first two vaults. To move items between all vaults upgrade your subscription.`}
onSubmit={doMoveItem}
onClose={closeVaultSelect}
{...modalState}
/>
<VaultInviteFromItemModal
vault={vault}
shareId={shareId}
itemId={itemId}
open={inviteOpen}
onClose={() => setInviteOpen(false)}
handleMoveToSharedVaultClick={handleMoveToSharedVault}
handleShareVaultClick={handleShareVaultClick}
handleCreateSharedVaultClick={handleCreateSharedVault}
/>
</>
);
};
| 7,588
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/CreditCard/CreditCard.edit.tsx
|
import { type VFC } from 'react';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { MaskedTextField } from '@proton/pass/components/Form/Field/MaskedTextField';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import { TextAreaField } from '@proton/pass/components/Form/Field/TextareaField';
import { TitleField } from '@proton/pass/components/Form/Field/TitleField';
import {
cardNumberHiddenValue,
cardNumberMask,
expDateMask,
} from '@proton/pass/components/Form/Field/masks/credit-card';
import { ItemEditPanel } from '@proton/pass/components/Layout/Panel/ItemEditPanel';
import type { ItemEditViewProps } from '@proton/pass/components/Views/types';
import { MAX_ITEM_NAME_LENGTH, MAX_ITEM_NOTE_LENGTH } from '@proton/pass/constants';
import { useDeobfuscatedItem } from '@proton/pass/hooks/useDeobfuscatedItem';
import { useDraftSync } from '@proton/pass/hooks/useItemDraft';
import type { CreditCardItemFormValues } from '@proton/pass/lib/validation/credit-card';
import { validateCreditCardForm } from '@proton/pass/lib/validation/credit-card';
import { CardType } from '@proton/pass/types/protobuf/item-v1';
import { obfuscate } from '@proton/pass/utils/obfuscate/xor';
const FORM_ID = 'edit-creditCard';
export const CreditCardEdit: VFC<ItemEditViewProps<'creditCard'>> = ({ vault, revision, onSubmit, onCancel }) => {
const { shareId } = vault;
const { data: item, itemId, revision: lastRevision } = revision;
const {
metadata: { name, note, itemUuid },
content,
} = useDeobfuscatedItem(item);
const initialValues: CreditCardItemFormValues = { ...content, shareId, name, note };
const form = useFormik<CreditCardItemFormValues>({
initialValues,
initialErrors: validateCreditCardForm(initialValues),
onSubmit: ({ name, note, ...creditCardValues }) => {
onSubmit({
type: 'creditCard',
shareId,
itemId,
lastRevision,
metadata: { name, note: obfuscate(note), itemUuid },
content: {
...creditCardValues,
cardType: CardType.Unspecified,
number: obfuscate(creditCardValues.number),
verificationNumber: obfuscate(creditCardValues.verificationNumber),
pin: obfuscate(creditCardValues.pin),
},
extraData: {},
extraFields: [],
});
},
validate: validateCreditCardForm,
validateOnChange: true,
});
useDraftSync<CreditCardItemFormValues>(form, {
type: 'creditCard',
mode: 'edit',
shareId: form.values.shareId,
itemId,
});
return (
<ItemEditPanel
type="creditCard"
formId={FORM_ID}
valid={form.isValid && form.dirty}
discardable={!form.dirty}
handleCancelClick={onCancel}
>
{() => (
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
<Field
lengthLimiters
name="name"
label={c('Label').t`Title`}
component={TitleField}
maxLength={MAX_ITEM_NAME_LENGTH}
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="cardholderName"
component={TextField}
icon="user"
label={c('Label').t`Name on card`}
placeholder={c('Placeholder').t`Full Name`}
/>
<Field
hidden
name="number"
component={MaskedTextField}
hiddenValue={cardNumberHiddenValue(form.values.number)}
icon="credit-card"
label={c('Label').t`Card number`}
mask={cardNumberMask(form.values.number)}
placeholder="1234 1234 1234 1234"
/>
<Field
name="expirationDate"
component={MaskedTextField}
icon="calendar-today"
label={c('Label').t`Expiration date`}
mask={expDateMask}
placeholder={c('Placeholder').t`MM/YYYY`}
/>
<Field
hidden
name="verificationNumber"
component={MaskedTextField}
hiddenValue="••••"
icon="credit-card"
label={c('Label').t`Security code`}
mask={{ mask: '0000' }}
placeholder="123"
/>
<Field
hidden
name="pin"
component={MaskedTextField}
hiddenValue="••••"
icon="grid-3"
label={c('Label').t`PIN`}
mask={{ mask: '000000000000' }}
placeholder="1234"
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="note"
label={c('Label').t`Note`}
placeholder={c('Placeholder').t`Add note`}
component={TextAreaField}
icon="note"
maxLength={MAX_ITEM_NOTE_LENGTH}
/>
</FieldsetCluster>
</Form>
</FormikProvider>
)}
</ItemEditPanel>
);
};
| 7,589
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/CreditCard/CreditCard.new.tsx
|
import { type VFC, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { MaskedTextField } from '@proton/pass/components/Form/Field/MaskedTextField';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import { TextAreaField } from '@proton/pass/components/Form/Field/TextareaField';
import { TitleField } from '@proton/pass/components/Form/Field/TitleField';
import { VaultSelectField } from '@proton/pass/components/Form/Field/VaultSelectField';
import {
cardNumberHiddenValue,
cardNumberMask,
expDateMask,
} from '@proton/pass/components/Form/Field/masks/credit-card';
import { ItemCreatePanel } from '@proton/pass/components/Layout/Panel/ItemCreatePanel';
import type { ItemNewViewProps } from '@proton/pass/components/Views/types';
import { MAX_ITEM_NAME_LENGTH, MAX_ITEM_NOTE_LENGTH } from '@proton/pass/constants';
import { useDraftSync } from '@proton/pass/hooks/useItemDraft';
import type { CreditCardItemFormValues } from '@proton/pass/lib/validation/credit-card';
import { validateCreditCardForm } from '@proton/pass/lib/validation/credit-card';
import { selectVaultLimits } from '@proton/pass/store/selectors';
import { CardType } from '@proton/pass/types/protobuf/item-v1';
import { obfuscate } from '@proton/pass/utils/obfuscate/xor';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
const FORM_ID = 'new-creditCard';
export const CreditCardNew: VFC<ItemNewViewProps<'creditCard'>> = ({ shareId, onSubmit, onCancel }) => {
const { vaultTotalCount } = useSelector(selectVaultLimits);
const initialValues: CreditCardItemFormValues = useMemo(() => {
return {
shareId,
name: '',
cardholderName: '',
number: '',
expirationDate: '',
verificationNumber: '',
pin: '',
note: '',
};
}, []);
const form = useFormik<CreditCardItemFormValues>({
initialValues,
initialErrors: validateCreditCardForm(initialValues),
onSubmit: ({ shareId, name, note, ...creditCardValues }) => {
const id = uniqueId();
onSubmit({
type: 'creditCard',
optimisticId: id,
shareId,
createTime: getEpoch(),
metadata: { name, note: obfuscate(note), itemUuid: id },
content: {
...creditCardValues,
cardType: CardType.Unspecified,
number: obfuscate(creditCardValues.number),
verificationNumber: obfuscate(creditCardValues.verificationNumber),
pin: obfuscate(creditCardValues.pin),
},
extraData: {},
extraFields: [],
});
},
validate: validateCreditCardForm,
validateOnBlur: true,
});
useDraftSync<CreditCardItemFormValues>(form, {
type: 'creditCard',
mode: 'new',
shareId: form.values.shareId,
itemId: 'draft-cc',
});
return (
<ItemCreatePanel
type="creditCard"
formId={FORM_ID}
valid={form.isValid}
handleCancelClick={onCancel}
discardable={!form.dirty}
>
{({ didEnter }) => (
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
{vaultTotalCount > 1 && (
<Field component={VaultSelectField} label={c('Label').t`Vault`} name="shareId" />
)}
<Field
lengthLimiters
name="name"
label={c('Label').t`Title`}
placeholder={c('Placeholder').t`Untitled`}
component={TitleField}
autoFocus={didEnter}
key={`creditCard-name-${didEnter}`}
maxLength={MAX_ITEM_NAME_LENGTH}
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="cardholderName"
component={TextField}
icon="user"
label={c('Label').t`Name on card`}
placeholder={c('Placeholder').t`Full Name`}
/>
<Field
hidden
name="number"
component={MaskedTextField}
hiddenValue={cardNumberHiddenValue(form.values.number)}
icon="credit-card"
label={c('Label').t`Card number`}
mask={cardNumberMask(form.values.number)}
placeholder="1234 1234 1234 1234"
/>
<Field
name="expirationDate"
component={MaskedTextField}
icon="calendar-today"
label={c('Label').t`Expiration date`}
mask={expDateMask}
placeholder={c('Placeholder').t`MM/YYYY`}
/>
<Field
hidden
name="verificationNumber"
component={MaskedTextField}
hiddenValue="••••"
icon="credit-card"
label={c('Label').t`Security code`}
mask={{ mask: '0000' }}
placeholder="123"
/>
<Field
hidden
name="pin"
component={MaskedTextField}
hiddenValue="••••"
icon="grid-3"
label={c('Label').t`PIN`}
mask={{ mask: '000000000000' }}
placeholder="1234"
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="note"
label={c('Label').t`Note`}
placeholder={c('Placeholder').t`Add note`}
component={TextAreaField}
icon="note"
maxLength={MAX_ITEM_NOTE_LENGTH}
/>
</FieldsetCluster>
</Form>
</FormikProvider>
)}
</ItemCreatePanel>
);
};
| 7,590
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/CreditCard/CreditCard.view.tsx
|
import { type VFC } from 'react';
import { useSelector } from 'react-redux';
import { c } from 'ttag';
import { MaskedValueControl } from '@proton/pass/components/Form/Field/Control/MaskedValueControl';
import { UpgradeControl } from '@proton/pass/components/Form/Field/Control/UpgradeControl';
import { ValueControl } from '@proton/pass/components/Form/Field/Control/ValueControl';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import {
cardNumberHiddenValue,
cardNumberMask,
expDateMask,
} from '@proton/pass/components/Form/Field/masks/credit-card';
import { TextAreaReadonly } from '@proton/pass/components/Form/legacy/TextAreaReadonly';
import { ItemViewPanel } from '@proton/pass/components/Layout/Panel/ItemViewPanel';
import type { ItemViewProps } from '@proton/pass/components/Views/types';
import { useDeobfuscatedItem } from '@proton/pass/hooks/useDeobfuscatedItem';
import { selectPassPlan } from '@proton/pass/store/selectors';
import { UserPassPlan } from '@proton/pass/types/api/plan';
export const CreditCardView: VFC<ItemViewProps<'creditCard'>> = ({ vault, revision, ...itemViewProps }) => {
const { data: item } = revision;
const {
metadata: { name, note },
content: { cardholderName, expirationDate, number, verificationNumber, pin },
} = useDeobfuscatedItem(item);
const isFreePlan = useSelector(selectPassPlan) === UserPassPlan.FREE;
return (
<ItemViewPanel type="creditCard" name={name} vault={vault} {...itemViewProps}>
<FieldsetCluster mode="read" as="div">
<ValueControl clickToCopy icon="user" label={c('Label').t`Name on card`} value={cardholderName} />
{isFreePlan ? (
<UpgradeControl icon="credit-card" label={c('Label').t`Card number`} />
) : (
<MaskedValueControl
clickToCopy
hidden
hiddenValue={cardNumberHiddenValue(number)}
icon="credit-card"
label={c('Label').t`Card number`}
mask={cardNumberMask(number)}
value={number}
/>
)}
<MaskedValueControl
clickToCopy
icon="calendar-today"
label={c('Label').t`Expiration date`}
mask={expDateMask}
value={expirationDate}
/>
<ValueControl
clickToCopy
hidden
hiddenValue="••••"
icon="shield"
label={c('Label').t`Security code`}
value={verificationNumber}
/>
<ValueControl hidden hiddenValue="••••" icon="grid-3" label={c('Label').t`PIN`} value={pin} />
</FieldsetCluster>
{note && (
<FieldsetCluster mode="read" as="div">
<ValueControl
clickToCopy
as={TextAreaReadonly}
icon="note"
label={c('Label').t`Note`}
value={note}
/>
</FieldsetCluster>
)}
</ItemViewPanel>
);
};
| 7,591
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Filters/Sort.tsx
|
import type { FC } from 'react';
import { c } from 'ttag';
import type { DropdownProps, IconName } from '@proton/components';
import { Dropdown, DropdownButton, DropdownMenu, Icon, usePopperAnchor } from '@proton/components';
import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton';
import { type ItemSortFilter } from '@proton/pass/types';
type Props = {
value: ItemSortFilter;
onChange: (value: ItemSortFilter) => void;
};
const getSortOptionDetails = (option: ItemSortFilter) => {
const options: Record<string, { label: string; shortLabel: string; icon: IconName }> = {
createTimeASC: {
// translator: this is sorting filter label from drop down menu
label: c('Label').t`Oldest to newest`,
// translator: this is short filter label for "Oldest to newest" (when filter is selected)
shortLabel: c('Label').t`Old-New`,
icon: 'arrow-down-arrow-up',
},
createTimeDESC: {
// translator: this is sorting filter label from drop down menu
label: c('Label').t`Newest to oldest`,
// translator: this is short filter label for "Newest to oldest" (when filter is selected)
shortLabel: c('Label').t`New-Old`,
icon: 'arrow-down-arrow-up',
},
recent: {
// translator: this is sorting filter label from drop down menu (Recent means items that have been recently used or updated ordered by time (today, last week, last 2 weeks, last month...))
label: c('Label').t`Most recent`,
// translator: this is short filter label for "Most recent" (when filter is selected)
shortLabel: c('Label').t`Recent`,
icon: 'clock',
},
titleASC: {
// translator: this is sorting filter label from drop down menu
label: c('Label').t`Alphabetical`,
// translator: this is short filter label for "Alphabetical" (when filter is selected)
shortLabel: c('Label').t`A-Z`,
icon: 'arrow-down-arrow-up',
},
};
return options[option];
};
const DROPDOWN_SIZE: DropdownProps['size'] = { width: '13rem' };
const ITEMS_SORT_OPTIONS: ItemSortFilter[] = ['recent', 'titleASC', 'createTimeDESC', 'createTimeASC'];
export const SortFilter: FC<Props> = ({ value, onChange }) => {
const { anchorRef, isOpen, close, toggle } = usePopperAnchor<HTMLButtonElement>();
return (
<>
<DropdownButton
onClick={toggle}
ref={anchorRef}
color="weak"
shape="solid"
size="small"
title={c('Action').t`Sort vault items`}
className="text-sm text-semibold flex-item-fluid-auto flex-item-nogrow flex-item-noshrink"
>
<span className="sr-only">{getSortOptionDetails(value).label}</span>
<Icon name={getSortOptionDetails(value).icon as IconName} className="inline mr-2" />
{getSortOptionDetails(value).shortLabel}
</DropdownButton>
<Dropdown
anchorRef={anchorRef}
isOpen={isOpen}
onClose={close}
offset={5}
originalPlacement="bottom-start"
size={DROPDOWN_SIZE}
>
<DropdownMenu>
{ITEMS_SORT_OPTIONS.map((type) => {
const { label, icon } = getSortOptionDetails(type);
return (
<DropdownMenuButton
key={type}
onClick={() => onChange(type)}
isSelected={value === type}
size="small"
label={label}
icon={icon}
ellipsis={false}
/>
);
})}
</DropdownMenu>
</Dropdown>
</>
);
};
| 7,592
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Filters/Type.tsx
|
import { type FC, useMemo } from 'react';
import { c } from 'ttag';
import type { DropdownProps, IconName } from '@proton/components';
import { Dropdown, DropdownButton, DropdownMenu, Icon, usePopperAnchor } from '@proton/components';
import { CountLabel } from '@proton/pass/components/Layout/Dropdown/CountLabel';
import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton';
import { itemTypeToIconName } from '@proton/pass/components/Layout/Icon/ItemIcon';
import type { ItemRevisionWithOptimistic, ItemTypeFilter } from '@proton/pass/types';
type Props = {
items: ItemRevisionWithOptimistic[];
value: ItemTypeFilter;
onChange: (value: ItemTypeFilter) => void;
};
const DROPDOWN_SIZE: DropdownProps['size'] = { width: '12rem' };
export const getItemTypeOptions = (): { [key in ItemTypeFilter]: { label: string; icon: IconName } } => ({
'*': {
label: c('Label').t`All`,
icon: 'grid-2',
},
login: {
label: c('Label').t`Logins`,
icon: itemTypeToIconName.login,
},
alias: {
label: c('Label').t`Aliases`,
icon: itemTypeToIconName.alias,
},
creditCard: {
label: c('Label').t`Cards`,
icon: itemTypeToIconName.creditCard,
},
note: {
label: c('Label').t`Notes`,
icon: itemTypeToIconName.note,
},
});
export const TypeFilter: FC<Props> = ({ items, value, onChange }) => {
const { anchorRef, isOpen, close, toggle } = usePopperAnchor<HTMLButtonElement>();
const options = useMemo(
() =>
Object.entries(getItemTypeOptions()).map(([type, { label, icon }]) => ({
type: type as ItemTypeFilter,
label,
icon,
count: type === '*' ? items.length : items.filter((item) => item.data.type === type).length,
})),
[items]
);
const selectedOption = options.find(({ type }) => type === value)!;
return (
<>
<DropdownButton
className="flex text-sm text-semibold flex-item-fluid-auto flex-item-nogrow flex-item-noshrink"
onClick={toggle}
ref={anchorRef}
color="weak"
shape="solid"
size="small"
title={c('Action').t`Filter vault items`}
>
<Icon name={selectedOption.icon} className="inline mr-2" />
{`${selectedOption.label} (${selectedOption.count})`}
</DropdownButton>
<Dropdown
anchorRef={anchorRef}
isOpen={isOpen}
onClose={close}
originalPlacement="bottom-start"
size={DROPDOWN_SIZE}
>
<DropdownMenu>
{options.map(({ type, count, label, icon }) => (
<DropdownMenuButton
key={type}
onClick={() => onChange(type)}
isSelected={type === value}
size="small"
label={<CountLabel label={label} count={count} />}
icon={icon}
/>
))}
</DropdownMenu>
</Dropdown>
</>
);
};
| 7,593
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/List/ItemsList.Item.scss
|
.button.pass-item-list--item {
border-radius: 0;
padding: 0;
&:focus-visible {
border-color: transparent;
box-shadow: none;
}
mark.is-light {
color: var(--interaction-norm);
font-weight: var(--font-weight-normal);
}
.pass-item-list--subtitle {
mark.is-light {
color: var(--interaction-weak-contrast);
font-weight: var(--font-weight-normal);
}
}
}
.button.is-active.pass-item-list--item {
background-color: var(--interaction-norm-minor-1);
}
| 7,594
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/List/ItemsList.Item.tsx
|
import { type VFC, memo } from 'react';
import { useSelector } from 'react-redux';
import { Link, type LinkProps } from 'react-router-dom';
import { ButtonLike, type ButtonLikeProps } from '@proton/atoms/Button';
import { Marks } from '@proton/components/components';
import { ItemIcon } from '@proton/pass/components/Layout/Icon/ItemIcon';
import { itemTypeToSubThemeClassName } from '@proton/pass/components/Layout/Theme/types';
import { VaultIcon } from '@proton/pass/components/Vault/VaultIcon';
import { matchChunks } from '@proton/pass/lib/search/match-chunks';
import { selectShare } from '@proton/pass/store/selectors';
import type { ItemRevisionWithOptimistic, ShareType } from '@proton/pass/types';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import clsx from '@proton/utils/clsx';
import { presentListItem } from './utils';
import './ItemsList.Item.scss';
type Props = Partial<LinkProps> &
ButtonLikeProps<any> & {
item: ItemRevisionWithOptimistic;
search?: string;
active?: boolean;
};
const ItemsListItemRaw: VFC<Props> = ({ item, search = '', active = false, ...rest }) => {
const { data, optimistic, failed, shareId } = item;
const { heading, subheading } = presentListItem(item);
const vault = useSelector(selectShare<ShareType.Vault>(shareId));
return (
<ButtonLike
as={Link}
to="#"
className={clsx([
'pass-item-list--item interactive-pseudo w-full relative',
optimistic && !failed && 'opacity-50',
active && 'is-active',
])}
color={failed ? 'warning' : 'weak'}
shape="ghost"
{...rest}
>
<div className="flex-nowrap flex w-full px-3 py-2 flex-align-items-center">
<ItemIcon
item={item}
size={20}
className={clsx('mr-3 flex-item-noshrink', itemTypeToSubThemeClassName[data.type])}
/>
<div className="text-left">
<span className="flex flex-align-items-center">
{search && (
<VaultIcon size={12} icon={vault?.content.display.icon} className="color-weak mr-1" />
)}
<span className="flex-item-fluid text-ellipsis">
<Marks chunks={matchChunks(heading, search)}>{heading}</Marks>
</span>
</span>
<div
className={clsx([
'pass-item-list--subtitle block color-weak text-sm text-ellipsis',
item.data.type === 'note' && isEmptyString(item.data.metadata.note.v) && 'text-italic',
])}
>
<Marks chunks={matchChunks(subheading, search)}>{subheading}</Marks>
</div>
</div>
</div>
</ButtonLike>
);
};
export const ItemsListItem = memo(ItemsListItemRaw);
| 7,595
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/List/ItemsList.tsx
|
import { type FC, type ReactElement, useEffect, useMemo, useRef } from 'react';
import type { List } from 'react-virtualized';
import { ItemsListItem } from '@proton/pass/components/Item/List/ItemsList.Item';
import { VirtualList } from '@proton/pass/components/Layout/List/VirtualList';
import { itemEq } from '@proton/pass/lib/items/item.predicates';
import { interpolateRecentItems } from '@proton/pass/lib/items/item.utils';
import type { ItemFilters, ItemRevisionWithOptimistic, SelectedItem } from '@proton/pass/types';
type Props = {
filters: ItemFilters;
items: ItemRevisionWithOptimistic[];
selectedItem?: SelectedItem;
totalCount: number;
onFilter: (update: Partial<ItemFilters>) => void;
onSelect: (shareId: string, itemId: string) => void;
placeholder: () => ReactElement;
};
export const ItemsList: FC<Props> = ({ items, filters, selectedItem, onSelect, placeholder }) => {
const listRef = useRef<List>(null);
useEffect(() => listRef.current?.scrollToRow(0), [filters.type, filters.sort]);
const { interpolation, interpolationIndexes } = useMemo(
() => interpolateRecentItems(items)(filters.sort === 'recent'),
[filters.type, filters.sort, items]
);
return (
<>
{items.length === 0 ? (
<div className="flex flex-justify-center flex-align-items-center w-full m-auto overflow-x-auto py-3">
{placeholder()}
</div>
) : (
<VirtualList
ref={listRef}
rowCount={interpolation.length}
interpolationIndexes={interpolationIndexes}
rowRenderer={({ style, index, key }) => {
const row = interpolation[index];
switch (row.type) {
case 'entry': {
const item = row.entry;
return (
<div style={style} key={key}>
<ItemsListItem
item={item}
onClick={(e) => {
e.preventDefault();
onSelect(item.shareId, item.itemId);
}}
id={`item-${item.shareId}-${item.itemId}`}
search={filters.search}
active={selectedItem && itemEq(selectedItem)(item)}
/>
</div>
);
}
case 'interpolation': {
return (
<div style={style} key={key} className="flex color-weak text-sm pt-2 pb-1 pl-3">
{row.cluster.label}
</div>
);
}
}
}}
/>
)}
</>
);
};
| 7,596
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/List/utils.ts
|
import { c } from 'ttag';
import { cardNumberHiddenValue } from '@proton/pass/components/Form/Field/masks/credit-card';
import type { ItemRevision, ItemType } from '@proton/pass/types';
import { deobfuscate } from '@proton/pass/utils/obfuscate/xor';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
type PresentedListItem = { heading: string; subheading: string };
type ItemListPresenterMap = { [T in ItemType]: (revision: ItemRevision<T>) => PresentedListItem };
const itemListPresenter: ItemListPresenterMap = {
note: ({ data }) => ({
heading: data.metadata.name,
subheading: isEmptyString(data.metadata.note.v) ? c('Warning').t`Empty note` : deobfuscate(data.metadata.note),
}),
login: ({ data }) => ({
heading: data.metadata.name,
subheading: deobfuscate(data.content.username),
}),
alias: ({ data, aliasEmail }) => ({
heading: data.metadata.name,
subheading: aliasEmail!,
}),
creditCard: ({ data }) => ({
heading: data.metadata.name,
subheading: cardNumberHiddenValue(deobfuscate(data.content.number)),
}),
};
export const presentListItem = <T extends ItemType>(revision: ItemRevision<T>): PresentedListItem =>
itemListPresenter[revision.data.type](revision);
| 7,597
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Login/Login.edit.tsx
|
import { type ReactElement, type VFC } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon } from '@proton/components';
import { ValueControl } from '@proton/pass/components/Form/Field/Control/ValueControl';
import { ExtraFieldGroup } from '@proton/pass/components/Form/Field/ExtraFieldGroup/ExtraFieldGroup';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { PasswordField } from '@proton/pass/components/Form/Field/PasswordField';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import { TextAreaField } from '@proton/pass/components/Form/Field/TextareaField';
import { TitleField } from '@proton/pass/components/Form/Field/TitleField';
import { UrlGroupField, createNewUrl } from '@proton/pass/components/Form/Field/UrlGroupField';
import { AliasModal } from '@proton/pass/components/Item/Alias/Alias.modal';
import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton';
import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton';
import { QuickActionsDropdown } from '@proton/pass/components/Layout/Dropdown/QuickActionsDropdown';
import { ItemEditPanel } from '@proton/pass/components/Layout/Panel/ItemEditPanel';
import type { ItemEditViewProps } from '@proton/pass/components/Views/types';
import { MAX_ITEM_NAME_LENGTH, MAX_ITEM_NOTE_LENGTH } from '@proton/pass/constants';
import { useAliasForLoginModal } from '@proton/pass/hooks/useAliasForLoginModal';
import { useDeobfuscatedItem } from '@proton/pass/hooks/useDeobfuscatedItem';
import { useDraftSync, useItemDraft } from '@proton/pass/hooks/useItemDraft';
import { obfuscateExtraFields } from '@proton/pass/lib/items/item.obfuscation';
import { getSecretOrUri, parseOTPValue } from '@proton/pass/lib/otp/otp';
import {
deriveAliasPrefix,
sanitizeLoginAliasHydration,
sanitizeLoginAliasSave,
} from '@proton/pass/lib/validation/alias';
import { validateLoginForm } from '@proton/pass/lib/validation/login';
import { itemCreationIntent } from '@proton/pass/store/actions';
import { passwordSave } from '@proton/pass/store/actions/creators/pw-history';
import { selectTOTPLimits } from '@proton/pass/store/selectors';
import type { EditLoginItemFormValues } from '@proton/pass/types';
import { prop } from '@proton/pass/utils/fp/lens';
import { obfuscate } from '@proton/pass/utils/obfuscate/xor';
import { merge } from '@proton/pass/utils/object/merge';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { parseUrl } from '@proton/pass/utils/url/parser';
const FORM_ID = 'edit-login';
export const LoginEdit: VFC<ItemEditViewProps<'login'>> = ({ revision, url, vault, onSubmit, onCancel }) => {
const dispatch = useDispatch();
const { needsUpgrade } = useSelector(selectTOTPLimits);
const { domain, subdomain } = url ?? {};
const { shareId } = vault;
const { data: item, itemId, revision: lastRevision } = revision;
const {
metadata: { name, note, itemUuid },
content: { username, password, urls, totpUri },
extraFields,
} = useDeobfuscatedItem(item);
const initialValues: EditLoginItemFormValues = {
name,
username,
password,
note,
shareId,
totpUri: getSecretOrUri(totpUri),
url: '',
urls: urls.map(createNewUrl),
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
extraFields,
};
const form = useFormik<EditLoginItemFormValues>({
initialValues,
initialErrors: validateLoginForm(initialValues),
onSubmit: ({ name, username, password, totpUri, url, urls, note, extraFields, ...values }) => {
const mutationTime = getEpoch();
const withAlias =
'withAlias' in values &&
values.withAlias &&
values.aliasSuffix !== undefined &&
!isEmptyString(values.aliasPrefix) &&
values.mailboxes.length > 0;
const normalizedOtpUri = parseOTPValue(totpUri, {
label: username || undefined,
issuer: name || undefined,
});
if (withAlias) {
const aliasOptimisticId = uniqueId();
dispatch(
itemCreationIntent({
type: 'alias',
optimisticId: aliasOptimisticId,
shareId,
createTime: mutationTime - 1 /* alias will be created before login in saga */,
metadata: {
name: `Alias for ${name}`,
note: obfuscate(''),
itemUuid: aliasOptimisticId,
},
content: {},
extraData: {
mailboxes: values.mailboxes,
prefix: values.aliasPrefix!,
signedSuffix: values.aliasSuffix!.signature,
aliasEmail: username,
},
extraFields: [],
})
);
}
onSubmit({
type: 'login',
itemId,
shareId,
lastRevision,
metadata: { name, note: obfuscate(note), itemUuid },
content: {
username: obfuscate(username),
password: obfuscate(password),
urls: Array.from(new Set(urls.map(({ url }) => url).concat(isEmptyString(url) ? [] : [url]))),
totpUri: obfuscate(normalizedOtpUri),
},
extraFields: obfuscateExtraFields(
extraFields.map((field) =>
field.type === 'totp'
? {
...field,
data: {
totpUri: parseOTPValue(field.data.totpUri, {
label: username || undefined,
issuer: name || undefined,
}),
},
}
: field
)
),
});
},
validate: validateLoginForm,
validateOnChange: true,
});
const showQuickAddUrl =
(subdomain || domain) &&
!form.values.urls
.map(prop('url'))
.concat(form.values.url)
.some((url) => url.includes(subdomain ?? domain!));
const itemDraft = useItemDraft<EditLoginItemFormValues>();
const aliasModal = useAliasForLoginModal(form, { lazy: !itemDraft?.formData.withAlias });
useDraftSync<EditLoginItemFormValues>(form, {
type: 'login',
mode: 'edit',
itemId: itemId,
shareId: form.values.shareId,
sanitizeSave: sanitizeLoginAliasSave,
sanitizeHydration: sanitizeLoginAliasHydration(aliasModal.aliasOptions),
});
return (
<>
<ItemEditPanel
type="login"
formId={FORM_ID}
valid={form.isValid && form.dirty}
discardable={!form.dirty}
handleCancelClick={onCancel}
>
{() => (
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
<Field
lengthLimiters
name="name"
label={c('Label').t`Title`}
component={TitleField}
maxLength={MAX_ITEM_NAME_LENGTH}
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="username"
label={(() => {
if (aliasModal.willCreate) return c('Label').t`Username (new alias)`;
if (aliasModal.relatedAlias) return c('Label').t`Username (alias)`;
return c('Label').t`Username`;
})()}
placeholder={c('Placeholder').t`Enter email or username`}
component={TextField}
itemType="login"
icon={aliasModal.usernameIsAlias ? 'alias' : 'user'}
actions={
[
aliasModal.willCreate && (
<QuickActionsDropdown color="weak" shape="solid" key="edit-alias">
<DropdownMenuButton
label={c('Action').t`Delete alias`}
icon="trash"
onClick={() =>
form.setValues((values) =>
merge(values, {
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
username: initialValues.username,
})
)
}
/>
</QuickActionsDropdown>
),
aliasModal.canCreate && (
<Button
icon
pill
color="weak"
shape="solid"
size="medium"
className="pass-item-icon"
title={c('Action').t`Generate alias`}
key="generate-alias"
tabIndex={-1}
onClick={() =>
form
.setValues((values) =>
merge(values, {
withAlias: true,
aliasPrefix: deriveAliasPrefix(values.name),
aliasSuffix: undefined,
mailboxes: [],
})
)
.then<any>(() => form.setFieldTouched('aliasPrefix', false))
.finally(() => aliasModal.setOpen(true))
}
>
<Icon name="alias" size={20} />
</Button>
),
].filter(Boolean) as ReactElement[]
}
/>
<Field
name="password"
label={c('Label').t`Password`}
placeholder={c('Placeholder').t`Enter password`}
component={PasswordField}
icon="key"
onPasswordGenerated={(value: string) => {
const { urls, url } = form.values;
const baseUrl = urls?.[0]?.url ?? url;
const { subdomain, domain, hostname } = parseUrl(baseUrl);
dispatch(
passwordSave({
id: uniqueId(),
value,
origin: subdomain ?? domain ?? hostname,
createTime: getEpoch(),
})
);
}}
/>
{
/* only allow adding a new TOTP code if user
* has not reached his plan's TOTP limit. If
* the user has downgraded and this item had
* a TOTP item, allow edit so user can retrieve
* the secret or remove it */
needsUpgrade && isEmptyString(form.values.totpUri) ? (
<ValueControl icon="lock" label={c('Label').t`2FA secret key (TOTP)`}>
<UpgradeButton inline />
</ValueControl>
) : (
<Field
hidden
name="totpUri"
label={c('Label').t`2FA secret key (TOTP)`}
placeholder={c('Placeholder').t`Add 2FA secret key`}
component={TextField}
icon="lock"
/>
)
}
</FieldsetCluster>
<FieldsetCluster>
<UrlGroupField
form={form}
renderExtraActions={
showQuickAddUrl
? ({ handleAdd }) => (
<Button
icon
color="norm"
shape="ghost"
size="small"
key="add-current-url"
title={c('Action').t`Add current URL`}
className="flex flex-align-items-center gap-1"
onClick={() => handleAdd(subdomain ?? domain!)}
>
<Icon name="plus" /> {c('Action').t`Add current URL`}
</Button>
)
: undefined
}
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="note"
label={c('Label').t`Note`}
placeholder={c('Placeholder').t`Add note`}
component={TextAreaField}
icon="note"
maxLength={MAX_ITEM_NOTE_LENGTH}
/>
</FieldsetCluster>
<ExtraFieldGroup form={form} />
</Form>
</FormikProvider>
)}
</ItemEditPanel>
<AliasModal
form={form}
shareId={shareId}
aliasOptions={aliasModal.aliasOptions}
loading={aliasModal.loading}
open={aliasModal.open}
onClose={() =>
form
.setValues((values) =>
merge(values, {
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
})
)
.then<any>(() => form.setFieldTouched('aliasPrefix', undefined))
.finally(() => aliasModal.setOpen(false))
}
handleSubmitClick={() =>
form
.setValues((values) => {
const { aliasPrefix, aliasSuffix } = values;
return !isEmptyString(aliasPrefix) && aliasSuffix
? merge(values, { username: aliasPrefix! + aliasSuffix!.value })
: values;
})
.then<any>(() => form.setFieldTouched('aliasPrefix', true))
.finally(() => aliasModal.setOpen(false))
}
/>
</>
);
};
| 7,598
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item
|
petrpan-code/ProtonMail/WebClients/packages/pass/components/Item/Login/Login.new.tsx
|
import { type ReactElement, type VFC, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { Form, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon } from '@proton/components/components/icon';
import { ValueControl } from '@proton/pass/components/Form/Field/Control/ValueControl';
import { ExtraFieldGroup } from '@proton/pass/components/Form/Field/ExtraFieldGroup/ExtraFieldGroup';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { PasswordField } from '@proton/pass/components/Form/Field/PasswordField';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import { TextAreaField } from '@proton/pass/components/Form/Field/TextareaField';
import { TitleField } from '@proton/pass/components/Form/Field/TitleField';
import { UrlGroupField, createNewUrl } from '@proton/pass/components/Form/Field/UrlGroupField';
import { VaultSelectField } from '@proton/pass/components/Form/Field/VaultSelectField';
import { AliasModal } from '@proton/pass/components/Item/Alias/Alias.modal';
import { UpgradeButton } from '@proton/pass/components/Layout/Button/UpgradeButton';
import { DropdownMenuButton } from '@proton/pass/components/Layout/Dropdown/DropdownMenuButton';
import { QuickActionsDropdown } from '@proton/pass/components/Layout/Dropdown/QuickActionsDropdown';
import { ItemCreatePanel } from '@proton/pass/components/Layout/Panel/ItemCreatePanel';
import type { ItemNewViewProps } from '@proton/pass/components/Views/types';
import { MAX_ITEM_NAME_LENGTH, MAX_ITEM_NOTE_LENGTH } from '@proton/pass/constants';
import { useAliasForLoginModal } from '@proton/pass/hooks/useAliasForLoginModal';
import { useDraftSync, useItemDraft } from '@proton/pass/hooks/useItemDraft';
import { obfuscateExtraFields } from '@proton/pass/lib/items/item.obfuscation';
import { parseOTPValue } from '@proton/pass/lib/otp/otp';
import {
deriveAliasPrefix,
sanitizeLoginAliasHydration,
sanitizeLoginAliasSave,
} from '@proton/pass/lib/validation/alias';
import { validateLoginForm } from '@proton/pass/lib/validation/login';
import { passwordSave } from '@proton/pass/store/actions/creators/pw-history';
import { selectTOTPLimits, selectVaultLimits } from '@proton/pass/store/selectors';
import type { LoginItemFormValues, NewLoginItemFormValues } from '@proton/pass/types';
import { type LoginWithAliasCreationDTO } from '@proton/pass/types';
import { obfuscate } from '@proton/pass/utils/obfuscate/xor';
import { merge } from '@proton/pass/utils/object/merge';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { isValidURL } from '@proton/pass/utils/url/is-valid-url';
import { parseUrl } from '@proton/pass/utils/url/parser';
const FORM_ID = 'new-login';
export const LoginNew: VFC<ItemNewViewProps<'login'>> = ({ shareId, url, onCancel, onSubmit }) => {
const { domain, subdomain } = url ?? {};
const dispatch = useDispatch();
const { search } = useLocation();
const { vaultTotalCount } = useSelector(selectVaultLimits);
const { needsUpgrade } = useSelector(selectTOTPLimits);
const initialValues: LoginItemFormValues = useMemo(() => {
const params = new URLSearchParams(search);
const maybeUrl = subdomain ?? domain ?? '';
const { valid, url } = isValidURL(maybeUrl);
return {
shareId,
name: maybeUrl,
username: params.get('username') ?? '',
password: '',
note: '',
totpUri: '',
url: valid ? createNewUrl(url).url : '',
urls: [],
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
extraFields: [],
};
}, []);
const form = useFormik<NewLoginItemFormValues>({
initialValues,
initialErrors: validateLoginForm(initialValues),
onSubmit: ({ name, note, username, password, shareId, totpUri, url, urls, extraFields, ...values }) => {
const createTime = getEpoch();
const optimisticId = uniqueId();
const withAlias =
values.withAlias &&
values.aliasSuffix !== undefined &&
!isEmptyString(values.aliasPrefix) &&
values.mailboxes.length > 0;
const extraData: LoginWithAliasCreationDTO = withAlias
? {
withAlias: true,
alias: {
type: 'alias',
optimisticId: `${optimisticId}-alias`,
shareId,
createTime,
metadata: {
name: `Alias for ${name}`,
note: obfuscate(''),
itemUuid: `${optimisticId}-alias`,
},
content: {},
extraData: {
mailboxes: values.mailboxes,
prefix: values.aliasPrefix!,
signedSuffix: values.aliasSuffix!.signature,
aliasEmail: username,
},
extraFields: [],
},
}
: { withAlias: false };
const normalizedOtpUri = parseOTPValue(totpUri, {
label: username || undefined,
issuer: name || undefined,
});
onSubmit({
type: 'login',
optimisticId,
shareId,
createTime,
metadata: {
name,
note: obfuscate(note),
itemUuid: optimisticId,
},
content: {
username: obfuscate(username),
password: obfuscate(password),
urls: Array.from(new Set(urls.map(({ url }) => url).concat(isEmptyString(url) ? [] : [url]))),
totpUri: obfuscate(normalizedOtpUri),
},
extraFields: obfuscateExtraFields(
extraFields.map((field) =>
field.type === 'totp'
? {
...field,
data: {
totpUri: parseOTPValue(field.data.totpUri, {
label: username || undefined,
issuer: name || undefined,
}),
},
}
: field
)
),
extraData,
});
},
validate: validateLoginForm,
validateOnBlur: true,
});
const itemDraft = useItemDraft<NewLoginItemFormValues>();
const aliasModal = useAliasForLoginModal(form, { lazy: !itemDraft?.formData.withAlias });
const draft = useDraftSync<NewLoginItemFormValues>(form, {
type: 'login',
mode: 'new',
itemId: 'draft-login',
shareId: form.values.shareId,
sanitizeSave: sanitizeLoginAliasSave,
sanitizeHydration: sanitizeLoginAliasHydration(aliasModal.aliasOptions),
});
return (
<>
<ItemCreatePanel
type="login"
formId={FORM_ID}
valid={form.isValid}
handleCancelClick={onCancel}
discardable={!form.dirty}
>
{({ didEnter }) => (
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
{vaultTotalCount > 1 && (
<Field component={VaultSelectField} label={c('Label').t`Vault`} name="shareId" />
)}
<Field
name="name"
label={c('Label').t`Title`}
placeholder={c('Placeholder').t`Untitled`}
component={TitleField}
autoFocus={!draft && didEnter}
key={`login-name-${didEnter}`}
maxLength={MAX_ITEM_NAME_LENGTH}
/>
</FieldsetCluster>
<FieldsetCluster>
<Field
name="username"
label={(() => {
if (aliasModal.willCreate) return c('Label').t`Username (new alias)`;
if (aliasModal.relatedAlias) return c('Label').t`Username (alias)`;
return c('Label').t`Username`;
})()}
placeholder={c('Placeholder').t`Enter email or username`}
component={TextField}
itemType="login"
icon={aliasModal.usernameIsAlias ? 'alias' : 'user'}
actions={
[
aliasModal.willCreate && (
<QuickActionsDropdown color="weak" shape="solid" key="edit-alias">
<DropdownMenuButton
label={c('Action').t`Delete alias`}
icon="trash"
onClick={() =>
form.setValues((values) =>
merge(values, {
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
username: initialValues.username,
})
)
}
/>
</QuickActionsDropdown>
),
aliasModal.canCreate && (
<Button
icon
pill
color="weak"
shape="solid"
size="medium"
className="pass-item-icon"
title={c('Action').t`Generate alias`}
key="generate-alias"
tabIndex={-1}
onClick={() =>
form
.setValues((values) =>
merge(values, {
withAlias: true,
aliasPrefix: deriveAliasPrefix(values.name),
aliasSuffix: undefined,
mailboxes: [],
})
)
.then<any>(() => form.setFieldTouched('aliasPrefix', false))
.finally(() => aliasModal.setOpen(true))
}
>
<Icon name="alias" size={20} />
</Button>
),
].filter(Boolean) as ReactElement[]
}
/>
<Field
name="password"
label={c('Label').t`Password`}
placeholder={c('Placeholder').t`Enter password`}
icon="key"
component={PasswordField}
onPasswordGenerated={(value: string) => {
const { urls, url } = form.values;
const baseUrl = urls?.[0]?.url ?? url;
const { subdomain, domain, hostname } = parseUrl(baseUrl);
dispatch(
passwordSave({
id: uniqueId(),
value,
origin: subdomain ?? domain ?? hostname,
createTime: getEpoch(),
})
);
}}
/>
{
/* only allow adding a new TOTP code if user
* has not reached his plan's TOTP limit */
needsUpgrade ? (
<ValueControl icon="lock" label={c('Label').t`2FA secret key (TOTP)`}>
<UpgradeButton inline />
</ValueControl>
) : (
<Field
hidden
name="totpUri"
label={c('Label').t`2FA secret key (TOTP)`}
placeholder={c('Placeholder').t`Add 2FA secret key`}
component={TextField}
icon="lock"
/>
)
}
</FieldsetCluster>
<FieldsetCluster>
<UrlGroupField form={form} />
</FieldsetCluster>
<FieldsetCluster>
<Field
name="note"
label={c('Label').t`Note`}
placeholder={c('Placeholder').t`Add note`}
component={TextAreaField}
icon="note"
maxLength={MAX_ITEM_NOTE_LENGTH}
/>
</FieldsetCluster>
<ExtraFieldGroup form={form} />
</Form>
</FormikProvider>
)}
</ItemCreatePanel>
<AliasModal
form={form}
shareId={shareId}
aliasOptions={aliasModal.aliasOptions}
loading={aliasModal.loading}
open={aliasModal.open}
onClose={() =>
form
.setValues((values) =>
merge(values, {
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
})
)
.then<any>(() => form.setFieldTouched('aliasPrefix', undefined))
.finally(() => aliasModal.setOpen(false))
}
handleSubmitClick={() =>
form
.setValues((values) => {
const { aliasPrefix, aliasSuffix } = values;
return !isEmptyString(aliasPrefix) && aliasSuffix
? merge(values, { username: aliasPrefix! + aliasSuffix!.value })
: values;
})
.then<any>(() => form.setFieldTouched('aliasPrefix', true))
.finally(() => aliasModal.setOpen(false))
}
/>
</>
);
};
| 7,599
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.