hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 1, "code_window": [ " const entries = {\n", " iframe: await presets.preview([], options),\n", " manager: await presets.manager([], options),\n", " };\n", "\n", " const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries });\n", "\n", " return presets.webpackFinal(webpackConfig, options);\n", "}\n", "\n", "export default async options => {\n", " const { corePresets = [], frameworkPresets = [], ...restOptions } = options;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return presets.webpack({}, { ...options, babelOptions, entries });\n" ], "file_path": "lib/core/src/server/config.js", "type": "replace", "edit_start_line_idx": 37 }
const path = require('path'); module.exports = (storybookBaseConfig, configType, defaultConfig) => { defaultConfig.module.rules.push({ test: [/\.stories\.js$/, /index\.js$/], loaders: [require.resolve('@storybook/addon-storysource/loader')], include: [path.resolve(__dirname, '../')], enforce: 'pre', }); return defaultConfig; };
examples/ember-cli/.storybook/webpack.config.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.0006892029196023941, 0.0004302924789953977, 0.00017138202383648604, 0.0004302924789953977, 0.0002589104697108269 ]
{ "id": 1, "code_window": [ " const entries = {\n", " iframe: await presets.preview([], options),\n", " manager: await presets.manager([], options),\n", " };\n", "\n", " const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries });\n", "\n", " return presets.webpackFinal(webpackConfig, options);\n", "}\n", "\n", "export default async options => {\n", " const { corePresets = [], frameworkPresets = [], ...restOptions } = options;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return presets.webpack({}, { ...options, babelOptions, entries });\n" ], "file_path": "lib/core/src/server/config.js", "type": "replace", "edit_start_line_idx": 37 }
import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; import './main.html'; Template.hello.onCreated(function helloOnCreated() { // counter starts at 0 this.counter = new ReactiveVar(0); }); Template.hello.helpers({ counter() { return Template.instance().counter.get(); }, }); Template.hello.events({ 'click button'(event, instance) { // increment the counter when button is clicked instance.counter.set(instance.counter.get() + 1); }, });
lib/cli/test/fixtures/meteor/client/main.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017836499318946153, 0.00017555657541379333, 0.0001720310392556712, 0.00017627370834816247, 0.0000026350771804573014 ]
{ "id": 2, "code_window": [ " }\n", "\n", " logger.info(`=> Using default webpack setup based on \"${defaultConfigName}\".`);\n", "}\n", "\n", "export function webpack(config, { configDir, configType, defaultConfigName }) {\n", " const defaultConfig = createDefaultWebpackConfig(config);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function wrapPresets(presets) {\n", " return {\n", " webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n", " };\n", "}\n", "\n", "async function createFinalDefaultConfig(presets, config, options) {\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 14 }
import { logger } from '@storybook/node-logger'; import loadCustomWebpackConfig from './loadCustomWebpackConfig'; import mergeConfigs from './mergeConfigs'; import { createDefaultWebpackConfig } from './config/webpack.config.default'; function informAboutCustomConfig(defaultConfigName) { if (!defaultConfigName) { logger.info('=> Using default webpack setup.'); return; } logger.info(`=> Using default webpack setup based on "${defaultConfigName}".`); } export function webpack(config, { configDir, configType, defaultConfigName }) { const defaultConfig = createDefaultWebpackConfig(config); // Check whether user has a custom webpack config file and // return the (extended) base configuration if it's not available. const customConfig = loadCustomWebpackConfig(configDir); if (customConfig === null) { informAboutCustomConfig(defaultConfigName); return defaultConfig; } if (typeof customConfig === 'function') { logger.info('=> Loading custom webpack config (full-control mode).'); return customConfig(config, configType, defaultConfig); } logger.info('=> Loading custom webpack config (extending mode).'); return mergeConfigs(config, customConfig); }
lib/core/src/server/core-preset-webpack-custom.js
1
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.998405396938324, 0.7283244132995605, 0.028524475172162056, 0.9431838989257812, 0.40650877356529236 ]
{ "id": 2, "code_window": [ " }\n", "\n", " logger.info(`=> Using default webpack setup based on \"${defaultConfigName}\".`);\n", "}\n", "\n", "export function webpack(config, { configDir, configType, defaultConfigName }) {\n", " const defaultConfig = createDefaultWebpackConfig(config);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function wrapPresets(presets) {\n", " return {\n", " webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n", " };\n", "}\n", "\n", "async function createFinalDefaultConfig(presets, config, options) {\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 14 }
require('./dist/index').register();
addons/ondevice-knobs/register.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017508340533822775, 0.00017508340533822775, 0.00017508340533822775, 0.00017508340533822775, 0 ]
{ "id": 2, "code_window": [ " }\n", "\n", " logger.info(`=> Using default webpack setup based on \"${defaultConfigName}\".`);\n", "}\n", "\n", "export function webpack(config, { configDir, configType, defaultConfigName }) {\n", " const defaultConfig = createDefaultWebpackConfig(config);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function wrapPresets(presets) {\n", " return {\n", " webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n", " };\n", "}\n", "\n", "async function createFinalDefaultConfig(presets, config, options) {\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 14 }
{ "transformer": "@babel/core", "method": "transform" }
riot-jest-transformer.json
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017141079297289252, 0.00017141079297289252, 0.00017141079297289252, 0.00017141079297289252, 0 ]
{ "id": 2, "code_window": [ " }\n", "\n", " logger.info(`=> Using default webpack setup based on \"${defaultConfigName}\".`);\n", "}\n", "\n", "export function webpack(config, { configDir, configType, defaultConfigName }) {\n", " const defaultConfig = createDefaultWebpackConfig(config);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function wrapPresets(presets) {\n", " return {\n", " webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n", " };\n", "}\n", "\n", "async function createFinalDefaultConfig(presets, config, options) {\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 14 }
# AngularCliV6 This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.2.5. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
lib/cli/test/fixtures/angular-cli-v6/README.md
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00016756418335717171, 0.0001657875400269404, 0.0001644516596570611, 0.00016534679161850363, 0.000001308344621975266 ]
{ "id": 3, "code_window": [ " const defaultConfig = createDefaultWebpackConfig(config);\n", "\n", " // Check whether user has a custom webpack config file and\n", " // return the (extended) base configuration if it's not available.\n", " const customConfig = loadCustomWebpackConfig(configDir);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return presets.webpackFinal(defaultConfig, options);\n", "}\n", "\n", "export async function webpack(config, options) {\n", " const { configDir, configType, defaultConfigName } = options;\n", " const presets = wrapPresets(options.presets);\n", "\n", " const finalConfig = await presets.webpackFinal(config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "add", "edit_start_line_idx": 16 }
import path from 'path'; import { logger } from '@storybook/node-logger'; import loadPresets from './presets'; import serverRequire from './serverRequire'; function wrapCorePresets(presets) { return { babel: async (config, args) => presets.apply('babel', config, args), webpack: async (config, args) => presets.apply('webpack', config, args), webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args), preview: async (config, args) => presets.apply('preview', config, args), manager: async (config, args) => presets.apply('manager', config, args), }; } function customPreset({ configDir }) { const presets = serverRequire(path.resolve(configDir, 'presets')); if (presets) { logger.warn( '"Custom presets" is an experimental and undocumented feature that will be changed or deprecated soon. Use it on your own risk.' ); return presets; } return []; } async function getWebpackConfig(options, presets) { const babelOptions = await presets.babel({}, options); const entries = { iframe: await presets.preview([], options), manager: await presets.manager([], options), }; const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries }); return presets.webpackFinal(webpackConfig, options); } export default async options => { const { corePresets = [], frameworkPresets = [], ...restOptions } = options; const presetsConfig = [ ...corePresets, require.resolve('./core-preset-babel-cache.js'), ...frameworkPresets, ...customPreset(options), require.resolve('./core-preset-webpack-custom.js'), ]; const presets = loadPresets(presetsConfig); return getWebpackConfig({ ...restOptions, presets }, wrapCorePresets(presets)); };
lib/core/src/server/config.js
1
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.0012498069554567337, 0.000551125209312886, 0.00018590233230497688, 0.00031129279523156583, 0.0004337314749136567 ]
{ "id": 3, "code_window": [ " const defaultConfig = createDefaultWebpackConfig(config);\n", "\n", " // Check whether user has a custom webpack config file and\n", " // return the (extended) base configuration if it's not available.\n", " const customConfig = loadCustomWebpackConfig(configDir);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return presets.webpackFinal(defaultConfig, options);\n", "}\n", "\n", "export async function webpack(config, options) {\n", " const { configDir, configType, defaultConfigName } = options;\n", " const presets = wrapPresets(options.presets);\n", "\n", " const finalConfig = await presets.webpackFinal(config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "add", "edit_start_line_idx": 16 }
{ "name": "riot-fixture", "version": "1.0.0", "private": true, "description": "A riot.js project", "author": "hypnos <[email protected]>", "scripts": { "build:js": "cross-env NODE_ENV=production webpack", "dev": "cross-env NODE_ENV=development webpack" }, "dependencies": { "riot": "^3.11.2" }, "devDependencies": { "cross-env": "^5.2.0", "common-tags": "^1.8.0", "global": "^4.3.2", "style-loader": "^0.22.1", "css-loader": "^1.0.0", "raw-loader": "^0.5.1", "riot-hot-reload": "^1.0.0", "riot-compiler": "^3.5.1", "storybook-addon-jsx": "latest", "storybook-readme": "latest", "riot": "latest", "webpack": "latest", "webpack-cli": "latest", "webpack-bundle-analyzer": "latest", "packer-webpack-plugin": "latest", "babel-loader": "latest", "babel-preset-env": "latest", "babel-register": "latest" }, "peerDependencies": { "babel-loader": "^7.0.0 || ^8.0.0" } }
lib/cli/test/fixtures/riot/package.json
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.0001724284520605579, 0.00017036605277098715, 0.00016867672093212605, 0.00017017954087350518, 0.0000013708144024349167 ]
{ "id": 3, "code_window": [ " const defaultConfig = createDefaultWebpackConfig(config);\n", "\n", " // Check whether user has a custom webpack config file and\n", " // return the (extended) base configuration if it's not available.\n", " const customConfig = loadCustomWebpackConfig(configDir);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return presets.webpackFinal(defaultConfig, options);\n", "}\n", "\n", "export async function webpack(config, options) {\n", " const { configDir, configType, defaultConfigName } = options;\n", " const presets = wrapPresets(options.presets);\n", "\n", " const finalConfig = await presets.webpackFinal(config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "add", "edit_start_line_idx": 16 }
import packageJson from '../../package.json'; export default { packageJson, defaultConfigName: 'create-react-app', frameworkPresets: [ require.resolve('./framework-preset-react.js'), require.resolve('./framework-preset-react-docgen.js'), require.resolve('./framework-preset-cra-styles.js'), ], };
app/react/src/server/options.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017788060358725488, 0.00017461032257415354, 0.0001713400415610522, 0.00017461032257415354, 0.0000032702810131013393 ]
{ "id": 3, "code_window": [ " const defaultConfig = createDefaultWebpackConfig(config);\n", "\n", " // Check whether user has a custom webpack config file and\n", " // return the (extended) base configuration if it's not available.\n", " const customConfig = loadCustomWebpackConfig(configDir);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return presets.webpackFinal(defaultConfig, options);\n", "}\n", "\n", "export async function webpack(config, options) {\n", " const { configDir, configType, defaultConfigName } = options;\n", " const presets = wrapPresets(options.presets);\n", "\n", " const finalConfig = await presets.webpackFinal(config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "add", "edit_start_line_idx": 16 }
If you are reporting a bug or requesting support, start here: ### Bug or support request summary _Please provide issue details here - What did you expect to happen? What happened instead?_ ### Steps to reproduce _Please provide necessary steps for reproduction of this issue. Describe the exact steps a maintainer has to take to make the problem occur. If the problem is non-trivial to reproduce, please link a repository or provide some code snippets._ _(A screencast can be useful for visual bugs, but it is not a substitute for a textual description.)_ ### Please specify which version of Storybook and optionally any affected addons that you're running - @storybook/react x.x.x - @storybook/addon-something x.x.x ### Affected platforms - _If UI related, please indicate browser, OS, and version_ - _If dependency related, please include relevant version numbers_ - _If developer tooling related, please include the platform information_ ### Screenshots / Screencast / Code Snippets (Optional) ```js // code here ``` End bug report support request - delete the rest below If you are creating a issue to track work to be completed, start here: ### Work summary _Please provide a description of the work to be completed here - Include some context as to why something needs to be done and link any related tickets._ ### Where to start _Please list the file(s) a contributor needs to figure out where to start work and include any docs or tutorials that may be applicable._ ### Acceptance criteria _Please include a checklist of the requirements necessary to close this ticket. The work should be narrowly scoped and limited to a few hours worth by an experienced developer at the most._ ### Who to contact _Add yourself and/or people who are familiar with the code changes and requirements. These people should be able to review the completed code._ End work issue - please tag this issue with the correct status and type labels
.github/ISSUE_TEMPLATE.md
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017338700126856565, 0.00016931310528889298, 0.00016747426707297564, 0.00016841459728311747, 0.000002189517772421823 ]
{ "id": 4, "code_window": [ "\n", " if (customConfig === null) {\n", " informAboutCustomConfig(defaultConfigName);\n", " return defaultConfig;\n", " }\n", "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return createFinalDefaultConfig(presets, config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 23 }
import { logger } from '@storybook/node-logger'; import loadCustomWebpackConfig from './loadCustomWebpackConfig'; import mergeConfigs from './mergeConfigs'; import { createDefaultWebpackConfig } from './config/webpack.config.default'; function informAboutCustomConfig(defaultConfigName) { if (!defaultConfigName) { logger.info('=> Using default webpack setup.'); return; } logger.info(`=> Using default webpack setup based on "${defaultConfigName}".`); } export function webpack(config, { configDir, configType, defaultConfigName }) { const defaultConfig = createDefaultWebpackConfig(config); // Check whether user has a custom webpack config file and // return the (extended) base configuration if it's not available. const customConfig = loadCustomWebpackConfig(configDir); if (customConfig === null) { informAboutCustomConfig(defaultConfigName); return defaultConfig; } if (typeof customConfig === 'function') { logger.info('=> Loading custom webpack config (full-control mode).'); return customConfig(config, configType, defaultConfig); } logger.info('=> Loading custom webpack config (extending mode).'); return mergeConfigs(config, customConfig); }
lib/core/src/server/core-preset-webpack-custom.js
1
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.9966513514518738, 0.28984779119491577, 0.0022004868369549513, 0.08026964217424393, 0.412874311208725 ]
{ "id": 4, "code_window": [ "\n", " if (customConfig === null) {\n", " informAboutCustomConfig(defaultConfigName);\n", " return defaultConfig;\n", " }\n", "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return createFinalDefaultConfig(presets, config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 23 }
/* eslint-disable no-console */ const shell = require('shelljs'); // exit with code 1 if there are some changed files if (shell.exec('git status --porcelain').stdout.trim() !== '') { console.error( 'Git repo is dirty, please consider updating lockfiles by running `yarn bootstrap --reset --core`' ); process.exit(1); }
scripts/repo-dirty-check.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017829662829171866, 0.00017653356189839542, 0.00017477049550507218, 0.00017653356189839542, 0.0000017630663933232427 ]
{ "id": 4, "code_window": [ "\n", " if (customConfig === null) {\n", " informAboutCustomConfig(defaultConfigName);\n", " return defaultConfig;\n", " }\n", "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return createFinalDefaultConfig(presets, config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 23 }
import { createApp } from '@storybook/mantra-core'; import Podda from '@storybook/podda'; import buildContext from './context'; import shortcutsModule from './modules/shortcuts'; import apiModule from './modules/api'; import uiModule from './modules/ui'; import { setContext, setActions } from './compose'; export class Provider { renderPreview() { throw new Error('Provider.renderPreview() is not implemented!'); } handleAPI() { throw new Error('Provider.handleAPI() is not implemented!'); } } export default function(domNode, provider) { if (!(provider instanceof Provider)) { throw new Error('provider is not extended from the base Provider'); } const defaultState = { ...shortcutsModule.defaultState, ...apiModule.defaultState, ...uiModule.defaultState, }; const clientStore = new Podda(defaultState); clientStore.registerAPI('toggle', (store, key) => store.set(key, !store.get(key))); const context = buildContext(clientStore, domNode, provider); const app = createApp(context); app.loadModule(shortcutsModule); app.loadModule(apiModule); app.loadModule(uiModule); setContext(context); setActions(app._bindContext(app.actions)); // eslint-disable-line app.init(); }
lib/ui/src/index.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00018350825121160597, 0.00017376487085130066, 0.0001676439424045384, 0.0001724939065752551, 0.000005246894488664111 ]
{ "id": 4, "code_window": [ "\n", " if (customConfig === null) {\n", " informAboutCustomConfig(defaultConfigName);\n", " return defaultConfig;\n", " }\n", "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return createFinalDefaultConfig(presets, config, options);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 23 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Addons|Centered button in center 1`] = ` <div id="sb-addon-centered-wrapper" style="position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; display: flex; align-items: center; overflow: auto;" > <div id="sb-addon-centered-inner" style="margin: auto; max-height: 100%;" > <button> I am a Button ! </button> </div> </div> `;
examples/html-kitchen-sink/stories/__snapshots__/addon-centered.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017563569417688996, 0.0001730502408463508, 0.00017046478751581162, 0.0001730502408463508, 0.000002585453330539167 ]
{ "id": 5, "code_window": [ "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n", " return customConfig(config, configType, defaultConfig);\n", " }\n", "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const finalDefaultConfig = await createFinalDefaultConfig(presets, config, options);\n", " return customConfig(finalConfig, configType, finalDefaultConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 28 }
import { logger } from '@storybook/node-logger'; import loadCustomWebpackConfig from './loadCustomWebpackConfig'; import mergeConfigs from './mergeConfigs'; import { createDefaultWebpackConfig } from './config/webpack.config.default'; function informAboutCustomConfig(defaultConfigName) { if (!defaultConfigName) { logger.info('=> Using default webpack setup.'); return; } logger.info(`=> Using default webpack setup based on "${defaultConfigName}".`); } export function webpack(config, { configDir, configType, defaultConfigName }) { const defaultConfig = createDefaultWebpackConfig(config); // Check whether user has a custom webpack config file and // return the (extended) base configuration if it's not available. const customConfig = loadCustomWebpackConfig(configDir); if (customConfig === null) { informAboutCustomConfig(defaultConfigName); return defaultConfig; } if (typeof customConfig === 'function') { logger.info('=> Loading custom webpack config (full-control mode).'); return customConfig(config, configType, defaultConfig); } logger.info('=> Loading custom webpack config (extending mode).'); return mergeConfigs(config, customConfig); }
lib/core/src/server/core-preset-webpack-custom.js
1
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.9906094670295715, 0.35083988308906555, 0.0007882467471063137, 0.20598092675209045, 0.4051932990550995 ]
{ "id": 5, "code_window": [ "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n", " return customConfig(config, configType, defaultConfig);\n", " }\n", "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const finalDefaultConfig = await createFinalDefaultConfig(presets, config, options);\n", " return customConfig(finalConfig, configType, finalDefaultConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 28 }
import React, { Component } from 'react' import { hot } from 'react-hot-loader' // import './app.css' import logo from './logo.png' class App extends Component { render () { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React-Static</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ) } } export default hot(module)(App)
lib/cli/test/fixtures/react_static_next/src/App.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017282152839470655, 0.00017076304357033223, 0.00016673321078997105, 0.00017273436242248863, 0.000002849737256838125 ]
{ "id": 5, "code_window": [ "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n", " return customConfig(config, configType, defaultConfig);\n", " }\n", "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const finalDefaultConfig = await createFinalDefaultConfig(presets, config, options);\n", " return customConfig(finalConfig, configType, finalDefaultConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 28 }
src .babelrc
app/riot/.npmignore
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.0001756785495672375, 0.0001756785495672375, 0.0001756785495672375, 0.0001756785495672375, 0 ]
{ "id": 5, "code_window": [ "\n", " if (typeof customConfig === 'function') {\n", " logger.info('=> Loading custom webpack config (full-control mode).');\n", " return customConfig(config, configType, defaultConfig);\n", " }\n", "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const finalDefaultConfig = await createFinalDefaultConfig(presets, config, options);\n", " return customConfig(finalConfig, configType, finalDefaultConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 28 }
import addons, { makeDecorator } from '@storybook/addons'; export const withNotes = makeDecorator({ name: 'withNotes', parameterName: 'notes', wrapper: (getStory, context, { options, parameters }) => { const channel = addons.getChannel(); const storyOptions = parameters || options; if (!storyOptions) { channel.emit('storybook/notes/add_notes', ''); return getStory(context); } const { text, markdown } = typeof storyOptions === 'string' ? { text: storyOptions } : storyOptions; if (!text && !markdown) { throw new Error('You must set of one of `text` or `markdown` on the `notes` parameter'); } channel.emit('storybook/notes/add_notes', text || markdown); return getStory(context); }, }); export const withMarkdownNotes = (text, options) => withNotes({ markdown: text, markdownOptions: options, });
addons/ondevice-notes/src/index.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017754966393113136, 0.00017608529014978558, 0.00017311838746536523, 0.00017683656187728047, 0.0000017868441091195564 ]
{ "id": 6, "code_window": [ "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n", " return mergeConfigs(config, customConfig);\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return mergeConfigs(finalConfig, customConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 33 }
import { logger } from '@storybook/node-logger'; import loadCustomWebpackConfig from './loadCustomWebpackConfig'; import mergeConfigs from './mergeConfigs'; import { createDefaultWebpackConfig } from './config/webpack.config.default'; function informAboutCustomConfig(defaultConfigName) { if (!defaultConfigName) { logger.info('=> Using default webpack setup.'); return; } logger.info(`=> Using default webpack setup based on "${defaultConfigName}".`); } export function webpack(config, { configDir, configType, defaultConfigName }) { const defaultConfig = createDefaultWebpackConfig(config); // Check whether user has a custom webpack config file and // return the (extended) base configuration if it's not available. const customConfig = loadCustomWebpackConfig(configDir); if (customConfig === null) { informAboutCustomConfig(defaultConfigName); return defaultConfig; } if (typeof customConfig === 'function') { logger.info('=> Loading custom webpack config (full-control mode).'); return customConfig(config, configType, defaultConfig); } logger.info('=> Loading custom webpack config (extending mode).'); return mergeConfigs(config, customConfig); }
lib/core/src/server/core-preset-webpack-custom.js
1
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.9934898614883423, 0.26262176036834717, 0.0025998323690146208, 0.02719864994287491, 0.42239072918891907 ]
{ "id": 6, "code_window": [ "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n", " return mergeConfigs(config, customConfig);\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return mergeConfigs(finalConfig, customConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 33 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Addons|Knobs All knobs 1`] = ` <div style="border: 2px dotted deeppink; padding: 8px 22px; border-radius: 8px" > <h1> My name is Jane, </h1> <h3> today is January 20, 2017 </h3> <p> I have a stock of 20 apples, costing $2.25 each. </p> <p> Also, I have: </p> <ul> <li> Laptop </li> <li> Book </li> <li> Whiskey </li> </ul> <p> Nice to meet you! </p> </div> `; exports[`Storyshots Addons|Knobs Simple 1`] = ` <div> I am John Doe and I'm 44 years old. </div> `; exports[`Storyshots Addons|Knobs XSS safety 1`] = `&lt;img src=x onerror="alert('XSS Attack')" &gt;`;
examples/html-kitchen-sink/stories/__snapshots__/addon-knobs.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017747671518009156, 0.00017457063950132579, 0.00016760366270318627, 0.00017568544717505574, 0.0000032426955840492155 ]
{ "id": 6, "code_window": [ "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n", " return mergeConfigs(config, customConfig);\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return mergeConfigs(finalConfig, customConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 33 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Addons|a11y Default 1`] = `<button />`; exports[`Storyshots Addons|a11y Delayed render 1`] = `<div />`; exports[`Storyshots Addons|a11y Disabled 1`] = ` <button disabled="" > Testing the a11y addon </button> `; exports[`Storyshots Addons|a11y Invalid contrast 1`] = ` <button style="color: black; background-color: brown;" > Testing the a11y addon </button> `; exports[`Storyshots Addons|a11y Label 1`] = ` <button> Testing the a11y addon </button> `;
examples/html-kitchen-sink/stories/__snapshots__/addon-a11y.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017438779468648136, 0.0001733641984174028, 0.00017156009562313557, 0.0001741447049425915, 0.0000012795476322935428 ]
{ "id": 6, "code_window": [ "\n", " logger.info('=> Loading custom webpack config (extending mode).');\n", "\n", " return mergeConfigs(config, customConfig);\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return mergeConfigs(finalConfig, customConfig);\n" ], "file_path": "lib/core/src/server/core-preset-webpack-custom.js", "type": "replace", "edit_start_line_idx": 33 }
import createFunctionEval from '../createFunctionEval'; import reservedKeywords from '../reservedKeywords'; describe('createFunctionEval', () => { it('Adds $ suffix for reserved names', () => { reservedKeywords.forEach(reservedKeyword => { expect(createFunctionEval(reservedKeyword).name).toBe(`${reservedKeyword}$`); }); }); });
addons/actions/src/lib/types/function/__tests__/createFunctionEval.test.js
0
https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9
[ 0.00017843932437244803, 0.00017634365940466523, 0.00017424799443688244, 0.00017634365940466523, 0.0000020956649677827954 ]
{ "id": 0, "code_window": [ " defaultTheme?: Theme;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, Partial<WithTheme<Theme>>>;\n", "\n", "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import { Theme } from './createMuiTheme'; import { PropInjector } from '@material-ui/types'; export interface WithTheme { theme: Theme; } export interface ThemedComponentProps extends Partial<WithTheme> { innerRef?: React.Ref<any>; } declare const withTheme: PropInjector<WithTheme, ThemedComponentProps>; export default withTheme;
packages/material-ui/src/styles/withTheme.d.ts
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0051774377934634686, 0.004749554209411144, 0.00432167062535882, 0.004749554209411144, 0.0004278835840523243 ]
{ "id": 0, "code_window": [ " defaultTheme?: Theme;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, Partial<WithTheme<Theme>>>;\n", "\n", "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import { assert } from 'chai'; import { hasValue, isFilled } from './utils'; describe('Input/utils.js', () => { describe('hasValue', () => { ['', 0].forEach(value => { it(`is true for ${value}`, () => { assert.strictEqual(hasValue(value), true); }); }); [null, undefined].forEach(value => { it(`is false for ${value}`, () => { assert.strictEqual(hasValue(value), false); }); }); }); describe('isFilled', () => { [' ', 0].forEach(value => { it(`is true for value ${value}`, () => { assert.strictEqual(isFilled({ value }), true); }); it(`is true for SSR defaultValue ${value}`, () => { assert.strictEqual(isFilled({ defaultValue: value }, true), true); }); }); [null, undefined, ''].forEach(value => { it(`is false for value ${value}`, () => { assert.strictEqual(isFilled({ value }), false); }); it(`is false for SSR defaultValue ${value}`, () => { assert.strictEqual(isFilled({ defaultValue: value }, true), false); }); }); }); });
packages/material-ui/src/InputBase/utils.test.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017737453163135797, 0.00017384078819304705, 0.00016798173601273447, 0.0001750034571159631, 0.000003518726998663624 ]
{ "id": 0, "code_window": [ " defaultTheme?: Theme;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, Partial<WithTheme<Theme>>>;\n", "\n", "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98C15.96 9.45 15.27 9 14.51 9H11V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z" /> , 'AirlineSeatLegroomExtraTwoTone');
packages/material-ui-icons/src/AirlineSeatLegroomExtraTwoTone.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017458826187066734, 0.00017458826187066734, 0.00017458826187066734, 0.00017458826187066734, 0 ]
{ "id": 0, "code_window": [ " defaultTheme?: Theme;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, Partial<WithTheme<Theme>>>;\n", "\n", "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M10.5 9h3c.28 0 .5-.22.5-.5V6h1.79c.45 0 .67-.54.35-.85l-3.79-3.79c-.2-.2-.51-.2-.71 0L7.85 5.15c-.31.31-.09.85.36.85H10v2.5c0 .28.22.5.5.5zm-2 1H6V8.21c0-.45-.54-.67-.85-.35l-3.79 3.79c-.2.2-.2.51 0 .71l3.79 3.79c.31.31.85.09.85-.36V14h2.5c.28 0 .5-.22.5-.5v-3c0-.28-.22-.5-.5-.5zm14.15 1.65l-3.79-3.79c-.32-.32-.86-.1-.86.35V10h-2.5c-.28 0-.5.22-.5.5v3c0 .28.22.5.5.5H18v1.79c0 .45.54.67.85.35l3.79-3.79c.2-.19.2-.51.01-.7zM13.5 15h-3c-.28 0-.5.22-.5.5V18H8.21c-.45 0-.67.54-.35.85l3.79 3.79c.2.2.51.2.71 0l3.79-3.79c.31-.31.09-.85-.35-.85H14v-2.5c0-.28-.22-.5-.5-.5z" /> , 'OpenWithRounded');
packages/material-ui-icons/src/OpenWithRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0003094866406172514, 0.0003094866406172514, 0.0003094866406172514, 0.0003094866406172514, 0 ]
{ "id": 1, "code_window": [ "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n", " innerRef?: React.Ref<any>;\n", "}\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 14 }
import * as React from 'react'; import { createStyles, withStyles, withTheme, WithTheme, WithStyles, makeStyles, } from '@material-ui/styles'; import Button from '@material-ui/core/Button'; import { Theme } from '@material-ui/core/styles'; // Example 1 const styles = ({ palette, spacing }: Theme) => ({ root: { padding: spacing(1), backgroundColor: palette.background.default, color: palette.primary.dark, }, }); // Shared types for examples interface ComponentProps extends WithStyles<typeof styles> { text: string; } const StyledExampleOne = withStyles(styles)(({ classes, text }: ComponentProps) => ( <div className={classes.root}>{text}</div> )); <StyledExampleOne text="I am styled!" />; // Example 2 const Component: React.FunctionComponent<ComponentProps & WithStyles<typeof styles>> = ({ classes, text, }) => <div className={classes.root}>{text}</div>; const StyledExampleTwo = withStyles(styles)(Component); <StyledExampleTwo text="I am styled!" />; // Example 3 const styleRule = createStyles({ root: { display: 'flex', alignItems: 'stretch', height: '100vh', width: '100%', }, }); const ComponentWithChildren: React.FunctionComponent<WithStyles<typeof styles>> = ({ classes, children, }) => <div className={classes.root}>{children}</div>; const StyledExampleThree = withStyles(styleRule)(ComponentWithChildren); <StyledExampleThree />; // Also works with a plain object const stylesAsPojo = { root: { backgroundColor: 'hotpink', }, }; const AnotherStyledSFC = withStyles({ root: { backgroundColor: 'hotpink' }, })(({ classes }: WithStyles<'root'>) => <div className={classes.root}>Stylish!</div>); // withTheme const ComponentWithTheme = withTheme<Theme, React.FunctionComponent<WithTheme<Theme>>>( ({ theme }: WithTheme<Theme>) => <div>{theme.spacing(1)}</div>, ); <ComponentWithTheme />; // withStyles + withTheme type AllTheProps = WithTheme<Theme> & WithStyles<typeof styles>; const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => ( <div className={classes.root}>{theme.palette.text.primary}</div> )); // missing prop theme <StyledComponent />; // $ExpectError const AllTheComposition = withTheme<Theme, typeof StyledComponent>(StyledComponent); <AllTheComposition />; { const Foo = withTheme<Theme, React.ComponentClass<WithTheme<Theme>>>( class extends React.Component<WithTheme<Theme>> { render() { return null; } }, ); <Foo />; } declare const themed: boolean; { // this is necessary so that TypesScript can infer the theme // usually it's better to just use withTheme<Theme> if you're not actual styling const themedStyles = (theme: Theme) => ({ root: {} }); // Test that withTheme: true guarantees the presence of the theme const Foo = withStyles(themedStyles, { withTheme: true })( class extends React.Component<WithTheme<Theme>> { render() { return <div style={{ margin: this.props.theme.spacing(1) }} />; } }, ); <Foo />; const Bar = withStyles(themedStyles, { withTheme: true })( ({ theme }: WithStyles<typeof themedStyles, true>) => ( <div style={{ margin: theme.spacing(1) }} /> ), ); <Bar />; } // Can't use withStyles effectively as a decorator in TypeScript // due to https://github.com/Microsoft/TypeScript/issues/4881 // @withStyles(styles) const DecoratedComponent = withStyles(styles)( class extends React.Component<ComponentProps & WithStyles<typeof styles>> { render() { const { classes, text } = this.props; return <div className={classes.root}>{text}</div>; } }, ); // no 'classes' property required at element creation time (#8267) <DecoratedComponent text="foo" />; // Allow nested pseudo selectors withStyles(theme => createStyles({ guttered: { '&:hover': { textDecoration: 'none', }, }, listItem: { '&:hover $listItemIcon': { visibility: 'inherit', }, }, }), ); { // allow top level media queries // https://github.com/mui-org/material-ui/issues/12277 // typescript thinks `content` is the CSS property not a classname const ambiguousStyles = createStyles({ content: { minHeight: '100vh', }, // $ExpectError '@media (min-width: 960px)': { content: { display: 'flex', }, }, }); const styles = createStyles({ contentClass: { minHeight: '100vh', }, '@media (min-width: 960px)': { contentClass: { display: 'flex', }, }, }); } { const styles = (theme: Theme) => createStyles({ // Styled similar to ListItemText root: { '&:first-child': { paddingLeft: 0, }, flex: '1 1 auto', padding: '0 16px', }, inset: { '&:first-child': { paddingLeft: theme.spacing(7), }, }, row: { alignItems: 'center', display: 'flex', flexDirection: 'row', }, }); interface ListItemContentProps extends WithStyles<typeof styles> { children?: React.ReactElement; inset?: boolean; row?: boolean; } const ListItemContent = withStyles(styles, { name: 'ui-ListItemContent' })( ({ children, classes, inset, row }: ListItemContentProps) => ( <div className={classes.root} color="textSecondary"> {children} </div> ), ); } { interface FooProps extends WithStyles<'x' | 'y'> { a: number; b: boolean; } const ListItemContent = withStyles({ x: {}, y: {} })((props: FooProps) => <div />); } { // https://github.com/mui-org/material-ui/issues/11109 // The real test here is with "strictFunctionTypes": false, // but we don't have a way currently to test under varying // TypeScript configurations. interface ComponentProps extends WithStyles<typeof styles> { caption: string; } const styles = (theme: Theme) => createStyles({ content: { margin: 4, }, }); const Component = (props: ComponentProps) => { return <div className={props.classes.content}>Hello {props.caption}</div>; }; const StyledComponent = withStyles(styles)(Component); class App extends React.Component { render() { return ( <div className="App"> <StyledComponent caption="Developer" /> </div> ); } } <App />; } { // https://github.com/mui-org/material-ui/issues/11191 const styles = (theme: Theme) => createStyles({ main: {}, }); interface Props extends WithStyles<typeof styles> { someProp?: string; } class SomeComponent extends React.PureComponent<Props> { render() { return <div />; } } const DecoratedSomeComponent = withStyles(styles)(SomeComponent); <DecoratedSomeComponent someProp="hello world" />; } { // https://github.com/mui-org/material-ui/issues/11312 withStyles(styles, { name: 'MyComponent', index: 0 })(() => <div />); } { // can't provide own `classes` type interface Props { classes: number; } class Component extends React.Component<Props & WithStyles<typeof styles>> {} // $ExpectError const StyledComponent = withStyles(styles)(Component); // implicit FunctionComponent withStyles(styles)((props: Props) => null); // $ExpectError withStyles(styles)((props: Props & WithStyles<typeof styles>) => null); // $ExpectError withStyles(styles)((props: Props & { children?: React.ReactNode }) => null); // $ExpectError withStyles(styles)( (props: Props & WithStyles<typeof styles> & { children?: React.ReactNode }) => null, // $ExpectError ); // explicit not but with "Property 'children' is missing in type 'ValidationMap<Props>'". // which is not helpful const StatelessComponent: React.FunctionComponent<Props> = props => null; const StatelessComponentWithStyles: React.FunctionComponent< Props & WithStyles<typeof styles> > = props => null; withStyles(styles)(StatelessComponent); // $ExpectError withStyles(styles)(StatelessComponentWithStyles); // $ExpectError } { // https://github.com/mui-org/material-ui/issues/12670 interface Props { nonDefaulted: string; defaulted: number; } class MyButton extends React.Component<Props & WithStyles<typeof styles>> { static defaultProps = { defaulted: 0, }; render() { const { classes, nonDefaulted, defaulted } = this.props; return ( <Button className={classes.btn}> {defaulted}, {nonDefaulted} </Button> ); } } const styles = () => createStyles({ btn: { color: 'red', }, }); const StyledMyButton = withStyles(styles)(MyButton); const CorrectUsage = () => <StyledMyButton nonDefaulted="2" />; // Property 'nonDefaulted' is missing in type '{}' const MissingPropUsage = () => <StyledMyButton />; // $ExpectError } { // styles from props interface StyleProps { color?: 'blue' | 'red'; } const styles = (theme: Theme) => ({ root: (props: StyleProps) => ({ backgroundColor: props.color || theme.palette.primary.main }), }); interface MyComponentProps extends WithStyles<typeof styles> { message: string; } class MyComponent extends React.Component<MyComponentProps> { render() { const { classes, color, message } = this.props; return ( <div className={classes.root}> {color}: {message} </div> ); } } const StyledMyComponent = withStyles(styles)(MyComponent); const renderedStyledMyComponent = <StyledMyComponent message="Hi" />; // number is not assignable to 'blue' | 'red' // $ExpectError interface InconsistentProps extends WithStyles<typeof styles> { color: number; } } function forwardRefTest() { const styles = createStyles({ root: { color: 'red' }, }); function Anchor(props: WithStyles<typeof styles>) { const { classes } = props; return <a className={classes.root} />; } const StyledAnchor = withStyles(styles)(Anchor); const anchorRef = React.useRef<HTMLAnchorElement>(null); // forwarded to function components which can't hold refs // property 'ref' does not exists <StyledAnchor ref={anchorRef} />; // $ExpectError <StyledAnchor innerRef={anchorRef} />; const RefableAnchor = React.forwardRef<HTMLAnchorElement, WithStyles<typeof styles>>( (props, ref) => { const { classes } = props; return <a className={classes.root} />; }, ); const StyledRefableAnchor = withStyles(styles)(RefableAnchor); <StyledRefableAnchor ref={anchorRef} />; const buttonRef = React.createRef<HTMLButtonElement>(); // HTMLButtonElement is missing properties <StyledRefableAnchor ref={buttonRef} />; // $ExpectError // undesired: `innerRef` is currently typed as any but for backwards compat we're keeping it // especially since `innerRef` will be removed in v5 and is equivalent to `ref` <StyledRefableAnchor innerRef={buttonRef} />; } { // https://github.com/mui-org/material-ui/pull/15546 // Update type definition to let CSS properties be functions interface testProps { foo: boolean; } const useStyles = makeStyles((theme: Theme) => ({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), height: 100, }), })); const styles = useStyles({ foo: true }); // $ExpectType string const root = styles.root; // $ExpectType string const root2 = styles.root2; } { // If there are no props, use the definition that doesn't accept them // https://github.com/mui-org/material-ui/issues/16198 // $ExpectType Record<"root", CSSProperties | (() => CSSProperties)> const styles = createStyles({ root: { width: 1, }, }); // $ExpectType Record<"root", CSSProperties | (() => CSSProperties)> const styles2 = createStyles({ root: () => ({ width: 1, }), }); interface testProps { foo: boolean; } // $ExpectType Record<"root", CreateCSSProperties<testProps> | ((props: testProps) => CreateCSSProperties<testProps>)> const styles3 = createStyles({ root: (props: testProps) => ({ width: 1, }), }); }
packages/material-ui-styles/test/styles.spec.tsx
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.9989660978317261, 0.20085741579532623, 0.00016716921527404338, 0.00023948127636685967, 0.39455580711364746 ]
{ "id": 1, "code_window": [ "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n", " innerRef?: React.Ref<any>;\n", "}\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 14 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-8 7c-.55 0-1 .45-1 1v3c0 1.1.9 2 2 2h3c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1-.45-1-1v-2c0-.55-.45-1-1-1zm1-9c0-.55.45-1 1-1h2c.55 0 1-.45 1-1s-.45-1-1-1H5c-1.1 0-2 .9-2 2v3c0 .55.45 1 1 1s1-.45 1-1V6zm14-3h-3c-.55 0-1 .45-1 1s.45 1 1 1h2c.55 0 1 .45 1 1v2c0 .55.45 1 1 1s1-.45 1-1V5c0-1.1-.9-2-2-2zm0 15c0 .55-.45 1-1 1h-2c-.55 0-1 .45-1 1s.45 1 1 1h3c1.1 0 2-.9 2-2v-3c0-.55-.45-1-1-1s-1 .45-1 1v2z" /> , 'CenterFocusStrongRounded');
packages/material-ui-icons/src/CenterFocusStrongRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016561818483751267, 0.00016561818483751267, 0.00016561818483751267, 0.00016561818483751267, 0 ]
{ "id": 1, "code_window": [ "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n", " innerRef?: React.Ref<any>;\n", "}\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 14 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12 2C8.13 2 5 5.13 5 9c0 4.17 4.42 9.92 6.24 12.11.4.48 1.13.48 1.53 0C14.58 18.92 19 13.17 19 9c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" /></React.Fragment> , 'PlaceRounded');
packages/material-ui-icons/legacy/PlaceRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016882119234651327, 0.00016882119234651327, 0.00016882119234651327, 0.00016882119234651327, 0 ]
{ "id": 1, "code_window": [ "export interface WithTheme<Theme = DefaultTheme> {\n", " theme: Theme;\n", " innerRef?: React.Ref<any>;\n", "}\n", "\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 14 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15 16h3c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1h-3c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1zm1-6h1v4h-1v-4zm-7 6h3c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1H9c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1zm1-6h1v4h-1v-4zM5 8h2v8H5zM2 4v16h20V4H2zm18 14H4V6h16v12z" /> , 'MoneyOutlined');
packages/material-ui-icons/src/MoneyOutlined.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016765993495937437, 0.00016765993495937437, 0.00016765993495937437, 0.00016765993495937437, 0 ]
{ "id": 2, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "export default function withTheme<\n", " Theme,\n", " C extends React.ComponentType<ConsistentWith<React.ComponentProps<C>, WithTheme<Theme>>>\n", ">(\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " ref?: React.Ref<unknown>;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, ThemedComponentProps>;\n", "\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 17 }
import { Theme } from './createMuiTheme'; import { PropInjector } from '@material-ui/types'; export interface WithTheme { theme: Theme; } export interface ThemedComponentProps extends Partial<WithTheme> { innerRef?: React.Ref<any>; } declare const withTheme: PropInjector<WithTheme, ThemedComponentProps>; export default withTheme;
packages/material-ui/src/styles/withTheme.d.ts
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.9951099753379822, 0.5004420876502991, 0.0057742176577448845, 0.5004420876502991, 0.4946678578853607 ]
{ "id": 2, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "export default function withTheme<\n", " Theme,\n", " C extends React.ComponentType<ConsistentWith<React.ComponentProps<C>, WithTheme<Theme>>>\n", ">(\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " ref?: React.Ref<unknown>;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, ThemedComponentProps>;\n", "\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 17 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M5.58 16.89l5.77-4.07c.56-.4.56-1.24 0-1.63L5.58 7.11C4.91 6.65 4 7.12 4 7.93v8.14c0 .81.91 1.28 1.58.82zM13 7.93v8.14c0 .81.91 1.28 1.58.82l5.77-4.07c.56-.4.56-1.24 0-1.63l-5.77-4.07c-.67-.47-1.58 0-1.58.81z" /> , 'FastForwardRounded');
packages/material-ui-icons/src/FastForwardRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0001662017748458311, 0.0001662017748458311, 0.0001662017748458311, 0.0001662017748458311, 0 ]
{ "id": 2, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "export default function withTheme<\n", " Theme,\n", " C extends React.ComponentType<ConsistentWith<React.ComponentProps<C>, WithTheme<Theme>>>\n", ">(\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " ref?: React.Ref<unknown>;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, ThemedComponentProps>;\n", "\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 17 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z" /> , 'Accessibility');
packages/material-ui-icons/src/Accessibility.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016742573643568903, 0.00016742573643568903, 0.00016742573643568903, 0.00016742573643568903, 0 ]
{ "id": 2, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "export default function withTheme<\n", " Theme,\n", " C extends React.ComponentType<ConsistentWith<React.ComponentProps<C>, WithTheme<Theme>>>\n", ">(\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " ref?: React.Ref<unknown>;\n", "}\n", "\n", "export function withThemeCreator<Theme = DefaultTheme>(\n", " option?: WithThemeCreatorOption<Theme>,\n", "): PropInjector<WithTheme<Theme>, ThemedComponentProps>;\n", "\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "add", "edit_start_line_idx": 17 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5l4-4 4 4 6-6v6zm0-8.5l-6 6-4-4-4 4V5h14v5.5zM13.5 9V6H12v6h1.5zm3.7 3l-2-3 2-3h-1.7l-2 3 2 3zM11 10.5H8.5v-.75H11V6H7v1.5h2.5v.75H7V12h4z" /> , 'ScoreOutlined');
packages/material-ui-icons/src/ScoreOutlined.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016605744895059615, 0.00016605744895059615, 0.00016605744895059615, 0.00016605744895059615, 0 ]
{ "id": 3, "code_window": [ ">(\n", " component: C,\n", "): React.ComponentType<\n", " Omit<JSX.LibraryManagedAttributes<C, React.ComponentProps<C>>, keyof WithTheme<Theme>> &\n", " Partial<WithTheme<Theme>>\n", ">;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " Partial<WithTheme<Theme>> &\n", " ThemedComponentProps\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 24 }
import * as React from 'react'; import { createStyles, withStyles, createMuiTheme, Theme, withTheme, StyleRulesCallback, WithStyles, WithTheme, makeStyles, styled, } from '@material-ui/core/styles'; import { ThemeProvider } from '@material-ui/styles'; import Button from '@material-ui/core/Button'; import { blue } from '@material-ui/core/colors'; // Shared types for examples interface ComponentProps extends WithStyles<typeof styles> { text: string; } // Example 1 const styles = ({ palette, spacing }: Theme) => ({ root: { padding: spacing(1), backgroundColor: palette.background.default, color: palette.primary.dark, }, }); const StyledExampleOne = withStyles(styles)(({ classes, text }: ComponentProps) => ( <div className={classes.root}>{text}</div> )); <StyledExampleOne text="I am styled!" />; // Example 2 const Component: React.FunctionComponent<ComponentProps & WithStyles<typeof styles>> = ({ classes, text, }) => <div className={classes.root}>{text}</div>; const StyledExampleTwo = withStyles(styles)(Component); <StyledExampleTwo text="I am styled!" />; // Example 3 const styleRule = createStyles({ root: { display: 'flex', alignItems: 'stretch', height: '100vh', width: '100%', }, }); const ComponentWithChildren: React.FunctionComponent<WithStyles<typeof styles>> = ({ classes, children, }) => <div className={classes.root}>{children}</div>; const StyledExampleThree = withStyles(styleRule)(ComponentWithChildren); <StyledExampleThree />; // Also works with a plain object const stylesAsPojo = { root: { backgroundColor: 'hotpink', }, }; const AnotherStyledSFC = withStyles({ root: { backgroundColor: 'hotpink' }, })(({ classes }: WithStyles<'root'>) => <div className={classes.root}>Stylish!</div>); // Overriding styles const theme = createMuiTheme({ palette: { type: 'dark', primary: blue, contrastThreshold: 3, tonalOffset: 0.2, common: { white: '#ffffff', }, }, typography: { h1: { fontSize: 24, }, fontSize: 18, }, mixins: { toolbar: { backgroundColor: 'red', }, }, breakpoints: { step: 3, }, transitions: { duration: { short: 50, }, }, spacing: 5, zIndex: { appBar: 42, }, overrides: { MuiButton: { // Name of the styleSheet root: { // Name of the rule background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }, }, }, props: { MuiButton: { disabled: true, }, MuiAppBar: { position: 'fixed', }, }, }); const theme2 = createMuiTheme({ palette: { primary: { main: blue[500], }, }, props: { MuiButton: { disabled: false, TouchRippleProps: { center: true, }, }, MuiTable: { cellPadding: 12, }, MuiButtonBase: { disableRipple: true, }, }, }); const t1: number = createMuiTheme().spacing(1); const t2: string = createMuiTheme().spacing(1, 2); const t3: string = createMuiTheme().spacing(1, 2, 3); const t4: string = createMuiTheme().spacing(1, 2, 3, 4); // $ExpectError const t5 = createMuiTheme().spacing(1, 2, 3, 4, 5); function OverridesTheme() { return ( <ThemeProvider theme={theme}> <Button>{'Overrides'}</Button> </ThemeProvider> ); } // withTheme const ComponentWithTheme = withTheme(({ theme }: WithTheme) => <div>{theme.spacing(1)}</div>); <ComponentWithTheme />; // withStyles + withTheme type AllTheProps = WithTheme & WithStyles<typeof styles>; const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => ( <div className={classes.root}>{theme.palette.text.primary}</div> )); // missing prop theme <StyledComponent />; // $ExpectError const AllTheComposition = withTheme(StyledComponent); <AllTheComposition />; { const Foo = withTheme( class extends React.Component<WithTheme> { render() { return null; } }, ); <Foo />; } declare const themed: boolean; { // Test that withTheme: true guarantees the presence of the theme const Foo = withStyles({}, { withTheme: true })( class extends React.Component<WithTheme> { hasRef() { // innerRef does not exists, originally caused https://github.com/mui-org/material-ui/issues/14095 return Boolean(this.props.innerRef); // $ExpectError } render() { return <div style={{ margin: this.props.theme.spacing(1) }} />; } }, ); <Foo />; const Bar = withStyles({}, { withTheme: true })(({ theme }: WithStyles<string, true>) => ( <div style={{ margin: theme.spacing(1) }} /> )); <Bar />; } // Can't use withStyles effectively as a decorator in TypeScript // due to https://github.com/Microsoft/TypeScript/issues/4881 // @withStyles(styles) const DecoratedComponent = withStyles(styles)( class extends React.Component<ComponentProps & WithStyles<typeof styles>> { render() { const { classes, text } = this.props; return <div className={classes.root}>{text}</div>; } }, ); // no 'classes' property required at element creation time (#8267) <DecoratedComponent text="foo" />; // Allow nested pseudo selectors withStyles(theme => createStyles({ guttered: { '&:hover': { textDecoration: 'none', }, }, listItem: { '&:hover $listItemIcon': { visibility: 'inherit', }, }, }), ); { // allow top level media queries // https://github.com/mui-org/material-ui/issues/12277 // typescript thinks `content` is the CSS property not a classname const ambiguousStyles = createStyles({ content: { minHeight: '100vh', }, // $ExpectError '@media (min-width: 960px)': { content: { display: 'flex', }, }, }); const styles = createStyles({ contentClass: { minHeight: '100vh', }, '@media (min-width: 960px)': { contentClass: { display: 'flex', }, }, }); } { const styles = (theme: Theme) => createStyles({ // Styled similar to ListItemText root: { '&:first-child': { paddingLeft: 0, }, flex: '1 1 auto', padding: '0 16px', }, inset: { '&:first-child': { paddingLeft: theme.spacing(7), }, }, row: { alignItems: 'center', display: 'flex', flexDirection: 'row', }, }); interface ListItemContentProps extends WithStyles<typeof styles> { children?: React.ReactElement; inset?: boolean; row?: boolean; } const ListItemContent = withStyles(styles, { name: 'ui-ListItemContent' })( ({ children, classes, inset, row }: ListItemContentProps) => ( <div className={classes.root} color="textSecondary"> {children} </div> ), ); } { interface FooProps extends WithStyles<'x' | 'y'> { a: number; b: boolean; } const ListItemContent = withStyles({ x: {}, y: {} })((props: FooProps) => <div />); } { // https://github.com/mui-org/material-ui/issues/11109 // The real test here is with "strictFunctionTypes": false, // but we don't have a way currently to test under varying // TypeScript configurations. interface ComponentProps extends WithStyles<typeof styles> { caption: string; } const styles = (theme: Theme) => createStyles({ content: { margin: 4, }, }); const Component = (props: ComponentProps) => { return <div className={props.classes.content}>Hello {props.caption}</div>; }; const StyledComponent = withStyles(styles)(Component); class App extends React.Component { render() { return ( <div className="App"> <StyledComponent caption="Developer" /> </div> ); } } <App />; } { // https://github.com/mui-org/material-ui/issues/11191 const styles = (theme: Theme) => createStyles({ main: {}, }); interface Props extends WithStyles<typeof styles> { someProp?: string; } class SomeComponent extends React.PureComponent<Props> { render() { return <div />; } } const DecoratedSomeComponent = withStyles(styles)(SomeComponent); <DecoratedSomeComponent someProp="hello world" />; } { // https://github.com/mui-org/material-ui/issues/11312 withStyles(styles, { name: 'MyComponent', index: 0 })(() => <div />); } { // https://github.com/mui-org/material-ui/issues/11164 const style: StyleRulesCallback<Theme, any, any> = theme => ({ text: theme.typography.body2, }); } { // can't provide own `classes` type interface Props { classes: number; } class Component extends React.Component<Props & WithStyles<typeof styles>> {} // $ExpectError const StyledComponent = withStyles(styles)(Component); // implicit FunctionComponent withStyles(styles)((props: Props) => null); // $ExpectError withStyles(styles)((props: Props & WithStyles<typeof styles>) => null); // $ExpectError withStyles(styles)((props: Props & { children?: React.ReactNode }) => null); // $ExpectError withStyles(styles)( (props: Props & WithStyles<typeof styles> & { children?: React.ReactNode }) => null, // $ExpectError ); // explicit not but with "Property 'children' is missing in type 'ValidationMap<Props>'". // which is not helpful const StatelessComponent: React.FunctionComponent<Props> = props => null; const StatelessComponentWithStyles: React.FunctionComponent< Props & WithStyles<typeof styles> > = props => null; withStyles(styles)(StatelessComponent); // $ExpectError withStyles(styles)(StatelessComponentWithStyles); // $ExpectError } { // https://github.com/mui-org/material-ui/issues/12670 interface Props { nonDefaulted: string; defaulted: number; } class MyButton extends React.Component<Props & WithStyles<typeof styles>> { static defaultProps = { defaulted: 0, }; render() { const { classes, nonDefaulted, defaulted } = this.props; return ( <Button className={classes.btn}> {defaulted}, {nonDefaulted} </Button> ); } } const styles = () => createStyles({ btn: { color: 'red', }, }); const StyledMyButton = withStyles(styles)(MyButton); const CorrectUsage = () => <StyledMyButton nonDefaulted="2" />; // Property 'nonDefaulted' is missing in type '{}' const MissingPropUsage = () => <StyledMyButton />; // $ExpectError } { // theme is defaulted to type of Theme const useStyles = makeStyles(theme => { // $ExpectType Theme const t = theme; return { root: { margin: t.spacing(1), }, }; }); } { // https://github.com/mui-org/material-ui/pull/15546 // Update type definition to let CSS properties be functions interface testProps { foo: boolean; } // makeStyles accepts properties as functions { const useStyles = makeStyles({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), }), }); const styles = useStyles({ foo: true }); // $ExpectType string const root = styles.root; // $ExpectType string const root2 = styles.root2; } // makeStyles accepts properties as functions using a callback { const useStyles = makeStyles(theme => ({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), margin: theme.spacing(1), }), })); const styles = useStyles({ foo: true }); // $ExpectType string const root = styles.root; // $ExpectType string const root2 = styles.root2; } // createStyles accepts properties as functions { const styles = createStyles({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), }), }); // $ExpectType string const root = makeStyles(styles)({ foo: true }).root; } // withStyles accepts properties as functions { withStyles({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), margin: 8, }), }); } // withStyles accepts properties as functions using a callback { withStyles(theme => ({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), height: theme.spacing(1), }), })); } } { // Make theme property on styled components optional // https://github.com/mui-org/material-ui/issues/16379#issuecomment-507209971 const style = (props: { value: number }) => ({}); const styleWithTheme = (props: { value: number; theme: Theme }) => ({}); const Component: React.FC = () => null; const ComponentWithTheme: React.FC<{ theme: { zIndex: { [k: string]: number } } }> = () => null; const ComponentStyled = styled(Component)(style); const ComponentStyledWithTheme = styled(Component)(styleWithTheme); const ComponentWithThemeStyled = styled(ComponentWithTheme)(style); const ComponentWithThemeStyledWithTheme = styled(ComponentWithTheme)(styleWithTheme); // prop 'theme' must not be required <ComponentStyled value={1} />; <ComponentStyledWithTheme value={1} />; // error: type {} is missing properties from 'Theme' ... <ComponentStyledWithTheme value={1} theme={{}} />; // $ExpectError // error: property 'theme' is missing in type ... (because the component requires it) <ComponentWithThemeStyled value={1} />; // $ExpectError <ComponentWithThemeStyledWithTheme value={1} />; // $ExpectError // error: type {} is not assignable to type ... <ComponentWithThemeStyledWithTheme value={1} theme={{}} />; // $ExpectError // error: missing properties from type 'ZIndex' ... <ComponentWithThemeStyledWithTheme value={1} theme={{ zIndex: { appBar: 100 } }} />; // $ExpectError const ComponentWithOptionalTheme: React.FC<{ theme?: { zIndex: { [k: string]: number } }; }> = () => null; const ComponentWithOptionalThemeStyledWithTheme = styled(ComponentWithOptionalTheme)( styleWithTheme, ); // prop 'theme' must not be required <ComponentWithOptionalThemeStyledWithTheme value={1} />; // error: property 'zIndex' is missing in type {} <ComponentWithOptionalThemeStyledWithTheme value={1} theme={{}} />; // $ExpectError // error: missing properties from type 'Theme' ... <ComponentWithOptionalThemeStyledWithTheme value={1} theme={{ zIndex: { appBar: 100 } }} />; // $ExpectError } { // Make sure theme and props have the correct types // https://github.com/mui-org/material-ui/issues/16351 // Theme has default type styled(Button)(({ theme }) => { // $ExpectType Theme theme; return { padding: theme.spacing(1) }; }); interface myProps { testValue: boolean; } // Type of props follow all the way to css properties styled(Button)<Theme, myProps>(({ theme, testValue }) => { // $ExpectType Theme theme; // $ExpectType boolean testValue; return { padding: props => { // $ExpectType myProps props; // $ExpectType boolean props.testValue; return theme.spacing(1); }, }; }); }
packages/material-ui/test/typescript/styles.spec.tsx
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.022940820083022118, 0.001233682851307094, 0.00016529098502360284, 0.00025080007617361844, 0.003049984108656645 ]
{ "id": 3, "code_window": [ ">(\n", " component: C,\n", "): React.ComponentType<\n", " Omit<JSX.LibraryManagedAttributes<C, React.ComponentProps<C>>, keyof WithTheme<Theme>> &\n", " Partial<WithTheme<Theme>>\n", ">;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " Partial<WithTheme<Theme>> &\n", " ThemedComponentProps\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 24 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z" /> , 'Security');
packages/material-ui-icons/src/Security.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0001682365982560441, 0.0001682365982560441, 0.0001682365982560441, 0.0001682365982560441, 0 ]
{ "id": 3, "code_window": [ ">(\n", " component: C,\n", "): React.ComponentType<\n", " Omit<JSX.LibraryManagedAttributes<C, React.ComponentProps<C>>, keyof WithTheme<Theme>> &\n", " Partial<WithTheme<Theme>>\n", ">;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " Partial<WithTheme<Theme>> &\n", " ThemedComponentProps\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 24 }
export { default } from './Popper';
packages/material-ui/src/Popper/index.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017317221499979496, 0.00017317221499979496, 0.00017317221499979496, 0.00017317221499979496, 0 ]
{ "id": 3, "code_window": [ ">(\n", " component: C,\n", "): React.ComponentType<\n", " Omit<JSX.LibraryManagedAttributes<C, React.ComponentProps<C>>, keyof WithTheme<Theme>> &\n", " Partial<WithTheme<Theme>>\n", ">;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " Partial<WithTheme<Theme>> &\n", " ThemedComponentProps\n" ], "file_path": "packages/material-ui-styles/src/withTheme/withTheme.d.ts", "type": "replace", "edit_start_line_idx": 24 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M22.41 12L12 1.59 1.59 11.99 12 22.41 22.41 12zM14 14.5V12h-4v3H8v-5h6V7.5l3.5 3.5-3.5 3.5z" /> , 'DirectionsSharp');
packages/material-ui-icons/src/DirectionsSharp.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0001694902457529679, 0.0001694902457529679, 0.0001694902457529679, 0.0001694902457529679, 0 ]
{ "id": 4, "code_window": [ "const ComponentWithTheme = withTheme<Theme, React.FunctionComponent<WithTheme<Theme>>>(\n", " ({ theme }: WithTheme<Theme>) => <div>{theme.spacing(1)}</div>,\n", ");\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme<Theme> & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui-styles/test/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 74 }
import * as React from 'react'; import { ConsistentWith, Omit, PropInjector } from '@material-ui/types'; import { DefaultTheme } from '../defaultTheme'; export interface WithThemeCreatorOption<Theme = DefaultTheme> { defaultTheme?: Theme; } export function withThemeCreator<Theme = DefaultTheme>( option?: WithThemeCreatorOption<Theme>, ): PropInjector<WithTheme<Theme>, Partial<WithTheme<Theme>>>; export interface WithTheme<Theme = DefaultTheme> { theme: Theme; innerRef?: React.Ref<any>; } export default function withTheme< Theme, C extends React.ComponentType<ConsistentWith<React.ComponentProps<C>, WithTheme<Theme>>> >( component: C, ): React.ComponentType< Omit<JSX.LibraryManagedAttributes<C, React.ComponentProps<C>>, keyof WithTheme<Theme>> & Partial<WithTheme<Theme>> >;
packages/material-ui-styles/src/withTheme/withTheme.d.ts
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.012159008532762527, 0.006440611090511084, 0.002940207486972213, 0.004222617484629154, 0.004077269695699215 ]
{ "id": 4, "code_window": [ "const ComponentWithTheme = withTheme<Theme, React.FunctionComponent<WithTheme<Theme>>>(\n", " ({ theme }: WithTheme<Theme>) => <div>{theme.spacing(1)}</div>,\n", ");\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme<Theme> & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui-styles/test/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 74 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19.77 4.93l1.4 1.4L8.43 19.07l-5.6-5.6 1.4-1.4 4.2 4.2L19.77 4.93m0-2.83L8.43 13.44l-4.2-4.2L0 13.47l8.43 8.43L24 6.33 19.77 2.1z" /> , 'DoneOutlineTwoTone');
packages/material-ui-icons/src/DoneOutlineTwoTone.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017790045239962637, 0.00017790045239962637, 0.00017790045239962637, 0.00017790045239962637, 0 ]
{ "id": 4, "code_window": [ "const ComponentWithTheme = withTheme<Theme, React.FunctionComponent<WithTheme<Theme>>>(\n", " ({ theme }: WithTheme<Theme>) => <div>{theme.spacing(1)}</div>,\n", ");\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme<Theme> & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui-styles/test/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 74 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 10H5V8c0-.55-.45-1-1-1s-1 .45-1 1v2H1c-.55 0-1 .45-1 1s.45 1 1 1h2v2c0 .55.45 1 1 1s1-.45 1-1v-2h2c.55 0 1-.45 1-1s-.45-1-1-1zm11 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5s-3 1.34-3 3 1.34 3 3 3zm0 2c-2 0-6 1-6 3v1c0 .55.45 1 1 1h10c.55 0 1-.45 1-1v-1c0-2-4-3-6-3zm6.62.16c.83.73 1.38 1.66 1.38 2.84v1.5c0 .17-.02.34-.05.5h2.55c.28 0 .5-.22.5-.5V16c0-1.54-2.37-2.49-4.38-2.84z" /> , 'GroupAddRounded');
packages/material-ui-icons/src/GroupAddRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016413989942520857, 0.00016413989942520857, 0.00016413989942520857, 0.00016413989942520857, 0 ]
{ "id": 4, "code_window": [ "const ComponentWithTheme = withTheme<Theme, React.FunctionComponent<WithTheme<Theme>>>(\n", " ({ theme }: WithTheme<Theme>) => <div>{theme.spacing(1)}</div>,\n", ");\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme<Theme> & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui-styles/test/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 74 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 3H3v18h18V3zm-2 16H5V5h14v14z" /> , 'CropDinSharp');
packages/material-ui-icons/src/CropDinSharp.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0001782425824785605, 0.0001782425824785605, 0.0001782425824785605, 0.0001782425824785605, 0 ]
{ "id": 5, "code_window": [ " theme: Theme;\n", "}\n", "\n", "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " innerRef?: React.Ref<any>;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 8 }
import * as React from 'react'; import { ConsistentWith, Omit, PropInjector } from '@material-ui/types'; import { DefaultTheme } from '../defaultTheme'; export interface WithThemeCreatorOption<Theme = DefaultTheme> { defaultTheme?: Theme; } export function withThemeCreator<Theme = DefaultTheme>( option?: WithThemeCreatorOption<Theme>, ): PropInjector<WithTheme<Theme>, Partial<WithTheme<Theme>>>; export interface WithTheme<Theme = DefaultTheme> { theme: Theme; innerRef?: React.Ref<any>; } export default function withTheme< Theme, C extends React.ComponentType<ConsistentWith<React.ComponentProps<C>, WithTheme<Theme>>> >( component: C, ): React.ComponentType< Omit<JSX.LibraryManagedAttributes<C, React.ComponentProps<C>>, keyof WithTheme<Theme>> & Partial<WithTheme<Theme>> >;
packages/material-ui-styles/src/withTheme/withTheme.d.ts
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.9584499597549438, 0.3274376094341278, 0.0011597416596487164, 0.022703077644109726, 0.4462797939777374 ]
{ "id": 5, "code_window": [ " theme: Theme;\n", "}\n", "\n", "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " innerRef?: React.Ref<any>;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 8 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M10 16.5l6-4.5-6-4.5zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /> , 'PlayCircleOutlineOutlined');
packages/material-ui-icons/src/PlayCircleOutlineOutlined.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016981700900942087, 0.00016981700900942087, 0.00016981700900942087, 0.00016981700900942087, 0 ]
{ "id": 5, "code_window": [ " theme: Theme;\n", "}\n", "\n", "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " innerRef?: React.Ref<any>;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 8 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z" /> , 'SkipNext');
packages/material-ui-icons/src/SkipNext.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0001699590648058802, 0.0001699590648058802, 0.0001699590648058802, 0.0001699590648058802, 0 ]
{ "id": 5, "code_window": [ " theme: Theme;\n", "}\n", "\n", "export interface ThemedComponentProps extends Partial<WithTheme> {\n", " innerRef?: React.Ref<any>;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " /**\n", " * Deprecated. Will be removed in v5. Refs are now automatically forwarded to\n", " * the inner component.\n", " * @deprecated since version 4.0\n", " */\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 8 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14zm-1-6h-3V8h-2v5H8l4 4 4-4z" /> , 'SystemUpdate');
packages/material-ui-icons/src/SystemUpdate.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00016953679732978344, 0.00016953679732978344, 0.00016953679732978344, 0.00016953679732978344, 0 ]
{ "id": 6, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "declare const withTheme: PropInjector<WithTheme, ThemedComponentProps>;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " ref?: React.Ref<unknown>;\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 9 }
import * as React from 'react'; import { createStyles, withStyles, createMuiTheme, Theme, withTheme, StyleRulesCallback, WithStyles, WithTheme, makeStyles, styled, } from '@material-ui/core/styles'; import { ThemeProvider } from '@material-ui/styles'; import Button from '@material-ui/core/Button'; import { blue } from '@material-ui/core/colors'; // Shared types for examples interface ComponentProps extends WithStyles<typeof styles> { text: string; } // Example 1 const styles = ({ palette, spacing }: Theme) => ({ root: { padding: spacing(1), backgroundColor: palette.background.default, color: palette.primary.dark, }, }); const StyledExampleOne = withStyles(styles)(({ classes, text }: ComponentProps) => ( <div className={classes.root}>{text}</div> )); <StyledExampleOne text="I am styled!" />; // Example 2 const Component: React.FunctionComponent<ComponentProps & WithStyles<typeof styles>> = ({ classes, text, }) => <div className={classes.root}>{text}</div>; const StyledExampleTwo = withStyles(styles)(Component); <StyledExampleTwo text="I am styled!" />; // Example 3 const styleRule = createStyles({ root: { display: 'flex', alignItems: 'stretch', height: '100vh', width: '100%', }, }); const ComponentWithChildren: React.FunctionComponent<WithStyles<typeof styles>> = ({ classes, children, }) => <div className={classes.root}>{children}</div>; const StyledExampleThree = withStyles(styleRule)(ComponentWithChildren); <StyledExampleThree />; // Also works with a plain object const stylesAsPojo = { root: { backgroundColor: 'hotpink', }, }; const AnotherStyledSFC = withStyles({ root: { backgroundColor: 'hotpink' }, })(({ classes }: WithStyles<'root'>) => <div className={classes.root}>Stylish!</div>); // Overriding styles const theme = createMuiTheme({ palette: { type: 'dark', primary: blue, contrastThreshold: 3, tonalOffset: 0.2, common: { white: '#ffffff', }, }, typography: { h1: { fontSize: 24, }, fontSize: 18, }, mixins: { toolbar: { backgroundColor: 'red', }, }, breakpoints: { step: 3, }, transitions: { duration: { short: 50, }, }, spacing: 5, zIndex: { appBar: 42, }, overrides: { MuiButton: { // Name of the styleSheet root: { // Name of the rule background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }, }, }, props: { MuiButton: { disabled: true, }, MuiAppBar: { position: 'fixed', }, }, }); const theme2 = createMuiTheme({ palette: { primary: { main: blue[500], }, }, props: { MuiButton: { disabled: false, TouchRippleProps: { center: true, }, }, MuiTable: { cellPadding: 12, }, MuiButtonBase: { disableRipple: true, }, }, }); const t1: number = createMuiTheme().spacing(1); const t2: string = createMuiTheme().spacing(1, 2); const t3: string = createMuiTheme().spacing(1, 2, 3); const t4: string = createMuiTheme().spacing(1, 2, 3, 4); // $ExpectError const t5 = createMuiTheme().spacing(1, 2, 3, 4, 5); function OverridesTheme() { return ( <ThemeProvider theme={theme}> <Button>{'Overrides'}</Button> </ThemeProvider> ); } // withTheme const ComponentWithTheme = withTheme(({ theme }: WithTheme) => <div>{theme.spacing(1)}</div>); <ComponentWithTheme />; // withStyles + withTheme type AllTheProps = WithTheme & WithStyles<typeof styles>; const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => ( <div className={classes.root}>{theme.palette.text.primary}</div> )); // missing prop theme <StyledComponent />; // $ExpectError const AllTheComposition = withTheme(StyledComponent); <AllTheComposition />; { const Foo = withTheme( class extends React.Component<WithTheme> { render() { return null; } }, ); <Foo />; } declare const themed: boolean; { // Test that withTheme: true guarantees the presence of the theme const Foo = withStyles({}, { withTheme: true })( class extends React.Component<WithTheme> { hasRef() { // innerRef does not exists, originally caused https://github.com/mui-org/material-ui/issues/14095 return Boolean(this.props.innerRef); // $ExpectError } render() { return <div style={{ margin: this.props.theme.spacing(1) }} />; } }, ); <Foo />; const Bar = withStyles({}, { withTheme: true })(({ theme }: WithStyles<string, true>) => ( <div style={{ margin: theme.spacing(1) }} /> )); <Bar />; } // Can't use withStyles effectively as a decorator in TypeScript // due to https://github.com/Microsoft/TypeScript/issues/4881 // @withStyles(styles) const DecoratedComponent = withStyles(styles)( class extends React.Component<ComponentProps & WithStyles<typeof styles>> { render() { const { classes, text } = this.props; return <div className={classes.root}>{text}</div>; } }, ); // no 'classes' property required at element creation time (#8267) <DecoratedComponent text="foo" />; // Allow nested pseudo selectors withStyles(theme => createStyles({ guttered: { '&:hover': { textDecoration: 'none', }, }, listItem: { '&:hover $listItemIcon': { visibility: 'inherit', }, }, }), ); { // allow top level media queries // https://github.com/mui-org/material-ui/issues/12277 // typescript thinks `content` is the CSS property not a classname const ambiguousStyles = createStyles({ content: { minHeight: '100vh', }, // $ExpectError '@media (min-width: 960px)': { content: { display: 'flex', }, }, }); const styles = createStyles({ contentClass: { minHeight: '100vh', }, '@media (min-width: 960px)': { contentClass: { display: 'flex', }, }, }); } { const styles = (theme: Theme) => createStyles({ // Styled similar to ListItemText root: { '&:first-child': { paddingLeft: 0, }, flex: '1 1 auto', padding: '0 16px', }, inset: { '&:first-child': { paddingLeft: theme.spacing(7), }, }, row: { alignItems: 'center', display: 'flex', flexDirection: 'row', }, }); interface ListItemContentProps extends WithStyles<typeof styles> { children?: React.ReactElement; inset?: boolean; row?: boolean; } const ListItemContent = withStyles(styles, { name: 'ui-ListItemContent' })( ({ children, classes, inset, row }: ListItemContentProps) => ( <div className={classes.root} color="textSecondary"> {children} </div> ), ); } { interface FooProps extends WithStyles<'x' | 'y'> { a: number; b: boolean; } const ListItemContent = withStyles({ x: {}, y: {} })((props: FooProps) => <div />); } { // https://github.com/mui-org/material-ui/issues/11109 // The real test here is with "strictFunctionTypes": false, // but we don't have a way currently to test under varying // TypeScript configurations. interface ComponentProps extends WithStyles<typeof styles> { caption: string; } const styles = (theme: Theme) => createStyles({ content: { margin: 4, }, }); const Component = (props: ComponentProps) => { return <div className={props.classes.content}>Hello {props.caption}</div>; }; const StyledComponent = withStyles(styles)(Component); class App extends React.Component { render() { return ( <div className="App"> <StyledComponent caption="Developer" /> </div> ); } } <App />; } { // https://github.com/mui-org/material-ui/issues/11191 const styles = (theme: Theme) => createStyles({ main: {}, }); interface Props extends WithStyles<typeof styles> { someProp?: string; } class SomeComponent extends React.PureComponent<Props> { render() { return <div />; } } const DecoratedSomeComponent = withStyles(styles)(SomeComponent); <DecoratedSomeComponent someProp="hello world" />; } { // https://github.com/mui-org/material-ui/issues/11312 withStyles(styles, { name: 'MyComponent', index: 0 })(() => <div />); } { // https://github.com/mui-org/material-ui/issues/11164 const style: StyleRulesCallback<Theme, any, any> = theme => ({ text: theme.typography.body2, }); } { // can't provide own `classes` type interface Props { classes: number; } class Component extends React.Component<Props & WithStyles<typeof styles>> {} // $ExpectError const StyledComponent = withStyles(styles)(Component); // implicit FunctionComponent withStyles(styles)((props: Props) => null); // $ExpectError withStyles(styles)((props: Props & WithStyles<typeof styles>) => null); // $ExpectError withStyles(styles)((props: Props & { children?: React.ReactNode }) => null); // $ExpectError withStyles(styles)( (props: Props & WithStyles<typeof styles> & { children?: React.ReactNode }) => null, // $ExpectError ); // explicit not but with "Property 'children' is missing in type 'ValidationMap<Props>'". // which is not helpful const StatelessComponent: React.FunctionComponent<Props> = props => null; const StatelessComponentWithStyles: React.FunctionComponent< Props & WithStyles<typeof styles> > = props => null; withStyles(styles)(StatelessComponent); // $ExpectError withStyles(styles)(StatelessComponentWithStyles); // $ExpectError } { // https://github.com/mui-org/material-ui/issues/12670 interface Props { nonDefaulted: string; defaulted: number; } class MyButton extends React.Component<Props & WithStyles<typeof styles>> { static defaultProps = { defaulted: 0, }; render() { const { classes, nonDefaulted, defaulted } = this.props; return ( <Button className={classes.btn}> {defaulted}, {nonDefaulted} </Button> ); } } const styles = () => createStyles({ btn: { color: 'red', }, }); const StyledMyButton = withStyles(styles)(MyButton); const CorrectUsage = () => <StyledMyButton nonDefaulted="2" />; // Property 'nonDefaulted' is missing in type '{}' const MissingPropUsage = () => <StyledMyButton />; // $ExpectError } { // theme is defaulted to type of Theme const useStyles = makeStyles(theme => { // $ExpectType Theme const t = theme; return { root: { margin: t.spacing(1), }, }; }); } { // https://github.com/mui-org/material-ui/pull/15546 // Update type definition to let CSS properties be functions interface testProps { foo: boolean; } // makeStyles accepts properties as functions { const useStyles = makeStyles({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), }), }); const styles = useStyles({ foo: true }); // $ExpectType string const root = styles.root; // $ExpectType string const root2 = styles.root2; } // makeStyles accepts properties as functions using a callback { const useStyles = makeStyles(theme => ({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), margin: theme.spacing(1), }), })); const styles = useStyles({ foo: true }); // $ExpectType string const root = styles.root; // $ExpectType string const root2 = styles.root2; } // createStyles accepts properties as functions { const styles = createStyles({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), }), }); // $ExpectType string const root = makeStyles(styles)({ foo: true }).root; } // withStyles accepts properties as functions { withStyles({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), margin: 8, }), }); } // withStyles accepts properties as functions using a callback { withStyles(theme => ({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), height: theme.spacing(1), }), })); } } { // Make theme property on styled components optional // https://github.com/mui-org/material-ui/issues/16379#issuecomment-507209971 const style = (props: { value: number }) => ({}); const styleWithTheme = (props: { value: number; theme: Theme }) => ({}); const Component: React.FC = () => null; const ComponentWithTheme: React.FC<{ theme: { zIndex: { [k: string]: number } } }> = () => null; const ComponentStyled = styled(Component)(style); const ComponentStyledWithTheme = styled(Component)(styleWithTheme); const ComponentWithThemeStyled = styled(ComponentWithTheme)(style); const ComponentWithThemeStyledWithTheme = styled(ComponentWithTheme)(styleWithTheme); // prop 'theme' must not be required <ComponentStyled value={1} />; <ComponentStyledWithTheme value={1} />; // error: type {} is missing properties from 'Theme' ... <ComponentStyledWithTheme value={1} theme={{}} />; // $ExpectError // error: property 'theme' is missing in type ... (because the component requires it) <ComponentWithThemeStyled value={1} />; // $ExpectError <ComponentWithThemeStyledWithTheme value={1} />; // $ExpectError // error: type {} is not assignable to type ... <ComponentWithThemeStyledWithTheme value={1} theme={{}} />; // $ExpectError // error: missing properties from type 'ZIndex' ... <ComponentWithThemeStyledWithTheme value={1} theme={{ zIndex: { appBar: 100 } }} />; // $ExpectError const ComponentWithOptionalTheme: React.FC<{ theme?: { zIndex: { [k: string]: number } }; }> = () => null; const ComponentWithOptionalThemeStyledWithTheme = styled(ComponentWithOptionalTheme)( styleWithTheme, ); // prop 'theme' must not be required <ComponentWithOptionalThemeStyledWithTheme value={1} />; // error: property 'zIndex' is missing in type {} <ComponentWithOptionalThemeStyledWithTheme value={1} theme={{}} />; // $ExpectError // error: missing properties from type 'Theme' ... <ComponentWithOptionalThemeStyledWithTheme value={1} theme={{ zIndex: { appBar: 100 } }} />; // $ExpectError } { // Make sure theme and props have the correct types // https://github.com/mui-org/material-ui/issues/16351 // Theme has default type styled(Button)(({ theme }) => { // $ExpectType Theme theme; return { padding: theme.spacing(1) }; }); interface myProps { testValue: boolean; } // Type of props follow all the way to css properties styled(Button)<Theme, myProps>(({ theme, testValue }) => { // $ExpectType Theme theme; // $ExpectType boolean testValue; return { padding: props => { // $ExpectType myProps props; // $ExpectType boolean props.testValue; return theme.spacing(1); }, }; }); }
packages/material-ui/test/typescript/styles.spec.tsx
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.9986746311187744, 0.1548914909362793, 0.00016666723240632564, 0.0009199142223224044, 0.3540268540382385 ]
{ "id": 6, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "declare const withTheme: PropInjector<WithTheme, ThemedComponentProps>;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " ref?: React.Ref<unknown>;\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 9 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15.5 16h-12c-.83 0-1.5.67-1.5 1.5S2.67 19 3.5 19h12c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5zm3.35-8.27c.62-.61 1-1.45 1-2.38 0-1.51-1-2.79-2.38-3.21-.48-.14-.97.22-.97.72 0 .33.21.62.52.71.77.23 1.33.94 1.33 1.78 0 .82-.53 1.51-1.27 1.76-.33.11-.58.39-.58.74V8c0 .37.27.69.64.75 1.93.31 3.36 2 3.36 4.02v1.48c0 .41.34.75.75.75s.75-.34.75-.75v-1.49c0-2.22-1.28-4.14-3.15-5.03zm-2.82 2.47h-1.3c-1.02 0-1.94-.73-2.07-1.75-.12-.95.46-1.7 1.3-1.93.32-.09.54-.38.54-.72 0-.49-.46-.86-.93-.72-1.42.41-2.45 1.73-2.42 3.28.03 1.84 1.62 3.29 3.46 3.29h1.42c1.05 0 1.97.74 1.97 2.05v.55c0 .41.33.75.75.75h.01c.41 0 .75-.33.75-.75v-.89c-.01-1.81-1.61-3.16-3.48-3.16zM18 16h1.5v3H18zm2.5 0H22v3h-1.5z" /> , 'SmokingRoomsRounded');
packages/material-ui-icons/src/SmokingRoomsRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.001466009533032775, 0.001466009533032775, 0.001466009533032775, 0.001466009533032775, 0 ]
{ "id": 6, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "declare const withTheme: PropInjector<WithTheme, ThemedComponentProps>;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " ref?: React.Ref<unknown>;\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 9 }
import React from 'react'; import { createMuiTheme } from '@material-ui/core/styles'; import { ThemeProvider } from '@material-ui/styles'; import { purple } from '@material-ui/core/colors'; import Button from '@material-ui/core/Button'; const theme = createMuiTheme({ palette: { primary: { main: purple[500] }, // Purple and green play nicely together. secondary: { main: '#11cb5f' }, // This is just green.A700 as hex. }, }); export default function Palette() { return ( <ThemeProvider theme={theme}> <Button color="primary">Primary</Button> <Button color="secondary">Secondary</Button> </ThemeProvider> ); }
docs/src/pages/customization/palette/Palette.tsx
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00031141197541728616, 0.00025969123817048967, 0.00018043030286207795, 0.0002872314362321049, 0.000056908676924649626 ]
{ "id": 6, "code_window": [ " innerRef?: React.Ref<any>;\n", "}\n", "\n", "declare const withTheme: PropInjector<WithTheme, ThemedComponentProps>;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " ref?: React.Ref<unknown>;\n" ], "file_path": "packages/material-ui/src/styles/withTheme.d.ts", "type": "add", "edit_start_line_idx": 9 }
export { default } from './DialogActions'; export * from './DialogActions';
packages/material-ui/src/DialogActions/index.d.ts
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.0001700574648566544, 0.0001700574648566544, 0.0001700574648566544, 0.0001700574648566544, 0 ]
{ "id": 7, "code_window": [ "\n", "// withTheme\n", "const ComponentWithTheme = withTheme(({ theme }: WithTheme) => <div>{theme.spacing(1)}</div>);\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui/test/typescript/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 173 }
import * as React from 'react'; import { createStyles, withStyles, withTheme, WithTheme, WithStyles, makeStyles, } from '@material-ui/styles'; import Button from '@material-ui/core/Button'; import { Theme } from '@material-ui/core/styles'; // Example 1 const styles = ({ palette, spacing }: Theme) => ({ root: { padding: spacing(1), backgroundColor: palette.background.default, color: palette.primary.dark, }, }); // Shared types for examples interface ComponentProps extends WithStyles<typeof styles> { text: string; } const StyledExampleOne = withStyles(styles)(({ classes, text }: ComponentProps) => ( <div className={classes.root}>{text}</div> )); <StyledExampleOne text="I am styled!" />; // Example 2 const Component: React.FunctionComponent<ComponentProps & WithStyles<typeof styles>> = ({ classes, text, }) => <div className={classes.root}>{text}</div>; const StyledExampleTwo = withStyles(styles)(Component); <StyledExampleTwo text="I am styled!" />; // Example 3 const styleRule = createStyles({ root: { display: 'flex', alignItems: 'stretch', height: '100vh', width: '100%', }, }); const ComponentWithChildren: React.FunctionComponent<WithStyles<typeof styles>> = ({ classes, children, }) => <div className={classes.root}>{children}</div>; const StyledExampleThree = withStyles(styleRule)(ComponentWithChildren); <StyledExampleThree />; // Also works with a plain object const stylesAsPojo = { root: { backgroundColor: 'hotpink', }, }; const AnotherStyledSFC = withStyles({ root: { backgroundColor: 'hotpink' }, })(({ classes }: WithStyles<'root'>) => <div className={classes.root}>Stylish!</div>); // withTheme const ComponentWithTheme = withTheme<Theme, React.FunctionComponent<WithTheme<Theme>>>( ({ theme }: WithTheme<Theme>) => <div>{theme.spacing(1)}</div>, ); <ComponentWithTheme />; // withStyles + withTheme type AllTheProps = WithTheme<Theme> & WithStyles<typeof styles>; const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => ( <div className={classes.root}>{theme.palette.text.primary}</div> )); // missing prop theme <StyledComponent />; // $ExpectError const AllTheComposition = withTheme<Theme, typeof StyledComponent>(StyledComponent); <AllTheComposition />; { const Foo = withTheme<Theme, React.ComponentClass<WithTheme<Theme>>>( class extends React.Component<WithTheme<Theme>> { render() { return null; } }, ); <Foo />; } declare const themed: boolean; { // this is necessary so that TypesScript can infer the theme // usually it's better to just use withTheme<Theme> if you're not actual styling const themedStyles = (theme: Theme) => ({ root: {} }); // Test that withTheme: true guarantees the presence of the theme const Foo = withStyles(themedStyles, { withTheme: true })( class extends React.Component<WithTheme<Theme>> { render() { return <div style={{ margin: this.props.theme.spacing(1) }} />; } }, ); <Foo />; const Bar = withStyles(themedStyles, { withTheme: true })( ({ theme }: WithStyles<typeof themedStyles, true>) => ( <div style={{ margin: theme.spacing(1) }} /> ), ); <Bar />; } // Can't use withStyles effectively as a decorator in TypeScript // due to https://github.com/Microsoft/TypeScript/issues/4881 // @withStyles(styles) const DecoratedComponent = withStyles(styles)( class extends React.Component<ComponentProps & WithStyles<typeof styles>> { render() { const { classes, text } = this.props; return <div className={classes.root}>{text}</div>; } }, ); // no 'classes' property required at element creation time (#8267) <DecoratedComponent text="foo" />; // Allow nested pseudo selectors withStyles(theme => createStyles({ guttered: { '&:hover': { textDecoration: 'none', }, }, listItem: { '&:hover $listItemIcon': { visibility: 'inherit', }, }, }), ); { // allow top level media queries // https://github.com/mui-org/material-ui/issues/12277 // typescript thinks `content` is the CSS property not a classname const ambiguousStyles = createStyles({ content: { minHeight: '100vh', }, // $ExpectError '@media (min-width: 960px)': { content: { display: 'flex', }, }, }); const styles = createStyles({ contentClass: { minHeight: '100vh', }, '@media (min-width: 960px)': { contentClass: { display: 'flex', }, }, }); } { const styles = (theme: Theme) => createStyles({ // Styled similar to ListItemText root: { '&:first-child': { paddingLeft: 0, }, flex: '1 1 auto', padding: '0 16px', }, inset: { '&:first-child': { paddingLeft: theme.spacing(7), }, }, row: { alignItems: 'center', display: 'flex', flexDirection: 'row', }, }); interface ListItemContentProps extends WithStyles<typeof styles> { children?: React.ReactElement; inset?: boolean; row?: boolean; } const ListItemContent = withStyles(styles, { name: 'ui-ListItemContent' })( ({ children, classes, inset, row }: ListItemContentProps) => ( <div className={classes.root} color="textSecondary"> {children} </div> ), ); } { interface FooProps extends WithStyles<'x' | 'y'> { a: number; b: boolean; } const ListItemContent = withStyles({ x: {}, y: {} })((props: FooProps) => <div />); } { // https://github.com/mui-org/material-ui/issues/11109 // The real test here is with "strictFunctionTypes": false, // but we don't have a way currently to test under varying // TypeScript configurations. interface ComponentProps extends WithStyles<typeof styles> { caption: string; } const styles = (theme: Theme) => createStyles({ content: { margin: 4, }, }); const Component = (props: ComponentProps) => { return <div className={props.classes.content}>Hello {props.caption}</div>; }; const StyledComponent = withStyles(styles)(Component); class App extends React.Component { render() { return ( <div className="App"> <StyledComponent caption="Developer" /> </div> ); } } <App />; } { // https://github.com/mui-org/material-ui/issues/11191 const styles = (theme: Theme) => createStyles({ main: {}, }); interface Props extends WithStyles<typeof styles> { someProp?: string; } class SomeComponent extends React.PureComponent<Props> { render() { return <div />; } } const DecoratedSomeComponent = withStyles(styles)(SomeComponent); <DecoratedSomeComponent someProp="hello world" />; } { // https://github.com/mui-org/material-ui/issues/11312 withStyles(styles, { name: 'MyComponent', index: 0 })(() => <div />); } { // can't provide own `classes` type interface Props { classes: number; } class Component extends React.Component<Props & WithStyles<typeof styles>> {} // $ExpectError const StyledComponent = withStyles(styles)(Component); // implicit FunctionComponent withStyles(styles)((props: Props) => null); // $ExpectError withStyles(styles)((props: Props & WithStyles<typeof styles>) => null); // $ExpectError withStyles(styles)((props: Props & { children?: React.ReactNode }) => null); // $ExpectError withStyles(styles)( (props: Props & WithStyles<typeof styles> & { children?: React.ReactNode }) => null, // $ExpectError ); // explicit not but with "Property 'children' is missing in type 'ValidationMap<Props>'". // which is not helpful const StatelessComponent: React.FunctionComponent<Props> = props => null; const StatelessComponentWithStyles: React.FunctionComponent< Props & WithStyles<typeof styles> > = props => null; withStyles(styles)(StatelessComponent); // $ExpectError withStyles(styles)(StatelessComponentWithStyles); // $ExpectError } { // https://github.com/mui-org/material-ui/issues/12670 interface Props { nonDefaulted: string; defaulted: number; } class MyButton extends React.Component<Props & WithStyles<typeof styles>> { static defaultProps = { defaulted: 0, }; render() { const { classes, nonDefaulted, defaulted } = this.props; return ( <Button className={classes.btn}> {defaulted}, {nonDefaulted} </Button> ); } } const styles = () => createStyles({ btn: { color: 'red', }, }); const StyledMyButton = withStyles(styles)(MyButton); const CorrectUsage = () => <StyledMyButton nonDefaulted="2" />; // Property 'nonDefaulted' is missing in type '{}' const MissingPropUsage = () => <StyledMyButton />; // $ExpectError } { // styles from props interface StyleProps { color?: 'blue' | 'red'; } const styles = (theme: Theme) => ({ root: (props: StyleProps) => ({ backgroundColor: props.color || theme.palette.primary.main }), }); interface MyComponentProps extends WithStyles<typeof styles> { message: string; } class MyComponent extends React.Component<MyComponentProps> { render() { const { classes, color, message } = this.props; return ( <div className={classes.root}> {color}: {message} </div> ); } } const StyledMyComponent = withStyles(styles)(MyComponent); const renderedStyledMyComponent = <StyledMyComponent message="Hi" />; // number is not assignable to 'blue' | 'red' // $ExpectError interface InconsistentProps extends WithStyles<typeof styles> { color: number; } } function forwardRefTest() { const styles = createStyles({ root: { color: 'red' }, }); function Anchor(props: WithStyles<typeof styles>) { const { classes } = props; return <a className={classes.root} />; } const StyledAnchor = withStyles(styles)(Anchor); const anchorRef = React.useRef<HTMLAnchorElement>(null); // forwarded to function components which can't hold refs // property 'ref' does not exists <StyledAnchor ref={anchorRef} />; // $ExpectError <StyledAnchor innerRef={anchorRef} />; const RefableAnchor = React.forwardRef<HTMLAnchorElement, WithStyles<typeof styles>>( (props, ref) => { const { classes } = props; return <a className={classes.root} />; }, ); const StyledRefableAnchor = withStyles(styles)(RefableAnchor); <StyledRefableAnchor ref={anchorRef} />; const buttonRef = React.createRef<HTMLButtonElement>(); // HTMLButtonElement is missing properties <StyledRefableAnchor ref={buttonRef} />; // $ExpectError // undesired: `innerRef` is currently typed as any but for backwards compat we're keeping it // especially since `innerRef` will be removed in v5 and is equivalent to `ref` <StyledRefableAnchor innerRef={buttonRef} />; } { // https://github.com/mui-org/material-ui/pull/15546 // Update type definition to let CSS properties be functions interface testProps { foo: boolean; } const useStyles = makeStyles((theme: Theme) => ({ root: { width: (prop: testProps) => (prop.foo ? 100 : 0), }, root2: (prop2: testProps) => ({ width: (prop: testProps) => (prop.foo && prop2.foo ? 100 : 0), height: 100, }), })); const styles = useStyles({ foo: true }); // $ExpectType string const root = styles.root; // $ExpectType string const root2 = styles.root2; } { // If there are no props, use the definition that doesn't accept them // https://github.com/mui-org/material-ui/issues/16198 // $ExpectType Record<"root", CSSProperties | (() => CSSProperties)> const styles = createStyles({ root: { width: 1, }, }); // $ExpectType Record<"root", CSSProperties | (() => CSSProperties)> const styles2 = createStyles({ root: () => ({ width: 1, }), }); interface testProps { foo: boolean; } // $ExpectType Record<"root", CreateCSSProperties<testProps> | ((props: testProps) => CreateCSSProperties<testProps>)> const styles3 = createStyles({ root: (props: testProps) => ({ width: 1, }), }); }
packages/material-ui-styles/test/styles.spec.tsx
1
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.9980199337005615, 0.2971508502960205, 0.00016534679161850363, 0.012172670103609562, 0.4226616322994232 ]
{ "id": 7, "code_window": [ "\n", "// withTheme\n", "const ComponentWithTheme = withTheme(({ theme }: WithTheme) => <div>{theme.spacing(1)}</div>);\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui/test/typescript/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 173 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" /> , 'DoneOutlined');
packages/material-ui-icons/src/DoneOutlined.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017871685849968344, 0.00017871685849968344, 0.00017871685849968344, 0.00017871685849968344, 0 ]
{ "id": 7, "code_window": [ "\n", "// withTheme\n", "const ComponentWithTheme = withTheme(({ theme }: WithTheme) => <div>{theme.spacing(1)}</div>);\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui/test/typescript/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 173 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM2 4h1l3.6 7.59-1.35 2.44C4.52 15.37 5.48 17 7 17h11c.55 0 1-.45 1-1s-.45-1-1-1H7l1.1-2h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.37-.66-.11-1.48-.87-1.48H5.21l-.67-1.43c-.16-.35-.52-.57-.9-.57H2c-.55 0-1 .45-1 1s.45 1 1 1zm15 14c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z" /> , 'LocalGroceryStoreRounded');
packages/material-ui-icons/src/LocalGroceryStoreRounded.js
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017501112597528845, 0.00017501112597528845, 0.00017501112597528845, 0.00017501112597528845, 0 ]
{ "id": 7, "code_window": [ "\n", "// withTheme\n", "const ComponentWithTheme = withTheme(({ theme }: WithTheme) => <div>{theme.spacing(1)}</div>);\n", "\n", "<ComponentWithTheme />;\n", "\n", "// withStyles + withTheme\n", "type AllTheProps = WithTheme & WithStyles<typeof styles>;\n", "\n", "const StyledComponent = withStyles(styles)(({ theme, classes }: AllTheProps) => (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const componentWithThemeRef = React.createRef<HTMLDivElement>();\n", "<ComponentWithTheme ref={componentWithThemeRef} />;\n" ], "file_path": "packages/material-ui/test/typescript/styles.spec.tsx", "type": "replace", "edit_start_line_idx": 173 }
{ "name": "nextjs", "version": "4.0.0", "private": true, "dependencies": { "@material-ui/core": "latest", "@material-ui/styles": "latest", "clsx": "latest", "next": "latest", "prop-types": "latest", "react": "latest", "react-dom": "latest" }, "scripts": { "dev": "next", "build": "next build", "start": "next start" } }
examples/nextjs/package.json
0
https://github.com/mui/material-ui/commit/b40a7739f510a80374b8ab9a875e6677b64460dd
[ 0.00017721763288136572, 0.00017651781672611833, 0.0001758179860189557, 0.00017651781672611833, 6.998234312050045e-7 ]
{ "id": 0, "code_window": [ " const classes = useStyles(props);\n", " const className = clsx(classes.root, classNameProp);\n", "\n", " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 82 }
import React from 'react'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import { chainPropTypes, getDisplayName } from '@material-ui/utils'; import hoistNonReactStatics from 'hoist-non-react-statics'; import makeStyles from '../makeStyles'; function omit(input, fields) { const output = {}; Object.keys(input).forEach(prop => { if (fields.indexOf(prop) === -1) { output[prop] = input[prop]; } }); return output; } // styled-components's API removes the mapping between components and styles. // Using components as a low-level styling construct can be simpler. function styled(Component) { const componentCreator = (style, options = {}) => { const { name, ...stylesOptions } = options; if (process.env.NODE_ENV !== 'production' && Component === undefined) { throw new Error( [ 'You are calling styled(Component)(style) with an undefined component.', 'You may have forgotten to import it.', ].join('\n'), ); } let classNamePrefix = name; if (process.env.NODE_ENV !== 'production' && !name) { // Provide a better DX outside production. const displayName = getDisplayName(Component); if (displayName !== undefined) { classNamePrefix = displayName; } } const stylesOrCreator = typeof style === 'function' ? theme => ({ root: props => style({ theme, ...props }) }) : { root: style }; const useStyles = makeStyles(stylesOrCreator, { Component, name: name || Component.displayName, classNamePrefix, ...stylesOptions, }); let filterProps; let propTypes = {}; if (style.filterProps) { filterProps = style.filterProps; delete style.filterProps; } /* eslint-disable react/forbid-foreign-prop-types */ if (style.propTypes) { propTypes = style.propTypes; delete style.propTypes; } /* eslint-enable react/forbid-foreign-prop-types */ const StyledComponent = React.forwardRef(function StyledComponent(props, ref) { const { children, className: classNameProp, clone, component: ComponentProp, ...other } = props; const classes = useStyles(props); const className = clsx(classes.root, classNameProp); if (clone) { return React.cloneElement(children, { className: clsx(children.props.className, className), }); } let spread = other; if (filterProps) { spread = omit(spread, filterProps); } if (typeof children === 'function') { return children({ className, ...spread }); } const FinalComponent = ComponentProp || Component; return ( <FinalComponent ref={ref} className={className} {...spread}> {children} </FinalComponent> ); }); StyledComponent.propTypes = { /** * A render function or node. */ children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), /** * @ignore */ className: PropTypes.string, /** * If `true`, the component will recycle it's children DOM element. * It's using `React.cloneElement` internally. */ clone: chainPropTypes(PropTypes.bool, props => { if (props.clone && props.component) { return new Error('You can not use the clone and component prop at the same time.'); } return null; }), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, ...propTypes, }; if (process.env.NODE_ENV !== 'production') { StyledComponent.displayName = `Styled(${classNamePrefix})`; } hoistNonReactStatics(StyledComponent, Component); return StyledComponent; }; return componentCreator; } export default styled;
packages/material-ui-styles/src/styled/styled.js
1
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.9979735016822815, 0.13625234365463257, 0.00016657428932376206, 0.0002663143095560372, 0.33795130252838135 ]
{ "id": 0, "code_window": [ " const classes = useStyles(props);\n", " const className = clsx(classes.root, classNameProp);\n", "\n", " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 82 }
--- title: React的 App Bar(应用栏)组件 components: AppBar, Toolbar, Menu --- # App Bar(应用栏) <p class="description">应用栏用来显示与当前屏幕相关的信息和操作。</p> [顶部应用栏](https://material.io/design/components/app-bars-top.html) 提供与当前屏幕相关的内容和操作。 它用于展示品牌、屏幕标题、导航和操作选项。 它可以转换为上下文相关的操作栏或直接用作导航栏。 ## 带按钮的应用栏 {{"demo": "pages/components/app-bar/ButtonAppBar.js"}} ## 简单的应用栏 {{"demo": "pages/components/app-bar/SimpleAppBar.js"}} ## 带一个主搜索输入框的应用栏 一个主搜索栏 {{"demo": "pages/components/app-bar/PrimarySearchAppBar.js"}} ## 带有菜单的应用栏 {{"demo": "pages/components/app-bar/MenuAppBar.js"}} ## 带有搜索输入框的应用栏 一个侧边搜索栏。 {{"demo": "pages/components/app-bar/SearchAppBar.js"}} ## 紧凑模式 (仅限桌面模式) {{"demo": "pages/components/app-bar/DenseAppBar.js"}} ## 底部应用栏 {{"demo": "pages/components/app-bar/BottomAppBar.js", "iframe": true, "maxWidth": 500}} ## 滚动 ### 隐藏应用栏 一个隐藏滚动条的应用栏。 {{"demo": "pages/components/app-bar/HideAppBar.js", "iframe": true, "maxWidth": 500}} ### 变高的应用栏 一个在滚动时变高的应用栏。 {{"demo": "pages/components/app-bar/ElevateAppBar.js", "iframe": true, "maxWidth": 500}} ### `useScrollTrigger([options]) => trigger` #### 参数 1. `options` (*Object* [optional]): - `options.disableHysteresis` (*Boolean* [optional]): 默认值为`false`。 禁用迟滞的效果。 在决定 `trigger` 的值时会忽略在滚动的方向。 - `options.target` (*Node* [optional]):默认值时 `window`。 - `options.threshold` (*Number* [optional]):默认值为 `100`。当垂直滚动超过此阈值时,则会更改 ` trigger ` 的值。 #### 返回结果 `trigger` :滚动位置是否符合标准? #### 例子 ```jsx import useScrollTrigger from '@material-ui/core/useScrollTrigger'; function HideOnScroll(props) { const trigger = useScrollTrigger(); return ( <Slide in={!trigger}> <div>你好</div> </Slide> ); } ```
docs/src/pages/components/app-bar/app-bar-zh.md
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00030460223206318915, 0.00018509296933189034, 0.00016563033568672836, 0.00016998207138385624, 0.00004236865424900316 ]
{ "id": 0, "code_window": [ " const classes = useStyles(props);\n", " const className = clsx(classes.root, classNameProp);\n", "\n", " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 82 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7V4z" /></React.Fragment> , 'FunctionsOutlined');
packages/material-ui-icons/src/FunctionsOutlined.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.0001725323818391189, 0.0001725323818391189, 0.0001725323818391189, 0.0001725323818391189, 0 ]
{ "id": 0, "code_window": [ " const classes = useStyles(props);\n", " const className = clsx(classes.root, classNameProp);\n", "\n", " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 82 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M3 19h13.46l-12-12H3zm7.12-12L21 17.88V7z" opacity=".3" /><path d="M21 7v10.88l1.85 1.85c.09-.23.15-.47.15-.73V7c0-1.11-.89-2-2-2h-7.58l3.29-3.3L16 1l-4 4-4-4-.7.7L10.58 5H8.12l2 2H21zm-.54 16l1.26-1.27-1.26 1.26zM2.41 2.13l-.14.14L1 3.54l1.53 1.53C1.65 5.28 1 6.06 1 7v12c0 1.1.9 2 2 2h15.46l1.99 1.99 1.26-1.26.15-.15L2.41 2.13zM3 19V7h1.46l12 12H3z" /></React.Fragment> , 'TvOffTwoTone');
packages/material-ui-icons/src/TvOffTwoTone.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017055893840733916, 0.00017055893840733916, 0.00017055893840733916, 0.00017055893840733916, 0 ]
{ "id": 1, "code_window": [ " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ...spread,\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 85 }
import React from 'react'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import { chainPropTypes, getDisplayName } from '@material-ui/utils'; import hoistNonReactStatics from 'hoist-non-react-statics'; import makeStyles from '../makeStyles'; function omit(input, fields) { const output = {}; Object.keys(input).forEach(prop => { if (fields.indexOf(prop) === -1) { output[prop] = input[prop]; } }); return output; } // styled-components's API removes the mapping between components and styles. // Using components as a low-level styling construct can be simpler. function styled(Component) { const componentCreator = (style, options = {}) => { const { name, ...stylesOptions } = options; if (process.env.NODE_ENV !== 'production' && Component === undefined) { throw new Error( [ 'You are calling styled(Component)(style) with an undefined component.', 'You may have forgotten to import it.', ].join('\n'), ); } let classNamePrefix = name; if (process.env.NODE_ENV !== 'production' && !name) { // Provide a better DX outside production. const displayName = getDisplayName(Component); if (displayName !== undefined) { classNamePrefix = displayName; } } const stylesOrCreator = typeof style === 'function' ? theme => ({ root: props => style({ theme, ...props }) }) : { root: style }; const useStyles = makeStyles(stylesOrCreator, { Component, name: name || Component.displayName, classNamePrefix, ...stylesOptions, }); let filterProps; let propTypes = {}; if (style.filterProps) { filterProps = style.filterProps; delete style.filterProps; } /* eslint-disable react/forbid-foreign-prop-types */ if (style.propTypes) { propTypes = style.propTypes; delete style.propTypes; } /* eslint-enable react/forbid-foreign-prop-types */ const StyledComponent = React.forwardRef(function StyledComponent(props, ref) { const { children, className: classNameProp, clone, component: ComponentProp, ...other } = props; const classes = useStyles(props); const className = clsx(classes.root, classNameProp); if (clone) { return React.cloneElement(children, { className: clsx(children.props.className, className), }); } let spread = other; if (filterProps) { spread = omit(spread, filterProps); } if (typeof children === 'function') { return children({ className, ...spread }); } const FinalComponent = ComponentProp || Component; return ( <FinalComponent ref={ref} className={className} {...spread}> {children} </FinalComponent> ); }); StyledComponent.propTypes = { /** * A render function or node. */ children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), /** * @ignore */ className: PropTypes.string, /** * If `true`, the component will recycle it's children DOM element. * It's using `React.cloneElement` internally. */ clone: chainPropTypes(PropTypes.bool, props => { if (props.clone && props.component) { return new Error('You can not use the clone and component prop at the same time.'); } return null; }), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, ...propTypes, }; if (process.env.NODE_ENV !== 'production') { StyledComponent.displayName = `Styled(${classNamePrefix})`; } hoistNonReactStatics(StyledComponent, Component); return StyledComponent; }; return componentCreator; } export default styled;
packages/material-ui-styles/src/styled/styled.js
1
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.9944151639938354, 0.06783494353294373, 0.00016469786351080984, 0.00020676363783422858, 0.24765540659427643 ]
{ "id": 1, "code_window": [ " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ...spread,\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 85 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19.77 7.23l.01-.01-3.19-3.19c-.29-.29-.77-.29-1.06 0-.29.29-.29.77 0 1.06l1.58 1.58c-1.05.4-1.76 1.47-1.58 2.71.16 1.1 1.1 1.99 2.2 2.11.47.05.88-.03 1.27-.2v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v15c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-6.5h1.5v4.86c0 1.31.94 2.5 2.24 2.63 1.5.15 2.76-1.02 2.76-2.49V9c0-.69-.28-1.32-.73-1.77zM12 10H6V6c0-.55.45-1 1-1h4c.55 0 1 .45 1 1v4zm6 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /></React.Fragment> , 'LocalGasStationRounded');
packages/material-ui-icons/src/LocalGasStationRounded.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00018035649554803967, 0.00018035649554803967, 0.00018035649554803967, 0.00018035649554803967, 0 ]
{ "id": 1, "code_window": [ " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ...spread,\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 85 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M4 6.55c2.6.77 5.28 1.16 8 1.16 2.72 0 5.41-.39 8-1.16v10.91c-2.6-.77-5.28-1.16-8-1.16-2.72 0-5.41.39-8 1.16V6.55M2 3.77v16.47s.77-.26.88-.3C5.82 18.85 8.91 18.3 12 18.3c3.09 0 6.18.55 9.12 1.64.11.04.88.3.88.3V3.77s-.77.26-.88.3C18.18 5.15 15.09 5.71 12 5.71s-6.18-.56-9.12-1.64c-.11-.05-.88-.3-.88-.3z" /></React.Fragment> , 'PanoramaHorizontalSharp');
packages/material-ui-icons/src/PanoramaHorizontalSharp.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017088418826460838, 0.00017088418826460838, 0.00017088418826460838, 0.00017088418826460838, 0 ]
{ "id": 1, "code_window": [ " if (clone) {\n", " return React.cloneElement(children, {\n", " className: clsx(children.props.className, className),\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ...spread,\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 85 }
const { JSDOM } = require('jsdom'); const Node = require('jsdom/lib/jsdom/living/node-document-position'); // We can use jsdom-global at some point if maintaining these lists is a burden. const whitelist = ['Element', 'HTMLElement', 'HTMLInputElement', 'Performance']; const blacklist = ['sessionStorage', 'localStorage']; function createDOM() { const dom = new JSDOM('', { pretendToBeVisual: true }); global.window = dom.window; global.Node = Node; global.document = dom.window.document; // Not yet supported: https://github.com/jsdom/jsdom/issues/317 global.document.createRange = () => ({ setStart: () => {}, setEnd: () => {}, commonAncestorContainer: { nodeName: 'BODY', ownerDocument: document, }, }); // Not yet supported: https://github.com/jsdom/jsdom/issues/2152 class Touch { constructor(instance) { this.instance = instance; } get identifier() { return this.instance.identifier; } get pageX() { return this.instance.pageX; } get pageY() { return this.instance.pageY; } get clientX() { return this.instance.clientX; } get clientY() { return this.instance.clientY; } } global.window.Touch = Touch; global.navigator = { userAgent: 'node.js', }; Object.keys(dom.window) .filter(key => !blacklist.includes(key)) .concat(whitelist) .forEach(key => { if (typeof global[key] === 'undefined') { global[key] = dom.window[key]; } }); // required for wait-for-expect // not added by jsdom by default window.Date = global.Date; } module.exports = createDOM;
test/utils/createDOM.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.0001737883867463097, 0.00017145948368124664, 0.0001703391899354756, 0.00017090047185774893, 0.00000114399881567806 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n", " if (typeof children === 'function') {\n", " return children({ className, ...spread });\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "replace", "edit_start_line_idx": 88 }
import React from 'react'; import { assert } from 'chai'; import PropTypes from 'prop-types'; import styled from './styled'; import { SheetsRegistry } from 'jss'; import { createMount } from '@material-ui/core/test-utils'; import { createGenerateClassName } from '@material-ui/styles'; import consoleErrorMock from 'test/utils/consoleErrorMock'; import StylesProvider from '../StylesProvider'; describe('styled', () => { let mount; let StyledButton; before(() => { // StrictModeViolation: uses makeStyles mount = createMount({ strict: false }); StyledButton = styled('button')({ background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }); }); after(() => { mount.cleanUp(); }); it('should work as expected', () => { const sheetsRegistry = new SheetsRegistry(); const generateClassName = createGenerateClassName(); mount( <StylesProvider sheetsRegistry={sheetsRegistry} generateClassName={generateClassName}> <StyledButton>Styled Components</StyledButton> </StylesProvider>, ); assert.strictEqual(sheetsRegistry.registry.length, 1); assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' }); }); describe('prop: clone', () => { it('should be able to clone the child element', () => { const wrapper = mount( <StyledButton clone> <div>Styled Components</div> </StyledButton>, ); assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV'); wrapper.setProps({ clone: false, }); assert.strictEqual(wrapper.getDOMNode().nodeName, 'BUTTON'); }); }); it('should filter some props', () => { const style = props => ({ background: props.color, borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }); style.filterProps = ['color']; style.propTypes = {}; const StyledDiv = styled('div')(style); const wrapper = mount( <StyledDiv data-test="enzyme" color="blue"> Styled Components </StyledDiv>, ); assert.strictEqual(wrapper.find('div').props().color, undefined); assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme'); }); describe('warnings', () => { beforeEach(() => { consoleErrorMock.spy(); }); afterEach(() => { consoleErrorMock.reset(); PropTypes.resetWarningCache(); }); it('warns if it cant detect the secondary action properly', () => { mount( <StyledButton clone component="div"> <div>Styled Components</div> </StyledButton>, ); assert.strictEqual(consoleErrorMock.callCount(), 1); assert.include( consoleErrorMock.args()[0][0], 'You can not use the clone and component prop at the same time', ); }); }); it('should accept a child function', () => { mount(<StyledButton>{props => <div {...props}>Styled Components</div>}</StyledButton>); }); });
packages/material-ui-styles/src/styled/styled.test.js
1
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.0011719128815457225, 0.0002552378864493221, 0.00016510352725163102, 0.00017304389621131122, 0.0002764116507023573 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n", " if (typeof children === 'function') {\n", " return children({ className, ...spread });\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "replace", "edit_start_line_idx": 88 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M17.75 8L14 4.25l-10 10V18h3.75l10-10zm3.66-3.66L17.66.59 15 3.25 18.75 7l2.66-2.66z" /><path fillOpacity=".36" d="M0 20h24v4H0v-4z" /></React.Fragment> , 'BorderColorSharp');
packages/material-ui-icons/src/BorderColorSharp.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017629135982133448, 0.00017629135982133448, 0.00017629135982133448, 0.00017629135982133448, 0 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n", " if (typeof children === 'function') {\n", " return children({ className, ...spread });\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "replace", "edit_start_line_idx": 88 }
export interface TileDataItem { img: string; title: string; author: string; cols: number; featured: boolean; } declare const tileData: TileDataItem[]; export default tileData;
docs/src/pages/components/grid-list/tileData.d.ts
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017452087195124477, 0.0001720970030874014, 0.00016967311967164278, 0.0001720970030874014, 0.0000024238761398009956 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " let spread = other;\n", " if (filterProps) {\n", " spread = omit(spread, filterProps);\n", " }\n", "\n", " if (typeof children === 'function') {\n", " return children({ className, ...spread });\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "replace", "edit_start_line_idx": 88 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20 11H4c-.55 0-1 .45-1 1s.45 1 1 1h16c.55 0 1-.45 1-1s-.45-1-1-1zM4 18h10c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zM20 6H4c-.55 0-1 .45-1 1v.01c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V7c0-.55-.45-1-1-1z" /></React.Fragment> , 'NotesRounded');
packages/material-ui-icons/src/NotesRounded.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017397888586856425, 0.00017397888586856425, 0.00017397888586856425, 0.00017397888586856425, 0 ]
{ "id": 3, "code_window": [ " /**\n", " * If `true`, the component will recycle it's children DOM element.\n", " * It's using `React.cloneElement` internally.\n", " */\n", " clone: chainPropTypes(PropTypes.bool, props => {\n", " if (props.clone && props.component) {\n", " return new Error('You can not use the clone and component prop at the same time.');\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " *\n", " * This prop will be deprecated and removed in v5\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 118 }
import React from 'react'; import { assert } from 'chai'; import PropTypes from 'prop-types'; import styled from './styled'; import { SheetsRegistry } from 'jss'; import { createMount } from '@material-ui/core/test-utils'; import { createGenerateClassName } from '@material-ui/styles'; import consoleErrorMock from 'test/utils/consoleErrorMock'; import StylesProvider from '../StylesProvider'; describe('styled', () => { let mount; let StyledButton; before(() => { // StrictModeViolation: uses makeStyles mount = createMount({ strict: false }); StyledButton = styled('button')({ background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }); }); after(() => { mount.cleanUp(); }); it('should work as expected', () => { const sheetsRegistry = new SheetsRegistry(); const generateClassName = createGenerateClassName(); mount( <StylesProvider sheetsRegistry={sheetsRegistry} generateClassName={generateClassName}> <StyledButton>Styled Components</StyledButton> </StylesProvider>, ); assert.strictEqual(sheetsRegistry.registry.length, 1); assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' }); }); describe('prop: clone', () => { it('should be able to clone the child element', () => { const wrapper = mount( <StyledButton clone> <div>Styled Components</div> </StyledButton>, ); assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV'); wrapper.setProps({ clone: false, }); assert.strictEqual(wrapper.getDOMNode().nodeName, 'BUTTON'); }); }); it('should filter some props', () => { const style = props => ({ background: props.color, borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }); style.filterProps = ['color']; style.propTypes = {}; const StyledDiv = styled('div')(style); const wrapper = mount( <StyledDiv data-test="enzyme" color="blue"> Styled Components </StyledDiv>, ); assert.strictEqual(wrapper.find('div').props().color, undefined); assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme'); }); describe('warnings', () => { beforeEach(() => { consoleErrorMock.spy(); }); afterEach(() => { consoleErrorMock.reset(); PropTypes.resetWarningCache(); }); it('warns if it cant detect the secondary action properly', () => { mount( <StyledButton clone component="div"> <div>Styled Components</div> </StyledButton>, ); assert.strictEqual(consoleErrorMock.callCount(), 1); assert.include( consoleErrorMock.args()[0][0], 'You can not use the clone and component prop at the same time', ); }); }); it('should accept a child function', () => { mount(<StyledButton>{props => <div {...props}>Styled Components</div>}</StyledButton>); }); });
packages/material-ui-styles/src/styled/styled.test.js
1
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.0018334499327465892, 0.0003850371576845646, 0.00016283061995636672, 0.0001738263526931405, 0.0004795190179720521 ]
{ "id": 3, "code_window": [ " /**\n", " * If `true`, the component will recycle it's children DOM element.\n", " * It's using `React.cloneElement` internally.\n", " */\n", " clone: chainPropTypes(PropTypes.bool, props => {\n", " if (props.clone && props.component) {\n", " return new Error('You can not use the clone and component prop at the same time.');\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " *\n", " * This prop will be deprecated and removed in v5\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 118 }
// Corresponds to 10 frames at 60 Hz. // A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B. export default function debounce(func, wait = 166) { let timeout; function debounced(...args) { // eslint-disable-next-line consistent-this const that = this; const later = () => { func.apply(that, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); } debounced.clear = () => { clearTimeout(timeout); }; return debounced; }
packages/material-ui/src/utils/debounce.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.0001752387179294601, 0.0001728444913169369, 0.00017062854021787643, 0.00017266620125155896, 0.000001886314521470922 ]
{ "id": 3, "code_window": [ " /**\n", " * If `true`, the component will recycle it's children DOM element.\n", " * It's using `React.cloneElement` internally.\n", " */\n", " clone: chainPropTypes(PropTypes.bool, props => {\n", " if (props.clone && props.component) {\n", " return new Error('You can not use the clone and component prop at the same time.');\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " *\n", " * This prop will be deprecated and removed in v5\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 118 }
import React from 'react'; import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import MuiDialogTitle from '@material-ui/core/DialogTitle'; import MuiDialogContent from '@material-ui/core/DialogContent'; import MuiDialogActions from '@material-ui/core/DialogActions'; import IconButton from '@material-ui/core/IconButton'; import CloseIcon from '@material-ui/icons/Close'; import Typography from '@material-ui/core/Typography'; const styles = theme => ({ root: { margin: 0, padding: theme.spacing(2), }, closeButton: { position: 'absolute', right: theme.spacing(1), top: theme.spacing(1), color: theme.palette.grey[500], }, }); const DialogTitle = withStyles(styles)(props => { const { children, classes, onClose } = props; return ( <MuiDialogTitle disableTypography className={classes.root}> <Typography variant="h6">{children}</Typography> {onClose ? ( <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}> <CloseIcon /> </IconButton> ) : null} </MuiDialogTitle> ); }); const DialogContent = withStyles(theme => ({ root: { padding: theme.spacing(2), }, }))(MuiDialogContent); const DialogActions = withStyles(theme => ({ root: { margin: 0, padding: theme.spacing(1), }, }))(MuiDialogActions); export default function CustomizedDialogs() { const [open, setOpen] = React.useState(false); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div> <Button variant="outlined" color="secondary" onClick={handleClickOpen}> Open dialog </Button> <Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}> <DialogTitle id="customized-dialog-title" onClose={handleClose}> Modal title </DialogTitle> <DialogContent dividers> <Typography gutterBottom> Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. </Typography> <Typography gutterBottom> Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. </Typography> <Typography gutterBottom> Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. </Typography> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Save changes </Button> </DialogActions> </Dialog> </div> ); }
docs/src/pages/components/dialogs/CustomizedDialogs.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017514399951323867, 0.00017306339577771723, 0.0001705994363874197, 0.00017326345550827682, 0.00000134017136588227 ]
{ "id": 3, "code_window": [ " /**\n", " * If `true`, the component will recycle it's children DOM element.\n", " * It's using `React.cloneElement` internally.\n", " */\n", " clone: chainPropTypes(PropTypes.bool, props => {\n", " if (props.clone && props.component) {\n", " return new Error('You can not use the clone and component prop at the same time.');\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " *\n", " * This prop will be deprecated and removed in v5\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.js", "type": "add", "edit_start_line_idx": 118 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M4 7c0-.55.45-1 1-1h16c.55 0 1-.45 1-1s-.45-1-1-1H4c-1.1 0-2 .9-2 2v11h-.5c-.83 0-1.5.67-1.5 1.5S.67 20 1.5 20H14v-3H4V7zm19 1h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z" /></React.Fragment> , 'DevicesRounded');
packages/material-ui-icons/src/DevicesRounded.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017328369722235948, 0.00017328369722235948, 0.00017328369722235948, 0.00017328369722235948, 0 ]
{ "id": 4, "code_window": [ " assert.strictEqual(sheetsRegistry.registry.length, 1);\n", " assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' });\n", " });\n", "\n", " describe('prop: clone', () => {\n", " it('should be able to clone the child element', () => {\n", " const wrapper = mount(\n", " <StyledButton clone>\n", " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " let wrapper;\n", "\n", " before(() => {\n", " wrapper = mount(\n", " <StyledButton clone data-test=\"enzyme\">\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "replace", "edit_start_line_idx": 47 }
import React from 'react'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import { chainPropTypes, getDisplayName } from '@material-ui/utils'; import hoistNonReactStatics from 'hoist-non-react-statics'; import makeStyles from '../makeStyles'; function omit(input, fields) { const output = {}; Object.keys(input).forEach(prop => { if (fields.indexOf(prop) === -1) { output[prop] = input[prop]; } }); return output; } // styled-components's API removes the mapping between components and styles. // Using components as a low-level styling construct can be simpler. function styled(Component) { const componentCreator = (style, options = {}) => { const { name, ...stylesOptions } = options; if (process.env.NODE_ENV !== 'production' && Component === undefined) { throw new Error( [ 'You are calling styled(Component)(style) with an undefined component.', 'You may have forgotten to import it.', ].join('\n'), ); } let classNamePrefix = name; if (process.env.NODE_ENV !== 'production' && !name) { // Provide a better DX outside production. const displayName = getDisplayName(Component); if (displayName !== undefined) { classNamePrefix = displayName; } } const stylesOrCreator = typeof style === 'function' ? theme => ({ root: props => style({ theme, ...props }) }) : { root: style }; const useStyles = makeStyles(stylesOrCreator, { Component, name: name || Component.displayName, classNamePrefix, ...stylesOptions, }); let filterProps; let propTypes = {}; if (style.filterProps) { filterProps = style.filterProps; delete style.filterProps; } /* eslint-disable react/forbid-foreign-prop-types */ if (style.propTypes) { propTypes = style.propTypes; delete style.propTypes; } /* eslint-enable react/forbid-foreign-prop-types */ const StyledComponent = React.forwardRef(function StyledComponent(props, ref) { const { children, className: classNameProp, clone, component: ComponentProp, ...other } = props; const classes = useStyles(props); const className = clsx(classes.root, classNameProp); if (clone) { return React.cloneElement(children, { className: clsx(children.props.className, className), }); } let spread = other; if (filterProps) { spread = omit(spread, filterProps); } if (typeof children === 'function') { return children({ className, ...spread }); } const FinalComponent = ComponentProp || Component; return ( <FinalComponent ref={ref} className={className} {...spread}> {children} </FinalComponent> ); }); StyledComponent.propTypes = { /** * A render function or node. */ children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), /** * @ignore */ className: PropTypes.string, /** * If `true`, the component will recycle it's children DOM element. * It's using `React.cloneElement` internally. */ clone: chainPropTypes(PropTypes.bool, props => { if (props.clone && props.component) { return new Error('You can not use the clone and component prop at the same time.'); } return null; }), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, ...propTypes, }; if (process.env.NODE_ENV !== 'production') { StyledComponent.displayName = `Styled(${classNamePrefix})`; } hoistNonReactStatics(StyledComponent, Component); return StyledComponent; }; return componentCreator; } export default styled;
packages/material-ui-styles/src/styled/styled.js
1
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.0024846310261636972, 0.0005135114770382643, 0.00016412627883255482, 0.00016909281839616597, 0.0007255644304677844 ]
{ "id": 4, "code_window": [ " assert.strictEqual(sheetsRegistry.registry.length, 1);\n", " assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' });\n", " });\n", "\n", " describe('prop: clone', () => {\n", " it('should be able to clone the child element', () => {\n", " const wrapper = mount(\n", " <StyledButton clone>\n", " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " let wrapper;\n", "\n", " before(() => {\n", " wrapper = mount(\n", " <StyledButton clone data-test=\"enzyme\">\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "replace", "edit_start_line_idx": 47 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l2.29 2.29c.63.63 1.71.18 1.71-.71V8.91c0-.89-1.08-1.34-1.71-.71L17 10.5z" /> , 'VideocamRounded');
packages/material-ui-icons/src/VideocamRounded.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017610353825148195, 0.00017610353825148195, 0.00017610353825148195, 0.00017610353825148195, 0 ]
{ "id": 4, "code_window": [ " assert.strictEqual(sheetsRegistry.registry.length, 1);\n", " assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' });\n", " });\n", "\n", " describe('prop: clone', () => {\n", " it('should be able to clone the child element', () => {\n", " const wrapper = mount(\n", " <StyledButton clone>\n", " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " let wrapper;\n", "\n", " before(() => {\n", " wrapper = mount(\n", " <StyledButton clone data-test=\"enzyme\">\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "replace", "edit_start_line_idx": 47 }
--- title: Componente React para Guias components: Tabs, Tab --- # Guias <p class="description">As guias facilitam a exploração e alternam entre diferentes visualizações.</p> As [guias](https://material.io/design/components/tabs.html) organizam e permitem a navegação entre grupos de conteúdo relacionados e no mesmo nível hierárquico. ## Guias simples Um exemplo simples sem frescuras. {{"demo": "pages/components/tabs/SimpleTabs.js"}} ### Etiquetas embrulhadas Os rótulos longos serão agrupados automaticamente nas guias. Se o marcador for muito longo para a guia, ele será excedido e o texto não ficará visível. {{"demo": "pages/components/tabs/TabsWrappedLabel.js"}} ### Guia desativada Uma guia pode ser desabilitada definindo a propriedade `disabled`. {{"demo": "pages/components/tabs/DisabledTabs.js"}} ## Guias fixas As guias fixas devem ser usadas com um número limitado de guias e quando o posicionamento consistente ajudar a memória muscular. ### Largura total A propriedade `variant="fullWidth"` deve ser usada em views menores. Esta demo também usa [react-swipeable-views](https://github.com/oliviertassinari/react-swipeable-views) para animar a transição de Guias e permite que estas sejam trocadas ao toque nos dispositivos. {{"demo": "pages/components/tabs/FullWidthTabs.js"}} ### Centralizado A propriedade `centered` deve ser usada para views maiores. {{"demo": "pages/components/tabs/CenteredTabs.js"}} ## Guias roláveis ### Botões de rolagem automáticos Botões de rolagem para esquerda e direita serão apresentados automaticamente em dispositivos desktop e ocultados em dispositivos mobile. (baseado na largura de exibição do dispositivo) {{"demo": "pages/components/tabs/ScrollableTabsButtonAuto.js"}} ### Botões de rolagem forçados Botões de rolagem para esquerda e direita serão apresentados independente da largura de exibição do dispositivo. {{"demo": "pages/components/tabs/ScrollableTabsButtonForce.js"}} ### Impedir botões de rolagem Botões de rolagem para esquerda e direita nunca serão exibidos. Toda e qualquer rolagem será iniciada através dos mecanismos do navegador do dispositivo (exemplo: arrastar para direita ou esquerda, roda do mouse + shipt, etc.) {{"demo": "pages/components/tabs/ScrollableTabsButtonPrevent.js"}} ## Guias customizadas Aqui está um exemplo de personalização do componente. Você pode aprender mais sobre isso na [página de documentação de substituições](/customization/components/). {{"demo": "pages/components/tabs/CustomizedTabs.js"}} ## Guias de navegação Por padrão as guias usam um elemento `button`, mas você pode definir sua própria tag ou seu próprio componente. Aqui vai um exemplo de implementação de guia de navegação: {{"demo": "pages/components/tabs/NavTabs.js"}} ## Guias com ícones O rótulo das guias podem ser compostos apenas por ícones ou apenas por texto. {{"demo": "pages/components/tabs/IconTabs.js"}} {{"demo": "pages/components/tabs/IconLabelTabs.js"}}
docs/src/pages/components/tabs/tabs-pt.md
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017575830861460418, 0.0001701329747447744, 0.00016364060866180807, 0.00016961262736003846, 0.000003893906068697106 ]
{ "id": 4, "code_window": [ " assert.strictEqual(sheetsRegistry.registry.length, 1);\n", " assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' });\n", " });\n", "\n", " describe('prop: clone', () => {\n", " it('should be able to clone the child element', () => {\n", " const wrapper = mount(\n", " <StyledButton clone>\n", " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " let wrapper;\n", "\n", " before(() => {\n", " wrapper = mount(\n", " <StyledButton clone data-test=\"enzyme\">\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "replace", "edit_start_line_idx": 47 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z" /> , 'List');
packages/material-ui-icons/src/List.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017690479580778629, 0.00017690479580778629, 0.00017690479580778629, 0.00017690479580778629, 0 ]
{ "id": 5, "code_window": [ " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n", " assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV');\n", " wrapper.setProps({\n", " clone: false,\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " });\n", "\n", " it('should be able to pass props to cloned element', () => {\n", " assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme');\n", " });\n", "\n", " it('should be able to clone the child element', () => {\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "add", "edit_start_line_idx": 53 }
import React from 'react'; import { assert } from 'chai'; import PropTypes from 'prop-types'; import styled from './styled'; import { SheetsRegistry } from 'jss'; import { createMount } from '@material-ui/core/test-utils'; import { createGenerateClassName } from '@material-ui/styles'; import consoleErrorMock from 'test/utils/consoleErrorMock'; import StylesProvider from '../StylesProvider'; describe('styled', () => { let mount; let StyledButton; before(() => { // StrictModeViolation: uses makeStyles mount = createMount({ strict: false }); StyledButton = styled('button')({ background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }); }); after(() => { mount.cleanUp(); }); it('should work as expected', () => { const sheetsRegistry = new SheetsRegistry(); const generateClassName = createGenerateClassName(); mount( <StylesProvider sheetsRegistry={sheetsRegistry} generateClassName={generateClassName}> <StyledButton>Styled Components</StyledButton> </StylesProvider>, ); assert.strictEqual(sheetsRegistry.registry.length, 1); assert.deepEqual(sheetsRegistry.registry[0].classes, { root: 'button-root-1' }); }); describe('prop: clone', () => { it('should be able to clone the child element', () => { const wrapper = mount( <StyledButton clone> <div>Styled Components</div> </StyledButton>, ); assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV'); wrapper.setProps({ clone: false, }); assert.strictEqual(wrapper.getDOMNode().nodeName, 'BUTTON'); }); }); it('should filter some props', () => { const style = props => ({ background: props.color, borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }); style.filterProps = ['color']; style.propTypes = {}; const StyledDiv = styled('div')(style); const wrapper = mount( <StyledDiv data-test="enzyme" color="blue"> Styled Components </StyledDiv>, ); assert.strictEqual(wrapper.find('div').props().color, undefined); assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme'); }); describe('warnings', () => { beforeEach(() => { consoleErrorMock.spy(); }); afterEach(() => { consoleErrorMock.reset(); PropTypes.resetWarningCache(); }); it('warns if it cant detect the secondary action properly', () => { mount( <StyledButton clone component="div"> <div>Styled Components</div> </StyledButton>, ); assert.strictEqual(consoleErrorMock.callCount(), 1); assert.include( consoleErrorMock.args()[0][0], 'You can not use the clone and component prop at the same time', ); }); }); it('should accept a child function', () => { mount(<StyledButton>{props => <div {...props}>Styled Components</div>}</StyledButton>); }); });
packages/material-ui-styles/src/styled/styled.test.js
1
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.9942299127578735, 0.08428702503442764, 0.00016685693117324263, 0.001174242701381445, 0.27436181902885437 ]
{ "id": 5, "code_window": [ " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n", " assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV');\n", " wrapper.setProps({\n", " clone: false,\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " });\n", "\n", " it('should be able to pass props to cloned element', () => {\n", " assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme');\n", " });\n", "\n", " it('should be able to clone the child element', () => {\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "add", "edit_start_line_idx": 53 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0zm24 24H0V0h24v24z" /><path d="M23 15h-2v2h2v-2zm0-4h-2v2h2v-2zm0 8h-2v2c1 0 2-1 2-2zM15 3h-2v2h2V3zm8 4h-2v2h2V7zm-2-4v2h2c0-1-1-2-2-2zM3 21h8v-6H1v4c0 1.1.9 2 2 2zM3 7H1v2h2V7zm12 12h-2v2h2v-2zm4-16h-2v2h2V3zm0 16h-2v2h2v-2zM3 3C2 3 1 4 1 5h2V3zm0 8H1v2h2v-2zm8-8H9v2h2V3zM7 3H5v2h2V3z" /></React.Fragment> , 'PhotoSizeSelectSmall');
packages/material-ui-icons/src/PhotoSizeSelectSmall.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00016845266509335488, 0.00016845266509335488, 0.00016845266509335488, 0.00016845266509335488, 0 ]
{ "id": 5, "code_window": [ " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n", " assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV');\n", " wrapper.setProps({\n", " clone: false,\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " });\n", "\n", " it('should be able to pass props to cloned element', () => {\n", " assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme');\n", " });\n", "\n", " it('should be able to clone the child element', () => {\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "add", "edit_start_line_idx": 53 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 12l-2-2-2 2 2 2 2-2zm10.71-4.29L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88zM19 10l-2 2 2 2 2-2-2-2z" /> , 'BluetoothConnected');
packages/material-ui-icons/src/BluetoothConnected.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017358518380206078, 0.00017358518380206078, 0.00017358518380206078, 0.00017358518380206078, 0 ]
{ "id": 5, "code_window": [ " <div>Styled Components</div>\n", " </StyledButton>,\n", " );\n", " assert.strictEqual(wrapper.getDOMNode().nodeName, 'DIV');\n", " wrapper.setProps({\n", " clone: false,\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " });\n", "\n", " it('should be able to pass props to cloned element', () => {\n", " assert.strictEqual(wrapper.find('div').props()['data-test'], 'enzyme');\n", " });\n", "\n", " it('should be able to clone the child element', () => {\n" ], "file_path": "packages/material-ui-styles/src/styled/styled.test.js", "type": "add", "edit_start_line_idx": 53 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M18 17h2v.5h-1v1h1v.5h-2v1h3v-4h-3v1zm1-9h1V4h-2v1h1v3zm-1 3h1.8L18 13.1v.9h3v-1h-1.8l1.8-2.1V10h-3v1zM2 5h14v2H2V5zm0 12h14v2H2v-2zm0-6h14v2H2v-2z" /> , 'FormatListNumberedRtlSharp');
packages/material-ui-icons/src/FormatListNumberedRtlSharp.js
0
https://github.com/mui/material-ui/commit/dc740b6346676ac57256e7eadf9b4d73e9d7a926
[ 0.00017402019875589758, 0.00017402019875589758, 0.00017402019875589758, 0.00017402019875589758, 0 ]
{ "id": 0, "code_window": [ " TypedDocumentNode,\n", " OperationResult,\n", " defaultExchanges,\n", "} from \"@urql/core\"\n", "import { devtoolsExchange } from \"@urql/devtools\"\n", "import * as E from \"fp-ts/Either\"\n", "import * as TE from \"fp-ts/TaskEither\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " OperationContext,\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "add", "edit_start_line_idx": 14 }
import { computed, ref, onMounted, onBeforeUnmount, reactive, Ref, } from "@nuxtjs/composition-api" import { DocumentNode } from "graphql/language" import { createClient, TypedDocumentNode, OperationResult, defaultExchanges, } from "@urql/core" import { devtoolsExchange } from "@urql/devtools" import * as E from "fp-ts/Either" import * as TE from "fp-ts/TaskEither" import { pipe, constVoid } from "fp-ts/function" import { subscribe } from "wonka" import clone from "lodash/clone" import { getAuthIDToken } from "~/helpers/fb/auth" const BACKEND_GQL_URL = process.env.CONTEXT === "production" ? "https://api.hoppscotch.io/graphql" : "https://api.hoppscotch.io/graphql" const client = createClient({ url: BACKEND_GQL_URL, fetchOptions: () => { const token = getAuthIDToken() return { headers: { authorization: token ? `Bearer ${token}` : "", }, } }, exchanges: [devtoolsExchange, ...defaultExchanges], }) /** * A wrapper type for defining errors possible in a GQL operation */ export type GQLError<T extends string> = | { type: "network_error" error: Error } | { type: "gql_error" error: T } const DEFAULT_QUERY_OPTIONS = { noPolling: false, pause: undefined as Ref<boolean> | undefined, } type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS type UseQueryLoading = { loading: true } type UseQueryLoaded< QueryFailType extends string = "", QueryReturnType = any > = { loading: false data: E.Either<GQLError<QueryFailType>, QueryReturnType> } type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> = | UseQueryLoading | UseQueryLoaded<QueryFailType, QueryReturnType> export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>( x: UseQueryReturn<QueryFailType, QueryReturnType> ): x is { loading: false data: E.Either<GQLError<QueryFailType>, QueryReturnType> } { return !x.loading } export function useGQLQuery< QueryReturnType = any, QueryFailType extends string = "", QueryVariables extends object = {} >( query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>, variables?: QueryVariables, options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS ): | { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> } | { loading: true } { type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType> const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options) const data = ref<DataType>() let subscription: { unsubscribe(): void } | null = null onMounted(() => { const gqlQuery = client.query<any, QueryVariables>(query, variables) const processResult = (result: OperationResult<any, QueryVariables>) => pipe( // The target result.data as QueryReturnType | undefined, // Define what happens if data does not exist (it is an error) E.fromNullable( pipe( // Take the network error value result.error?.networkError, // If it null, set the left to the generic error name E.fromNullable(result.error?.name), E.match( // The left case (network error was null) (gqlErr) => <GQLError<QueryFailType>>{ type: "gql_error", error: gqlErr as QueryFailType, }, // The right case (it was a GraphQL Error) (networkErr) => <GQLError<QueryFailType>>{ type: "network_error", error: networkErr, } ) ) ) ) if (finalOptions.noPolling) { gqlQuery.toPromise().then((result) => { data.value = processResult(result) }) } else { subscription = pipe( gqlQuery, subscribe((result) => { data.value = processResult(result) }) ) } }) onBeforeUnmount(() => { subscription?.unsubscribe() }) return reactive({ loading: computed(() => !data.value), data: data!, }) as | { loading: false data: DataType } | { loading: true } } export const runMutation = < MutationReturnType = any, MutationFailType extends string = "", MutationVariables extends {} = {} >( mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>, variables?: MutationVariables ): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> => pipe( TE.tryCatch( () => client.mutation<MutationReturnType>(mutation, variables).toPromise(), () => constVoid() as never // The mutation function can never fail, so this will never be called ;) ), TE.chainEitherK((result) => pipe( result.data as MutationReturnType, // If we have the result, then okay E.fromNullable( // Result is null pipe( result.error?.networkError, // Check for network error E.fromNullable(result.error?.name), // If it is null, then it is a GQL error E.match( // The left case (network error was null) (gqlErr) => <GQLError<MutationFailType>>{ type: "gql_error", error: gqlErr as MutationFailType, }, // The right case (it was a GraphQL Error) (networkErr) => <GQLError<MutationFailType>>{ type: "network_error", error: networkErr, } ) ) ) ) ) )
packages/hoppscotch-app/helpers/backend/GQLClient.ts
1
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.9210847616195679, 0.04455241933465004, 0.00016625280841253698, 0.00022366146731656045, 0.19600224494934082 ]
{ "id": 0, "code_window": [ " TypedDocumentNode,\n", " OperationResult,\n", " defaultExchanges,\n", "} from \"@urql/core\"\n", "import { devtoolsExchange } from \"@urql/devtools\"\n", "import * as E from \"fp-ts/Either\"\n", "import * as TE from \"fp-ts/TaskEither\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " OperationContext,\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "add", "edit_start_line_idx": 14 }
export const JavaUnirestCodegen = { id: "java-unirest", name: "Java Unirest", language: "java", generator: ({ url, pathName, queryString, auth, httpUser, httpPassword, bearerToken, method, rawInput, rawParams, rawRequestBody, contentType, headers, }) => { const requestString = [] // initial request setup let requestBody = rawInput ? rawParams : rawRequestBody const verbs = [ { verb: "GET", unirestMethod: "get" }, { verb: "POST", unirestMethod: "post" }, { verb: "PUT", unirestMethod: "put" }, { verb: "PATCH", unirestMethod: "patch" }, { verb: "DELETE", unirestMethod: "delete" }, { verb: "HEAD", unirestMethod: "head" }, { verb: "OPTIONS", unirestMethod: "options" }, ] // create client and request const verb = verbs.find((v) => v.verb === method) requestString.push( `HttpResponse<String> response = Unirest.${verb.unirestMethod}("${url}${pathName}?${queryString}")\n` ) if (auth === "Basic Auth") { const basic = `${httpUser}:${httpPassword}` requestString.push( `.header("authorization", "Basic ${window.btoa( unescape(encodeURIComponent(basic)) )}") \n` ) } else if (auth === "Bearer Token" || auth === "OAuth 2.0") { requestString.push(`.header("authorization", "Bearer ${bearerToken}") \n`) } // custom headers if (headers) { headers.forEach(({ key, value }) => { if (key) { requestString.push(`.header("${key}", "${value}")\n`) } }) } if (contentType) { requestString.push(`.header("Content-Type", "${contentType}")\n`) } // set body if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (contentType.includes("x-www-form-urlencoded")) { requestBody = `"${requestBody}"` } else { requestBody = JSON.stringify(requestBody) } requestString.push(`.body(${requestBody})`) } requestString.push(`\n.asString();\n`) return requestString.join("") }, }
packages/hoppscotch-app/helpers/codegen/generators/java-unirest.js
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017707103688735515, 0.0001721605658531189, 0.00016924526426009834, 0.00017186070908792317, 0.0000024669534468557686 ]
{ "id": 0, "code_window": [ " TypedDocumentNode,\n", " OperationResult,\n", " defaultExchanges,\n", "} from \"@urql/core\"\n", "import { devtoolsExchange } from \"@urql/devtools\"\n", "import * as E from \"fp-ts/Either\"\n", "import * as TE from \"fp-ts/TaskEither\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " OperationContext,\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "add", "edit_start_line_idx": 14 }
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg>
packages/hoppscotch-app/assets/icons/paperclip.svg
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017080517136491835, 0.00017080517136491835, 0.00017080517136491835, 0.00017080517136491835, 0 ]
{ "id": 0, "code_window": [ " TypedDocumentNode,\n", " OperationResult,\n", " defaultExchanges,\n", "} from \"@urql/core\"\n", "import { devtoolsExchange } from \"@urql/devtools\"\n", "import * as E from \"fp-ts/Either\"\n", "import * as TE from \"fp-ts/TaskEither\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " OperationContext,\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "add", "edit_start_line_idx": 14 }
[build.environment] NODE_VERSION = "14" NPM_FLAGS = "--prefix=/dev/null" [build] base = "/" publish = "packages/hoppscotch-app/dist" command = "npx pnpm i --store=node_modules/.pnpm-store && npx pnpm run generate" [[redirects]] from = "/discord" to = "https://discord.gg/GAMWxmR" status = 301 force = true [[redirects]] from = "/telegram" to = "https://t.me/hoppscotch" status = 301 force = true [[redirects]] from = "/beta" to = "https://forms.gle/XPYDMp8m6JHNWcYp9" status = 301 force = true [[redirects]] from = "/careers" to = "https://hoppscotch.notion.site/3b9d5d5239a043bfb91701faabf5b8f0" status = 301 force = true [[redirects]] from = "/newsletter" to = "http://eepurl.com/hy0eWH" status = 301 force = true [[redirects]] from = "/twitter" to = "https://twitter.com/hoppscotch_io" status = 301 force = true [[redirects]] from = "/github" to = "https://github.com/hoppscotch/hoppscotch" status = 301 force = true
netlify.toml
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017738043970894068, 0.00017512783233541995, 0.00017082634440157562, 0.00017560597916599363, 0.0000022452240955317393 ]
{ "id": 1, "code_window": [ " MutationVariables extends {} = {}\n", ">(\n", " mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n", " variables?: MutationVariables\n", "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " variables?: MutationVariables,\n", " additionalConfig?: Partial<OperationContext>\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 173 }
import { computed, ref, onMounted, onBeforeUnmount, reactive, Ref, } from "@nuxtjs/composition-api" import { DocumentNode } from "graphql/language" import { createClient, TypedDocumentNode, OperationResult, defaultExchanges, } from "@urql/core" import { devtoolsExchange } from "@urql/devtools" import * as E from "fp-ts/Either" import * as TE from "fp-ts/TaskEither" import { pipe, constVoid } from "fp-ts/function" import { subscribe } from "wonka" import clone from "lodash/clone" import { getAuthIDToken } from "~/helpers/fb/auth" const BACKEND_GQL_URL = process.env.CONTEXT === "production" ? "https://api.hoppscotch.io/graphql" : "https://api.hoppscotch.io/graphql" const client = createClient({ url: BACKEND_GQL_URL, fetchOptions: () => { const token = getAuthIDToken() return { headers: { authorization: token ? `Bearer ${token}` : "", }, } }, exchanges: [devtoolsExchange, ...defaultExchanges], }) /** * A wrapper type for defining errors possible in a GQL operation */ export type GQLError<T extends string> = | { type: "network_error" error: Error } | { type: "gql_error" error: T } const DEFAULT_QUERY_OPTIONS = { noPolling: false, pause: undefined as Ref<boolean> | undefined, } type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS type UseQueryLoading = { loading: true } type UseQueryLoaded< QueryFailType extends string = "", QueryReturnType = any > = { loading: false data: E.Either<GQLError<QueryFailType>, QueryReturnType> } type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> = | UseQueryLoading | UseQueryLoaded<QueryFailType, QueryReturnType> export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>( x: UseQueryReturn<QueryFailType, QueryReturnType> ): x is { loading: false data: E.Either<GQLError<QueryFailType>, QueryReturnType> } { return !x.loading } export function useGQLQuery< QueryReturnType = any, QueryFailType extends string = "", QueryVariables extends object = {} >( query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>, variables?: QueryVariables, options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS ): | { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> } | { loading: true } { type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType> const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options) const data = ref<DataType>() let subscription: { unsubscribe(): void } | null = null onMounted(() => { const gqlQuery = client.query<any, QueryVariables>(query, variables) const processResult = (result: OperationResult<any, QueryVariables>) => pipe( // The target result.data as QueryReturnType | undefined, // Define what happens if data does not exist (it is an error) E.fromNullable( pipe( // Take the network error value result.error?.networkError, // If it null, set the left to the generic error name E.fromNullable(result.error?.name), E.match( // The left case (network error was null) (gqlErr) => <GQLError<QueryFailType>>{ type: "gql_error", error: gqlErr as QueryFailType, }, // The right case (it was a GraphQL Error) (networkErr) => <GQLError<QueryFailType>>{ type: "network_error", error: networkErr, } ) ) ) ) if (finalOptions.noPolling) { gqlQuery.toPromise().then((result) => { data.value = processResult(result) }) } else { subscription = pipe( gqlQuery, subscribe((result) => { data.value = processResult(result) }) ) } }) onBeforeUnmount(() => { subscription?.unsubscribe() }) return reactive({ loading: computed(() => !data.value), data: data!, }) as | { loading: false data: DataType } | { loading: true } } export const runMutation = < MutationReturnType = any, MutationFailType extends string = "", MutationVariables extends {} = {} >( mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>, variables?: MutationVariables ): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> => pipe( TE.tryCatch( () => client.mutation<MutationReturnType>(mutation, variables).toPromise(), () => constVoid() as never // The mutation function can never fail, so this will never be called ;) ), TE.chainEitherK((result) => pipe( result.data as MutationReturnType, // If we have the result, then okay E.fromNullable( // Result is null pipe( result.error?.networkError, // Check for network error E.fromNullable(result.error?.name), // If it is null, then it is a GQL error E.match( // The left case (network error was null) (gqlErr) => <GQLError<MutationFailType>>{ type: "gql_error", error: gqlErr as MutationFailType, }, // The right case (it was a GraphQL Error) (networkErr) => <GQLError<MutationFailType>>{ type: "network_error", error: networkErr, } ) ) ) ) ) )
packages/hoppscotch-app/helpers/backend/GQLClient.ts
1
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.997723400592804, 0.05143751949071884, 0.00016588227299507707, 0.001234249328263104, 0.21170005202293396 ]
{ "id": 1, "code_window": [ " MutationVariables extends {} = {}\n", ">(\n", " mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n", " variables?: MutationVariables\n", "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " variables?: MutationVariables,\n", " additionalConfig?: Partial<OperationContext>\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 173 }
#!/bin/sh . "$(dirname "$0")/_/husky.sh" npm run pre-commit
.husky/pre-commit
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017537010717205703, 0.00017537010717205703, 0.00017537010717205703, 0.00017537010717205703, 0 ]
{ "id": 1, "code_window": [ " MutationVariables extends {} = {}\n", ">(\n", " mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n", " variables?: MutationVariables\n", "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " variables?: MutationVariables,\n", " additionalConfig?: Partial<OperationContext>\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 173 }
<svg xmlns="http://www.w3.org/2000/svg" width="142" height="127"> <path fill="url(#a)" d="M105 57c.2-.3.4-.6.4-1 .8-4.9-15-11.5-35.1-14.7s-37.2-1.8-38 3.1c-.1.4 0 .7.1 1.1-.5-.2-29.6 81.5-29.6 81.5h110S106 57 105 57z"/> <path fill="#fff" d="M91 49.5c1.9 1.1 2.9 2.3 2.8 3.3-.5 3.1-11.9 3.8-25.6 1.7C54.6 52.3 43.9 48 44.4 45c.2-1 1.5-1.8 3.6-2.2-7 .3-11.6 1.6-12 3.8-.6 4.1 13.4 9.7 31.4 12.6 18 2.9 33.1 1.8 33.8-2.2.4-2.4-3.6-5-10.2-7.5z"/> <path fill="url(#b)" d="M73.7 20.1c9.8 1.5 19 3.5 27.3 5.7C99.8 13.4 90.3 2.9 77.5.9s-24.9 5-30 16.3c8.2.5 17 1.4 26.2 2.9z"/> <path fill="url(#c)" d="M73.7 20.1C34.9 14 2.3 16.5.9 25.8c-1 6.1 11.7 13.6 31.6 19.7-.1-.4-.1-.7-.1-1.1.8-4.9 17.8-6.3 38-3.1s35.9 9.8 35.1 14.7c-.1.4-.2.7-.4 1 20.7.3 35.1-2.9 36.1-9 1.4-9.3-28.8-21.8-67.5-27.9zM48 28.7c-1.6-.3-2.8-1.8-2.5-3.4.3-1.6 1.8-2.8 3.4-2.5 1.6.3 2.8 1.8 2.5 3.4-.2 1.6-1.8 2.7-3.4 2.5zm23.9 2.8c-2.2-.3-3.7-2.4-3.3-4.6.3-2.2 2.4-3.7 4.6-3.3 2.2.3 3.7 2.4 3.3 4.6-.4 2.1-2.5 3.6-4.6 3.3zm23.5 4.7c-1.6-.3-2.8-1.8-2.5-3.4.3-1.6 1.8-2.8 3.4-2.5 1.6.3 2.8 1.8 2.5 3.4-.2 1.6-1.8 2.8-3.4 2.5z"/> <linearGradient id="a" gradientUnits="userSpaceOnUse" x1="71.305" y1="41.487" x2="56.415" y2="135.498"> <stop offset="0" stop-color="#52FA7B" stop-opacity=".75"/> <stop offset="1" stop-color="#52FA7B" stop-opacity=".25"/> </linearGradient> <linearGradient id="b" gradientUnits="userSpaceOnUse" x1="77.87" y1=".956" x2="74.181" y2="21.874"> <stop offset="0" stop-color="#969BA1"/> <stop offset=".254" stop-color="#82868B"/> <stop offset=".5" stop-color="#76797E"/> <stop offset=".726" stop-color="#72757A"/> <stop offset="1" stop-color="#6B6E73"/> </linearGradient> <radialGradient id="c" cx="71" cy="36.883" r="69.985" fx="71.211" fy="-13.911" gradientTransform="matrix(.989 .148 -.037 .249 2.155 17.202)" gradientUnits="userSpaceOnUse"> <stop offset=".347" stop-color="#969BA1"/> <stop offset=".901" stop-color="#83878C"/> <stop offset=".949" stop-color="#72757A"/> </radialGradient> </svg>
packages/hoppscotch-app/static/images/ufo_logo.svg
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.002070958726108074, 0.0008075932855717838, 0.00017357192700728774, 0.00017824920359998941, 0.0008933362551033497 ]
{ "id": 1, "code_window": [ " MutationVariables extends {} = {}\n", ">(\n", " mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n", " variables?: MutationVariables\n", "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " variables?: MutationVariables,\n", " additionalConfig?: Partial<OperationContext>\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 173 }
import { execPreRequestScript } from "../preRequest" import "@relmify/jest-fp-ts" describe("execPreRequestScript", () => { test("returns the updated envirionment properly", () => { return expect( execPreRequestScript( ` pw.env.set("bob", "newbob") `, [{ key: "bob", value: "oldbob" }, { key: "foo", value: "bar" }] )() ).resolves.toEqualRight([ { key: "bob", value: "newbob" }, { key: "foo", value: "bar" } ]) }) test("fails if the key is not a string", () => { return expect( execPreRequestScript( ` pw.env.set(10, "newbob") `, [{ key: "bob", value: "oldbob" }, { key: "foo", value: "bar" }] )() ).resolves.toBeLeft() }) test("fails if the value is not a string", () => { return expect( execPreRequestScript( ` pw.env.set("bob", 10) `, [{ key: "bob", value: "oldbob" }, { key: "foo", value: "bar" }] )() ).resolves.toBeLeft() }) test("fails for invalid syntax", () => { return expect( execPreRequestScript( ` pw.env.set("bob", `, [{ key: "bob", value: "oldbob" }, { key: "foo", value: "bar" }] )() ).resolves.toBeLeft() }) test("creates new env variable if doesn't exist", () => { return expect( execPreRequestScript( ` pw.env.set("foo", "bar") `, [] )() ).resolves.toEqualRight( [{ key: "foo", value: "bar" }] ) }) })
packages/hoppscotch-js-sandbox/src/__tests__/preRequest.spec.ts
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017603185551706702, 0.00017399586795363575, 0.00016922186478041112, 0.00017456697241868824, 0.0000020993925318180118 ]
{ "id": 2, "code_window": [ "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n", " () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n", " () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n", " ),\n", " TE.chainEitherK((result) =>\n", " pipe(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " () =>\n", " client\n", " .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n", " .toPromise(),\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 177 }
import gql from "graphql-tag" import { pipe } from "fp-ts/function" import * as TE from "fp-ts/TaskEither" import { runMutation } from "../GQLClient" import { TeamName } from "../types/TeamName" type DeleteTeamErrors = | "team/not_required_role" | "team/invalid_id" | "team/member_not_found" | "ea/not_invite_or_admin" type ExitTeamErrors = | "team/invalid_id" | "team/member_not_found" | "ea/not_invite_or_admin" type CreateTeamErrors = "team/name_invalid" | "ea/not_invite_or_admin" export const createTeam = (name: TeamName) => pipe( runMutation< { createTeam: { id: string name: string } }, CreateTeamErrors >( gql` mutation CreateTeam($name: String!) { createTeam(name: $name) { id name } } `, { name, } ), TE.map(({ createTeam }) => createTeam) ) export const deleteTeam = (teamID: string) => runMutation<void, DeleteTeamErrors>( gql` mutation DeleteTeam($teamID: ID!) { deleteTeam(teamID: $teamID) } `, { teamID, } ) export const leaveTeam = (teamID: string) => runMutation<void, ExitTeamErrors>( gql` mutation ExitTeam($teamID: ID!) { leaveTeam(teamID: $teamID) } `, { teamID, } )
packages/hoppscotch-app/helpers/backend/mutations/Team.ts
1
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00024209613911807537, 0.00018457378610037267, 0.00016445825167465955, 0.00017462638788856566, 0.00002485444929334335 ]
{ "id": 2, "code_window": [ "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n", " () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n", " () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n", " ),\n", " TE.chainEitherK((result) =>\n", " pipe(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " () =>\n", " client\n", " .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n", " .toPromise(),\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 177 }
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience - Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: - The use of sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][mozilla coc]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][faq]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [mozilla coc]: https://github.com/mozilla/diversity [faq]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations
CODE_OF_CONDUCT.md
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017733461572788656, 0.00017238383588846773, 0.00016881524061318487, 0.00017213016690220684, 0.0000023065722416504286 ]
{ "id": 2, "code_window": [ "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n", " () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n", " () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n", " ),\n", " TE.chainEitherK((result) =>\n", " pipe(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " () =>\n", " client\n", " .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n", " .toPromise(),\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 177 }
<template> <div class="flex"> <SmartItem svg="log-out" :label="`${$t('auth.logout')}`" @click.native=" () => { $emit('confirm-logout') confirmLogout = true } " /> <SmartConfirmModal :show="confirmLogout" :title="`${$t('confirm.logout')}`" @hide-modal="confirmLogout = false" @resolve="logout" /> </div> </template> <script lang="ts"> import { defineComponent } from "@nuxtjs/composition-api" import { signOutUser } from "~/helpers/fb/auth" export default defineComponent({ data() { return { confirmLogout: false, } }, methods: { async logout() { try { await signOutUser() this.$toast.success(`${this.$t("auth.logged_out")}`, { icon: "vpn_key", }) } catch (e) { console.error(e) this.$toast.error(`${this.$t("error.something_went_wrong")}`, { icon: "error_outline", }) } }, }, }) </script>
packages/hoppscotch-app/components/firebase/Logout.vue
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.0001775420387275517, 0.00017461313109379262, 0.00017213376122526824, 0.0001743600150803104, 0.000001969559434655821 ]
{ "id": 2, "code_window": [ "): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n", " pipe(\n", " TE.tryCatch(\n", " () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n", " () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n", " ),\n", " TE.chainEitherK((result) =>\n", " pipe(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " () =>\n", " client\n", " .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n", " .toPromise(),\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts", "type": "replace", "edit_start_line_idx": 177 }
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path></svg>
packages/hoppscotch-app/assets/icons/book-open.svg
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017306226072832942, 0.00017306226072832942, 0.00017306226072832942, 0.00017306226072832942, 0 ]
{ "id": 3, "code_window": [ " deleteTeam(teamID: $teamID)\n", " }\n", " `,\n", " {\n", " teamID,\n", " }\n", " )\n", "\n", "export const leaveTeam = (teamID: string) =>\n", " runMutation<void, ExitTeamErrors>(\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 54 }
import { computed, ref, onMounted, onBeforeUnmount, reactive, Ref, } from "@nuxtjs/composition-api" import { DocumentNode } from "graphql/language" import { createClient, TypedDocumentNode, OperationResult, defaultExchanges, } from "@urql/core" import { devtoolsExchange } from "@urql/devtools" import * as E from "fp-ts/Either" import * as TE from "fp-ts/TaskEither" import { pipe, constVoid } from "fp-ts/function" import { subscribe } from "wonka" import clone from "lodash/clone" import { getAuthIDToken } from "~/helpers/fb/auth" const BACKEND_GQL_URL = process.env.CONTEXT === "production" ? "https://api.hoppscotch.io/graphql" : "https://api.hoppscotch.io/graphql" const client = createClient({ url: BACKEND_GQL_URL, fetchOptions: () => { const token = getAuthIDToken() return { headers: { authorization: token ? `Bearer ${token}` : "", }, } }, exchanges: [devtoolsExchange, ...defaultExchanges], }) /** * A wrapper type for defining errors possible in a GQL operation */ export type GQLError<T extends string> = | { type: "network_error" error: Error } | { type: "gql_error" error: T } const DEFAULT_QUERY_OPTIONS = { noPolling: false, pause: undefined as Ref<boolean> | undefined, } type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS type UseQueryLoading = { loading: true } type UseQueryLoaded< QueryFailType extends string = "", QueryReturnType = any > = { loading: false data: E.Either<GQLError<QueryFailType>, QueryReturnType> } type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> = | UseQueryLoading | UseQueryLoaded<QueryFailType, QueryReturnType> export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>( x: UseQueryReturn<QueryFailType, QueryReturnType> ): x is { loading: false data: E.Either<GQLError<QueryFailType>, QueryReturnType> } { return !x.loading } export function useGQLQuery< QueryReturnType = any, QueryFailType extends string = "", QueryVariables extends object = {} >( query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>, variables?: QueryVariables, options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS ): | { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> } | { loading: true } { type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType> const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options) const data = ref<DataType>() let subscription: { unsubscribe(): void } | null = null onMounted(() => { const gqlQuery = client.query<any, QueryVariables>(query, variables) const processResult = (result: OperationResult<any, QueryVariables>) => pipe( // The target result.data as QueryReturnType | undefined, // Define what happens if data does not exist (it is an error) E.fromNullable( pipe( // Take the network error value result.error?.networkError, // If it null, set the left to the generic error name E.fromNullable(result.error?.name), E.match( // The left case (network error was null) (gqlErr) => <GQLError<QueryFailType>>{ type: "gql_error", error: gqlErr as QueryFailType, }, // The right case (it was a GraphQL Error) (networkErr) => <GQLError<QueryFailType>>{ type: "network_error", error: networkErr, } ) ) ) ) if (finalOptions.noPolling) { gqlQuery.toPromise().then((result) => { data.value = processResult(result) }) } else { subscription = pipe( gqlQuery, subscribe((result) => { data.value = processResult(result) }) ) } }) onBeforeUnmount(() => { subscription?.unsubscribe() }) return reactive({ loading: computed(() => !data.value), data: data!, }) as | { loading: false data: DataType } | { loading: true } } export const runMutation = < MutationReturnType = any, MutationFailType extends string = "", MutationVariables extends {} = {} >( mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>, variables?: MutationVariables ): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> => pipe( TE.tryCatch( () => client.mutation<MutationReturnType>(mutation, variables).toPromise(), () => constVoid() as never // The mutation function can never fail, so this will never be called ;) ), TE.chainEitherK((result) => pipe( result.data as MutationReturnType, // If we have the result, then okay E.fromNullable( // Result is null pipe( result.error?.networkError, // Check for network error E.fromNullable(result.error?.name), // If it is null, then it is a GQL error E.match( // The left case (network error was null) (gqlErr) => <GQLError<MutationFailType>>{ type: "gql_error", error: gqlErr as MutationFailType, }, // The right case (it was a GraphQL Error) (networkErr) => <GQLError<MutationFailType>>{ type: "network_error", error: networkErr, } ) ) ) ) ) )
packages/hoppscotch-app/helpers/backend/GQLClient.ts
1
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.002399354474619031, 0.00041085269185714424, 0.00016637191583868116, 0.0001736007397994399, 0.0005953888176009059 ]
{ "id": 3, "code_window": [ " deleteTeam(teamID: $teamID)\n", " }\n", " `,\n", " {\n", " teamID,\n", " }\n", " )\n", "\n", "export const leaveTeam = (teamID: string) =>\n", " runMutation<void, ExitTeamErrors>(\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 54 }
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
packages/hoppscotch-app/assets/icons/chevron-right.svg
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.0001741012092679739, 0.0001741012092679739, 0.0001741012092679739, 0.0001741012092679739, 0 ]
{ "id": 3, "code_window": [ " deleteTeam(teamID: $teamID)\n", " }\n", " `,\n", " {\n", " teamID,\n", " }\n", " )\n", "\n", "export const leaveTeam = (teamID: string) =>\n", " runMutation<void, ExitTeamErrors>(\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 54 }
<svg xmlns="http://www.w3.org/2000/svg" width="142" height="127"> <path fill="url(#a)" d="M105 57c.2-.3.4-.6.4-1 .8-4.9-15-11.5-35.1-14.7s-37.2-1.8-38 3.1c-.1.4 0 .7.1 1.1-.5-.2-29.6 81.5-29.6 81.5h110S106 57 105 57z"/> <path fill="#fff" d="M91 49.5c1.9 1.1 2.9 2.3 2.8 3.3-.5 3.1-11.9 3.8-25.6 1.7C54.6 52.3 43.9 48 44.4 45c.2-1 1.5-1.8 3.6-2.2-7 .3-11.6 1.6-12 3.8-.6 4.1 13.4 9.7 31.4 12.6 18 2.9 33.1 1.8 33.8-2.2.4-2.4-3.6-5-10.2-7.5z"/> <path fill="url(#b)" d="M73.7 20.1c9.8 1.5 19 3.5 27.3 5.7C99.8 13.4 90.3 2.9 77.5.9s-24.9 5-30 16.3c8.2.5 17 1.4 26.2 2.9z"/> <path fill="url(#c)" d="M73.7 20.1C34.9 14 2.3 16.5.9 25.8c-1 6.1 11.7 13.6 31.6 19.7-.1-.4-.1-.7-.1-1.1.8-4.9 17.8-6.3 38-3.1s35.9 9.8 35.1 14.7c-.1.4-.2.7-.4 1 20.7.3 35.1-2.9 36.1-9 1.4-9.3-28.8-21.8-67.5-27.9zM48 28.7c-1.6-.3-2.8-1.8-2.5-3.4.3-1.6 1.8-2.8 3.4-2.5 1.6.3 2.8 1.8 2.5 3.4-.2 1.6-1.8 2.7-3.4 2.5zm23.9 2.8c-2.2-.3-3.7-2.4-3.3-4.6.3-2.2 2.4-3.7 4.6-3.3 2.2.3 3.7 2.4 3.3 4.6-.4 2.1-2.5 3.6-4.6 3.3zm23.5 4.7c-1.6-.3-2.8-1.8-2.5-3.4.3-1.6 1.8-2.8 3.4-2.5 1.6.3 2.8 1.8 2.5 3.4-.2 1.6-1.8 2.8-3.4 2.5z"/> <linearGradient id="a" gradientUnits="userSpaceOnUse" x1="71.305" y1="41.487" x2="56.415" y2="135.498"> <stop offset="0" stop-color="#52FA7B" stop-opacity=".75"/> <stop offset="1" stop-color="#52FA7B" stop-opacity=".25"/> </linearGradient> <linearGradient id="b" gradientUnits="userSpaceOnUse" x1="77.87" y1=".956" x2="74.181" y2="21.874"> <stop offset="0" stop-color="#969BA1"/> <stop offset=".254" stop-color="#82868B"/> <stop offset=".5" stop-color="#76797E"/> <stop offset=".726" stop-color="#72757A"/> <stop offset="1" stop-color="#6B6E73"/> </linearGradient> <radialGradient id="c" cx="71" cy="36.883" r="69.985" fx="71.211" fy="-13.911" gradientTransform="matrix(.989 .148 -.037 .249 2.155 17.202)" gradientUnits="userSpaceOnUse"> <stop offset=".347" stop-color="#969BA1"/> <stop offset=".901" stop-color="#83878C"/> <stop offset=".949" stop-color="#72757A"/> </radialGradient> </svg>
packages/hoppscotch-app/static/images/ufo_logo.svg
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.0007829973474144936, 0.0003781111736316234, 0.00017502681293990463, 0.00017630936054047197, 0.0002862982510123402 ]
{ "id": 3, "code_window": [ " deleteTeam(teamID: $teamID)\n", " }\n", " `,\n", " {\n", " teamID,\n", " }\n", " )\n", "\n", "export const leaveTeam = (teamID: string) =>\n", " runMutation<void, ExitTeamErrors>(\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 54 }
MIT License Copyright (c) 2020 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
LICENSE
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017774970910977572, 0.0001725263864500448, 0.00016899917682167143, 0.00017083024431485683, 0.000003768341912291362 ]
{ "id": 4, "code_window": [ " `,\n", " {\n", " teamID,\n", " }\n", " )" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 66 }
import gql from "graphql-tag" import { pipe } from "fp-ts/function" import * as TE from "fp-ts/TaskEither" import { runMutation } from "../GQLClient" import { TeamName } from "../types/TeamName" type DeleteTeamErrors = | "team/not_required_role" | "team/invalid_id" | "team/member_not_found" | "ea/not_invite_or_admin" type ExitTeamErrors = | "team/invalid_id" | "team/member_not_found" | "ea/not_invite_or_admin" type CreateTeamErrors = "team/name_invalid" | "ea/not_invite_or_admin" export const createTeam = (name: TeamName) => pipe( runMutation< { createTeam: { id: string name: string } }, CreateTeamErrors >( gql` mutation CreateTeam($name: String!) { createTeam(name: $name) { id name } } `, { name, } ), TE.map(({ createTeam }) => createTeam) ) export const deleteTeam = (teamID: string) => runMutation<void, DeleteTeamErrors>( gql` mutation DeleteTeam($teamID: ID!) { deleteTeam(teamID: $teamID) } `, { teamID, } ) export const leaveTeam = (teamID: string) => runMutation<void, ExitTeamErrors>( gql` mutation ExitTeam($teamID: ID!) { leaveTeam(teamID: $teamID) } `, { teamID, } )
packages/hoppscotch-app/helpers/backend/mutations/Team.ts
1
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.9919354915618896, 0.2679719626903534, 0.00022303835430648178, 0.004657242447137833, 0.4201333224773407 ]
{ "id": 4, "code_window": [ " `,\n", " {\n", " teamID,\n", " }\n", " )" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 66 }
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>
packages/hoppscotch-app/assets/icons/external-link.svg
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.0001693288650130853, 0.0001693288650130853, 0.0001693288650130853, 0.0001693288650130853, 0 ]
{ "id": 4, "code_window": [ " `,\n", " {\n", " teamID,\n", " }\n", " )" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 66 }
<template> <div class=" bg-gradient-to-r from-gradientFrom via-gradientVia to-gradientTo flex flex-col items-center justify-center " > <img src="https://tiny.cc/hoppscotch_screenshot_1" alt="Screenshot" class="rounded-lg ring-dividerLight mt-8 max-w-5/6 ring-4" /> </div> </template>
packages/hoppscotch-app/components/landing/Screenshot.vue
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.0001704066089587286, 0.0001692313380772248, 0.00016805606719572097, 0.0001692313380772248, 0.0000011752708815038204 ]
{ "id": 4, "code_window": [ " `,\n", " {\n", " teamID,\n", " }\n", " )" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " },\n", " {\n", " additionalTypenames: [\"Team\"],\n" ], "file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts", "type": "add", "edit_start_line_idx": 66 }
import { Lens } from "./lenses" const imageLens: Lens = { lensName: "response.image", isSupportedContentType: (contentType) => /\bimage\/(?:gif|jpeg|png|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)\b/i.test( contentType ), renderer: "imageres", rendererImport: () => import("~/components/lenses/renderers/ImageLensRenderer.vue"), } export default imageLens
packages/hoppscotch-app/helpers/lenses/imageLens.ts
0
https://github.com/hoppscotch/hoppscotch/commit/e30e4edfce661204a1e815859b5e7ac8b4d18b2f
[ 0.00017552886856719851, 0.00017491800826974213, 0.00017430716252420098, 0.00017491800826974213, 6.108530214987695e-7 ]
{ "id": 0, "code_window": [ "export interface EventLike {\n", "\tpreventDefault(): void;\n", "\tstopPropagation(): void;\n", "}\n", "\n", "export const EventHelper = {\n", "\tstop: <T extends EventLike>(e: T, cancelBubble?: boolean): T => {\n", "\t\te.preventDefault();\n", "\t\tif (cancelBubble) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isEventLike(obj: unknown): obj is EventLike {\n", "\tconst candidate = obj as EventLike | undefined;\n", "\n", "\treturn !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');\n", "}\n", "\n" ], "file_path": "src/vs/base/browser/dom.ts", "type": "add", "edit_start_line_idx": 827 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { INotificationViewItem, isNotificationViewItem, NotificationsModel } from 'vs/workbench/common/notifications'; import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions'; import { localize } from 'vs/nls'; import { IListService, WorkbenchList } from 'vs/platform/list/browser/listService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NotificationMetrics, NotificationMetricsClassification, notificationToMetrics } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry'; import { NotificationFocusedContext, NotificationsCenterVisibleContext, NotificationsToastsVisibleContext } from 'vs/workbench/common/contextkeys'; import { INotificationService } from 'vs/platform/notification/common/notification'; // Center export const SHOW_NOTIFICATIONS_CENTER = 'notifications.showList'; export const HIDE_NOTIFICATIONS_CENTER = 'notifications.hideList'; const TOGGLE_NOTIFICATIONS_CENTER = 'notifications.toggleList'; // Toasts export const HIDE_NOTIFICATION_TOAST = 'notifications.hideToasts'; const FOCUS_NOTIFICATION_TOAST = 'notifications.focusToasts'; const FOCUS_NEXT_NOTIFICATION_TOAST = 'notifications.focusNextToast'; const FOCUS_PREVIOUS_NOTIFICATION_TOAST = 'notifications.focusPreviousToast'; const FOCUS_FIRST_NOTIFICATION_TOAST = 'notifications.focusFirstToast'; const FOCUS_LAST_NOTIFICATION_TOAST = 'notifications.focusLastToast'; // Notification export const COLLAPSE_NOTIFICATION = 'notification.collapse'; export const EXPAND_NOTIFICATION = 'notification.expand'; const TOGGLE_NOTIFICATION = 'notification.toggle'; export const CLEAR_NOTIFICATION = 'notification.clear'; export const CLEAR_ALL_NOTIFICATIONS = 'notifications.clearAll'; export const TOGGLE_DO_NOT_DISTURB_MODE = 'notifications.toggleDoNotDisturbMode'; export interface INotificationsCenterController { readonly isVisible: boolean; show(): void; hide(): void; clearAll(): void; } export interface INotificationsToastController { focus(): void; focusNext(): void; focusPrevious(): void; focusFirst(): void; focusLast(): void; hide(): void; } export function registerNotificationCommands(center: INotificationsCenterController, toasts: INotificationsToastController, model: NotificationsModel): void { function getNotificationFromContext(listService: IListService, context?: unknown): INotificationViewItem | undefined { if (isNotificationViewItem(context)) { return context; } const list = listService.lastFocusedList; if (list instanceof WorkbenchList) { const focusedElement = list.getFocusedElements()[0]; if (isNotificationViewItem(focusedElement)) { return focusedElement; } } return undefined; } // Show Notifications Cneter CommandsRegistry.registerCommand(SHOW_NOTIFICATIONS_CENTER, () => { toasts.hide(); center.show(); }); // Hide Notifications Center KeybindingsRegistry.registerCommandAndKeybindingRule({ id: HIDE_NOTIFICATIONS_CENTER, weight: KeybindingWeight.WorkbenchContrib + 50, when: NotificationsCenterVisibleContext, primary: KeyCode.Escape, handler: accessor => { const telemetryService = accessor.get(ITelemetryService); for (const notification of model.notifications) { if (notification.visible) { telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent)); } } center.hide(); } }); // Toggle Notifications Center CommandsRegistry.registerCommand(TOGGLE_NOTIFICATIONS_CENTER, accessor => { if (center.isVisible) { center.hide(); } else { toasts.hide(); center.show(); } }); // Clear Notification KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLEAR_NOTIFICATION, weight: KeybindingWeight.WorkbenchContrib, when: NotificationFocusedContext, primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace }, handler: (accessor, args?) => { const notification = getNotificationFromContext(accessor.get(IListService), args); if (notification && !notification.hasProgress) { notification.close(); } } }); // Expand Notification KeybindingsRegistry.registerCommandAndKeybindingRule({ id: EXPAND_NOTIFICATION, weight: KeybindingWeight.WorkbenchContrib, when: NotificationFocusedContext, primary: KeyCode.RightArrow, handler: (accessor, args?) => { const notification = getNotificationFromContext(accessor.get(IListService), args); notification?.expand(); } }); // Collapse Notification KeybindingsRegistry.registerCommandAndKeybindingRule({ id: COLLAPSE_NOTIFICATION, weight: KeybindingWeight.WorkbenchContrib, when: NotificationFocusedContext, primary: KeyCode.LeftArrow, handler: (accessor, args?) => { const notification = getNotificationFromContext(accessor.get(IListService), args); notification?.collapse(); } }); // Toggle Notification KeybindingsRegistry.registerCommandAndKeybindingRule({ id: TOGGLE_NOTIFICATION, weight: KeybindingWeight.WorkbenchContrib, when: NotificationFocusedContext, primary: KeyCode.Space, secondary: [KeyCode.Enter], handler: accessor => { const notification = getNotificationFromContext(accessor.get(IListService)); notification?.toggle(); } }); // Hide Toasts CommandsRegistry.registerCommand(HIDE_NOTIFICATION_TOAST, accessor => { const telemetryService = accessor.get(ITelemetryService); for (const notification of model.notifications) { if (notification.visible) { telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent)); } } toasts.hide(); }); KeybindingsRegistry.registerKeybindingRule({ id: HIDE_NOTIFICATION_TOAST, weight: KeybindingWeight.WorkbenchContrib - 50, // lower when not focused (e.g. let editor suggest win over this command) when: NotificationsToastsVisibleContext, primary: KeyCode.Escape }); KeybindingsRegistry.registerKeybindingRule({ id: HIDE_NOTIFICATION_TOAST, weight: KeybindingWeight.WorkbenchContrib + 100, // higher when focused when: ContextKeyExpr.and(NotificationsToastsVisibleContext, NotificationFocusedContext), primary: KeyCode.Escape }); // Focus Toasts CommandsRegistry.registerCommand(FOCUS_NOTIFICATION_TOAST, () => toasts.focus()); // Focus Next Toast KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FOCUS_NEXT_NOTIFICATION_TOAST, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext), primary: KeyCode.DownArrow, handler: (accessor) => { toasts.focusNext(); } }); // Focus Previous Toast KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FOCUS_PREVIOUS_NOTIFICATION_TOAST, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext), primary: KeyCode.UpArrow, handler: (accessor) => { toasts.focusPrevious(); } }); // Focus First Toast KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FOCUS_FIRST_NOTIFICATION_TOAST, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext), primary: KeyCode.PageUp, secondary: [KeyCode.Home], handler: (accessor) => { toasts.focusFirst(); } }); // Focus Last Toast KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FOCUS_LAST_NOTIFICATION_TOAST, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext), primary: KeyCode.PageDown, secondary: [KeyCode.End], handler: (accessor) => { toasts.focusLast(); } }); // Clear All Notifications CommandsRegistry.registerCommand(CLEAR_ALL_NOTIFICATIONS, () => center.clearAll()); // Toggle Do Not Disturb Mode CommandsRegistry.registerCommand(TOGGLE_DO_NOT_DISTURB_MODE, accessor => { const notificationService = accessor.get(INotificationService); notificationService.doNotDisturbMode = !notificationService.doNotDisturbMode; }); // Commands for Command Palette const category = { value: localize('notifications', "Notifications"), original: 'Notifications' }; MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: SHOW_NOTIFICATIONS_CENTER, title: { value: localize('showNotifications', "Show Notifications"), original: 'Show Notifications' }, category } }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: HIDE_NOTIFICATIONS_CENTER, title: { value: localize('hideNotifications', "Hide Notifications"), original: 'Hide Notifications' }, category }, when: NotificationsCenterVisibleContext }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: CLEAR_ALL_NOTIFICATIONS, title: { value: localize('clearAllNotifications', "Clear All Notifications"), original: 'Clear All Notifications' }, category } }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_DO_NOT_DISTURB_MODE, title: { value: localize('toggleDoNotDisturbMode', "Toggle Do Not Disturb Mode"), original: 'Toggle Do Not Disturb Mode' }, category } }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: FOCUS_NOTIFICATION_TOAST, title: { value: localize('focusNotificationToasts', "Focus Notification Toast"), original: 'Focus Notification Toast' }, category }, when: NotificationsToastsVisibleContext }); }
src/vs/workbench/browser/parts/notifications/notificationsCommands.ts
1
https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc
[ 0.00026792462449520826, 0.00017745938384905457, 0.00016872513515409082, 0.00017473348998464644, 0.000018250233551952988 ]
{ "id": 0, "code_window": [ "export interface EventLike {\n", "\tpreventDefault(): void;\n", "\tstopPropagation(): void;\n", "}\n", "\n", "export const EventHelper = {\n", "\tstop: <T extends EventLike>(e: T, cancelBubble?: boolean): T => {\n", "\t\te.preventDefault();\n", "\t\tif (cancelBubble) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isEventLike(obj: unknown): obj is EventLike {\n", "\tconst candidate = obj as EventLike | undefined;\n", "\n", "\treturn !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');\n", "}\n", "\n" ], "file_path": "src/vs/base/browser/dom.ts", "type": "add", "edit_start_line_idx": 827 }
{ "comments": { "lineComment": "//", "blockComment": [ "/*", "*/" ] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], { "open": "\"", "close": "\"", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["<", ">"] ], "indentationRules": { "increaseIndentPattern": "^.*\\{[^}\"']*$|^.*\\([^\\)\"']*$", "decreaseIndentPattern": "^\\s*(\\s*\\/[*].*[*]\\/\\s*)*[})]" }, "folding": { "markers": { "start": "^\\s*//\\s*#?region\\b", "end": "^\\s*//\\s*#?endregion\\b" } } }
extensions/rust/language-configuration.json
0
https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc
[ 0.00017631490482017398, 0.00017358855984639376, 0.00017224096518475562, 0.00017289919196628034, 0.00000160860622600012 ]