text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```xml /** * Import CSV files into DuckDb */ import * as log from "loglevel"; import * as path from "path"; import { Connection, Database } from "duckdb-async"; import * as prettyHRTime from "pretty-hrtime"; import { initS3 } from "./s3utils"; let uniqMap: { [cid: string]: number } = {}; /* add a numeric _N suffix to an identifer to make it unique */ const uniquify = (src: string): string => { let entry = uniqMap[src]; if (entry === undefined) { uniqMap[src] = 1; return src; // no suffix needed } const ret = src + "_" + entry.toString(); uniqMap[src] = ++entry; return ret; }; /* map to alphanumeric */ const mapIdent = (src: string): string => { const ret = src.replace(/[^a-z0-9_]/gi, "_"); return ret; }; const isAlpha = (ch: string): boolean => /^[A-Z]$/i.test(ch); const MAXLEN = 16; /* generate a SQL table name from pathname */ const genTableName = (pathname: string): string => { const extName = path.extname(pathname); const baseName = path.basename(pathname, extName); let baseIdent = mapIdent(baseName); if (baseIdent.length >= MAXLEN) { baseIdent = baseIdent.slice(0, MAXLEN); } if (!isAlpha(baseIdent[0])) { baseIdent = "t_" + baseIdent; } const tableName = uniquify(baseIdent); return tableName; }; /** * Native import using DuckDB's built-in import facilities. */ export const nativeCSVImport = async ( db: Database, filePath: string, tableName?: string ): Promise<string> => { const importStart = process.hrtime(); const dbConn = await db.connect(); await initS3(dbConn); if (!tableName) { tableName = genTableName(filePath); } const query = `CREATE OR REPLACE TABLE ${tableName} AS SELECT * FROM read_csv_auto('${filePath}')`; // console.log('nativeCSVImport: executing: ', query); try { /* const resObj = await dbConn.executeIterator(query); const resRows = resObj.fetchAllRows() as any[]; */ const resRows = await dbConn.all(query); // console.log('nativeCSVImport: result: ', resRows[0]); const info = resRows[0]; // console.log('info.Count: \"' + info.Count + '\", type: ', typeof info.Count); } catch (err) { console.log("caught exception while importing: ", err); console.log("retrying with SAMPLE_SIZE=-1:"); const noSampleQuery = `CREATE OR REPLACE TABLE ${tableName} AS SELECT * FROM read_csv_auto('${filePath}', sample_size=-1)`; try { /* const resObj = await dbConn.executeIterator(noSampleQuery); const resRows = resObj.fetchAllRows() as any[]; */ const resRows = await dbConn.all(noSampleQuery); // console.log('nativeCSVImport: result: ', resRows[0]); const info = resRows[0]; log.debug( 'nativeCSVImport: info.Count: "' + info.Count + '", type: ', typeof info.Count ); } catch (noSampleErr) { console.log("caught exception with no sampling: ", noSampleErr); throw noSampleErr; } } const importTime = process.hrtime(importStart); log.info( "DuckDB nativeCSVImport: import completed in ", prettyHRTime(importTime) ); return tableName; }; /** * Native import using DuckDB's built-in import facilities. */ export const nativeParquetImport = async ( db: Database, filePath: string, tableName?: string ): Promise<string> => { const importStart = process.hrtime(); const dbConn = await db.connect(); await initS3(dbConn); if (!tableName) { tableName = genTableName(filePath); } const query = `CREATE OR REPLACE VIEW ${tableName} AS SELECT * FROM parquet_scan('${filePath}')`; log.debug("*** parquet import: ", query); try { // Creating a view doesn't return a useful result. await dbConn.exec(query); } catch (err) { console.log("caught exception while importing: ", err); throw err; } const [es, ens] = process.hrtime(importStart); log.info( "DuckDB nativeParquetImport: import completed in %ds %dms", es, ens / 1e6 ); return tableName; }; ```
/content/code_sandbox/packages/reltab-duckdb/src/csvimport.ts
xml
2016-10-24T18:59:04
2024-08-16T16:29:52
tad
antonycourtney/tad
3,125
1,030
```xml import { chartOptionsCompositeMark as render } from '../plots/api/chart-options-composite-mark'; import { createNodeGCanvas } from './utils/createNodeGCanvas'; import { sleep } from './utils/sleep'; import './utils/useSnapshotMatchers'; describe('chart.mark()', () => { const canvas = createNodeGCanvas(640, 480); it('chart.render() should render composite mark.', async () => { const { finished } = render({ canvas }); await finished; await sleep(20); const dir = `${__dirname}/snapshots/api`; await expect(canvas).toMatchDOMSnapshot(dir, render.name); }); afterAll(() => { canvas?.destroy(); }); }); ```
/content/code_sandbox/__tests__/integration/api-chart-options-composite-mark.spec.ts
xml
2016-05-26T09:21:04
2024-08-15T16:11:17
G2
antvis/G2
12,060
150
```xml import {CollectionViewer, SelectionChange, DataSource} from '@angular/cdk/collections'; import {FlatTreeControl} from '@angular/cdk/tree'; import {ChangeDetectionStrategy, Component, Injectable, inject, signal} from '@angular/core'; import {BehaviorSubject, merge, Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import {MatProgressBarModule} from '@angular/material/progress-bar'; import {MatIconModule} from '@angular/material/icon'; import {MatButtonModule} from '@angular/material/button'; import {MatTreeModule} from '@angular/material/tree'; /** Flat node with expandable and level information */ export class DynamicFlatNode { constructor( public item: string, public level = 1, public expandable = false, public isLoading = signal(false), ) {} } /** * Database for dynamic data. When expanding a node in the tree, the data source will need to fetch * the descendants data from the database. */ @Injectable({providedIn: 'root'}) export class DynamicDatabase { dataMap = new Map<string, string[]>([ ['Fruits', ['Apple', 'Orange', 'Banana']], ['Vegetables', ['Tomato', 'Potato', 'Onion']], ['Apple', ['Fuji', 'Macintosh']], ['Onion', ['Yellow', 'White', 'Purple']], ]); rootLevelNodes: string[] = ['Fruits', 'Vegetables']; /** Initial data from database */ initialData(): DynamicFlatNode[] { return this.rootLevelNodes.map(name => new DynamicFlatNode(name, 0, true)); } getChildren(node: string): string[] | undefined { return this.dataMap.get(node); } isExpandable(node: string): boolean { return this.dataMap.has(node); } } /** * File database, it can build a tree structured Json object from string. * Each node in Json object represents a file or a directory. For a file, it has filename and type. * For a directory, it has filename and children (a list of files or directories). * The input will be a json object string, and the output is a list of `FileNode` with nested * structure. */ export class DynamicDataSource implements DataSource<DynamicFlatNode> { dataChange = new BehaviorSubject<DynamicFlatNode[]>([]); get data(): DynamicFlatNode[] { return this.dataChange.value; } set data(value: DynamicFlatNode[]) { this._treeControl.dataNodes = value; this.dataChange.next(value); } constructor( private _treeControl: FlatTreeControl<DynamicFlatNode>, private _database: DynamicDatabase, ) {} connect(collectionViewer: CollectionViewer): Observable<DynamicFlatNode[]> { this._treeControl.expansionModel.changed.subscribe(change => { if ( (change as SelectionChange<DynamicFlatNode>).added || (change as SelectionChange<DynamicFlatNode>).removed ) { this.handleTreeControl(change as SelectionChange<DynamicFlatNode>); } }); return merge(collectionViewer.viewChange, this.dataChange).pipe(map(() => this.data)); } disconnect(collectionViewer: CollectionViewer): void {} /** Handle expand/collapse behaviors */ handleTreeControl(change: SelectionChange<DynamicFlatNode>) { if (change.added) { change.added.forEach(node => this.toggleNode(node, true)); } if (change.removed) { change.removed .slice() .reverse() .forEach(node => this.toggleNode(node, false)); } } /** * Toggle the node, remove from display list */ toggleNode(node: DynamicFlatNode, expand: boolean) { const children = this._database.getChildren(node.item); const index = this.data.indexOf(node); if (!children || index < 0) { // If no children, or cannot find the node, no op return; } node.isLoading.set(true); setTimeout(() => { if (expand) { const nodes = children.map( name => new DynamicFlatNode(name, node.level + 1, this._database.isExpandable(name)), ); this.data.splice(index + 1, 0, ...nodes); } else { let count = 0; for ( let i = index + 1; i < this.data.length && this.data[i].level > node.level; i++, count++ ) {} this.data.splice(index + 1, count); } // notify the change this.dataChange.next(this.data); node.isLoading.set(false); }, 1000); } } /** * @title Tree with dynamic data */ @Component({ selector: 'tree-dynamic-example', templateUrl: 'tree-dynamic-example.html', styleUrl: 'tree-dynamic-example.css', standalone: true, imports: [MatTreeModule, MatButtonModule, MatIconModule, MatProgressBarModule], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TreeDynamicExample { constructor() { const database = inject(DynamicDatabase); this.treeControl = new FlatTreeControl<DynamicFlatNode>(this.getLevel, this.isExpandable); this.dataSource = new DynamicDataSource(this.treeControl, database); this.dataSource.data = database.initialData(); } treeControl: FlatTreeControl<DynamicFlatNode>; dataSource: DynamicDataSource; getLevel = (node: DynamicFlatNode) => node.level; isExpandable = (node: DynamicFlatNode) => node.expandable; hasChild = (_: number, _nodeData: DynamicFlatNode) => _nodeData.expandable; } ```
/content/code_sandbox/src/components-examples/material/tree/tree-dynamic/tree-dynamic-example.ts
xml
2016-01-04T18:50:02
2024-08-16T11:21:13
components
angular/components
24,263
1,211
```xml // // // Microsoft Bot Framework: path_to_url // // Bot Framework Emulator Github: // path_to_url // // All rights reserved. // // 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. // import * as Fs from 'fs'; export const getFilesInDir = (path: string) => { return Fs.readdirSync(path, 'utf-8'); }; ```
/content/code_sandbox/packages/app/main/src/utils/getFilesInDir.ts
xml
2016-11-11T23:15:09
2024-08-16T12:45:29
BotFramework-Emulator
microsoft/BotFramework-Emulator
1,803
289
```xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="zh_CN"> <context> <name>Data::SyncthingLauncher</name> <message> <location filename="../misc/syncthinglauncher.cpp" line="138"/> <source>Not built with libsyncthing support.</source> <translation> libsyncthing </translation> </message> </context> <context> <name>QtGui</name> <message> <location filename="../webview/webviewdialog.cpp" line="250"/> <source>Unable to open Syncthing UI via &quot;%1&quot;: %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="89"/> <source>The network connection is currently considered metered.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="90"/> <source>The network connection is currently not considered metered.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="91"/> <source>Unable to determine whether the network connection is metered; assuming an unmetered connection.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::AppearanceOptionPage</name> <message> <location filename="../settings/appearanceoptionpage.ui" line="12"/> <source>Appearance</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="28"/> <source>Frame shape</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="42"/> <source>No frame</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="47"/> <source>Box</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="52"/> <source>Panel</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="57"/> <source>Styled panel</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="65"/> <source>Frame shadow</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="79"/> <source>Plain</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="84"/> <source>Raised</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="89"/> <source>Sunken</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="97"/> <source>Tab position</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="111"/> <source>Top</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="116"/> <source>Bottom</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="121"/> <source>Left</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="126"/> <source>Right</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="341"/> <source>Show tab texts</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="355"/> <source>Prefer icons from theme over ForkAwesome icons (needs restart to apply)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="364"/> <source>Icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="378"/> <source>Popup</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="383"/> <source>Normal window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="388"/> <source>Window without titlebar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="393"/> <source>None - open Syncthing directly</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="401"/> <source>Window type</source> <translation type="unfinished"></translation> </message> <message> <source>Colors</source> <translation type="vanished"></translation> </message> <message> <source>Bright custom text colors (use for dark color scheme)</source> <translation type="vanished"></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="221"/> <source>Optional GUI elements</source> <translation> GUI </translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="334"/> <source>Traffic statistics</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="228"/> <source>Positioning</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="240"/> <source>Use cursor position</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="250"/> <source>Otherwise assume tray icon coordinates to be:</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="149"/> <location filename="../settings/appearanceoptionpage.ui" line="187"/> <location filename="../settings/appearanceoptionpage.ui" line="271"/> <location filename="../settings/appearanceoptionpage.ui" line="293"/> <source> px</source> <translation> </translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="274"/> <source>x: </source> <translation>x: </translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="296"/> <source>y: </source> <translation>y: </translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="134"/> <source>Menu size</source> <translation></translation> </message> <message> <location filename="../settings/appearanceoptionpage.ui" line="171"/> <source> x </source> <translation> x </translation> </message> </context> <context> <name>QtGui::ApplyWizardPage</name> <message> <location filename="../settings/applywizardpage.ui" line="6"/> <source>General</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="912"/> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="913"/> <source>Apply selected configuration</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="914"/> <source>Review the summary of the configuration changes before applying them</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="938"/> <source>Summary:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="952"/> <source>Keep %1 %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="952"/> <source>enabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="952"/> <source>disabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="953"/> <source>%1 %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="953"/> <source>Enable</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="953"/> <source>Disable</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="963"/> <source>Keep connection and launcher configuration as-is</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="966"/> <source>Configure Syncthing Tray to use the currently running Syncthing instance</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="967"/> <source>Do &lt;i&gt;not&lt;/i&gt; change how Syncthing is launched</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="971"/> <source>Start Syncthing via Syncthing Tray&apos;s launcher</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="973"/> <source>executable from PATH as separate process, &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="974"/> <source>built-in Syncthing library, &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="979"/> <source>Start Syncthing by enabling and starting its systemd unit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="981"/> <source>Using user unit &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="982"/> <source>Using system unit &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="991"/> <source>systemd integration</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="997"/> <source>Preserve existing autostart entry for &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1003"/> <source>Override</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1003"/> <source>Delete</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1004"/> <source>%1 existing autostart entry for &quot;%2&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1006"/> <source>autostart of Syncthing Tray</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1011"/> <source>Further information:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1011"/> <source>Click on &quot;Show details from setup detection&quot; for further details.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1012"/> <source>If you want to do amendments, you can head back one or more steps.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1012"/> <source>If you abort now, nothing will be changed.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::AutostartOptionPage</name> <message> <location filename="../settings/autostartoptionpage.ui" line="12"/> <source>Autostart</source> <translation></translation> </message> <message> <location filename="../settings/autostartoptionpage.ui" line="27"/> <source>Start the tray icon when the desktop environment launches</source> <translation></translation> </message> <message> <location filename="../settings/autostartoptionpage.ui" line="75"/> <source>Delete existing entry</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="843"/> <source>This is achieved by adding a *.desktop file under &lt;i&gt;~/.config/autostart&lt;/i&gt; so the setting only affects the current user.</source> <translation> &lt;i&gt;~/.config/autostart&lt;/i&gt; *.desktop </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="846"/> <source>This is achieved by adding a registry key under &lt;i&gt;HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run&lt;/i&gt; so the setting only affects the current user. Note that the startup entry is invalidated when moving &lt;i&gt;syncthingtray.exe&lt;/i&gt;.</source> <translation> &lt;i&gt;HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run&lt;/i&gt; &lt;i&gt;syncthingtray.exe&lt;/i&gt; </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="850"/> <source>This is achieved by adding a *.plist file under &lt;i&gt;~/Library/LaunchAgents&lt;/i&gt; so the setting only affects the current user.</source> <translation> &lt;i&gt;~/Library/LaunchAgents&lt;/i&gt; *.plist </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="854"/> <source>This feature has not been implemented for your platform (yet).</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1064"/> <source>unable to modify startup entry</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1094"/> <source>There is already an autostart entry for &quot;%1&quot;. It will not be overridden when applying changes unless you delete it first.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::AutostartWizardPage</name> <message> <location filename="../settings/autostartwizardpage.ui" line="6"/> <source>General</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/autostartwizardpage.ui" line="19"/> <source>Start Syncthing Tray on login (only affects sessions of the current user)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/autostartwizardpage.ui" line="46"/> <source>You previously selected to start Syncthing via the built-in launcher so Syncthing itself will be started automatically on login as well.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/autostartwizardpage.ui" line="56"/> <source>You previously selected to start Syncthing via systemd so its systemd-unit will be enabled. This means Syncthing itself will start automatically independently of this setting which only affects the tray icon.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/autostartwizardpage.ui" line="66"/> <source>Since Syncthing is running independently of Syncthing Tray on your system, this does not affect when Syncthing itself is launched.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/autostartwizardpage.ui" line="76"/> <source>The currently running Syncthing instance is started via Syncthing Tray so Syncthing itself will be started automatically on login as well.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/autostartwizardpage.ui" line="86"/> <source>This setting is about Syncthing Tray itself. If Syncthing is started via Syncthing Tray&apos;s launcher it will indirectly affect Syncthing as well, though.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="836"/> <source>Configure autostart</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="837"/> <source>Select whether to start Syncthing Tray automatically</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="891"/> <source>Do not modify the existing autostart entry for &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::BuiltinWebViewOptionPage</name> <message> <source>General</source> <translation type="obsolete"></translation> </message> <message> <source>Syncthing Tray has not been built with vieb view support utilizing either Qt WebKit or Qt WebEngine. The Web UI will be opened in the default web browser instead.</source> <translation type="obsolete">Syncthing Tray Qt WebKit Qt WebEngine UI </translation> </message> <message> <location filename="../settings/builtinwebviewoptionpage.ui" line="12"/> <location filename="../settings/settingsdialog.cpp" line="1703"/> <source>Built-in web view</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/builtinwebviewoptionpage.ui" line="22"/> <source>Zoom factor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/builtinwebviewoptionpage.ui" line="45"/> <source>Hiding</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/builtinwebviewoptionpage.ui" line="52"/> <source>Keep web view running when currently not shown</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1705"/> <source>Syncthing Tray has not been built with vieb view support utilizing either Qt WebKit or Qt WebEngine.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::ConnectionOptionPage</name> <message> <location filename="../settings/connectionoptionpage.ui" line="12"/> <source>Connection</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="30"/> <source>Config label</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="80"/> <source>Move currently selected configuration down</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="97"/> <source>Move currently selected configuration up</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="114"/> <source>Add secondary instance</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="131"/> <source>Remove currently selected secondary instance</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="161"/> <source>It is possible to save multiple configurations. This allows switching quickly between multiple Syncthing instances using the connection button in the right corner of the tray menu. The config label is an arbitrary name to identify a configuration and does not have to match the name of the corresponding Syncthing device. The first configuration is the primary/default configuration.</source> <translation> Syncthing Syncthing /</translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="171"/> <source>Syncthing URL</source> <translation>Syncthing URL</translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="185"/> <source>Authentication</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="202"/> <source>User</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="219"/> <source>Password</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="512"/> <source>API key</source> <translation>API </translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="236"/> <source>HTTPS certificate</source> <translation>HTTPS </translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="178"/> <source>&quot;path_to_url&quot; or &quot;path_to_url&quot;, e.g. &quot;path_to_url for local instance with default settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="192"/> <source>Supply credentials for HTTP authentication (normally the API key is sufficient)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="267"/> <source>Insert values from local Syncthing configuration</source> <translation> Syncthing </translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="284"/> <source>Select config file manually</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="311"/> <source>Poll interval</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="335"/> <source>Frequency for updating traffic statistics and download speed</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="338"/> <location filename="../settings/connectionoptionpage.ui" line="381"/> <location filename="../settings/connectionoptionpage.ui" line="410"/> <location filename="../settings/connectionoptionpage.ui" line="442"/> <location filename="../settings/connectionoptionpage.ui" line="539"/> <location filename="../settings/connectionoptionpage.ui" line="591"/> <source> ms</source> <translation> </translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="351"/> <source>Traffic</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="358"/> <source>Device statistics</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="378"/> <source>Frequency for updating device statistics</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="394"/> <source>Errors</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="407"/> <source>Frequency to poll for new errors</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="423"/> <source>Reconnect</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="436"/> <source>Time to wait for reconnecting again when the connection to Syncthing has been lost. This setting might be overruled by systemd and launcher settings.</source> <translation> Syncthing systemd </translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="439"/> <source>no</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="461"/> <source>Whether to connect automatically on startup. This setting might be overruled by systemd and launcher settings.</source> <translation> systemd </translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="464"/> <source>Connect automatically on startup</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="471"/> <source>Overall status</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="611"/> <source>Options</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="623"/> <source>Select what information should be considered to compute the overall status:</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="481"/> <source>Current status</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="488"/> <source>disconnected</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="501"/> <source>Apply connection settings and try to reconnect with the currently selected config</source> <translation></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="519"/> <source>The API key displayed in Syncthing&apos;s settings dialog</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="526"/> <source>The timeout for normal requests to Syncthing&apos;s API. Set to zero to enforce no timeout.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="529"/> <source>Transfer timeout</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="536"/> <source>no timeout</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="568"/> <source>Show advanced configuration</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="578"/> <source>The timeout for long-polling requests to Syncthing&apos;s event API. Set to zero to use Syncthing&apos;s default timeout and no timeout being enforced from Syncthing Tray&apos;s side.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="581"/> <source>Long polling int.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="588"/> <source>Syncthing&apos;s default with no timeout</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/connectionoptionpage.ui" line="604"/> <source>Pause all devices while the local network connection is metered</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="127"/> <source>Auto-detected for local instance</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="171"/> <source>Select Syncthing config file</source> <translation> Syncthing </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="179"/> <source>Unable to parse the Syncthing config file.</source> <translation> Syncthing </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="281"/> <source>Unable to load specified certificate &quot;%1&quot;.</source> <translation> &quot;%1&quot;</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="307"/> <source>Instance %1</source> <translation> %1</translation> </message> </context> <context> <name>QtGui::DBusStatusNotifier</name> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="25"/> <source> - internal error</source> <translation> - </translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="26"/> <source> - launcher error</source> <translation> - </translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="27"/> <source>Syncthing notification</source> <translation>Syncthing </translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="29"/> <source> - new device</source> <translation> - </translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="30"/> <source> - new folder</source> <translation> - </translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="33"/> <source>Disconnected from Syncthing</source> <translation> Syncthing </translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="34"/> <source>Try to reconnect</source> <translation></translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="38"/> <location filename="../misc/dbusstatusnotifier.cpp" line="42"/> <source>View details</source> <translation></translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="46"/> <source>Show</source> <translation></translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="46"/> <source>Dismiss</source> <translation></translation> </message> <message> <location filename="../misc/dbusstatusnotifier.cpp" line="52"/> <source>Open web UI</source> <translation> UI</translation> </message> </context> <context> <name>QtGui::DetectionWizardPage</name> <message> <location filename="../settings/wizard.cpp" line="528"/> <source>Checking current Syncthing setup</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="529"/> <source>Checking Syncthing configuration and whether Syncthing is already running or can be started </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="535"/> <source>Check again</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="587"/> <source>Re-visit setup detection</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="588"/> <source>You might trigger checking the Syncthing setup again</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="614"/> <source>It looks like Syncthing has not been running on this system before as its configuration cannot be found. Is that correct?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="610"/> <source>Yes, continue configuration</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="611"/> <source>No, let me select Syncthing&apos;s configuration file manually</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="620"/> <source>Select Syncthing&apos;s configuration file</source> <translation type="unfinished"></translation> </message> <message> <source>no</source> <translation type="obsolete"></translation> </message> </context> <context> <name>QtGui::DirectoryErrorsDialog</name> <message> <location filename="../misc/direrrorsdialog.cpp" line="28"/> <source>Errors for folder %1</source> <translation> %1 </translation> </message> <message> <location filename="../misc/direrrorsdialog.cpp" line="46"/> <source>Remove non-empty directories</source> <translation></translation> </message> <message numerus="yes"> <location filename="../misc/direrrorsdialog.cpp" line="83"/> <source>%1 item(s) out-of-sync</source> <translation> <numerusform>%1 </numerusform> </translation> </message> <message> <location filename="../misc/direrrorsdialog.cpp" line="113"/> <source>Remove non-empty directories for folder &quot;%1&quot;</source> <translation> &quot;%1&quot; </translation> </message> <message> <location filename="../misc/direrrorsdialog.cpp" line="114"/> <source>Do you really want to remove the following directories:</source> <translation></translation> </message> <message> <location filename="../misc/direrrorsdialog.cpp" line="137"/> <source>Unable to remove the following dirs:</source> <translation></translation> </message> </context> <context> <name>QtGui::FinalWizardPage</name> <message> <location filename="../settings/wizard.cpp" line="1071"/> <source>Waiting for configuration wizard completed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1072"/> <source>Changes are being applied</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1078"/> <source>Configuration wizard completed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1082"/> <source>All changes have been applied</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1084"/> <source>&lt;p&gt;The configuration has been changed successfully. The way Syncthing Tray connects to and starts Syncthing has not changed, though. You may configure this manually in the settings.&lt;/p&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1087"/> <source>&lt;p&gt;The configuration has been changed successfully. You can close the wizard and &lt;a href=&quot;openSyncthing&quot;&gt;open Syncthing&lt;/a&gt; to pair remote devices and add folders for sharing. If you need further help, read the &lt;a href=&quot;openDocs&quot;&gt;documentation to get started&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;To initiate the pairing from another device, the device ID of this Syncthing device is displayed below.&lt;/p&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1096"/> <source>Not all changes could be applied</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="1100"/> <source>You may try to head back one or more steps and try again or finish the wizard and configure Syncthing Tray manually.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::GeneralWebViewOptionPage</name> <message> <location filename="../settings/generalwebviewoptionpage.ui" line="12"/> <source>General</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/generalwebviewoptionpage.ui" line="22"/> <source>Open Syncthing&apos;s UI via</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/generalwebviewoptionpage.ui" line="28"/> <source>Syncthing Tray&apos;s built-in web view</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/generalwebviewoptionpage.ui" line="35"/> <source>Tab in the default web browser</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/generalwebviewoptionpage.ui" line="50"/> <source>Chromium-based browser in &quot;app mode&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/generalwebviewoptionpage.ui" line="57"/> <source>...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1679"/> <source>Custom command to launch Syncthing&apos;s UI - </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1680"/> <source>&lt;p&gt;Enter a custom command to launch Syncthing&apos;s UI. The expression &lt;code&gt;%SYNCTHING_URL%&lt;/code&gt; will be replaced with the Syncthing-URL.&lt;/p&gt;&lt;p&gt;Leave the command empty to use the auto-detection.&lt;/p&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::IconsOptionPage</name> <message> <location filename="../settings/iconsoptionpage.ui" line="12"/> <source>Icons</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="39"/> <source>Use Drag &amp; Drop to re-use a selected color at a different position.</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="46"/> <source>Status icons</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="54"/> <source>Increase the rendering size if you&apos;re using a tray area with extraordinarily big icons.</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="57"/> <source>Rendering size</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="97"/> <source>? px</source> <translation>? </translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="106"/> <source>Stroke width</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="113"/> <source>Thick</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="132"/> <source>Background color 1</source> <translation> 1</translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="142"/> <source>Background color 2</source> <translation> 2</translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="162"/> <source>Preview</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="152"/> <source>Foreground color</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="197"/> <source>Restore previous settings</source> <translation></translation> </message> <message> <location filename="../settings/iconsoptionpage.ui" line="208"/> <source>Use preset</source> <translation></translation> </message> </context> <context> <name>QtGui::IconsOptionPageBase</name> <message> <location filename="../settings/settingsdialog.cpp" line="645"/> <source>UI icons</source> <translation>UI </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="647"/> <source>These icon settings are used within Syncthing Tray&apos;s UI.</source> <translation> Syncthing Tray UI </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="651"/> <source>System icons</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="652"/> <source>These icon settings are used for the system tray icon and the notifications.</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="654"/> <source>Use same settings as for UI icons</source> <translation> UI </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="715"/> <source>Colorful background with gradient (default)</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="721"/> <source>Transparent background and dark foreground (for bright themes)</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="727"/> <source>Transparent background and bright foreground (for dark themes)</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="790"/> <source>Select colors manually (no longer follow system palette)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="791"/> <source>Transparent background and foreground depending on system palette</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="748"/> <source>%1 px (scaled to %2 px)</source> <translation>%1 %2 </translation> </message> </context> <context> <name>QtGui::InternalErrorsDialog</name> <message> <location filename="../misc/internalerrorsdialog.cpp" line="27"/> <source>Internal errors</source> <translation></translation> </message> <message> <location filename="../misc/internalerrorsdialog.cpp" line="28"/> <source>Request URL:</source> <translation> URL</translation> </message> <message> <location filename="../misc/internalerrorsdialog.cpp" line="29"/> <source>Response:</source> <translation></translation> </message> <message> <location filename="../misc/internalerrorsdialog.cpp" line="55"/> <source>Clear errors</source> <translation></translation> </message> <message numerus="yes"> <location filename="../misc/internalerrorsdialog.cpp" line="117"/> <source>%1 error(s) occurred</source> <translation> <numerusform> %1 </numerusform> </translation> </message> </context> <context> <name>QtGui::LauncherOptionPage</name> <message> <location filename="../settings/launcheroptionpage.ui" line="6"/> <source>Syncthing launcher</source> <translation>Syncthing </translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="21"/> <source>Launch Syncthing when starting the tray icon</source> <translation> Syncthing</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="43"/> <source>Syncthing executable</source> <translation>Syncthing </translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="53"/> <source>Arguments</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="63"/> <source>Use built-in Syncthing library</source> <translation> Syncthing </translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="70"/> <source>Set directory for configuration and keys</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="73"/> <source>Config directory</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="83"/> <source>Log level</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="91"/> <source>Debug</source> <translation>Debug</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="96"/> <source>Verbose</source> <translation>Verbose</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="101"/> <source>Info</source> <translation>Info</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="106"/> <source>Warning</source> <translation>Warning</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="111"/> <source>Fatal</source> <translation>Fatal</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="119"/> <source>Set database directory (falls back to config directory if empty)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="122"/> <source>Data directory</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="132"/> <source>Options</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="139"/> <source>Replace ${var} or $var in directories with values from environment</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="149"/> <source>Show start/stop button on tray for local instance</source> <translation>/</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="156"/> <source>Consider process status for notifications and reconnect attempts concerning local instance Don&apos;t reconnect when the process is not running Try to reconnect when starting the process Suppress notification about disconnect when Syncthing has been stopped manually</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="166"/> <source>Stop automatically when network connection is metered</source> <translation type="unfinished"></translation> </message> <message> <source>Consider process status for reconnect attempts to local instance Don&apos;t reconnect when the process is not running Try to reconnect when starting the process</source> <translation type="vanished"> </translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="193"/> <source>Syncthing log (interleaved stdout/stderr)</source> <translation>/</translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="206"/> <source>Apply and launch now</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="223"/> <location filename="../settings/settingsdialog.cpp" line="1276"/> <source>Stop launched instance</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="242"/> <source>No log messages available yet</source> <translation></translation> </message> <message> <location filename="../settings/launcheroptionpage.ui" line="249"/> <source>Ensure latest log is visible</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1135"/> <source>%1-launcher</source> <translation>%1-</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1136"/> <source>Launch %1 when starting the tray icon</source> <translation> %1</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1139"/> <source>%1 executable</source> <translation>%1 </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1140"/> <source>%1 log (interleaved stdout/stderr)</source> <translation>%1 /</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1157"/> <source>Restore default</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1163"/> <source>Show Syncthing releases/downloads</source> <translation> Syncthing /</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1311"/> <source>%1 exited with exit code %2</source> <translation>%1 %2</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1314"/> <source>%1 crashed with exit code %2</source> <translation>%1 %2</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1347"/> <source>failed to start (e.g. executable does not exist or not permission error)</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1350"/> <source>process crashed</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1353"/> <source>timeout error</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1356"/> <source>read error</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1359"/> <source>write error</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1362"/> <source>unknown process error</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1365"/> <source>An error occurred when running %1: %2</source> <translation> %1 : %2</translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1418"/> <source>Kill launched instance</source> <translation></translation> </message> </context> <context> <name>QtGui::MainConfigWizardPage</name> <message> <location filename="../settings/wizard.cpp" line="641"/> <source>Select what configuration to apply</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="642"/> <source>Something when wrong when checking the Syncthing setup.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="643"/> <source>Show details from setup detection</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="719"/> <source>Systemd</source> <translation type="unfinished">Systemd</translation> </message> <message> <location filename="../settings/wizard.cpp" line="751"/> <source>&lt;b&gt;The Syncthing config could be located under &quot;%1&quot; but it seems invalid/incomplete.&lt;/b&gt; Hence Syncthing is assumed to be not running.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="743"/> <source>Looks like Syncthing is not running yet. You can launch it via %1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="743"/> <source> and </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="6"/> <source>General</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="23"/> <source>Configure Syncthing Tray for currently running Syncthing instance</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="30"/> <source>Start installed Syncthing application via Syncthing Tray</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="37"/> <source>Start Syncthing application that is built into Syncthing Tray</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="44"/> <source>Start Syncthing via systemd user-unit (enables and starts the unit %1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="51"/> <source>Start Syncthing via systemd system-unit (enables and starts the unit %1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="58"/> <source>Keep settings for how to connect to Syncthing and start Syncthing as they are</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="65"/> <source>Enable systemd-integration</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/mainconfigwizardpage.ui" line="92"/> <source>Click next to configure Syncthing Tray according to the selected options. You can also reconduct the checks the available options are based on by heading back. If you cancel the wizard, no configuration changes will be made.</source> <translation type="unfinished"></translation> </message> <message> <source>no</source> <translation type="obsolete"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="692"/> <source>Looks like Syncthing is already running and Syncthing Tray can be configured accordingly automatically.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="726"/> <source>Syncthing Tray&apos;s launcher</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="745"/> <source>Looks like Syncthing is not running yet and needs to be installed before Syncthing Tray can be configured.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::NotificationsOptionPage</name> <message> <location filename="../settings/notificationsoptionpage.ui" line="6"/> <source>Notifications</source> <translation></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="16"/> <source>Notify on</source> <translation></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="22"/> <source>disconnect</source> <translation></translation> </message> <message> <source>internal errors</source> <translation type="vanished"></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="29"/> <source>internal errors (if disabled connection errors are only shown within &quot;Internal errors&quot; accessible from the menu!)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="36"/> <source>errors/notifications from Syncthing</source> <translation> Syncthing /</translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="43"/> <source>sync of local folder complete</source> <translation></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="50"/> <source>sync of remote folder complete</source> <translation></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="57"/> <source>new/unknown device connects</source> <translation>/</translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="64"/> <source>remote device shares new/unknown folder</source> <translation>/</translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="71"/> <source>errors of Syncthing launcher</source> <translation>Syncthing </translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="81"/> <source>Notification API</source> <translation> API</translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="87"/> <source>D-Bus &amp;notifications (org.freedesktop.Notifications)</source> <translation>D-Bus &amp; (org.freedesktop.Notifications)</translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="94"/> <source>&amp;Method provided by Qt (might be overridden by QPA plugin)</source> <translation>&amp;Qt QPA </translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="104"/> <source>Misc</source> <translation></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="110"/> <source>Ignore inavailability of Syncthing the specified number of seconds after Syncthing has been started; has only effect if the Syncthing start can be determined which is currently only supported for the local instance started via Systemd or the internal launcher.</source> <translation> Syncthing Syncthing Syncthing Systemd </translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="120"/> <source>don&apos;t ignore</source> <translation></translation> </message> <message> <location filename="../settings/notificationsoptionpage.ui" line="123"/> <source> s</source> <translation> </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="490"/> <source>Configured to use D-Bus notifications but D-Bus notification daemon seems unavailabe.</source> <translation> DBus D-Bus </translation> </message> </context> <context> <name>QtGui::OtherDialogs</name> <message> <location filename="../misc/otherdialogs.cpp" line="60"/> <source>Own device ID</source> <translation> ID</translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="70"/> <source>device ID is unknown</source> <translation> ID </translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="78"/> <source>Copy to clipboard</source> <translation></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="115"/> <source>Remote/global tree of folder &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="148"/> <source>Manage ignore patterns (experimental)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="224"/> <source>Ignore patterns of folder &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="277"/> <source>Do you want to save the changes?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="254"/> <source>Ignore patterns have been changed.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="176"/> <source>Edit manually</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="178"/> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="180"/> <source>No</source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/otherdialogs.cpp" line="261"/> <source>Unable to save ignore patterns: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::SettingsDialog</name> <message> <location filename="../settings/settingsdialog.cpp" line="1754"/> <source>Tray</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1762"/> <source>Web view</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1769"/> <source>Startup</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1771"/> <source>additional tool</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1771"/> <source>Extra launcher</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1794"/> <source>Settings</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1800"/> <source>Start wizard</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::StatusInfo</name> <message> <source>Initializing ...</source> <translation type="vanished"> ...</translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="46"/> <source>Not connected to Syncthing</source> <translation> Syncthing</translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="49"/> <source>Trying to reconnect every %1 ms</source> <translation> %1 </translation> </message> <message> <source>Reconnecting ...</source> <translation type="vanished"> ...</translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="18"/> <source>Initializing </source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="44"/> <source>Connecting to Syncthing </source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="55"/> <source>Reconnecting </source> <translation type="unfinished"></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="62"/> <location filename="../misc/statusinfo.cpp" line="88"/> <source>Synchronization is ongoing</source> <translation></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="63"/> <location filename="../misc/statusinfo.cpp" line="67"/> <source>At least one folder is out of sync</source> <translation></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="71"/> <source>Notifications available</source> <translation></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="76"/> <source>Syncthing is idling</source> <translation>Syncthing </translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="80"/> <source>Syncthing is scanning</source> <translation>Syncthing </translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="84"/> <source>At least one device is paused</source> <translation></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="92"/> <source>At least one remote folder is not in sync</source> <translation></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="96"/> <source>Status is unknown</source> <translation></translation> </message> <message> <location filename="../misc/statusinfo.cpp" line="119"/> <source>Not connected to other devices</source> <translation></translation> </message> <message numerus="yes"> <location filename="../misc/statusinfo.cpp" line="143"/> <source>Connected to %1 devices</source> <translation> <numerusform> %1 </numerusform> </translation> </message> <message numerus="yes"> <source>Connected to %1 and %2 other devices</source> <translation type="vanished"> <numerusform> %1 %2 </numerusform> </translation> </message> <message numerus="yes"> <location filename="../misc/statusinfo.cpp" line="150"/> <source>Connected to %1 and %2</source> <translation> <numerusform> %1 %2</numerusform> </translation> </message> <message numerus="yes"> <location filename="../misc/statusinfo.cpp" line="153"/> <source>Connected to %1</source> <translation> <numerusform> %1</numerusform> </translation> </message> </context> <context> <name>QtGui::SyncthingKiller</name> <message> <location filename="../misc/syncthingkiller.cpp" line="58"/> <source>The process %1 (PID: %2) has been requested to terminate but hasn&apos;t reacted yet. Kill the process? This dialog closes automatically when the process finally terminates.</source> <translation> %1 (PID: %2) </translation> </message> <message> <location filename="../misc/syncthingkiller.cpp" line="64"/> <source>Keep running</source> <translation></translation> </message> <message> <location filename="../misc/syncthingkiller.cpp" line="65"/> <source>Kill process</source> <translation></translation> </message> </context> <context> <name>QtGui::SystemdOptionPage</name> <message> <location filename="../settings/systemdoptionpage.ui" line="6"/> <source>Systemd</source> <translation>Systemd</translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="21"/> <source>Show start/stop button on tray for local instance when systemd is available</source> <translation> systemd /</translation> </message> <message> <source>Consider systemd unit status for reconnect attempts to local instance Don&apos;t reconnect when unit not active/running Try to reconnect when unit becomes active/running</source> <translation type="vanished"> systemd / /</translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="28"/> <source>Consider systemd unit status for notifications and reconnect attempts concerning local instance Don&apos;t reconnect when unit not active/running Try to reconnect when unit becomes active/running Suppress notification about disconnect when Syncthing has been stopped manually</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="38"/> <source>Stop automatically when network connection is metered</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="79"/> <source>Syncthing unit</source> <translation>Syncthing </translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="89"/> <source>System unit</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="102"/> <source>Description</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="117"/> <location filename="../settings/systemdoptionpage.ui" line="172"/> <location filename="../settings/systemdoptionpage.ui" line="261"/> <location filename="../settings/settingsdialog.cpp" line="1578"/> <location filename="../settings/settingsdialog.cpp" line="1587"/> <source>unknown</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="132"/> <source>Current status</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="185"/> <source>Start</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="202"/> <source>Stop</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="221"/> <source>Unit file state</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="274"/> <source>Enable</source> <translation></translation> </message> <message> <location filename="../settings/systemdoptionpage.ui" line="291"/> <source>Disable</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1454"/> <source>Reload all unit files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1513"/> <source>It is not possible to show the start/stop button for the systemd service and the internal launcher at the same time. The systemd service precedes.</source> <translation> systemd / systemd </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1519"/> <source>It is not possible to consider the systemd service and the internal launcher for reconnects at the same time. The systemd service precedes.</source> <translation> systemd systemd </translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1551"/> <source>specified unit is either inactive or doesn&apos;t exist</source> <translation></translation> </message> <message> <location filename="../settings/settingsdialog.cpp" line="1573"/> <source>since </source> <translation> </translation> </message> </context> <context> <name>QtGui::TextViewDialog</name> <message> <location filename="../misc/textviewdialog.cpp" line="62"/> <location filename="../misc/textviewdialog.cpp" line="71"/> <source>Log</source> <translation></translation> </message> </context> <context> <name>QtGui::WebPage</name> <message> <source>Select path for Syncthing directory ...</source> <translation type="vanished"> Syncthing ...</translation> </message> <message> <location filename="../webview/webpage.cpp" line="493"/> <source>Select path for Syncthing directory </source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::WebViewDialog</name> <message> <location filename="../webview/webviewdialog.cpp" line="46"/> <source>Syncthing</source> <translation>Syncthing</translation> </message> </context> <context> <name>QtGui::WebViewOptionPage</name> <message> <source>General</source> <translation type="vanished"></translation> </message> <message> <source>Usage</source> <translation type="vanished"></translation> </message> <message> <source>Disable web view (open regular web browser instead)</source> <translation type="vanished"></translation> </message> <message> <source>Zoom factor</source> <translation type="vanished"></translation> </message> <message> <source>Hiding</source> <translation type="vanished"></translation> </message> <message> <source>Keep web view running when currently not shown</source> <translation type="vanished"></translation> </message> <message> <source>Syncthing Tray has not been built with vieb view support utilizing either Qt WebKit or Qt WebEngine. The Web UI will be opened in the default web browser instead.</source> <translation type="vanished">Syncthing Tray Qt WebKit Qt WebEngine UI </translation> </message> </context> <context> <name>QtGui::WelcomeWizardPage</name> <message> <location filename="../settings/wizard.cpp" line="449"/> <source>Welcome to Syncthing Tray</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="450"/> <source>It looks like you&apos;re launching Syncthing Tray for the first time.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="451"/> <source>You must configure how to connect to Syncthing and how to launch Syncthing (if that&apos;s wanted) when using Syncthing Tray the first time.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="454"/> <source>Wizard&apos;s start page</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="455"/> <source>This wizard will help you configuring Syncthing Tray.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="460"/> <source>Start guided setup</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="462"/> <source>Allows to configure Syncthing Tray automatically for the local Syncthing instance and helps you starting Syncthing if wanted.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="470"/> <source>Configure connection and launcher settings manually</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="472"/> <source>Head back to settings to configure connection and launcher manually</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="475"/> <source>Note that the connection settings allow importing URL, credentials and API-key from the local Syncthing configuration.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="491"/> <source>Show Syncthing&apos;s documentation</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="492"/> <source>It contains general information about configuring Syncthing.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="498"/> <source>Show Syncthing Tray&apos;s README</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="499"/> <source>It contains documentation about this GUI integration specifically.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QtGui::Wizard</name> <message> <location filename="../settings/wizard.cpp" line="74"/> <source>Setup wizard - </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="218"/> <source>The internal launcher has not been initialized.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="230"/> <source>The service handler has not been initialized.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="263"/> <source>Unable to locate Syncthing config file.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="265"/> <source>Located Syncthing config file: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="267"/> <source>Syncthing config file looks ok.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="269"/> <source>Syncthing config file looks invalid/incomplete.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="272"/> <source>Syncthing configuration:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="280"/> <source>Could connect to Syncthing under: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="281"/> <source>Syncthing version: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="282"/> <source>Syncthing device ID: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="283"/> <source>Syncthing status: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="285"/> <source>Additional Syncthing status info: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="320"/> <source>Autostart:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="321"/> <source>Currently %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="321"/> <source>enabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="321"/> <source>disabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="323"/> <source>Points to &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="365"/> <source>The Syncthing process exited prematurely. </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="378"/> <source>The Syncthing service stopped prematurely. </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="402"/> <source>Ran into timeout while waiting for Syncthing to create config file. Maybe Syncthing created its config file under an unexpected location. </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="413"/> <source>Checkout Syncthing&apos;s log for details.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="417"/> <source> It can be accessed within the &lt;a href=&quot;openLauncherSettings&quot;&gt;launcher settings&lt;/a&gt;.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="422"/> <source> It is normally written to the system journal (and can be accessed via e.g. journalctl).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="290"/> <source>API connection:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="293"/> <source>API connection errors:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="300"/> <source>State of user unit file &quot;%1&quot;: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="301"/> <source>State of system unit file &quot;%1&quot;: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="298"/> <source>Systemd:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="288"/> <source>Could NOT connect to Syncthing under: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="304"/> <source>No available</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="310"/> <source>Could test-launch Syncthing successfully, exit code: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="311"/> <source>Syncthing version returned from test-launch: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="313"/> <source>Unable to test-launch Syncthing: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="315"/> <source>Built-in Syncthing available: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="315"/> <source>yes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="315"/> <source>no</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="316"/> <source>Launcher:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../settings/wizard.cpp" line="331"/> <source>Details from setup detection - </source> <translation type="unfinished"></translation> </message> </context> <context> <name>Settings::Connection</name> <message> <location filename="../settings/settings.cpp" line="679"/> <source>Backup of %1 (created by wizard)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Settings::restore</name> <message> <location filename="../settings/settings.cpp" line="330"/> <source>Unable to load certificate &quot;%1&quot; when restoring settings.</source> <translation> &quot;%1&quot;</translation> </message> </context> </TS> ```
/content/code_sandbox/syncthingwidgets/translations/syncthingwidgets_zh_CN.ts
xml
2016-08-24T22:46:19
2024-08-16T13:39:56
syncthingtray
Martchus/syncthingtray
1,558
20,613
```xml /// /// /// /// path_to_url /// /// Unless required by applicable law or agreed to in writing, software /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// import { Component, Inject, InjectionToken, Injector, Input, OnDestroy, OnInit, StaticProvider, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { WidgetContext } from '@home/models/widget-component.models'; import { UtilsService } from '@core/services/utils.service'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { cloneDateRangeNavigatorModel, DateIntervalEntry, dateIntervalsMap, DateRangeNavigatorModel, DateRangeNavigatorSettings, getFormattedDate } from '@home/components/widget/lib/date-range-navigator/date-range-navigator.models'; import { KeyValue } from '@angular/common'; import * as _moment from 'moment'; import { ConnectedPosition, Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay'; import { ComponentPortal } from '@angular/cdk/portal'; import { MatSelect } from '@angular/material/select'; import { Subscription } from 'rxjs'; import { HistoryWindowType, TimewindowType } from '@shared/models/time/time.models'; import { isDefined } from '@core/utils'; @Component({ selector: 'tb-date-range-navigator-widget', templateUrl: './date-range-navigator.component.html', styleUrls: ['./date-range-navigator.component.scss'] }) export class DateRangeNavigatorWidgetComponent extends PageComponent implements OnInit, OnDestroy { @Input() ctx: WidgetContext; @ViewChild('datePicker', {static: true}) datePickerSelect: MatSelect; settings: DateRangeNavigatorSettings; datesMap = dateIntervalsMap; advancedModel: DateRangeNavigatorModel = {}; selectedDateInterval: number; customInterval: DateIntervalEntry; selectedStepSize: number; private firstUpdate = true; private dashboardTimewindowChangedSubscription: Subscription; originalOrder = (a: KeyValue<string, DateIntervalEntry>, b: KeyValue<string, DateIntervalEntry>): number => { return 0; } constructor(private utils: UtilsService, private overlay: Overlay, private viewContainerRef: ViewContainerRef, protected store: Store<AppState>) { super(store); } ngOnInit(): void { this.settings = this.ctx.settings; this.settings.useSessionStorage = isDefined(this.settings.useSessionStorage) ? this.settings.useSessionStorage : true; let selection; if (this.settings.useSessionStorage) { selection = this.readFromStorage('date-range'); } if (selection) { this.advancedModel = { chosenLabel: selection.name, startDate: _moment(selection.start), endDate: _moment(selection.end) }; } else { const end = new Date(); end.setHours(23, 59, 59, 999); this.advancedModel = { startDate: _moment((end.getTime() + 1) - this.datesMap[this.settings.initialInterval || 'week'].ts), endDate: _moment(end.getTime()) }; this.advancedModel.chosenLabel = getFormattedDate(this.advancedModel); } this.selectedStepSize = this.datesMap[this.settings.stepSize || 'day'].ts; this.widgetContextTimewindowSync(); this.dashboardTimewindowChangedSubscription = this.ctx.dashboard.dashboardTimewindowChanged.subscribe(() => { this.widgetContextTimewindowSync(); }); } ngOnDestroy(): void { if (this.dashboardTimewindowChangedSubscription) { this.dashboardTimewindowChangedSubscription.unsubscribe(); this.dashboardTimewindowChangedSubscription = null; } } openNavigatorPanel($event: Event) { if ($event) { $event.stopPropagation(); } this.datePickerSelect.close(); const target = $event.target || $event.srcElement || $event.currentTarget; const config = new OverlayConfig(); config.backdropClass = 'cdk-overlay-transparent-backdrop'; config.hasBackdrop = true; config.panelClass = 'tb-date-range-navigator-panel'; const connectedPosition: ConnectedPosition = { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top' }; config.positionStrategy = this.overlay.position().flexibleConnectedTo(target as HTMLElement) .withPositions([connectedPosition]); const overlayRef = this.overlay.create(config); overlayRef.backdropClick().subscribe(() => { overlayRef.dispose(); }); const providers: StaticProvider[] = [ { provide: DATE_RANGE_NAVIGATOR_PANEL_DATA, useValue: { model: cloneDateRangeNavigatorModel(this.advancedModel), settings: this.settings, onChange: model => { this.advancedModel = model; this.triggerChange(); } } as DateRangeNavigatorPanelData }, { provide: OverlayRef, useValue: overlayRef } ]; const injector = Injector.create({parent: this.viewContainerRef.injector, providers}); overlayRef.attach(new ComponentPortal(DateRangeNavigatorPanelComponent, this.viewContainerRef, injector)); this.ctx.detectChanges(); } private widgetContextTimewindowSync() { if (!this.firstUpdate) { this.updateAdvancedModel(); } this.updateDateInterval(); if (this.settings.useSessionStorage) { this.updateStorageDate(); } if (this.firstUpdate) { this.firstUpdate = false; this.updateTimewindow(this.advancedModel.startDate.valueOf(), this.advancedModel.endDate.valueOf()); } this.ctx.detectChanges(); } private updateAdvancedModel() { const timewindow = this.ctx.dashboardTimewindow; if (timewindow.selectedTab === TimewindowType.HISTORY && timewindow.history.historyType === HistoryWindowType.FIXED) { const fixedTimewindow = timewindow.history.fixedTimewindow; this.advancedModel.startDate = _moment(fixedTimewindow.startTimeMs); this.advancedModel.endDate = _moment(fixedTimewindow.endTimeMs); this.advancedModel.chosenLabel = getFormattedDate(this.advancedModel); } } private updateTimewindow(startTime: number, endTime: number) { this.ctx.dashboard.onUpdateTimewindow(startTime, endTime, 10, true); } private updateDateInterval() { const interval = this.advancedModel.endDate.valueOf() - this.advancedModel.startDate.valueOf(); for (const key of Object.keys(this.datesMap)) { if (Object.prototype.hasOwnProperty.call(this.datesMap, key)) { if (this.datesMap[key].ts === interval || this.datesMap[key].ts === interval + 1 || this.datesMap[key].ts === interval - 1) { this.selectedDateInterval = this.datesMap[key].ts; this.customInterval = undefined; return; } } } this.selectedDateInterval = interval; this.customInterval = {ts: interval, label: 'Custom interval'}; } triggerChange() { this.updateTimewindow(this.advancedModel.startDate.valueOf(), this.advancedModel.endDate.valueOf()); } changeInterval() { const endTime = this.ctx.dashboard.dashboardTimewindow.history ? this.ctx.dashboard.dashboardTimewindow.history.fixedTimewindow.endTimeMs : this.advancedModel.endDate.valueOf(); this.updateTimewindow(endTime - this.selectedDateInterval / 2, endTime + this.selectedDateInterval / 2); } goBack() { this.step(-1); } goForth() { this.step(1); } private step(direction: number) { const startTime = this.ctx.dashboard.dashboardTimewindow.history ? this.ctx.dashboard.dashboardTimewindow.history.fixedTimewindow.startTimeMs : this.advancedModel.startDate.valueOf(); const endTime = this.ctx.dashboard.dashboardTimewindow.history ? this.ctx.dashboard.dashboardTimewindow.history.fixedTimewindow.endTimeMs : this.advancedModel.endDate.valueOf(); this.updateTimewindow(startTime + this.selectedStepSize * direction, endTime + this.selectedStepSize * direction); } private readFromStorage(itemKey: string): any { if (window.sessionStorage.getItem(itemKey)) { const selection = JSON.parse(window.sessionStorage.getItem(itemKey)); selection.start = new Date(parseInt(selection.start, 10)); selection.end = new Date(parseInt(selection.end, 10)); return selection; } return undefined; } private updateStorageDate() { this.saveIntoStorage('date-range', { start: this.advancedModel.startDate.valueOf(), end: this.advancedModel.endDate.valueOf(), name: this.advancedModel.chosenLabel }); } private saveIntoStorage(keyName: string, selection: any) { if (selection) { window.sessionStorage.setItem(keyName, JSON.stringify(selection)); } } } const DATE_RANGE_NAVIGATOR_PANEL_DATA = new InjectionToken<any>('DateRangeNavigatorPanelData'); export interface DateRangeNavigatorPanelData { model: DateRangeNavigatorModel; settings: DateRangeNavigatorSettings; onChange: (model: DateRangeNavigatorModel) => void; } @Component({ selector: 'tb-date-range-navigator-panel', templateUrl: './date-range-navigator-panel.component.html', styleUrls: ['./date-range-navigator-panel.component.scss'], encapsulation: ViewEncapsulation.None }) export class DateRangeNavigatorPanelComponent { settings: DateRangeNavigatorSettings; model: DateRangeNavigatorModel; locale: any = {}; constructor(@Inject(DATE_RANGE_NAVIGATOR_PANEL_DATA) public data: DateRangeNavigatorPanelData, private overlayRef: OverlayRef) { this.model = data.model; this.settings = data.settings; this.locale.firstDay = this.settings.firstDayOfWeek || 1; this.locale.daysOfWeek = _moment.weekdaysMin(); this.locale.monthNames = _moment.monthsShort(); } choosedDate($event) { this.model = $event; this.model.chosenLabel = getFormattedDate(this.model); if (this.settings.autoConfirm) { this.data.onChange(this.model); this.overlayRef.dispose(); } } apply() { this.data.onChange(this.model); this.overlayRef.dispose(); } } ```
/content/code_sandbox/ui-ngx/src/app/modules/home/components/widget/lib/date-range-navigator/date-range-navigator.component.ts
xml
2016-12-01T09:33:30
2024-08-16T19:58:25
thingsboard
thingsboard/thingsboard
16,820
2,232
```xml import { PayloadAction, createSlice } from "@reduxjs/toolkit"; import { User, getUserList } from "../services/jsonPlaceholder"; import { AppThunk, AppState } from "."; interface UserList { readyStatus: string; items: User[]; error: string | null; } export const initialState: UserList = { readyStatus: "invalid", items: [], error: null, }; const userList = createSlice({ name: "userList", initialState, reducers: { getRequesting: (state: UserList) => { state.readyStatus = "request"; }, getSuccess: (state, { payload }: PayloadAction<User[]>) => { state.readyStatus = "success"; state.items = payload; }, getFailure: (state, { payload }: PayloadAction<string>) => { state.readyStatus = "failure"; state.error = payload; }, }, }); export default userList.reducer; export const { getRequesting, getSuccess, getFailure } = userList.actions; export const fetchUserList = (): AppThunk => async (dispatch) => { dispatch(getRequesting()); const { error, data } = await getUserList(); if (error) { dispatch(getFailure(error.message)); } else { dispatch(getSuccess(data as User[])); } }; const shouldFetchUserList = (state: AppState) => state.userList.readyStatus !== "success"; export const fetchUserListIfNeed = (): AppThunk => (dispatch, getState) => { if (shouldFetchUserList(getState())) return dispatch(fetchUserList()); return null; }; ```
/content/code_sandbox/src/store/userList.ts
xml
2016-08-29T10:26:56
2024-08-12T08:38:34
react-cool-starter
wellyshen/react-cool-starter
1,309
343
```xml <vector xmlns:android="path_to_url" android:width="24dp" android:height="24dp" android:tint="#FFFFFF" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z" /> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_about_us_24dp.xml
xml
2016-02-22T10:00:46
2024-08-16T15:37:50
Images-to-PDF
Swati4star/Images-to-PDF
1,174
157
```xml // export * from './vsc'; // // export * from './vscodePath'; export * from './utils'; // export * from './vsHelp'; ```
/content/code_sandbox/src/utils/index.ts
xml
2016-05-15T09:50:55
2024-08-16T02:15:39
vscode-background
shalldie/vscode-background
1,281
34
```xml // See LICENSE.txt for license information. import React, {useCallback, useMemo} from 'react'; import {useIntl} from 'react-intl'; import {FlatList, Text} from 'react-native'; import ChannelItem from '@components/channel_item'; import {HOME_PADDING} from '@constants/view'; import {useTheme} from '@context/theme'; import {useIsTablet} from '@hooks/device'; import {changeOpacity, makeStyleSheetFromTheme} from '@utils/theme'; import {typography} from '@utils/typography'; import Empty from './empty_state'; import type ChannelModel from '@typings/database/models/servers/channel'; const getStyleSheet = makeStyleSheetFromTheme((theme: Theme) => ({ empty: { alignItems: 'center', flexGrow: 1, justifyContent: 'center', }, heading: { color: changeOpacity(theme.sidebarText, 0.64), ...typography('Heading', 75), textTransform: 'uppercase', paddingVertical: 8, marginTop: 12, ...HOME_PADDING, }, })); type UnreadCategoriesProps = { onChannelSwitch: (channel: Channel | ChannelModel) => void; onlyUnreads: boolean; unreadChannels: ChannelModel[]; unreadThreads: {unreads: boolean; mentions: number}; } const extractKey = (item: ChannelModel) => item.id; const UnreadCategories = ({onChannelSwitch, onlyUnreads, unreadChannels, unreadThreads}: UnreadCategoriesProps) => { const intl = useIntl(); const theme = useTheme(); const isTablet = useIsTablet(); const styles = getStyleSheet(theme); const renderItem = useCallback(({item}: {item: ChannelModel}) => { return ( <ChannelItem channel={item} onPress={onChannelSwitch} testID='channel_list.category.unreads.channel_item' shouldHighlightActive={true} shouldHighlightState={true} isOnHome={true} /> ); }, [onChannelSwitch]); const showEmptyState = onlyUnreads && !unreadChannels.length; const containerStyle = useMemo(() => { return [ showEmptyState && !isTablet && styles.empty, ]; }, [styles, showEmptyState, isTablet]); const showTitle = !onlyUnreads || (onlyUnreads && !showEmptyState); const EmptyState = showEmptyState && !isTablet ? ( <Empty onlyUnreads={onlyUnreads}/> ) : undefined; if (!unreadChannels.length && !unreadThreads.mentions && !unreadThreads.unreads && !onlyUnreads) { return null; } return ( <> {showTitle && <Text style={styles.heading} > {intl.formatMessage({id: 'mobile.channel_list.unreads', defaultMessage: 'UNREADS'})} </Text> } <FlatList contentContainerStyle={containerStyle} data={unreadChannels} renderItem={renderItem} keyExtractor={extractKey} ListEmptyComponent={EmptyState} removeClippedSubviews={true} /> </> ); }; export default UnreadCategories; ```
/content/code_sandbox/app/screens/home/channel_list/categories_list/categories/unreads/unreads.tsx
xml
2016-10-07T16:52:32
2024-08-16T12:08:38
mattermost-mobile
mattermost/mattermost-mobile
2,155
683
```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <groupId>com.didispace</groupId> <artifactId>chapter6-3</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <description>InfluxDB</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.influxdb</groupId> <artifactId>influxdb-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ```
/content/code_sandbox/2.x/chapter6-3/pom.xml
xml
2016-08-21T03:39:06
2024-08-16T17:54:09
SpringBoot-Learning
dyc87112/SpringBoot-Learning
15,676
405
```xml import configureStore from 'redux-mock-store'; import reduxThunk from 'redux-thunk'; import { saveMemberAction } from './saveMember'; import { memberFormValidation } from '../memberFormValidation'; import { MemberEntity } from '../../../model/memberEntity'; const middlewares = [reduxThunk]; const getMockStore = configureStore(middlewares); describe('member/actions/saveMember tests', () => { it('should call to apiMembers.SAVE_MEMBER with value', (done) => { // Arrange const member: MemberEntity = { id: 12345, avatar_url: "avatar test", login: "login test" } const validateFormStub = jest.spyOn(memberFormValidation, 'validateForm'); //act const store = getMockStore(); store.dispatch<any>(saveMemberAction(member)) .then(() => { expect(validateFormStub).toHaveBeenCalledWith(member); done(); }); }); it('should call to apiMembers.SAVE_MEMBER with no value. Returning error', (done) => { // Arrange const member: MemberEntity = { id: 12345, avatar_url: "avatar test", login: "login test" } const fieldName = "id"; const value = undefined; const validateFormStub = jest.spyOn(memberFormValidation, 'validateForm').mockRejectedValue(new Error("some error message")); //act const store = getMockStore(); store.dispatch<any>(saveMemberAction(member)) .catch((e: Error) => { expect(validateFormStub).toHaveBeenCalledWith(member); expect(e.message).toEqual("some error message"); done(); }); }); }); ```
/content/code_sandbox/old_class_components_samples/13 TestComponents/src/components/member/actions/saveMember.spec.ts
xml
2016-02-28T11:58:58
2024-07-21T08:53:34
react-typescript-samples
Lemoncode/react-typescript-samples
1,846
359
```xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/game_board" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="@dimen/margine_top" > <ImageView android:id="@+id/time_bar_image" android:layout_width="@dimen/clock_width" android:layout_height="@dimen/clock_height" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="@dimen/clock_margin_right" android:src="@drawable/time_bar" /> <TextView android:id="@+id/time_bar_text" android:layout_width="@dimen/clock_width" android:layout_height="@dimen/clock_height" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="@dimen/clock_text_margin_right" android:gravity="center" android:shadowColor="#2eaed9" android:shadowDx="4" android:shadowDy="4" android:shadowRadius="4" android:text="00:60" android:textColor="#FFFFFF" android:textSize="@dimen/clock_text_size" /> </RelativeLayout> <FrameLayout android:id="@+id/game_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > </FrameLayout> </LinearLayout> </FrameLayout> ```
/content/code_sandbox/subs/game/src/main/res/layout/game_fragment.xml
xml
2016-08-08T08:52:10
2024-08-12T19:24:13
AndroidAnimationExercise
REBOOTERS/AndroidAnimationExercise
1,868
401
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /** * Interface describing `dsapxsum`. */ interface Routine { /** * Adds a constant to each single-precision floating-point strided array element and computes the sum using extended accumulation and returning an extended precision result. * * @param N - number of indexed elements * @param alpha - constant * @param x - input array * @param stride - stride length * @returns sum * * @example * var Float32Array = require( '@stdlib/array/float32' ); * * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); * * var v = dsapxsum( x.length, 5.0, x, 1 ); * // returns 16.0 */ ( N: number, alpha: number, x: Float32Array, stride: number ): number; /** * Adds a constant to each single-precision floating-point strided array element and computes the sum using extended accumulation and alternative indexing semantics and returning an extended precision result. * * @param N - number of indexed elements * @param alpha - constant * @param x - input array * @param stride - stride length * @param offset - starting index * @returns sum * * @example * var Float32Array = require( '@stdlib/array/float32' ); * * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); * * var v = dsapxsum.ndarray( x.length, 5.0, x, 1, 0 ); * // returns 16.0 */ ndarray( N: number, alpha: number, x: Float32Array, stride: number, offset: number ): number; } /** * Adds a constant to each single-precision floating-point strided array element and computes the sum using extended accumulation and returning an extended precision result. * * @param N - number of indexed elements * @param alpha - constant * @param x - input array * @param stride - stride length * @returns sum * * @example * var Float32Array = require( '@stdlib/array/float32' ); * * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); * * var v = dsapxsum( x.length, 5.0, x, 1 ); * // returns 16.0 * * @example * var Float32Array = require( '@stdlib/array/float32' ); * * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); * * var v = dsapxsum.ndarray( x.length, 5.0, x, 1, 0 ); * // returns 16.0 */ declare var dsapxsum: Routine; // EXPORTS // export = dsapxsum; ```
/content/code_sandbox/lib/node_modules/@stdlib/blas/ext/base/dsapxsum/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
725
```xml import * as React from 'react'; import { render } from '@testing-library/react'; import List from '../index'; describe('List', () => { it('renders correctly', () => { const { container } = render( <List> <List.Item title="Item 1" /> <List.Item title="Item 2" /> </List>, ); expect(container).toMatchSnapshot(); }); }); ```
/content/code_sandbox/packages/zarm/src/list/__tests__/index.test.tsx
xml
2016-07-13T11:45:37
2024-08-12T19:23:48
zarm
ZhongAnTech/zarm
1,707
90
```xml import * as React from 'react'; import { useDispatch } from 'react-redux'; import * as Suggestions from 'shared/models/HighLevelSearch/Suggestions'; import { getSuggestionsFromLocalStorage } from '../suggestionsFromLocalStorage'; import * as actions from './actions'; const useSuggestionsFromLocalStorage = (initialQuery: string) => { const dispatch = useDispatch(); const [, forceUpdate] = React.useReducer((x) => x + 1, 0); const suggestions = getSuggestionsFromLocalStorage(); React.useEffect(() => { actions.addNewRecentSearch(initialQuery); }, [initialQuery]); return { suggestions, addFavoriteToSuggestions: (recentSearch: Suggestions.RecentSearch) => { dispatch(actions.addFavoriteToSuggestions(recentSearch)); forceUpdate(); }, removeFavoriteFromSuggestions: (favorite: Suggestions.Favorite) => { dispatch(actions.removeFavoriteFromSuggestions(favorite)); forceUpdate(); }, }; }; export default useSuggestionsFromLocalStorage; ```
/content/code_sandbox/webapp/client/src/features/highLevelSearch/store/useSuggestionsFromLocalStorage.tsx
xml
2016-10-19T01:07:26
2024-08-14T03:53:55
modeldb
VertaAI/modeldb
1,689
209
```xml <!-- Description: feed tagline --> <feed version="0.3" xmlns="path_to_url#"> <tagline>Feed Tagline</tagline> </feed> ```
/content/code_sandbox/testdata/translator/atom/feed_description_-_atom03_feed_tagline.xml
xml
2016-01-23T02:44:34
2024-08-16T15:16:03
gofeed
mmcdole/gofeed
2,547
39
```xml export { registerDataTransform } from './register-data-transform'; export { registerShape } from './register-shape'; export { chartChangeSize } from './chart-change-size'; export { chartAutoFit } from './chart-auto-fit'; export { markChangeData } from './mark-change-data'; export { markChangeDataTooltip } from './mark-change-data-tooltip'; export { chartOnItemElement } from './chart-on-item-element'; export { chartOnSeriesElement } from './chart-on-series-element'; export { chartAxisLabelFormatter } from './chart-axis-label-formatter'; export { chartHOMMark } from './chart-hom-mark'; export { chartOptions } from './chart-options'; export { viewFacetCircle } from './view-facetCircle'; export { chartEmitLegendFilter } from './chart-emit-legend-filter'; export { chartChangeSizePolar } from './chart-change-size-polar'; export { chartChangeDataFacet } from './chart-change-data-facet'; export { chartRenderClearAnimation } from './chart-render-clear-animation'; export { chartOnBrushFilter } from './chart-on-brush-filter'; export { chartOptionsChangeData } from './chart-options-change-data'; export { chartOnFocusContext } from './chart-on-focus-context'; export { chartEmitItemTooltip } from './chart-emit-item-tooltip'; export { chartEmitSeriesTooltip } from './chart-emit-series-tooltip'; export { chartEmitPieTooltip } from './chart-emit-pie-tooltip'; export { chartRenderUpdateAttributes } from './chart-render-update-attributes'; export { chartRenderUpdateNonAnimation } from './chart-render-update-non-animation'; export { chartEmitBrushHighlightX } from './chart-emit-brush-highlight-x'; export { chartRenderBrushEnd } from './chart-render-brush-end'; export { chartChangeDataEmpty } from './chart-change-data-empty'; export { chartEmitSliderFilter } from './chart-emit-slider-filter'; export { chartEmitElementHighlight } from './chart-emit-element-highlight'; export { chartEmitElementSelect } from './chart-emit-element-select'; export { chartEmitElementSelectSingle } from './chart-emit-element-select-single'; export { chartEmitLegendHighlight } from './chart-emit-legend-highlight'; export { chartEmitBrushHighlightAxisVertical } from './chart-emit-brush-highlight-axis-vertical'; export { chartEmitBrushHighlightAxisHorizontal } from './chart-emit-brush-highlight-axis-horizontal'; export { chartEmitBrushHighlightAxisCross } from './chart-emit-brush-highlight-axis-cross'; export { chartEmitScrollbarFilter } from './chart-emit-scrollbar-filter'; export { chartOptionsCompositeMark } from './chart-options-composite-mark'; export { chartEmitItemTooltipHideContent } from './chart-emit-item-tooltip-hide-content'; export { chartEmitClickTooltip } from './chart-emit-click-tooltip'; export { chartChangeDataLegend } from './chart-change-data-legend'; export { chartTooltipMultiChart } from './chart-tooltip-multi-chart'; export { chartOnTextClick } from './chart-on-text-click'; export { chartOnComponentClick } from './chart-on-component-click'; export { chartRenderEvent } from './chart-render-event'; export { chartOnBrushHighlightTooltip } from './chart-on-brush-highlight-tooltip'; export { chartChangeSizeCustomShape } from './chart-change-size-custom-shape'; export { chartOptionsCallbackChildren } from './chart-options-callback-children'; export { chartAutoFitSlider } from './chart-auto-fit-slider'; export { chart3d } from './chart-3d'; export { chartOnScrollbarFilter } from './chart-on-scrollbar-filter'; export { chartAutoFitHeight } from './chart-auto-fit-height'; export { chartAutoFitWidth } from './chart-auto-fit-width'; export { chartOnLabelClick } from './chart-on-label-click'; export { chartChangeSizeLabelRotate } from './chart-change-size-label-rotate'; export { chartWordCloudCanvas } from './chart-word-cloud-canvas'; ```
/content/code_sandbox/__tests__/plots/api/index.ts
xml
2016-05-26T09:21:04
2024-08-15T16:11:17
G2
antvis/G2
12,060
836
```xml import { packageName } from '../../util/pkg-name'; import { yesOption } from '../../util/arg-common'; export const removeCommand = { name: 'remove', description: 'Remove a deployment by name or id.', arguments: [ { name: '...deploymentId|deploymentName', required: true, }, ], options: [ { ...yesOption, description: 'Skip confirmation', }, { name: 'safe', shorthand: 's', type: Boolean, deprecated: false, description: 'Skip deployments with an active alias', }, { name: 'hard', shorthand: null, type: Boolean, deprecated: false }, ], examples: [ { name: 'Remove a deployment identified by `deploymentId`', value: `${packageName} remove my-app`, }, { name: 'Remove all deployments with name `my-app`', value: `${packageName} remove deploymentId`, }, { name: 'Remove two deployments with IDs `eyWt6zuSdeus` and `uWHoA9RQ1d1o`', value: `${packageName} remove eyWt6zuSdeus uWHoA9RQ1d1o`, }, ], } as const; ```
/content/code_sandbox/packages/cli/src/commands/remove/command.ts
xml
2016-09-09T01:12:08
2024-08-16T17:39:45
vercel
vercel/vercel
12,545
282
```xml <?xml version="1.0" encoding="utf-8"?> <?define Version="2.0.8.4000" ?> <?define Manufacturer="Digimezzo" ?> <?define Product="Dopamine" ?> <?define ProductCab="Dopamine.cab" ?> <?define DowngradeMessage="A newer version of this application is already installed. If you are sure you want to downgrade, remove the existing installation via Programs and Features." ?> <?define BannerBmp="Dopamine.BannerBmp.bmp" ?> <?define DialogBmp="Dopamine.DialogBmp.bmp" ?> <?define UpgradeCode="744d2eee-0923-4e96-9efd-1ee5f13db75b"?> <Wix xmlns="path_to_url"> <Product Id="*" Name="$(var.Product)" Language="1033" Version="$(var.Version)" Manufacturer="$(var.Manufacturer)" UpgradeCode="$(var.UpgradeCode)"> <!-- Packaging --> <!-- ========= --> <Package Description="$(var.Product)" Comments="$(var.Product)" InstallerVersion="500" Compressed="yes" /> <Media Id="1" Cabinet="$(var.ProductCab)" EmbedCab="yes" /> <MajorUpgrade AllowSameVersionUpgrades="yes" DowngradeErrorMessage="$(var.DowngradeMessage)" /> <InstallExecuteSequence> <Custom Action="KillApplication" After="LaunchConditions"/> </InstallExecuteSequence> <WixVariable Id="WixUIBannerBmp" Value="$(var.BannerBmp)" /> <WixVariable Id="WixUIDialogBmp" Value="$(var.DialogBmp)" /> <!-- Icons --> <!-- ===== --> <!-- This just defines an icon that can be used anywhere else --> <Icon Id="$(var.Product).ico" SourceFile="$(var.Product).exe" /> <!-- Properties --> <!-- ========== --> <Property Id="WixShellExecTarget" Value="[#$(var.Product).exe]" /> <Property Id="QtExecCmdLine" Value='"taskkill.exe" /f /im $(var.Product).exe'/> <Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT" Value="Launch $(var.Product)" /> <Property Id="WIXUI_INSTALLDIR" Value="INSTALLFOLDER" /> <!-- This adds an icon for Add/Remove Programs. The Value is the Id of the Icon defined above --> <Property Id="ARPPRODUCTICON" Value="$(var.Product).ico" /> <!-- Custom actions --> <!-- ============== --> <CustomAction Id="LaunchApplication" BinaryKey="WixCA" DllEntry="WixShellExec" Impersonate="yes" /> <CustomAction Id="KillApplication" BinaryKey="WixCA" DllEntry="CAQuietExec" Execute="immediate" Return="ignore"/> <!-- User interface --> <!-- ============== --> <UI> <UIRef Id="DonateWixUI_InstallDir" /> <!-- Skip licence dialog (next 2 lines) --> <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="InstallDirDlg" Order="2">1</Publish> <Publish Dialog="InstallDirDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="2">1</Publish> <!-- Launch application --> <Publish Dialog="DonateExitDialog" Control="Finish" Event="DoAction" Value="LaunchApplication">WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 and NOT Installed</Publish> </UI> <!-- Directory tree --> <!-- ============== --> <Directory Id="TARGETDIR" Name="SourceDir"> <!-- Start Menu --> <Directory Id="ProgramMenuFolder"/> <!-- Program Files --> <Directory Id="ProgramFilesFolder" Name="PFiles"> <Directory Id="INSTALLFOLDER" Name="$(var.Product)"> <!-- Ffmpeg --> <Directory Id="FFMPEGFOLDER" Name="FFmpeg"> <Directory Id="FFMPEGBINFOLDER" Name="bin"> <Directory Id="FFMPEGBINWINDOWSFOLDER" Name="windows"> <Directory Id="FFMPEGBINWINDOWSX64FOLDER" Name="x64"> <Component Id="FFMPEGX64CMP" DiskId="1" Guid="A212950C-30F5-4130-9BC0-431DE13E9A40"> <File Id="AVCODECX64" Source="FFmpeg\bin\windows\x64\avcodec-57.dll" /> <File Id="AVFORMATX64" Source="FFmpeg\bin\windows\x64\avformat-57.dll" /> <File Id="AVUTILX64" Source="FFmpeg\bin\windows\x64\avutil-55.dll" /> <File Id="SWRESAMPLEX64" Source="FFmpeg\bin\windows\x64\swresample-2.dll" /> </Component> </Directory> <Directory Id="FFMPEGBINWINDOWSX86FOLDER" Name="x86"> <Component Id="FFMPEGX86CMP" DiskId="1" Guid="DCB59B57-7456-4F78-A919-5F0B9D35FF1C"> <File Id="AVCODECX86" Source="FFmpeg\bin\windows\x86\avcodec-57.dll" /> <File Id="AVFORMATX86" Source="FFmpeg\bin\windows\x86\avformat-57.dll" /> <File Id="AVUTILX86" Source="FFmpeg\bin\windows\x86\avutil-55.dll" /> <File Id="SWRESAMPLEX86" Source="FFmpeg\bin\windows\x86\swresample-2.dll" /> </Component> </Directory> </Directory> </Directory> </Directory> <!-- SQLite --> <Directory Id="X64FOLDER" Name="x64"> <Component Id="X64CMP" DiskId="1" Guid="89332F0B-AF41-49AC-9B8D-D1E8AD9E50F1"> <File Id="ESQLITEX64" Source="x64\e_sqlite3.dll" /> </Component> </Directory> <Directory Id="X86FOLDER" Name="x86"> <Component Id="X86CMP" DiskId="1" Guid="4A1279BA-C6C3-43D3-A1BB-EBA723DEF405"> <File Id="ESQLITEX86" Source="x86\e_sqlite3.dll" /> </Component> </Directory> <!-- Icons --> <Directory Id="ICONSFOLDER" Name="Icons"> <Component Id="ICONSCMP" DiskId="1" Guid="69CA5CE5-F8DF-45E3-A6A1-837785389740"> <File Source="Icons\Aiff.ico" /> <File Source="Icons\Dopamine.ico" /> <File Source="Icons\Dopamine - White.ico" /> <File Source="Icons\Dopamine.png" /> <File Source="Icons\Dopamine - White.png" /> <File Source="Icons\Flac.ico" /> <File Source="Icons\Generic.ico" /> <File Source="Icons\Legacy tray.ico" /> <File Source="Icons\M3u.ico" /> <File Source="Icons\M4a.ico" /> <File Source="Icons\Mp3.ico" /> <File Source="Icons\Ogg.ico" /> <File Source="Icons\Opus.ico" /> <File Source="Icons\Tray_black.ico" /> <File Source="Icons\Tray_white.ico" /> <File Source="Icons\Wav.ico" /> <File Source="Icons\Wma.ico" /> <File Source="Icons\Zpl.ico" /> </Component> </Directory> <!-- Language --> <Directory Id="LANGUAGESFOLDER" Name="Languages"> <Component Id="LANGUAGESCMP" DiskId="1" Guid="9226C125-A567-45E2-ADC8-95D5256BB8B7"> <File Source="Languages\BG.xml" /> <File Source="Languages\CS.xml" /> <File Source="Languages\DA.xml" /> <File Source="Languages\DE.xml" /> <File Source="Languages\EL.xml" /> <File Source="Languages\EN.xml" /> <File Source="Languages\ES.xml" /> <File Source="Languages\FI.xml" /> <File Source="Languages\FR.xml" /> <File Source="Languages\HR.xml" /> <File Source="Languages\HU.xml" /> <File Source="Languages\ID.xml" /> <File Source="Languages\IT.xml" /> <File Source="Languages\JP.xml" /> <File Source="Languages\KMR.xml" /> <File Source="Languages\KO.xml" /> <File Source="Languages\NL.xml" /> <File Source="Languages\NO.xml" /> <File Source="Languages\PL.xml" /> <File Source="Languages\PT-BR.xml" /> <File Source="Languages\PT-PT.xml" /> <File Source="Languages\RU.xml" /> <File Source="Languages\SR-Cyrl.xml" /> <File Source="Languages\SR-Latn.xml" /> <File Source="Languages\SV.xml" /> <File Source="Languages\TR.xml" /> <File Source="Languages\UK.xml" /> <File Source="Languages\VI.xml" /> <File Source="Languages\ZH-CN.xml" /> <File Source="Languages\ZH-TW.xml" /> </Component> </Directory> <!-- Equalizer --> <Directory Id="EQUALIZERFOLDER" Name="Equalizer"> <Component Id="EQUALIZERCMP" DiskId="1" Guid="FF9E83AA-FEEF-4F34-B8DB-60EF19477587"> <File Source="Equalizer\Classical.deq" /> <File Source="Equalizer\Club.deq" /> <File Source="Equalizer\Dance.deq" /> <File Source="Equalizer\Full bass and treble.deq" /> <File Source="Equalizer\Full bass.deq" /> <File Source="Equalizer\Full treble.deq" /> <File Source="Equalizer\Headphones.deq" /> <File Source="Equalizer\Large hall.deq" /> <File Source="Equalizer\Live.deq" /> <File Source="Equalizer\Party.deq" /> <File Source="Equalizer\Pop.deq" /> <File Source="Equalizer\Reggae.deq" /> <File Source="Equalizer\Rock.deq" /> <File Source="Equalizer\Ska.deq" /> <File Source="Equalizer\Soft rock.deq" /> <File Source="Equalizer\Soft.deq" /> <File Source="Equalizer\Techno.deq" /> </Component> </Directory> <!-- Application --> <Component Id="MAINCMP" DiskId="1" Guid="9B925874-C592-453A-BCA8-4CF8D8E60511"> <!-- Files --> <File Source="Dopamine.exe"> <Shortcut Id="ExeShortcut" Directory="ProgramMenuFolder" Name="Dopamine" WorkingDirectory="INSTALLFOLDER" Icon="$(var.Product).ico" IconIndex="0" /> </File> <File Source="Dopamine.exe.config" /> <File Source="Changelog.txt" /> <File Source="BaseSettings.xml" /> <File Source="CommonServiceLocator.dll" /> <File Source="Prism.dll" /> <File Source="Prism.DryIoc.Wpf.dll" /> <File Source="Prism.Wpf.dll" /> <File Source="Digimezzo.Foundation.Core.dll" /> <File Source="Digimezzo.Foundation.WPF.dll" /> <File Source="DiscordRPC.dll" /> <File Source="Dopamine.Core.dll" /> <File Source="Dopamine.Data.dll" /> <File Source="Dopamine.Icons.dll" /> <File Source="Dopamine.Services.dll" /> <File Source="CSCore.dll" /> <File Source="CSCore.Ffmpeg.dll" /> <File Source="GongSolutions.WPF.DragDrop.dll" /> <File Source="Ionic.Zip.dll" /> <File Source="NVorbis.dll" /> <File Source="SQLite-net.dll" /> <File Source="SQLitePCLRaw.batteries_green.dll" /> <File Source="SQLitePCLRaw.batteries_v2.dll" /> <File Source="SQLitePCLRaw.core.dll" /> <File Source="SQLitePCLRaw.provider.e_sqlite3.dll" /> <File Source="System.Windows.Interactivity.dll" /> <File Source="taglib-sharp.dll" /> <File Source="WPFFolderBrowser.dll" /> <File Source="DryIoc.dll" /> <File Source="Newtonsoft.Json.dll" /> <!-- Registry --> <RegistryKey Root="HKCR" Key="Directory\Shell\PlayWithDopamine"> <RegistryValue Type="string" Value="Play with Dopamine"/> </RegistryKey> <RegistryKey Root="HKCR" Key="Directory\Shell\PlayWithDopamine\command"> <RegistryValue Type="string" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;"/> </RegistryKey> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities" Name="ApplicationName" Value="Dopamine" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities" Name="ApplicationDescription" Value="Dopamine audio player" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".aiff" Value="Dopamine.aiff" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".m3u" Value="Dopamine.m3u" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".zpl" Value="Dopamine.zpl" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".mp3" Value="Dopamine.mp3" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".ogg" Value="Dopamine.ogg" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".wma" Value="Dopamine.wma" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".flac" Value="Dopamine.flac" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".m4a" Value="Dopamine.m4a" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Dopamine\Capabilities\FileAssociations" Name=".opus" Value="Dopamine.opus" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\RegisteredApplications" Name="Dopamine" Value="SOFTWARE\Dopamine\Capabilities" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Applications\Dopamine.exe" Name="FriendlyAppName" Value="Dopamine" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.aiff" Value="Dopamine aiff file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.aiff\DefaultIcon" Value="[ICONSFOLDER]Aiff.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.aiff\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.m3u" Value="Dopamine m3u file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.m3u\DefaultIcon" Value="[ICONSFOLDER]M3u.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.m3u\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.zpl" Value="Dopamine zpl file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.zpl\DefaultIcon" Value="[ICONSFOLDER]Zpl.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.zpl\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.mp3" Value="Dopamine mp3 file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.mp3\DefaultIcon" Value="[ICONSFOLDER]Mp3.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.mp3\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.ogg" Value="Dopamine ogg file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.ogg\DefaultIcon" Value="[ICONSFOLDER]Ogg.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.ogg\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.wma" Value="Dopamine wma file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.wma\DefaultIcon" Value="[ICONSFOLDER]Wma.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.wma\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.flac" Value="Dopamine flac file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.flac\DefaultIcon" Value="[ICONSFOLDER]Flac.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.flac\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.m4a" Value="Dopamine m4a file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.m4a\DefaultIcon" Value="[ICONSFOLDER]M4a.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.m4a\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.m3u" Value="Dopamine m3u file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.m3u\DefaultIcon" Value="[ICONSFOLDER]M3u.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.m3u\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.zpl" Value="Dopamine zpl file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.zpl\DefaultIcon" Value="[ICONSFOLDER]Zpl.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.zpl\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.mp3" Value="Dopamine mp3 file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.mp3\DefaultIcon" Value="[ICONSFOLDER]Mp3.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.mp3\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.ogg" Value="Dopamine ogg file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.ogg\DefaultIcon" Value="[ICONSFOLDER]Ogg.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.ogg\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.wma" Value="Dopamine wma file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.wma\DefaultIcon" Value="[ICONSFOLDER]Wma.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.wma\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.flac" Value="Dopamine flac file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.flac\DefaultIcon" Value="[ICONSFOLDER]Flac.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.flac\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.m4a" Value="Dopamine m4a file" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.m4a\DefaultIcon" Value="[ICONSFOLDER]M4a.ico,0" Type="string" /> <RegistryValue Root="HKCR" Key="SOFTWARE\Classes\Dopamine.m4a\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.opus" Value="Dopamine opus file" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.opus\DefaultIcon" Value="[ICONSFOLDER]Opus.ico,0" Type="string" /> <RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Dopamine.opus\shell\open\command" Value="&quot;[INSTALLFOLDER]Dopamine.exe&quot; &quot;%1&quot;" Type="string" /> </Component> </Directory> </Directory> </Directory> <!-- Components to add --> <!-- ================= --> <Feature Id="DefaultFeature" Title="Main Feature" Level="1"> <ComponentRef Id="FFMPEGX64CMP" /> <ComponentRef Id="FFMPEGX86CMP" /> <ComponentRef Id="ICONSCMP" /> <ComponentRef Id="LANGUAGESCMP" /> <ComponentRef Id="EQUALIZERCMP" /> <ComponentRef Id="MAINCMP" /> <ComponentRef Id="X64CMP" /> <ComponentRef Id="X86CMP" /> </Feature> </Product> <!-- Customization --> <!-- ============= --> <Fragment> <UI Id="DonateWixUI_InstallDir"> <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" /> <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" /> <TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" /> <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" /> <Property Id="WixUI_Mode" Value="InstallDir" /> <DialogRef Id="BrowseDlg" /> <DialogRef Id="DiskCostDlg" /> <DialogRef Id="ErrorDlg" /> <DialogRef Id="FatalError" /> <DialogRef Id="FilesInUse" /> <DialogRef Id="MsiRMFilesInUse" /> <DialogRef Id="PrepareDlg" /> <DialogRef Id="ProgressDlg" /> <DialogRef Id="ResumeDlg" /> <DialogRef Id="UserExit" /> <Publish Dialog="BrowseDlg" Control="OK" Event="DoAction" Value="WixUIValidatePath" Order="3">1</Publish> <Publish Dialog="BrowseDlg" Control="OK" Event="SpawnDialog" Value="InvalidDirDlg" Order="4"><![CDATA[WIXUI_INSTALLDIR_VALID<>"1"]]></Publish> <Publish Dialog="DonateExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish> <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">Installed AND PATCH</Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="SetTargetPath" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="DoAction" Value="WixUIValidatePath" Order="2">NOT WIXUI_DONTVALIDATEPATH</Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="SpawnDialog" Value="InvalidDirDlg" Order="3"><![CDATA[NOT WIXUI_DONTVALIDATEPATH AND WIXUI_INSTALLDIR_VALID<>"1"]]></Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="4">WIXUI_DONTVALIDATEPATH OR WIXUI_INSTALLDIR_VALID="1"</Publish> <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Property="_BrowseProperty" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish> <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish> <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg" Order="1">NOT Installed</Publish> <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="2">Installed AND NOT PATCH</Publish> <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="2">Installed AND PATCH</Publish> <Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg">1</Publish> <Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> <Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> <Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg">1</Publish> <Property Id="ARPNOMODIFY" Value="1" /> </UI> <UIRef Id="WixUI_Common" /> </Fragment> <Fragment> <UI> <Dialog Id="DonateExitDialog" Width="370" Height="270" Title="!(loc.ExitDialog_Title)"> <Control Id="Finish" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Cancel="yes" Text="!(loc.WixUIFinish)" /> <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Disabled="yes" Text="!(loc.WixUICancel)" /> <Control Id="Bitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="234" TabSkip="no" Text="!(loc.ExitDialogBitmap)" /> <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Disabled="yes" Text="!(loc.WixUIBack)" /> <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" /> <Control Id="Description" Type="Text" X="135" Y="70" Width="220" Height="40" Transparent="yes" NoPrefix="yes" Text="!(loc.ExitDialogDescription)" /> <Control Id="Title" Type="Text" X="135" Y="20" Width="220" Height="60" Transparent="yes" NoPrefix="yes" Text="!(loc.ExitDialogTitle)" /> <Control Id="OptionalText" Type="Text" X="135" Y="110" Width="220" Height="80" Transparent="yes" NoPrefix="yes" Hidden="yes" Text="[WIXUI_EXITDIALOGOPTIONALTEXT]"> <Condition Action="show">WIXUI_EXITDIALOGOPTIONALTEXT AND NOT Installed</Condition> </Control> <Control Id="DonateHyperLink" Type="Hyperlink" X="135" Y="125" Height="40" Width="200" Transparent="yes"> <Text> <![CDATA[If you like this software, please consider donating. Thank you! <a href="path_to_url">Donate via PayPal</a>]]> </Text> </Control> <Control Id="OptionalCheckBoxText" Type="Text" X="148" Y="190" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="[WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT]"> <Condition Action="show">WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT AND NOT Installed</Condition> </Control> <Control Id="OptionalCheckBox" Type="CheckBox" X="135" Y="190" Width="10" Height="10" Hidden="yes" Property="WIXUI_EXITDIALOGOPTIONALCHECKBOX" CheckBoxValue="1" Text="[WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT]"> <Condition Action="show">WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT AND NOT Installed</Condition> </Control> </Dialog> <InstallUISequence> <Show Dialog="DonateExitDialog" OnExit="success" Overridable="yes" /> </InstallUISequence> <AdminUISequence> <Show Dialog="DonateExitDialog" OnExit="success" Overridable="yes" /> </AdminUISequence> </UI> </Fragment> </Wix> ```
/content/code_sandbox/Dopamine/Dopamine.wxs
xml
2016-07-13T21:34:42
2024-08-15T03:30:43
dopamine-windows
digimezzo/dopamine-windows
1,786
7,290
```xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="path_to_url" xmlns:app="path_to_url"> <item android:id="@id/action_search" android:icon="@mipmap/ic_search" android:title="@string/menu_search" app:showAsAction="ifRoom" /> <item android:id="@id/action_notification" android:icon="@mipmap/ic_notifications" android:title="@string/menu_notifications" app:showAsAction="ifRoom" /> <item android:id="@id/action_settings" android:orderInCategory="100" android:title="@string/menu_settings" app:showAsAction="never" /> <item android:id="@id/action_about" android:orderInCategory="101" android:title="@string/menu_about_us" app:showAsAction="never" /> </menu> ```
/content/code_sandbox/src/main/res/menu/zhihu_toolbar_menu.xml
xml
2016-02-01T07:29:58
2024-07-24T21:59:04
AndroidSystemUiTraining
D-clock/AndroidSystemUiTraining
1,126
198
```xml import type { RxPluginPreCreateRxQueryArgs, RxPluginPrePrepareQueryArgs, FilledMangoQuery, RxJsonSchema, RxDocumentData } from '../../types/index.d.ts'; /** * accidentally passing a non-valid object into the query params * is very hard to debug especially when queries are observed * This is why we do some checks here in dev-mode */ export declare function checkQuery(args: RxPluginPreCreateRxQueryArgs): void; export declare function checkMangoQuery(args: RxPluginPrePrepareQueryArgs): void; export declare function areSelectorsSatisfiedByIndex<RxDocType>(schema: RxJsonSchema<RxDocumentData<RxDocType>>, query: FilledMangoQuery<RxDocType>): boolean; /** * Ensures that the selector does not contain any RegExp instance. * @recursive */ export declare function ensureObjectDoesNotContainRegExp(selector: any): void; ```
/content/code_sandbox/dist/types/plugins/dev-mode/check-query.d.ts
xml
2016-12-02T19:34:42
2024-08-16T15:47:20
rxdb
pubkey/rxdb
21,054
190
```xml export { ServicesDatatable } from './ServicesDatatable'; ```
/content/code_sandbox/app/react/kubernetes/services/ServicesView/ServicesDatatable/index.tsx
xml
2016-05-19T20:15:28
2024-08-16T19:15:14
portainer
portainer/portainer
30,083
13
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>0.12.2</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>$(CURRENT_PROJECT_VERSION)</string> <key>NSPrincipalClass</key> <string></string> </dict> </plist> ```
/content/code_sandbox/GSKStretchyHeaderView/GSKStretchyHeaderView/Info.plist
xml
2016-02-27T14:30:08
2024-08-09T08:57:24
GSKStretchyHeaderView
gskbyte/GSKStretchyHeaderView
1,749
248
```xml /* * Squidex Headless CMS * * @license */ /* eslint-disable @typescript-eslint/no-implied-eval */ /* eslint-disable no-useless-return */ import { AbstractControl, ValidatorFn } from '@angular/forms'; import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { isValidValue, Language } from '../internal'; import { AppLanguageDto } from '../services/app-languages.service'; import { FieldDto, RootFieldDto, SchemaDto } from '../services/schemas.service'; import { fieldInvariant } from '../services/schemas.types'; import { CompiledRules, RuleContext, RulesProvider } from './contents.form-rules'; export type TranslationStatus = { [language: string]: number }; export function contentsTranslationStatus(datas: any[], schema: SchemaDto, languages: ReadonlyArray<Language>) { const result: TranslationStatus = {}; for (const data of datas) { const status = contentTranslationStatus(data, schema, languages); for (const language of languages) { const iso2Code = language.iso2Code; result[iso2Code] = (result[iso2Code] || 0) + status[iso2Code]; } } for (const language of languages) { const iso2Code = language.iso2Code; result[iso2Code] = Math.round(result[iso2Code] / datas.length); } return result; } export function contentTranslationStatus(data: any, schema: SchemaDto, languages: ReadonlyArray<Language>) { const result: TranslationStatus = {}; const localizedFields = schema.fields.filter(x => x.isLocalizable); for (const language of languages) { let percent = 0; for (const field of localizedFields) { if (isValidValue(data?.[field.name]?.[language.iso2Code])) { percent++; } } if (localizedFields.length > 0) { percent = Math.round(100 * percent / localizedFields.length); } else { percent = 100; } result[language.iso2Code] = percent; } return result; } export function fieldTranslationStatus(data: any) { const result: { [field: string]: boolean } = {}; for (const [key, value] of Object.entries(data)) { result[key] = isValidValue(value); } return result; } export abstract class Hidden { private readonly hidden$ = new BehaviorSubject<boolean>(false); public get hidden() { return this.hidden$.value; } public get hiddenChanges(): Observable<boolean> { return this.hidden$; } public get visibleChanges(): Observable<boolean> { return this.hidden$.pipe(map(x => !x)); } protected setHidden(hidden: boolean) { if (hidden !== this.hidden) { this.hidden$.next(hidden); } } } export type FieldGroup<T = FieldDto> = { separator?: T; fields: T[] }; export function groupFields<T extends FieldDto>(fields: ReadonlyArray<T>, keepEmpty = false): FieldGroup<T>[] { const result: FieldGroup<T>[] = []; let currentSeparator: T | undefined; let currentFields: T[] = []; for (const field of fields) { if (field.properties.isContentField) { currentFields.push(field); } else { if (currentFields.length > 0 || keepEmpty) { result.push({ separator: currentSeparator, fields: currentFields }); } currentFields = []; currentSeparator = field; } } if (currentFields.length > 0 || keepEmpty) { result.push({ separator: currentSeparator, fields: currentFields }); } return result; } export class FieldSection<TSeparator, TChild extends { hidden: boolean }> extends Hidden { constructor( public readonly separator: TSeparator | undefined, public readonly fields: ReadonlyArray<TChild>, ) { super(); } public updateHidden() { let visible = false; for (const child of this.fields) { visible = visible || !child.hidden; } this.setHidden(!visible); } } type Partition = { key: string; isOptional: boolean }; export class PartitionConfig { private readonly invariant: ReadonlyArray<Partition> = [{ key: fieldInvariant, isOptional: false }]; private readonly languages: ReadonlyArray<Partition>; constructor(languages: ReadonlyArray<AppLanguageDto>) { this.languages = languages.map(l => this.get(l)); } public get(language?: AppLanguageDto) { if (!language) { return this.invariant[0]; } return { key: language.iso2Code, isOptional: language.isOptional }; } public getAll(field: RootFieldDto) { return field.isLocalizable ? this.languages : this.invariant; } } export type AbstractContentFormState = { isDisabled?: boolean; isHidden?: boolean; isRequired?: boolean; }; export interface FormGlobals { partitions: PartitionConfig; schema: SchemaDto; schemas: { [id: string ]: SchemaDto }; remoteValidator?: ValidatorFn; } export abstract class AbstractContentForm<T extends FieldDto, TForm extends AbstractControl> extends Hidden { private readonly collapsed$ = new BehaviorSubject<boolean | null>(null); private readonly ruleSet: CompiledRules; public get collapsed() { return this.collapsed$.value; } public get collapsedChanges(): Observable<boolean | null> { return this.collapsed$; } protected constructor( public readonly globals: FormGlobals, public readonly field: T, public readonly fieldPath: string, public readonly form: TForm, public readonly isOptional: boolean, public readonly rules: RulesProvider, ) { super(); this.ruleSet = rules.getRules(this); } public path(relative: string) { return `${this.fieldPath}.${relative}`; } public collapse() { this.collapsed$.next(true); } public expand() { this.collapsed$.next(false); } public updateState(context: RuleContext, itemData: any, parentState: AbstractContentFormState) { const state = { isDisabled: this.field.isDisabled || parentState.isDisabled === true, isHidden: parentState.isHidden === true, isRequired: this.field.properties.isRequired && !this.isOptional, }; for (const rule of this.ruleSet.rules) { if (rule.eval(context, itemData)) { if (rule.action === 'Disable') { state.isDisabled = true; } else if (rule.action === 'Hide') { state.isHidden = true; } else { state.isRequired = true; } } } this.setHidden(state.isHidden); if (state.isDisabled !== this.form.disabled) { if (state.isDisabled) { this.form.disable(SELF); } else { this.form.enable(SELF); } } this.updateCustomState(context, itemData, state); } public setValue(value: any) { this.form.reset(value); } public unset() { this.form.setValue(undefined); } protected updateCustomState(_context: RuleContext, _itemData: any, _state: AbstractContentFormState): void { return; } } const SELF = { onlySelf: true }; ```
/content/code_sandbox/frontend/src/app/shared/state/contents.forms-helpers.ts
xml
2016-08-29T05:53:40
2024-08-16T17:39:38
squidex
Squidex/squidex
2,222
1,574
```xml import { getNamedRouteRegex } from './route-regex' import { parseParameter } from './route-regex' describe('getNamedRouteRegex', () => { it('should handle interception markers adjacent to dynamic path segments', () => { const regex = getNamedRouteRegex('/photos/(.)[author]/[id]', true) expect(regex.routeKeys).toEqual({ nxtIauthor: 'nxtIauthor', nxtPid: 'nxtPid', }) expect(regex.groups['author']).toEqual({ pos: 1, repeat: false, optional: false, }) expect(regex.groups['id']).toEqual({ pos: 2, repeat: false, optional: false, }) expect(regex.re.test('/photos/(.)next/123')).toBe(true) }) it('should match named routes correctly when interception markers are adjacent to dynamic segments', () => { let regex = getNamedRouteRegex('/(.)[author]/[id]', true) let namedRegexp = new RegExp(regex.namedRegex) expect(namedRegexp.test('/[author]/[id]')).toBe(false) expect(namedRegexp.test('/(.)[author]/[id]')).toBe(true) regex = getNamedRouteRegex('/(..)(..)[author]/[id]', true) namedRegexp = new RegExp(regex.namedRegex) expect(namedRegexp.test('/[author]/[id]')).toBe(false) expect(namedRegexp.test('/(..)(..)[author]/[id]')).toBe(true) }) it('should handle multi-level interception markers', () => { const regex = getNamedRouteRegex('/photos/(..)(..)[author]/[id]', true) expect(regex.routeKeys).toEqual({ nxtIauthor: 'nxtIauthor', nxtPid: 'nxtPid', }) expect(regex.groups['author']).toEqual({ pos: 1, repeat: false, optional: false, }) expect(regex.groups['id']).toEqual({ pos: 2, repeat: false, optional: false, }) expect(regex.re.test('/photos/(..)(..)next/123')).toBe(true) }) it('should handle interception markers not adjacent to dynamic path segments', () => { const regex = getNamedRouteRegex('/photos/(.)author/[id]', true) expect(regex.routeKeys).toEqual({ nxtPid: 'nxtPid', }) expect(regex.groups['author']).toBeUndefined() expect(regex.groups['id']).toEqual({ pos: 1, repeat: false, optional: false, }) expect(regex.re.test('/photos/(.)author/123')).toBe(true) }) it('should handle optional dynamic path segments', () => { const regex = getNamedRouteRegex('/photos/[[id]]', true) expect(regex.routeKeys).toEqual({ nxtPid: 'nxtPid', }) expect(regex.groups['id']).toEqual({ pos: 1, repeat: false, optional: true, }) }) it('should handle optional catch-all dynamic path segments', () => { const regex = getNamedRouteRegex('/photos/[[...id]]', true) expect(regex.routeKeys).toEqual({ nxtPid: 'nxtPid', }) expect(regex.groups['id']).toEqual({ pos: 1, repeat: true, optional: true, }) expect(regex.re.test('/photos/1')).toBe(true) expect(regex.re.test('/photos/1/2/3')).toBe(true) expect(regex.re.test('/photos')).toBe(true) }) }) describe('parseParameter', () => { it('should parse a optional catchall parameter', () => { const param = '[[...slug]]' const expected = { key: 'slug', repeat: true, optional: true } const result = parseParameter(param) expect(result).toEqual(expected) }) it('should parse a catchall parameter', () => { const param = '[...slug]' const expected = { key: 'slug', repeat: true, optional: false } const result = parseParameter(param) expect(result).toEqual(expected) }) it('should parse a optional parameter', () => { const param = '[[foo]]' const expected = { key: 'foo', repeat: false, optional: true } const result = parseParameter(param) expect(result).toEqual(expected) }) it('should parse a dynamic parameter', () => { const param = '[bar]' const expected = { key: 'bar', repeat: false, optional: false } const result = parseParameter(param) expect(result).toEqual(expected) }) it('should parse non-dynamic parameter', () => { const param = 'fizz' const expected = { key: 'fizz', repeat: false, optional: false } const result = parseParameter(param) expect(result).toEqual(expected) }) }) ```
/content/code_sandbox/packages/next/src/shared/lib/router/utils/route-regex.test.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
1,068
```xml import SideNavbar from './SideNavbar'; export default SideNavbar; ```
/content/code_sandbox/docs/components/SideNavbar/index.tsx
xml
2016-06-06T02:27:46
2024-08-16T16:41:54
rsuite
rsuite/rsuite
8,263
14
```xml import Button from "@erxes/ui/src/components/Button"; import FormControl from "@erxes/ui/src/components/form/Control"; import FormGroup from "@erxes/ui/src/components/form/Group"; import DateControl from "@erxes/ui/src/components/form/DateControl"; import { __ } from "@erxes/ui/src/utils"; import { IField, IFieldLogic } from "@erxes/ui/src/types"; import React from "react"; import { dateTypeChoices, numberTypeChoices, stringTypeChoices, } from "../constants"; import { DateWrapper, LogicItem, LogicRow, RowSmall } from "../styles"; import { Column } from "@erxes/ui/src/styles/main"; type Props = { onChangeLogic: ( name: string, value: string | number | Date, index: number ) => void; logic: IFieldLogic; fields: IField[]; index: number; removeLogic: (index: number) => void; }; function FieldLogic(props: Props) { const { fields, logic, onChangeLogic, removeLogic, index } = props; const getSelectedField = () => { return fields.find( (field) => field._id === logic.fieldId || field._id === logic.tempFieldId ); }; const getOperatorOptions = () => { const selectedField = getSelectedField(); if (selectedField && selectedField.validation) { if (selectedField.validation === "number") { return numberTypeChoices; } if (selectedField.validation.includes("date")) { return dateTypeChoices; } } return stringTypeChoices; }; const onChangeFieldId = (e) => { const value = e.target.value; onChangeLogic("fieldId", "", index); onChangeLogic( value.startsWith("tempId") ? "tempFieldId" : "fieldId", value, index ); const operators = getOperatorOptions(); onChangeLogic("logicOperator", operators[1].value, index); }; const onChangeLogicOperator = (e) => { onChangeLogic("logicOperator", e.target.value, index); }; const onChangeLogicValue = (e) => { onChangeLogic("logicValue", e.target.value, index); }; const onDateChange = (value) => { onChangeLogic("logicValue", value, index); }; const remove = () => { removeLogic(index); }; const renderLogicValue = () => { const selectedField = getSelectedField(); if (selectedField) { if ( selectedField.type === "check" || selectedField.type === "select" || selectedField.type === "radio" ) { return ( <FormControl componentclass="select" defaultValue={logic.logicValue} name="logicValue" onChange={onChangeLogicValue} > <option value="" /> {selectedField.options && selectedField.options.map((option) => ( <option key={option} value={option}> {option} </option> ))} </FormControl> ); } if (["date", "datetime"].includes(selectedField.validation || "")) { return ( <DateWrapper> <DateControl placeholder={__("pick a date")} value={logic.logicValue} timeFormat={ selectedField.validation === "datetime" ? true : false } onChange={onDateChange} /> </DateWrapper> ); } if (selectedField.validation === "number") { return ( <FormControl defaultValue={logic.logicValue} name="logicValue" onChange={onChangeLogicValue} type={"number"} /> ); } return ( <FormControl defaultValue={logic.logicValue} name="logicValue" onChange={onChangeLogicValue} /> ); } return null; }; return ( <LogicItem> <LogicRow> <Column> <FormGroup> <FormControl componentclass="select" value={logic.fieldId || logic.tempFieldId} name="fieldId" onChange={onChangeFieldId} > <option value="" /> {fields.map((field) => ( <option key={field._id} value={field._id}> {field.text} </option> ))} </FormControl> </FormGroup> <LogicRow> <RowSmall> <FormControl componentclass="select" defaultValue={logic.logicOperator} name="logicOperator" options={getOperatorOptions()} onChange={onChangeLogicOperator} /> </RowSmall> <Column>{renderLogicValue()}</Column> </LogicRow> </Column> <Button onClick={remove} btnStyle="danger" icon="times" /> </LogicRow> </LogicItem> ); } export default FieldLogic; ```
/content/code_sandbox/packages/ui-forms/src/forms/components/FieldLogic.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
1,050
```xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/layout" xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent"> <io.netopen.hotbitmapgg.view.NewCreditSesameView android:id="@+id/sesame_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <ImageView android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/sesame_view" android:layout_centerInParent="true" android:background="@mipmap/ic_ting_play" /> </RelativeLayout> ```
/content/code_sandbox/app/src/main/res/layout/fragment_1.xml
xml
2016-09-01T13:02:40
2024-08-02T07:38:11
CreditSesameRingView
HotBitmapGG/CreditSesameRingView
1,176
177
```xml <vector xmlns:android="path_to_url" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <path android:pathData="M9.172,4.172C9.922,3.421 10.939,3 12,3C13.061,3 14.078,3.421 14.828,4.172C15.579,4.922 16,5.939 16,7V10H8V7C8,5.939 8.421,4.922 9.172,4.172ZM6,10V7C6,5.409 6.632,3.883 7.757,2.757C8.883,1.632 10.409,1 12,1C13.591,1 15.117,1.632 16.243,2.757C17.368,3.883 18,5.409 18,7V10H19C20.657,10 22,11.343 22,13V20C22,21.657 20.657,23 19,23H5C3.343,23 2,21.657 2,20V13C2,11.343 3.343,10 5,10H6ZM17,12H7H5C4.448,12 4,12.448 4,13V20C4,20.552 4.448,21 5,21H19C19.552,21 20,20.552 20,20V13C20,12.448 19.552,12 19,12H17Z" android:fillColor="#ffffff" android:fillType="evenOdd"/> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_lock.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
410
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions id="definition" xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:activiti="path_to_url" targetNamespace="Examples"> <process id="miParallelUserTasksBasedOnCollection"> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="miTasks" /> <userTask id="miTasks" name="My Task ${loopCounter}" activiti:assignee="${assignee}"> <multiInstanceLoopCharacteristics isSequential="false"> <loopDataInputRef>assigneeList</loopDataInputRef> <inputDataItem name="assignee" /> <completionCondition>${nrOfCompletedInstances/nrOfInstances >= 0.6 }</completionCondition> </multiInstanceLoopCharacteristics> </userTask> <sequenceFlow id="flow3" sourceRef="miTasks" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> </definitions> ```
/content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/multiinstance/MultiInstanceTest.testParallelUserTasksBasedOnCollection.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
243
```xml import grpcJSOriginal from '@grpc/grpc-js'; import { EventEmitter } from 'events'; import { vi } from 'vitest'; const grpcJs = vi.requireActual('@grpc/grpc-js') as typeof grpcJSOriginal; const mockCallWrite = vi.fn(); const mockCallEnd = vi.fn(); const mockCallCancel = vi.fn(); export const status = grpcJs.status; class MockCall extends EventEmitter { write(...args) { mockCallWrite(...args); } end(...args) { mockCallEnd(...args); } cancel(...args) { mockCallCancel(...args); } } let mockCall = new MockCall(); const makeMockCall = () => { mockCall = new MockCall(); }; const getMockCall = () => mockCall; const mockConstructor = vi.fn(); const mockMakeUnaryRequest = vi.fn(); const mockMakeClientStreamRequest = vi.fn(); const mockMakeServerStreamRequest = vi.fn(); const mockMakeBidiStreamRequest = vi.fn(); const mockCreateInsecure = vi.fn(); const mockCreateSsl = vi.fn(); export const grpcMocks = { getMockCall, mockConstructor, mockMakeUnaryRequest, mockMakeClientStreamRequest, mockMakeServerStreamRequest, mockMakeBidiStreamRequest, mockCreateInsecure, mockCreateSsl, mockCallWrite, mockCallEnd, mockCallCancel, }; class MockGrpcClient { constructor(...args) { mockConstructor(...args); } makeUnaryRequest(...args) { mockMakeUnaryRequest(...args); makeMockCall(); return getMockCall(); } makeClientStreamRequest(...args) { mockMakeClientStreamRequest(...args); makeMockCall(); return getMockCall(); } makeServerStreamRequest(...args) { mockMakeServerStreamRequest(...args); makeMockCall(); return getMockCall(); } makeBidiStreamRequest(...args) { mockMakeBidiStreamRequest(...args); makeMockCall(); return getMockCall(); } } export function makeGenericClientConstructor() { return MockGrpcClient; } export class Metadata { /** * Mock Metadata class to avoid TypeError: grpc.Metadata is not a constructor */ constructor() { // Do nothing } } export const credentials = { createInsecure: mockCreateInsecure, createSsl: mockCreateSsl, }; ```
/content/code_sandbox/packages/insomnia/src/__mocks__/@grpc/grpc-js.ts
xml
2016-04-23T03:54:26
2024-08-16T16:50:44
insomnia
Kong/insomnia
34,054
524
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /** * Returns the enumeration constant associated with an ndarray data type policy value. * * ## Notes * * - Downstream consumers of this function should **not** rely on specific integer values (e.g., `SAME == 0`). Instead, the function should be used in an opaque manner. * * @param policy - policy value * @returns enumeration constant * * @example * var v = resolve( 'same' ); * // returns <number> */ declare function resolve( policy: any ): number | null; // EXPORTS // export = resolve; ```
/content/code_sandbox/lib/node_modules/@stdlib/ndarray/base/output-policy-resolve-enum/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
177
```xml /* * path_to_url * * or in the 'license' file accompanying this file. This file is distributed * on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either */ import WsClient from 'ws'; import { ClientConfigBuilder } from './builder/ClientConfigBuilder'; import { SkillInvokerConfigBuilder } from './builder/SkillInvokerConfigBuilder'; import { WebSocketClientConfigBuilder } from './builder/WebSocketClientConfigBuilder'; import { LocalDebugClient } from './client/LocalDebugClient'; import { argsParser, getHandlerFunction } from './util/ArgsParserUtils'; const { argv } = argsParser(); const clientConfig = new ClientConfigBuilder() .withAccessToken(argv.accessToken) .withHandlerName(argv.handlerName) .withSkillEntryFile(argv.skillEntryFile) .withSkillId(argv.skillId) .withRegion(argv.region) .build(); const skillInvokerConfig = new SkillInvokerConfigBuilder() .withHandler(getHandlerFunction(clientConfig.skillEntryFile, clientConfig.handlerName)) .build(); const webSocketClientConfig = new WebSocketClientConfigBuilder() .withSkillId(clientConfig.skillId) .withAccessToken(clientConfig.accessToken) .withRegion(clientConfig.region) .build(); const webSocketClient = new WsClient(webSocketClientConfig.webSocketServerUri, { headers: webSocketClientConfig.headers, }); const client = new LocalDebugClient(webSocketClient, skillInvokerConfig); ```
/content/code_sandbox/ask-sdk-local-debug/lib/LocalDebuggerInvoker.ts
xml
2016-06-24T06:26:05
2024-08-14T12:39:19
alexa-skills-kit-sdk-for-nodejs
alexa/alexa-skills-kit-sdk-for-nodejs
3,118
314
```xml // @ts-ignore ts-migrate(2305) FIXME: Module '"react"' has no exported member 'Node'. import type { Node } from 'react'; import React, { Component } from 'react'; import { observer } from 'mobx-react'; import { defineMessages, intlShape } from 'react-intl'; import moment from 'moment'; import LocalizableError from '../../../i18n/LocalizableError'; import { IS_ICO_PUBLIC_KEY_SHARING_ENABLED, IS_WALLET_PUBLIC_KEY_SHARING_ENABLED, IS_WALLET_UNDELEGATION_ENABLED, } from '../../../config/walletsConfig'; import BorderedBox from '../../widgets/BorderedBox'; import InlineEditingInput from '../../widgets/forms/InlineEditingInput'; import ReadOnlyInput from '../../widgets/forms/ReadOnlyInput'; import UndelegateWalletButton from './UndelegateWalletButton'; import DelegateWalletButton from './DelegateWalletButton'; import UndelegateWalletConfirmationDialog from './UndelegateWalletConfirmationDialog'; import WalletSettingsActionConfirmationDialog from './WalletSettingsRemoveConfirmationDialog'; import UnpairWallet from './UnpairWallet'; import DeleteWallet from './DeleteWallet'; import ChangeSpendingPasswordDialog from './ChangeSpendingPasswordDialog'; import globalMessages from '../../../i18n/global-messages'; import styles from './WalletSettings.scss'; import WalletRecoveryPhraseVerificationWidget from './WalletRecoveryPhraseVerificationWidget'; import type { Locale } from '../../../../../common/types/locales.types'; import { momentLocales } from '../../../../../common/types/locales.types'; import ICOPublicKeyBox from './ICOPublicKeyBox'; import WalletPublicKeyBox from './WalletPublicKeyBox'; import ICOPublicKeyDialog from './ICOPublicKeyDialog'; import ICOPublicKeyQRCodeDialog from './ICOPublicKeyQRCodeDialog'; import WalletPublicKeyDialog from './WalletPublicKeyDialog'; import WalletPublicKeyQRCodeDialog from './WalletPublicKeyQRCodeDialog'; import type { ReactIntlMessage } from '../../../types/i18nTypes'; export const messages: Record<string, ReactIntlMessage> = defineMessages({ assuranceLevelLabel: { id: 'wallet.settings.assurance', defaultMessage: '!!!Transaction assurance security level', description: 'Label for the "Transaction assurance security level" dropdown.', }, undelegateWalletHeader: { id: 'wallet.settings.undelegateWallet.header', defaultMessage: '!!!Undelegating your wallet', description: 'Undelegate wallet header on the wallet settings page.', }, undelegateWalletWarning: { id: 'wallet.settings.undelegateWallet.warning', defaultMessage: '!!!If you are planning to stop using this wallet and remove all funds, you should first undelegate it to recover your 2 ada deposit. You will continue getting delegation rewards during the three Cardano epochs after undelegating your wallet.', description: 'Undelegate wallet warning explaining the consequences.', }, undelegateWalletDisabledWarning: { id: 'wallet.settings.undelegateWallet.disabledWarning', defaultMessage: "!!!This wallet is synchronizing with the blockchain, so this wallet's delegation status is currently unknown, and undelegation is not possible.", description: 'Undelegate wallet disabled warning explaining why it is disabled.', }, delegateWalletHeader: { id: 'wallet.settings.delegateWallet.header', defaultMessage: '!!!Delegate your wallet', description: 'Delegate wallet header on the wallet settings page.', }, delegateWalletWarning: { id: 'wallet.settings.delegateWallet.warning', defaultMessage: "!!!This wallet is not delegated. Please, delegate the stake from this wallet to earn rewards and support the Cardano network's security.", description: 'Delegate wallet warning.', }, delegateWalletDisabledWarning: { id: 'wallet.settings.delegateWallet.disabledWarning', defaultMessage: "!!!This wallet is synchronizing with the blockchain, so this wallet's delegation status is currently unknown, and delegation is not possible.", description: 'Delegate wallet disabled warning explaining why it is disabled.', }, name: { id: 'wallet.settings.name.label', defaultMessage: '!!!Name', description: 'Label for the "Name" text input on the wallet settings page.', }, passwordLabel: { id: 'wallet.settings.password', defaultMessage: '!!!Password', description: 'Label for the "Password" field.', }, passwordLastUpdated: { id: 'wallet.settings.passwordLastUpdated', defaultMessage: '!!!Last updated', description: 'Last updated X time ago message.', }, passwordNotSet: { id: 'wallet.settings.passwordNotSet', defaultMessage: "!!!You still don't have password", description: "You still don't have password set message.", }, }); type Props = { walletId: string; walletName: string; isRestoring: boolean; isSyncing: boolean; isDelegating: boolean; walletPublicKey: string | null | undefined; icoPublicKey: string | null | undefined; creationDate: Date; spendingPasswordUpdateDate: Date | null | undefined; error?: LocalizableError | null | undefined; openDialogAction: (...args: Array<any>) => any; isDialogOpen: (...args: Array<any>) => any; onFieldValueChange: (...args: Array<any>) => any; onStartEditing: (...args: Array<any>) => any; onStopEditing: (...args: Array<any>) => any; onCancel: (...args: Array<any>) => any; onVerifyRecoveryPhrase: (...args: Array<any>) => any; onCopyWalletPublicKey: (...args: Array<any>) => any; onCopyICOPublicKey: (...args: Array<any>) => any; updateDataForActiveDialogAction: (...args: Array<any>) => any; onDelegateClick: (...args: Array<any>) => any; nameValidator: (...args: Array<any>) => any; isLegacy: boolean; changeSpendingPasswordDialog: Node; walletPublicKeyDialogContainer: Node; icoPublicKeyDialogContainer: Node; walletPublicKeyQRCodeDialogContainer: Node; icoPublicKeyQRCodeDialogContainer: Node; undelegateWalletDialogContainer: Node; deleteWalletDialogContainer: Node; unpairWalletDialogContainer: Node; shouldDisplayRecoveryPhrase: boolean; recoveryPhraseVerificationDate: Date | null | undefined; recoveryPhraseVerificationStatus: string; recoveryPhraseVerificationStatusType: string; wordCount: number; locale: Locale; isSpendingPasswordSet: boolean; isHardwareWallet: boolean; }; type State = { isFormBlocked: boolean; }; @observer class WalletSettings extends Component<Props, State> { static contextTypes = { intl: intlShape.isRequired, }; state = { isFormBlocked: false, }; componentDidUpdate() { const { isDialogOpen } = this.props; const { isFormBlocked } = this.state; // Set "name" input to active and "unblock form" on Dialog close if ( !isDialogOpen(WalletSettingsActionConfirmationDialog) && !isDialogOpen(ChangeSpendingPasswordDialog) && isFormBlocked ) { this.unblockForm(); } } componentWillUnmount() { // This call is used to prevent display of old successfully-updated messages this.props.onCancel(); } onBlockForm = () => { this.setState({ isFormBlocked: true, }); }; unblockForm = () => { this.setState({ isFormBlocked: false, }); }; onUndelegateWalletClick = async () => { const { walletId, openDialogAction, updateDataForActiveDialogAction, } = this.props; this.onBlockForm(); openDialogAction({ dialog: UndelegateWalletConfirmationDialog, }); updateDataForActiveDialogAction({ data: { walletId, }, }); }; renderUndelegateWalletBox = () => { const { intl } = this.context; const { isDelegating, isRestoring, isSyncing, isLegacy, isDialogOpen, onDelegateClick, undelegateWalletDialogContainer, } = this.props; /// @TODO: Once undelegation for rewarded wallet works fine with api, remove reward checking and config if (!IS_WALLET_UNDELEGATION_ENABLED || isLegacy) { return null; } let headerMessage; let warningMessage; if (isDelegating) { headerMessage = intl.formatMessage(messages.undelegateWalletHeader); warningMessage = isRestoring || isSyncing ? intl.formatMessage(messages.undelegateWalletDisabledWarning) : intl.formatMessage(messages.undelegateWalletWarning); } else { headerMessage = intl.formatMessage(messages.delegateWalletHeader); warningMessage = isRestoring || isSyncing ? intl.formatMessage(messages.delegateWalletDisabledWarning) : intl.formatMessage(messages.delegateWalletWarning); } return ( <> <BorderedBox className={styles.undelegateWalletBox}> <span>{headerMessage}</span> <div className={styles.contentBox}> <div> <p>{warningMessage}</p> </div> {isDelegating ? ( <UndelegateWalletButton disabled={isRestoring || isSyncing} onUndelegate={this.onUndelegateWalletClick} /> ) : ( <DelegateWalletButton disabled={isRestoring || isSyncing} onDelegate={onDelegateClick} /> )} </div> </BorderedBox> {isDialogOpen(UndelegateWalletConfirmationDialog) ? undelegateWalletDialogContainer : false} </> ); }; render() { const { intl } = this.context; const { walletName, creationDate, spendingPasswordUpdateDate, error, isDialogOpen, openDialogAction, onFieldValueChange, onStartEditing, onStopEditing, onCancel, onVerifyRecoveryPhrase, nameValidator, isLegacy, changeSpendingPasswordDialog, recoveryPhraseVerificationDate, recoveryPhraseVerificationStatus, recoveryPhraseVerificationStatusType, locale, isSpendingPasswordSet, isHardwareWallet, shouldDisplayRecoveryPhrase, wordCount, walletPublicKeyDialogContainer, walletPublicKeyQRCodeDialogContainer, icoPublicKeyDialogContainer, icoPublicKeyQRCodeDialogContainer, deleteWalletDialogContainer, unpairWalletDialogContainer, } = this.props; const { isFormBlocked } = this.state; // Set Japanese locale to moment. Default is en-US moment.locale(momentLocales[locale]); const passwordMessage = isSpendingPasswordSet ? intl.formatMessage(messages.passwordLastUpdated, { lastUpdated: moment(spendingPasswordUpdateDate) .locale(this.context.intl.locale) .fromNow(), }) : intl.formatMessage(messages.passwordNotSet); return ( <div className={styles.root}> <BorderedBox> <InlineEditingInput className="walletName" label={intl.formatMessage(messages.name)} value={walletName} maxLength={40} onFocus={() => onStartEditing('name')} onBlur={onStopEditing} onCancel={onCancel} onSubmit={(value) => onFieldValueChange('name', value)} isValid={nameValidator} valueErrorMessage={intl.formatMessage( globalMessages.invalidWalletName )} readOnly={isFormBlocked} /> {!isHardwareWallet && ( <ReadOnlyInput label={intl.formatMessage(messages.passwordLabel)} value={passwordMessage} isSet={isSpendingPasswordSet} withButton onClick={() => { this.onBlockForm(); openDialogAction({ dialog: ChangeSpendingPasswordDialog, }); }} /> )} {shouldDisplayRecoveryPhrase && ( <WalletRecoveryPhraseVerificationWidget onVerify={onVerifyRecoveryPhrase} recoveryPhraseVerificationDate={recoveryPhraseVerificationDate} // @ts-ignore ts-migrate(2769) FIXME: No overload matches this call. recoveryPhraseVerificationStatus={ recoveryPhraseVerificationStatus } recoveryPhraseVerificationStatusType={ recoveryPhraseVerificationStatusType } creationDate={creationDate} locale={locale} wordCount={wordCount} isLegacy={isLegacy} /> )} {error && <p className={styles.error}>{intl.formatMessage(error)}</p>} </BorderedBox> {isDialogOpen(ChangeSpendingPasswordDialog) ? changeSpendingPasswordDialog : false} {IS_WALLET_PUBLIC_KEY_SHARING_ENABLED && !isLegacy && ( <> <WalletPublicKeyBox publicKey={this.props.walletPublicKey} locale={this.props.locale} onCopyWalletPublicKey={this.props.onCopyWalletPublicKey} openDialogAction={this.props.openDialogAction} /> {isDialogOpen(WalletPublicKeyDialog) && walletPublicKeyDialogContainer} {isDialogOpen(WalletPublicKeyQRCodeDialog) && walletPublicKeyQRCodeDialogContainer} </> )} {IS_ICO_PUBLIC_KEY_SHARING_ENABLED && !isLegacy && !isHardwareWallet && ( <> <ICOPublicKeyBox publicKey={this.props.icoPublicKey} locale={this.props.locale} onCopyICOPublicKey={this.props.onCopyICOPublicKey} openDialogAction={this.props.openDialogAction} /> {isDialogOpen(ICOPublicKeyDialog) && icoPublicKeyDialogContainer} {isDialogOpen(ICOPublicKeyQRCodeDialog) && icoPublicKeyQRCodeDialogContainer} </> )} {this.renderUndelegateWalletBox()} {isHardwareWallet ? ( <UnpairWallet openDialogAction={openDialogAction} isDialogOpen={isDialogOpen} unpairWalletDialogContainer={unpairWalletDialogContainer} onBlockForm={this.onBlockForm} /> ) : ( <DeleteWallet openDialogAction={openDialogAction} isDialogOpen={isDialogOpen} deleteWalletDialogContainer={deleteWalletDialogContainer} onBlockForm={this.onBlockForm} /> )} </div> ); } } export default WalletSettings; ```
/content/code_sandbox/source/renderer/app/components/wallet/settings/WalletSettings.tsx
xml
2016-10-05T13:48:54
2024-08-13T22:03:19
daedalus
input-output-hk/daedalus
1,230
3,092
```xml import withLegend, { LegendProps } from './withLegend'; import LegendView from './legendView'; export { LegendProps, withLegend, LegendView }; export default withLegend(LegendView); ```
/content/code_sandbox/packages/f2/src/components/legend/index.tsx
xml
2016-08-29T06:26:23
2024-08-16T15:50:14
F2
antvis/F2
7,877
41
```xml import { InferAttributes, InferCreationAttributes, Op, type SaveOptions, type FindOptions, } from "sequelize"; import { BelongsTo, Column, Default, ForeignKey, IsIn, Table, DataType, Scopes, AfterCreate, AfterUpdate, } from "sequelize-typescript"; import { CollectionPermission, DocumentPermission } from "@shared/types"; import Collection from "./Collection"; import Document from "./Document"; import Group from "./Group"; import User from "./User"; import ParanoidModel from "./base/ParanoidModel"; import Fix from "./decorators/Fix"; /** * Represents a group's permission to access a collection or document. */ @Scopes(() => ({ withGroup: { include: [ { association: "group", }, ], }, withCollection: { where: { collectionId: { [Op.ne]: null, }, }, include: [ { association: "collection", }, ], }, withDocument: { where: { documentId: { [Op.ne]: null, }, }, include: [ { association: "document", }, ], }, })) @Table({ tableName: "group_permissions", modelName: "group_permission" }) @Fix class GroupMembership extends ParanoidModel< InferAttributes<GroupMembership>, Partial<InferCreationAttributes<GroupMembership>> > { @Default(CollectionPermission.ReadWrite) @IsIn([Object.values(CollectionPermission)]) @Column(DataType.STRING) permission: CollectionPermission | DocumentPermission; // associations /** The collection that this permission grants the group access to. */ @BelongsTo(() => Collection, "collectionId") collection?: Collection | null; /** The collection ID that this permission grants the group access to. */ @ForeignKey(() => Collection) @Column(DataType.UUID) collectionId?: string | null; /** The document that this permission grants the group access to. */ @BelongsTo(() => Document, "documentId") document?: Document | null; /** The document ID that this permission grants the group access to. */ @ForeignKey(() => Document) @Column(DataType.UUID) documentId?: string | null; /** If this represents the permission on a child then this points to the permission on the root */ @BelongsTo(() => GroupMembership, "sourceId") source?: GroupMembership | null; /** If this represents the permission on a child then this points to the permission on the root */ @ForeignKey(() => GroupMembership) @Column(DataType.UUID) sourceId?: string | null; /** The group that this permission is granted to. */ @BelongsTo(() => Group, "groupId") group: Group; /** The group ID that this permission is granted to. */ @ForeignKey(() => Group) @Column(DataType.UUID) groupId: string; /** The user that created this permission. */ @BelongsTo(() => User, "createdById") createdBy: User; /** The user ID that created this permission. */ @ForeignKey(() => User) @Column(DataType.UUID) createdById: string; /** * Find the root membership for a document and (optionally) group. * * @param documentId The document ID to find the membership for. * @param groupId The group ID to find the membership for. * @param options Additional options to pass to the query. * @returns A promise that resolves to the root memberships for the document and group, or null. */ static async findRootMembershipsForDocument( documentId: string, groupId?: string, options?: FindOptions<GroupMembership> ): Promise<GroupMembership[]> { const memberships = await this.findAll({ where: { documentId, ...(groupId ? { groupId } : {}), }, }); const rootMemberships = await Promise.all( memberships.map((membership) => membership?.sourceId ? this.findByPk(membership.sourceId, options) : membership ) ); return rootMemberships.filter(Boolean) as GroupMembership[]; } @AfterUpdate static async updateSourcedMemberships( model: GroupMembership, options: SaveOptions<GroupMembership> ) { if (model.sourceId || !model.documentId) { return; } const { transaction } = options; if (model.changed("permission")) { await this.update( { permission: model.permission, }, { where: { sourceId: model.id, }, transaction, } ); } } @AfterCreate static async createSourcedMemberships( model: GroupMembership, options: SaveOptions<GroupMembership> ) { if (model.sourceId || !model.documentId) { return; } return this.recreateSourcedMemberships(model, options); } /** * Recreate all sourced permissions for a given permission. */ static async recreateSourcedMemberships( model: GroupMembership, options: SaveOptions<GroupMembership> ) { if (!model.documentId) { return; } const { transaction } = options; await this.destroy({ where: { sourceId: model.id, }, transaction, }); const document = await Document.unscoped().findOne({ attributes: ["id"], where: { id: model.documentId, }, transaction, }); if (!document) { return; } const childDocumentIds = await document.findAllChildDocumentIds( { publishedAt: { [Op.ne]: null, }, }, { transaction, } ); for (const childDocumentId of childDocumentIds) { await this.create( { documentId: childDocumentId, groupId: model.groupId, permission: model.permission, sourceId: model.id, createdById: model.createdById, createdAt: model.createdAt, updatedAt: model.updatedAt, }, { transaction, } ); } } } export default GroupMembership; ```
/content/code_sandbox/server/models/GroupMembership.ts
xml
2016-05-22T21:31:47
2024-08-16T19:57:22
outline
outline/outline
26,751
1,322
```xml import "reflect-metadata" import { DataSource } from "../../../src/data-source/DataSource" import { closeTestingConnections, createTestingConnections, reloadTestingDatabases, } from "../../utils/test-utils" import { Document } from "../bulk-save-case2/entity/Document" describe("benchmark > bulk-save > case-querybuilder", () => { let connections: DataSource[] before( async () => (connections = await createTestingConnections({ __dirname, enabledDrivers: ["postgres"], })), ) beforeEach(() => reloadTestingDatabases(connections)) after(() => closeTestingConnections(connections)) it("testing bulk save of 10000 objects", () => Promise.all( connections.map(async (connection) => { const documents: Document[] = [] for (let i = 0; i < 10000; i++) { const document = new Document() document.id = i.toString() document.docId = "label/" + i document.context = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel faucibus nunc. Etiam volutpat vel urna in scelerisque. Cras a erat ipsum. " document.label = "label/" + i document.date = new Date() documents.push(document) } await connection .createQueryRunner() .query( `CREATE TABLE "document" ("id" text NOT NULL, "docId" text NOT NULL, "label" text NOT NULL, "context" text NOT NULL, "date" TIMESTAMP WITH TIME ZONE NOT NULL, CONSTRAINT "PK_e57d3357f83f3cdc0acffc3d777" PRIMARY KEY ("id"))`, ) await connection.manager .createQueryBuilder() .insert() .into("document", [ "id", "docId", "label", "context", "date", ]) .values(documents) .execute() }), )) }) ```
/content/code_sandbox/test/benchmark/bulk-save-querybuilder/bulk-save-querybuilder.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
423
```xml import { c } from 'ttag'; import type { MailSettings } from '@proton/shared/lib/interfaces'; import { SIGN } from '@proton/shared/lib/mail/mailSettings'; import { Option, SelectTwo } from '../../../components'; import type { SelectChangeEvent } from '../../../components/selectTwo/select'; interface Props { id?: string; value?: boolean; mailSettings?: MailSettings; disabled?: boolean; onChange: (value: boolean | undefined) => void; } const SignEmailsSelect = ({ id, value, mailSettings, disabled, onChange }: Props) => { // An `undefined` value indicates the "default" option is selected. // However, `undefined` cannot be used as `Option` identifier, hence we convert to/from `null`. const handleChange = ({ value }: SelectChangeEvent<boolean | null>) => onChange(value === null ? undefined : value); const SIGN_LABEL = c('Signing preference for emails').t`Sign`; const DO_NOT_SIGN_LABEL = c('Signing preference for emails').t`Don't sign`; const globalDefaultText = mailSettings?.Sign === SIGN.ENABLED ? SIGN_LABEL : DO_NOT_SIGN_LABEL; return ( <SelectTwo id={id} value={value === undefined ? null : value} onChange={handleChange} disabled={disabled}> <Option title={c('Default signing preference').t`Use global default (${globalDefaultText})`} value={null} /> <Option title={SIGN_LABEL} value={true} /> <Option title={DO_NOT_SIGN_LABEL} value={false} /> </SelectTwo> ); }; export default SignEmailsSelect; ```
/content/code_sandbox/packages/components/containers/contacts/email/SignEmailsSelect.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
345
```xml import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; import { Component, OnDestroy } from '@angular/core'; import { Observable, Subject, map, takeUntil } from 'rxjs'; @Component({ selector: 'app-content-container', templateUrl: './content-container.component.html', styleUrls: ['./content-container.component.scss'], }) export class ContentContainerComponent implements OnDestroy { isSmall!: Observable<boolean>; destroyed = new Subject<void>(); constructor(breakpointObserver: BreakpointObserver) { this.isSmall = breakpointObserver .observe([Breakpoints.XSmall, Breakpoints.Small]) .pipe( map((result) => result.matches), takeUntil(this.destroyed) ); } ngOnDestroy() { this.destroyed.next(); this.destroyed.complete(); } } ```
/content/code_sandbox/apps/docs-app/src/app/components/content-container/content-container.component.ts
xml
2016-07-11T23:30:52
2024-08-15T15:20:45
covalent
Teradata/covalent
2,228
170
```xml import React, { useEffect } from "react"; import { useTheme } from "@/hooks"; import * as styles from "./Layout.module.scss"; interface Props { children: React.ReactNode; } const Layout: React.FC<Props> = ({ children }: Props) => { const [{ mode }] = useTheme(); useEffect(() => { document.documentElement.className = mode; }, [mode]); return <div className={styles.layout}>{children}</div>; }; export default Layout; ```
/content/code_sandbox/src/components/Layout/Layout.tsx
xml
2016-03-11T21:02:37
2024-08-15T23:09:27
gatsby-starter-lumen
alxshelepenok/gatsby-starter-lumen
1,987
99
```xml <?xml version="1.0" encoding="utf-8"?> <!-- ~ ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <pathInterpolator xmlns:android="path_to_url" xmlns:tools="path_to_url" android:controlX1="0.2" android:controlX2="0.8" android:controlY1="0.0" android:controlY2="1.0" tools:ignore="UnusedAttribute" /> ```
/content/code_sandbox/lib/java/com/google/android/material/progressindicator/res/anim/linear_indeterminate_line1_head_interpolator.xml
xml
2016-12-05T16:11:29
2024-08-16T17:51:42
material-components-android
material-components/material-components-android
16,176
135
```xml <Project Sdk="Tizen.NET.Sdk/1.0.9"> <PropertyGroup> <TargetFramework>tizen40</TargetFramework> <OutputType>Exe</OutputType> <RootNamespace>SkiaSharpSample.Platform</RootNamespace> <AssemblyName>TizenOS</AssemblyName> <DefineConstants>$(DefineConstants);__TIZEN__;</DefineConstants> <LangVersion>8.0</LangVersion> </PropertyGroup> <ItemGroup> <PackageReference Include="Xamarin.Essentials" Version="1.5.1" /> <PackageReference Include="Xamarin.Forms" Version="4.8.0.1821" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\..\binding\SkiaSharp.SceneGraph.Classic\SkiaSharp.SceneGraph.Classic.csproj" /> <ProjectReference Include="..\..\..\..\binding\SkiaSharp.Skottie.Classic\SkiaSharp.Skottie.Classic.csproj" /> <ProjectReference Include="..\Core\Core.csproj" /> <ProjectReference Include="..\..\..\..\binding\SkiaSharp.Classic\SkiaSharp.Classic.csproj" /> <ProjectReference Include="..\..\..\..\source\SkiaSharp.Views\SkiaSharp.Views.Tizen\SkiaSharp.Views.Tizen.csproj" /> <ProjectReference Include="..\..\..\..\source\SkiaSharp.Views.Forms\SkiaSharp.Views.Forms.Tizen\SkiaSharp.Views.Forms.Tizen.csproj" /> <ProjectReference Include="..\..\..\..\binding\HarfBuzzSharp.Classic\HarfBuzzSharp.Classic.csproj" /> <ProjectReference Include="..\..\..\..\source\SkiaSharp.HarfBuzz\SkiaSharp.HarfBuzz\SkiaSharp.HarfBuzz.csproj" /> </ItemGroup> <ItemGroup> <Folder Include="res\" /> <DefaultTpkResFiles Include="..\..\Shared\Media\content-font.ttf"> <Link>res\content-font.ttf</Link> </DefaultTpkResFiles> </ItemGroup> <ItemGroup> <Compile Include="..\..\PlatformShared\*.cs" Link="PlatformShared\%(Filename)%(Extension)" /> </ItemGroup> <Import Project="..\..\..\..\output\SkiaSharp\nuget\build\tizen40\SkiaSharp.targets" Condition="Exists('..\..\..\..\output\SkiaSharp\nuget\build\tizen40\SkiaSharp.targets')" /> <Import Project="..\..\..\..\output\HarfBuzzSharp\nuget\build\tizen40\HarfBuzzSharp.targets" Condition="Exists('..\..\..\..\output\HarfBuzzSharp\nuget\build\tizen40\HarfBuzzSharp.targets')" /> </Project> ```
/content/code_sandbox/samples/Gallery/Xamarin.Forms/Tizen/TizenOS.csproj
xml
2016-02-22T17:54:43
2024-08-16T17:53:42
SkiaSharp
mono/SkiaSharp
4,347
617
```xml import type { MutableRefObject } from 'react'; import { useEffect, useRef } from 'react'; import usePrevious from '@proton/hooks/usePrevious'; const LONG_TAP_TIMEOUT = 500; const OPEN_DELAY_TIMEOUT = 1000; const CLOSE_DELAY_TIMEOUT = 250; let visibleTimeout = 0; let globalId = 0; enum State { Opened, Closing, } type CloseCb = (immediate?: boolean) => void; type OpenCb = (immediate?: boolean) => void; const tooltips = new Map<number, { state: State; close: MutableRefObject<CloseCb> }>(); const closePendingTooltips = () => { for (let [id, entry] of tooltips) { if (entry.state === State.Closing) { entry.close.current(); tooltips.delete(id); } } }; interface Props { open: OpenCb; close: CloseCb; isOpen: boolean; isExternalOpen?: boolean; openDelay?: number; closeDelay?: number; longTapDelay?: number; } const useTooltipHandlers = ({ open: outsideOpen, close: outsideClose, isOpen, isExternalOpen, openDelay = OPEN_DELAY_TIMEOUT, closeDelay = CLOSE_DELAY_TIMEOUT, longTapDelay = LONG_TAP_TIMEOUT, }: Props) => { const idRef = useRef(-1); if (idRef.current === -1) { idRef.current = ++globalId; } const id = idRef.current; const closeTimeoutRef = useRef(0); const longTapTimeoutRef = useRef(0); const ignoreFocusRef = useRef(false); const ignoreNonTouchEventsRef = useRef(false); const ignoreNonTouchEventsTimeoutRef = useRef(0); const closeRef = useRef(outsideClose); const openRef = useRef(outsideOpen); const wasExternallyOpened = usePrevious(isExternalOpen); useEffect(() => { const entry = tooltips.get(id); if (!entry) { return; } closeRef.current = outsideClose; openRef.current = outsideOpen; }); useEffect(() => { return () => { window.clearTimeout(closeTimeoutRef.current); window.clearTimeout(longTapTimeoutRef.current); window.clearTimeout(ignoreNonTouchEventsTimeoutRef.current); tooltips.get(id)?.close.current(); tooltips.delete(id); }; }, [id]); const open = (immediate?: boolean) => { window.clearTimeout(visibleTimeout); window.clearTimeout(closeTimeoutRef.current); const oldTooltip = tooltips.get(id); tooltips.set(id, { state: State.Opened, close: closeRef }); if (oldTooltip?.state === State.Closing) { return; } closePendingTooltips(); openRef.current(immediate); }; const close = () => { window.clearTimeout(visibleTimeout); // Trying to close something that isn't open. if (tooltips.get(id)?.state !== State.Opened) { return; } window.clearTimeout(closeTimeoutRef.current); if (!closeDelay) { outsideClose(); tooltips.delete(id); return; } tooltips.set(id, { state: State.Closing, close: closeRef }); closeTimeoutRef.current = window.setTimeout(() => { const entry = tooltips.get(id); if (entry?.state === State.Closing) { entry.close.current(false); tooltips.delete(id); } }, closeDelay); }; const handleCloseTooltip = () => { window.clearTimeout(longTapTimeoutRef.current); longTapTimeoutRef.current = 0; window.clearTimeout(ignoreNonTouchEventsTimeoutRef.current); // Clear non-touch events after a small timeout to avoid the focus event accidentally triggering it after touchend // touchstart -> touchend -> focus ignoreNonTouchEventsTimeoutRef.current = window.setTimeout(() => { ignoreNonTouchEventsRef.current = false; }, 100); close(); }; useEffect(() => { if (!isOpen) { return; } // Edge case for elements that don't gain focus, they'll never receive a blur event to close the tooltip // for example if long-tapping a span with text, this is to force close the tooltip on next touchstart document.addEventListener('touchstart', close); return () => { document.removeEventListener('touchstart', close); }; }, [isOpen, close]); const handleTouchStart = () => { window.clearTimeout(ignoreNonTouchEventsTimeoutRef.current); ignoreNonTouchEventsTimeoutRef.current = 0; window.clearTimeout(longTapTimeoutRef.current); // Initiate a long-tap timer to open the tooltip on touch devices longTapTimeoutRef.current = window.setTimeout(() => { open(); longTapTimeoutRef.current = 0; }, longTapDelay); // Also set to ignore non-touch events ignoreNonTouchEventsRef.current = true; }; const handleTouchEnd = () => { // Tooltip was opened from a long tap, no need to close if (isOpen && !longTapTimeoutRef.current) { return; } // Otherwise it's either not opened or it wasn't opened from the long tap, so we can set to close the tooltip window.clearTimeout(longTapTimeoutRef.current); longTapTimeoutRef.current = 0; handleCloseTooltip(); }; const handleMouseEnter = () => { if (ignoreNonTouchEventsRef.current) { return; } window.clearTimeout(visibleTimeout); if (tooltips.size || !openDelay || isOpen) { open(); } else { visibleTimeout = window.setTimeout(() => { open(false); }, openDelay); } }; const handleMouseDown = () => { if (ignoreNonTouchEventsRef.current) { return; } // Close the tooltip on mouse down, and ignore the upcoming focus event (on chrome) ignoreFocusRef.current = true; close(); }; const handleMouseLeave = () => { // Reset ignore focus when leaving the element ignoreFocusRef.current = false; if (ignoreNonTouchEventsRef.current) { return; } close(); }; const handleFocus = () => { // Reset ignore focus if it's set. Manages the case for // mousedown -> mouseup -> focus // and mouseleave never triggered, just as a safety mechanism to reset ignore if (ignoreNonTouchEventsRef.current || ignoreFocusRef.current) { ignoreFocusRef.current = false; return; } open(); }; useEffect(() => { /** * if `isExternalOpen` shifted from being `true` * to `undefined` we can safely close the tooltip : * the tooltip is no longer externally controllable * (ie: errored InputField lost focus) */ if (isExternalOpen === undefined) { if (wasExternallyOpened) { close(); } return; } if (isExternalOpen && !isOpen) { return open(); } if (!isExternalOpen && isOpen) { return close(); } }, [isExternalOpen, isOpen]); if (isExternalOpen !== undefined) { return {}; } return { onTouchEnd: handleTouchEnd, onTouchStart: handleTouchStart, onMouseDown: handleMouseDown, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onFocus: handleFocus, onBlur: handleCloseTooltip, }; }; export default useTooltipHandlers; ```
/content/code_sandbox/packages/components/components/tooltip/useTooltipHandlers.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
1,631
```xml <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>TextChatWindow</class> <widget class="QWidget" name="TextChatWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>450</width> <height>500</height> </rect> </property> <property name="windowTitle"> <string>System Information</string> </property> <layout class="QVBoxLayout" name="verticalLayout_2"> <property name="spacing"> <number>0</number> </property> <property name="leftMargin"> <number>0</number> </property> <property name="topMargin"> <number>0</number> </property> <property name="rightMargin"> <number>0</number> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="common::TextChatWidget" name="text_chat_widget" native="true"/> </item> </layout> <action name="action_save"> <property name="icon"> <iconset resource="../resources/client.qrc"> <normaloff>:/img/disk.png</normaloff>:/img/disk.png</iconset> </property> <property name="text"> <string>Save</string> </property> <property name="toolTip"> <string>Save (Ctrl+S)</string> </property> <property name="shortcut"> <string notr="true">Ctrl+S</string> </property> </action> <action name="action_print"> <property name="icon"> <iconset resource="../resources/client.qrc"> <normaloff>:/img/printer.png</normaloff>:/img/printer.png</iconset> </property> <property name="text"> <string>Print</string> </property> <property name="toolTip"> <string>Print (Ctrl+P)</string> </property> <property name="shortcut"> <string notr="true">Ctrl+P</string> </property> </action> <action name="action_copy_row"> <property name="text"> <string>Copy Row</string> </property> </action> <action name="action_copy_name"> <property name="text"> <string>Copy Name</string> </property> </action> <action name="action_copy_value"> <property name="text"> <string>Copy Value</string> </property> </action> <action name="action_refresh"> <property name="icon"> <iconset resource="../resources/client.qrc"> <normaloff>:/img/arrow-circle-double.png</normaloff>:/img/arrow-circle-double.png</iconset> </property> <property name="text"> <string>Refresh</string> </property> <property name="toolTip"> <string>Refresh (F5)</string> </property> <property name="shortcut"> <string notr="true">F5</string> </property> </action> </widget> <customwidgets> <customwidget> <class>common::TextChatWidget</class> <extends>QWidget</extends> <header>common/ui/text_chat_widget.h</header> <container>1</container> </customwidget> </customwidgets> <resources> <include location="../resources/client.qrc"/> </resources> <connections/> </ui> ```
/content/code_sandbox/source/client/ui/text_chat/qt_text_chat_window.ui
xml
2016-10-26T16:17:31
2024-08-16T13:37:42
aspia
dchapyshev/aspia
1,579
821
```xml <!-- ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <dataset> <metadata> <column name="host"/> <column name="event"/> <column name="total"/> <column name="total_latency"/> <column name="avg_latency"/> <column name="max_latency"/> </metadata> </dataset> ```
/content/code_sandbox/test/e2e/sql/src/test/resources/cases/dql/dataset/empty_storage_units/mysql/select_mysql_sys_waits_by_host_by_latency.xml
xml
2016-01-18T12:49:26
2024-08-16T15:48:11
shardingsphere
apache/shardingsphere
19,707
131
```xml #!/usr/bin/env node import chalk from 'chalk'; import { statSync } from 'fs'; import { relative } from 'path'; import prompts from 'prompts'; import * as Android from './Android'; import * as Ios from './Ios'; import { CommandError, Options } from './Options'; function fileExists(filePath: string): boolean { try { return statSync(filePath).isFile(); } catch { return false; } } export function getAvailablePlatforms( options: Pick<Options, 'projectRoot' | 'infoPath' | 'manifestPath'> ): string[] { const platforms: string[] = []; if (options.infoPath) { if (!fileExists(options.infoPath)) { throw new CommandError(`Custom Info.plist does not exist at path "${options.infoPath}"`); } platforms.push('ios'); } else if (Ios.isAvailable(options.projectRoot)) { platforms.push('ios'); } if (options.manifestPath) { if (!fileExists(options.manifestPath)) { throw new CommandError( `Custom AndroidManifest.xml does not exist at path "${options.manifestPath}"` ); } platforms.push('android'); } else if (Android.isAvailable(options.projectRoot)) { platforms.push('android'); } return platforms; } /** * Ensure the URI scheme is a valid string. * * @param uri URI scheme prefix to validate */ function ensureUriString(uri: any): string { if (!uri) { throw new CommandError('Please supply a URI protocol'); } if (typeof uri !== 'string') { throw new CommandError(`URI protocol should be of type string. Instead got: ${typeof uri}`); } return uri.trim(); } /** * Normalize a URI scheme prefix according to [RFC 2396](path_to_url * * @param uri URI scheme prefix to validate */ async function normalizeUriProtocolAsync(uri: any): Promise<string> { const trimmedUri = ensureUriString(uri); const [protocol] = trimmedUri.split(':'); const normalizedUri = protocol.toLowerCase(); if (normalizedUri !== uri) { // Create a warning. if (normalizedUri) { console.log( chalk.yellow( `\u203A Supplied URI protocol "${trimmedUri}" does not match normalized scheme "${normalizedUri}".` ) ); const { answer } = await prompts({ type: 'confirm', name: 'answer', message: `Would you like to use "${normalizedUri}" instead?`, initial: true, }); if (answer) return normalizedUri; } else { throw new CommandError( `Supplied URI protocol "${trimmedUri}" does not appear to be spec compliant: path_to_url` ); } } return trimmedUri; } export async function addAsync(options: Options): Promise<string[]> { // Although schemes are case-insensitive, the canonical form is // lowercase and documents that specify schemes must do so with lowercase letters. options.uri = await normalizeUriProtocolAsync(options.uri); const results: string[] = []; let actionOccurred = false; if (options.ios) { if (await Ios.addAsync(options)) { actionOccurred = true; logPlatformMessage('iOS', `Added URI protocol "${options.uri}" to project`); results.push('ios'); } } if (options.android) { if (await Android.addAsync(options)) { actionOccurred = true; logPlatformMessage('Android', `Added URI protocol "${options.uri}" to project`); results.push('android'); } } if (!actionOccurred) { console.log( chalk.yellow( 'No URI schemes could be added. Please ensure there is a native project available.' ) ); } return results; } export async function removeAsync(options: Options): Promise<string[]> { options.uri = ensureUriString(options.uri); const results: string[] = []; let actionOccurred = false; if (options.ios) { if (await Ios.removeAsync(options)) { actionOccurred = true; logPlatformMessage('iOS', `Removed URI protocol "${options.uri}" from project`); results.push('ios'); } } if (options.android) { if (await Android.removeAsync(options)) { actionOccurred = true; logPlatformMessage('Android', `Removed URI protocol "${options.uri}" from project`); results.push('android'); } } if (!actionOccurred) { console.log( chalk.yellow( 'No URI schemes could be removed. Please ensure there is a native project available.' ) ); } return results; } export async function openAsync( options: Pick<Options, 'uri' | 'ios' | 'android' | 'projectRoot'> & { androidPackage?: string } ): Promise<void> { options.uri = ensureUriString(options.uri); if (options.ios) { logPlatformMessage('iOS', `Opening URI "${options.uri}" in simulator`); await Ios.openAsync(options); } if (options.android) { logPlatformMessage('Android', `Opening URI "${options.uri}" in emulator`); await Android.openAsync(options); } } export async function listAsync( options: Pick<Options, 'infoPath' | 'projectRoot' | 'manifestPath'> ): Promise<void> { let actionOccurred = false; if (options.infoPath) { actionOccurred = true; const schemes = await Ios.getAsync(options); logPlatformMessage( 'iOS', `Schemes for config: ./${relative(options.projectRoot, options.infoPath)}` ); logSchemes(schemes); } if (options.manifestPath) { actionOccurred = true; const schemes = await Android.getAsync(options); logPlatformMessage( 'Android', `Schemes for config: ./${relative(options.projectRoot, options.manifestPath)}` ); logSchemes(schemes); } if (!actionOccurred) { console.log(chalk.yellow('Could not find any native URI schemes to list.')); } } function logPlatformMessage(platform: string, message: string): void { console.log(chalk.magenta(`\u203A ${chalk.bold(platform)}: ${message}`)); } function logSchemes(schemes: string[]): void { for (const scheme of schemes) console.log(`${chalk.dim('\u203A ')}${scheme}${chalk.dim('://')}`); console.log(''); } ```
/content/code_sandbox/packages/uri-scheme/src/URIScheme.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
1,402
```xml export enum eMethodModifier { Public = '', Private = 'private ', Async = 'async ', PrivateAsync = 'private async ', } ```
/content/code_sandbox/npm/ng-packs/packages/schematics/src/enums/method-modifier.ts
xml
2016-12-03T22:56:24
2024-08-16T16:24:05
abp
abpframework/abp
12,657
32
```xml import * as React from 'react'; import { useSelector } from 'react-redux'; import { IRepository } from 'shared/models/Versioning/Repository'; import { IFolderElement, IFullCommitComponentLocationComponents, } from 'shared/models/Versioning/RepositoryData'; import matchType from 'shared/utils/matchType'; import { selectCurrentWorkspaceName } from 'features/workspaces/store'; import * as RouteHeplers from '../../../routeHelpers'; import NavigationItem from '../NavigationItem/NavigationItem'; interface ILocalProps { repositoryName: IRepository['name']; fullCommitComponentLocationComponents: IFullCommitComponentLocationComponents; data: IFolderElement; } const FolderElement = ({ data, repositoryName, fullCommitComponentLocationComponents, }: ILocalProps) => { const currentWorkspaceName = useSelector(selectCurrentWorkspaceName); return ( <NavigationItem name={data.name} iconType={matchType( { folder: () => 'folder', blob: () => 'file' }, data.type )} to={RouteHeplers.addName(data.name, data.type, { ...fullCommitComponentLocationComponents, workspaceName: currentWorkspaceName, repositoryName, })} /> ); }; export default FolderElement; ```
/content/code_sandbox/webapp/client/src/features/versioning/repositoryData/view/RepositoryData/DataNavigation/FolderView/FolderElement/FolderElement.tsx
xml
2016-10-19T01:07:26
2024-08-14T03:53:55
modeldb
VertaAI/modeldb
1,689
270
```xml import React from 'react'; import * as Svg from 'react-native-svg'; import Example from './Example'; const { Circle, Path, Rect, G, Text, ClipPath, Defs } = Svg; function PressExample() { return ( <Svg.Svg height="100" width="100"> <Circle cx="50%" cy="50%" r="38%" fill="red" onPress={() => alert('Press on Circle')} /> <Rect x="20%" y="20%" width="60%" height="60%" fill="blue" onLongPress={() => alert('Long press on Rect')} /> <Path d="M50,5L20,99L95,39L5,39L80,99z" fill="pink" /> </Svg.Svg> ); } PressExample.title = 'Press on the red circle or long press on the blue rectangle to trigger the events'; function HoverExample() { const [hover, setHover] = React.useState(false); return ( <Svg.Svg height="120" width="120"> <Defs> <ClipPath id="clip"> <Circle r="30" cx="50%" cy="50%" /> </ClipPath> </Defs> <G> <G> <Path d="M50,5L20,99L95,39L5,39L80,99z" clipPath="url(#clip)" stroke={hover ? 'rgba(10, 10, 10, 0.5)' : 'black'} fill={hover ? 'pink' : 'red'} strokeWidth="6" delayPressIn={0} onPressIn={() => setHover(true)} onPressOut={() => setHover(false)} x="0" y="0" scale="1.2" /> </G> </G> </Svg.Svg> ); } HoverExample.title = 'Hover the svg path'; function GroupExample() { return ( <Svg.Svg height="120" width="120" viewBox="0 0 240 240"> <G onPress={() => alert('Pressed on G')}> <G scale="1.4"> <G> <Circle cx="80" cy="80" r="30" fill="green" x="20" scale="1.2" /> <Text fontWeight="bold" fontSize="40" x="50" y="10" scale="2" onPress={() => alert('Pressed on Text')}> H </Text> <Rect x="20" y="20" width="40" height="40" fill="yellow" /> </G> </G> </G> </Svg.Svg> ); } GroupExample.title = 'Bind touch events callback on Group element with viewBox'; const icon = ( <Svg.Svg height="20" width="20"> <Circle fill="#ccc" stroke="#000" cx="11.1" cy="4.4" r="2.6" /> <Path fill="#fff" stroke="#000" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" d={` M6.2,9.4 c0,0,0-0.1,0-0.2c0-0.2,0.1-0.3,0.1-0.4c0.2-0.4,0.5-0.7,1-0.7c0.3,0,0.5,0,0.6,0h0.1v0.7V10 M8.1,8.8c0,0,0-0.1,0-0.2 c0-0.2,0.1-0.3,0.1-0.4c0.2-0.4,0.5-0.7,1-0.7c0.3,0,0.5,0,0.6,0h0.1v1.9 M10.1,7.5v-2c0,0,0-0.1,0-0.2c0-0.2,0.1-0.3,0.1-0.4 c0.2-0.4,0.5-0.6,0.9-0.7c0.4,0,0.7,0.2,0.9,0.7C12,5,12,5.2,12,5.4c0,0.1,0,0.1,0,0.2v6c1.4-1.8,2.4-1.8,2.8,0.1 c-1.7,1.5-2.9,3.7-3.4,6.4l-5.8,0c-0.2-0.6-0.5-1.4-0.7-2.5c-0.3-1-0.5-2.5-0.6-4.5l0-0.8c0-0.1,0-0.1,0-0.2c0-0.2,0.1-0.3,0.1-0.4 c0.2-0.4,0.5-0.7,1-0.7c0.3,0,0.5,0,0.6,0l0.1,0v0.5c0,0,0,0,0,0l0,1.1l0,0.2 M6.2,10.9l0-0.4 `} /> </Svg.Svg> ); const TouchEvents: Example = { icon, samples: [PressExample, HoverExample, GroupExample], }; export default TouchEvents; ```
/content/code_sandbox/apps/native-component-list/src/screens/SVG/examples/TouchEvents.tsx
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
1,310
```xml /* * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. * */ import { InvalidPeerInfoError, PeerInboundHandshakeError, RPCResponseError, InvalidRPCResponseError, InvalidProtocolMessageError, InvalidRPCRequestError, RPCResponseAlreadySentError, RequestFailError, ExistingPeerError, InvalidNodeInfoError, } from '../../src/errors'; import { p2pTypes } from '../../src'; import { constructPeerId } from '../../src/utils'; describe('errors', () => { describe('#PeerInboundHandshakeError', () => { const remoteAddress = '127.0.0.1'; const statusCode = 4501; const defaultMessage = `Received inbound connection from peer ${remoteAddress} which is already in our triedPeers map.`; let peerTransportError: PeerInboundHandshakeError; beforeEach(() => { peerTransportError = new PeerInboundHandshakeError(defaultMessage, statusCode, remoteAddress); }); it('should create a new instance of PeerInboundHandshakeError', () => { expect(peerTransportError).toBeInstanceOf(PeerInboundHandshakeError); }); it('should set error name to `PeerInboundHandshakeError`', () => { expect(peerTransportError.name).toBe('PeerInboundHandshakeError'); }); it('should set error property remoteAddress when passed as an argument', () => { expect(peerTransportError.remoteAddress).toEqual(remoteAddress); }); }); describe('#RPCResponseError', () => { const peerId = '127.0.0.1:5001'; const defaultMessage = `Error when fetching peerlist of peer with peer Id ${peerId}`; let rpcGetPeersFailed: RPCResponseError; beforeEach(() => { rpcGetPeersFailed = new RPCResponseError(defaultMessage, peerId); }); it('should create a new instance of RPCResponseError', () => { expect(rpcGetPeersFailed).toBeInstanceOf(RPCResponseError); }); it('should set error name to `RPCResponseError`', () => { expect(rpcGetPeersFailed.name).toBe('RPCResponseError'); }); it('should set error property peer Id when passed as an argument', () => { expect(rpcGetPeersFailed).toMatchObject({ name: 'RPCResponseError', peerId: constructPeerId('127.0.0.1', 5001), }); }); }); describe('#InvalidPeerInfoError', () => { const defaultMessage = 'Invalid peer ipAddress or port'; let invalidPeer: InvalidPeerInfoError; beforeEach(() => { invalidPeer = new InvalidPeerInfoError(defaultMessage); }); it('should create a new instance of InvalidPeerInfoError', () => { expect(invalidPeer).toBeInstanceOf(InvalidPeerInfoError); }); it('should set error name to `InvalidPeerInfoError`', () => { expect(invalidPeer.name).toBe('InvalidPeerInfoError'); }); it('should set error message when passed an argument', () => { expect(invalidPeer.message).toEqual(defaultMessage); }); }); describe('#ExistingPeerError', () => { const existingPeerErrorMessagge = 'Peer already exists'; const peerInfo: p2pTypes.P2PPeerInfo = { ipAddress: '0.0.0.0', port: 5000, peerId: constructPeerId('0.0.0.0', 5000), }; let existingPeer: ExistingPeerError; beforeEach(() => { existingPeer = new ExistingPeerError(peerInfo); }); it('should create a new instance of ExistingPeerError', () => { expect(existingPeer).toBeInstanceOf(ExistingPeerError); }); it('should set error name to `ExistingPeerError`', () => { expect(existingPeer.name).toBe('ExistingPeerError'); }); it(`should set error message to ${existingPeerErrorMessagge}`, () => { expect(existingPeer.message).toEqual(existingPeerErrorMessagge); }); it('should set peerInfo parameter when passing an argument', () => { expect(existingPeer.peerInfo).toEqual(peerInfo); }); }); describe('#InvalidNodeInfoError', () => { const InvalidNodeInfoErrorMessagge = 'Invalid NodeInfo version'; let invalidNodeInfo: InvalidNodeInfoError; beforeEach(() => { invalidNodeInfo = new InvalidNodeInfoError(InvalidNodeInfoErrorMessagge); }); it('should create a new instance of InvalidNodeInfoError', () => { expect(invalidNodeInfo).toBeInstanceOf(InvalidNodeInfoError); }); it('should set error name to `InvalidNodeInfoError`', () => { expect(invalidNodeInfo.name).toBe('InvalidNodeInfoError'); }); // eslint-disable-next-line @typescript-eslint/restrict-template-expressions it(`should set error message to ${InvalidNodeInfoError}`, () => { expect(invalidNodeInfo.message).toEqual(InvalidNodeInfoErrorMessagge); }); }); describe('#InvalidRPCResponseError', () => { const defaultMessage = 'Invalid response type'; let invalidRPCResponse: InvalidRPCResponseError; beforeEach(() => { invalidRPCResponse = new InvalidRPCResponseError(defaultMessage); }); it('should create a new instance of InvalidRPCResponse', () => { expect(invalidRPCResponse).toBeInstanceOf(InvalidRPCResponseError); }); it('should set error name to `InvalidRPCResponseError`', () => { expect(invalidRPCResponse.name).toBe('InvalidRPCResponseError'); }); it('should set error message when passed an argument', () => { expect(invalidRPCResponse.message).toEqual(defaultMessage); }); }); describe('#InvalidProtocolMessageError', () => { const defaultMessage = 'Invalid protocol message'; let invalidProtocolMessageError: InvalidProtocolMessageError; beforeEach(() => { invalidProtocolMessageError = new InvalidProtocolMessageError(defaultMessage); }); it('should create a new instance of InvalidProtocolMessageError', () => { expect(invalidProtocolMessageError).toBeInstanceOf(InvalidProtocolMessageError); }); it('should set error name to `InvalidProtocolMessageError`', () => { expect(invalidProtocolMessageError.name).toBe('InvalidProtocolMessageError'); }); it('should set error message when passed an argument', () => { expect(invalidProtocolMessageError.message).toEqual(defaultMessage); }); }); describe('#InvalidRPCRequestError', () => { let invalidRPCRequestError: InvalidRPCRequestError; const defaultMessage = 'Invalid RPC request error'; beforeEach(() => { invalidRPCRequestError = new InvalidRPCRequestError(defaultMessage); }); it('should create a new instance of InvalidRPCRequestError', () => { expect(invalidRPCRequestError).toBeInstanceOf(InvalidRPCRequestError); }); it('should set error name to `InvalidRPCRequestError`', () => { expect(invalidRPCRequestError.name).toBe('InvalidRPCRequestError'); }); it('should set error message when passed an argument', () => { expect(invalidRPCRequestError.message).toEqual(defaultMessage); }); }); describe('#RPCResponseAlreadySentError', () => { const defaultMessage = 'Response was already sent'; let rpcResponseAlreadySentError: RPCResponseAlreadySentError; beforeEach(() => { rpcResponseAlreadySentError = new RPCResponseAlreadySentError(defaultMessage); }); it('should create a new instance of RPCResponseAlreadySentError', () => { expect(rpcResponseAlreadySentError).toBeInstanceOf(RPCResponseAlreadySentError); }); it('should set error name to `RPCResponseAlreadySentError`', () => { expect(rpcResponseAlreadySentError.name).toBe('ResponseAlreadySentError'); }); it('should set error message when passed an argument', () => { expect(rpcResponseAlreadySentError.message).toEqual(defaultMessage); }); }); describe('#RequestFailError', () => { const defaultMessage = 'Request failed due to no peers found in peer selection'; const errorResponseMessage = 'Invalid block id'; const response = new Error(errorResponseMessage); const peerId = '127.0.0.1:4000'; const peerVersion = '1.5.0'; let requestFailError: RequestFailError; beforeEach(() => { requestFailError = new RequestFailError(defaultMessage, response, peerId, peerVersion); }); it('should create a new instance of RequestFailError', () => { expect(requestFailError).toBeInstanceOf(RequestFailError); }); it('should set error name to `RequestFailError`', () => { expect(requestFailError.name).toBe('RequestFailError'); }); it('should set error message when passed an argument', () => { expect(requestFailError.message).toBe( `${defaultMessage}: Peer Id: ${peerId}: Peer Version: ${peerVersion}`, ); }); it('should set response object within this custom error', () => { expect(requestFailError.response).toMatchObject({ message: errorResponseMessage, }); }); }); }); ```
/content/code_sandbox/elements/lisk-p2p/test/unit/errors.spec.ts
xml
2016-02-01T21:45:35
2024-08-15T19:16:48
lisk-sdk
LiskArchive/lisk-sdk
2,721
2,129
```xml import seedrandom from "seedrandom"; import { variable } from "../engine/Autodiff.js"; import * as ad from "../types/ad.js"; import { OptStages } from "../types/state.js"; import { ColorV, FloatV, VectorV } from "../types/value.js"; import { colorV, floatV, randFloat, vectorV } from "../utils/Util.js"; type Range = [number, number]; // NOTE: I moved `canvasSize` here from Canvas.tsx, which re-exports it, to avoid a circular import in `Style`. // export const canvasSize: [number, number] = [800, 700]; // export const canvasXRange: Range = [-canvasSize[0] / 2, canvasSize[0] / 2]; // export const canvasYRange: Range = [-canvasSize[1] / 2, canvasSize[1] / 2]; export interface Canvas { width: number; height: number; size: [number, number]; xRange: Range; yRange: Range; } export const makeCanvas = (width: number, height: number): Canvas => ({ width, height, size: [width, height], xRange: [-width / 2, width / 2], yRange: [-height / 2, height / 2], }); export type Sampler = (rng: seedrandom.prng) => number; export interface Pending { tag: "Pending"; pending: number; // placeholder value to use until label collection completes } export interface Sampled { tag: "Sampled"; sampler: Sampler; } export interface InputMeta { init: Pending | Sampled; stages: OptStages; // can be the empty set, meaning unoptimized } export type InputFactory = (meta: InputMeta) => ad.Var; // NOTE: stateful! export interface Context { makeInput: InputFactory; } /** * Return a simple `Context` which starts with a `seedrandom` PRNG seeded with * `variation`, and for each `makeInput` invocation, sets `val` by calling the * using the given `sampler` or placeholder `pending` value. */ export const simpleContext = (variation: string): Context => { const rng = seedrandom(variation); return { makeInput: (meta) => variable( meta.init.tag === "Sampled" ? meta.init.sampler(rng) : meta.init.pending, ), }; }; export const uniform = (min: number, max: number): Sampler => (rng: seedrandom.prng) => randFloat(rng, min, max); export const constSampler = (n: number): Sampler => (rng: seedrandom.prng) => n; export const sampleVector = ( { makeInput }: Context, canvas: Canvas, ): VectorV<ad.Num> => vectorV([ makeInput({ init: { tag: "Sampled", sampler: uniform(...canvas.xRange) }, stages: "All", }), makeInput({ init: { tag: "Sampled", sampler: uniform(...canvas.yRange) }, stages: "All", }), ]); export const sampleWidth = ( { makeInput }: Context, canvas: Canvas, ): FloatV<ad.Num> => floatV( makeInput({ // BUG: when canvas width is too small this will error out init: { tag: "Sampled", sampler: uniform(3, canvas.width / 6) }, stages: "All", }), ); export const sampleHeight = ( { makeInput }: Context, canvas: Canvas, ): FloatV<ad.Num> => floatV( makeInput({ // BUG: when canvas width is too small this will error out init: { tag: "Sampled", sampler: uniform(3, canvas.height / 6) }, stages: "All", }), ); export const sampleStroke = ({ makeInput }: Context): FloatV<ad.Num> => floatV( makeInput({ init: { tag: "Sampled", sampler: uniform(0.5, 3) }, stages: "All", }), ); export const sampleColor = ({ makeInput }: Context): ColorV<ad.Num> => { const [min, max] = [0.1, 0.9]; return colorV({ tag: "RGBA", contents: [ makeInput({ init: { tag: "Sampled", sampler: uniform(min, max) }, stages: "All", }), makeInput({ init: { tag: "Sampled", sampler: uniform(min, max) }, stages: "All", }), makeInput({ init: { tag: "Sampled", sampler: uniform(min, max) }, stages: "All", }), 0.5, ], }); }; ```
/content/code_sandbox/packages/core/src/shapes/Samplers.ts
xml
2016-09-22T04:47:19
2024-08-16T13:00:54
penrose
penrose/penrose
6,760
1,067
```xml export const colors = { green: { hex: '#00ff00', rgb: 'rgb(0, 255, 0)' }, red: { hex: '#ff0000', rgb: 'rgb(255, 0, 0)' }, blue: { hex: '#0000ff', rgb: 'rgb(0, 0, 255)' }, orange: { hex: '#ffa500', rgb: 'rgb(255, 165, 0)' }, purple: { hex: '#a020f0', rgb: 'rgb(160, 32, 240)' }, black: { hex: '#000000', rgb: 'rgb(0, 0, 0)' }, }; ```
/content/code_sandbox/tests/playwright/enums/colors.ts
xml
2016-05-30T13:05:46
2024-08-16T13:13:10
elementor
elementor/elementor
6,507
156
```xml /* * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * * path_to_url * * Unless required by applicable law or agreed to in writing, * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * specific language governing permissions and limitations */ #import "WXRichText.h" #import "WXSDKManager.h" #import "WXSDKEngine.h" #import "WXConvert.h" #import "WXSDKInstance.h" #import "WXComponent+Layout.h" #import "WXNavigationProtocol.h" #import "WXImgLoaderProtocol.h" #import "WXComponentManager.h" #import "WXLog.h" #import "WXDarkSchemeProtocol.h" #import "WXAssert.h" #include <pthread/pthread.h> @interface WXRichNode : NSObject @property (nonatomic, strong) NSString *type; @property (nonatomic, strong) NSString *ref; @property (nonatomic, strong) NSString *text; @property (nonatomic, strong) UIColor *color; @property (nonatomic, strong) UIColor *darkSchemeColor; @property (nonatomic, strong) UIColor *lightSchemeColor; @property (nonatomic, strong) UIColor *backgroundColor; @property (nonatomic, strong) UIColor *darkSchemeBackgroundColor; @property (nonatomic, strong) UIColor *lightSchemeBackgroundColor; @property (nonatomic, strong) NSString *fontFamily; @property (nonatomic, assign) CGFloat fontSize; @property (nonatomic, assign) CGFloat fontWeight; @property (nonatomic, assign) WXTextStyle fontStyle; @property (nonatomic, assign) WXTextDecoration textDecoration; @property (nonatomic, strong) NSString *pseudoRef; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat height; @property (nonatomic, strong) NSURL *href; @property (nonatomic, strong) NSURL *src; @property (nonatomic, assign) NSRange range; @property (nonatomic, strong) NSMutableArray *childNodes; @end @implementation WXRichNode - (instancetype)init { if (self = [super init]) { _childNodes = [[NSMutableArray alloc] init]; } return self; } @end @interface WXRichTextView : UITextView @end @implementation WXRichTextView - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.isAccessibilityElement = YES; self.accessibilityTraits |= UIAccessibilityTraitStaticText; self.opaque = NO; self.editable = NO; self.contentMode = UIViewContentModeRedraw; self.textContainerInset = UIEdgeInsetsZero; self.textContainer.lineFragmentPadding = 0.0f; self.textContainer.lineBreakMode = NSLineBreakByClipping; } return self; } @end #define WX_STYLE_FILL_RICHTEXT(key, type)\ do {\ id value = styles[@#key]; \ if (value) { \ node.key = [WXConvert type:value];\ } else if (!([@#key isEqualToString:@"backgroundColor"] || \ [@#key isEqualToString:@"weexDarkSchemeBackgroundColor"] || \ [@#key isEqualToString:@"textDecoration"]) && superNode.key ) { \ node.key = superNode.key; \ } \ } while(0); #define WX_STYLE_FILL_RICHTEXT_PIXEL(key)\ do {\ id value = styles[@#key];\ if (value) {\ node.key = [WXConvert WXPixelType:value scaleFactor:self.weexInstance.pixelScaleFactor];\ } else if (superNode.key ) { \ node.key = superNode.key; \ } \ } while(0); @implementation WXRichText { WXRichTextView *textView; NSMutableArray *_richNodes; NSMutableDictionary *_nodeRanges; NSMutableDictionary *_styles; NSMutableDictionary *_attributes; NSTextAlignment _textAlign; UIColor *_backgroundColor; pthread_mutex_t _attributedStringMutex; pthread_mutexattr_t _propertMutexAttr; CGFloat _lineHeight; BOOL _selectable; } - (void)dealloc { pthread_mutex_destroy(&_attributedStringMutex); pthread_mutexattr_destroy(&_propertMutexAttr); } - (WXRichTextView *)textView { if (!textView) { textView = [[WXRichTextView alloc]init]; textView.delegate = self; textView.scrollEnabled = NO; textView.selectable = _selectable; } return textView; } - (instancetype)initWithRef:(NSString *)ref type:(NSString *)type styles:(NSDictionary *)styles attributes:(NSDictionary *)attributes events:(NSArray *)events weexInstance:(WXSDKInstance *)weexInstance { self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance]; if (self) { _richNodes = [NSMutableArray new]; _nodeRanges = [NSMutableDictionary new]; _styles = [NSMutableDictionary dictionaryWithDictionary:styles]; _attributes = [NSMutableDictionary dictionaryWithDictionary:attributes]; _textAlign = styles[@"textAlign"] ? [WXConvert NSTextAlignment:styles[@"textAlign"]] : NSTextAlignmentLeft; _lineHeight = styles[@"lineHeight"] ? [WXConvert CGFloat:styles[@"lineHeight"]] / 2: 0; pthread_mutexattr_init(&(_propertMutexAttr)); pthread_mutexattr_settype(&(_propertMutexAttr), PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&(_attributedStringMutex), &(_propertMutexAttr)); _selectable = YES; if (_attributes[@"selectable"]) { _selectable = [WXConvert BOOL:_attributes[@"selectable"]]; } } return self; } - (void)fillAttributes:(NSDictionary *)attributes { id value = attributes[@"value"]; if (!value) { return; } if ([value isKindOfClass:[NSString class]]) { value = [WXUtility objectFromJSON:value]; } if ([value isKindOfClass: [NSArray class]]) { [_richNodes removeAllObjects]; WXRichNode *rootNode = [[WXRichNode alloc]init]; [_richNodes addObject:rootNode]; rootNode.type = @"root"; if (_styles) { [self fillCSSStyles:_styles toNode:rootNode superNode:nil]; } for (NSDictionary *dict in value) { [self recursivelyAddChildNode:dict toSuperNode:rootNode]; } _backgroundColor = rootNode.backgroundColor?:[UIColor clearColor]; } } - (void)fillCSSStyles:(NSDictionary *)styles toNode:(WXRichNode *)node superNode:(WXRichNode *)superNode { WX_STYLE_FILL_RICHTEXT(color, UIColor) WX_STYLE_FILL_RICHTEXT(darkSchemeColor, UIColor) WX_STYLE_FILL_RICHTEXT(lightSchemeColor, UIColor) WX_STYLE_FILL_RICHTEXT(backgroundColor, UIColor) WX_STYLE_FILL_RICHTEXT(darkSchemeBackgroundColor, UIColor) WX_STYLE_FILL_RICHTEXT(lightSchemeBackgroundColor, UIColor) WX_STYLE_FILL_RICHTEXT(fontFamily, NSString) WX_STYLE_FILL_RICHTEXT_PIXEL(fontSize) WX_STYLE_FILL_RICHTEXT(fontWeight, WXTextWeight) WX_STYLE_FILL_RICHTEXT(fontStyle, WXTextStyle) WX_STYLE_FILL_RICHTEXT(textDecoration, WXTextDecoration) WX_STYLE_FILL_RICHTEXT_PIXEL(width) WX_STYLE_FILL_RICHTEXT_PIXEL(height) } - (void)fillAttributes:(NSDictionary *)attributes toNode:(WXRichNode *)node superNode:(WXRichNode *)superNode { if (attributes[@"pseudoRef"]) { node.pseudoRef = attributes[@"pseudoRef"]; node.href = [NSURL URLWithString:@"click://"]; } if (attributes[@"href"]) { node.href = [NSURL URLWithString:attributes[@"href"]]; } else if (superNode.href) { node.href = superNode.href; if (!(node.pseudoRef.length) && superNode.pseudoRef.length) { node.pseudoRef = superNode.pseudoRef; } } if (attributes[@"src"]) { node.src = [NSURL URLWithString:attributes[@"src"]]; } if (attributes[@"value"] ) { id value = attributes[@"value"]; if ([value isKindOfClass:[NSString class]]) { node.text = (NSString *)value; } } } - (void)recursivelyAddChildNode:(NSDictionary *)nodeValue toSuperNode:(WXRichNode *)superNode { if (![nodeValue isKindOfClass:[NSDictionary class]]) { WXLogError(@"Invalid rich text structure."); return; } if (![nodeValue[@"type"] isKindOfClass:[NSString class]]) { WXLogError(@"Invalid rich text structure."); return; } WXRichNode *node = [[WXRichNode alloc]init]; [_richNodes addObject:node]; node.type = nodeValue[@"type"]; [self fillCSSStyles:nodeValue[@"style"] toNode:node superNode:superNode]; if (nodeValue[@"attr"]) { [self fillAttributes:nodeValue[@"attr"] toNode:node superNode:superNode]; } if (nodeValue[@"children"]) { id value = nodeValue[@"children"]; if ([value isKindOfClass:[NSArray class]]) { NSArray *children = (NSArray *)value; for(NSDictionary *childValue in children){ [self recursivelyAddChildNode:childValue toSuperNode:node]; } } } } - (WXRichNode*)findRichNode:(NSString*)ref { NSMutableArray *array = [NSMutableArray arrayWithArray:_richNodes]; for (WXRichNode* node in array) { if ([node.ref isEqualToString:ref]) { return node; } } return nil; } - (NSInteger)indexOfRichNode:(WXRichNode*)node { NSInteger index = -1; NSMutableArray *array = [NSMutableArray arrayWithArray:_richNodes]; for (WXRichNode* item in array) { if ([item.ref isEqualToString:node.ref]) { return index+1; } index++; } return index; } - (void)removeChildNode:(NSString*)ref superNodeRef:(NSString *)superNodeRef { WXRichNode* node = [self findRichNode:ref]; WXRichNode* superNode = [self findRichNode:@"_root"]; if (superNodeRef.length > 0) { superNode = [self findRichNode:superNodeRef]; } if (superNode) { [superNode.childNodes removeObject:node]; } [_richNodes removeObject:node]; [self setNeedsLayout]; [self innerLayout]; } - (void)addChildNode:(NSString *)type ref:(NSString*)ref styles:(NSDictionary*)styles attributes:(NSDictionary*)attributes toSuperNodeRef:(NSString *)superNodeRef { if ([_richNodes count] == 0) { WXRichNode *rootNode = [[WXRichNode alloc]init]; [_richNodes addObject:rootNode]; rootNode.type = @"root"; rootNode.ref = @"_root"; if (_styles) { [self fillCSSStyles:_styles toNode:rootNode superNode:nil]; } _backgroundColor = rootNode.backgroundColor?:[UIColor clearColor]; } WXRichNode* superNode = [self findRichNode:@"_root"]; if (superNodeRef.length > 0) { superNode = [self findRichNode:superNodeRef]; } WXRichNode *node = [[WXRichNode alloc]init]; node.ref = ref; NSInteger index = [self indexOfRichNode:superNode]; if (index < 0) { return; } if (index == 0) { [_richNodes addObject:node]; } else { [_richNodes insertObject:node atIndex:(index + superNode.childNodes.count + 1)]; } [superNode.childNodes addObject:node]; node.type = type; [self fillCSSStyles:styles toNode:node superNode:superNode]; [self fillAttributes:attributes toNode:node superNode:superNode]; [self setNeedsLayout]; [self innerLayout]; } #pragma mark - Subclass - (UIView *)loadView { return [self textView]; } - (void)viewDidUnload { textView = nil; } - (void)viewDidLoad { [self innerLayout]; } - (void)layoutDidFinish { [self innerLayout]; } - (void)innerLayout { __weak typeof(self) wself = self; WXPerformBlockOnComponentThread(^{ __strong typeof(wself) sself = wself; if (sself) { if (sself.flexCssNode == nullptr) { return; } UIEdgeInsets padding = { WXFloorPixelValue(sself.flexCssNode->getPaddingTop()+sself.flexCssNode->getBorderWidthTop()), WXFloorPixelValue(sself.flexCssNode->getPaddingLeft()+sself.flexCssNode->getBorderWidthLeft()), WXFloorPixelValue(sself.flexCssNode->getPaddingBottom()+sself.flexCssNode->getBorderWidthBottom()), WXFloorPixelValue(sself.flexCssNode->getPaddingRight()+sself.flexCssNode->getBorderWidthRight()) }; NSMutableAttributedString* attrString = [sself buildAttributeString]; WXPerformBlockOnMainThread(^{ WXRichTextView* view = [sself textView]; view.attributedText = attrString; view.textContainerInset = padding; view.backgroundColor = [UIColor clearColor]; }); } }); } - (CGSize (^)(CGSize))measureBlock { __weak typeof(self) weakSelf = self; return ^CGSize (CGSize constrainedSize) { NSMutableAttributedString *attributedString = [weakSelf buildAttributeString]; CGFloat width = constrainedSize.width; if (isnan(width)) { width = CGFLOAT_MAX; } CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil]; CGSize computedSize = rect.size; if(weakSelf.flexCssNode != nullptr){ if (!isnan(weakSelf.flexCssNode->getMinWidth())) { computedSize.width = MAX(computedSize.width, weakSelf.flexCssNode->getMinWidth()); } if (!isnan(weakSelf.flexCssNode->getMaxWidth())) { computedSize.width = MIN(computedSize.width, weakSelf.flexCssNode->getMaxWidth()); } if (!isnan(weakSelf.flexCssNode->getMinHeight())) { computedSize.width = MAX(computedSize.height, weakSelf.flexCssNode->getMinHeight()); } if (!isnan(weakSelf.flexCssNode->getMaxHeight())) { computedSize.width = MIN(computedSize.height, weakSelf.flexCssNode->getMaxHeight()); } } return (CGSize) { WXCeilPixelValue(computedSize.width), WXCeilPixelValue(computedSize.height) }; }; } - (void)schemeDidChange:(NSString*)scheme { [super schemeDidChange:scheme]; if ([self isViewLoaded]) { // Force inner layout [self innerLayout]; } } - (WXColorScene)colorSceneType { return WXColorSceneText; } #pragma mark Text Building - (NSMutableAttributedString *)buildAttributeString { pthread_mutex_lock(&(_attributedStringMutex)); [self fillAttributes:_attributes]; NSMutableArray *array = [NSMutableArray arrayWithArray:_richNodes]; pthread_mutex_unlock(&(_attributedStringMutex)); NSMutableDictionary *nodeRange = [NSMutableDictionary dictionary]; NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] init]; NSUInteger location; BOOL invert = self.invertForDarkScheme; // Invert default background color. UIColor* defaultTextColor = [UIColor blackColor]; UIColor* defaultBackgroundColor = _backgroundColor; if (invert && [self.weexInstance isDarkScheme]) { defaultTextColor = [[WXSDKInstance darkSchemeColorHandler] getInvertedColorFor:[UIColor blackColor] ofScene:[self colorSceneType] withDefault:[UIColor blackColor]]; defaultBackgroundColor = [[WXSDKInstance darkSchemeColorHandler] getInvertedColorFor:_backgroundColor ofScene:[self colorSceneType] withDefault:_backgroundColor]; } __weak typeof(self) weakSelf = self; for (WXRichNode *node in array) { location = attrStr.length; if ([node.type isEqualToString:@"span"]) { if (node.text && [node.text length] > 0) { NSString *text = node.text; [attrStr.mutableString appendString:text]; NSRange range = NSMakeRange(location, text.length); UIColor* textColor = [self.weexInstance chooseColor:node.color lightSchemeColor:node.lightSchemeColor darkSchemeColor:node.darkSchemeColor invert:invert scene:[self colorSceneType]]; UIColor* bgColor = [self.weexInstance chooseColor:node.backgroundColor lightSchemeColor:node.lightSchemeBackgroundColor darkSchemeColor:node.darkSchemeBackgroundColor invert:invert scene:[self colorSceneType]]; [attrStr addAttribute:NSForegroundColorAttributeName value:textColor ?: defaultTextColor range:range]; [attrStr addAttribute:NSBackgroundColorAttributeName value:bgColor ?: defaultBackgroundColor range:range]; UIFont *font = [WXUtility fontWithSize:node.fontSize textWeight:node.fontWeight textStyle:WXTextStyleNormal fontFamily:node.fontFamily scaleFactor:self.weexInstance.pixelScaleFactor]; if (font) { [attrStr addAttribute:NSFontAttributeName value:font range:range]; } if (node.fontStyle == WXTextStyleItalic) { [attrStr addAttribute:NSObliquenessAttributeName value:@0.3 range:range]; } else { [attrStr addAttribute:NSObliquenessAttributeName value:@0 range:range]; } [attrStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:WXTextDecorationNone] range:range]; [attrStr addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:WXTextDecorationNone] range:range]; if (node.textDecoration == WXTextDecorationUnderline) { [attrStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:WXTextDecorationUnderline] range:range]; } else if (node.textDecoration == WXTextDecorationLineThrough) { [attrStr addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:WXTextDecorationLineThrough] range:range]; } if (node.href) { [attrStr addAttribute:NSLinkAttributeName value:node.href range:range]; } else { [attrStr removeAttribute:NSLinkAttributeName range:range]; } NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.alignment = _textAlign; if(_lineHeight != 0 ) { paragraphStyle.minimumLineHeight = _lineHeight; paragraphStyle.maximumLineHeight = _lineHeight; [attrStr addAttribute:NSBaselineOffsetAttributeName value:@((_lineHeight - font.lineHeight)/2) range:range]; } [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range]; [nodeRange setObject:node forKey:NSStringFromRange(range)]; } } else if ([node.type isEqualToString:@"image"]) { NSTextAttachment *imgAttachment = [[NSTextAttachment alloc]init]; imgAttachment.bounds = CGRectMake(0, 0, node.width, node.height); NSAttributedString *attachAttriStr = [NSAttributedString attributedStringWithAttachment:imgAttachment]; [attrStr appendAttributedString:attachAttriStr]; NSRange range = NSMakeRange(location, attachAttriStr.length); [attrStr addAttribute:NSFontAttributeName value: [UIFont systemFontOfSize:node.height] range:range]; if (node.href) { [attrStr addAttribute:NSLinkAttributeName value:node.href range:range]; } else { [attrStr removeAttribute:NSLinkAttributeName range:range]; } [nodeRange setObject:node forKey:NSStringFromRange(range)]; if (node.src) { [[self imageLoader] downloadImageWithURL:node.src.absoluteString imageFrame:imgAttachment.bounds userInfo:nil completed:^(UIImage *image, NSError *error, BOOL finished) { dispatch_async(dispatch_get_main_queue(), ^{ imgAttachment.image = image; [[weakSelf textView].layoutManager invalidateDisplayForCharacterRange:range]; }); }]; } } } pthread_mutex_lock(&(_attributedStringMutex)); [_nodeRanges removeAllObjects]; _nodeRanges = [NSMutableDictionary dictionaryWithDictionary:nodeRange]; pthread_mutex_unlock(&(_attributedStringMutex)); return attrStr; } - (void)updateStyles:(NSDictionary *)styles { if (styles[@"textAlign"]) { _textAlign = [WXConvert NSTextAlignment:styles[@"textAlign"]]; } if (styles[@"lineHeight"]) { _lineHeight = [WXConvert CGFloat:styles[@"lineHeight"]] / 2; } WXPerformBlockOnComponentThread(^{ [_styles addEntriesFromDictionary:styles]; [self syncTextStorageForView]; }); } - (void)updateChildNodeStyles:(NSDictionary *)styles ref:(NSString*)ref parentRef:(NSString*)parentRef { WXPerformBlockOnComponentThread(^{ WXRichNode* node = [self findRichNode:ref]; if (node) { WXRichNode* superNode = [self findRichNode:@"_root"]; if (parentRef.length > 0) { superNode = [self findRichNode:parentRef]; } if (superNode) { [self fillCSSStyles:styles toNode:node superNode:superNode]; [self syncTextStorageForView]; } } }); } - (void)updateAttributes:(NSDictionary *)attributes { WXAssertMainThread(); if (attributes[@"selectable"]) { _selectable = [WXConvert BOOL:attributes[@"selectable"]]; } [self textView].selectable = _selectable; __weak WXRichText* weakSelf = self; WXPerformBlockOnComponentThread(^{ __strong WXRichText* strongSelf = weakSelf; if (strongSelf == nil) { return; } strongSelf->_attributes = [NSMutableDictionary dictionaryWithDictionary:attributes]; [strongSelf syncTextStorageForView]; }); } - (void)updateChildNodeAttributes:(NSDictionary *)attributes ref:(NSString*)ref parentRef:(NSString*)parentRef { WXPerformBlockOnComponentThread(^{ WXRichNode* node = [self findRichNode:ref]; if (node) { WXRichNode* superNode = [self findRichNode:@"_root"]; if (parentRef.length > 0) { superNode = [self findRichNode:parentRef]; } if (superNode) { [self fillAttributes:attributes toNode:node superNode:superNode]; [self syncTextStorageForView]; } } }); } - (void)syncTextStorageForView { pthread_mutex_lock(&(_attributedStringMutex)); [self fillAttributes:_attributes]; pthread_mutex_unlock(&(_attributedStringMutex)); if (_styles[@"height"]) { [self innerLayout]; } else { [self setNeedsLayout]; } } #pragma mark - UITextView Delegate - (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange { return NO; } - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { if (!URL) { return NO; } NSString *rangeStr = NSStringFromRange(characterRange); WXRichNode *node = [_nodeRanges objectForKey:rangeStr]; if (![[node.href absoluteString] isEqualToString:@"click://"]) { id<WXNavigationProtocol> navigationHandler = [self navigationHandler]; if ([navigationHandler respondsToSelector:@selector(pushViewControllerWithParam: completion: withContainer:)]) { [navigationHandler pushViewControllerWithParam:@{@"url":URL.absoluteString} completion:^(NSString *code, NSDictionary *responseData) { } withContainer:self.weexInstance.viewController]; } else { WXLogError(@"Event handler of class %@ does not respond to pushViewControllerWithParam", NSStringFromClass([navigationHandler class])); } } else if (node.pseudoRef) { NSMutableDictionary *params = [NSMutableDictionary new]; [params setObject:node.pseudoRef forKey:@"pseudoRef"]; [[WXSDKManager bridgeMgr] fireEvent:self.weexInstance.instanceId ref:self.ref type:@"itemclick" params:params domChanges:nil]; } return NO; } # pragma mark - imageLoader - (id<WXImgLoaderProtocol>)imageLoader { static id<WXImgLoaderProtocol> imageLoader; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ imageLoader = [WXSDKEngine handlerForProtocol:@protocol(WXImgLoaderProtocol)]; }); return imageLoader; } - (id<WXNavigationProtocol>)navigationHandler { static id<WXNavigationProtocol> navigationHandler; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ navigationHandler = [WXSDKEngine handlerForProtocol:@protocol(WXNavigationProtocol)]; }); return navigationHandler; } @end ```
/content/code_sandbox/ios/sdk/WeexSDK/Sources/Component/WXRichText.mm
xml
2016-03-11T10:18:11
2024-08-16T06:43:02
weex
alibaba/weex
18,250
5,416
```xml <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.ctrip.framework.xpipe</groupId> <artifactId>xpipe-parent</artifactId> <version>1.2.15</version> </parent> <groupId>com.ctrip.framework.xpipe.redis</groupId> <artifactId>redis-parent</artifactId> <packaging>pom</packaging> <modules> <module>redis-core</module> <module>redis-keeper</module> <module>redis-meta</module> <module>redis-console</module> <module>redis-checker</module> <module>redis-integration-test</module> <module>redis-proxy</module> <module>redis-proxy-client</module> </modules> <profiles> <profile> <id>package</id> <modules> <module>package</module> </modules> </profile> </profiles> </project> ```
/content/code_sandbox/redis/pom.xml
xml
2016-03-29T12:22:36
2024-08-12T11:25:42
x-pipe
ctripcorp/x-pipe
1,977
268
```xml <resources> <string name="app_name">ZeusPlugin</string> <string name="string1"></string> </resources> ```
/content/code_sandbox/app/src/main/res/values/strings.xml
xml
2016-08-05T08:24:54
2024-08-02T08:55:58
ZeusPlugin
iReaderAndroid/ZeusPlugin
1,015
31
```xml import Insights from './insight'; import Dashboards from './dashboard'; import Reports from './report'; import Sections from './section'; export { Insights, Dashboards, Reports, Sections }; ```
/content/code_sandbox/packages/plugin-insight-api/src/graphql/resolvers/queries/index.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
38
```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFrameworks>$(AspNetTestTfm);$(AspNetTestTfm)-browser1.0</TargetFrameworks> <EnableSdkContainerSupport>false</EnableSdkContainerSupport> <!-- Until we have support for it, pretend it supports it --> <TargetPlatformSupported>true</TargetPlatformSupported> </PropertyGroup> <!-- Until we have support for it, pretend it supports it --> <ItemGroup> <SdkSupportedTargetPlatformVersion Include="1.0" /> </ItemGroup> <PropertyGroup> <!-- We don't want to run build server when not running as tests. --> <UseRazorBuildServer>false</UseRazorBuildServer> </PropertyGroup> <ItemGroup Condition="'$([MSBuild]::GetTargetPlatformIdentifier($(TargetFramework)))' == 'browser'"> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.0-preview.4.23260.4" /> </ItemGroup> <Target Name="_IntrospectGetCopyToOutputDirectoryItems"> <Message Text="AllItemsFullPathWithTargetPath: %(AllItemsFullPathWithTargetPath.TargetPath)" Importance="High" /> </Target> <Target Name="_IntrospectWatchItems" DependsOnTargets="_RazorSdkCustomCollectWatchItems"> <Message Text="Watch: %(Watch.FileName)%(Watch.Extension)" Importance="High" /> </Target> <Target Name="_IntrospectRazorGenerateComponentDesignTime" DependsOnTargets="RazorGenerateComponentDesignTime"> <Message Text="RazorComponentWithTargetPath: %(RazorComponentWithTargetPath.FileName) %(RazorComponentWithTargetPath.TargetPath)" Importance="High" /> </Target> <Target Name="_IntrospectReferences" AfterTargets="ResolveAssemblyReferences"> <PropertyGroup> <_ReferencesFilePath>$(IntermediateOutputPath)captured-references.txt</_ReferencesFilePath> </PropertyGroup> <ItemGroup> <_CapturedReferences Include="@(ReferencePath->'%(Identity)')"/> </ItemGroup> <WriteLinesToFile File="$(_ReferencesFilePath)" Lines="@(_CapturedReferences)" Overwrite="true"/> </Target> </Project> ```
/content/code_sandbox/test/TestAssets/TestProjects/RazorComponentAppMultitarget/RazorComponentAppMultitarget.csproj
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
491
```xml <?xml version="1.0" encoding="utf-8"?> <!-- path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <selector xmlns:android="path_to_url"> <!-- Disabled --> <item android:alpha="@dimen/material_emphasis_disabled" android:color="?attr/colorOnSurface" android:state_enabled="false" /> <!-- Uncheckable --> <item android:color="?attr/colorOnContainer" android:state_checkable="false" /> <!-- Checked Buttons. --> <item android:color="?attr/colorOnSecondaryContainer" android:state_checked="true" /> <!-- Not-checked Buttons. --> <item android:color="?attr/colorOnSurface" /> </selector> ```
/content/code_sandbox/lib/java/com/google/android/material/button/res/color/m3_text_button_foreground_color_selector.xml
xml
2016-12-05T16:11:29
2024-08-16T17:51:42
material-components-android
material-components/material-components-android
16,176
173
```xml import { CommonModule } from "@angular/common"; import { Component, Input } from "@angular/core"; import { RouterLink } from "@angular/router"; import { firstValueFrom } from "rxjs"; import { JslibModule } from "@bitwarden/angular/jslib.module"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { SendType } from "@bitwarden/common/tools/send/enums/send-type"; import { SendView } from "@bitwarden/common/tools/send/models/view/send.view"; import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction"; import { BadgeModule, ButtonModule, DialogService, IconButtonModule, ItemModule, SectionComponent, SectionHeaderComponent, ToastService, TypographyModule, } from "@bitwarden/components"; @Component({ imports: [ CommonModule, ItemModule, ButtonModule, BadgeModule, IconButtonModule, SectionComponent, TypographyModule, JslibModule, SectionHeaderComponent, RouterLink, ], selector: "app-send-list-items-container", templateUrl: "send-list-items-container.component.html", standalone: true, }) export class SendListItemsContainerComponent { sendType = SendType; /** * The list of sends to display. */ @Input() sends: SendView[] = []; @Input() headerText: string; constructor( protected dialogService: DialogService, protected environmentService: EnvironmentService, protected i18nService: I18nService, protected logService: LogService, protected platformUtilsService: PlatformUtilsService, protected sendApiService: SendApiService, protected toastService: ToastService, ) {} async deleteSend(s: SendView): Promise<boolean> { const confirmed = await this.dialogService.openSimpleDialog({ title: { key: "deleteSend" }, content: { key: "deleteSendConfirmation" }, type: "warning", }); if (!confirmed) { return false; } await this.sendApiService.delete(s.id); try { this.toastService.showToast({ variant: "success", title: null, message: this.i18nService.t("deletedSend"), }); } catch (e) { this.logService.error(e); } } async copySendLink(send: SendView) { const env = await firstValueFrom(this.environmentService.environment$); const link = env.getSendUrl() + send.accessId + "/" + send.urlB64Key; this.platformUtilsService.copyToClipboard(link); this.toastService.showToast({ variant: "success", title: null, message: this.i18nService.t("valueCopied", this.i18nService.t("sendLink")), }); } } ```
/content/code_sandbox/libs/tools/send/send-ui/src/send-list-items-container/send-list-items-container.component.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
669
```xml <!-- ~ ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <project xmlns:xsi="path_to_url" xmlns="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.networknt</groupId> <artifactId>light-4j</artifactId> <version>2.1.36-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>handler</artifactId> <packaging>jar</packaging> <description>A module defines interface or abstract classes for handlers.</description> <dependencies> <dependency> <groupId>com.networknt</groupId> <artifactId>config</artifactId> </dependency> <dependency> <groupId>com.networknt</groupId> <artifactId>utility</artifactId> </dependency> <dependency> <groupId>com.networknt</groupId> <artifactId>http-string</artifactId> </dependency> <dependency> <groupId>com.networknt</groupId> <artifactId>status</artifactId> </dependency> <dependency> <groupId>com.networknt</groupId> <artifactId>handler-config</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>org.owasp.encoder</groupId> <artifactId>encoder</artifactId> </dependency> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-core</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.networknt</groupId> <artifactId>common</artifactId> </dependency> </dependencies> </project> ```
/content/code_sandbox/handler/pom.xml
xml
2016-09-09T22:28:14
2024-08-14T17:35:43
light-4j
networknt/light-4j
3,614
600
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions id="taskAssigneeExample" xmlns="path_to_url" xmlns:activiti="path_to_url" targetNamespace="Examples"> <process id="multipleCandidatesGroup" name="Multiple candidate groups example"> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="theTask" /> <userTask id="theTask" name="Approve expenses" > <documentation> Judge expenses of employees before end of fiscal quarter. </documentation> <potentialOwner> <resourceAssignmentExpression> <formalExpression>group(accountancy), group(management)</formalExpression> </resourceAssignmentExpression> </potentialOwner> </userTask> <sequenceFlow id="flow2" sourceRef="theTask" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> </definitions> ```
/content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/examples/bpmn/usertask/taskcandidate/TaskCandidateTest.testMultipleCandidateGroups.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
227
```xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/indicator_container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" /> <LinearLayout android:id="@+id/title_container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" /> </FrameLayout> ```
/content/code_sandbox/magicindicator/src/main/res/layout/pager_navigator_layout_no_scroll.xml
xml
2016-06-26T08:20:43
2024-08-16T18:33:28
MagicIndicator
hackware1993/MagicIndicator
9,699
127
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import {ipcRenderer, webFrame} from 'electron'; import {truncate} from 'lodash'; import * as path from 'path'; import {WebAppEvents} from '@wireapp/webapp-events'; import {EVENT_TYPE} from '../lib/eventType'; import * as locale from '../locale'; import {getLogger} from '../logging/getLogger'; import * as EnvironmentUtil from '../runtime/EnvironmentUtil'; import {AutomatedSingleSignOn} from '../sso/AutomatedSingleSignOn'; const logger = getLogger(path.basename(__filename)); webFrame.setVisualZoomLevelLimits(1, 1); window.locStrings = locale.LANGUAGES[locale.getCurrent()]; window.locStringsDefault = locale.LANGUAGES.en; window.locale = locale.getCurrent(); window.isMac = EnvironmentUtil.platform.IS_MAC_OS; const getSelectedWebview = (): Electron.WebviewTag | null => document.querySelector<Electron.WebviewTag>('.Webview:not(.hide)'); const getWebviewById = (id: string): Electron.WebviewTag | null => document.querySelector<Electron.WebviewTag>(`.Webview[data-accountid="${id}"]`); const subscribeToMainProcessEvents = (): void => { ipcRenderer.on(EVENT_TYPE.ACCOUNT.SSO_LOGIN, (_event, code: string) => new AutomatedSingleSignOn().start(code)); ipcRenderer.on( EVENT_TYPE.ACTION.JOIN_CONVERSATION, async (_event, {code, key, domain}: {code: string; key: string; domain?: string}) => { const selectedWebview = getSelectedWebview(); if (selectedWebview) { await selectedWebview.send(EVENT_TYPE.ACTION.JOIN_CONVERSATION, {code, key, domain}); } }, ); ipcRenderer.on(EVENT_TYPE.UI.SYSTEM_MENU, async (_event, action: string) => { const selectedWebview = getSelectedWebview(); if (selectedWebview) { await selectedWebview.send(action); } }); ipcRenderer.on(WebAppEvents.LIFECYCLE.SSO_WINDOW_CLOSED, async () => { const selectedWebview = getSelectedWebview(); if (selectedWebview) { await selectedWebview.send(WebAppEvents.LIFECYCLE.SSO_WINDOW_CLOSED); } }); ipcRenderer.on(EVENT_TYPE.WEBAPP.CHANGE_LOCATION_HASH, async (_event, hash: string) => { const selectedWebview = getSelectedWebview(); if (selectedWebview) { await selectedWebview.send(EVENT_TYPE.WEBAPP.CHANGE_LOCATION_HASH, hash); } }); ipcRenderer.on(EVENT_TYPE.EDIT.COPY, () => getSelectedWebview()?.copy()); ipcRenderer.on(EVENT_TYPE.EDIT.CUT, () => getSelectedWebview()?.cut()); ipcRenderer.on(EVENT_TYPE.EDIT.PASTE, () => getSelectedWebview()?.paste()); ipcRenderer.on(EVENT_TYPE.EDIT.REDO, () => getSelectedWebview()?.redo()); ipcRenderer.on(EVENT_TYPE.EDIT.SELECT_ALL, () => getSelectedWebview()?.selectAll()); ipcRenderer.on(EVENT_TYPE.EDIT.UNDO, () => getSelectedWebview()?.undo()); ipcRenderer.on(EVENT_TYPE.WRAPPER.RELOAD, (): void => { const webviews = document.querySelectorAll<Electron.WebviewTag>('webview'); webviews.forEach(webview => webview.reload()); }); ipcRenderer.on(EVENT_TYPE.ACTION.SWITCH_ACCOUNT, (event, accountIndex: number) => { window.dispatchEvent(new CustomEvent(EVENT_TYPE.ACTION.SWITCH_ACCOUNT, {detail: {accountIndex}})); }); ipcRenderer.on(EVENT_TYPE.ACTION.START_LOGIN, event => { window.dispatchEvent(new CustomEvent(EVENT_TYPE.ACTION.START_LOGIN)); }); }; const setupIpcInterface = (): void => { window.sendBadgeCount = (count: number, ignoreFlash: boolean): void => { ipcRenderer.send(EVENT_TYPE.UI.BADGE_COUNT, {count, ignoreFlash}); }; window.submitDeepLink = (url: string): void => { ipcRenderer.send(EVENT_TYPE.ACTION.DEEP_LINK_SUBMIT, url); }; window.sendDeleteAccount = (accountId: string, sessionID?: string): Promise<void> => { const truncatedId = truncate(accountId, {length: 5}); return new Promise((resolve, reject) => { const accountWebview = getWebviewById(accountId); if (!accountWebview) { // eslint-disable-next-line prefer-promise-reject-errors return reject(`Webview for account "${truncatedId}" does not exist`); } logger.info(`Processing deletion of "${truncatedId}"`); const viewInstanceId = accountWebview.getWebContentsId(); ipcRenderer.on(EVENT_TYPE.ACCOUNT.DATA_DELETED, () => resolve()); ipcRenderer.send(EVENT_TYPE.ACCOUNT.DELETE_DATA, viewInstanceId, accountId, sessionID); }); }; window.sendLogoutAccount = async (accountId: string): Promise<void> => { const accountWebview = getWebviewById(accountId); logger.log(`Sending logout signal to webview for account "${truncate(accountId, {length: 5})}".`); await accountWebview?.send(EVENT_TYPE.ACTION.SIGN_OUT); }; window.sendConversationJoinToHost = async ( accountId: string, code: string, key: string, domain?: string, ): Promise<void> => { const accountWebview = getWebviewById(accountId); logger.log(`Sending conversation join data to webview for account "${truncate(accountId, {length: 5})}".`); await accountWebview?.send(WebAppEvents.CONVERSATION.JOIN, {code, key, domain}); }; }; setupIpcInterface(); subscribeToMainProcessEvents(); window.addEventListener('focus', () => { const selectedWebview = getSelectedWebview(); if (selectedWebview) { selectedWebview.blur(); selectedWebview.focus(); } }); ```
/content/code_sandbox/electron/src/preload/preload-app.ts
xml
2016-07-26T13:55:48
2024-08-16T03:45:51
wire-desktop
wireapp/wire-desktop
1,075
1,344
```xml import { render, screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import * as React from 'react'; import { consoleMocks } from '@rqb-testing'; import { LogType, TestID, defaultPlaceholderFieldLabel, defaultPlaceholderFieldName, defaultPlaceholderOperatorName, standardClassnames as sc, defaultTranslations as t, } from '../defaults'; import { messages } from '../messages'; import type { ActionProps, ActionWithRulesAndAddersProps, ControlElementsProp, Field, FieldByValue, FieldSelectorProps, FullCombinator, FullField, FullOperator, FullOption, Option, OptionGroup, QueryBuilderProps, RuleGroupProps, RuleGroupType, RuleGroupTypeIC, RuleProps, RuleType, ValidationMap, ValueSelectorProps, } from '../types'; import { defaultValidator, findPath, generateID, getOption, move, numericRegex, toFullOption, } from '../utils'; import { QueryBuilder } from './QueryBuilder'; import { QueryBuilderContext } from './QueryBuilderContext'; import { defaultControlElements } from './defaults'; import { ValueSelector } from './ValueSelector'; import { ActionElement } from './ActionElement'; import { waitABeat } from './testUtils'; import { getQuerySelectorById, useQueryBuilderQuery, useQueryBuilderSelector } from '../redux'; const user = userEvent.setup(); const { consoleError } = consoleMocks(); describe('when rendered', () => { it('has the correct role', () => { render(<QueryBuilder />); expect(screen.getByRole('form')).toBeInTheDocument(); }); it('has the correct className', () => { render(<QueryBuilder />); expect(screen.getByRole('form')).toHaveClass(sc.queryBuilder); }); it('renders the root RuleGroup', () => { render(<QueryBuilder />); expect(screen.getByTestId(TestID.ruleGroup)).toBeInTheDocument(); }); }); describe('when rendered with defaultQuery only', () => { it('changes the query in uncontrolled state', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder defaultQuery={{ combinator: 'and', rules: [{ field: 'firstName', operator: '=', value: 'Steve' }], }} onQueryChange={onQueryChange} /> ); expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ id: expect.any(String) }) ); expect(screen.getAllByTestId(TestID.rule)).toHaveLength(1); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByTestId(TestID.rule)).toHaveLength(2); }); }); describe('when rendered with onQueryChange callback', () => { it('calls onQueryChange with query', () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const idGenerator = () => 'id'; render(<QueryBuilder onQueryChange={onQueryChange} idGenerator={idGenerator} />); expect(onQueryChange).toHaveBeenCalledTimes(1); const query: RuleGroupType = { combinator: 'and', rules: [], not: false, }; expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onQueryChange).toHaveBeenLastCalledWith({ ...query, id: 'id' }); }); }); describe('when initial query without fields is provided, create rule should work', () => { it('is able to create rule on add rule click', async () => { render(<QueryBuilder />); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); }); }); describe('when initial query with duplicate fields is provided', () => { it('passes down a unique set of fields by name', async () => { render( <QueryBuilder fields={[ { name: 'dupe', label: 'One' }, { name: 'dupe', label: 'Two' }, ]} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); expect(screen.getAllByTestId(TestID.fields)).toHaveLength(1); }); it('passes down a unique set of fields by value', async () => { render( <QueryBuilder fields={[ { name: 'notdupe1', value: 'dupe', label: 'One' }, { name: 'notdupe2', value: 'dupe', label: 'Two' }, ]} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); expect(screen.getAllByTestId(TestID.fields)).toHaveLength(1); }); }); describe('when fields have no name property', () => { it('passes down a unique set of fields by value', async () => { render( <QueryBuilder addRuleToNewGroups fields={[ { value: 'f1', label: 'One' }, { value: 'f2', label: 'Two' }, ]} /> ); expect(within(screen.getByTestId(TestID.fields)).getAllByRole('option')).toHaveLength(2); }); }); describe('when initial query with fields object is provided', () => { it('passes down fields sorted by label using the key as name', async () => { render( <QueryBuilder fields={{ xyz: { name: 'dupe', label: 'One' }, abc: { name: 'dupe', label: 'Two' }, }} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); expect(screen.getByTestId(TestID.fields).querySelectorAll('option')).toHaveLength(2); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option')).map(opt => opt.value) ).toEqual(['xyz', 'abc']); expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.getByText('Two')).toBeInTheDocument(); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option'))[0] ).toHaveTextContent('One'); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option'))[1] ).toHaveTextContent('Two'); }); it('respects autoSelectField={false}', async () => { render( <QueryBuilder fields={{ xyz: { name: 'dupe', label: 'One' }, abc: { name: 'dupe', label: 'Two' }, }} autoSelectField={false} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); expect(screen.getByTestId(TestID.fields).querySelectorAll('option')).toHaveLength(3); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option')).map(opt => opt.value) ).toEqual([defaultPlaceholderFieldName, 'xyz', 'abc']); expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.getByText('Two')).toBeInTheDocument(); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option'))[0] ).toHaveTextContent(defaultPlaceholderFieldLabel); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option'))[1] ).toHaveTextContent('One'); expect( Array.from(screen.getByTestId(TestID.fields).querySelectorAll('option'))[2] ).toHaveTextContent('Two'); }); it('does not mutate a fields array with duplicates', () => { const fields: Field[] = [ { name: 'f', label: 'Field' }, { name: 'f', label: 'Field' }, ]; render(<QueryBuilder fields={fields} />); expect(fields).toHaveLength(2); }); it('does not mutate a fields option group array with duplicates', () => { const optgroups: OptionGroup<Field>[] = [ { label: 'OG1', options: [{ name: 'f1', label: 'Field' }] }, { label: 'OG1', options: [{ name: 'f2', label: 'Field' }] }, { label: 'OG2', options: [{ name: 'f1', label: 'Field' }] }, ]; render(<QueryBuilder fields={optgroups} />); expect(optgroups).toHaveLength(3); for (const og of optgroups.map(og => og.options)) { expect(og).toHaveLength(1); } }); }); describe('when initial query, without ID, is provided', () => { const queryWithoutID: RuleGroupType = { combinator: 'and', not: false, rules: [{ field: 'firstName', value: 'Test without ID', operator: '=' }], }; const fields: Field[] = [ { name: 'firstName', label: 'First Name' }, { name: 'lastName', label: 'Last Name' }, { name: 'age', label: 'Age' }, ]; const setup = () => ({ selectors: render(<QueryBuilder query={queryWithoutID} fields={fields} />), }); it('contains a <Rule /> with the correct props', () => { setup(); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); expect(screen.getByTestId(TestID.fields)).toHaveValue('firstName'); expect(screen.getByTestId(TestID.operators)).toHaveValue('='); expect(screen.getByTestId(TestID.valueEditor)).toHaveValue('Test without ID'); }); it('has a select control with the provided fields', () => { setup(); expect(screen.getByTestId(TestID.fields).querySelectorAll('option')).toHaveLength(3); }); it('has a field selector with the correct field', () => { setup(); expect(screen.getByTestId(TestID.fields)).toHaveValue('firstName'); }); it('has an operator selector with the correct operator', () => { setup(); expect(screen.getByTestId(TestID.operators)).toHaveValue('='); }); it('has an input control with the correct value', () => { setup(); expect(screen.getByTestId(TestID.rule).querySelector('input')).toHaveValue('Test without ID'); }); }); describe('when fields are provided with optgroups', () => { const query: RuleGroupType = { combinator: 'and', not: false, rules: [{ field: 'firstName', value: 'Test without ID', operator: '=' }], }; const fields: OptionGroup<Field>[] = [ { label: 'Names', options: [ { name: 'firstName', label: 'First Name' }, { name: 'lastName', label: 'Last Name' }, ], }, { label: 'Numbers', options: [{ name: 'age', label: 'Age' }] }, ]; const setup = () => ({ selectors: render(<QueryBuilder defaultQuery={query} fields={fields} />), }); it('renders correctly', () => { setup(); expect(screen.getByTestId(TestID.fields).querySelectorAll('optgroup')).toHaveLength(2); }); it('selects the correct field', async () => { setup(); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByTestId(TestID.fields)[1]).toHaveValue('firstName'); }); it('selects the default option', async () => { const { selectors: { rerender }, } = setup(); rerender(<QueryBuilder defaultQuery={query} fields={fields} autoSelectField={false} />); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByTestId(TestID.fields)[1]).toHaveValue(defaultPlaceholderFieldName); }); }); describe('when initial operators are provided', () => { const operators: Option[] = [ { name: 'null', label: 'Custom Is Null' }, { name: 'notNull', label: 'Is Not Null' }, { name: 'in', label: 'In' }, { name: 'notIn', label: 'Not In' }, ]; const fields: Field[] = [ { name: 'firstName', label: 'First Name' }, { name: 'lastName', label: 'Last Name' }, { name: 'age', label: 'Age' }, ]; const query: RuleGroupType = { combinator: 'and', not: false, rules: [ { field: 'firstName', value: 'Test', operator: '=', }, ], }; const setup = () => ({ selectors: render(<QueryBuilder operators={operators} fields={fields} query={query} />), }); it('uses the given operators', () => { setup(); expect(screen.getByTestId(TestID.operators).querySelectorAll('option')).toHaveLength(4); }); it('matches the label of the first operator', () => { setup(); expect(screen.getByTestId(TestID.operators).querySelectorAll('option')[0]).toHaveTextContent( 'Custom Is Null' ); }); }); describe('when base properties are provided', () => { it('includes base properties', async () => { const fieldSelectorReporter = jest.fn(); const operatorSelectorReporter = jest.fn(); const combinatorSelectorReporter = jest.fn(); const getSelector = (type: 'field' | 'operator' | 'combinator') => (props: ValueSelectorProps) => { const opt = getOption(props.options, props.value!); ({ field: fieldSelectorReporter, operator: operatorSelectorReporter, combinator: combinatorSelectorReporter, })[type](opt); return null; }; render( <QueryBuilder addRuleToNewGroups fields={[ { value: 'f1', label: 'One' }, { value: 'f2', label: 'Two' }, ]} baseField={{ base: 'field' }} baseOperator={{ base: 'operator' }} baseCombinator={{ base: 'combinator' }} controlElements={{ fieldSelector: getSelector('field'), operatorSelector: getSelector('operator'), combinatorSelector: getSelector('combinator'), }} /> ); expect(fieldSelectorReporter).toHaveBeenCalledWith(expect.objectContaining({ base: 'field' })); expect(operatorSelectorReporter).toHaveBeenCalledWith( expect.objectContaining({ base: 'operator' }) ); expect(combinatorSelectorReporter).toHaveBeenCalledWith( expect.objectContaining({ base: 'combinator' }) ); }); }); describe('get* callbacks', () => { const fields: FullField[] = [ { name: 'firstName', label: 'First Name' }, { name: 'lastName', label: 'Last Name' }, { name: 'age', label: 'Age' }, ].map(o => toFullOption(o)); const rule: RuleType = { field: 'lastName', value: 'Another Test', operator: '=', }; const query: RuleGroupType = { combinator: 'or', not: false, rules: [rule], }; describe('when getOperators fn prop is provided', () => { it('invokes custom getOperators function', () => { const getOperators = jest.fn(() => [{ name: 'op1', label: 'Operator 1' }]); render(<QueryBuilder query={query} fields={fields} getOperators={getOperators} />); expect(getOperators).toHaveBeenCalledWith(rule.field, { fieldData: fields[1] }); }); it('handles invalid getOperators return value', () => { render(<QueryBuilder query={query} fields={fields} getOperators={() => null} />); expect(screen.getByTestId(TestID.operators)).toHaveValue('='); }); }); describe('when getValueEditorType fn prop is provided', () => { it('invokes custom getValueEditorType function', () => { const getValueEditorType = jest.fn(() => 'text' as const); render( <QueryBuilder query={query} fields={fields} getValueEditorType={getValueEditorType} /> ); expect(getValueEditorType).toHaveBeenCalledWith(rule.field, rule.operator, { fieldData: fields[1], }); }); it('handles invalid getValueEditorType function', () => { render(<QueryBuilder query={query} fields={fields} getValueEditorType={() => null} />); expect(screen.getByTestId(TestID.valueEditor)).toHaveAttribute('type', 'text'); }); it('prefers valueEditorType field property as string', () => { const checkboxFields: FullField[] = fields.map(f => ({ ...f, valueEditorType: 'checkbox' })); render( <QueryBuilder query={query} fields={checkboxFields} getValueEditorType={() => 'text'} /> ); expect(screen.getByTestId(TestID.valueEditor)).toHaveAttribute('type', 'checkbox'); }); it('prefers valueEditorType field property as function', () => { const checkboxFields = fields.map(f => ({ ...f, valueEditorType: () => 'checkbox' })); render( <QueryBuilder query={query} fields={checkboxFields} getValueEditorType={() => 'text'} /> ); expect(screen.getByTestId(TestID.valueEditor)).toHaveAttribute('type', 'checkbox'); }); }); describe('when getInputType fn prop is provided', () => { it('invokes custom getInputType function', () => { const getInputType = jest.fn(() => 'text' as const); render(<QueryBuilder query={query} fields={fields} getInputType={getInputType} />); expect(getInputType).toHaveBeenCalledWith(rule.field, rule.operator, { fieldData: fields[1], }); }); it('handles invalid getInputType function', () => { render(<QueryBuilder query={query} fields={fields} getInputType={() => null} />); expect(screen.getByTestId(TestID.valueEditor)).toHaveAttribute('type', 'text'); }); }); describe('when getValues fn prop is provided', () => { const getValueEditorType = () => 'select' as const; it('invokes custom getValues function', () => { const getValues = jest.fn(() => [{ name: 'test', label: 'Test' }]); render( <QueryBuilder query={query} fields={fields} getValueEditorType={getValueEditorType} getValues={getValues} /> ); expect(getValues).toHaveBeenCalledWith(rule.field, rule.operator, { fieldData: fields[1] }); }); it('invokes custom getValues function returning value-based options', () => { const getValues = jest.fn((): FieldByValue[] => [{ value: 'test', label: 'Test' }]); render( <QueryBuilder query={query} fields={fields} getValueEditorType={getValueEditorType} getValues={getValues} /> ); expect(getValues).toHaveBeenCalledWith(rule.field, rule.operator, { fieldData: fields[1] }); }); it('generates the correct number of options', () => { const getValues = jest.fn(() => [{ name: 'test', label: 'Test' }]); render( <QueryBuilder query={query} fields={fields} getValueEditorType={getValueEditorType} getValues={getValues} /> ); const opts = screen.getByTestId(TestID.valueEditor).querySelectorAll('option'); expect(opts).toHaveLength(1); }); it('handles invalid getValues function', () => { // @ts-expect-error getValues should return an array of options or option groups render(<QueryBuilder query={query} fields={fields} getValues={() => null} />); const select = screen.getByTestId(TestID.valueEditor); const opts = select.querySelectorAll('option'); expect(opts).toHaveLength(0); }); }); }); describe('actions', () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, { name: 'field3', label: 'Field 3', valueEditorType: 'select' }, ]; const setup = (xp?: QueryBuilderProps<RuleGroupType, FullOption, FullOption, FullOption>) => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); return { onQueryChange, selectors: render(<QueryBuilder fields={fields} onQueryChange={onQueryChange} {...xp} />), }; }; it('updates field with arbitrary value', async () => { const fieldSelector = ({ value, handleOnChange }: FieldSelectorProps) => ( <input type="text" value={value} onChange={e => handleOnChange(e.target.value)} /> ); const { onQueryChange } = setup({ controlElements: { fieldSelector }, addRuleToNewGroups: true, }); const input = screen.getAllByRole('textbox')[0]; await user.type(input, 'f', { initialSelectionStart: 0, initialSelectionEnd: 10 }); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ field: 'f' })] }) ); }); it('creates a new rule and remove that rule', async () => { const { onQueryChange } = setup(); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeInTheDocument(); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.anything()] }) ); await user.click(screen.getByTestId(TestID.removeRule)); expect(screen.queryByTestId(TestID.rule)).toBeNull(); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); }); it('creates a new group and remove that group', async () => { const { onQueryChange } = setup(); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); await user.click(screen.getByTestId(TestID.addGroup)); expect(screen.getAllByTestId(TestID.ruleGroup)).toHaveLength(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.anything()] }) ); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ combinator: 'and' })); await user.click(screen.getByTestId(TestID.removeGroup)); expect(screen.getAllByTestId(TestID.ruleGroup)).toHaveLength(1); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); }); it('creates a new rule and change the fields', async () => { const { onQueryChange } = setup(); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.anything()] }) ); await user.selectOptions(screen.getByTestId(TestID.fields), 'field2'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ field: 'field2' })] }) ); }); it('creates a new rule and change the operator', async () => { const { onQueryChange } = setup(); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.anything()] }) ); await user.selectOptions(screen.getByTestId(TestID.operators), '!='); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '!=' })] }) ); }); it('changes the combinator of the root group', async () => { const { onQueryChange } = setup(); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); await user.selectOptions(screen.getByTestId(TestID.combinators), 'or'); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ rules: [] })); expect(onQueryChange).toHaveBeenLastCalledWith(expect.objectContaining({ combinator: 'or' })); }); it('sets default value for a rule', async () => { const { selectors: { rerender }, onQueryChange, } = setup(); rerender( <QueryBuilder fields={fields} onQueryChange={onQueryChange} getValues={(field: string) => { if (field === 'field1' || field === 'field3') { return [ { name: 'value1', label: 'Value 1' }, { name: 'value2', label: 'Value 2' }, ]; } return []; }} getValueEditorType={f => (f === 'field2' ? 'checkbox' : 'text')} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: '' })] }) ); await user.selectOptions(screen.getByTestId(TestID.fields), 'field2'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ field: 'field2', value: false })], }) ); await user.selectOptions(screen.getByTestId(TestID.fields), 'field3'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ field: 'field3', value: 'value1' })], }) ); }); it('sets default value for a "radio" rule', async () => { const fs: Field[] = [ { name: 'f', label: 'F', valueEditorType: 'radio', values: [ { name: 'value1', label: 'Value 1' }, { name: 'value2', label: 'Value 2' }, ], }, ]; const { onQueryChange } = setup({ fields: fs }); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'value1' })], }) ); }); }); describe('resetOnFieldChange prop', () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, ]; const setup = () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); return { onQueryChange, selectors: render(<QueryBuilder fields={fields} onQueryChange={onQueryChange} />), }; }; it('resets the operator and value when true', async () => { const { onQueryChange } = setup(); await user.click(screen.getByTestId(TestID.addRule)); await user.selectOptions(screen.getByTestId(TestID.operators), '>'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '>' })] }) ); await user.type(screen.getByTestId(TestID.valueEditor), 'Test'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'Test' })] }) ); await user.selectOptions(screen.getByTestId(TestID.fields), 'field2'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '=', value: '' })] }) ); }); it('does not reset the operator and value when false', async () => { const { selectors: { rerender }, onQueryChange, } = setup(); rerender( <QueryBuilder resetOnFieldChange={false} fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); await user.selectOptions(screen.getByTestId(TestID.operators), '>'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '>' })] }) ); await user.type(screen.getByTestId(TestID.valueEditor), 'Test'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'Test' })] }) ); await user.selectOptions(screen.getByTestId(TestID.fields), 'field2'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '>', value: 'Test' })], }) ); }); }); describe('resetOnOperatorChange prop', () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, { name: 'field3', label: 'Field 3', values: [ { name: 'value1', label: 'Value 1' }, { name: 'value2', label: 'Value 2' }, ], }, ]; it('resets the value when true', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder resetOnOperatorChange fields={fields} onQueryChange={onQueryChange} addRuleToNewGroups /> ); await user.selectOptions(screen.getByTestId(TestID.operators), '>'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '>' })] }) ); await user.type(screen.getByTestId(TestID.valueEditor), 'Test'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'Test' })] }) ); await user.selectOptions(screen.getByTestId(TestID.operators), '='); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '=', value: '' })] }) ); // Does not choose a value from the values list when the operator changes await user.selectOptions(screen.getByTestId(TestID.fields), 'field3'); await user.selectOptions(screen.getByTestId(TestID.operators), 'beginsWith'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: 'beginsWith', value: '' })], }) ); }); it('does not reset the value when false', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder resetOnOperatorChange={false} fields={fields} onQueryChange={onQueryChange} addRuleToNewGroups /> ); await user.selectOptions(screen.getByTestId(TestID.operators), '>'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '>' })] }) ); await user.type(screen.getByTestId(TestID.valueEditor), 'Test'); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'Test' })] }) ); await user.selectOptions(screen.getByTestId(TestID.operators), '='); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: '=', value: 'Test' })], }) ); }); }); describe('getDefaultField prop', () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, ]; it('sets the default field as a string', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render(<QueryBuilder getDefaultField="field2" fields={fields} onQueryChange={onQueryChange} />); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ field: 'field2' })] }) ); }); it('sets the default field as a function', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder getDefaultField={() => 'field2'} fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ field: 'field2' })] }) ); }); }); describe('getDefaultOperator prop', () => { const fields: Field[] = [{ name: 'field1', label: 'Field 1' }]; it('sets the default operator as a string', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder getDefaultOperator="beginsWith" fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: 'beginsWith' })] }) ); }); it('sets the default operator as a function', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder getDefaultOperator={() => 'beginsWith'} fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: 'beginsWith' })] }) ); }); }); describe('defaultOperator property in field', () => { it('sets the default operator', async () => { const fields: Field[] = [{ name: 'field1', label: 'Field 1', defaultOperator: 'beginsWith' }]; const onQueryChange = jest.fn<never, [RuleGroupType]>(); render(<QueryBuilder fields={fields} onQueryChange={onQueryChange} />); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ operator: 'beginsWith' })] }) ); }); }); describe('getDefaultValue prop', () => { it('sets the default value', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const fields: Field[] = [ { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, ]; render( <QueryBuilder getDefaultValue={() => 'Test Value'} fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'Test Value' })] }) ); }); }); describe('onAddRule prop', () => { it('cancels the rule addition', async () => { const onLog = jest.fn(); const onQueryChange = jest.fn<never, [RuleGroupType]>(); const onAddRule = jest.fn(() => false as const); render( <QueryBuilder onAddRule={onAddRule} onQueryChange={onQueryChange} debugMode onLog={onLog} /> ); expect(onQueryChange).toHaveBeenCalledTimes(1); await user.click(screen.getByTestId(TestID.addRule)); expect(onAddRule).toHaveBeenCalled(); expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ rule: expect.anything(), parentPath: expect.any(Array), query: expect.anything(), }) ); }); it('allows the rule addition', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render(<QueryBuilder onAddRule={() => true} onQueryChange={onQueryChange} />); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange.mock.calls[1][0].rules).toHaveLength(1); }); it('modifies the rule addition', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const rule: RuleType = { field: 'test', operator: '=', value: 'modified' }; render(<QueryBuilder onAddRule={() => rule} onQueryChange={onQueryChange} />); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'modified' })] }) ); }); it('specifies the preceding combinator', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); const dq: RuleGroupTypeIC = { rules: [{ field: 'f1', operator: '=', value: 'v1' }] }; const rule: RuleType = { field: 'test', operator: '=', value: 'modified', combinatorPreceding: 'or', }; render(<QueryBuilder onAddRule={() => rule} onQueryChange={onQueryChange} defaultQuery={dq} />); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: expect.arrayContaining([expect.anything(), 'or']) }) ); expect(screen.getByTestId(TestID.combinators)).toHaveValue('or'); }); it('passes handleOnClick context to onAddRule', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const rule: RuleType = { field: 'test', operator: '=', value: 'modified' }; const AddRuleAction = (props: ActionWithRulesAndAddersProps) => ( <> <button onClick={e => props.handleOnClick(e, false)}>Fail</button> <button onClick={e => props.handleOnClick(e, true)}>Succeed</button> </> ); render( <QueryBuilder onAddRule={(_r, _pp, _q, c) => c && rule} onQueryChange={onQueryChange} enableMountQueryChange={false} controlElements={{ addRuleAction: AddRuleAction }} /> ); await user.click(screen.getByText('Fail')); expect(onQueryChange).not.toHaveBeenCalled(); await user.click(screen.getByText('Succeed')); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'modified' })] }) ); }); }); describe('onAddGroup prop', () => { it('cancels the group addition', async () => { const onLog = jest.fn(); const onQueryChange = jest.fn<never, [RuleGroupType]>(); const onAddGroup = jest.fn(() => false as const); render( <QueryBuilder onAddGroup={onAddGroup} onQueryChange={onQueryChange} debugMode onLog={onLog} /> ); expect(onQueryChange).toHaveBeenCalledTimes(1); await user.click(screen.getByTestId(TestID.addGroup)); expect(onAddGroup).toHaveBeenCalled(); expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ ruleGroup: expect.anything(), parentPath: expect.any(Array), query: expect.anything(), }) ); }); it('allows the group addition', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const onLog = jest.fn(); render( <QueryBuilder onAddGroup={() => true} onQueryChange={onQueryChange} debugMode onLog={onLog} /> ); await user.click(screen.getByTestId(TestID.addGroup)); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange.mock.calls[1][0].rules).toHaveLength(1); }); it('modifies the group addition', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const group: RuleGroupType = { combinator: 'fake', rules: [] }; render(<QueryBuilder onAddGroup={() => group} onQueryChange={onQueryChange} />); await user.click(screen.getByTestId(TestID.addGroup)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [expect.objectContaining({ combinator: 'fake', rules: [] })], }) ); }); it('specifies the preceding combinator', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); const group: RuleGroupTypeIC = { rules: [], combinatorPreceding: 'or' }; render( <QueryBuilder onAddGroup={() => group} onQueryChange={onQueryChange} defaultQuery={{ rules: [{ field: 'f1', operator: '=', value: 'v1' }] }} /> ); await user.click(screen.getByTestId(TestID.addGroup)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: expect.arrayContaining([expect.anything(), 'or']) }) ); expect(screen.getByTestId(TestID.combinators)).toHaveValue('or'); }); it('passes handleOnClick context to onAddGroup', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const ruleGroup: RuleGroupType = { combinator: 'fake', rules: [] }; const AddGroupAction = (props: ActionWithRulesAndAddersProps) => ( <> <button onClick={e => props.handleOnClick(e, false)}>Fail</button> <button onClick={e => props.handleOnClick(e, true)}>Succeed</button> </> ); render( <QueryBuilder onAddGroup={(_g, _pp, _q, c) => c && ruleGroup} onQueryChange={onQueryChange} enableMountQueryChange={false} controlElements={{ addGroupAction: AddGroupAction }} /> ); await user.click(screen.getByText('Fail')); expect(onQueryChange).not.toHaveBeenCalled(); await user.click(screen.getByText('Succeed')); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [expect.objectContaining({ combinator: 'fake', rules: [] })], }) ); }); }); describe('onMoveRule prop', () => { const defaultQuery: RuleGroupType = { combinator: 'and', rules: [ { field: 'f1', operator: '=', value: 'v1' }, { field: 'f2', operator: '=', value: 'v2' }, { combinator: 'and', rules: [ { field: 'f3', operator: '=', value: 'v3' }, { field: 'f4', operator: '=', value: 'v4' }, ], }, ], }; it('cancels the rule move', async () => { const onLog = jest.fn(); const onQueryChange = jest.fn<never, [RuleGroupType]>(); const onMoveRule = jest.fn(() => false); render( <QueryBuilder onMoveRule={onMoveRule} onQueryChange={onQueryChange} defaultQuery={defaultQuery} debugMode onLog={onLog} showShiftActions /> ); expect(onQueryChange).toHaveBeenCalledTimes(1); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onMoveRule).toHaveBeenCalled(); expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ ruleOrGroup: expect.anything(), oldPath: expect.any(Array), newPath: 'down', query: expect.anything(), nextQuery: expect.anything(), }) ); }); it('allows the rule move', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder defaultQuery={defaultQuery} showShiftActions onMoveRule={() => true} onQueryChange={onQueryChange} /> ); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onQueryChange).toHaveBeenLastCalledWith( move(onQueryChange.mock.calls[0][0], [0], 'down') ); }); it('modifies the rule move', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const newQuery: RuleGroupType = { combinator: 'and', rules: [] }; render( <QueryBuilder defaultQuery={defaultQuery} showShiftActions onMoveRule={() => newQuery} onQueryChange={onQueryChange} /> ); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onQueryChange).toHaveBeenLastCalledWith(newQuery); }); }); describe('onMoveGroup prop', () => { const defaultQuery: RuleGroupType = { combinator: 'and', rules: [ { combinator: 'and', rules: [ { field: 'f3', operator: '=', value: 'v3' }, { field: 'f4', operator: '=', value: 'v4' }, ], }, { field: 'f1', operator: '=', value: 'v1' }, { field: 'f2', operator: '=', value: 'v2' }, ], }; it('cancels the group move', async () => { const onLog = jest.fn(); const onQueryChange = jest.fn<never, [RuleGroupType]>(); const onMoveGroup = jest.fn(() => false); render( <QueryBuilder onMoveGroup={onMoveGroup} onQueryChange={onQueryChange} defaultQuery={defaultQuery} debugMode onLog={onLog} showShiftActions /> ); expect(onQueryChange).toHaveBeenCalledTimes(1); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onMoveGroup).toHaveBeenCalled(); expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ ruleOrGroup: expect.anything(), oldPath: expect.any(Array), newPath: 'down', query: expect.anything(), nextQuery: expect.anything(), }) ); }); it('allows the group move', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder defaultQuery={defaultQuery} showShiftActions onMoveGroup={() => true} onQueryChange={onQueryChange} /> ); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onQueryChange).toHaveBeenLastCalledWith( move(onQueryChange.mock.calls[0][0], [0], 'down') ); }); it('modifies the group move', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const newQuery: RuleGroupType = { combinator: 'and', rules: [] }; render( <QueryBuilder defaultQuery={defaultQuery} showShiftActions onMoveGroup={() => newQuery} onQueryChange={onQueryChange} /> ); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onQueryChange).toHaveBeenLastCalledWith(newQuery); }); }); describe('onRemove prop', () => { it('cancels the removal', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder defaultQuery={{ combinator: 'and', rules: [ { combinator: 'and', rules: [{ field: 'field1', operator: '=', value: 'value1' }], }, ], }} onRemove={() => false} onQueryChange={onQueryChange} enableMountQueryChange={false} /> ); await user.click(screen.getByTestId(TestID.removeGroup)); await user.click(screen.getByTestId(TestID.removeRule)); expect(onQueryChange).not.toHaveBeenCalled(); }); }); describe('defaultValue property in field', () => { it('sets the default value', async () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1', defaultValue: 'Test Value 1' }, { name: 'field2', label: 'Field 2', defaultValue: 'Test Value 2' }, ]; const onQueryChange = jest.fn<never, [RuleGroupType]>(); render(<QueryBuilder fields={fields} onQueryChange={onQueryChange} />); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'Test Value 1' })] }) ); }); }); describe('values property in field', () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1', defaultValue: 'test', values: [ { name: 'test', label: 'Test value 1' }, { name: 'test2', label: 'Test2' }, ], }, { name: 'field2', label: 'Field 2', defaultValue: 'test', values: [{ name: 'test', label: 'Test' }], }, ]; it('sets the values list', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder getValueEditorType={() => 'select'} fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByTestId(TestID.valueEditor)).toHaveLength(1); expect(screen.getByTestId(TestID.valueEditor).getElementsByTagName('option')).toHaveLength(2); expect(screen.getByDisplayValue('Test value 1')).toBeInTheDocument(); }); it('sets the values list for "between" operator', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder getValueEditorType={() => 'select'} getDefaultOperator="between" fields={fields} onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByTestId(TestID.valueEditor)).toHaveLength(1); const betweenSelects = screen .getAllByRole('combobox') .filter(bs => bs.classList.contains(sc.valueListItem)); expect(betweenSelects).toHaveLength(2); for (const bs of betweenSelects) { expect(bs.getElementsByTagName('option')).toHaveLength(2); expect(bs).toHaveValue('test'); } expect(screen.getAllByDisplayValue('Test value 1')).toHaveLength(2); }); }); describe('inputType property in field', () => { it('sets the input type', async () => { const fields: Field[] = [{ name: 'field1', label: 'Field 1', inputType: 'number' }]; const onQueryChange = jest.fn<never, [RuleGroupType]>(); const { container } = render( <QueryBuilder fields={fields} onQueryChange={onQueryChange} addRuleToNewGroups /> ); expect(container.querySelector('input[type="number"]')).toBeDefined(); }); }); describe('valueEditorType property in field', () => { it('sets the value editor type', async () => { const fields: Field[] = [{ name: 'field1', label: 'Field 1', valueEditorType: 'select' }]; const onQueryChange = jest.fn<never, [RuleGroupType]>(); const { container } = render( <QueryBuilder fields={fields} onQueryChange={onQueryChange} addRuleToNewGroups /> ); expect(container.querySelector(`select.${sc.value}`)).toBeDefined(); }); }); describe('operators property in field', () => { it('sets the operators options', async () => { const operators = [{ name: '=', label: '=' }]; const fields: Field[] = [ { name: 'field1', label: 'Field 1', operators }, { name: 'field2', label: 'Field 2', operators }, ]; const onQueryChange = jest.fn<never, [RuleGroupType]>(); const { container } = render( <QueryBuilder fields={fields} onQueryChange={onQueryChange} addRuleToNewGroups /> ); expect(container.querySelector(`select.${sc.operators}`)).toBeDefined(); expect(container.querySelectorAll(`select.${sc.operators} option`)).toHaveLength(1); }); }); describe('autoSelectField', () => { const operators = [{ name: '=', label: '=' }]; const fields: Field[] = [ { name: 'field1', label: 'Field 1', operators }, { name: 'field2', label: 'Field 2', operators }, ]; it('initially hides the operator selector and value editor', async () => { const { container } = render(<QueryBuilder fields={fields} autoSelectField={false} />); await user.click(screen.getByTestId(TestID.addRule)); expect(container.querySelectorAll(`select.${sc.fields}`)).toHaveLength(1); expect(container.querySelectorAll(`select.${sc.operators}`)).toHaveLength(0); expect(container.querySelectorAll(`.${sc.value}`)).toHaveLength(0); }); it('uses the placeholderLabel and placeholderName', async () => { const placeholderName = 'Test placeholder name'; const placeholderLabel = 'Test placeholder label'; render( <QueryBuilder fields={fields} autoSelectField={false} translations={{ fields: { placeholderLabel, placeholderName } }} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByDisplayValue(placeholderLabel)).toHaveValue(placeholderName); }); it('uses the placeholderGroupLabel', async () => { const placeholderGroupLabel = 'Test group placeholder'; const { container } = render( <QueryBuilder fields={[{ label: 'Fields', options: fields }]} autoSelectField={false} translations={{ fields: { placeholderGroupLabel } }} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect( container.querySelector(`optgroup[label="${placeholderGroupLabel}"]`) ).toBeInTheDocument(); }); }); describe('autoSelectOperator', () => { const operators = [{ name: '=', label: '=' }]; const fields: Field[] = [ { name: 'field1', label: 'Field 1', operators }, { name: 'field2', label: 'Field 2', operators }, ]; it('initially hides the value editor', async () => { const { container } = render(<QueryBuilder fields={fields} autoSelectOperator={false} />); await user.click(screen.getByTestId(TestID.addRule)); expect(container.querySelectorAll(`select.${sc.fields}`)).toHaveLength(1); expect(container.querySelectorAll(`select.${sc.operators}`)).toHaveLength(1); expect(screen.getByTestId(TestID.operators)).toHaveValue(defaultPlaceholderOperatorName); expect(container.querySelectorAll(`.${sc.value}`)).toHaveLength(0); }); it('uses the placeholderLabel and placeholderName', async () => { const placeholderName = 'Test placeholder name'; const placeholderLabel = 'Test placeholder label'; render( <QueryBuilder fields={fields} autoSelectOperator={false} translations={{ operators: { placeholderLabel, placeholderName } }} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByDisplayValue(placeholderLabel)).toHaveValue(placeholderName); }); it('uses the placeholderGroupLabel', async () => { const placeholderGroupLabel = 'Test group placeholder'; const { container } = render( <QueryBuilder fields={fields.map(f => ({ ...f, operators: [{ label: 'Operators', options: operators }], }))} autoSelectOperator={false} translations={{ operators: { placeholderGroupLabel } }} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect( container.querySelector(`optgroup[label="${placeholderGroupLabel}"]`) ).toBeInTheDocument(); }); }); describe('valueEditorType "multiselect" default values', () => { const fields: Field[] = [ { name: 'field1', label: 'Field 1', valueEditorType: 'multiselect', values: [ { name: 'test1', label: 'Test1' }, { name: 'test2', label: 'Test2' }, ], }, ]; it('does not unnecessarily select a value - string values', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render(<QueryBuilder fields={fields} addRuleToNewGroups onQueryChange={onQueryChange} />); expect(onQueryChange).toHaveBeenCalledWith( expect.objectContaining({ id: expect.any(String), combinator: 'and', not: false, rules: [ { id: expect.any(String), field: 'field1', operator: '=', value: '', valueSource: 'value', }, ], }) ); }); it('does not unnecessarily select a value - lists as arrays', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder fields={fields} addRuleToNewGroups onQueryChange={onQueryChange} listsAsArrays /> ); expect(onQueryChange).toHaveBeenCalledWith( expect.objectContaining({ id: expect.any(String), combinator: 'and', not: false, rules: [ { id: expect.any(String), field: 'field1', operator: '=', value: [], valueSource: 'value', }, ], }) ); }); }); describe('addRuleToNewGroups', () => { const query: RuleGroupType = { combinator: 'and', rules: [] }; it('does not add a rule when the component is created', () => { render(<QueryBuilder query={query} addRuleToNewGroups />); expect(screen.queryByTestId(TestID.rule)).toBeNull(); }); it('adds a rule when a new group is created', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render(<QueryBuilder query={query} onQueryChange={onQueryChange} addRuleToNewGroups />); await user.click(screen.getByTestId(TestID.addGroup)); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ rules: [expect.objectContaining({ field: defaultPlaceholderFieldName })], }), ], }) ); }); it('adds a rule when mounted if no initial query is provided', () => { render(<QueryBuilder addRuleToNewGroups />); expect(screen.getByTestId(TestID.rule)).toBeDefined(); }); }); describe('showShiftActions', () => { it('is disabled if rule is locked', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ combinator: 'and', rules: [ { combinator: 'and', rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, { field: 'lastName', operator: '=', value: 'Vai' }, ], disabled: true, }, ], }} /> ); const shiftRuleButtons = screen .getAllByTestId(TestID.ruleGroup)[1] .querySelectorAll(`.${sc.shiftActions}>button`); for (const b of Array.from(shiftRuleButtons)) { expect(b).toBeDisabled(); } }); describe('standard rule groups', () => { it('shifts rules', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ combinator: 'and', rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); expect(screen.getAllByText(t.shiftActionUp.label)[0]).toBeDisabled(); expect(screen.getAllByText(t.shiftActionDown.label).at(-1)).toBeDisabled(); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [ expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }) ); }); it('clones rules', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ combinator: 'and', rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); expect(screen.getAllByText(t.shiftActionUp.label)[0]).toBeDisabled(); expect(screen.getAllByText(t.shiftActionDown.label).at(-1)).toBeDisabled(); await user.keyboard('{Alt>}'); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); await user.keyboard('{/Alt}'); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }) ); }); it('shifts rule groups', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ combinator: 'and', rules: [ { field: 'lastName', operator: '=', value: 'Vai' }, { combinator: 'or', rules: [{ field: 'firstName', operator: '=', value: 'Steve' }], }, ], }} /> ); await user.click(screen.getAllByText(t.shiftActionUp.label)[1]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [ expect.objectContaining({ combinator: 'or', rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }), expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), ], }) ); }); }); describe('independent combinators', () => { it('shifts rules with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, 'and', { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); expect(screen.getAllByText(t.shiftActionUp.label)[0]).toBeDisabled(); expect(screen.getAllByText(t.shiftActionDown.label).at(-1)).toBeDisabled(); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), 'and', expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }) ); }); it('clones rules with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, 'and', { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); expect(screen.getAllByText(t.shiftActionUp.label)[0]).toBeDisabled(); expect(screen.getAllByText(t.shiftActionDown.label).at(-1)).toBeDisabled(); await user.keyboard('{Alt>}'); await user.click(screen.getAllByText(t.shiftActionDown.label)[0]); await user.keyboard('{/Alt}'); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), 'and', expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), 'and', expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }) ); }); it('shifts first rule with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder showShiftActions onQueryChange={onQueryChange} defaultQuery={{ rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, 'and', { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); await user.click(screen.getAllByText(t.shiftActionUp.label)[1]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), 'and', expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }) ); }); }); }); describe('showCloneButtons', () => { describe('standard rule groups', () => { it('clones rules', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder showCloneButtons onQueryChange={onQueryChange} defaultQuery={{ combinator: 'and', rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); await user.click(screen.getAllByText(t.cloneRule.label)[0]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), ], }) ); }); it('clones rule groups', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder showCloneButtons onQueryChange={onQueryChange} defaultQuery={{ combinator: 'and', rules: [ { combinator: 'or', rules: [{ field: 'firstName', operator: '=', value: 'Steve' }], }, { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); await user.click(screen.getAllByText(t.cloneRule.label)[0]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ combinator: 'and', rules: [ expect.objectContaining({ combinator: 'or', rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }), expect.objectContaining({ combinator: 'or', rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }), expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), ], }) ); }); }); describe('independent combinators', () => { it('clones a single rule with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder showCloneButtons onQueryChange={onQueryChange} defaultQuery={{ rules: [{ field: 'firstName', operator: '=', value: 'Steve' }], }} /> ); await user.click(screen.getByText(t.cloneRule.label)); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), 'and', expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), ], }) ); }); it('clones first rule with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder showCloneButtons onQueryChange={onQueryChange} defaultQuery={{ rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, 'and', { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); await user.click(screen.getAllByText(t.cloneRule.label)[0]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), 'and', expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), 'and', expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), ], }) ); }); it('clones last rule with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder showCloneButtons onQueryChange={onQueryChange} defaultQuery={{ rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, 'or', { field: 'lastName', operator: '=', value: 'Vai' }, ], }} /> ); await user.click(screen.getAllByText(t.cloneRule.label)[1]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ field: 'firstName', operator: '=', value: 'Steve' }), 'or', expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), 'or', expect.objectContaining({ field: 'lastName', operator: '=', value: 'Vai' }), ], }) ); }); }); }); describe('idGenerator', () => { it('uses custom id generator', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const rule = (props: RuleProps) => ( <div> <button type="button" onClick={() => props.actions.moveRule(props.path, [0], true)}> clone </button> </div> ); render( <QueryBuilder idGenerator={() => `${Math.random()}`} onQueryChange={onQueryChange} controlElements={{ rule }} /> ); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ id: expect.stringMatching(numericRegex) }) ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ id: expect.stringMatching(numericRegex) })], }) ); await user.click(screen.getByTestId(TestID.addGroup)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ id: expect.stringMatching(numericRegex) }), expect.objectContaining({ id: expect.stringMatching(numericRegex) }), ], }) ); await user.click(screen.getByText('clone')); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ id: expect.stringMatching(numericRegex) }), expect.objectContaining({ id: expect.stringMatching(numericRegex) }), ], }) ); }); }); describe('independent combinators', () => { it('renders a rule group with independent combinators', () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render(<QueryBuilder defaultQuery={{ rules: [] }} onQueryChange={onQueryChange} />); expect(screen.getByTestId(TestID.ruleGroup)).toBeDefined(); expect(onQueryChange).toHaveBeenLastCalledWith( expect.not.objectContaining({ combinator: expect.anything() }) ); }); it('renders a rule group with addRuleToNewGroups', async () => { render(<QueryBuilder addRuleToNewGroups defaultQuery={{ rules: [] }} />); await user.click(screen.getByTestId(TestID.addGroup)); expect(screen.getByTestId(TestID.rule)).toBeDefined(); }); it('calls onQueryChange with query', () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); const dq: RuleGroupTypeIC = { id: 'id', rules: [], not: false }; render(<QueryBuilder onQueryChange={onQueryChange} defaultQuery={dq} />); expect(onQueryChange).toHaveBeenCalledTimes(1); expect(onQueryChange).toHaveBeenLastCalledWith(dq); }); it('adds rules with independent combinators', async () => { // render(<QueryBuilder defaultQuery={{ rules: [] }} />); render(<QueryBuilder defaultQuery={{ rules: [] }} />); expect(screen.queryAllByTestId(TestID.combinators)).toHaveLength(0); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.rule)).toBeDefined(); expect(screen.queryAllByTestId(TestID.combinators)).toHaveLength(0); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByTestId(TestID.rule)).toHaveLength(2); expect(screen.getAllByTestId(TestID.combinators)).toHaveLength(1); expect(screen.getByTestId(TestID.combinators)).toHaveValue('and'); await user.selectOptions(screen.getByTestId(TestID.combinators), 'or'); await user.click(screen.getByTestId(TestID.addRule)); const combinatorSelectors = screen.getAllByTestId(TestID.combinators); expect(combinatorSelectors[0]).toHaveValue('or'); }); it('adds groups with independent combinators', async () => { render(<QueryBuilder defaultQuery={{ rules: [] }} />); expect(screen.queryAllByTestId(TestID.combinators)).toHaveLength(0); await user.click(screen.getByTestId(TestID.addGroup)); expect(screen.getAllByTestId(TestID.ruleGroup)).toHaveLength(2); expect(screen.queryAllByTestId(TestID.combinators)).toHaveLength(0); await user.click(screen.getAllByTestId(TestID.addGroup)[0]); expect(screen.getAllByTestId(TestID.ruleGroup)).toHaveLength(3); expect(screen.getAllByTestId(TestID.combinators)).toHaveLength(1); expect(screen.getByTestId(TestID.combinators)).toHaveValue('and'); await user.selectOptions(screen.getByTestId(TestID.combinators), 'or'); await user.click(screen.getAllByTestId(TestID.addGroup)[0]); const combinatorSelectors = screen.getAllByTestId(TestID.combinators); expect(combinatorSelectors[0]).toHaveValue('or'); }); it('removes rules along with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); const query: RuleGroupTypeIC = { rules: [ { field: 'firstName', operator: '=', value: '1' }, 'and', { field: 'firstName', operator: '=', value: '2' }, 'or', { field: 'firstName', operator: '=', value: '3' }, ], }; const { rerender } = render(<QueryBuilder query={query} onQueryChange={onQueryChange} />); expect(screen.getAllByTestId(TestID.rule)).toHaveLength(3); expect(screen.getAllByTestId(TestID.combinators)).toHaveLength(2); await user.click(screen.getAllByTestId(TestID.removeRule)[1]); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ { field: 'firstName', operator: '=', value: '1' }, 'or', { field: 'firstName', operator: '=', value: '3' }, ], }) ); rerender( <QueryBuilder query={onQueryChange.mock.lastCall?.[0]} onQueryChange={onQueryChange} /> ); await user.click(screen.getAllByTestId(TestID.removeRule)[0]); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: expect.arrayContaining([expect.objectContaining({ value: '3' })]), }) ); }); it('removes groups along with independent combinators', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); const query: RuleGroupTypeIC = { rules: [{ rules: [] }, 'and', { rules: [] }, 'or', { rules: [] }], }; const { rerender } = render(<QueryBuilder query={query} onQueryChange={onQueryChange} />); expect(screen.getAllByTestId(TestID.ruleGroup)).toHaveLength(4); expect(screen.getAllByTestId(TestID.combinators)).toHaveLength(2); expect(onQueryChange).toHaveBeenCalledTimes(1); await user.click(screen.getAllByTestId(TestID.removeGroup)[1]); expect(onQueryChange).toHaveBeenCalledTimes(2); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [ expect.objectContaining({ rules: [] }), 'or', expect.objectContaining({ rules: [] }), ], }) ); rerender( <QueryBuilder query={onQueryChange.mock.lastCall?.[0]} onQueryChange={onQueryChange} /> ); await user.click(screen.getAllByTestId(TestID.removeGroup)[0]); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ rules: [] })] }) ); }); }); describe('validation', () => { it('does not validate if no validator function is provided', () => { render(<QueryBuilder />); expect(screen.getByRole('form')).not.toHaveClass(sc.valid); expect(screen.getByRole('form')).not.toHaveClass(sc.invalid); }); it('validates groups if default validator function is provided', async () => { const { container } = render(<QueryBuilder validator={defaultValidator} />); await user.click(screen.getByTestId(TestID.addGroup)); // Expect the root group to be valid (contains the inner group) expect(container.querySelectorAll(`.${sc.ruleGroup}.${sc.valid}`)).toHaveLength(1); // Expect the inner group to be invalid (empty) expect(container.querySelectorAll(`.${sc.ruleGroup}.${sc.invalid}`)).toHaveLength(1); }); it('uses custom validator function returning false', () => { const validator = jest.fn(() => false); render(<QueryBuilder validator={validator} />); expect(validator).toHaveBeenCalled(); expect(screen.getByRole('form')).not.toHaveClass(sc.valid); expect(screen.getByRole('form')).toHaveClass(sc.invalid); }); it('uses custom validator function returning true', () => { const validator = jest.fn(() => true); render(<QueryBuilder validator={validator} />); expect(validator).toHaveBeenCalled(); expect(screen.getByRole('form')).toHaveClass(sc.valid); expect(screen.getByRole('form')).not.toHaveClass(sc.invalid); }); it('passes down validationMap to children', () => { const valMap: ValidationMap = { id: { valid: false, reasons: ['invalid'] }, }; const RuleGroupValMapDisplay = (props: RuleGroupProps) => ( <div data-testid={TestID.ruleGroup}>{JSON.stringify(props.schema.validationMap)}</div> ); render( <QueryBuilder validator={() => valMap} controlElements={{ ruleGroup: RuleGroupValMapDisplay }} /> ); expect(screen.getByTestId(TestID.ruleGroup).innerHTML).toBe(JSON.stringify(valMap)); }); }); describe('disabled', () => { it('has the correct classname', () => { const { container } = render(<QueryBuilder disabled />); expect(container.querySelectorAll('div')[0]).toHaveClass(sc.disabled); }); it('has the correct classname when disabled prop is false but root group is disabled', () => { const { container } = render( <QueryBuilder query={{ disabled: true, combinator: 'and', rules: [] }} /> ); expect(container.querySelectorAll('div')[0]).not.toHaveClass(sc.disabled); }); it('prevents changes when disabled', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder fields={[ { name: 'field0', label: 'Field 0' }, { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, { name: 'field3', label: 'Field 3' }, { name: 'field4', label: 'Field 4' }, ]} enableMountQueryChange={false} onQueryChange={onQueryChange} showCloneButtons showNotToggle disabled query={{ rules: [ { field: 'field0', operator: '=', value: '0' }, 'and', { field: 'field1', operator: '=', value: '1' }, 'and', { field: 'field2', operator: '=', value: '2' }, 'and', { rules: [ { field: 'field3', operator: '=', value: '3' }, 'and', { field: 'field4', operator: '=', value: '4' }, ], }, ], }} /> ); await user.click(screen.getAllByTitle(t.addRule.title)[0]); await user.click(screen.getAllByTitle(t.addGroup.title)[0]); await user.click(screen.getAllByTitle(t.removeRule.title)[0]); await user.click(screen.getAllByTitle(t.removeGroup.title)[0]); await user.click(screen.getAllByTitle(t.cloneRule.title)[0]); await user.click(screen.getAllByTitle(t.cloneRuleGroup.title)[0]); await user.click(screen.getAllByLabelText(t.notToggle.label)[0]); await user.selectOptions(screen.getAllByDisplayValue('Field 0')[0], 'field1'); await user.selectOptions(screen.getAllByDisplayValue('=')[0], '>'); await user.type(screen.getAllByDisplayValue('4')[0], 'Not 4'); expect(onQueryChange).not.toHaveBeenCalled(); }); it('disables a specific path and its children', () => { render( <QueryBuilder disabled={[[2]]} query={{ combinator: 'and', rules: [ { field: 'firstName', operator: '=', value: 'Steve' }, { field: 'lastName', operator: '=', value: 'Vai' }, { combinator: 'and', rules: [{ field: 'age', operator: '>', value: 28 }], }, ], }} /> ); // First two rules (paths [0] and [1]) are enabled expect(screen.getAllByTestId(TestID.fields)[0]).not.toBeDisabled(); expect(screen.getAllByTestId(TestID.operators)[0]).not.toBeDisabled(); expect(screen.getAllByTestId(TestID.valueEditor)[0]).not.toBeDisabled(); expect(screen.getAllByTestId(TestID.fields)[1]).not.toBeDisabled(); expect(screen.getAllByTestId(TestID.operators)[1]).not.toBeDisabled(); expect(screen.getAllByTestId(TestID.valueEditor)[1]).not.toBeDisabled(); // Rule group at path [2] is disabled expect(screen.getAllByTestId(TestID.combinators)[1]).toBeDisabled(); expect(screen.getAllByTestId(TestID.addRule)[1]).toBeDisabled(); expect(screen.getAllByTestId(TestID.addGroup)[1]).toBeDisabled(); expect(screen.getAllByTestId(TestID.fields)[2]).toBeDisabled(); expect(screen.getAllByTestId(TestID.operators)[2]).toBeDisabled(); expect(screen.getAllByTestId(TestID.valueEditor)[2]).toBeDisabled(); }); it('prevents changes from rogue components when disabled', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); const ruleToAdd: RuleType = { field: 'f1', operator: '=', value: 'v1' }; const groupToAdd: RuleGroupTypeIC = { rules: [] }; render( <QueryBuilder fields={[ { name: 'field0', label: 'Field 0' }, { name: 'field1', label: 'Field 1' }, { name: 'field2', label: 'Field 2' }, { name: 'field3', label: 'Field 3' }, { name: 'field4', label: 'Field 4' }, ]} enableMountQueryChange={false} onQueryChange={onQueryChange} enableDragAndDrop showCloneButtons showNotToggle disabled controlElements={{ ruleGroupHeaderElements: ({ actions }) => ( <> <button onClick={() => actions.onRuleAdd(ruleToAdd, [])}>onRuleAdd</button> <button onClick={() => actions.onGroupAdd(groupToAdd, [])}>onGroupAdd</button> <button onClick={() => actions.onPropChange('not', true, [])}>onPropChange</button> <button onClick={() => actions.onGroupRemove([6])}>onGroupRemove</button> </> ), ruleGroupBodyElements: ({ actions }) => ( <> <button onClick={() => actions.onPropChange('field', 'f2', [0])}>onPropChange</button> <button onClick={() => actions.onPropChange('combinator', 'or', [1])}> onPropChange </button> <button onClick={() => actions.onRuleRemove([0])}>onRuleRemove</button> <button onClick={() => actions.moveRule([6], [0])}>moveRule</button> <button onClick={() => actions.moveRule([6], [0], true)}>moveRule</button> </> ), }} query={{ rules: [ { field: 'field0', operator: '=', value: '0' }, 'and', { field: 'field1', operator: '=', value: '1' }, 'and', { field: 'field2', operator: '=', value: '2' }, 'and', { rules: [ { field: 'field3', operator: '=', value: '3' }, 'and', { field: 'field4', operator: '=', value: '4' }, ], }, ], }} /> ); const rg = screen.getByTestId(TestID.ruleGroup); for (const b of Array.from(rg.querySelectorAll('button'))) { await user.click(b); } expect(onQueryChange).not.toHaveBeenCalled(); }); }); describe('locked rules', () => { it('top level lock button is disabled when disabled prop is set on component', () => { render(<QueryBuilder showLockButtons disabled />); expect(screen.getByTestId(TestID.lockGroup)).toBeDisabled(); }); it('does not update the query when the root group is disabled', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder fields={[ { name: 'field0', label: 'Field 0' }, { name: 'field1', label: 'Field 1' }, ]} enableMountQueryChange={false} onQueryChange={onQueryChange} enableDragAndDrop showCloneButtons showNotToggle controlElements={{ ruleGroup: ({ actions }) => ( <div data-testid={TestID.ruleGroup}> <button onClick={() => actions.onPropChange('not', true, [])} /> <button onClick={() => actions.onPropChange('field', 'f1', [0])} /> </div> ), }} query={{ disabled: true, rules: [{ field: 'field0', operator: '=', value: '0' }], }} /> ); const rg = screen.getByTestId(TestID.ruleGroup); for (const b of Array.from(rg.querySelectorAll('button'))) { await user.click(b); } expect(onQueryChange).not.toHaveBeenCalled(); }); it('does not update the query when an ancestor group is disabled', async () => { const onQueryChange = jest.fn<never, [RuleGroupTypeIC]>(); render( <QueryBuilder fields={[ { name: 'field0', label: 'Field 0' }, { name: 'field1', label: 'Field 1' }, ]} enableMountQueryChange={false} onQueryChange={onQueryChange} enableDragAndDrop showCloneButtons showNotToggle controlElements={{ ruleGroup: ({ actions }) => ( <div data-testid={TestID.ruleGroup}> <button onClick={() => actions.onPropChange('not', true, [2])} /> <button onClick={() => actions.onPropChange('field', 'f1', [2, 0])} /> </div> ), }} query={{ rules: [ { field: 'field0', operator: '=', value: '0' }, 'and', { disabled: true, rules: [{ field: 'field1', operator: '=', value: '1' }], }, ], }} /> ); const rg = screen.getByTestId(TestID.ruleGroup); for (const b of Array.from(rg.querySelectorAll('button'))) { await user.click(b); } expect(onQueryChange).not.toHaveBeenCalled(); }); }); describe('value source field', () => { const fields: Field[] = [ { name: 'f1', label: 'Field 1', valueSources: ['field'] }, { name: 'f2', label: 'Field 2', valueSources: ['field'] }, { name: 'f3', label: 'Field 3', valueSources: ['field'], comparator: () => false, }, // @ts-expect-error valueSources cannot be an empty array { name: 'f4', label: 'Field 4', valueSources: [] }, { name: 'f5', label: 'Field 5', valueSources: ['field', 'value'] }, ]; const fieldsWithBetween: Field[] = [ { name: 'fb', label: 'Field B', valueSources: ['field'], defaultOperator: 'between', }, ...fields, ]; it('sets the right default value', async () => { render(<QueryBuilder fields={fields} getDefaultField="f1" />); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByDisplayValue(fields.filter(f => f.name !== 'f1')[0].label)).toHaveClass( sc.value ); }); it('sets the right default value for "between" operator', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder fields={fieldsWithBetween} getDefaultField="fb" onQueryChange={onQueryChange} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getAllByDisplayValue(fields.filter(f => f.name !== 'fb')[0].label)).toHaveLength( 2 ); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: 'f1,f1' })] }) ); }); it('sets the right default value for "between" operator and listsAsArrays', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); render( <QueryBuilder fields={fieldsWithBetween} getDefaultField="fb" onQueryChange={onQueryChange} listsAsArrays /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onQueryChange).toHaveBeenLastCalledWith( expect.objectContaining({ rules: [expect.objectContaining({ value: ['f1', 'f1'] })] }) ); }); it('handles empty comparator results', async () => { render(<QueryBuilder fields={fields} getDefaultField="f3" />); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.getByTestId(TestID.valueEditor).getElementsByTagName('option')).toHaveLength(0); }); it('handles invalid valueSources property', async () => { render(<QueryBuilder fields={fields} getDefaultField="f4" />); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.queryByDisplayValue('Field 1')).toBeNull(); }); it('sets the default valueSource correctly', async () => { render(<QueryBuilder fields={fields} getDefaultField="f1" />); await user.click(screen.getByTestId(TestID.addRule)); await user.selectOptions(screen.getByTestId(TestID.fields), 'f5'); expect(screen.getByTestId(TestID.valueSourceSelector)).toHaveValue('field'); }); }); describe('dynamic classNames', () => { it('has correct group-based classNames', () => { render( <QueryBuilder fields={[{ name: 'f1', label: 'F1', className: 'custom-fieldBased-class' }]} combinators={[{ name: 'or', label: 'OR', className: 'custom-combinatorBased-class' }]} operators={[{ name: 'op', label: 'Op', className: 'custom-operatorBased-class' }]} getRuleClassname={() => 'custom-ruleBased-class'} getRuleGroupClassname={() => 'custom-groupBased-class'} query={{ combinator: 'or', rules: [{ field: 'f1', operator: 'op', value: 'v1' }] }} /> ); expect(screen.getByTestId(TestID.ruleGroup)).toHaveClass( 'custom-groupBased-class', 'custom-combinatorBased-class' ); expect(screen.getByTestId(TestID.rule)).toHaveClass( 'custom-ruleBased-class', 'custom-fieldBased-class', 'custom-operatorBased-class' ); }); }); describe('redux functions', () => { it('gets the query from the store', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const testFunc = jest.fn(); const getQueryBtnText = 'Get Query'; const dispatchQueryBtnText = 'Dispatch Query'; const rule = ({ schema: { getQuery, dispatchQuery } }: RuleProps) => ( <> <button onClick={() => testFunc(getQuery())}>{getQueryBtnText}</button> <button onClick={() => dispatchQuery({ combinator: 'or', rules: [] })}> {' '} {dispatchQueryBtnText}{' '} </button> </> ); render(<QueryBuilder onQueryChange={onQueryChange} controlElements={{ rule }} />); await user.click(screen.getByTestId(TestID.addRule)); await user.click(screen.getByText(getQueryBtnText)); expect(testFunc.mock.lastCall?.[0]).toMatchObject({ combinator: 'and', not: false, rules: [ { field: '~', operator: '=', value: '', valueSource: 'value', }, ], }); await user.click(screen.getByText(dispatchQueryBtnText)); expect(onQueryChange.mock.lastCall?.[0]).toMatchObject({ combinator: 'or', rules: [] }); }); it('updates the store when an entirely new query prop is provided', async () => { const emptyQuery: RuleGroupType = { combinator: 'and', rules: [] }; const QBApp = ({ query }: { query: RuleGroupType }) => { const [q, sq] = React.useState(query); return ( <> <button type="button" onClick={() => sq(emptyQuery)}> Reset </button> <QueryBuilder query={q} onQueryChange={sq} enableMountQueryChange={false} /> </> ); }; render(<QBApp query={emptyQuery} />); await user.click(screen.getByTestId(TestID.addRule)); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.queryAllByTestId(TestID.rule)).toHaveLength(2); await user.click(screen.getByText('Reset')); expect(screen.queryAllByTestId(TestID.rule)).toHaveLength(0); await user.click(screen.getByTestId(TestID.addRule)); expect(screen.queryAllByTestId(TestID.rule)).toHaveLength(1); }); }); describe('nested object immutability', () => { it('does not modify rules it does not have to modify', async () => { const onQueryChange = jest.fn<never, [RuleGroupType]>(); const immutableRule: RuleType = { field: 'this', operator: '=', value: 'should stay the same', }; const defaultQuery: RuleGroupType = { combinator: 'and', rules: [ { field: 'this', operator: '=', value: 'can change' }, { combinator: 'and', rules: [immutableRule] }, ], }; const props: QueryBuilderProps<typeof defaultQuery, FullField, FullOperator, FullCombinator> = { onQueryChange, defaultQuery, enableMountQueryChange: false, }; render(<QueryBuilder {...props} />); const { calls } = onQueryChange.mock; await user.click(screen.getAllByTestId(TestID.addRule)[0]); expect(calls[0][0]).not.toBe(defaultQuery); expect(findPath([0], calls[0][0])).toMatchObject(findPath([0], defaultQuery) as RuleType); expect(findPath([1, 0], calls[0][0])).toMatchObject(immutableRule); await user.selectOptions(screen.getAllByTestId(TestID.operators)[0], '>'); expect(findPath([0], calls[1][0])).not.toBe(findPath([0], calls[0][0])); expect(findPath([1, 0], calls[1][0])).toMatchObject(immutableRule); }); }); describe('controlElements bulk override properties', () => { const actionElement = (props: ActionProps) => ( <button data-testid={props.testID}>{'actionElement'}</button> ); const valueSelector = (props: ValueSelectorProps) => ( <select data-testid={props.testID} value="v1"> <option value="v1">v1</option> </select> ); it('works from props', () => { render( <QueryBuilder showCloneButtons showLockButtons controlElements={{ actionElement, valueSelector }} query={{ combinator: 'and', rules: [{ combinator: 'or', rules: [{ field: 'f1', operator: '=', value: 'not "v1"' }] }], }} /> ); expect(screen.getAllByTestId(TestID.addGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.addRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.removeGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.removeRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.cloneGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.cloneRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.lockGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.lockRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.combinators)[0]).toHaveValue('v1'); expect(screen.getAllByTestId(TestID.fields)[0]).toHaveValue('v1'); expect(screen.getAllByTestId(TestID.operators)[0]).toHaveValue('v1'); }); it('works from context', () => { render( <QueryBuilderContext.Provider value={{ controlElements: { actionElement, valueSelector } }}> <QueryBuilder showCloneButtons showLockButtons query={{ combinator: 'and', rules: [{ combinator: 'or', rules: [{ field: 'f1', operator: '=', value: 'v1' }] }], }} /> </QueryBuilderContext.Provider> ); expect(screen.getAllByTestId(TestID.addGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.addRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.removeGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.removeRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.cloneGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.cloneRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.lockGroup)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.lockRule)[0]).toHaveTextContent('actionElement'); expect(screen.getAllByTestId(TestID.combinators)[0]).toHaveValue('v1'); expect(screen.getAllByTestId(TestID.fields)[0]).toHaveValue('v1'); expect(screen.getAllByTestId(TestID.operators)[0]).toHaveValue('v1'); }); }); describe('null controlElements', () => { const query: RuleGroupType = { combinator: 'and', rules: [{ combinator: 'or', rules: [{ field: 'f1', operator: '=', value: 'v1' }] }], }; const controlElements: ControlElementsProp<FullField, string> = { addGroupAction: null, addRuleAction: null, cloneGroupAction: null, cloneRuleAction: null, combinatorSelector: null, dragHandle: null, fieldSelector: null, inlineCombinator: null, lockGroupAction: null, lockRuleAction: null, notToggle: null, operatorSelector: null, removeGroupAction: null, removeRuleAction: null, shiftActions: null, valueEditor: null, valueSourceSelector: null, }; const expectNothing = () => { expect(screen.queryAllByTestId(TestID.addGroup)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.addRule)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.cloneGroup)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.cloneRule)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.combinators)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.dragHandle)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.fields)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.lockGroup)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.lockRule)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.notToggle)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.operators)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.removeGroup)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.removeRule)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.shiftActions)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.valueEditor)).toHaveLength(0); expect(screen.queryAllByTestId(TestID.valueSourceSelector)).toHaveLength(0); }; it('uses `null` from context', () => { render( <QueryBuilderContext.Provider value={{ controlElements }}> <QueryBuilder showCloneButtons showLockButtons showNotToggle showShiftActions query={query} /> </QueryBuilderContext.Provider> ); expectNothing(); }); it('uses `null` from props', () => { render( <QueryBuilder showCloneButtons showLockButtons controlElements={controlElements} query={query} /> ); expectNothing(); }); it('overrides bulk overrides with `null` from context', () => { render( <QueryBuilderContext.Provider value={{ controlElements: { ...controlElements, actionElement: ActionElement, valueSelector: ValueSelector, }, }}> <QueryBuilder showCloneButtons showLockButtons showNotToggle showShiftActions query={query} /> </QueryBuilderContext.Provider> ); expectNothing(); }); it('overrides bulk overrides with `null` from props', () => { render( <QueryBuilder showCloneButtons showLockButtons controlElements={{ ...controlElements, actionElement: ActionElement, valueSelector: ValueSelector, }} query={query} /> ); expectNothing(); }); }); describe('selector hooks', () => { const queryTracker = jest.fn(); const UseQueryBuilderSelector = (props: RuleGroupProps) => { const q = useQueryBuilderSelector(getQuerySelectorById(props.schema.qbId)); queryTracker(q ?? false); return null; }; const UseQueryBuilderQueryPARAM = (props: RuleGroupProps) => { const q = useQueryBuilderQuery(props); queryTracker(q ?? false); return null; }; const UseQueryBuilderQueryNOPARAM = () => { const q = useQueryBuilderQuery(); queryTracker(q ?? false); return null; }; const generateQuery = (value: string): RuleGroupType => ({ combinator: 'and', rules: [{ field: 'f1', operator: '=', value }], }); beforeEach(() => { queryTracker.mockClear(); }); describe.each([ { RG: UseQueryBuilderSelector, testName: 'useQueryBuilderSelector' }, { RG: UseQueryBuilderQueryPARAM, testName: 'useQueryBuilderQuery with parameter' }, { RG: UseQueryBuilderQueryNOPARAM, testName: 'useQueryBuilderQuery without parameter' }, ])('$testName', ({ RG }) => { it('returns a query on first render without query prop', () => { const query: RuleGroupType = { combinator: 'and', rules: [] }; render(<QueryBuilder controlElements={{ ruleGroup: RG }} />); expect(queryTracker).toHaveBeenNthCalledWith(1, expect.objectContaining(query)); }); it('returns a query on first render with defaultQuery prop', () => { const query = generateQuery('defaultQuery prop'); render(<QueryBuilder defaultQuery={query} controlElements={{ ruleGroup: RG }} />); expect(queryTracker).toHaveBeenNthCalledWith( 1, expect.objectContaining({ combinator: 'and', rules: [expect.objectContaining(query.rules[0])], }) ); }); it('returns a query on first render with query prop', () => { const query = generateQuery('query prop'); render(<QueryBuilder query={query} controlElements={{ ruleGroup: RG }} />); expect(queryTracker).toHaveBeenNthCalledWith( 1, expect.objectContaining({ combinator: 'and', rules: [expect.objectContaining(query.rules[0])], }) ); }); }); }); describe('debug mode', () => { it('logs updates', async () => { const onLog = jest.fn(); const fields: Field[] = [ { name: 'f1', label: 'Field 1' }, { name: 'f2', label: 'Field 2' }, ]; const defaultQuery: RuleGroupType = { combinator: 'and', rules: [] }; const RuleGroupOG = defaultControlElements.ruleGroup; render( <QueryBuilder debugMode fields={fields} defaultQuery={defaultQuery} onLog={onLog} controlElements={{ ruleGroup: props => ( <div> <button onClick={() => props.actions.moveRule([1], [0])}>moveRule</button> <RuleGroupOG {...props} /> </div> ), }} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.add })); await user.selectOptions(screen.getByTestId(TestID.operators), '>'); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.update })); await user.click(screen.getByTestId(TestID.addRule)); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.add })); await user.click(screen.getByText('moveRule')); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.move })); await user.click(screen.getAllByTestId(TestID.removeRule)[0]); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.remove })); await user.click(screen.getByTestId(TestID.addGroup)); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.add })); await user.click(screen.getByTestId(TestID.removeGroup)); expect(onLog).toHaveBeenLastCalledWith(expect.objectContaining({ type: LogType.remove })); }); it('logs failed additions and removals due to onAdd/Remove handlers', async () => { const onLog = jest.fn(); const f = () => false as const; const defaultQuery: RuleGroupType = { combinator: 'and', rules: [{ field: 'f1', operator: '=', value: 'v1' }], }; render( <QueryBuilder debugMode query={defaultQuery} onLog={onLog} onRemove={f} onAddGroup={f} onAddRule={f} /> ); await user.click(screen.getByTestId(TestID.addRule)); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ type: LogType.onAddRuleFalse }) ); await user.click(screen.getByTestId(TestID.addGroup)); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ type: LogType.onAddGroupFalse }) ); await user.click(screen.getByTestId(TestID.removeRule)); expect(onLog).toHaveBeenLastCalledWith( expect.objectContaining({ type: LogType.onRemoveFalse }) ); }); it('logs failed query updates due to disabled prop', async () => { const onLog = jest.fn(); const defaultQuery: RuleGroupType = { disabled: true, combinator: 'and', rules: [], }; const ruleGroup = ({ path, actions: { moveRule, onGroupAdd, onGroupRemove, onRuleAdd, onPropChange }, }: RuleGroupProps) => ( <> <button onClick={() => onPropChange('combinator', 'or', [])}>Change Combinator</button> <button onClick={() => onRuleAdd({ field: 'f', operator: '=', value: 'v' }, [])}> Add Rule </button> <button onClick={() => onGroupAdd({ combinator: 'and', rules: [] }, [])}>Add Group</button> <button onClick={() => moveRule(path, [0], true)}>Clone Group</button> <button onClick={() => onGroupRemove(path)}>Remove Group</button> </> ); render( <QueryBuilder debugMode enableMountQueryChange={false} query={defaultQuery} onLog={onLog} controlElements={{ ruleGroup }} /> ); for (const btnText of [ 'Change Combinator', 'Add Rule', 'Add Group', 'Clone Group', 'Remove Group', ]) { await user.click(screen.getAllByText(btnText)[0]); } expect(onLog).toHaveBeenCalledTimes(5); }); }); describe('controlled/uncontrolled warnings', () => { it('tracks changes from controlled to uncontrolled and vice versa', async () => { const getQuery = (): RuleGroupType => ({ combinator: generateID(), rules: [], }); const { rerender } = render(<QueryBuilder enableMountQueryChange={false} />); await waitABeat(); expect(consoleError).not.toHaveBeenCalled(); rerender(<QueryBuilder query={getQuery()} />); await waitABeat(); expect(consoleError).toHaveBeenLastCalledWith(messages.errorUncontrolledToControlled); rerender(<QueryBuilder defaultQuery={getQuery()} query={getQuery()} />); await waitABeat(); expect(consoleError).toHaveBeenLastCalledWith(messages.errorBothQueryDefaultQuery); rerender(<QueryBuilder defaultQuery={getQuery()} />); await waitABeat(); expect(consoleError).toHaveBeenLastCalledWith(messages.errorControlledToUncontrolled); // Start the process over and test that the warnings are not re-triggered const errorCallCount = consoleError.mock.calls.length; rerender(<QueryBuilder query={getQuery()} />); await waitABeat(); rerender(<QueryBuilder defaultQuery={getQuery()} query={getQuery()} />); await waitABeat(); rerender(<QueryBuilder defaultQuery={getQuery()} />); await waitABeat(); expect(consoleError.mock.calls).toHaveLength(errorCallCount); }); }); describe('deprecated props', () => { it('warns about unnecessary independentCombinators prop', async () => { render(<QueryBuilder query={{ rules: [] }} />); await waitABeat(); expect(consoleError).not.toHaveBeenCalledWith( messages.errorUnnecessaryIndependentCombinatorsProp ); render(<QueryBuilder independentCombinators={false} query={{ rules: [] }} />); await waitABeat(); expect(consoleError).toHaveBeenCalledWith(messages.errorUnnecessaryIndependentCombinatorsProp); }); it('warns about invalid independentCombinators prop', async () => { render(<QueryBuilder independentCombinators query={{ rules: [] }} />); await waitABeat(); expect(consoleError).not.toHaveBeenCalledWith(messages.errorInvalidIndependentCombinatorsProp); render(<QueryBuilder independentCombinators query={{ combinator: 'and', rules: [] }} />); await waitABeat(); expect(consoleError).toHaveBeenCalledWith(messages.errorInvalidIndependentCombinatorsProp); }); }); ```
/content/code_sandbox/packages/react-querybuilder/src/components/QueryBuilder.test.tsx
xml
2016-06-17T22:03:19
2024-08-16T10:28:42
react-querybuilder
react-querybuilder/react-querybuilder
1,131
25,550
```xml import resolveFrom from 'resolve-from'; import semver from 'semver'; export interface VersionInfo { expoSdkVersion: string; iosDeploymentTarget: string; reactNativeVersionRange: string; androidAgpVersion?: string; supportCliIntegration?: boolean; } export const ExpoVersionMappings: VersionInfo[] = [ // Please keep sdk versions in sorted order (latest sdk first) { expoSdkVersion: '52.0.0', iosDeploymentTarget: '15.1', reactNativeVersionRange: '>= 0.76.0', supportCliIntegration: true, }, { expoSdkVersion: '51.0.0', iosDeploymentTarget: '13.4', reactNativeVersionRange: '>= 0.74.0', supportCliIntegration: true, }, { expoSdkVersion: '50.0.0', iosDeploymentTarget: '13.4', reactNativeVersionRange: '>= 0.73.0', supportCliIntegration: true, }, { expoSdkVersion: '49.0.0', iosDeploymentTarget: '13.0', reactNativeVersionRange: '>= 0.72.0', supportCliIntegration: true, }, { expoSdkVersion: '48.0.0', iosDeploymentTarget: '13.0', reactNativeVersionRange: '>= 0.71.0', androidAgpVersion: '7.4.1', }, { expoSdkVersion: '47.0.0', iosDeploymentTarget: '13.0', reactNativeVersionRange: '>= 0.70.0', }, { expoSdkVersion: '46.0.0', iosDeploymentTarget: '12.4', reactNativeVersionRange: '>= 0.69.0', }, { expoSdkVersion: '45.0.0', iosDeploymentTarget: '12.0', reactNativeVersionRange: '>= 0.65.0', }, { expoSdkVersion: '44.0.0', iosDeploymentTarget: '12.0', reactNativeVersionRange: '< 0.68.0', }, { expoSdkVersion: '43.0.0', iosDeploymentTarget: '12.0', reactNativeVersionRange: '< 0.68.0', }, ]; export function getDefaultSdkVersion(projectRoot: string): VersionInfo { const reactNativePackageJsonPath = resolveFrom.silent(projectRoot, 'react-native/package.json'); if (!reactNativePackageJsonPath) { throw new Error(`Unable to find react-native package - projectRoot[${projectRoot}]`); } const reactNativeVersion = require(reactNativePackageJsonPath).version; const versionInfo = ExpoVersionMappings.find((info) => semver.satisfies(reactNativeVersion, info.reactNativeVersionRange) ); if (!versionInfo) { throw new Error( `Unable to find compatible expo sdk version - reactNativeVersion[${reactNativeVersion}]` ); } return versionInfo; } export function getLatestSdkVersion(): VersionInfo { return ExpoVersionMappings[0]; } export function getVersionInfo(sdkVersion: string): VersionInfo | null { return ExpoVersionMappings.find((info) => info.expoSdkVersion === sdkVersion) ?? null; } ```
/content/code_sandbox/packages/install-expo-modules/src/utils/expoVersionMappings.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
746
```xml import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { TagDocModule } from '@doc/tag/tagdoc.module'; import { TagDemo } from './tagdemo'; import { TagDemoRoutingModule } from './tagdemo-routing.module'; @NgModule({ imports: [CommonModule, TagDemoRoutingModule, TagDocModule], declarations: [TagDemo] }) export class TagDemoModule {} ```
/content/code_sandbox/src/app/showcase/pages/tag/tagdemo.module.ts
xml
2016-01-16T09:23:28
2024-08-16T19:58:20
primeng
primefaces/primeng
9,969
87
```xml import { Formatter } from './formatter-interface'; import { Reporter } from './reporter-interface'; export class PlainReporter implements Reporter { constructor(private formatter: Formatter, private header: HTMLElement, private content: HTMLElement) {} setHeader(header: string) { this.header.innerHTML = header; } reportErrors(errors: any[]) { this.content.innerHTML = this.formatter.formatErrors(errors); } clearHeader() { this.header.innerHTML = ''; } clearContent() { this.content.innerHTML = ''; } highlight(id: any) { document.getElementById(id)!.classList.add('error-highlight'); } dropHighlight(id: any) { document.getElementById(id)!.classList.remove('error-highlight'); } } ```
/content/code_sandbox/docs/src/app-linter/plain-reporter.ts
xml
2016-02-10T17:22:40
2024-08-14T16:41:28
codelyzer
mgechev/codelyzer
2,446
154
```xml export type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never ```
/content/code_sandbox/packages/player/src/types.ts
xml
2016-03-06T15:19:53
2024-08-15T14:27:10
signal
ryohey/signal
1,238
31
```xml import { ControlLabel, Form, FormGroup } from "../form"; import Button from "../Button"; import FormControl from "../form/Control"; import { ModalFooter } from "../../styles/main"; import React from "react"; import { VISITOR_AUDIENCE_RULES } from "../../constants/engage"; type Props = { closeModal: () => void; onChange: (e: any) => void; }; type State = { selectedMembers: string[]; }; class RuleForm extends React.Component<Props, State> { constructor(props: Props) { super(props); } onSelect = (e: any) => { this.props.onChange(e); this.props.closeModal(); }; renderContent = () => { const { closeModal } = this.props; return ( <> <FormGroup> <ControlLabel>Rules</ControlLabel> <p> Add rules as many as you want</p> <FormControl componentclass="select" onChange={this.onSelect}> {VISITOR_AUDIENCE_RULES.map((rule, index) => ( <option key={index} value={rule.value}> {rule.text} </option> ))} </FormControl> </FormGroup> <ModalFooter> <Button btnStyle="simple" type="button" icon="cancel-1" onClick={closeModal} > Close </Button> </ModalFooter> </> ); }; render() { return <Form renderContent={this.renderContent} />; } } export default RuleForm; ```
/content/code_sandbox/packages/erxes-ui/src/components/rule/RuleForm.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
328
```xml import { ColorPicker } from './colorpicker'; /** * Custom change event. * @see {@link ColorPicker.onChange} * @group Events */ export interface ColorPickerChangeEvent { /** * Browser event */ originalEvent: Event; /** * Selected color value. */ value: string | object; } ```
/content/code_sandbox/src/app/components/colorpicker/colorpicker.interface.ts
xml
2016-01-16T09:23:28
2024-08-16T19:58:20
primeng
primefaces/primeng
9,969
71
```xml import { QueryRunner } from "../query-runner/QueryRunner" import { Subject } from "./Subject" import { SubjectTopoligicalSorter } from "./SubjectTopoligicalSorter" import { SubjectChangedColumnsComputer } from "./SubjectChangedColumnsComputer" import { SubjectWithoutIdentifierError } from "../error/SubjectWithoutIdentifierError" import { SubjectRemovedAndUpdatedError } from "../error/SubjectRemovedAndUpdatedError" import { MongoEntityManager } from "../entity-manager/MongoEntityManager" import { ObjectLiteral } from "../common/ObjectLiteral" import { SaveOptions } from "../repository/SaveOptions" import { RemoveOptions } from "../repository/RemoveOptions" import { BroadcasterResult } from "../subscriber/BroadcasterResult" import { NestedSetSubjectExecutor } from "./tree/NestedSetSubjectExecutor" import { ClosureSubjectExecutor } from "./tree/ClosureSubjectExecutor" import { MaterializedPathSubjectExecutor } from "./tree/MaterializedPathSubjectExecutor" import { OrmUtils } from "../util/OrmUtils" import { UpdateResult } from "../query-builder/result/UpdateResult" import { ObjectUtils } from "../util/ObjectUtils" import { InstanceChecker } from "../util/InstanceChecker" /** * Executes all database operations (inserts, updated, deletes) that must be executed * with given persistence subjects. */ export class SubjectExecutor { // your_sha256_hash--------- // Public Properties // your_sha256_hash--------- /** * Indicates if executor has any operations to execute (e.g. has insert / update / delete operations to be executed). */ hasExecutableOperations: boolean = false // your_sha256_hash--------- // Protected Properties // your_sha256_hash--------- /** * QueryRunner used to execute all queries with a given subjects. */ protected queryRunner: QueryRunner /** * Persistence options. */ protected options?: SaveOptions & RemoveOptions /** * All subjects that needs to be operated. */ protected allSubjects: Subject[] /** * Subjects that must be inserted. */ protected insertSubjects: Subject[] = [] /** * Subjects that must be updated. */ protected updateSubjects: Subject[] = [] /** * Subjects that must be removed. */ protected removeSubjects: Subject[] = [] /** * Subjects that must be soft-removed. */ protected softRemoveSubjects: Subject[] = [] /** * Subjects that must be recovered. */ protected recoverSubjects: Subject[] = [] // your_sha256_hash--------- // Constructor // your_sha256_hash--------- constructor( queryRunner: QueryRunner, subjects: Subject[], options?: SaveOptions & RemoveOptions, ) { this.queryRunner = queryRunner this.allSubjects = subjects this.options = options this.validate() this.recompute() } // your_sha256_hash--------- // Public Methods // your_sha256_hash--------- /** * Executes all operations over given array of subjects. * Executes queries using given query runner. */ async execute(): Promise<void> { // console.time("SubjectExecutor.execute"); // broadcast "before" events before we start insert / update / remove operations let broadcasterResult: BroadcasterResult | undefined = undefined if (!this.options || this.options.listeners !== false) { // console.time(".broadcastBeforeEventsForAll"); broadcasterResult = this.broadcastBeforeEventsForAll() if (broadcasterResult.promises.length > 0) await Promise.all(broadcasterResult.promises) // console.timeEnd(".broadcastBeforeEventsForAll"); } // since event listeners and subscribers can call save methods and/or trigger entity changes we need to recompute operational subjects // recompute only in the case if any listener or subscriber was really executed if (broadcasterResult && broadcasterResult.count > 0) { // console.time(".recompute"); this.insertSubjects.forEach((subject) => subject.recompute()) this.updateSubjects.forEach((subject) => subject.recompute()) this.removeSubjects.forEach((subject) => subject.recompute()) this.softRemoveSubjects.forEach((subject) => subject.recompute()) this.recoverSubjects.forEach((subject) => subject.recompute()) this.recompute() // console.timeEnd(".recompute"); } // make sure our insert subjects are sorted (using topological sorting) to make cascade inserts work properly // console.timeEnd("prepare"); // execute all insert operations // console.time(".insertion"); this.insertSubjects = new SubjectTopoligicalSorter( this.insertSubjects, ).sort("insert") await this.executeInsertOperations() // console.timeEnd(".insertion"); // recompute update operations since insertion can create updation operations for the // properties it wasn't able to handle on its own (referenced columns) this.updateSubjects = this.allSubjects.filter( (subject) => subject.mustBeUpdated, ) // execute update operations // console.time(".updation"); await this.executeUpdateOperations() // console.timeEnd(".updation"); // make sure our remove subjects are sorted (using topological sorting) when multiple entities are passed for the removal // console.time(".removal"); this.removeSubjects = new SubjectTopoligicalSorter( this.removeSubjects, ).sort("delete") await this.executeRemoveOperations() // console.timeEnd(".removal"); // recompute soft-remove operations this.softRemoveSubjects = this.allSubjects.filter( (subject) => subject.mustBeSoftRemoved, ) // execute soft-remove operations await this.executeSoftRemoveOperations() // recompute recover operations this.recoverSubjects = this.allSubjects.filter( (subject) => subject.mustBeRecovered, ) // execute recover operations await this.executeRecoverOperations() // update all special columns in persisted entities, like inserted id or remove ids from the removed entities // console.time(".updateSpecialColumnsInPersistedEntities"); this.updateSpecialColumnsInPersistedEntities() // console.timeEnd(".updateSpecialColumnsInPersistedEntities"); // finally broadcast "after" events after we finish insert / update / remove operations if (!this.options || this.options.listeners !== false) { // console.time(".broadcastAfterEventsForAll"); broadcasterResult = this.broadcastAfterEventsForAll() if (broadcasterResult.promises.length > 0) await Promise.all(broadcasterResult.promises) // console.timeEnd(".broadcastAfterEventsForAll"); } // console.timeEnd("SubjectExecutor.execute"); } // your_sha256_hash--------- // Protected Methods // your_sha256_hash--------- /** * Validates all given subjects. */ protected validate() { this.allSubjects.forEach((subject) => { if (subject.mustBeUpdated && subject.mustBeRemoved) throw new SubjectRemovedAndUpdatedError(subject) }) } /** * Performs entity re-computations - finds changed columns, re-builds insert/update/remove subjects. */ protected recompute(): void { new SubjectChangedColumnsComputer().compute(this.allSubjects) this.insertSubjects = this.allSubjects.filter( (subject) => subject.mustBeInserted, ) this.updateSubjects = this.allSubjects.filter( (subject) => subject.mustBeUpdated, ) this.removeSubjects = this.allSubjects.filter( (subject) => subject.mustBeRemoved, ) this.softRemoveSubjects = this.allSubjects.filter( (subject) => subject.mustBeSoftRemoved, ) this.recoverSubjects = this.allSubjects.filter( (subject) => subject.mustBeRecovered, ) this.hasExecutableOperations = this.insertSubjects.length > 0 || this.updateSubjects.length > 0 || this.removeSubjects.length > 0 || this.softRemoveSubjects.length > 0 || this.recoverSubjects.length > 0 } /** * Broadcasts "BEFORE_INSERT", "BEFORE_UPDATE", "BEFORE_REMOVE", "BEFORE_SOFT_REMOVE", "BEFORE_RECOVER" events for all given subjects. */ protected broadcastBeforeEventsForAll(): BroadcasterResult { const result = new BroadcasterResult() if (this.insertSubjects.length) this.insertSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastBeforeInsertEvent( result, subject.metadata, subject.entity!, ), ) if (this.updateSubjects.length) this.updateSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastBeforeUpdateEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.diffColumns, subject.diffRelations, ), ) if (this.removeSubjects.length) this.removeSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastBeforeRemoveEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.identifier, ), ) if (this.softRemoveSubjects.length) this.softRemoveSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastBeforeSoftRemoveEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.identifier, ), ) if (this.recoverSubjects.length) this.recoverSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastBeforeRecoverEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.identifier, ), ) return result } /** * Broadcasts "AFTER_INSERT", "AFTER_UPDATE", "AFTER_REMOVE", "AFTER_SOFT_REMOVE", "AFTER_RECOVER" events for all given subjects. * Returns void if there wasn't any listener or subscriber executed. * Note: this method has a performance-optimized code organization. */ protected broadcastAfterEventsForAll(): BroadcasterResult { const result = new BroadcasterResult() if (this.insertSubjects.length) this.insertSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastAfterInsertEvent( result, subject.metadata, subject.entity!, subject.identifier, ), ) if (this.updateSubjects.length) this.updateSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastAfterUpdateEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.diffColumns, subject.diffRelations, ), ) if (this.removeSubjects.length) this.removeSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastAfterRemoveEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.identifier, ), ) if (this.softRemoveSubjects.length) this.softRemoveSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastAfterSoftRemoveEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.identifier, ), ) if (this.recoverSubjects.length) this.recoverSubjects.forEach((subject) => this.queryRunner.broadcaster.broadcastAfterRecoverEvent( result, subject.metadata, subject.entity!, subject.databaseEntity, subject.identifier, ), ) return result } /** * Executes insert operations. */ protected async executeInsertOperations(): Promise<void> { // group insertion subjects to make bulk insertions const [groupedInsertSubjects, groupedInsertSubjectKeys] = this.groupBulkSubjects(this.insertSubjects, "insert") // then we run insertion in the sequential order which is important since we have an ordered subjects for (const groupName of groupedInsertSubjectKeys) { const subjects = groupedInsertSubjects[groupName] // we must separately insert entities which does not have any values to insert // because its not possible to insert multiple entities with only default values in bulk const bulkInsertMaps: ObjectLiteral[] = [] const bulkInsertSubjects: Subject[] = [] const singleInsertSubjects: Subject[] = [] if (this.queryRunner.connection.driver.options.type === "mongodb") { subjects.forEach((subject) => { if (subject.metadata.createDateColumn && subject.entity) { subject.entity[ subject.metadata.createDateColumn.databaseName ] = new Date() } if (subject.metadata.updateDateColumn && subject.entity) { subject.entity[ subject.metadata.updateDateColumn.databaseName ] = new Date() } subject.createValueSetAndPopChangeMap() bulkInsertSubjects.push(subject) bulkInsertMaps.push(subject.entity!) }) } else if ( this.queryRunner.connection.driver.options.type === "oracle" ) { subjects.forEach((subject) => { singleInsertSubjects.push(subject) }) } else { subjects.forEach((subject) => { // we do not insert in bulk in following cases: // - when there is no values in insert (only defaults are inserted), since we cannot use DEFAULT VALUES expression for multiple inserted rows // - when entity is a tree table, since tree tables require extra operation per each inserted row // - when oracle is used, since oracle's bulk insertion is very bad if ( subject.changeMaps.length === 0 || subject.metadata.treeType || this.queryRunner.connection.driver.options.type === "oracle" || this.queryRunner.connection.driver.options.type === "sap" ) { singleInsertSubjects.push(subject) } else { bulkInsertSubjects.push(subject) bulkInsertMaps.push( subject.createValueSetAndPopChangeMap(), ) } }) } // for mongodb we have a bit different insertion logic if ( InstanceChecker.isMongoEntityManager(this.queryRunner.manager) ) { const insertResult = await this.queryRunner.manager.insert( subjects[0].metadata.target, bulkInsertMaps, ) subjects.forEach((subject, index) => { subject.identifier = insertResult.identifiers[index] subject.generatedMap = insertResult.generatedMaps[index] subject.insertedValueSet = bulkInsertMaps[index] }) } else { // here we execute our insertion query // we need to enable entity updation because we DO need to have updated insertedMap // which is not same object as our entity that's why we don't need to worry about our entity to get dirty // also, we disable listeners because we call them on our own in persistence layer if (bulkInsertMaps.length > 0) { const insertResult = await this.queryRunner.manager .createQueryBuilder() .insert() .into(subjects[0].metadata.target) .values(bulkInsertMaps) .updateEntity( this.options && this.options.reload === false ? false : true, ) .callListeners(false) .execute() bulkInsertSubjects.forEach((subject, index) => { subject.identifier = insertResult.identifiers[index] subject.generatedMap = insertResult.generatedMaps[index] subject.insertedValueSet = bulkInsertMaps[index] }) } // insert subjects which must be inserted in separate requests (all default values) if (singleInsertSubjects.length > 0) { for (const subject of singleInsertSubjects) { subject.insertedValueSet = subject.createValueSetAndPopChangeMap() // important to have because query builder sets inserted values into it // for nested set we execute additional queries if (subject.metadata.treeType === "nested-set") await new NestedSetSubjectExecutor( this.queryRunner, ).insert(subject) await this.queryRunner.manager .createQueryBuilder() .insert() .into(subject.metadata.target) .values(subject.insertedValueSet) .updateEntity( this.options && this.options.reload === false ? false : true, ) .callListeners(false) .execute() .then((insertResult) => { subject.identifier = insertResult.identifiers[0] subject.generatedMap = insertResult.generatedMaps[0] }) // for tree tables we execute additional queries if (subject.metadata.treeType === "closure-table") { await new ClosureSubjectExecutor( this.queryRunner, ).insert(subject) } else if ( subject.metadata.treeType === "materialized-path" ) { await new MaterializedPathSubjectExecutor( this.queryRunner, ).insert(subject) } } } } subjects.forEach((subject) => { if (subject.generatedMap) { subject.metadata.columns.forEach((column) => { const value = column.getEntityValue( subject.generatedMap!, ) if (value !== undefined && value !== null) { const preparedValue = this.queryRunner.connection.driver.prepareHydratedValue( value, column, ) column.setEntityValue( subject.generatedMap!, preparedValue, ) } }) } }) } } /** * Updates all given subjects in the database. */ protected async executeUpdateOperations(): Promise<void> { const updateSubject = async (subject: Subject) => { if (!subject.identifier) throw new SubjectWithoutIdentifierError(subject) // for mongodb we have a bit different updation logic if ( InstanceChecker.isMongoEntityManager(this.queryRunner.manager) ) { const partialEntity = this.cloneMongoSubjectEntity(subject) if ( subject.metadata.objectIdColumn && subject.metadata.objectIdColumn.propertyName ) { delete partialEntity[ subject.metadata.objectIdColumn.propertyName ] } if ( subject.metadata.createDateColumn && subject.metadata.createDateColumn.propertyName ) { delete partialEntity[ subject.metadata.createDateColumn.propertyName ] } if ( subject.metadata.updateDateColumn && subject.metadata.updateDateColumn.propertyName ) { partialEntity[ subject.metadata.updateDateColumn.propertyName ] = new Date() } const manager = this.queryRunner.manager as MongoEntityManager await manager.update( subject.metadata.target, subject.identifier, partialEntity, ) } else { const updateMap: ObjectLiteral = subject.createValueSetAndPopChangeMap() // for tree tables we execute additional queries switch (subject.metadata.treeType) { case "nested-set": await new NestedSetSubjectExecutor( this.queryRunner, ).update(subject) break case "closure-table": await new ClosureSubjectExecutor( this.queryRunner, ).update(subject) break case "materialized-path": await new MaterializedPathSubjectExecutor( this.queryRunner, ).update(subject) break } // here we execute our updation query // we need to enable entity updation because we update a subject identifier // which is not same object as our entity that's why we don't need to worry about our entity to get dirty // also, we disable listeners because we call them on our own in persistence layer const updateQueryBuilder = this.queryRunner.manager .createQueryBuilder() .update(subject.metadata.target) .set(updateMap) .updateEntity( this.options && this.options.reload === false ? false : true, ) .callListeners(false) if (subject.entity) { updateQueryBuilder.whereEntity(subject.identifier) } else { // in this case identifier is just conditions object to update by updateQueryBuilder.where(subject.identifier) } const updateResult = await updateQueryBuilder.execute() let updateGeneratedMap = updateResult.generatedMaps[0] if (updateGeneratedMap) { subject.metadata.columns.forEach((column) => { const value = column.getEntityValue(updateGeneratedMap!) if (value !== undefined && value !== null) { const preparedValue = this.queryRunner.connection.driver.prepareHydratedValue( value, column, ) column.setEntityValue( updateGeneratedMap!, preparedValue, ) } }) if (!subject.generatedMap) { subject.generatedMap = {} } Object.assign(subject.generatedMap, updateGeneratedMap) } } } // Nested sets need to be updated one by one // Split array in two, one with nested set subjects and the other with the remaining subjects const nestedSetSubjects: Subject[] = [] const remainingSubjects: Subject[] = [] for (const subject of this.updateSubjects) { if (subject.metadata.treeType === "nested-set") { nestedSetSubjects.push(subject) } else { remainingSubjects.push(subject) } } // Run nested set updates one by one const nestedSetPromise = new Promise<void>(async (ok, fail) => { for (const subject of nestedSetSubjects) { try { await updateSubject(subject) } catch (error) { fail(error) } } ok() }) // Run all remaining subjects in parallel await Promise.all([ ...remainingSubjects.map(updateSubject), nestedSetPromise, ]) } /** * Removes all given subjects from the database. * * todo: we need to apply topological sort here as well */ protected async executeRemoveOperations(): Promise<void> { // group insertion subjects to make bulk insertions const [groupedRemoveSubjects, groupedRemoveSubjectKeys] = this.groupBulkSubjects(this.removeSubjects, "delete") for (const groupName of groupedRemoveSubjectKeys) { const subjects = groupedRemoveSubjects[groupName] const deleteMaps = subjects.map((subject) => { if (!subject.identifier) throw new SubjectWithoutIdentifierError(subject) return subject.identifier }) // for mongodb we have a bit different updation logic if ( InstanceChecker.isMongoEntityManager(this.queryRunner.manager) ) { const manager = this.queryRunner.manager as MongoEntityManager await manager.delete(subjects[0].metadata.target, deleteMaps) } else { // for tree tables we execute additional queries switch (subjects[0].metadata.treeType) { case "nested-set": await new NestedSetSubjectExecutor( this.queryRunner, ).remove(subjects) break case "closure-table": await new ClosureSubjectExecutor( this.queryRunner, ).remove(subjects) break } // here we execute our deletion query // we don't need to specify entities and set update entity to true since the only thing query builder // will do for use is a primary keys deletion which is handled by us later once persistence is finished // also, we disable listeners because we call them on our own in persistence layer await this.queryRunner.manager .createQueryBuilder() .delete() .from(subjects[0].metadata.target) .where(deleteMaps) .callListeners(false) .execute() } } } private cloneMongoSubjectEntity(subject: Subject): ObjectLiteral { const target: ObjectLiteral = {} if (subject.entity) { for (const column of subject.metadata.columns) { OrmUtils.mergeDeep( target, column.getEntityValueMap(subject.entity), ) } } return target } /** * Soft-removes all given subjects in the database. */ protected async executeSoftRemoveOperations(): Promise<void> { await Promise.all( this.softRemoveSubjects.map(async (subject) => { if (!subject.identifier) throw new SubjectWithoutIdentifierError(subject) let updateResult: UpdateResult // for mongodb we have a bit different updation logic if ( InstanceChecker.isMongoEntityManager( this.queryRunner.manager, ) ) { const partialEntity = this.cloneMongoSubjectEntity(subject) if ( subject.metadata.objectIdColumn && subject.metadata.objectIdColumn.propertyName ) { delete partialEntity[ subject.metadata.objectIdColumn.propertyName ] } if ( subject.metadata.createDateColumn && subject.metadata.createDateColumn.propertyName ) { delete partialEntity[ subject.metadata.createDateColumn.propertyName ] } if ( subject.metadata.updateDateColumn && subject.metadata.updateDateColumn.propertyName ) { partialEntity[ subject.metadata.updateDateColumn.propertyName ] = new Date() } if ( subject.metadata.deleteDateColumn && subject.metadata.deleteDateColumn.propertyName ) { partialEntity[ subject.metadata.deleteDateColumn.propertyName ] = new Date() } const manager = this.queryRunner .manager as MongoEntityManager updateResult = await manager.update( subject.metadata.target, subject.identifier, partialEntity, ) } else { // here we execute our soft-deletion query // we need to enable entity soft-deletion because we update a subject identifier // which is not same object as our entity that's why we don't need to worry about our entity to get dirty // also, we disable listeners because we call them on our own in persistence layer const softDeleteQueryBuilder = this.queryRunner.manager .createQueryBuilder() .softDelete() .from(subject.metadata.target) .updateEntity( this.options && this.options.reload === false ? false : true, ) .callListeners(false) if (subject.entity) { softDeleteQueryBuilder.whereEntity(subject.identifier) } else { // in this case identifier is just conditions object to update by softDeleteQueryBuilder.where(subject.identifier) } updateResult = await softDeleteQueryBuilder.execute() } subject.generatedMap = updateResult.generatedMaps[0] if (subject.generatedMap) { subject.metadata.columns.forEach((column) => { const value = column.getEntityValue( subject.generatedMap!, ) if (value !== undefined && value !== null) { const preparedValue = this.queryRunner.connection.driver.prepareHydratedValue( value, column, ) column.setEntityValue( subject.generatedMap!, preparedValue, ) } }) } // experiments, remove probably, need to implement tree tables children removal // if (subject.updatedRelationMaps.length > 0) { // await Promise.all(subject.updatedRelationMaps.map(async updatedRelation => { // if (!updatedRelation.relation.isTreeParent) return; // if (!updatedRelation.value !== null) return; // // if (subject.metadata.treeType === "closure-table") { // await new ClosureSubjectExecutor(this.queryRunner).deleteChildrenOf(subject); // } // })); // } }), ) } /** * Recovers all given subjects in the database. */ protected async executeRecoverOperations(): Promise<void> { await Promise.all( this.recoverSubjects.map(async (subject) => { if (!subject.identifier) throw new SubjectWithoutIdentifierError(subject) let updateResult: UpdateResult // for mongodb we have a bit different updation logic if ( InstanceChecker.isMongoEntityManager( this.queryRunner.manager, ) ) { const partialEntity = this.cloneMongoSubjectEntity(subject) if ( subject.metadata.objectIdColumn && subject.metadata.objectIdColumn.propertyName ) { delete partialEntity[ subject.metadata.objectIdColumn.propertyName ] } if ( subject.metadata.createDateColumn && subject.metadata.createDateColumn.propertyName ) { delete partialEntity[ subject.metadata.createDateColumn.propertyName ] } if ( subject.metadata.updateDateColumn && subject.metadata.updateDateColumn.propertyName ) { partialEntity[ subject.metadata.updateDateColumn.propertyName ] = new Date() } if ( subject.metadata.deleteDateColumn && subject.metadata.deleteDateColumn.propertyName ) { partialEntity[ subject.metadata.deleteDateColumn.propertyName ] = null } const manager = this.queryRunner .manager as MongoEntityManager updateResult = await manager.update( subject.metadata.target, subject.identifier, partialEntity, ) } else { // here we execute our restory query // we need to enable entity restory because we update a subject identifier // which is not same object as our entity that's why we don't need to worry about our entity to get dirty // also, we disable listeners because we call them on our own in persistence layer const softDeleteQueryBuilder = this.queryRunner.manager .createQueryBuilder() .restore() .from(subject.metadata.target) .updateEntity( this.options && this.options.reload === false ? false : true, ) .callListeners(false) if (subject.entity) { softDeleteQueryBuilder.whereEntity(subject.identifier) } else { // in this case identifier is just conditions object to update by softDeleteQueryBuilder.where(subject.identifier) } updateResult = await softDeleteQueryBuilder.execute() } subject.generatedMap = updateResult.generatedMaps[0] if (subject.generatedMap) { subject.metadata.columns.forEach((column) => { const value = column.getEntityValue( subject.generatedMap!, ) if (value !== undefined && value !== null) { const preparedValue = this.queryRunner.connection.driver.prepareHydratedValue( value, column, ) column.setEntityValue( subject.generatedMap!, preparedValue, ) } }) } // experiments, remove probably, need to implement tree tables children removal // if (subject.updatedRelationMaps.length > 0) { // await Promise.all(subject.updatedRelationMaps.map(async updatedRelation => { // if (!updatedRelation.relation.isTreeParent) return; // if (!updatedRelation.value !== null) return; // // if (subject.metadata.treeType === "closure-table") { // await new ClosureSubjectExecutor(this.queryRunner).deleteChildrenOf(subject); // } // })); // } }), ) } /** * Updates all special columns of the saving entities (create date, update date, version, etc.). * Also updates nullable columns and columns with default values. */ protected updateSpecialColumnsInPersistedEntities(): void { // update inserted entity properties if (this.insertSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities( this.insertSubjects, ) // update updated entity properties if (this.updateSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities( this.updateSubjects, ) // update soft-removed entity properties if (this.softRemoveSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities( this.softRemoveSubjects, ) // update recovered entity properties if (this.recoverSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities( this.recoverSubjects, ) // remove ids from the entities that were removed if (this.removeSubjects.length) { this.removeSubjects.forEach((subject) => { if (!subject.entity) return subject.metadata.primaryColumns.forEach((primaryColumn) => { primaryColumn.setEntityValue(subject.entity!, undefined) }) }) } // other post-persist updations this.allSubjects.forEach((subject) => { if (!subject.entity) return subject.metadata.relationIds.forEach((relationId) => { relationId.setValue(subject.entity!) }) // mongo _id remove if ( InstanceChecker.isMongoEntityManager(this.queryRunner.manager) ) { if ( subject.metadata.objectIdColumn && subject.metadata.objectIdColumn.databaseName && subject.metadata.objectIdColumn.databaseName !== subject.metadata.objectIdColumn.propertyName ) { delete subject.entity[ subject.metadata.objectIdColumn.databaseName ] } } }) } /** * Updates all special columns of the saving entities (create date, update date, version, etc.). * Also updates nullable columns and columns with default values. */ protected updateSpecialColumnsInInsertedAndUpdatedEntities( subjects: Subject[], ): void { subjects.forEach((subject) => { if (!subject.entity) return // set values to "null" for nullable columns that did not have values subject.metadata.columns.forEach((column) => { // if table inheritance is used make sure this column is not child's column if ( subject.metadata.childEntityMetadatas.length > 0 && subject.metadata.childEntityMetadatas .map((metadata) => metadata.target) .indexOf(column.target) !== -1 ) return // entities does not have virtual columns if (column.isVirtual) return // if column is deletedAt if (column.isDeleteDate) return // update nullable columns if (column.isNullable) { const columnValue = column.getEntityValue(subject.entity!) if (columnValue === undefined) column.setEntityValue(subject.entity!, null) } // update relational columns if (subject.updatedRelationMaps.length > 0) { subject.updatedRelationMaps.forEach( (updatedRelationMap) => { updatedRelationMap.relation.joinColumns.forEach( (column) => { if (column.isVirtual === true) return column.setEntityValue( subject.entity!, ObjectUtils.isObject( updatedRelationMap.value, ) ? column.referencedColumn!.getEntityValue( updatedRelationMap.value, ) : updatedRelationMap.value, ) }, ) }, ) } }) // merge into entity all generated values returned by a database if (subject.generatedMap) this.queryRunner.manager.merge( subject.metadata.target as any, subject.entity, subject.generatedMap, ) }) } /** * Groups subjects by metadata names (by tables) to make bulk insertions and deletions possible. * However there are some limitations with bulk insertions of data into tables with generated (increment) columns * in some drivers. Some drivers like mysql and sqlite does not support returning multiple generated columns * after insertion and can only return a single generated column value, that's why its not possible to do bulk insertion, * because it breaks insertion result's generatedMap and leads to problems when this subject is used in other subjects saves. * That's why we only support bulking in junction tables for those drivers. * * Other drivers like postgres and sql server support RETURNING / OUTPUT statement which allows to return generated * id for each inserted row, that's why bulk insertion is not limited to junction tables in there. */ protected groupBulkSubjects( subjects: Subject[], type: "insert" | "delete", ): [{ [key: string]: Subject[] }, string[]] { const group: { [key: string]: Subject[] } = {} const keys: string[] = [] const hasReturningDependColumns = subjects.some((subject) => { return subject.metadata.getInsertionReturningColumns().length > 0 }) const groupingAllowed = type === "delete" || this.queryRunner.connection.driver.isReturningSqlSupported( "insert", ) || hasReturningDependColumns === false subjects.forEach((subject, index) => { const key = groupingAllowed || subject.metadata.isJunction ? subject.metadata.name : subject.metadata.name + "_" + index if (!group[key]) { group[key] = [subject] keys.push(key) } else { group[key].push(subject) } }) return [group, keys] } } ```
/content/code_sandbox/src/persistence/SubjectExecutor.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
7,646
```xml /* eslint-env jest */ import { nextTestSetup } from 'e2e-utils' import { check } from 'next-test-utils' describe('Deprecated @next/font warning', () => { const { next, skipped } = nextTestSetup({ files: { 'pages/index.js': '', }, dependencies: { '@next/font': 'canary', }, skipStart: true, }) if (skipped) return it('should warn if @next/font is in deps', async () => { await next.start() await check(() => next.cliOutput, /ready/i) await check( () => next.cliOutput, new RegExp('please use the built-in `next/font` instead') ) await next.stop() await next.clean() }) it('should not warn if @next/font is not in deps', async () => { // Remove @next/font from deps const packageJson = JSON.parse(await next.readFile('package.json')) delete packageJson.dependencies['@next/font'] await next.patchFile('package.json', JSON.stringify(packageJson)) await next.start() await check(() => next.cliOutput, /ready/i) expect(next.cliOutput).not.toInclude( 'please use the built-in `next/font` instead' ) await next.stop() await next.clean() }) }) ```
/content/code_sandbox/test/development/next-font/deprecated-package.test.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
293
```xml /* * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. */ import styled, {css} from 'styled-components'; import {Tile as BaseTitle} from '@carbon/react'; import {styles} from '@carbon/elements'; import {Link} from 'modules/components/Link'; import {ErrorMessage as BaseErrorMessage} from 'modules/components/ErrorMessage'; type GridProps = { $numberOfColumns: 1 | 2; }; const Grid = styled.div<GridProps>` ${({$numberOfColumns}) => { return css` width: 100%; height: 100%; padding: var(--cds-spacing-05); display: grid; grid-template-rows: 158px 1fr; grid-gap: var(--cds-spacing-05); ${$numberOfColumns === 2 ? css` grid-template-columns: 1fr 1fr; & > ${Tile}:first-of-type { grid-column-start: 1; grid-column-end: 3; } ` : css` grid-template-columns: 1fr; `} `; }} `; const ScrollableContent = styled.div` overflow-y: auto; display: flex; flex-direction: column; flex: 1; `; const Tile = styled(BaseTitle)` display: flex; flex-direction: column; border: 1px solid var(--cds-border-subtle-01); `; const TileTitle = styled.h2` ${styles.productiveHeading02}; color: var(--cds-text-primary); margin-bottom: var(--cds-spacing-06); `; const LinkWrapper = styled(Link)` display: block; text-decoration: none !important; padding: var(--cds-spacing-03) 0; `; const ErrorMessage = styled(BaseErrorMessage)` margin: auto; `; const Li = styled.li` // override the hover color on expandable row's children &:hover { background-color: var(--cds-layer-hover); } `; export { Grid, ScrollableContent, Tile, TileTitle, LinkWrapper, ErrorMessage, Li, }; ```
/content/code_sandbox/operate/client/src/App/Dashboard/styled.ts
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
472
```xml // A mock function to mimic making an async request for data export const fetchCount = async (amount = 1) => { const response = await fetch("path_to_url", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ amount }), }); const result: { data: number } = await response.json(); return result; }; ```
/content/code_sandbox/examples/with-redux/lib/features/counter/counterAPI.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
88
```xml <?xml version="1.0" encoding="utf-8"?> <!-- /* ** ** ** ** path_to_url ** ** Unless required by applicable law or agreed to in writing, software ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ --> <resources> <!-- key_height + key_bottom_gap = popup_key_height --> <dimen name="key_height">0.290in</dimen> <dimen name="key_bottom_gap">0.000in</dimen> <dimen name="key_horizontal_pad">0.000in</dimen> <dimen name="key_vertical_pad">0.025in</dimen> <dimen name="key_vertical_pad_compact">0.000in</dimen> <dimen name="popup_key_height">0.325in</dimen> <dimen name="keyboard_bottom_padding">0.06in</dimen> <dimen name="bubble_pointer_offset">22dip</dimen> <dimen name="candidate_strip_height">42dip</dimen> <dimen name="candidate_strip_fading_edge_length">63dip</dimen> <dimen name="spacebar_vertical_correction">4dip</dimen> <!-- If the screen height in landscape is larger than the below value, then the keyboard will not go into extract (fullscreen) mode. --> <dimen name="max_height_for_fullscreen">2.5in</dimen> <!-- Key size for 5-row mode. Scaled up by 1.25 for 4-row mode. --> <dimen name="key_text_size">0.11in</dimen> <dimen name="key_label_text_size">0.083in</dimen> <dimen name="key_preview_text_size_large">40sp</dimen> <dimen name="key_preview_offset">0.000in</dimen> <!-- key_preview_text_size_large x 2 --> <dimen name="key_preview_height">80sp</dimen> <!-- Amount of allowance for selecting keys in a mini popup keyboard by sliding finger. --> <!-- popup_key_height x 1.7 --> <dimen name="mini_keyboard_slide_allowance">0.553in</dimen> <!-- popup_key_height x 1.0 --> <dimen name="mini_keyboard_vertical_correction">-0.325in</dimen> <dimen name="key_hysteresis_distance">0.05in</dimen> <!-- We use "inch", not "dip" because this value tries dealing with physical distance related to user's finger. --> <dimen name="keyboard_vertical_correction">-0.05in</dimen> <dimen name="candidate_min_touchable_width">0.3in</dimen> </resources> ```
/content/code_sandbox/app/src/main/res/values/dimens.xml
xml
2016-01-22T21:40:54
2024-08-16T11:54:30
hackerskeyboard
klausw/hackerskeyboard
1,807
623
```xml import sinon from "sinon"; import { ERROR_CODES } from "coral-common/common/lib/errors"; import { pureMerge } from "coral-common/common/lib/utils"; import { InvalidRequestError } from "coral-framework/lib/errors"; import { GQLResolver } from "coral-framework/schema"; import { act, createResolversStub, CreateTestRendererParams, replaceHistoryLocation, wait, waitForElement, within, } from "coral-framework/testHelpers"; import create from "../create"; import { settings, users } from "../fixtures"; const viewer = users.admins[0]; async function createTestRenderer( params: CreateTestRendererParams<GQLResolver> = {} ) { replaceHistoryLocation("path_to_url"); const { testRenderer, context } = create({ ...params, resolvers: pureMerge( createResolversStub<GQLResolver>({ Query: { settings: () => settings, viewer: () => pureMerge<typeof viewer>(viewer, { email: "", }), }, }), params.resolvers ), initLocalState: (localRecord, source, environment) => { localRecord.setValue("ADD_EMAIL_ADDRESS", "authView"); if (params.initLocalState) { params.initLocalState(localRecord, source, environment); } }, }); return await act(async () => { const container = await waitForElement(() => within(testRenderer.root).getByTestID("completeAccountBox") ); const form = within(container).getByType("form"); const emailAddressField = within(form).getByLabelText("Email Address"); const confirmEmailAddressField = within(form).getByLabelText( "Confirm Email Address" ); return { context, testRenderer, form, root: testRenderer.root, emailAddressField, confirmEmailAddressField, container, }; }); } it("shows server error", async () => { const email = "hans@test.com"; const resolvers = createResolversStub<GQLResolver>({ Mutation: { setEmail: () => { throw new Error("server error"); }, }, }); const { form, emailAddressField, confirmEmailAddressField } = await createTestRenderer({ resolvers, muteNetworkErrors: true, }); const submitButton = form.find( (i) => i.type === "button" && i.props.type === "submit" ); act(() => emailAddressField.props.onChange({ target: { value: email } })); act(() => confirmEmailAddressField.props.onChange({ target: { value: email }, }) ); act(() => { form.props.onSubmit(); }); expect(emailAddressField.props.disabled).toBe(true); expect(confirmEmailAddressField.props.disabled).toBe(true); expect(submitButton.props.disabled).toBe(true); await act(async () => { await wait(() => { expect(submitButton.props.disabled).toBe(false); }); }); }); it("successfully sets email", async () => { const email = "hans@test.com"; const resolvers = createResolversStub<GQLResolver>({ Mutation: { setEmail: ({ variables }) => { expectAndFail(variables).toEqual({ email, }); return { user: { id: "me", email, }, }; }, }, }); const { form, emailAddressField, confirmEmailAddressField } = await createTestRenderer({ resolvers, }); const submitButton = form.find( (i) => i.type === "button" && i.props.type === "submit" ); act(() => emailAddressField.props.onChange({ target: { value: email } })); act(() => confirmEmailAddressField.props.onChange({ target: { value: email }, }) ); act(() => { form.props.onSubmit(); }); expect(emailAddressField.props.disabled).toBe(true); expect(confirmEmailAddressField.props.disabled).toBe(true); expect(submitButton.props.disabled).toBe(true); await act(async () => { await wait(() => { expect(submitButton.props.disabled).toBe(false); }); }); expect(resolvers.Mutation!.setEmail!.called).toBe(true); }); it("switch to link account", async () => { const email = "hans@test.com"; const setEmail = sinon.stub().callsFake((_: any, data: any) => { throw new InvalidRequestError({ code: ERROR_CODES.DUPLICATE_EMAIL, traceID: "traceID", }); }); const { testRenderer, form, emailAddressField, confirmEmailAddressField } = await createTestRenderer({ resolvers: { Mutation: { setEmail, }, }, muteNetworkErrors: true, }); const submitButton = form.find( (i) => i.type === "button" && i.props.type === "submit" ); act(() => emailAddressField.props.onChange({ target: { value: email } })); act(() => confirmEmailAddressField.props.onChange({ target: { value: email }, }) ); act(() => { form.props.onSubmit(); }); expect(emailAddressField.props.disabled).toBe(true); expect(confirmEmailAddressField.props.disabled).toBe(true); expect(submitButton.props.disabled).toBe(true); await act(async () => { await waitForElement(() => within(testRenderer.root).getByTestID("linkAccount-container") ); }); }); ```
/content/code_sandbox/client/src/core/client/admin/test/auth/addEmailAddress.spec.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
1,170
```xml import * as React from 'react'; import { Toolbar, Input } from '@fluentui/react-northstar'; import { MoreIcon, ItalicIcon, SearchIcon } from '@fluentui/react-icons-northstar'; const ToolbarExamplePopupInMenu = () => { const [menu1Open, setMenu1Open] = React.useState(false); const [menu2Open, setMenu2Open] = React.useState(false); return ( <Toolbar aria-label="Popup in menu" items={[ { icon: <MoreIcon />, key: 'menu1', active: menu1Open, title: 'More', menu: [ { key: 'popup', content: 'Open Popup', popup: <Input icon={<SearchIcon />} placeholder="Search..." />, }, ], menuOpen: menu1Open, onMenuOpenChange: (e, { menuOpen }) => { setMenu1Open(menuOpen); }, }, { icon: <ItalicIcon {...{ outline: true }} />, key: 'italic', kind: 'toggle', title: 'Italic', }, { icon: <MoreIcon />, key: 'menu2', active: menu2Open, title: 'More', menu: [ { key: 'popup', content: 'Open Popup', popup: <Input icon={<SearchIcon />} placeholder="Search..." />, }, { key: 'about', content: 'About...' }, ], menuOpen: menu2Open, onMenuOpenChange: (e, { menuOpen }) => { setMenu2Open(menuOpen); }, }, ]} /> ); }; export default ToolbarExamplePopupInMenu; ```
/content/code_sandbox/packages/fluentui/docs/src/examples/components/Toolbar/Usage/ToolbarExamplePopupInMenu.shorthand.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
377
```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <groupId>com.journaldev.spring</groupId> <artifactId>SpringDataSource</artifactId> <name>SpringDataSource</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.6</java-version> <org.springframework-version>4.0.2.RELEASE</org.springframework-version> <org.aspectj-version>1.7.4</org.aspectj-version> <org.slf4j-version>1.7.5</org.slf4j-version> <jackson.databind-version>2.2.3</jackson.databind-version> </properties> <dependencies> <!-- Spring JDBC Support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> <!-- Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.databind-version}</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project> ```
/content/code_sandbox/Spring/SpringDataSource/pom.xml
xml
2016-05-02T05:43:21
2024-08-16T06:51:39
journaldev
WebJournal/journaldev
1,314
1,540
```xml <test> <create_query>CREATE VIEW numbers_view AS SELECT number from numbers_mt(100000000) order by number desc</create_query> <!-- This must have been an EXPLAIN test. --> <query>select number from (select number from numbers(500000000) order by -number) limit 10</query> <query>select number from (select number from numbers_mt(1500000000) order by -number) limit 10</query> <query short="1">select number from numbers_view limit 100</query> </test> ```
/content/code_sandbox/tests/performance/push_down_limit.xml
xml
2016-06-02T08:28:18
2024-08-16T18:39:33
ClickHouse
ClickHouse/ClickHouse
36,234
123
```xml import { c } from 'ttag'; import type { IconName } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { toMap } from '@proton/shared/lib/helpers/object'; import type { MailSettings } from '@proton/shared/lib/interfaces'; import type { Folder } from '@proton/shared/lib/interfaces/Folder'; import type { Label } from '@proton/shared/lib/interfaces/Label'; import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import { LABELS_AUTO_READ, LABELS_UNMODIFIABLE_BY_USER, LABEL_IDS_TO_HUMAN } from '../constants'; import type { Conversation } from '../models/conversation'; import type { Element } from '../models/element'; import type { MessageWithOptionalBody } from '../store/messages/messagesTypes'; import { getLabelIDs } from './elements'; const { INBOX, TRASH, SPAM, ARCHIVE, SENT, DRAFTS, ALL_SENT, ALL_DRAFTS, SCHEDULED, OUTBOX, STARRED, ALL_MAIL, SNOOZED, ALMOST_ALL_MAIL, } = MAILBOX_LABEL_IDS; const DEFAULT_FOLDERS = [INBOX, TRASH, SPAM, ARCHIVE, SENT, DRAFTS, SCHEDULED, OUTBOX]; export type LabelChanges = { [labelID: string]: boolean }; export interface FolderInfo { icon: IconName; name: string; to: string; color?: string; parentID?: string | number; } interface FolderMap { [id: string]: FolderInfo; } const alwaysMessageLabels = [DRAFTS, ALL_DRAFTS, SENT, ALL_SENT]; const SYSTEM_LABELS = [STARRED, SNOOZED, ALL_MAIL, ALMOST_ALL_MAIL, SCHEDULED, ALL_SENT, ALL_DRAFTS, OUTBOX, INBOX]; export const isSystemLabel = (labelID: string) => SYSTEM_LABELS.includes(labelID as MAILBOX_LABEL_IDS); export const getHumanLabelID = (labelID: string) => LABEL_IDS_TO_HUMAN[labelID as MAILBOX_LABEL_IDS] || labelID; export const isCustomLabelOrFolder = (labelID: string) => !Object.values(MAILBOX_LABEL_IDS).includes(labelID as MAILBOX_LABEL_IDS); export const isAlwaysMessageLabels = (labelID: string) => alwaysMessageLabels.includes(labelID as MAILBOX_LABEL_IDS); export const labelIncludes = (labelID: string, ...labels: (MAILBOX_LABEL_IDS | string)[]) => labels.includes(labelID as MAILBOX_LABEL_IDS); export const isCustomLabel = (labelID: string, labels: Label[] = []) => labels.some((label) => label.ID === labelID); export const isLabel = (labelID: string, labels: Label[] = []) => labelIncludes(labelID, STARRED) || isCustomLabel(labelID, labels); export const isCustomFolder = (labelID: string, folders: Folder[] = []) => folders.some((folder) => folder.ID === labelID); export const getStandardFolders = (): FolderMap => ({ [INBOX]: { icon: 'inbox', name: c('Link').t`Inbox`, to: '/inbox', }, [TRASH]: { icon: 'trash', name: c('Link').t`Trash`, to: '/trash', }, [SPAM]: { icon: 'fire', name: c('Link').t`Spam`, to: '/spam', }, [ARCHIVE]: { icon: 'archive-box', name: c('Link').t`Archive`, to: '/archive', }, [SENT]: { icon: 'paper-plane', name: c('Link').t`Sent`, to: `/${LABEL_IDS_TO_HUMAN[SENT]}`, }, [ALL_SENT]: { icon: 'paper-plane', name: c('Link').t`Sent`, to: `/${LABEL_IDS_TO_HUMAN[ALL_SENT]}`, }, [DRAFTS]: { icon: 'file-lines', name: c('Link').t`Drafts`, to: `/${LABEL_IDS_TO_HUMAN[DRAFTS]}`, }, [ALL_DRAFTS]: { icon: 'file-lines', name: c('Link').t`Drafts`, to: `/${LABEL_IDS_TO_HUMAN[ALL_DRAFTS]}`, }, [SCHEDULED]: { icon: 'paper-plane-clock', name: c('Link').t`Scheduled`, to: `/${LABEL_IDS_TO_HUMAN[SCHEDULED]}`, }, [STARRED]: { icon: 'star', name: c('Link').t`Starred`, to: `/${LABEL_IDS_TO_HUMAN[STARRED]}`, }, [SNOOZED]: { icon: 'clock', name: c('Link').t`Snooze`, to: `/${LABEL_IDS_TO_HUMAN[SNOOZED]}`, }, [ALL_MAIL]: { icon: 'envelopes', name: c('Link').t`All mail`, to: `/${LABEL_IDS_TO_HUMAN[ALL_MAIL]}`, }, [ALMOST_ALL_MAIL]: { icon: 'envelopes', name: c('Link').t`All mail`, to: `/${LABEL_IDS_TO_HUMAN[ALMOST_ALL_MAIL]}`, }, // [OUTBOX]: { // icon: 'inbox-out', // name: c('Mailbox').t`Outbox`, // to: `/${LABEL_IDS_TO_HUMAN[OUTBOX]}`, // }, }); export const getLabelName = (labelID: string, labels: Label[] = [], folders: Folder[] = []): string => { if (labelID in LABEL_IDS_TO_HUMAN) { const folders = getStandardFolders(); return folders[labelID].name; } const labelsMap = toMap(labels, 'ID'); if (labelID in labelsMap) { return labelsMap[labelID]?.Name || labelID; } const foldersMap = toMap(folders, 'ID'); if (labelID in foldersMap) { return foldersMap[labelID]?.Name || labelID; } return labelID; }; export const getLabelNames = (changes: string[], labels: Label[], folders: Folder[]) => { if (!changes || changes.length === 0) { return; } return changes.map((ID) => getLabelName(ID, labels, folders)); }; export const getCurrentFolders = ( element: Element | undefined, labelID: string, customFoldersList: Folder[], mailSettings: MailSettings ): FolderInfo[] => { const { ShowMoved } = mailSettings; const labelIDs = Object.keys(getLabelIDs(element, labelID)); const standardFolders = getStandardFolders(); const customFolders = toMap(customFoldersList, 'ID'); return labelIDs .filter((labelID) => { if ([SENT, ALL_SENT].includes(labelID as MAILBOX_LABEL_IDS)) { return (hasBit(ShowMoved, SHOW_MOVED.SENT) ? ALL_SENT : SENT) === labelID; } if ([DRAFTS, ALL_DRAFTS].includes(labelID as MAILBOX_LABEL_IDS)) { return (hasBit(ShowMoved, SHOW_MOVED.DRAFTS) ? ALL_DRAFTS : DRAFTS) === labelID; } // We don't want to show the All mail folder in the details if ([ALL_MAIL, ALMOST_ALL_MAIL].includes(labelID as MAILBOX_LABEL_IDS)) { return false; } // We don't wait to show both the starred and empty start folder if (labelID === STARRED) { return false; } return true; }) .filter((labelID) => standardFolders[labelID] || customFolders[labelID]) .map((labelID) => { if (standardFolders[labelID]) { return standardFolders[labelID]; } const folder = customFolders[labelID]; return { icon: 'folder', name: folder?.Name, to: `/${folder?.ID}`, color: folder?.Color, parentID: folder?.ParentID, }; }); }; export const getCurrentFolderID = (labelIDs: string[] = [], customFoldersList: Folder[] = []): string => { const allFolderIDs = [...DEFAULT_FOLDERS, ...customFoldersList.map(({ ID }) => ID)]; return labelIDs.find((labeID) => allFolderIDs.includes(labeID)) || ''; }; export const getFolderName = (labelID: string, customFoldersList: Folder[] = []): string => { const standardFolders = getStandardFolders(); if (standardFolders[labelID]) { return standardFolders[labelID].name; } const { Name = '' } = customFoldersList.find(({ ID }) => ID === labelID) || {}; return Name; }; export const isAutoRead = (labelID: MAILBOX_LABEL_IDS | string) => LABELS_AUTO_READ.includes(labelID as MAILBOX_LABEL_IDS); export const isUnmodifiableByUser = (labelID: MAILBOX_LABEL_IDS | string) => LABELS_UNMODIFIABLE_BY_USER.includes(labelID as MAILBOX_LABEL_IDS); export interface UnreadStatus { id: string; unread: number; } export const applyLabelChangesOnMessage = <T>( message: MessageWithOptionalBody & T, changes: LabelChanges, unreadStatuses?: UnreadStatus[] ): MessageWithOptionalBody & T => { const { LabelIDs: inputLabelIDs } = message; const LabelIDs = [...inputLabelIDs]; Object.keys(changes).forEach((labelID) => { const index = LabelIDs.findIndex((existingLabelID) => existingLabelID === labelID); if (changes[labelID]) { if (index === -1) { LabelIDs.push(labelID); } } else if (index >= 0) { LabelIDs.splice(index, 1); } }); if (unreadStatuses) { const elementUnreadStatus = unreadStatuses.find((element) => element.id === message.ID)?.unread; if (elementUnreadStatus) { return { ...message, LabelIDs, Unread: elementUnreadStatus }; } } return { ...message, LabelIDs }; }; export const applyLabelChangesOnConversation = ( conversation: Conversation, changes: LabelChanges, unreadStatuses?: UnreadStatus[] ): Conversation => { let Time = conversation.Time; const Labels = [...(conversation.Labels || [])]; Object.keys(changes).forEach((labelID) => { const index = Labels.findIndex((existingLabel) => existingLabel.ID === labelID); if (changes[labelID]) { if (index === -1) { Labels.push({ ID: labelID, ContextNumMessages: conversation.NumMessages || 1, }); } else { Labels[index] = { ...Labels[index], ContextNumMessages: conversation.NumMessages || 1, }; } } else if (index >= 0) { // When the conversation has been received through the event manager it will not have a Time field // By removing the label, we are losing the context time associated // If we rollback that change, both label time and fallback on conversation will be missing // By filling the conversation time at label removal, we ensure there will be a time on rollback if (Time === undefined) { Time = Labels[index].ContextTime; } Labels.splice(index, 1); } }); if (unreadStatuses) { const elementUnreadStatus = unreadStatuses.find((element) => element.id === conversation.ID)?.unread; if (elementUnreadStatus) { return { ...conversation, Time, Labels, NumUnread: elementUnreadStatus }; } } return { ...conversation, Time, Labels }; }; export const applyLabelChangesOnOneMessageOfAConversation = ( conversation: Conversation, changes: LabelChanges ): { updatedConversation: Conversation; conversationChanges: LabelChanges } => { let Time = conversation.Time; const Labels = [...(conversation.Labels || [])]; const conversationChanges: LabelChanges = {}; Object.keys(changes).forEach((labelID) => { const index = Labels.findIndex((existingLabel) => existingLabel.ID === labelID); const hasLabel = index >= 0; const numMessages = Labels?.[index]?.ContextNumMessages || 0; if (changes[labelID]) { if (hasLabel) { Labels[index] = { ...Labels[index], ContextNumMessages: numMessages + 1 }; } else { Labels.push({ ID: labelID, ContextNumMessages: 1 }); conversationChanges[labelID] = true; } } else if (hasLabel) { if (numMessages <= 1) { // When the conversation has been received through the event manager it will not have a Time field // By removing the label, we are losing the context time associated // If we rollback that change, both label time and fallback on conversation will be missing // By filling the conversation time at label removal, we ensure there will be a time on rollback if (Time === undefined) { Time = Labels[index].ContextTime; } Labels.splice(index, 1); conversationChanges[labelID] = false; } else { Labels[index] = { ...Labels[index], ContextNumMessages: numMessages - 1 }; } } }); return { updatedConversation: { ...conversation, Time, Labels }, conversationChanges }; }; // For some locations, we want to display the total number of messages instead of the number of unreads (e.g. Scheduled folder) export const shouldDisplayTotal = (labelID: string) => { const needsDisplayTotalLabels = [SCHEDULED, SNOOZED]; return needsDisplayTotalLabels.includes(labelID as MAILBOX_LABEL_IDS); }; export const canMoveAll = ( currentLabelID: string, targetLabelID: string, elementIDs: string[], selectedIDs: string[], isSearch: boolean ) => { // We also need to hide move all actions in ALL_DRAFTS and ALL_SENT location because the goal of this setting // is to keep the message in DRAFTS and SENT locations all the time. return ( !labelIncludes(currentLabelID, targetLabelID, ALL_MAIL, SCHEDULED, ALL_DRAFTS, ALL_SENT) && elementIDs.length > 0 && selectedIDs.length === 0 && !isSearch ); }; export const getSortedChanges = (changes: { [labelID: string]: boolean; }): { toLabel: string[]; toUnlabel: string[] } => { return Object.keys(changes).reduce<{ toLabel: string[]; toUnlabel: string[] }>( (acc, labelID) => { if (changes[labelID]) { acc.toLabel.push(labelID); } else { acc.toUnlabel.push(labelID); } return acc; }, { toLabel: [], toUnlabel: [] } ); }; ```
/content/code_sandbox/applications/mail/src/app/helpers/labels.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
3,340
```xml import type { ReactNode } from 'react'; import { type KeyboardEvent, useRef } from 'react'; import { FieldArray, type FormikContextType, type FormikErrors } from 'formik'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, InputFieldTwo } from '@proton/components/'; import { maybeErrorMessage } from '@proton/pass/hooks/useFieldControl'; import type { UrlGroupValues, UrlItem } from '@proton/pass/types'; import { isEmptyString } from '@proton/pass/utils/string/is-empty-string'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import { isValidURL } from '@proton/pass/utils/url/is-valid-url'; import { FieldBox } from './Layout/FieldBox'; export type UrlGroupProps<V extends UrlGroupValues = UrlGroupValues> = { form: FormikContextType<V>; renderExtraActions?: (helpers: { handleRemove: (idx: number) => () => void; handleAdd: (url: string) => void; handleReplace: (idx: number) => (url: string) => void; }) => ReactNode; }; export const createNewUrl = (url: string) => ({ id: uniqueId(), url: isValidURL(url).valid ? url : '' }); export const UrlGroupField = <T extends UrlGroupValues>({ form, renderExtraActions }: UrlGroupProps<T>) => { const inputRef = useRef<HTMLInputElement>(null); const { values, errors, handleChange } = form; const onKeyEnter = (event: KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { event.preventDefault(); /* avoid submitting the form */ event.currentTarget.blur(); } }; const hasURL = Boolean(values.url) || values.urls.some(({ url }) => !isEmptyString(url)); return ( <FieldBox icon="earth"> <label htmlFor="next-url-field" className="field-two-label text-sm" style={{ color: hasURL ? 'var(--text-weak)' : 'inherit' }} > {c('Label').t`Websites`} </label> <FieldArray name="urls" render={(helpers) => { const handleRemove = helpers.handleRemove; const handleReplace = (index: number) => (url: string) => helpers.replace(index, { id: values.urls[index].id, url }); const handleAdd = (url: string) => { helpers.push(createNewUrl(isValidURL(url).url)); return form.setFieldValue('url', ''); }; return ( <> <ul className="unstyled m-0 mb-1"> {values.urls.map(({ url, id }, index) => ( <li key={id} className="flex items-center flex-nowrap"> <InputFieldTwo error={(errors.urls?.[index] as FormikErrors<UrlItem>)?.url} onValue={handleReplace(index)} onBlur={() => handleReplace(index)(isValidURL(url).url)} value={url} unstyled assistContainerClassName="empty:hidden" inputClassName="color-norm p-0 rounded-none" placeholder="https://" onKeyDown={onKeyEnter} /> <Button icon pill className="shrink-0 ml-2" color="weak" onClick={handleRemove(index)} shape="ghost" size="small" title={c('Action').t`Delete`} > <Icon name="cross" size={5} className="color-weak" /> </Button> </li> ))} </ul> <InputFieldTwo unstyled id="next-url-field" assistContainerClassName="empty:hidden" inputClassName="color-norm p-0 rounded-none" placeholder="https://" name="url" value={values.url} error={maybeErrorMessage(errors.url)} onChange={handleChange} onBlur={() => values.url && !errors.url && handleAdd(values.url)} onKeyDown={onKeyEnter} ref={inputRef} /> <hr className="mt-3 mb-1" /> {renderExtraActions?.({ handleAdd, handleRemove, handleReplace })} <Button icon color="norm" shape="ghost" size="small" title={c('Action').t`Add`} className="flex items-center gap-1" onClick={() => handleAdd(values.url).then(() => inputRef.current?.focus())} > <Icon name="plus" /> {c('Action').t`Add`} </Button> </> ); }} /> </FieldBox> ); }; ```
/content/code_sandbox/packages/pass/components/Form/Field/UrlGroupField.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
1,022
```xml export interface EncryptPartResult { dataPacket: Uint8Array; signature: string; } export interface SignPartResult { data: string; signature: string; } ```
/content/code_sandbox/packages/shared/lib/interfaces/calendar/PartResult.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
38
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>SchemeUserState</key> <dict> <key>SlideMenu.xcscheme</key> <dict> <key>orderHint</key> <integer>0</integer> </dict> </dict> <key>SuppressBuildableAutocreation</key> <dict> <key>F4C1CF011A84F64E00728CAD</key> <dict> <key>primary</key> <true/> </dict> <key>F4C1CF161A84F64E00728CAD</key> <dict> <key>primary</key> <true/> </dict> </dict> </dict> </plist> ```
/content/code_sandbox/Project 16 - SlideMenu/SlideMenu.xcodeproj/xcuserdata/Allen.xcuserdatad/xcschemes/xcschememanagement.plist
xml
2016-02-13T14:02:12
2024-08-16T09:41:59
30DaysofSwift
allenwong/30DaysofSwift
11,506
225
```xml /** * @license * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ import "#src/widget/render_scale_widget.css"; import { debounce, throttle } from "lodash-es"; import type { UserLayer } from "#src/layer/index.js"; import type { RenderScaleHistogram } from "#src/render_scale_statistics.js"; import { getRenderScaleFromHistogramOffset, getRenderScaleHistogramOffset, numRenderScaleHistogramBins, renderScaleHistogramBinSize, renderScaleHistogramOrigin, } from "#src/render_scale_statistics.js"; import type { TrackableValueInterface } from "#src/trackable_value.js"; import { WatchableValue } from "#src/trackable_value.js"; import { serializeColor } from "#src/util/color.js"; import { hsvToRgb } from "#src/util/colorspace.js"; import { RefCounted } from "#src/util/disposable.js"; import type { ActionEvent } from "#src/util/event_action_map.js"; import { EventActionMap, registerActionListener, } from "#src/util/event_action_map.js"; import { vec3 } from "#src/util/geom.js"; import { clampToInterval } from "#src/util/lerp.js"; import { MouseEventBinder } from "#src/util/mouse_bindings.js"; import { numberToStringFixed } from "#src/util/number_to_string.js"; import { formatScaleWithUnitAsString } from "#src/util/si_units.js"; import type { LayerControlFactory } from "#src/widget/layer_control.js"; const updateInterval = 200; const inputEventMap = EventActionMap.fromObject({ mousedown0: { action: "set" }, wheel: { action: "adjust-via-wheel" }, dblclick0: { action: "reset" }, }); function formatPixelNumber(x: number) { if (x < 1 || x > 1024) { const exponent = Math.log2(x) | 0; const coeff = x / 2 ** exponent; return `${numberToStringFixed(coeff, 1)}p${exponent}`; } return Math.round(x) + ""; } export interface RenderScaleWidgetOptions { histogram: RenderScaleHistogram; target: TrackableValueInterface<number>; } export class RenderScaleWidget extends RefCounted { label = document.createElement("div"); element = document.createElement("div"); canvas = document.createElement("canvas"); legend = document.createElement("div"); legendRenderScale = document.createElement("div"); legendSpatialScale = document.createElement("div"); legendChunks = document.createElement("div"); protected logScaleOrigin = renderScaleHistogramOrigin; protected unitOfTarget = "px"; private ctx = this.canvas.getContext("2d")!; hoverTarget = new WatchableValue<[number, number] | undefined>(undefined); private throttledUpdateView = this.registerCancellable( throttle(() => this.debouncedUpdateView(), updateInterval, { leading: true, trailing: true, }), ); private debouncedUpdateView = this.registerCancellable( debounce(() => this.updateView(), 0), ); adjustViaWheel(event: WheelEvent) { const deltaY = this.getWheelMoveValue(event); if (deltaY === 0) { return; } this.hoverTarget.value = undefined; const logScaleMax = Math.round( this.logScaleOrigin + numRenderScaleHistogramBins * renderScaleHistogramBinSize, ); const targetValue = clampToInterval( [2 ** this.logScaleOrigin, 2 ** (logScaleMax - 1)], this.target.value * 2 ** Math.sign(deltaY), ) as number; this.target.value = targetValue; event.preventDefault(); } constructor( public histogram: RenderScaleHistogram, public target: TrackableValueInterface<number>, ) { super(); const { canvas, label, element, legend, legendRenderScale, legendSpatialScale, legendChunks, } = this; label.className = "neuroglancer-render-scale-widget-prompt"; element.className = "neuroglancer-render-scale-widget"; element.title = inputEventMap.describe(); legend.className = "neuroglancer-render-scale-widget-legend"; element.appendChild(label); element.appendChild(canvas); element.appendChild(legend); legendRenderScale.title = "Target resolution of data in screen pixels"; legendChunks.title = "Number of chunks rendered"; legend.appendChild(legendRenderScale); legend.appendChild(legendChunks); legend.appendChild(legendSpatialScale); this.registerDisposer(histogram.changed.add(this.throttledUpdateView)); this.registerDisposer( histogram.visibility.changed.add(this.debouncedUpdateView), ); this.registerDisposer(target.changed.add(this.debouncedUpdateView)); this.registerDisposer(new MouseEventBinder(canvas, inputEventMap)); this.registerDisposer(target.changed.add(this.debouncedUpdateView)); this.registerDisposer( this.hoverTarget.changed.add(this.debouncedUpdateView), ); const getTargetValue = (event: MouseEvent) => { const position = (event.offsetX / canvas.width) * numRenderScaleHistogramBins; return getRenderScaleFromHistogramOffset(position, this.logScaleOrigin); }; this.registerEventListener(canvas, "pointermove", (event: MouseEvent) => { this.hoverTarget.value = [getTargetValue(event), event.offsetY]; }); this.registerEventListener(canvas, "pointerleave", () => { this.hoverTarget.value = undefined; }); this.registerDisposer( registerActionListener<MouseEvent>(canvas, "set", (actionEvent) => { this.target.value = getTargetValue(actionEvent.detail); }), ); this.registerDisposer( registerActionListener<WheelEvent>( canvas, "adjust-via-wheel", (actionEvent) => { this.adjustViaWheel(actionEvent.detail); }, ), ); this.registerDisposer( registerActionListener(canvas, "reset", (event) => { this.reset(); event.preventDefault(); }), ); const resizeObserver = new ResizeObserver(() => this.debouncedUpdateView()); resizeObserver.observe(canvas); this.registerDisposer(() => resizeObserver.disconnect()); this.updateView(); } getWheelMoveValue(event: WheelEvent) { return event.deltaY; } reset() { this.hoverTarget.value = undefined; this.target.reset(); } updateView() { const { ctx } = this; const { canvas } = this; const width = (canvas.width = canvas.offsetWidth); const height = (canvas.height = canvas.offsetHeight); const targetValue = this.target.value; const hoverValue = this.hoverTarget.value; { const { legendRenderScale } = this; const value = hoverValue === undefined ? targetValue : hoverValue[0]; const valueString = formatPixelNumber(value); legendRenderScale.textContent = valueString + " " + this.unitOfTarget; } function binToCanvasX(bin: number) { return (bin * width) / numRenderScaleHistogramBins; } ctx.clearRect(0, 0, width, height); const { histogram } = this; // histogram.begin(this.frameNumberCounter.frameNumber); const { value: histogramData, spatialScales } = histogram; if (!histogram.visibility.visible) { histogramData.fill(0); } const sortedSpatialScales = Array.from(spatialScales.keys()); sortedSpatialScales.sort(); const tempColor = vec3.create(); let maxCount = 1; const numRows = spatialScales.size; let totalPresent = 0; let totalNotPresent = 0; for (let bin = 0; bin < numRenderScaleHistogramBins; ++bin) { let count = 0; for (let row = 0; row < numRows; ++row) { const index = row * numRenderScaleHistogramBins * 2 + bin; const presentCount = histogramData[index]; const notPresentCount = histogramData[index + numRenderScaleHistogramBins]; totalPresent += presentCount; totalNotPresent += notPresentCount; count += presentCount + notPresentCount; } maxCount = Math.max(count, maxCount); } totalNotPresent -= histogram.fakeChunkCount; const maxBarHeight = height; const yScale = maxBarHeight / Math.log(1 + maxCount); function countToCanvasY(count: number) { return height - Math.log(1 + count) * yScale; } let hoverSpatialScale: number | undefined = undefined; if (hoverValue !== undefined) { const i = Math.floor( getRenderScaleHistogramOffset(hoverValue[0], this.logScaleOrigin), ); if (i >= 0 && i < numRenderScaleHistogramBins) { let sum = 0; const hoverY = hoverValue[1]; for ( let spatialScaleIndex = numRows - 1; spatialScaleIndex >= 0; --spatialScaleIndex ) { const spatialScale = sortedSpatialScales[spatialScaleIndex]; const row = spatialScales.get(spatialScale)!; const index = 2 * row * numRenderScaleHistogramBins + i; const count = histogramData[index] + histogramData[index + numRenderScaleHistogramBins]; if (count === 0) continue; const yStart = Math.round(countToCanvasY(sum)); sum += count; const yEnd = Math.round(countToCanvasY(sum)); if (yEnd <= hoverY && hoverY <= yStart) { hoverSpatialScale = spatialScale; break; } } } } if (hoverSpatialScale !== undefined) { totalPresent = 0; totalNotPresent = 0; const row = spatialScales.get(hoverSpatialScale)!; const baseIndex = 2 * row * numRenderScaleHistogramBins; for (let bin = 0; bin < numRenderScaleHistogramBins; ++bin) { const index = baseIndex + bin; totalPresent += histogramData[index]; totalNotPresent += histogramData[index + numRenderScaleHistogramBins]; } if (Number.isFinite(hoverSpatialScale)) { this.legendSpatialScale.textContent = formatScaleWithUnitAsString( hoverSpatialScale, "m", { precision: 2, elide1: false }, ); } else { this.legendSpatialScale.textContent = "unknown"; } } else { this.legendSpatialScale.textContent = ""; } this.legendChunks.textContent = `${totalPresent}/${ totalPresent + totalNotPresent }`; const spatialScaleColors = sortedSpatialScales.map((spatialScale) => { const saturation = spatialScale === hoverSpatialScale ? 0.5 : 1; let hue; if (Number.isFinite(spatialScale)) { hue = (((Math.log2(spatialScale) * 0.1) % 1) + 1) % 1; } else { hue = 0; } hsvToRgb(tempColor, hue, saturation, 1); const presentColor = serializeColor(tempColor); hsvToRgb(tempColor, hue, saturation, 0.5); const notPresentColor = serializeColor(tempColor); return [presentColor, notPresentColor]; }); for (let i = 0; i < numRenderScaleHistogramBins; ++i) { let sum = 0; for ( let spatialScaleIndex = numRows - 1; spatialScaleIndex >= 0; --spatialScaleIndex ) { const spatialScale = sortedSpatialScales[spatialScaleIndex]; const row = spatialScales.get(spatialScale)!; const index = row * numRenderScaleHistogramBins * 2 + i; const presentCount = histogramData[index]; const notPresentCount = histogramData[index + numRenderScaleHistogramBins]; const count = presentCount + notPresentCount; if (count === 0) continue; const xStart = Math.round(binToCanvasX(i)); const xEnd = Math.round(binToCanvasX(i + 1)); const yStart = Math.round(countToCanvasY(sum)); sum += count; const yEnd = Math.round(countToCanvasY(sum)); const ySplit = (presentCount * yEnd + notPresentCount * yStart) / count; ctx.fillStyle = spatialScaleColors[spatialScaleIndex][1]; ctx.fillRect(xStart, yEnd, xEnd - xStart, ySplit - yEnd); ctx.fillStyle = spatialScaleColors[spatialScaleIndex][0]; ctx.fillRect(xStart, ySplit, xEnd - xStart, yStart - ySplit); } } { const value = targetValue; ctx.fillStyle = "#fff"; const startOffset = binToCanvasX( getRenderScaleHistogramOffset(value, this.logScaleOrigin), ); const lineWidth = 1; ctx.fillRect(Math.floor(startOffset), 0, lineWidth, height); } if (hoverValue !== undefined) { const value = hoverValue[0]; ctx.fillStyle = "#888"; const startOffset = binToCanvasX( getRenderScaleHistogramOffset(value, this.logScaleOrigin), ); const lineWidth = 1; ctx.fillRect(Math.floor(startOffset), 0, lineWidth, height); } } } export class VolumeRenderingRenderScaleWidget extends RenderScaleWidget { protected unitOfTarget = "samples"; protected logScaleOrigin = 1; getWheelMoveValue(event: WheelEvent) { return -event.deltaY; } } const TOOL_INPUT_EVENT_MAP = EventActionMap.fromObject({ "at:shift+wheel": { action: "adjust-via-wheel" }, "at:shift+dblclick0": { action: "reset" }, }); export function renderScaleLayerControl< LayerType extends UserLayer, WidgetType extends RenderScaleWidget, >( getter: (layer: LayerType) => RenderScaleWidgetOptions, widgetClass: new ( histogram: RenderScaleHistogram, target: TrackableValueInterface<number>, ) => WidgetType = RenderScaleWidget as new ( histogram: RenderScaleHistogram, target: TrackableValueInterface<number>, ) => WidgetType, ): LayerControlFactory<LayerType, RenderScaleWidget> { return { makeControl: (layer, context) => { const { histogram, target } = getter(layer); const control = context.registerDisposer( new widgetClass(histogram, target), ); return { control, controlElement: control.element }; }, activateTool: (activation, control) => { activation.bindInputEventMap(TOOL_INPUT_EVENT_MAP); activation.bindAction( "adjust-via-wheel", (event: ActionEvent<WheelEvent>) => { event.stopPropagation(); event.preventDefault(); control.adjustViaWheel(event.detail); }, ); activation.bindAction("reset", (event: ActionEvent<WheelEvent>) => { event.stopPropagation(); event.preventDefault(); control.reset(); }); }, }; } ```
/content/code_sandbox/src/widget/render_scale_widget.ts
xml
2016-05-27T02:37:25
2024-08-16T07:24:25
neuroglancer
google/neuroglancer
1,045
3,306
```xml import { Component, OnInit } from '@angular/core'; import { MegaMenuItem } from 'primeng/api'; import { Code } from '@domain/code'; @Component({ selector: 'vertical-doc', template: ` <app-docsectiontext> <p>Layout of the MegaMenu is changed with the <i>orientation</i> property that accepts <i>horizontal</i> and <i>vertical</i> as options.</p> </app-docsectiontext> <div class="card"> <p-megaMenu [model]="items" orientation="vertical" /> </div> <app-code [code]="code" selector="mega-menu-vertical-demo"></app-code> ` }) export class VerticalDoc implements OnInit { items: MegaMenuItem[] | undefined; ngOnInit() { this.items = [ { label: 'Furniture', icon: 'pi pi-box', items: [ [ { label: 'Living Room', items: [{ label: 'Accessories' }, { label: 'Armchair' }, { label: 'Coffee Table' }, { label: 'Couch' }, { label: 'TV Stand' }] } ], [ { label: 'Kitchen', items: [{ label: 'Bar stool' }, { label: 'Chair' }, { label: 'Table' }] }, { label: 'Bathroom', items: [{ label: 'Accessories' }] } ], [ { label: 'Bedroom', items: [{ label: 'Bed' }, { label: 'Chaise lounge' }, { label: 'Cupboard' }, { label: 'Dresser' }, { label: 'Wardrobe' }] } ], [ { label: 'Office', items: [{ label: 'Bookcase' }, { label: 'Cabinet' }, { label: 'Chair' }, { label: 'Desk' }, { label: 'Executive Chair' }] } ] ] }, { label: 'Electronics', icon: 'pi pi-mobile', items: [ [ { label: 'Computer', items: [{ label: 'Monitor' }, { label: 'Mouse' }, { label: 'Notebook' }, { label: 'Keyboard' }, { label: 'Printer' }, { label: 'Storage' }] } ], [ { label: 'Home Theather', items: [{ label: 'Projector' }, { label: 'Speakers' }, { label: 'TVs' }] } ], [ { label: 'Gaming', items: [{ label: 'Accessories' }, { label: 'Console' }, { label: 'PC' }, { label: 'Video Games' }] } ], [ { label: 'Appliances', items: [{ label: 'Coffee Machine' }, { label: 'Fridge' }, { label: 'Oven' }, { label: 'Vaccum Cleaner' }, { label: 'Washing Machine' }] } ] ] }, { label: 'Sports', icon: 'pi pi-clock', items: [ [ { label: 'Football', items: [{ label: 'Kits' }, { label: 'Shoes' }, { label: 'Shorts' }, { label: 'Training' }] } ], [ { label: 'Running', items: [{ label: 'Accessories' }, { label: 'Shoes' }, { label: 'T-Shirts' }, { label: 'Shorts' }] } ], [ { label: 'Swimming', items: [{ label: 'Kickboard' }, { label: 'Nose Clip' }, { label: 'Swimsuits' }, { label: 'Paddles' }] } ], [ { label: 'Tennis', items: [{ label: 'Balls' }, { label: 'Rackets' }, { label: 'Shoes' }, { label: 'Training' }] } ] ] } ]; } code: Code = { basic: `<p-megaMenu [model]="items" orientation="vertical" />`, html: `<div class="card"> <p-megaMenu [model]="items" orientation="vertical" /> </div>`, typescript: `import { Component, OnInit } from '@angular/core'; import { MegaMenuItem } from 'primeng/api'; import { MegaMenuModule } from 'primeng/megamenu'; @Component({ selector: 'mega-menu-vertical-demo', templateUrl: './mega-menu-vertical-demo.html', standalone: true, imports: [MegaMenuModule] }) export class MegaMenuVerticalDemo implements OnInit { items: MegaMenuItem[] | undefined; ngOnInit() { this.items = [ { label: 'Furniture', icon: 'pi pi-box', items: [ [ { label: 'Living Room', items: [{ label: 'Accessories' }, { label: 'Armchair' }, { label: 'Coffee Table' }, { label: 'Couch' }, { label: 'TV Stand' }] } ], [ { label: 'Kitchen', items: [{ label: 'Bar stool' }, { label: 'Chair' }, { label: 'Table' }] }, { label: 'Bathroom', items: [{ label: 'Accessories' }] } ], [ { label: 'Bedroom', items: [{ label: 'Bed' }, { label: 'Chaise lounge' }, { label: 'Cupboard' }, { label: 'Dresser' }, { label: 'Wardrobe' }] } ], [ { label: 'Office', items: [{ label: 'Bookcase' }, { label: 'Cabinet' }, { label: 'Chair' }, { label: 'Desk' }, { label: 'Executive Chair' }] } ] ] }, { label: 'Electronics', icon: 'pi pi-mobile', items: [ [ { label: 'Computer', items: [{ label: 'Monitor' }, { label: 'Mouse' }, { label: 'Notebook' }, { label: 'Keyboard' }, { label: 'Printer' }, { label: 'Storage' }] } ], [ { label: 'Home Theather', items: [{ label: 'Projector' }, { label: 'Speakers' }, { label: 'TVs' }] } ], [ { label: 'Gaming', items: [{ label: 'Accessories' }, { label: 'Console' }, { label: 'PC' }, { label: 'Video Games' }] } ], [ { label: 'Appliances', items: [{ label: 'Coffee Machine' }, { label: 'Fridge' }, { label: 'Oven' }, { label: 'Vaccum Cleaner' }, { label: 'Washing Machine' }] } ] ] }, { label: 'Sports', icon: 'pi pi-clock', items: [ [ { label: 'Football', items: [{ label: 'Kits' }, { label: 'Shoes' }, { label: 'Shorts' }, { label: 'Training' }] } ], [ { label: 'Running', items: [{ label: 'Accessories' }, { label: 'Shoes' }, { label: 'T-Shirts' }, { label: 'Shorts' }] } ], [ { label: 'Swimming', items: [{ label: 'Kickboard' }, { label: 'Nose Clip' }, { label: 'Swimsuits' }, { label: 'Paddles' }] } ], [ { label: 'Tennis', items: [{ label: 'Balls' }, { label: 'Rackets' }, { label: 'Shoes' }, { label: 'Training' }] } ] ] } ] } }` }; } ```
/content/code_sandbox/src/app/showcase/doc/megamenu/verticaldoc.ts
xml
2016-01-16T09:23:28
2024-08-16T19:58:20
primeng
primefaces/primeng
9,969
1,790
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import {COLOR_V2} from '@wireapp/react-ui-kit'; export const BLUE = { color: '#0667c8', id: 1, name: 'Blue', }; export const GREEN = { color: COLOR_V2.GREEN, id: 2, name: 'Green', }; export const RED = { color: COLOR_V2.RED, id: 4, name: 'Red', }; export const AMBER = { color: COLOR_V2.AMBER, id: 5, name: 'Orange', }; export const TURQUOISE = { color: COLOR_V2.TURQUOISE ? COLOR_V2.TURQUOISE : '#5de6ff', id: 6, name: 'Turquoise', }; export const PURPLE = { color: COLOR_V2.PURPLE, id: 7, name: 'Purple', }; export const ACCENT_COLORS = [BLUE, GREEN, RED, AMBER, TURQUOISE, PURPLE]; export const colorFromId = (id?: number) => { const accentColor = ACCENT_COLORS.find(color => color.id === id); return accentColor && accentColor.color; }; ```
/content/code_sandbox/electron/renderer/src/lib/accentColor.ts
xml
2016-07-26T13:55:48
2024-08-16T03:45:51
wire-desktop
wireapp/wire-desktop
1,075
352
```xml import React from 'react'; import { screen, render } from '@testing-library/react'; import { EditorState, ContentState } from 'draft-js'; import { PluginFunctions } from '@draft-js-plugins/editor'; import createCounterPlugin from '../../index'; jest.mock('linaria'); describe('CounterPlugin Word Counter', () => { const createEditorStateFromText = (text: string): EditorState => { const contentState = ContentState.createFromText(text); return EditorState.createWithContent(contentState); }; it('instantiates plugin and counts 5 words', () => { const counterPlugin = createCounterPlugin(); const text = 'Hello there, how are you?'; const editorState = createEditorStateFromText(text); counterPlugin.initialize!({ getEditorState: () => editorState, } as PluginFunctions); const { WordCounter } = counterPlugin; render(<WordCounter />); expect(screen.getByText('5')).toBeInTheDocument(); }); }); ```
/content/code_sandbox/packages/counter/src/WordCounter/__test__/index.test.tsx
xml
2016-02-26T09:54:56
2024-08-16T18:16:31
draft-js-plugins
draft-js-plugins/draft-js-plugins
4,087
208
```xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorBackgroundSecondary">#ECEFF1</color> <color name="colorStateImage">#B0BEC5</color> <color name="colorPrimary">#009688</color> <color name="colorPrimaryDark">#00675b</color> <color name="colorAccent">#40c4ff</color> <color name="stateError">#F44336</color> </resources> ```
/content/code_sandbox/app/src/main/res/values/colors.xml
xml
2016-10-15T15:27:17
2024-08-16T06:53:53
dns66
julian-klode/dns66
2,104
111
```xml import Logger from '../../infrastructure/logging/logger'; import { COMPODOC_DEFAULTS } from '../defaults'; import { InternalConfiguration } from '../entities/internal-configuration'; import { PublicConfiguration } from '../entities/public-configuration'; import { Flag, PUBLIC_FLAGS } from '../entities/public-flags'; import { CLIProgram } from '../entities/cli-program'; export class ConfigurationRepository { private static instance: ConfigurationRepository; public publicConfiguration: PublicConfiguration; public internalConfiguration: InternalConfiguration; constructor() { this.publicConfiguration = new PublicConfiguration(); this.internalConfiguration = new InternalConfiguration(); } public static getInstance() { if (!ConfigurationRepository.instance) { ConfigurationRepository.instance = new ConfigurationRepository(); } return ConfigurationRepository.instance; } public update(configExplorerResult) { this.publicConfiguration = Object.assign( this.publicConfiguration, configExplorerResult.config ); } public init(currentProgram: CLIProgram) { PUBLIC_FLAGS.forEach((publicFlag: Flag) => { if (this.publicConfiguration[publicFlag.label]) { this.internalConfiguration[publicFlag.label] = this.publicConfiguration[ publicFlag.label ]; } if (currentProgram.hasOwnProperty(publicFlag.label)) { this.internalConfiguration[publicFlag.label] = currentProgram[publicFlag.label]; } }); /** * Specific use-cases flags */ if (this.publicConfiguration.coverageTest) { this.internalConfiguration.coverageTest = 0; this.internalConfiguration.coverageTestThreshold = typeof this.publicConfiguration.coverageTest === 'string' ? parseInt(this.publicConfiguration.coverageTest, 10) : COMPODOC_DEFAULTS.defaultCoverageThreshold; } if (currentProgram.coverageTest) { this.internalConfiguration.coverageTest = 0; this.internalConfiguration.coverageTestThreshold = typeof currentProgram.coverageTest === 'string' ? parseInt(currentProgram.coverageTest, 10) : COMPODOC_DEFAULTS.defaultCoverageThreshold; } if (this.publicConfiguration.coverageMinimumPerFile) { this.internalConfiguration.coverageTestPerFile = true; this.internalConfiguration.coverageMinimumPerFile = typeof this.publicConfiguration.coverageMinimumPerFile === 'string' ? parseInt(this.publicConfiguration.coverageMinimumPerFile, 10) : COMPODOC_DEFAULTS.defaultCoverageMinimumPerFile; } if (currentProgram.coverageMinimumPerFile) { this.internalConfiguration.coverageTestPerFile = true; this.internalConfiguration.coverageMinimumPerFile = typeof currentProgram.coverageMinimumPerFile === 'string' ? parseInt(currentProgram.coverageMinimumPerFile, 10) : COMPODOC_DEFAULTS.defaultCoverageMinimumPerFile; } if (this.publicConfiguration.coverageTestThresholdFail) { this.internalConfiguration.coverageTestThresholdFail = this.publicConfiguration.coverageTestThresholdFail; } if (currentProgram.coverageTestThresholdFail) { this.internalConfiguration.coverageTestThresholdFail = currentProgram.coverageTestThresholdFail; } if (this.publicConfiguration.host) { this.internalConfiguration.host = this.publicConfiguration.host; this.internalConfiguration.hostname = this.publicConfiguration.host; } if (currentProgram.host) { this.internalConfiguration.host = currentProgram.host; this.internalConfiguration.hostname = currentProgram.host; } if (this.publicConfiguration.minimal) { this.internalConfiguration.disableSearch = true; this.internalConfiguration.disableRoutesGraph = true; this.internalConfiguration.disableGraph = true; this.internalConfiguration.disableCoverage = true; } if (currentProgram.minimal) { this.internalConfiguration.disableSearch = true; this.internalConfiguration.disableRoutesGraph = true; this.internalConfiguration.disableGraph = true; this.internalConfiguration.disableCoverage = true; } if ( currentProgram.navTabConfig && JSON.parse(currentProgram.navTabConfig).length !== COMPODOC_DEFAULTS.navTabConfig.length ) { this.internalConfiguration.navTabConfig = JSON.parse(currentProgram.navTabConfig); } if (this.publicConfiguration.silent) { Logger.silent = true; } if (currentProgram.silent) { Logger.silent = true; } } } export default ConfigurationRepository.getInstance(); ```
/content/code_sandbox/src-refactored/core/repositories/config.repository.ts
xml
2016-10-17T07:09:28
2024-08-14T16:30:10
compodoc
compodoc/compodoc
3,980
904
```xml import { existsSync } from 'fs'; import { join, resolve } from 'path'; import { IOptions, IRule } from 'tslint'; import { arrayify, camelize, find } from 'tslint/lib/utils'; export function convertRuleOptions(ruleConfiguration: Map<string, Partial<IOptions>>): IOptions[] { const output: IOptions[] = []; ruleConfiguration.forEach(({ ruleArguments, ruleSeverity }, ruleName) => { const options: IOptions = { disabledIntervals: [], // deprecated, so just provide an empty array. ruleArguments: ruleArguments || [], ruleName, ruleSeverity: ruleSeverity || 'error', }; output.push(options); }); return output; } const cachedRules = new Map<string, any | 'not-found'>(); function transformName(name: string): string { // camelize strips out leading and trailing underscores and dashes, so make sure they aren't passed to camelize // the regex matches the groups (leading underscores and dashes)(other characters)(trailing underscores and dashes) const nameMatch = name.match(/^([-_]*)(.*?)([-_]*)$/); if (nameMatch === null) { return `${name}Rule`; } return `${nameMatch[1]}${camelize(nameMatch[2])}${nameMatch[3]}Rule`; } /** * @param directory - An absolute path to a directory of rules * @param ruleName - A name of a rule in filename format. ex) "someLintRule" */ function loadRule(directory: string, ruleName: string): any | 'not-found' { const fullPath = join(directory, ruleName); if (existsSync(`${fullPath}.js`)) { const ruleModule = require(fullPath) as { Rule: any } | undefined; if (ruleModule !== undefined) { return ruleModule.Rule; } } return 'not-found'; } export function getRelativePath(directory?: string | null, relativeTo?: string): string | undefined { if (directory !== null && directory !== undefined) { const basePath = relativeTo !== undefined ? relativeTo : process.cwd(); return resolve(basePath, directory); } return undefined; } function loadCachedRule(directory: string, ruleName: string, isCustomPath?: boolean): any | undefined { // use cached value if available const fullPath = join(directory, ruleName); const cachedRule = cachedRules.get(fullPath); if (cachedRule !== undefined) { return cachedRule === 'not-found' ? undefined : cachedRule; } // get absolute path let absolutePath: string | undefined = directory; if (isCustomPath) { absolutePath = getRelativePath(directory); if (absolutePath !== undefined && !existsSync(absolutePath)) { throw new Error(`Could not find custom rule directory: ${directory}`); } } const Rule = absolutePath === undefined ? 'not-found' : loadRule(absolutePath, ruleName); cachedRules.set(fullPath, Rule); return Rule === 'not-found' ? undefined : Rule; } function findRule(name: string, rulesDirectories?: string | string[]): any | undefined { const camelizedName = transformName(name); return find(arrayify(rulesDirectories), (dir) => loadCachedRule(dir, camelizedName, true)); } export function loadRules(ruleOptionsList: IOptions[], rulesDirectories?: string | string[], isJs = false): IRule[] { const rules: IRule[] = []; const notFoundRules: string[] = []; const notAllowedInJsRules: string[] = []; for (const ruleOptions of ruleOptionsList) { if (ruleOptions.ruleSeverity === 'off') { // Perf: don't bother finding the rule if it's disabled. continue; } const ruleName = ruleOptions.ruleName; const Rule = findRule(ruleName, rulesDirectories); if (Rule === undefined) { notFoundRules.push(ruleName); } else if (isJs && Rule.metadata !== undefined && Rule.metadata.typescriptOnly) { notAllowedInJsRules.push(ruleName); } else { const rule = new Rule(ruleOptions); if (rule.isEnabled()) { rules.push(rule); } } } return rules; } ```
/content/code_sandbox/test/utils.ts
xml
2016-02-10T17:22:40
2024-08-14T16:41:28
codelyzer
mgechev/codelyzer
2,446
923
```xml /** * @file * Photopile Web Part React JSX component. * * Contains JSX code to render the web part with HTML templates. * * Author: Olivier Carpentier */ import * as React from 'react'; import { Spinner, SpinnerType } from 'office-ui-fabric-react/lib/Spinner'; import { IPhotopileWebPartProps } from '../IPhotopileWebPartProps'; import { IWebPartContext } from '@microsoft/sp-webpart-base'; import * as strings from 'mystrings'; import styles from '../PhotopileWebPart.module.scss'; import { SPPicturesListService } from '../SPPicturesListService'; import { ISPListItem } from '../ISPList'; import * as photopile from 'photopileModule'; require('jquery'); require('jqueryui'); require('../css/photopile.scss'); require('photopileModule'); /** * @interface * Defines Photopile web part state. */ export interface IPhotopileState { results?: ISPListItem[]; loaded: boolean; } /** * @class * Defines Photopile web part class. */ export default class PhotopileWebPart extends React.Component<IPhotopileWebPartProps, IPhotopileState> { //page context private myPageContext: IWebPartContext; /** * @function * Photopile web part contructor. */ constructor(props: IPhotopileWebPartProps, context: IWebPartContext) { super(props, context); //Save the context this.myPageContext = props.context; //Init the component state this.state = { results: [], loaded: false }; }; /** * @function * JSX Element render method */ public render(): JSX.Element { if (this.props.listName == null || this.props.listName == '') { //Display select a list message return ( <div className="ms-MessageBar"> <div className="ms-MessageBar-content"> <div className="ms-MessageBar-icon"> <i className="ms-Icon ms-Icon--infoCircle"></i> </div> <div className="ms-MessageBar-text"> {strings.ErrorSelectList} </div> </div> </div> ); } else { if (this.state.loaded == false) { //Display the loading spinner with the Office UI Fabric Spinner control return ( <div className={ styles.photopileWebPart }> <div className={ styles.workingOnItSpinner }> <Spinner type={ SpinnerType.normal } /> <div className={ styles.loadingLabel }> <label className="ms-Label"> {strings.Loading}</label> </div> </div> </div> ); } else if (this.state.results.length == 0) { //Display message no items return ( <div className="ms-MessageBar ms-MessageBar--error"> <div className="ms-MessageBar-content"> <div className="ms-MessageBar-icon"> <i className="ms-Icon ms-Icon--xCircle"></i> </div> <div className="ms-MessageBar-text"> {strings.ErrorNoItems} </div> </div> </div> ); } else { //Display the items list return ( <div className='photopile-wrapper'> <ul className='photopile'> {this.state.results.map((object:ISPListItem, i:number) => { //Select the best Alt text with title, description or file's name var altText: string = object.Title; if (altText == null || altText == '') altText = object.Description; if (altText == null || altText == '') altText = object.File.Name; //Render the item return ( <li> <a href={object.File.ServerRelativeUrl}> <img src={object.File.ThumbnailServerUrl} alt={altText} width="133" height="100"/> </a> </li> ); })} </ul> </div> ); } } } /** * @function * Function called when the component did mount */ public componentDidMount(): void { if (this.props.listName != null && this.props.listName != '') { //Init the Picture list service const picturesListService: SPPicturesListService = new SPPicturesListService(this.props, this.myPageContext); //Load the list of pictures from the current lib picturesListService.getPictures(this.props.listName) .then((response) => { //Modify the component state with the json result this.setState({ results: response.value, loaded: true}); }); } } /** * @function * Function called when the web part properties has changed */ public componentWillReceiveProps(nextProps: IPhotopileWebPartProps): void { //Define the state with empty results this.setState({ results: [], loaded: false}); if (nextProps.listName != null && nextProps.listName != '') { //Init the Picture list service const picturesListService: SPPicturesListService = new SPPicturesListService(nextProps, this.myPageContext); //Load the list of pictures from the current lib picturesListService.getPictures(nextProps.listName) .then((response) => { //Modify the component state with the json result this.setState({ results: response.value, loaded: true}); }); } } /** * @function * Function called when the component has been rendered (ie HTML code is ready) */ public componentDidUpdate(prevProps: IPhotopileWebPartProps, prevState: IPhotopileState): void { if (this.state.loaded) { //Init photopile options photopile.setNumLayers(this.props.numLayers); photopile.setThumbOverlap(this.props.thumbOverlap); photopile.setThumbRotation(this.props.thumbRotation); photopile.setThumbBorderWidth(this.props.thumbBorderWidth); photopile.setThumbBorderColor(this.props.thumbBorderColor); photopile.setThumbBorderHover(this.props.thumbBorderHover); photopile.setDraggable(this.props.draggable); photopile.setFadeDuration(this.props.fadeDuration); photopile.setPickupDuration(this.props.pickupDuration); photopile.setPhotoZIndex(this.props.photoZIndex); photopile.setPhotoBorder(this.props.photoBorder); photopile.setPhotoBorderColor(this.props.photoBorderColor); photopile.setShowInfo(this.props.showInfo); photopile.setAutoplayGallery(this.props.autoplayGallery); photopile.setAutoplaySpeed(this.props.autoplaySpeed); //Init photopile photopile.scatter(); } } } ```
/content/code_sandbox/samples/jquery-photopile/src/webparts/photopileWebPart/components/PhotopileWebPart.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
1,495
```xml <!-- Description: entry source logo --> <feed xmlns="path_to_url"> <entry> <source> <logo>path_to_url </source> </entry> </feed> ```
/content/code_sandbox/testdata/parser/atom/atom10_feed_entry_source_logo.xml
xml
2016-01-23T02:44:34
2024-08-16T15:16:03
gofeed
mmcdole/gofeed
2,547
44
```xml /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in path_to_url */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** * IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags * because those flags need to be set before `zone.js` being loaded, and webpack * will put import in the top of bundle, so user need to create a separate file * in this directory (for example: zone-flags.ts), and put the following flags * into that file, and then add the following code before importing zone.js. * import './zone-flags'; * * The flags allowed in zone-flags.ts are listed here. * * The following flags will work for all browsers. * * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ ```
/content/code_sandbox/apps/shim-clr-ui/src/polyfills.ts
xml
2016-09-29T17:24:17
2024-08-11T17:06:15
clarity
vmware-archive/clarity
6,431
579
```xml <epp xmlns="urn:ietf:params:xml:ns:epp-1.0"> <command> <update> <domain:update xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"> <domain:name>example.tld</domain:name> <domain:add> <domain:contact type="admin">mak21</domain:contact> <domain:contact type="billing">mak21</domain:contact> <domain:contact type="tech">mak21</domain:contact> </domain:add> <domain:rem> <domain:contact type="admin">sh8013</domain:contact> <domain:contact type="billing">sh8013</domain:contact> <domain:contact type="tech">sh8013</domain:contact> </domain:rem> <domain:chg> <domain:registrant>mak21</domain:registrant> </domain:chg> </domain:update> </update> <clTRID>ABC-12345</clTRID> </command> </epp> ```
/content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_update_remove_multiple_contacts.xml
xml
2016-02-29T20:16:48
2024-08-15T19:49:29
nomulus
google/nomulus
1,685
246
```xml import timekeeper from "timekeeper"; import { pureMerge } from "coral-common/common/lib/utils"; import { GQLResolver } from "coral-framework/schema"; import { createResolversStub, CreateTestRendererParams, waitForElement, within, } from "coral-framework/testHelpers"; import { createComment, createComments, createStory, createUser, createUserStatus, } from "coral-test/helpers/fixture"; import { settings } from "../../fixtures"; import create from "./create"; const bannedUser = createUser(); bannedUser.status = createUserStatus(true); const story = createStory({ comments: createComments(3) }); const firstComment = story.comments.edges[0].node; const reactedComment = createComment(); async function createTestRenderer( params: CreateTestRendererParams<GQLResolver> = {} ) { const { testRenderer, context } = create({ ...params, resolvers: pureMerge( createResolversStub<GQLResolver>({ Query: { settings: () => settings, viewer: () => bannedUser, stream: () => pureMerge<typeof story>(story, { comments: { edges: [ ...story.comments.edges, { node: pureMerge<typeof reactedComment>(reactedComment, { actionCounts: { reaction: { total: 1 } }, }), cursor: reactedComment.createdAt, }, ], }, }), }, }), params.resolvers ), initLocalState: (localRecord, source, environment) => { localRecord.setValue(story.id, "storyID"); localRecord.setValue(3000, "notificationsPollRate"); if (params.initLocalState) { params.initLocalState(localRecord, source, environment); } }, }); const tabPane = await waitForElement(() => within(testRenderer.root).getByTestID("current-tab-pane") ); return { testRenderer, context, tabPane, }; } afterAll(() => { timekeeper.reset(); }); it("disables comment stream", async () => { timekeeper.freeze(firstComment.createdAt as Date); const { testRenderer, tabPane } = await createTestRenderer(); await waitForElement(() => within(testRenderer.root).getByTestID("comments-allComments-log") ); within(tabPane).getAllByText("Your account has been banned", { exact: false, }); expect(within(tabPane).queryByTestID("comment-reply-button")).toBeNull(); expect(within(tabPane).queryByTestID("comment-report-button")).toBeNull(); expect(within(tabPane).queryByTestID("comment-edit-button")).toBeNull(); expect( within(tabPane).getByTestID("comment-reaction-button").props.disabled ).toBe(true); }); ```
/content/code_sandbox/client/src/core/client/stream/test/comments/stream/banned.spec.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
604
```xml import React, { useState, useCallback, FormEventHandler } from 'react' import styled from '../../../design/lib/styled' import { stringify } from 'querystring' import cc from 'classcat' import { createLoginEmailRequest } from '../../api/auth/email' import { boostHubBaseUrl } from '../../lib/consts' import { LoadingButton } from '../../../design/components/atoms/Button' interface EmailFormProps { query?: any disabled: boolean setDisabled: (val: boolean) => void setError: (err: unknown) => void email?: string } const EmailForm = ({ query, disabled, setDisabled, setError, email: initialEmail = '', }: EmailFormProps) => { const [step, setStep] = useState<'email' | 'code'>('email') const [email, setEmail] = useState<string>(initialEmail) const [code, setCode] = useState<string>('') const [sending, setSending] = useState<boolean>(false) const emailChangeHandler: React.ChangeEventHandler<HTMLInputElement> = useCallback( (event) => { setEmail(event.target.value) setStep('email') }, [setEmail] ) const codeChangeHandler: React.ChangeEventHandler<HTMLInputElement> = useCallback( (event) => { setCode(event.target.value) }, [setCode] ) const onSubmit: FormEventHandler = useCallback( async (event) => { event?.preventDefault() if (disabled || sending || step === 'code') { return } setSending(true) setDisabled(true) try { await createLoginEmailRequest({ email, ...query }) setStep('code') } catch (error) { setError(error) } setSending(false) setDisabled(false) }, [disabled, sending, setDisabled, step, setStep, email, query, setError] ) if (step === 'code') { const linkIsDisabled = code.length < 7 || disabled return ( <StyledEmailForm onSubmit={onSubmit}> <label>Email</label> <input type='text' value={email} placeholder='Email...' onChange={emailChangeHandler} /> <p className='text-center'> We just sent a temporary signin code to your email. <br /> Please check your inbox. </p> <input type='text' value={code} placeholder='Paste signin code' onChange={codeChangeHandler} /> <LoadingButton variant='primary' className={cc(['submit-email', linkIsDisabled && 'disabled'])} onClick={() => { setDisabled(true) setSending(true) window.location.href = `${boostHubBaseUrl}/api/oauth/email/callback?${stringify( { code, email, } )}` }} disabled={linkIsDisabled} spinning={sending} > Continue with signin code </LoadingButton> </StyledEmailForm> ) } return ( <StyledEmailForm onSubmit={onSubmit}> <label>EMAIL</label> <input type='text' value={email} placeholder='Email...' onChange={emailChangeHandler} /> <LoadingButton className='submit-email' variant='primary' type='submit' disabled={disabled} size='lg' spinning={sending} > Continue with email </LoadingButton> </StyledEmailForm> ) } export default EmailForm const StyledEmailForm = styled.form` margin-left: auto; margin-right: auto; color: #9da0a5; label { display: block; margin: ${({ theme }) => theme.sizes.spaces.sm}px auto; text-align: left; width: 100%; } input { padding: ${({ theme }) => theme.sizes.spaces.sm}px ${({ theme }) => theme.sizes.spaces.sm}px; border: none; border-radius: 2px; border: 1px solid #d2d3d6; ::placeholder { color: #45474b; } width: 100%; height: 40px; } .submit-email { width: 100%; margin: ${({ theme }) => theme.sizes.spaces.sm}px 0; } a.submit-email.disabled { opacity: 0.3; pointer-events: none; } .text-center { margin-top: ${({ theme }) => theme.sizes.spaces.sm}px; } ` ```
/content/code_sandbox/src/cloud/components/SignInForm/EmailForm.tsx
xml
2016-11-19T14:30:34
2024-08-16T03:13:45
BoostNote-App
BoostIO/BoostNote-App
3,745
1,001
```xml import React from 'react'; import { Checkbox, Stack, Icon, Box } from 'native-base'; import { MaterialCommunityIcons } from '@expo/vector-icons'; export const Example = () => { return ( <Box alignItems="center"> <Stack direction={{ base: 'column', md: 'row' }} space={3} alignItems="flex-start" > <Checkbox value="orange" colorScheme="orange" size="md" icon={<Icon as={<MaterialCommunityIcons name="bullseye" />} />} defaultIsChecked > Darts </Checkbox> <Checkbox value="dark" colorScheme="dark" size="md" icon={<Icon as={<MaterialCommunityIcons name="bat" />} />} defaultIsChecked > Movie </Checkbox> <Checkbox colorScheme="red" value="red" size="md" icon={<Icon as={<MaterialCommunityIcons name="campfire" />} />} defaultIsChecked > Camping </Checkbox> <Checkbox value="blue" colorScheme="blue" size="md" icon={<Icon as={<MaterialCommunityIcons name="chess-knight" />} />} defaultIsChecked > Chess </Checkbox> </Stack> </Box> ); }; ```
/content/code_sandbox/example/storybook/stories/components/primitives/Checkbox/customIcon.tsx
xml
2016-04-15T11:37:23
2024-08-14T16:16:44
NativeBase
GeekyAnts/NativeBase
20,132
296
```xml This file is part of GNU Emacs. GNU Emacs is free software: you can redistribute it and/or modify (at your option) any later version. GNU Emacs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with GNU Emacs. If not, see <path_to_url --> <locatingRules xmlns="path_to_url"> <transformURI fromPattern="*.xml" toPattern="*.rnc"/> <uri pattern="*.xsl" typeId="XSLT"/> <uri pattern="*.html" typeId="XHTML"/> <uri pattern="*.rng" typeId="RELAX NG"/> <uri pattern="*.rdf" typeId="RDF"/> <uri pattern="*.dbk" typeId="DocBook"/> <namespace ns="path_to_url" typeId="XSLT"/> <namespace ns="path_to_url#" typeId="RDF"/> <namespace ns="path_to_url" typeId="XHTML"/> <namespace ns="path_to_url" typeId="RELAX NG"/> <namespace ns="path_to_url" uri="locate.rnc"/> <documentElement localName="stylesheet" typeId="XSLT"/> <documentElement prefix="xsl" localName="transform" typeId="XSLT"/> <documentElement localName="html" typeId="XHTML"/> <documentElement localName="grammar" typeId="RELAX NG"/> <documentElement prefix="" localName="article" typeId="DocBook"/> <documentElement prefix="" localName="book" typeId="DocBook"/> <documentElement prefix="" localName="chapter" typeId="DocBook"/> <documentElement prefix="" localName="part" typeId="DocBook"/> <documentElement prefix="" localName="refentry" typeId="DocBook"/> <documentElement prefix="" localName="section" typeId="DocBook"/> <documentElement localName="RDF" typeId="RDF"/> <documentElement prefix="rdf" typeId="RDF"/> <documentElement localName="locatingRules" uri="locate.rnc"/> <typeId id="XSLT" uri="xslt.rnc"/> <typeId id="RELAX NG" uri="relaxng.rnc"/> <typeId id="XHTML" uri="xhtml.rnc"/> <typeId id="DocBook" uri="docbook.rnc"/> <typeId id="RDF" uri="rdfxml.rnc"/> <documentElement prefix="office" typeId="OpenDocument"/> <documentElement prefix="manifest" localName="manifest" typeId="OpenDocument Manifest"/> <typeId id="OpenDocument" uri="od-schema-v1.2-os.rnc"/> <typeId id="OpenDocument Manifest" uri="od-manifest-schema-v1.2-os.rnc"/> </locatingRules> ```
/content/code_sandbox/etc/schema/schemas.xml
xml
2016-11-22T23:29:21
2024-08-12T19:26:13
remacs
remacs/remacs
4,582
625
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import {useIntl} from 'react-intl'; import {Button, Column, Columns, Container, H3, Modal, Text} from '@wireapp/react-ui-kit'; import {useSingleInstance} from 'src/script/hooks/useSingleInstance'; import {Config} from '../../Config'; import {appAlreadyOpenStrings} from '../../strings'; interface AppAlreadyOpenProps { fullscreen?: boolean; } export const AppAlreadyOpen = ({fullscreen}: AppAlreadyOpenProps) => { const {formatMessage: _} = useIntl(); const {hasOtherInstance, killRunningInstance} = useSingleInstance(); if (!hasOtherInstance) { return null; } return ( <Modal fullscreen={fullscreen}> <Container style={{maxWidth: '320px'}} data-uie-name="modal-already-open"> <H3 style={{fontWeight: 500, marginTop: '10px'}} data-uie-name="status-modal-title"> {_(appAlreadyOpenStrings.headline, {brandName: Config.getConfig().BRAND_NAME})} </H3> <Text data-uie-name="status-modal-text">{_(appAlreadyOpenStrings.text)}</Text> <Columns style={{marginTop: '20px'}}> <Column style={{textAlign: 'center'}}> <Button type="button" block onClick={killRunningInstance} style={{marginBottom: '10px'}} data-uie-name="do-action" > {_(appAlreadyOpenStrings.continueButton)} </Button> </Column> </Columns> </Container> </Modal> ); }; ```
/content/code_sandbox/src/script/auth/component/AppAlreadyOpen.tsx
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
428