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
|
petrpan-code/ProtonMail/WebClients/packages/atoms/README.md
|
The 'atoms' of the atomic-design component-architecture paradigm: https://bradfrost.com/blog/post/atomic-web-design/
The 'atoms' folder is home to proton brand-identity design-system specific reusable components which work independently of the applications they are used inside of.
Fit the description of base components / presentational components / dumb components / pure components.
Necessarily compositional.
Ideally functional, controlled (only props in events out) & stateful only to the containment of local ui-logic e.g. hover / focus states.
1 module per component. Should be kept 1 level deep. No grouping or nesting (other than for purely semantic co-location as in a component is so complex that its implementation details spans across multiple files).
| 5,000
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/babel.config.js
|
module.exports = {
presets: ['@babel/preset-env', ['@babel/preset-react', { runtime: 'automatic' }], '@babel/preset-typescript'],
plugins: [
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-runtime',
'transform-require-context',
],
};
| 5,001
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/generateUID.ts
|
let current = 0;
const generateUID = (prefix?: string) => `${prefix || 'id'}-${current++}`;
export default generateUID;
| 5,002
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/globals.d.ts
|
/**
* Can't call this index.d.ts, otherwise it conflicts with index.ts
*/
declare module '*.mdx' {
const mdx: any;
export default mdx;
}
declare module '*.png' {
const img: string;
export default img;
}
| 5,003
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/index.ts
|
export * from './Avatar';
export * from './Button';
export * from './Card';
export * from './CircleLoader';
export * from './Donut';
export * from './Href';
export * from './Input';
export * from './Kbd';
export * from './NotificationDot';
export * from './Scroll';
export * from './Slider';
export * from './Stepper';
export * from './VerticalSteps';
export * from './Vr';
| 5,004
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/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|mutex-browser|pmcrypto|bip39)/)'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js',
},
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm)$': '@proton/components/__mocks__/fileMock.js',
'\\.(css|scss|less)$': '@proton/components/__mocks__/styleMock.js',
'\\.(md)$': '<rootDir>/src/__mocks__/mdMock.ts',
},
reporters: ['default', ['jest-junit', { outputName: 'test-report.xml' }]],
collectCoverageFrom: ['**/*.tsx', '!**/*.stories.tsx'],
coverageReporters: ['text', 'lcov', 'cobertura'],
coverageThreshold: {
global: {
branches: 66,
functions: 50,
lines: 51,
statements: 52,
},
},
};
| 5,005
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/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;
| 5,006
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/jest.setup.js
|
import '@testing-library/jest-dom';
| 5,007
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/jest.transform.js
|
// Custom Jest transform implementation that injects test-specific babel presets.
module.exports = require('babel-jest').default.createTransformer({
presets: ['@babel/preset-env', ['@babel/preset-react', { runtime: 'automatic' }], '@babel/preset-typescript'],
plugins: [
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-runtime',
'@babel/plugin-proposal-optional-chaining',
'transform-class-properties',
'transform-require-context',
],
});
| 5,008
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/package.json
|
{
"name": "@proton/atoms",
"description": "",
"license": "GPL-3.0",
"sideEffects": false,
"main": "index.ts",
"scripts": {
"check-types": "tsc",
"create-atom": "ts-node -P create-atom/tsconfig.create-atom.json create-atom/index",
"i18n:validate": "proton-i18n validate lint-functions",
"i18n:validate:context": "proton-i18n extract && proton-i18n validate",
"lint": "eslint . --ext .js,.ts,.tsx --quiet --cache",
"pretty": "prettier --write $(find . -path ./node_modules -prune -o -type f -name '*.js' -o -name '*.ts' -o -name '*.tsx')",
"storybook": "start-storybook -p 6006 --docs --no-manager-cache",
"storybook-raw": "start-storybook -p 6006",
"test": "jest --coverage --runInBand --ci",
"test:dev": "jest --watch"
},
"dependencies": {
"@proton/i18n": "workspace:packages/i18n",
"@proton/pack": "workspace:packages/pack",
"@proton/shared": "workspace:packages/shared",
"@proton/styles": "workspace:packages/styles",
"@proton/testing": "workspace:packages/testing",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-polymorphic-types": "^2.0.0",
"ttag": "^1.7.29"
},
"devDependencies": {
"@babel/core": "^7.23.3",
"@babel/preset-react": "^7.23.3",
"@babel/preset-typescript": "^7.23.3",
"@proton/eslint-config-proton": "workspace:packages/eslint-config-proton",
"@storybook/addon-actions": "^6.5.16",
"@storybook/addon-essentials": "^6.5.16",
"@storybook/addon-links": "^6.5.16",
"@storybook/addon-storysource": "^6.5.16",
"@storybook/builder-webpack5": "^6.5.16",
"@storybook/manager-webpack5": "^6.5.16",
"@storybook/react": "^6.5.16",
"@storybook/source-loader": "^6.5.16",
"@testing-library/jest-dom": "^6.1.4",
"@testing-library/react": "^12.1.5",
"@types/jest": "^29.5.9",
"@types/mustache": "^4.2.5",
"@types/node": "^20.9.3",
"@types/react": "^17.0.71",
"@types/react-dom": "^17.0.24",
"babel-loader": "^9.1.3",
"chalk": "^4.1.2",
"commander": "^11.1.0",
"eslint": "^8.54.0",
"eslint-plugin-storybook": "^0.6.15",
"jest": "^29.7.0",
"mustache": "^4.2.0",
"netlify-cli": "^17.5.3",
"prettier": "^3.1.0",
"ts-loader": "^9.5.1",
"ts-node": "^10.9.1",
"typescript": "^5.3.2",
"webpack": "^5.89.0"
}
}
| 5,009
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/atoms/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 5,010
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/index.scss
|
@import '~@proton/colors/themes/dist/duotone.theme.css';
@import '~@proton/styles/scss/proton-ui-storybook';
body {
overflow: scroll !important;
color: inherit;
}
pre code {
line-height: 1.5 !important;
}
// dirty fixes while waiting to have better solutions
.language-markup code {
inline-size: 100%;
white-space: pre-wrap;
}
.icon-ko,
.icon-ok {
&::after {
position: absolute;
inset-block-start: 0.75em;
inset-inline-end: 0;
padding-block: 0;
padding-inline: 0 0.5em;
font-size: 2em;
}
}
.icon-ko::after {
content: '×';
color: var(--signal-danger);
}
.icon-ok::after {
content: '✔';
color: var(--signal-success);
}
.icon-ko button {
display: none; // don't copy shit!
}
table {
&.no-bg {
tr {
background: none !important;
}
}
}
.sbdocs-h2 {
margin-block-start: 2em !important;
border: none !important;
}
// Fix weird margin on auto scroll
.docs-story > div {
margin: 0;
}
.icon-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 1em;
}
.sbdocs-a {
&#{&} {
@extend .link;
}
}
| 5,011
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/main.js
|
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { getJsLoader } = require('@proton/pack/webpack/js.loader');
const getCssLoaders = require('@proton/pack/webpack/css.loader');
const getAssetsLoaders = require('@proton/pack/webpack/assets.loader');
module.exports = {
core: {
builder: 'webpack5',
},
staticDirs: [],
stories: ['../**/*.stories.mdx', '../**/*.stories.@(js|jsx|ts|tsx)'],
addons: ['@storybook/addon-links', '@storybook/addon-storysource', '@storybook/addon-essentials'],
typescript: {
check: false,
checkOptions: {},
reactDocgen: 'react-docgen-typescript',
reactDocgenTypescriptOptions: {
shouldRemoveUndefinedFromOptional: true,
propFilter: (property) => {
if (property.parent) {
/**
* Only generate docs for properties which are not a part of the @types
* package. That way we don't get all the inherited dom attributes for
* example from "React.FC<React.HTMLAttributes<HTMLDivElement>>".
*
* Usually examples covered in Storybook docs as well as react-docgen-typescript
* itself show a different code-snippet to deal with this, one which ignores
* solely based on "node_modules".
*
* Since we're defining the components used in our storybook outside this codebase
* and importing it through node_modules, that won't do for us, we need to be
* more specific.
*/
return !property.parent.fileName.includes('/node_modules/@types/');
}
return true;
},
},
},
webpackFinal: async (config, { configType }) => {
const isProduction = configType === 'PRODUCTION';
const options = {
isProduction,
hasReactRefresh: false,
};
return {
...config,
resolve: {
...config.resolve,
fallback: {
...config.resolve.fallback,
// For some reason storybook brings in openpgp as a dependency and we need to
// explicitly disable these in the webpack config
stream: false,
crypto: false,
},
},
module: {
...config.module,
rules: [
...config.module.rules.filter((rule) => {
return rule.test.toString().includes('mdx');
}),
{
test: /\.stories\.(tsx|mdx)?$/,
use: [
{
loader: require.resolve('@storybook/source-loader'),
options: { parser: 'typescript' },
},
],
enforce: 'pre',
},
...[getJsLoader(options), ...getCssLoaders(options), ...getAssetsLoaders(options)],
],
},
plugins: [
...config.plugins,
new MiniCssExtractPlugin({
filename: isProduction ? '[name].[contenthash:8].css' : '[name].css',
chunkFilename: isProduction ? '[id].[contenthash:8].css' : '[id].css',
}),
],
node: {
...config.node,
__dirname: true,
__filename: true,
},
};
},
};
| 5,012
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/manager.js
|
import { addons } from '@storybook/addons';
import { themes } from '@storybook/theming';
import theme from './theme';
addons.setConfig({ theme: theme });
| 5,013
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/preview-head.html
|
<script src="prismjs.js"></script>
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
| 5,014
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/preview.js
|
import { CacheProvider, Icons, ModalsChildren, ModalsProvider, NotificationsProvider } from '@proton/components';
import ApiProvider from '@proton/components/containers/api/ApiProvider';
import ConfigProvider from '@proton/components/containers/config/Provider';
import createCache from '@proton/shared/lib/helpers/cache';
import './prismjs.js';
import theme from './theme';
import './index.scss';
const cacheRef = createCache();
const tempConfig = {
...config,
APP_NAME: 'proton-mail',
};
const config = {
CLIENT_TYPE: 1,
CLIENT_SECRET: '',
APP_VERSION: '4.999.999',
COMMIT: '555f347c5ccc1e12c35db347337664fd277d23c3',
BRANCH: 'heads/packages',
DATE_VERSION: 'Fri, 14 Jan 2022 13:48:36 GMT',
APP_NAME: 'proton-storybook',
API_URL: '/api',
LOCALES: {},
API_VERSION: '3',
VERSION_PATH: '/assets/version.json',
SENTRY_DSN: '',
};
export const decorators = [
(Story) => (
<ConfigProvider config={tempConfig}>
<Icons />
<NotificationsProvider>
<ModalsProvider>
<ApiProvider config={tempConfig}>
<ModalsChildren />
<CacheProvider cache={cacheRef}>
<Story />
</CacheProvider>
</ApiProvider>
</ModalsProvider>
</NotificationsProvider>
</ConfigProvider>
),
];
const order = [
'introduction-',
'changelog-',
'components-',
'css-',
'theming-explanations-',
'theming-usage-',
'theming-taxonomy-',
'proton-ui-',
];
const priority = ['introduction-', 'changelog-', 'theming-'];
export const parameters = {
viewMode: 'docs',
actions: { argTypesRegex: '^on[A-Z].*' },
controls: { expanded: true },
docs: { theme: theme },
options: {
storySort: (a, b) => {
const aName = a[0];
const bName = b[0];
if (priority.some((name) => aName.includes(name) || bName.includes(name))) {
const aIdx = order.findIndex((i) => aName.indexOf(i) > -1);
const bIdx = order.findIndex((i) => bName.indexOf(i) > -1);
return aIdx - bIdx;
}
return a[1].kind === b[1].kind ? 0 : a[1].id.localeCompare(b[1].id, undefined, { numeric: true });
},
},
};
| 5,015
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/prismjs.css
|
/* prism */
/**
* prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com)
* @author Lea Verou
*/
code {
display: inline-block !important;
font-size: 1.1em !important;
padding: 0.25em !important;
border-radius: 5px !important;
background: #f6f7fa !important !important;
line-height: 1 !important;
}
code[class*='language-'],
pre[class*='language-'] {
width: 100% !important;
color: black !important;
text-shadow: 0 1px white !important;
font-family: Consolas, Monaco, monospace !important;
text-align: left !important;
/*white-space: pre !important;*/
word-spacing: normal !important;
font-size: 1.6rem !important;
-moz-tab-size: 4 !important;
-o-tab-size: 4 !important;
tab-size: 4 !important;
-webkit-hyphens: none !important;
-moz-hyphens: none !important;
-ms-hyphens: none !important;
hyphens: none !important;
border-radius: 5px !important;
}
[dir='rtl'] code[class*='language-'],
[dir='rtl'] pre[class*='language-'] {
text-align: right !important;
}
[dir='ltr'] code[class*='language-'],
[dir='ltr'] pre[class*='language-'] {
text-align: left !important;
}
/* Code blocks */
pre[class*='language-'] {
padding: 1em !important;
margin: 0.5em 0 !important;
overflow: auto !important;
}
pre[class*='language-'].m-0 {
margin: 0 !important;
}
:not(pre) > code[class*='language-'],
pre[class*='language-'] {
background: #f6f7fa !important;
}
/* Inline code */
:not(pre) > code[class*='language-'] {
padding: 0.1em !important;
border-radius: 0.3em !important;
font-size: 0.8em !important;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: #344559 !important;
}
.token.punctuation {
color: #4a4646 !important !important;
}
.namespace {
opacity: 0.7 !important;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.function,
.token.class-name,
.token.constant {
color: #905 !important;
}
.token.selector,
.token.attr-name,
.token.string {
color: #085300 !important;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: #803c24 !important !important;
background: rgba(255, 255, 255, 0.5) !important;
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #0227a9 !important;
}
.token.regex,
.token.important {
color: #e90 !important;
}
.token.important {
font-weight: bold !important;
}
.token.entity {
cursor: help !important;
}
@media (prefers-color-scheme: dark) {
code {
background: #262a33 !important;
}
code[class*='language-'],
pre[class*='language-'] {
color: #ccc !important;
background: none !important;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace !important;
text-shadow: none !important;
font-size: 1.4rem !important;
text-align: left !important;
white-space: pre !important;
word-spacing: normal !important;
word-break: normal !important;
word-wrap: normal !important;
line-height: 1.5 !important;
-moz-tab-size: 4 !important;
-o-tab-size: 4 !important;
tab-size: 4 !important;
-webkit-hyphens: none !important;
-moz-hyphens: none !important;
-ms-hyphens: none !important;
hyphens: none !important;
}
/* Code blocks */
pre[class*='language-'] {
padding: 1em !important;
margin: 0.5em 0 !important;
overflow: auto !important;
}
:not(pre) > code[class*='language-'],
pre[class*='language-'] {
background: #2d2d2d !important;
}
/* Inline code */
:not(pre) > code[class*='language-'] {
padding: 0.1em !important;
border-radius: 0.3em !important;
white-space: normal !important;
}
.token.comment,
.token.block-comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: #999 !important;
}
.token.punctuation {
color: #ccc !important;
}
.token.tag,
.token.attr-name,
.token.namespace,
.token.deleted {
color: #e2777a !important;
}
.token.function-name {
color: #6196cc !important;
}
.token.boolean,
.token.number,
.token.function {
color: #f08d49 !important;
}
.token.property,
.token.class-name,
.token.constant,
.token.symbol {
color: #f8c555 !important;
}
.token.selector,
.token.important,
.token.atrule,
.token.keyword,
.token.builtin {
color: #cc99cd !important;
}
.token.string,
.token.char,
.token.attr-value,
.token.regex,
.token.variable {
color: #7ec699 !important;
}
.token.operator,
.token.entity,
.token.url {
color: #67cdcc !important;
}
.token.important,
.token.bold {
font-weight: bold !important;
}
.token.italic {
font-style: italic !important;
}
.token.entity {
cursor: help !important;
}
.token.inserted {
color: green !important;
}
}
| 5,016
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/prismjs.js
|
/* PrismJS 1.15.0
https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript&plugins=keep-markup */
var _self =
'undefined' != typeof window
? window
: 'undefined' != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope
? self
: {},
Prism = (function () {
var e = /\blang(?:uage)?-([\w-]+)\b/i,
t = 0,
n = (_self.Prism = {
manual: _self.Prism && _self.Prism.manual,
disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
util: {
encode: function (e) {
return e instanceof a
? new a(e.type, n.util.encode(e.content), e.alias)
: 'Array' === n.util.type(e)
? e.map(n.util.encode)
: e
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/\u00a0/g, ' ');
},
type: function (e) {
return Object.prototype.toString.call(e).slice(8, -1);
},
objId: function (e) {
return e.__id || Object.defineProperty(e, '__id', { value: ++t }), e.__id;
},
clone: function (e, t) {
var a = n.util.type(e);
switch (((t = t || {}), a)) {
case 'Object':
if (t[n.util.objId(e)]) return t[n.util.objId(e)];
var r = {};
t[n.util.objId(e)] = r;
for (var l in e) e.hasOwnProperty(l) && (r[l] = n.util.clone(e[l], t));
return r;
case 'Array':
if (t[n.util.objId(e)]) return t[n.util.objId(e)];
var r = [];
return (
(t[n.util.objId(e)] = r),
e.forEach(function (e, a) {
r[a] = n.util.clone(e, t);
}),
r
);
}
return e;
},
},
languages: {
extend: function (e, t) {
var a = n.util.clone(n.languages[e]);
for (var r in t) a[r] = t[r];
return a;
},
insertBefore: function (e, t, a, r) {
r = r || n.languages;
var l = r[e],
i = {};
for (var o in l)
if (l.hasOwnProperty(o)) {
if (o == t) for (var s in a) a.hasOwnProperty(s) && (i[s] = a[s]);
a.hasOwnProperty(o) || (i[o] = l[o]);
}
var u = r[e];
return (
(r[e] = i),
n.languages.DFS(n.languages, function (t, n) {
n === u && t != e && (this[t] = i);
}),
i
);
},
DFS: function (e, t, a, r) {
r = r || {};
for (var l in e)
e.hasOwnProperty(l) &&
(t.call(e, l, e[l], a || l),
'Object' !== n.util.type(e[l]) || r[n.util.objId(e[l])]
? 'Array' !== n.util.type(e[l]) ||
r[n.util.objId(e[l])] ||
((r[n.util.objId(e[l])] = !0), n.languages.DFS(e[l], t, l, r))
: ((r[n.util.objId(e[l])] = !0), n.languages.DFS(e[l], t, null, r)));
},
},
plugins: {},
highlightAll: function (e, t) {
n.highlightAllUnder(document, e, t);
},
highlightAllUnder: function (e, t, a) {
var r = {
callback: a,
selector:
'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code',
};
n.hooks.run('before-highlightall', r);
for (var l, i = r.elements || e.querySelectorAll(r.selector), o = 0; (l = i[o++]); )
n.highlightElement(l, t === !0, r.callback);
},
highlightElement: function (t, a, r) {
for (var l, i, o = t; o && !e.test(o.className); ) o = o.parentNode;
o && ((l = (o.className.match(e) || [, ''])[1].toLowerCase()), (i = n.languages[l])),
(t.className = t.className.replace(e, '').replace(/\s+/g, ' ') + ' language-' + l),
t.parentNode &&
((o = t.parentNode),
/pre/i.test(o.nodeName) &&
(o.className = o.className.replace(e, '').replace(/\s+/g, ' ') + ' language-' + l));
var s = t.textContent,
u = { element: t, language: l, grammar: i, code: s };
if ((n.hooks.run('before-sanity-check', u), !u.code || !u.grammar))
return (
u.code &&
(n.hooks.run('before-highlight', u),
(u.element.textContent = u.code),
n.hooks.run('after-highlight', u)),
n.hooks.run('complete', u),
void 0
);
if ((n.hooks.run('before-highlight', u), a && _self.Worker)) {
var g = new Worker(n.filename);
(g.onmessage = function (e) {
(u.highlightedCode = e.data),
n.hooks.run('before-insert', u),
(u.element.innerHTML = u.highlightedCode),
n.hooks.run('after-highlight', u),
n.hooks.run('complete', u),
r && r.call(u.element);
}),
g.postMessage(JSON.stringify({ language: u.language, code: u.code, immediateClose: !0 }));
} else
(u.highlightedCode = n.highlight(u.code, u.grammar, u.language)),
n.hooks.run('before-insert', u),
(u.element.innerHTML = u.highlightedCode),
n.hooks.run('after-highlight', u),
n.hooks.run('complete', u),
r && r.call(t);
},
highlight: function (e, t, r) {
var l = { code: e, grammar: t, language: r };
return (
n.hooks.run('before-tokenize', l),
(l.tokens = n.tokenize(l.code, l.grammar)),
n.hooks.run('after-tokenize', l),
a.stringify(n.util.encode(l.tokens), l.language)
);
},
matchGrammar: function (e, t, a, r, l, i, o) {
var s = n.Token;
for (var u in a)
if (a.hasOwnProperty(u) && a[u]) {
if (u == o) return;
var g = a[u];
g = 'Array' === n.util.type(g) ? g : [g];
for (var c = 0; c < g.length; ++c) {
var h = g[c],
f = h.inside,
d = !!h.lookbehind,
m = !!h.greedy,
p = 0,
y = h.alias;
if (m && !h.pattern.global) {
var v = h.pattern.toString().match(/[imuy]*$/)[0];
h.pattern = RegExp(h.pattern.source, v + 'g');
}
h = h.pattern || h;
for (var b = r, k = l; b < t.length; k += t[b].length, ++b) {
var w = t[b];
if (t.length > e.length) return;
if (!(w instanceof s)) {
if (m && b != t.length - 1) {
h.lastIndex = k;
var _ = h.exec(e);
if (!_) break;
for (
var j = _.index + (d ? _[1].length : 0),
P = _.index + _[0].length,
A = b,
x = k,
O = t.length;
O > A && (P > x || (!t[A].type && !t[A - 1].greedy));
++A
)
(x += t[A].length), j >= x && (++b, (k = x));
if (t[b] instanceof s) continue;
(I = A - b), (w = e.slice(k, x)), (_.index -= k);
} else {
h.lastIndex = 0;
var _ = h.exec(w),
I = 1;
}
if (_) {
d && (p = _[1] ? _[1].length : 0);
var j = _.index + p,
_ = _[0].slice(p),
P = j + _.length,
N = w.slice(0, j),
S = w.slice(P),
C = [b, I];
N && (++b, (k += N.length), C.push(N));
var E = new s(u, f ? n.tokenize(_, f) : _, y, _, m);
if (
(C.push(E),
S && C.push(S),
Array.prototype.splice.apply(t, C),
1 != I && n.matchGrammar(e, t, a, b, k, !0, u),
i)
)
break;
} else if (i) break;
}
}
}
}
},
tokenize: function (e, t) {
var a = [e],
r = t.rest;
if (r) {
for (var l in r) t[l] = r[l];
delete t.rest;
}
return n.matchGrammar(e, a, t, 0, 0, !1), a;
},
hooks: {
all: {},
add: function (e, t) {
var a = n.hooks.all;
(a[e] = a[e] || []), a[e].push(t);
},
run: function (e, t) {
var a = n.hooks.all[e];
if (a && a.length) for (var r, l = 0; (r = a[l++]); ) r(t);
},
},
}),
a = (n.Token = function (e, t, n, a, r) {
(this.type = e),
(this.content = t),
(this.alias = n),
(this.length = 0 | (a || '').length),
(this.greedy = !!r);
});
if (
((a.stringify = function (e, t, r) {
if ('string' == typeof e) return e;
if ('Array' === n.util.type(e))
return e
.map(function (n) {
return a.stringify(n, t, e);
})
.join('');
var l = {
type: e.type,
content: a.stringify(e.content, t, r),
tag: 'span',
classes: ['token', e.type],
attributes: {},
language: t,
parent: r,
};
if (e.alias) {
var i = 'Array' === n.util.type(e.alias) ? e.alias : [e.alias];
Array.prototype.push.apply(l.classes, i);
}
n.hooks.run('wrap', l);
var o = Object.keys(l.attributes)
.map(function (e) {
return e + '="' + (l.attributes[e] || '').replace(/"/g, '"') + '"';
})
.join(' ');
return (
'<' +
l.tag +
' class="' +
l.classes.join(' ') +
'"' +
(o ? ' ' + o : '') +
'>' +
l.content +
'</' +
l.tag +
'>'
);
}),
!_self.document)
)
return _self.addEventListener
? (n.disableWorkerMessageHandler ||
_self.addEventListener(
'message',
function (e) {
var t = JSON.parse(e.data),
a = t.language,
r = t.code,
l = t.immediateClose;
_self.postMessage(n.highlight(r, n.languages[a], a)), l && _self.close();
},
!1
),
_self.Prism)
: _self.Prism;
var r = document.currentScript || [].slice.call(document.getElementsByTagName('script')).pop();
return (
r &&
((n.filename = r.src),
n.manual ||
r.hasAttribute('data-manual') ||
('loading' !== document.readyState
? window.requestAnimationFrame
? window.requestAnimationFrame(n.highlightAll)
: window.setTimeout(n.highlightAll, 16)
: document.addEventListener('DOMContentLoaded', n.highlightAll))),
_self.Prism
);
})();
'undefined' != typeof module && module.exports && (module.exports = Prism),
'undefined' != typeof global && (global.Prism = Prism);
(Prism.languages.markup = {
comment: /<!--[\s\S]*?-->/,
prolog: /<\?[\s\S]+?\?>/,
doctype: /<!DOCTYPE[\s\S]+?>/i,
cdata: /<!\[CDATA\[[\s\S]*?]]>/i,
tag: {
pattern:
/<\/?(?!\d)[^\s>\/=$<%]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i,
greedy: !0,
inside: {
tag: { pattern: /^<\/?[^\s>\/]+/i, inside: { punctuation: /^<\/?/, namespace: /^[^\s>\/:]+:/ } },
'attr-value': {
pattern: /=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+)/i,
inside: { punctuation: [/^=/, { pattern: /(^|[^\\])["']/, lookbehind: !0 }] },
},
punctuation: /\/?>/,
'attr-name': { pattern: /[^\s>\/]+/, inside: { namespace: /^[^\s>\/:]+:/ } },
},
},
entity: /&#?[\da-z]{1,8};/i,
}),
(Prism.languages.markup.tag.inside['attr-value'].inside.entity = Prism.languages.markup.entity),
Prism.hooks.add('wrap', function (a) {
'entity' === a.type && (a.attributes.title = a.content.replace(/&/, '&'));
}),
(Prism.languages.xml = Prism.languages.markup),
(Prism.languages.html = Prism.languages.markup),
(Prism.languages.mathml = Prism.languages.markup),
(Prism.languages.svg = Prism.languages.markup);
(Prism.languages.css = {
comment: /\/\*[\s\S]*?\*\//,
atrule: { pattern: /@[\w-]+?[\s\S]*?(?:;|(?=\s*\{))/i, inside: { rule: /@[\w-]+/ } },
url: /url\((?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
selector: /[^{}\s][^{};]*?(?=\s*\{)/,
string: { pattern: /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: !0 },
property: /[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,
important: /!important\b/i,
function: /[-a-z0-9]+(?=\()/i,
punctuation: /[(){};:,]/,
}),
(Prism.languages.css.atrule.inside.rest = Prism.languages.css),
Prism.languages.markup &&
(Prism.languages.insertBefore('markup', 'tag', {
style: {
pattern: /(<style[\s\S]*?>)[\s\S]*?(?=<\/style>)/i,
lookbehind: !0,
inside: Prism.languages.css,
alias: 'language-css',
greedy: !0,
},
}),
Prism.languages.insertBefore(
'inside',
'attr-value',
{
'style-attr': {
pattern: /\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,
inside: {
'attr-name': { pattern: /^\s*style/i, inside: Prism.languages.markup.tag.inside },
punctuation: /^\s*=\s*['"]|['"]\s*$/,
'attr-value': { pattern: /.+/i, inside: Prism.languages.css },
},
alias: 'language-css',
},
},
Prism.languages.markup.tag
));
Prism.languages.clike = {
comment: [
{ pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, lookbehind: !0 },
{ pattern: /(^|[^\\:])\/\/.*/, lookbehind: !0, greedy: !0 },
],
string: { pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: !0 },
'class-name': {
pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i,
lookbehind: !0,
inside: { punctuation: /[.\\]/ },
},
keyword:
/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
boolean: /\b(?:true|false)\b/,
function: /\w+(?=\()/,
number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,
operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
punctuation: /[{}[\];(),.:]/,
};
(Prism.languages.javascript = Prism.languages.extend('clike', {
'class-name': [
Prism.languages.clike['class-name'],
{
pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/,
lookbehind: !0,
},
],
keyword: [
{ pattern: /((?:^|})\s*)(?:catch|finally)\b/, lookbehind: !0 },
/\b(?:as|async|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,
],
number: /\b(?:(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+)n?|\d+n|NaN|Infinity)\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?/,
function: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*\(|\.(?:apply|bind|call)\()/,
operator: /-[-=]?|\+[+=]?|!=?=?|<<?=?|>>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/,
})),
(Prism.languages.javascript['class-name'][0].pattern =
/(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/),
Prism.languages.insertBefore('javascript', 'keyword', {
regex: {
pattern:
/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^\/\\\[\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})\]]))/,
lookbehind: !0,
greedy: !0,
},
'function-variable': {
pattern:
/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\([^()]*\)|[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/i,
alias: 'function',
},
parameter: [
{
pattern: /(function(?:\s+[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)[^\s()][^()]*?(?=\s*\))/,
lookbehind: !0,
inside: Prism.languages.javascript,
},
{ pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/, inside: Prism.languages.javascript },
{ pattern: /(\(\s*)[^\s()][^()]*?(?=\s*\)\s*=>)/, lookbehind: !0, inside: Prism.languages.javascript },
{
pattern:
/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)[^\s()][^()]*?(?=\s*\)\s*\{)/,
lookbehind: !0,
inside: Prism.languages.javascript,
},
],
constant: /\b[A-Z][A-Z\d_]*\b/,
}),
Prism.languages.insertBefore('javascript', 'string', {
'template-string': {
pattern: /`(?:\\[\s\S]|\${[^}]+}|[^\\`])*`/,
greedy: !0,
inside: {
interpolation: {
pattern: /\${[^}]+}/,
inside: {
'interpolation-punctuation': { pattern: /^\${|}$/, alias: 'punctuation' },
rest: Prism.languages.javascript,
},
},
string: /[\s\S]+/,
},
},
}),
Prism.languages.markup &&
Prism.languages.insertBefore('markup', 'tag', {
script: {
pattern: /(<script[\s\S]*?>)[\s\S]*?(?=<\/script>)/i,
lookbehind: !0,
inside: Prism.languages.javascript,
alias: 'language-javascript',
greedy: !0,
},
}),
(Prism.languages.js = Prism.languages.javascript);
!(function () {
'undefined' != typeof self &&
self.Prism &&
self.document &&
document.createRange &&
((Prism.plugins.KeepMarkup = !0),
Prism.hooks.add('before-highlight', function (e) {
if (e.element.children.length) {
var n = 0,
o = [],
t = function (e, d) {
var r = {};
d || ((r.clone = e.cloneNode(!1)), (r.posOpen = n), o.push(r));
for (var a = 0, s = e.childNodes.length; s > a; a++) {
var l = e.childNodes[a];
1 === l.nodeType ? t(l) : 3 === l.nodeType && (n += l.data.length);
}
d || (r.posClose = n);
};
t(e.element, !0), o && o.length && (e.keepMarkup = o);
}
}),
Prism.hooks.add('after-highlight', function (e) {
if (e.keepMarkup && e.keepMarkup.length) {
var n = function (e, o) {
for (var t = 0, d = e.childNodes.length; d > t; t++) {
var r = e.childNodes[t];
if (1 === r.nodeType) {
if (!n(r, o)) return !1;
} else
3 === r.nodeType &&
(!o.nodeStart &&
o.pos + r.data.length > o.node.posOpen &&
((o.nodeStart = r), (o.nodeStartPos = o.node.posOpen - o.pos)),
o.nodeStart &&
o.pos + r.data.length >= o.node.posClose &&
((o.nodeEnd = r), (o.nodeEndPos = o.node.posClose - o.pos)),
(o.pos += r.data.length));
if (o.nodeStart && o.nodeEnd) {
var a = document.createRange();
return (
a.setStart(o.nodeStart, o.nodeStartPos),
a.setEnd(o.nodeEnd, o.nodeEndPos),
o.node.clone.appendChild(a.extractContents()),
a.insertNode(o.node.clone),
a.detach(),
!1
);
}
}
return !0;
};
e.keepMarkup.forEach(function (o) {
n(e.element, { node: o, pos: 0 });
}),
(e.highlightedCode = e.element.innerHTML);
}
}));
})();
| 5,017
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/.storybook/theme.js
|
import { create } from '@storybook/theming/create';
export default create({
base: 'light',
colorPrimary: '#657ee4',
colorSecondary: '#526ee0',
// // UI
appBg: 'rgb(247, 249, 252)',
// appContentBg: 'white',
appBorderColor: '#dde6ec',
appBorderRadius: 3,
// // Typography
fontBase:
'-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif',
fontCode: 'SFMono-Regular, Consolas, "Liberation Mono", "Menlo", monospace, monospace',
// // Text colors
textColor: '#262a33',
textInverseColor: 'rgba(255,255,255,0.9)',
// // Toolbar default and active colors
barTextColor: '#f6f7fa',
barSelectedColor: '#657ee4',
barBg: '#3c414e',
// Form colors
inputBg: '#fcfdff',
inputBorder: '#dde6ec',
inputTextColor: 'black',
inputBorderRadius: 3,
brandTitle: 'Proton Design System',
brandUrl: 'https://design-system.protontech.ch/',
//
brandImage:
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgOTIuNSAxNS4xIiBjbGFzcz0ibG9nbyIgYXJpYS1sYWJlbGxlZGJ5PSJsb2dvX190aXRsZSI+PGc+PHBhdGggZD0iTTE5LjUsMy43aC0zdjExLjFoMS45di0zLjloMS4xYzEuMSwwLjEsMi4yLTAuMiwzLjEtMC45czEuMy0xLjcsMS4zLTIuOEMyMy45LDUsMjIuMywzLjcsMTkuNSwzLjd6IE0xOC40LDUuM2gxLjFjMS42LDAsMi40LDAuNiwyLjQsMkMyMiw3LjksMjEuNyw4LjUsMjEuMyw5Yy0wLjUsMC4zLTEuMiwwLjUtMS44LDAuNGgtMS4xVjUuM3oiPjwvcGF0aD48cGF0aCBkPSJNMjkuMiw2Yy0wLjksMC0xLjYsMC41LTIsMS4ybC0wLjEtMS4xaC0xLjZ2OC42aDEuOVYxMGMwLjMtMS41LDAuOC0yLjEsMS43LTIuMWMwLjIsMCwwLjQsMCwwLjcsMC4xaDAuMWwwLjMtMS44SDMwQzI5LjgsNi4xLDI5LjUsNiwyOS4yLDZ6Ij48L3BhdGg+PHBhdGggZD0iTTM0LjYsNmMtMS4xLDAtMi4yLDAuNC0yLjksMS4zYy0xLjMsMS45LTEuMyw0LjUsMCw2LjVjMS41LDEuNiwzLjksMS43LDUuNSwwLjJjMC4xLTAuMSwwLjItMC4yLDAuMi0wLjJjMS4zLTEuOSwxLjMtNC41LDAtNi41QzM2LjcsNi41LDM1LjcsNiwzNC42LDZ6IE0zNC41LDEzLjVjLTEuMywwLTEuOS0xLTEuOS0yLjljLTAuMS0wLjgsMC4xLTEuNiwwLjUtMi4zYzAuMy0wLjUsMC44LTAuNywxLjQtMC43YzAuNSwwLDEuMSwwLjIsMS40LDAuN2MwLjQsMC43LDAuNiwxLjUsMC41LDIuMkMzNi40LDEyLjUsMzUuOCwxMy41LDM0LjUsMTMuNXoiPjwvcGF0aD48cGF0aCBkPSJNNDQsMTMuMWMtMC4zLDAuMi0wLjYsMC4zLTEsMC4zYy0wLjUsMC0wLjgtMC4yLTAuOC0xVjcuOEg0NGwwLjItMS41aC0ydi0ybC0xLjksMC4ydjEuOEgzOXYxLjVoMS40djQuN2MwLDAuNywwLjIsMS40LDAuNiwxLjljMC41LDAuNSwxLjEsMC43LDEuOCwwLjdzMS40LTAuMiwyLTAuNmwwLjItMC4xTDQ0LjIsMTNMNDQsMTMuMXoiPjwvcGF0aD48cGF0aCBkPSJNNDkuMSw2Yy0xLjEsMC0yLjIsMC40LTIuOSwxLjNjLTEuMywxLjktMS4zLDQuNSwwLDYuNWMxLjUsMS42LDMuOSwxLjcsNS41LDAuMmMwLjEtMC4xLDAuMi0wLjIsMC4yLTAuMmMxLjMtMS45LDEuMy00LjUsMC02LjVDNTEuMiw2LjUsNTAuMiw2LDQ5LjEsNnogTTQ5LjEsMTMuNWMtMS4zLDAtMS45LTEtMS45LTIuOWMtMC4xLTAuOCwwLjEtMS42LDAuNS0yLjNjMC4zLTAuNSwwLjgtMC43LDEuNC0wLjdjMC41LDAsMS4xLDAuMiwxLjQsMC43QzUwLjgsOSw1MSw5LjcsNTEsMTAuNUM1MSwxMi41LDUwLjMsMTMuNSw0OS4xLDEzLjV6Ij48L3BhdGg+PHBhdGggZD0iTTU4LjksNmMtMC41LDAtMS4xLDAuMS0xLjUsMC40Yy0wLjMsMC4yLTAuNiwwLjQtMC44LDAuNmwtMC4xLTAuOWgtMS42djguNmgxLjl2LTZjMC42LTAuOSwxLjEtMS4zLDEuOS0xLjNjMC42LDAsMS4xLDAuMiwxLjEsMS40djUuOWgxLjlWOC44YzAtMC43LTAuMi0xLjQtMC43LTJDNjAuMyw2LjMsNTkuNiw2LDU4LjksNnoiPjwvcGF0aD48cGF0aCBkPSJNNzAuOCwzLjdsLTIsNy4ybC0yLjEtNy4yaC0yLjNsLTAuOSwxMS4xaDEuOGwwLjQtNC45YzAuMS0xLjEsMC4xLTIuMiwwLjItMy4ybDIuMSw2LjloMS43bDItNi45YzAsMC45LDAuMSwyLDAuMiwzLjFsMC40LDVoMS45TDczLjEsMy43SDcwLjh6Ij48L3BhdGg+PHBhdGggZD0iTTgyLjMsMTIuN1Y5YzAuMS0wLjgtMC4yLTEuNi0wLjgtMi4yQzgwLjksNi4zLDgwLDYsNzkuMiw2Yy0xLDAtMiwwLjItMi45LDAuNmwtMC4yLDAuMWwwLjUsMS40TDc2LjgsOGMwLjctMC4zLDEuNC0wLjQsMi4xLTAuNEM4MCw3LjYsODAuNCw4LDgwLjQsOXYwLjRoLTFjLTEtMC4xLTIsMC4yLTIuOCwwLjdjLTEuMiwxLTEuNCwyLjgtMC40LDRsMC4xLDAuMWMwLjYsMC41LDEuMywwLjgsMi4xLDAuN2MwLjksMCwxLjgtMC4zLDIuNC0xYzAuMywwLjYsMC45LDEsMS42LDFoMC4ybDAuNC0xLjRsLTAuMi0wLjFDODIuNSwxMy41LDgyLjMsMTMuNCw4Mi4zLDEyLjd6IE03OC43LDEzLjVjLTAuOCwwLTEuMi0wLjQtMS4yLTEuM2MwLTAuNCwwLjEtMC44LDAuNS0xLjFjMC41LTAuMywxLTAuNCwxLjYtMC40aDAuOXYxLjZDODAuMSwxMy4xLDc5LjQsMTMuNSw3OC43LDEzLjVMNzguNywxMy41eiI+PC9wYXRoPjxwYXRoIGQ9Ik04NS43LDIuM2MtMC43LDAtMS4yLDAuNS0xLjIsMS4yYzAsMC4zLDAuMSwwLjYsMC4zLDAuOGMwLjIsMC4yLDAuNSwwLjMsMC45LDAuM2MwLjcsMCwxLjItMC41LDEuMi0xLjFTODYuNCwyLjMsODUuNywyLjNMODUuNywyLjN6Ij48L3BhdGg+PHJlY3QgeD0iODQuOCIgeT0iNi4yIiB3aWR0aD0iMS45IiBoZWlnaHQ9IjguNiI+PC9yZWN0PjxwYXRoIGQ9Ik05MS45LDEzLjNsLTAuMiwwLjFjLTAuMSwwLjEtMC4zLDAuMS0wLjQsMC4xcy0wLjMsMC0wLjMtMC40VjIuN0w4OS4xLDN2MTBjLTAuMSwxLDAuNSwxLjksMS41LDJjMC4xLDAsMC4yLDAsMC40LDBjMC41LDAsMC45LTAuMSwxLjMtMC4zbDAuMi0wLjFMOTEuOSwxMy4zeiI+PC9wYXRoPjwvZz48Zz48cGF0aCBkPSJNNS4zLDBDMi42LDAsMC4zLDIuMSwwLDQuOHYzLjNjMCwwLDAsMC40LDEsMS4xUzQuNywxMiw1LjMsMTJzMy4zLTIsNC4zLTIuOHMxLTEuMSwxLTEuMVY0LjhDMTAuMywyLjEsOC4xLDAsNS4zLDB6IE04LjQsNi42SDIuM1Y0LjhDMi42LDMuMSw0LjMsMiw2LDIuNGMxLjIsMC4yLDIuMiwxLjIsMi40LDIuNFY2LjZ6Ij48L3BhdGg+PHBhdGggZD0iTTUuMywxMi43Yy0wLjQtMC4xLTAuOS0wLjItMS4yLTAuNGMtMC41LTAuNC00LjEtMy00LjEtM3Y1LjFDMCwxNC43LDAuMywxNSwwLjcsMTVsMCwwSDEwYzAuMywwLDAuNy0wLjIsMC43LTAuNmwwLDBWOS4zYzAsMC0zLjYsMi42LTQuMSwyLjlDNi4yLDEyLjUsNS44LDEyLjcsNS4zLDEyLjd6Ij48L3BhdGg+PC9nPjx0aXRsZSBpZD0ibG9nb19fdGl0bGUiPlByb3Rvbk1haWw8L3RpdGxlPjwvc3ZnPg==',
});
| 5,018
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/Avatar.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
# Avatar
Generally used to highlight user initials.
```js
import { Avatar } from '@proton/atoms';
```
<Canvas withSource="open">
<Story id="components-avatar--basic" />
</Canvas>
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,019
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/Avatar.scss
|
@import '~@proton/styles/scss/lib';
.avatar {
inline-size: rem($conversation-icon-size);
block-size: rem($conversation-icon-size);
font-size: 0.75rem; // 12
background-color: var(--primary);
color: var(--primary-contrast);
&--weak {
background-color: var(--background-strong);
color: var(--text-norm);
}
}
| 5,020
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/Avatar.stories.tsx
|
import Avatar, { AvatarProps } from './Avatar';
import mdx from './Avatar.mdx';
export default {
component: Avatar,
title: 'components/Avatar',
parameters: { docs: { page: mdx } },
};
export const Playground = ({ ...args }) => <Avatar {...args}>PM</Avatar>;
const args: AvatarProps<'span'> = {};
Playground.args = args;
export const Basic = () => <Avatar>HF</Avatar>;
| 5,021
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/Avatar.test.tsx
|
import { render } from '@testing-library/react';
import Avatar from './Avatar';
describe('<Avatar />', () => {
it('accepts a custom class attribute', () => {
const child = 'MJ';
const { getByText } = render(<Avatar className="custom">{child}</Avatar>);
const element = getByText(child);
expect(element).toHaveClass('custom');
expect(element.getAttribute('class')).not.toBe('custom');
});
});
| 5,022
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/Avatar.tsx
|
import { ElementType } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import clsx from '@proton/utils/clsx';
import './Avatar.scss';
export type AvatarProps<E extends ElementType> = PolymorphicPropsWithoutRef<{ color?: 'weak' | 'norm' }, E>;
const defaultElement = 'span';
const Avatar = <E extends ElementType = typeof defaultElement>({
className: classNameProp,
color,
as,
...rest
}: PolymorphicPropsWithoutRef<{}, E>) => {
const className = clsx(
classNameProp,
'avatar rounded inline-flex flex-justify-center flex-align-items-center',
color === 'weak' && 'avatar--weak'
);
const Element: ElementType = as || defaultElement;
return <Element className={className} {...rest} aria-hidden="true" />;
};
export default Avatar;
| 5,023
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/index.ts
|
export { default as Avatar } from './Avatar';
export * from './Avatar';
| 5,024
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/Button.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { Alert, InlineLinkButton } from '@proton/components';
# Button
```js
import { Button } from '@proton/atoms';
```
The button is an essential element of any design. It's meant to look and behave as an interactive element of your page.
## How to use
<Canvas withSource="open">
<Story id="components-button--example" />
</Canvas>
## Variants
<Alert type="info" className="my-6">
The button with <code>underline</code> shape comes with default paddings to ensure alignment when used in a same row
as another button or input field. It is not meant to be used inside a text content. If you need a button with a real
link shape{' '}
<InlineLinkButton onClick={() => alert('See? This is a real button.')}>such as this one</InlineLinkButton>, use the{' '}
<code>InlineLinkButton</code> component instead.
<br />
<a href="?path=/docs/components-inlinelinkbutton--basic">Check out the InlineLinkButton component</a>
</Alert>
<Story id="components-button--sandbox" />
<Story id="components-button--variants" />
## Polymorphic buttons
A button can also be used as another component, with the `ButtonLike` component.
<Canvas>
<Story id="components-button--like" />
</Canvas>
## Props
<Primary />
<ArgsTable story={PRIMARY_STORY} />
| 5,025
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/Button.stories.tsx
|
import { useState } from 'react';
import { Button, ButtonLike } from '@proton/atoms';
import { Checkbox, Icon, RadioGroup, Table, TableBody, TableCell, TableHeader, TableRow } from '@proton/components';
import mdx from './Button.mdx';
export default {
component: Button,
title: 'components/Button',
parameters: {
docs: {
page: mdx,
},
},
};
export const Example = () => (
<Button color="norm" size="large">
Loremium
</Button>
);
export const Basic = ({ ...args }) => <Button {...args}>Loremium</Button>;
Basic.args = {};
type ButtonProps = React.ComponentProps<typeof Button>;
const shapes: Required<ButtonProps>['shape'][] = ['solid', 'outline', 'ghost', 'underline'];
const colors: Required<ButtonProps>['color'][] = ['norm', 'weak', 'danger', 'warning', 'success', 'info'];
const sizes: Required<ButtonProps>['size'][] = ['small', 'medium', 'large'];
const toggles = ['loading', 'pill', 'fullWidth', 'icon', 'disabled'] as const;
const buttonContainerClassName = 'flex flex-item-fluid flex-align-items-center flex-justify-center border';
export const Sandbox = () => {
const [selectedShape, setSelectedShape] = useState<Required<ButtonProps>['shape']>('solid');
const [selectedColor, setSelectedColor] = useState<Required<ButtonProps>['color']>('weak');
const [selectedSize, setSelectedSize] = useState<Required<ButtonProps>['size']>('medium');
const [selectedToggles, setSelectedToggles] = useState(toggles.map(() => false));
const button = (
<Button
shape={selectedShape}
color={selectedColor}
size={selectedSize}
{...selectedToggles.reduce<{ [key: string]: boolean }>((acc, value, i) => {
acc[toggles[i]] = value;
return acc;
}, {})}
>
{selectedToggles[toggles.indexOf('icon')] ? (
<Icon name="brand-proton-mail" />
) : (
<>
{selectedShape} {selectedColor} {selectedSize}
</>
)}
</Button>
);
return (
<div className="flex-no-min-children flex-column md:flex-row py-7">
<div className="flex flex-column flex-nowrap md:flex-item-fluid">
<div className="mr-8 mb-4">
<strong className="block mb-4">Color</strong>
<RadioGroup
name="selected-color"
onChange={(v) => setSelectedColor(v)}
value={selectedColor}
options={colors.map((color) => ({ value: color, label: color }))}
/>
</div>
<div className="mr-8 mb-4">
<strong className="block mb-4">Shape</strong>
<RadioGroup
name="selected-shape"
onChange={(v) => setSelectedShape(v)}
value={selectedShape}
options={shapes.map((shape) => ({ value: shape, label: shape }))}
/>
</div>
<div className="mr-8 mb-4">
<strong className="block mb-4">Size</strong>
<RadioGroup
name="selected-size"
onChange={(v) => setSelectedSize(v)}
value={selectedSize}
options={sizes.map((size) => ({ value: size, label: size }))}
/>
</div>
<div className="mr-8 mb-4">
<strong className="block mb-4">Toggles</strong>
{toggles.map((prop, i) => {
return (
<div className="mb-2" key={i}>
<Checkbox
checked={selectedToggles[i]}
onChange={({ target: { checked } }) => {
setSelectedToggles(
selectedToggles.map((oldValue, otherIndex) =>
otherIndex === i ? checked : oldValue
)
);
}}
>
{prop}
</Checkbox>
</div>
);
})}
</div>
</div>
<div className={buttonContainerClassName}>{button}</div>
</div>
);
};
export const Variants = () => {
return (
<Table className="color-norm">
<TableHeader>
<TableRow>
<TableCell>
<></>
</TableCell>
{colors.map((color) => (
<TableCell key={color} scope="col">
{color}
</TableCell>
))}
</TableRow>
</TableHeader>
<TableBody>
{shapes.map((shape) => (
<TableRow key={shape}>
<TableCell>{shape}</TableCell>
{colors.map((color) => (
<TableCell key={color}>
<div className="flex gap-2 flex-justify-center">
<Button shape={shape} color={color}>
Lorem
</Button>
{shape !== 'underline' && (
<Button icon shape={shape} color={color}>
<Icon name="brand-proton-mail" alt="Lorem" />
</Button>
)}
</div>
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
);
};
const Component = (props: any) => {
return <div {...props}>Component</div>;
};
export const Like = () => {
return (
<div>
<div>
<ButtonLike as="a" shape="outline" color="norm" href="https://proton.me">
Link
</ButtonLike>
</div>
<div className="mt-4">
<ButtonLike as={Component} color="danger" className="mb-4" />
</div>
</div>
);
};
| 5,026
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/Button.test.tsx
|
import { render } from '@testing-library/react';
import { Button } from './Button';
describe('<Button />', () => {
it('has button root', () => {
const { container } = render(<Button />);
const button = container.querySelector('button');
expect(button).toBeVisible();
});
it('has type="button" attribute', () => {
const { container } = render(<Button />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('type', 'button');
});
});
| 5,027
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/Button.tsx
|
import { Ref, forwardRef } from 'react';
import ButtonLike, { ButtonLikeProps } from './ButtonLike';
export interface ButtonProps extends Omit<ButtonLikeProps<'button'>, 'as' | 'ref'> {}
const ButtonBase = (props: ButtonProps, ref: Ref<HTMLButtonElement>) => {
return <ButtonLike type="button" ref={ref} {...props} as="button" />;
};
/*
export because of
https://github.com/storybookjs/storybook/issues/9511
https://github.com/styleguidist/react-docgen-typescript/issues/314
https://github.com/styleguidist/react-docgen-typescript/issues/215
*/
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(ButtonBase);
| 5,028
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/ButtonLike.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
/*
* Button shape
*/
.button {
display: inline-block;
padding-block: em(7); // 36 height
padding-inline: em(15);
border: 1px solid var(--button-default-border-color, transparent);
border-radius: var(--border-radius-md);
outline: none; // be careful of a11y
background-color: var(--button-default-background-color, transparent);
color: var(--button-default-text-color, inherit);
text-align: center;
cursor: pointer; // In case of a tag different from a or button
transition: 0.15s easing(ease-out-quint), background-position 0s;
@supports selector(:focus-visible:has(a, b)) {
// had to do this because of Safari
outline: unset;
}
&,
&:hover,
&:focus,
&:focus-within,
&:active {
text-decoration: none;
}
&:hover,
&.is-hover {
border-color: var(--button-hover-border-color, transparent);
background-color: var(--button-hover-background-color, transparent);
color: var(--button-hover-text-color, inherit);
opacity: 1; // In case the button is invisible as default
}
@supports not selector(:focus-visible:has(a, b)) {
&:focus,
&:focus-within {
border-color: var(--focus-outline);
box-shadow: 0 0 0 #{$focus-ring-size} var(--focus-ring);
color: var(--button-default-text-color, inherit);
}
}
@supports selector(:focus-visible:has(a, b)) {
&:focus {
// explicitly set color in case focus state get invoked
color: var(--button-default-text-color, inherit);
}
&:focus-visible,
&:has(*:focus-visible) {
border-color: var(--focus-outline);
box-shadow: 0 0 0 #{$focus-ring-size} var(--focus-ring);
color: var(--button-default-text-color, inherit);
}
}
&:active,
&.is-active,
// When clicking on a button to expand a container, we usually don't need to specify the `aria-controls` attribute
// because the expanded container is right next to that button, so the `aria-expanded` style makes sense,
// but in some cases that expanded container isn't so obviously visually connected to that button, so we use
// `aria-controls` to specify it, and avoid the `aria-expanded` style in the same time.
&[aria-expanded='true']:not([aria-controls]) {
border-color: var(--button-active-border-color, transparent);
background-color: var(--button-active-background-color, transparent);
color: var(--button-active-text-color, inherit);
opacity: 1; // In case the button is invisible as default
}
&[disabled],
&.is-disabled {
pointer-events: none;
background-color: var(--button-hover-background-color, transparent);
&:not([aria-busy='true']) {
border-color: transparent;
background-color: var(--interaction-weak, transparent);
color: var(--text-weak, inherit);
opacity: 0.5;
&[class*='button-ghost'] {
background-color: var(--button-default-background-color, transparent);
}
}
}
}
.button-underline {
position: relative;
display: inline-block;
padding-block: em(7);
outline: none; // be careful of a11y
color: var(--button-default-text-color, inherit);
text-decoration: underline;
transition: 0.15s easing(ease-out-quint);
@supports selector(:focus-visible:has(a, b)) {
// had to do this because of Safari
outline: unset;
}
&::after {
content: '';
position: absolute;
inset-block: em(4);
inset-inline: em(-3);
z-index: 1;
border-radius: var(--border-radius-md);
border: 1px solid transparent;
pointer-events: none;
transition: 0.15s easing(ease-out-quad);
}
@supports not selector(:focus-visible:has(a, b)) {
&:focus,
&:focus-within {
&::after {
border-color: var(--focus-outline);
box-shadow: 0 0 0 #{$focus-ring-size} var(--focus-ring);
}
}
}
@supports selector(:focus-visible:has(a, b)) {
&:focus-visible,
&:has(*:focus-visible) {
&::after {
border-color: var(--focus-outline);
box-shadow: 0 0 0 #{$focus-ring-size} var(--focus-ring);
}
}
}
&,
&.button-small,
&.button-large {
padding-inline: 0; // To ensure vertical alignments
}
&:hover,
&:focus,
&:focus-within,
&:active {
text-decoration: none;
}
&:hover,
&:focus,
&:focus-within {
color: var(--button-hover-text-color, inherit);
}
&:active,
&.is-active {
color: var(--button-active-text-color, inherit);
}
&[disabled],
&.is-disabled {
pointer-events: none;
&:not([aria-busy='true']) {
color: var(--text-weak, inherit);
opacity: 0.5;
}
}
}
/*
* Button variants
*/
@each $color in (norm, weak, danger, warning, success, info) {
// Initialize namespace
$group: if($color == 'norm' or $color == 'weak', 'interaction', 'signal');
// Solid shape
.button-solid-#{$color} {
$solid-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'contrast'))});
--button-default-background-color: var(--#{dash-join($group, $color)});
--button-hover-background-color: var(--#{dash-join($group, $color, 'major-1')});
--button-active-background-color: var(--#{dash-join($group, $color, 'major-2')});
--button-default-text-color: #{$solid-text-color};
--button-hover-text-color: #{$solid-text-color};
--button-active-text-color: #{$solid-text-color};
@if $color == 'norm' {
--focus-outline: var(--interaction-norm-major-2);
}
}
// Outline shape
.button-outline-#{$color} {
--button-default-background-color: var(--background-norm);
--button-hover-background-color: var(--#{dash-join($group, $color, 'minor-2')});
--button-active-background-color: var(--#{dash-join($group, $color, 'minor-1')});
--button-default-border-color: var(--#{dash-join($group, $color, 'major-1')});
--button-hover-border-color: var(--#{dash-join($group, $color, 'major-2')});
--button-active-border-color: var(--#{dash-join($group, $color, 'major-3')});
--button-default-text-color: var(
--#{if($color == 'weak' or $color == 'norm', 'text-norm', dash-join($group, $color, 'major-1'))}
);
--button-hover-text-color: var(
--#{if($color == 'weak' or $color == 'norm', 'text-norm', dash-join($group, $color, 'major-2'))}
);
--button-active-text-color: var(
--#{if($color == 'weak' or $color == 'norm', 'text-norm', dash-join($group, $color, 'major-3'))}
);
}
// Ghost shape
.button-ghost-#{$color} {
--button-default-background-color: var(--interaction-default);
--button-hover-background-color: var(--interaction-default-hover);
--button-active-background-color: var(--interaction-default-active);
--button-default-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'major-1'))});
--button-hover-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'major-2'))});
--button-active-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'major-3'))});
}
// Underline shape
.button-underline-#{$color} {
--button-default-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'major-1'))});
--button-hover-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'major-2'))});
--button-active-text-color: var(--#{if($color == 'weak', 'text-norm', dash-join($group, $color, 'major-3'))});
}
}
/*
* Modifiers
*/
.button-small {
padding-block: em(3); // 28px height
padding-inline: em(11);
}
.button-large {
padding-block: em(9, 16); // 44px height
padding-inline: em(19, 16);
font-size: em(16);
line-height: #{math.div(24, 16)};
}
.button-for-icon {
padding: em(9); // To have same height as fields
&.button-small {
padding: em(5);
}
&.button-large {
padding-block: em(13, 16);
padding-inline: em(13, 16);
}
& > svg {
display: block;
transition: opacity 0.25s ease-out;
}
}
// Loading state
.button[aria-busy='true'] {
position: relative;
&:not(.button-for-icon) {
&:not(.w-full) {
padding-inline-end: em(40);
&.button-small {
padding-inline-end: em(32);
}
&.button-large {
padding-inline-end: em(44);
}
}
.button-loader-container {
inset-inline-end: em(16);
}
&.button-small .button-loader-container {
inset-inline-end: em(10);
}
&.button-large .button-loader-container {
inset-inline-end: em(20);
}
}
&.button-for-icon {
& > svg {
opacity: 0;
}
.button-loader-container {
inset: 0;
}
}
}
.button-underline[aria-busy='true'] {
position: relative;
padding-inline-end: em(20);
.button-loader-container {
inset-inline-end: 0;
}
}
.button-loader-container {
position: absolute;
inset-block: 0;
display: flex;
justify-content: center;
align-items: center;
animation: 0.25s ease-out both anime-button-loader-container-fade-in;
@keyframes anime-button-loader-container-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
}
.button-pill {
border-radius: 2em;
}
| 5,029
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/ButtonLike.test.tsx
|
/* eslint-disable jsx-a11y/tabindex-no-positive */
import { fireEvent, render } from '@testing-library/react';
import ButtonLike from './ButtonLike';
const testid = 'button-like';
describe('<ButtonLike />', () => {
it('renders with children', () => {
const children = 'hello';
const { container } = render(<ButtonLike>{children}</ButtonLike>);
const rootElement = container.firstChild;
expect(rootElement?.textContent).toBe(children);
});
it('adds button class by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button');
});
it('forwards className', () => {
const className = 'should-be-forwarded';
const { container } = render(<ButtonLike className={className} />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass(className);
});
it('allows clicking of button', () => {
const mockOnClick = jest.fn();
const { getByTestId } = render(<ButtonLike onClick={mockOnClick} data-testid={testid} />);
const rootElement = getByTestId(testid);
fireEvent.click(rootElement);
expect(rootElement).not.toBeDisabled();
expect(mockOnClick).toHaveBeenCalledTimes(1);
});
it('allows setting of tabIndex', () => {
const { container } = render(<ButtonLike tabIndex={0} />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('tabIndex', '0');
});
it('sets aria-busy attribute to false by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('aria-busy', 'false');
});
it('does not show loader component by default', () => {
const { container } = render(<ButtonLike />);
const loaderComponent = container.querySelector('.button-loader-container');
expect(loaderComponent).toBeNull();
});
describe('as', () => {
it('defaults to button element', () => {
const { container } = render(<ButtonLike />);
const button = container.querySelector('button');
expect(button).toBeVisible();
});
it('allows setting of root element', () => {
const { container } = render(<ButtonLike as="a" />);
const button = container.querySelector('button');
const a = container.querySelector('a');
expect(button).toBeNull();
expect(a).toBeVisible();
});
it(`adds 'inline-block text-center' classes if 'as' prop is not 'button'`, () => {
const { container } = render(<ButtonLike as="a" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('inline-block');
expect(rootElement).toHaveClass('text-center');
});
});
describe('loading', () => {
it('disables button', () => {
const mockOnClick = jest.fn();
const { getByTestId } = render(<ButtonLike loading onClick={mockOnClick} data-testid={testid} />);
const rootElement = getByTestId(testid);
fireEvent.click(rootElement);
expect(rootElement).toBeDisabled();
expect(mockOnClick).toHaveBeenCalledTimes(0);
});
it('adds aria-busy attribute when loading', () => {
const { container } = render(<ButtonLike loading />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('aria-busy', 'true');
});
it('sets tabIndex to -1', () => {
const { container } = render(<ButtonLike loading tabIndex={0} />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('tabIndex', '-1');
});
it('renders loader component', () => {
const { container } = render(<ButtonLike loading />);
const loaderComponent = container.querySelector('.button-loader-container');
expect(loaderComponent).toBeVisible();
});
});
describe('disabled', () => {
it('sets tabIndex to -1', () => {
const { container } = render(<ButtonLike disabled tabIndex={0} />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('tabIndex', '-1');
});
it('disables button', () => {
const mockOnClick = jest.fn();
const { getByTestId } = render(<ButtonLike disabled onClick={mockOnClick} data-testid={testid} />);
const rootElement = getByTestId(testid);
fireEvent.click(rootElement);
expect(rootElement).toBeDisabled();
expect(mockOnClick).toHaveBeenCalledTimes(0);
});
});
describe('shape', () => {
it('defaults to outline if color is weak', () => {
const { container } = render(<ButtonLike color="weak" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-outline-weak');
});
it('defaults to solid if color is not weak', () => {
const { container } = render(<ButtonLike color="norm" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-norm');
});
describe('solid', () => {
it('uses button-solid-weak class', () => {
const { container } = render(<ButtonLike shape="solid" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-weak');
});
});
describe('outline', () => {
it('uses button-outline-weak class', () => {
const { container } = render(<ButtonLike shape="outline" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-outline-weak');
});
});
describe('ghost', () => {
it('uses button-ghost-weak class', () => {
const { container } = render(<ButtonLike shape="ghost" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-ghost-weak');
});
});
describe('underline', () => {
it('removes button class', () => {
const { container } = render(<ButtonLike shape="underline" />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('button');
});
it('adds button-underline class', () => {
const { container } = render(<ButtonLike shape="underline" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-underline');
});
it('does not render as pill even if pill is true', () => {
const { container } = render(<ButtonLike shape="underline" pill />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('button-pill');
});
it('does not render as icon even if icon is true', () => {
const { container } = render(<ButtonLike shape="underline" icon />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('button-for-icon');
});
it('does not render full width even if fullWidth is true', () => {
const { container } = render(<ButtonLike shape="underline" fullWidth />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('w-full');
});
});
});
describe('color', () => {
it('defaults to weak', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-outline-weak');
});
describe('norm', () => {
it('uses button-solid-norm class', () => {
const { container } = render(<ButtonLike color="norm" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-norm');
});
});
describe('weak', () => {
it('uses button-solid-weak class', () => {
const { container } = render(<ButtonLike color="weak" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-outline-weak');
});
});
describe('danger', () => {
it('uses button-solid-danger class', () => {
const { container } = render(<ButtonLike color="danger" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-danger');
});
});
describe('warning', () => {
it('uses button-solid-warning class', () => {
const { container } = render(<ButtonLike color="warning" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-warning');
});
});
describe('success', () => {
it('uses button-solid-success class', () => {
const { container } = render(<ButtonLike color="success" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-success');
});
});
describe('info', () => {
it('uses button-solid-info class', () => {
const { container } = render(<ButtonLike color="info" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-solid-info');
});
});
});
describe('size', () => {
it('defaults to medium', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
/**
* There is no button-medium class,
* so we assert that the other size classes aren't included
*/
expect(rootElement).not.toHaveClass('button-large');
expect(rootElement).not.toHaveClass('button-small');
});
it('adds button-small class when size is small', () => {
const { container } = render(<ButtonLike size="small" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-small');
});
it('adds button-large class when size is large', () => {
const { container } = render(<ButtonLike size="large" />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-large');
});
});
describe('fullWidth', () => {
it('adds w-full class if fullWidth is true', () => {
const { container } = render(<ButtonLike fullWidth />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('w-full');
});
it('does not add w-full class by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('w-full');
});
});
describe('pill', () => {
it('adds button-pill class if pill is true', () => {
const { container } = render(<ButtonLike pill />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-pill');
});
it('does not add button-pill class by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('button-pill');
});
});
describe('icon', () => {
it('adds button-for-icon class if icon is true', () => {
const { container } = render(<ButtonLike icon />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-for-icon');
});
it('does not add button-for-icon class by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('button-for-icon');
});
});
describe('group', () => {
it('adds button-group-item class if group is true', () => {
const { container } = render(<ButtonLike group />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('button-group-item');
});
it('does not add button-group-item class by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('button-group-item');
});
});
describe('selected', () => {
it('adds is-selected class if group and selected is true', () => {
const { container } = render(<ButtonLike group selected />);
const rootElement = container.firstChild;
expect(rootElement).toHaveClass('is-selected');
});
it('does not add is-selected class if group is false and selected is true', () => {
const { container } = render(<ButtonLike selected />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('is-selected');
});
it('does not add is-selected by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveClass('is-selected');
});
});
describe('roleProps', () => {
it('adds no role by default', () => {
const { container } = render(<ButtonLike />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveAttribute('role');
});
it('adds button role if onClick handler exists and no type is defined', () => {
const { container } = render(<ButtonLike onClick={() => {}} type={undefined} />);
const rootElement = container.firstChild;
expect(rootElement).toHaveAttribute('role', 'button');
});
it('adds no role if type is defined', () => {
const { container } = render(<ButtonLike type="button" />);
const rootElement = container.firstChild;
expect(rootElement).not.toHaveAttribute('role');
});
});
});
| 5,030
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/ButtonLike.tsx
|
import { ElementType, ForwardedRef, ReactElement, forwardRef } from 'react';
import { PolymorphicPropsWithRef } from 'react-polymorphic-types';
import { ThemeColorUnion } from '@proton/colors';
import clsx from '@proton/utils/clsx';
import { CircleLoader } from '../CircleLoader';
import './ButtonLike.scss';
export type ButtonLikeShape = 'solid' | 'outline' | 'ghost' | 'underline';
export type ButtonLikeSize = 'small' | 'medium' | 'large';
interface ButtonLikeOwnProps {
/**
* Whether the button should render a loader.
* Button is disabled when this prop is true.
*/
loading?: boolean;
/**
* Controls the shape of the button.
* - `solid` for filled button
* - `outline` for bordered button
* - `ghost` for minimalistic button with hover/focus changing
* - `underline` for underlined text button, with paddings for alignment
*/
shape?: ButtonLikeShape;
/**
* Controls the colors of the button.
* Exact styles applied depend on the chosen shape as well.
*/
color?: ThemeColorUnion;
/**
* Controls how large the button should be.
*/
size?: ButtonLikeSize;
/**
* Puts the button in a disabled state.
*/
disabled?: boolean;
/**
* If true, the button will take up the full width of its container.
*/
fullWidth?: boolean;
/**
* If true, display as pill.
*/
pill?: boolean;
/**
* If true, display as icon.
*/
icon?: boolean;
/**
* If true, this button is part of a button group.
*/
group?: boolean;
/**
* For a selected item inside a group.
*/
selected?: boolean;
/**
* Locator for e2e tests.
*/
'data-testid'?: string;
}
export type ButtonLikeProps<E extends ElementType> = PolymorphicPropsWithRef<ButtonLikeOwnProps, E>;
const defaultElement = 'button';
const ButtonLikeBase = <E extends ElementType = typeof defaultElement>(
{
loading = false,
disabled = false,
className,
tabIndex,
children,
shape: shapeProp,
color = 'weak',
size = 'medium',
fullWidth,
pill,
icon,
group,
selected = false,
as,
'data-testid': dataTestId,
...restProps
}: ButtonLikeProps<E>,
ref: ForwardedRef<Element>
) => {
const isDisabled = loading || disabled;
const shape = shapeProp || (color === 'weak' ? 'outline' : 'solid');
const isUnderlineShape = shape === 'underline';
const Element: ElementType = as || defaultElement;
const buttonClassName = clsx(
isUnderlineShape ? 'button-underline' : 'button',
!isUnderlineShape && pill && 'button-pill',
!isUnderlineShape && icon && 'button-for-icon',
!isUnderlineShape && fullWidth && 'w-full',
group && 'button-group-item',
group && selected && 'is-selected',
size !== 'medium' && `button-${size}`,
`button-${shape}-${color}`,
Element !== 'button' && 'inline-block text-center',
className
);
const roleProps = restProps.onClick && !restProps.type ? { role: 'button' } : undefined;
return (
<Element
ref={ref}
className={buttonClassName}
disabled={isDisabled}
tabIndex={isDisabled ? -1 : tabIndex}
aria-busy={loading}
data-testid={dataTestId}
{...roleProps}
{...restProps}
>
{children}
{loading && (
<span className="button-loader-container">
<CircleLoader />
</span>
)}
</Element>
);
};
const ButtonLike: <E extends ElementType = typeof defaultElement>(props: ButtonLikeProps<E>) => ReactElement | null =
forwardRef(ButtonLikeBase);
export default ButtonLike;
| 5,031
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/index.ts
|
export * from './Button';
export { default as ButtonLike } from './ButtonLike';
export * from './ButtonLike';
| 5,032
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Card/Card.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
# Card
```js
import { Card } from '@proton/atoms';
```
This component currently is a container with a bit of styling adhering to a "card / surface" concept, however design is pending on this so for now we're only adding this thin layer, no other card-related components or logic.
<Canvas withSource="open">
<Story id="components-card--basic" />
</Canvas>
### With Action
This isn't really part of the Card's api, it's just an example of a use-case commonly encountered.
<Canvas>
<Story id="components-card--with-action-horizontal" />
</Canvas>
## Sandbox
<Story id="components-card--sandbox" />
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,033
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Card/Card.stories.tsx
|
import { useState } from 'react';
import { Button } from '@proton/atoms';
import { Checkbox } from '@proton/components';
import Card from './Card';
import mdx from './Card.mdx';
export default {
component: Card,
title: 'components/Card',
parameters: { docs: { page: mdx } },
};
export const Basic = () => (
<Card>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit doloribus nobis eos iusto. Ducimus numquam laborum
aliquid culpa! Dolor voluptatem modi inventore error, qui repudiandae consequatur autem vitae illum
voluptatibus?
</Card>
);
export const WithActionHorizontal = () => (
<Card className="flex flex-align-items-center">
<p className="m-0 mr-8 flex-item-fluid">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tempore ipsa dolores delectus fugit consequuntur
impedit velit officia tenetur, magni placeat, voluptatum porro unde repudiandae cum explicabo assumenda
distinctio, mollitia voluptate.
</p>
<Button color="norm">Upgrade</Button>
</Card>
);
const toggles = ['bordered', 'rounded', 'background'] as const;
export const Sandbox = () => {
const [selectedToggles, setSelectedToggles] = useState([true, false, true]);
const tabsExample = (
<Card
{...selectedToggles.reduce<{ [key: string]: boolean }>((acc, value, i) => {
acc[toggles[i]] = value;
return acc;
}, {})}
>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit doloribus nobis eos iusto. Ducimus numquam
laborum aliquid culpa! Dolor voluptatem modi inventore error, qui repudiandae consequatur autem vitae illum
voluptatibus?
</Card>
);
return (
<div className="flex flex-align-items-stretch py-7">
<div>{tabsExample}</div>
<div className="mr-8">
<strong className="block mt-4">Options</strong>
{toggles.map((prop, i) => {
return (
<div className="mb-2">
<Checkbox
checked={selectedToggles[i]}
onChange={({ target: { checked } }) => {
setSelectedToggles(
selectedToggles.map((oldValue, otherIndex) =>
otherIndex === i ? checked : oldValue
)
);
}}
>
{prop}
</Checkbox>
</div>
);
})}
</div>
</div>
);
};
| 5,034
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Card/Card.test.tsx
|
import { render } from '@testing-library/react';
import Card from './Card';
describe('<Card />', () => {
it('renders with a border and background by default', () => {
const { container } = render(<Card>Lorem ipsum dolor sit amet consectetur adipisicing elit.</Card>);
expect(container.firstChild).toHaveClass('border');
expect(container.firstChild).toHaveClass('bg-weak');
});
it('renders without a border and background if explicitly specified', () => {
const { container } = render(
<Card bordered={false} background={false}>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</Card>
);
expect(container.firstChild).not.toHaveClass('border');
expect(container.firstChild).not.toHaveClass('bg-weak');
});
it('renders rounded', () => {
const { container } = render(<Card rounded>Lorem ipsum dolor sit amet consectetur adipisicing elit.</Card>);
expect(container.firstChild).toHaveClass('rounded');
});
});
| 5,035
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Card/Card.tsx
|
import { ElementType } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import clsx from '@proton/utils/clsx';
export interface CardOwnProps {
bordered?: boolean;
rounded?: boolean;
background?: boolean;
}
export type CardProps<E extends ElementType> = PolymorphicPropsWithoutRef<CardOwnProps, E>;
const defaultElement = 'div';
const Card = <E extends ElementType = typeof defaultElement>({
className,
bordered = true,
rounded = false,
background = true,
as,
...rest
}: CardProps<E>) => {
const Element: ElementType = as || defaultElement;
return (
<Element
className={clsx('p-4', className, rounded && 'rounded', bordered && 'border', background && 'bg-weak')}
{...rest}
/>
);
};
export default Card;
| 5,036
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Card/index.ts
|
export { default as Card } from './Card';
export * from './Card';
| 5,037
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/CircleLoader.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { CircleLoader } from './CircleLoader';
# CircleLoader
```js
import { CircleLoader } from '@proton/atoms';
```
The `CircleLoader` should be used to indicate that a component / data is loading.<br /> The loader color can be changed using color classes like `color-primary`.
<Canvas withSource="open">
<Story id="components-circleloader--basic" />
</Canvas>
## Sizes
Possible sizes are `small`, `medium`, and `large`, with `small` being the default.
<Canvas>
<Story id="components-circleloader--sizes" />
</Canvas>
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,038
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/CircleLoader.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
.circle-loader {
$total-length: 43.699; // total length of path, calculated by getTotalLength() in JS
$looping-percent: 60;
$looping-length: math.div($looping-percent * $total-length, 100);
display: inline-block;
inline-size: 1em;
block-size: 1em;
transform-origin: 50%;
font-size: 1em;
vertical-align: middle;
&-track,
&-circle {
fill: none;
stroke-width: var(--stroke-width, 2);
stroke-linecap: round;
stroke: currentcolor;
}
&-track {
opacity: 0.2;
}
&-circle {
stroke-dasharray: #{$looping-length * 1px}, #{($total-length - $looping-length) * 1px};
animation: anime-loader-stroke 1s linear infinite;
@keyframes anime-loader-stroke {
from {
stroke-dashoffset: $total-length;
}
to {
stroke-dashoffset: 0;
}
}
}
/*
&.is-small {
Small is the default
}
*/
&.is-medium {
--stroke-width: 1.3;
font-size: em(32);
}
&.is-large {
--stroke-width: 1;
font-size: em(48);
}
}
| 5,039
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/CircleLoader.stories.tsx
|
import CircleLoader from './CircleLoader';
import mdx from './CircleLoader.mdx';
export default {
component: CircleLoader,
title: 'components/CircleLoader',
parameters: { docs: { page: mdx } },
};
export const Basic = () => (
<>
<CircleLoader />
<br />
<CircleLoader size="medium" className="color-primary" />
<br />
<CircleLoader size="large" className="color-danger" />
</>
);
export const Sizes = () => (
<div className="block">
<div>Small</div>
<CircleLoader />
<div className="mt-8">Medium</div>
<CircleLoader size="medium" />
<div className="mt-8">Large</div>
<CircleLoader size="large" />
</div>
);
| 5,040
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/CircleLoader.test.tsx
|
import { render } from '@testing-library/react';
import CircleLoader from './CircleLoader';
const circleLoaderTestId = 'circle-loader';
describe('<CircleLoader />', () => {
it('passes className', () => {
const { getByTestId } = render(<CircleLoader className="should-be-passed" data-testid={circleLoaderTestId} />);
const circleLoaderElement = getByTestId(circleLoaderTestId);
expect(circleLoaderElement).toHaveClass('should-be-passed');
});
it('defaults to small size', () => {
const { getByTestId } = render(<CircleLoader data-testid={circleLoaderTestId} />);
const circleLoaderElement = getByTestId(circleLoaderTestId);
expect(circleLoaderElement).toHaveClass('circle-loader');
});
it('adds is-medium class when size is medium', () => {
const { getByTestId } = render(<CircleLoader size="medium" data-testid={circleLoaderTestId} />);
const circleLoaderElement = getByTestId(circleLoaderTestId);
expect(circleLoaderElement).toHaveClass('is-medium');
});
it('adds is-large class when size is large', () => {
const { getByTestId } = render(<CircleLoader size="large" data-testid={circleLoaderTestId} />);
const circleLoaderElement = getByTestId(circleLoaderTestId);
expect(circleLoaderElement).toHaveClass('is-large');
});
it('renders sr-only item', () => {
const { getByTestId } = render(<CircleLoader data-testid={circleLoaderTestId} />);
const circleLoaderElement = getByTestId(circleLoaderTestId);
const srElement = circleLoaderElement.nextSibling;
expect(srElement).toHaveClass('sr-only');
expect(srElement?.textContent).toBe('Loading');
});
});
| 5,041
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/CircleLoader.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
import generateUID from '../generateUID';
import './CircleLoader.scss';
export type CircleLoaderSize = 'small' | 'medium' | 'large';
export interface CircleLoaderProps extends ComponentPropsWithoutRef<'svg'> {
size?: CircleLoaderSize;
srLabelHidden?: Boolean;
}
const CircleLoader = ({ size, className, srLabelHidden, ...rest }: CircleLoaderProps) => {
const uid = generateUID('circle-loader');
return (
<>
<svg
xmlns="http://www.w3.org/2000/svg"
className={clsx('circle-loader', size && `is-${size}`, className)}
viewBox="0 0 16 16"
data-testid="circle-loader"
{...rest}
>
<defs>
<circle id={uid} cx="8" cy="8" r="7" />
</defs>
<use href={`#${uid}`} className="circle-loader-track" />
<use href={`#${uid}`} className="circle-loader-circle" />
</svg>
{!srLabelHidden ? <span className="sr-only">{c('Info').t`Loading`}</span> : null}
</>
);
};
export default CircleLoader;
| 5,042
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/index.ts
|
export { default as CircleLoader } from './CircleLoader';
export * from './CircleLoader';
| 5,043
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Donut/Donut.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
# Donut
```js
import { Donut } from '@proton/atoms';
```
<Canvas withSource="open">
<Story id="components-donut--basic" />
</Canvas>
## With slider
This isn't really part of the api, it's just used to demonstrate that the Donut is able to adapt in real time to react state changes (through the `segments` property), as well as automatically scale past 100 percent, should the percentages of all segments add up to more than 100.
<Canvas>
<Story id="components-donut--with-slider" />
</Canvas>
## Accessibility
Since the Donut itself is only visual to represent % share of allocation, one way to make this data accessible is to add screen-reader text inside assistive texts used to label the individual Donut segments.
<Canvas>
<Story id="components-donut--accessibility" />
</Canvas>
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,044
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Donut/Donut.stories.tsx
|
import { ChangeEvent, useState } from 'react';
import { ThemeColor, getVariableFromThemeColor } from '@proton/colors';
import Donut from './Donut';
import mdx from './Donut.mdx';
export default {
component: Donut,
title: 'components/Donut',
parameters: {
docs: {
page: mdx,
},
},
};
export const Basic = () => {
return (
<div style={{ width: 200, height: 200 }}>
<Donut
segments={[
[20, ThemeColor.Danger],
[10, ThemeColor.Warning],
[15, ThemeColor.Success],
[10, ThemeColor.Norm],
[5, ThemeColor.Weak],
]}
/>
</div>
);
};
export const WithSlider = () => {
const [success, setSuccess] = useState(20);
return (
<div>
<input
className="mb-8"
style={{ appearance: 'auto' }}
type="range"
value={success}
min={0}
max={200}
onInput={(e: ChangeEvent<HTMLInputElement>) => setSuccess(Number(e.target.value))}
/>
<div style={{ width: 200, height: 200 }}>
<Donut
segments={[
[40, ThemeColor.Danger],
[20, ThemeColor.Warning],
[success, ThemeColor.Success],
]}
/>
</div>
</div>
);
};
export const Accessibility = () => {
const used = 40;
const alreadyAllocated = 20;
const allocated = 30;
const labelledSegments = [
{ label: 'Already used', value: [used, ThemeColor.Danger] },
{ label: 'Already allocated', value: [alreadyAllocated, ThemeColor.Warning] },
{ label: 'Allocated', value: [allocated, ThemeColor.Success] },
] as const;
return (
<div className="flex flex-align-items-center">
<div className="mr-8" style={{ width: 160, height: 160 }}>
<Donut segments={labelledSegments.map(({ value }) => value as [number, string])} />
</div>
<div>
{labelledSegments.map(({ label, value: [share, color] }) => (
<div className="mb-4 flex flex-align-items-center">
<span
className="inline-block mr-4"
style={{
width: 36,
height: 24,
borderRadius: 8,
background: `var(${getVariableFromThemeColor(color)})`,
}}
/>
<strong>
<span className="sr-only">{share} GB</span>
{label}
</strong>
</div>
))}
</div>
</div>
);
};
| 5,045
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Donut/Donut.test.tsx
|
import { render } from '@testing-library/react';
import { ThemeColor } from '@proton/colors/types';
import Donut from './Donut';
describe('<Donut />', () => {
it('renders specified segments', () => {
const { container } = render(
<Donut
segments={[
[20, ThemeColor.Danger],
[10, ThemeColor.Warning],
]}
/>
);
expect(container.querySelectorAll('rect')).toHaveLength(4);
expect(container.querySelectorAll('circle')).toHaveLength(3);
});
});
| 5,046
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Donut/Donut.tsx
|
import { ThemeColor, getVariableFromThemeColor } from '@proton/colors';
import useUid from '@proton/components/hooks/useUid';
import percentOf from '@proton/utils/percentOf';
export type DonutSegmentColor = ThemeColor | string;
const themeColors = Object.values(ThemeColor);
export interface DonutProps {
/**
* Array of "number, string" tuples that represent the individual
* segments of the donut chart, consisting of:
* `[ percentage (number), color (ThemeColor | string) ]`
*
* If the sum of all percentages is less than 100, the Donut
* will display an additional, auto-generated segment using a neutral
* color to represent an empty or remaining amount. If all percentages
* sum up to more than 100, the Donut will scale all segments
* relative to the sum of all percentages. It's possible to create a
* remaining amount manually even if the sum exceeds 100, by creating
* a custom last chunk with a neutral background.
*/
segments: [number, DonutSegmentColor][];
/**
* Gap in absolute viewbox units to apply between individual
* arc segments of the donut chart.
*/
gap?: number;
/**
* color code of background segment
*/
backgroundSegmentColor?: string;
}
const Donut = ({ segments, gap = 4, backgroundSegmentColor = 'var(--background-strong)' }: DonutProps) => {
const uid = useUid('straight-gaps');
const box = 200;
const width = box / 6;
const radius = box / 2 - width / 2;
const circumference = 2 * Math.PI * radius;
const offset = percentOf(25, circumference);
const sumOfAllChunks = segments.reduce((sum, [n]) => sum + n, 0);
const runningSumOfAllChunks = segments.reduce(
(runningSum, [n], i) => [...runningSum, (runningSum[i - 1] || 0) + n],
[] as number[]
);
const remaining = [100 - sumOfAllChunks, backgroundSegmentColor] as const;
const allChunks = [...segments, remaining].map((chunk) => {
const [percentage, color] = chunk;
if (themeColors.includes(color as ThemeColor)) {
return [percentage, `var(${getVariableFromThemeColor(color as ThemeColor)})`] as const;
}
return chunk;
});
/**
* Make sure arc segments scale relative to either 100 percent or the sum of
* all chunks should it be greater than 100. Chunk percentages should ideally
* never add up to more than 100, however if they do all arc segments need to
* be scaled down to avoid overflow beyond one rotation of the donut.
*/
const scale = sumOfAllChunks > 100 ? 100 / sumOfAllChunks : 1;
return (
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox={`0 0 ${box} ${box}`}>
{gap > 0 && (
<defs>
<mask id={uid}>
<rect x="0" y="0" width={box} height={box} fill="white" />
{allChunks.map(([, color], i) => {
const angle = scale * percentOf(runningSumOfAllChunks[i - 1] || 0, 360) - 90;
return (
<rect
key={color}
transform={`rotate(${angle} ${box / 2} ${box / 2})`}
x={box / 2}
y={box / 2 - gap / 2}
width={box / 2 + 1}
height={gap}
fill="black"
/>
);
})}
</mask>
</defs>
)}
<g mask={gap > 0 ? `url(#${uid})` : undefined}>
{allChunks.map(([percentage, color], i) => {
const arcLength = scale * Math.max(0, percentOf(percentage, circumference));
const strokeDashOffset =
offset - scale * percentOf(runningSumOfAllChunks[i - 1] || 0, circumference);
return (
<circle
key={color}
fill="none"
cx={box / 2}
cy={box / 2}
r={radius}
stroke={color}
strokeWidth={width}
strokeDasharray={`${arcLength} ${circumference - arcLength}`}
strokeDashoffset={strokeDashOffset}
/>
);
})}
</g>
</svg>
);
};
export default Donut;
| 5,047
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Donut/index.ts
|
export { default as Donut } from './Donut';
export * from './Donut';
| 5,048
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Href/Href.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { Href } from './Href';
# Href
```js
import { Href } from '@proton/atoms';
```
Simple anchor tag wrapper with opinionated defaults.
<Canvas withSource="open">
<Story id="components-href--basic" />
</Canvas>
## Defaults
`href` defaults to `#`, `target` defaults to `_blank`, and `rel` defaults to `noopener noreferrer nofollow`.
| 5,049
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Href/Href.stories.tsx
|
import Href from './Href';
import mdx from './Href.mdx';
export default {
component: Href,
title: 'components/Href',
parameters: { docs: { page: mdx } },
};
export const Basic = () => <Href href="https://proton.me">Visit the Proton website</Href>;
| 5,050
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Href/Href.test.tsx
|
import { render } from '@testing-library/react';
import Href from './Href';
describe('<Href />', () => {
it('defaults href to #', () => {
const { container } = render(<Href>Link text</Href>);
expect(container.firstChild).toHaveAttribute('href', '#');
});
it('allows setting of href', () => {
const href = 'hello';
const { container } = render(<Href href={href}>Link text</Href>);
expect(container.firstChild).toHaveAttribute('href', href);
});
it(`defaults target to '_blank'`, () => {
const { container } = render(<Href>Link text</Href>);
expect(container.firstChild).toHaveAttribute('target', '_blank');
});
it('allows setting of target', () => {
const target = 'target';
const { container } = render(<Href target={target}>Link text</Href>);
expect(container.firstChild).toHaveAttribute('target', target);
});
it(`defaults rel to 'noopener noreferrer nofollow'`, () => {
const { container } = render(<Href>Link text</Href>);
expect(container.firstChild).toHaveAttribute('rel', 'noopener noreferrer nofollow');
});
it('allows setting of rel', () => {
const rel = 'rel';
const { container } = render(<Href rel={rel}>Link text</Href>);
expect(container.firstChild).toHaveAttribute('rel', rel);
});
it('forwards anchor props', () => {
const className = 'className';
const childText = 'Link text';
const { container } = render(<Href className={className}>{childText}</Href>);
expect(container.firstChild).toHaveClass(className);
expect(container.firstChild?.textContent).toBe(childText);
});
});
| 5,051
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Href/Href.tsx
|
import { ComponentPropsWithRef, ReactNode, Ref, forwardRef } from 'react';
import clsx from '@proton/utils/clsx';
export interface HrefProps extends ComponentPropsWithRef<'a'> {
children: ReactNode;
}
const Href = (
{ href = '#', target = '_blank', rel = 'noopener noreferrer nofollow', children, ...rest }: HrefProps,
ref: Ref<HTMLAnchorElement>
) => (
<a href={href} target={target} rel={rel} ref={ref} className={clsx('link link-focus', rest.className)} {...rest}>
{children}
</a>
);
export default forwardRef<HTMLAnchorElement, HrefProps>(Href);
| 5,052
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Href/index.ts
|
export { default as Href } from './Href';
export * from './Href';
| 5,053
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Input/Input.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { Alert } from '@proton/components';
import { Input } from './Input';
# Input
```js
import { Input } from '@proton/atoms';
```
Basic input html element wrapper with disabled/error states, styling, and input adornments.
<Alert>
If you are looking to wrap the input with labels or hint text, please see{' '}
<a href="?path=/docs/components-inputfield--basic">InputField</a>.
</Alert>
<Canvas withSource="open">
<Story id="components-input--basic" />
</Canvas>
## Controlled input
Use the `value` and `onValue` props to control the input.
<Canvas withSource="open">
<Story id="components-input--controlled" />
</Canvas>
## Error state
Use the `error` prop to add error styling.
<Canvas>
<Story id="components-input--error" />
</Canvas>
## Disabled state
Use the `disabled` prop to disable the input. This prevents the user interacting with the input and adds disabled styling.
<Canvas>
<Story id="components-input--disabled" />
</Canvas>
## Unstyled
Use the `unstyled` prop to remove any default styling.
<Canvas>
<Story id="components-input--unstyled" />
</Canvas>
## Adornments
Use the `prefix` and `suffix` props to adorn the input.
<Canvas>
<Story id="components-input--adornments" />
</Canvas>
## Props
<ArgsTable story={PRIMARY_STORY} />
| 5,054
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Input/Input.stories.tsx
|
import { useState } from 'react';
import { Icon, Option, SelectTwo } from '@proton/components';
import { Input } from './Input';
import mdx from './Input.mdx';
export default {
component: Input,
title: 'components/Input',
parameters: { docs: { page: mdx } },
};
export const Basic = () => {
const [value, setValue] = useState('');
const handleValue = (updatedValue: string) => setValue(updatedValue);
return <Input placeholder="Placeholder" value={value} onValue={handleValue} />;
};
export const Controlled = () => {
const [value, setValue] = useState('');
const handleValue = (updatedValue: string) => setValue(updatedValue);
return (
<>
<Input placeholder="Placeholder" value={value} onValue={handleValue} />
<p className="mb-1">
The `disableChange` prop can be used to prevent the input value from updating. Try updating the value
from the input below.
</p>
<Input disableChange placeholder="Placeholder" value={value} onValue={handleValue} />
</>
);
};
export const Error = () => {
return <Input error />;
};
export const Disabled = () => {
return (
<>
<Input disabled />
<p className="mb-1">Note the disabled styling added to the prefix and suffix</p>
<Input disabled prefix={<Icon name="magnifier" />} suffix="@protonmail.com" />
</>
);
};
export const Unstyled = () => {
return <Input unstyled prefix={<Icon name="magnifier" />} placeholder="Search" />;
};
export const Adornments = () => {
return (
<>
<Input className="mb-2" prefix={<Icon name="magnifier" />} />
<Input className="mb-2" placeholder="**** **** **** ****" suffix={<Icon name="credit-card" />} />
<Input className="mb-2" placeholder="username" suffix="@protonmail.com" />
<Input
className="mb-2"
placeholder="username"
suffix={
<SelectTwo unstyled value="pm.me">
<Option key="pm.me" value="pm.me" title="pm.me">
@pm.me
</Option>
<Option key="protonmail.com" value="protonmail.com" title="protonmail.com">
@protonmail.com
</Option>
</SelectTwo>
}
/>
</>
);
};
| 5,055
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Input/Input.test.tsx
|
import { Matcher, MatcherOptions, fireEvent, render } from '@testing-library/react';
import { Input } from './Input';
type GetByTestIdType = (id: Matcher, options?: MatcherOptions | undefined) => HTMLElement;
const inputRootTestid = 'input-root';
const inputElementTestid = 'input-input-element';
describe('<Input />', () => {
describe('uncontrolled', () => {
it('sets input element value', () => {
const { getByTestId } = render(<Input />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(input).toHaveValue('a');
});
});
describe('onValue', () => {
it('calls onValue with value when input is fired', () => {
const onValue = jest.fn();
const { getByTestId } = render(<Input onValue={onValue} />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(onValue).toHaveBeenCalledWith('a');
});
});
describe('onChange', () => {
it('calls onChange when input is fired', () => {
const onChange = jest.fn();
const { getByTestId } = render(<Input onChange={onChange} />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(onChange.mock.lastCall[0].target.value).toEqual('a');
});
});
describe('disableChange', () => {
describe('true', () => {
it('does not call onValue when input is fired', () => {
const onValue = jest.fn();
const { getByTestId } = render(<Input onValue={onValue} disableChange />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(onValue).not.toHaveBeenCalled();
});
it('does not call onChange when input is fired', () => {
const onChange = jest.fn();
const { getByTestId } = render(<Input onChange={onChange} disableChange />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(onChange).not.toHaveBeenCalled();
});
});
describe('false', () => {
it('calls onValue when input is fired', () => {
const onValue = jest.fn();
const { getByTestId } = render(<Input onValue={onValue} />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(onValue).toHaveBeenCalled();
});
it('calls onChange when input is fired', () => {
const onChange = jest.fn();
const { getByTestId } = render(<Input onChange={onChange} />);
const input = getByTestId(inputElementTestid);
fireEvent.input(input, { target: { value: 'a' } });
expect(onChange).toHaveBeenCalled();
});
});
});
describe('disabled', () => {
it('does not add disabled class by default', () => {
const { getByTestId } = render(<Input />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).not.toHaveClass('disabled');
});
it('does not set disabled attribute by default', () => {
const { getByTestId } = render(<Input />);
const input = getByTestId(inputElementTestid);
expect(input).not.toHaveAttribute('disabled');
});
describe('when false', () => {
it('adds disabled class', () => {
const { getByTestId } = render(<Input disabled={false} />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).not.toHaveClass('disabled');
});
it('sets disabled attribute to true', () => {
const { getByTestId } = render(<Input disabled={false} />);
const input = getByTestId(inputElementTestid);
expect(input).not.toHaveAttribute('disabled');
});
});
describe('when true', () => {
it('adds disabled class', () => {
const { getByTestId } = render(<Input disabled />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).toHaveClass('disabled');
});
it('sets disabled attribute to true', () => {
const { getByTestId } = render(<Input disabled />);
const input = getByTestId(inputElementTestid);
expect(input).toHaveAttribute('disabled');
});
});
});
describe('error', () => {
it('does not add error class by default', () => {
const { getByTestId } = render(<Input />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).not.toHaveClass('error');
});
it('does not set aria-invalid by default', () => {
const { getByTestId } = render(<Input />);
const inputElement = getByTestId(inputElementTestid);
expect(inputElement).toHaveAttribute('aria-invalid', 'false');
});
describe('falsey', () => {
const assertNoError = (getByTestId: GetByTestIdType) => {
const inputRoot = getByTestId(inputRootTestid);
const inputElement = getByTestId(inputElementTestid);
expect(inputRoot).not.toHaveClass('error');
expect(inputElement).toHaveAttribute('aria-invalid', 'false');
};
it('does not add error if error is false', () => {
const { getByTestId } = render(<Input error={false} />);
assertNoError(getByTestId);
});
it('does not add error if error is empty string', () => {
const { getByTestId } = render(<Input error="" />);
assertNoError(getByTestId);
});
});
describe('truthy', () => {
const assertError = (getByTestId: GetByTestIdType) => {
const inputRoot = getByTestId(inputRootTestid);
const inputElement = getByTestId(inputElementTestid);
expect(inputRoot).toHaveClass('error');
expect(inputElement).toHaveAttribute('aria-invalid', 'true');
};
it('does not add error if error is true', () => {
const { getByTestId } = render(<Input error={true} />);
assertError(getByTestId);
});
it('does not add error if error is non empty string', () => {
const { getByTestId } = render(<Input error="hello" />);
assertError(getByTestId);
});
it('does not add error if error is <></>', () => {
const { getByTestId } = render(<Input error={<></>} />);
assertError(getByTestId);
});
});
});
describe('unstyled', () => {
it('does not add unstyled class by default', () => {
const { getByTestId } = render(<Input />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).not.toHaveClass('unstyled');
});
describe('when false', () => {
it('does not add unstyled class', () => {
const { getByTestId } = render(<Input unstyled={false} />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).not.toHaveClass('unstyled');
});
});
describe('when true', () => {
it('adds unstyled class', () => {
const { getByTestId } = render(<Input unstyled />);
const inputRoot = getByTestId(inputRootTestid);
expect(inputRoot).toHaveClass('unstyled');
});
});
});
});
| 5,056
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Input/Input.tsx
|
import { ComponentPropsWithRef, ReactNode, Ref, forwardRef } from 'react';
import clsx from '@proton/utils/clsx';
export interface InputProps extends Omit<ComponentPropsWithRef<'input'>, 'prefix'> {
onValue?: (value: string) => void;
disableChange?: boolean;
disabled?: boolean;
error?: ReactNode | boolean;
unstyled?: boolean;
prefix?: ReactNode;
suffix?: ReactNode;
containerRef?: Ref<HTMLDivElement>;
containerProps?: ComponentPropsWithRef<'div'>;
inputClassName?: string;
prefixClassName?: string;
}
const InputBase = (props: InputProps, ref: Ref<HTMLInputElement>) => {
const {
onValue,
disableChange,
disabled = false,
error,
unstyled,
prefix,
suffix,
containerProps,
containerRef,
inputClassName,
prefixClassName,
className: classNameProp,
...rest
} = props;
return (
<div
className={clsx(
'input flex flex-nowrap flex-align-items-stretch flex-item-fluid relative',
Boolean(error) && 'error',
disabled && 'disabled',
unstyled && 'unstyled',
classNameProp
)}
ref={containerRef}
data-testid="input-root"
{...containerProps}
>
{prefix && (
<div
className={clsx(
'input-adornment ml-2 flex flex-align-items-center flex-item-noshrink flex-nowrap gap-2',
prefixClassName
)}
data-testid="input-prefix"
>
{prefix}
</div>
)}
<div className="flex flex-item-fluid">
<input
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
spellCheck="false"
aria-invalid={!!error}
disabled={disabled}
data-testid="input-input-element"
{...rest}
ref={ref}
onChange={(e) => {
if (disableChange) {
return;
}
onValue?.(e.target.value);
rest.onChange?.(e);
}}
className={clsx('input-element w-full', inputClassName)}
/>
</div>
{suffix && (
<div className="input-adornment mr-2 flex flex-align-items-center flex-item-noshrink flex-nowrap gap-2">
{suffix}
</div>
)}
</div>
);
};
/*
export because of
https://github.com/storybookjs/storybook/issues/9511
https://github.com/styleguidist/react-docgen-typescript/issues/314
https://github.com/styleguidist/react-docgen-typescript/issues/215
*/
export const Input = forwardRef<HTMLInputElement, InputProps>(InputBase);
| 5,057
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Input/index.ts
|
export * from './Input';
| 5,058
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/Kbd.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { Kbd } from './Kbd';
# Kbd
```js
import { Kbd } from '@proton/atoms';
```
The `Kbd` component is used to display keyboard shortcuts and provides the correct aria-label for screen readers.
<Canvas withSource="open">
<Story id="components-kbd--basic" />
</Canvas>
<ArgsTable story={PRIMARY_STORY} />
| 5,059
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/Kbd.scss
|
@import '~@proton/styles/scss/lib';
.kbd {
padding-block: 0;
padding-inline: em(4);
background-color: var(--background-strong);
color: var(--text-norm);
border: 1px solid var(--border-norm);
border-radius: var(--border-radius-sm);
}
| 5,060
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/Kbd.stories.tsx
|
import Kbd from './Kbd';
import mdx from './Kbd.mdx';
export default {
component: Kbd,
title: 'components/Kbd',
parameters: { docs: { page: mdx } },
};
export const Basic = () => <Kbd shortcut="N" />;
| 5,061
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/Kbd.test.tsx
|
import { render } from '@testing-library/react';
import Kbd from './Kbd';
describe('<Kbd />', () => {
it('should render with className kbd and additional className', () => {
const { container } = render(<Kbd shortcut="N" className="should-be-passed" />);
expect(container.firstChild).toHaveClass('kbd');
expect(container.firstChild).toHaveClass('should-be-passed');
});
it('should render element with text content N', () => {
const { container } = render(<Kbd shortcut="N" />);
expect(container.textContent).toBe('N');
});
});
| 5,062
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/Kbd.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
import './Kbd.scss';
export interface KbdProps extends ComponentPropsWithoutRef<'kbd'> {
shortcut: String;
}
const Kbd = ({ shortcut, className, ...rest }: KbdProps) => {
return (
<kbd className={clsx('kbd', className)} aria-label={c('Label').t`Keyboard shortcut: ${shortcut}`} {...rest}>
{shortcut}
</kbd>
);
};
export default Kbd;
| 5,063
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/index.ts
|
export { default as Kbd } from './Kbd';
export * from './Kbd';
| 5,064
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/NotificationDot/NotificationDot.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
# NotificationDot
```js
import { NotificationDot } from '@proton/atoms';
```
The `NotificationDot` is a circle which can be colored. It takes no opinion on its positioning.
<Canvas withSource="open">
<Story id="components-notificationdot--basic" />
</Canvas>
## Colors
`ThemeColor` can be used to color the dot.
<Canvas>
<Story id="components-notificationdot--colors" />
</Canvas>
## Position helper
A `notification-dot--top-right` css class to align the center of the dot to the top right of the container.
<Canvas>
<Story id="components-notificationdot--position-helper" />
</Canvas>
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,065
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/NotificationDot/NotificationDot.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
$size-dot: rem(12) !default;
.notification-dot {
inline-size: $size-dot;
block-size: $size-dot;
&--top-right {
margin-inline-end: -#{math.div($size-dot, 2)};
margin-block-start: -#{math.div($size-dot, 2)};
}
}
| 5,066
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/NotificationDot/NotificationDot.stories.tsx
|
import { ThemeColor } from '@proton/colors';
import { Card } from '..';
import NotificationDot from './NotificationDot';
import mdx from './NotificationDot.mdx';
export default {
component: NotificationDot,
title: 'components/NotificationDot',
parameters: { docs: { page: mdx } },
};
export const Basic = () => <NotificationDot />;
export const Colors = () => (
<div className="flex">
{Object.values(ThemeColor).map((color) => (
<NotificationDot className="mr-4" color={color} />
))}
</div>
);
export const PositionHelper = () => (
<>
<Card className="relative mb-4">
With helper
<NotificationDot className="absolute top right notification-dot--top-right" />
</Card>
<Card className="relative">
Without helper
<NotificationDot className="absolute top right" />
</Card>
</>
);
| 5,067
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/NotificationDot/NotificationDot.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import { ThemeColor, getVariableFromThemeColor } from '@proton/colors';
import clsx from '@proton/utils/clsx';
import './NotificationDot.scss';
export interface NotificationDotProps extends ComponentPropsWithoutRef<'span'> {
/**
* Controls the color of the dot.
*/
color?: ThemeColor;
/**
* Adds sr-only text for vocalization
*/
alt?: String;
}
const NotificationDot = ({ color = ThemeColor.Norm, className, alt, ...rest }: NotificationDotProps) => {
return (
<span
className={clsx(className, 'notification-dot rounded-50')}
style={{ backgroundColor: `var(${getVariableFromThemeColor(color)})` }}
{...rest}
>
{alt && <span className="sr-only">{alt}</span>}
</span>
);
};
export default NotificationDot;
| 5,068
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/NotificationDot/index.ts
|
export { default as NotificationDot } from './NotificationDot';
export * from './NotificationDot';
| 5,069
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Scroll/Scroll.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
# Scroll
```js
import { Scroll } from '@proton/atoms';
```
The `Scroll` component is a utility component which makes an area scrollable should its content overflow the maximum dimensions of its parent. It also adds some styling in the form of shadows to indicate to the user that an area is scrollable/has off-screen parts.
<Canvas withSource="open">
<Story id="components-scroll--basic" />
</Canvas>
## Horizontal
Use the `horizontal` prop to switch to horizontal scrolling.
<Canvas>
<Story id="components-scroll--horizontal" />
</Canvas>
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,070
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Scroll/Scroll.scss
|
@import '~@proton/styles/scss/lib';
$scrollshadow-size: rem(5) !default;
.scroll {
&-outer {
&-horizontal {
position: relative;
.scroll-child {
/*
* the reason this is using inline-block is because
* we need direct access to a child element of the scroll
* container in order to know when the edges of these two
* elements overlap (that way we can tell that the scroll
* is either at the very start, at the very end or somewhere
* in the middle)
*
* however, a block element always takes the width of their
* parent, whereas an inline-block element will take the width
* of their child, which would be the overflowing scrollable
* content in this case
*
* "width: 100%" in order to maintain a block element behaviour
* even though using "display: inline-block"
*
*/
display: inline-block;
min-inline-size: 100%;
}
.scroll-inner {
overflow-x: auto;
}
.scroll-start-shadow,
.scroll-end-shadow {
z-index: 1;
position: absolute;
inset-block-start: 0;
inline-size: $scrollshadow-size;
block-size: 100%;
opacity: 0;
transition: 250ms easing(ease-out-cubic);
}
.scroll-start-shadow {
inset-inline-start: 0;
background: linear-gradient(90deg, rgb(0 0 0 / var(--shadow-norm-opacity)), transparent);
}
.scroll-end-shadow {
inset-inline-end: 0;
background: linear-gradient(270deg, rgb(0 0 0 / var(--shadow-norm-opacity)), transparent);
}
.scroll-start-shadow-visible,
.scroll-end-shadow-visible {
opacity: 1;
}
}
&-vertical {
block-size: 100%;
position: relative;
.scroll-inner {
block-size: 100%;
overflow-y: auto;
}
.scroll-start-shadow,
.scroll-end-shadow {
z-index: 1;
position: absolute;
inset-inline-start: 0;
inset-inline-end: 0;
block-size: $scrollshadow-size;
transition: 250ms easing(ease-out-cubic);
opacity: 0;
}
.scroll-start-shadow {
inset-block-start: 0;
background: linear-gradient(180deg, rgb(0 0 0 / var(--shadow-norm-opacity)), transparent);
}
.scroll-end-shadow {
inset-block-end: 0;
background: linear-gradient(0deg, rgb(0 0 0 / var(--shadow-norm-opacity)), transparent);
}
.scroll-start-shadow-visible,
.scroll-end-shadow-visible {
opacity: 1;
}
}
}
}
| 5,071
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Scroll/Scroll.stories.tsx
|
import Scroll from './Scroll';
import mdx from './Scroll.mdx';
export default {
component: Scroll,
title: 'components/Scroll',
parameters: { docs: { page: mdx } },
};
export const Basic = () => {
return (
<Scroll className="border" style={{ height: 160 }}>
<div className="px-4 text-justify">
<p style={{ maxWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
<p style={{ maxWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
<p style={{ maxWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
<p style={{ maxWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
</div>
</Scroll>
);
};
export const Horizontal = () => {
return (
<Scroll horizontal className="border">
<div className="p-4 flex flex-nowrap">
<p className="pr-7" style={{ minWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
<p className="pr-7" style={{ minWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
<p className="pr-7" style={{ minWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
<p style={{ minWidth: 400 }}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium unde, blanditiis rem accusamus
obcaecati enim amet, voluptatibus nemo facilis illum aut itaque in? Deleniti iure amet qui vero,
blanditiis quos?
</p>
</div>
</Scroll>
);
};
| 5,072
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Scroll/Scroll.tsx
|
import { ComponentPropsWithoutRef, Ref, useEffect, useRef, useState } from 'react';
import { useCombinedRefs } from '@proton/hooks';
import clsx from '@proton/utils/clsx';
import './Scroll.scss';
const TOLERANCE = 4;
export interface ScrollProps extends ComponentPropsWithoutRef<'div'> {
horizontal?: boolean;
customContainerRef?: Ref<HTMLElement>;
}
const Scroll = ({ children, horizontal, className, customContainerRef, ...rest }: ScrollProps) => {
const scrollContainerRef = useRef<HTMLDivElement>(null);
const scrollChildRef = useRef<HTMLDivElement>(null);
const [showStartShadow, setShowStartShadow] = useState(false);
const [showEndShadow, setShowEndShadow] = useState(false);
const containersRefs = customContainerRef
? [scrollContainerRef, customContainerRef as Ref<HTMLDivElement>]
: [scrollContainerRef];
const containerRefs = useCombinedRefs(...containersRefs);
const setShadows = (container: HTMLDivElement, child: HTMLDivElement) => {
if (!container || !child) {
return;
}
const containerRect = container.getBoundingClientRect();
const childRect = child.getBoundingClientRect();
const isOnStartEdge = horizontal
? containerRect.left - childRect.left < TOLERANCE
: containerRect.top - childRect.top < TOLERANCE;
const isOnEndEdge = horizontal
? childRect.right - containerRect.right < TOLERANCE
: childRect.bottom - containerRect.bottom < TOLERANCE;
/*
* We're passing a callback here so that we can have access to the previous
* respective show shadow value. If we reference "showStartShadow" or
* "showEndShadow" directly here, we run into a stale closure issue because
* "setShadows" is passed to the resize observer in the useEffect below.
*
* I was cautious at first because I was afraid that calling useState's set
* functions every time like this just to receive access to the real previous
* state value might have some negative impact on rendering performance. However,
* useState seems to internally handle reference equality comparison optimizations.
* These setState's do not trigger re-renders if they return the exact same value
* as what was already set.
*
* This is mostly an effort to be able to re-use only one resize observer.
* An alternative would've been to clean up and re-create a resize observer in the
* useEffect below, passing setShadows (wrapped in useCallback that is) into the
* dependency array, but I thought this would be the cleaner solution, albeit a bit
* weird imo.
*/
setShowStartShadow((previousShowStartShadow) =>
isOnStartEdge === previousShowStartShadow ? !previousShowStartShadow : previousShowStartShadow
);
setShowEndShadow((previousShowEndShadow) =>
isOnEndEdge === previousShowEndShadow ? !previousShowEndShadow : previousShowEndShadow
);
};
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
setShadows(scrollContainerRef.current!, scrollChildRef.current!);
});
resizeObserver.observe(scrollChildRef.current!);
resizeObserver.observe(scrollContainerRef.current!);
return () => {
resizeObserver.disconnect();
};
}, []);
const handleScroll = ({ currentTarget: scrollContainer }: React.UIEvent<HTMLDivElement, UIEvent>) => {
const { current: scrollChild } = scrollChildRef;
/*
* safeguard if scrollChild hasn't mounted inside the dom yet
* impossible case I think, since they would render together
* and a scroll event could only trigger after they are physically
* mounted, ts doesn't know this though
*/
if (!scrollChild) {
return;
}
setShadows(scrollContainer, scrollChild);
};
return (
<div {...rest} className={clsx(horizontal ? 'scroll-outer-horizontal' : 'scroll-outer-vertical', className)}>
<div
className={clsx(
'scroll-start-shadow no-pointer-events',
showStartShadow && 'scroll-start-shadow-visible'
)}
aria-hidden="true"
/>
<div
className={clsx('scroll-end-shadow no-pointer-events', showEndShadow && 'scroll-end-shadow-visible')}
aria-hidden="true"
/>
<div className="scroll-inner" ref={containerRefs} onScroll={handleScroll}>
<div className="scroll-child" ref={scrollChildRef}>
{children}
</div>
</div>
</div>
);
};
export default Scroll;
| 5,073
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Scroll/ScrollShadows.tsx
|
import { ReactNode } from 'react';
interface Props {
children: ReactNode;
}
const ScrollShadows = ({ children }: Props) => {
return (
<div className="relative">
<div className="scrollshadow-sticky scrollshadow-sticky--top" aria-hidden="true" />
<div className="scrollshadow-static scrollshadow-static--top" aria-hidden="true" />
{children}
<div className="scrollshadow-sticky scrollshadow-sticky--bottom" aria-hidden="true" />
<div className="scrollshadow-static scrollshadow-static--bottom" aria-hidden="true" />
</div>
);
};
export default ScrollShadows;
| 5,074
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Scroll/index.ts
|
export { default as Scroll } from './Scroll';
export { default as ScrollShadows } from './ScrollShadows';
| 5,075
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/Slider.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
# Slider
```js
import { Slider } from '@proton/atoms';
```
<Canvas withSource="open">
<Story id="components-slider--basic" />
</Canvas>
## Marks
You can use the slider with "marks" for the min & max values.
<Canvas>
<Story id="components-slider--marks" />
</Canvas>
## Color
All Theme colors are available to color the Slider with.
<Canvas>
<Story id="components-slider--color" />
</Canvas>
## Size
The Slider comes in two sizes "small" & "medium", where "medium" is the default when omitted.
<Canvas>
<Story id="components-slider--size" />
</Canvas>
## Steps
The Slider is configurable to only allow values that round to a nearest "step" via the `step` property. If set, the thumb of the Slider won't move until the pointer that is dragging it is closer to a different step-point than the one where it currently is. In this configuration, the slider displays the real internal value of the slider as opposed to defaulting to `Math.round`, formatted based on the number of decimals found in the specified `step` value.
<Canvas>
<Story id="components-slider--step" />
</Canvas>
## Min & Max
The `min` & `max` properties allow specifying in which numeric interval the Slider should operate.
<Canvas>
<Story id="components-slider--min-max" />
</Canvas>
Although it doesn't fit the semantics of the concept of `min` & `max`, it is technically possible to have `max` be smaller than `min` if one wishes to invert the directionality of the `Slider`.
<Canvas>
<Story id="components-slider--min-max-inverted" />
</Canvas>
## Custom value display format
The `getDisplayedValue` prop allows you to apply custom formatting to the real internal value of the slider. In the case where no step is specified, this value is a decimal as opposed to an integer value, however by default `Math.round` is used to format the real internal value for display.
<Canvas>
<Story id="components-slider--custom-value-display-format" />
</Canvas>
## Props
The Slider interface supports all additional html attributes of the `<input />` element via rest spreading.
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,076
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/Slider.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
$height-track: 16 !default;
$height-track-small: 8 !default;
$size-track-thumb: 36 !default;
$size-track-thumb-small: 28 !default;
.slider {
/**
* Prevent scroll while interacting with slider on mobile.
* Support on iOS safari for this CSS property starts on version 13.
*
* TODO: may have to add support for iOS safari < 13 for this behaviour.
*/
touch-action: none;
block-size: rem($height-track);
/**
* Inline-block and 100% width prevents the bottom margin from collapsing in parent.
*/
inline-size: 100%;
display: inline-block;
&-rail,
&-track,
&-thumb {
position: absolute;
}
&-rail {
background: var(--background-strong);
inline-size: 100%;
block-size: 100%;
/*
* The track is nested inside of the rail, so to make the
* border-radius apply to both the rail & the track we clip
* it with overflow: hidden.
*/
border-radius: rem(math.div($height-track, 2));
overflow: hidden;
}
&-track {
background: var(--track-background);
block-size: 100%;
}
&-thumb {
block-size: rem($size-track-thumb);
inline-size: rem($size-track-thumb);
transition: none;
user-select: none;
display: flex;
align-items: center;
justify-content: center;
transform: translateX(-50%) translateY(-10px);
[dir='rtl'] & {
transform: translateX(50%) translateY(-10px);
}
&-input {
inline-size: 100%;
block-size: 100%;
}
}
&-small {
block-size: rem($height-track-small);
.slider-thumb {
block-size: rem($size-track-thumb-small);
inline-size: rem($size-track-thumb-small);
padding: 0;
}
.slider-rail {
border-radius: rem(math.div($height-track-small, 2));
}
}
&-marks {
/**
* Combined height of slider mark (12) + slider mark label line height (20).
* If we don't provide a bottom margin anything added underneath the Slider
* collapses into the marks / labels.
*/
margin-block-end: rem(32);
.slider-rail {
/*
* No border-radius when marks are applied so that the marks nicely align
* with the corners of the non-rounded rail.
*/
border-radius: 0;
}
}
}
| 5,077
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/Slider.stories.tsx
|
import { useState } from 'react';
import Slider from './Slider';
import mdx from './Slider.mdx';
export default {
component: Slider,
title: 'components/Slider',
parameters: {
docs: {
page: mdx,
},
},
};
export const Basic = () => {
const [value, setValue] = useState(25);
return (
<div className="p-7">
<Slider value={value} onChange={setValue} />
</div>
);
};
export const Marks = () => {
const [value, setValue] = useState(25);
return (
<div className="p-7">
<Slider marks value={value} onChange={setValue} />
</div>
);
};
export const Color = () => {
const [value, setValue] = useState(25);
return (
<div className="p-7">
<div>
<Slider color="success" value={value} onInput={setValue} />
</div>
<div className="mt-8">
<Slider color="danger" value={value} onInput={setValue} />
</div>
<div className="mt-8">
<Slider color="info" value={value} onInput={setValue} />
</div>
<div className="mt-8">
<Slider color="norm" value={value} onInput={setValue} />
</div>
<div className="mt-8">
<Slider color="warning" value={value} onInput={setValue} />
</div>
<div className="mt-8">
<Slider color="weak" value={value} onInput={setValue} />
</div>
</div>
);
};
export const Size = () => {
const [value, setValue] = useState(25);
return (
<div className="p-7">
<div>
<Slider size="small" value={value} onInput={setValue} />
</div>
<div className="mt-8">
<Slider value={value} onInput={setValue} />
</div>
</div>
);
};
export const Step = () => {
const [value, setValue] = useState(0.2);
return (
<div className="p-7">
<Slider step={0.01} min={0} max={1} value={value} onChange={setValue} />
</div>
);
};
export const MinMax = () => {
const [value, setValue] = useState(2000);
return (
<div className="p-7">
<Slider min={1000} max={10000} value={value} onChange={setValue} />
</div>
);
};
export const MinMaxInverted = () => {
const [value, setValue] = useState(-10);
return (
<div className="p-7">
<Slider min={20} max={-20} value={value} onChange={setValue} />
</div>
);
};
export const CustomValueDisplayFormat = () => {
const [value, setValue] = useState(20);
return (
<div className="p-7">
<Slider value={value} onChange={setValue} getDisplayedValue={(v) => `${v.toFixed(2)}px`} />
</div>
);
};
| 5,078
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/Slider.test.tsx
|
import { fireEvent, render } from '@testing-library/react';
import Slider from './Slider';
describe('<Slider />', () => {
it('renders min and max mark labels', () => {
const { getByTestId } = render(<Slider marks min={10} max={100} />);
expect(getByTestId('slider-mark-min').textContent).toBe('10');
expect(getByTestId('slider-mark-max').textContent).toBe('100');
});
/**
* Again, rather a safeguard than a recommended use-case
*/
it("inverts directionality (and doesn't break) if min is larger than max", () => {
const { getByTestId } = render(<Slider marks min={100} max={10} />);
expect(getByTestId('slider-mark-min').textContent).toBe('100');
expect(getByTestId('slider-mark-max').textContent).toBe('10');
});
it('restricts a value to stay within min & max bounds', () => {
const min = 10;
const max = 100;
const { getByTestId } = render(<Slider value={50} min={min} max={max} />);
const input = getByTestId('slider-input');
fireEvent.input(input, { target: { value: '0' } });
expect(getByTestId('slider-input').getAttribute('aria-valuenow')).toEqual(String(min));
fireEvent.input(input, { target: { value: '110' } });
expect(getByTestId('slider-input').getAttribute('aria-valuenow')).toEqual(String(max));
});
});
| 5,079
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/Slider.tsx
|
import {
ChangeEvent,
ComponentPropsWithoutRef,
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
useRef,
useState,
} from 'react';
import { ThemeColorUnion } from '@proton/colors';
import Icon from '@proton/components/components/icon/Icon';
import Tooltip from '@proton/components/components/tooltip/Tooltip';
import { useRightToLeft } from '@proton/components/containers/rightToLeft';
import useSynchronizingState from '@proton/hooks/useSynchronizingState';
import clamp from '@proton/utils/clamp';
import clsx from '@proton/utils/clsx';
import percentage from '@proton/utils/percentage';
import ButtonLike from '../Button/ButtonLike';
import SliderMark from './SliderMark';
import './Slider.scss';
interface SliderProps extends Omit<ComponentPropsWithoutRef<'input'>, 'value' | 'size' | 'onChange' | 'onInput'> {
/**
* The current value of the Slider. Allows for external control of the Slider.
*/
value?: number;
/**
* The minimum allowed value that can be selected using the Slider
*/
min?: number;
/**
* The maximum allowed value that can be selected using the Slider
*/
max?: number;
/**
* Minimum numeric interval / unit in which the Slider should operate
*/
step?: number;
/**
* Size of the Slider.
*/
size?: 'small' | 'medium';
/**
* Adds marks to the beginning and end of the Slider's rail indicating
* min and max values visually.
*/
marks?: boolean;
/**
* Controls the color of the track (filled out portion of the Slider rail)
* And maybe the color of other things in the future, hehe. #future-proof-docs
*/
color?: ThemeColorUnion;
/**
* Allows for custom formatting of the value that is displayed in the
* Slider's label. By default, unless `step` is specified the number shown
* is formatted using Math.round, however internally the actual number can
* be decimal.
*/
getDisplayedValue?: (value: number) => number | string;
/**
* Emits the number selected via the Slider on change.
* Change in this context is defined as the number selected at the
* moment of the thumb drag ending. (same as `<input type="range" />`)
*/
onChange?: (value: number) => void;
/**
* Same as the onChange prop, however on input instead, defined in
* this context as any ongoing input to the Slider component even if
* not considered "ended".
*/
onInput?: (value: number) => void;
}
const Slider = ({
value,
min = 0,
max = 100,
marks = false,
size = 'medium',
color = 'success',
step,
getDisplayedValue,
onChange,
onInput,
...rest
}: SliderProps) => {
const [rtl] = useRightToLeft();
const [tooltipOpen, setTooltipOpen] = useState(false);
const [internalValue, setInternalValue] = useSynchronizingState(value || min);
const [dragging, setDragging] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const thumbInputRef = useRef<HTMLInputElement>(null);
/**
* The "touches" property of the TouchEvent emitted on "touchend" is an empty array
* (at least in the case of dealing with a single touch). Since we're using touches
* to computed the value from the clientX of any given touch, we run into a problem
* where we don't have a value to emit a commit (change) with on touchend.
*
* We also don't have access to the current "internalValue" state since our touchend
* handler dissapears inside document.addEventListener with a stale closure over
* internalValue.
*
* To solve this we manually track the most recent touch event in a mutative,
* pointer-referenced manner via this react ref and consume it on touchend.
*
*/
const latestTouchRef = useRef<TouchEvent | null>(null);
/**
* Doesn't fit semantically to have max smaller than min, however this allows
* it to be technically possible to do. Slider would then start with the higher
* number and end with the lower number if considered from left-to-right e.g.:
*
* |-----------|
* 10 -10
*
* Without this the component is not functional should min be larger than max.
* Also potentially useful for dynamic min max props which might accidentally be inverted.
*/
const clampInsideInterval = min < max ? (n: number) => clamp(n, min, max) : (n: number) => clamp(n, max, min);
const clampedInternalValue = clampInsideInterval(internalValue);
const interval = max - min;
const getValueFromXCoordinate = (x: number) => {
const rootRect = rootRef.current?.getBoundingClientRect();
if (!rootRect) {
return NaN;
}
const intervalInPx = rootRect.right - rootRect.left;
const distanceToStart = rtl ? rootRect.right - x : x - rootRect.left;
const pxToValueRatio = intervalInPx / interval;
const valueFromMouseEvent = distanceToStart / pxToValueRatio;
return min + (step ? Math.round(valueFromMouseEvent / step) * step : valueFromMouseEvent);
};
const handleInput = (v: number) => {
const clamped = clampInsideInterval(v);
if (!isNaN(Number(clamped))) {
setInternalValue(clamped);
onInput?.(clamped);
}
};
const handleCommit = (v: number) => {
const clamped = clampInsideInterval(v);
if (!isNaN(Number(clamped))) {
setInternalValue(clamped);
onChange?.(clamped);
}
};
const handleXCoordinateInput = (x: number) => {
handleInput(getValueFromXCoordinate(x));
};
const handleXCoordinateCommit = (x: number) => {
handleCommit(getValueFromXCoordinate(x));
};
const handleStart = (e: ReactMouseEvent | ReactTouchEvent, x: number) => {
/*
* Prevents text from being selected while user
* is mousemoving after a mousedown event.
*
* Implementation taken from react material-ui.
*/
e.preventDefault();
thumbInputRef.current?.focus();
handleXCoordinateInput(x);
setDragging(true);
};
const handleMouseMove = (e: MouseEvent) => {
handleXCoordinateInput(e.clientX);
};
const handleMouseUp = (e: MouseEvent) => {
handleXCoordinateCommit(e.clientX);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
setDragging(false);
};
const handleMouseDown = (e: ReactMouseEvent) => {
const { nativeEvent } = e;
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
handleStart(e, nativeEvent.clientX);
};
const handleTouchMove = (e: TouchEvent) => {
latestTouchRef.current = e;
handleXCoordinateInput(e.touches[0].clientX);
};
const handleTouchEnd = () => {
const latestClientXTouch = latestTouchRef.current?.touches[0].clientX;
/**
* Since both handleTouchStart & hadleTouchMove set latestTouchRef.current
* to the most recent touch event, it shouldn't ever be possible for this
* to actually be undefined. Still I'm not 100% sure a touchend event can't
* fire without a prior touchstart, so just in case this is a little physical
* safeguard instead of a typecast.
*/
if (latestClientXTouch) {
handleXCoordinateCommit(latestClientXTouch);
}
document.removeEventListener('touchmove', handleTouchMove);
document.removeEventListener('touchend', handleTouchEnd);
thumbInputRef.current?.blur();
setDragging(false);
};
const handleTouchStart = (e: ReactTouchEvent) => {
latestTouchRef.current = e.nativeEvent;
handleStart(e, e.nativeEvent.touches[0].clientX);
document.addEventListener('touchmove', handleTouchMove);
document.addEventListener('touchend', handleTouchEnd);
};
/* as in handle the onInput event of the <input /> element */
const handleInputInput = (e: ChangeEvent<HTMLInputElement>) => {
handleInput(Number(e.target.value));
};
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
handleCommit(Number(e.target.value));
};
const renderDisplayedValue = () => {
if (getDisplayedValue) {
return getDisplayedValue(clampedInternalValue);
}
/**
* If "step" is specified, render the displayed value with
* padded zeros based on the decimals of the step value.
* There are no decimals if "step" is an integer to begin with.
*/
if (step && step !== Math.floor(step)) {
const [, decimals] = String(step).split('.');
return clampedInternalValue.toFixed(decimals.length);
}
return Math.round(clampedInternalValue);
};
const valueInPercent = percentage(interval, clampedInternalValue - min);
return (
<div
dir={rtl ? 'rtl' : 'ltr'}
ref={rootRef}
className={clsx('slider', marks && 'slider-marks', size === 'small' && 'slider-small', 'relative')}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
>
<div className="slider-rail">
<div
className="slider-track"
style={{
width: `${valueInPercent}%`,
'--track-background': `var(--signal-${color}, var(--interaction-${color}))`,
}}
/>
</div>
{marks && (
<>
<SliderMark className="slider-mark-min" aria-hidden="true" data-testid="slider-mark-min">
{min}
</SliderMark>
<SliderMark className="slider-mark-max" aria-hidden="true" data-testid="slider-mark-max">
{max}
</SliderMark>
</>
)}
<Tooltip
title={renderDisplayedValue()}
isOpen={tooltipOpen || dragging}
closeDelay={0}
openDelay={0}
updateAnimationFrame={
true /* Needed to ensure it's next to the button. Otherwise only updated on title change. */
}
>
<ButtonLike
icon
color="weak"
shape="outline"
as="span"
style={{ '--left-custom': `${valueInPercent}%` }}
data-testid="slider-thumb"
className={clsx(
'slider-thumb left-custom shadow-norm relative',
dragging && 'slider-thumb-dragging'
)}
>
<input
onFocus={() => {
setTooltipOpen(true);
}}
onBlur={() => {
setTooltipOpen(false);
}}
type="range"
ref={thumbInputRef}
value={value}
min={min}
max={max}
step={step}
aria-valuenow={clampedInternalValue}
aria-orientation="horizontal"
data-testid="slider-input"
className="sr-only slider-thumb-input"
onChange={handleInputChange}
onInput={handleInputInput}
{...rest}
/>
<Icon name="arrows-left-right" />
</ButtonLike>
</Tooltip>
</div>
);
};
export default Slider;
| 5,080
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/SliderMark.scss
|
@import '~@proton/styles/scss/lib';
.slider-mark {
inline-size: 1px;
block-size: rem(12);
background: var(--text-norm);
position: absolute;
inset-block-start: 100%;
&-min {
inset-inline-start: 0;
}
&-max {
inset-inline-end: 0;
}
}
.slider-mark-label {
inset-block-start: 100%;
position: absolute;
transform: translateX(calc(-50% + 0.5px));
[dir='rtl'] & {
transform: translateX(calc(50% - 0.5px));
}
}
| 5,081
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/SliderMark.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import clsx from '@proton/utils/clsx';
import './SliderMark.scss';
const SliderMark = ({ children, className, ...rest }: ComponentPropsWithoutRef<'span'>) => {
return (
<span className={clsx('slider-mark', className)} {...rest}>
<span className="slider-mark-label">{children}</span>
</span>
);
};
export default SliderMark;
| 5,082
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/index.ts
|
export { default as Slider } from './Slider';
| 5,083
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Step.tsx
|
import { useContext } from 'react';
import clsx from '@proton/utils/clsx';
import StepListItem, { StepListItemProps } from './StepListItem';
import StepperContext from './StepperContext';
export interface StepProps extends Omit<StepListItemProps, 'firstItem' | 'active' | 'complete' | 'children'> {
children?: string;
}
const Step = ({
index,
children,
className,
...rest
}: StepProps & {
/**
* `index` of the step. Added automatically by Stepper.
*/
index?: number;
}) => {
const { activeStep } = useContext(StepperContext);
const firstItem = index === 0;
const active = index === activeStep;
const complete = index !== undefined && index < activeStep;
return (
<StepListItem
firstItem={firstItem}
active={active}
complete={complete}
className={clsx('stepper-label flex-item-fluid', className)}
{...rest}
>
<span
className={clsx(
'mt-2 text-sm text-center text-ellipsis-two-lines',
active && 'text-semibold',
!active && 'opacity-70'
)}
title={children}
{...rest}
>
{children}
</span>
</StepListItem>
);
};
export default Step;
| 5,084
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/StepIndicator.tsx
|
import { useContext } from 'react';
import clsx from '@proton/utils/clsx';
import StepListItem, { StepListItemProps } from './StepListItem';
import StepperContext from './StepperContext';
export interface StepIndicatorProps extends Omit<StepListItemProps, 'firstItem' | 'active' | 'complete'> {}
const StepIndicator = ({
index,
className,
...rest
}: StepIndicatorProps & {
/**
* `index` of the step. Added automatically by Stepper.
*/
index?: number;
}) => {
const { activeStep } = useContext(StepperContext);
const firstItem = index === 0;
const active = index === activeStep;
const complete = index !== undefined && index < activeStep;
return (
<StepListItem
firstItem={firstItem}
active={active}
complete={complete}
className={clsx('relative flex-item-fluid flex flex-column flex-align-items-center flex-nowrap', className)}
{...rest}
>
{!firstItem && <div className="stepper-item-connector" />}
<span className="stepper-item-dot" />
</StepListItem>
);
};
export default StepIndicator;
| 5,085
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/StepListItem.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import clsx from '@proton/utils/clsx';
export interface StepListItemProps extends ComponentPropsWithoutRef<'li'> {
firstItem: boolean;
active: boolean;
complete: boolean;
}
const StepListItem = ({ firstItem, active, complete, children, className, ...rest }: StepListItemProps) => {
return (
<li
{...rest}
className={clsx(
'stepper-item',
active && 'stepper-item--active',
complete && 'stepper-item--completed',
className
)}
aria-current={active ? 'step' : false}
>
{children}
</li>
);
};
export default StepListItem;
| 5,086
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Stepper.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { Stepper } from './Stepper';
# Stepper
```js
import { Stepper } from '@proton/atoms';
```
The `Stepper` displays progress through sequential steps. It is controlled by passing the current step index as the `activeStep` prop.
<Canvas withSource="open">
<Story id="components-stepper--basic" />
</Canvas>
## Position
The length of the connectors is limited to `120px`, meaning the `Step`'s might not fill the width of the `Stepper` container. You can use the `position` prop to set the position of the steps within the stepper.
<Canvas>
<Story id="components-stepper--centered" />
</Canvas>
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,087
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Stepper.scss
|
@import '~@proton/styles/scss/lib';
.stepper {
$dot-size: em(12);
$weak-opacity: 0.7;
$connector-height: em(2);
$connector-gap: em(2);
$connector-max-width: em(120);
inline-size: 100%;
&-item {
max-inline-size: calc($connector-max-width + $dot-size - $connector-gap);
&-dot {
inline-size: $dot-size;
block-size: $dot-size;
border-radius: 50%;
}
&-connector {
block-size: $connector-height;
position: absolute;
inset-block-start: calc(($dot-size - $connector-height) / 2);
inset-inline: calc(-50% + $connector-gap) calc(50% + $connector-gap + $dot-size / 2);
}
/**
* dot and connector default color
*/
&-dot,
&-connector {
background-color: var(--interaction-norm);
opacity: $weak-opacity;
}
/**
* dot and connector active and completed
*/
&--active &-dot,
&--completed &-dot,
&--active &-connector,
&--completed &-connector {
opacity: 1;
}
}
@include media('<=xsmall') {
$connector-max-width: em(40); // smaller for mobile
&-item {
max-inline-size: calc($connector-max-width + $dot-size - $connector-gap);
}
&-label {
visibility: hidden;
&.stepper-item--active {
visibility: visible;
flex: 2 1 0px;
min-block-size: 3em; // for signup, I need to have a predictible height (and it could avoid jumps btw)
min-inline-size: 50%; // YOLO, enough space for text
}
}
}
}
| 5,088
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Stepper.stories.tsx
|
import { useState } from 'react';
import { RadioGroup } from '@proton/components/components';
import { Button } from '../Button';
import Step from './Step';
import Stepper, { StepperProps } from './Stepper';
import mdx from './Stepper.mdx';
export default {
component: Stepper,
subcomponents: { Step },
title: 'components/Stepper',
parameters: { docs: { page: mdx } },
};
export const Basic = () => {
const [activeStep, setActiveStep] = useState(0);
const steps = ['Item 1', 'Item 2 with super long label. I should wrap.', 'Item 3', 'Item 4'];
return (
<>
<Stepper position="center" activeStep={activeStep}>
{steps.map((step) => (
<Step key={step}>{step}</Step>
))}
</Stepper>
<div className="mt-11 flex flex-justify-end">
<Button
className="mr-2"
color="norm"
disabled={activeStep === 0}
onClick={() => setActiveStep((step) => step - 1)}
>
Previous
</Button>
<Button
color="norm"
disabled={activeStep === steps.length - 1}
onClick={() => setActiveStep((step) => step + 1)}
>
Next
</Button>
</div>
</>
);
};
const positionVariants: Required<StepperProps>['position'][] = ['start', 'center', 'end'];
export const Centered = () => {
const [activeStep, setActiveStep] = useState(0);
const [position, setPosition] = useState<Required<StepperProps>['position']>('start');
const steps = ['Item 1', 'Item 2.', 'Item 3', 'Item 4'];
return (
<>
<div className="mb-8">
<strong className="block mb-4">Position</strong>
<RadioGroup
name="selected-variant"
onChange={setPosition}
value={position}
options={positionVariants.map((variant) => ({ value: variant, label: variant }))}
/>
</div>
<Stepper position={position} activeStep={activeStep}>
{steps.map((step) => (
<Step key={step}>{step}</Step>
))}
</Stepper>
<div className="mt-11 flex flex-justify-end">
<Button
className="mr-2"
color="norm"
disabled={activeStep === 0}
onClick={() => setActiveStep((step) => step - 1)}
>
Previous
</Button>
<Button
color="norm"
disabled={activeStep === steps.length - 1}
onClick={() => setActiveStep((step) => step + 1)}
>
Next
</Button>
</div>
</>
);
};
| 5,089
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Stepper.test.tsx
|
import { render } from '@testing-library/react';
import Step from './Step';
import Stepper from './Stepper';
describe('<Stepper />', () => {
it('renders a label for each item', () => {
const { container } = render(
<Stepper activeStep={0}>
<Step>Item 1</Step>
<Step>Item 2</Step>
</Stepper>
);
const labelSteps = container.querySelectorAll('.stepper-labels li');
const labelSelector = 'span';
expect(labelSteps[0].querySelector(labelSelector)?.textContent).toBe('Item 1');
expect(labelSteps[1].querySelector(labelSelector)?.textContent).toBe('Item 2');
});
it('renders a dot for each item', () => {
const { container } = render(
<Stepper activeStep={0}>
<Step>Item 1</Step>
<Step>Item 2</Step>
</Stepper>
);
const indicatorSteps = container.querySelectorAll('.stepper-indicators li');
const dotSelector = '.stepper-item-dot';
expect(indicatorSteps[0].querySelector(dotSelector)).not.toBeNull();
expect(indicatorSteps[1].querySelector(dotSelector)).not.toBeNull();
});
it('renders connector if step is not the first step', () => {
const { container } = render(
<Stepper activeStep={0}>
<Step>Item 1</Step>
<Step>Item 2</Step>
</Stepper>
);
const indicatorSteps = container.querySelectorAll('.stepper-indicators li');
const dotSelector = '.stepper-item-connector';
expect(indicatorSteps[0].querySelector(dotSelector)).toBeNull();
expect(indicatorSteps[1].querySelector(dotSelector)).not.toBeNull();
});
it('adds active class to current step', () => {
const { container } = render(
<Stepper activeStep={0}>
<Step>Item 1</Step>
<Step>Item 2</Step>
</Stepper>
);
const indicatorSteps = container.querySelectorAll('.stepper-indicators li');
const labelSteps = container.querySelectorAll('.stepper-labels li');
expect(indicatorSteps[0]).toHaveClass('stepper-item--active');
expect(labelSteps[0]).toHaveClass('stepper-item--active');
});
it('adds completed class to previous step', () => {
const { container } = render(
<Stepper activeStep={1}>
<Step>Item 1</Step>
<Step>Item 2</Step>
</Stepper>
);
const indicatorSteps = container.querySelectorAll('.stepper-indicators li');
const labelSteps = container.querySelectorAll('.stepper-labels li');
expect(indicatorSteps[0]).toHaveClass('stepper-item--completed');
expect(labelSteps[0]).toHaveClass('stepper-item--completed');
});
});
| 5,090
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Stepper.tsx
|
import { Children, ComponentPropsWithoutRef, ReactElement, cloneElement, isValidElement, useMemo } from 'react';
import clsx from '@proton/utils/clsx';
import Step from './Step';
import StepIndicator from './StepIndicator';
import StepperContext from './StepperContext';
import './Stepper.scss';
export interface StepperProps extends ComponentPropsWithoutRef<'div'> {
/**
* Index of the currently active step.
*/
activeStep: number;
/**
* Sets the position of the steps. Defaults to `center`.
*/
position?: 'start' | 'center' | 'end';
}
const Stepper = ({ activeStep, position = 'center', className, children, ...rest }: StepperProps) => {
const childrenArray = Children.toArray(children).filter((child) => isValidElement(child) && child.type === Step);
const stepIndicators = childrenArray.map((step, index) => {
return <StepIndicator index={index} key={(step as ReactElement).key} />;
});
const steps = childrenArray.map((step, index) => {
return cloneElement(step as ReactElement, {
index,
...(step as ReactElement).props,
});
});
const contextValue = useMemo(() => ({ activeStep }), [activeStep]);
const sharedUlClasses = clsx(
'unstyled flex-no-min-children gap-2 flex-nowrap m-0',
`flex-justify-${position}`
);
return (
<StepperContext.Provider value={contextValue}>
<div className={clsx('stepper', className)} {...rest}>
<ul className={clsx('stepper-indicators', sharedUlClasses)} aria-hidden="true">
{stepIndicators}
</ul>
<ul className={clsx('stepper-labels', sharedUlClasses)}>{steps}</ul>
</div>
</StepperContext.Provider>
);
};
export default Stepper;
| 5,091
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/StepperContext.ts
|
import { createContext } from 'react';
export interface StepperContextContextValue {
activeStep: number;
}
const StepperContext = createContext({} as StepperContextContextValue);
export default StepperContext;
| 5,092
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/index.ts
|
export { default as Stepper } from './Stepper';
export { default as Step } from './Step';
export * from './Stepper';
export * from './Step';
| 5,093
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalStep.tsx
|
import { ComponentPropsWithoutRef, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
export interface VerticalStepProps extends ComponentPropsWithoutRef<'li'> {
description?: ReactNode;
icon: ReactNode;
/**
* 'next': default state
* 'done': icon will be colored as success
* 'passed': icon will be colored as success, text will look like disabled, and green will be applied to the "path" to the next icon
*/
status?: 'next' | 'done' | 'passed';
}
const VerticalStep = ({ title, description, icon, status = 'next', className, ...rest }: VerticalStepProps) => {
return (
<li
{...rest}
className={clsx(
'flex flex-nowrap flex-align-items-start vertical-steps-item',
status === 'passed' && 'vertical-steps-item--next-done',
className
)}
>
<div
className={clsx(
'flex-item-noshrink rounded-50 vertical-steps-icon-container flex',
['done', 'passed'].includes(status) ? 'bg-success' : 'bg-strong'
)}
>
{icon}
</div>
<div
className={clsx(
'flex-item-fluid pl-2 flex flex-column flex-nowrap relative vertical-steps-item-text',
status === 'passed' && 'color-disabled'
)}
>
{title ? <span className={clsx([status !== 'passed' && 'text-semibold'])}>{title}</span> : null}
{description ? (
<span className={clsx(['text-sm', status !== 'passed' && 'color-weak'])}>{description}</span>
) : null}
</div>
</li>
);
};
export default VerticalStep;
| 5,094
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalSteps.mdx
|
import { ArgsTable, Canvas, PRIMARY_STORY, Primary, Story } from '@storybook/addon-docs';
import { VerticalSteps } from './VerticalSteps';
# VerticalSteps
```js
import { VerticalSteps } from '@proton/atoms';
```
`VerticalSteps` helps to create a vertical timeline UI. Each item accepts a few props: `title`, `description`, `status` (done, passed, next), `icon`.
<Canvas withSource="open">
<Story id="components-verticalsteps--basic" />
</Canvas>
## Props
<div class="hidden">
<Primary />
</div>
<ArgsTable story={PRIMARY_STORY} />
| 5,095
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalSteps.scss
|
@import '~@proton/styles/scss/lib';
.vertical-steps {
&-item {
padding-block-end: 1.5em;
background: linear-gradient(
90deg,
transparent 0%,
transparent rem(15),
var(--background-strong) rem(15),
var(--background-strong) rem(17),
transparent rem(17)
);
&--next-done {
background: linear-gradient(
90deg,
transparent 0%,
transparent rem(15),
var(--signal-success) rem(15),
var(--signal-success) rem(17),
transparent rem(17)
);
}
&-text {
margin-block-start: rem(-2); // small trick to compensate line-height, for vertical centering
}
&:last-child {
background: none;
}
}
&-icon-container {
inline-size: rem(32);
block-size: rem(32);
}
}
| 5,096
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalSteps.stories.tsx
|
import { Icon } from '@proton/components';
import VerticalStep from './VerticalStep';
import VerticalSteps from './VerticalSteps';
import mdx from './VerticalSteps.mdx';
export default {
component: VerticalSteps,
subcomponents: { VerticalStep },
title: 'components/VerticalSteps',
parameters: { docs: { page: mdx } },
};
export const Basic = () => (
<VerticalSteps>
<VerticalStep
icon={<Icon name="checkmark" className="m-auto" size={16} />}
title="Choose a username"
description="You successfully selected your new email address."
status="passed"
/>
<VerticalStep
icon={<Icon name="lock" className="m-auto" size={16} />}
title="Today: get instant access"
description="15 GB secure mailbox with unlimited personalisation."
status="done"
/>
<VerticalStep
icon={<Icon name="bell" className="m-auto" size={16} />}
title="Day 24: Trial end reminder"
description="We’ll send you a notice. Cancel anytime."
/>
<VerticalStep
icon={<Icon name="calendar-row" className="m-auto" size={16} />}
title="Day 30: Trial ends"
description="Your subscription will start Jan 16th. Cancel anytime before."
/>
</VerticalSteps>
);
| 5,097
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalSteps.test.tsx
|
import { RenderResult, render } from '@testing-library/react';
import VerticalStep from './VerticalStep';
import VerticalSteps from './VerticalSteps';
function renderBasicVerticalSteps() {
return render(
<VerticalSteps>
<VerticalStep
icon="checkmark"
title="Choose a username"
description="You successfully selected your new email address."
status="passed"
/>
<VerticalStep
icon="lock"
title="Today: get instant access"
description="15 GB secure mailbox with unlimited personalisation."
status="done"
/>
<VerticalStep
icon="bell"
title="Day 24: Trial end reminder"
description="We’ll send you a notice. Cancel anytime."
/>
<VerticalStep
icon="calendar-row"
title="Day 30: Trial ends"
description="Your subscription will start Jan 16th. Cancel anytime before."
/>
</VerticalSteps>
);
}
describe('<VerticalSteps /> with basic render', () => {
let output: RenderResult<typeof import('@testing-library/dom/types/queries'), HTMLElement, HTMLElement>;
beforeEach(() => {
output = renderBasicVerticalSteps();
});
it('should display 4 steps', () => {
const { container } = output;
expect(container.querySelectorAll('li')).toHaveLength(4);
});
it('should display titles', () => {
const { container } = output;
const titles = container.querySelectorAll('.vertical-steps-item-text > span:first-child');
expect(titles).toHaveLength(4);
expect(titles[0].textContent).toBe('Choose a username');
expect(titles[1].textContent).toBe('Today: get instant access');
expect(titles[2].textContent).toBe('Day 24: Trial end reminder');
expect(titles[3].textContent).toBe('Day 30: Trial ends');
});
it('should display descriptions', () => {
const { container } = output;
const descriptions = container.querySelectorAll('.vertical-steps-item-text > span:last-child');
expect(descriptions).toHaveLength(4);
expect(descriptions[0].textContent).toBe('You successfully selected your new email address.');
expect(descriptions[1].textContent).toBe('15 GB secure mailbox with unlimited personalisation.');
expect(descriptions[2].textContent).toBe('We’ll send you a notice. Cancel anytime.');
expect(descriptions[3].textContent).toBe('Your subscription will start Jan 16th. Cancel anytime before.');
});
});
| 5,098
|
0
|
petrpan-code/ProtonMail/WebClients/packages/atoms
|
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalSteps.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import clsx from '@proton/utils/clsx';
import './VerticalSteps.scss';
export interface VerticalStepsProps extends ComponentPropsWithoutRef<'ul'> {}
const VerticalSteps = ({ className, ...rest }: VerticalStepsProps) => {
return <ul {...rest} className={clsx(['unstyled flex flex-column flex-nowrap vertical-steps', className])} />;
};
export default VerticalSteps;
| 5,099
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.