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": 0, "code_window": [ " pipeline:\n", " jobs:\n", " - checkout:\n", " filters:\n", " branches:\n", " ignore:\n", " - l10n\n", " - /dependabot\\//\n", " - test_unit:\n", " requires:\n", " - checkout\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " # Ideally we only run this pipeline if the base branch is `master` or `next`.\n", " # CircleCI doesn't support it because branch filters are based on target branch.\n", " # We approximate it by running on `master`, `next` and any PR (assuming they always target master or next).\n", " only:\n", " - master\n", " - next\n", " # pull requests have its branch name following the `pull/$CIRCLE_PR_NUMBER` scheme.\n", " - /pull\\/.*/\n" ], "file_path": ".circleci/config.yml", "type": "replace", "edit_start_line_idx": 232 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19.44 12.99l-.01.02c.04-.33.08-.67.08-1.01 0-.34-.03-.66-.07-.99l.01.02 2.44-1.92-2.43-4.22-2.87 1.16.01.01c-.52-.4-1.09-.74-1.71-1h.01L14.44 2H9.57l-.44 3.07h.01c-.62.26-1.19.6-1.71 1l.01-.01-2.88-1.17-2.44 4.22 2.44 1.92.01-.02c-.04.33-.07.65-.07.99 0 .34.03.68.08 1.01l-.01-.02-2.1 1.65-.33.26 2.43 4.2 2.88-1.15-.02-.04c.53.41 1.1.75 1.73 1.01h-.03L9.58 22h4.85s.03-.18.06-.42l.38-2.65h-.01c.62-.26 1.2-.6 1.73-1.01l-.02.04 2.88 1.15 2.43-4.2s-.14-.12-.33-.26l-2.11-1.66zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z" /> , 'SettingsSharp');
packages/material-ui-icons/src/SettingsSharp.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00017982350254897028, 0.00017982350254897028, 0.00017982350254897028, 0.00017982350254897028, 0 ]
{ "id": 0, "code_window": [ " pipeline:\n", " jobs:\n", " - checkout:\n", " filters:\n", " branches:\n", " ignore:\n", " - l10n\n", " - /dependabot\\//\n", " - test_unit:\n", " requires:\n", " - checkout\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " # Ideally we only run this pipeline if the base branch is `master` or `next`.\n", " # CircleCI doesn't support it because branch filters are based on target branch.\n", " # We approximate it by running on `master`, `next` and any PR (assuming they always target master or next).\n", " only:\n", " - master\n", " - next\n", " # pull requests have its branch name following the `pull/$CIRCLE_PR_NUMBER` scheme.\n", " - /pull\\/.*/\n" ], "file_path": ".circleci/config.yml", "type": "replace", "edit_start_line_idx": 232 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M17 8H7c-2.21 0-4 1.79-4 4s1.79 4 4 4h10c2.21 0 4-1.79 4-4s-1.79-4-4-4zm0 7c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z" opacity=".3" /><path d="M17 6H7c-3.31 0-6 2.69-6 6s2.69 6 6 6h10c3.31 0 6-2.69 6-6s-2.69-6-6-6zm0 10H7c-2.21 0-4-1.79-4-4s1.79-4 4-4h10c2.21 0 4 1.79 4 4s-1.79 4-4 4zm0-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" /></React.Fragment> , 'ToggleOnTwoTone');
packages/material-ui-icons/src/ToggleOnTwoTone.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00016992019664030522, 0.00016992019664030522, 0.00016992019664030522, 0.00016992019664030522, 0 ]
{ "id": 1, "code_window": [ "on:\n", " # So that PRs touching the same files as the push are updated\n", " push:\n", " branches-ignore:\n", " # PRs are almost never based off of dependabot PRs\n", " - 'dependabot/**'\n", " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 4 }
name: 'Maintenance' on: # So that PRs touching the same files as the push are updated push: branches-ignore: # PRs are almost never based off of dependabot PRs - 'dependabot/**' # So that the `dirtyLabel` is removed if conflicts are resolved # Could put too much strain on rate limit # If we hit the rate limit too often remove this event pull_request_target: branches-ignore: # These PRs are almost fully automated so labelling them is not as important. # They do burst the GitHub API though so we're ignoring them to not hit the rate limit - 'dependabot/**' types: [synchronize] jobs: main: runs-on: ubuntu-latest steps: - name: check if prs are dirty uses: eps1lon/actions-label-merge-conflict@releases/2.x with: dirtyLabel: 'PR: out-of-date' removeOnDirtyLabel: 'PR: ready to ship' repoToken: '${{ secrets.GITHUB_TOKEN }}' retryAfter: 130 retryMax: 10
.github/workflows/maintenance.yml
1
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.9966548681259155, 0.3371020555496216, 0.00067752820905298, 0.013973725959658623, 0.46640586853027344 ]
{ "id": 1, "code_window": [ "on:\n", " # So that PRs touching the same files as the push are updated\n", " push:\n", " branches-ignore:\n", " # PRs are almost never based off of dependabot PRs\n", " - 'dependabot/**'\n", " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 4 }
# よくある質問と回答 <p class="description">特定の問題で立ち往生していますか? Check some of these common gotchas first in the FAQ.</p> If you still can't find what you're looking for, you can refer to our [support page](/getting-started/support/). ## Material-UIは最高です。 プロジェクトを支援するにはどのようにできますか? Material-UIをサポートする方法はたくさんあります。 - **ライブラリを布教する** Evangelize Material-UI by [linking to material-ui.com](https://material-ui.com/) on your website, every backlink matters. Follow us on [Twitter](https://twitter.com/MaterialUI), like and retweet the important news. Or just talk about us with your friends. - **Give us feedback**. Tell us what we're doing well or where we can improve. Please upvote (👍) the issues that you are the most interested in seeing solved. - **Help new users**. You can answer questions on [StackOverflow](https://stackoverflow.com/questions/tagged/material-ui). - **Make changes happen**. - Edit the documentation. Every page has an "EDIT THIS PAGE" link in the top right. - Report bugs or missing features by [creating an issue](https://github.com/mui-org/material-ui/issues/new). - Review and comment on existing [pull requests](https://github.com/mui-org/material-ui/pulls) and [issues](https://github.com/mui-org/material-ui/issues). - Help [translate](https://translate.material-ui.com) the documentation. - [Improve our documentation](https://github.com/mui-org/material-ui/tree/master/docs), fix bugs, or add features by [submitting a pull request](https://github.com/mui-org/material-ui/pulls). - **Support us financially on [OpenCollective](https://opencollective.com/material-ui)**. If you use Material-UI in a commercial project and would like to support its continued development by becoming a Sponsor, or in a side or hobby project and would like to become a Backer, you can do so through OpenCollective. All funds donated are managed transparently, and Sponsors receive recognition in the README and on the Material-UI home page. ## productionビルドでコンポーネントが正しくレンダリングされないのはなぜですか? The #1 reason this likely happens is due to class name conflicts once your code is in a production bundle. Material-UIが機能するためには、`className`ページ上のすべてのコンポーネントの値は、[クラス名ジェネレータ](/styles/advanced/#class-names)の単一インスタンスによって生成される必要があります。 To correct this issue, all components on the page need to be initialized such that there is only ever **one class name generator** among them. さまざまなシナリオで、誤って2つのクラス名ジェネレータを使用することになる事例 - 誤ってMaterial-UIの2つのバージョンを**bundle**してしまっている場合、 依存関係がMaterial-UIを対の依存関係として正しく設定されていない可能性があります - You are using `StylesProvider` for a **subset** of your React tree. - バンドラーを使用していて、それが原因で複数のクラス名ジェネレータインスタンスが作成されるようにコードを分割している場合。 > Webパックで[SplitChunksPlugin](https://webpack.js.org/plugins/split-chunks-plugin/)を使用している場合は、[`最適化`で`runtimeChunk`](https://webpack.js.org/configuration/optimization/#optimization-runtimechunk)設定を構成してみてください。 Overall, it's simple to recover from this problem by wrapping each Material-UI application with [`StylesProvider`](/styles/api/#stylesprovider) components at the top of their component trees **and using a single class name generator shared among them**. ## モーダルを開くと、fixed positionされたDOMが移動するのはなぜですか? Scrolling is blocked as soon as a modal is opened. This prevents interacting with the background when the modal should be the only interactive content. However, removing the scrollbar can make your **fixed positioned elements** move. この場合、Material-UIにこれらのDOMを処理するように伝えるために、グローバルな `.mui-fixed`クラス名を適用することができます。 ## 波紋アニメーションをグローバルに無効にする方法は? 波紋アニメーションは、BaseButtonコンポーネントからのみ発生しています。 テーマに次のように指定することで、波紋アニメーションをグローバルに無効にすることができます。 ```js import { createMuiTheme } from '@material-ui/core'; const theme = createMuiTheme({ props: { // Name of the component ⚛️ MuiButtonBase: { // The properties to apply disableRipple: true, // No more ripple, on the whole application 💣! }, }, }); ``` ## 移行をグローバルに無効にするにはどうすればよいですか? Material-UI uses the same theme helper for creating all its transitions. Therefore you can disable all transitions by overriding the helper in your theme: ```js import { createMuiTheme } from '@material-ui/core'; const theme = createMuiTheme({ transitions: { // So we have `transition: none;` everywhere create: () => 'none', }, }); ``` It can be useful to disable transitions during visual testing or to improve performance on low-end devices. You can go one step further by disabling all transitions and animations effects: ```js import { createMuiTheme } from '@material-ui/core'; const theme = createMuiTheme({ overrides: { // Name of the component ⚛️ MuiCssBaseline: { // Name of the rule '@global': { '*, *::before, *::after': { transition: 'none !important', animation: 'none !important', }, }, }, }, }); ``` Notice that the usage of `CssBaseline` is required for the above approach to work. If you choose not to use it, you can still disable transitions and animations by including these CSS rules: ```css *, *::before, *::after { transition: 'none !important'; animation: 'none !important'; } ``` ## アプリのスタイルを設定するにはJSSを使用する必要がありますか? いいえ、必須ではありません。 But this dependency comes built in, so carries no additional bundle size overhead. Perhaps, however, you're adding some Material-UI components to an app that already uses another styling solution, or are already familiar with a different API, and don't want to learn a new one? その場合は、[スタイルライブラリの相互運用](/guides/interoperability/)セクションで、Material-UIコンポーネントを別のスタイルのライブラリでスタイル変更することがいかに簡単であるかを示します。 ## インラインスタイルとCSSのどちらを使用すべきか 経験則として、動的styleプロパティにはinline-styleのみを使用してください。 CSSの代替手段は、次のようなより多くの利点を提供します。 - auto-prefixing - デバックのしやすさ - メディアクエリ - keyframes ## react-routerの使い方は? We detail the [integration with third-party routing libraries](/guides/composition/#routing-libraries) like react-router, Gatsby or Next.js in our guide. ## どうやってDOM要素にアクセスできますか? DOM内の何かを描画するすべてのMaterial-UIコンポーネントは、そのrefを基礎となるDOMコンポーネントに転送します。 つまり、Material-UIコンポーネントにアタッチされたrefを読み取ることでDOM要素 を取得できます。 ```jsx // or a ref setter function const ref = React.createRef(); // render <Button ref={ref} />; // usage const element = ref.current; ``` 問題のMaterial-UIコンポーネントがそのrefを転送するかどうかわからない場合は、 [Button API](/api/button/#props)など、「プロパティ」のAPIドキュメントを確認できます。 含む > Refはルート要素に転送されます。 refを使用してDOM要素にアクセスできることを示します。 ## ページにスタイルのインスタンスがいくつかあります 次のような警告メッセージがコンソールに表示される場合は、ページ上で`@material-ui/styles`のインスタンスがいくつか初期化されている可能性があります。 > It looks like there are several instances of `@material-ui/styles` initialized in this application. This may cause theme propagation issues, broken class names, specificity issues, and make your application bigger without a good reason. ### 考えられる理由: これが起こる一般的な理由はいくつかあります。 - 依存関係のどこかに別の`@material-ui/styles`ライブラリがあります。 - プロジェクト(例:yarn workspaces)にmonorepo構造があり、`@material-ui/styles`モジュールが複数のパッケージ(これは前のとだいたい同じです)に依存しています。 - `@material-ui/styles`を使用する複数のアプリケーションが同じページ(たとえば、webpackの複数のエントリポイントが同じページにロードされる。)で実行されています。 ### node_modulesの重複モジュール If you think that the issue may be in the duplication of the @material-ui/styles module somewhere in your dependencies, there are several ways to check this. You can use `npm ls @material-ui/styles`, `yarn list @material-ui/styles` or `find -L ./node_modules | grep /@material-ui/styles/package.json` commands in your application folder. これらのコマンドで重複が識別されない場合は、バンドルを分析して@material-ui/stylesの複数のインスタンスを探してください。 これらのコマンドで重複が識別されない場合は、バンドルを分析して@material-ui/stylesの複数のインスタンスを探してください。 重複が発生している問題であることがわかった場合は、いくつかの解決方法があります。 Npmを使用している場合は、`npm dedupe`を実行してみてください。 このコマンドは、ローカルの依存関係を検索し、共通の依存関係をツリーの上位に移動して構造を単純化しようとします。 Webパックを使用している場合は、@material-ui/stylesモジュールを[解決](https://webpack.js.org/configuration/resolve/#resolve-modules)する方法を変更できます。 Webpackが依存関係を検索するデフォルトの順序を上書きし、アプリケーションのnode_modulesをデフォルトのノードモジュール解決順序よりも優先させることができます。 ```diff resolve: { + alias: { + "@material-ui/styles": path.resolve(appFolder, "node_modules", "@material-ui/styles"), + } } ``` ### Lernaでの使用 One possible fix to get @material-ui/styles to run in a Lerna monorepo across packages is to [hoist](https://github.com/lerna/lerna/blob/master/doc/hoist.md) shared dependencies to the root of your monorepo file. --hoistフラグを指定してbootstrap option を実行してみてください。 ```sh lerna bootstrap --hoist ``` または、パッケージから@material-ui/stylesを削除することもできます。jsonファイルを作成し、手動で最上位のパッケージに上げます。jsonファイルを使用します。 Lernaルートフォルダー内のpackage.jsonファイルの例 ```json { "name": "my-monorepo", "devDependencies": { "lerna": "latest" }, "dependencies": { "@material-ui/styles": "^4.0.0" }, "scripts": { "bootstrap": "lerna bootstrap", "clean": "lerna clean", "start": "lerna run start", "build": "lerna run build" } } ``` ### 1つのページで複数のアプリケーションを実行する 1つのページで複数のアプリケーションを実行している場合は、それらすべてに1つの@material-ui/stylesモジュールを使用することを検討してください。 Webパックを使用している場合は、[CommonsChunkPlugin](https://webpack.js.org/plugins/commons-chunk-plugin/)を使用して@material-ui/stylesモジュールを含む明示的な[vendor chunk](https://webpack.js.org/plugins/commons-chunk-plugin/#explicit-vendor-chunk), を作成できます。 ```diff module.exports = { entry: { + vendor: ["@material-ui/styles"], app1: "./src/app.1.js", app2: "./src/app.2.js", }, plugins: [ + new webpack.optimize.CommonsChunkPlugin({ + name: "vendor", + minChunks: Infinity, + }), ] } ``` ## サーバーでアプリが正しくレンダリングされない 動作しない場合は、99%のケースで設定の問題になります。 A missing property, a wrong call order, or a missing component – server-side rendering is strict about configuration, and the best way to find out what's wrong is to compare your project to an already working setup. Check out the [reference implementations](/guides/server-rendering/#reference-implementations), bit by bit. ### CSSは最初のロードでのみ機能し、その後欠落します CSSは、ページの最初のロード時にのみ生成されます。 この場合、CSSは連続した要求に対してサーバに存在しません。 #### 実行するアクション The styling solution relies on a cache, the *sheets manager*, to only inject the CSS once per component type (if you use two buttons, you only need the CSS of the button one time). 要求ごとに**新しい`シート`インスタンスを作成する必要があります**。 *修正の例:* ```diff -// Create a sheets instance. -const sheets = new ServerStyleSheets(); function handleRender(req, res) { + // Create a sheets instance. + const sheets = new ServerStyleSheets(); //… // Render the component to a string. const html = ReactDOMServer.renderToString( ``` ### Reactクラス名のハイドレーションの不一致 クライアントとサーバーの間にクラス名の不一致があります。 最初の要求で機能する場合があります。 う1つの症状は、初期ページ・ロードとクライアント・スクリプトのダウンロードの間でスタイル設定が変更されることです。 #### 実行するアクション クラス名の値は、[class name generator](/styles/advanced/#class-names)の概念に基づいています。 ページ全体を**単一のジェネレーターでレンダリングする必要があります** 。 このジェネレーターは、サーバーとクライアントで同じように動作する必要があります。 例えば: - 要求ごとに新しいクラス名ジェネレータを提供する必要があります。 しかし、異なるリクエスト間で`createGenerateClassName()`を共有すべきではありません。 *修正の例:* ```diff -// Create a new class name generator. -const generateClassName = createGenerateClassName(); function handleRender(req, res) { + // Create a new class name generator. + const generateClassName = createGenerateClassName(); //… // Render the component to a string. const html = ReactDOMServer.renderToString( ``` - しかし、異なるリクエスト間で**createGenerateClassName()**を共有すべきではありません。 マイナーバージョンの不一致でも、スタイルの問題が発生する可能性があります。 バージョン番号を確認するには、アプリケーションを構築する環境と配備環境で`npm list@material-ui/core`を実行します Package.jsonの依存関係に特定のMUIバージョンを指定することで、異なる環境で同じバージョンを使用することもできます。 *修正の例(package.json):* ```diff "dependencies": { ... - "@material-ui/core": "^4.0.0", + "@material-ui/core": "4.0.0", ... }, ``` - サーバーとクライアントが同じ`process.env.NODE_ENV` valueを共有していることを確認する必要があります。 ## 私が見ている色とこのサイトで見ている色が違うのはなぜですか? ドキュメントサイトはカスタムテーマを使用しています。 したがって、カラーパレットがあるMaterial-UIが提供しているデフォルトのテーマは異なります。 テーマのカスタマイズについて学ぶには、この[ページ](/customization/theming/)を参照してください。 ## Component Xがrefオブジェクトの代わりにpropでDOMノードを必要とするのはなぜですか? [Portal](/api/portal/#props)または[Popper](/api/popper/#props)のようなコンポーネントでは、それぞれ `container` または`anchorEl`プロパティにDOMノードが必要です。 これらのプロップにrefオブジェクトを渡し、Material-UIに現在の値にアクセスさせると便利です。 これは、次のような単純なシナリオで機能します。 ```jsx function App() { const container = React.useRef(null); return ( <div className="App"> <Portal container={container}> <span>portaled children</span> </Portal> <div ref={container} /> </div> ); } ``` ここで、`Portal`は、`container.current`が使用可能の場合にのみ、子をコンテナーにマウントします。 ポータルの単純な実装は次のとおりです。 ```jsx function Portal({ children, container }) { const [node, setNode] = React.useState(null); React.useEffect(() => { setNode(container.current); }, [container]); if (node === null) { return null; } return ReactDOM.createPortal(children, node); } ``` この単純なヒューリスティックな` Portal ` refはエフェクトが実行される前に最新であるため、マウント後に再レンダリングされる可能性があります。 ただし、refが最新であるからといって、定義済みインスタンスを指しているわけではありません。 refがref転送コンポーネントに接続されている場合、DOMノードがいつ使用可能になるかは不明です。 In the example above, the `Portal` would run an effect once, but might not re-render because `ref.current` is still `null`. This is especially apparent for React.lazy components in Suspense. 上記の実装では、DOMノードの変更も考慮できませんでした。 このため、Reactが`Portal`をいつ再レンダリングするかを決定できるように、実際のDOMノードを持つプロップが必要です。 ```jsx function App() { const [container, setContainer] = React.useState(null); const handleRef = React.useCallback(instance => setContainer(instance), [setContainer]) return ( <div className="App"> <Portal container={container}> <span>Portaled</span> </Portal> <div ref={handleRef} /> </div> ); } ``` ## Clsxの依存関係は何ですか? [clsx](https://github.com/lukeed/clsx) is a tiny utility for constructing `className` strings conditionally, out of an object with keys being the class strings, and values being booleans. Instead of writing: ```jsx // let disabled = false, selected = true; return ( <div className={`MuiButton-root ${disabled ? 'Mui-disabled' : ''} ${selected ? 'Mui-selected' : ''}`} /> ); ``` you can do: ```jsx import clsx from 'clsx'; return ( <div className={clsx('MuiButton-root', { 'Mui-disabled': disabled, 'Mui-selected': selected, })} /> ); ```
docs/src/pages/getting-started/faq/faq-ja.md
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.000502676353789866, 0.00019004734349437058, 0.00016083357331808656, 0.0001701585715636611, 0.00006861634756205603 ]
{ "id": 1, "code_window": [ "on:\n", " # So that PRs touching the same files as the push are updated\n", " push:\n", " branches-ignore:\n", " # PRs are almost never based off of dependabot PRs\n", " - 'dependabot/**'\n", " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z" /> , 'Work');
packages/material-ui-icons/src/Work.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.0001756489073159173, 0.0001756489073159173, 0.0001756489073159173, 0.0001756489073159173, 0 ]
{ "id": 1, "code_window": [ "on:\n", " # So that PRs touching the same files as the push are updated\n", " push:\n", " branches-ignore:\n", " # PRs are almost never based off of dependabot PRs\n", " - 'dependabot/**'\n", " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import { makeStyles, Theme, createStyles } from '@material-ui/core/styles'; import Alert from '@material-ui/lab/Alert'; import CheckIcon from '@material-ui/icons/Check'; import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline'; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { width: '100%', '& > * + *': { marginTop: theme.spacing(2), }, }, }), ); export default function IconAlerts() { const classes = useStyles(); return ( <div className={classes.root}> <Alert icon={<CheckIcon fontSize="inherit" />} severity="success"> This is a success alert — check it out! </Alert> <Alert iconMapping={{ success: <CheckCircleOutlineIcon fontSize="inherit" />, }} > This is a success alert — check it out! </Alert> <Alert icon={false} severity="success"> This is a success alert — check it out! </Alert> </div> ); }
docs/src/pages/components/alert/IconAlerts.tsx
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00017834678874351084, 0.00017577302060090005, 0.0001730207004584372, 0.0001758623111527413, 0.0000020496790966717526 ]
{ "id": 2, "code_window": [ " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n", " pull_request_target:\n", " branches-ignore:\n", " # These PRs are almost fully automated so labelling them is not as important.\n", " # They do burst the GitHub API though so we're ignoring them to not hit the rate limit\n", " - 'dependabot/**'\n", " types: [synchronize]\n", "\n", "jobs:\n", " main:\n", " runs-on: ubuntu-latest\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 11 }
trigger: branches: include: - '*' exclude: - l10n - dependabot/* schedules: - cron: '0 0 * * *' displayName: Run with React canary branches: include: - master - next always: true # https://developercommunity.visualstudio.com/comments/949241/view.html pr: branches: include: - '*' pool: vmImage: 'ubuntu-latest' variables: DOCS_NEXT_CACHE_FOLDER: $(Build.SourcesDirectory)/docs/.next/cache # azure-pipelines don't support variables per trigger # We assume that the only scheduled job we have is for react@next ${{ if eq( variables['Build.Reason'], 'Schedule' ) }}: # npm dist tag for `react` (https://docs.npmjs.com/cli/dist-tag) REACT_DIST_TAG: 'next' # Path for artifacts uploaded to S3 that can be used as a permalink S3_ARTIFACTS_PATH_PERMA: 'artifacts/$(Build.SourceBranchName)-react-$(REACT_DIST_TAG)/$(Build.SourceVersion)/' ${{ if ne( variables['Build.Reason'], 'Schedule' ) }}: REACT_DIST_TAG: 'stable' # Preserve this path structure since it is locked in various tooling S3_ARTIFACTS_PATH_PERMA: 'artifacts/$(Build.SourceBranchName)/$(Build.SourceVersion)/' steps: - task: NodeTool@0 inputs: versionSpec: '10.x' displayName: 'Install Node.js' - script: | node scripts/use-react-dist-tag.js $(REACT_DIST_TAG) yarn install displayName: 'install dependencies' - script: | yarn lerna run --ignore @material-ui/icons --parallel --scope "@material-ui/*" build displayName: 'build @material-ui packages' - script: | cd packages/material-ui/build npm version 0.0.0-canary.$(Build.SourceVersion) --no-git-tag-version npm pack mv material-ui-core-0.0.0-canary.$(Build.SourceVersion).tgz ../../../material-ui-core.tgz displayName: 'create @material-ui/core canary distributable' - task: S3Upload@1 inputs: regionName: 'eu-central-1' bucketName: 'eps1lon-material-ui' globExpressions: '*.tgz' targetFolder: $(S3_ARTIFACTS_PATH_PERMA) filesAcl: 'public-read' displayName: 'Upload distributables to S3' condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) env: AWS_ACCESS_KEY_ID: $(AWS_ACCESS_KEY_ID) AWS_SECRET_ACCESS_KEY: $(AWS_SECRET_ACCESS_KEY) - task: PublishPipelineArtifact@1 inputs: artifactName: 'canaries' targetPath: 'material-ui-core.tgz' - task: Cache@2 inputs: key: 'yarn | "$(Agent.OS)" | yarn.lock' restoreKeys: | yarn | "$(Agent.OS)" yarn path: $(DOCS_NEXT_CACHE_FOLDER) displayName: Cache nextjs build - script: | mkdir -p scripts/sizeSnapshot/build yarn docs:build | tee scripts/sizeSnapshot/build/docs.next displayName: 'build docs for size snapshot' env: NODE_OPTIONS: '--max_old_space_size=4096' - script: | yarn size:snapshot displayName: 'create a size snapshot' - task: PublishPipelineArtifact@1 displayName: 'persist size snapshot as pipeline artifact' inputs: artifactName: 'size-snapshot' targetPath: 'size-snapshot.json' - task: AmazonWebServices.aws-vsts-tools.S3Upload.S3Upload@1 displayName: 'persist size snapshot on S3' condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) inputs: awsCredentials: 's3 artifacts' regionName: 'eu-central-1' bucketName: 'eps1lon-material-ui' sourceFolder: '$(System.DefaultWorkingDirectory)' globExpressions: 'size-snapshot.json' targetFolder: $(S3_ARTIFACTS_PATH_PERMA) filesAcl: 'public-read' contentType: application/json logRequest: true logResponse: true - task: AmazonWebServices.aws-vsts-tools.S3Upload.S3Upload@1 displayName: 'symlink size-snapshot to latest' condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'), ne(variables['Build.Reason'], 'Schedule')) inputs: awsCredentials: 's3 artifacts' regionName: 'eu-central-1' bucketName: 'eps1lon-material-ui' sourceFolder: '$(System.DefaultWorkingDirectory)' globExpressions: 'size-snapshot.json' targetFolder: 'artifacts/$(Build.SourceBranchName)/latest/' filesAcl: 'public-read' contentType: application/json logRequest: true logResponse: true - script: | yarn danger ci displayName: 'run danger on PRs' condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest')) env: AZURE_BUILD_ID: $(Build.BuildId) DANGER_GITHUB_API_TOKEN: $(GITHUB_API_TOKEN)
azure-pipelines.yml
1
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.0002900991530623287, 0.00018004966841544956, 0.00016418826999142766, 0.00017157512775156647, 0.00003029951039934531 ]
{ "id": 2, "code_window": [ " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n", " pull_request_target:\n", " branches-ignore:\n", " # These PRs are almost fully automated so labelling them is not as important.\n", " # They do burst the GitHub API though so we're ignoring them to not hit the rate limit\n", " - 'dependabot/**'\n", " types: [synchronize]\n", "\n", "jobs:\n", " main:\n", " runs-on: ubuntu-latest\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 11 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 9c-.04-4.39-3.6-7.93-8-7.93S4.04 4.61 4 9v6c0 4.42 3.58 8 8 8s8-3.58 8-8V9zm-2 0h-5V3.16c2.81.47 4.96 2.9 5 5.84zm-7-5.84V9H6c.04-2.94 2.19-5.37 5-5.84zM18 15c0 3.31-2.69 6-6 6s-6-2.69-6-6v-4h12v4z" /> , 'MouseOutlined');
packages/material-ui-icons/src/MouseOutlined.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.0001759071892593056, 0.0001759071892593056, 0.0001759071892593056, 0.0001759071892593056, 0 ]
{ "id": 2, "code_window": [ " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n", " pull_request_target:\n", " branches-ignore:\n", " # These PRs are almost fully automated so labelling them is not as important.\n", " # They do burst the GitHub API though so we're ignoring them to not hit the rate limit\n", " - 'dependabot/**'\n", " types: [synchronize]\n", "\n", "jobs:\n", " main:\n", " runs-on: ubuntu-latest\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 11 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M21 5c-1.11-.35-2.33-.5-3.5-.5-1.95 0-4.05.4-5.5 1.5-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6v14.65c0 .25.25.5.5.5.1 0 .15-.05.25-.05C3.1 20.45 5.05 20 6.5 20c1.95 0 4.05.4 5.5 1.5 1.35-.85 3.8-1.5 5.5-1.5 1.65 0 3.35.3 4.75 1.05.1.05.15.05.25.05.25 0 .5-.25.5-.5V6c-.6-.45-1.25-.75-2-1zm0 13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5V8c1.35-.85 3.8-1.5 5.5-1.5 1.2 0 2.4.15 3.5.5v11.5z" /><path d="M17.5 10.5c.88 0 1.73.09 2.5.26V9.24c-.79-.15-1.64-.24-2.5-.24-1.7 0-3.24.29-4.5.83v1.66c1.13-.64 2.7-.99 4.5-.99zM13 12.49v1.66c1.13-.64 2.7-.99 4.5-.99.88 0 1.73.09 2.5.26V11.9c-.79-.15-1.64-.24-2.5-.24-1.7 0-3.24.3-4.5.83zM17.5 14.33c-1.7 0-3.24.29-4.5.83v1.66c1.13-.64 2.7-.99 4.5-.99.88 0 1.73.09 2.5.26v-1.52c-.79-.16-1.64-.24-2.5-.24z" /></React.Fragment> , 'MenuBook');
packages/material-ui-icons/src/MenuBook.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.000215745487366803, 0.000215745487366803, 0.000215745487366803, 0.000215745487366803, 0 ]
{ "id": 2, "code_window": [ " # So that the `dirtyLabel` is removed if conflicts are resolved\n", " # Could put too much strain on rate limit\n", " # If we hit the rate limit too often remove this event\n", " pull_request_target:\n", " branches-ignore:\n", " # These PRs are almost fully automated so labelling them is not as important.\n", " # They do burst the GitHub API though so we're ignoring them to not hit the rate limit\n", " - 'dependabot/**'\n", " types: [synchronize]\n", "\n", "jobs:\n", " main:\n", " runs-on: ubuntu-latest\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " branches:\n", " - master\n", " - next\n" ], "file_path": ".github/workflows/maintenance.yml", "type": "replace", "edit_start_line_idx": 11 }
import * as React from 'react'; import { withStyles, Theme, createStyles, makeStyles, } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; const StyledTableCell = withStyles((theme: Theme) => createStyles({ head: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white, }, body: { fontSize: 14, }, }), )(TableCell); const StyledTableRow = withStyles((theme: Theme) => createStyles({ root: { '&:nth-of-type(odd)': { backgroundColor: theme.palette.action.hover, }, // hide last border '&:last-child td, &:last-child th': { border: 0, }, }, }), )(TableRow); function createData( name: string, calories: number, fat: number, carbs: number, protein: number, ) { return { name, calories, fat, carbs, protein }; } const rows = [ createData('Frozen yoghurt', 159, 6.0, 24, 4.0), createData('Ice cream sandwich', 237, 9.0, 37, 4.3), createData('Eclair', 262, 16.0, 24, 6.0), createData('Cupcake', 305, 3.7, 67, 4.3), createData('Gingerbread', 356, 16.0, 49, 3.9), ]; const useStyles = makeStyles({ table: { minWidth: 700, }, }); export default function CustomizedTables() { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="customized table"> <TableHead> <TableRow> <StyledTableCell>Dessert (100g serving)</StyledTableCell> <StyledTableCell align="right">Calories</StyledTableCell> <StyledTableCell align="right">Fat&nbsp;(g)</StyledTableCell> <StyledTableCell align="right">Carbs&nbsp;(g)</StyledTableCell> <StyledTableCell align="right">Protein&nbsp;(g)</StyledTableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <StyledTableRow key={row.name}> <StyledTableCell component="th" scope="row"> {row.name} </StyledTableCell> <StyledTableCell align="right">{row.calories}</StyledTableCell> <StyledTableCell align="right">{row.fat}</StyledTableCell> <StyledTableCell align="right">{row.carbs}</StyledTableCell> <StyledTableCell align="right">{row.protein}</StyledTableCell> </StyledTableRow> ))} </TableBody> </Table> </TableContainer> ); }
docs/src/pages/components/tables/CustomizedTables.tsx
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00017736927838996053, 0.00017386880062986165, 0.0001661612041061744, 0.00017462711548432708, 0.0000027946427962888265 ]
{ "id": 3, "code_window": [ "trigger:\n", " branches:\n", " include:\n", " - '*'\n", " exclude:\n", " - l10n\n", " - dependabot/*\n", "\n", "schedules:\n", " - cron: '0 0 * * *'\n", " displayName: Run with React canary\n", " branches:\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " - 'master'\n", " - 'next'\n" ], "file_path": "azure-pipelines.yml", "type": "replace", "edit_start_line_idx": 3 }
name: 'Maintenance' on: # So that PRs touching the same files as the push are updated push: branches-ignore: # PRs are almost never based off of dependabot PRs - 'dependabot/**' # So that the `dirtyLabel` is removed if conflicts are resolved # Could put too much strain on rate limit # If we hit the rate limit too often remove this event pull_request_target: branches-ignore: # These PRs are almost fully automated so labelling them is not as important. # They do burst the GitHub API though so we're ignoring them to not hit the rate limit - 'dependabot/**' types: [synchronize] jobs: main: runs-on: ubuntu-latest steps: - name: check if prs are dirty uses: eps1lon/actions-label-merge-conflict@releases/2.x with: dirtyLabel: 'PR: out-of-date' removeOnDirtyLabel: 'PR: ready to ship' repoToken: '${{ secrets.GITHUB_TOKEN }}' retryAfter: 130 retryMax: 10
.github/workflows/maintenance.yml
1
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.0011952195782214403, 0.0007884558290243149, 0.0001731309457682073, 0.000997017021290958, 0.0004425604420248419 ]
{ "id": 3, "code_window": [ "trigger:\n", " branches:\n", " include:\n", " - '*'\n", " exclude:\n", " - l10n\n", " - dependabot/*\n", "\n", "schedules:\n", " - cron: '0 0 * * *'\n", " displayName: Run with React canary\n", " branches:\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " - 'master'\n", " - 'next'\n" ], "file_path": "azure-pipelines.yml", "type": "replace", "edit_start_line_idx": 3 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z" /> , 'Block');
packages/material-ui-icons/src/Block.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00016596690693404526, 0.00016596690693404526, 0.00016596690693404526, 0.00016596690693404526, 0 ]
{ "id": 3, "code_window": [ "trigger:\n", " branches:\n", " include:\n", " - '*'\n", " exclude:\n", " - l10n\n", " - dependabot/*\n", "\n", "schedules:\n", " - cron: '0 0 * * *'\n", " displayName: Run with React canary\n", " branches:\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " - 'master'\n", " - 'next'\n" ], "file_path": "azure-pipelines.yml", "type": "replace", "edit_start_line_idx": 3 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M9.17 6H4v12h16V8h-8.83l-2-2z" opacity=".3" /><path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V6h5.17l2 2H20v10zm-2.5-5.88v3.38h-3v-5h1.38l1.62 1.62zM16.5 9H13v8h6v-5.5L16.5 9z" /></React.Fragment> , 'SnippetFolderTwoTone');
packages/material-ui-icons/src/SnippetFolderTwoTone.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00016754328680690378, 0.00016754328680690378, 0.00016754328680690378, 0.00016754328680690378, 0 ]
{ "id": 3, "code_window": [ "trigger:\n", " branches:\n", " include:\n", " - '*'\n", " exclude:\n", " - l10n\n", " - dependabot/*\n", "\n", "schedules:\n", " - cron: '0 0 * * *'\n", " displayName: Run with React canary\n", " branches:\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " - 'master'\n", " - 'next'\n" ], "file_path": "azure-pipelines.yml", "type": "replace", "edit_start_line_idx": 3 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M6.36 18.78L6.61 21l1.62-1.54 2.77-7.6c-.68-.17-1.28-.51-1.77-.98l-2.87 7.9zM14.77 10.88c-.49.47-1.1.81-1.77.98l2.77 7.6L17.39 21l.26-2.22-2.88-7.9zM15 8c0-1.3-.84-2.4-2-2.82V3h-2v2.18C9.84 5.6 9 6.7 9 8c0 1.66 1.34 3 3 3s3-1.34 3-3zm-3 1c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /> , 'Architecture');
packages/material-ui-icons/src/Architecture.js
0
https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462
[ 0.00016673305071890354, 0.00016673305071890354, 0.00016673305071890354, 0.00016673305071890354, 0 ]
{ "id": 0, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 117 }
'use strict'; const fs = require('fs'); const path = require('path'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createAuthRequest } = require('../../../../../test/helpers/request'); let strapi; let rq; let rqAdmin; let uploadFolder; describe('Uploads folder (GraphQL)', () => { beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); }); describe('uploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('multipleUploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); });
packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.998593270778656, 0.2559056282043457, 0.0001656609820201993, 0.004525825381278992, 0.428683340549469 ]
{ "id": 0, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 117 }
export const ADD_ATTRIBUTE = 'ContentTypeBuilder/DataManagerProvider/ADD_ATTRIBUTE'; export const ADD_CUSTOM_FIELD_ATTRIBUTE = 'ContentTypeBuilder/DataManagerProvider/ADD_CUSTOM_FIELD_ATTRIBUTE'; export const ADD_CREATED_COMPONENT_TO_DYNAMIC_ZONE = 'ContentTypeBuilder/DataManagerProvider/ADD_CREATED_COMPONENT_TO_DYNAMIC_ZONE'; export const CHANGE_DYNAMIC_ZONE_COMPONENTS = 'ContentTypeBuilder/DataManagerProvider/CHANGE_DYNAMIC_ZONE_COMPONENTS'; export const CREATE_SCHEMA = 'ContentTypeBuilder/DataManagerProvider/CREATE_SCHEMA'; export const CREATE_COMPONENT_SCHEMA = 'ContentTypeBuilder/DataManagerProvider/CREATE_COMPONENT_SCHEMA'; export const DELETE_NOT_SAVED_TYPE = 'ContentTypeBuilder/DataManagerProvider/DELETE_NOT_SAVED_TYPE'; export const EDIT_ATTRIBUTE = 'ContentTypeBuilder/DataManagerProvider/EDIT_ATTRIBUTE'; export const EDIT_CUSTOM_FIELD_ATTRIBUTE = 'ContentTypeBuilder/DataManagerProvider/EDIT_CUSTOM_FIELD_ATTRIBUTE'; export const GET_DATA_SUCCEEDED = 'ContentTypeBuilder/DataManagerProvider/GET_DATA_SUCCEEDED'; export const RELOAD_PLUGIN = 'ContentTypeBuilder/DataManagerProvider/RELOAD_PLUGIN'; export const REMOVE_FIELD_FROM_DISPLAYED_COMPONENT = 'ContentTypeBuilder/DataManagerProvider/REMOVE_FIELD_FROM_DISPLAYED_COMPONENT'; export const REMOVE_COMPONENT_FROM_DYNAMIC_ZONE = 'ContentTypeBuilder/DataManagerProvider/REMOVE_COMPONENT_FROM_DYNAMIC_ZONE'; export const REMOVE_FIELD = 'ContentTypeBuilder/DataManagerProvider/REMOVE_FIELD'; export const SET_MODIFIED_DATA = 'ContentTypeBuilder/DataManagerProvider/SET_MODIFIED_DATA'; export const UPDATE_SCHEMA = 'ContentTypeBuilder/DataManagerProvider/UPDATE_SCHEMA';
packages/core/content-type-builder/admin/src/components/DataManagerProvider/constants.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00031026481883600354, 0.0002400700032012537, 0.000172762869624421, 0.00023718233569525182, 0.0000561720626137685 ]
{ "id": 0, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 117 }
'use strict'; const { join } = require('path'); const fse = require('fs-extra'); const { defaultsDeep, getOr, get } = require('lodash/fp'); const { env } = require('@strapi/utils'); const loadConfigFile = require('../../app-configuration/load-config-file'); const loadFiles = require('../../../load/load-files'); const getEnabledPlugins = require('./get-enabled-plugins'); const getUserPluginsConfig = require('./get-user-plugins-config'); const defaultPlugin = { bootstrap() {}, destroy() {}, register() {}, config: { default: {}, validator() {}, }, routes: [], controllers: {}, services: {}, policies: {}, middlewares: {}, contentTypes: {}, }; const applyUserExtension = async (plugins) => { const extensionsDir = strapi.dirs.dist.extensions; if (!(await fse.pathExists(extensionsDir))) { return; } const extendedSchemas = await loadFiles(extensionsDir, '**/content-types/**/schema.json'); const strapiServers = await loadFiles(extensionsDir, '**/strapi-server.js'); for (const pluginName of Object.keys(plugins)) { const plugin = plugins[pluginName]; // first: load json schema for (const ctName of Object.keys(plugin.contentTypes)) { const extendedSchema = get([pluginName, 'content-types', ctName, 'schema'], extendedSchemas); if (extendedSchema) { plugin.contentTypes[ctName].schema = { ...plugin.contentTypes[ctName].schema, ...extendedSchema, }; } } // second: execute strapi-server extension const strapiServer = get([pluginName, 'strapi-server'], strapiServers); if (strapiServer) { plugins[pluginName] = await strapiServer(plugin); } } }; const applyUserConfig = async (plugins) => { const userPluginsConfig = await getUserPluginsConfig(); for (const pluginName of Object.keys(plugins)) { const plugin = plugins[pluginName]; const userPluginConfig = getOr({}, `${pluginName}.config`, userPluginsConfig); const defaultConfig = typeof plugin.config.default === 'function' ? plugin.config.default({ env }) : plugin.config.default; const config = defaultsDeep(defaultConfig, userPluginConfig); try { plugin.config.validator(config); } catch (e) { throw new Error(`Error regarding ${pluginName} config: ${e.message}`); } plugin.config = config; } }; const loadPlugins = async (strapi) => { const plugins = {}; const enabledPlugins = await getEnabledPlugins(strapi); strapi.config.set('enabledPlugins', enabledPlugins); for (const pluginName of Object.keys(enabledPlugins)) { const enabledPlugin = enabledPlugins[pluginName]; const serverEntrypointPath = join(enabledPlugin.pathToPlugin, 'strapi-server.js'); // only load plugins with a server entrypoint if (!(await fse.pathExists(serverEntrypointPath))) { continue; } const pluginServer = loadConfigFile(serverEntrypointPath); plugins[pluginName] = defaultsDeep(defaultPlugin, pluginServer); } // TODO: validate plugin format await applyUserConfig(plugins); await applyUserExtension(plugins); for (const pluginName of Object.keys(plugins)) { strapi.container.get('plugins').add(pluginName, plugins[pluginName]); } }; module.exports = loadPlugins;
packages/core/strapi/lib/core/loaders/plugins/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001755770790623501, 0.0001734200632199645, 0.00016949880227912217, 0.0001739778817864135, 0.000001928348410729086 ]
{ "id": 0, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 117 }
import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'; import { useSelector, shallowEqual } from 'react-redux'; import axios from 'axios'; import { axiosInstance } from '../../../core/utils'; import formatLayouts from './utils/formatLayouts'; import reducer, { initialState } from './reducer'; import { makeSelectModelAndComponentSchemas } from '../../pages/App/selectors'; import { getRequestUrl } from '../../utils'; const useFetchContentTypeLayout = (contentTypeUID) => { const [{ error, isLoading, layout, layouts }, dispatch] = useReducer(reducer, initialState); const schemasSelector = useMemo(makeSelectModelAndComponentSchemas, []); const { schemas } = useSelector((state) => schemasSelector(state), shallowEqual); const isMounted = useRef(true); const getData = useCallback( async (uid, source) => { if (layouts[uid]) { dispatch({ type: 'SET_LAYOUT_FROM_STATE', uid }); return; } dispatch({ type: 'GET_DATA' }); try { const endPoint = getRequestUrl(`content-types/${uid}/configuration`); const { data: { data }, } = await axiosInstance.get(endPoint, { cancelToken: source.token }); dispatch({ type: 'GET_DATA_SUCCEEDED', data: formatLayouts(data, schemas), }); } catch (error) { if (axios.isCancel(error)) { return; } if (isMounted.current) { console.error(error); } if (isMounted.current) { dispatch({ type: 'GET_DATA_ERROR', error }); } } }, [layouts, schemas] ); useEffect(() => { return () => { isMounted.current = false; }; }, []); useEffect(() => { const CancelToken = axios.CancelToken; const source = CancelToken.source(); getData(contentTypeUID, source); return () => { source.cancel('Operation canceled by the user.'); }; }, [contentTypeUID, getData]); const updateLayout = useCallback( (data) => { dispatch({ type: 'UPDATE_LAYOUT', newLayout: formatLayouts(data, schemas), }); }, [schemas] ); return { error, isLoading, layout, updateLayout, }; }; export default useFetchContentTypeLayout;
packages/core/admin/admin/src/content-manager/hooks/useFetchContentTypeLayout/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001756772107910365, 0.00017350692360196263, 0.00016843483899720013, 0.00017441506497561932, 0.0000024060850591922645 ]
{ "id": 1, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 172 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9986369013786316, 0.34387272596359253, 0.00016395156853832304, 0.002854864578694105, 0.464840292930603 ]
{ "id": 1, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 172 }
{ "Analytics": "Analitika", "Auth.components.Oops.text": "A fiókodat felfüggesztettük", "Auth.components.Oops.text.admin": "Amennyiben ez hiba, kérjük vegye fel a kapcsolatot az adminisztrátorokkal!", "Auth.components.Oops.title": "Oops...", "Auth.form.button.forgot-password": "Email küldése", "Auth.form.button.go-home": "Vissza a kezdőlapra", "Auth.form.button.login": "Bejelentkezés", "Auth.form.button.login.providers.error": "Nem sikerült kapcsolódni a szolgáltatón keresztül", "Auth.form.button.login.strapi": "Bejelentkezés Strapi-val", "Auth.form.button.password-recovery": "Jelszó visszaállítása", "Auth.form.button.register": "Kezdjük", "Auth.form.confirmPassword.label": "Jelszó megerősítése", "Auth.form.currentPassword.label": "Jelenlegi jelszó", "Auth.form.email.label": "Email", "Auth.form.email.placeholder": "e.g. [email protected]", "Auth.form.error.blocked": "A fiókodat az adminisztrátor blokkolta", "Auth.form.error.code.provide": "Hibás a megadott kód", "Auth.form.error.confirmed": "Az email cím nincs megerősítve", "Auth.form.error.email.invalid": "Hibás email.", "Auth.form.error.email.provide": "Kérjük adja meg felhasználónevét és jelszavát.", "Auth.form.error.email.taken": "Ez az email cím már foglalt.", "Auth.form.error.invalid": "Felhasználónév vagy jelszó hibás.", "Auth.form.error.params.provide": "Hibás a megadott adat.", "Auth.form.error.password.format": "A jelszó nem tartalmazhatja a `$` szimbólumot többször, mint három.", "Auth.form.error.password.local": "Ez a felhasználó nem állított be jelszót, kérjük jelentkezzen be szolgáltatón keresztül.", "Auth.form.error.password.matching": "A jelszavak nem egeyznek.", "Auth.form.error.password.provide": "Kérjük adja meg a jelszavát.", "Auth.form.error.ratelimit": "Túl sok próbálkozás, kérjük próbálkozzon újra egy perc múlva.", "Auth.form.error.user.not-exist": "Ez az email nem létezik.", "Auth.form.error.username.taken": "A felhasználónév foglalt.", "Auth.form.firstname.label": "Keresztnév", "Auth.form.firstname.placeholder": "e.g. Kai", "Auth.form.forgot-password.email.label": "Adja meg az email címét", "Auth.form.forgot-password.email.label.success": "Az email-t sikeresen kiküldtük", "Auth.form.lastname.label": "Vezetéknév", "Auth.form.lastname.placeholder": "e.g. Doe", "Auth.form.password.hide-password": "Jelszó elrejtése", "Auth.form.password.hint": "A jelszónak legalább 8 karaktert, 1 nagybetűt, 1 kisbetűt és 1 számot kell tartalmaznia.", "Auth.form.password.show-password": "Jelszó megjelenítése", "Auth.form.register.news.label": "Értesítést kérek az új funkciókról és javításokról (ezzel elfogadja a {terms} és a {policy}).", "Auth.form.register.subtitle": "Ez csak az admin oldalra való bejelentkezésre ad lehetőséget. Minden elmentett adat a saját adatbázisaba kerül mentésre.", "Auth.form.rememberMe.label": "Emlékezz rám", "Auth.form.username.label": "Felhasználónév", "Auth.form.username.placeholder": "e.g. Kai_Doe", "Auth.form.welcome.subtitle": "Bejelentkezés a Strapi fiókjába", "Auth.form.welcome.title": "Üdvözöljük!", "Auth.link.forgot-password": "Elfelejtette a jelszavát?", "Auth.link.ready": "Készen áll a bejelentkezésre?", "Auth.link.signin": "Bejelentkezés", "Auth.link.signin.account": "Már van felhasználói fiókja?", "Auth.login.sso.divider": "Vagy bejelentkezés ezzel:", "Auth.login.sso.loading": "Szolgáltatók betöltése...", "Auth.login.sso.subtitle": "Bejelentkezés a fiókjába SSO-val", "Auth.privacy-policy-agreement.policy": "adatvédelmi nyilatkozat", "Auth.privacy-policy-agreement.terms": "felhasználási feltételek", "Content Manager": "Tartalom Menedzser", "Content Type Builder": "Tartalomtípus építő", "Documentation": "Dokumentáció", "Email": "Email", "Files Upload": "Fájl feltöltés", "HomePage.helmet.title": "Kezdőlap", "HomePage.roadmap": "Nézze meg a terveinket", "HomePage.welcome.congrats": "Gratulálunk!", "HomePage.welcome.congrats.content": "Első adminisztrátorként jelentkezett be. Ahhoz, hogy felfedezhesse a Strapi funkcióit,", "HomePage.welcome.congrats.content.bold": "azt ajánljuk, hogy hozza létre az első tartalomtípust.", "Media Library": "Média Könyvtár", "New entry": "Új elem", "Password": "Jelszó", "Provider": "Szolgáltató", "ResetPasswordToken": "Token visszaállítása", "Role": "Szerepkör", "Roles & Permissions": "Szerepkörök & Engedélyek", "Roles.ListPage.notification.delete-all-not-allowed": "Egyes szerepkörök nem törölhetők, mivel felhasználókhoz vannak társítva", "Roles.ListPage.notification.delete-not-allowed": "A felhasználókhoz társított szerepkör nem törölhető", "Roles.RoleRow.select-all": "{name} kiválasztása tömeges műveletekhez", "Roles.components.List.empty.withSearch": "Nincs a keresésnek megfelelő szerepkör ({search})...", "Settings.PageTitle": "Beállítások - {name}", "Settings.apiTokens.addFirstToken": "Első API Token hozzáadása", "Settings.apiTokens.addNewToken": "Új API Token hozzáadása", "Settings.apiTokens.copy.editMessage": "Biztonsági okokból csak egyszer láthatja a tokent.", "Settings.apiTokens.copy.editTitle": "Ez a token már nem elérhető.", "Settings.apiTokens.copy.lastWarning": "Másolja le a tokent, mert később már nem lesz látható!", "Settings.apiTokens.create": "Új hozzáadása", "Settings.apiTokens.description": "Az API felhasználásához generált tokenek listája", "Settings.apiTokens.emptyStateLayout": "Még nincs tartalom hozzáadva...", "Settings.apiTokens.notification.copied": "Token a vágólapra másolva.", "Settings.apiTokens.title": "API Token-ek", "Settings.apiTokens.types.full-access": "Teljes hozzáférés", "Settings.apiTokens.types.read-only": "Csak olvasható", "Settings.application.description": "Az adminisztrációs panel globális információi", "Settings.application.edition-title": "Aktuális csomag", "Settings.application.get-help": "Kérje segítségünket", "Settings.application.link-pricing": "Tekintse meg az összes csomagot", "Settings.application.link-upgrade": "Frissítse az adminisztrációs panelt", "Settings.application.node-version": "node verzió", "Settings.application.strapi-version": "strapi verzió", "Settings.application.strapiVersion": "strapi verzió", "Settings.application.title": "Áttekintés", "Settings.error": "Hiba", "Settings.global": "Globális Beállítások", "Settings.permissions": "Adminisztrációs panel", "Settings.permissions.category": "{category} engedélyeinek beállításai", "Settings.permissions.category.plugins": "{category} plugin engedélyeinek beállításai", "Settings.permissions.conditions.anytime": "Bármikor", "Settings.permissions.conditions.apply": "Alkalmaz", "Settings.permissions.conditions.can": "Tudja", "Settings.permissions.conditions.conditions": "Határozza meg a feltételeket", "Settings.permissions.conditions.links": "Linkek", "Settings.permissions.conditions.no-actions": "Először választania kell egy műveletet (create, read, update, ...) mielőtt megadja a feltételeket.", "Settings.permissions.conditions.none-selected": "Bármikor", "Settings.permissions.conditions.or": "VAGY", "Settings.permissions.conditions.when": "Mikor", "Settings.permissions.select-all-by-permission": "Minden {label} hozzáféres kiválasztása", "Settings.permissions.select-by-permission": "{label} hozzáféres kiválasztása", "Settings.permissions.users.create": "Új felhasználó meghívása", "Settings.permissions.users.email": "Email", "Settings.permissions.users.firstname": "Keresztnév", "Settings.permissions.users.lastname": "Vezetéknév", "Settings.permissions.users.form.sso": "Csatlakozas SSO-val", "Settings.permissions.users.form.sso.description": "Ha engedélyezve van (ON), a felhasználók bejelentkezhetnek SSO-n keresztül", "Settings.permissions.users.listview.header.subtitle": "Minden felhasználó, aki hozzáfér a Strapi adminisztrációs panelhez", "Settings.permissions.users.tabs.label": "Hozzáférések Tab", "Settings.profile.form.notify.data.loaded": "Profiladatok betöltve", "Settings.profile.form.section.experience.clear.select": "A kiválasztott felület nyelvének törlése", "Settings.profile.form.section.experience.documentation": "dokumentáció", "Settings.profile.form.section.experience.interfaceLanguage": "A felület nyelve", "Settings.profile.form.section.experience.interfaceLanguage.hint": "Ez csak a saját felületét jeleníti meg a kiválasztott nyelven.", "Settings.profile.form.section.experience.interfaceLanguageHelp": "A kiválasztás csak az Ön számára módosítja a felület nyelvét. Kérjük, olvassa el ezt a {document}, hogy más nyelveket a csapata számára is elérhetővé tehesse.", "Settings.profile.form.section.experience.title": "Tapasztalat", "Settings.profile.form.section.helmet.title": "Felhasználói profil", "Settings.profile.form.section.profile.page.title": "Profil oldal", "Settings.roles.create.description": "Határozza meg a szerephezkörhöz biztosított jogokat", "Settings.roles.create.title": "Szerepkör létrehozása", "Settings.roles.created": "A szerepkör létrejött", "Settings.roles.edit.title": "Szerepkör módosítása", "Settings.roles.form.created": "Létrehozva", "Settings.roles.form.description": "A szerepkör neve és leírása", "Settings.roles.form.permission.property-label": "{label} hozzáfére's", "Settings.roles.form.permissions.attributesPermissions": "Mezők hozzáférései", "Settings.roles.form.permissions.create": "Létrehoz", "Settings.roles.form.permissions.delete": "Töröl", "Settings.roles.form.permissions.publish": "Közzétesz", "Settings.roles.form.permissions.read": "Olvasás", "Settings.roles.form.permissions.update": "Frissítés", "Settings.roles.list.button.add": "Új szerepkör hozzáadása", "Settings.roles.list.description": "Szerepkörök listája", "Settings.roles.title.singular": "Szerepkör", "Settings.sso.description": "Konfigurálja az egyszeri bejelentkezés funkció beállításait.", "Settings.sso.form.defaultRole.description": "Az új hitelesített felhasználót a kiválasztott szerepkörhöz csatolja", "Settings.sso.form.defaultRole.description-not-allowed": "Nincs megfelelő engedélye az adminisztrátori szerepkörök olvasásához", "Settings.sso.form.defaultRole.label": "Alapértelmezett szerepkör", "Settings.sso.form.registration.description": "Egyszeri bejelentkezéskor, ha nincs fiók, hozzon létre új felhasználót", "Settings.sso.form.registration.label": "Automatikus regisztráció", "Settings.sso.title": "Egyszeri bejelentkezés", "Settings.webhooks.create": "Webhook létrehozása", "Settings.webhooks.create.header": "Új fejléc létrehozása", "Settings.webhooks.created": "Webhook létrehozva", "Settings.webhooks.event.publish-tooltip": "Ez az esemény csak olyan tartalmak esetében létezik, amelyeknél engedélyezve van a Piszkozat/Közzététel rendszer", "Settings.webhooks.events.create": "Létrehoz", "Settings.webhooks.events.update": "Frissít", "Settings.webhooks.form.events": "Esemnények", "Settings.webhooks.form.headers": "Fejléc", "Settings.webhooks.form.url": "Url", "Settings.webhooks.headers.remove": "Fejlésor eltávolítása {number}", "Settings.webhooks.key": "Kulcs", "Settings.webhooks.list.button.add": "Új webhook létrehozása", "Settings.webhooks.list.description": "Értesítések a POST módosításairól", "Settings.webhooks.list.empty.description": "Nem található webhook", "Settings.webhooks.list.empty.link": "Tekintse meg dokumentációnkat", "Settings.webhooks.list.empty.title": "Még nincsenek webhookok", "Settings.webhooks.list.th.actions": "Műveletek", "Settings.webhooks.list.th.status": "Státusz", "Settings.webhooks.singular": "webhook", "Settings.webhooks.title": "Webhook-ok", "Settings.webhooks.trigger": "Kapcsoló", "Settings.webhooks.trigger.cancel": "Kapcsoló törlése", "Settings.webhooks.trigger.pending": "Folyamatban…", "Settings.webhooks.trigger.save": "Kérjük mentse", "Settings.webhooks.trigger.success": "Sikerült!", "Settings.webhooks.trigger.success.label": "A kapcsoló sikerült", "Settings.webhooks.trigger.test": "Teszt-kapcsoló", "Settings.webhooks.trigger.title": "Először mentsen", "Settings.webhooks.value": "Érték", "Username": "Felhasználónév", "Users": "Felhasználók", "Users & Permissions": "Felhasználók & Engedélyek", "Users.components.List.empty": "Nincsenek felhasználók...", "Users.components.List.empty.withFilters": "Nincs a beállított szűrőknek megfelelő felhasználó..", "Users.components.List.empty.withSearch": "Nincs a keresének megfelelő felhasználó ({search})...", "admin.pages.MarketPlacePage.helmet": "Piactér - Plugin-ok", "admin.pages.MarketPlacePage.submit.plugin.link": "Plugin küldése", "admin.pages.MarketPlacePage.subtitle": "Hozzon ki többet a Strapi-ból", "anErrorOccurred": "Hoppá! Valami elromlott. Kérlek próbáld újra.", "app.component.CopyToClipboard.label": "Másolás a vágólapra", "app.component.search.label": "{target} keresése", "app.component.table.duplicate": "{target} duplikálása", "app.component.table.edit": "{target} szerkesztése", "app.component.table.select.one-entry": "{target} kiválasztása", "app.components.BlockLink.blog": "Blog", "app.components.BlockLink.blog.content": "Olvassa el a legfrissebb híreket a Strapiról és az ökoszisztémáról.", "app.components.BlockLink.code": "Kód példák", "app.components.BlockLink.code.content": "Tanuljon a közösség által fejlesztett valós projektek segítségével.", "app.components.BlockLink.documentation.content": "Fedezze fel az alapvető fogalmakat, útmutatókat és utasításokat.", "app.components.BlockLink.tutorial": "Oktatóanyagok", "app.components.BlockLink.tutorial.content": "Kövesse az utasításokat a Strapi használatához és testreszabásához.", "app.components.Button.cancel": "Mégsem", "app.components.Button.confirm": "Megerősítés", "app.components.Button.reset": "Visszaállítás", "app.components.ComingSoonPage.comingSoon": "Hamarosan", "app.components.ConfirmDialog.title": "Megerősítés", "app.components.DownloadInfo.download": "Letöltés folyamatban...", "app.components.DownloadInfo.text": "Ez eltarthat egy percig. Köszönjük a türelmét.", "app.components.EmptyAttributes.title": "Még nincsenek mezők", "app.components.EmptyStateLayout.content-document": "Nem található tartalom", "app.components.EmptyStateLayout.content-permissions": "Nincs megfelelő jogosultsága a tartalomhozhoz", "app.components.HomePage.button.blog": "Bővebben a blogon", "app.components.HomePage.community": "Csatlakozz a közösséghez", "app.components.HomePage.community.content": "Beszélgessen a csapattagokkal, a közreműködőkkel és a fejlesztőkkel különböző csatornákon.", "app.components.HomePage.create": "Hozza létre az első tartalomtípust", "app.components.HomePage.roadmap": "Tekintse meg terveinket", "app.components.HomePage.welcome": "Üdvözöljük a fedélzeten 👋", "app.components.HomePage.welcome.again": "Üdvözöljük 👋", "app.components.HomePage.welcomeBlock.content": "Gratulálunk! Első rendszergazdaként jelentkezett be. A Strapi által nyújtott funkciók felfedezéséhez javasoljuk, hogy hozza létre első tartalomtípusát!", "app.components.HomePage.welcomeBlock.content.again": "Reméljük, hogy jól halad a projektje! Olvassa el a Strapi legfrissebb híreit. Visszajelzései alapján mindent megteszünk, hogy javítsuk a terméket.", "app.components.HomePage.welcomeBlock.content.issues": "problémák.", "app.components.HomePage.welcomeBlock.content.raise": " vagy írjon ", "app.components.ImgPreview.hint": "Húzza a fájlt erre a területre, vagy {browse} a feltöltendő fájlért", "app.components.ImgPreview.hint.browse": "tallózás", "app.components.InputFile.newFile": "Új fájl hozzáadása", "app.components.InputFileDetails.open": "Megnyitás új lapon", "app.components.InputFileDetails.originalName": "Eredeti név:", "app.components.InputFileDetails.remove": "Fájl eltávolítása", "app.components.InputFileDetails.size": "Méret:", "app.components.InstallPluginPage.Download.description": "A bővítmény letöltése és telepítése eltarthat néhány másodpercig.", "app.components.InstallPluginPage.Download.title": "Letöltés...", "app.components.InstallPluginPage.description": "Bővítse alkalmazását erőfeszítés nélkül.", "app.components.LeftMenu.collapse": "A navigációs sáv összecsukása", "app.components.LeftMenu.expand": "A navigációs sáv kinyitása", "app.components.LeftMenu.logout": "Kijelentkezés", "app.components.LeftMenu.navbrand.title": "Strapi Műszerfal", "app.components.LeftMenu.navbrand.workplace": "Munkaterület", "app.components.LeftMenuFooter.help": "Segítség", "app.components.LeftMenuFooter.poweredBy": "Powered by ", "app.components.LeftMenuLinkContainer.collectionTypes": "Gyűjtemény típusai", "app.components.LeftMenuLinkContainer.configuration": "Beállítások", "app.components.LeftMenuLinkContainer.general": "Általános", "app.components.LeftMenuLinkContainer.noPluginsInstalled": "Nincs bővítmény telepítve", "app.components.LeftMenuLinkContainer.plugins": "Bővítmények", "app.components.LeftMenuLinkContainer.singleTypes": "Egyedülálló típusok", "app.components.ListPluginsPage.deletePlugin.description": "A bővítmény eltávolítása eltarthat néhány másodpercig.", "app.components.ListPluginsPage.deletePlugin.title": "Eltávolítás", "app.components.ListPluginsPage.description": "A telepített bővítmények listája.", "app.components.ListPluginsPage.helmet.title": "A bővítmények listája", "app.components.Logout.logout": "Kijelentkezés", "app.components.Logout.profile": "Profil", "app.components.MarketplaceBanner": "Fedezze fel a közösség által épített modulokat, és még sok más fantasztikus dolgot, amik segítenek a projekt elindításában.", "app.components.MarketplaceBanner.image.alt": "a strapi rocket logo", "app.components.MarketplaceBanner.link": "Nézze meg most", "app.components.NotFoundPage.back": "Vissza a kezdőoldalra", "app.components.NotFoundPage.description": "Nem található", "app.components.Official": "Hivatalos", "app.components.Onboarding.help.button": "Súgó gomb", "app.components.Onboarding.label.completed": "% elkészült", "app.components.Onboarding.title": "Bemutató videók", "app.components.PluginCard.Button.label.download": "Letöltés", "app.components.PluginCard.Button.label.install": "Már telepítve van", "app.components.PluginCard.PopUpWarning.install.impossible.autoReload.needed": "Az automatikus újratöltés funkciót engedélyezni kell. Kérjük, indítsa el az alkalmazást ezzel a paranccsal: `yarn develop`.", "app.components.PluginCard.PopUpWarning.install.impossible.confirm": "Megértettem!", "app.components.PluginCard.PopUpWarning.install.impossible.environment": "Biztonsági okokból egy plugin csak fejlesztői környezetben tölthető le.", "app.components.PluginCard.PopUpWarning.install.impossible.title": "A letöltés nem lehetséges", "app.components.PluginCard.compatible": "Kompatibilis az alkalmazásoddal", "app.components.PluginCard.compatibleCommunity": "Kompatibilis a közösséggel", "app.components.PluginCard.more-details": "További részletek", "app.components.ToggleCheckbox.off-label": "Kikapcsol", "app.components.ToggleCheckbox.on-label": "Bekapcsol", "app.components.UpgradePlanModal.button": "Tudj meg többet", "app.components.UpgradePlanModal.limit-reached": "Elérted a korlátot", "app.components.UpgradePlanModal.text-ce": "Közösségi kiadás", "app.components.UpgradePlanModal.text-ee": "Vállalati kiadás", "app.components.UpgradePlanModal.text-power": "Frissítsen a Vállalati kiadásra, hogy megismerhesse a Strapi teljes funkcionalitását.", "app.components.UpgradePlanModal.text-strapi": "a Strapi, ha frissíti tervét a", "app.components.Users.MagicLink.connect": "Másolja ki és ossza meg ezt a linket, hogy hozzáférést biztosítson ehhez a felhasználóhoz", "app.components.Users.MagicLink.connect.sso": "Küldje el ezt a linket a felhasználónak. Az első bejelentkezés történhet SSO szolgáltatón keresztül", "app.components.Users.ModalCreateBody.block-title.details": "Felhasználói adatok", "app.components.Users.ModalCreateBody.block-title.roles": "A felhasználó szerepkörei", "app.components.Users.ModalCreateBody.block-title.roles.description": "Egy felhasználónak lehet egy, illetve több szerepköre is", "app.components.Users.SortPicker.button-label": "Rendezés", "app.components.Users.SortPicker.sortby.email_asc": "Email (A - Z)", "app.components.Users.SortPicker.sortby.email_desc": "Email (Z - A)", "app.components.Users.SortPicker.sortby.firstname_asc": "Keresztnév (A - Z)", "app.components.Users.SortPicker.sortby.firstname_desc": "Keresztnév (Z - A)", "app.components.Users.SortPicker.sortby.lastname_asc": "Vezetéknév (A - Z)", "app.components.Users.SortPicker.sortby.lastname_desc": "Vezetéknév (Z - A)", "app.components.Users.SortPicker.sortby.username_asc": "Felhasználónév (A - Z)", "app.components.Users.SortPicker.sortby.username_desc": "Felhasználónév (Z - A)", "app.components.listPlugins.button": "Új bővítmény hozzáadása", "app.components.listPlugins.title.none": "Nincs telepítve bővítmény", "app.components.listPluginsPage.deletePlugin.error": "Hiba történt a bővítmény eltávolítása közben", "app.containers.App.notification.error.init": "Hiba történt az API kérése közben", "app.containers.AuthPage.ForgotPasswordSuccess.text.contact-admin": "Ha nem kapja meg ezt a linket, forduljon az adminisztrátorhoz.", "app.containers.AuthPage.ForgotPasswordSuccess.text.email": "Eltarthat néhány percig, amíg megkapja a jelszó-helyreállítási linket.", "app.containers.AuthPage.ForgotPasswordSuccess.title": "Email elküdlve", "app.containers.Users.EditPage.form.active.label": "Aktív", "app.containers.Users.EditPage.header.label": "{name} módosítása", "app.containers.Users.EditPage.header.label-loading": "Felhasználó szerkesztése", "app.containers.Users.EditPage.roles-bloc-title": "A hozzárendelt szerepkörök", "app.containers.Users.ModalForm.footer.button-success": "Felhasználó meghívása", "app.links.configure-view": "A nézet testreszabása", "app.static.links.cheatsheet": "Puska", "app.utils.SelectOption.defaultMessage": " ", "app.utils.add-filter": "Szűrő hozzáadása", "app.utils.close-label": "Bezárás", "app.utils.defaultMessage": " ", "app.utils.duplicate": "Duplikálás", "app.utils.edit": "Szerkesztés", "app.utils.errors.file-too-big.message": "A fájl mérete túl nagy", "app.utils.filter-value": "Szűrési érték", "app.utils.filters": "Szűrők", "app.utils.notify.data-loaded": "A {target} betöltődött", "app.utils.placeholder.defaultMessage": " ", "app.utils.publish": "Közzétesz", "app.utils.select-all": "Minden kiválasztása", "app.utils.select-field": "Mező kiválasztása", "app.utils.select-filter": "Szűrő kiválasztása", "app.utils.unpublish": "Közzététel visszavonása", "clearLabel": "Kiürít", "coming.soon": "Ez a tartalom jelenleg fejlesztés alatt áll, és néhány héten belül újra elérhető lesz!", "component.Input.error.validation.integer": "Az értéknek egész számnak kell lennie", "components.AutoReloadBlocker.description": "Futtassa a Strapit a következő parancsok egyikével:", "components.AutoReloadBlocker.header": "Ehhez a bővítményhez töltse be újra a funkciót.", "components.ErrorBoundary.title": "Valami elromlott...", "components.FilterOptions.FILTER_TYPES.$contains": "tartalmazza (nagybetű érzékeny)", "components.FilterOptions.FILTER_TYPES.$endsWith": "erre végződik", "components.FilterOptions.FILTER_TYPES.$eq": "egyenlő", "components.FilterOptions.FILTER_TYPES.$gt": "nagyobb, mint", "components.FilterOptions.FILTER_TYPES.$gte": "nagyobb, vagy egyenlő, mint", "components.FilterOptions.FILTER_TYPES.$lt": "kisebb, mint", "components.FilterOptions.FILTER_TYPES.$lte": "kisebb, vagy egyenlő, mint", "components.FilterOptions.FILTER_TYPES.$ne": "nem", "components.FilterOptions.FILTER_TYPES.$notContains": "nem tartalmazza (nagybetű érzékeny)", "components.FilterOptions.FILTER_TYPES.$notNull": "nem null", "components.FilterOptions.FILTER_TYPES.$null": "null", "components.FilterOptions.FILTER_TYPES.$startsWith": "ezzel kezdődik", "components.Input.error.attribute.key.taken": "Ez az érték már létezik", "components.Input.error.attribute.sameKeyAndName": "Nem lehet egyenlő", "components.Input.error.attribute.taken": "Ez a mezőnév már létezik", "components.Input.error.contain.lowercase": "A jelszónak tartalmaznia kell legalább egy kisbetűt", "components.Input.error.contain.number": "A jelszónak tartalmaznia kell legalább egy számot", "components.Input.error.contain.uppercase": "A jelszónak tartalmaznia kell legalább egy nagybetűt", "components.Input.error.contentTypeName.taken": "Ez a név már létezik", "components.Input.error.custom-error": "{errorMessage} ", "components.Input.error.password.noMatch": "A jelszavak nem egyeznek", "components.Input.error.validation.email": "Érvénytelen e-mail", "components.Input.error.validation.json": "Hibás JSON formátum", "components.Input.error.validation.lowercase": "Az értéknek kisbetűs karakterláncnak kell lennie", "components.Input.error.validation.max": "A megadott érték túl nagy.", "components.Input.error.validation.maxLength": "A megadott érték túl hosszú.", "components.Input.error.validation.min": "A megadott érték túl alacsony.", "components.Input.error.validation.minLength": "A megadott érték túl rövid.", "components.Input.error.validation.minSupMax": "Nem lehet felsőbbrendű", "components.Input.error.validation.regex": "A megadott érték formátuma nem megfelelő.", "components.Input.error.validation.required": "Ez az érték kötelező.", "components.Input.error.validation.unique": "Ez az érték már használatban van.", "components.InputSelect.option.placeholder": "Válasszon itt", "components.ListRow.empty": "Nincsenek megjelenítendő adatok.", "components.NotAllowedInput.text": "Nincs jogosultsága a mező megtekintéséhez", "components.OverlayBlocker.description": "Olyan funkciót használ, amelynek újra kell indítania a szervert. Kérjük, várja meg, amíg a szerver feláll.", "components.OverlayBlocker.description.serverError": "A szervernek újra kellett volna indulnia, kérjük, ellenőrizze a logokat a terminálban.", "components.OverlayBlocker.title": "Újraindításra vár...", "components.OverlayBlocker.title.serverError": "Az újraindítás a vártnál tovább tart", "components.PageFooter.select": "Bejegyzések oldalanként", "components.ProductionBlocker.description": "Biztonsági okokból le kell tiltanunk ezt a bővítményt más környezetekben.", "components.ProductionBlocker.header": "Ez a bővítmény csak fejlesztői környezetben érhető el.", "components.Search.placeholder": "Keresés...", "components.TableHeader.sort": "Rendezés {label} szerint", "components.Wysiwyg.ToggleMode.markdown-mode": "Markdown mód", "components.Wysiwyg.ToggleMode.preview-mode": "Előnézet mód", "components.Wysiwyg.collapse": "Összecsuk", "components.Wysiwyg.selectOptions.H1": "Cím H1", "components.Wysiwyg.selectOptions.H2": "Cím H2", "components.Wysiwyg.selectOptions.H3": "Cím H3", "components.Wysiwyg.selectOptions.H4": "Cím H4", "components.Wysiwyg.selectOptions.H5": "Cím H5", "components.Wysiwyg.selectOptions.H6": "Cím H6", "components.Wysiwyg.selectOptions.title": "Cím hozzádása", "components.WysiwygBottomControls.charactersIndicators": "karakterek", "components.WysiwygBottomControls.fullscreen": "Kinyit", "components.WysiwygBottomControls.uploadFiles": "Fájlok behúzása, beillesztése a vágólapról vagy {browse}.", "components.WysiwygBottomControls.uploadFiles.browse": "Válassza ki őket", "components.pagination.go-to": "Ugrás a(z) {page} oldalra", "components.pagination.go-to-next": "Ugrás a következő oldalra", "components.pagination.go-to-previous": "Ugrás az előző oldalra", "components.pagination.remaining-links": "És {number} további link", "components.popUpWarning.button.cancel": "Mégsem", "components.popUpWarning.button.confirm": "Megerősítés", "components.popUpWarning.message": "Biztosan törölni szeretné?", "components.popUpWarning.title": "Erősítse meg", "content-manager.App.schemas.data-loaded": "A sémák sikeresen betöltve", "content-manager.DynamicTable.relation-loaded": "A kapcsolatok betöltődtek", "content-manager.EditRelations.title": "Relációs adatok", "content-manager.HeaderLayout.button.label-add-entry": "Új bejegyzés létrehozása", "content-manager.api.id": "API ID", "content-manager.components.AddFilterCTA.add": "Szűrők", "content-manager.components.AddFilterCTA.hide": "Szűrők", "content-manager.components.DragHandle-label": "Húz", "content-manager.components.DraggableAttr.edit": "Kattintson a szerkesztéshez", "content-manager.components.DraggableCard.delete.field": "{item} törlése", "content-manager.components.DraggableCard.edit.field": "{item} szerkesztése", "content-manager.components.DraggableCard.move.field": "{item} mozgatása", "content-manager.components.DynamicTable.row-line": "{number}. sor", "content-manager.components.DynamicZone.ComponentPicker-label": "Válasszon egy komponenst", "content-manager.components.DynamicZone.add-component": "Komponens hozzáadása a {componentName}-hoz", "content-manager.components.DynamicZone.delete-label": "{name} törlése", "content-manager.components.DynamicZone.error-message": "Az összetevő hibát (hibákat) tartalmaz", "content-manager.components.DynamicZone.missing-components": "Hiányzik {number} komponens", "content-manager.components.DynamicZone.move-down-label": "Mozgassa a komponenst lefelé", "content-manager.components.DynamicZone.move-up-label": "Mozgassa a komponenst felfelé", "content-manager.components.DynamicZone.pick-compo": "Válasszon egy komponenst", "content-manager.components.DynamicZone.required": "A komponens kötelező", "content-manager.components.EmptyAttributesBlock.button": "Ugrás a beállítások oldalra", "content-manager.components.EmptyAttributesBlock.description": "Módosíthatja a beállításait", "content-manager.components.FieldItem.linkToComponentLayout": "Állítsa be az összetevő elrendezését", "content-manager.components.FieldSelect.label": "Mező hozzáadása", "content-manager.components.FilterOptions.button.apply": "Alkalmaz", "content-manager.components.FiltersPickWrapper.PluginHeader.actions.apply": "Alkalmaz", "content-manager.components.FiltersPickWrapper.PluginHeader.actions.clearAll": "Mindent kitöröl", "content-manager.components.FiltersPickWrapper.PluginHeader.description": "Állítsa be a bejegyzések szűréséhez alkalmazandó feltételeket", "content-manager.components.FiltersPickWrapper.PluginHeader.title.filter": "Szűrők", "content-manager.components.FiltersPickWrapper.hide": "Elrejt", "content-manager.components.LeftMenu.Search.label": "Tartalomtípus keresése", "content-manager.components.LeftMenu.collection-types": "Gyűjteménytípusok", "content-manager.components.LeftMenu.single-types": "Egyedülálló típusok", "content-manager.components.LimitSelect.itemsPerPage": "Oldalankénti elemek száma", "content-manager.components.NotAllowedInput.text": "Nincs jogosultság a mező megtekintéséhez", "content-manager.components.RepeatableComponent.error-message": "Az összetevő(k) hibát tartalmaz(nak)", "content-manager.components.Search.placeholder": "Bejegyzés keresése...", "content-manager.components.Select.draft-info-title": "Állapot: Piszkozat", "content-manager.components.Select.publish-info-title": "Állapot: Közzétett", "content-manager.components.SettingsViewWrapper.pluginHeader.description.edit-settings": "A szerkesztési nézet megjelenésének testreszabása.", "content-manager.components.SettingsViewWrapper.pluginHeader.description.list-settings": "A listanézet beállításainak megadása.", "content-manager.components.SettingsViewWrapper.pluginHeader.title": "A nézet testreszabása - {name}", "content-manager.components.TableDelete.delete": "Mindegyik törlése", "content-manager.components.TableDelete.deleteSelected": "A kiválasztott elem törlése", "content-manager.components.TableDelete.label": "{number} elem kiválasztva", "content-manager.components.TableEmpty.withFilters": "Nincsenek {contentType} az alkalmazott szűrőkkel...", "content-manager.components.TableEmpty.withSearch": "A megadott kereséssel ({search}) nincs {contentType}...", "content-manager.components.TableEmpty.withoutFilter": "Nincs {contentType}...", "content-manager.components.empty-repeatable": "Még nincs elem hozzáadva. Kattintson az alábbi gombra a hozzáadásához.", "content-manager.components.notification.info.maximum-requirement": "Már elérte a mezők maximális számát", "content-manager.components.notification.info.minimum-requirement": "A minimális követelménynek megfelelő mezőt hozzáadtuk", "content-manager.components.repeatable.reorder.error": "Hiba történt az mezők átrendezése közben. Kérjük, próbálja újra", "content-manager.components.reset-entry": "Bejegyzés visszaállítása", "content-manager.components.uid.apply": "alkalmaz", "content-manager.components.uid.available": "Elérhető", "content-manager.components.uid.regenerate": "Megújít", "content-manager.components.uid.suggested": "javasolt", "content-manager.components.uid.unavailable": "Nem érhető el", "content-manager.containers.Edit.Link.Layout": "Az elrendezés testreszabása", "content-manager.containers.Edit.Link.Model": "A gyűjteménytípus szerkesztése", "content-manager.containers.Edit.addAnItem": "Elem hozzáadása...", "content-manager.containers.Edit.clickToJump": "Kattintson a bejegyzésre ugráshoz", "content-manager.containers.Edit.delete": "Törlés", "content-manager.containers.Edit.delete-entry": "Bejegyzés törlése", "content-manager.containers.Edit.editing": "Szerkesztés...", "content-manager.containers.Edit.information": "Információ", "content-manager.containers.Edit.information.by": "által", "content-manager.containers.Edit.information.created": "Létrehozva", "content-manager.containers.Edit.information.draftVersion": "piszkozat", "content-manager.containers.Edit.information.editing": "Szerkesztés", "content-manager.containers.Edit.information.lastUpdate": "Utolsó frissítés", "content-manager.containers.Edit.information.publishedVersion": "közzétett változat", "content-manager.containers.Edit.pluginHeader.title.new": "Bejegyzés létrehozása", "content-manager.containers.Edit.reset": "Visszaállítás", "content-manager.containers.Edit.returnList": "Vissza a listához", "content-manager.containers.Edit.seeDetails": "Részletek", "content-manager.containers.Edit.submit": "Mentés", "content-manager.containers.EditSettingsView.modal-form.edit-field": "Mező szerkesztése", "content-manager.containers.EditView.add.new-entry": "Bejegyzés hozzáadása", "content-manager.containers.EditView.notification.errors": "Az űrlap hibás", "content-manager.containers.Home.introduction": "A bejegyzések szerkesztéséhez lépjen a bal oldali menüben található hivatkozásra. Ennek a bővítménynek nem módosíthatóak a beállításai, és még mindig aktív fejlesztés alatt áll.", "content-manager.containers.Home.pluginHeaderDescription": "Kezelje bejegyzéseit egy sokoldalú és szép felületen keresztül.", "content-manager.containers.Home.pluginHeaderTitle": "Tartalomkezelő", "content-manager.containers.List.draft": "Piszkozat", "content-manager.containers.List.errorFetchRecords": "Hiba", "content-manager.containers.List.published": "Közzétett", "content-manager.containers.ListPage.displayedFields": "Megjelenített mezők", "content-manager.containers.ListPage.items": "{number} elem", "content-manager.containers.ListPage.table-headers.publishedAt": "Állapot", "content-manager.containers.ListSettingsView.modal-form.edit-label": "{fieldName} szerkesztése", "content-manager.containers.SettingPage.add.field": "Másik mező beszúrása", "content-manager.containers.SettingPage.attributes": "Attribútummezők", "content-manager.containers.SettingPage.attributes.description": "Attribútumok sorrendjének meghatározása", "content-manager.containers.SettingPage.editSettings.description": "Húzza a megfelelő helyre a mezőket a végleges megjelenítés kialakításához", "content-manager.containers.SettingPage.editSettings.entry.title": "Bejegyzés címe", "content-manager.containers.SettingPage.editSettings.entry.title.description": "A bejegyzés megjelenített mezőjének beállítása", "content-manager.containers.SettingPage.editSettings.relation-field.description": "A megjelenített mező beállítása szerkesztési és listanézetben", "content-manager.containers.SettingPage.editSettings.title": "Nézet szerkesztése (beállítások)", "content-manager.containers.SettingPage.layout": "Elrendezés", "content-manager.containers.SettingPage.listSettings.description": "Konfigurálja a beállításokat ehhez a gyűjteménytípushoz", "content-manager.containers.SettingPage.listSettings.title": "Lista nézet (beállítások)", "content-manager.containers.SettingPage.pluginHeaderDescription": "Gyűjteménytípus speciális beállításainak megadása", "content-manager.containers.SettingPage.settings": "Beállítások", "content-manager.containers.SettingPage.view": "Nézet", "content-manager.containers.SettingViewModel.pluginHeader.title": "Tartalom kezelő - {name}", "content-manager.containers.SettingsPage.Block.contentType.description": "A beállítások testreszabása", "content-manager.containers.SettingsPage.Block.contentType.title": "Gyűjteménytípusok", "content-manager.containers.SettingsPage.Block.generalSettings.description": "A gyűjteménytípusok alapértelmezett beállításainak testreszabása", "content-manager.containers.SettingsPage.Block.generalSettings.title": "Általános", "content-manager.containers.SettingsPage.pluginHeaderDescription": "Az összes gyűjteménytípus és csoport beállításainak testreszabása", "content-manager.containers.SettingsView.list.subtitle": "A gyűjteménytípusok és csoportok elrendezésének és megjelenítésének testreszabása", "content-manager.containers.SettingsView.list.title": "Megjelenítés beállításai", "content-manager.edit-settings-view.link-to-ctb.components": "Komponensek szerkesztése", "content-manager.edit-settings-view.link-to-ctb.content-types": "Tartalomtípusok szerkesztése", "content-manager.emptyAttributes.button": "Ugrás a gyűjteménytípus-készítőhöz", "content-manager.emptyAttributes.description": "Adja hozzá az első mezőt a gyűjtemény típusához", "content-manager.emptyAttributes.title": "Még nincsenek mezők", "content-manager.error.attribute.key.taken": "Ez az érték már létezik", "content-manager.error.attribute.sameKeyAndName": "Nem lehetnek egyenlők", "content-manager.error.attribute.taken": "Ez a mezőnév már létezik", "content-manager.error.contentTypeName.taken": "Ez a név már létezik", "content-manager.error.model.fetch": "Hiba történt a modellek konfigurációjának lekérése során.", "content-manager.error.record.create": "Hiba történt a rekord létrehozása közben.", "content-manager.error.record.delete": "Hiba történt a rekord törlése közben.", "content-manager.error.record.fetch": "Hiba történt a rekord lekérése során.", "content-manager.error.record.update": "Hiba történt a rekord frissítése közben.", "content-manager.error.records.count": "Hiba történt a rekordok számának lekérése közben.", "content-manager.error.records.fetch": "Hiba történt a rekordok lekérése közben.", "content-manager.error.schema.generation": "Hiba történt a séma létrehozása során.", "content-manager.error.validation.json": "Nem megfelelő JSON formátum", "content-manager.error.validation.max": "A megadott érték túl magas.", "content-manager.error.validation.maxLength": "A megadott érték túl hosszú.", "content-manager.error.validation.min": "A megadott érték túl alacsony.", "content-manager.error.validation.minLength": "A megadott érték túl rövid.", "content-manager.error.validation.minSupMax": "Nem lehet magasabb", "content-manager.error.validation.regex": "A megadott érték nem megfelelő.", "content-manager.error.validation.required": "Az érték megadása kötelező.", "content-manager.form.Input.bulkActions": "Tömeges művelet engedélyezése", "content-manager.form.Input.defaultSort": "Alapértelmezett rendezési attribútum", "content-manager.form.Input.description": "Leírás", "content-manager.form.Input.description.placeholder": "Megjelenítési név a profilban", "content-manager.form.Input.editable": "Szerkeszthető mező", "content-manager.form.Input.filters": "Szűrők engedélyezése", "content-manager.form.Input.label": "Címke", "content-manager.form.Input.label.inputDescription": "Ez az érték felülírja a táblázat fejlécében megjelenő címkét", "content-manager.form.Input.pageEntries": "Bejegyzések oldalanként", "content-manager.form.Input.pageEntries.inputDescription": "Megjegyzés: Ezt az értéket felülírhatja a Gyűjteménytípus beállításainak oldalán.", "content-manager.form.Input.placeholder": "Helykitöltő", "content-manager.form.Input.placeholder.placeholder": "Alapérték", "content-manager.form.Input.search": "Keresés engedélyezése", "content-manager.form.Input.search.field": "Keresés engedélyezése ezen a mezőn", "content-manager.form.Input.sort.field": "Rendezés engedélyezése ezen a mezőn", "content-manager.form.Input.sort.order": "Alapértelmezett rendezési sorrend", "content-manager.form.Input.wysiwyg": "Megjelenítés, mint WYSIWYG", "content-manager.global.displayedFields": "Megjelenített mezők", "content-manager.groups": "Csoportok", "content-manager.groups.numbered": "Csoportok ({number})", "content-manager.header.name": "Tartalom", "content-manager.link-to-ctb": "Modell szerkesztése", "content-manager.models": "Gyűjteménytípusok", "content-manager.models.numbered": "Gyűjteménytípusok ({number})", "content-manager.notification.error.displayedFields": "Legalább egy megjelenített mezőre szükség van", "content-manager.notification.error.relationship.fetch": "Hiba történt a kapcsolat lekérése során.", "content-manager.notification.info.SettingPage.disableSort": "Legalább egy attribútumnak rendezhetőnek kell lennie", "content-manager.notification.info.minimumFields": "Legalább egy mezőt meg kell jeleníteni", "content-manager.notification.upload.error": "Hiba történt a fájlok feltöltése közben", "content-manager.pageNotFound": "Az oldal nem található", "content-manager.pages.NoContentType.button": "Tartalomtípus létrehozása", "content-manager.pages.NoContentType.text": "Még nincs tartalom, javasoljuk, hogy hozza létre az első tartalomtípust.", "content-manager.permissions.not-allowed.create": "Nem hozhat létre dokumentumot", "content-manager.permissions.not-allowed.update": "Ezt a dokumentumot nem tekintheti meg", "content-manager.plugin.description.long": "Gyors mód az adatbázisban lévő adatok megtekintéséhez, szerkesztéséhez és törléséhez.", "content-manager.plugin.description.short": "Gyors mód az adatbázisban lévő adatok megtekintéséhez, szerkesztéséhez és törléséhez.", "content-manager.popover.display-relations.label": "Kapcsolatok megjelenítése", "content-manager.success.record.delete": "Törölve", "content-manager.success.record.publish": "Közzétéve", "content-manager.success.record.save": "Mentett", "content-manager.success.record.unpublish": "Nem közzétett", "content-manager.utils.data-loaded": "{number} elem sikeresen betöltődött", "content-manager.popUpWarning.warning.publish-question": "Biztosan közzé akarja tenni?", "content-manager.popUpwarning.warning.has-draft-relations.button-confirm": "Igen, közzététel", "form.button.done": "Kész", "global.prompt.unsaved": "Biztos, hogy elhagyja ezt az oldalt? Az összes módosítása elveszik", "notification.contentType.relations.conflict": "A tartalomtípusnak ellenkező kapcsolatai vannak", "notification.default.title": "Információ:", "notification.error": "Hiba lépett fel", "notification.error.layout": "Nem sikerült lekérni az elrendezést", "notification.form.error.fields": "Az űrlap kitöltése hibás", "notification.form.success.fields": "Változtatások elmentve", "notification.link-copied": "A link a vágólapra másolva", "notification.permission.not-allowed-read": "Ezt a dokumentumot nem tekintheti meg", "notification.success.delete": "Az elemet törölték", "notification.success.saved": "Mentve", "notification.success.title": "Sikeres:", "notification.version.update.message": "Megjelent a Strapi új verziója!", "notification.warning.title": "Figyelmeztetés:", "or": "Vagy", "request.error.model.unknown": "Ez a modell nem létezik", "skipToContent": "Kihagyás", "submit": "Küldés" }
packages/core/admin/admin/src/translations/hu.json
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017969887994695455, 0.00017454769113101065, 0.0001667308242758736, 0.0001750935916788876, 0.0000029476816507667536 ]
{ "id": 1, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 172 }
import React from 'react'; import { ThemeProvider, lightTheme } from '@strapi/design-system'; import { QueryClientProvider, QueryClient } from 'react-query'; import { render as renderTL, screen, waitFor, fireEvent } from '@testing-library/react'; import { useSelectionState, useQueryParams, TrackingProvider } from '@strapi/helper-plugin'; import { MemoryRouter } from 'react-router-dom'; import { IntlProvider } from 'react-intl'; import { useMediaLibraryPermissions } from '../../../hooks/useMediaLibraryPermissions'; import { useFolders } from '../../../hooks/useFolders'; import { useAssets } from '../../../hooks/useAssets'; import { useFolder } from '../../../hooks/useFolder'; import { MediaLibrary } from '../MediaLibrary'; const FIXTURE_ASSET_PAGINATION = { pageCount: 1, page: 1, pageSize: 10, total: 1, }; const FIXTURE_ASSETS = [ { id: 77, name: '3874873.jpg', alternativeText: null, caption: null, width: 400, height: 400, formats: { thumbnail: { name: 'thumbnail_3874873.jpg', hash: 'thumbnail_3874873_b5818bb250', ext: '.jpg', mime: 'image/jpeg', width: 156, height: 156, size: 3.97, path: null, url: '/uploads/thumbnail_3874873_b5818bb250.jpg', }, }, hash: '3874873_b5818bb250', ext: '.jpg', mime: 'image/jpeg', size: 11.79, url: '/uploads/3874873_b5818bb250.jpg', previewUrl: null, provider: 'local', provider_metadata: null, createdAt: '2021-10-18T08:04:56.326Z', updatedAt: '2021-10-18T08:04:56.326Z', }, ]; jest.mock('../../../hooks/useMediaLibraryPermissions'); jest.mock('../../../hooks/useFolders'); jest.mock('../../../hooks/useFolder'); jest.mock('../../../hooks/useAssets'); jest.mock('@strapi/helper-plugin', () => ({ ...jest.requireActual('@strapi/helper-plugin'), useRBAC: jest.fn(), useNotification: jest.fn(() => jest.fn()), useQueryParams: jest.fn().mockReturnValue([{ query: {}, rawQuery: '' }, jest.fn()]), useSelectionState: jest .fn() .mockReturnValue([[], { selectOne: jest.fn(), selectAll: jest.fn() }]), })); jest.mock('../../../utils', () => ({ ...jest.requireActual('../../../utils'), getTrad: (x) => x, })); const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false, }, }, }); const renderML = () => renderTL( <QueryClientProvider client={queryClient}> <IntlProvider locale="en" messages={{}}> <TrackingProvider> <ThemeProvider theme={lightTheme}> <MemoryRouter> <MediaLibrary /> </MemoryRouter> </ThemeProvider> </TrackingProvider> </IntlProvider> </QueryClientProvider> ); describe('Media library homepage', () => { afterEach(() => { jest.clearAllMocks(); }); describe('navigation', () => { it('focuses the title when mounting the component', () => { renderML(); expect(screen.getByRole('main')).toHaveFocus(); }); }); describe('loading state', () => { it('shows a loader when resolving the permissions', () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: true, canCreate: false, canRead: false, }); renderML(); expect(screen.getByRole('main').getAttribute('aria-busy')).toBe('true'); expect(screen.getByText('Loading content.')).toBeInTheDocument(); }); it('shows a loader while resolving assets', () => { useAssets.mockReturnValueOnce({ isLoading: true }); renderML(); expect(screen.getByRole('main').getAttribute('aria-busy')).toBe('true'); expect(screen.getByText('Loading content.')).toBeInTheDocument(); }); it('shows a loader while resolving folders', () => { useFolders.mockReturnValueOnce({ isLoading: true }); renderML(); expect(screen.getByRole('main').getAttribute('aria-busy')).toBe('true'); expect(screen.getByText('Loading content.')).toBeInTheDocument(); }); }); describe('general actions', () => { describe('filters', () => { it('shows the filters dropdown when the user is allowed to read', () => { renderML(); expect(screen.getByText('Filters')).toBeInTheDocument(); }); it('hides the filters dropdown when the user is not allowed to read', () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canRead: false, canCreate: false, }); renderML(); expect(screen.queryByText('app.utils.filters')).not.toBeInTheDocument(); }); }); describe('sort by', () => { it('shows the sort by dropdown when the user is allowed to read', () => { renderML(); expect(screen.getByText('Sort by')).toBeInTheDocument(); }); it('hides the sort by dropdown when the user is not allowed to read', () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canRead: false, canCreate: false, }); renderML(); expect(screen.queryByText('Sort by')).not.toBeInTheDocument(); }); [ 'createdAt:DESC', 'createdAt:ASC', 'name:ASC', 'name:DESC', 'updatedAt:DESC', 'updatedAt:ASC', ].forEach((sortKey) => { it(`modifies the URL with the according params: ${sortKey}`, async () => { const setQueryMock = jest.fn(); useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: {} }, setQueryMock]); renderML(); fireEvent.mouseDown(screen.getByText('Sort by')); await waitFor(() => expect(screen.getByText(sortKey)).toBeInTheDocument()); fireEvent.mouseDown(screen.getByText(sortKey)); await waitFor(() => expect(screen.queryByText(sortKey)).not.toBeInTheDocument()); expect(setQueryMock).toBeCalledWith({ sort: sortKey }); }); }); }); describe('select all', () => { it('shows the select all button when the user is allowed to update', () => { renderML(); expect(screen.getByLabelText('Select all folders & assets')).toBeInTheDocument(); }); it('hides the select all if there are not folders and assets', () => { useAssets.mockReturnValueOnce({ isLoading: false, error: null, data: {}, }); useFolders.mockReturnValueOnce({ data: [], isLoading: false, error: null, }); renderML(); expect(screen.queryByLabelText('Select all assets')).not.toBeInTheDocument(); }); it('hides the select all button when the user is not allowed to update', () => { useMediaLibraryPermissions.mockReturnValue({ isLoading: false, canRead: true, canCreate: true, canUpdate: false, }); renderML(); expect(screen.queryByLabelText('Select all assets')).not.toBeInTheDocument(); }); }); describe('create asset', () => { it('hides the "Upload new asset" button when the user does not have the permissions to', async () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canRead: false, canCreate: false, }); renderML(); await waitFor(() => expect(screen.queryByText(`Add new assets`)).not.toBeInTheDocument()); }); it('shows the "Upload assets" button when the user does have the permissions to', async () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canRead: true, canCreate: true, }); renderML(); await waitFor(() => expect(screen.getByText(`Add new assets`)).toBeInTheDocument()); }); }); describe('create folder', () => { it('shows the create button if the user has create permissions', () => { renderML(); expect(screen.getByText('Add new folder')).toBeInTheDocument(); }); it('hides the create button if the user does not have create permissions', () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canCreate: false, }); renderML(); expect(screen.queryByText('Add new folder')).not.toBeInTheDocument(); }); }); }); describe('content', () => { it('should show breadcrumbs navigation', () => { renderML(); expect(screen.queryByLabelText('Folders navigation')).toBeInTheDocument(); }); it('should hide breadcrumbs navigation if in root folder', () => { useFolder.mockReturnValueOnce({ isLoading: false, data: undefined }); renderML(); expect(screen.queryByLabelText('Folders navigation')).not.toBeInTheDocument(); }); it('does display empty state upload first assets if no folder or assets', () => { useFolders.mockReturnValueOnce({ data: [], isLoading: false, error: null, }); useAssets.mockReturnValueOnce({ isLoading: false, error: null, data: {}, }); renderML(); expect(screen.queryByText('Upload your first assets...')).toBeInTheDocument(); }); it('does display empty state no results found if searching with no results', () => { useAssets.mockReturnValueOnce({ isLoading: false, error: null, data: {}, }); useFolders.mockReturnValueOnce({ data: [], isLoading: false, error: null, }); useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { _q: 'true' } }, jest.fn()]); renderML(); expect( screen.queryByText('There are no elements with the applied filters') ).toBeInTheDocument(); }); it('does not display assets title if searching and no folders', () => { useFolders.mockReturnValueOnce({ data: [], isLoading: false, error: null, }); useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { _q: 'true' } }, jest.fn()]); renderML(); expect(screen.queryByText('Assets')).not.toBeInTheDocument(); }); it('does not display folders title if searching and no assets', () => { useAssets.mockReturnValueOnce({ isLoading: false, error: null, data: {}, }); useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { _q: 'true' } }, jest.fn()]); renderML(); expect(screen.queryByText('Folders')).not.toBeInTheDocument(); }); it('displays folders and folders title', () => { renderML(); expect(screen.getByText('Folders (1)')).toBeInTheDocument(); expect(screen.getByText('1 folder, 1 asset')).toBeInTheDocument(); }); it('displays folder with checked checkbox when is selected', () => { useSelectionState.mockReturnValueOnce([ [ { id: 1, name: 'Folder 1', children: { count: 1 }, createdAt: '', files: { count: 1 }, path: '/1', pathId: 1, updatedAt: '', type: 'folder', }, ], { selectOne: jest.fn(), selectAll: jest.fn() }, ]); renderML(); expect(screen.getByTestId('folder-checkbox-1')).toBeChecked(); }); it('doest not displays folder with checked checkbox when is not selected', () => { renderML(); expect(screen.getByTestId('folder-checkbox-1')).not.toBeChecked(); }); it('does not display folders if the user does not have read permissions', () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canRead: false, canCreate: false, }); renderML(); expect(screen.queryByText('1 folder, 1 asset')).not.toBeInTheDocument(); expect(screen.queryByText('Folders (1)')).not.toBeInTheDocument(); }); it('does display folders if a search is performed', () => { useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { _q: 'true' } }, jest.fn()]); renderML(); expect(screen.queryByText('1 folder, 1 asset')).toBeInTheDocument(); expect(screen.queryByText('Folders (1)')).toBeInTheDocument(); }); it('does display folders if the media library is being filtered', () => { useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { filters: 'true' } }, jest.fn()]); renderML(); expect(screen.queryByText('1 folder, 1 asset')).toBeInTheDocument(); expect(screen.queryByText('Folders (1)')).toBeInTheDocument(); }); it('does not fetch folders if the current page !== 1', () => { useAssets.mockReturnValueOnce({ isLoading: false, data: { pagination: { ...FIXTURE_ASSET_PAGINATION, pageCount: 2, page: 2, total: 2, }, results: FIXTURE_ASSETS, }, }); useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { _q: 'true' } }, jest.fn()]); renderML(); expect(useFolders).toHaveBeenCalledWith(expect.objectContaining({ enabled: false })); }); it('does not fetch folders if the mime-type was applied', () => { useAssets.mockReturnValueOnce({ isLoading: false, data: { pagination: { ...FIXTURE_ASSET_PAGINATION, pageCount: 2, page: 2, total: 2, }, results: FIXTURE_ASSETS, }, }); useQueryParams.mockReturnValueOnce([ { rawQuery: '', query: { _q: '', filters: { $and: { mime: 'audio' } } } }, jest.fn(), ]); renderML(); expect(useFolders).toHaveBeenCalledWith(expect.objectContaining({ enabled: false })); }); it('displays assets', () => { renderML(); expect(screen.getByText('3874873.jpg')).toBeInTheDocument(); }); it('does not display assets if the user does not have read permissions', () => { useMediaLibraryPermissions.mockReturnValueOnce({ isLoading: false, canRead: false, canCreate: false, }); renderML(); expect(screen.queryByText('3874873.jpg')).not.toBeInTheDocument(); }); it('does display empty assets action, if there are no assets and no folders', () => { useAssets.mockReturnValueOnce({ isLoading: false, data: { pagination: FIXTURE_ASSET_PAGINATION, results: [], }, }); useFolders.mockReturnValueOnce({ isLoading: false, data: [], }); renderML(); expect(screen.queryByText('Upload your first assets...')).toBeInTheDocument(); }); it('does not display empty assets action, if there are no assets, no folders and the user is currently filtering', () => { useQueryParams.mockReturnValueOnce([{ rawQuery: '', query: { filters: 'true' } }, jest.fn()]); useAssets.mockReturnValueOnce({ isLoading: false, error: null, data: { pagination: FIXTURE_ASSET_PAGINATION, results: [], }, }); useFolders.mockReturnValueOnce({ isLoading: false, error: null, data: [], }); renderML(); expect( screen.queryByText('There are no elements with the applied filters') ).toBeInTheDocument(); expect(screen.queryByText('header.actions.add-assets')).not.toBeInTheDocument(); }); }); });
packages/core/upload/admin/src/pages/App/tests/MediaLibrary.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00019734358647838235, 0.00017198952264152467, 0.00016299341223202646, 0.00017278008454013616, 0.000005286840860208031 ]
{ "id": 1, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 172 }
#!/usr/bin/env node 'use strict'; require('./create-strapi-app');
packages/cli/create-strapi-app/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00016687062452547252, 0.00016687062452547252, 0.00016687062452547252, 0.00016687062452547252, 0 ]
{ "id": 2, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 257 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9986101388931274, 0.31836438179016113, 0.0001640278787817806, 0.002222290961071849, 0.45727023482322693 ]
{ "id": 2, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 257 }
'use strict'; // eslint-disable-next-line node/no-extraneous-require const { features } = require('@strapi/strapi/lib/utils/ee'); const createLocalStrategy = require('../../../server/services/passport/local-strategy'); const sso = require('./passport/sso'); const getPassportStrategies = () => { const localStrategy = createLocalStrategy(strapi); if (!features.isEnabled('sso')) { return [localStrategy]; } if (!strapi.isLoaded) { sso.syncProviderRegistryWithConfig(); } const providers = sso.providerRegistry.getAll(); const strategies = providers.map((provider) => provider.createStrategy(strapi)); return [localStrategy, ...strategies]; }; module.exports = { getPassportStrategies, }; if (features.isEnabled('sso')) { Object.assign(module.exports, sso); }
packages/core/admin/ee/server/services/passport.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017518091772217304, 0.0001739189901854843, 0.00017288446542806923, 0.00017380528151988983, 8.626266208011657e-7 ]
{ "id": 2, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 257 }
const ellipsisCardTitle = (title) => { const formatedTitle = title.length > 20 ? `${title.substring(0, 20)}...` : title; return formatedTitle; }; export default ellipsisCardTitle;
packages/core/admin/admin/src/content-manager/pages/ListSettingsView/utils/ellipsisCardTitle.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001763127074809745, 0.0001763127074809745, 0.0001763127074809745, 0.0001763127074809745, 0 ]
{ "id": 2, "code_window": [ " name: 'API Uploads (1)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 257 }
'use strict'; // Helpers. const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createAuthRequest, createRequest } = require('../../../../../test/helpers/request'); describe('Authenticated User', () => { let rq; let strapi; beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); }); afterAll(async () => { await strapi.destroy(); }); describe('GET /users/me', () => { test('Returns sanitized user info', async () => { const res = await rq({ url: '/admin/users/me', method: 'GET', body: {}, }); expect(res.statusCode).toBe(200); expect(res.body.data).toMatchObject({ id: expect.anything(), firstname: expect.stringOrNull(), lastname: expect.stringOrNull(), username: expect.stringOrNull(), email: expect.any(String), isActive: expect.any(Boolean), }); }); test('Returns forbidden on unauthenticated query', async () => { const req = createRequest({ strapi }); const res = await req({ url: '/admin/users/me', method: 'GET', body: {}, }); expect(res.statusCode).toBe(401); }); }); describe('PUT /users/me', () => { test('Returns forbidden on unauthenticated query', async () => { const req = createRequest({ strapi }); const res = await req({ url: '/admin/users/me', method: 'PUT', body: {}, }); expect(res.statusCode).toBe(401); }); test('Fails when trying to edit roles', async () => { const res = await rq({ url: '/admin/users/me', method: 'PUT', body: { roles: [1], }, }); expect(res.statusCode).toBe(400); expect(res.body).toMatchObject({ error: { details: { errors: [ { message: 'this field has unspecified keys: roles', name: 'ValidationError', path: [], }, ], }, message: 'this field has unspecified keys: roles', name: 'ValidationError', status: 400, }, }); }); test('Fails when trying to edit isActive', async () => { const res = await rq({ url: '/admin/users/me', method: 'PUT', body: { isActive: 12, }, }); expect(res.statusCode).toBe(400); expect(res.body).toMatchObject({ error: { details: { errors: [ { message: 'this field has unspecified keys: isActive', name: 'ValidationError', path: [], }, ], }, message: 'this field has unspecified keys: isActive', name: 'ValidationError', status: 400, }, }); }); test('Fails when trying to set invalid inputs', async () => { const res = await rq({ url: '/admin/users/me', method: 'PUT', body: { isActive: 12, }, }); expect(res.statusCode).toBe(400); expect(res.body).toMatchObject({ error: { details: { errors: [ { message: 'this field has unspecified keys: isActive', name: 'ValidationError', path: [], }, ], }, message: 'this field has unspecified keys: isActive', name: 'ValidationError', status: 400, }, }); }); test('Allows edition of names', async () => { const input = { firstname: 'newFirstName', lastname: 'newLastaName', }; const res = await rq({ url: '/admin/users/me', method: 'PUT', body: input, }); expect(res.statusCode).toBe(200); expect(res.body.data).toMatchObject({ id: expect.anything(), email: expect.any(String), firstname: input.firstname, lastname: input.lastname, username: expect.stringOrNull(), isActive: expect.any(Boolean), }); }); test('Updating password requires currentPassword', async () => { const input = { password: 'newPassword1234', }; const res = await rq({ url: '/admin/users/me', method: 'PUT', body: input, }); expect(res.statusCode).toBe(400); expect(res.body).toMatchObject({ data: null, error: { status: 400, name: 'ValidationError', message: 'currentPassword is a required field', details: { errors: [ { message: 'currentPassword is a required field', name: 'ValidationError', path: ['currentPassword'], }, ], }, }, }); }); test('Updating password requires currentPassword to be valid', async () => { const input = { password: 'newPassword1234', currentPassword: 'wrongPass', }; const res = await rq({ url: '/admin/users/me', method: 'PUT', body: input, }); expect(res.statusCode).toBe(400); expect(res.body).toMatchObject({ data: null, error: { details: { currentPassword: ['Invalid credentials'], }, message: 'ValidationError', name: 'BadRequestError', status: 400, }, }); }); }); });
packages/core/admin/server/tests/admin-authenticated-user.test.api.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017515869694761932, 0.00017223430040758103, 0.00016649029566906393, 0.00017246675270143896, 0.0000021822506823809817 ]
{ "id": 3, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "});" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 312 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.998636782169342, 0.3446733355522156, 0.00016339986177626997, 0.0020230221562087536, 0.45868971943855286 ]
{ "id": 3, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "});" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 312 }
/** * Depending on the selected field find the possible filters to apply * @param {Object} fieldSchema.type the type of the filter * @returns {Object[]} */ const getFilterList = ({ fieldSchema: { type: fieldType, mainField } }) => { const type = mainField?.schema.type ? mainField.schema.type : fieldType; switch (type) { case 'enumeration': { return [ { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$eq', defaultMessage: 'is', }, value: '$contains', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$ne', defaultMessage: 'is not', }, value: '$notContains', }, ]; } case 'date': { return [ { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$eq', defaultMessage: 'is' }, value: '$eq', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$ne', defaultMessage: 'is not' }, value: '$ne', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$gt', defaultMessage: 'is greater than', }, value: '$gt', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$gte', defaultMessage: 'is greater than or equal to', }, value: '$gte', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$lt', defaultMessage: 'is less than', }, value: '$lt', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$lte', defaultMessage: 'is less than or equal to', }, value: '$lte', }, ]; } default: return [ { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$eq', defaultMessage: 'is' }, value: '$eq', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$ne', defaultMessage: 'is not' }, value: '$ne', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$null', defaultMessage: 'is null', }, value: '$null', }, { intlLabel: { id: 'components.FilterOptions.FILTER_TYPES.$notNull', defaultMessage: 'is not null', }, value: '$notNull', }, ]; } }; export default getFilterList;
packages/core/upload/admin/src/components/FilterPopover/utils/getFilterList.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001770766102708876, 0.00017460786330047995, 0.00017006265989039093, 0.00017557496903464198, 0.0000023471266104024835 ]
{ "id": 3, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "});" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 312 }
import { setContentTypeLinks } from '../actions'; describe('Content Manager | App | actions', () => { it('should format the setContentTypeLinks action', () => { const authorizedCtLinks = [{ title: 'addresses', uid: 'address' }]; const authorizedStLinks = [{ title: 'Home page', uid: 'homepage' }]; const models = [ { kind: 'singleType', uid: 'homepage' }, { kind: 'collectionType', uid: 'address' }, ]; const components = []; const expected = { type: 'ContentManager/App/SET_CONTENT_TYPE_LINKS', data: { authorizedCtLinks, authorizedStLinks, contentTypeSchemas: models, components, }, }; expect(setContentTypeLinks(authorizedCtLinks, authorizedStLinks, models, components)).toEqual( expected ); }); });
packages/core/admin/admin/src/content-manager/pages/App/tests/actions.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001744120818329975, 0.0001717421255307272, 0.00016855822468642145, 0.00017225607007276267, 0.0000024173007204808528 ]
{ "id": 3, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "});" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 312 }
export default [ 'strapi::errors', 'strapi::security', 'strapi::cors', 'strapi::poweredBy', 'strapi::logger', 'strapi::query', 'strapi::body', 'strapi::session', 'strapi::favicon', 'strapi::public', ];
packages/generators/app/lib/resources/files/ts/config/middlewares.ts
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017229894001502544, 0.00017118063988164067, 0.0001700623397482559, 0.00017118063988164067, 0.0000011183001333847642 ]
{ "id": 4, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 120 }
'use strict'; const fs = require('fs'); const path = require('path'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createAuthRequest } = require('../../../../../test/helpers/request'); let strapi; let rq; let rqAdmin; let uploadFolder; describe('Uploads folder (GraphQL)', () => { beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); }); describe('uploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('multipleUploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); });
packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9985781908035278, 0.25688686966896057, 0.00016604179108981043, 0.005575402639806271, 0.4281688928604126 ]
{ "id": 4, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 120 }
'use strict'; const { createTestBuilder } = require('../../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../../test/helpers/strapi'); const { createAuthRequest } = require('../../../../../../test/helpers/request'); const builder = createTestBuilder(); let strapi; let rq; const ct = { displayName: 'withfloat', singularName: 'withfloat', pluralName: 'withfloats', attributes: { field: { type: 'float', }, }, }; describe('Test type float', () => { beforeAll(async () => { await builder.addContentType(ct).build(); strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); }); afterAll(async () => { await strapi.destroy(); await builder.cleanup(); }); test('Create entry with value input JSON', async () => { const inputValue = 12.31; const res = await rq.post('/content-manager/collection-types/api::withfloat.withfloat', { body: { field: inputValue, }, }); expect(res.statusCode).toBe(200); expect(res.body).toMatchObject({ field: inputValue, }); }); test('Create entry with integer should convert to float', async () => { const inputValue = 1821; const res = await rq.post('/content-manager/collection-types/api::withfloat.withfloat', { body: { field: inputValue, }, }); expect(res.statusCode).toBe(200); expect(res.body).toMatchObject({ field: 1821.0, }); }); test('Reading entry, returns correct value', async () => { const res = await rq.get('/content-manager/collection-types/api::withfloat.withfloat'); expect(res.statusCode).toBe(200); expect(res.body.pagination).toBeDefined(); expect(Array.isArray(res.body.results)).toBe(true); res.body.results.forEach((entry) => { expect(entry.field).toEqual(expect.any(Number)); }); }); test('Updating entry sets the right value and format', async () => { const res = await rq.post('/content-manager/collection-types/api::withfloat.withfloat', { body: { field: 11.2, }, }); const updateRes = await rq.put( `/content-manager/collection-types/api::withfloat.withfloat/${res.body.id}`, { body: { field: 14, }, } ); expect(updateRes.statusCode).toBe(200); expect(updateRes.body).toMatchObject({ id: res.body.id, field: 14.0, }); }); });
packages/core/content-manager/server/tests/fields/float.test.api.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017814658349379897, 0.0001746663183439523, 0.00017072685295715928, 0.0001745430927257985, 0.0000021059574919490842 ]
{ "id": 4, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 120 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Content-Manager || RelationInput should render and match snapshot 1`] = ` .c36 { border: 0; -webkit-clip: rect(0 0 0 0); clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .c0 { padding-bottom: 12px; } .c2 { -webkit-flex-basis: 70%; -ms-flex-preferred-size: 70%; flex-basis: 70%; } .c8 { padding-right: 12px; } .c12 { padding-right: 8px; } .c15 { background: #ffffff; padding-top: 8px; padding-right: 16px; padding-bottom: 8px; padding-left: 16px; border-radius: 4px; border-color: #dcdce4; border: 1px solid #dcdce4; } .c18 { padding-top: 4px; padding-right: 16px; padding-bottom: 4px; min-width: 0px; } .c23 { background: #eaf5ff; padding-top: 4px; padding-right: 8px; padding-bottom: 4px; padding-left: 8px; border-radius: 4px; border-color: #b8e1ff; border: 1px solid #b8e1ff; } .c26 { padding-left: 16px; } .c28 { color: #666687; width: 12px; } .c31 { background: #eafbe7; padding-top: 4px; padding-right: 8px; padding-bottom: 4px; padding-left: 8px; border-radius: 4px; border-color: #c6f0c2; border: 1px solid #c6f0c2; } .c34 { padding-top: 8px; } .c1 { -webkit-align-items: end; -webkit-box-align: end; -ms-flex-align: end; align-items: end; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; gap: 8px; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .c3 { -webkit-align-items: stretch; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c7 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .c16 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .c6 { font-size: 0.75rem; line-height: 1.33; font-weight: 600; color: #32324d; } .c13 { font-size: 0.75rem; line-height: 1.33; color: #4945ff; } .c22 { font-size: 0.875rem; line-height: 1.43; color: #32324d; } .c25 { font-size: 0.875rem; line-height: 1.43; font-weight: 600; color: #006096; } .c30 { font-size: 0.875rem; line-height: 1.43; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #4945ff; } .c33 { font-size: 0.875rem; line-height: 1.43; font-weight: 600; color: #2f6846; } .c35 { font-size: 0.75rem; line-height: 1.33; color: #666687; } .c4 > * { margin-top: 0; margin-bottom: 0; } .c4 > * + * { margin-top: 4px; } .c29 path { fill: #666687; } .c11 { background: transparent; border: none; position: relative; outline: none; } .c11[aria-disabled='true'] { pointer-events: none; } .c11[aria-disabled='true'] svg path { fill: #666687; } .c11 svg { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; font-size: 0.625rem; } .c11 svg path { fill: #4945ff; } .c11:after { -webkit-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; border-radius: 8px; content: ''; position: absolute; top: -4px; bottom: -4px; left: -4px; right: -4px; border: 2px solid transparent; } .c11:focus-visible { outline: none; } .c11:focus-visible:after { border-radius: 8px; content: ''; position: absolute; top: -5px; bottom: -5px; left: -5px; right: -5px; border: 2px solid #4945ff; } .c9 { background: transparent; border: none; position: relative; z-index: 1; } .c9 svg { height: 0.6875rem; width: 0.6875rem; } .c9 svg path { fill: #666687; } .c10 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; background: none; border: none; } .c10 svg { width: 0.5625rem; } .c24 .c5 { color: #0c75af; } .c32 .c5 { color: #328048; } .c20 { display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-text-decoration: none; text-decoration: none; color: #4945ff; position: relative; outline: none; } .c20 svg path { -webkit-transition: fill 150ms ease-out; transition: fill 150ms ease-out; fill: currentColor; } .c20 svg { font-size: 0.625rem; } .c20 .c5 { -webkit-transition: color 150ms ease-out; transition: color 150ms ease-out; color: currentColor; } .c20:hover { color: #7b79ff; } .c20:active { color: #271fe0; } .c20:after { -webkit-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; border-radius: 8px; content: ''; position: absolute; top: -4px; bottom: -4px; left: -4px; right: -4px; border: 2px solid transparent; } .c20:focus-visible { outline: none; } .c20:focus-visible:after { border-radius: 8px; content: ''; position: absolute; top: -5px; bottom: -5px; left: -5px; right: -5px; border: 2px solid #4945ff; } .c17 { width: 100%; min-width: 0; } .c14 { position: relative; overflow-x: hidden; overflow-y: auto; } .c14:before, .c14:after { position: absolute; width: 100%; height: 4px; z-index: 1; } .c14:before { background: linear-gradient(rgba(33,33,52,0.1) 0%,rgba(0,0,0,0) 100%); top: 0; } .c14:after { background: linear-gradient(rgba(0,0,0,0) 0%,rgba(33,33,52,0.1) 100%); bottom: 0; } .c21 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inherit; } .c19 > span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inherit; } .c27 svg path { fill: #8e8ea9; } .c27:hover svg path, .c27:focus svg path { fill: #666687; } <div> <div> <div class="c0 c1" wrap="wrap" > <div class="c2 c3 c4" spacing="1" > <label class="c5 c6" for="1" > <div class="c7" > Some Relation </div> </label> <div class=" css-1iyvlxg-container" > <span class="css-1f43avz-a11yText-A11yText" id="react-select-2-live-region" /> <span aria-atomic="false" aria-live="polite" aria-relevant="additions text" class="css-1f43avz-a11yText-A11yText" /> <div class=" css-1e1stxh-control" > <div class=" css-do2euy-ValueContainer" > <div class=" css-17f8yyk-placeholder" id="react-select-2-placeholder" > Select... </div> <div class=" css-aaf1np-Input" data-value="" > <input aria-autocomplete="list" aria-describedby="react-select-2-placeholder" aria-expanded="false" aria-haspopup="true" aria-invalid="false" autocapitalize="none" autocomplete="off" autocorrect="off" class="" id="1" role="combobox" spellcheck="false" style="opacity: 1; width: 100%; grid-area: 1 / 2; min-width: 2px; border: 0px; margin: 0px; outline: 0; padding: 0px;" tabindex="0" type="text" value="" /> </div> </div> <div class=" css-1hb7zxy-IndicatorsContainer" > <button class="c8 c9 c10" type="button" > <svg fill="none" height="1em" viewBox="0 0 14 8" width="1em" xmlns="http://www.w3.org/2000/svg" > <path clip-rule="evenodd" d="M14 .889a.86.86 0 01-.26.625L7.615 7.736A.834.834 0 017 8a.834.834 0 01-.615-.264L.26 1.514A.861.861 0 010 .889c0-.24.087-.45.26-.625A.834.834 0 01.875 0h12.25c.237 0 .442.088.615.264a.86.86 0 01.26.625z" fill="#32324D" fill-rule="evenodd" /> </svg> </button> </div> </div> <input name="some-relation-1" type="hidden" value="" /> </div> </div> <button aria-disabled="false" class="c7 c11" type="button" > <span aria-hidden="true" class="c12" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path clip-rule="evenodd" d="M15.681 2.804A9.64 9.64 0 0011.818 2C6.398 2 2 6.48 2 12c0 5.521 4.397 10 9.818 10 2.03 0 4.011-.641 5.67-1.835a9.987 9.987 0 003.589-4.831 1.117 1.117 0 00-.664-1.418 1.086 1.086 0 00-1.393.676 7.769 7.769 0 01-2.792 3.758 7.546 7.546 0 01-4.41 1.428V4.222h.002a7.492 7.492 0 013.003.625 7.61 7.61 0 012.5 1.762l.464.551-2.986 3.042a.186.186 0 00.129.316H22V3.317a.188.188 0 00-.112-.172.179.179 0 00-.199.04l-2.355 2.4-.394-.468-.02-.02a9.791 9.791 0 00-3.239-2.293zm-3.863 1.418V2v2.222zm0 0v15.556c-4.216 0-7.636-3.484-7.636-7.778s3.42-7.777 7.636-7.778z" fill="#212134" fill-rule="evenodd" /> </svg> </span> <span class="c5 c13" > Load more </span> </button> </div> <div class="c14" > <div class="c3 c4" spacing="1" > <div style="position: relative; height: 150px; overflow: auto; will-change: transform; direction: ltr;" > <ol style="height: 150px; width: 100%;" > <li class="" style="position: absolute; left: 0px; top: 0px; height: 50px; width: 100%;" > <div class="c15 c16" > <div class="c16 c17" > <div class="c18 c19" > <span> <a aria-current="page" aria-describedby="tooltip-1" class="c20 c21 active" href="/" tabindex="0" > <span class="c5 c22" > Relation 1 </span> </a> </span> </div> <div class="c23 c24" > <span class="c5 c25" > Draft </span> </div> </div> <div class="c26" > <button aria-label="Remove" class="c27" data-testid="remove-relation-1" type="button" > <svg class="c28 c29" fill="none" height="1em" viewBox="0 0 24 24" width="12px" xmlns="http://www.w3.org/2000/svg" > <path d="M24 2.417L21.583 0 12 9.583 2.417 0 0 2.417 9.583 12 0 21.583 2.417 24 12 14.417 21.583 24 24 21.583 14.417 12 24 2.417z" fill="#212134" /> </svg> </button> </div> </div> </li> <li class="" style="position: absolute; left: 0px; top: 50px; height: 50px; width: 100%;" > <div class="c15 c16" > <div class="c16 c17" > <div class="c18 c19" > <span> <span aria-describedby="tooltip-3" class="c5 c30" tabindex="0" > Relation 2 </span> </span> </div> <div class="c31 c32" > <span class="c5 c33" > Published </span> </div> </div> <div class="c26" > <button aria-label="Remove" class="c27" data-testid="remove-relation-2" type="button" > <svg class="c28 c29" fill="none" height="1em" viewBox="0 0 24 24" width="12px" xmlns="http://www.w3.org/2000/svg" > <path d="M24 2.417L21.583 0 12 9.583 2.417 0 0 2.417 9.583 12 0 21.583 2.417 24 12 14.417 21.583 24 24 21.583 14.417 12 24 2.417z" fill="#212134" /> </svg> </button> </div> </div> </li> <li class="" style="position: absolute; left: 0px; top: 100px; height: 50px; width: 100%;" > <div class="c15 c16" > <div class="c16 c17" > <div class="c18 c19" > <span> <span aria-describedby="tooltip-5" class="c5 c30" tabindex="0" > Relation 3 </span> </span> </div> </div> <div class="c26" > <button aria-label="Remove" class="c27" data-testid="remove-relation-3" type="button" > <svg class="c28 c29" fill="none" height="1em" viewBox="0 0 24 24" width="12px" xmlns="http://www.w3.org/2000/svg" > <path d="M24 2.417L21.583 0 12 9.583 2.417 0 0 2.417 9.583 12 0 21.583 2.417 24 12 14.417 21.583 24 24 21.583 14.417 12 24 2.417z" fill="#212134" /> </svg> </button> </div> </div> </li> </ol> </div> </div> </div> <div class="c34" > <p class="c5 c35" id="1-hint" > this is a description </p> </div> </div> <div class="c36" > <p aria-live="polite" aria-relevant="all" id="live-region-log" role="log" /> <p aria-live="polite" aria-relevant="all" id="live-region-status" role="status" /> <p aria-live="assertive" aria-relevant="all" id="live-region-alert" role="alert" /> </div> </div> `;
packages/core/admin/admin/src/content-manager/components/RelationInput/tests/__snapshots__/RelationInput.test.js.snap
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001799593446776271, 0.00017483020201325417, 0.00016528168634977192, 0.00017540539556648582, 0.000002976169298563036 ]
{ "id": 4, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 120 }
import set from 'lodash/set'; /** * @param {string} endpath – the final path that you're looking to replace * @returns {function} findLeafReducer – a function that will be used in the reduce */ export const findLeafByPathAndReplace = (endpath, replaceWith) => { /** * @param {object} acc – the data tree * @param {*} curr – string, this _could_ be used to index the accumulator * @param {*} ind - your current index of the array you're reducing * @returns {object} – the new object with the replaced values */ const findLeafAndReplace = (acc, curr, ind, currentArr) => { /** * Because we're returning the `accumulator[current]` at the bottom * and some components may not exist at this point, we check if `accumulator` * exists before trying to access & replace properties. */ if (!acc) return acc; /** * If this is the last item in the array of paths * and the current path is not undefined in the accumulator * then we assume it's a leaf and we can replace it. */ if (endpath === curr && acc[curr] !== undefined) { set(acc, curr, replaceWith); return acc; } /** * If the value of the accumulator[current] is an array * then we need to loop over it and call the reducer again * this time with each array item being the accumulator. */ if (Array.isArray(acc[curr])) { acc[curr].forEach((item) => { currentArr.slice(ind + 1).reduce(findLeafAndReplace, item); }); } /** * accumulator[current]return accumulator[current] instead of the main accumulator, * this will stop the same keys overwrite the wrong objects */ return acc[curr]; }; return findLeafAndReplace; };
packages/core/admin/admin/src/content-manager/components/EditViewDataManagerProvider/utils/findLeafByPathAndReplace.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017599006241653115, 0.00017336990276817232, 0.0001706090260995552, 0.0001727233175188303, 0.0000018796728227243875 ]
{ "id": 5, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 165 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9983407258987427, 0.32128262519836426, 0.0001630870101507753, 0.0035701156593859196, 0.45651304721832275 ]
{ "id": 5, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 165 }
'use strict'; module.exports = { permission: { schema: require('./Permission') }, user: { schema: require('./User') }, role: { schema: require('./Role') }, 'api-token': { schema: require('./api-token') }, 'api-token-permission': { schema: require('./api-token-permission') }, };
packages/core/admin/server/content-types/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001758248545229435, 0.0001758248545229435, 0.0001758248545229435, 0.0001758248545229435, 0 ]
{ "id": 5, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 165 }
import { normalizeSearchResults } from '../normalizeSearchResults'; const FIXTURE_RELATIONS = { data: { pages: [ { results: [ { id: 3, name: 'Relation 3', publishedAt: '2022-08-24T09:29:11.38', }, { id: 2, name: 'Relation 2', publishedAt: '', }, { id: 1, name: 'Relation 1', }, ], }, ], }, }; describe('RelationInputDataManager || normalizeSearchResults', () => { test('add publicationState attribute to each relation', () => { expect(normalizeSearchResults(FIXTURE_RELATIONS, {})).toStrictEqual({ data: [ expect.objectContaining({ publicationState: 'published' }), expect.objectContaining({ publicationState: 'draft' }), expect.objectContaining({ publicationState: false }), ], }); }); test('add mainField attribute to each relation', () => { expect( normalizeSearchResults(FIXTURE_RELATIONS, { mainFieldName: 'name', }) ).toStrictEqual({ data: [ expect.objectContaining({ mainField: FIXTURE_RELATIONS.data.pages[0].results[0].name, }), expect.objectContaining({ mainField: FIXTURE_RELATIONS.data.pages[0].results[1].name, }), expect.objectContaining({ mainField: FIXTURE_RELATIONS.data.pages[0].results[2].name, }), ], }); }); });
packages/core/admin/admin/src/content-manager/components/RelationInputDataManager/utils/tests/normalizeSearchResults.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00023778372269589454, 0.00018362260016147047, 0.00016955958562903106, 0.00017553674115333706, 0.000022220874598133378 ]
{ "id": 5, "code_window": [ " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 165 }
'use strict'; const _ = require('lodash'); const { cloneDeep, isPlainObject } = require('lodash/fp'); const { subject: asSubject } = require('@casl/ability'); const createSanitizeHelpers = require('./sanitize'); const { buildStrapiQuery, buildCaslQuery } = require('./query-builers'); module.exports = ({ ability, action, model }) => ({ ability, action, model, get isAllowed() { return this.ability.can(action, model); }, toSubject(target, subjectType = model) { return asSubject(subjectType, target); }, pickPermittedFieldsOf(data, options = {}) { return this.sanitizeInput(data, options); }, getQuery(queryAction = action) { if (_.isUndefined(queryAction)) { throw new Error('Action must be defined to build a permission query'); } return buildStrapiQuery(buildCaslQuery(ability, queryAction, model)); }, addPermissionsQueryTo(query = {}, action) { const newQuery = cloneDeep(query); const permissionQuery = this.getQuery(action); newQuery.filters = isPlainObject(query.filters) ? { $and: [query.filters, permissionQuery] } : permissionQuery; return newQuery; }, ...createSanitizeHelpers({ action, ability, model }), });
packages/core/admin/server/services/permission/permissions-manager/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017724299686960876, 0.00017459395166952163, 0.0001727893977658823, 0.00017329692491330206, 0.000001944518317031907 ]
{ "id": 6, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 232 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.998335063457489, 0.30116742849349976, 0.00016442766354884952, 0.003863108344376087, 0.447498083114624 ]
{ "id": 6, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 232 }
'use strict'; const { createAPI } = require('./api'); const createAdminAPI = (strapi) => { const opts = { prefix: '', // '/admin'; type: 'admin', }; return createAPI(strapi, opts); }; module.exports = { createAdminAPI };
packages/core/strapi/lib/services/server/admin-api.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017225935880560428, 0.00017186024342663586, 0.00017146114259958267, 0.00017186024342663586, 3.9910810301080346e-7 ]
{ "id": 6, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 232 }
{ "BoundRoute.title": "Rota definida para", "EditForm.inputSelect.description.role": "Ele anexará o novo usuário autenticado ao nível selecionado.", "EditForm.inputSelect.label.role": "Nível padrão para usuários autenticados", "EditForm.inputToggle.description.email": "Não permitir que o usuário crie várias contas usando o mesmo endereço de e-mail com diferentes provedores de autenticação.", "EditForm.inputToggle.description.sign-up": "Quando desativado (OFF), o processo de registro é proibido. Nenhum novo usuário poderá se registrar, não importa o provedor usado.", "EditForm.inputToggle.label.email": "Limitar 1 conta por endereço de email", "EditForm.inputToggle.label.sign-up": "Ativar registro de usuários", "HeaderNav.link.advancedSettings": "Configurações avançadas", "HeaderNav.link.emailTemplates": "Modelos de email", "HeaderNav.link.providers": "Provedores", "Plugin.permissions.plugins.description": "Defina todas as ações permitidas para o plugin {name}.", "Plugins.header.description": "Somente ações vinculadas por uma rota estão listadas abaixo.", "Plugins.header.title": "Permissões", "Policies.header.hint": "Selecione as ações do aplicativo ou as ações do plugin e clique no ícone do cog para exibir a rota", "Policies.header.title": "Configurações avançadas", "PopUpForm.Email.email_templates.inputDescription": "Se não tiver certeza de como usar variáveis, {link}", "PopUpForm.Email.options.from.email.label": "Email do remetente", "PopUpForm.Email.options.from.email.placeholder": "[email protected]", "PopUpForm.Email.options.from.name.label": "Nome do remetente", "PopUpForm.Email.options.from.name.placeholder": "Kai Doe", "PopUpForm.Email.options.message.label": "Mensagem", "PopUpForm.Email.options.object.label": "Assunto", "PopUpForm.Email.options.response_email.label": "Email de resposta", "PopUpForm.Email.options.response_email.placeholder": "[email protected]", "PopUpForm.Providers.enabled.description": "Se desativado, os usuários não poderão usar este provedor", "PopUpForm.Providers.enabled.label": "Ativar", "PopUpForm.Providers.key.label": "ID do cliente", "PopUpForm.Providers.key.placeholder": "TEXT", "PopUpForm.Providers.redirectURL.front-end.label": "O URL de redirecionamento para seu aplicativo front-end", "PopUpForm.Providers.secret.label": "Segredo do Cliente", "PopUpForm.Providers.secret.placeholder": "TEXT", "PopUpForm.Providers.subdomain.label": "Host URI (Subdomain)", "PopUpForm.Providers.subdomain.placeholder": "my.subdomain.com", "PopUpForm.header.edit.email-templates": "Editar modelos de email", "notification.success.submit": "As configurações foram atualizadas", "plugin.description.long": "Proteja sua API com um processo de autenticação completo baseado no JWT. Esse plugin também vem com uma estratégia de ACL que permite gerenciar as permissões entre os grupos de usuários.", "plugin.description.short": "Proteja sua API com um processo de autenticação completo baseado no JWT", "plugin.name": "Papéis e permissões" }
packages/plugins/users-permissions/admin/src/translations/pt-BR.json
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017626363842282444, 0.00017357613251078874, 0.000170891682500951, 0.00017438895883969963, 0.0000019240837900724728 ]
{ "id": 6, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 232 }
import React, { useEffect, useRef } from 'react'; import { useIntl } from 'react-intl'; import { useQuery, useMutation, useQueryClient } from 'react-query'; import { useHistory } from 'react-router-dom'; import qs from 'qs'; import { SettingsPageTitle, useFocusWhenNavigate, useNotification, NoPermissions, useRBAC, NoContent, DynamicTable, useTracking, useGuidedTour, LinkButton, } from '@strapi/helper-plugin'; import { HeaderLayout, ContentLayout } from '@strapi/design-system/Layout'; import { Main } from '@strapi/design-system/Main'; import { Button } from '@strapi/design-system/Button'; import Plus from '@strapi/icons/Plus'; import { axiosInstance } from '../../../../../core/utils'; import adminPermissions from '../../../../../permissions'; import tableHeaders from './utils/tableHeaders'; import TableRows from './DynamicTable'; const ApiTokenListView = () => { useFocusWhenNavigate(); const queryClient = useQueryClient(); const { formatMessage } = useIntl(); const toggleNotification = useNotification(); const { allowedActions: { canCreate, canDelete, canUpdate, canRead }, } = useRBAC(adminPermissions.settings['api-tokens']); const { push } = useHistory(); const { trackUsage } = useTracking(); const { startSection } = useGuidedTour(); const startSectionRef = useRef(startSection); useEffect(() => { if (startSectionRef.current) { startSectionRef.current('apiTokens'); } }, []); useEffect(() => { push({ search: qs.stringify({ sort: 'name:ASC' }, { encode: false }) }); }, [push]); const headers = tableHeaders.map((header) => ({ ...header, metadatas: { ...header.metadatas, label: formatMessage(header.metadatas.label), }, })); const { data: apiTokens, status, isFetching, } = useQuery( ['api-tokens'], async () => { trackUsage('willAccessTokenList'); const { data: { data }, } = await axiosInstance.get(`/admin/api-tokens`); trackUsage('didAccessTokenList', { number: data.length }); return data; }, { enabled: canRead, onError() { toggleNotification({ type: 'warning', message: { id: 'notification.error', defaultMessage: 'An error occured' }, }); }, } ); const isLoading = canRead && ((status !== 'success' && status !== 'error') || (status === 'success' && isFetching)); const deleteMutation = useMutation( async (id) => { await axiosInstance.delete(`/admin/api-tokens/${id}`); }, { async onSuccess() { await queryClient.invalidateQueries(['api-tokens']); trackUsage('didDeleteToken'); }, onError(err) { if (err?.response?.data?.data) { toggleNotification({ type: 'warning', message: err.response.data.data }); } else { toggleNotification({ type: 'warning', message: { id: 'notification.error', defaultMessage: 'An error occured' }, }); } }, } ); const shouldDisplayDynamicTable = canRead && apiTokens; const shouldDisplayNoContent = canRead && !apiTokens && !canCreate; const shouldDisplayNoContentWithCreationButton = canRead && !apiTokens && canCreate; return ( <Main aria-busy={isLoading}> <SettingsPageTitle name="API Tokens" /> <HeaderLayout title={formatMessage({ id: 'Settings.apiTokens.title', defaultMessage: 'API Tokens' })} subtitle={formatMessage({ id: 'Settings.apiTokens.description', defaultMessage: 'List of generated tokens to consume the API', })} primaryAction={ canCreate ? ( <LinkButton data-testid="create-api-token-button" startIcon={<Plus />} size="S" onClick={() => trackUsage('willAddTokenFromList')} to="/settings/api-tokens/create" > {formatMessage({ id: 'Settings.apiTokens.create', defaultMessage: 'Create new API Token', })} </LinkButton> ) : undefined } /> <ContentLayout> {!canRead && <NoPermissions />} {shouldDisplayDynamicTable && ( <DynamicTable headers={headers} contentType="api-tokens" rows={apiTokens} withBulkActions={canDelete || canUpdate || canRead} isLoading={isLoading} onConfirmDelete={(id) => deleteMutation.mutateAsync(id)} > <TableRows canRead={canRead} canDelete={canDelete} canUpdate={canUpdate} rows={apiTokens} withBulkActions={canDelete || canUpdate || canRead} /> </DynamicTable> )} {shouldDisplayNoContentWithCreationButton && ( <NoContent content={{ id: 'Settings.apiTokens.addFirstToken', defaultMessage: 'Add your first API Token', }} action={ <Button variant="secondary" startIcon={<Plus />}> {formatMessage({ id: 'Settings.apiTokens.addNewToken', defaultMessage: 'Add new API Token', })} </Button> } /> )} {shouldDisplayNoContent && ( <NoContent content={{ id: 'Settings.apiTokens.emptyStateLayout', defaultMessage: 'You don’t have any content yet...', }} /> )} </ContentLayout> </Main> ); }; export default ApiTokenListView;
packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/ListView/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017815575120039284, 0.00017340568592771888, 0.00016898338799364865, 0.00017379011842422187, 0.00000253452276410826 ]
{ "id": 7, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 278 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9983904361724854, 0.2947888970375061, 0.00016423867782577872, 0.0024879639968276024, 0.4455525279045105 ]
{ "id": 7, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 278 }
import { renderHook } from '@testing-library/react-hooks'; import { useTrackUsage } from '..'; const trackUsageMock = jest.fn(); jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn(() => jest.fn()), useSelector: jest.fn(() => 'init'), })); jest.mock('@strapi/helper-plugin', () => ({ useTracking: jest.fn(() => ({ trackUsage: trackUsageMock })), })); describe('Admin | pages | Admin | useTrackUsage', () => { it('should call the trackUsage method on mount with didAccessAuthenticatedAdministration', () => { const { rerender } = renderHook(() => useTrackUsage()); rerender(); expect(trackUsageMock).toHaveBeenCalledTimes(1); expect(trackUsageMock).toHaveBeenCalledWith('didAccessAuthenticatedAdministration'); }); });
packages/core/admin/admin/src/pages/Admin/tests/useTrackUsage.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001786321954568848, 0.00017746210505720228, 0.00017645971092861146, 0.00017729437968228012, 8.948067602432275e-7 ]
{ "id": 7, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 278 }
Copyright (c) 2015-present Strapi Solutions SAS Portions of the Strapi software are licensed as follows: * All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE". * All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. MIT Expat License 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.
packages/providers/email-sendgrid/LICENSE
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001741055166348815, 0.0001712192315608263, 0.0001696268591331318, 0.0001699253625702113, 0.0000020445363588805776 ]
{ "id": 7, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 278 }
import checkLatestStrapiVersion from '../checkLatestStrapiVersion'; describe('ADMIN | utils | checkLatestStrapiVersion', () => { it('should return true if the current version is lower than the latest published version', () => { expect(checkLatestStrapiVersion('v3.3.2', 'v3.3.4')).toBeTruthy(); expect(checkLatestStrapiVersion('3.3.2', 'v3.3.4')).toBeTruthy(); expect(checkLatestStrapiVersion('v3.3.2', '3.3.4')).toBeTruthy(); expect(checkLatestStrapiVersion('3.3.2', '3.3.4')).toBeTruthy(); }); it('should return false if the current version is equal to the latest published version', () => { expect(checkLatestStrapiVersion('3.3.4', 'v3.3.4')).toBeFalsy(); expect(checkLatestStrapiVersion('v3.3.4', '3.3.4')).toBeFalsy(); expect(checkLatestStrapiVersion('3.3.4', '3.3.4')).toBeFalsy(); }); it('should return false if the current version is a beta of the next release', () => { expect(checkLatestStrapiVersion('3.4.0-beta.1', 'v3.3.4')).toBeFalsy(); expect(checkLatestStrapiVersion('v3.4.0-beta.1', '3.3.4')).toBeFalsy(); expect(checkLatestStrapiVersion('3.4.0-beta.1', '3.3.4')).toBeFalsy(); }); });
packages/core/admin/admin/src/components/AuthenticatedApp/utils/tests/checkLatestStrapiVersion.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001768285728758201, 0.00017518724780529737, 0.00017420845688320696, 0.00017452471365686506, 0.000001167751520370075 ]
{ "id": 8, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 362 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9984912872314453, 0.31753334403038025, 0.00016405868518631905, 0.0019936561584472656, 0.456246554851532 ]
{ "id": 8, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 362 }
import React, { memo, useMemo } from 'react'; import PropTypes from 'prop-types'; import { BaseCheckbox } from '@strapi/design-system/BaseCheckbox'; import { Box } from '@strapi/design-system/Box'; import { Stack } from '@strapi/design-system/Stack'; import { Typography } from '@strapi/design-system/Typography'; import styled from 'styled-components'; import get from 'lodash/get'; import IS_DISABLED from 'ee_else_ce/pages/SettingsPage/pages/Roles/EditPage/components/GlobalActions/utils/constants'; import { useIntl } from 'react-intl'; import { usePermissionsDataManager } from '../../../../../../../hooks'; import { cellWidth, firstRowWidth } from '../Permissions/utils/constants'; import { findDisplayedActions, getCheckboxesState } from './utils'; const CenteredStack = styled(Stack)` align-items: center; justify-content: center; width: ${cellWidth}; flex-shrink: 0; `; const GlobalActions = ({ actions, isFormDisabled, kind }) => { const { formatMessage } = useIntl(); const { modifiedData, onChangeCollectionTypeGlobalActionCheckbox } = usePermissionsDataManager(); const displayedActions = useMemo(() => { return findDisplayedActions(actions); }, [actions]); const checkboxesState = useMemo(() => { return getCheckboxesState(displayedActions, modifiedData[kind]); }, [modifiedData, displayedActions, kind]); return ( <Box paddingBottom={4} paddingTop={6} style={{ paddingLeft: firstRowWidth }}> <Stack horizontal spacing={0}> {displayedActions.map(({ label, actionId }) => { return ( <CenteredStack key={actionId} spacing={3}> <Typography variant="sigma" textColor="neutral500"> {formatMessage({ id: `Settings.roles.form.permissions.${label.toLowerCase()}`, defaultMessage: label, })} </Typography> <BaseCheckbox disabled={isFormDisabled || IS_DISABLED} onValueChange={(value) => { onChangeCollectionTypeGlobalActionCheckbox(kind, actionId, value); }} name={actionId} aria-label={formatMessage( { id: `Settings.permissions.select-all-by-permission`, defaultMessage: 'Select all {label} permissions', }, { label: formatMessage({ id: `Settings.roles.form.permissions.${label.toLowerCase()}`, defaultMessage: label, }), } )} value={get(checkboxesState, [actionId, 'hasAllActionsSelected'], false)} indeterminate={get(checkboxesState, [actionId, 'hasSomeActionsSelected'], false)} /> </CenteredStack> ); })} </Stack> </Box> ); }; GlobalActions.defaultProps = { actions: [], }; GlobalActions.propTypes = { actions: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.string.isRequired, actionId: PropTypes.string.isRequired, subjects: PropTypes.array.isRequired, }) ), isFormDisabled: PropTypes.bool.isRequired, kind: PropTypes.string.isRequired, }; export default memo(GlobalActions);
packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/GlobalActions/index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017702124023344368, 0.0001730914955260232, 0.00016798589786048979, 0.00017263797053601593, 0.0000027313551527186064 ]
{ "id": 8, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 362 }
'use strict'; const { assignDefaultLocale, syncLocalizations, syncNonLocalizedAttributes } = require('../localizations')(); const locales = require('../locales')(); const contentTypes = require('../content-types')(); const model = { uid: 'test-model', pluginOptions: { i18n: { localized: true, }, }, attributes: { title: { type: 'string', pluginOptions: { i18n: { localized: true, }, }, }, stars: { type: 'integer', }, }, }; const allLocalizedModel = { uid: 'test-model', pluginOptions: { i18n: { localized: true, }, }, attributes: { title: { type: 'string', pluginOptions: { i18n: { localized: true, }, }, }, stars: { type: 'integer', pluginOptions: { i18n: { localized: true, }, }, }, }, }; const setGlobalStrapi = () => { global.strapi = { plugins: { i18n: { services: { locales, 'content-types': contentTypes, }, }, }, }; }; describe('localizations service', () => { describe('assignDefaultLocale', () => { test('Does not change the input if locale is already defined', async () => { setGlobalStrapi(); const input = { locale: 'myLocale' }; await assignDefaultLocale(input); expect(input).toStrictEqual({ locale: 'myLocale' }); }); test('Use default locale to set the locale on the input data', async () => { setGlobalStrapi(); const getDefaultLocaleMock = jest.fn(() => 'defaultLocale'); global.strapi.plugins.i18n.services.locales.getDefaultLocale = getDefaultLocaleMock; const input = {}; await assignDefaultLocale(input); expect(input).toStrictEqual({ locale: 'defaultLocale' }); expect(getDefaultLocaleMock).toHaveBeenCalled(); }); }); describe('syncLocalizations', () => { test('Updates every other localizations with correct ids', async () => { setGlobalStrapi(); const update = jest.fn(); global.strapi.query = () => { return { update }; }; const localizations = [{ id: 2 }, { id: 3 }]; const entry = { id: 1, locale: 'test', localizations }; await syncLocalizations(entry, { model }); expect(update).toHaveBeenCalledTimes(localizations.length); expect(update).toHaveBeenNthCalledWith(1, { where: { id: 2 }, data: { localizations: [1, 3] }, }); expect(update).toHaveBeenNthCalledWith(2, { where: { id: 3 }, data: { localizations: [1, 2] }, }); }); }); describe('syncNonLocalizedAttributes', () => { test('Does nothing if no localizations set', async () => { setGlobalStrapi(); const update = jest.fn(); global.strapi.query = () => { return { update }; }; const entry = { id: 1, locale: 'test' }; await syncNonLocalizedAttributes(entry, { model }); expect(update).not.toHaveBeenCalled(); }); test('Does not update the current locale', async () => { setGlobalStrapi(); const update = jest.fn(); global.strapi.query = () => { return { update }; }; const entry = { id: 1, locale: 'test', localizations: [] }; await syncNonLocalizedAttributes(entry, { model }); expect(update).not.toHaveBeenCalled(); }); test('Does not update if all the fields are localized', async () => { setGlobalStrapi(); const update = jest.fn(); global.strapi.query = () => { return { update }; }; const entry = { id: 1, locale: 'test', localizations: [] }; await syncNonLocalizedAttributes(entry, { model: allLocalizedModel }); expect(update).not.toHaveBeenCalled(); }); test('Updates locales with non localized fields only', async () => { setGlobalStrapi(); const update = jest.fn(); global.strapi.entityService = { update }; const entry = { id: 1, locale: 'test', title: 'Localized', stars: 1, localizations: [{ id: 2, locale: 'fr' }], }; await syncNonLocalizedAttributes(entry, { model }); expect(update).toHaveBeenCalledTimes(1); expect(update).toHaveBeenCalledWith(model.uid, 2, { data: { stars: 1 } }); }); }); });
packages/plugins/i18n/server/services/__tests__/localizations.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017572747310623527, 0.0001733264944050461, 0.00016801009769551456, 0.00017386114632245153, 0.0000018896409983426565 ]
{ "id": 8, "code_window": [ " name: 'API Uploads (2)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 362 }
import pluginId from '../pluginId'; const getTrad = (id) => `${pluginId}.${id}`; export default getTrad;
packages/plugins/users-permissions/admin/src/utils/getTrad.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017282285261899233, 0.00017282285261899233, 0.00017282285261899233, 0.00017282285261899233, 0 ]
{ "id": 9, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 410 }
'use strict'; const fs = require('fs'); const path = require('path'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createAuthRequest } = require('../../../../../test/helpers/request'); let strapi; let rq; let rqAdmin; let uploadFolder; describe('Uploads folder (GraphQL)', () => { beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); }); describe('uploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('multipleUploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); });
packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9984235763549805, 0.30601105093955994, 0.0001660121779423207, 0.003680182620882988, 0.4516705572605133 ]
{ "id": 9, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 410 }
import { renderHook } from '@testing-library/react-hooks'; import { axiosInstance } from '../../../core/utils'; import useRegenerate from '../index'; jest.spyOn(axiosInstance, 'get').mockResolvedValue({ data: { data: { accessKey: 'this is my new access key', }, }, }); jest.mock('@strapi/helper-plugin', () => ({ ...jest.requireActual('@strapi/helper-plugin'), useNotification: jest.fn(), })); describe('useRegenerate', () => { it('returns a function to regenerate the data and a boolean', () => { const { result } = renderHook(() => useRegenerate(1, (accessKey) => accessKey)); expect(result.current).toEqual({ regenerateData: expect.any(Function), isLoadingConfirmation: false, }); }); });
packages/core/admin/admin/src/hooks/useRegenerate/tests/index.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017860783555079252, 0.00017696669965516776, 0.0001760891027515754, 0.00017620314611122012, 0.0000011613952892730595 ]
{ "id": 9, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 410 }
import reducer from '../reducer'; describe('USERS PERMISSIONS | HOOKS | USEROLESLIST | reducer', () => { describe('DEFAULT_ACTION', () => { it('should return the initialState', () => { const state = { test: true, }; expect(reducer(state, {})).toEqual(state); }); }); describe('GET_DATA', () => { it('should set the isLoading key to true', () => { const state = { roles: ['tests'], isLoading: false, }; const action = { type: 'GET_DATA', }; const expected = { roles: [], isLoading: true, }; expect(reducer(state, action)).toEqual(expected); }); }); describe('GET_DATA_ERROR', () => { it('should set isLoading to false is an error occured', () => { const action = { type: 'GET_DATA_ERROR', }; const initialState = { roles: [], isLoading: true, }; const expected = { roles: [], isLoading: false, }; expect(reducer(initialState, action)).toEqual(expected); }); }); describe('GET_DATA_SUCCEEDED', () => { it('should return the state with the role list', () => { const action = { type: 'GET_DATA_SUCCEEDED', data: [ { id: 1, name: 'Super admin', description: 'This is the super admin role', }, ], }; const initialState = { roles: [], isLoading: true, }; const expected = { roles: [ { id: 1, name: 'Super admin', description: 'This is the super admin role', }, ], isLoading: false, }; expect(reducer(initialState, action)).toEqual(expected); }); }); });
packages/plugins/users-permissions/admin/src/hooks/useRolesList/tests/reducer.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001782864419510588, 0.00017210943042300642, 0.00016377329302486032, 0.0001717807463137433, 0.000004381656708574155 ]
{ "id": 9, "code_window": [ " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", "\n", " uploadFolder = file.folder;\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 410 }
import { SchemaUID, GetArrayValues } from '../../utils'; import { Attribute, ConfigurableOption, MinMaxOption, RequiredOption } from './base'; import { GetAttributesValues } from './utils'; export interface DynamicZoneAttributeProperties<T extends Strapi.ComponentUIDs[] = []> { components: T; } export type DynamicZoneAttribute<T extends Strapi.ComponentUIDs[] = []> = Attribute<'dynamiczone'> & // Properties DynamicZoneAttributeProperties<T> & // Options ConfigurableOption & MinMaxOption & RequiredOption; type DynamicZoneValue<T extends Strapi.ComponentUIDs[]> = Array< GetArrayValues<T> extends infer P ? P extends SchemaUID ? GetAttributesValues<P> & { __component: P } : never : never >; export type GetDynamicZoneAttributeValue<T extends Attribute> = T extends DynamicZoneAttribute< infer U > ? DynamicZoneValue<U> : never;
packages/core/strapi/lib/types/core/attributes/dynamic-zone.d.ts
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0001771968527464196, 0.00017260498134419322, 0.0001680083223618567, 0.0001726097398204729, 0.000003751203394131153 ]
{ "id": 10, "code_window": [ " name: 'API Uploads (3)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 565 }
'use strict'; const fs = require('fs'); const path = require('path'); // Helpers. const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest, createAuthRequest, } = require('../../../../../test/helpers/request'); const builder = createTestBuilder(); const data = { dogs: [], }; let strapi; let rq; let rqAdmin; let uploadFolder; const dogModel = { displayName: 'Dog', singularName: 'dog', pluralName: 'dogs', kind: 'collectionType', attributes: { pic: { type: 'media', }, }, }; describe('Uploads folder', () => { beforeAll(async () => { await builder.addContentType(dogModel).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); await builder.cleanup(); }); describe('Regular upload', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload to an entity', () => { test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/dogs?populate=*', formData: { data: '{}', 'files.pic': fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.attributes.pic.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Attach to an entity', () => { beforeAll(async () => { const res = await rq({ method: 'POST', url: '/dogs', formData: { data: '{}', }, }); data.dogs.push(res.body.data); }); test('Uploaded file goes into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { data: '{}', files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (2)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), refId: data.dogs[0].id, ref: 'api::dog.dog', field: 'pic', }, }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body[0].id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('Upload with multiple files', () => { test('Uploaded files go into a specific folder', async () => { const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploaded files with fileInfo', async () => { const fileInfo = [ { name: 'file1', alternativeText: 'file1', caption: 'file1', }, { name: 'file2', alternativeText: 'file2', caption: 'file2', }, ]; const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], fileInfo: fileInfo.map(JSON.stringify), }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file, index) => expect(file).toMatchObject({ ...fileInfo[index], folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }) ); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (3)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (3)', parent: null, }, }); const res = await rq({ method: 'POST', url: '/upload', formData: { files: [ fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), fs.createReadStream(path.join(__dirname, '../utils/strapi.jpg')), ], }, }); expect(res.statusCode).toBe(200); const { body: { results: files }, } = await rqAdmin({ method: 'GET', url: '/upload/files', qs: { filters: { id: { $in: res.body.map(({ id }) => id), }, }, populate: '*', }, }); files.forEach((file) => { expect(file).toMatchObject({ folder: { name: 'API Uploads (4)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); }); expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true); uploadFolder = files[0].folder; }); }); });
packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.9979069232940674, 0.04959570989012718, 0.0001644576113903895, 0.0004455521993804723, 0.19072023034095764 ]
{ "id": 10, "code_window": [ " name: 'API Uploads (3)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 565 }
'use strict'; const { createTestBuilder } = require('../../../../../test/helpers/builder'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createContentAPIRequest } = require('../../../../../test/helpers/request'); let strapi; let rq; const component = { displayName: 'somecomponent', attributes: { name: { type: 'string', }, }, }; const ct = { singularName: 'withcomponent', pluralName: 'withcomponents', displayName: 'With Component', attributes: { field: { type: 'component', component: 'default.somecomponent', repeatable: true, required: false, min: 2, max: 5, }, }, }; describe('Non repeatable and Not required component', () => { const builder = createTestBuilder(); beforeAll(async () => { await builder.addComponent(component).addContentType(ct).build(); strapi = await createStrapiInstance(); rq = await createContentAPIRequest({ strapi }); rq.setURLPrefix('/api/withcomponents'); }); afterAll(async () => { await strapi.destroy(); await builder.cleanup(); }); describe('POST new entry', () => { test('Creating entry with JSON works', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'someString', }, ], }, }, qs: { populate: ['field'], }, }); expect(res.statusCode).toBe(200); expect(Array.isArray(res.body.data.attributes.field)).toBe(true); expect(res.body.data.attributes.field).toEqual( expect.arrayContaining([ expect.objectContaining({ id: expect.anything(), name: 'someString', }), ]) ); }); test.each(['someString', 128219, false, {}, null])( 'Throws if the field is not an array %p', async (value) => { const res = await rq.post('/', { body: { data: { field: value, }, }, }); expect(res.statusCode).toBe(400); } ); test('Throws when sending a non empty array with less then the min', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'test', }, ], }, }, }); expect(res.statusCode).toBe(400); }); test('Success when sending an empty array', async () => { const res = await rq.post('/', { body: { data: { field: [], }, }, }); expect(res.statusCode).toBe(200); }); test('Throws when sending too many items', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'one', }, { name: 'one', }, { name: 'one', }, { name: 'one', }, { name: 'one', }, { name: 'one', }, ], }, }, }); expect(res.statusCode).toBe(400); }); test('Can send input without the component field', async () => { const res = await rq.post('/', { body: { data: {}, }, qs: { populate: ['field'], }, }); expect(res.statusCode).toBe(200); expect(res.body.data.attributes.field).toEqual([]); }); }); describe('GET entries', () => { test('Data is ordered in the order sent', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'firstString', }, { name: 'someString', }, ], }, }, qs: { populate: ['field'], }, }); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(Array.isArray(getRes.body.data.attributes.field)).toBe(true); expect(getRes.body.data.attributes.field[0]).toMatchObject({ name: 'firstString', }); expect(getRes.body.data.attributes.field[1]).toMatchObject({ name: 'someString', }); }); test('Should return entries with their nested components', async () => { const res = await rq.get('/', { qs: { populate: ['field'], }, }); expect(res.statusCode).toBe(200); expect(Array.isArray(res.body.data)).toBe(true); res.body.data.forEach((entry) => { expect(Array.isArray(entry.attributes.field)).toBe(true); if (entry.attributes.field.length === 0) return; expect(entry.attributes.field).toEqual( expect.arrayContaining([ expect.objectContaining({ name: expect.any(String), }), ]) ); }); }); }); describe('PUT entry', () => { test.each(['someString', 128219, false, {}, null])( 'Throws when sending invalid updated field %p', async (value) => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'someString', }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: value, }, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(400); // shouldn't have been updated const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(getRes.body.data).toMatchObject({ id: res.body.data.id, attributes: { field: res.body.data.attributes.field }, }); } ); test('Updates order at each request', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'otherString', }, ], }, }, qs: { populate: ['field'], }, }); expect(res.body.data.attributes.field[0]).toMatchObject({ name: 'someString', }); expect(res.body.data.attributes.field[1]).toMatchObject({ name: 'otherString', }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: [ { name: 'otherString', }, { name: 'someString', }, ], }, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(200); expect(Array.isArray(updateRes.body.data.attributes.field)).toBe(true); expect(updateRes.body.data.attributes.field[0]).toMatchObject({ name: 'otherString', }); expect(updateRes.body.data.attributes.field[1]).toMatchObject({ name: 'someString', }); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(Array.isArray(getRes.body.data.attributes.field)).toBe(true); expect(getRes.body.data.attributes.field[0]).toMatchObject({ name: 'otherString', }); expect(getRes.body.data.attributes.field[1]).toMatchObject({ name: 'someString', }); }); test('Keeps the previous value if component not sent', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'otherString', }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: {}, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(200); expect(updateRes.body.data).toMatchObject({ id: res.body.data.id, attributes: { field: res.body.data.attributes.field }, }); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(getRes.body.data).toMatchObject({ id: res.body.data.id, attributes: { field: res.body.data.attributes.field }, }); }); test('Throws when not enough items', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'new String', }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: [ { name: 'lala', }, ], }, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(400); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(getRes.body.data).toMatchObject(res.body.data); }); test('Throws when too many items', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'test', }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: [ { name: 'someString', }, { name: 'someString', }, { name: 'someString', }, { name: 'someString', }, { name: 'someString', }, { name: 'someString', }, ], }, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(400); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(getRes.body.data).toMatchObject(res.body.data); }); test('Replaces the previous components if sent without id', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'test' }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: [ { name: 'new String', }, { name: 'test', }, ], }, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(200); const oldIds = res.body.data.attributes.field.map((val) => val.id); updateRes.body.data.attributes.field.forEach((val) => { expect(oldIds.includes(val.id)).toBe(false); }); expect(updateRes.body.data).toMatchObject({ id: res.body.data.id, attributes: { field: [ { name: 'new String', }, { name: 'test', }, ], }, }); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(getRes.body.data).toMatchObject({ id: res.body.data.id, attributes: { field: [ { name: 'new String', }, { name: 'test', }, ], }, }); }); test('Throws on invalid id in component', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'test', }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: [ { id: 'invalid_id', name: 'new String', }, ], }, }, qs: { populate: ['field'], }, }); expect(updateRes.statusCode).toBe(400); }); test('Updates component with ids, create new ones and removes old ones', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'one', }, { name: 'two', }, { name: 'three', }, ], }, }, qs: { populate: ['field'], }, }); const updateRes = await rq.put(`/${res.body.data.id}`, { body: { data: { field: [ { id: res.body.data.attributes.field[0].id, // send old id to update the previous component name: 'newOne', }, { name: 'newTwo', }, { id: res.body.data.attributes.field[2].id, name: 'three', }, { name: 'four', }, ], }, }, qs: { populate: ['field'], }, }); const expectedResult = { id: res.body.data.id, attributes: { field: [ { id: res.body.data.attributes.field[0].id, name: 'newOne', }, { name: 'newTwo', }, { id: res.body.data.attributes.field[2].id, name: 'three', }, { name: 'four', }, ], }, }; expect(updateRes.statusCode).toBe(200); expect(updateRes.body.data).toMatchObject(expectedResult); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(200); expect(getRes.body.data).toMatchObject(expectedResult); }); }); describe('DELETE entry', () => { test('Returns entry with components', async () => { const res = await rq.post('/', { body: { data: { field: [ { name: 'someString', }, { name: 'someOtherString', }, { name: 'otherSomeString', }, ], }, }, qs: { populate: ['field'], }, }); const deleteRes = await rq.delete(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(deleteRes.statusCode).toBe(200); expect(deleteRes.body.data).toMatchObject(res.body.data); const getRes = await rq.get(`/${res.body.data.id}`, { qs: { populate: ['field'], }, }); expect(getRes.statusCode).toBe(404); }); }); });
packages/core/strapi/tests/components/repeatable-not-required-min-max.test.api.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017708487575873733, 0.0001719719439279288, 0.00016524465172551572, 0.0001719063293421641, 0.000002439645641061361 ]
{ "id": 10, "code_window": [ " name: 'API Uploads (3)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 565 }
import createProvidersArray from '../createProvidersArray'; describe('USERS PERMISSIONS | CONTAINERS | Providers | utils | createProvidersArray', () => { it('should format the data correctly', () => { const data = { email: { enabled: true, icon: 'envelope' }, discord: { callback: '/auth/discord/callback', enabled: false, icon: 'discord', key: '', scope: ['identify', 'email'], secret: '', }, cognito: { enabled: false, icon: 'aws', key: '', secret: '', subdomain: '', callback: '/auth/cognito/callback', scope: ['email', 'openid', 'profile'], }, }; const expected = [ { name: 'cognito', icon: ['fab', 'aws'], enabled: false, subdomain: '', }, { name: 'discord', icon: ['fab', 'discord'], enabled: false, }, { name: 'email', icon: ['fas', 'envelope'], enabled: true, }, ]; expect(createProvidersArray(data)).toEqual(expected); }); });
packages/plugins/users-permissions/admin/src/pages/Providers/utils/tests/createProvidersArray.test.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.0005373230087570846, 0.0002452062035445124, 0.00016641680849716067, 0.0001739777362672612, 0.00014608980563934892 ]
{ "id": 10, "code_window": [ " name: 'API Uploads (3)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 565 }
'use strict'; const { resolve } = require('path'); const { statSync, existsSync } = require('fs'); const { yup, importDefault } = require('@strapi/utils'); const srcSchema = yup .object() .shape({ bootstrap: yup.mixed().isFunction(), register: yup.mixed().isFunction(), destroy: yup.mixed().isFunction(), }) .noUnknown(); const validateSrcIndex = (srcIndex) => { return srcSchema.validateSync(srcIndex, { strict: true, abortEarly: false }); }; module.exports = (strapi) => { if (!existsSync(strapi.dirs.dist.src)) { return; } const pathToSrcIndex = resolve(strapi.dirs.dist.src, 'index.js'); if (!existsSync(pathToSrcIndex) || statSync(pathToSrcIndex).isDirectory()) { return {}; } const srcIndex = importDefault(pathToSrcIndex); try { validateSrcIndex(srcIndex); } catch (e) { strapi.stopWithError({ message: `Invalid file \`./src/index.js\`: ${e.message}` }); } return srcIndex; };
packages/core/strapi/lib/core/loaders/src-index.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017651153029873967, 0.00017370536806993186, 0.00017156025569420308, 0.0001733748649712652, 0.0000019101405541732674 ]
{ "id": 11, "code_window": [ " name: 'API Uploads (4)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 627 }
'use strict'; const fs = require('fs'); const path = require('path'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const { createAuthRequest } = require('../../../../../test/helpers/request'); let strapi; let rq; let rqAdmin; let uploadFolder; describe('Uploads folder (GraphQL)', () => { beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); rqAdmin = await createAuthRequest({ strapi }); }); afterAll(async () => { // delete all folders const res = await rqAdmin({ method: 'GET', url: '/upload/folders', }); await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: res.body.data.map((f) => f.id), }, }); await strapi.destroy(); }); describe('uploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation uploadFile($file: Upload!) { upload(file: $file) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.file'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.upload.data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); describe('multipleUploadFile', () => { test('Uploaded file goes into a specific folder', async () => { const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (1)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); test('Uploads folder is recreated if deleted (handle duplicates)', async () => { await rqAdmin({ method: 'POST', url: '/upload/actions/bulk-delete', body: { folderIds: [uploadFolder.id], }, }); await rqAdmin({ method: 'POST', url: '/upload/folders', body: { name: 'API Uploads (1)', parent: null, }, }); const formData = { operations: JSON.stringify({ query: /* GraphQL */ ` mutation multipleUploadFile($files: [Upload]!) { multipleUpload(files: $files) { data { id } } } `, }), map: JSON.stringify({ nFile1: ['variables.files'] }), nFile1: fs.createReadStream(path.join(__dirname, '../utils/rec.jpg')), }; const res = await rq({ method: 'POST', url: '/graphql', formData }); expect(res.statusCode).toBe(200); const { body: file } = await rqAdmin({ method: 'GET', url: `/upload/files/${res.body.data.multipleUpload[0].data.id}`, }); expect(file).toMatchObject({ folder: { name: 'API Uploads (2)', pathId: expect.any(Number), }, folderPath: `/${file.folder.pathId}`, }); expect(file.folder.id).not.toBe(uploadFolder.id); uploadFolder = file.folder; }); }); });
packages/core/upload/tests/content-api/graphql-upload-automatic-folder.test.api.js
1
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.009605287574231625, 0.0017740949988365173, 0.00016974352183751762, 0.0005991451907902956, 0.002229670062661171 ]
{ "id": 11, "code_window": [ " name: 'API Uploads (4)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 627 }
{ "coming-soon": "이 콘텐츠는 개발중이며 몇 주 뒤에 만나볼 수 있습니다!", "components.Row.open": "열기", "components.Row.regenerate": "재생성", "containers.HomePage.Block.title": "버전", "containers.HomePage.Button.update": "업데이트", "containers.HomePage.PluginHeader.title": "도큐멘테이션 - 설정", "containers.HomePage.PopUpWarning.confirm": "이해합니다.", "containers.HomePage.PopUpWarning.message": "이 버전을 삭제하시겠습니까?", "containers.HomePage.copied": "토큰이 클립보드에 복사되었습니다.", "containers.HomePage.form.jwtToken": "JWT token 얻기", "containers.HomePage.form.jwtToken.description": "이 토큰을 복사하고 swagger에서 리퀘스트를 요청하는데 사용하세요.", "containers.HomePage.form.password": "비밀번호", "containers.HomePage.form.password.inputDescription": "문서에 액세스하기 위한 비밀번호를 설정합니다.", "containers.HomePage.form.restrictedAccess": "액세스 제한", "containers.HomePage.form.restrictedAccess.inputDescription": "도큐멘테이션 엔드포인트를 비공개로 설정합니다. 기본적으로 접근 권한은 공용(Public)입니다.", "containers.HomePage.form.showGeneratedFiles": "생성된 파일 보기", "containers.HomePage.form.showGeneratedFiles.inputDescription": "생성된 문서를 재정의하려는 경우에 유용합니다.\n플러그인은 모델 및 플러그인별로 분할된 파일을 생성합니다.\n이 옵션을 활성화하면 문서를 보다 쉽게 커스터마이징 할 수 있습니다.", "error.deleteDoc.versionMissing": "삭제하려는 버전이 존재하지 않습니다.", "error.noVersion": "버전은 필수 항목입니다.", "error.regenerateDoc": "문서를 재생성하는 중에 오류가 발생했습니다.", "error.regenerateDoc.versionMissing": "생성하려는 버전이 존재하지 않습니다.", "notification.delete.success": "문서가 삭제되었습니다.", "notification.generate.success": "문서가 생성되었습니다.", "notification.update.success": "설정이 업데이트되었습니다.", "pages.PluginPage.Button.open": "도큐멘테이션 열기", "pages.PluginPage.header.description": "도큐멘테이션 플러그인 설정", "pages.PluginPage.table.generated": "최종 생성일", "pages.PluginPage.table.icon.regenerate": "{target} 재생성", "pages.PluginPage.table.icon.show": "{target} 열기", "pages.PluginPage.table.version": "버전", "pages.SettingsPage.Button.description": "도큐멘테이션 플러그인 설정", "pages.SettingsPage.header.save": "저장", "pages.SettingsPage.toggle.hint": "도큐멘테이션 엔드포인트를 비공개로 설정합니다.", "pages.SettingsPage.toggle.label": "액세스 제한", "plugin.description.long": "SWAGER UI를 사용하여 오픈 API 문서를 만들고 API를 시각화합니다.", "plugin.description.short": "SWAGER UI를 사용하여 오픈 API 문서를 만들고 API를 시각화합니다.", "plugin.name": "도큐멘테이션" }
packages/plugins/documentation/admin/src/translations/ko.json
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00019695295486599207, 0.00017923020641319454, 0.00016681128181517124, 0.00017657830903772265, 0.000011990110579063185 ]
{ "id": 11, "code_window": [ " name: 'API Uploads (4)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 627 }
'use strict'; const { groupBy, pipe, mapValues, map, isEmpty } = require('lodash/fp'); const { createQueryBuilder } = require('../query'); const getMorphToManyRowsLinkedToMorphOne = (rows, { uid, attributeName, typeColumn, db }) => rows.filter((row) => { const relatedType = row[typeColumn.name]; const field = row.field; const targetAttribute = db.metadata.get(relatedType).attributes[field]; // ensure targeted field is the right one + check if it is a morphOne return ( targetAttribute?.target === uid && targetAttribute?.morphBy === attributeName && targetAttribute?.relation === 'morphOne' ); }); const deleteRelatedMorphOneRelationsAfterMorphToManyUpdate = async ( rows, { uid, attributeName, joinTable, db, transaction: trx } ) => { const { morphColumn } = joinTable; const { idColumn, typeColumn } = morphColumn; const morphOneRows = getMorphToManyRowsLinkedToMorphOne(rows, { uid, attributeName, typeColumn, db, }); const groupByType = groupBy(typeColumn.name); const groupByField = groupBy('field'); const typeAndFieldIdsGrouped = pipe(groupByType, mapValues(groupByField))(morphOneRows); const orWhere = []; for (const [type, v] of Object.entries(typeAndFieldIdsGrouped)) { for (const [field, arr] of Object.entries(v)) { orWhere.push({ [typeColumn.name]: type, field, [idColumn.name]: { $in: map(idColumn.name, arr) }, }); } } if (!isEmpty(orWhere)) { await createQueryBuilder(joinTable.name, db) .delete() .where({ $or: orWhere }) .transacting(trx) .execute(); } }; module.exports = { deleteRelatedMorphOneRelationsAfterMorphToManyUpdate, };
packages/core/database/lib/entity-manager/morph-relations.js
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00017619859136175364, 0.0001721250737318769, 0.00016777843120507896, 0.00017231571837328374, 0.000002810661271723802 ]
{ "id": 11, "code_window": [ " name: 'API Uploads (4)',\n", " pathId: expect.any(Number),\n", " },\n", " folderPath: `/${file.folder.pathId}`,\n", " });\n", " expect(file.folder.id).not.toBe(uploadFolder.id);\n", " });\n", "\n", " expect(files.every((file) => file.folder.id === files[0].folder.id)).toBe(true);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/upload/tests/content-api/upload-automatic-folder.test.api.js", "type": "replace", "edit_start_line_idx": 627 }
import type Koa from 'koa'; import { Database } from '@strapi/database'; import type { StringMap } from './utils'; import type { GenericController } from '../../../core-api/controller' import type { GenericService } from '../../../core-api/service' // TODO move custom fields types to a separate file interface CustomFieldServerOptions { /** * The name of the custom field */ name: string; /** * The name of the plugin creating the custom field */ plugin?: string; /** * The existing Strapi data type the custom field uses */ type: string; } interface CustomFields { register: (customFields: CustomFieldServerOptions[] | CustomFieldServerOptions) => void; } /** * The Strapi interface implemented by the main Strapi class. */ export interface Strapi { /** * Getter for the Strapi enterprise edition configuration */ readonly EE: any; /** * Getter for the Strapi configuration container */ readonly config: any; /** * Getter for the Strapi auth container */ readonly auth: any; /** * Getter for the Strapi content API container */ readonly contentAPI: any; /** * Getter for the Strapi sanitizers container */ readonly sanitizers: any; /** * Getter for the Strapi services container * * It returns all the registered services */ readonly services: StringMap<GenericService>; /** * Find a service using its unique identifier */ service<T extends GenericService = GenericService>(uid: string): T | undefined; /** * Getter for the Strapi controllers container * * It returns all the registered controllers */ readonly controllers: StringMap<GenericController>; /** * Find a controller using its unique identifier */ controller(uid: string): GenericController | undefined; /** * Getter for the Strapi content types container * * It returns all the registered content types */ readonly contentTypes: any; /** * Find a content type using its unique identifier */ contentType(uid: string): any; /** * The custom fields registry * * It returns the custom fields interface */ readonly customFields: CustomFields; /** * Getter for the Strapi policies container * * It returns all the registered policies */ readonly policies: any; /** * Find a policy using its name */ policy(name: string): any; /** * Getter for the Strapi middlewares container * * It returns all the registered middlewares */ readonly middlewares: any; /** * Find a middleware using its name */ middleware(): any; /** * Getter for the Strapi plugins container * * It returns all the registered plugins */ readonly plugins: any; /** * Find a plugin using its name */ plugin(name: string): any; /** * Getter for the Strapi hooks container * * It returns all the registered hooks */ readonly hooks: any; /** * Find a hook using its name */ hook(): any; /** * Getter for the Strapi APIs container * * It returns all the registered APIs */ readonly api: any; /** * Strapi Register Lifecycle. * * - Load * - The user application * - The plugins * - The admin * - The APIs * - The components * - The middlewares * - The policies * - Trigger Strapi internal bootstrap * - Create the webhooks runner * - Create the internal hooks registry. * - Init the telemetry cron job and middleware * - Run all the `register` lifecycle methods loaded by the user application or the enabled plugins */ register(): Promise<Strapi>; /** * Bootstraping phase. * * - Load all the content types * - Initialize the database layer * - Initialize the entity service * - Run the schemas/database synchronization * - Start the webhooks and initializing middlewares and routes * - Run all the `bootstrap` lifecycle methods loaded by the * user application or the enabled plugins */ bootstrap(): Promise<Strapi>; /** * Destroy phase * * - Destroy Strapi server * - Run all the `destroy` lifecycle methods loaded by the * user application or the enabled plugins * - Cleanup the event hub * - Gracefully stop the database * - Stop the telemetry and cron instance * - Cleanup the global scope by removing global.strapi */ destroy(): Promise<void>; /** * Run all functions registered for a given lifecycle. (Strapi core, user app, plugins) */ runLifecyclesFunctions<T extends Lifecycles[keyof Lifecycles]>(lifecycleName: T): Promise<void>; /** * Load the application if needed and start the server */ start(): Promise<void>; /** * Stop the server and provide a custom error and message */ stopWithError<TError = unknown>(error: TError, customMessage?: string): void; /** * Gracefully stop the server * Call the destroy method. */ stop(code?: number): void; /** * Load the server and the user application. * It basically triggers the register and bootstrap phases */ load(): Promise<Strapi>; /** * Restart the server and reload all the configuration. * It re-runs all the lifecycles phases. * * @example * ``` ts * setImmediate(() => strapi.reload()); * ``` */ reload(): () => void; /** * Initialize and start all the webhooks registered in the webhook store */ startWebhooks(): Promise<void>; /** * Method called when the server is fully initialized and listen to incomming requests. * It handles tasks such as logging the startup message * or automatically opening the administration panel. */ postListen(): Promise<void>; /** * Start listening for incomming requests */ listen(): Promise<void | Error>; /** * Opent he administration panel in a browser if the option is enabled. * You can disable it using the admin.autoOpen configuration variable. * * Note: It only works in development envs. */ openAdmin(options: { isInitialized: boolean }): Promise<void>; /** * Load the admin panel server logic into the server code and initialize its configuration. */ loadAdmin(): Promise<void>; /** * Resolve every enabled plugin and load them into the application. */ loadPlugins(): Promise<void>; /** * Load every global policies in the policies container by * reading from the `strapi.dirs.dist.policies` directory. */ loadPolicies(): Promise<void>; /** * Load every APIs and their components (config, routes, controllers, services, * policies, middlewares, content-types) in the API container. */ loadAPIs(): Promise<void>; /** * Resolve every components in the user application and store them in `strapi.components` */ loadComponents(): Promise<void>; /** * Load every global and core middlewares in the middlewares container by * reading from the `strapi.dirs.dist.middlewares` and internal middlewares directory. */ loadMiddlewares(): Promise<void>; /** * Load the user application in the server by reading the `src/index.js` file. */ loadApp(): Promise<void>; /** * Add internal hooks to the hooks container. * Those hooks are meant for internal usage and might break in future releases. */ registerInternalHooks(): void; /** * Find a model (content-type, component) based on its unique identifier. */ getModel(uid: string): any; /** * Binds database queries for a specific model based on its unique identifier. */ query(uid: string): any; /** * Main Strapi container holding all the registries and providers (config, content-types, services, policies, etc...) */ container: any; /** * References to all the directories handled by Strapi */ dirs: StrapiDirectories; /** * Internal flag used to check if the application has been loaded */ isLoaded: boolean; /** * Fully reload the application */ reload(): void; /** * Holds a reference to the Koa application and the http server used by Strapi */ server: any; /** * Strapi util used to manage application files */ fs: any; /** * Event hub used to send and receive events from anywhere in the application */ eventHub: any; /** * Internal util used to log stats and messages on application Startup */ startupLogger: any; /** * Strapi logger used to send errors, warning or information messages */ log: any; /** * Used to manage cron within Strapi */ cron: any; /** * Telemetry util used to collect anonymous data on the application usage */ telemetry: any; /** * Strapi DB layer instance */ db: Database; /** * Core Store accessor */ store: any; /** * Entity Validator instance */ entityValidator: any; /** * Entity Service instance */ entityService: any; } export interface Lifecycles { REGISTER: 'register'; BOOTSTRAP: 'bootstrap'; DESTROY: 'destroy'; } export interface StrapiDirectories { static: { public: string; }; app: { root: string; src: string; api: string; components: string; extensions: string; policies: string; middlewares: string; config: string; }; dist: { root: string; src: string; api: string; components: string; extensions: string; policies: string; middlewares: string; config: string; }; }
packages/core/strapi/lib/types/core/strapi/index.d.ts
0
https://github.com/strapi/strapi/commit/78b83190707b5818d67e77bfd24c9e87c70291ef
[ 0.00018391605408396572, 0.0001682722504483536, 0.00016024436627049, 0.00016779682482592762, 0.00000512880342284916 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui';\n", "import { DashboardModel } from 'app/features/dashboard/state';\n", "\n", "import { SaveDashboardDrawer } from './SaveDashboardDrawer';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { reportInteraction } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 3 }
import React from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui'; import { DashboardModel } from 'app/features/dashboard/state'; import { SaveDashboardDrawer } from './SaveDashboardDrawer'; interface SaveDashboardButtonProps { dashboard: DashboardModel; onSaveSuccess?: () => void; size?: ComponentSize; } export const SaveDashboardButton: React.FC<SaveDashboardButtonProps> = ({ dashboard, onSaveSuccess, size }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, }); }} aria-label={selectors.pages.Dashboard.Settings.General.saveDashBoard} > Save dashboard </Button> ); }} </ModalsController> ); }; export const SaveDashboardAsButton: React.FC<SaveDashboardButtonProps & { variant?: ButtonVariant }> = ({ dashboard, onSaveSuccess, variant, size, }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, isCopy: true, }); }} variant={variant} aria-label={selectors.pages.Dashboard.Settings.General.saveAsDashBoard} > Save as </Button> ); }} </ModalsController> ); };
public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx
1
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.972520649433136, 0.14094118773937225, 0.00025683865533210337, 0.000824175716843456, 0.3395041525363922 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui';\n", "import { DashboardModel } from 'app/features/dashboard/state';\n", "\n", "import { SaveDashboardDrawer } from './SaveDashboardDrawer';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { reportInteraction } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 3 }
import { createAction } from '@reduxjs/toolkit'; import { BucketAggregation, BucketAggregationType, BucketAggregationWithField } from '../aggregations'; export const addBucketAggregation = createAction<BucketAggregation['id']>('@bucketAggs/add'); export const removeBucketAggregation = createAction<BucketAggregation['id']>('@bucketAggs/remove'); export const changeBucketAggregationType = createAction<{ id: BucketAggregation['id']; newType: BucketAggregationType; }>('@bucketAggs/change_type'); export const changeBucketAggregationField = createAction<{ id: BucketAggregation['id']; newField: BucketAggregationWithField['field']; }>('@bucketAggs/change_field'); export const changeBucketAggregationSetting = createAction<{ bucketAgg: BucketAggregation; settingName: string; newValue: any; }>('@bucketAggs/change_setting');
public/app/plugins/datasource/elasticsearch/components/QueryEditor/BucketAggregationsEditor/state/actions.ts
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017525911971461028, 0.00017413421301171184, 0.00017300932086072862, 0.00017413421301171184, 0.0000011248994269408286 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui';\n", "import { DashboardModel } from 'app/features/dashboard/state';\n", "\n", "import { SaveDashboardDrawer } from './SaveDashboardDrawer';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { reportInteraction } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 3 }
import { config } from '@grafana/runtime'; import { AlertTab } from './AlertTab'; import { PanelAlertTabContent } from './unified/PanelAlertTabContent'; // route between unified and "old" alerting pages based on feature flag export default config.unifiedAlertingEnabled ? PanelAlertTabContent : AlertTab;
public/app/features/alerting/AlertTabIndex.tsx
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00016855806461535394, 0.00016855806461535394, 0.00016855806461535394, 0.00016855806461535394, 0 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui';\n", "import { DashboardModel } from 'app/features/dashboard/state';\n", "\n", "import { SaveDashboardDrawer } from './SaveDashboardDrawer';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { reportInteraction } from '@grafana/runtime';\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 3 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2,13.5v2a1,1,0,0,0,1,1H13a3,3,0,0,0,6,0h2a1,1,0,0,0,1-1v-8a3,3,0,0,0-3-3H9a3,3,0,0,0-3,3v7H4v-1a1,1,0,0,0-2,0Zm13,3a1,1,0,1,1,1,1A1,1,0,0,1,15,16.5Zm-7-6H20v4H18.22a3,3,0,0,0-4.44,0H8Zm0-3a1,1,0,0,1,1-1H19a1,1,0,0,1,1,1v1H8Z"/></svg>
public/img/icons/unicons/luggage-cart.svg
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.0001741877058520913, 0.0001741877058520913, 0.0001741877058520913, 0.0001741877058520913, 0 ]
{ "id": 1, "code_window": [ " <Button\n", " size={size}\n", " onClick={() => {\n", " showModal(SaveDashboardDrawer, {\n", " dashboard,\n", " onSaveSuccess,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " reportInteraction('grafana_dashboard_save_as_clicked');\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 51 }
import { useEffect } from 'react'; import useAsyncFn from 'react-use/lib/useAsyncFn'; import { locationUtil } from '@grafana/data'; import { locationService, reportInteraction } from '@grafana/runtime'; import appEvents from 'app/core/app_events'; import { useAppNotification } from 'app/core/copy/appNotification'; import { contextSrv } from 'app/core/core'; import { updateDashboardName } from 'app/core/reducers/navBarTree'; import { DashboardModel } from 'app/features/dashboard/state'; import { saveDashboard as saveDashboardApiCall } from 'app/features/manage-dashboards/state/actions'; import { useDispatch } from 'app/types'; import { DashboardSavedEvent } from 'app/types/events'; import { SaveDashboardOptions } from './types'; const saveDashboard = async (saveModel: any, options: SaveDashboardOptions, dashboard: DashboardModel) => { let folderUid = options.folderUid; if (folderUid === undefined) { folderUid = dashboard.meta.folderUid ?? saveModel.folderUid; } const result = await saveDashboardApiCall({ ...options, folderUid, dashboard: saveModel }); // fetch updated access control permissions await contextSrv.fetchUserPermissions(); return result; }; export const useDashboardSave = (dashboard: DashboardModel) => { const [state, onDashboardSave] = useAsyncFn( async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) => await saveDashboard(clone, options, dashboard), [] ); const dispatch = useDispatch(); const notifyApp = useAppNotification(); useEffect(() => { if (state.error && !state.loading) { notifyApp.error(state.error.message ?? 'Error saving dashboard'); } if (state.value) { dashboard.version = state.value.version; dashboard.clearUnsavedChanges(); // important that these happen before location redirect below appEvents.publish(new DashboardSavedEvent()); notifyApp.success('Dashboard saved'); reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, { name: dashboard.title, url: state.value.url, }); const currentPath = locationService.getLocation().pathname; const newUrl = locationUtil.stripBaseFromUrl(state.value.url); if (newUrl !== currentPath) { setTimeout(() => locationService.replace(newUrl)); } if (dashboard.meta.isStarred) { dispatch( updateDashboardName({ id: dashboard.uid, title: dashboard.title, url: newUrl, }) ); } } }, [dashboard, state, notifyApp, dispatch]); return { state, onDashboardSave }; };
public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx
1
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.01258167251944542, 0.003648788435384631, 0.0001751500240061432, 0.002206900157034397, 0.003930411767214537 ]
{ "id": 1, "code_window": [ " <Button\n", " size={size}\n", " onClick={() => {\n", " showModal(SaveDashboardDrawer, {\n", " dashboard,\n", " onSaveSuccess,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " reportInteraction('grafana_dashboard_save_as_clicked');\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 51 }
package login import ( "context" "github.com/grafana/grafana/pkg/services/user" ) type AuthInfoService interface { LookupAndUpdate(ctx context.Context, query *GetUserByAuthInfoQuery) (*user.User, error) GetAuthInfo(ctx context.Context, query *GetAuthInfoQuery) error GetUserLabels(ctx context.Context, query GetUserLabelsQuery) (map[int64]string, error) GetExternalUserInfoByLogin(ctx context.Context, query *GetExternalUserInfoByLoginQuery) error SetAuthInfo(ctx context.Context, cmd *SetAuthInfoCommand) error UpdateAuthInfo(ctx context.Context, cmd *UpdateAuthInfoCommand) error DeleteUserAuthInfo(ctx context.Context, userID int64) error } const ( SAMLAuthModule = "auth.saml" LDAPAuthModule = "ldap" AuthProxyAuthModule = "authproxy" JWTModule = "jwt" RenderModule = "render" ) func GetAuthProviderLabel(authModule string) string { switch authModule { case "oauth_github": return "GitHub" case "oauth_google": return "Google" case "oauth_azuread": return "AzureAD" case "oauth_gitlab": return "GitLab" case "oauth_okta": return "Okta" case "oauth_grafana_com", "oauth_grafananet": return "grafana.com" case SAMLAuthModule: return "SAML" case LDAPAuthModule, "": // FIXME: verify this situation doesn't exist anymore return "LDAP" case JWTModule: return "JWT" case AuthProxyAuthModule: return "Auth Proxy" default: return "OAuth" // FIXME: replace with "Unknown" and handle generic oauth as a case } }
pkg/services/login/authinfo.go
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017522017878945917, 0.00017070827016141266, 0.00016656110528856516, 0.0001705501927062869, 0.000003219254722353071 ]
{ "id": 1, "code_window": [ " <Button\n", " size={size}\n", " onClick={() => {\n", " showModal(SaveDashboardDrawer, {\n", " dashboard,\n", " onSaveSuccess,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " reportInteraction('grafana_dashboard_save_as_clicked');\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 51 }
package accesscontrol_test import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/datasources" ) func TestResolvers_AttributeScope(t *testing.T) { // Calls allow us to see how many times the fakeDataSourceResolution has been called calls := 0 fakeDataSourceResolver := accesscontrol.ScopeAttributeResolverFunc(func(ctx context.Context, orgID int64, initialScope string) ([]string, error) { calls++ if initialScope == "datasources:name:testds" { return []string{accesscontrol.Scope("datasources", "id", "1")}, nil } else if initialScope == "datasources:name:testds2" { return []string{accesscontrol.Scope("datasources", "id", "2")}, nil } else if initialScope == "datasources:name:test:ds4" { return []string{accesscontrol.Scope("datasources", "id", "4")}, nil } else if initialScope == "datasources:name:testds5*" { return []string{accesscontrol.Scope("datasources", "id", "5")}, nil } else { return nil, datasources.ErrDataSourceNotFound } }) tests := []struct { name string orgID int64 evaluator accesscontrol.Evaluator wantEvaluator accesscontrol.Evaluator wantCalls int wantErr error }{ { name: "should work with scope less permissions", evaluator: accesscontrol.EvalPermission("datasources:read"), wantEvaluator: accesscontrol.EvalPermission("datasources:read"), wantCalls: 0, }, { name: "should handle an error", orgID: 1, evaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "testds3")), wantErr: datasources.ErrDataSourceNotFound, wantCalls: 1, }, { name: "should resolve a scope", orgID: 1, evaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "testds")), wantEvaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "id", "1")), wantCalls: 1, }, { name: "should resolve nested scopes with cache", orgID: 1, evaluator: accesscontrol.EvalAll( accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "testds")), accesscontrol.EvalAny( accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "testds")), accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "testds2")), ), ), wantEvaluator: accesscontrol.EvalAll( accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "id", "1")), accesscontrol.EvalAny( accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "id", "1")), accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "id", "2")), ), ), wantCalls: 2, }, { name: "should resolve name with colon", orgID: 1, evaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "test:ds4")), wantEvaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "id", "4")), wantCalls: 1, }, { name: "should resolve names with '*'", orgID: 1, evaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "name", "testds5*")), wantEvaluator: accesscontrol.EvalPermission("datasources:read", accesscontrol.Scope("datasources", "id", "5")), wantCalls: 1, }, { name: "should return error if no resolver is found for scope", orgID: 1, evaluator: accesscontrol.EvalPermission("dashboards:read", "dashboards:id:1"), wantEvaluator: nil, wantCalls: 0, wantErr: accesscontrol.ErrResolverNotFound, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { resolvers := accesscontrol.NewResolvers(log.NewNopLogger()) // Reset calls counter calls = 0 // Register a resolution method resolvers.AddScopeAttributeResolver("datasources:name:", fakeDataSourceResolver) // Test mutate := resolvers.GetScopeAttributeMutator(tt.orgID) resolvedEvaluator, err := tt.evaluator.MutateScopes(context.Background(), mutate) if tt.wantErr != nil { assert.ErrorAs(t, err, &tt.wantErr, "expected an error during the resolution of the scope") return } assert.NoError(t, err) assert.EqualValues(t, tt.wantEvaluator, resolvedEvaluator, "permission did not match expected resolution") assert.Equal(t, tt.wantCalls, calls, "cache has not been used") }) } }
pkg/services/accesscontrol/resolvers_test.go
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017730485706124455, 0.0001744947221595794, 0.00016578486247453839, 0.00017568777548149228, 0.000003140633907605661 ]
{ "id": 1, "code_window": [ " <Button\n", " size={size}\n", " onClick={() => {\n", " showModal(SaveDashboardDrawer, {\n", " dashboard,\n", " onSaveSuccess,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " reportInteraction('grafana_dashboard_save_as_clicked');\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx", "type": "add", "edit_start_line_idx": 51 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M11.29,17.3,10,18.59V7A1,1,0,0,0,8,7v11.6L6.71,17.3a1,1,0,0,0-1.42,0,1,1,0,0,0,0,1.41l3,3a1,1,0,0,0,1.42,0l3-3a1,1,0,0,0,0-1.41A1,1,0,0,0,11.29,17.3ZM22,3a1,1,0,0,0-1-1H3A1,1,0,0,0,2,3V9a1,1,0,0,0,1,1H5A1,1,0,0,0,5,8H4V4H20V8H13a1,1,0,0,0,0,2h1v5a1,1,0,0,0,1,1h6a1,1,0,0,0,1-1V9h0ZM20,14H16V10h4Z"/></svg>
public/img/icons/unicons/bring-front.svg
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.0001713196252239868, 0.0001713196252239868, 0.0001713196252239868, 0.0001713196252239868, 0 ]
{ "id": 2, "code_window": [ " };\n", " }, [dashboard, previous.value, options, isNew]);\n", "\n", " const [showDiff, setShowDiff] = useState(false);\n", " const { state, onDashboardSave } = useDashboardSave(dashboard);\n", " const onSuccess = onSaveSuccess\n", " ? () => {\n", " onDismiss();\n", " onSaveSuccess();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { state, onDashboardSave } = useDashboardSave(dashboard, isCopy);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardDrawer.tsx", "type": "replace", "edit_start_line_idx": 63 }
import React from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui'; import { DashboardModel } from 'app/features/dashboard/state'; import { SaveDashboardDrawer } from './SaveDashboardDrawer'; interface SaveDashboardButtonProps { dashboard: DashboardModel; onSaveSuccess?: () => void; size?: ComponentSize; } export const SaveDashboardButton: React.FC<SaveDashboardButtonProps> = ({ dashboard, onSaveSuccess, size }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, }); }} aria-label={selectors.pages.Dashboard.Settings.General.saveDashBoard} > Save dashboard </Button> ); }} </ModalsController> ); }; export const SaveDashboardAsButton: React.FC<SaveDashboardButtonProps & { variant?: ButtonVariant }> = ({ dashboard, onSaveSuccess, variant, size, }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, isCopy: true, }); }} variant={variant} aria-label={selectors.pages.Dashboard.Settings.General.saveAsDashBoard} > Save as </Button> ); }} </ModalsController> ); };
public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx
1
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.9937961101531982, 0.4191914200782776, 0.00017168150225188583, 0.05455171689391136, 0.4674828052520752 ]
{ "id": 2, "code_window": [ " };\n", " }, [dashboard, previous.value, options, isNew]);\n", "\n", " const [showDiff, setShowDiff] = useState(false);\n", " const { state, onDashboardSave } = useDashboardSave(dashboard);\n", " const onSuccess = onSaveSuccess\n", " ? () => {\n", " onDismiss();\n", " onSaveSuccess();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { state, onDashboardSave } = useDashboardSave(dashboard, isCopy);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardDrawer.tsx", "type": "replace", "edit_start_line_idx": 63 }
--- aliases: [] hide_menu: true title: Release notes for Grafana 9.1.7 --- <!-- Auto generated by update changelog github action --> # Release notes for Grafana 9.1.7 ### Features and enhancements - **Chore:** Upgrade Go version to 1.19.1 (backport). [#55733](https://github.com/grafana/grafana/pull/55733), [@sakjur](https://github.com/sakjur) - **CloudWatch:** Add missing AWS/Prometheus metrics. [#54990](https://github.com/grafana/grafana/pull/54990), [@jangaraj](https://github.com/jangaraj) - **Explore:** Add feature tracking events. [#54514](https://github.com/grafana/grafana/pull/54514), [@L-M-K-B](https://github.com/L-M-K-B) - **Graphite:** Add error information to graphite queries tracing. [#55249](https://github.com/grafana/grafana/pull/55249), [@jesusvazquez](https://github.com/jesusvazquez) - **Prometheus:** Restore FromAlert header. [#55255](https://github.com/grafana/grafana/pull/55255), [@kylebrandt](https://github.com/kylebrandt) - **SAML:** Account for all orgs in org_mapping (#3855). (Enterprise) - **Search:** Add search index configuration options. [#55525](https://github.com/grafana/grafana/pull/55525), [@ArturWierzbicki](https://github.com/ArturWierzbicki) - **Thresholds:** Add option for dashed line style. [#55875](https://github.com/grafana/grafana/pull/55875), [@leeoniya](https://github.com/leeoniya) ### Bug fixes - **Alerting:** Fix default query's data source when no default datasource specified. [#55435](https://github.com/grafana/grafana/pull/55435), [@konrad147](https://github.com/konrad147) - **Alerting:** Fix mathexp.NoData cannot be reduced. [#55347](https://github.com/grafana/grafana/pull/55347), [@grobinson-grafana](https://github.com/grobinson-grafana) - **Alerting:** Skip unsupported file types on provisioning. [#55573](https://github.com/grafana/grafana/pull/55573), [@JohnnyQQQQ](https://github.com/JohnnyQQQQ) - **AzureMonitor:** Ensure resourceURI template variable is migrated. [#56095](https://github.com/grafana/grafana/pull/56095), [@aangelisc](https://github.com/aangelisc) - **Dashboard:** Fix plugin dashboard save as button. [#55197](https://github.com/grafana/grafana/pull/55197), [@lpskdl](https://github.com/lpskdl) - **Docs:** Fix decimals: auto docs for panel edit. [#55477](https://github.com/grafana/grafana/pull/55477), [@joshhunt](https://github.com/joshhunt) - **Fix:** RBAC handle `error no resolver` found. [#55676](https://github.com/grafana/grafana/pull/55676), [@gamab](https://github.com/gamab) - **Fix:** RBAC handle `error no resolver` found. (Enterprise) - **LibraryPanelSearch:** Refactor and fix hyphen issue. [#55314](https://github.com/grafana/grafana/pull/55314), [@kaydelaney](https://github.com/kaydelaney) - **Live:** Fix live streaming with `live-service-web-worker` feature flag enabled. [#55528](https://github.com/grafana/grafana/pull/55528), [@ArturWierzbicki](https://github.com/ArturWierzbicki) - **QueryField:** Fix wrong cursor position on autocomplete. [#55576](https://github.com/grafana/grafana/pull/55576), [@svennergr](https://github.com/svennergr)
docs/sources/release-notes/release-notes-9-1-7.md
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017464588745497167, 0.00016997402417473495, 0.00016428066010121256, 0.00017048479639925063, 0.0000043156564970558975 ]
{ "id": 2, "code_window": [ " };\n", " }, [dashboard, previous.value, options, isNew]);\n", "\n", " const [showDiff, setShowDiff] = useState(false);\n", " const { state, onDashboardSave } = useDashboardSave(dashboard);\n", " const onSuccess = onSaveSuccess\n", " ? () => {\n", " onDismiss();\n", " onSaveSuccess();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { state, onDashboardSave } = useDashboardSave(dashboard, isCopy);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardDrawer.tsx", "type": "replace", "edit_start_line_idx": 63 }
// Copyright 2023 Grafana Labs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package grafanaplugin composableKinds: PanelCfg: { lineage: { seqs: [ { schemas: [ { PanelOptions: { // Comma-separated list of values used to filter alert results labels: string // Name of the alertmanager used as a source for alerts alertmanager: string // Expand all alert groups by default expandAll: bool } @cuetsy(kind="interface") }, ] }, ] } }
public/app/plugins/panel/alertGroups/panelcfg.cue
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.0001771171228028834, 0.0001732112723402679, 0.00017148077313322574, 0.00017212360398843884, 0.000002274789721923298 ]
{ "id": 2, "code_window": [ " };\n", " }, [dashboard, previous.value, options, isNew]);\n", "\n", " const [showDiff, setShowDiff] = useState(false);\n", " const { state, onDashboardSave } = useDashboardSave(dashboard);\n", " const onSuccess = onSaveSuccess\n", " ? () => {\n", " onDismiss();\n", " onSaveSuccess();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { state, onDashboardSave } = useDashboardSave(dashboard, isCopy);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/SaveDashboardDrawer.tsx", "type": "replace", "edit_start_line_idx": 63 }
import { SeriesVisibilityChangeMode } from '..'; export function mapMouseEventToMode(event: React.MouseEvent): SeriesVisibilityChangeMode { if (event.ctrlKey || event.metaKey || event.shiftKey) { return SeriesVisibilityChangeMode.AppendToSelection; } return SeriesVisibilityChangeMode.ToggleSelection; }
packages/grafana-ui/src/components/VizLegend/utils.ts
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017507806478533894, 0.00017507806478533894, 0.00017507806478533894, 0.00017507806478533894, 0 ]
{ "id": 3, "code_window": [ " return result;\n", "};\n", "\n", "export const useDashboardSave = (dashboard: DashboardModel) => {\n", " const [state, onDashboardSave] = useAsyncFn(\n", " async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) =>\n", " await saveDashboard(clone, options, dashboard),\n", " []\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const useDashboardSave = (dashboard: DashboardModel, isCopy = false) => {\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 28 }
import { useEffect } from 'react'; import useAsyncFn from 'react-use/lib/useAsyncFn'; import { locationUtil } from '@grafana/data'; import { locationService, reportInteraction } from '@grafana/runtime'; import appEvents from 'app/core/app_events'; import { useAppNotification } from 'app/core/copy/appNotification'; import { contextSrv } from 'app/core/core'; import { updateDashboardName } from 'app/core/reducers/navBarTree'; import { DashboardModel } from 'app/features/dashboard/state'; import { saveDashboard as saveDashboardApiCall } from 'app/features/manage-dashboards/state/actions'; import { useDispatch } from 'app/types'; import { DashboardSavedEvent } from 'app/types/events'; import { SaveDashboardOptions } from './types'; const saveDashboard = async (saveModel: any, options: SaveDashboardOptions, dashboard: DashboardModel) => { let folderUid = options.folderUid; if (folderUid === undefined) { folderUid = dashboard.meta.folderUid ?? saveModel.folderUid; } const result = await saveDashboardApiCall({ ...options, folderUid, dashboard: saveModel }); // fetch updated access control permissions await contextSrv.fetchUserPermissions(); return result; }; export const useDashboardSave = (dashboard: DashboardModel) => { const [state, onDashboardSave] = useAsyncFn( async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) => await saveDashboard(clone, options, dashboard), [] ); const dispatch = useDispatch(); const notifyApp = useAppNotification(); useEffect(() => { if (state.error && !state.loading) { notifyApp.error(state.error.message ?? 'Error saving dashboard'); } if (state.value) { dashboard.version = state.value.version; dashboard.clearUnsavedChanges(); // important that these happen before location redirect below appEvents.publish(new DashboardSavedEvent()); notifyApp.success('Dashboard saved'); reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, { name: dashboard.title, url: state.value.url, }); const currentPath = locationService.getLocation().pathname; const newUrl = locationUtil.stripBaseFromUrl(state.value.url); if (newUrl !== currentPath) { setTimeout(() => locationService.replace(newUrl)); } if (dashboard.meta.isStarred) { dispatch( updateDashboardName({ id: dashboard.uid, title: dashboard.title, url: newUrl, }) ); } } }, [dashboard, state, notifyApp, dispatch]); return { state, onDashboardSave }; };
public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx
1
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.9976332187652588, 0.7436957955360413, 0.0012146785156801343, 0.9917119741439819, 0.42747971415519714 ]
{ "id": 3, "code_window": [ " return result;\n", "};\n", "\n", "export const useDashboardSave = (dashboard: DashboardModel) => {\n", " const [state, onDashboardSave] = useAsyncFn(\n", " async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) =>\n", " await saveDashboard(clone, options, dashboard),\n", " []\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const useDashboardSave = (dashboard: DashboardModel, isCopy = false) => {\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 28 }
import { fireEvent, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { createLokiDatasource } from '../../mocks'; import { LokiQuery, LokiQueryType } from '../../types'; import { LokiQueryBuilderOptions } from './LokiQueryBuilderOptions'; describe('LokiQueryBuilderOptions', () => { it('Can change query type', async () => { const { props } = setup(); screen.getByTitle('Click to edit options').click(); expect(screen.getByLabelText('Range')).toBeChecked(); screen.getByLabelText('Instant').click(); expect(props.onChange).toHaveBeenCalledWith({ ...props.query, queryType: LokiQueryType.Instant, }); }); it('Can change legend format', async () => { const { props } = setup(); screen.getByTitle('Click to edit options').click(); const element = screen.getByLabelText('Legend'); await userEvent.type(element, 'asd'); fireEvent.keyDown(element, { key: 'Enter', code: 'Enter', charCode: 13 }); expect(props.onChange).toHaveBeenCalledWith({ ...props.query, legendFormat: 'asd', }); }); }); function setup(queryOverrides: Partial<LokiQuery> = {}) { const props = { query: { refId: 'A', expr: '', ...queryOverrides, }, onRunQuery: jest.fn(), onChange: jest.fn(), maxLines: 20, datasource: createLokiDatasource(), }; const { container } = render(<LokiQueryBuilderOptions {...props} />); return { container, props }; }
public/app/plugins/datasource/loki/querybuilder/components/LokiQueryBuilderOptions.test.tsx
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.0001761589664965868, 0.00017347683024127036, 0.00017110756016336381, 0.00017369026318192482, 0.0000018526461644796655 ]
{ "id": 3, "code_window": [ " return result;\n", "};\n", "\n", "export const useDashboardSave = (dashboard: DashboardModel) => {\n", " const [state, onDashboardSave] = useAsyncFn(\n", " async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) =>\n", " await saveDashboard(clone, options, dashboard),\n", " []\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const useDashboardSave = (dashboard: DashboardModel, isCopy = false) => {\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 28 }
{{>partial_header}} package {{packageName}} {{#operations}} import ( "github.com/go-macaron/binding" "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/models" apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" "github.com/grafana/grafana/pkg/services/ngalert/metrics" "github.com/grafana/grafana/pkg/middleware" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" ) type {{classname}} interface { {{#operation}} {{nickname}}(*contextmodel.ReqContext) response.Response{{/operation}} } {{#operations}}{{#operation}} func (f *{{classname}}Handler) {{nickname}}(ctx *contextmodel.ReqContext) response.Response { {{#hasPathParams}} // Parse Path Parameters{{/hasPathParams}}{{#pathParams}} {{paramName}}Param := web.Params(ctx.Req)[":{{baseName}}"]{{/pathParams}} {{#bodyParams}} // Parse Request Body conf := apimodels.{{dataType}}{} if err := web.Bind(ctx.Req, &conf); err != nil { return response.Error(http.StatusBadRequest, "bad request data", err) } {{/bodyParams}}return f.handle{{nickname}}(ctx{{#bodyParams}}, conf{{/bodyParams}}{{#pathParams}}, {{paramName}}Param{{/pathParams}}) } {{/operation}}{{/operations}} func (api *API) Register{{classname}}Endpoints(srv {{classname}}, m *metrics.API) { api.RouteRegister.Group("", func(group routing.RouteRegister){ {{#operations}}{{#operation}} group.{{httpMethod}}( toMacaronPath("{{{path}}}"), api.authorize(http.Method{{httpMethod}}, "{{{path}}}"), metrics.Instrument( http.Method{{httpMethod}}, "{{{path}}}", srv.{{nickname}}, m, ), ){{/operation}}{{/operations}} }, middleware.ReqSignedIn) }{{#operation}} {{/operation}}{{/operations}}
pkg/services/ngalert/api/tooling/swagger-codegen/templates/controller-api.mustache
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017406184633728117, 0.00017085410945583135, 0.00016666438023094088, 0.0001717211416689679, 0.000002767711066553602 ]
{ "id": 3, "code_window": [ " return result;\n", "};\n", "\n", "export const useDashboardSave = (dashboard: DashboardModel) => {\n", " const [state, onDashboardSave] = useAsyncFn(\n", " async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) =>\n", " await saveDashboard(clone, options, dashboard),\n", " []\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const useDashboardSave = (dashboard: DashboardModel, isCopy = false) => {\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 28 }
import React from 'react'; import { UseFormRegister } from 'react-hook-form'; import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; import { Checkbox, FieldSet, HorizontalGroup, LinkButton, VerticalGroup } from '@grafana/ui/src'; import { SharePublicDashboardAcknowledgmentInputs, SharePublicDashboardInputs } from './SharePublicDashboard'; type Acknowledge = { type: keyof SharePublicDashboardAcknowledgmentInputs; description: string; testId: string; info: { href: string; tooltip: string; }; }; const selectors = e2eSelectors.pages.ShareDashboardModal.PublicDashboard; const ACKNOWLEDGES: Acknowledge[] = [ { type: 'publicAcknowledgment', description: 'Your entire dashboard will be public', testId: selectors.WillBePublicCheckbox, info: { href: 'https://grafana.com/docs/grafana/latest/dashboards/dashboard-public/', tooltip: 'Learn more about public dashboards', }, }, { type: 'dataSourcesAcknowledgment', description: 'Publishing currently only works with a subset of datasources', testId: selectors.LimitedDSCheckbox, info: { href: 'https://grafana.com/docs/grafana/latest/datasources/', tooltip: 'Learn more about public datasources', }, }, { type: 'usageAcknowledgment', description: 'Making a dashboard public causes queries to run each time it is viewed, which may increase costs', testId: selectors.CostIncreaseCheckbox, info: { href: 'https://grafana.com/docs/grafana/latest/enterprise/query-caching/', tooltip: 'Learn more about query caching', }, }, ]; export const AcknowledgeCheckboxes = ({ disabled, register, }: { disabled: boolean; register: UseFormRegister<SharePublicDashboardInputs>; }) => ( <> <p>Before you click Save, please acknowledge the following information:</p> <FieldSet disabled={disabled}> <VerticalGroup spacing="md"> {ACKNOWLEDGES.map((acknowledge) => ( <HorizontalGroup key={acknowledge.type} spacing="none" align="center"> <Checkbox {...register(acknowledge.type)} label={acknowledge.description} data-testid={acknowledge.testId} /> <LinkButton variant="primary" href={acknowledge.info.href} target="_blank" fill="text" icon="info-circle" rel="noopener noreferrer" tooltip={acknowledge.info.tooltip} /> </HorizontalGroup> ))} </VerticalGroup> </FieldSet> </> );
public/app/features/dashboard/components/ShareModal/SharePublicDashboard/AcknowledgeCheckboxes.tsx
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.0012593247229233384, 0.0003342397103551775, 0.00017161783762276173, 0.0001909833517856896, 0.0003317225200589746 ]
{ "id": 4, "code_window": [ "\n", " // important that these happen before location redirect below\n", " appEvents.publish(new DashboardSavedEvent());\n", " notifyApp.success('Dashboard saved');\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", "\n", " const currentPath = locationService.getLocation().pathname;\n", " const newUrl = locationUtil.stripBaseFromUrl(state.value.url);\n", "\n", " if (newUrl !== currentPath) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isCopy) {\n", " reportInteraction('grafana_dashboard_copied', {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " } else {\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " }\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 48 }
import React from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui'; import { DashboardModel } from 'app/features/dashboard/state'; import { SaveDashboardDrawer } from './SaveDashboardDrawer'; interface SaveDashboardButtonProps { dashboard: DashboardModel; onSaveSuccess?: () => void; size?: ComponentSize; } export const SaveDashboardButton: React.FC<SaveDashboardButtonProps> = ({ dashboard, onSaveSuccess, size }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, }); }} aria-label={selectors.pages.Dashboard.Settings.General.saveDashBoard} > Save dashboard </Button> ); }} </ModalsController> ); }; export const SaveDashboardAsButton: React.FC<SaveDashboardButtonProps & { variant?: ButtonVariant }> = ({ dashboard, onSaveSuccess, variant, size, }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, isCopy: true, }); }} variant={variant} aria-label={selectors.pages.Dashboard.Settings.General.saveAsDashBoard} > Save as </Button> ); }} </ModalsController> ); };
public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx
1
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.002053892007097602, 0.0008481735712848604, 0.00017368468979839236, 0.00048026477452367544, 0.0007271445356309414 ]
{ "id": 4, "code_window": [ "\n", " // important that these happen before location redirect below\n", " appEvents.publish(new DashboardSavedEvent());\n", " notifyApp.success('Dashboard saved');\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", "\n", " const currentPath = locationService.getLocation().pathname;\n", " const newUrl = locationUtil.stripBaseFromUrl(state.value.url);\n", "\n", " if (newUrl !== currentPath) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isCopy) {\n", " reportInteraction('grafana_dashboard_copied', {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " } else {\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " }\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 48 }
package setting import ( "time" "gopkg.in/ini.v1" ) type DateFormats struct { FullDate string `json:"fullDate"` UseBrowserLocale bool `json:"useBrowserLocale"` Interval DateFormatIntervals `json:"interval"` DefaultTimezone string `json:"defaultTimezone"` DefaultWeekStart string `json:"defaultWeekStart"` } type DateFormatIntervals struct { Millisecond string `json:"millisecond"` Second string `json:"second"` Minute string `json:"minute"` Hour string `json:"hour"` Day string `json:"day"` Month string `json:"month"` Year string `json:"year"` } const localBrowser = "browser" func valueAsTimezone(section *ini.Section, keyName string) (string, error) { timezone := section.Key(keyName).MustString(localBrowser) if timezone == localBrowser { return localBrowser, nil } location, err := time.LoadLocation(timezone) if err != nil { return localBrowser, err } return location.String(), nil } func (cfg *Cfg) readDateFormats() { dateFormats := cfg.Raw.Section("date_formats") cfg.DateFormats.FullDate = valueAsString(dateFormats, "full_date", "YYYY-MM-DD HH:mm:ss") cfg.DateFormats.Interval.Millisecond = valueAsString(dateFormats, "interval_millisecond", "HH:mm:ss.SSS") cfg.DateFormats.Interval.Second = valueAsString(dateFormats, "interval_second", "HH:mm:ss") cfg.DateFormats.Interval.Minute = valueAsString(dateFormats, "interval_minute", "HH:mm") cfg.DateFormats.Interval.Hour = valueAsString(dateFormats, "interval_hour", "MM-DD HH:mm") cfg.DateFormats.Interval.Day = valueAsString(dateFormats, "interval_day", "YYYY-MM-DD") cfg.DateFormats.Interval.Month = valueAsString(dateFormats, "interval_month", "YYYY-MM") cfg.DateFormats.Interval.Year = "YYYY" cfg.DateFormats.UseBrowserLocale = dateFormats.Key("use_browser_locale").MustBool(false) timezone, err := valueAsTimezone(dateFormats, "default_timezone") if err != nil { cfg.Logger.Warn("Unknown timezone as default_timezone", "err", err) } cfg.DateFormats.DefaultTimezone = timezone cfg.DateFormats.DefaultWeekStart = valueAsString(dateFormats, "default_week_start", "browser") }
pkg/setting/date_formats.go
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.0010190065950155258, 0.0002937490935437381, 0.0001683393056737259, 0.00017349184781778604, 0.00029609425109811127 ]
{ "id": 4, "code_window": [ "\n", " // important that these happen before location redirect below\n", " appEvents.publish(new DashboardSavedEvent());\n", " notifyApp.success('Dashboard saved');\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", "\n", " const currentPath = locationService.getLocation().pathname;\n", " const newUrl = locationUtil.stripBaseFromUrl(state.value.url);\n", "\n", " if (newUrl !== currentPath) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isCopy) {\n", " reportInteraction('grafana_dashboard_copied', {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " } else {\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " }\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 48 }
package store import ( "context" "fmt" "sync" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/grafana/grafana/pkg/infra/filestorage" ac "github.com/grafana/grafana/pkg/services/accesscontrol" ) type nestedTree struct { rootsByOrgId map[int64][]storageRuntime lookup map[int64]map[string]storageRuntime orgInitMutex sync.Mutex initializeOrgStorages func(orgId int64) []storageRuntime } var ( _ storageTree = (*nestedTree)(nil) ) func asNameToFileStorageMap(storages []storageRuntime) map[string]storageRuntime { lookup := make(map[string]storageRuntime) for _, storage := range storages { isUnderContentRoot := storage.Meta().Config.UnderContentRoot prefix := storage.Meta().Config.Prefix if !isUnderContentRoot { lookup[prefix] = storage } else { lookup[fmt.Sprintf("%s/%s", RootContent, prefix)] = storage } } return lookup } func (t *nestedTree) init() { t.orgInitMutex.Lock() defer t.orgInitMutex.Unlock() t.lookup = make(map[int64]map[string]storageRuntime, len(t.rootsByOrgId)) for orgId, storages := range t.rootsByOrgId { t.lookup[orgId] = asNameToFileStorageMap(storages) } } func (t *nestedTree) assureOrgIsInitialized(orgId int64) { t.orgInitMutex.Lock() defer t.orgInitMutex.Unlock() if _, ok := t.rootsByOrgId[orgId]; !ok { orgStorages := t.initializeOrgStorages(orgId) t.rootsByOrgId[orgId] = orgStorages t.lookup[orgId] = asNameToFileStorageMap(orgStorages) } } func (t *nestedTree) getRoot(orgId int64, path string) (storageRuntime, string) { t.assureOrgIsInitialized(orgId) if path == "" { return nil, "" } rootKey, path := splitFirstSegment(path) root, ok := t.lookup[orgId][rootKey] if ok && root != nil { if root.Meta().Config.Prefix == RootContent && path != "" && path != "/" { mountedKey, nestedPath := splitFirstSegment(path) nestedLookupKey := rootKey + filestorage.Delimiter + mountedKey nestedRoot, nestedOk := t.lookup[orgId][nestedLookupKey] if nestedOk && nestedRoot != nil { return nestedRoot, filestorage.Delimiter + nestedPath } if orgId != ac.GlobalOrgID { globalRoot, globalOk := t.lookup[ac.GlobalOrgID][nestedLookupKey] if globalOk && globalRoot != nil { return globalRoot, filestorage.Delimiter + nestedPath } } } return root, filestorage.Delimiter + path } if orgId != ac.GlobalOrgID { globalRoot, ok := t.lookup[ac.GlobalOrgID][rootKey] if ok && globalRoot != nil { if globalRoot.Meta().Config.Prefix == RootContent && path != "" && path != "/" { mountedKey, nestedPath := splitFirstSegment(path) nestedLookupKey := rootKey + filestorage.Delimiter + mountedKey nestedRoot, nestedOk := t.lookup[orgId][nestedLookupKey] if nestedOk && nestedRoot != nil { return nestedRoot, filestorage.Delimiter + nestedPath } globalNestedRoot, globalOk := t.lookup[ac.GlobalOrgID][nestedLookupKey] if globalOk && globalNestedRoot != nil { return globalNestedRoot, filestorage.Delimiter + nestedPath } } return globalRoot, filestorage.Delimiter + path } } return nil, path // not found or not ready } func (t *nestedTree) GetFile(ctx context.Context, orgId int64, path string) (*filestorage.File, error) { if path == "" { return nil, nil // not found } root, path := t.getRoot(orgId, path) if root == nil { return nil, nil // not found (or not ready) } store := root.Store() if store == nil { return nil, fmt.Errorf("store not ready") } file, _, err := store.Get(ctx, path, nil) return file, err } func filterStoragesUnderContentRoot(storages []storageRuntime) []storageRuntime { out := make([]storageRuntime, 0) for _, s := range storages { if s.Meta().Config.UnderContentRoot { out = append(out, s) } } return out } func (t *nestedTree) getStorages(orgId int64) []storageRuntime { globalStorages := make([]storageRuntime, 0) globalStorages = append(globalStorages, t.rootsByOrgId[ac.GlobalOrgID]...) if orgId == ac.GlobalOrgID { return append(make([]storageRuntime, 0), globalStorages...) } orgPrefixes := make(map[string]bool) storages := make([]storageRuntime, 0) for _, s := range t.rootsByOrgId[orgId] { storages = append(storages, s) orgPrefixes[s.Meta().Config.Prefix] = true } for _, s := range globalStorages { // prefer org-specific storage over global with the same prefix if ok := orgPrefixes[s.Meta().Config.Prefix]; !ok { storages = append(storages, s) } } return storages } func (t *nestedTree) ListFolder(ctx context.Context, orgId int64, path string, accessFilter filestorage.PathFilter) (*StorageListFrame, error) { if path == "" || path == "/" { t.assureOrgIsInitialized(orgId) idx := 0 storages := t.getStorages(orgId) count := len(storages) grafanaStorageLogger.Info("Listing root folder", "path", path, "storageCount", len(storages)) names := data.NewFieldFromFieldType(data.FieldTypeString, count) title := data.NewFieldFromFieldType(data.FieldTypeString, count) descr := data.NewFieldFromFieldType(data.FieldTypeString, count) mtype := data.NewFieldFromFieldType(data.FieldTypeString, count) title.Name = titleListFrameField names.Name = nameListFrameField descr.Name = descriptionListFrameField mtype.Name = mediaTypeListFrameField for _, f := range storages { meta := f.Meta() names.Set(idx, meta.Config.Prefix) title.Set(idx, meta.Config.Name) descr.Set(idx, meta.Config.Description) mtype.Set(idx, "directory") idx++ } frame := data.NewFrame("", names, title, descr, mtype) frame.SetMeta(&data.FrameMeta{ Type: data.FrameTypeDirectoryListing, }) return &StorageListFrame{frame}, nil } root, path := t.getRoot(orgId, path) if root == nil { return nil, nil // not found (or not ready) } var storages []storageRuntime if root.Meta().Config.Prefix == RootContent && (path == "" || path == "/") { storages = filterStoragesUnderContentRoot(t.getStorages(orgId)) } grafanaStorageLogger.Info("Listing folder", "path", path, "storageCount", len(storages), "root", root.Meta().Config.Prefix) store := root.Store() if store == nil { return nil, fmt.Errorf("store not ready") } pathFilter := accessFilter if root.Meta().Config.Prefix == RootContent && len(storages) > 0 { // create a PathFilter that will filter out folders that are "shadowed" by the mounted storages pathFilter = filestorage.NewAndPathFilter( accessFilter, t.createPathFilterForContentRoot(storages), ) } listResponse, err := store.List(ctx, path, nil, &filestorage.ListOptions{ Recursive: false, WithFolders: true, WithFiles: true, Filter: pathFilter, }) if err != nil { return nil, err } count := len(listResponse.Files) + len(storages) names := data.NewFieldFromFieldType(data.FieldTypeString, count) mtype := data.NewFieldFromFieldType(data.FieldTypeString, count) fsize := data.NewFieldFromFieldType(data.FieldTypeInt64, count) names.Name = nameListFrameField mtype.Name = mediaTypeListFrameField fsize.Name = sizeListFrameField fsize.Config = &data.FieldConfig{ Unit: "bytes", } idx := 0 for _, s := range storages { names.Set(idx, s.Meta().Config.Prefix) mtype.Set(idx, filestorage.DirectoryMimeType) fsize.Set(idx, int64(0)) idx++ } for _, f := range listResponse.Files { names.Set(idx, f.Name) mtype.Set(idx, f.MimeType) fsize.Set(idx, f.Size) idx++ } frame := data.NewFrame("", names, mtype, fsize) frame.SetMeta(&data.FrameMeta{ Type: data.FrameTypeDirectoryListing, Custom: map[string]interface{}{ "HasMore": listResponse.HasMore, }, }) return &StorageListFrame{frame}, nil } func (t *nestedTree) createPathFilterForContentRoot(storages []storageRuntime) filestorage.PathFilter { disallowedPrefixes := make([]string, 0) disallowedPaths := make([]string, 0) for _, s := range storages { path := filestorage.Delimiter + s.Meta().Config.Prefix disallowedPaths = append(disallowedPaths, path) disallowedPrefixes = append(disallowedPrefixes, path+filestorage.Delimiter) } grafanaStorageLogger.Info("Created a path filter for the content root", "disallowedPrefixes", disallowedPrefixes, "disallowedPaths", disallowedPaths) return filestorage.NewPathFilter(nil, nil, disallowedPrefixes, disallowedPaths) }
pkg/services/store/tree.go
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017815710452850908, 0.00017343090439680964, 0.0001622228155611083, 0.0001749553921399638, 0.000004128017280891072 ]
{ "id": 4, "code_window": [ "\n", " // important that these happen before location redirect below\n", " appEvents.publish(new DashboardSavedEvent());\n", " notifyApp.success('Dashboard saved');\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", "\n", " const currentPath = locationService.getLocation().pathname;\n", " const newUrl = locationUtil.stripBaseFromUrl(state.value.url);\n", "\n", " if (newUrl !== currentPath) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isCopy) {\n", " reportInteraction('grafana_dashboard_copied', {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " } else {\n", " reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {\n", " name: dashboard.title,\n", " url: state.value.url,\n", " });\n", " }\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 48 }
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { dateTime } from '@grafana/data'; import { AlertRule, AlertRuleDTO, AlertRulesState, NotificationChannelOption, NotificationChannelState, NotifierDTO, } from 'app/types'; import unifiedAlertingReducer from '../unified/state/reducers'; import alertDef from './alertDef'; export const initialState: AlertRulesState = { items: [], searchQuery: '', isLoading: false, }; export const initialChannelState: NotificationChannelState = { notificationChannelTypes: [], notificationChannel: {}, notifiers: [], }; function convertToAlertRule(dto: AlertRuleDTO, state: string): AlertRule { const stateModel = alertDef.getStateDisplayModel(state); const rule: AlertRule = { ...dto, stateText: stateModel.text, stateIcon: stateModel.iconClass, stateClass: stateModel.stateClass, stateAge: dateTime(dto.newStateDate).fromNow(true), }; if (rule.state !== 'paused') { if (rule.executionError) { rule.info = 'Execution Error: ' + rule.executionError; } if (rule.evalData && rule.evalData.noData) { rule.info = 'Query returned no data'; } } return rule; } const alertRulesSlice = createSlice({ name: 'alertRules', initialState, reducers: { loadAlertRules: (state) => { return { ...state, isLoading: true }; }, loadedAlertRules: (state, action: PayloadAction<AlertRuleDTO[]>): AlertRulesState => { const alertRules: AlertRuleDTO[] = action.payload; const alertRulesViewModel: AlertRule[] = alertRules.map((rule) => { return convertToAlertRule(rule, rule.state); }); return { ...state, items: alertRulesViewModel, isLoading: false }; }, setSearchQuery: (state, action: PayloadAction<string>): AlertRulesState => { return { ...state, searchQuery: action.payload }; }, }, }); const notificationChannelSlice = createSlice({ name: 'notificationChannel', initialState: initialChannelState, reducers: { setNotificationChannels: (state, action: PayloadAction<NotifierDTO[]>): NotificationChannelState => { return { ...state, notificationChannelTypes: transformNotifiers(action.payload), notifiers: action.payload, }; }, notificationChannelLoaded: (state, action: PayloadAction<any>): NotificationChannelState => { const notificationChannel = action.payload; const selectedType: NotifierDTO = state.notifiers.find((t) => t.type === notificationChannel.type)!; const secureChannelOptions = selectedType.options.filter((o: NotificationChannelOption) => o.secure); /* If any secure field is in plain text we need to migrate it to use secure field instead. */ if ( secureChannelOptions.length > 0 && secureChannelOptions.some((o: NotificationChannelOption) => { return notificationChannel.settings[o.propertyName] !== ''; }) ) { return migrateSecureFields(state, action.payload, secureChannelOptions); } return { ...state, notificationChannel: notificationChannel }; }, resetSecureField: (state, action: PayloadAction<string>): NotificationChannelState => { return { ...state, notificationChannel: { ...state.notificationChannel, secureFields: { ...state.notificationChannel.secureFields, [action.payload]: false }, }, }; }, }, }); export const { loadAlertRules, loadedAlertRules, setSearchQuery } = alertRulesSlice.actions; export const { setNotificationChannels, notificationChannelLoaded, resetSecureField } = notificationChannelSlice.actions; export const alertRulesReducer = alertRulesSlice.reducer; export const notificationChannelReducer = notificationChannelSlice.reducer; export default { alertRules: alertRulesReducer, notificationChannel: notificationChannelReducer, unifiedAlerting: unifiedAlertingReducer, }; function migrateSecureFields( state: NotificationChannelState, notificationChannel: any, secureChannelOptions: NotificationChannelOption[] ) { const cleanedSettings: { [key: string]: string } = {}; const secureSettings: { [key: string]: string } = {}; secureChannelOptions.forEach((option) => { secureSettings[option.propertyName] = notificationChannel.settings[option.propertyName]; cleanedSettings[option.propertyName] = ''; }); return { ...state, notificationChannel: { ...notificationChannel, settings: { ...notificationChannel.settings, ...cleanedSettings }, secureSettings: { ...secureSettings }, }, }; } function transformNotifiers(notifiers: NotifierDTO[]) { return notifiers .map((option: NotifierDTO) => { return { value: option.type, label: option.name, ...option, typeName: option.type, }; }) .sort((o1, o2) => { if (o1.name > o2.name) { return 1; } return -1; }); }
public/app/features/alerting/state/reducers.ts
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017573182412888855, 0.00017212679085787386, 0.00016551651060581207, 0.00017231242964044213, 0.0000027230976229475345 ]
{ "id": 5, "code_window": [ " })\n", " );\n", " }\n", " }\n", " }, [dashboard, state, notifyApp, dispatch]);\n", "\n", " return { state, onDashboardSave };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, [dashboard, isCopy, state, notifyApp, dispatch]);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 69 }
import React from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { Button, ButtonVariant, ComponentSize, ModalsController } from '@grafana/ui'; import { DashboardModel } from 'app/features/dashboard/state'; import { SaveDashboardDrawer } from './SaveDashboardDrawer'; interface SaveDashboardButtonProps { dashboard: DashboardModel; onSaveSuccess?: () => void; size?: ComponentSize; } export const SaveDashboardButton: React.FC<SaveDashboardButtonProps> = ({ dashboard, onSaveSuccess, size }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, }); }} aria-label={selectors.pages.Dashboard.Settings.General.saveDashBoard} > Save dashboard </Button> ); }} </ModalsController> ); }; export const SaveDashboardAsButton: React.FC<SaveDashboardButtonProps & { variant?: ButtonVariant }> = ({ dashboard, onSaveSuccess, variant, size, }) => { return ( <ModalsController> {({ showModal, hideModal }) => { return ( <Button size={size} onClick={() => { showModal(SaveDashboardDrawer, { dashboard, onSaveSuccess, onDismiss: hideModal, isCopy: true, }); }} variant={variant} aria-label={selectors.pages.Dashboard.Settings.General.saveAsDashBoard} > Save as </Button> ); }} </ModalsController> ); };
public/app/features/dashboard/components/SaveDashboard/SaveDashboardButton.tsx
1
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.004164885263890028, 0.001614834414795041, 0.00016813444381114095, 0.0012188786640763283, 0.0013989651342853904 ]
{ "id": 5, "code_window": [ " })\n", " );\n", " }\n", " }\n", " }, [dashboard, state, notifyApp, dispatch]);\n", "\n", " return { state, onDashboardSave };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, [dashboard, isCopy, state, notifyApp, dispatch]);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 69 }
import { Registry } from '@grafana/data'; import { PromVisualQueryOperationCategory } from '../types'; import { QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDef, VisualQueryModeller } from './types'; export interface VisualQueryBinary<T> { operator: string; vectorMatchesType?: 'on' | 'ignoring'; vectorMatches?: string; query: T; } export interface PromLokiVisualQuery { metric?: string; labels: QueryBuilderLabelFilter[]; operations: QueryBuilderOperation[]; binaryQueries?: Array<VisualQueryBinary<PromLokiVisualQuery>>; } export abstract class LokiAndPromQueryModellerBase implements VisualQueryModeller { protected operationsRegistry: Registry<QueryBuilderOperationDef>; private categories: string[] = []; constructor(getOperations: () => QueryBuilderOperationDef[]) { this.operationsRegistry = new Registry<QueryBuilderOperationDef>(getOperations); } protected setOperationCategories(categories: string[]) { this.categories = categories; } getOperationsForCategory(category: string) { return this.operationsRegistry.list().filter((op) => op.category === category && !op.hideFromList); } getAlternativeOperations(key: string) { return this.operationsRegistry.list().filter((op) => op.alternativesKey && op.alternativesKey === key); } getCategories() { return this.categories; } getOperationDef(id: string): QueryBuilderOperationDef | undefined { return this.operationsRegistry.getIfExists(id); } renderOperations(queryString: string, operations: QueryBuilderOperation[]) { for (const operation of operations) { const def = this.operationsRegistry.getIfExists(operation.id); if (!def) { throw new Error(`Could not find operation ${operation.id} in the registry`); } queryString = def.renderer(operation, def, queryString); } return queryString; } renderBinaryQueries(queryString: string, binaryQueries?: Array<VisualQueryBinary<PromLokiVisualQuery>>) { if (binaryQueries) { for (const binQuery of binaryQueries) { queryString = `${this.renderBinaryQuery(queryString, binQuery)}`; } } return queryString; } private renderBinaryQuery(leftOperand: string, binaryQuery: VisualQueryBinary<PromLokiVisualQuery>) { let result = leftOperand + ` ${binaryQuery.operator} `; if (binaryQuery.vectorMatches) { result += `${binaryQuery.vectorMatchesType}(${binaryQuery.vectorMatches}) `; } return result + this.renderQuery(binaryQuery.query, true); } renderLabels(labels: QueryBuilderLabelFilter[]) { if (labels.length === 0) { return ''; } let expr = '{'; for (const filter of labels) { if (expr !== '{') { expr += ', '; } expr += `${filter.label}${filter.op}"${filter.value}"`; } return expr + `}`; } renderQuery(query: PromLokiVisualQuery, nested?: boolean) { let queryString = `${query.metric ?? ''}${this.renderLabels(query.labels)}`; queryString = this.renderOperations(queryString, query.operations); if (!nested && this.hasBinaryOp(query) && Boolean(query.binaryQueries?.length)) { queryString = `(${queryString})`; } queryString = this.renderBinaryQueries(queryString, query.binaryQueries); if (nested && (this.hasBinaryOp(query) || Boolean(query.binaryQueries?.length))) { queryString = `(${queryString})`; } return queryString; } hasBinaryOp(query: PromLokiVisualQuery): boolean { return ( query.operations.find((op) => { const def = this.getOperationDef(op.id); return def?.category === PromVisualQueryOperationCategory.BinaryOps; }) !== undefined ); } }
public/app/plugins/datasource/prometheus/querybuilder/shared/LokiAndPromQueryModellerBase.ts
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00024300662335008383, 0.0001758852886268869, 0.000167479069205001, 0.00017046756693162024, 0.00001947560849657748 ]
{ "id": 5, "code_window": [ " })\n", " );\n", " }\n", " }\n", " }, [dashboard, state, notifyApp, dispatch]);\n", "\n", " return { state, onDashboardSave };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, [dashboard, isCopy, state, notifyApp, dispatch]);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 69 }
import resolve from '@rollup/plugin-node-resolve'; import path from 'path'; import dts from 'rollup-plugin-dts'; import esbuild from 'rollup-plugin-esbuild'; import { externals } from 'rollup-plugin-node-externals'; const pkg = require('./package.json'); export default [ { input: 'src/index.ts', plugins: [externals({ deps: true, packagePath: './package.json' }), resolve(), esbuild()], output: [ { format: 'cjs', sourcemap: true, dir: path.dirname(pkg.publishConfig.main), }, { format: 'esm', sourcemap: true, dir: path.dirname(pkg.publishConfig.module), preserveModules: true, // @ts-expect-error (TS cannot assure that `process.env.PROJECT_CWD` is a string) preserveModulesRoot: path.join(process.env.PROJECT_CWD, `packages/grafana-e2e-selectors/src`), }, ], }, { input: './compiled/index.d.ts', plugins: [dts()], output: { file: pkg.publishConfig.types, format: 'es', }, }, ];
packages/grafana-e2e-selectors/rollup.config.ts
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.00017058626690413803, 0.00016963487723842263, 0.00016860838513821363, 0.00016967245028354228, 8.868791496752237e-7 ]
{ "id": 5, "code_window": [ " })\n", " );\n", " }\n", " }\n", " }, [dashboard, state, notifyApp, dispatch]);\n", "\n", " return { state, onDashboardSave };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, [dashboard, isCopy, state, notifyApp, dispatch]);\n" ], "file_path": "public/app/features/dashboard/components/SaveDashboard/useDashboardSave.tsx", "type": "replace", "edit_start_line_idx": 69 }
clickhouse: image: clickhouse/clickhouse-server:latest container_name: clickhouse ports: - "8123:8123"
devenv/docker/blocks/clickhouse/docker-compose.yaml
0
https://github.com/grafana/grafana/commit/029253d5f6f1761f1a9d9e742c0c750ebc3d7392
[ 0.000169466802617535, 0.000169466802617535, 0.000169466802617535, 0.000169466802617535, 0 ]
{ "id": 0, "code_window": [ "import React, { FunctionComponent } from 'react';\n", "import { H2 } from '@storybook/components/html';\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { HeaderMdx } from './mdx';\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 2 }
import React, { FunctionComponent } from 'react'; import { H2 } from '@storybook/components/html'; interface HeadingProps { children: JSX.Element | string; } export const Heading: FunctionComponent<HeadingProps> = ({ children }) => <H2>{children}</H2>;
addons/docs/src/blocks/Heading.tsx
1
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.5584475994110107, 0.5584475994110107, 0.5584475994110107, 0.5584475994110107, 0 ]
{ "id": 0, "code_window": [ "import React, { FunctionComponent } from 'react';\n", "import { H2 } from '@storybook/components/html';\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { HeaderMdx } from './mdx';\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 2 }
import { Meta, Story, Preview } from '@storybook/addon-docs/blocks'; import { linkTo } from '@storybook/addon-links'; import Welcome from './Welcome'; <Meta title="Welcome" component={Welcome} /> # Welcome This is a test document written in MDX that defines a `Welcome` story wrapped in a `Preview` doc block: <Preview withToolbar> <Story name="to Storybook"> {{ components: { Welcome, }, template: '<welcome :showApp="action" />', methods: { action: linkTo('Button'), }, }} </Story> </Preview>
lib/cli/generators/VUE/template-mdx/stories/0-Welcome.stories.mdx
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017121314886026084, 0.00016870733816176653, 0.00016642585978843272, 0.00016848302038852125, 0.0000019608287402661517 ]
{ "id": 0, "code_window": [ "import React, { FunctionComponent } from 'react';\n", "import { H2 } from '@storybook/components/html';\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { HeaderMdx } from './mdx';\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 2 }
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.<br /> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.<br /> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br /> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/).
examples/cra-ts-kitchen-sink/README.md
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017153604130726308, 0.00016704962763469666, 0.00016395548300351948, 0.00016732852964196354, 0.000002702188794501126 ]
{ "id": 0, "code_window": [ "import React, { FunctionComponent } from 'react';\n", "import { H2 } from '@storybook/components/html';\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { HeaderMdx } from './mdx';\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 2 }
# Release Process A Storybook release process based on [Semver](http://semver.org/). In short: 1. Merge all PRs into `next`, which is the default branch. Cherry-pick bugfix PRs into `master`, which is the stable release. 2. Every week: release patch releases off `master` to the NPM tag `latest`, and alpha releases off `next` to the NPM tag `next` (as e.g. `4.1.0-alpha.0`). 3. Every month or two, merge `next` into `master` and release a minor/major version according to `semver`. We set minor release dates as soon as we have feature clarity and manage to those dates: - Date should be a Monday so if we slip we don't get pushed into the weekend - T-3wk: - Draft announcement and socialize - Announce dates in #maintenance so people can react - T-1wk: - If you want your feature in the release, it should already be released on next by this time - Create release branch and only cherrypick bugfixes - Set up launch plan ## Motivation During the Storybook 3.x transition we've undergone a series of growing pains as we've opened up the development process. We've had questions about: 1. how to adhere to semver? 2. how to do marketing releases (while adhering to semver)? 3. how to introduce significant new features (e.g. vue support, story hierarchy)? 4. how to converge on key design decisions (e.g. new addons API)? 5. how to schedule releases? 6. how to maintain quality/stability through the process? 7. how to pay down tech debt as we go? This process attempts to address all these concerns in one shot. ## Semver [Semver](http://semver.org/) dictates three types of release: 1. MAJOR version when you make incompatible API changes, 2. MINOR version when you add functionality in a backwards-compatible manner, and 3. PATCH version when you make backwards-compatible bug fixes. We'll do our best to adhere to Semver, but won't be religious about it. In particular, we may occasionally release small bits of new functionality in PATCH releases. We'll try our best to restrict breaking changes to MAJOR releases. ## PATCH releases Every bugfix should go out as soon as we've verified the fix, and based on the current rate of contribution, we should be issuing PATCH releases weekly. Eventually, we'll automate the process so that a release will go out every time a PR is merged into `master`, and we've already laid most of the groundwork for this. ## MINOR releases Every new feature, particularly significant ones (e.g. Vue support, deep hierarchy for stories) deserves more attention: 1. They should be well-tested by the community before we release. 2. They often have architectural implications for the entire Storybook ecosystem, so should be discussed thoroughly before release. Doing `alpha` releases allow us to test in the community without necessarily achieving agreement. 3. They often deserve proper marketing treatment (blog posts, release announcement, podcast, etc.) Therefore we release `alpha` versions continuously on the NPM `next` tag to allow people to test out features as soon as they are ready. In general, we should release 2-3 headline features per minor release for marketing purposes. Each headline feature should get its own blog post on the Storybook medium publication, and the release itself should also get a blog post. ## MAJOR releases We should avoid major releases, but won't hold ourselves back on this. Making storybook better is the prime directive, and if we have to make breaking changes to do it, we will. That said, MAJOR releases should have killer features that reward users for upgrading, and should not be used to scratch our own architectural itches -- unless those itches are really killing development in some meaningful way. ## Blocking bugs Most PATCH releases come from community members, who generously fix problems as they come up. However, there are also bugs that never get picked up and just sit there gathering upvotes and "me too" comments. We need a way to make sure that these bugs get addressed. For every non-PATCH release, we nominate a small number of bugs that must be addressed before a release can go out by adding them to the milestone. For example, here's a list of blocking bugs [for the 3.2 milestone](https://github.com/storybookjs/storybook/milestone/3). Adding bugs to the milestone helps people looking for good ways to contribute, or to understand what is blocking the release so they can actually do something about it. Discussion about which bugs are critical happens in the `#maintenance` channel [in our Slack](https://now-examples-slackin-rrirkqohko.now.sh/) [![Storybook Slack](https://now-examples-slackin-rrirkqohko.now.sh/badge.svg)](https://now-examples-slackin-rrirkqohko.now.sh/) If you're experiencing a bug, the best way to make sure that it gets attention is to upvote it by adding a "thumbs-up" reaction in Github. This way important bugs quickly bubble to the top [with a search](https://github.com/storybookjs/storybook/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20sort%3Areactions-%2B1-desc%20label%3Abug). The best way to make sure a bug gets addressed quickly is to fix it yourself and issue a PR. If the fix is good, we'll try to release it quickly in a patch release. ## Decision-making - For PATCH changes, all discussion can occur in issue/PR comments (and random slack chat as needed). - For MINOR feature changes, there are multiple stages of discussion: - The feature may be discussed in an issue before it is implemented (ex: <https://github.com/storybookjs/storybook/issues/151>) - Once it's implemented, the discussion may occur on the PR (ex: <https://github.com/storybookjs/storybook/pull/1329>) - If people disagree on an implementation and it can't be resolved in discussion, they may issue alternative PR's with different ideas - Ultimately the maintainers will reach a consensus before merging the changes. There is no set process for this, but we're all adults. - Since MINOR features are released in alpha before they are fully released, new issues may be created by end users, etc. - For MAJOR infrastructural changes, the discussion may take place over time, in gists, issues, slack discussions, etc. - Once the breaking changes have been reduced to an actual implementation, it looks pretty much like a feature release (only with higher stakes and probably a longer stabilization process). ## FAQ's #### How does my PR get merged? - For PATCH PR's, any maintainer can review, test, approve, and merge it. - For MINOR/MAJOR PR's, once a maintainer reviews, tests, and approves it, s/he should clear it with the other maintainers before merging it into the release branch. - Once a release date has been set and we cut off merging, we'll create a temporary branch to hold that release so that it doesn't block merging to `next`.
RELEASES.md
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017498443776275963, 0.00016803563630674034, 0.00016408106603194028, 0.0001661040587350726, 0.000003665271378849866 ]
{ "id": 1, "code_window": [ "\n", "interface HeadingProps {\n", " children: JSX.Element | string;\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "export interface HeadingProps {\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "replace", "edit_start_line_idx": 3 }
import React, { FunctionComponent } from 'react'; import { H2 } from '@storybook/components/html'; interface HeadingProps { children: JSX.Element | string; } export const Heading: FunctionComponent<HeadingProps> = ({ children }) => <H2>{children}</H2>;
addons/docs/src/blocks/Heading.tsx
1
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.9991783499717712, 0.9991783499717712, 0.9991783499717712, 0.9991783499717712, 0 ]
{ "id": 1, "code_window": [ "\n", "interface HeadingProps {\n", " children: JSX.Element | string;\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "export interface HeadingProps {\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "replace", "edit_start_line_idx": 3 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Metadata/Combined Combined 1 1`] = ` <storybook-dynamic-app-root cfr={[Function CodegenComponentFactoryResolver]} data={[Function Object]} target={[Function ViewContainerRef_]} > <ng-component> <storybook-simple-token-component ng-reflect-name="Prop Name" > <h3> Prop Name </h3> <p> Items: </p> <ul> <li> Joe </li> <li> Jane </li> </ul> </storybook-simple-token-component> </ng-component> </storybook-dynamic-app-root> `; exports[`Storyshots Metadata/Combined Combined 2 1`] = ` <storybook-dynamic-app-root cfr={[Function CodegenComponentFactoryResolver]} data={[Function Object]} target={[Function ViewContainerRef_]} > <ng-component> <storybook-simple-token-component ng-reflect-name="CustomPipe: Prop Name" > <h3> CustomPipe: Prop Name </h3> <p> Items: </p> <ul> <li> Joe </li> <li> Jane </li> </ul> </storybook-simple-token-component> </ng-component> </storybook-dynamic-app-root> `;
examples/angular-cli/src/stories/__snapshots__/metadata-combined.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017526948067825288, 0.00017178409325424582, 0.00016859486640896648, 0.00017108423344325274, 0.0000020162478904239833 ]
{ "id": 1, "code_window": [ "\n", "interface HeadingProps {\n", " children: JSX.Element | string;\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "export interface HeadingProps {\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "replace", "edit_start_line_idx": 3 }
import { ButtonComponent } from './doc-button.component'; export default { title: 'DocButton', component: ButtonComponent, parameters: { docs: { iframeHeight: 120 } }, }; export const Basic = () => ({ component: ButtonComponent, props: { label: 'Docs Test', }, });
examples/angular-cli/src/stories/doc-button/doc-button.stories.ts
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00020630106155294925, 0.00018751004245132208, 0.0001687190233496949, 0.00018751004245132208, 0.00001879101910162717 ]
{ "id": 1, "code_window": [ "\n", "interface HeadingProps {\n", " children: JSX.Element | string;\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "export interface HeadingProps {\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "replace", "edit_start_line_idx": 3 }
#app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } .text-align-center { text-align: center; } .main { padding: 15px; line-height: 1.4; font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif; background-color: #ffffff; } .logo { height: 150px; } .link { color: #1474f3; text-decoration: none; border-bottom: 1px solid #1474f3; padding-bottom: 2px; } .code { font-size: 15; font-weight: 600; padding: 2px 5px; border: 1px solid #eae9e9; border-radius: 4px; background-color: #f3f2f2; color: #3a3a3a; } .codeBlock { background-color: #f3f2f2; padding: 1px 10px; margin: 10px 0; } .note { opacity: 0.5; } .banner { padding: 10px; border-radius: 5px; }
examples/ember-cli/app/styles/app.css
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017368749831803143, 0.00017037651559803635, 0.00016773059905972332, 0.00017032280447892845, 0.0000017640347778069554 ]
{ "id": 2, "code_window": [ " children: JSX.Element | string;\n", "}\n" ], "labels": [ "add", "keep" ], "after_edit": [ " disableAnchor?: boolean;\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 5 }
import React, { FunctionComponent } from 'react'; import { H2 } from '@storybook/components/html'; interface HeadingProps { children: JSX.Element | string; } export const Heading: FunctionComponent<HeadingProps> = ({ children }) => <H2>{children}</H2>;
addons/docs/src/blocks/Heading.tsx
1
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.9958974123001099, 0.9958974123001099, 0.9958974123001099, 0.9958974123001099, 0 ]
{ "id": 2, "code_window": [ " children: JSX.Element | string;\n", "}\n" ], "labels": [ "add", "keep" ], "after_edit": [ " disableAnchor?: boolean;\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 5 }
SKIP_PREFLIGHT_CHECK=true NODE_PATH=src
examples/cra-ts-kitchen-sink/.env
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00022523973893839866, 0.00022523973893839866, 0.00022523973893839866, 0.00022523973893839866, 0 ]
{ "id": 2, "code_window": [ " children: JSX.Element | string;\n", "}\n" ], "labels": [ "add", "keep" ], "after_edit": [ " disableAnchor?: boolean;\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 5 }
import React, { FC, SyntheticEvent } from 'react'; interface TSProps { /** * this is case 1. * @param { SyntheticEvent } event - React's original event. * @returns {void} */ case1: (event: SyntheticEvent) => void; /** * should not be visible since it's ignored. * @ignore */ case2: string; } /** * Button functional component (React.FC) */ export const TypeScriptProps: FC<TSProps> = ({ case1, case2 }) => ( <button type="button" onClick={case1}> JSDoc with TypeScript! {case2} </button> );
examples/cra-ts-kitchen-sink/src/stories/docgen-tests/jsdoc/jsdoc-ts.tsx
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00042377522913739085, 0.00025593757163733244, 0.00017000234220176935, 0.00017403512902092189, 0.00011869056470459327 ]
{ "id": 2, "code_window": [ " children: JSX.Element | string;\n", "}\n" ], "labels": [ "add", "keep" ], "after_edit": [ " disableAnchor?: boolean;\n" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "add", "edit_start_line_idx": 5 }
/* eslint-disable import/no-extraneous-dependencies */ import { addParameters } from '@storybook/client-api'; import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks'; addParameters({ docs: { container: DocsContainer, page: DocsPage, }, });
addons/docs/src/frameworks/common/config.ts
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017736540758050978, 0.00017490828759036958, 0.00017245115304831415, 0.00017490828759036958, 0.000002457127266097814 ]
{ "id": 3, "code_window": [ "}\n", "export const Heading: FunctionComponent<HeadingProps> = ({ children }) => <H2>{children}</H2>;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "\n", "export const Heading: FunctionComponent<HeadingProps> = ({ children, disableAnchor }) => {\n", " if (disableAnchor || typeof children !== 'string') {\n", " return <H2>{children}</H2>;\n", " }\n", " const tagID = children.toLowerCase().replace(/[^a-z0-9]/gi, '-');\n", " return (\n", " <HeaderMdx as=\"h2\" id={tagID}>\n", " {children}\n", " </HeaderMdx>\n", " );\n", "};" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "replace", "edit_start_line_idx": 6 }
import React, { FC, SyntheticEvent } from 'react'; import { Source } from '@storybook/components'; import { Code, components } from '@storybook/components/html'; import { document, window } from 'global'; import { isNil } from 'lodash'; import { styled } from '@storybook/theming'; import { DocsContext, DocsContextProps } from './DocsContext'; import { scrollToElement } from './utils'; // Hacky utility for dealing with functions or values in MDX Story elements export const makeStoryFn = (val: any) => (typeof val === 'function' ? val : () => val); // Hacky utilty for adding mdxStoryToId to the default context export const AddContext: FC<DocsContextProps> = props => { const { children, ...rest } = props; const parentContext = React.useContext(DocsContext); return ( <DocsContext.Provider value={{ ...parentContext, ...rest }}>{children}</DocsContext.Provider> ); }; interface CodeOrSourceMdxProps { className?: string; } export const CodeOrSourceMdx: FC<CodeOrSourceMdxProps> = ({ className, children, ...rest }) => { // markdown-to-jsx does not add className to inline code if ( typeof className !== 'string' && (typeof children !== 'string' || !(children as string).match(/[\n\r]/g)) ) { return <Code>{children}</Code>; } // className: "lang-jsx" const language = className && className.split('-'); return ( <Source language={(language && language[1]) || 'plaintext'} format={false} code={children as string} {...rest} /> ); }; function generateHrefWithHash(hash: string): string { const url = new URL(window.parent.location); const href = `${url.origin}/${url.search}#${hash}`; return href; } // @ts-ignore const A = components.a; interface AnchorInPageProps { hash: string; } const AnchorInPage: FC<AnchorInPageProps> = ({ hash, children }) => ( <A href={hash} onClick={(event: SyntheticEvent) => { event.preventDefault(); const hashValue = hash.substring(1); const element = document.getElementById(hashValue); if (!isNil(element)) { window.parent.history.replaceState(null, '', generateHrefWithHash(hashValue)); scrollToElement(element); } }} > {children} </A> ); interface AnchorMdxProps { href: string; target: string; } export const AnchorMdx: FC<AnchorMdxProps> = props => { const { href, target, children, ...rest } = props; if (!isNil(href)) { // Enable scrolling for in-page anchors. if (href.startsWith('#')) { return <AnchorInPage hash={href}>{children}</AnchorInPage>; } // Links to other pages of SB should use the base URL of the top level iframe instead of the base URL of the preview iframe. if (target !== '_blank') { const parentUrl = new URL(window.parent.location.href); const newHref = `${parentUrl.origin}${href}`; return ( <A href={newHref} target={target} {...rest}> {children} </A> ); } } // External URL dont need any modification. return <A {...props} />; }; const SUPPORTED_MDX_HEADERS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; const OcticonHeaders = SUPPORTED_MDX_HEADERS.reduce( (acc, headerType) => ({ ...acc, // @ts-ignore [headerType]: styled(components[headerType])({ '& svg': { visibility: 'hidden', }, '&:hover svg': { visibility: 'visible', }, }), }), {} ); const OcticonAnchor = styled.a(() => ({ float: 'left', paddingRight: '4px', marginLeft: '-20px', })); interface HeaderWithOcticonAnchorProps { as: string; id: string; children: any; } const HeaderWithOcticonAnchor: FC<HeaderWithOcticonAnchorProps> = ({ as, id, children, ...rest }) => { // @ts-ignore const OcticonHeader = OcticonHeaders[as]; return ( <OcticonHeader id={id} {...rest}> <OcticonAnchor aria-hidden="true" href={generateHrefWithHash(id)} onClick={() => { const element = document.getElementById(id); if (!isNil(element)) { scrollToElement(element); } }} > <svg viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fillRule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z" /> </svg> </OcticonAnchor> {children} </OcticonHeader> ); }; interface HeaderMdxProps { as: string; id: string; } const HeaderMdx: FC<HeaderMdxProps> = props => { const { as, id, children, ...rest } = props; // An id should have been added on every header by the "remark-slug" plugin. if (!isNil(id)) { return ( <HeaderWithOcticonAnchor as={as} id={id} {...rest}> {children} </HeaderWithOcticonAnchor> ); } // @ts-ignore const Header = components[as]; // Make sure it still work if "remark-slug" plugin is not present. return <Header {...props} />; }; export const HeadersMdx = SUPPORTED_MDX_HEADERS.reduce( (acc, headerType) => ({ ...acc, // @ts-ignore [headerType]: (props: object) => <HeaderMdx as={headerType} {...props} />, }), {} );
addons/docs/src/blocks/mdx.tsx
1
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.9884557723999023, 0.09823385626077652, 0.00016947132826317102, 0.002517733257263899, 0.2881113588809967 ]
{ "id": 3, "code_window": [ "}\n", "export const Heading: FunctionComponent<HeadingProps> = ({ children }) => <H2>{children}</H2>;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "\n", "export const Heading: FunctionComponent<HeadingProps> = ({ children, disableAnchor }) => {\n", " if (disableAnchor || typeof children !== 'string') {\n", " return <H2>{children}</H2>;\n", " }\n", " const tagID = children.toLowerCase().replace(/[^a-z0-9]/gi, '-');\n", " return (\n", " <HeaderMdx as=\"h2\" id={tagID}>\n", " {children}\n", " </HeaderMdx>\n", " );\n", "};" ], "file_path": "addons/docs/src/blocks/Heading.tsx", "type": "replace", "edit_start_line_idx": 6 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Welcome to Storybook 1`] = ` <article style={ Object { "backgroundColor": "#fff", "color": "#000", "fontFamily": "\\"Helvetica Neue\\", Helvetica, \\"Segoe UI\\", Arial, freesans, sans-serif", "lineHeight": 1.4, "padding": 15, } } > <h1> Welcome to storybook </h1> <p> This is a UI component dev environment for your app. </p> <p> We've added some basic stories inside the <code style={ Object { "backgroundColor": "#f3f2f2", "border": "1px solid #eae9e9", "borderRadius": 4, "color": "#3a3a3a", "fontSize": 15, "fontWeight": 600, "padding": "2px 5px", } } > src/stories </code> directory. <br /> A story is a single state of one or more UI components. You can have as many stories as you want. <br /> (Basically a story is like a visual test case.) </p> <p> See these sample <button onClick={[Function]} style={ Object { "backgroundColor": "transparent", "borderBottom": "1px solid #1474f3", "borderLeft": "none", "borderRight": "none", "borderTop": "none", "color": "#1474f3", "cursor": "pointer", "font": "inherit", "padding": 0, "paddingBottom": 2, "textDecoration": "none", } } type="button" > stories </button> for a component called  <code style={ Object { "backgroundColor": "#f3f2f2", "border": "1px solid #eae9e9", "borderRadius": 4, "color": "#3a3a3a", "fontSize": 15, "fontWeight": 600, "padding": "2px 5px", } } > Button </code> . </p> <p> Just like that, you can add your own components as stories. <br /> You can also edit those components and see changes right away. <br /> (Try editing the <code style={ Object { "backgroundColor": "#f3f2f2", "border": "1px solid #eae9e9", "borderRadius": 4, "color": "#3a3a3a", "fontSize": 15, "fontWeight": 600, "padding": "2px 5px", } } > Button </code> stories located at  <code style={ Object { "backgroundColor": "#f3f2f2", "border": "1px solid #eae9e9", "borderRadius": 4, "color": "#3a3a3a", "fontSize": 15, "fontWeight": 600, "padding": "2px 5px", } } > src/stories/index.js </code> .) </p> <p> Usually we create stories with smaller UI components in the app. <br /> Have a look at the  <a href="https://storybook.js.org/basics/writing-stories" rel="noopener noreferrer" style={ Object { "borderBottom": "1px solid #1474f3", "color": "#1474f3", "paddingBottom": 2, "textDecoration": "none", } } target="_blank" > Writing Stories </a>  section in our documentation. </p> <p style={ Object { "opacity": 0.5, } } > <b> NOTE: </b> <br /> Have a look at the <code style={ Object { "backgroundColor": "#f3f2f2", "border": "1px solid #eae9e9", "borderRadius": 4, "color": "#3a3a3a", "fontSize": 15, "fontWeight": 600, "padding": "2px 5px", } } > .storybook/webpack.config.js </code> to add webpack loaders and plugins you are using in this project. </p> </article> `;
addons/storyshots/storyshots-core/stories/required_with_context/__snapshots__/Welcome.stories.foo
0
https://github.com/storybookjs/storybook/commit/14df7d561a1d050b536d894b06154a820dc6f059
[ 0.00017455531633459032, 0.0001705294125713408, 0.00016685915761627257, 0.00016956710896920413, 0.000002272230403832509 ]